This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
mobilecritical PriorityID: tauri-webview-state-restoration-gpu-fallback

Tauri 2.0 Webview State Restoration Hardware-Fallback Invariant

Enforces deterministic lifecycle persistence, headless state snapshots, and automatic software-rendering fallback surfaces in Tauri 2.0 mobile deployments. Eliminates fatal black-screen freezing caused by WebGL/GPU context eviction during Android Activity pause/resume and iOS application background transitions.

Prohibited Anti-Pattern: Unchecked Webview GPU Context Eviction Leading to Unrecoverable Mobile Black Screen

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Tauri 2.0 Webview State Restoration Hardware-Fallback Invariant - Enforces deterministic lifecycle persistence, headless state snapshots, and automatic software-rendering fallback surfaces in Tauri 2.0 mobile deployments. Eliminates fatal black-screen freezing caused by WebGL/GPU context eviction during Android Activity pause/resume and iOS application background transitions.
globs: src-tauri/src/**/*.rs, src/**/*.{ts,tsx,js,jsx}, src-tauri/tauri.conf.json
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/tauri-webview-state-restoration-gpu-fallback"
---

# Tauri 2.0 Webview State Restoration Hardware-Fallback Invariant

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Unchecked Webview GPU Context Eviction Leading to Unrecoverable Mobile Black Screen

## System Constraints
You are a Principal Engineer enforcing the Tauri 2.0 Webview State Restoration Hardware-Fallback Invariant. Mandate deterministic client-state snapshotting prior to mobile OS backgrounding, programmatic detection and mitigation of WebGL/WebGPU context loss, and failover to headless/software rendering or hot-reloading state surfaces. Ensure that application state is hydrated safely without unhandled canvas tears or permanent black-screen deadlocks.

## Strict Guidelines
- Engineers MUST ALWAYS listen to Tauri lifecycle events (`tauri://blur`, `tauri://focus`, or native mobile resume signals) and commit a synchronous local snapshot before the process is suspended.
- Engineers MUST ALWAYS intercept `webglcontextlost` and `webglcontextrestored` events on canvas elements, immediately invoking `event.preventDefault()` to allow context recovery.
- Services MUST implement a software-rendering or DOM-based fallback surface if GPU context restoration fails within a deterministic timeout threshold (e.g., 2000ms).
- Components NEVER assume canvas textures or GPU buffers persist across background/foreground app cycles on iOS or Android.
- Code SHOULD leverage Tauri plugins (e.g., store or persistent key-value bridges) to serialize viewport, navigation, and input state to disk synchronously upon receiving background notifications.

## Bad vs Good Implementations
### Webview GPU Context Recovery & Headless Snapshot Hydration

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Canvas context loss is unhandled. On Android/iOS suspend, the GPU context is dropped; without calling preventDefault() on 'webglcontextlost' and having a restoration pipeline, the surface enters an irrecoverable black screen state.
```typescript
import { useEffect } from 'react';

export function CanvasSurface() {
  useEffect(() => {
    const canvas = document.getElementById('render-surface') as HTMLCanvasElement;
    const gl = canvas.getContext('webgl2');
    // Blindly assumes context lives indefinitely
    // If mobile OS suspends the app, the GPU context is dropped,
    // leaving an unrecoverable blank/black canvas on resume.
    if (gl) {
      gl.clearColor(0.1, 0.1, 0.1, 1.0);
      gl.clear(gl.COLOR_BUFFER_BIT);
    }
  }, []);

  return <canvas id="render-surface" className="w-full h-full" />;
}
```

