cd /news/ai-agents/building-a-tui-mission-control-for-a… · home › topics › ai-agents › article
[ARTICLE · art-177843] src=dev.to ↗ pub= topic=ai-agents verified=true sentiment=↑ positive

Building a TUI Mission Control for AI Coding Agents: Claude Code, Codex, and Gemini CLI from Your Phone

A developer published a tutorial for building a Go-based "mission control" dashboard that runs Claude Code, OpenAI Codex, and Gemini CLI side by side. The single binary attaches each coding agent to a pseudo-terminal, streams output through bounded ring buffers into a tview TUI, and exposes a WebSocket bridge so sessions can be monitored and commanded from a phone. The design keeps output flowing one way (PTY to ring buffer to TUI and WebSocket) and input the other, so the dashboard can restart without losing agent state.

recommendation

Attach each coding agent to a PTY and stream its output through a fixed-size ring buffer to both your TUI and a WebSocket bridge, keeping input flowing back to the PTY.

more in playbook: Designing agent systems
by read12 min views2 publishedNov 28, 2026

Originally published on tamiz.pro.

Running Claude Code, OpenAI Codex, and Gemini CLI side by side is powerful—until you lose track of which agent is doing what. Terminal tabs pile up, context switches multiply, and the moment you step away from your laptop, you're blind. This tutorial builds a mission control in Go: a local TUI dashboard for your desk and a mobile web bridge that lets you monitor, command, and triage every AI coding session from your phone.

The system is a single Go binary with three cooperating layers:

claude, codex, gemini) runs inside a pseudo-terminal (PTY) rather than a plain pipe. A PTY preserves interactive prompts, ANSI colors, and raw-mode keyboard input, which is essential because these agents expect a real terminal.tview application renders a live list of sessions, a streaming output pane, and a command input field. It reads from in-memory ring buffers so you can scroll back through recent output without re-reading the PTY. Data flows in one direction for output (PTY → ring buffer → TUI + WebSocket) and in the reverse direction for input (TUI input field or phone input → PTY write). This keeps the mission control stateless enough to restart without losing agent state, as long as the binary itself stays alive.

git for version control You do not need Docker. The PTY package we use works natively on Unix-like systems.

Create a new directory and initialize the module. We will use four dependencies: creack/pty for pseudo-terminals, rivo/tview for the TUI, gorilla/websocket for the mobile bridge, and standard library packages for HTTP and JSON.

mkdir agent-mission-control && cd agent-mission-control
go mod init agent-mission-control
go get github.com/creack/pty@latest
go get github.com/rivo/tview@latest
go get github.com/gdamore/tcell/v2@latest
go get github.com/gorilla/websocket@latest

Create the project layout:

agent-mission-control/
├── main.go
├── manager.go
├── session.go
├── ringbuffer.go
├── tui.go
├── web.go
├── agents.json
└── web/
    └── index.html

The heart of the system is the session engine. A Session wraps an exec.Cmd attached to a PTY, captures output into a bounded ring buffer, and exposes a thread-safe Write method for sending keystrokes.

We need a fixed-size buffer so a chatty agent cannot exhaust memory. Create ringbuffer.go:

package main

import "sync"

// RingBuffer keeps the most recent writes up to a maximum size.
type RingBuffer struct {
    mu   sync.Mutex
    data []byte
    size int
}

func NewRingBuffer(size int) *RingBuffer {
    return &RingBuffer{
        data: make([]byte, 0, size),
        size: size,
    }
}

func (r *RingBuffer) Write(p []byte) (int, error) {
    r.mu.Lock()
    defer r.mu.Unlock()
    r.data = append(r.data, p...)
    if len(r.data) > r.size {
        r.data = r.data[len(r.data)-r.size:]
    }
    return len(p), nil
}

func (r *RingBuffer) String() string {
    r.mu.Lock()
    defer r.mu.Unlock()
    return string(r.data)
}

Create session.go. The OnOutput callback lets the manager fan out bytes to both the TUI and the web bridge without the session knowing about either.

package main

import (
    "fmt"
    "os"
    "os/exec"
    "strings"
    "sync"

    "github.com/creack/pty"
)

type Session struct {
    ID       string
    Name     string
    Command  string
    PTY      *os.File
    Cmd      *exec.Cmd
    Output   *RingBuffer
    OnOutput func(id string, data []byte)

    mu     sync.Mutex
    active bool
}

func NewSession(id, name, command string) *Session {
    return &Session{
        ID:      id,
        Name:    name,
        Command: command,
        Output:  NewRingBuffer(128 * 1024),
    }
}

func (s *Session) Start() error {
    parts := strings.Fields(s.Command)
    if len(parts) == 0 {
        return fmt.Errorf("empty command")
    }

    cmd := exec.Command(parts[0], parts[1:]...)
    cmd.Env = append(os.Environ(), "TERM=xterm-256color")

    ptmx, err := pty.Start(cmd)
    if err != nil {
        return err
    }

    s.PTY = ptmx
    s.Cmd = cmd
    s.active = true

    go s.readLoop()
    go func() {
        _ = cmd.Wait()
        s.mu.Lock()
        s.active = false
        s.mu.Unlock()
    }()

    return nil
}

func (s *Session) readLoop() {
    buf := make([]byte, 4096)
    for {
        n, err := s.PTY.Read(buf)
        if n > 0 {
            chunk := make([]byte, n)
            copy(chunk, buf[:n])
            s.Output.Write(chunk)
            if s.OnOutput != nil {
                s.OnOutput(s.ID, chunk)
            }
        }
        if err != nil {
            break
        }
    }
}

func (s *Session) Write(data string) error {
    _, err := s.PTY.Write([]byte(data))
    return err
}

func (s *Session) IsActive() bool {
    s.mu.Lock()
    defer s.mu.Unlock()
    return s.active
}

func (s *Session) Stop() error {
    if s.Cmd != nil && s.Cmd.Process != nil {
        return s.Cmd.Process.Kill()
    }
    return nil
}

Create manager.go. The manager owns sessions, preserves insertion order for the UI, and notifies registered listeners on every output chunk.

package main

import "sync"

type OutputFunc func(sessionID string, data []byte)

type Manager struct {
    mu        sync.RWMutex
    sessions  map[string]*Session
    order     []string
    listeners []OutputFunc
}

func NewManager() *Manager {
    return &Manager{
        sessions: make(map[string]*Session),
    }
}

func (m *Manager) AddListener(fn OutputFunc) {
    m.mu.Lock()
    defer m.mu.Unlock()
    m.listeners = append(m.listeners, fn)
}

func (m *Manager) notify(id string, data []byte) {
    m.mu.RLock()
    defer m.mu.RUnlock()
    for _, fn := range m.listeners {
        fn(id, data)
    }
}

func (m *Manager) Add(s *Session) error {
    m.mu.Lock()
    if _, exists := m.sessions[s.ID]; exists {
        m.mu.Unlock()
        return fmt.Errorf("session %s already exists", s.ID)
    }
    m.sessions[s.ID] = s
    m.order = append(m.order, s.ID)
    m.mu.Unlock()

    s.OnOutput = m.notify
    return s.Start()
}

func (m *Manager) Get(id string) (*Session, bool) {
    m.mu.RLock()
    defer m.mu.RUnlock()
    s, ok := m.sessions[id]
    return s, ok
}

func (m *Manager) List() []*Session {
    m.mu.RLock()
    defer m.mu.RUnlock()
    out := make([]*Session, 0, len(m.order))
    for _, id := range m.order {
        if s, ok := m.sessions[id]; ok {
            out = append(out, s)
        }
    }
    return out
}

Design note: The OnOutput hook is synchronous. If a web client stalls, it could block the PTY read loop in a naive implementation. In this tutorial the WebSocket broadcast is fast and non-blocking because websocket.Conn.WriteMessage buffers internally, but for very high-throughput agents you may want to decouple with a channel and a dedicated writer goroutine.

The local dashboard uses tview to lay out a sidebar of agents, a scrolling output window, and a command input. Create tui.go.

package main

import (
    "fmt"
    "time"

    "github.com/gdamore/tcell/v2"
    "github.com/rivo/tview"
)

type TUI struct {
    app       *tview.Application
    manager   *Manager
    list      *tview.List
    output    *tview.TextView
    input     *tview.InputField
    currentID string
}

