Skip to main content

termden_core/
model.rs

1use serde::{Deserialize, Serialize};
2
3macro_rules! id_type {
4    ($name:ident) => {
5        #[derive(
6            Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize,
7        )]
8        #[serde(transparent)]
9        pub struct $name(pub u32);
10
11        impl $name {
12            pub const fn new(value: u32) -> Self {
13                Self(value)
14            }
15
16            pub const fn raw(self) -> u32 {
17                self.0
18            }
19        }
20    };
21}
22
23id_type!(WorkspaceId);
24id_type!(HarnessId);
25
26impl HarnessId {
27    /// Layout leaves of the activity and stats screens; never real harnesses.
28    pub const ACTIVITY: Self = Self(u32::MAX);
29    pub const STATS: Self = Self(u32::MAX - 1);
30
31    pub fn is_screen(self) -> bool {
32        self == Self::ACTIVITY || self == Self::STATS
33    }
34}
35id_type!(SubagentId);
36
37/// The kind of process a harness runs.
38///
39/// `Shell` is the generic escape hatch: any command can live in a harness, but
40/// the agent adapters are what give us subagent telemetry.
41#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
42#[serde(rename_all = "kebab-case")]
43pub enum HarnessKind {
44    ClaudeCode,
45    OpenCode,
46    Pi,
47    Shell,
48}
49
50impl HarnessKind {
51    pub fn badge(self) -> &'static str {
52        match self {
53            HarnessKind::ClaudeCode => "CC",
54            HarnessKind::OpenCode => "OC",
55            HarnessKind::Pi => "PI",
56            HarnessKind::Shell => "SH",
57        }
58    }
59
60    pub fn label(self) -> &'static str {
61        match self {
62            HarnessKind::ClaudeCode => "Claude Code",
63            HarnessKind::OpenCode => "opencode",
64            HarnessKind::Pi => "pi",
65            HarnessKind::Shell => "shell",
66        }
67    }
68
69    pub fn default_command(self) -> &'static str {
70        match self {
71            HarnessKind::ClaudeCode => "claude",
72            HarnessKind::OpenCode => "opencode",
73            HarnessKind::Pi => "pi",
74            HarnessKind::Shell => "$SHELL",
75        }
76    }
77
78    pub const ALL: [HarnessKind; 4] = [
79        HarnessKind::ClaudeCode,
80        HarnessKind::OpenCode,
81        HarnessKind::Pi,
82        HarnessKind::Shell,
83    ];
84}
85
86#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
87#[serde(rename_all = "kebab-case")]
88pub enum HarnessStatus {
89    /// Producing tokens or running a tool.
90    Working,
91    /// Waiting for input.
92    Idle,
93    /// Blocked on a question / permission prompt.
94    NeedsInput,
95    /// Exited non-zero or hit a provider error.
96    Error,
97}
98
99impl HarnessStatus {
100    pub fn label(self) -> &'static str {
101        match self {
102            HarnessStatus::Working => "working",
103            HarnessStatus::Idle => "idle",
104            HarnessStatus::NeedsInput => "needs input",
105            HarnessStatus::Error => "error",
106        }
107    }
108}
109
110/// A child agent spawned by a harness (Claude Code Task, opencode child
111/// session, pi equivalent).
112#[derive(Debug, Clone, Serialize, Deserialize)]
113pub struct Subagent {
114    pub id: SubagentId,
115    pub label: String,
116    pub detail: String,
117    pub elapsed: String,
118    pub working: bool,
119}
120
121#[derive(Debug, Clone, Serialize, Deserialize)]
122pub struct Harness {
123    pub id: HarnessId,
124    pub workspace: WorkspaceId,
125    pub name: String,
126    pub kind: HarnessKind,
127    /// Working directory, relative to the workspace root when possible.
128    pub cwd: String,
129    pub status: HarnessStatus,
130    #[serde(default)]
131    pub subagents: Vec<Subagent>,
132    #[serde(default)]
133    pub unread: u16,
134    /// Short role the agent sets for itself ("frontend", "debugger").
135    #[serde(default)]
136    pub tag: String,
137    /// One-line description of what the agent is doing, set by the agent.
138    #[serde(default)]
139    pub title: String,
140    /// Pronouns the agent chose for itself ("she/her", "they/them").
141    #[serde(default)]
142    pub pronouns: String,
143    /// Index into the theme accents; unset until `assign_agent_colors` runs.
144    #[serde(default)]
145    pub color: Option<usize>,
146    /// Whether its arrival is already in the activity feed. Agents start false
147    /// and announce themselves when they pick a name; shells log at once.
148    /// Older state files default to true so nothing is logged twice.
149    #[serde(default = "default_true")]
150    pub announced: bool,
151    /// Whether its first working turn is already in the activity feed.
152    #[serde(default = "default_true")]
153    pub started: bool,
154}
155
156fn default_true() -> bool {
157    true
158}
159
160impl Harness {
161    pub fn working_subagents(&self) -> usize {
162        self.subagents.iter().filter(|agent| agent.working).count()
163    }
164
165    pub fn has_live_subagents(&self) -> bool {
166        self.working_subagents() > 0
167    }
168
169    pub fn subagent_count(&self) -> usize {
170        self.subagents.len()
171    }
172}
173
174/// A workspace is a named view over a folder. Two workspaces may point at the
175/// same folder, and a workspace may point at a subfolder of another project.
176#[derive(Debug, Clone, Serialize, Deserialize)]
177pub struct Workspace {
178    pub id: WorkspaceId,
179    pub name: String,
180    pub path: String,
181    /// Index into the active theme's accent palette.
182    pub accent: usize,
183    pub expanded: bool,
184    /// The pinned general-purpose workspace (not tied to a project folder).
185    #[serde(default)]
186    pub home: bool,
187    /// Put away: shown in the Unloaded section, its tiles detached (the
188    /// tmux sessions keep running).
189    #[serde(default)]
190    pub unloaded: bool,
191    pub harnesses: Vec<Harness>,
192}
193
194impl Workspace {
195    pub fn harness(&self, id: HarnessId) -> Option<&Harness> {
196        self.harnesses.iter().find(|harness| harness.id == id)
197    }
198
199    pub fn harness_mut(&mut self, id: HarnessId) -> Option<&mut Harness> {
200        self.harnesses.iter_mut().find(|harness| harness.id == id)
201    }
202
203    pub fn working(&self) -> usize {
204        self.harnesses
205            .iter()
206            .filter(|harness| harness.status == HarnessStatus::Working)
207            .count()
208    }
209
210    pub fn unread(&self) -> u16 {
211        self.harnesses.iter().map(|harness| harness.unread).sum()
212    }
213}
214
215/// One message in a harness mailbox. Persisted so a reload loses nothing.
216#[derive(Debug, Clone, Serialize, Deserialize)]
217pub struct Mail {
218    pub to: HarnessId,
219    /// Sender's display name at send time (`user` for the human or termdenctl
220    /// outside a tile).
221    pub from: String,
222    pub text: String,
223    #[serde(default)]
224    pub read: bool,
225}
226
227/// One line of the activity feed. Persisted so a reload keeps the history.
228#[derive(Debug, Clone, Default, Serialize, Deserialize)]
229pub struct Activity {
230    /// Local wall-clock "HH:MM" when it happened.
231    pub time: String,
232    pub name: String,
233    pub message: String,
234    pub accent: usize,
235    /// Recipient of a mail entry (`name → to`) and their color.
236    #[serde(default)]
237    pub to: Option<(String, usize)>,
238    /// Harness this line is about; the feed reads its current name and color.
239    #[serde(default)]
240    pub harness: Option<HarnessId>,
241    /// Message body of a mail entry, shown when its bubble is opened.
242    #[serde(default)]
243    pub detail: Option<String>,
244    /// Results page path (`r/<id>/`) of a share entry.
245    #[serde(default)]
246    pub link: Option<String>,
247    /// Bubble expanded in the activity screen.
248    #[serde(skip)]
249    pub open: bool,
250}
251
252/// Work an agent shows the user (images, videos, files): view only, nothing
253/// is sent back. Served by the app's local results page.
254#[derive(Debug, Clone, Serialize, Deserialize)]
255pub struct Showcase {
256    /// Stable id in the page URL (`r/<id>/`).
257    pub id: u64,
258    pub from: HarnessId,
259    /// The agent's name when it shared, for after it is gone.
260    pub from_name: String,
261    pub title: String,
262    pub description: String,
263    /// Wall-clock time it was shared, e.g. `14:05`.
264    pub time: String,
265    pub items: Vec<ShowItem>,
266}
267
268#[derive(Debug, Clone, Serialize, Deserialize)]
269pub struct ShowItem {
270    pub path: std::path::PathBuf,
271    pub caption: String,
272    pub description: String,
273}
274
275/// Accent indices agents may get: the theme accents minus green (termden's own
276/// status) and red (errors).
277pub const AGENT_COLORS: [usize; 6] = [0, 1, 3, 4, 5, 6];
278
279/// An agent's color follows its name (FNV-1a), so it is the same after a
280/// restart or when the agent comes back. Two names can share one.
281pub fn agent_color(name: &str) -> usize {
282    let hash = name.bytes().fold(0xcbf29ce484222325u64, |h, b| {
283        (h ^ b as u64).wrapping_mul(0x100000001b3)
284    });
285    AGENT_COLORS[(hash >> 32) as usize % AGENT_COLORS.len()]
286}
287
288pub fn assign_agent_colors(workspaces: &mut [Workspace]) {
289    for harness in workspaces.iter_mut().flat_map(|w| &mut w.harnesses) {
290        harness.color = Some(agent_color(&harness.name));
291    }
292}
293
294#[cfg(test)]
295mod color_tests {
296    use super::*;
297
298    #[test]
299    fn color_depends_only_on_the_name() {
300        assert_eq!(agent_color("Sable"), agent_color("Sable"));
301        assert!(AGENT_COLORS.contains(&agent_color("Quill")));
302        let names = ["Sable", "Quill", "Tamsin", "Okonkwo", "Wren", "Bartholomew"];
303        let colors: std::collections::HashSet<_> = names.iter().map(|n| agent_color(n)).collect();
304        assert!(colors.len() > 1);
305    }
306}