Agent chat

Connect an official Agent backend to ChatPanel, or compose the message and rich input components

@downcity/ui provides AgentChatMessage, AgentWorkMessage, UserMessage, ChatInput, MarkdownView, and a complete ChatPanel. Desktop and React products use these SDK surfaces. The backend owns Agent execution and canonical Session history; the browser owns its client connection.

Start from the full-stack example

The repository includes public/templates/agent. From the repository root:

pnpm install
cp public/templates/agent/.env.example public/templates/agent/.env
# Set DEEPSEEK_API_KEY in the local .env file.
pnpm --dir public/templates/agent dev

Open http://127.0.0.1:5174. For a built frontend served by the same backend:

pnpm --dir public/templates/agent build
pnpm --dir public/templates/agent start

Open http://127.0.0.1:5314. AGENT_WORKSPACE_PATH selects the project directory. AGENT_STORAGE_PATH selects private runtime storage; its default is ~/.downcity-template-agent. The server restores its most recent chat Session after a restart.

The server composes Agent, Workspace, LocalStorageProvider, and City, then calls city.http({ host: "127.0.0.1", port }). The application bootstrap endpoint returns the server-selected Session address. Messages, streaming, interactions, stop, and retry use the official SDK transport.

This is a local, single-user example. A multi-user application must authenticate requests and isolate the Agent/Session collection for each user in the backend. Keep model keys on the server. A Session ID is a locator, not authorization.

Connect a Session

Use the browser entry of @downcity/city and pass the existing Session actor to connect_chat_session:

import { RemoteAgent } from "@downcity/city/browser";
import { ChatPanel, connect_chat_session } from "@downcity/ui";

const client = new RemoteAgent({
  url: new URL("/agents/template-agent/workspaces/default", location.origin).href,
});
const session = await client.sessions.get(session_id, "chat");
const connection = await connect_chat_session(session);

// Render in your component:
<ChatPanel runtime={connection.runtime} title="Project helper" />;

// Read an earlier history page when requested:
await connection.load_earlier();

// On component teardown:
connection.close();
await client.close();

The connection establishes a ready event subscription before reading history. It merges canonical message revisions and Part deltas, exposes current model retry eligibility, and forwards submissions and Interaction responses to the same Session. Normal input queues while execution is active; steer input is submitted immediately. After model failure releases resources, queued inputs continue in order. A failed input submission or actual disconnection retains the queue head and pauses dispatch; uncertain prompts are never replayed automatically. Retry uses the original failed Step ModelCall in the same Turn and canonical Message, while the old call result remains failed. Stop forwards the message_id and revision observed when clicked, rejecting stale controls after same-Turn recovery. Rebuild a disconnected client and read authoritative history.

connection.close() only releases its UI subscription. The caller closes the RemoteAgent it created. Use the complete effect cleanup pattern in templates/agent/web/src/app.tsx when mounting in React.

Messages

Loading preview…

AgentChatMessage displays a light, left-aligned bubble. Its avatar occupies a separate left column aligned with the message top; the right column contains the name, runtime status, and content. Short bubbles fit their content; long bubbles are limited to the available column width or 42rem. Set show_identity={false} for a consecutive reply to omit the repeated avatar and name while preserving content alignment. continues_previous and continues_next control spacing between replies.

Pass runtime feedback through status: it appears at the top inside the bubble, above the content. Empty content uses the same bubble, and streamed content fills it in place. Hosts provide this status when the model request starts, without waiting for the first token. Sent and read receipts belong in the user message’s meta; an input is read once consumed, independently of reply activity. footer holds supplementary information below the content and actions, such as file change summaries. Copy and retry actions appear below the content on hover or keyboard focus; use actions to provide your own controls. Default timestamps use subdued styling and appear on hover or keyboard focus.

AgentWorkMessage displays a compact, full-width document without an identity row or avatar column. It places status in the bottom bar alongside footer. Both Agent components share streaming Markdown, tool/reasoning activity, attachments, and error feedback. UserMessage provides a right-aligned bubble, long-text expansion, and an editing surface. MarkdownView renders the same Markdown, code, formulas, and diagrams used by chat messages.

Use session_message_to_chat_message to project a canonical Session record. Tool-owned approvals and questions stay at their tool position. The default form supports approval and text/single-select/multi-select questions. Resolved interactions show their canonical status. Private questions require render_interaction and the Agent private submission API; the default form does not send secrets through the public Session response endpoint.

For application-specific Power content, file navigation, and richer activity details, use AgentMessageContent with blocks and render_block, or UserMessageContent with render_file and render_reference. SDK content components own Markdown, ordering, and error/retry feedback. Desktop supplies its Power renderer, workspace file previews, and runtime eligibility through these boundaries.

Rich input

Loading preview…

ChatInput takes a structured Tiptap document, a stable editor_key, update_draft, and send_message. It handles cursor state, rich text, code paste, references, attachment nodes, keyboard commands, candidate menus, send/stop state, and asynchronous target checks. The host owns draft storage and the Session queue.

Pasting a standalone local file:// URL inserts a file reference with its filename and a full-path tooltip. Percent-encode spaces and special characters in filenames. Code-block paste, paste without formatting, and addresses mixed into prose stay as text. File references store only the address and project to a local-file-reference Context; they do not read file contents or create attachments. Hosts can supply file previews and accessibility feedback through host.render_reference. Import read_local_file_reference and local_file_reference_tag from @downcity/ui/composer to share the URL parsing rules.

project_chat_composer(document) produces ordered text, context, file, and data content for session.prompt({ query: parts }). This preserves references and attachments in their original position. Import pure conversion functions from @downcity/ui/composer in server or Electron Main code.

Use host to provide translations, file/reference previews, avatars, and external reference/draft synchronization channels. attachments supplies workspace file lookup and reads. Browser file uploads use the built-in picker when attachment capability is supplied; max_attachment_bytes defaults to 20 MiB. The server must enforce its own upload and resource access limits.

Switch editor_key when changing the input owner. The editor flushes the old draft and revokes late asynchronous inserts before restoring the next document. Use draft_scope to distinguish an editing transaction from the normal draft.

Styles

@import "tailwindcss";
@import "@downcity/ui/source.css";
@import "@downcity/ui/styles.css";
@import "@downcity/ui/markdown.css";

styles.css includes the shared input and reference-node styles. source.css lets Tailwind scan SDK components. MarkdownViewProvider supplies resource resolution, link opening, and Markdown language/text-size settings for the host.

Model controls and session status

Use Model controls for searchable form/chat model menus, reasoning, approval mode, and pricing. Use Status panel for the queue, canonical approval/question forms, and descendant sessions. Supply a full session_key, host-owned data, translations, and callbacks; load @downcity/ui/status-panel.css for the panel and forms.

Input Part presentation

Input Parts belong to canonical Agent messages and retain their original sequence. A host may hide internal events in its presentation projection without changing history or model input. Desktop interprets background results through each Power's independent input slot. A null description creates no visible content block; details use safe Markdown and existing attachment previews and mount only on expansion. See Custom Power for the contract.