Introducing a new way to review your PRs.

Read the announcement

getnao / nao

👾 nao is the #1 open source agentic BI. (1) Create context with nao-core cli, (2) deploy nao chat interface for everyone

View on GitHub

23 documents · Updated Nov 23, 2026

docs / agent-and-chat

Agent and chat experience

The agent and chat experience turns a user's analysis question into a live conversation with a project-aware agent. It checks access, stores the user turn, streams the agent's work and answer to the chat view, then saves the completed turn so the conversation can continue later.

Conversation lifecycle

Request entry

The request starts in the chat view and reaches the authenticated agent endpoint as a message with its chat mode, model choice, mentions, attachments, and optional citation. The service resolves the project from the existing chat or the user's current context before it starts agent work.

The request is checked against the conversation type and the user's project role. A viewer cannot send a regular message, and an onboarding conversation cannot be continued as a regular conversation. These checks keep the message in the project and mode where it belongs.

References: apps/…/use-agent.ts• L220-265 apps/…/agent.ts• L16-35 apps/…/agent-run.ts• L36-97

Message persistence

The backend records the user turn before it creates the agent run. A new request creates a chat and a first message. A later request adds a message to the existing chat, while an edit or resend creates a new active version of that turn instead of erasing its history.

Images and documents follow the same chat message shape, but the system keeps their content in the right place for later use. Images are made available to the model as image data. Documents remain in project storage and are described by their saved path so the agent can read them when needed.

References: apps/…/agent.ts• L43-140 apps/…/agent.ts• L148-196 apps/…/agent.ts• L1214-1282 apps/…/chat.queries.ts• L175-220

Agent execution

The agent runs with the selected project model and an agent profile that defines the purpose and limits of the run. The profile can set its tools, prompt source, output form, memory and rule boundaries, step limits, and usage category. The same run loop can therefore serve interactive analysis and focused flows without giving every flow the same context.

The model layer presents one common choice of provider, model, context size, thinking controls, and sampling controls while adapting those settings to the selected model. It removes unsupported controls and fits reasoning budgets to provider limits, so a saved setting cannot make an otherwise valid model request fail. In managed cloud mode, the same layer reserves and records model usage against the organization's credit wallet, including completed, failed, and stopped streams.

Before the run starts, the service checks user, project, model, and usage access. It then gathers the project context that the profile allows, such as data access, database schema, mentions, skills, and available tools. File, story, skill, and database access remain subject to the run's grants and project policies. Skills can come from the project, the user, or the built-in catalog, and the agent loads them only when a task needs them. For example, the custom-story guide gives the agent the rules for creating or editing a custom story without exposing that guide as a user-facing choice.

The shared run loop also limits stuck behavior. It can stop after a completed answer or clarification request, and it stops repeated invalid, failed, or identical work before a turn loops without progress. Dedicated profiles can add their own turn-ending tools or require a tool at the next step.

The agent can delegate broad project discovery to an exploration subagent. That subagent searches project files, reads relevant content, and reports paths and definitions within a bounded step count, so the main agent can use focused context instead of scanning the project itself. The search surface can also include permitted user files and story content, while filtering paths and rules that the run cannot access.

For supported runs, code analysis takes place in an isolated sandbox owned by the current user and project. The sandbox can receive allowed project files, chat images, query results, and selected stored files, and can return files to durable user storage. Secrets flow into the sandbox for code to use, while command output is scrubbed before it returns to the agent.

Profiles support more than the main project chat. An automation profile runs a prompt without user interaction and delivers its answer through integration tools. An automation editor profile lets the chat beside an automation's form inspect and change that automation. A Context Hub editor profile lets the chat change the user's context files while keeping shared rules and user memories out of that run. Its optional recommendation tools are enabled only when the feature flag allows them. These profiles keep dedicated product flows within the same agent lifecycle while giving each flow its own purpose and boundaries.

Before the model sees the conversation, the service folds in current artifacts, citation context, story and skill mentions, database references, attachments, memory, and project rules. Rules are rendered for the user's allowed groups, and database objects and columns are filtered by warehouse access and column security. It also applies conversation compaction and provider-specific message handling. The agent can therefore move from a natural-language question to analysis work without making the chat client manage that context itself.

