Build on Anna 103_Agent Session Usage

# Build on Anna 103 -Agent Session Usage

Agent Session Usage

Stop Relying Solely on llm.complete: Manage Ongoing Conversations with Anna Agent Session

Hello, Anna developers!

When integrating AI into an Anna App, you will likely start with llm.complete: send a prompt, receive a response, and render the result on the screen. With just a few lines of code, AI can summarize articles, polish introductions, or brainstorm ideas. It is fast, straightforward, and easy to get started with.

However, a user’s next request may be: “This proposal looks good. Please make it simpler.” They may then want to adjust the tone, stop a response midway, or refresh the page and return later to continue the conversation. To handle these interactions smoothly, the frontend must manage conversation context, monitor execution state for each turn, and coordinate cancellation and state recovery.

This tutorial shows you how to build robust, ongoing conversational flows with Anna Agent Session: create a session, then advance the same task one turn at a time. The Anna platform maintains conversation context, while the frontend retains control over per-turn prompt adjustments, tool scoping, cancellation, and session recovery.

We will start with the familiar llm.complete and use a small example to walk through creating a session, asking follow-up questions, displaying streaming output, adjusting the response style, using search, and handling cancellation and recovery. As long as you understand basic JavaScript and async/await, you can follow along without first setting up a model service or tool backend.

When Should You Use Agent Session?

Business need Recommended approach
A single-turn request, such as summarization, translation, rewriting, or one-off generation llm.complete
An ongoing workflow, such as multi-turn follow-ups, tool calls, task cancellation, and recovery after a refresh Agent Session

Key takeaway: llm.complete is designed for isolated, single-turn requests; Agent Session is built for multi-turn tasks that require context continuity and lifecycle management.


What You Will Learn (Estimated Time: ~15 Minutes)

Through a minimal companion Demo, you will learn the core Agent Session lifecycle:

  1. Creation and lifecycle: Create a Session, preserve context across multiple turns, and release it when the conversation ends;

  2. Run execution: Adjust system prompts and restrict the available tool scope for each Run;

  3. Streaming and resilience: Consume streaming output, inspect tool calls, handle cancellation and failure, and recover state after a page refresh or connection interruption.

:light_bulb: Note on persistence: A Session is designed to track an active task within its operational lifecycle. It is subject to context-window constraints and time-to-live (TTL) expiration. Long-term chat history and business data should still be persisted by your application.


3-Minute Quick Start

Want to see it in action before diving into the implementation?

  1. Start the Demo by following Section 2, then open the Session tab;

  2. Click Create session, select 1. Set context, and run it;

  3. After the status of this turn changes to Succeeded, do not create a new Session. Select 2. Follow up and run it again.

If the second turn answers correctly based on the context provided in the first turn, the Session is working as expected.

Now let’s explore the underlying implementation and API details.

1. From a Single Model Call to an Ongoing Conversation

Let’s begin with a standard llm.complete call. The example below assumes that the App is connected to Anna Runtime and has declared ["complete"] under ui.host_api.llm in the manifest; the complete connection code is covered in Section 4.

const reply = await anna.llm.complete({
  messages: [{
    role: "user",
    content: {
      type: "text",
      text: "Suggest three features for a reading list app for frontend developers.",
    },
  }],
  maxTokens: 512,
});

console.log(reply.content.text);

This request bundles the product type, target audience, and task into a single payload, allowing the model to generate suggestions directly.

If the next call only asks Who is the app for?, the model will not automatically receive the product background from the previous request. llm.complete** is stateless: the model sees only the messages explicitly passed in the current request.**

You can also use it to implement a multi-turn conversation: save the user messages and model responses yourself, then pass the necessary history into the next call. For a one-off summarization or rewriting task, llm.complete itself is a good fit.

When you need ongoing interaction around the same task, a Session can maintain context for you and expose dedicated APIs for managing each Run:

  • Context continuity: Reuse the same Session and submit only the latest message for each turn.

  • Dynamic control: Set the default session prompt, then adjust the response style or narrow tool access for individual turns.

  • Execution tracking: Read incremental text and lifecycle events from the Stream, cancel the current task, or inspect a Run whose result was not received.

  • Session recovery: After a page refresh, reconnect to a still-valid Session using its saved session ID.

Streaming output itself can also be implemented with llm.stream. The focus of learning about Sessions here is to manage context, per-turn execution, and the session lifecycle together.