func NewTUI(m *Manager) *TUI {
    t := &TUI{
        app:     tview.NewApplication(),
        manager: m,
        list:    tview.NewList().ShowSecondaryText(false),
        output:  tview.NewTextView().SetDynamicColors(true).SetScrollable(true).SetWrap(true),
        input:   tview.NewInputField().SetLabel("Send> ").SetFieldWidth(0),
    }

    t.list.SetBorder(true).SetTitle("Agents")
    t.output.SetBorder(true).SetTitle("Output")
    t.input.SetBorder(true).SetTitle("Command")

    t.list.SetChangedFunc(func(index int, mainText string, secondaryText string, shortcut rune) {
        sessions := t.manager.List()
        if index >= 0 && index < len(sessions) {
            t.currentID = sessions[index].ID
            t.refreshOutput()
        }
    })

    t.input.SetDoneFunc(func(key tcell.Key) {
        if key == tcell.KeyEnter && t.currentID != "" {
            if s, ok := t.manager.Get(t.currentID); ok {
                _ = s.Write(t.input.GetText() + "\n")
            }
            t.input.SetText("")
        }
    })

    rightFlex := tview.NewFlex().SetDirection(tview.FlexRow).
        AddItem(t.output, 0, 1, false).
        AddItem(t.input, 3, 0, true)

    mainFlex := tview.NewFlex().
        AddItem(t.list, 30, 0, true).
        AddItem(rightFlex, 0, 2, false)

    mainFlex.SetBorder(true).SetTitle("Agent Mission Control")

    t.app.SetRoot(mainFlex, true).EnableMouse(true)
    go t.autoRefresh()
    return t
}

func (t *TUI) refreshOutput() {
    if s, ok := t.manager.Get(t.currentID); ok {
        t.output.SetText(s.Output.String())
        t.output.ScrollToEnd()
    }
}

func (t *TUI) autoRefresh() {
    ticker := time.NewTicker(500 * time.Millisecond)
    defer ticker.Stop()
    for range ticker.C {
        t.app.QueueUpdateDraw(func() {
            t.list.Clear()
            for _, s := range t.manager.List() {
                status := "[green]●[white]"
                if !s.IsActive() {
                    status = "[red]○[white]"
                }
                t.list.AddItem(fmt.Sprintf("%s %s", status, s.Name), "", 0, nil)
            }
            if t.currentID != "" {
                t.refreshOutput()
            }
        })
    }
}

func (t *TUI) Run() error {
    return t.app.Run()
}

Key bindings are inherited from tview: Tab cycles focus, arrow keys navigate the list, and Ctrl+C exits the entire application. Because the TUI runs in the main goroutine, the web server must run in a background goroutine.

The web bridge is a thin HTTP server that upgrades connections to WebSocket and relays JSON messages. Create web.go.

package main

import (
    "embed"
    "encoding/json"
    "log"
    "net/http"
    "os"
    "sync"

    "github.com/gorilla/websocket"
)

//go:embed web/*
var webFS embed.FS

type WSMessage struct {
    Type     string              `json:"type"`
    Session  string              `json:"session,omitempty"`
    Data     string              `json:"data,omitempty"`
    Sessions []map[string]string `json:"sessions,omitempty"`
}

type WebServer struct {
    manager  *Manager
    upgrader websocket.Upgrader
    clients  sync.Map
}

func NewWebServer(m *Manager) *WebServer {
    ws := &WebServer{
        manager: m,
        upgrader: websocket.Upgrader{
            CheckOrigin: func(r *http.Request) bool { return true },
        },
    }

    m.AddListener(func(id string, data []byte) {
        ws.broadcast(WSMessage{Type: "output", Session: id, Data: string(data)})
    })

    return ws
}

func (w *WebServer) broadcast(msg WSMessage) {
    payload, _ := json.Marshal(msg)
    w.clients.Range(func(key, value any) bool {
        if conn, ok := key.(*websocket.Conn); ok {
            _ = conn.WriteMessage(websocket.TextMessage, payload)
        }
        return true
    })
}

func (w *WebServer) auth(next http.HandlerFunc) http.HandlerFunc {
    return func(rw http.ResponseWriter, r *http.Request) {
        token := r.URL.Query().Get("token")
        if token == "" || token != os.Getenv("MC_TOKEN") {
            http.Error(rw, "unauthorized", http.StatusUnauthorized)
            return
        }
        next(rw, r)
    }
}

