AI chat replies
How the built-in AI chat turns a message into edits, how a reply ends, and how what happens to its edits afterwards reaches the transcript and the model. ACP and Pi chats share the transcript, the saved conversation, and the marks on a reply, but run their own tool loop and agent presence.
Where the chat lives
On desktop the chat has a column of its own, the last panel of the editor's splitter to the right of the properties panel (src/components/editor/EditorWorkspace.vue), so the Design tab and the conversation show together. chatColumnOpen in src/app/ai/chat/panel.ts says whether it is open; it is the chat.columnOpen preference, so the column stays as the person left it across reloads. The sparkles button among the document's actions in the top bar (src/components/editor/EditorWorkspaceTopBarActions.vue), ⌘J (toggleAI in src/app/shell/keyboard/actions.ts), and a notification's click (showChatPanel) open it.
ChatPanel is mounted once there and stays mounted while the column is closed: the panel collapses to no width rather than unmounting, because the panel owns the conversation's submission state, its queue of waiting messages, and the permission prompts an agent may raise while the column is shut. Opening and closing go through useEditorWorkspaceLayout, which gives the properties panel back its width afterwards so the canvas, not the properties panel, pays for the column. The side panels are sized in pixels and saved as { layers, properties, chat } by src/app/shell/layout-storage.ts, which reads layouts saved in percent by earlier versions as the pixels they had. Phones keep the chat as a tab of the bottom drawer (MobileDrawer.vue), which mounts its own ChatPanel.
A reply belongs to the conversation that started it, not to the tab in front. Switching documents during a reply keeps it running: loadDocument in chat/history/controller.ts enters its away state instead of detaching, so the history session keeps saving and createChatSessionManager keeps the chat and its agent session, remembering the conversation that chat answers. The panel in front keeps showing that conversation with the run-location notice (chat/run-location/, ChatRunLocation.vue), naming the agent and the document with a button that opens it, and its composer keeps only Stop. Returning during the reply re-attaches the same chat; returning after it ended takes it back through resumeChat, without starting the agent again. A reply that ends while another document shows hands the panel back to that document. Stop, New chat, opening another conversation, and closing the conversation's own tab end the reply; looking at another document does not.
A prompt from outside the chat
Home's prompt (HomePromptComposer) and the prompt over an empty page (EditorCanvasPrompt) write a first message before the document's chat shows. Both first make sure a model is configured: ensureChatConfigured in src/app/ai/chat/setup.ts opens guided setup (runAISetup) and goes on only when the chat is configured once it closes, so a dismissed setup keeps the prompt where it was written. Home then creates the design through the same path as its Design button, so a Cloud workspace or storage target still applies.
The prompt itself waits in src/app/ai/chat/pending-prompt.ts, keyed by the document's EditorStore, and sendPromptToDocument shows that document's chat (the column, or the drawer's AI tab on a phone). ChatPanel takes it with takePendingPrompt once history.initialize() has loaded the active document's conversation, and submits it as the composer would; it also watches for one arriving while it is mounted, which is how the canvas prompt reaches a chat that is already open. Unlike the queue of messages written while the agent works, which tab switches clear, a pending prompt belongs to its document and waits until that document's chat takes it; a closed document's goes with its store.
offersCanvasPrompt in src/app/ai/chat/canvas-prompt.ts decides when the canvas shows its prompt: an editable design whose current page has no layers, no local agent working, no prompt waiting, the chat.canvasPrompt preference on, and the prompt not closed or used for that document. It is mounted only in the desktop editor layout, never on Home, in preview, or on phones, and only its card takes the pointer. Playwright's default storage state turns the preference off so empty-canvas specs draw unobstructed; tests/e2e/chat/canvas-prompt.spec.ts turns it on.
A message goes out
src/app/ai/chat/submission/use.ts sends a message through the AI SDK's Chat. Before sending, it appends notes for the model to the text: the layers you referenced, and the edits you undid or redid since the model last heard (context.ts). The transcript shows only what you wrote; stripModelNotes removes the notes. Notes go on the newest message only. Earlier messages never change, so the provider can keep caching the conversation up to the new message.
chat/history/continuation.ts (requestMessages) leaves tool calls without a result out of the request. They stay in the saved transcript.
The model comes from createAIModelRuntime (src/app/ai/models/runtime.ts), with the connection's saved key. A pairdraw connection has no key: it names a workspace on the Home Cloud server, and its model talks to the AI service that server's discovery advertises, through @/app/cloud/integration (src/app/cloud/ai/). Each request carries a short-lived token Cloud signs for that workspace, replaced shortly before it expires and once more when the service refuses it (cloudAIFetch in packages/cloud/src/client/ai.ts), so the service never sees the person's Cloud session.
Skills
Skills are SKILL.md folders in the Agent Skills format (src/app/ai/skills/). The direct chat lists the enabled skills the model may load, by name and description, after its instructions (skillCatalog), and offers two tools while any user-invocable skill is enabled: load_skill returns a skill's instructions and the files in its folder, and read_skill_file reads one of those files, never a path the skill does not list. Scripts in a skill do not run in this chat. The listing is part of the instructions a saved trace records, so a rebuilt request matches the one sent.
Every message first reads the skills again (library.ts): those uploaded in Settings › Skills, kept in IndexedDB as their SKILL.md and text files (sources/uploaded.ts), then, on the desktop, ~/.agents/skills and ~/.claude/skills, through the shell's skill_folders and skill_folder_file commands (desktop/src/agents/skills.rs). Those read only .agents/skills and .claude/skills folders, follow symlinked skills, and read nothing outside a folder with a SKILL.md. On the desktop the library also reads the .agents/skills and .claude/skills folders from the open document's folder up to its repository root, stopping below the home folder (sources/project.ts, project_skill_folders); their skills come after uploads and before the user's own, nearest folder first, and stay off until the user trusts that folder in Settings › Skills, since a skill is instructions the model follows. Uploads are on from the start; the coding agents' folders hold mostly coding workflows, so they start off, and the AI setup's review step offers their skills one by one (AISetupSkills, withPickedSkills). Settings › Skills switches sources and skills either way (preferences.ts, settings/use.ts); of two skills with the same name, the first one switched on is offered, so an upload wins over a folder. The built-in skills (sources/builtin.ts, their Markdown in skills/builtin/) are embedded at build time and read once, so the browser has them too; they come last, so a user's skill with the same name wins, and are on until their source is switched off. A frontmatter that is not valid YAML, usually a description with an unquoted : , is read line by line with a warning rather than dropped.
A message that starts with /skill:name runs that skill, as in pi; the composer's Pick a skill menu (ChatSkillPicker, not offered to ACP agents) writes that command at the start with withSkillCommand, replacing one already there: the request carries the skill's instructions in a note after the text (appendSkillContext), which the transcript leaves out, so every agent follows it without looking it up. Pi gets the enabled skills the model may load, with their text files, in its session configuration (skills/harness.ts), and its harness writes them into Pi's own skills folder. Names, descriptions, instructions, paths, and JSON framing share a 384 KB budget counted in exact UTF-8 JSON bytes; the instructions are reserved first, files past it are left out, and no lazy chunk is imported once the budget is spent. ACP agents keep their own skills.
References
Messages name layers, pages, and skills with Markdown links in the pairdraw: scheme, [Hero](pairdraw://node/12:34) (chat/references/link.ts), in both directions: the composer inserts them and the system prompt asks the model to cite what it touched the same way. The composer is a CodeMirror field (components/chat/composer/), built like the variable formula field: @ completes layers (the current page's first, then other loaded pages'), pages, and skills (references/candidates.ts), and / at the start of a message completes the skills the user can run, or an ACP agent's own commands from available_commands_update (agents/acp/commands.ts). A reference shows as a chip that edits as one unit. The transcript renders the same chip (ChatReferenceChip): replies get references rewritten to an inline chat-reference component before Markdown renders them, so other links keep the renderer's own handling, and the user's text is split around them. The selection button inserts the selected layers as references, and the layers a message mentions go with it as previews (references/nodes.ts), rebuilt from the text when a sent message is edited, which also runs a /skill: again; a message with images still cannot be edited. Hovering a layer chip outlines the layer on the canvas. A chip follows renames, shows its written label once its target is gone, and on click shows the layer on its page, switches to the page, or opens the skill in Settings › Skills; a conversation from another document resolves nothing by ID.
Messages while the agent works
The field stays open while a reply runs, as in pi and Claude Code (chat/queue.ts). Enter queues a steering message and Alt+Enter a follow-up; both show dimmed after the reply until sent. The built-in chat's tool loop also stops once the current step's tool calls finish whenever a steering message waits (yieldWhen in transports/tool-loop.ts), so that message goes in with the step's results, without the step-limit notice. When a reply ends, steering messages go first, then follow-ups, one per reply; a failed reply keeps them. ACP agents and Pi cannot take a message mid-turn, so theirs wait until the turn ends. Escape, or Stop, ends the reply and sends what waits; Up on the first line takes the waiting messages back into the field, images included; changing conversations drops them.
With nothing waiting, Up on the first line and Down on the last step through the prompts sent in the conversation, as a shell's history does (chat/history/prompts.ts); once a recalled prompt is edited, the arrows move the caret again. Text files, such as Markdown, CSS, or code, attach beside images (attachment/text/), up to four per message and 200 KB each. The model reads them in a note after the message (appendFileContext in chat/context.ts), which the transcript strips like the other model notes and shows as attachment tiles; an edited message keeps the note. On the desktop, file: links in replies become chat-file components that show the file in its folder through the Tauri opener and never open it (chat/references/files.ts); the browser's hardened renderer refuses them. A conversation remembers the model profile it last used, saved as soon as it changes, and reopening it selects that profile again. Once a conversation has messages, a switch that leaves context behind asks first (switchContextLoss in chat/history/backend.ts): a coding agent starts from its own session and never sees the messages so far, while a built-in model reads the whole transcript with every request, so leaving an agent for one only drops what the agent's session held, such as its file reads and tool results. Switching between built-in models does not ask.
The chat header pins a style kit (colours, fonts, direction) and up to four reference images to a conversation (chat/pins/), stored with it in the chat database. The isolated Vision model describes each image once, as it is pinned; the conversation's model reads only that description. A request carries the pins in a note after its text only when they changed since the model last heard of them (appendPinnedContext in chat/pins/note.ts, found by lastPinnedNote in the earlier messages), so they cost their tokens once; unpinning everything sends one note saying so. Pinned text is escaped, square brackets included, so an image's text or an imported name cannot close the note or forge another. An image still being described lands in the conversation it was pinned to after a switch, even an unsaved draft, which the history keeps for that (updatePins in chat/history/controller.ts); a conversation left with no messages, title, or pins is forgotten rather than listed. Beside the pins, a context meter shows how full the model's context window is, in tokens only: the built-in chat records each step's tokens in the reply's metadata (stepContextMetadata), an ACP agent's usage_update gives its own window, and otherwise the window comes from models.dev (chat/context-window/).
Two more notes describe the canvas, read as the message is sent so a queued message sees what the agent left (appendCanvasNotes in chat/submission/notes.ts). Let it cook in the composer (ChatExplorePicker, its choice in ai/explore/state.ts) adds an <explore> note (appendExploreContext): variants carry their count, axis (layout or style), and a row placed right of everything on the page, level with the layer they start from (ai/explore/placement.ts), whose copies the note has moved onto the page when that layer sits inside another; "Don't iterate" asks for one design without the review pass. An edited message keeps the note it was sent with (exploreContextOf). Notes people leave on layers for agents, a context and a prompt, are plugin data on the layer (agentNotes, @pairdraw/scene-graph/agent-notes), edited in the Design panel's Notes for AI section, whose Run prompt sends the prompt to the chat naming the layer. A request carries the notes of the layers it names and the selection, with what holds and what is inside them, or of the whole page when there are none, plus a .pen file's context fields and prompt and context cards, up to 30 and each layer name with the same notes once (notes/collect.ts, appendLayerNotesContext). A note an earlier request carried unchanged is left out, and past about 6,000 characters notes are listed by layer only, to be sent whole by a later request. The notes are framed as stored in the document, since an opened file's author may have written them, never as instructions.
A run
transports/tool-loop.ts starts a run (reply/run.ts) when the message is sent, before the model is reached, so a Stop at any point ends a run that exists. A Run belongs to one reply and holds:
- the page it works on, which your navigation does not move and the agent's
switch_pagedoes; - the step budget captured when the message started;
- each page as it was before the run first edited it, for
diff_changes; - every undo entry its calls pushed, with the tool and call that pushed it;
- the calls that changed the document, and the undone calls it already told the model about.
The chat's agent is one presence entry per document (presence/registry.ts). It shows as thinking when the run starts and points at the layers each call changed, on whichever page they are. With Follow agents on, following starts with the run and ends when the agent rests and none of your other agents is at work. An agent you chose to follow keeps you with it while it rests.
Every edit that runEditorTool records, from a reply or from an outside client, goes to showAIEdit (src/app/ai/motion/) with its DocumentChange: added layers trace in through the renderer's aiEnter, changed ones flash, and their top-level frames stay marked active until the edits pause, or until the reply ends when the edit belongs to one. The overlays live in packages/core/src/canvas/overlays/ai/draw.ts and draw on frames the flash pump asks for with requestRepaint.
A tool call
Every call of a Pairdraw tool, from the chat, a coding agent through MCP, or WebMCP, runs through runEditorTool (tools/runner.ts); tools/index.ts passes the chat's calls with their reply:
- Calls that change a document take its lock in turn, since whole-page snapshots must not interleave. A reply's call that gets the lock after the reply ended changes nothing and returns an error.
- The document change is captured and pushed as one undo step; a call that throws part way, such as a failing
eval, is put back whole from that capture and pushes none (rollbackOnThrowineditor/history/edit.ts), unless something else wrote to the document meanwhile: a recorded step, another open edit or batch, text editing, or a room's change (noteOutsideWriteindocument/io/outside-writes.ts). Then the call keeps its step, so the other writes are not reverted. The automation bridge'sevaltakes the same lock (acquireDocumentEdit). A reply's call labels itaiUndoLabel(tool)and records it on the call's own run, the one it started in, even if a later reply has begun; another client's call is labelled by its source, such asAgentorWebMCP. - The change is recorded for the chat's change review, and the agent points at it.
recordToolChange(tools/changes/capture.ts) copies only the page children the change touched (touchedTopLevelIds), on both sides, and diffs their JSX; a change to variables or a move to another page copies whole pages instead. Fonts load for the layers the call touched, not the whole page. - Preview images of the change render later, from those frozen copies plus the layers drawn over or under the changed region, through a queue per document (
tools/changes/previews.ts): one at a time, only while none of the reply's calls is editing and after a short pause, yielding between previews. Closing the document drops the queue. - While a
rendercall is still streaming, its JSX previews on the canvas (preview/), rebuilt at most every 120 ms. A preview keeps one private renderer per CanvasKit until its calls end (createJSXPreviewRecorder), so each rebuild measures only text it has not shaped before. The agent's cursor points at the newest element; updates closer together than 400 ms glide at an even pace over each gap rather than easing to a stop (presence/motion.ts). - A call's result reaches the model as JSON.
evalconverts what a script returns, as MCP and the CLI print it. - If you undid or redid the run's own edits since the model last heard, the result carries an
undoNotesaying so.
A reply ends
A run ends once, in one of three ways: finished (onFinish), failed (handleError), or stopped (the request's abort signal). The agent goes idle and its cursor leaves the canvas, and the design check, held off while the reply edited, checks the page once. A tool already running keeps going: its edit lands in its run, but cannot move the agent again.
When the chat's own onFinish reports a reply that was stopped, failed, or cut off, settleEndedReply waits for the run's last edit, then settles the message (reply/settle.ts):
- reasoning and text are marked done;
- each call that never reported back fails with whether it changed the document, which the model reads next time;
- a stopped reply is marked stopped.
Diagnostics record chat.completed, chat.stopped, or chat.failed.
A reply that finished or failed on its own, rather than one you stopped or one cut off by a disconnect, also reaches notifyReplyEnded (chat/notifications.ts). It quotes the last text part as plain text and sends it through the shared notification service (shell/notifications/), which sends nothing while you are looking at that document. An ACP agent's permission request that is still unanswered after AGENT_INPUT_NOTIFY_DELAY_MS notifies through the same service, by the onUnanswered callback of requestPermissionFromUser.
reply/undo.ts records the reply's turn (reply/turns.ts) once the run settles, so an edit landing after Stop belongs to the reply.
An ACP reply
An ACP agent calls Pairdraw's tools through the MCP server, and its replies keep their edits the same way. The ACP transport (transports/acp.ts) starts a run for each reply with startAgentRun, without the built-in chat's agent presence, since the agent shows through its MCP session, and ends it however the reply ends. Each MCP tool call carries the chat id from the agent's x-pairdraw-chat header and the call's id in the agent's conversation, which Codex sends as _meta.callId and Claude Code as _meta["claudecode/toolUseId"]. While the reply goes on, a call that edits the chat's own document joins the run through runEditorTool, which automation/bridge/tool-handlers.ts calls with the reply, so Revert, Restore, and the undone marks work as for a provider model.
The transport does not start the agent itself: it asks the app's AgentHost (agents/host/) to spawn it and speaks ACP over the stdio streams the host returns. Setup goes through the same host to look agents up, install their adapters and Pairdraw's companions, sign in, and check that a session reaches the tools. The desktop app's host, tauriAgentHost, runs them through the shell commands pinned in desktop/capabilities/default.json. In the browser, companionAgentHost reaches the companion (pairdraw-connect, packages/mcp/src/agents/) the tab paired with in src/app/automation/companion/: lookups and installs are HTTP calls, and each agent's stdio, or a terminal sign-in, runs over its own WebSocket as binary frames, so closing the socket stops the program. While paired, the app's automation bridge and the agent's MCP link use the companion's server and the tab's session token. Connecting an agent in one action (agents/setup/connect.ts) runs those steps in order, stops at the first that fails, and resumes from it.
Undo and the model
A turn keeps the reply's calls and their undo entries. On every undo history change, each turn works out which of its calls are undone with UndoManager.stateOf: an entry on the redo stack is undone, one on the undo stack applied. An entry that left the history keeps its last state; undone and then cleared from Redo by a new edit, it stays undone. Changes are written to the reply's metadata, and the transcript reads only the metadata.
Edit → Undo and the chat's Revert changes therefore end in the same state: Revert undoes the reply's edits still applied, when they are the newest on the undo stack, and Restore changes redoes its undone edits, when Redo would bring exactly those back next.
undoToReport compares each reply's undone calls with what the model was last told, and the next message carries the difference as a note. The report records the message that carried it. If that message is sent again, for example when you edit it, the report is made again.
Saved conversations
A reply's metadata (chat/metadata.ts) keeps whether you stopped it, and its edits with those undone and what the model was last told. Conversations save messages with structuredClone, so metadata is written from the plain message, never from the chat's reactive copy. A save copies only messages and changes replaced since the last one, and the reply still streaming (chat/history/messages.ts); while a reply runs, the conversation is saved at most every five seconds and once as it ends (chat/history/session.ts). Reopening a conversation settles any reply saved mid-way. The undo history does not survive closing a document, so a reopened reply keeps its marks but offers no Revert or Restore.
Compaction and Fast tasks
A long conversation is compacted into a summary before the context window fills (chat/compaction/): the model writes a summary of everything before the latest one, and later requests send the summary and what followed it (messagesSinceCompaction in marker.ts), while the transcript keeps every message with a divider that opens the summary. Compaction runs before a message would leave too little room (compactIfFull, on by default as the chat.compactAutomatically preference), between a reply's steps when a request passes the threshold (steps.ts), from /compact with optional instructions, and as Compact and retry on a context-limit failure (isContextLimitError in chat/failure.ts). The threshold keeps the whole reply allowance, up to half the window (autoCompactAt in limits.ts); the summary request drops images and files, cuts long text and tool data, and keeps the newest messages within a budget derived from the writer's window (summarize.ts). A failed compaction changes nothing and offers Retry; a compaction is dropped when the conversation was switched, edited, or regenerated while it ran. ACP agents and Pi keep compacting their own context.
Fast tasks has two readers, both through fastTasksRuntime (models/fast.ts), which gives the model assigned to Fast tasks itself and null for "Same as Design" or no model, so nothing changes until one is assigned. conversationTitle (chat/history/title.ts) asks it for a title once a conversation's first reply is in, through askModel (models/ask.ts) with the answer's shape as structured output and thinking off; the history controller's nameConversation sets it as a generated title unless the person named the conversation meanwhile, and a failure keeps the title taken from the first message. summaryWriter (chat/compaction/model.ts) picks who writes a compaction summary: the Fast tasks model when it is an API model with a known window, else the conversation's own, because a summary request carries the conversation itself. A coding agent assigned to Fast tasks cannot be asked outside a chat yet, so titles and summaries stay as they are without one.
Custom prompts and design reviews
Settings → Prompts holds the person's own instructions (app/ai/prompts/, stored in the prompts preferences, which hold no credentials). The Design prompt is plain Markdown: systemPrompt() (chat/system-prompt.ts) adds it after Pairdraw's instructions or puts it in their place, with the design JSX reference always last; the tool loop reads it once per reply, and ACP and Pi sessions read it when they start. Review, chat titles, and compaction summaries are Knap templates (templates/*.knap.md, the knap package loaded with the first prompt it fills): renderPrompt (engine.ts) fills the person's template when they wrote one and Pairdraw's otherwise, and a template of theirs that cannot render gives way to the built-in one, so a mistake in Settings never stops the work it is for. Text equal to the built-in saves as no change, so later updates to it still arrive. The editor is CodeMirror with Knap highlighting, diagnostics by line, completion of tags, filters, and the variables in scope, and a preview filled with the definition's sample values (definitions.ts gives each prompt's variables their types).
/review asks the Review model to review the selection or the page (review/run.ts): it sees the layers rendered when its profile reads images (tools/vision/render.ts), with their structure and lint findings from the describe and lint tools, and may ask once to see up to three layers closer. Attached images are references the design is compared against; the focus text after the command steers it. The findings join the conversation as a review message (review/message.ts), which the transcript draws as a card with Fix these — no model reads it until the person sends it on, and messagesSinceCompaction and firstReply leave it out. Each AI edit's change preview offers Review this change (reviewChange), judging the edit from its before and after images and JSX. A model that cannot be asked outside a chat (Pi, or an ACP agent until one-off asks land) refuses the review.
Traces
Save trace… in the conversation menu writes a file to reproduce what the agent did (chat/trace/export.ts). It holds the conversation's messages, its runs, and its diagnostic events.
A run is one message sent and every step the model took to answer it (chat/trace/recorder.ts). It records the model and settings, the last message sent, and per step the response's finish reason, usage, warnings, and duration; a failed run keeps the error, and the step that failed is the one after the last recorded. Instructions and the tools offered are stored once under their fingerprints and shared by every run that used them.
A step's request is not stored. It is the conversation through the run's last message, as requestMessages and compaction prepared it, plus the reply's earlier steps from the latest summary before them; chat/trace/rebuild.ts rebuilds it and compares its fingerprint with the one recorded when the step ran, so a rebuild that no longer matches what was sent is reported instead of replayed. Runs live in the chat database beside their conversation and are deleted with it.