In this article, an “ongoing conversation” means a multi-turn interaction around the same task that may need to be interrupted and recovered. A Session has an expiration time, and the model also has a context-length limit; the complete chat history and business data that need long-term retention should still be managed by the application.

2. Companion Demo: Local Setup and Hands-On Exploration

To make these interactions easier to observe, this tutorial includes an Anna Agent Session Demo. It maps session creation, message execution, cancellation, and recovery directly to UI actions. You can also inspect every outgoing request and incoming frame alongside the code.

This is a standalone, frontend-only project written in vanilla JavaScript. React and Vue applications can use the same SDK calls; simply write the received data into component state.

Running it locally is optional. You can read the examples below directly. If you want to personally test how a Session retains context, adjusts per-turn requirements, and restores a conversation, start the Demo by following the steps below.

Prerequisites and Local Setup

First, prepare **Node.js 22+, npm, Git, and **uv. Experiments with a real model also require an account that can use Anna models and has available quota.

First, download and build the project:

git clone https://github.com/wuyyyyyou/anna-agent-session-demo.git
cd anna-agent-session-demo
npm ci
npm run build

Then log in to the Anna Host you want to connect to. The example below uses staging. If you use another Host, replace the address in both commands:

npm exec -- anna-app login --host https://staging.anna.partners
npm run dev -- --llm-account https://staging.anna.partners

Open the dashboard address printed in the terminal, usually http://localhost:5180/. On the first launch, the CLI downloads local runtime components through uv, so you may need to wait briefly.

The Demo is pinned to CLI 0.1.58. This version connects to the logged-in real account by default, and --llm-account selects the Host. The --llm real argument found in some older documentation is no longer available in this version. Real model calls consume account quota.

Enter the App through the dashboard provided by the CLI. The Anna SDK needs to communicate with the Host. Opening the HTML file directly or serving the page with only a standard static server will not allow you to complete these experiments.

If you only want to look at the interface for now, run npm run dev:mock. It uses preset text and tool frames and does not require login. To verify whether the AI remembers earlier context, perform a real search, or test cancellation behavior, you must still use the real-model mode described above.

Once the Demo opens, you will see three tabs:

Tab What it is used for
Session Create a session, send messages, observe responses, cancel, and restore
LLM Try standalone llm.complete calls and compare them with an ongoing conversation
Call records Inspect raw request payloads, returned frames, and elapsed time when troubleshooting

If you have started the Demo, first wait until Connected to Anna appears in the upper-right corner, then open the Session tab. We will first use a two-turn conversation without tools to observe how context carries over.

3. First Experiment: Two Consecutive Questions in One Session

Imagine you are designing a reading list application. First brief the AI on the target audience, then ask it to suggest features based on that context.

In the Demo’s Session tab, keep the default No tools option and click Create session.

Click 1. Set context, then click Run selected session. The button fills in:

I'm building a reading list app for frontend developers. Remember these details and confirm in one sentence.

This simply gives the model a piece of context that is easy to verify: you are building a reading list application for frontend developers. Session responses & diagnostics at the bottom of the page will display the response as it arrives.

When this turn displays Succeeded, click 2. Follow up and run it again:

Who is the app for? Suggest three features they would find useful.

Do not create a new Session for this turn. Observe whether the response still centers on “frontend developers” and a “reading list.” It may suggest saving articles, categorizing them by topic, and tracking reading progress, or it may offer other reasonable features. What matters is whether the context carries over, not whether you receive one fixed answer.

The second turn does not repeat the background from the first turn or manually concatenate previous messages. The Session manages the existing conversation context, so the frontend only needs to submit the new question for this turn.

For comparison, you can submit the two prompts separately in the LLM tab, then inspect the requests under Call records: the Demo’s standalone calls do not automatically include the previous user message and model response. Inspecting the request content is more reliable than judging only from the model’s response whether it received the earlier context.

Core Concepts: Session, Run, and Stream

Object How to understand it Example from above
Session A conversational workspace that maintains context, the default prompt, and the tool scope The discussion about the reading list application
Run A single execution turn within an active Session First establishing context, then generating feature suggestions
Stream The asynchronous transport that progressively delivers Run data to the frontend Text chunks, tool progress, and terminal status

Their relationship is:

The same Session
  ├─ Run 1 → Stream 1
  ├─ Run 2 → Stream 2
  └─ Run 3 → Stream 3

Each creation produces a new Session. Reuse an existing Session for an ongoing conversation; create a new one when the user starts a new topic or resets the conversation.

