Building the Chat App for a Personal Agent

5 min read

The problem

An agent's work does not fit in a text box. A single turn can include a tool call, a screenshot, a card that needs a tap, a background helper that finishes two minutes later, and a scheduled message at 9 AM. A plain request and response chat cannot show any of that, and a user who cannot see what the agent is doing will not trust it.

The chat app needs to:

  1. Stream events as they happen, not one reply at the end.
  2. Render different kinds of events as different cards.
  3. Send taps back: approve, deny, pick an option, react.

Terms are in the glossary.

How this Muse instance's surfaces work

From the agent's side, there are more surfaces than a chat log:

  • The main chat and side chats. Side chats are separate conversations with their own title and transcript, usually started by the user when a topic deserves its own thread.
  • Option buttons. For a bounded choice, I can offer short replies the user taps. Tapping sends that exact text as the user's next message, so the loop needs nothing special to handle it.
  • Widgets. Small interactive HTML cards inside the chat. They must work in light and dark themes, so they use the app's theme variables instead of hard-coded colors. Their state lives in a bridge the app provides, not in browser storage, because the widget is replayed from history later and needs its state back. They are size-limited, since they are stored with the chat.
  • Approval and sign-in cards, from Part 8 and Part 5.
  • Reactions. A quick thumbs-up on a reply is a signal, not a message.
  • Other tabs. A Goals tab for durable outcomes and tracked plans, a Feed of short posts written in the background, documents, and Spaces, which are small apps the user describes and the agent builds.

The design lesson is that the agent does not draw any of this. It emits typed events or calls a tool that creates a card, and the app decides how to render it.

Hand-drawn event stream: the agent emits events into one SSE stream; the UI picks a renderer per event type: message bubble, tool chip, approval card, option buttons, browser card, handoff or job card

flowchart LR
  A["Agent loop"] -- "emit(type, data)" --> E["Event list per chat"]
  E -- "SSE" --> UI["Browser"]
  UI --> R1["message: bubble"]
  UI --> R2["tool_call: chip"]
  UI --> R3["approval: card with buttons"]
  UI --> R4["options: tap buttons"]
  UI --> R5["browser: screenshot card"]
  UI --> R6["subagent / job_message: status cards"]
  R3 -- "POST /api/approve" --> A
  R4 -- "POST /api/send" --> A

Step 1: events, not replies

Every interesting thing in the loop calls emit. Each event gets a sequence number, so a client can reconnect and ask for everything after the last one it saw.

python
# tinymuse/agent.py
    def emit(self, kind, **data):
        with self.cond:
            self.events.append({"seq": len(self.events), "type": kind, "t": time.time(), **data})
            self.cond.notify_all()

Step 2: stream them with server-sent events

Server-sent events are a one-way stream over plain HTTP with the text/event-stream type. The browser's EventSource reconnects by itself. For a chat where the server talks far more than the client, that is simpler than WebSockets.

python
# tinymuse/server.py
@api.get("/api/stream/{cid}")
async def stream(cid: str, after: int = -1):
    chat = app.chat(cid)

    async def gen():
        seen = after
        while True:
            new = [e for e in chat.events if e["seq"] > seen]
            for e in new:
                seen = e["seq"]
                yield f"data: {json.dumps(e)}\n\n"
            await asyncio.sleep(0.25)
    return StreamingResponse(gen(), media_type="text/event-stream")


@api.post("/api/send")
async def send(req: Request):
    body = await req.json()
    chat = app.chat(body.get("chat", "main"))
    threading.Thread(target=app.run_turn, args=(chat, body["text"]), daemon=True).start()
    return {"ok": True}


@api.post("/api/approve")
async def approve(req: Request):
    b = await req.json()
    return {"ok": app.approvals.decide(b["id"], b["decision"])}

/api/send returns at once and runs the turn in a thread. The answer arrives on the stream, the same way a sub-agent handoff or a scheduled job does. That is the point: the UI has one path for everything.

sequenceDiagram
  participant B as Browser
  participant S as FastAPI
  participant L as Loop thread
  B->>S: GET /api/stream/main (EventSource)
  B->>S: POST /api/send {text}
  S->>L: start run_turn
  S-->>B: {"ok": true}
  L-->>S: emit tool_call
  S-->>B: data: {"type":"tool_call",...}
  L-->>S: emit approval
  S-->>B: data: {"type":"approval",...}
  B->>S: POST /api/approve {id, approve}
  S->>L: decide(id)
  L-->>S: emit approval_done, message
  S-->>B: data: ... (stamp card, show reply)

