hashbrown

Save text conversations

Saving a text conversation lets a user refresh a page and continue with the earlier exchange. Browser storage works for a small, device-local draft when cross-device access and server ownership are unnecessary. Save a narrow, versioned format so a future release can recognize or reject it safely.

Let’s store only completed user and assistant text. Loading it should replace history without generating a reply; the next explicit user message starts the next request.

Save text, then load it deliberately

Scroll horizontally to see the full diagram, or expand it.

Browser appLocalstorageChatruntime1 Completed text2 Save validatedtext3 Load and validate4 Replace idle history5 Send follow-up
Save keeps a completed text copy. Load replaces an idle conversation; the next user message starts a request.
Read the diagram

The browser application validates completed user and assistant text before explicitly saving a versioned document to local storage. After refresh, an explicit load reads and validates the document, then replaces idle SDK history. Loading sends no model request. An explicit follow-up starts a fresh run using that restored text. This format does not preserve tool calls or a paused agent checkpoint.

Save text, then load it deliberately

Save keeps a completed text copy. Load replaces an idle conversation; the next user message starts a request.

Read the diagram

The browser application validates completed user and assistant text before explicitly saving a versioned document to local storage. After refresh, an explicit load reads and validates the document, then replaces idle SDK history. Loading sends no model request. An explicit follow-up starts a fresh run using that restored text. This format does not preserve tool calls or a paused agent checkpoint.

Store a bounded text document

Create an application helper such as saved-text.ts. It has no SDK dependency and can be shared by both frontends:

export type SavedMessage = { role: 'user' | 'assistant'; content: string };
export function decodeSavedText(json: string): SavedMessage[] {
  if (new TextEncoder().encode(json).length > 64_000)
    throw new Error('Saved text is too large');
  const document: unknown = JSON.parse(json);
  if (!document || typeof document !== 'object')
    throw new Error('Invalid document');
  const { version, messages } = document as Record<string, unknown>;
  if (
    Object.keys(document).some(
      (key) => key !== 'version' && key !== 'messages',
    ) ||
    version !== 1 ||
    !Array.isArray(messages) ||
    messages.length > 40
  )
    throw new Error('Unsupported document');
  for (const message of messages) {
    if (
      !message ||
      typeof message !== 'object' ||
      Object.keys(message).some((key) => key !== 'role' && key !== 'content') ||
      !['user', 'assistant'].includes(message.role) ||
      typeof message.content !== 'string' ||
      !message.content.trim() ||
      message.content.length > 2_000
    )
      throw new Error('Unsupported message');
  }
  if (
    messages.length &&
    (!messages.some((m) => m.role === 'user') ||
      messages.at(-1).role !== 'assistant')
  )
    throw new Error('Incomplete exchange');
  return messages.map(({ role, content }) => ({ role, content }));
}

// Call from an explicit browser Load action, after mounting.
export function readSavedText(key: string): SavedMessage[] {
  const json = window.localStorage.getItem(key);
  return json === null ? [] : decodeSavedText(json);
}

// Convert the saved format to the SDK's assistant input shape.
export function readSavedChatMessages(key: string) {
  return readSavedText(key).map((message) =>
    message.role === 'assistant'
      ? { role: 'assistant' as const, content: message.content, toolCalls: [] }
      : { role: 'user' as const, content: message.content },
  );
}

// Call only with text from a successfully completed current run.
export function writeSavedText(key: string, messages: SavedMessage[]) {
  const json = JSON.stringify({ version: 1, messages });
  decodeSavedText(json); // Apply the same contract before replacing storage.
  window.localStorage.setItem(key, json);
}

The saved format deliberately omits SDK metadata. readSavedChatMessages adds the required empty toolCalls array for assistant inputs before passing them to setMessages. Use this integration with the Angular Quickstart provider. Provide SavedHelpChat on the conversation component to give the resource an injection context and matching lifetime.

import { Injectable } from '@angular/core';
import { chatResource } from '@hashbrownai/angular';
import { readSavedChatMessages } from './saved-text';

@Injectable()
export class SavedHelpChat {
  readonly chat = chatResource({
    system: 'Help explain our public returns policy.',
  });
  load() {
    if (
      this.chat.isLoading() ||
      this.chat.isResuming() ||
      this.chat.pendingInterrupts() ||
      this.chat.recovery().required
    ) {
      throw new Error(
        'Finish the current interaction before loading saved text.',
      );
    }
    this.chat.setMessages(readSavedChatMessages('help-chat:v1'));
  }
}

Call load() from an explicit browser Load handler and catch validation or storage errors there so the screen can display them. An assistant-ended document loads without a request; the SDK assigns new message IDs. Loading is allowed only while idle, with no active tool, interrupt, or required recovery.

For Save, first require a current successful run with lastRunFinishReason equal to stop, supported nonempty text, and no loading, error, interruption, or required recovery. Project only user/assistant string content, then call writeSavedText inside try/catch. Never serialize an arbitrary SDK message list into this narrow format. Keep the previous value when validation or storage fails, and offer explicit clearing for an invalid existing document. Browser storage is origin-local plain text; use server storage for ownership and synchronization.

Explore it in the workbench

The workbench below replays a recorded run of this lesson.

Save Lighthouse and Harbor, refresh, then load completed text into a fresh chat.