Detailed execution stages are described in Agent runtime. Tool selection, memory, and prompt rules are described in Agent tools, memory, and prompts.

References: apps/…/agent.ts• L312-387 apps/…/agent.ts• L528-567 apps/…/agent.ts• L697-744 apps/…/agent.ts• L760-827 apps/…/types.ts• L8-48 apps/…/onboarding.ts• L11-40 apps/…/index.ts• L1-21 apps/…/story-kit.skill.ts• L1-9 apps/…/stop-conditions.ts• L5-93 apps/…/automation.ts• L5-29 apps/…/automation-editor.ts• L8-22 apps/…/context-editor.ts• L14-33 apps/…/story-model.ts• L11-33 apps/…/provider-meta.ts• L363-385 apps/…/provider-meta.ts• L1105-1176 apps/…/providers.ts• L298-377 apps/…/providers.ts• L438-453 apps/…/providers.ts• L455-652 apps/…/managed-ai.ts• L44-71 apps/…/managed-ai.ts• L92-165 apps/…/managed-ai.ts• L254-339 apps/…/model-prices.ts• L7-32 apps/…/explore.ts• L14-35 apps/…/grep.ts• L68-110 apps/…/grep.ts• L180-234 apps/…/load-skill.ts• L12-81 apps/…/execute-sandboxed-code.ts• L406-524 apps/…/execute-sandboxed-code.ts• L385-403 apps/…/user-rules.ts• L16-35 apps/…/user-rules.ts• L92-155 apps/…/user-rules.ts• L352-409

Streamed response

The answer travels back as a server-sent event stream. The stream carries assistant text, reasoning, tool activity, and compaction updates as they become available. It also carries chat events such as the new chat identity, the saved user message identity, and title changes. Memory extraction and title generation can start while the run proceeds.

The client uses those events to show work in progress without waiting for the full answer. Reasoning appears in a collapsible thinking panel, while compaction appears as a separate expandable summary or error. Streaming Markdown seals complete blocks before rendering the still-changing tail, which keeps tables, code, links, and special answer tags stable as more text arrives.

When the stream ends, the service settles tool parts and saves the assistant turn with its stop state, usage, model, and any error. The completed message can then render richer answer features, such as stored-file chips, story references, query citations, and support actions. A new chat moves from its temporary view to its saved route, and a generated title updates both the durable chat and the live view.

This diagram shows how a question becomes live output and then a reloadable conversation.

flowchart LR
    A[User question] --> B[Chat client]
    B --> C[Authenticated agent request]
    C --> D[Access and project checks]
    D --> E[Persist user turn]
    E --> F[Project-aware agent run]
    F --> G[Stream text and work events]
    G --> H[Live chat view]
    G --> I[Persist completed assistant turn]
    I --> J[Reloadable conversation]

References: apps/…/agent.ts• L599-691 apps/…/agent.ts• L860-923 apps/…/agent.ts• L37-72 apps/…/use-agent.ts• L167-218 apps/…/use-agent.ts• L268-301 apps/…/assistant-reasoning.tsx• L14-59 apps/…/assistant-compaction.tsx• L10-35 apps/…/streaming-markdown.tsx• L23-85

Conversation state

The chat is the durable record of the exchange. It contains the active messages, message parts, source, model details, stop state, usage, and any active edit version. The chat query reconstructs that record for the client, while the client cache mirrors streamed messages during a run and refreshes from the server after the run ends.

Users can stop or cancel a run. Stopping interrupts the current agent. Cancelling also decides whether to keep the partial turn or remove the empty last turn and restore the user's input. This gives the user a safe way to retry without losing the conversation's prior state.

The live view also keeps user message features tied to that state. Users can edit, resend, copy, and move between message versions. Citations stay attached to the user turn so a copied or edited request can preserve its source references.

References: apps/…/chat.queries.ts• L175-260 apps/…/chat.routes.ts• L148-183 apps/…/use-agent.ts• L373-432 apps/…/use-agent.ts• L591-630 apps/…/user-message.tsx• L198-347

Analysis outputs

Artifacts

Artifacts are useful outputs that outlive one message and remain easy to find in the conversation. The chat experience gathers stories, mentioned stories, user files, query results, and charts from the visible message history, then presents them through the chat's Library entry point. The Library docks beside the chat when the layout has room. Otherwise, it stays available from a compact button.

