Skip to content

Instantly share code, notes, and snippets.

@dui
Created May 18, 2026 21:53
Show Gist options
  • Select an option

  • Save dui/80ba3bb2fc4dcaaaf6f16ad924a8686b to your computer and use it in GitHub Desktop.

Select an option

Save dui/80ba3bb2fc4dcaaaf6f16ad924a8686b to your computer and use it in GitHub Desktop.
Run codex's TUI and app-server as separate processes so other TUIs/tools can attach to the same session
# Spawn codex's app-server on a free port and attach a TUI to it via --remote.
# By default, codex's TUI bundles its own app-server. Splitting them lets other
# TUIs or tools plug into the same running session.
#
# Usage:
# cr # random free port, server dies with TUI
# cr --keep # leave the server running after TUI exits
# cr 8765 # use port 8765 (start server if not already up)
# cr ws://host:8765 # attach TUI to an already-running app-server
codex-remote() {
local keep=0 port url log_file server_pid started_server=0 codex_status
if [[ "$1" == "--keep" ]]; then
keep=1
shift
fi
if [[ "$1" == ws://* || "$1" == wss://* ]]; then
url="$1"
port="${url##*:}"
port="${port%%/*}"
elif [[ -n "$1" ]]; then
port="$1"
url="ws://127.0.0.1:${port}"
else
for _ in {1..100}; do
port=$((20000 + RANDOM % 40000))
lsof -nP -iTCP:"$port" -sTCP:LISTEN >/dev/null 2>&1 || break
done
url="ws://127.0.0.1:${port}"
fi
log_file="/tmp/codex-app-server-${port}.log"
if ! lsof -nP -iTCP:"$port" -sTCP:LISTEN >/dev/null 2>&1; then
codex --dangerously-bypass-approvals-and-sandbox app-server --listen "$url" >"$log_file" 2>&1 &
server_pid=$!
started_server=1
for _ in {1..20}; do
lsof -nP -iTCP:"$port" -sTCP:LISTEN >/dev/null 2>&1 && break
sleep 0.1
done
fi
if (( keep && started_server )); then
print -u2 "codex app-server listening at $url (pid $server_pid, log $log_file)"
fi
if (( started_server && ! keep )); then
{
codex --dangerously-bypass-approvals-and-sandbox --remote "$url"
codex_status=$?
} always {
kill "$server_pid" >/dev/null 2>&1
wait "$server_pid" 2>/dev/null
}
return "$codex_status"
fi
codex --dangerously-bypass-approvals-and-sandbox --remote "$url"
}
alias cr=codex-remote
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment