---
title: "Chat"
description: "A local conversation with an editable prompt and response actions."
---

# Chat

A local conversation with an editable prompt and response actions.

## Usage

Send the suggested prompts to replay three scripted turns. Reasoning, commands and Markdown arrive progressively. Enter sends; Shift+Enter inserts a newline. Reset starts a new thread; Latest message returns to the live edge.

## Example

````contract
use FieldFocus from "@rightui/ui"
use FontWeights from "@rightui/ui"
use uiFontFamily, MessageFrame, MessageContent, BubbleFrame, MessageIcon from "@rightui/ui"
use TraceFrame, TraceLine, TraceDisclosure, TraceCollapsible, CodeBlockContent from "@rightui/ui"
use ButtonAI as ButtonContent from "@rightui/ui"
use CompactAiMenu, InputGroupFrame, InputGroupAddon from "@rightui/ui"
use AdvancedMenuEntry from "@rightui/ui"
use Markdown from "@rightui/ui"
use uiReveal from "@rightui/ui"

shape ChatTurn
  id: number
  prompt: string
  script: number
  started: number

fn chatReply(turn: number): string = turn == 0 ? "next-themes is already set up in `app/layout.tsx`, so the toggle only has to call `setTheme`.\n\n**Changes**\n\n- Added `components/mode-toggle.tsx` with a Light and Dark option.\n- Put `<ModeToggle />` next to the Appearance heading in `app/settings/page.tsx`.\n\n```tsx\nconst { setTheme } = useTheme()\n```\n" : turn == 1 ? "It was set to `light`. I updated the `ThemeProvider` in `app/layout.tsx`:\n\n```tsx\n<ThemeProvider attribute=\"class\" defaultTheme=\"system\" enableSystem>\n```\n\nNew visitors now get the theme from their OS. The toggle also has a **System** option, so anyone who picked Light or Dark can switch back.\n" : turn == 2 ? "The build passes, so it is ready to ship.\n\n- Compiled in **4.2s**.\n- No lint or type errors.\n- Generated all **12** static pages.\n" : "This demo only knows the scripted turns. Press reset to start over."
fn chatThought(turn: number): string = turn == 0 ? "I need to know how themes are set up before I add a toggle. If next-themes is already in the layout, the toggle only has to call setTheme." : turn == 1 ? "The default theme lives on the ThemeProvider. I should check what it is set to now." : turn == 2 ? "" : ""
fn chatCommand(turn: number): string = turn == 0 ? "rg -l ThemeProvider app" : turn == 1 ? "rg -n defaultTheme app/layout.tsx" : turn == 2 ? "pnpm build" : ""
fn chatOutput(turn: number): string = turn == 0 ? "app/layout.tsx" : turn == 1 ? "12:  <ThemeProvider attribute=\"class\" defaultTheme=\"light\">" : turn == 2 ? "▲ Next.js 16.0.0\n\n✓ Compiled successfully in 4.2s\n✓ Linting and checking validity of types\n✓ Generating static pages (12/12)" : ""

component ChatResponse
  props
    id: string
    script: number
    elapsed: number
    reduced: bool
  inject
    uiFont: string
  state thoughtOpen = false
  derive thoughtEnd = script < 2 ? 600 + chatThought(script).length * 16 : 600
  derive commandStart = thoughtEnd + 400
  derive commandEnd = commandStart + (script == 2 ? 1600 : 800)
  derive replyStart = script == 3 ? 600 : commandEnd + 500
  derive reply = chatReply(script).slice(0, max(0, floor((elapsed - replyStart) / 16)))
  action toggleThought
    thoughtOpen = not thoughtOpen
  view
    MessageFrame(id=id, align="start")
      MessageContent(id=id + "-content", align="start")
        column gap="ui.space-12"
          TraceFrame()
            if script < 2 and elapsed >= 600
              TraceDisclosure(id=id + "-thought", title=(elapsed < thoughtEnd ? "Thinking" : "Thought"), icon="check", status=(elapsed < thoughtEnd ? "running" : ""), open=(thoughtOpen or elapsed < thoughtEnd), reduced=reduced, toggle=toggleThought)
                text chatThought(script).slice(0, max(0, floor((elapsed - 600) / 16))) font-size="ui.text-sm" line-height="ui.leading-relaxed" white-space="pre-wrap" font-family=uiFontFamily(uiFont) data-rightui-font="body"
            if script < 3 and elapsed >= commandStart
              if elapsed < commandEnd
                TraceLine(title="Running " + chatCommand(script), icon="terminal", status="running", reduced=reduced)
              else
                TraceCollapsible(id=id + "-command", title="Ran " + chatCommand(script), icon="terminal", status="", initiallyOpen=false, reduced=reduced)
                  CodeBlockContent(id=id + "-output", code=chatOutput(script))
          if reply != ""
            Markdown(id=id + "-reply", content=reply)

component Demo
  props
    width: number
    reduced: bool
  inject
    uiWeights: FontWeights
    uiFont: string
    rightuiDemoTime: number
    rightuiRunDemo: action
  state turns: ChatTurn[] = []
  state draft = "Add a dark mode toggle to the settings page."
  state busyUntil = 0
  state away = false
  state selectedContext = ""
  derive busy = rightuiDemoTime < busyUntil
  action edit(value: string)
    draft = value
  action reset
    if not busy
      turns = []
      draft = "Add a dark mode toggle to the settings page."
      selectedContext = ""
      away = false
  action chooseContext(group: string, value: string)
    if value == "Add Photos & Files"
      showPicker("ai-chat-files")
    else
      selectedContext = value
  action picked(files: Picked[])
    selectedContext = files.map(file => file.name).join(", ")
  action moved(x: number, y: number, e: ScrollEvent)
    away = e.scrollHeight - e.scrollTop - e.clientHeight > 24
  action latest
    match turns.at(-1)
      case some(turn)
        if reduced
          scrollIntoView("ai-chat-thread", turn.id, block="end", behavior="instant")
        else
          scrollIntoView("ai-chat-thread", turn.id, block="end", behavior="smooth")
      case none
        away = false
  action send
    if draft.trim() != "" and not busy
      let prompt = draft.trim()
      let nextLength = turns.length + 1
      let script = prompt == "Add a dark mode toggle to the settings page." ? 0 : prompt == "Make it follow the system setting by default." ? 1 : prompt == "Run the build before I ship it." ? 2 : 3
      let duration = (script == 3 ? 600 : (script < 2 ? 600 + chatThought(script).length * 16 : 600) + 400 + (script == 2 ? 1600 : 800) + 500) + chatReply(script).length * 16 + 100
      turns = turns.concat([ChatTurn(id=turns.length, prompt=prompt, script=script, started=rightuiDemoTime)])
      busyUntil = rightuiDemoTime + duration
      rightuiRunDemo(duration)
      draft = nextLength == 1 ? "Make it follow the system setting by default." : nextLength == 2 ? "Run the build before I ship it." : ""
  action keys(k: string, e: KeyboardEvent)
    if k == "Enter" and not e.shiftKey and not e.isComposing
      preventDefault()
      send()
  view
    column width="100%" height=800 gap="ui.space-16" min-width=0 background-color="ui.background"
      input id="ai-chat-files" type="file" multiple=true change=picked display="none" font-family=uiFontFamily(uiFont) data-rightui-font="body"
      row justify-content="space-between" align-items="flex-start" gap="ui.space-16" padding="ui.space-32 ui.space-32 ui.space-16"
        column gap="ui.space-4"
          text "New Thread" font-weight=uiWeights.medium font-family=uiFontFamily(uiFont) data-rightui-font="body"
          text "Ask the agent to change your code." font-size="ui.text-sm" color="ui.muted-foreground" font-family=uiFontFamily(uiFont) data-rightui-font="body"
        ButtonContent(id="ai-chat-reset", label="Reset conversation", variant="outline", size="icon", disabled=busy, press=reset)
          MessageIcon(name="arrow.clockwise", filled=false)
      if turns.length == 0
        column flex=1 gap="ui.space-8" align-items="center" justify-content="center" padding="ui.space-32"
          view width="ui.space-40" height="ui.space-40" display="flex" align-items="center" justify-content="center" border-radius="ui.radius-md" background-color="ui.muted"
            MessageIcon(name="message", filled=false)
          text "What should we build?" font-size="ui.text-lg" font-weight=uiWeights.medium font-family=uiFontFamily(uiFont) data-rightui-font="body"
          text "The agent can read your code, run commands and make changes. Press send to start." max-width="20rem" text-align="center" font-size="ui.text-sm" line-height="ui.leading-relaxed" color="ui.muted-foreground" font-family=uiFontFamily(uiFont) data-rightui-font="body"
      else
        column flex=1 min-height=0 position="relative"
          list id="ai-chat-thread" testId="ai-chat-thread" aria-busy=busy appearance="none" virtualized=true scroll-start="end" scrollFollowEnd=true scroll=moved flex=1 min-height=0
            for turn in turns key=turn.id
              column gap="ui.space-24" padding="ui.space-0 ui.space-32 ui.space-24" min-width=0
                MessageFrame(id="ai-chat-user-" + turn.id.toString(), align="end")
                  MessageContent(id="ai-chat-user-content-" + turn.id.toString(), align="end")
                    BubbleFrame(id="ai-chat-bubble-" + turn.id.toString(), align="end", variant="muted")
                      text turn.prompt white-space="pre-wrap" animation=(reduced ? "none" : "uiReveal ui.duration-normal ui.easing both") font-family=uiFontFamily(uiFont) data-rightui-font="body"
                if rightuiDemoTime - turn.started >= 600
                  ChatResponse(id="ai-chat-assistant-" + turn.id.toString(), script=turn.script, elapsed=rightuiDemoTime - turn.started, reduced=reduced)
          if away
            row position="absolute" bottom="ui.space-8" left=0 right=0 justify-content="center"
              ButtonContent(id="ai-chat-latest", label="Latest message", variant="outline", size="sm", disabled=false, press=latest)
                svg width="ui.space-16" height="ui.space-16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="ui.icon-stroke" aria-hidden=true
                  path d="M12 5v14m-6-6 6 6 6-6"
      column padding="ui.space-0 ui.space-32 ui.space-32" gap="ui.space-8"
        InputGroupFrame(id="ai-chat-composer")
          textarea class=FieldFocus id="ai-chat-thread-draft" testId="ai-chat-thread-draft" value=draft input=edit key=keys aria-label="Message" placeholder="Ask the agent..." min-height="ui.space-56" border="0" padding="ui.space-12" background-color="transparent" color="ui.foreground" font-size="ui.text-sm" font-family=uiFontFamily(uiFont) data-rightui-font="body"
          InputGroupAddon(id="ai-chat-toolbar")
            CompactAiMenu(id="ai-chat-context", label="Add context", prefix="Context", entries=[AdvancedMenuEntry(id="files", parent="", label="Add Photos & Files", kind="item", shortcut="", disabled=false, group="effort", value="Add Photos & Files"), AdvancedMenuEntry(id="separator", parent="", label="", kind="separator", shortcut="", disabled=false, group="", value=""), AdvancedMenuEntry(id="research", parent="", label="Deep Research", kind="item", shortcut="", disabled=false, group="effort", value="Deep Research"), AdvancedMenuEntry(id="web", parent="", label="Web Search", kind="item", shortcut="", disabled=false, group="effort", value="Web Search")], value=selectedContext, reduced=reduced, radio=chooseContext)
            view flex=1
            ButtonContent(id="ai-chat-thread-send", label="Send", variant="default", size="icon-sm", disabled=(draft.trim() == "" or busy), press=send)
              MessageIcon(name="arrow.up", filled=false)
        if selectedContext != ""
          text selectedContext role="status" font-size="ui.text-xs" color="ui.muted-foreground" font-family=uiFontFamily(uiFont) data-rightui-font="body"

````

## Keyboard

Tab to controls; Enter or Space to activate buttons.

## Demo runtime

Timed examples use an injected clock. Add these members to your root component. Replace the scripted state with events from your TypeScript or Rust data source when connecting a model.

```contract
use defaultFontWeights from "@rightui/ui"
  state demoTime = 0
  state demoUntil = 0
  provide
    uiFont = "theme"
    uiWeights = defaultFontWeights()
    rightuiDemoTime = demoTime
    rightuiRunDemo = runDemo
  action runDemo(duration: number)
    demoUntil = max(demoUntil, demoTime + duration)
  action tickDemo
    demoTime = min(demoUntil, demoTime + 32)
  task demoClock when demoTime < demoUntil
    every(32, tickDemo)
```

## Source

File: patterns/ai-elements/chat.contract

````contract
use FieldFocus from "@rightui/ui"
use FontWeights from "@rightui/ui"
use uiFontFamily, MessageFrame, MessageContent, BubbleFrame, MessageIcon from "@rightui/ui"
use TraceFrame, TraceLine, TraceDisclosure, TraceCollapsible, CodeBlockContent from "@rightui/ui"
use ButtonAI as ButtonContent from "@rightui/ui"
use CompactAiMenu, InputGroupFrame, InputGroupAddon from "@rightui/ui"
use AdvancedMenuEntry from "@rightui/ui"
use Markdown from "@rightui/ui"
use uiReveal from "@rightui/ui"

