Original Files
0 B Empty
Single HTML
0 B Ready
Offline PDF
0 B 0 pages

Turn Your Project Into 1 Offline File

Select your HTML file along with any images, fonts, or sounds. Everything is compressed and combined into a single file that works completely offline.

Drop your HTML, images, fonts, or folder here Tap here to select your files
Select multiple files at once or drop an entire project folder Supports HTML pages, pictures, custom fonts, and sound effects
index.html
Ready to save

Extra Media & Fonts Added

Some added files aren't linked to your HTML yet. Open Advanced to connect them or cut sprite sheets.

Check Links
1. Project Files Empty
Drop HTML, folders, pictures, fonts, or audio Tap to add HTML, pictures, fonts, or audio
No files added yet
2. App Code
0 B
3. Size & Quality Options 72% Quality • Extra Small
Converts images to modern WebP format whenever it reduces file size.
Image Quality: 72%
Max Dimensions:
Compresses your entire app and fonts so the final HTML and PDF take up minimal space.
Automatically makes uploaded font files available to your page CSS.
Developer & PDF Layout Tweaks
Paste-and-Go Cartridge Generator

Master AI System Prompt

Copy this prompt into Claude, ChatGPT, or Gemini, replace the placeholder at the bottom with your app or game description, and generate a compliant single-file ConsoleZero cartridge.

Unrestricted Visual Styling
Does not force ConsoleZero’s dark UI palette onto your cartridges—AI models can design light paper tools, retro pixel interfaces, or high-contrast field screens.
Selective Bridge Wiring (Zero Bloat)
Instructs the AI to integrate only the hardware bridges your requested app genuinely uses, preventing unused sensor polling and unnecessary permission prompts.
CONSOLEZERO_MASTER_PROMPT.txt Ready to copy
Build a 100% single-file offline HTML/CSS/JS app ("cartridge") for the ConsoleZero airgapped Android WebView.