Stories can open in the side panel. Files can open in an attachment viewer. Query entries take the user back to the related tool result, and charts preserve the query and display choice that produced them. Stories may be classic documents or custom story projects. A custom story can remain a draft while its files change and becomes a live artifact only after it builds and is published.

On a later agent turn, the backend rebuilds the current artifact set and adds a compact description to the model context so the agent can refer to the same outputs without repeating their full content. Query artifacts keep a query identity and result shape so later work can revisit or reshape an earlier result. Queries can read project files through the local analysis database, use an allowed connected warehouse, or use the semantic query path when raw warehouse SQL is not enabled. The system places this description in the latest user turn and keeps a cache boundary before it, so the stable conversation prefix can be reused while artifact state changes.

References: apps/…/chat-artifacts.ts• L35-59 apps/…/chat-artifacts-menu.tsx• L35-85 apps/…/chat-artifacts-menu.tsx• L148-208 apps/…/chat-artifacts.ts• L16-75 apps/…/agent.ts• L676-708 apps/…/prompt-cache.ts• L24-38 apps/…/prompt-cache-artifacts.test.ts• L30-81 apps/…/execute-sql.ts• L32-115 apps/…/execute-sql.ts• L169-229 apps/…/page-query-result.ts• L8-45 apps/…/display-chart.ts• L9-82 apps/…/story.ts• L48-87 apps/…/story.ts• L298-355 apps/…/story.ts• L435-470

Attachments and citations

Attachments and citations connect a question to source material. The input can include images, stored documents, or a selected text range from a story. The agent receives enough information to inspect the source or act on the selected block, while the chat keeps the link visible as part of the user turn.

The backend describes the latest citations in full for the agent and replaces older citation markers with quoted text. This lets a follow-up question keep its source meaning without repeating all citation metadata in every turn. The user view shows citation references as interactive mentions that open the related source.

References: apps/…/chat-input.tsx• L114-139 apps/…/user-message.tsx• L132-190 apps/…/chat.ts• L174-217 apps/…/agent.ts• L1063-1075 apps/…/agent.ts• L1284-1347

Answer rendering

Answer rendering turns streamed or saved assistant text into readable analysis output without confusing model markup with user-visible content. During streaming, only safe live components are shown and incomplete file tags stay hidden. After the answer settles, stored files become openable or downloadable chips, story references become cards or links, query values become citation popovers, and support links become an in-app support action.

The renderer preserves ordinary Markdown and code examples. It also detects text direction per block, which keeps mixed-language answers readable. These rules apply to both live answers and saved answers so replay does not change the meaning of the original response.

References: apps/…/citation-text.tsx• L48-90 apps/…/citation-text.tsx• L105-121 apps/…/citation-text.tsx• L209-311 apps/…/streaming-markdown.tsx• L23-85 apps/…/citation-text.test.tsx• L57-168 apps/…/citation-text.test.tsx• L314-357

Response actions

Response actions extend a completed answer beyond the live message. A user can rate the response with optional feedback, copy one message or the full chat, export the chat as Markdown or PDF, and save a suitable response as a test when the user has permission.

These actions connect the live chat to review and reuse. Feedback updates the saved response and refreshes chat review data, while exports use the chat's title and selected content options so the output can move into another workflow.

References: apps/…/assistant-message-actions.tsx• L42-123 apps/…/assistant-message-actions.tsx• L165-235

User experience boundaries

Chat modes

The product supports regular project analysis, onboarding, and example conversations. These modes share the conversational surface but use different project resolution and access rules. Onboarding remains separate from regular project work so setup messages do not enter the normal analysis history.

Onboarding is a guided setup conversation. It records progress, displays copyable local-agent prompts and terminal commands, asks the user to select a warehouse, and displays a secure credential form instead of accepting secrets in chat. Warehouse setup then runs in the background and reports whether it is ready, stopped, or needs a retry. When setup is complete, the collected business context can seed the project's initial rules. A restart moves the user to a new onboarding conversation.

The onboarding profile can require a warehouse choice or credential form immediately after the database flow starts. These user-facing hand-offs end the turn so the next message carries the user's selection or form result.