shape ChatTurn
  id: number
  prompt: string
  script: number
  started: number

fn chatReply(turn: number): string = turn == 0 ? "next-themes is already set up in `app/layout.tsx`, so the toggle only has to call `setTheme`.\n\n**Changes**\n\n- Added `components/mode-toggle.tsx` with a Light and Dark option.\n- Put `<ModeToggle />` next to the Appearance heading in `app/settings/page.tsx`.\n\n```tsx\nconst { setTheme } = useTheme()\n```\n" : turn == 1 ? "It was set to `light`. I updated the `ThemeProvider` in `app/layout.tsx`:\n\n```tsx\n<ThemeProvider attribute=\"class\" defaultTheme=\"system\" enableSystem>\n```\n\nNew visitors now get the theme from their OS. The toggle also has a **System** option, so anyone who picked Light or Dark can switch back.\n" : turn == 2 ? "The build passes, so it is ready to ship.\n\n- Compiled in **4.2s**.\n- No lint or type errors.\n- Generated all **12** static pages.\n" : "This demo only knows the scripted turns. Press reset to start over."
fn chatThought(turn: number): string = turn == 0 ? "I need to know how themes are set up before I add a toggle. If next-themes is already in the layout, the toggle only has to call setTheme." : turn == 1 ? "The default theme lives on the ThemeProvider. I should check what it is set to now." : turn == 2 ? "" : ""
fn chatCommand(turn: number): string = turn == 0 ? "rg -l ThemeProvider app" : turn == 1 ? "rg -n defaultTheme app/layout.tsx" : turn == 2 ? "pnpm build" : ""
fn chatOutput(turn: number): string = turn == 0 ? "app/layout.tsx" : turn == 1 ? "12:  <ThemeProvider attribute=\"class\" defaultTheme=\"light\">" : turn == 2 ? "▲ Next.js 16.0.0\n\n✓ Compiled successfully in 4.2s\n✓ Linting and checking validity of types\n✓ Generating static pages (12/12)" : ""