4. Initialize a Session on the Frontend

Now let’s map the UI operations above to code. The snippets below run in the frontend module inside the Anna App iframe and show the core calls for integrating Session into your own page. The Demo’s complete configuration and page code are available in the repository, so you can compare them while running it.

Declare Capabilities in the Manifest

Merge the following section into the App’s manifest.json, while retaining the existing bundle, view, and other configuration:

{
  "ui": {
    "host_api": {
      "llm": ["complete"],
      "agent": {
        "session": {
          "auto": true,
          "fixed": null
        },
        "tools": ["web_search"]
      }
    }
  }
}

llm: ["complete"] corresponds to the standalone model call in Section 1, while agent.session corresponds to the session capability; the two are declared separately. If you are only integrating Session, you can omit the llm field here.

session.auto: true allows the App to create sessions that automatically select tools. The auto here is the tool-resolution mode; it does not mean that a tool will be called in every turn. We declare web_search in advance for the search experiment later in the tutorial.

Connect to Anna Runtime

The frontend entry point must be loaded as an ES Module:

<script type="module" src="./app.js"></script>

Connect to the Host in app.js:

import { AnnaAppRuntime } from "/static/anna-apps/_sdk/latest/index.js";

const anna = await AnnaAppRuntime.connect();

connect() returns the primary frontend client for calling Host APIs. Anna handles sessions, models, and tool execution, while the page initiates requests and renders results.

Create a Session for a New Conversation

const SESSION_KEY = "tutorial.agent-session.uuid";

const session = await anna.agent.session({
  submode: "auto",
  systemPrompt: "Keep your answers concise and practical.",
  quotaCaps: { allowed_tools: [] },
});

localStorage.setItem(SESSION_KEY, session.app_session_uuid);

We set a default rule to “keep answers concise and practical” and temporarily disable tools with allowed_tools: []. Although the manifest declares the search capability, this text-only session will not use search.

The returned session is the session object provided by the SDK. You can later call its run(), cancel(), history(), refresh(), and delete() methods directly. The UUID is saved so the original session can be found after a page refresh; authentication credentials are managed by the Host and SDK.

Execute the creation code once when starting a new conversation. After that, the Send button should use the existing session to start a new Run. If you create a Session every time a message is sent, each message will start an independent conversation.

5. Execute Runs: Stream Output and Track Status

After the Session has been created, each new message starts a Run. The frontend must progressively render the text received during that turn and confirm whether it ultimately succeeded, failed, or was cancelled before deciding how to continue.

First, prepare an area for the response on your page:

<pre id="answer"></pre>

To keep the later examples concise, we reuse the Demo’s read-turn.js. It consumes the entire Stream, accumulates text chunks, emits tool events, and determines the Run result. The repository already contains this file. When migrating it to your own App, also copy its dependencies, session-run.js and record-utils.js.

import { readTurn } from "./read-turn.js";

const answer = document.getElementById("answer");
const runId = crypto.randomUUID();

const first = await readTurn(session.run({
  run_id: runId,
  content: "I'm building a reading list app for frontend developers. Remember these details and confirm in one sentence.",
}), {
  onText: (_chunk, fullText) => {
    answer.textContent = fullText;
  },
  onMeta: (meta) => console.log("Actual model:", meta.model),
});

console.log(first.status, first.text);

session.run() immediately returns an asynchronous iterable Stream. It is enough to think of it as “a queue that progressively delivers data”: for await...of waits for the next frame, processes it, then waits for the following frame.

The text-reading logic inside readTurn is equivalent to:

let text = "";

for await (const frame of stream) {
  for (const choice of frame.choices ?? []) {
    if (typeof choice.delta?.content === "string") {
      text += choice.delta.content;
      answer.textContent = text;
    }
  }
}

Here, stream is the value returned by session.run(...). The short snippet above only demonstrates text accumulation. In actual use, you also need to handle task status and errors, as readTurn does.

A typical text frame looks like the following. This is the payload the SDK passes to the application, and its content is only an illustration of the format:

{
  "event": "sse",
  "choices": [{
    "index": 0,
    "delta": { "content": "frontend developers" }
  }]
}

delta.content is a newly added text fragment, so it must be appended rather than replacing the current text with each fragment. A chat interface usually creates an assistant message first and continuously updates that message. In React or Vue, you can update component state in the onText callback.

Beyond Text: Stream Lifecycle Events

The same Stream also contains other events:

Event or field How the page should use it
frame.event === "run_meta" Inspect runtime information such as the actual model and tool scope
delta.content Append response text
delta.tool_start / delta.tool_end Display tool start and return events
delta.task_complete Determine success, failure, or termination, and read information such as the model and usage
delta.task_cancelled Confirm task cancellation
frame.event === "error" Save and display the error
frame.event === "end" The transmission has ended; determine the final result together with task events

readTurn normalizes the result to succeeded, failed, cancelled, or unknown; a successful task frame from the Host uses task_complete.status: "completed". Only when the Stream ends without a clear task result should you first display “Result pending confirmation” and then query the status.

The SDK may place request errors that occur when starting a Run in an error frame within the Stream, so you also need to check first.status and first.error. Exceptions from connection and creation calls, as well as exceptions thrown by Stream iteration itself, should be handled with try...catch at the call site. Text received before a failure or cancellation can still be retained.

6. Continue the Conversation with Per-Turn Overrides

After the first turn succeeds, submit a follow-up using the same session:

if (first.status !== "succeeded") {
  throw new Error("Handle the previous run's result before continuing.");
}

const second = await readTurn(session.run({
  content: "Who is the app for? Suggest three features they would find useful.",
}), {
  onText: (_chunk, fullText) => { answer.textContent = fullText; },
});

console.log(second.status, second.text);

This request contains only the new question; the Session manages the earlier background. If you use llm.complete, you need to include the relevant history in messages. Here, the frontend only needs to reuse the same session.

Global Defaults vs. Per-Turn Overrides

The systemPrompt used when creating the Session is the default rule. If you only want one turn to sound more playful, you can override it in that run() call:

// First confirm that the previous turn completed successfully.
const tagline = await readTurn(session.run({
  content: "Write a one-line description of the app.",
  systemPrompt: "For this turn, write a playful tagline. Return only the tagline.",
}));
console.log(tagline.status, tagline.text);

In the Demo, this corresponds to 3. Style override. After it ends, click 4. Default style, or omit the override field in code:

if (tagline.status !== "succeeded") {
  throw new Error("Handle the previous run's result before continuing.");
}

const description = await readTurn(session.run({
  content: "Describe the app again in one sentence.",
}));
console.log(description.status, description.text);

A Run-level systemPrompt overrides only the current turn and does not modify the session’s default rule. If it is omitted in the next turn, the default prompt set when the Session was created is used again. Style is a characteristic of model-generated output, so the wording will vary. To verify the parameter scope, inspect the requests for these two turns under Call records.

One real run with this set of prompts first produced the following tagline:

Because 60 open tabs isn’t a reading list—it’s a cry for help.

After the override was omitted in the next turn, the response returned to a direct product description:

A dedicated reading list built for frontend developers to save, organize, and interact with the latest web dev tutorials and resources.

Both turns know that this is the same reading list application; what changes is the writing requirement for the current turn. This lets you generate a title in one turn and explain a proposal in another while retaining the session’s default rules throughout the ongoing conversation. You do not need to receive exactly the same sentences; the point is to understand the scope of the two prompts.

This tutorial lets the platform select the model automatically. When you need to express a model preference, you can pass modelPreferences in each run(). It is a soft preference; the actual routing should still be determined from run_meta.model or the model specified in the task-completion frame.

7. Enable Tools and Scope Permissions

Some questions in an ongoing conversation require external data. A Session can invoke declared platform tools, while creation parameters and per-turn parameters restrict their available scope.

Next, perform a separate search experiment. In the Demo, select All declared tools, click Create session, and then run 5. Search.

We create a new session here because the previous session used allowed_tools: [], narrowing its tool scope to “no tools.” The new session does not inherit the reading list application’s context. If your product needs to use search within the same conversation, enable the required tools at creation time and then narrow them for individual turns. The corresponding code is:

const searchSession = await anna.agent.session({
  submode: "auto",
  systemPrompt: "Keep your answers concise and practical.",
  quotaCaps: { allowed_tools: ["web_search"] },
});

const searchResult = await readTurn(searchSession.run({
  content: "Use web_search to find the MDN documentation for JavaScript async iterators. Explain the idea briefly and include the source URL. If search returns no results, say so.",
}), {
  onText: (_chunk, fullText) => { answer.textContent = fullText; },
  onToolStart: (tool) => console.log("Tool started:", tool.id, tool.name, tool.input),
  onToolEnd: (tool) => console.log("Tool returned:", tool.id, tool.name, tool.output),
});