Recorded in the real Angular workbench with OpenAI and actual Hashbrown text chat. Only validated completed text is retained; this is not a canonical agent checkpoint. Saving is explicit. No tools, generated UI, or executed plan steps. Unchanged provider events are paced at 20 ms for filming; the normal host adds no delay. Footage slowed to half speed for readability. Replay makes no requests or storage writes. No narration. Read the text walkthrough.

Open full workbench
Open full workbench

Let's keep our two-step plan after a refresh. We'll save a completed Lighthouse exchange, save a second conversation as Harbor, then refresh and load Lighthouse into a new chat. A follow-up will show which text actually reached the model.

The saved-text selector chooses a browser slot. The left sidebar still chooses a live conversation. Selecting a saved slot does not load its messages or send a request. We make those actions explicit so you can see what each one changes.

Use the panel above, or run the workbench on your machine. The checked Angular client uses real Hashbrown requests and provider streaming.

Save Text Deliberately

  1. Complete the Lighthouse request and save it to the Lighthouse slot.
  2. Create a new live conversation from the sidebar. Select Harbor, name its plan Harbor, and save the completed reply there.
  3. Refresh the page. The live conversations and their old timeline are gone; the saved text remains.
  4. Select Lighthouse and load its text. Loading makes no model request.
  5. Send a follow-up, inspect the restored context in Requests, and save after the new reply succeeds.

The replay shows three provider requests across independent live instances. The timeline after refresh contains this page's load and continuation. It does not reconstruct the old requests or their timings. Replay makes no requests and writes no storage.

Define a Small Format

The browser document has version: 1 and messages with only role and string content:

const savedText = {
  version: 1,
  messages: [
    { role: 'user', content: 'Name our plan Lighthouse.' },
    {
      role: 'assistant',
      content: 'Lighthouse has two steps: outline, then record.',
    },
  ],
};

The helper permits at most 40 messages, 2,000 characters per message, and 64,000 serialized UTF-8 bytes. It rejects oversized data instead of truncating it. Those limits leave room for the workbench server's request envelope and another user message.

A nonempty document must include a user message and end with an assistant reply. Unknown fields, unknown versions, unsupported roles, malformed JSON, and tool-bearing histories are rejected. Load passes validated assistant-ended text to setMessages. It briefly schedules the replacement, then settles without a model request. The SDK assigns fresh IDs after restoration. The format does not preserve a canonical checkpoint, shared state, generated UI, activities, provider metadata, or pending interrupt ownership.

runtime/workbench-history.ts
export interface WorkbenchTextDocument {
  readonly version: 1;
  readonly messages: readonly {
    readonly role: 'user' | 'assistant';
    readonly content: string;
  }[];
}

Require a Successful Reply

The client checks lastRunFinishReason === 'stop' together with the current live cursor and SDK lifecycle. It also requires supported, nonempty text and no loading, resuming, error, pending interrupt, or required recovery.

Stopping a stream can leave partial text visible. A length limit, refusal, filtering, or failure can also end a request without producing a successful exchange. None of those outcomes replaces the last saved document. Restoring old text clears the SDK's completion evidence; saving becomes available after the next successful reply.

angular/src/app/history-workbench.ts
readonly chat = chatResource({
    system: workbenchHistorySystem,
    transport: createWorkbenchTransport(
      this.store,
      undefined,
      this.lesson.endpoint,
    ),
  });

The shared action helper checks the actual SDK observation as well as the selected capture:

runtime/workbench-history-client.ts
const savable = () =>
  mutable() &&
  observation().finishReason === 'stop' &&
  canSaveWorkbenchHistory(store.getSnapshot());

Reads happen after mounting, when selecting a slot, and before loading it. They never run during server rendering. Saving is an explicit action; mounting, streaming, selecting, loading, refreshing, and replaying do not write an empty or partial conversation over the saved value.

Handle Storage Failures

Browser storage can be blocked, full, or unavailable. Reads, writes, deletes, and even access to the storage getter can throw. The helper reports the failure while keeping the live conversation usable.

An invalid or unknown document stays untouched. Clear the selected saved slot explicitly before replacing it. Each slot has its own namespaced key and one atomic write. Clearing Lighthouse leaves Harbor alone. The inspector shows the last-read document; it is not a live view of changes from another tab.

Choose the Right Persistence Boundary

Browser storage belongs to this origin and browser profile. It is plain text available to scripts on the origin. It provides neither server authorization nor cross-device synchronization or cross-tab conflict control. Decide what is appropriate to retain, how long to keep it, and what happens on sign-out. Do not save secrets here.

The Lighthouse and Harbor labels are application lookup keys. They are independent of the new SDK thread ID after refresh. Supplying an old threadId does not load a transcript or make a text document resumable.

Use Message history to understand the setter, Threads for application-owned server storage, and Interrupt and resume for live workflow ownership.

For a runnable TypeScript/Postgres reference that survives a server restart, see Durable recovery with b4.run. It separates conversation checkpoints, native approval grants, and the application’s accepted plan.

Save text conversationsStore a bounded text documentExplore it in the workbenchSave Text DeliberatelyDefine a Small FormatRequire a Successful ReplyHandle Storage FailuresChoose the Right Persistence Boundary