component ChatResponse
  props
    id: string
    script: number
    elapsed: number
    reduced: bool
  inject
    uiFont: string
  state thoughtOpen = false
  derive thoughtEnd = script < 2 ? 600 + chatThought(script).length * 16 : 600
  derive commandStart = thoughtEnd + 400
  derive commandEnd = commandStart + (script == 2 ? 1600 : 800)
  derive replyStart = script == 3 ? 600 : commandEnd + 500
  derive reply = chatReply(script).slice(0, max(0, floor((elapsed - replyStart) / 16)))
  action toggleThought
    thoughtOpen = not thoughtOpen
  view
    MessageFrame(id=id, align="start")
      MessageContent(id=id + "-content", align="start")
        column gap="ui.space-12"
          TraceFrame()
            if script < 2 and elapsed >= 600
              TraceDisclosure(id=id + "-thought", title=(elapsed < thoughtEnd ? "Thinking" : "Thought"), icon="check", status=(elapsed < thoughtEnd ? "running" : ""), open=(thoughtOpen or elapsed < thoughtEnd), reduced=reduced, toggle=toggleThought)
                text chatThought(script).slice(0, max(0, floor((elapsed - 600) / 16))) font-size="ui.text-sm" line-height="ui.leading-relaxed" white-space="pre-wrap" font-family=uiFontFamily(uiFont) data-rightui-font="body"
            if script < 3 and elapsed >= commandStart
              if elapsed < commandEnd
                TraceLine(title="Running " + chatCommand(script), icon="terminal", status="running", reduced=reduced)
              else
                TraceCollapsible(id=id + "-command", title="Ran " + chatCommand(script), icon="terminal", status="", initiallyOpen=false, reduced=reduced)
                  CodeBlockContent(id=id + "-output", code=chatOutput(script))
          if reply != ""
            Markdown(id=id + "-reply", content=reply)