References: apps/…/use-agent.ts• L45-46 apps/…/agent-run.ts• L44-79 apps/…/chat.ts• L206-217 apps/…/onboarding.ts• L16-40 apps/…/index.ts• L11-26 apps/…/request-warehouse-selection.ts• L4-12 apps/…/request-warehouse-credentials.ts• L4-18 apps/…/wait-for-warehouse-setup.ts• L7-23 apps/…/generate-onboarding-rules.ts• L6-27 apps/…/restart-onboarding.ts• L6-18

Client state

The chat page exposes one agent state to its input, message list, controls, and artifact view. A client agent instance stays associated with a chat while it runs, which lets the user change views or use more than one chat without losing the active stream. Read-only views use the same message shape without send, stop, or edit actions.

References: apps/…/agent.provider.tsx• L44-114 apps/…/agents.ts• L1-28 apps/…/_sidebar-layout._chat-layout.$chatId.tsx• L71-103

Conversation replay

A conversation replay is a read-only view of a saved chat for review. It loads the durable messages and related metadata, then presents the same user turns, assistant work, tool results, citations, model labels, timing, and feedback without starting a new agent run.

The replay keeps saved answer behavior separate from live controls. It filters superseded query work, groups tool calls, shows compaction state, hides timestamps that belong only to fork copies, and preserves citation pills for forked selections. An engineer or reviewer can move between feedback and tool errors, open related stories in the side panel, inspect chat analytics, and use a stable link to return to the same chat.

References: apps/…/chats-replay-panel.tsx• L38-64 apps/…/chats-replay-panel.tsx• L116-203 apps/…/chat-messages-readonly.tsx• L38-103 apps/…/chat-messages-readonly.tsx• L138-281

The chat page is the product-level view of a larger agent system. Read Agent runtime for the run lifecycle and response control. Read Agent tools, memory, and prompts for how the agent gains project context, remembers useful facts, and follows prompt policy.

Change checklist

When these files or sections are changed, remember to consider these:

  • Keep the request mode, project resolution, and stored message source aligned. A mismatch can route a valid-looking message to the wrong conversation type.
  • Keep streamed custom events aligned with the client event handler. New-chat routing, title updates, compaction display, and server message IDs depend on those event contracts.
  • Keep active message versions and artifact collection aligned. Edits and resends must not leave stale query, story, chart, or file entries in the visible conversation.
  • Keep artifact placement and prompt-cache boundaries aligned. Moving the artifact summary can reduce cache reuse or give a later turn stale context.
  • Keep stop and cancel behavior aligned between the client agent and the server agent registry. A client-only stop can leave a server run active.
  • Keep streamed and settled answer tag rules aligned. A tag that is safe after completion must not appear as broken markup while it is still incomplete.
  • Keep replay metadata and read-only rendering aligned. Missing message models, feedback links, fork metadata, or compaction parts can make a saved review misleading without changing the chat record.
  • Keep response actions aligned with chat and feedback contracts. Export options, response ratings, and save-as-test eligibility depend on the message shape and the user's permissions.
  • Keep each agent profile's purpose, tools, prompt boundaries, step and output limits, and usage category aligned with its caller. Dedicated editor, onboarding, and automation flows must not inherit interactive chat behavior by accident.
  • Keep onboarding hand-off tools, turn-ending rules, setup status, and the next user message aligned. A form can display correctly while the agent continues with the wrong assumption if the turn does not end.
  • Keep model catalog capabilities, provider request options, context limits, and price data aligned. A model can appear selectable while failing at run time or charging the wrong amount if these contracts drift.
  • Keep model capability metadata aligned with provider inference settings. Thinking, sampling, and extra options must be removed, clamped, or translated consistently for each provider.
  • Keep managed model aliases and managed-provider availability aligned with usage billing. Legacy names must resolve to billable models without bypassing user and organization checks.
  • Keep SQL tool policy aligned with project semantic-layer mode and query identity. Switching the allowed query path can change whether a result is safe to run or whether saved charts and stories still point to the right query.
  • Keep chart and story artifact contracts aligned. A chart or story that uses a query must preserve its query identity when the result is edited or displayed again.
  • Keep internal skill descriptions aligned with the tools and capabilities available to the run. A skill must not tell the agent to use a missing tool or apply custom-story rules to a classic story.
  • Keep skill availability aligned with project grants, path access, and the prompt's listed skills. A hidden project skill must not be exposed by the load error or made usable by a run without access.
  • Keep search, sandbox mounts, and rules rendering aligned with project and user-file access. A tool must not return paths or rule lines that the current run cannot read.
  • Keep sandbox ownership, reuse, expiry, secret redaction, and durable file storage aligned. Reusing a sandbox across users or projects can cross the data boundary, while losing the output copy can make a successful analysis appear to have no artifact.
  • Keep database context catalogs aligned with warehouse and column security. Cached schema context must refresh when generated database metadata changes.