Step 3: one renderer per event type

The whole client is about 60 lines of HTML and JavaScript. This is the core:

javascript
// tinymuse/ui.html
function render(e){
 if(e.type==='message'){
  const cls=e.role==='handoff'?'msg handoff':'msg '+e.role;
  const d=el(cls,(e.role==='handoff'?'<span class="tag">handoff from a sub-agent</span>':'')+esc(e.text));
  if(e.role==='assistant')d.ondblclick=()=>{d.insertAdjacentHTML('beforeend','<span class="react">&#128077;</span>');post('/api/react',{chat,seq:e.seq,emoji:'thumbs_up'})};
 }
 if(e.type==='tool_call')el('chip','tool: '+esc(e.name)+'('+esc(JSON.stringify(e.args)).slice(0,90)+')');
 if(e.type==='approval'){const c=el('card approval',`<b>Approve ${esc(e.name)}?</b><pre>${esc(JSON.stringify(e.args,null,1))}</pre>`);
  const a=document.createElement('button');a.className='go';a.textContent='Approve';const n=document.createElement('button');n.textContent='Deny';
  a.onclick=()=>post('/api/approve',{id:e.id,decision:'approve'});n.onclick=()=>post('/api/approve',{id:e.id,decision:'deny'});c.append(a,n);c.id='ap-'+e.id}
 if(e.type==='approval_done'){const c=document.getElementById('ap-'+e.id);if(c){c.querySelectorAll('button').forEach(b=>b.remove());c.insertAdjacentHTML('beforeend','<span class="pill">'+e.decision+'</span>')}}
 if(e.type==='options'){const d=el('opts','');e.options.forEach(o=>{const b=document.createElement('button');b.textContent=o;b.onclick=()=>send(o);d.appendChild(b)})}
 if(e.type==='browser')el('card',`<b>Browser</b> ${esc(e.title)}<br><span class="tag">${esc(e.url)}</span><img class="shot" src="/shots/${e.shot}">`);
 if(e.type==='takeover')el('card',`<b>Your turn</b><br>${esc(e.text)}<br><br><button class="go">Open live browser</button>`);
 if(e.type==='subagent')el('chip',`sub-agent ${e.id}: <span class="pill">${e.status}</span>`);
 if(e.type==='job_message')el('msg job_message','<span class="tag">scheduled job '+esc(e.job)+'</span>'+esc(e.text));
 refresh();
}

Every piece of model or tool text goes through esc before it touches the page. Agent output is untrusted too. A page the agent read could contain HTML, and you do not want it running in your chat.

Step 4: option buttons are just messages

The tool that shows options emits an event and returns:

python
@tool("Show the user tappable reply options.", question="the question", options="options separated by |")
def ask_options(question, options, ctx):
    opts = [o.strip() for o in options.split("|") if o.strip()][:4]
    ctx["chat"].emit("options", question=question, options=opts)
    return "options shown; wait for the user's tap"

A tap calls send(o), so the chosen text arrives as a normal user message. From the real model run, asked "Ask me with tappable options whether to text or email Lena next time":

Screenshot: ask_options tool chip and two tap buttons, "text" and "email", under the request

The screenshots in this series

All nine UI screenshots were taken by a Playwright script that drives this app like a user: it types each message, waits for the expected card, clicks Approve where needed, and saves a 1360 by 860 screenshot at 1.5x scale. The model behind them was Llama 3.3 70B on Cloudflare Workers AI.

What tinymuse leaves out

  • Reconnect replay. The stream supports after=<seq>, but the page does not pass it yet, so a reload replays every event of the session.
  • Token streaming. Messages arrive whole. Streaming the model's tokens into the bubble is the next step for a snappier feel.
  • Mobile layout. The sidebar should collapse on a phone.
  • Real widgets. A sandboxed iframe with a state bridge is the safe way to let the agent ship interactive cards.

What to take from this

  • Make the agent emit typed events and let the app render them.
  • One stream for everything: replies, handoffs, jobs.
  • Escape all agent text before rendering it.

Next, Part 10: keeping all of this running.

Scope: this describes how this Muse instance works, observed in November 2026. Meta's actual implementation may differ and change. The code is our own open reference build, tinymuse, not Meta's code.

Sources