func (w *WebServer) HandleConnections(rw http.ResponseWriter, r *http.Request) {
    conn, err := w.upgrader.Upgrade(rw, r, nil)
    if err != nil {
        log.Printf("ws upgrade: %v", err)
        return
    }
    defer conn.Close()
    w.clients.Store(conn, true)
    defer w.clients.Delete(conn)

    // Send the session roster immediately.
    var roster []map[string]string
    for _, s := range w.manager.List() {
        roster = append(roster, map[string]string{"id": s.ID, "name": s.Name})
    }
    _ = conn.WriteJSON(WSMessage{Type: "list", Sessions: roster})

    for {
        var msg WSMessage
        if err := conn.ReadJSON(&msg); err != nil {
            break
        }
        if msg.Type == "command" && msg.Session != "" {
            if s, ok := w.manager.Get(msg.Session); ok {
                _ = s.Write(msg.Data + "\n")
            }
        }
    }
}

func (w *WebServer) Start(addr string) error {
    mux := http.NewServeMux()
    mux.HandleFunc("/ws", w.auth(w.HandleConnections))
    mux.Handle("/", http.FileServer(http.FS(webFS)))
    log.Printf("web bridge listening on %s", addr)
    return http.ListenAndServe(addr, mux)
}

The auth middleware reads a bearer token from the query string. This is intentionally simple for LAN use; we will harden it later.

The phone client is a single HTML file embedded into the binary. It connects to the WebSocket, renders a horizontal session picker, streams output, and provides a command bar. Create web/index.html.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<title>Agent Control</title>
<style>
  * { box-sizing: border-box; }
  body {
    font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
    background: #0d1117; color: #c9d1d9;
    margin: 0; padding: 0;
    display: flex; flex-direction: column;
    height: 100dvh; overflow: hidden;
  }
  #sessions {
    display: flex; overflow-x: auto; background: #161b22;
    border-bottom: 1px solid #30363d; -webkit-overflow-scrolling: touch;
  }
  .session {
    padding: 12px 16px; white-space: nowrap; border-right: 1px solid #30363d;
    color: #8b949e; font-size: 14px;
  }
  .session.active { background: #1f6feb; color: #fff; }
  #output {
    flex: 1; overflow-y: auto; padding: 12px;
    white-space: pre-wrap; word-break: break-word; font-size: 13px; line-height: 1.4;
  }
  #cmd { display: flex; border-top: 1px solid #30363d; background: #161b22; }
  #cmd input {
    flex: 1; padding: 14px; border: none; background: transparent;
    color: #c9d1d9; font-family: inherit; font-size: 14px; outline: none;
  }
  #cmd button {
    padding: 0 20px; border: none; background: #238636; color: #fff; font-weight: 600;
  }
</style>
</head>
<body>
<div id="sessions"></div>
<div id="output"></div>
<div id="cmd">
  <input id="input" placeholder="Type a command…" autocomplete="off" autocorrect="off" spellcheck="false">
  <button id="send">Send</button>
</div>
<script>
  const token = new URLSearchParams(location.search).get('token') || '';
  const proto = location.protocol === 'https:' ? 'wss:' : 'ws:';
  const ws = new WebSocket(`${proto}//${location.host}/ws?token=${encodeURIComponent(token)}`);

  const sessionsEl = document.getElementById('sessions');
  const outputEl = document.getElementById('output');
  const inputEl = document.getElementById('input');
  let current = null;

  ws.onmessage = (e) => {
    const msg = JSON.parse(e.data);
    if (msg.type === 'list') {
      sessionsEl.innerHTML = '';
      msg.sessions.forEach(s => {
        const div = document.createElement('div');
        div.className = 'session';
        div.textContent = s.name;
        div.onclick = () => {
          current = s.id;
          document.querySelectorAll('.session').forEach(el => el.classList.remove('active'));
          div.classList.add('active');
          outputEl.textContent = '';
        };
        sessionsEl.appendChild(div);
      });
      if (msg.sessions.length && !current) {
        current = msg.sessions[0].id;
        sessionsEl.firstChild.classList.add('active');
      }
    } else if (msg.type === 'output' && msg.session === current) {
      outputEl.textContent += msg.data;
      outputEl.scrollTop = outputEl.scrollHeight;
    }
  };

  function send() {
    if (!current || !inputEl.value) return;
    ws.send(JSON.stringify({ type: 'command', session: current, data: inputEl.value }));
    inputEl.value = '';
  }

  document.getElementById('send').onclick = send;
  inputEl.addEventListener('keydown', (e) => { if (e.key === 'Enter') send(); });