HARD RULES:
- Single HTML file with inline <style> and <script>. ZERO external URLs, CDNs, fonts, or libraries (blockNetworkLoads=true).
- Mobile-first UI/UX: Design exclusively for handheld mobile devices (touch-friendly controls, single-column vertical layout, thumb-zone ergonomics, zero hover dependencies).
- Freedom of visual theme/colors (light, dark, retro, minimal—match the user's request). Never use CSS backdrop-filter.
- Include: <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover">
- Use min-height: 100dvh; font-size >= 16px on inputs; >= 48x48px touch targets with touch-action: manipulation.
- Never use alert(), confirm(), or prompt()—render all feedback inline in the DOM.
- Live camera <video> MUST have: autoplay playsinline muted.
- WebAudio AudioContext starts suspended: always run "if (ctx.state === 'suspended') await ctx.resume();" inside a tap handler.
- Draw graphics/audio via Canvas, inline SVG, WebAudio, or Base64 Data URIs (or window.__ASSETS__["sheet.png#slices"] for Cartridge Maker).

BRIDGES (ONLY wire bridges the requested app actually uses; guard all native calls):
- Permissions check: JSON.parse(window.AndroidNativeUtils?.getPermissionsJson() || "{}")
- GPS ("gps"): navigator.geolocation OR JSON.parse(window.AndroidNativeGps.getDeviceLocation()) -> {status, lat, lng, accuracy} (optional: cancelLocationSearch())
- Haptics ("haptics"): navigator.vibrate(ms) OR window.AndroidNativeUtils?.vibrate(ms) (max 2000)
- Clipboard ("clipboard"): navigator.clipboard.writeText(t) OR window.AndroidNativeUtils?.copyToClipboard(t)
- Alerts ("notifications"): new Notification(title, {body}) OR window.AndroidNativeUtils?.showNotification(title, body)
- Export ("export"): window.AndroidFileExporter?.saveTextFile(text, name, mime) (also: saveBase64File, shareTextFile, printDocument, printHtml)
- Import ("import"): File ingress & uploads via <input type="file"> (CSV, JSON, images, data) - check perms.import
- Sensors ("sensors"): JSON.parse(window.AndroidSensors.getSensorData()) -> {status, accelerometer, gyroscope, magnetometer, light}
- NFC ("nfc", "nfcWrite", "nfcLock"): new NDEFReader() (scan/write/makeReadOnly) OR window.AndroidNfc: readNfcTag() -> {status:"success", tagId, payload} & armWritePayload(JSON.stringify({type, data, lockAfterWrite})) + window.onNfcWriteComplete(success, message). Require 2-step inline confirmation before irreversible tag locking.
- Camera ("camera"): <input type="file" accept="image/*" capture="environment"> OR navigator.mediaDevices.getUserMedia({video:{facingMode:"environment"}})
- Mic ("mic"): navigator.mediaDevices.getUserMedia({audio:true}) + AudioContext AnalyserNode
- External Intents ("externalLinks"): window.location.href = "geo:lat,lng?q=lat,lng" or "tel:..."
- Storage: localStorage / IndexedDB (isolated per cartridge origin).

Output ONLY the complete single-file HTML code block, tailored to the following app request:
[DESCRIBE YOUR APP OR GAME HERE]
Want to Use Your Own Photos, Sprites, or Custom Fonts?
By default, the prompt above tells the AI to draw everything with code so your app works immediately with zero extra files. If you want to supply your own images, sprite sheets, audio, or fonts, paste this extra line at the bottom of your prompt—then switch to the Easy or Advanced tab here and drop in the generated HTML + your files to pack them into one offline file.
CUSTOM_ASSETS_ADDON.txt Optional Add-On
CUSTOM ASSETS OVERRIDE: For [LIST YOUR ASSETS, e.g., the player sprite, background photo, or custom font], do NOT draw inline SVGs—use clean relative filenames (like "player.png" or "background.jpg") so I can pack my own files in Cartridge Maker.
Airgapped Cartridge Runtime • Public SDK & Hardware Specification

ConsoleZero Developer Reference

Build self-contained HTML, CSS, and JavaScript applications—called cartridges—that execute inside an airgapped Android sandbox with isolated local persistence and 12 granular, Default-OFF hardware bridges.

Package Model
100% Single-File HTML
Network Boundary
blockNetworkLoads = true
Origin Isolation
https://[slug].consolezero.local/
Hardware Security
12 Default-OFF Permissions
Section 01 • Architecture & SDK Reference

Developer Manual, 12 Hardware Bridges & Starter Boilerplate

Explore the airgapped sandbox architecture, WebView rendering invariants, all 12 native bridge APIs, and the downloadable single-file starter template.

1.1 Airgapped Single-File Model & Origin Isolation

ConsoleZero executes portable web utilities—imported as .html, .htm, .txt, .json, or self-contained cartridge .pdf files—inside a locked-down Android WebView container. Every cartridge runs locally with zero telemetry and zero outbound network connectivity.

01 • Single-File Payload

Self-Contained Source

All HTML, CSS, JavaScript, and embedded assets reside in a single portable file—or are inlined via Cartridge Maker—with zero external CDN references.

02 • Isolated Origin

Per-Cartridge Sandbox

Each cartridge loads from its own private local origin (https://[slug].consolezero.local/), keeping localStorage and IndexedDB walled off from every other cartridge.

03 • Native Bridges

Gated Hardware Layer

Both standard W3C Web APIs and window.Android* JavaScript interfaces remain gated behind user-controlled, Default-OFF toggles until explicitly enabled.

1.2 The Default-OFF Permission Philosophy

Every hardware and system capability in ConsoleZero defaults to DISABLED whenever a cartridge is imported. JavaScript running inside a cartridge has read-only visibility into its permission state and cannot programmatically enable toggles or escalate privileges. On startup, ConsoleZero also checks physical device hardware chips (such as NFC or Gyroscope) and disables unsupported toggles automatically.

Runtime Permission Inspection Read-Only Bridge
function getConsoleZeroPermissions() {
  if (!window.AndroidNativeUtils || typeof window.AndroidNativeUtils.getPermissionsJson !== 'function') {
    return { inContainer: false, airgapped: false };
  }
  try {
    const perms = JSON.parse(window.AndroidNativeUtils.getPermissionsJson());
    return { inContainer: true, ...perms };
    // Example keys: gps, camera, mic, haptics, clipboard,
    // externalLinks, sensors, nfc, nfcWrite, nfcLock, notifications, export, import, airgapped
  } catch (err) {
    return { inContainer: true, parseError: err.message };
  }
}

1.3 Mobile WebView Rules & Rendering Invariants

Mobile Chromium WebViews enforce stricter media, viewport, and GPU compositing constraints than desktop browsers. Follow these seven invariants so cartridges behave reliably across Android phones and tablets:

Invariant Platform Behavior Required Implementation
Zero Remote Assets blockNetworkLoads = true drops all external HTTP/HTTPS requests silently. Inline all CSS, JS, SVG, Canvas graphics, and Data URIs inside the HTML file.
Viewport & 100dvh Soft keyboards and system bars resize dynamic mobile viewports; 100vh clips content. Include viewport meta and use min-height: 100dvh on full-screen layouts.
16px Input Minimum Mobile WebViews auto-zoom the viewport when focusing form fields smaller than 16px. Set font-size: 16px on all input, select, and textarea elements.
48px Touch Targets Small interactive controls cause mis-taps on handheld devices in field conditions. Use min-height: 48px, min-width: 48px, and touch-action: manipulation.
No backdrop-filter Frosted blur layers can corrupt WebView GPU compositing and flicker over WebRTC or maps. Use solid or alpha-tinted opaque surfaces instead of backdrop-filter: blur().
WebAudio Gesture Gate WebView initializes AudioContext in the suspended state until user interaction. Call if (ctx.state === 'suspended') await ctx.resume(); inside a tap handler.
Inline Camera Video Live camera streams refuse to render inline or trigger fullscreen without playback flags. Always declare <video autoplay playsinline muted> on WebRTC video elements.

1.4 Complete Reference: 12 Hardware Bridges & Platform Capabilities

ConsoleZero exposes native hardware through both direct window.Android* interfaces and standard HTML5 Web API polyfills. Only integrate the bridges your cartridge actively requires, and always handle disabled or desktop-fallback states gracefully.

Showing 12 of 12
Bridge 01

Offline GNSS Satellite GPS

key: gps

Acquires real satellite latitude, longitude, and accuracy offline without cellular service or Wi-Fi.

Practical Use Cases Field surveys, waypoint logging, offline coordinate calculators, emergency check-ins.
Exposed Interfaces navigator.geolocation • window.AndroidNativeGps
Rule & Behavior: First cold fix may return status "acquiring" while satellites lock in the background. Call cancelLocationSearch() to abort active polling if the user leaves the view.
navigator.geolocation • window.AndroidNativeGps
function requestGpsFix(onUpdate) {
  if (window.AndroidNativeGps) {
    const res = JSON.parse(window.AndroidNativeGps.getDeviceLocation());
    // status: "success" | "acquiring" | "disabled" | "error"
    if (res.status === 'success') {
      onUpdate({ lat: res.lat, lng: res.lng, accuracyFt: res.accuracy });
    } else {
      onUpdate({ pending: res.status === 'acquiring', message: res.message });
    }
    return;
  }
  navigator.geolocation?.getCurrentPosition(
    pos => onUpdate({ lat: pos.coords.latitude, lng: pos.coords.longitude }),
    err => onUpdate({ message: err.message })
  );
}

function stopGpsSearch() {
  window.AndroidNativeGps?.cancelLocationSearch?.();
}
Bridge 02

Haptic Vibration Feedback

key: haptics

Fires crisp tactile vibration impulses for button presses, barcode detections, timers, and arcade hits.

Practical Use Cases QR/NFC scan confirmations, game collisions, metronomes, tactile keypad clicks.
Exposed Interfaces navigator.vibrate • AndroidNativeUtils.vibrate
Rule & Behavior: Native bridge caps pulse duration at 2000ms. Keep game and UI pulses brief (25–120ms) for responsive feedback.
navigator.vibrate • window.AndroidNativeUtils.vibrate
function triggerHaptic(ms = 60) {
  if (window.AndroidNativeUtils && typeof window.AndroidNativeUtils.vibrate === 'function') {
    window.AndroidNativeUtils.vibrate(ms);
  } else if (typeof navigator.vibrate === 'function') {
    navigator.vibrate(ms);
  }
}
Bridge 03

System Clipboard Copy

key: clipboard

Copies generated coordinates, passwords, diagnostic summaries, or scanned payloads to the Android clipboard.

Practical Use Cases Password/key generators, coordinate sharing, QR/NFC payload copy buttons.
Exposed Interfaces navigator.clipboard • copyToClipboard
Rule & Behavior: When granted, the container displays a native Toast confirmation. Keep an inline fallback status message for desktop testing.
navigator.clipboard.writeText • copyToClipboard
async function copyToSystemClipboard(text, statusEl) {
  try {
    if (window.AndroidNativeUtils?.copyToClipboard) {
      window.AndroidNativeUtils.copyToClipboard(text);
    } else if (navigator.clipboard?.writeText) {
      await navigator.clipboard.writeText(text);
    }
    if (statusEl) statusEl.textContent = 'Copied to clipboard.';
  } catch (err) {
    if (statusEl) statusEl.textContent = 'Clipboard unavailable: ' + err.message;
  }
}
Bridge 04

Local System Notifications

key: notifications

Dispatches offline Android system notifications for countdown timers, interval reminders, and background alerts.

Practical Use Cases Field checklists, interval timers, sensor threshold alerts, offline Pomodoro apps.
Exposed Interfaces new Notification • showNotification
Rule & Behavior: Supports both the standard HTML5 Notification constructor (with requestPermission) and the direct showNotification(title, body) bridge.
new Notification • AndroidNativeUtils.showNotification
function sendOfflineAlert(title, body) {
  if (window.AndroidNativeUtils?.showNotification) {
    window.AndroidNativeUtils.showNotification(title, body);
    return;
  }
  if ('Notification' in window) {
    if (Notification.permission === 'granted') {
      new Notification(title, { body });
    } else if (Notification.permission !== 'denied') {
      Notification.requestPermission().then(perm => {
        if (perm === 'granted') new Notification(title, { body });
      });
    }
  }
}
Bridge 05

App-Scoped File Exporter

key: export

Saves CSV, JSON, text, or Base64 files directly to Android Downloads/, shares files, or invokes native print without broad storage permissions.

Practical Use Cases Field log CSV exports, high-score backups, inspection reports, printable checklists.
Exposed Interfaces window.AndroidFileExporter
Rule & Behavior: Rate-limited to 1 request every 3 seconds and always presents a native user confirmation dialog before saving or sharing.
saveTextFile • saveBase64File • shareTextFile • printDocument
function exportCsvToDownloads(csvText, fileName = 'field_log.csv') {
  if (window.AndroidFileExporter?.saveTextFile) {
    window.AndroidFileExporter.saveTextFile(csvText, fileName, 'text/csv');
    return true;
  }
  const blob = new Blob([csvText], { type: 'text/csv;charset=utf-8' });
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url;
  a.download = fileName;
  a.click();
  URL.revokeObjectURL(url);
  return true;
}

// Additional exporter methods:
// window.AndroidFileExporter?.saveBase64File(base64Data, 'image.png', 'image/png');
// window.AndroidFileExporter?.shareTextFile(csvText, 'field_log.csv', 'text/csv');
// window.AndroidFileExporter?.printDocument();
// window.AndroidFileExporter?.printHtml('<h1>Inspection Report</h1>');
Bridge 06

Motion & Ambient Light Sensors

key: sensors

Streams live 3-axis Accelerometer, Gyroscope, Magnetometer/Compass, and Ambient Light (Lux) telemetry at UI polling speed.

Practical Use Cases Spirit levels, tilt-steered arcade games, compass headings, light meters, vibration loggers.
Exposed Interfaces window.AndroidSensors.getSensorData()
Rule & Behavior: Check status === "success" on each poll; returns "disabled" when off. Missing hardware chips automatically report 0.
window.AndroidSensors.getSensorData()
function pollMotionAndLight() {
  if (!window.AndroidSensors?.getSensorData) return null;
  const data = JSON.parse(window.AndroidSensors.getSensorData());
  if (data.status !== 'success') return null;
  return {
    accel: data.accelerometer, // { x, y, z }
    gyro: data.gyroscope,      // { x, y, z }
    mag: data.magnetometer,    // { x, y, z }
    lux: data.light            // ambient lux float
  };
}
Bridge 07

NFC Tag Reader, Writer & Lock

keys: nfc • nfcWrite • nfcLock

Reads NDEF payloads and Hex Tag IDs, formats/writes text, URI, or MIME records, and optionally locks physical tags read-only.

Practical Use Cases Asset inventory tags, equipment inspection logs, offline contact or URL cards.
Exposed Interfaces new NDEFReader() • window.AndroidNfc
Rule & Behavior: IRREVERSIBLE LOCK: Setting lockAfterWrite: true or calling makeReadOnly() permanently seals the tag. Require an explicit 2-step inline UI confirmation first.
new NDEFReader() • window.AndroidNfc
// Read tag scan polling -> returns { status: 'success'|'waiting'|'error', tagId, payload }
function readNfc() {
  if (!window.AndroidNfc) return { status: 'unavailable' };
  return JSON.parse(window.AndroidNfc.readNfcTag());
}

// Arm write or write+lock for physical tag tap -> returns { status: 'armed', message }
function armNfcWrite(data, type = 'url', lockAfterWrite = false) {
  if (!window.AndroidNfc) return { status: 'unavailable' };
  const payload = JSON.stringify({ type, data, lockAfterWrite });
  return JSON.parse(window.AndroidNfc.armWritePayload(payload));
}

// Global callback triggered by ConsoleZero when physical NFC tap completes
window.onNfcWriteComplete = function(success, message) {
  console.log('NFC Write Result:', success, message);
};
Bridge 08

Camera Capture & WebRTC Video

key: camera

Supports both system camera photo capture via file inputs and live rear/front WebRTC video streams on canvas or video elements.

Practical Use Cases QR/barcode scanners, field photo attachments, visual inspection tools, AR overlays.
Exposed Interfaces <input capture> • getUserMedia({ video })
Rule & Behavior: Live <video> elements MUST include autoplay playsinline muted. Without playsinline, mobile WebViews fail to render frames inline.
<video autoplay playsinline muted> • getUserMedia
// HTML: <video id="cam-preview" autoplay playsinline muted></video>
async function startRearCamera(videoEl) {
  const stream = await navigator.mediaDevices.getUserMedia({
    video: { facingMode: 'environment' },
    audio: false
  });
  videoEl.srcObject = stream;
  await videoEl.play();
  return stream;
}
// Photo-only capture HTML:
// <input type="file" accept="image/*" capture="environment">
Bridge 09

Microphone & WebAudio Streams

key: mic

Captures live microphone streams for acoustic analysis and powers zero-dependency WebAudio synthesizers.

Practical Use Cases Decibel meters, instrument tuners, spectrum visualizers, procedural arcade SFX.
Exposed Interfaces getUserMedia({ audio: true }) • AudioContext
Rule & Behavior: AudioContext boots in "suspended" state inside mobile WebViews. Always invoke await audioCtx.resume() inside a user tap handler.
getUserMedia({ audio: true }) • AudioContext
async function startDecibelMeter() {
  const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
  const ctx = new (window.AudioContext || window.webkitAudioContext)();
  if (ctx.state === 'suspended') await ctx.resume();
  const analyser = ctx.createAnalyser();
  analyser.fftSize = 256;
  ctx.createMediaStreamSource(stream).connect(analyser);
  return { ctx, analyser, stream };
}
Bridge 10

External Link Routing

key: externalLinks

Hands off map coordinates, phone numbers, or external links to native Android apps when explicitly permitted.

Practical Use Cases Opening saved GPS pins in an offline map app, dialing emergency contacts from field guides.
Exposed Interfaces geo: • tel: • Intent Handoff
Rule & Behavior: When disabled in Cartridge Settings, all external intent navigation is blocked at the container boundary with a security notice.
geo: • tel: • Intent Handoff
function openInMapsApp(lat, lng) {
  window.location.href = `geo:${lat},${lng}?q=${lat},${lng}`;
}

function openPhoneDialer(number) {
  window.location.href = `tel:${encodeURIComponent(number)}`;
}
Bridge 11

Isolated Local Storage Persistence

built-in: origin

Persists user state, offline records, and high scores per cartridge under https://[slug].consolezero.local/.

Practical Use Cases Offline databases, inspection forms, arcade high-score tables, user preferences.
Exposed Interfaces localStorage • IndexedDB
Rule & Behavior: Storage is strictly isolated per cartridge slug—other cartridges cannot access it, and deleting a cartridge wipes its origin storage.
localStorage • IndexedDB
function saveCartridgeState(key, data) {
  try {
    localStorage.setItem(key, JSON.stringify(data));
    return true;
  } catch (err) {
    return false;
  }
}

function loadCartridgeState(key, fallback) {
  try {
    const raw = localStorage.getItem(key);
    return raw ? JSON.parse(raw) : fallback;
  } catch (err) {
    return fallback;
  }
}
Bridge 12

Asset Inlining & Cartridge Maker

built-in: zero-cdn

Renders crisp visuals offline using procedural Canvas/SVG, inline Base64 Data URIs, or Cartridge Maker asset bundling.

Practical Use Cases Retro sprite games, offline icon sets, custom embedded fonts, synthesized audio WAVs.
Exposed Interfaces Canvas / SVG • Base64 • __ASSETS__
Rule & Behavior: Relative paths like ./sprite.png fail unless inlined into Base64 Data URIs or bundled via Cartridge Maker (window.__ASSETS__).
Canvas / SVG • Base64 • window.__ASSETS__
// Procedural sprite or Cartridge Maker slice lookup
function getSpriteFrame(sheetKey, index) {
  const slices = window.__ASSETS__ && window.__ASSETS__[sheetKey + '#slices'];
  if (Array.isArray(slices) && slices[index]) {
    return slices[index]; // Base64 Data URI
  }
  return null; // Fallback to procedural Canvas 2D drawing
}

No hardware bridges match your current filter.

Section 02 • Ready-to-Run Template

Minimal Starter Boilerplate

A clean, production-ready single-file HTML/CSS/JS starter cartridge demonstrating mobile WebView rules, safe bridge detection, localStorage persistence, haptics, clipboard copy, and CSV export—with zero external dependencies and graceful desktop browser fallbacks.

consolezero-starter.html Zero External CDNs
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover">
  <title>ConsoleZero Field Starter</title>
  <style>
    :root {
      --bg: #101012;
      --card: #24242A;
      --well: #141418;
      --border: #2E2E36;
      --text: #FFFFFF;
      --text-soft: #E4E4E7;
      --accent: #38BDF8;
      --accent-ink: #001D29;
      --ok: #4ADE80;
      --warn: #FDE047;
    }
    * { box-sizing: border-box; -webkit-tap-highlight-color: transparent; }
    html, body {
      margin: 0;
      padding: 0;
      min-height: 100dvh;
      background: var(--bg);
      color: var(--text);
      font-family: system-ui, -apple-system, sans-serif;
    }
    main {
      max-width: 640px;
      margin: 0 auto;
      padding: 16px;
      display: flex;
      flex-direction: column;
      gap: 12px;
    }
    .card {
      background: var(--card);
      border: 1px solid var(--border);
      border-radius: 16px;
      padding: 16px;
      display: flex;
      flex-direction: column;
      gap: 10px;
    }
    h1 { margin: 0; font-size: 20px; color: var(--accent); }
    p { margin: 0; font-size: 14px; color: var(--text-soft); line-height: 1.5; }
    label { font-size: 13px; font-weight: 600; color: var(--text-soft); }
    input[type="text"] {
      width: 100%;
      min-height: 48px;
      padding: 10px 12px;
      border-radius: 10px;
      border: 1px solid var(--border);
      background: var(--well);
      color: var(--text);
      font-size: 16px;
    }
    .btn-row { display: flex; flex-wrap: wrap; gap: 8px; }
    button {
      min-height: 48px;
      min-width: 48px;
      padding: 10px 16px;
      border-radius: 12px;
      border: none;
      background: var(--accent);
      color: var(--accent-ink);
      font-size: 15px;
      font-weight: 700;
      cursor: pointer;
      touch-action: manipulation;
    }
    button.secondary {
      background: var(--well);
      color: var(--text);
      border: 1px solid var(--border);
    }
    .status-box {
      background: var(--well);
      border: 1px solid var(--border);
      border-radius: 10px;
      padding: 10px 12px;
      font-family: ui-monospace, monospace;
      font-size: 13px;
      color: var(--ok);
      word-break: break-word;
    }
  </style>
</head>
<body>
  <main>
    <section class="card">
      <h1>ConsoleZero Starter Cartridge</h1>
      <p id="env-status">Checking container environment...</p>
      <label for="note-input">Field Note (Persisted Locally)</label>
      <input id="note-input" type="text" placeholder="Enter offline note or measurement...">
      <div class="btn-row">
        <button type="button" onclick="saveNote()">Save Note</button>
        <button type="button" class="secondary" onclick="pulseHaptic()">Vibrate</button>
        <button type="button" class="secondary" onclick="copyNote()">Copy</button>
        <button type="button" class="secondary" onclick="exportCsv()">Export CSV</button>
      </div>
      <div class="status-box" id="log-box">Ready.</div>
    </section>
  </main>

  <script>
    const STORAGE_KEY = 'cz_starter_notes_v1';

    function setLog(msg) {
      const el = document.getElementById('log-box');
      if (el) el.textContent = msg;
    }

    function detectEnvironment() {
      const envEl = document.getElementById('env-status');
      if (!envEl) return;
      if (window.AndroidNativeUtils?.getPermissionsJson) {
        try {
          const perms = JSON.parse(window.AndroidNativeUtils.getPermissionsJson());
          envEl.textContent = 'Running in ConsoleZero Airgapped Sandbox (haptics: ' + perms.haptics + ', export: ' + perms.export + ').';
        } catch (err) {
          envEl.textContent = 'ConsoleZero container detected.';
        }
      } else {
        envEl.textContent = 'Running in standard web browser fallback mode.';
      }
    }

    function loadSavedNote() {
      const input = document.getElementById('note-input');
      if (!input) return;
      try {
        const saved = localStorage.getItem(STORAGE_KEY);
        if (saved) input.value = saved;
      } catch (err) {
        setLog('Storage unavailable: ' + err.message);
      }
    }

    function saveNote() {
      const input = document.getElementById('note-input');
      if (!input) return;
      try {
        localStorage.setItem(STORAGE_KEY, input.value);
        pulseHaptic(40);
        setLog('Saved locally at ' + new Date().toLocaleTimeString());
      } catch (err) {
        setLog('Save failed: ' + err.message);
      }
    }

    function pulseHaptic(ms = 75) {
      if (window.AndroidNativeUtils?.vibrate) {
        window.AndroidNativeUtils.vibrate(ms);
        setLog('Triggered native haptic pulse (' + ms + 'ms).');
      } else if (typeof navigator.vibrate === 'function') {
        navigator.vibrate(ms);
        setLog('Triggered browser vibration (' + ms + 'ms).');
      } else {
        setLog('Haptics unavailable in this browser.');
      }
    }

    async function copyNote() {
      const input = document.getElementById('note-input');
      const text = input ? input.value : '';
      if (!text) {
        setLog('Enter text before copying.');
        return;
      }
      if (window.AndroidNativeUtils?.copyToClipboard) {
        window.AndroidNativeUtils.copyToClipboard(text);
        setLog('Sent text to Android clipboard.');
      } else if (navigator.clipboard?.writeText) {
        await navigator.clipboard.writeText(text);
        setLog('Copied to clipboard.');
      } else {
        setLog('Clipboard API unavailable.');
      }
    }

    function exportCsv() {
      const input = document.getElementById('note-input');
      const note = (input ? input.value : '').replace(/"/g, '""');
      const csv = 'Timestamp,Note\n' + new Date().toISOString() + ',"' + note + '"\n';
      if (window.AndroidFileExporter?.saveTextFile) {
        window.AndroidFileExporter.saveTextFile(csv, 'starter_note.csv', 'text/csv');
        setLog('Export requested via AndroidFileExporter.');
      } else {
        const blob = new Blob([csv], { type: 'text/csv;charset=utf-8' });
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = 'starter_note.csv';
        a.click();
        URL.revokeObjectURL(url);
        setLog('Downloaded starter_note.csv.');
      }
    }

    detectEnvironment();
    loadSavedNote();
  </script>
</body>
</html>