#### Production Standard (Correct)
> **Standard**: Intercepts webglcontextlost with preventDefault(), sets up a fallback surface timeout to guard against hung GPU drivers, listens to tauri://blur for proactive snapshot persistence, and allows safe context restoration upon mobile foregrounding.
```typescript
import { useEffect, useRef, useState } from 'react';
import { listen } from '@tauri-apps/api/event';

interface SurfaceSnapshot {
  timestamp: number;
  viewMatrix: number[];
}

export function CanvasSurface() {
  const canvasRef = useRef<HTMLCanvasElement | null>(null);
  const [fallbackActive, setFallbackActive] = useState<boolean>(false);
  const snapshotRef = useRef<SurfaceSnapshot>({ timestamp: Date.now(), viewMatrix: [1, 0, 0, 1] });

  useEffect(() => {
    const canvas = canvasRef.current;
    if (!canvas) return;

    let gl = canvas.getContext('webgl2');
    let restorationTimer: ReturnType<typeof setTimeout> | null = null;

    const handleContextLost = (e: Event) => {
      e.preventDefault(); // Invariant: prevents permanent Webview tear
      restorationTimer = setTimeout(() => {
        // Fallback: If GPU fails to restore within 2000ms, switch to 2D/DOM fallback surface
        setFallbackActive(true);
      }, 2000);
    };

    const handleContextRestored = () => {
      if (restorationTimer) clearTimeout(restorationTimer);
      setFallbackActive(false);
      gl = canvas.getContext('webgl2');
      // Reinitialize shaders and restore buffers from snapshotRef
    };

    canvas.addEventListener('webglcontextlost', handleContextLost, false);
    canvas.addEventListener('webglcontextrestored', handleContextRestored, false);

    const unlistenPromise = listen('tauri://blur', () => {
      // Synchronously flush state before OS suspension
      sessionStorage.setItem('tauri_surface_state', JSON.stringify(snapshotRef.current));
    });

    return () => {
      canvas.removeEventListener('webglcontextlost', handleContextLost);
      canvas.removeEventListener('webglcontextrestored', handleContextRestored);
      if (restorationTimer) clearTimeout(restorationTimer);
      unlistenPromise.then(unlisten => unlisten());
    };
  }, []);

  if (fallbackActive) {
    return <div className="fallback-surface">Hardware acceleration paused. Tap to refresh.</div>;
  }

  return <canvas ref={canvasRef} id="render-surface" className="w-full h-full" />;
}
```

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 State Restoration Hardware-Fallback Invariant

Tauri 2.0 Webview State Restoration Hardware-Fallback Invariant defines an industrial-grade behavioral standard for mobile engineering. Enforces deterministic lifecycle persistence, headless state snapshots, and automatic software-rendering fallback surfaces in Tauri 2.0 mobile deployments. Eliminates fatal black-screen freezing caused by WebGL/GPU context eviction during Android Activity pause/resume and iOS application background transitions. 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: Unchecked Webview GPU Context Eviction Leading to Unrecoverable Mobile Black Screen 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 DriftUnchecked Webview GPU Context Eviction Leading to Unrecoverable Mobile Black ScreenCritical
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 listen to Tauri lifecycle events (`tauri

Engineers MUST ALWAYS listen to Tauri lifecycle events (`tauri://blur`, `tauri://focus`, or native mobile resume signals) and commit a synchronous local snapshot before the process is suspended.

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 ALWAYS intercept `webglcontextlost` and `webglcontextrestored` events on canvas elements, immediately invoking `event.preventDefault()` to allow context recovery.

Engineers MUST ALWAYS intercept `webglcontextlost` and `webglcontextrestored` events on canvas elements, immediately invoking `event.preventDefault()` to allow context recovery.

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

Services MUST implement a software-rendering or DOM-based fallback surface if GPU context restoration fails within a deterministic timeout threshold (e.g., 2000ms).

Services MUST implement a software-rendering or DOM-based fallback surface if GPU context restoration fails within a deterministic timeout threshold (e.g., 2000ms).

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

Components NEVER assume canvas textures or GPU buffers persist across background/foreground app cycles on iOS or Android.

Components NEVER assume canvas textures or GPU buffers persist across background/foreground app cycles on iOS or 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

Code SHOULD leverage Tauri plugins (e.g., store or persistent key-value bridges) to serialize viewport, navigation, and input state to disk synchronously upon receiving background notifications.

Code SHOULD leverage Tauri plugins (e.g., store or persistent key-value bridges) to serialize viewport, navigation, and input state to disk synchronously upon receiving background notifications.

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 State Restoration Hardware-Fallback Invariant critical for AI coding assistants?

Enforces deterministic lifecycle persistence, headless state snapshots, and automatic software-rendering fallback surfaces in Tauri 2.0 mobile deployments. Eliminates fatal black-screen freezing caused by WebGL/GPU context eviction during Android Activity pause/resume and iOS application background transitions. 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 (Unchecked Webview GPU Context Eviction Leading to Unrecoverable Mobile Black Screen) 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