</script>
</body>
</html>

Mobile UX tip: 100dvh accounts for dynamic browser toolbars on iOS and Android, preventing the input bar from being hidden behind navigation chrome.

Create agents.json so you can change the roster without recompiling.

[
  { "id": "claude", "name": "Claude Code", "command": "claude" },
  { "id": "codex",  "name": "OpenAI Codex", "command": "codex" },
  { "id": "gemini", "name": "Gemini CLI",   "command": "gemini" }
]

Now the entry point, main.go:

package main

import (
    "encoding/json"
    "log"
    "os"
)

type AgentConfig struct {
    ID      string `json:"id"`
    Name    string `json:"name"`
    Command string `json:"command"`
}

func loadAgents(path string) ([]AgentConfig, error) {
    data, err := os.ReadFile(path)
    if err != nil {
        return nil, err
    }
    var agents []AgentConfig
    if err := json.Unmarshal(data, &agents); err != nil {
        return nil, err
    }
    return agents, nil
}

func main() {
    if os.Getenv("MC_TOKEN") == "" {
        log.Fatal("MC_TOKEN environment variable is required")
    }

    agents, err := loadAgents("agents.json")
    if err != nil {
        log.Fatalf("load agents: %v", err)
    }

    m := NewManager()
    for _, a := range agents {
        s := NewSession(a.ID, a.Name, a.Command)
        if err := m.Add(s); err != nil {
            log.Printf("start %s: %v", a.Name, err)
        }
    }

    web := NewWebServer(m)
    go func() {
        if err := web.Start("0.0.0.0:8080"); err != nil {
            log.Fatalf("web server: %v", err)
        }
    }()

    tui := NewTUI(m)
    if err := tui.Run(); err != nil {
        log.Fatal(err)
    }
}

Build and run:

go build -o mission-control .
export MC_TOKEN="$(openssl rand -hex 16)"
./mission-control

On your phone, open http://<your-lan-ip>:8080/?token=$MC_TOKEN. The session picker appears at the top, output streams below, and the command bar sends keystrokes to the selected agent.

A LAN-only dashboard is useful, but a few changes make it production-safe:

tmux session so the binary—and therefore the agents—survive disconnects.

  tmux new -s agents
  ./mission-control
agents.example.com {
    reverse_proxy localhost:8080
  }

0.0.0.0:8080 exposes the tool to every interface. On a shared network, bind to a specific interface or use an SSH tunnel:

  ssh -L 8080:localhost:8080 user@devbox

If you want deeper operational patterns for long-running developer tools, the team at Tamiz publishes practical write-ups on terminal-first infrastructure. Their Insights archive covers PTY internals and remote development workflows in more detail.

Can I add other CLI agents beyond Claude Code, Codex, and Gemini CLI?

Yes. The session engine is command-agnostic. Add a new entry to agents.json with the shell command that launches your tool. As long as the process reads from stdin and writes ANSI-compatible output to stdout, it will work inside the PTY.

Why use a PTY instead of exec.Command with pipes?

Pipes byte-stream stdout but do not emulate terminal behavior. Many AI CLIs detect TTY-ness and switch to interactive mode, render spinners, or prompt for confirmation. A PTY provides the terminal semantics these tools expect.

How do I keep agent processes alive if the mission control restarts?

The current design couples agent lifetime to the mission control process. For true persistence, run each agent inside its own tmux window and have the mission control attach read-only, or refactor the session engine to use daemon-style process supervisors. For most single-user workflows, keeping the mission control itself inside tmux is sufficient.

── more in #ai-agents 4 stories · sorted by recency
── more on @claude code 3 stories trending now
sponsored brought to you by zahid.host 4,200+ EU-deployed projects
reading about agents? ship yours in a single git push.

Run your AI side-project on zahid.host

EU-based hosting, git-push deploys, automatic HTTPS, no cold starts. Free tier with a custom domain — perfect for shipping the agent you just read about.

$git push zahid main
→ Live at https://your-agent.zahid.host ✓
Get free account → Pricing
from €0/mo · no card required
LIVE [news/building-a-tui-missi…] indexed:0 read:12min 2026-11-28 · —