Back to Insights
AI & Machine Learning•Building a TUI Mission Control for Your AI Coding Agents: Manage Claude Code, Codex, and Gemini CLI from Your Phone•tutorial•November 28, 2026•18 min read

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

Build a Go-based mission control that manages Claude Code, Codex, and Gemini CLI sessions from a local TUI and your phone via a mobile web bridge.

T
Tamiz UddinFull-Stack Engineer

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.

Table of Contents

Architecture Overview

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

  1. PTY Session Manager – Each AI CLI (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.
  2. TUI Dashboard – A 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.
  3. Web Bridge – An embedded HTTP server exposes a WebSocket endpoint. Every byte written by an agent is fanned out to connected phone browsers as JSON messages. The mobile client is a single responsive HTML file served from the same binary.

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.

Prerequisites

  • Go 1.21 or newer
  • A Linux, macOS, or WSL2 environment where the AI CLIs are already installed and authenticated
  • A phone on the same LAN as your development machine
  • git for version control

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

1. Scaffold the Go Module

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.

bash
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:

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

2. Build the PTY Session Engine

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.

Ring buffer

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

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)
}

Session

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.

go
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
}

Manager

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

go
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.

3. Create the TUI Dashboard

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

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.

4. Add the WebSocket Bridge

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

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.

5. Ship the Mobile Client

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.

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.

6. Wire Everything Together

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

json
[
  { "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:

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:

bash
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.

Production Hardening

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

  • Run inside tmux. If the mission control binary crashes or you close your laptop, the PTYs die with it. Start the tool inside a tmux session so the binary—and therefore the agents—survive disconnects.

    bash
    tmux new -s agents
    ./mission-control
    # Detach with Ctrl-b d, reattach with tmux attach -t agents
    
  • Terminate TLS. The token travels as a query parameter, which is visible in logs. Put Caddy or Nginx in front to terminate TLS and strip the query param before forwarding.

    caddy
    agents.example.com {
      reverse_proxy localhost:8080
    }
    
  • Bind carefully. 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:

    bash
    ssh -L 8080:localhost:8080 user@devbox
    
  • Rate-limit WebSocket writes. For extremely verbose agents, wrap the broadcast in a channel and coalesce writes so a slow phone connection cannot apply backpressure to the PTY read loop.

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.

Frequently Asked Questions

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.

code