How to Save Unsent AI Prompts When the Network or Provider Goes Offline

You are deep in a flow state, drafting a complex, multi-file architectural refactoring prompt for your LLM coding assistant. You spend five minutes meticulously organizing your code snippets, setting constraints, and detailing the edge cases you want the model to consider. You hit Enter.

Then, silence.

The spinning loader stalls. A toast notification quietly slides into view: Network Error: Failed to fetch, or worse, the provider's API gateway returns a blunt 503 Service Unavailable because an upstream cluster just shed load.

When you refresh the page or restart your client application, your text area is empty. Your carefully crafted prompt—a masterpiece of context engineering that took ten minutes to write—evaporated because it lived solely in a transient DOM state.

For most web applications, losing a paragraph of text is an annoyance. For AI-powered developer tools, chat interfaces, and agentic workflows, losing an unsent prompt breaks the developer feedback loop. As developers build heavier reliance on AI tooling, handling offline states and transient network partitions isn't just an edge-case nicety; it's a core requirement for a resilient developer experience.

Let's examine how to architect bulletproof local persistence for unsent AI prompts, moving from naive browser storage to robust transactional queues.


📋 Table of Contents


The Anatomy of Prompt Loss in AI Interfaces

When an AI request fails, the failure usually happens at one of three layers: the client network layer (your local Wi-Fi drops), the edge proxy layer (Cloudflare or API gateway timeout), or the model inference layer (the provider's GPUs run out of VRAM or return a rate-limit error).

Most modern AI chat UIs handle the response failing by showing a retry button. But they rarely handle the request failing before it hits the wire—or worse, failing while streaming chunks and clearing the input buffer prematurely to "prepare for the response."

[User Types Prompt] 
       │
       ▼
[UI Clears Input Buffer] ──(DANGER ZONE: Buffer wiped before network ack)
       │
       ▼
[Fetch API / WebSocket Send] 
       │
       ├──────► [Success: Response Streams]
       └──────► [Failure: Network Drop / 503] ──► Prompt Lost Forever!

To solve this, we need to invert our mental model: An AI prompt must be treated as a persisted transaction the moment the user stops typing or initiates submission, rather than a transient variable in component state.


1. The Naive localStorage Trap and Its Race Conditions

Scenario: You want a quick fix, so you wire up a React useEffect to sync your prompt input state directly to localStorage on every keystroke.

Why it matters: localStorage is synchronous, blocking the main thread. If your user is typing quickly in a heavy web IDE or chat interface, synchronous writes to disk can cause perceptible input lag (frame drops). Furthermore, localStorage has a strict 5MB limit per origin, and if two browser tabs attempt to write state simultaneously, you hit silent race conditions where the older state overwrites the newer one.

Solution: Abandon synchronous storage for active typing streams. Instead, leverage localStorage only as a debounced backup for simple text inputs, or skip it entirely in favor of asynchronous storage engines.

Code:

import { useEffect, useRef } from 'react';

// A debounced hook for lightweight draft persistence
export function useDebouncedDraft(key: string, value: string, delay = 300) {
  const timeoutRef = useRef<NodeJS.Timeout | null>(null);

  useEffect(() => {
    if (timeoutRef.current) {
      clearTimeout(timeoutRef.current);
    }

    timeoutRef.current = setTimeout(() => {
      try {
        if (value.trim() === '') {
          localStorage.removeItem(key);
        } else {
          localStorage.setItem(key, value);
        }
      } catch (error) {
        // Handle QuotaExceededError gracefully
        console.warn('Failed to save prompt draft to localStorage:', error);
      }
    }, delay);

    return () => {
      if (timeoutRef.current) clearTimeout(timeoutRef.current);
    };
  }, [key, value, delay]);
}

Why this works: Debouncing ensures we aren't hammering the storage layer on every single keystroke (which can happen at 100+ words per minute), reducing main thread contention.

⚠️ Gotcha: localStorage values are plain strings. If your AI prompt includes metadata—such as attached file references, system prompt overrides, or temperature settings—serializing everything into a giant JSON string on every keystroke will quickly degrade garbage collection performance.


2. Moving to IndexedDB with Promisified Transactions

Scenario: Your AI prompts contain large code blocks, markdown structures, and references to previous conversation context. localStorage's 5MB ceiling is too small, and its synchronous nature locks the UI.

Why it matters: IndexedDB provides an asynchronous, transactional object store capable of holding hundreds of megabytes (or gigabytes, depending on browser quotas and available disk space). However, the native IndexedDB API is notoriously verbose, built around event listeners rather than modern async/await patterns.

Solution: Use a lightweight, promise-based wrapper like idb by Jake Archibald, or write a concise abstraction layer that handles object stores for unsent drafts cleanly.

Code:

import { openDB, DBSchema } from 'idb';

interface PromptDraftDB extends DBSchema {
  drafts: {
    key: string;
    value: {
      id: string;
      content: string;
      model: string;
      createdAt: number;
      attachments: Array<{ name: string; size: number; type: string }>;
    };
    indexes: { 'by-date': number };
  };
}

export async function getDraftDB() {
  return openDB<PromptDraftDB>('ai-prompt-store', 1, {
    upgrade(db) {
      const store = db.createObjectStore('drafts', { keyPath: 'id' });
      store.createIndex('by-date', 'createdAt');
    },
  });
}

export async function savePromptDraft(content: string, model: string, attachments = []) {
  const db = await getDraftDB();
  const id = 'current-active-draft'; // Or a unique session ID
  
  await db.put('drafts', {
    id,
    content,
    model,
    createdAt: Date.now(),
    attachments,
  });
}

export async function retrievePromptDraft() {
  const db = await getDraftDB();
  return await db.get('drafts', 'current-active-draft');
}

Why this works: IndexedDB operations run off the main thread in browser worker/background threads, preventing UI jank. Transactions ensure that if your write fails halfway through due to a storage glitch, the database rolls back cleanly instead of leaving corrupted JSON strings.


3. Optimistic UI Mutations and the Draft State Machine

Scenario: The user clicks "Send." The UI immediately clears the text area and displays a loading skeleton. Two seconds later, the network drops. The prompt was cleared from the input, but never reached the server.

Why it matters: Clearing the input buffer before the network request receives an HTTP 200 OK or a successful WebSocket acknowledgment is the #1 cause of lost prompts in modern web apps.

Solution: Implement a explicit state machine for prompt submission: IDLE ➔ TYPING ➔ SUBMITTING ➔ ACKNOWLEDGED (or FAILED_OFFLINE). The draft should only be deleted from local storage after the API gateway confirms receipt.

┌──────┐      Keystroke      ┌────────┐
│ IDLE │ ──────────────────► │ TYPING │
└──────┘                     └────────┘
   ▲                             │
   │      Draft Cleared          │ Click Send
   │      on Server Ack          ▼
┌──────────────┐          ┌────────────┐
│ ACKNOWLEDGED │ ◄─────── │ SUBMITTING │
└──────────────┘          └────────────┘
                                 │
                                 │ Network Failure / 503
                                 ▼
                          ┌────────────────┐
                          │ FAILED_OFFLINE │ (Prompt preserved!)
                          └────────────────┘

Code:

type SubmissionState = 'IDLE' | 'TYPING' | 'SUBMITTING' | 'ACKNOWLEDGED' | 'FAILED_OFFLINE';

interface UsePromptSubmissionReturn {
  state: SubmissionState;
  submitPrompt: (promptText: string) => Promise<void>;
  retryPrompt: () => Promise<void>;
}

// Conceptual state machine transition logic
export function handleSubmissionFailure(error: unknown) {
  if (!navigator.onLine || isNetworkError(error)) {
    // Transition to FAILED_OFFLINE
    // Keep local IndexedDB draft intact!
    return 'FAILED_OFFLINE';
  }
  // Handle application-level errors separately
  return 'IDLE';
}

function isNetworkError(error: unknown): boolean {
  return error instanceof TypeError && error.message === 'Failed to fetch';
}

Why this works: By decoupling the clearing of the input box from the click event, you ensure that failure states are treated as first-class citizens. If the network drops, the user sees a banner: "Network offline. Your prompt has been saved. Click to retry."


4. Handling Multimodal Prompts: Staging Images and Blobs Locally

Scenario: Your AI interface allows users to paste screenshots, drag-and-drop PDFs, or upload audio recordings alongside their text prompt. The user is offline, or the upload request times out midway.

Why it matters: Text is tiny; binary attachments (ArrayBuffer, Blob, File) are large. If you only store the text string of the prompt in IndexedDB, your multimodal attachments vanish the moment the page reloads during an outage.

Solution: Store raw File or Blob objects directly inside your IndexedDB object store alongside the text content. IndexedDB natively supports structured cloning for File and Blob objects in modern browsers.

Code:

export async function saveMultimodalDraft(
  text: string, 
  files: File[]
): Promise<string> {
  const db = await getDraftDB();
  const draftId = crypto.randomUUID();

  // IndexedDB can store File objects directly without manual base64 encoding
  await db.put('drafts', {
    id: draftId,
    content: text,
    model: 'claude-3-5-sonnet', // example model
    createdAt: Date.now(),
    attachments: files.map(file => ({
      name: file.name,
      size: file.size,
      type: file.type,
      data: file, // Storing the raw Blob/File instance
    })),
  });

  return draftId;
}

Why this works: Converting large images or PDFs to Base64 strings to cram them into localStorage bloats memory usage by ~33% and grinds JSON serialization to a halt. Storing raw Blob/File references in IndexedDB avoids serialization overhead entirely.

💡 Practical note: Browsers enforce storage quotas across your entire origin. Storing dozens of high-res screenshots in IndexedDB will trigger eviction warnings much faster than text. Implement an LRU (Least Recently Used) cleanup routine for drafts older than 7 days.


5. Network Boundary Detection and Auto-Resume Guardrails

Scenario: The user loses connection, types a prompt, sees the offline banner, and walks away. Ten minutes later, their Wi-Fi reconnects. You want the app to automatically fire the pending prompt without requiring manual intervention.

Why it matters: Relying solely on window.addEventListener('online', ...) can lead to false positives. A browser might fire online when connected to a local router that has no internet access (e.g., a captive hotel Wi-Fi portal or corporate firewall block).

Solution: Combine navigator.onLine events with a lightweight heartbeat probe (a HEAD request or a cheap /healthz ping) before attempting to flush pending drafts to the LLM API.

Code:

import { useEffect } from 'react';
import { retrievePromptDraft } from './db';

export function useAutoResumeDrafts(onReadyToSubmit: (draft: any) => void) {
  useEffect(() => {
    async function handleOnline() {
      // Verify actual internet connectivity, not just physical link state
      try {
        const response = await fetch('/api/healthz', { 
          method: 'HEAD',
          cache: 'no-store',
          signal: AbortSignal.timeout(3000) 
        });
        
        if (response.ok) {
          const draft = await retrievePromptDraft();
          if (draft && draft.content.trim().length > 0) {
            onReadyToSubmit(draft);
          }
        }
      } catch (err) {
        console.log('Network event fired, but actual connectivity check failed.');
      }
    }

    window.addEventListener('online', handleOnline);
    return () => window.removeEventListener('online', handleOnline);
  }, [onReadyToSubmit]);
}

Why this works: The online event only tells you the network card status changed. Adding a timeout-guarded health check prevents your client from spamming dead requests into a failing proxy gateway as soon as the local interface comes alive.


6. Managing Quota Exhaustion and Storage Eviction Policies

Scenario: Your user's browser is running low on disk space. The browser's storage manager suddenly evicts your application's IndexedDB store, wiping out all saved prompt drafts without warning.

Why it matters: By default, browser storage is best-effort (evictable). If the device fills up, the browser reserves the right to wipe unpersisted local databases to free up space for system operations.

Solution: Request persistent storage via the Storage API (navigator.storage.persist()) and check your current usage against the available quota before letting users stage large multimodal prompts.

Code:

export async function requestPersistentStorage(): Promise<boolean> {
  if (navigator.storage && navigator.storage.persist) {
    const isPersisted = await navigator.storage.persisted();
    if (isPersisted) {
      return true;
    }
    
    // Request permission from the browser (may prompt user or auto-grant based on heuristics)
    const granted = await navigator.storage.persist();
    return granted;
  }
  return false;
}

export async function checkStorageQuota() {
  if (navigator.storage && navigator.storage.estimate) {
    const estimate = await navigator.storage.estimate();
    const quota = estimate.quota || 0;
    const usage = estimate.usage || 0;
    
    const percentageUsed = (usage / quota) * 100;
    return {
      quotaMB: (quota / (1024 * 1024)).toFixed(2),
      usageMB: (usage / (1024 * 1024)).toFixed(2),
      percentageUsed: percentageUsed.toFixed(1),
    };
  }
  return null;
}

Why this works: Calling navigator.storage.persist() elevates your origin's storage bucket from evictable to persistent, protecting user prompt history from automatic browser cleanup during low-disk conditions.


7. Cross-Tab Synchronization for Multi-Window Workflows

Scenario: The user has your AI chat app open in two different browser tabs. They type a prompt in Tab A, experience a network drop, switch to Tab B, and wonder why their draft isn't visible there.

Why it matters: Modern developers frequently work with multiple tabs open simultaneously—one for debugging, one for code generation, one for documentation. State fragmentation between tabs creates cognitive friction.

Solution: Use the BroadcastChannel API to sync draft creation, modification, and offline status changes across all open instances of your application in real time.

Code:

// draftChannel.ts
const draftChannel = new BroadcastChannel('ai-prompt-draft-sync');

export function broadcastDraftUpdate(draftId: string, content: string) {
  draftChannel.postMessage({
    type: 'DRAFT_UPDATED',
    payload: { draftId, content, updatedAt: Date.now() },
  });
}

export function subscribeToDraftSync(onSync: (content: string) => void) {
  draftChannel.onmessage = (event) => {
    if (event.data.type === 'DRAFT_UPDATED') {
      onSync(event.data.payload.content);
    }
  };
  
  return () => {
    draftChannel.close();
  };
}

Why this works: BroadcastChannel enables simple, zero-server pub/sub communication between same-origin tabs and workers. When Tab A updates an offline draft, Tab B immediately reflects the change without needing a round-trip to server storage.


The Production Architecture Checklist

When designing a robust offline-first prompt preservation layer for an AI application, evaluate your implementation against this architectural checklist:

Dimension Naive Approach (localStorage) Production Approach (IndexedDB + State Machine)
Storage Capacity ~5MB hard limit per origin Hundreds of MBs / GBs (browser dependent)
Main Thread Impact Synchronous blocking (causes UI jank) Asynchronous transactions off-main-thread
Binary / Multimodal Support Impossible (requires Base64 conversion) Native support for File and Blob objects
Failure Safety Vulnerable to silent race conditions ACID-compliant transactional rollbacks
Eviction Protection Best-effort (easily wiped by browser) Protected via navigator.storage.persist()
Multi-Tab Sync Requires complex storage event wiring Clean pub/sub via BroadcastChannel

Building resilient AI developer tooling requires shifting our perspective from treating the network as a reliable permanent pipe to treating it as an unreliable transport medium. By shifting prompt draft management from volatile component memory into structured local persistence, you ensure that a dropped connection never costs a developer their hard work.

Post a Comment

Previous Post Next Post