component Demo
  props
    width: number
    reduced: bool
  inject
    uiWeights: FontWeights
    uiFont: string
    rightuiDemoTime: number
    rightuiRunDemo: action
  state turns: ChatTurn[] = []
  state draft = "Add a dark mode toggle to the settings page."
  state busyUntil = 0
  state away = false
  state selectedContext = ""
  derive busy = rightuiDemoTime < busyUntil
  action edit(value: string)
    draft = value
  action reset
    if not busy
      turns = []
      draft = "Add a dark mode toggle to the settings page."
      selectedContext = ""
      away = false
  action chooseContext(group: string, value: string)
    if value == "Add Photos & Files"
      showPicker("ai-chat-files")
    else
      selectedContext = value
  action picked(files: Picked[])
    selectedContext = files.map(file => file.name).join(", ")
  action moved(x: number, y: number, e: ScrollEvent)
    away = e.scrollHeight - e.scrollTop - e.clientHeight > 24
  action latest
    match turns.at(-1)
      case some(turn)
        if reduced
          scrollIntoView("ai-chat-thread", turn.id, block="end", behavior="instant")
        else
          scrollIntoView("ai-chat-thread", turn.id, block="end", behavior="smooth")
      case none
        away = false
  action send
    if draft.trim() != "" and not busy
      let prompt = draft.trim()
      let nextLength = turns.length + 1
      let script = prompt == "Add a dark mode toggle to the settings page." ? 0 : prompt == "Make it follow the system setting by default." ? 1 : prompt == "Run the build before I ship it." ? 2 : 3
      let duration = (script == 3 ? 600 : (script < 2 ? 600 + chatThought(script).length * 16 : 600) + 400 + (script == 2 ? 1600 : 800) + 500) + chatReply(script).length * 16 + 100
      turns = turns.concat([ChatTurn(id=turns.length, prompt=prompt, script=script, started=rightuiDemoTime)])
      busyUntil = rightuiDemoTime + duration
      rightuiRunDemo(duration)
      draft = nextLength == 1 ? "Make it follow the system setting by default." : nextLength == 2 ? "Run the build before I ship it." : ""
  action keys(k: string, e: KeyboardEvent)
    if k == "Enter" and not e.shiftKey and not e.isComposing
      preventDefault()
      send()
  view
    column width="100%" height=800 gap="ui.space-16" min-width=0 background-color="ui.background"
      input id="ai-chat-files" type="file" multiple=true change=picked display="none" font-family=uiFontFamily(uiFont) data-rightui-font="body"
      row justify-content="space-between" align-items="flex-start" gap="ui.space-16" padding="ui.space-32 ui.space-32 ui.space-16"
        column gap="ui.space-4"
          text "New Thread" font-weight=uiWeights.medium font-family=uiFontFamily(uiFont) data-rightui-font="body"
          text "Ask the agent to change your code." font-size="ui.text-sm" color="ui.muted-foreground" font-family=uiFontFamily(uiFont) data-rightui-font="body"
        ButtonContent(id="ai-chat-reset", label="Reset conversation", variant="outline", size="icon", disabled=busy, press=reset)
          MessageIcon(name="arrow.clockwise", filled=false)
      if turns.length == 0
        column flex=1 gap="ui.space-8" align-items="center" justify-content="center" padding="ui.space-32"
          view width="ui.space-40" height="ui.space-40" display="flex" align-items="center" justify-content="center" border-radius="ui.radius-md" background-color="ui.muted"
            MessageIcon(name="message", filled=false)
          text "What should we build?" font-size="ui.text-lg" font-weight=uiWeights.medium font-family=uiFontFamily(uiFont) data-rightui-font="body"
          text "The agent can read your code, run commands and make changes. Press send to start." max-width="20rem" text-align="center" font-size="ui.text-sm" line-height="ui.leading-relaxed" color="ui.muted-foreground" font-family=uiFontFamily(uiFont) data-rightui-font="body"
      else
        column flex=1 min-height=0 position="relative"
          list id="ai-chat-thread" testId="ai-chat-thread" aria-busy=busy appearance="none" virtualized=true scroll-start="end" scrollFollowEnd=true scroll=moved flex=1 min-height=0
            for turn in turns key=turn.id
              column gap="ui.space-24" padding="ui.space-0 ui.space-32 ui.space-24" min-width=0
                MessageFrame(id="ai-chat-user-" + turn.id.toString(), align="end")
                  MessageContent(id="ai-chat-user-content-" + turn.id.toString(), align="end")
                    BubbleFrame(id="ai-chat-bubble-" + turn.id.toString(), align="end", variant="muted")
                      text turn.prompt white-space="pre-wrap" animation=(reduced ? "none" : "uiReveal ui.duration-normal ui.easing both") font-family=uiFontFamily(uiFont) data-rightui-font="body"
                if rightuiDemoTime - turn.started >= 600
                  ChatResponse(id="ai-chat-assistant-" + turn.id.toString(), script=turn.script, elapsed=rightuiDemoTime - turn.started, reduced=reduced)
          if away
            row position="absolute" bottom="ui.space-8" left=0 right=0 justify-content="center"
              ButtonContent(id="ai-chat-latest", label="Latest message", variant="outline", size="sm", disabled=false, press=latest)
                svg width="ui.space-16" height="ui.space-16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="ui.icon-stroke" aria-hidden=true
                  path d="M12 5v14m-6-6 6 6 6-6"
      column padding="ui.space-0 ui.space-32 ui.space-32" gap="ui.space-8"
        InputGroupFrame(id="ai-chat-composer")
          textarea class=FieldFocus id="ai-chat-thread-draft" testId="ai-chat-thread-draft" value=draft input=edit key=keys aria-label="Message" placeholder="Ask the agent..." min-height="ui.space-56" border="0" padding="ui.space-12" background-color="transparent" color="ui.foreground" font-size="ui.text-sm" font-family=uiFontFamily(uiFont) data-rightui-font="body"
          InputGroupAddon(id="ai-chat-toolbar")
            CompactAiMenu(id="ai-chat-context", label="Add context", prefix="Context", entries=[AdvancedMenuEntry(id="files", parent="", label="Add Photos & Files", kind="item", shortcut="", disabled=false, group="effort", value="Add Photos & Files"), AdvancedMenuEntry(id="separator", parent="", label="", kind="separator", shortcut="", disabled=false, group="", value=""), AdvancedMenuEntry(id="research", parent="", label="Deep Research", kind="item", shortcut="", disabled=false, group="effort", value="Deep Research"), AdvancedMenuEntry(id="web", parent="", label="Web Search", kind="item", shortcut="", disabled=false, group="effort", value="Web Search")], value=selectedContext, reduced=reduced, radio=chooseContext)
            view flex=1
            ButtonContent(id="ai-chat-thread-send", label="Send", variant="default", size="icon-sm", disabled=(draft.trim() == "" or busy), press=send)
              MessageIcon(name="arrow.up", filled=false)
        if selectedContext != ""
          text selectedContext role="status" font-size="ui.text-xs" color="ui.muted-foreground" font-family=uiFontFamily(uiFont) data-rightui-font="body"

````
