use std::fs;
use std::io::{BufRead, BufReader, Write};
use std::os::unix::fs::PermissionsExt;
use std::os::unix::net::{UnixListener, UnixStream};
use alacritty_terminal::term::TermMode;
use gpui::{Context, Keystroke};
use serde_json::json;
use termden_core::state::control_socket;
use termden_core::{HarnessId, HarnessKind, WorkspaceId};
use crate::pty;
use crate::state::TermdenApp;
type Request = (String, async_channel::Sender<String>);
pub fn listen(cx: &mut Context<TermdenApp>) {
let path = control_socket();
if UnixStream::connect(&path).is_ok() {
eprintln!(
"termden: another instance owns {}; control disabled",
path.display()
);
return;
}
let _ = fs::remove_file(&path);
if let Some(dir) = path.parent() {
let _ = fs::create_dir_all(dir);
let _ = fs::set_permissions(dir, fs::Permissions::from_mode(0o700));
}
let listener = match UnixListener::bind(&path) {
Ok(listener) => listener,
Err(error) => {
eprintln!("termden: could not bind {}: {error}", path.display());
return;
}
};
let (tx, rx) = async_channel::unbounded::<Request>();
std::thread::spawn(move || {
for stream in listener.incoming().flatten() {
let tx = tx.clone();
std::thread::spawn(move || serve(stream, tx));
}
});
cx.spawn(async move |this, cx| {
while let Ok((line, reply)) = rx.recv().await {
let out = this
.update(cx, |this, cx| {
let out = this.command(line.as_str(), cx);
cx.notify();
out
})
.unwrap_or_else(|_| "error: app is shutting down".into());
let _ = reply.send(out).await;
}
})
.detach();
}
fn serve(stream: UnixStream, tx: async_channel::Sender<Request>) {
let mut line = String::new();
if BufReader::new(&stream).read_line(&mut line).is_err() {
return;
}
let (reply_tx, reply_rx) = async_channel::bounded(1);
if tx
.send_blocking((line.trim().to_string(), reply_tx))
.is_err()
{
return;
}
if let Ok(out) = reply_rx.recv_blocking() {
let mut stream = stream;
let _ = writeln!(stream, "{out}");
}
}
pub const HELP: &str = "\
commands (<h> is a harness id or name; <ws> a workspace id or name):
ping liveness check
whoami <h> kind, name and tag of a harness (used by the git hook)
state JSON: workspaces, harnesses, layouts, window size
activity [on|off] show or hide the activity screen
stats [on|off] JSON: per-workspace tokens, MCP servers and uptime;
`on`/`off` shows or hides the stats pane
screen [h] visible text of a terminal (default: focused)
history <h> [lines] scrollback + screen, last N lines (default 200)
send <h> <text> type text into a harness (no Enter)
key <h> <key>... press keys: enter, escape, ctrl-c, up, tab, ...
focus <h> focus a tile (layout and zoom stay user-only)
add <kind> [ws] start claude|opencode|pi|shell (default: active);
`wait` on it before sending, input during startup
can be lost
close <h> | restart <h> kill a harness | re-attach an exited one
show <json> show the user results (images, video, files) in the browser;
prints the page URL. {from,title,description,items:[{path,caption,description}]}
rename <h> <name> rename a harness
version running version, and a newer release if one is out
update [show|check] check now for a release, or install it / show its popup; the
user confirms the restart into it
title <h> [text] set what a harness is working on (empty clears)
tag <h> [text] set a harness role tag (empty clears)
pronouns <h> [text] set a harness's pronouns (empty clears)
add-workspace <dir> new workspace on a folder
activate <ws> switch workspace (also loads an unloaded one)
unload <ws> put a workspace away (not Home); tmux keeps running
rename-workspace <ws> <n> rename a workspace
mail-send <json> deliver {from,to,text} (JSON keys, from may be 0)
mail-read <h> JSON: unread messages for <h>, marked read
log <h|0> <text> post a line to the activity feed
settings [close|themes] open (or close) the settings popup; `themes` opens the theme panel
theme [id|list] set a colour theme, list them, or cycle to the next
reload offer the user a restart (sidebar banner); termden never
restarts unasked, the user confirms";
impl TermdenApp {
fn find_harness(&self, arg: Option<&str>) -> Option<HarnessId> {
let arg = arg?;
if let Ok(raw) = arg.parse() {
let id = HarnessId::new(raw);
return self.harness(id).map(|_| id);
}
let named =
|w: &termden_core::Workspace| w.harnesses.iter().find(|h| h.name == arg).map(|h| h.id);
self.workspace(self.active)
.and_then(named)
.or_else(|| self.workspaces.iter().find_map(named))
}
fn find_workspace(&self, arg: Option<&str>) -> Option<WorkspaceId> {
let arg = arg?;
self.workspaces
.iter()
.find(|w| w.id.raw().to_string() == arg || w.name == arg)
.map(|w| w.id)
}
fn command(&mut self, line: &str, cx: &mut Context<Self>) -> String {
let mut words = line.split_whitespace();
let verb = words.next().unwrap_or("help");
let arg = words.next();
let rest = || {
let after_verb = line.trim_start()[verb.len()..].trim_start();
after_verb[arg.map_or(0, str::len)..]
.trim_start()
.to_string()
};
const NO_HARNESS: &str = "error: unknown harness";
match verb {
"ping" => "pong".into(),
"state" => self.state_json().to_string(),
"stats" => match arg {
Some("on") => {
self.set_screen(HarnessId::STATS, true);
cx.notify();
"ok".into()
}
Some("off") => {
self.set_screen(HarnessId::STATS, false);
cx.notify();
"ok".into()
}
_ => self.stats_json().to_string(),
},
"activity" => {
self.set_screen(HarnessId::ACTIVITY, arg != Some("off"));
cx.notify();
"ok".into()
}
"whoami" => match self.find_harness(arg).and_then(|id| self.harness(id)) {
Some((_, h)) => format!(
"{}\t{}\t{}",
if h.kind == HarnessKind::Shell {
"shell"
} else {
"agent"
},
h.name,
h.tag
),
None => NO_HARNESS.into(),
},
"screen" => match arg.map_or(self.focused, |a| self.find_harness(Some(a))) {
Some(id) => match self.sessions.get(&id) {
Some(session) => session.screen_text(),
None => format!("error: harness {} has no live terminal", id.raw()),
},
None => NO_HARNESS.into(),
},
"history" => {
let Some(id) = self.find_harness(arg) else {
return NO_HARNESS.into();
};
let lines: u32 = words.next().and_then(|n| n.parse().ok()).unwrap_or(200);
pty::capture_history(id, lines)
}
"send" | "key" => {
let Some(id) = self.find_harness(arg) else {
return NO_HARNESS.into();
};
let Some(session) = self.sessions.get_mut(&id).filter(|s| !s.exited) else {
return format!("error: harness {} has no live terminal", id.raw());
};
if verb == "send" {
session.input(rest().into_bytes());
return "ok".into();
}
let app_cursor = session.term.lock().mode().contains(TermMode::APP_CURSOR);
for key in words {
let bytes = Keystroke::parse(key)
.ok()
.and_then(|k| pty::key_bytes(&k, app_cursor));
match bytes {
Some(bytes) => session.input(bytes),
None => return format!("error: unknown key {key}"),
}
}
"ok".into()
}
"focus" => match self.find_harness(arg) {
Some(id) => {
self.focus_harness(id);
"ok".into()
}
None => NO_HARNESS.into(),
},
"add" => {
let kind = match arg {
Some("claude") => HarnessKind::ClaudeCode,
Some("opencode") => HarnessKind::OpenCode,
Some("pi") => HarnessKind::Pi,
Some("shell") | None => HarnessKind::Shell,
Some(other) => return format!("error: unknown kind {other}"),
};
let ws = match words.next() {
Some(w) => match self.find_workspace(Some(w)) {
Some(ws) => ws,
None => return "error: unknown workspace".into(),
},
None => self.active,
};
match self.add_harness(ws, kind) {
Some(id) => {
self.sync_sessions(cx);
id.raw().to_string()
}
None => "error: unknown workspace".into(),
}
}
"close" | "restart" => match self.find_harness(arg) {
Some(id) => {
if verb == "close" {
self.close_harness(id);
} else {
self.restart_harness(id);
}
"ok".into()
}
None => NO_HARNESS.into(),
},
"rename" => {
let Some(id) = self.find_harness(arg) else {
return NO_HARNESS.into();
};
let name = rest();
if name.is_empty() {
return "error: missing name".into();
}
self.rename_harness(id, name);
"ok".into()
}
"title" => {
let Some(id) = self.find_harness(arg) else {
return NO_HARNESS.into();
};
self.title_harness(id, rest().trim().to_string());
"ok".into()
}
"tag" => {
let Some(id) = self.find_harness(arg) else {
return NO_HARNESS.into();
};
self.tag_harness(id, rest().trim().to_string());
"ok".into()
}
"pronouns" => {
let Some(id) = self.find_harness(arg) else {
return NO_HARNESS.into();
};
self.set_pronouns(id, rest());
"ok".into()
}
"add-workspace" => {
let dir = line.trim_start_matches("add-workspace").trim();
let path = std::path::absolute(dir).unwrap_or_else(|_| dir.into());
if !path.is_dir() {
return format!("error: not a directory: {dir}");
}
self.add_workspace(&path).raw().to_string()
}
"activate" => match self.find_workspace(arg) {
Some(ws) => {
self.activate_workspace(ws);
"ok".into()
}
None => "error: unknown workspace".into(),
},
"unload" => match self.find_workspace(arg) {
Some(ws) => {
self.unload_workspace(ws);
"ok".into()
}
None => "error: unknown workspace".into(),
},
"rename-workspace" => {
let Some(ws) = self.find_workspace(arg) else {
return "error: unknown workspace".into();
};
let name = rest();
if name.is_empty() {
return "error: missing name".into();
}
if let Some(workspace) = self.workspace_mut(ws) {
workspace.name = name;
}
self.save();
"ok".into()
}
"mail-send" => {
let body: serde_json::Value =
match serde_json::from_str(line.trim_start()["mail-send".len()..].trim()) {
Ok(body) => body,
Err(error) => return format!("error: bad json: {error}"),
};
let Some(to) = self.find_harness(body["to"].as_str()) else {
return NO_HARNESS.into();
};
let from = self.find_harness(body["from"].as_str());
let text = body["text"].as_str().unwrap_or("").trim().to_string();
if text.is_empty() || text.len() > 20_000 {
return "error: text must be 1..20000 bytes".into();
}
if from == Some(to) {
return "error: cannot message yourself".into();
}
self.send_mail(from, to, text);
"ok".into()
}
"mail-read" => match self.find_harness(arg) {
Some(id) => {
let mail: Vec<_> = self
.read_mail(id)
.into_iter()
.map(|m| json!({ "from": m.from, "text": m.text }))
.collect();
json!(mail).to_string()
}
None => NO_HARNESS.into(),
},
"log" => {
let text = rest();
let agent = self.find_harness(arg).filter(|&id| {
self.harness(id)
.is_some_and(|(_, h)| h.kind != HarnessKind::Shell)
});
match agent {
Some(id) => self.log_harness(id, text),
None => self.log("Termden", text, 0),
}
"ok".into()
}
"show" => {
let body: serde_json::Value =
match serde_json::from_str(line.trim_start()["show".len()..].trim()) {
Ok(body) => body,
Err(error) => return format!("error: bad json: {error}"),
};
let Some(from) = self.find_harness(body["from"].as_str()) else {
return NO_HARNESS.into();
};
let Some(url) = crate::choices::url() else {
return "error: results server is not running".into();
};
match crate::showcase::parse(&body) {
Ok((title, description, items)) => {
self.add_showcase(from, title, description, items);
format!("{url}r/")
}
Err(error) => format!("error: {error}"),
}
}
"settings" => {
self.settings_open = arg != Some("close");
if arg == Some("themes") {
self.theme_browser = Some(crate::settings::ThemeBrowser {
filter: String::new(),
});
self.theme_scroll_to
.set(crate::settings::panel_index("", &self.config.theme.0));
}
"ok".into()
}
"theme" => match arg {
None => {
self.cycle_theme();
self.config.theme.0.clone()
}
Some("list") => crate::theme::all()
.iter()
.map(|t| format!("{:<22} {}", t.id, t.name))
.collect::<Vec<_>>()
.join("\n"),
Some(id) if crate::theme::all().iter().any(|t| t.id == id) => {
self.set_theme(id);
id.into()
}
Some(id) => format!("error: unknown theme {id} (see `theme list`)"),
},
"version" => match &self.update {
Some(update) => format!(
"{} ({} available)",
crate::update::VERSION,
update.release.tag
),
None => crate::update::VERSION.into(),
},
"update" if arg == Some("check") => {
self.check_now(cx);
"checking; `termdenctl version` shows the result in a moment".into()
}
"update" => {
self.update_open = self.update.is_some();
match arg {
Some("show") => "ok".into(),
_ => self.apply_update(cx),
}
}
"reload" => {
self.request_restart("Restart requested");
"restart offered to the user (sidebar banner)".into()
}
_ => HELP.into(),
}
}
fn stats_json(&self) -> serde_json::Value {
let workspaces: Vec<_> = self
.workspaces
.iter()
.map(|workspace| {
let stats = self.stats.workspaces.get(&workspace.id);
let agents: Vec<_> = workspace
.harnesses
.iter()
.filter(|harness| harness.kind != HarnessKind::Shell)
.map(|harness| {
let agent = stats.and_then(|stats| stats.agent(harness.id));
json!({
"id": harness.id,
"name": harness.name,
"kind": harness.kind,
"started": agent.and_then(|agent| agent.started),
"age_s": agent.and_then(|agent| agent.age()),
"tracked": agent.is_some_and(|agent| agent.tracked),
"context_percent": agent.and_then(|agent| agent.context_percent),
"cache": agent.and_then(|agent| agent.cache).map(|cache| json!({
"ttl_min": cache.ttl_min,
"left_min": cache.left_min,
"context": cache.context,
})),
"mcp": agent.map(|agent| agent.mcp.clone()).unwrap_or_default(),
"tokens": agent.and_then(|agent| agent.usage).map(|usage| json!({
"input": usage.input,
"output": usage.output,
"cache_read": usage.cache_read,
"cache_write": usage.cache_write,
})),
})
})
.collect();
json!({
"id": workspace.id,
"name": workspace.name,
"age_s": stats.and_then(|stats| stats.age()),
"mcp": stats.map(|stats| stats.mcp.clone()).unwrap_or_default(),
"tokens": stats.filter(|stats| stats.known()).map(|stats| stats.usage()).map(|usage| json!({
"input": usage.input,
"output": usage.output,
"cache_read": usage.cache_read,
"cache_write": usage.cache_write,
})),
"agents": agents,
})
})
.collect();
json!({
"mode": format!("{:?}", self.mode).to_lowercase(),
"open": self.screen_on(HarnessId::STATS),
"active": self.active,
"sampled_s": self.stats.at.map(|at| at.elapsed().as_secs()),
"plans": self.stats.plans.iter().map(|plan| json!({
"name": plan.name,
"limits": plan.limits.iter().map(|limit| json!({
"label": limit.label,
"used_percent": limit.used_percent,
"resets_at": limit.resets_at,
})).collect::<Vec<_>>(),
})).collect::<Vec<_>>(),
"workspaces": workspaces,
})
}
fn state_json(&self) -> serde_json::Value {
let workspaces: Vec<_> = self
.workspaces
.iter()
.map(|w| {
let harnesses: Vec<_> = w
.harnesses
.iter()
.map(|h| {
let session = self.sessions.get(&h.id);
json!({
"id": h.id,
"name": h.name,
"kind": h.kind,
"status": h.status,
"cwd": h.cwd,
"tmux": format!("td-{}", h.id.raw()),
"live": session.is_some_and(|s| !s.exited),
"unread": h.unread,
"tag": h.tag,
"pronouns": h.pronouns,
"agent_title": h.title,
"title": session.map(|s| s.title.clone()),
"grid": session.map(|s| [s.cols, s.rows]),
})
})
.collect();
json!({
"id": w.id,
"name": w.name,
"path": w.path,
"harnesses": harnesses,
"layout": self.layouts.get(&w.id),
})
})
.collect();
json!({
"pid": std::process::id(),
"uptime_s": self.started.elapsed().as_secs_f32(),
"mode": format!("{:?}", self.mode).to_lowercase(),
"window": {
"width": self.viewport.0, "height": self.viewport.1,
"title_bar": self.config.title_bar,
"server_decorations": self.server_decorations,
"own_chrome": self.own_chrome.is_some(),
"tiled": self.tiled,
"maximized": self.own_chrome == Some(true),
"session": std::env::var("XDG_SESSION_TYPE").unwrap_or_default(),
"desktop": std::env::var("XDG_CURRENT_DESKTOP").unwrap_or_default(),
},
"theme": self.config.theme,
"active": self.active,
"focused": self.focused,
"zoomed": self.zoomed,
"tmux_socket": pty::tmux_socket(),
"workspaces": workspaces,
})
}
}