Important failure modes

TriggerConsequenceGuard
A request uses a mode that does not match its existing chatThe request is rejected instead of changing the chat's meaningValidate the chat mode before resolving the run
A user without send access submits a regular messageThe message is not stored or sent to the modelCheck project role and billing access before persistence
Onboarding displays a warehouse form but the turn does not endThe agent can continue without the user's choice or credentialsTreat selection, credential, and restart tools as turn-ending hand-offs
Warehouse setup stops or loses its statusThe user cannot tell whether setup needs input or a retryPersist setup state and expose wait and retry outcomes in the onboarding chat
The stream disconnects during a runThe client may stop showing progress while the server still needs to settle the turnTrack disconnects and persist the final stop or error state
An edited turn is treated as an overwriteVersion history and retry behavior become incorrectSupersede the old active branch and retain version metadata
Artifact rebuilding failsThe agent may lose useful conversation contextFall back to the original history instead of failing the whole run
Artifact text moves across the cache boundaryLater turns lose prompt-cache reuse or cache stale artifact contextKeep the artifact summary attached to the current user turn and cache only the stable prefix
A bounded or dedicated profile inherits interactive tools, rules, or memoryAn automation, story, onboarding, or editor run can use the wrong context or continue beyond its intended purposeKeep profile purpose, tool access, prompt exclusions, step limits, output form, and usage category explicit
The agent repeats invalid, failed, or identical tool workA turn wastes model calls or never reaches a user-visible answerApply invalid-call, tool-error, repeated-call, repeated-step, and total-step stop conditions
A custom story is edited without a usable published buildThe user sees a draft that cannot become a live artifactKeep draft edits separate from publish and report build errors before publication
A query ID is lost when a result is editedA chart, table, or story can point to an old or missing resultPreserve query IDs for in-place edits and page only stored query results
Raw SQL uses a disabled warehouse path or a stale query identityThe query is blocked, or a chart or story reads a result that no longer matches its saved queryEnforce the project query policy and preserve query IDs when a result is edited
An incomplete saved-file or story tag is rendered as settled contentThe live answer shows broken markup or an unsafe actionRender only safe streaming tags and wait for complete tags before enabling answer components
A citation marker is not normalized between the agent and chat rendererThe answer loses its source link or shows raw citation markupKeep citation marker formats and interactive citation components aligned
A selected model has stale capability or price metadataThe provider rejects the request or usage is charged with the wrong rateResolve model controls and prices from the same provider catalog and price book
Provider inference settings exceed the selected model's capabilitiesThe provider rejects the request or the model receives a control it cannot honorResolve settings from the model capability catalog and clamp or remove unsupported options
A managed stream ends without a usage outcomeThe wallet reservation or usage record stays out of sync with the visible chat resultRecord completed, failed, and aborted calls with the run and message context
A skill is listed without a matching grant or allowed project pathThe agent can receive context that the user cannot access, or the skill name leaks through an errorApply the same access checks when listing and loading project skills
Search or sandbox context includes a path outside the current access scopeThe agent can inspect project, story, or user-file content that the run should not seeResolve canonical paths and filter every search result and sandbox mount by run policy
A sandbox is reused with a different user or projectFiles or secrets from one owner can reach another runBind pooled sandboxes to the user-project owner and reject mismatched reuse
Sandbox output contains a secret or a saved file is not copied to durable storageSensitive values reach the model, or a user loses a file after the sandbox expiresRedact command output and copy only validated output files into the owner's storage
Cached database context does not reflect changed metadata or column policyThe agent can use stale schema information or suggest a blocked columnRecompute the catalog from its freshness signature and apply table and column access checks
Replay data or metadata fails to loadReviewers see an incomplete chat or cannot inspect the related evidenceKeep loading and error states explicit and render replay data only after the saved record is ready
Feedback or export actions use stale chat dataThe user sees an incorrect rating or an incomplete exported conversationUpdate the local chat record after feedback and build exports from the current message set and metadata

