This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
mobilecritical PriorityID: capacitor-7-wkwebview-state-persistence-memory-trim

Capacitor 7 WKWebView Process Eviction State Persistence and Memory Trim Standard

Enforces deterministic state serialization and memory trimming invariants for hybrid Capacitor 7 applications facing aggressive OS thermal throttling or iOS Jetsam process termination. Prevents silent WKWebView content process drops from causing catastrophic user data loss by binding native lifecycle events to resilient, schema-validated storage snapshots and proactive cache deallocation.

Prohibited Anti-Pattern: Relying on In-Memory State and Window Lifecycle Events Under Aggressive Mobile OS WebProcess Termination

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Capacitor 7 WKWebView Process Eviction State Persistence and Memory Trim Standard - Enforces deterministic state serialization and memory trimming invariants for hybrid Capacitor 7 applications facing aggressive OS thermal throttling or iOS Jetsam process termination. Prevents silent WKWebView content process drops from causing catastrophic user data loss by binding native lifecycle events to resilient, schema-validated storage snapshots and proactive cache deallocation.
globs: src/**/*.{ts,tsx}, src/store/**/*.{ts,tsx}, src/lifecycle/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/capacitor-7-wkwebview-state-persistence-memory-trim"
---

# Capacitor 7 WKWebView Process Eviction State Persistence and Memory Trim Standard

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Relying on In-Memory State and Window Lifecycle Events Under Aggressive Mobile OS WebProcess Termination

## System Constraints
You are a Principal Mobile Architect enforcing Capacitor 7 WKWebView process eviction resilience and memory trim boundaries. In iOS and Android hybrid apps, the native OS kills backgrounded or high-memory WebContent processes (Jetsam / onTrimMemory) without triggering window 'unload' or 'beforeunload'. You must ensure all state machines decouple hot in-memory state from recovery snapshots, hook directly into Capacitor native lifecycle bridges, and rigorously prune uncompressed assets before application backgrounding occurs.

## Strict Guidelines
- Engineers MUST ALWAYS listen to Capacitor 7 `App.addListener('appStateChange', ...)` instead of relying on standard DOM `visibilitychange` or `pagehide` events for critical state persistence.
- Engineers MUST NOT maintain uncompressed binary blobs, high-resolution base64 strings, or large decoupled canvas buffers in JavaScript memory when the app transitions to `isActive: false`.
- State managers MUST commit a schema-versioned, synchronous snapshot to resilient native-backed storage (Capacitor Preferences, SQLite, or Safe FileSystem) immediately upon receiving `appStateChange({ isActive: false })`.
- Rehydration pipelines MUST validate stored snapshot schema versions and integrity hashes during application bootstrap, invalidating and gracefully fallback-migrating corrupted or out-of-date eviction snapshots.
- Components NEVER store dirty multi-step transactional state exclusively in volatile memory (e.g., standard React useState or Pinia/Redux memory trees) without a background-safe persistence coordinator.

## Bad vs Good Implementations
### Naive In-Memory State Retention vs. Capacitor 7 Lifecycle Memory Trim Coordinator

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Window-level lifecycle events like 'beforeunload' and 'pagehide' do not fire when iOS Jetsam or thermal engines terminate the com.apple.WebKit.WebContent process in the background. Retaining heavy cached assets in memory also drastically increases the process footprint, making the app the primary target for OS eviction.
```typescript
import { useState, useEffect } from 'react';

export const useFormState = () => {
  const [formData, setFormData] = useState({ step: 1, answers: {}, cachedAssets: [] });

  useEffect(() => {
    // ANTI-PATTERN: Standard DOM unload events are completely bypassed
    // when iOS WKWebView WebContent process terminates via Jetsam.
    const handleUnload = () => {
      localStorage.setItem('form_backup', JSON.stringify(formData));
    };
    window.addEventListener('beforeunload', handleUnload);
    return () => window.removeEventListener('beforeunload', handleUnload);
  }, [formData]);

  return { formData, setFormData };
};
```

#### Production Standard (Correct)
> **Standard**: Production invariant compliant implementation ensuring memory safety, deterministic execution, and zero runtime hallucination.
```typescript
import { App, AppState } from '@capacitor/app';
import { Preferences } from '@capacitor/preferences';

interface SnapshotPayload {
  version: number;
  timestamp: number;
  answers: Record<string, unknown>;
}

const SNAPSHOT_KEY = 'app_eviction_snapshot_v1';
const SCHEMA_VERSION = 1;

export class StateEvictionCoordinator {
  private static inMemoryAnswers: Record<string, unknown> = {};
  private static heavyAssetCache: Map<string, ArrayBuffer> = new Map();
  private static isInitialized = false;

  public static async initialize(): Promise<void> {
    if (this.isInitialized) return;

    // 1. Recover state snapshot if recovering from process eviction
    const { value } = await Preferences.get({ key: SNAPSHOT_KEY });
    if (value) {
      try {
        const parsed: SnapshotPayload = JSON.parse(value);
        if (parsed.version === SCHEMA_VERSION) {
          this.inMemoryAnswers = parsed.answers;
        }
      } catch (e) {
        console.error('Snapshot corruption detected, resetting to clean state', e);
        await Preferences.remove({ key: SNAPSHOT_KEY });
      }
    }

    // 2. Bind directly to native Capacitor App lifecycle
    await App.addListener('appStateChange', async (state: AppState) => {
      if (!state.isActive) {
        await this.handleMemoryTrimAndSnapshot();
      }
    });

    this.isInitialized = true;
  }

  public static updateField(key: string, value: unknown): void {
    this.inMemoryAnswers[key] = value;
  }

  private static async handleMemoryTrimAndSnapshot(): Promise<void> {
    // A. Memory Trim: Purge volatile uncompressed assets to reduce Jetsam kill priority
    this.heavyAssetCache.clear();

    // B. Critical State Persistence: Commit atomic state to native preferences
    const snapshot: SnapshotPayload = {
      version: SCHEMA_VERSION,
      timestamp: Date.now(),
      answers: this.inMemoryAnswers
    };

    await Preferences.set({
      key: SNAPSHOT_KEY,
      value: JSON.stringify(snapshot)
    });
  }
}
```

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: Capacitor 7 WKWebView Process Eviction State Persistence and Memory Trim Standard

Capacitor 7 WKWebView Process Eviction State Persistence and Memory Trim Standard defines an industrial-grade behavioral standard for mobile engineering. Enforces deterministic state serialization and memory trimming invariants for hybrid Capacitor 7 applications facing aggressive OS thermal throttling or iOS Jetsam process termination. Prevents silent WKWebView content process drops from causing catastrophic user data loss by binding native lifecycle events to resilient, schema-validated storage snapshots and proactive cache deallocation. 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 In-Memory State and Window Lifecycle Events Under Aggressive Mobile OS WebProcess Termination 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 In-Memory State and Window Lifecycle Events Under Aggressive Mobile OS WebProcess TerminationCritical
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 Capacitor 7 `App.addListener('appStateChange', ...)` instead of relying on standard DOM `visibilitychange` or `pagehide` events for critical state persistence.

Engineers MUST ALWAYS listen to Capacitor 7 `App.addListener('appStateChange', ...)` instead of relying on standard DOM `visibilitychange` or `pagehide` events for critical state persistence.

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 maintain uncompressed binary blobs, high-resolution base64 strings, or large decoupled canvas buffers in JavaScript memory when the app transitions to `isActive

Engineers MUST NOT maintain uncompressed binary blobs, high-resolution base64 strings, or large decoupled canvas buffers in JavaScript memory when the app transitions to `isActive: false`.

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

State managers MUST commit a schema-versioned, synchronous snapshot to resilient native-backed storage (Capacitor Preferences, SQLite, or Safe FileSystem) immediately upon receiving `appStateChange({ isActive

State managers MUST commit a schema-versioned, synchronous snapshot to resilient native-backed storage (Capacitor Preferences, SQLite, or Safe FileSystem) immediately upon receiving `appStateChange({ isActive: false })`.

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

Rehydration pipelines MUST validate stored snapshot schema versions and integrity hashes during application bootstrap, invalidating and gracefully fallback-migrating corrupted or out-of-date eviction snapshots.

Rehydration pipelines MUST validate stored snapshot schema versions and integrity hashes during application bootstrap, invalidating and gracefully fallback-migrating corrupted or out-of-date eviction snapshots.

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 store dirty multi-step transactional state exclusively in volatile memory (e.g., standard React useState or Pinia/Redux memory trees) without a background-safe persistence coordinator.

Components NEVER store dirty multi-step transactional state exclusively in volatile memory (e.g., standard React useState or Pinia/Redux memory trees) without a background-safe persistence coordinator.

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 Capacitor 7 WKWebView Process Eviction State Persistence and Memory Trim Standard critical for AI coding assistants?

Enforces deterministic state serialization and memory trimming invariants for hybrid Capacitor 7 applications facing aggressive OS thermal throttling or iOS Jetsam process termination. Prevents silent WKWebView content process drops from causing catastrophic user data loss by binding native lifecycle events to resilient, schema-validated storage snapshots and proactive cache deallocation. 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 In-Memory State and Window Lifecycle Events Under Aggressive Mobile OS WebProcess Termination) 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

Capacitor