console.log(searchResult.status, searchResult.text);

Expand the tool records in the Demo to see the query and output. The frontend can use the id of the same tool call to update an “In progress” record to “Returned.”

Tools run on the platform, and the frontend receives and displays their events. After receiving tool_start, do not execute the same search again from the frontend.

Why Pass allowed_tools After Declaring the Tool?

The manifest determines which tools the App may request. Creation parameters can narrow this scope further, and per-turn parameters can narrow it again:

Platform tool catalog ∩ manifest declarations ∩ allowed_tools at creation ∩ allowed_tools for this turn

Omitting allowed_tools means this layer applies no additional restriction. Explicitly passing [] means this layer allows no tools. No layer can expand permissions beyond the manifest. web_search also requires the corresponding Web authorization on the platform.

If you do not see the expected tool events, first inspect the catalog and the actual tool scope for the current turn:

const catalog = await anna.agent.session.catalog();
console.table(catalog.platform_tools);

Pay attention to eligible and blocked_by, and evaluate them together with the creation receipt, run_meta.granted_tools, and actual tool events. The local CLI’s catalog and authorization may be broader than the manifest; an official App is still governed by manifest and Host checks. Therefore, even when All declared tools is selected in the Demo, it explicitly passes allowed_tools: ["web_search"] to ensure that the local search experiment enables only this tool.

Tool output may be a JSON string, so first check its type and then try to parse it. A search returning no results can still be a normal tool response. The tool returning, finding information, and the entire Run succeeding are three separate conditions that must be evaluated. A link appearing in the model’s response also does not automatically mean that the source was retrieved by the search tool.

8. Cancel an Active Run

In the Demo, run 6. Long answer and click Cancel current run while it is still producing output. Observe whether the partial text is retained and whether the final status is cancelled or succeeded.

Cancellation needs to identify a specific Run, so generating a run_id before execution is convenient. You can connect a button on your own page like this:

<button id="cancel" type="button" disabled>Cancel current run</button>
const longRunId = crypto.randomUUID();
const cancelButton = document.getElementById("cancel");

async function cancelThisTurn() {
  try {
    const ack = await session.cancel(longRunId);
    console.log("Cancellation acknowledgement:", ack);
  } catch (error) {
    console.error("Cancellation failed:", error.code, error.message);
  }
}

cancelButton.addEventListener("click", cancelThisTurn);
cancelButton.disabled = false;

try {
  const result = await readTurn(session.run({
    run_id: longRunId,
    content: "Write a detailed guide to JavaScript async iterators, with several complete code examples and exercises.",
    systemPrompt: "For this turn, give a thorough explanation with examples.",
  }), {
    onText: (_chunk, fullText) => { answer.textContent = fullText; },
  });
  console.log("Final result:", result.status);
} finally {
  cancelButton.disabled = true;
  cancelButton.removeEventListener("click", cancelThisTurn);
}

cancel() is a best-effort operation. cancelled: true in the acknowledgement means the cancellation signal was accepted. Some text may still arrive afterward, and the final result may still show success if the task had already completed.

Therefore, the page can first display “Cancelling,” continue reading the Stream, and then display the final result based on the task events. Exiting the for await loop only stops the frontend from reading; it does not send a cancellation request to the platform.

Cancellation applies to the current Run. After confirming that this turn has ended, you can continue asking questions in the same Session.

The Demo’s Move to background also does not cancel the task: as long as the page remains open, the task continues running and collecting frames. Do not send the next turn while a Run in the same Session is still unfinished. If the task result is uncertain, query its status first.

9. Restore a Session After a Page Refresh

The user may refresh the page and return later to continue discussing the same task. To continue this conversation, the frontend must find the original Session instead of executing the creation code again.

In the Demo, first let the previous turn reach a definite final state, then refresh the dashboard. Find the original UUID under Saved session IDs, click Restore, and continue asking questions.

A page refresh loses JavaScript objects, but the Session on the platform may still be valid. After reconnecting to Runtime, use the UUID saved in Section 4:

const savedUuid = localStorage.getItem(SESSION_KEY);
if (!savedUuid) throw new Error("No saved session. Start a new conversation first.");

const restored = anna.agent.session.attach(savedUuid);
await restored.refresh();

// The previous turn must have ended before continuing in the same session.
const continued = await readTurn(restored.run({
  content: "Who is the reading list app for?",
}), {
  onText: (_chunk, fullText) => { answer.textContent = fullText; },
});