Key files

FileWhy to read it
apps/…/use-agent.tsShows how the client sends requests, consumes stream events, mirrors messages, and handles stop, cancel, edit, and retry actions.
apps/…/agent.tsShows the external streaming boundary for an agent request.
apps/…/agent-run.tsShows how project, mode, role, and billing checks select an allowed run.
apps/…/agent.tsShows the handoff from a request to a persisted user turn and an agent stream.
apps/…/agent.tsShows how a run becomes a project-aware response, prepares source context, streams work, and saves the final assistant turn.
apps/…/types.tsShows the shared controls that give each agent run its purpose, context boundaries, tools, limits, output form, and usage category.
apps/…/onboarding.tsShows how onboarding gets a dedicated prompt, tool set, and required warehouse hand-offs.
apps/…/index.tsShows which onboarding actions can hand control back to the user.
apps/…/index.tsShows the catalog of built-in guides that the agent can load on demand.
apps/…/story-kit.skill.tsShows the guide used when the agent authors a custom story.
apps/…/stop-conditions.tsShows how the run ends on a completed interaction or repeated stuck work.
apps/…/automation.tsShows the bounded, unattended profile that sends answers through automation integrations.
apps/…/automation-editor.tsShows the profile for the chat that works beside an automation form.
apps/…/context-editor.tsShows the profile for editing user context while excluding shared rules and user memories.
apps/…/execute-sandboxed-code.tsShows how code work receives allowed context, uses isolated execution, redacts secrets, and saves selected output files.
apps/…/grep.tsShows how agent search spans permitted project, user-file, story, and story-library content while preserving visible rules.
apps/…/load-skill.tsShows how project, personal, and internal skills are resolved without exposing inaccessible project skills.
apps/…/user-rules.tsShows how project rules and database context are rendered with group, table, and column access controls.
apps/…/story-model.tsShows the bounded profile used when a custom story asks for one answer from its own data.
apps/…/provider-meta.tsShows the provider and model catalog that defines model limits and supported controls.
apps/…/providers.tsShows how a selected model becomes a provider request with compatible inference settings.
apps/…/managed-ai.tsShows managed model selection and usage reservation, metering, and wallet charging.
apps/…/model-prices.tsShows how model token prices are resolved for usage records and reservations.
apps/…/explore.tsShows the bounded project-discovery agent used when context is not yet known.
apps/…/index.tsShows how the run's data, storage, story, map, MCP, and focused tool surfaces are selected.
apps/…/execute-sql.tsShows how agent queries use local data, warehouses, semantic queries, and stable query identities.
apps/…/page-query-result.tsShows how later turns inspect more rows from a stored query result without rerunning it.
apps/…/display-chart.tsShows how query results become chart or table artifacts for supported chat surfaces.
apps/…/story.tsShows how classic and custom stories become versioned or published analysis artifacts.
apps/…/chat.queries.tsShows how durable chat messages and active message versions are reconstructed.
apps/…/chat-artifacts.tsShows how stored stories and query results become reusable conversation context.
apps/…/citation-text.tsxShows how live and settled assistant text becomes Markdown, citations, file actions, story references, and support actions.
apps/…/streaming-markdown.tsxShows how changing Markdown is split into stable blocks for live rendering.
apps/…/user-message.tsxShows how user attachments, citations, mentions, editing, resending, copying, and message versions appear in chat.
apps/…/assistant-message-actions.tsxShows how users rate, copy, export, and reuse completed responses.
apps/…/prompt-cache.tsShows how stable conversation content and changing artifact context share prompt caching.
apps/…/chats-replay-panel.tsxShows how a saved conversation becomes a review view with navigation, side-panel access, and analytics.
apps/…/chat-messages-readonly.tsxShows how saved messages, tool work, citations, compaction, timing, models, and feedback appear without live controls.
apps/…/chat-artifacts-menu.tsxShows how analysis outputs become a user-facing Library.