# Add Chat Export to an AI SDK Chatbot

Yes. An agent adds a Markdown and JSON export route that follows your chat visibility rules, a sidebar download item, a Playwright test, and opens a pull request.

[Run this on Rush](https://cloud.getrush.ai/run/add-chat-export/ai-sdk/). Opens the console with this prompt ready to send, in a Project that has your repository.

## What the agent does

The agent reads how a chat is stored and who may read it. In an app built from vercel/chatbot, `lib/db/schema.ts` has `Chat` with `title`, `userId`, `createdAt` and a `visibility` of `public` or `private`, and `Message_v2` with `role`, `parts` and `attachments` as JSON and `createdAt`. `lib/db/queries.ts` connects with `postgres` and Drizzle and exposes `getChatById` and `getMessagesByChatId`, ordered by `createdAt`. `app/(chat)/api/messages/route.ts` is the access rule in code: a private chat answers 403 unless the session's user owns it, a public one is readable by anyone, and `isReadonly` marks a reader who is not the owner. `lib/utils.ts` has `convertToUIMessages` and `getTextFromMessage`, which joins a message's text parts, and `lib/types.ts` defines `ChatMessage` with tool parts for `getWeather`, `createDocument`, `updateDocument` and `requestSuggestions`. `components/chat/sidebar-history-item.tsx` gives each chat a menu with Share (Private or Public) and Delete, `components/chat/icons.tsx` already has a `DownloadIcon`, and `lib/errors.ts` answers failures through `ChatbotError` codes such as `forbidden:chat`. `package.json` runs `ultracite` for `check` and `fix`, and `test` runs Playwright with `PLAYWRIGHT=True`, which makes `lib/ai/providers.ts` use the mock models.

The export is a pure function first. `lib/export.ts` gets `chatToMarkdown(chat, messages)`: the title as a heading, the chat's date, then one section per message headed by its role with the `createdAt` from its metadata, the text parts through `getTextFromMessage`, reasoning parts left out, each tool part as a single line naming the tool and its state, and each attachment as a link. A `chatToJson` returns `{ chat, messages }` with the messages exactly as `convertToUIMessages` shapes them, so a reader can import the file elsewhere.

`app/(chat)/api/export/route.ts` serves it: `GET` with `chatId` and `format` (`markdown` by default, or `json`), the same session and visibility check as `/api/messages`, a `ChatbotError` for a missing or forbidden chat, and a `Content-Disposition: attachment` header with a filename made from the title. The sidebar menu in `sidebar-history-item.tsx` gains an Export item with `DownloadIcon` that navigates to the route so the browser downloads the file, placed between Share and Delete. No new table or column is needed.

The test lives with the others in `tests/e2e/`: it sends a message, waits for the mock model's reply, reads the chat id from the URL, fetches the export through `page.request`, and asserts a 200, a Markdown content type, and that the body contains the prompt and the reply; a second browser context, which the app signs in as a different guest, gets 403 for the private chat and 200 after the first context switches it to public. The sandbox has no Docker, so the agent installs Postgres with `apt-get`, sets `POSTGRES_URL`, runs `pnpm db:migrate` and then `pnpm test` for the new file and `pnpm check` for the lint and format rules.

## Start it with one API call

`POST https://api.phoenix.so/o/{org}/sessions`

```json
{
  "agent": "claude",
  "input": "Add chat export. Write lib/export.ts with chatToMarkdown and chatToJson: title heading, chat date, one section per message by role with its createdAt, text parts via getTextFromMessage, reasoning parts omitted, one line per tool part naming the tool and its state, attachments as links. Add GET app/(chat)/api/export/route.ts taking chatId and format (markdown by default or json) with the same session and visibility check as /api/messages, ChatbotError answers for missing or forbidden chats, and a Content-Disposition attachment filename from the title. Add an Export item with DownloadIcon to the chat menu in sidebar-history-item.tsx between Share and Delete. Write a Playwright test in tests/e2e that sends a message, exports the chat, checks the body, and shows a second guest gets 403 until the chat is public. Run it against a local Postgres after pnpm db:migrate, then pnpm check. Open a pull request quoting the test output.",
  "resources": [
    {
      "url": "https://github.com/your-org/your-app"
    }
  ]
}
```

1. **Get an API key.** In the console, open Settings, then API keys, and create a key for your org. Send it in the Authorization header as a Bearer token.
2. **Send the request.** POST the body in request.json to https://api.phoenix.so/o/{org}/sessions, with your repository as the resources URL. The run starts in its own cloud sandbox.
3. **Read what came back.** Follow the run on its live stream or wait for the run.completed webhook, then read the result and its trajectory.

## What comes back

The pull request adds `lib/export.ts`, `app/(chat)/api/export/route.ts` and `tests/e2e/export.test.ts`, and changes `components/chat/sidebar-history-item.tsx`. Its description quotes the Playwright output for the new file and the `pnpm check` result, and includes a short sample of the Markdown an exported chat produces.

A reviewer compares the route's check against `/api/messages` line by line, since that is the rule the app already trusts, and reads `chatToMarkdown` for what it leaves out: reasoning parts and tool inputs stay private to the run that produced them. The transcript at GET /o/{org}/sessions/{id}/messages has the database setup and the test run; the session's `changes` read has each file's diff.

The route reads only; nothing in the database changes, and a public chat's export carries exactly what its page already shows.

## Run it on every Linear issue labelled feature

Add an automation on the Project with a `linear` trigger on `linear.issue.labeled` and the label your product work uses, with this prompt as its text. Each labelled issue starts one run with the issue as its context, on its own branch, and the pull request links back to it. The trigger adds the issue after the prompt and fills in no placeholder, and a change made by an app integration never fires it.

The automation's `max_runs_per_hour` holds a burst of labels to that many runs an hour. From your own server, the same run starts with this body and the issue URL in `resources`, with a `request_id` that is a UUID v5 of the issue id so a retried start returns the run already begun.

## Why run it on Rush?

The risky line in an export feature is the access check, not the formatting, and the only proof that convinces is a second user trying the route and getting refused. That needs two signed-in browsers, a database and the app running against mock models, which the sandbox sets up for the run and tears down after; the request and both responses are in the transcript.

A chatbot with several deployments, or a team with several apps on the template, runs this once per repository in parallel and reviews one small diff each, with the same two-user test in every pull request.

## Frequently asked questions

### Why Markdown and JSON, not PDF?

Markdown is what the chat already renders and what a person pastes into a document; JSON keeps the message parts as the app stores them for import somewhere else. A PDF needs a renderer and fonts in the serverless function. Ask for it in the prompt and the agent adds it as a third format.

### Does an export include tool calls and reasoning?

Tool parts appear as one line each with the tool name and state, so the reader knows a weather lookup or a document edit happened without the raw arguments. Reasoning parts are left out entirely. Both choices are in `chatToMarkdown` and are easy to change.

### Can a public chat be exported by anyone?

Yes, exactly as its page can be read by anyone. The route uses the same rule as `/api/messages`: private means owner only, public means anyone, and the test checks both with a second guest session.

### What about attachments?

They are listed as links to their stored URLs, which the app already puts in `attachments` on each message. The files themselves are not bundled; a zip export would need a storage read per file and is a separate run.

## More AI SDK jobs

- [Trim Long Chats to the Model's Context Window with the AI SDK](https://getrush.ai/run/add-context-window-trimming/ai-sdk/)
- [Add a Fallback Model to an AI SDK Chat Route](https://getrush.ai/run/add-model-fallbacks/ai-sdk/)
- [Track Token Usage per User in an AI SDK Chatbot](https://getrush.ai/run/add-token-usage-tracking/ai-sdk/)

## The same job on other stacks

- [Add Chat Export to a Reflex Chat App](https://getrush.ai/run/add-chat-export/reflex/)
- [Add Chat History Export to a Streamlit App from a Linear Issue](https://getrush.ai/run/add-chat-export/streamlit/)

## More jobs like this: Turn a Linear label into a PR

- [Add a Checkout UI Extension to a Shopify App](https://getrush.ai/run/add-checkout-ui-extension/shopify-app/)

## Keep reading

- [How a Rush run works on your repository, from request to pull request](https://getrush.ai/cloud/)
- [Compare cloud agents, agent sandboxes and AI code review](https://getrush.ai/compare/)
- [Rush pricing: Free, Pro and Max](https://getrush.ai/pricing/)
