termden 0.8.2

Workspaces and tiled terminals for coding agents (Claude Code, opencode, pi)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
//! Control socket of the running app: one line in, one reply out.
//! `termdenctl` is the client; agents use it to inspect and drive termden
//! while developing it from inside itself.
//!
//! Access control is the 0700 runtime directory around the socket.
//! shortcut: no SO_PEERCRED check yet; add it when the daemon takes over
//! the socket (roadmap step 3).

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 {
    /// A harness by id, else by name (the active workspace wins ties).
    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();
        // Everything after the verb and its first argument, spacing intact.
        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()
            }
            // `shell|agent <tab> name <tab> tag`, for the git commit hook.
            "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) => {
                        // Start it now so `send` right after `add` works.
                        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" => {
                // Show the popup too, so a CLI update is visible in the window.
                self.update_open = self.update.is_some();
                match arg {
                    Some("show") => "ok".into(),
                    _ => self.apply_update(cx),
                }
            }
            "reload" => {
                // Agents may not restart termden under the user; ask instead.
                self.request_restart("Restart requested");
                "restart offered to the user (sidebar banner)".into()
            }
            _ => HELP.into(),
        }
    }

    /// Per-workspace usage as JSON: what the stats pane draws, for scripts.
    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 diagnostics: what was asked for, whether the
                // compositor can draw it, and whether termden draws its own.
                "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,
        })
    }
}