console.log(continued.status, continued.text);

Initialization after a refresh should enter this recovery branch and skip the code that creates a new Session. The differences between the operations are:

Operation What it does
anna.agent.session(...) Creates a new session
attach(uuid) Wraps an existing UUID on the frontend without creating a session or sending a request to verify its validity
refresh() Requests that the Host verify the existing session and refresh its expiration time
history() Makes a best-effort attempt to read recent messages for display on the page

A Session has an expiration time. Saving its UUID does not mean it is retained permanently. An expired, deleted, or revoked session cannot be reactivated with attach(). To display lifecycle information, read expires_at, max_lifetime_at, and idle_ttl_seconds from the current SDK. refresh() can extend the idle expiration time but cannot go beyond max_lifetime_at. The expires_in value of a short-lived authentication credential is not the expiration time of the entire session.

When recovery fails, retain the error information. Let the user start a new conversation only after clearly confirming that the Session has expired or been revoked. For network or permission issues, address the cause first; do not silently create a new session and give the user the false impression that the original context is still available.

Restoring Context and Rendering Chat History Are Separate Tasks

The AI remembering earlier context does not automatically make the old chat bubbles reappear on the page. The App can save its own chat history or read recent history from the platform:

const { messages } = await restored.history({ limit: 50 });
console.log(messages);

history() is a best-effort read interface and may return an empty array. An empty history alone does not prove that the Session is invalid or that a Run failed. The Demo separately saves call records in IndexedDB, so text and frames received locally remain available after a refresh.

If the local UUID is lost, you can also list the current App’s sessions and let the user choose the conversation to restore:

const { sessions } = await anna.agent.session.list({ limit: 50 });
console.table(sessions);

10. Resume After a Disconnection and Read Archived Frames

An ongoing conversation must also handle cases where “the result of the previous Run is uncertain.” A network interruption or suspended background tab may prevent the frontend from receiving output while the Run continues on the platform. In this case, first confirm the status of the previous Run, then decide whether to continue or retry.

The Demo provides Check run status and Read archived frames. They answer “What is the status of this Run now?” and “Can the output of this Run be retrieved?” respectively, without executing the model again.

In code, the query requires the original Session UUID and run_id:

const state = await anna.agent.session.runStatus({
  app_session_uuid: session.app_session_uuid,
  run_id: runId,
});
console.log(state.status, state.stream_id);
Status Next step
queued / running Continue waiting or restore frames; do not send a duplicate request yet
completed This Run has executed; retrieve its output
failed / cancelled Inspect the error or cancellation result, then decide whether to retry

If you receive a stream_id, you can read one page of archived frames:

const archived = await anna.agent.session.frames({
  stream_id: state.stream_id,
  after_seq: 0,
  limit: 500,
});
console.log(archived.frames, archived.complete);

Archived frames include a seq. When continuing to read, use the last sequence number from the previous page as after_seq. When reconstructing a response, deduplicate frames by sequence number to avoid appending text that has already been displayed. The Demo saves the read position, so clicking repeatedly continues reading from where it stopped.

These recovery interfaces require SDK 0.18.0+ and a Host that supports the corresponding methods. The archive has a time window and rate limits and is suitable for recovering recent Runs. To continue querying a particular Run after a page refresh, also save that Run’s run_id; the Demo stores it in the local call record.

11. Release Sessions Gracefully

A completed Run means that the current turn has ended; the conversation can still continue. Release the corresponding Session only when the user deletes the conversation or explicitly resets it:

await restored.delete();

if (localStorage.getItem(SESSION_KEY) === restored.app_session_uuid) {
  localStorage.removeItem(SESSION_KEY);
}

Remove the local UUID only after confirming that deletion succeeded. The search experiment created a separate searchSession, which can also be released with await searchSession.delete() when it ends. Do not delete a Session after every response, or the next turn will not be able to continue with the original context.

When integrating Session into your own chat interface, let the Send button create a Run in the existing Session, let the Cancel button target the current Run, and let page initialization restore the session from its saved UUID. Then write text, tool events, and task status from the Stream into chat bubbles, progress indicators, and status messages. With these pieces, the ongoing conversation has a complete frontend interaction flow.

Standalone summarization and rewriting can still use llm.complete. When users need to keep advancing the same task, a Session lets you continue the context, control behavior for each turn, and handle cancellation, recovery, and the end of the conversation throughout the entire process.

For additional interface details, continue with the following resources: