This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
mobilecritical PriorityID: capacitor-webkit-memory-footprint-ceiling

Capacitor 7 Isolated WebKit Memory Ceiling & Hardware Buffer Offload Guardrail

Enforces strict memory ceiling controls and hardware buffer offloading on Capacitor 7 isolated renderer processes to eliminate OS-level Jetsam and low-memory killer (LMK) terminations. Mandates native file-system referencing, immediate Blob URL revocation, aggressive canvas cleanup, and zero-copy native plugin interfaces.

Prohibited Anti-Pattern: Retaining High-Resolution Media Bitmaps and Unbounded Binary Payloads Inside WebKit Memory Heap

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Capacitor 7 Isolated WebKit Memory Ceiling & Hardware Buffer Offload Guardrail - Enforces strict memory ceiling controls and hardware buffer offloading on Capacitor 7 isolated renderer processes to eliminate OS-level Jetsam and low-memory killer (LMK) terminations. Mandates native file-system referencing, immediate Blob URL revocation, aggressive canvas cleanup, and zero-copy native plugin interfaces.
globs: src/**/*.{ts,tsx,vue,svelte}, ios/App/**/*.{swift,m}, android/app/**/*.{java,kt}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/capacitor-webkit-memory-footprint-ceiling"
---

# Capacitor 7 Isolated WebKit Memory Ceiling & Hardware Buffer Offload Guardrail

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Retaining High-Resolution Media Bitmaps and Unbounded Binary Payloads Inside WebKit Memory Heap

## System Constraints
You are a Principal Mobile Architect enforcing isolated process WebKit memory limits for Capacitor 7 enterprise mobile applications. In iOS WKWebView, the `com.apple.WebKit.WebContent` process runs in a sandboxed, memory-constrained OS slice subject to aggressive Jetsam termination (typically 200MB-300MB on mid-tier hardware, causing silent white-screen crashes via `webViewWebContentProcessDidTerminate:`). You must mandate zero base64 payload transport over the bridge, immediate native disk caching for binary streams, explicit canvas and image buffer dereferencing, and proactive native memory telemetry.

## Strict Guidelines
- Engineers MUST ALWAYS offload file downloads, camera captures, and image transformations directly to the native filesystem and reference them via `Capacitor.convertFileSrc()` rather than loading raw Base64 or ArrayBuffers into the WebKit JS heap.
- Engineers MUST NOT bridge large binary buffers (greater than 512KB) across the Capacitor JavaScript-to-Native bridge as serialized strings or base64 data URIs.
- Code MUST explicitly revoke every object URL via `URL.revokeObjectURL()` immediately after media element hydration or load assignment to prevent WebKit blob registry leakage.
- Services MUST destroy WebGL contexts (`WEBGL_lose_context.loseContext()`) and zero out Canvas dimensions (`canvas.width = 0; canvas.height = 0`) before unmounting views to force immediate unbacking of hardware graphics textures.
- Components NEVER render unbounded lists containing non-virtualized image assets; all image feeds must implement recycling window virtualizers and constrain `loading='lazy'` decoded image counts.

## Bad vs Good Implementations
### Native Disk Offload vs Base64 In-Memory Bridge Transfer

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Transporting image captures as Base64 strings inflates the memory footprint by 33% across the bridge, forces synchronous JSON serialization in the isolated WebKit process, and prevents hardware texture offloading, driving the WebContent process toward Jetsam termination.
```typescript
import { Camera, CameraResultType, CameraSource } from '@capacitor/camera';

// ANTI-PATTERN: Captures raw base64 into WebKit heap, duplicating memory during bridge decoding
export async function captureInspectionPhoto(): Promise<string> {
  const photo = await Camera.getPhoto({
    quality: 90,
    resultType: CameraResultType.Base64,
    source: CameraSource.Camera,
  });

  // Storing a 12MP uncompressed Base64 string consumes 30-50MB of WebContent process heap,
  // accelerating iOS Jetsam termination threshold.
  const dataUrl = `data:image/jpeg;base64,${photo.base64String}`;
  return dataUrl;
}
```

#### Production Standard (Correct)
> **Standard**: Using `CameraResultType.Uri` keeps image decoding within native CoreGraphics/Metal buffers, bypassing the WebKit JavaScript heap entirely. The bridge passes only a small path string, and `Capacitor.convertFileSrc` loads the file directly via the custom URL scheme handler.
```typescript
import { Camera, CameraResultType, CameraSource } from '@capacitor/camera';
import { Capacitor } from '@capacitor/core';
import { Filesystem, Directory } from '@capacitor/filesystem';

// PRODUCTION INVARIANT: Direct native file reference without loading raw pixels into JS heap
export async function captureInspectionPhoto(): Promise<string> {
  const photo = await Camera.getPhoto({
    quality: 85,
    resultType: CameraResultType.Uri,
    source: CameraSource.Camera,
  });

  if (!photo.path) {
    throw new Error('Camera operation failed to persist file to native storage.');
  }

  // Move file to sandboxed persistent app storage natively without crossing the JS bridge
  const fileName = `inspect_${Date.now()}.jpg`;
  const savedFile = await Filesystem.copy({
    from: photo.path,
    to: fileName,
    toDirectory: Directory.Data,
  });

  // Convert file path to local safe scheme (e.g. capacitor://localhost/_capacitor_file_/)
  // WKWebView decodes and renders offscreen native hardware buffers outside JS engine heap
  return Capacitor.convertFileSrc(savedFile.uri);
}
```

### Immediate Context Release for Ephemeral Canvas Processing

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: An orphaned `<canvas>` with explicit width/height retains uncompressed 32-bit RGBA hardware backing textures inside WebKit's graphics layer tree even after being detached, causing silent process kills during heavy mobile usage.
```typescript
export function processSignatureThumbnail(signatureDataUrl: string): HTMLCanvasElement {
  // ANTI-PATTERN: Orphaned canvas retaining decoded bitmap memory
  const canvas = document.createElement('canvas');
  canvas.width = 2048;
  canvas.height = 2048;
  const ctx = canvas.getContext('2d');
  const img = new Image();
  img.src = signatureDataUrl;
  img.onload = () => {
    ctx?.drawImage(img, 0, 0, 512, 512);
  };
  // Canvas retains 16MB backing store in WebKit indefinitely without cleanup
  return canvas;
}
```

#### Production Standard (Correct)
> **Standard**: Wrapping ephemeral canvas processing in a `try...finally` block guarantees that `URL.revokeObjectURL()` frees memory from WebKit's internal blob map and setting canvas dimensions to 0x0 instantly deallocates the hardware bitmap buffer.
```typescript
export async function generateSignatureBlob(sourceBlob: Blob): Promise<Blob> {
  // PRODUCTION INVARIANT: Controlled canvas allocation with immediate dimension zeroing
  const objectUrl = URL.createObjectURL(sourceBlob);
  const canvas = document.createElement('canvas');
  canvas.width = 512;
  canvas.height = 512;
  const ctx = canvas.getContext('2d', { willReadFrequently: false });

  try {
    const img = await new Promise<HTMLImageElement>((resolve, reject) => {
      const element = new Image();
      element.onload = () => resolve(element);
      element.onerror = reject;
      element.src = objectUrl;
    });

    ctx?.drawImage(img, 0, 0, 512, 512);

    return await new Promise<Blob>((resolve, reject) => {
      canvas.toBlob(
        (blob) => (blob ? resolve(blob) : reject(new Error('Export failed'))),
        'image/webp',
        0.8
      );
    });
  } finally {
    // Revoke object URL immediately to reclaim WebKit blob registry memory
    URL.revokeObjectURL(objectUrl);
    // Force graphics layer to release hardware texture buffer
    canvas.width = 0;
    canvas.height = 0;
  }
}
```

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 Isolated WebKit Memory Ceiling & Hardware Buffer Offload Guardrail

Capacitor 7 Isolated WebKit Memory Ceiling & Hardware Buffer Offload Guardrail defines an industrial-grade behavioral standard for mobile engineering. Enforces strict memory ceiling controls and hardware buffer offloading on Capacitor 7 isolated renderer processes to eliminate OS-level Jetsam and low-memory killer (LMK) terminations. Mandates native file-system referencing, immediate Blob URL revocation, aggressive canvas cleanup, and zero-copy native plugin interfaces. 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: Retaining High-Resolution Media Bitmaps and Unbounded Binary Payloads Inside WebKit Memory Heap 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 DriftRetaining High-Resolution Media Bitmaps and Unbounded Binary Payloads Inside WebKit Memory HeapCritical
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 offload file downloads, camera captures, and image transformations directly to the native filesystem and reference them via `Capacitor.convertFileSrc()` rather than loading raw Base64 or ArrayBuffers into the WebKit JS heap.

Engineers MUST ALWAYS offload file downloads, camera captures, and image transformations directly to the native filesystem and reference them via `Capacitor.convertFileSrc()` rather than loading raw Base64 or ArrayBuffers into the WebKit JS heap.

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 bridge large binary buffers (greater than 512KB) across the Capacitor JavaScript-to-Native bridge as serialized strings or base64 data URIs.

Engineers MUST NOT bridge large binary buffers (greater than 512KB) across the Capacitor JavaScript-to-Native bridge as serialized strings or base64 data URIs.

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 MUST explicitly revoke every object URL via `URL.revokeObjectURL()` immediately after media element hydration or load assignment to prevent WebKit blob registry leakage.

Code MUST explicitly revoke every object URL via `URL.revokeObjectURL()` immediately after media element hydration or load assignment to prevent WebKit blob registry leakage.

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 destroy WebGL contexts (`WEBGL_lose_context.loseContext()`) and zero out Canvas dimensions (`canvas.width = 0

Services MUST destroy WebGL contexts (`WEBGL_lose_context.loseContext()`) and zero out Canvas dimensions (`canvas.width = 0; canvas.height = 0`) before unmounting views to force immediate unbacking of hardware graphics textures.

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 render unbounded lists containing non-virtualized image assets

Components NEVER render unbounded lists containing non-virtualized image assets; all image feeds must implement recycling window virtualizers and constrain `loading='lazy'` decoded image counts.

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 Isolated WebKit Memory Ceiling & Hardware Buffer Offload Guardrail critical for AI coding assistants?

Enforces strict memory ceiling controls and hardware buffer offloading on Capacitor 7 isolated renderer processes to eliminate OS-level Jetsam and low-memory killer (LMK) terminations. Mandates native file-system referencing, immediate Blob URL revocation, aggressive canvas cleanup, and zero-copy native plugin interfaces. 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 (Retaining High-Resolution Media Bitmaps and Unbounded Binary Payloads Inside WebKit Memory Heap) 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