1pub mod i18n;
11
12pub const VERSION_WITH_HASH: &str = env!("ERTANGLE_VERSION_WITH_HASH");
14
15use serde::{Deserialize, Serialize};
16use std::collections::{BTreeMap, HashMap, VecDeque};
17use std::time::{SystemTime, UNIX_EPOCH};
18use tr::tr;
19
20const LEGACY_ENV_PREFIX: &str = "TERMADE_";
22const ENV_PREFIX: &str = "ERTANGLE_";
23
24fn legacy_env_name(name: &str) -> Option<String> {
26 name.strip_prefix(ENV_PREFIX)
27 .map(|rest| format!("{LEGACY_ENV_PREFIX}{rest}"))
28}
29
30fn env_lookup<T>(name: &str, get: impl Fn(&str) -> Option<T>) -> Option<T> {
32 get(name).or_else(|| legacy_env_name(name).and_then(|old| get(&old)))
33}
34
35pub fn env_var(name: &str) -> Option<String> {
37 env_lookup(name, |k| std::env::var(k).ok())
38}
39
40pub fn env_var_os(name: &str) -> Option<std::ffi::OsString> {
42 env_lookup(name, |k| std::env::var_os(k))
43}
44
45#[cfg(test)]
46mod env_compat_tests {
47 use super::*;
48 use std::collections::HashMap;
49
50 fn lookup(map: &HashMap<&str, &str>, name: &str) -> Option<String> {
51 env_lookup(name, |k| map.get(k).map(|v| v.to_string()))
52 }
53
54 #[test]
55 fn prefers_new_name() {
56 let m = HashMap::from([("ERTANGLE_X", "new"), ("TERMADE_X", "old")]);
57 assert_eq!(lookup(&m, "ERTANGLE_X").as_deref(), Some("new"));
58 }
59
60 #[test]
61 fn falls_back_to_legacy_name() {
62 let m = HashMap::from([("TERMADE_X", "old")]);
63 assert_eq!(lookup(&m, "ERTANGLE_X").as_deref(), Some("old"));
64 }
65
66 #[test]
67 fn unset_returns_none_and_other_prefixes_have_no_legacy() {
68 let m = HashMap::from([("TERMADE_X", "old")]);
69 assert_eq!(lookup(&m, "ERTANGLE_Y"), None);
70 assert_eq!(lookup(&m, "OTHER_X"), None);
71 assert_eq!(legacy_env_name("HOME"), None);
72 }
73}
74
75pub fn now_millis() -> u64 {
77 SystemTime::now()
78 .duration_since(UNIX_EPOCH)
79 .map(|d| d.as_millis() as u64)
80 .unwrap_or(0)
81}
82
83pub fn new_id(prefix: &str) -> String {
85 let u = uuid::Uuid::new_v4().simple().to_string();
86 format!("{prefix}_{}", &u[..12])
87}
88
89pub type SessionId = String;
90pub type MsgId = String;
91pub type TaskId = String;
92
93pub type Seq = u64;
95
96#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
102#[serde(rename_all = "snake_case")]
103pub enum AgentKind {
104 #[serde(alias = "open_code", alias = "opencode", alias = "OpenCode")]
105 OpenCode,
106 #[serde(alias = "claude", alias = "claude-code", alias = "ClaudeCode")]
107 ClaudeCode,
108 #[serde(alias = "Codex")]
109 Codex,
110 #[serde(alias = "agy", alias = "gemini", alias = "Antigravity")]
111 Antigravity,
112 Custom(String),
114}
115
116impl AgentKind {
117 pub fn id(&self) -> &str {
119 match self {
120 AgentKind::OpenCode => "opencode",
121 AgentKind::ClaudeCode => "claude",
122 AgentKind::Codex => "codex",
123 AgentKind::Antigravity => "antigravity",
124 AgentKind::Custom(name) => name,
125 }
126 }
127
128 pub fn parse(s: &str) -> Option<AgentKind> {
129 Some(match s.to_ascii_lowercase().as_str() {
130 "opencode" | "open_code" | "oc" => AgentKind::OpenCode,
131 "claude" | "claude-code" | "claudecode" => AgentKind::ClaudeCode,
132 "codex" => AgentKind::Codex,
133 "antigravity" | "agy" | "gemini" => AgentKind::Antigravity,
134 _ => return None,
135 })
136 }
137
138 pub fn builtins() -> [AgentKind; 4] {
140 [
141 AgentKind::OpenCode,
142 AgentKind::ClaudeCode,
143 AgentKind::Codex,
144 AgentKind::Antigravity,
145 ]
146 }
147
148 pub fn pty_command(&self) -> (&str, Vec<&'static str>) {
150 match self {
151 AgentKind::OpenCode => ("opencode", vec![]),
152 AgentKind::ClaudeCode => ("claude", vec![]),
153 AgentKind::Codex => ("codex", vec![]),
154 AgentKind::Antigravity => ("agy", vec![]),
155 AgentKind::Custom(cmd) => (cmd.as_str(), vec![]),
156 }
157 }
158
159 pub fn acp_command(&self) -> Option<(&str, Vec<&'static str>)> {
164 match self {
165 AgentKind::OpenCode => Some(("opencode", vec!["acp"])),
166 AgentKind::Antigravity => Some(("agy", vec!["acp"])),
167 _ => None,
168 }
169 }
170}
171
172impl std::fmt::Display for AgentKind {
173 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
174 f.write_str(self.id())
175 }
176}
177
178#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
184#[serde(rename_all = "snake_case")]
185pub enum Role {
186 Coordinator,
188 #[default]
190 Worker,
191 Reviewer,
193 Custom(String),
194}
195
196impl Role {
197 pub fn id(&self) -> &str {
198 match self {
199 Role::Coordinator => "coordinator",
200 Role::Worker => "worker",
201 Role::Reviewer => "reviewer",
202 Role::Custom(n) => n,
203 }
204 }
205 pub fn parse(s: &str) -> Role {
206 match s.to_ascii_lowercase().as_str() {
207 "coordinator" | "coord" => Role::Coordinator,
208 "reviewer" | "review" => Role::Reviewer,
209 "worker" => Role::Worker,
210 other => Role::Custom(other.to_string()),
211 }
212 }
213}
214
215#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
216#[serde(rename_all = "snake_case")]
217pub enum SessionStatus {
218 Starting,
219 Idle,
220 Busy,
221 WaitingApproval,
222 Sleeping,
224 Exited,
225 Failed,
226}
227
228impl SessionStatus {
229 pub fn glyph(self) -> &'static str {
231 match self {
232 SessionStatus::Starting => "◌",
233 SessionStatus::Idle => "○",
234 SessionStatus::Busy => "●",
235 SessionStatus::WaitingApproval => "⏸",
236 SessionStatus::Sleeping => "☾",
237 SessionStatus::Exited => "✓",
238 SessionStatus::Failed => "✗",
239 }
240 }
241 pub fn is_live(self) -> bool {
242 !matches!(self, SessionStatus::Exited | SessionStatus::Failed)
243 }
244}
245
246#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize, Default)]
247pub struct Cost {
248 pub usd: f64,
249 pub input_tokens: u64,
250 pub output_tokens: u64,
251}
252
253#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
255pub struct ContextUsage {
256 pub used: u64,
257 pub window: Option<u64>,
259}
260
261impl ContextUsage {
262 pub fn percent(&self) -> Option<f32> {
263 self.window
264 .filter(|w| *w > 0)
265 .map(|w| self.used as f32 * 100.0 / w as f32)
266 }
267
268 pub fn short(&self) -> String {
270 match (self.window, self.percent()) {
271 (Some(w), Some(p)) => {
272 format!("{}/{} {:.0}%", human_tokens(self.used), human_tokens(w), p)
273 }
274 _ => human_tokens(self.used),
275 }
276 }
277}
278
279pub fn human_tokens(n: u64) -> String {
281 match n {
282 0..=999 => n.to_string(),
283 1_000..=999_999 => format!("{}k", (n as f64 / 1000.0).round() as u64),
284 _ => {
285 let m = n as f64 / 1_000_000.0;
286 if (m - m.round()).abs() < 0.05 {
287 format!("{}M", m.round() as u64)
288 } else {
289 format!("{m:.1}M")
290 }
291 }
292 }
293}
294
295pub fn format_usd_limit(limit: f64) -> String {
297 if (limit - limit.round()).abs() < 1e-6 {
298 format!("${:.0}", limit)
299 } else {
300 format!("${:.2}", limit)
301 }
302}
303
304#[derive(Debug, Clone, Serialize, Deserialize)]
306pub struct Session {
307 pub id: SessionId,
308 pub kind: AgentKind,
309 pub label: String,
311 pub cwd: String,
313 pub branch: Option<String>,
315 pub role: Role,
316 pub status: SessionStatus,
317 pub model: Option<String>,
318 pub cost: Cost,
319 pub parent: Option<SessionId>,
321 pub created_ms: u64,
322 pub transport: String,
324 #[serde(default)]
326 pub status_note: Option<String>,
327 #[serde(default)]
329 pub repo_root: Option<String>,
330 #[serde(default)]
332 pub permission: PermissionPolicy,
333 #[serde(default)]
335 pub context: Option<ContextUsage>,
336 #[serde(default)]
339 pub native_id: Option<String>,
340 #[serde(default)]
342 pub budget_usd: Option<f64>,
343 #[serde(default)]
345 pub over_budget: bool,
346 #[serde(default)]
348 pub handed_off_to: Option<SessionId>,
349 #[serde(default)]
351 pub effort: Option<String>,
352 #[serde(default)]
354 pub slash_commands: Vec<String>,
355 #[serde(default)]
357 pub active_tools: Vec<ActiveTool>,
358 #[serde(default)]
360 pub bg_procs: Vec<BgProc>,
361 #[serde(default)]
363 pub tool_calls: u32,
364 #[serde(default)]
367 pub ended_ms: Option<u64>,
368}
369
370impl Session {
371 pub fn ended_or_created_ms(&self) -> u64 {
373 self.ended_ms.unwrap_or(self.created_ms)
374 }
375
376 pub fn project_root(&self) -> &str {
378 self.repo_root.as_deref().unwrap_or(&self.cwd)
379 }
380
381 pub fn format_budget(&self) -> Option<String> {
383 self.budget_usd
384 .map(|limit| format!("${:.2}/{}", self.cost.usd, format_usd_limit(limit)))
385 }
386}
387
388#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
390pub struct ActiveTool {
391 pub name: String,
392 pub summary: String,
393 pub started_ms: u64,
394 pub is_subagent: bool,
395}
396
397#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
399pub struct BgProc {
400 pub pid: u32,
401 pub name: String,
402 pub cmdline: String,
403 #[serde(default)]
404 pub elapsed_secs: u64,
405}
406
407pub fn is_subagent_tool(name: &str) -> bool {
409 let lower = name.to_ascii_lowercase();
410 matches!(
411 lower.as_str(),
412 "task" | "agent" | "dispatch_agent" | "invoke_subagent" | "spawn_agent" | "subagent"
413 )
414}
415
416#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
422#[serde(rename_all = "snake_case")]
423pub enum Target {
424 Direct(SessionId),
425 Channel(String),
426 Broadcast,
427}
428
429impl Target {
430 pub fn parse(s: &str) -> Target {
435 let s = s.trim();
436 if s == "*" || s.eq_ignore_ascii_case("broadcast") {
437 Target::Broadcast
438 } else if let Some(ch) = s.strip_prefix('#').or_else(|| s.strip_prefix("channel:")) {
439 Target::Channel(ch.to_string())
440 } else if let Some(d) = s.strip_prefix('@') {
441 Target::Direct(d.to_string())
442 } else {
443 Target::Direct(s.to_string())
444 }
445 }
446}
447
448#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
449#[serde(rename_all = "snake_case")]
450pub enum MsgKind {
451 #[default]
452 Chat,
453 Handoff,
455 Question,
456 Answer,
457 Status,
458 Artifact,
460}
461
462impl MsgKind {
463 pub fn id(self) -> &'static str {
464 match self {
465 MsgKind::Chat => "chat",
466 MsgKind::Handoff => "handoff",
467 MsgKind::Question => "question",
468 MsgKind::Answer => "answer",
469 MsgKind::Status => "status",
470 MsgKind::Artifact => "artifact",
471 }
472 }
473
474 pub fn parse(s: &str) -> Option<MsgKind> {
475 Some(match s.to_ascii_lowercase().as_str() {
476 "chat" | "message" => MsgKind::Chat,
477 "handoff" => MsgKind::Handoff,
478 "question" | "ask" => MsgKind::Question,
479 "answer" | "reply" => MsgKind::Answer,
480 "status" => MsgKind::Status,
481 "artifact" => MsgKind::Artifact,
482 _ => return None,
483 })
484 }
485}
486
487#[derive(Debug, Clone, Serialize, Deserialize)]
488pub struct BusMessage {
489 pub id: MsgId,
490 pub from: SessionId,
491 pub to: Target,
492 #[serde(default)]
493 pub kind: MsgKind,
494 pub body: String,
495 pub reply_to: Option<MsgId>,
496 pub ts: u64,
497}
498
499impl BusMessage {
500 pub fn matches_recipient(&self, session_id: &str, label: Option<&str>) -> bool {
505 match &self.to {
506 Target::Broadcast | Target::Channel(_) => self.from != session_id,
507 Target::Direct(target) => target == session_id || label.is_some_and(|l| l == target),
508 }
509 }
510}
511
512#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
513#[serde(rename_all = "snake_case")]
514pub enum TaskStatus {
515 #[serde(alias = "Todo")]
516 Todo,
517 #[serde(alias = "Doing")]
518 Doing,
519 #[serde(alias = "Blocked")]
520 Blocked,
521 #[serde(alias = "Review")]
522 Review,
523 #[serde(alias = "Done")]
524 Done,
525}
526
527impl TaskStatus {
528 pub fn id(self) -> &'static str {
529 match self {
530 TaskStatus::Todo => "todo",
531 TaskStatus::Doing => "doing",
532 TaskStatus::Blocked => "blocked",
533 TaskStatus::Review => "review",
534 TaskStatus::Done => "done",
535 }
536 }
537
538 pub fn parse(s: &str) -> Option<TaskStatus> {
539 Some(match s.to_ascii_lowercase().as_str() {
540 "todo" | "open" => TaskStatus::Todo,
541 "doing" | "in_progress" | "in-progress" | "working" => TaskStatus::Doing,
542 "blocked" => TaskStatus::Blocked,
543 "review" => TaskStatus::Review,
544 "done" | "completed" | "closed" => TaskStatus::Done,
545 _ => return None,
546 })
547 }
548}
549
550#[derive(Debug, Clone, Serialize, Deserialize)]
551pub struct Task {
552 pub id: TaskId,
553 pub title: String,
554 #[serde(default)]
555 pub detail: String,
556 pub status: TaskStatus,
557 pub assignee: Option<SessionId>,
558 #[serde(default)]
559 pub created_by: Option<SessionId>,
560 #[serde(default)]
561 pub depends_on: Vec<TaskId>,
562 pub updated_ms: u64,
563}
564
565#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
566#[serde(rename_all = "snake_case")]
567pub enum ArtifactKind {
568 #[default]
569 File,
570 Branch,
571 Diff,
572}
573
574impl ArtifactKind {
575 pub fn id(self) -> &'static str {
576 match self {
577 ArtifactKind::File => "file",
578 ArtifactKind::Branch => "branch",
579 ArtifactKind::Diff => "diff",
580 }
581 }
582
583 pub fn parse(s: &str) -> Option<ArtifactKind> {
584 Some(match s.to_ascii_lowercase().as_str() {
585 "file" | "path" => ArtifactKind::File,
586 "branch" => ArtifactKind::Branch,
587 "diff" | "patch" => ArtifactKind::Diff,
588 _ => return None,
589 })
590 }
591}
592
593#[derive(Debug, Clone, Serialize, Deserialize)]
595pub struct Artifact {
596 pub id: String,
597 pub session: SessionId,
598 pub kind: ArtifactKind,
599 pub path: String,
600 #[serde(default)]
601 pub note: String,
602 pub ts: u64,
603}
604
605#[derive(Debug, Clone, Serialize, Deserialize)]
607pub struct ReviewComment {
608 pub id: String,
609 pub session: SessionId,
610 pub location: String,
612 pub comment: String,
613 pub ts: u64,
614}
615
616#[derive(Debug, Clone, Serialize, Deserialize)]
618pub struct WorktreeInfo {
619 pub session: SessionId,
620 pub label: String,
621 pub path: String,
622 pub branch: String,
623 pub live: bool,
624 pub changed_files: usize,
625 pub summary: String,
626}
627
628#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
640#[serde(rename_all = "snake_case")]
641pub enum PermissionPolicy {
642 Ask,
644 #[default]
646 Auto,
647 Bypass,
649}
650
651impl PermissionPolicy {
652 pub fn rank(&self) -> u8 {
654 match self {
655 PermissionPolicy::Ask => 0,
656 PermissionPolicy::Auto => 1,
657 PermissionPolicy::Bypass => 2,
658 }
659 }
660
661 pub fn min_policy(self, other: PermissionPolicy) -> PermissionPolicy {
663 if other.rank() < self.rank() {
664 other
665 } else {
666 self
667 }
668 }
669
670 pub fn id(&self) -> &'static str {
671 match self {
672 PermissionPolicy::Ask => "ask",
673 PermissionPolicy::Auto => "auto",
674 PermissionPolicy::Bypass => "bypass",
675 }
676 }
677
678 pub fn parse(s: &str) -> Option<PermissionPolicy> {
679 Some(match s.to_ascii_lowercase().as_str() {
680 "ask" | "manual" => PermissionPolicy::Ask,
681 "auto" | "accept-edits" | "acceptedits" => PermissionPolicy::Auto,
682 "bypass" | "yolo" | "dangerous" => PermissionPolicy::Bypass,
683 _ => return None,
684 })
685 }
686
687 pub fn auto_approves(&self) -> bool {
689 matches!(self, PermissionPolicy::Auto | PermissionPolicy::Bypass)
690 }
691
692 pub fn claude_flags(&self) -> Vec<&'static str> {
694 match self {
695 PermissionPolicy::Ask => vec!["--permission-mode", "manual"],
696 PermissionPolicy::Auto => vec!["--permission-mode", "acceptEdits"],
697 PermissionPolicy::Bypass => vec!["--dangerously-skip-permissions"],
698 }
699 }
700
701 pub fn codex_flags(&self) -> Vec<&'static str> {
706 vec![]
707 }
708
709 pub fn codex_approval_policy(&self) -> &'static str {
711 match self {
712 PermissionPolicy::Ask => "untrusted",
713 PermissionPolicy::Auto => "on-request",
714 PermissionPolicy::Bypass => "never",
715 }
716 }
717}
718
719impl std::fmt::Display for PermissionPolicy {
720 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
721 f.write_str(self.id())
722 }
723}
724
725#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
726#[serde(rename_all = "snake_case")]
727pub enum Decision {
728 #[serde(alias = "Allow")]
729 Allow,
730 #[serde(alias = "always", alias = "Always", alias = "AllowAlways")]
732 AllowAlways,
733 #[serde(alias = "Deny")]
734 Deny,
735}
736
737#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
739pub struct QuestionOption {
740 pub label: String,
741 #[serde(default, skip_serializing_if = "Option::is_none")]
742 pub description: Option<String>,
743 #[serde(default, skip_serializing_if = "Option::is_none")]
745 pub value: Option<String>,
746}
747
748impl QuestionOption {
749 pub fn new(label: impl Into<String>, description: Option<&str>) -> Self {
750 Self {
751 label: label.into(),
752 description: description.map(str::to_string),
753 value: None,
754 }
755 }
756
757 pub fn plain(label: impl Into<String>) -> Self {
758 Self {
759 label: label.into(),
760 description: None,
761 value: None,
762 }
763 }
764
765 pub fn with_value(
767 label: impl Into<String>,
768 description: Option<&str>,
769 value: impl Into<String>,
770 ) -> Self {
771 Self {
772 label: label.into(),
773 description: description.map(str::to_string),
774 value: Some(value.into()),
775 }
776 }
777}
778
779#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
781pub struct UserQuestion {
782 pub id: String,
784 pub session: SessionId,
785 #[serde(default, skip_serializing_if = "Option::is_none")]
786 pub header: Option<String>,
787 pub question: String,
788 #[serde(default)]
789 pub options: Vec<QuestionOption>,
790 #[serde(default)]
791 pub multi_select: bool,
792 #[serde(default)]
793 pub custom: bool,
794 #[serde(default, skip_serializing_if = "Option::is_none")]
796 pub group: Option<String>,
797}
798
799#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
801pub struct QuestionAnswer {
802 pub id: String,
803 pub session: SessionId,
804 pub answers: Vec<String>,
805}
806
807#[derive(Debug, Clone, Serialize, Deserialize)]
809pub struct PermissionRequest {
810 pub req: String,
812 pub session: SessionId,
813 pub title: String,
815 pub detail: String,
817}
818
819#[derive(Debug, Clone, Serialize, Deserialize)]
825#[serde(tag = "kind", rename_all = "snake_case")]
826#[expect(
827 clippy::large_enum_variant,
828 reason = "事件列舉變體大小差異大,部分變體攜帶完整快照狀態"
829)]
830pub enum Event {
831 Snapshot {
833 state: Box<State>,
834 },
835 SessionStarted {
836 session: Session,
837 },
838 SessionStatus {
839 session: SessionId,
840 status: SessionStatus,
841 },
842 SessionContext {
844 session: SessionId,
845 used: u64,
846 window: Option<u64>,
847 },
848 QuotaUpdated {
850 quota: Quota,
851 },
852 SessionLimited {
854 session: SessionId,
855 detail: String,
856 },
857 SessionRemoved {
859 session: SessionId,
860 },
861 ArchivePruned {
863 sessions: Vec<SessionId>,
864 },
865 SessionModel {
867 session: SessionId,
868 model: String,
869 },
870 SessionCommands {
872 session: SessionId,
873 commands: Vec<String>,
874 },
875 SessionEffort {
877 session: SessionId,
878 effort: String,
879 },
880 SessionNativeId {
882 session: SessionId,
883 native_id: String,
884 },
885 SessionCleared {
888 session: SessionId,
889 },
890 SessionLabel {
891 session: SessionId,
892 label: String,
893 },
894 SessionNote {
896 session: SessionId,
897 note: String,
898 },
899 SessionHandedOff {
901 from: SessionId,
902 to: SessionId,
903 },
904 UserPrompt {
906 session: SessionId,
907 text: String,
908 #[serde(default, skip_serializing_if = "Option::is_none")]
911 from: Option<String>,
912 },
913 Output {
915 session: SessionId,
916 text: String,
917 },
918 OutputAppend {
921 session: SessionId,
922 text: String,
923 },
924 InboxRead {
926 session: SessionId,
927 msg: String,
928 },
929 SessionBgProcs {
931 session: SessionId,
932 procs: Vec<BgProc>,
933 },
934 ToolCall {
935 session: SessionId,
936 name: String,
937 #[serde(default)]
938 input: String,
939 ok: Option<bool>,
941 #[serde(default)]
942 output: Option<String>,
943 },
944 PermissionRequested {
945 request: PermissionRequest,
946 },
947 PermissionResolved {
948 session: SessionId,
949 req: String,
950 decision: Decision,
951 },
952 QuestionRequested {
953 question: UserQuestion,
954 },
955 QuestionResolved {
956 session: SessionId,
957 id: String,
958 #[serde(default)]
959 answers: Vec<String>,
960 },
961 BusMessage {
962 message: BusMessage,
963 },
964 TaskChanged {
965 task: Task,
966 },
967 ArtifactShared {
968 artifact: Artifact,
969 },
970 ReviewCommented {
971 review: ReviewComment,
972 },
973 SessionExited {
974 session: SessionId,
975 code: Option<i32>,
976 },
977 Cost {
978 session: SessionId,
979 cost: Cost,
980 },
981 SessionOverBudget {
983 session: SessionId,
984 spent: f64,
985 limit: f64,
986 },
987 SessionBudget {
989 session: SessionId,
990 budget_usd: Option<f64>,
991 },
992 LogHealth {
994 ok: bool,
995 },
996 QueueChanged {
998 session: SessionId,
999 items: Vec<String>,
1000 },
1001}
1002
1003#[derive(Debug, Clone, Serialize, Deserialize)]
1005pub struct Record {
1006 pub seq: Seq,
1007 pub ts: u64,
1008 #[serde(flatten)]
1009 pub event: Event,
1010}
1011
1012pub const TRANSCRIPT_CAP: usize = 4000;
1018pub const PROMPT_FROM_ERTANGLE: &str = "ertangle";
1020pub const USER_PROMPT_MARK: &str = "❯ ";
1022pub const OTHER_PROMPT_MARK: &str = "» ";
1024
1025pub fn parse_prompt_line(line: &str) -> Option<(Option<&str>, &str)> {
1027 if let Some(rest) = line.strip_prefix(USER_PROMPT_MARK) {
1028 return Some((None, rest));
1029 }
1030 let rest = line.strip_prefix(OTHER_PROMPT_MARK)?.strip_prefix('[')?;
1031 let (name, text) = rest.split_once("] ")?;
1032 Some((Some(name), text))
1033}
1034pub const ARCHIVED_SESSIONS_CAP: usize = 100;
1036pub const ARCHIVED_MAX_DAYS: u64 = 30;
1038pub const ARCHIVED_TRANSCRIPT_CAP: usize = 200;
1040pub const MESSAGE_CAP: usize = 1000;
1042pub const ARTIFACT_CAP: usize = 500;
1044
1045fn default_true() -> bool {
1046 true
1047}
1048
1049#[derive(Debug, Clone, Serialize, Deserialize)]
1050pub struct State {
1051 pub seq: Seq,
1052 pub sessions: BTreeMap<SessionId, Session>,
1053 #[serde(default)]
1055 pub archived_sessions: BTreeMap<SessionId, Session>,
1056 pub tasks: BTreeMap<TaskId, Task>,
1057 pub messages: Vec<BusMessage>,
1058 #[serde(default)]
1059 pub artifacts: Vec<Artifact>,
1060 #[serde(default)]
1061 pub reviews: Vec<ReviewComment>,
1062 pub pending_permissions: BTreeMap<String, PermissionRequest>,
1064 #[serde(default)]
1066 pub pending_questions: BTreeMap<String, UserQuestion>,
1067 pub transcripts: HashMap<SessionId, VecDeque<String>>,
1069 #[serde(default = "default_true")]
1071 pub log_ok: bool,
1072 #[serde(default)]
1074 pub quotas: BTreeMap<String, Quota>,
1075 #[serde(default)]
1077 pub queues: BTreeMap<SessionId, Vec<String>>,
1078 #[serde(default)]
1080 pub inbox_cursors: BTreeMap<SessionId, String>,
1081}
1082
1083impl Default for State {
1084 fn default() -> Self {
1085 State {
1086 seq: 0,
1087 sessions: BTreeMap::new(),
1088 archived_sessions: BTreeMap::new(),
1089 tasks: BTreeMap::new(),
1090 messages: Vec::new(),
1091 artifacts: Vec::new(),
1092 reviews: Vec::new(),
1093 pending_permissions: BTreeMap::new(),
1094 pending_questions: BTreeMap::new(),
1095 transcripts: HashMap::new(),
1096 log_ok: true,
1097 quotas: BTreeMap::new(),
1098 queues: BTreeMap::new(),
1099 inbox_cursors: BTreeMap::new(),
1100 }
1101 }
1102}
1103
1104impl State {
1105 pub fn new() -> Self {
1106 Self::default()
1107 }
1108
1109 fn remove_session_questions(&mut self, session: &str) {
1111 let ids: Vec<String> = self
1112 .pending_questions
1113 .values()
1114 .filter(|q| q.session == session)
1115 .map(|q| q.id.clone())
1116 .collect();
1117 for id in ids {
1118 self.pending_questions.remove(&id);
1119 }
1120 }
1121
1122 fn push_transcript_line(&mut self, session: &str, line: String) {
1123 let buf = self.transcripts.entry(session.to_string()).or_default();
1124 buf.push_back(line);
1125 while buf.len() > TRANSCRIPT_CAP {
1126 buf.pop_front();
1127 }
1128 }
1129
1130 pub fn archive_session(&mut self, session: &str) {
1132 self.remove_session_questions(session);
1133 if let Some(mut s) = self.sessions.remove(session) {
1134 if s.native_id.is_some() {
1135 s.status = SessionStatus::Exited;
1136 s.active_tools.clear();
1137 s.bg_procs.clear();
1138 let need_summary = s
1139 .status_note
1140 .as_deref()
1141 .is_none_or(|n| n.is_empty() || n.contains(":resume"));
1142 if need_summary {
1143 if let Some(last_prompt) = self.transcripts.get(session).and_then(|buf| {
1144 buf.iter()
1145 .rev()
1146 .find_map(|line| parse_prompt_line(line).map(|(_, t)| t))
1147 }) {
1148 let snippet: String = last_prompt.trim().chars().take(80).collect();
1149 if !snippet.is_empty() {
1150 s.status_note = Some(snippet);
1151 }
1152 }
1153 }
1154 if let Some(buf) = self.transcripts.get_mut(session) {
1155 while buf.len() > ARCHIVED_TRANSCRIPT_CAP {
1156 buf.pop_front();
1157 }
1158 }
1159 self.archived_sessions.insert(session.to_string(), s);
1160 } else {
1161 self.transcripts.remove(session);
1162 }
1163 } else {
1164 self.transcripts.remove(session);
1165 }
1166 self.queues.remove(session);
1167 self.pending_permissions.retain(|_, p| p.session != session);
1168 self.pending_questions.retain(|_, q| q.session != session);
1169 }
1170
1171 pub fn archived_to_prune(
1174 &self,
1175 now_ms: u64,
1176 max_count: usize,
1177 max_days: u64,
1178 ) -> Vec<SessionId> {
1179 let max_age_ms = max_days.saturating_mul(86_400_000);
1180 let mut by_age: Vec<(&SessionId, u64)> = self
1181 .archived_sessions
1182 .iter()
1183 .map(|(id, s)| (id, s.ended_or_created_ms()))
1184 .collect();
1185 by_age.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(b.0)));
1187 by_age
1188 .into_iter()
1189 .enumerate()
1190 .filter(|(i, (_, ended))| *i >= max_count || now_ms.saturating_sub(*ended) > max_age_ms)
1191 .map(|(_, (id, _))| id.clone())
1192 .collect()
1193 }
1194
1195 pub fn apply(&mut self, rec: &Record) {
1197 self.seq = self.seq.max(rec.seq);
1198 match &rec.event {
1199 Event::Snapshot { state } => {
1200 *self = (**state).clone();
1201 self.seq = rec.seq;
1202 }
1203 Event::SessionStarted { session } => {
1204 self.archived_sessions.remove(&session.id);
1205 let mut session = session.clone();
1206 if session.status.is_live() {
1207 session.ended_ms = None;
1208 }
1209 self.sessions.insert(session.id.clone(), session);
1210 }
1211 Event::SessionStatus { session, status } => {
1212 if let Some(s) = self.sessions.get_mut(session) {
1213 s.status = *status;
1214 s.ended_ms = if status.is_live() {
1215 None
1216 } else {
1217 s.ended_ms.or(Some(rec.ts))
1218 };
1219 if *status != SessionStatus::Busy && *status != SessionStatus::WaitingApproval {
1220 s.active_tools.clear();
1221 }
1222 }
1223 }
1224 Event::InboxRead { session, msg } => {
1225 self.inbox_cursors.insert(session.clone(), msg.clone());
1226 }
1227 Event::SessionBgProcs { session, procs } => {
1228 if let Some(s) = self.sessions.get_mut(session) {
1229 s.bg_procs = procs.clone();
1230 }
1231 }
1232 Event::SessionContext {
1233 session,
1234 used,
1235 window,
1236 } => {
1237 if let Some(s) = self.sessions.get_mut(session) {
1238 let window = window.or(s.context.and_then(|c| c.window));
1240 let used = if *used == 0 {
1242 s.context.map_or(0, |c| c.used)
1243 } else {
1244 *used
1245 };
1246 s.context = Some(ContextUsage { used, window });
1247 }
1248 }
1249 Event::QuotaUpdated { quota } => {
1250 self.quotas.insert(quota.agent.clone(), quota.clone());
1251 }
1252 Event::SessionLimited { session, detail } => {
1253 if let Some(s) = self.sessions.get_mut(session) {
1254 s.status = SessionStatus::Failed;
1255 s.ended_ms = s.ended_ms.or(Some(rec.ts));
1256 let d: String = detail.chars().take(80).collect();
1257 s.status_note = Some(tr!("額度用完:{d} (可用 handoff 交接)", d = d));
1258 }
1259 }
1260 Event::SessionRemoved { session } => {
1261 self.archive_session(session);
1262 }
1263 Event::ArchivePruned { sessions } => {
1264 for id in sessions {
1265 self.archived_sessions.remove(id);
1266 self.transcripts.remove(id);
1267 }
1268 }
1269 Event::SessionModel { session, model } => {
1270 if let Some(s) = self.sessions.get_mut(session) {
1271 s.model = Some(model.clone());
1272 }
1273 }
1274 Event::SessionCommands { session, commands } => {
1275 if let Some(s) = self.sessions.get_mut(session) {
1276 s.slash_commands = commands.clone();
1277 }
1278 }
1279 Event::SessionEffort { session, effort } => {
1280 if let Some(s) = self.sessions.get_mut(session) {
1281 s.effort = Some(effort.clone());
1282 }
1283 }
1284 Event::SessionNativeId { session, native_id } => {
1285 if let Some(s) = self.sessions.get_mut(session) {
1286 s.native_id = Some(native_id.clone());
1287 }
1288 }
1289 Event::SessionCleared { session } => {
1290 self.remove_session_questions(session);
1291 self.pending_permissions
1292 .retain(|_, p| p.session != *session);
1293 self.transcripts.remove(session);
1294 if let Some(s) = self.sessions.get_mut(session) {
1295 s.native_id = None;
1296 s.cost = Cost::default();
1297 s.context = None;
1298 s.status_note = None;
1299 s.slash_commands.clear();
1300 s.active_tools.clear();
1301 s.bg_procs.clear();
1302 s.tool_calls = 0;
1303 s.over_budget = false;
1304 }
1305 }
1306 Event::SessionLabel { session, label } => {
1307 if let Some(s) = self.sessions.get_mut(session) {
1308 s.label = label.clone();
1309 } else if let Some(s) = self.archived_sessions.get_mut(session) {
1310 s.label = label.clone();
1311 }
1312 }
1313 Event::SessionNote { session, note } => {
1314 if let Some(s) = self.sessions.get_mut(session) {
1315 s.status_note = if note.is_empty() {
1316 None
1317 } else {
1318 Some(note.clone())
1319 };
1320 }
1321 }
1322 Event::SessionHandedOff { from, to } => {
1323 if let Some(s) = self.sessions.get_mut(from) {
1324 s.handed_off_to = Some(to.clone());
1325 }
1326 }
1327 Event::UserPrompt {
1328 session,
1329 text,
1330 from,
1331 } => {
1332 let head = match from {
1335 None => USER_PROMPT_MARK.to_string(),
1336 Some(f) => {
1337 let name = self
1338 .sessions
1339 .get(f)
1340 .map(|s| s.label.clone())
1341 .unwrap_or_else(|| f.clone());
1342 format!("{OTHER_PROMPT_MARK}[{name}] ")
1343 }
1344 };
1345 let buf = self.transcripts.entry(session.clone()).or_default();
1346 let text = text.trim_end_matches('\n');
1347 if !text.is_empty() {
1348 for (i, line) in text.split('\n').enumerate() {
1349 if i == 0 {
1350 buf.push_back(format!("{head}{line}"));
1351 } else {
1352 buf.push_back(format!(" {line}"));
1353 }
1354 }
1355 }
1356 while buf.len() > TRANSCRIPT_CAP {
1357 buf.pop_front();
1358 }
1359 }
1360 Event::Output { session, text } => {
1361 let buf = self.transcripts.entry(session.clone()).or_default();
1362 let mut parts: Vec<&str> = text.split('\n').collect();
1364 if parts.last() == Some(&"") {
1365 parts.pop();
1366 }
1367 for line in parts {
1368 buf.push_back(line.to_string());
1369 }
1370 while buf.len() > TRANSCRIPT_CAP {
1371 buf.pop_front();
1372 }
1373 }
1374 Event::OutputAppend { session, text } => {
1375 let buf = self.transcripts.entry(session.clone()).or_default();
1376 let mut parts = text.split('\n');
1377 if let Some(first) = parts.next() {
1378 match buf.back_mut() {
1379 Some(last) => last.push_str(first),
1380 None => buf.push_back(first.to_string()),
1381 }
1382 }
1383 let rest: Vec<&str> = parts.collect();
1384 let rest = match rest.split_last() {
1386 Some((&"", init)) => init,
1387 _ => &rest[..],
1388 };
1389 for line in rest {
1390 buf.push_back((*line).to_string());
1391 }
1392 while buf.len() > TRANSCRIPT_CAP {
1393 buf.pop_front();
1394 }
1395 }
1396 Event::ToolCall {
1397 session,
1398 name,
1399 input,
1400 ok,
1401 output,
1402 } => {
1403 if let Some(s) = self.sessions.get_mut(session) {
1404 if ok.is_none() && !name.is_empty() {
1405 s.tool_calls = s.tool_calls.saturating_add(1);
1406 let is_sub = is_subagent_tool(name);
1407 let sum = tool_summary(input).unwrap_or_default();
1408 s.active_tools.push(ActiveTool {
1409 name: name.clone(),
1410 summary: sum,
1411 started_ms: now_millis(),
1412 is_subagent: is_sub,
1413 });
1414 } else if ok.is_some() {
1415 if !name.is_empty() {
1416 if let Some(pos) = s.active_tools.iter().position(|t| t.name == *name) {
1417 s.active_tools.remove(pos);
1418 } else if !s.active_tools.is_empty() {
1419 s.active_tools.remove(0);
1420 }
1421 } else if !s.active_tools.is_empty() {
1422 s.active_tools.remove(0);
1423 }
1424 }
1425 }
1426 if ok.is_none() && !name.is_empty() {
1427 let line = match tool_summary(input) {
1428 Some(sum) => format!("▸ {name}: {sum}"),
1429 None => format!("▸ {name}"),
1430 };
1431 self.push_transcript_line(session, line);
1432 } else if let Some(ok) = ok {
1433 let out = output.as_deref().unwrap_or("");
1435 let first = out.lines().find(|l| !l.trim().is_empty()).unwrap_or("");
1436 let extra = out
1437 .lines()
1438 .filter(|l| !l.trim().is_empty())
1439 .count()
1440 .saturating_sub(1);
1441 let mut text: String = first.trim().chars().take(100).collect();
1442 if first.trim().chars().count() > 100 || extra > 0 {
1443 text.push_str(&if extra > 0 {
1444 tr!(" …(+{extra} 行)", extra = extra)
1445 } else {
1446 "…".into()
1447 });
1448 }
1449 let line = match (ok, text.is_empty()) {
1450 (true, true) => " ✓".to_string(),
1451 (true, false) => format!(" ✓ {text}"),
1452 (false, true) => format!(" ✗ {}", tr!("失敗")),
1453 (false, false) => format!(" ✗ {text}"),
1454 };
1455 self.push_transcript_line(session, line);
1456 }
1457 }
1458 Event::PermissionRequested { request } => {
1459 self.pending_permissions
1460 .insert(request.req.clone(), request.clone());
1461 if let Some(s) = self.sessions.get_mut(&request.session) {
1462 s.status = SessionStatus::WaitingApproval;
1463 }
1464 }
1465 Event::PermissionResolved { req, .. } => {
1466 self.pending_permissions.remove(req);
1467 }
1468 Event::QuestionRequested { question } => {
1469 self.pending_questions
1470 .insert(question.id.clone(), question.clone());
1471 if let Some(s) = self.sessions.get_mut(&question.session) {
1472 s.status = SessionStatus::WaitingApproval;
1473 }
1474 }
1475 Event::QuestionResolved { id, .. } => {
1476 self.pending_questions.remove(id);
1477 }
1478 Event::BusMessage { message } => {
1479 self.messages.push(message.clone());
1480 while self.messages.len() > MESSAGE_CAP {
1481 self.messages.remove(0);
1482 }
1483 }
1484 Event::TaskChanged { task } => {
1485 self.tasks.insert(task.id.clone(), task.clone());
1486 }
1487 Event::ArtifactShared { artifact } => {
1488 self.artifacts.push(artifact.clone());
1489 while self.artifacts.len() > ARTIFACT_CAP {
1490 self.artifacts.remove(0);
1491 }
1492 }
1493 Event::ReviewCommented { review } => {
1494 let line = format!("💬 review [{}]: {}", review.location, review.comment);
1495 self.push_transcript_line(&review.session, line);
1496 self.reviews.push(review.clone());
1497 while self.reviews.len() > ARTIFACT_CAP {
1498 self.reviews.remove(0);
1499 }
1500 }
1501 Event::SessionExited { session, .. } => {
1502 self.remove_session_questions(session);
1503 if let Some(s) = self.sessions.get_mut(session) {
1504 if s.status.is_live() {
1505 s.status = SessionStatus::Exited;
1506 }
1507 s.ended_ms = s.ended_ms.or(Some(rec.ts));
1508 }
1509 }
1510 Event::Cost { session, cost } => {
1511 if let Some(s) = self.sessions.get_mut(session) {
1512 s.cost = *cost;
1513 }
1514 }
1515 Event::SessionOverBudget { session, .. } => {
1516 if let Some(s) = self.sessions.get_mut(session) {
1517 s.over_budget = true;
1518 }
1519 }
1520 Event::SessionBudget {
1521 session,
1522 budget_usd,
1523 } => {
1524 if let Some(s) = self.sessions.get_mut(session) {
1525 s.budget_usd = *budget_usd;
1526 s.over_budget = false;
1527 }
1528 }
1529 Event::LogHealth { ok } => {
1530 self.log_ok = *ok;
1531 }
1532 Event::QueueChanged { session, items } => {
1533 if items.is_empty() {
1534 self.queues.remove(session);
1535 } else {
1536 self.queues.insert(session.clone(), items.clone());
1537 }
1538 }
1539 }
1540 }
1541
1542 pub fn session_depth(&self, sid: &str) -> usize {
1544 let mut depth = 0;
1545 let mut cur = sid;
1546 let mut seen = std::collections::HashSet::new();
1547 while seen.insert(cur) {
1548 let Some(parent) = self
1549 .sessions
1550 .get(cur)
1551 .and_then(|s| s.parent.as_deref())
1552 .filter(|p| self.sessions.contains_key(*p))
1553 else {
1554 break;
1555 };
1556 depth += 1;
1557 cur = parent;
1558 }
1559 depth
1560 }
1561
1562 pub fn tree_root(&self, sid: &str) -> SessionId {
1564 let mut cur = sid;
1565 let mut seen = std::collections::HashSet::new();
1566 while seen.insert(cur) {
1567 let Some(parent) = self
1568 .sessions
1569 .get(cur)
1570 .and_then(|s| s.parent.as_deref())
1571 .filter(|p| self.sessions.contains_key(*p))
1572 else {
1573 break;
1574 };
1575 cur = parent;
1576 }
1577 cur.to_string()
1578 }
1579
1580 pub fn tree_sessions(&self, sid: &str) -> Vec<SessionId> {
1582 let root = self.tree_root(sid);
1583 self.sessions
1584 .keys()
1585 .filter(|id| self.tree_root(id) == root)
1586 .cloned()
1587 .collect()
1588 }
1589
1590 pub fn tree_cost_usd(&self, sid: &str) -> f64 {
1592 let root = self.tree_root(sid);
1593 self.sessions
1594 .values()
1595 .filter(|s| self.tree_root(&s.id) == root)
1596 .map(|s| s.cost.usd)
1597 .sum()
1598 }
1599
1600 pub fn live_children_count(&self, parent_id: &str) -> usize {
1602 self.sessions
1603 .values()
1604 .filter(|s| s.parent.as_deref() == Some(parent_id) && s.status.is_live())
1605 .count()
1606 }
1607
1608 pub fn sessions_sorted(&self) -> Vec<&Session> {
1610 let mut v: Vec<&Session> = self.sessions.values().collect();
1611 v.sort_by_key(|s| s.created_ms);
1612 v
1613 }
1614
1615 pub fn live_sessions(&self) -> impl Iterator<Item = &Session> {
1616 self.sessions.values().filter(|s| s.status.is_live())
1617 }
1618
1619 pub fn total_cost(&self) -> Cost {
1621 let mut total = Cost::default();
1622 for s in self.sessions.values() {
1623 total.usd += s.cost.usd;
1624 total.input_tokens = total.input_tokens.saturating_add(s.cost.input_tokens);
1625 total.output_tokens = total.output_tokens.saturating_add(s.cost.output_tokens);
1626 }
1627 total
1628 }
1629
1630 pub fn unfinished_deps(&self, task: &Task) -> Vec<&Task> {
1633 task.depends_on
1634 .iter()
1635 .filter_map(|id| self.tasks.get(id))
1636 .filter(|t| t.status != TaskStatus::Done)
1637 .collect()
1638 }
1639
1640 pub fn resolve_session_id(&self, id_or_label: &str) -> Option<SessionId> {
1642 let needle = id_or_label.trim().trim_start_matches('@');
1643 if self.sessions.contains_key(needle) {
1644 return Some(needle.to_string());
1645 }
1646 self.sessions
1647 .values()
1648 .filter(|s| s.label == needle && s.status.is_live())
1649 .max_by_key(|s| s.created_ms)
1650 .or_else(|| {
1651 self.sessions
1652 .values()
1653 .filter(|s| s.label == needle)
1654 .max_by_key(|s| s.created_ms)
1655 })
1656 .map(|s| s.id.clone())
1657 }
1658
1659 pub fn resolve_resumable_session(&self, id_or_label: &str) -> Option<(Session, bool)> {
1661 let needle = id_or_label.trim().trim_start_matches('@');
1662 if needle.is_empty() {
1663 return None;
1664 }
1665 if let Some(s) = self.sessions.get(needle) {
1666 return Some((s.clone(), false));
1667 }
1668 if let Some(s) = self.archived_sessions.get(needle) {
1669 return Some((s.clone(), true));
1670 }
1671 if let Some(s) = self
1672 .sessions
1673 .values()
1674 .filter(|s| s.label == needle && !s.status.is_live())
1675 .max_by_key(|s| s.created_ms)
1676 {
1677 return Some((s.clone(), false));
1678 }
1679 if let Some(s) = self
1680 .archived_sessions
1681 .values()
1682 .filter(|s| s.label == needle)
1683 .max_by_key(|s| s.created_ms)
1684 {
1685 return Some((s.clone(), true));
1686 }
1687 if let Some(s) = self
1688 .sessions
1689 .values()
1690 .filter(|s| s.label == needle)
1691 .max_by_key(|s| s.created_ms)
1692 {
1693 return Some((s.clone(), false));
1694 }
1695 if let Some(s) = self
1696 .sessions
1697 .values()
1698 .filter(|s| s.native_id.as_deref() == Some(needle))
1699 .max_by_key(|s| s.created_ms)
1700 {
1701 return Some((s.clone(), false));
1702 }
1703 if let Some(s) = self
1704 .archived_sessions
1705 .values()
1706 .filter(|s| s.native_id.as_deref() == Some(needle))
1707 .max_by_key(|s| s.created_ms)
1708 {
1709 return Some((s.clone(), true));
1710 }
1711 None
1712 }
1713
1714 pub fn successor_of(&self, id: &str) -> SessionId {
1716 let mut cur = id.to_string();
1717 let mut seen = vec![cur.clone()];
1718 for _ in 0..16 {
1719 let Some(next) = self
1720 .sessions
1721 .get(&cur)
1722 .and_then(|s| s.handed_off_to.clone())
1723 else {
1724 break;
1725 };
1726 if seen.contains(&next) {
1727 break;
1728 }
1729 seen.push(next.clone());
1730 cur = next;
1731 }
1732 cur
1733 }
1734
1735 pub fn inbox_for(&self, session_id: &str, after_msg_id: Option<&str>) -> Vec<BusMessage> {
1737 let resolved = self
1738 .resolve_session_id(session_id)
1739 .unwrap_or_else(|| session_id.to_string());
1740 let label = self.sessions.get(&resolved).map(|s| s.label.as_str());
1741 let start = after_msg_id
1742 .and_then(|id| self.messages.iter().position(|m| m.id == id))
1743 .map(|idx| idx + 1)
1744 .unwrap_or(0);
1745 self.messages
1746 .get(start..)
1747 .unwrap_or(&[])
1748 .iter()
1749 .filter(|m| m.matches_recipient(&resolved, label))
1750 .cloned()
1751 .collect()
1752 }
1753
1754 pub fn export_markdown(
1759 &self,
1760 root_id: &str,
1761 include_tree: bool,
1762 diff: Option<&str>,
1763 ) -> Result<String, String> {
1764 let root = self
1765 .resolve_session_id(root_id)
1766 .ok_or_else(|| tr!("找不到 session:{id}", id = root_id))?;
1767 let root_session = self
1768 .sessions
1769 .get(&root)
1770 .ok_or_else(|| tr!("找不到 session:{id}", id = root))?;
1771
1772 let mut members: Vec<&Session> = if include_tree {
1773 let mut v: Vec<&Session> = self
1774 .tree_sessions(&root)
1775 .iter()
1776 .filter_map(|id| self.sessions.get(id))
1777 .collect();
1778 v.sort_by_key(|s| (self.session_depth(&s.id), s.created_ms, s.id.clone()));
1779 v
1780 } else {
1781 vec![root_session]
1782 };
1783 if let Some(pos) = members.iter().position(|s| s.id == root) {
1785 let root_ref = members.remove(pos);
1786 members.insert(0, root_ref);
1787 }
1788
1789 let member_ids: Vec<&str> = members.iter().map(|s| s.id.as_str()).collect();
1790 let total_usd: f64 = members.iter().map(|s| s.cost.usd).sum();
1791 let total_in: u64 = members
1792 .iter()
1793 .fold(0u64, |acc, s| acc.saturating_add(s.cost.input_tokens));
1794 let total_out: u64 = members
1795 .iter()
1796 .fold(0u64, |acc, s| acc.saturating_add(s.cost.output_tokens));
1797
1798 let mut out = String::new();
1799 out.push_str(&tr!("# 協作報告:{label}\n\n", label = root_session.label));
1800
1801 out.push_str(&format!("## {}\n\n", tr!("元資料")));
1802 out.push_str(&format!("| {} | {} |\n", tr!("項目"), tr!("值")));
1803 out.push_str("| --- | --- |\n");
1804 let row = |k: String, v: String| format!("| {k} | {v} |\n");
1805 out.push_str(&row(tr!("標籤"), root_session.label.clone()));
1806 out.push_str(&row(
1807 tr!("Agent / Model"),
1808 format!(
1809 "{}{}{}",
1810 root_session.kind.id(),
1811 root_session
1812 .model
1813 .as_deref()
1814 .map(|m| format!(" / {m}"))
1815 .unwrap_or_default(),
1816 root_session
1817 .effort
1818 .as_deref()
1819 .map(|e| format!(" (effort: {e})"))
1820 .unwrap_or_default()
1821 ),
1822 ));
1823 out.push_str(&row(tr!("角色"), root_session.role.id().to_string()));
1824 out.push_str(&row(
1825 tr!("分支"),
1826 root_session.branch.clone().unwrap_or_else(|| "-".into()),
1827 ));
1828 out.push_str(&row(
1829 tr!("狀態"),
1830 format!(
1831 "{} {}",
1832 root_session.status.glyph(),
1833 status_text(root_session.status)
1834 ),
1835 ));
1836 out.push_str(&row(
1837 tr!("總花費"),
1838 format!(
1839 "${total_usd:.4} ({} in / {} out tokens)",
1840 total_in, total_out
1841 ),
1842 ));
1843 out.push('\n');
1844
1845 if include_tree && members.len() > 1 {
1846 out.push_str(&format!("## {}\n\n", tr!("子 Session 階層")));
1847 out.push_str(&format!(
1848 "| {} | {} | {} | {} | {} |\n",
1849 tr!("標籤"),
1850 tr!("角色"),
1851 tr!("Agent / Model"),
1852 tr!("狀態"),
1853 tr!("花費")
1854 ));
1855 out.push_str("| --- | --- | --- | --- | --- |\n");
1856 for s in &members {
1857 let indent = " ".repeat(self.session_depth(&s.id));
1858 out.push_str(&format!(
1859 "| {indent}{} | {} | {}{} | {} {} | ${:.4} |\n",
1860 s.label,
1861 s.role.id(),
1862 s.kind.id(),
1863 s.model
1864 .as_deref()
1865 .map(|m| format!(" / {m}"))
1866 .unwrap_or_default(),
1867 s.status.glyph(),
1868 status_text(s.status),
1869 s.cost.usd,
1870 ));
1871 }
1872 out.push('\n');
1873 }
1874
1875 let related: Vec<&Task> = self
1876 .tasks
1877 .values()
1878 .filter(|t| {
1879 t.assignee
1880 .as_deref()
1881 .is_some_and(|id| member_ids.contains(&id))
1882 || t.created_by
1883 .as_deref()
1884 .is_some_and(|id| member_ids.contains(&id))
1885 })
1886 .collect();
1887 if !related.is_empty() {
1888 out.push_str(&format!("## {}\n\n", tr!("關聯任務")));
1889 out.push_str(&format!(
1890 "| {} | {} | {} | {} |\n",
1891 tr!("編號"),
1892 tr!("標題"),
1893 tr!("狀態"),
1894 tr!("負責人")
1895 ));
1896 out.push_str("| --- | --- | --- | --- |\n");
1897 for t in related {
1898 let assignee = t.assignee.as_deref().and_then(|id| self.sessions.get(id));
1899 out.push_str(&format!(
1900 "| {} | {} | {} | {} |\n",
1901 t.id,
1902 t.title,
1903 t.status.id(),
1904 assignee.map(|s| s.label.as_str()).unwrap_or("-")
1905 ));
1906 }
1907 out.push('\n');
1908 }
1909
1910 out.push_str(&format!("## {}\n\n", tr!("對話與執行紀錄")));
1911 for s in &members {
1912 out.push_str(&format!("### {} ({})\n\n", s.label, s.role.id()));
1913 let lines = self.transcripts.get(&s.id);
1914 match lines {
1915 Some(lines) if !lines.is_empty() => {
1916 out.push_str("```text\n");
1917 for line in lines.iter().filter(|l| !l.starts_with(" ✓")) {
1919 out.push_str(line);
1920 out.push('\n');
1921 }
1922 out.push_str("```\n\n");
1923 }
1924 _ => {
1925 out.push_str(&format!("_{}_\n\n", tr!("(尚無逐字稿)")));
1926 }
1927 }
1928 }
1929
1930 if let Some(diff) = diff.filter(|d| !d.trim().is_empty()) {
1931 out.push_str(&format!(
1932 "## Git Diff\n\n```diff\n{}\n```\n",
1933 diff.trim_end()
1934 ));
1935 }
1936
1937 Ok(redact_secrets(&out))
1938 }
1939}
1940
1941fn status_text(status: SessionStatus) -> String {
1943 match status {
1944 SessionStatus::Starting => tr!("啟動中"),
1945 SessionStatus::Idle => tr!("閒置"),
1946 SessionStatus::Busy => tr!("執行中"),
1947 SessionStatus::WaitingApproval => tr!("等待核准"),
1948 SessionStatus::Sleeping => tr!("休眠"),
1949 SessionStatus::Exited => tr!("已結束"),
1950 SessionStatus::Failed => tr!("失敗"),
1951 }
1952}
1953
1954#[derive(Debug, Clone, Serialize, Deserialize)]
1966pub struct PolicyEngine {
1967 pub allow: Vec<String>,
1968 pub deny: Vec<String>,
1969}
1970
1971impl Default for PolicyEngine {
1972 fn default() -> Self {
1973 Self {
1974 allow: vec![
1975 "Read".into(),
1976 "Grep".into(),
1977 "Glob".into(),
1978 "git status".into(),
1979 "git diff".into(),
1980 "git log".into(),
1981 ],
1982 deny: vec![
1983 "rm -rf /".into(),
1984 "rm -rf ~".into(),
1985 "git push --force".into(),
1986 "git push -f".into(),
1987 "/.ssh/".into(),
1988 "id_rsa".into(),
1989 "mkfs.".into(),
1990 ],
1991 }
1992 }
1993}
1994
1995impl PolicyEngine {
1996 pub fn parse_toml(src: &str) -> Self {
1998 let mut engine = Self::default();
1999 for raw_line in src.lines() {
2000 let line = raw_line.split('#').next().unwrap_or("").trim();
2001 if line.is_empty() {
2002 continue;
2003 }
2004 if let Some((k, v)) = line.split_once('=') {
2005 let key = k.trim();
2006 let list = parse_string_array(v.trim());
2007 if key == "allow" && !list.is_empty() {
2008 engine.allow = list;
2009 } else if key == "deny" && !list.is_empty() {
2010 engine.deny = list;
2011 }
2012 }
2013 }
2014 engine
2015 }
2016
2017 pub fn evaluate(&self, title: &str, detail: &str) -> Option<Decision> {
2022 let combined = format!("{title} {detail}");
2023 for pat in &self.deny {
2025 if !pat.is_empty() && combined.contains(pat.as_str()) {
2026 return Some(Decision::Deny);
2027 }
2028 }
2029 let command = command_text(detail);
2032 for pat in &self.allow {
2033 if pat.is_empty() {
2034 continue;
2035 }
2036 let title_tool = title.split_whitespace().next().unwrap_or("");
2037 if title_tool == pat
2038 || word_prefix(title, pat)
2039 || command.as_deref().is_some_and(|c| word_prefix(c, pat))
2040 {
2041 return Some(Decision::Allow);
2042 }
2043 }
2044 None
2045 }
2046
2047 pub fn merged_with(&self, local: &PolicyEngine) -> PolicyEngine {
2049 let mut out = self.clone();
2050 for d in &local.deny {
2051 if !out.deny.contains(d) {
2052 out.deny.push(d.clone());
2053 }
2054 }
2055 for a in &local.allow {
2056 if !out.allow.contains(a) {
2057 out.allow.push(a.clone());
2058 }
2059 }
2060 out
2061 }
2062}
2063
2064fn word_prefix(text: &str, pat: &str) -> bool {
2066 let t = text.trim_start();
2067 t.starts_with(pat)
2068 && t[pat.len()..]
2069 .chars()
2070 .next()
2071 .is_none_or(char::is_whitespace)
2072}
2073
2074fn command_text(detail: &str) -> Option<String> {
2076 let Ok(v) = serde_json::from_str::<serde_json::Value>(detail) else {
2078 return Some(detail.to_string());
2079 };
2080 match &v {
2081 serde_json::Value::String(s) => Some(s.clone()),
2082 serde_json::Value::Object(m) => ["command", "cmd"]
2083 .iter()
2084 .find_map(|k| m.get(*k).and_then(|x| x.as_str()))
2085 .map(str::to_string),
2086 _ => None,
2087 }
2088}
2089
2090fn parse_string_array(s: &str) -> Vec<String> {
2091 let s = s.trim().trim_start_matches('[').trim_end_matches(']');
2092 s.split(',')
2093 .map(|item| item.trim().trim_matches('"').trim_matches('\'').to_string())
2094 .filter(|item| !item.is_empty())
2095 .collect()
2096}
2097
2098pub fn tool_summary(input: &str) -> Option<String> {
2100 let v: serde_json::Value = serde_json::from_str(input).ok()?;
2101 let one_line = |s: &str| -> String {
2102 let t: String = s.split_whitespace().collect::<Vec<_>>().join(" ");
2103 if t.chars().count() > 100 {
2104 format!("{}…", t.chars().take(100).collect::<String>())
2105 } else {
2106 t
2107 }
2108 };
2109 match &v {
2110 serde_json::Value::Null => None,
2111 serde_json::Value::String(s) if !s.trim().is_empty() => Some(one_line(s)),
2112 serde_json::Value::Object(m) => {
2113 for k in [
2114 "command",
2115 "cmd",
2116 "file_path",
2117 "path",
2118 "pattern",
2119 "url",
2120 "query",
2121 "description",
2122 "prompt",
2123 ] {
2124 if let Some(x) = m.get(k).and_then(|x| x.as_str()) {
2125 if !x.trim().is_empty() {
2126 return Some(one_line(x));
2127 }
2128 }
2129 }
2130 if m.keys()
2132 .all(|k| matches!(k.as_str(), "cwd" | "workdir" | "timeout"))
2133 {
2134 None
2135 } else {
2136 Some(one_line(&v.to_string()))
2137 }
2138 }
2139 _ => None,
2140 }
2141}
2142
2143#[cfg(test)]
2144mod tool_summary_tests {
2145 use super::tool_summary;
2146
2147 #[test]
2148 fn picks_the_descriptive_field() {
2149 assert_eq!(
2150 tool_summary(r#"{"command":"cargo fmt","cwd":"/tmp"}"#).as_deref(),
2151 Some("cargo fmt")
2152 );
2153 assert!(
2154 tool_summary(r#"{"cwd":"/mnt"}"#).is_none(),
2155 "只有 cwd 的物件沒有資訊量,不該印 JSON"
2156 );
2157 assert!(tool_summary(r#"{"workdir":"/mnt","timeout":10}"#).is_none());
2158 let other = tool_summary(r#"{"mcp":"x","args":["a"]}"#);
2159 assert!(
2160 other.as_deref().is_some_and(|s| s.contains("\"mcp\"")),
2161 "未知欄位仍要能看到原文:{other:?}"
2162 );
2163 assert!(tool_summary("not json").is_none());
2164 }
2165}
2166
2167#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
2169pub struct QuotaWindow {
2170 pub name: String,
2172 pub used_percent: f32,
2173 pub resets_at_ms: Option<u64>,
2175}
2176
2177#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
2179pub struct Quota {
2180 pub agent: String,
2182 pub windows: Vec<QuotaWindow>,
2183 pub reached: bool,
2185 #[serde(default)]
2187 pub warning: bool,
2188 pub updated_ms: u64,
2189}
2190
2191pub fn format_remaining(ms: u64) -> String {
2193 let mins = ms / 60_000;
2194 match mins {
2195 0 => "<1m".into(),
2196 1..=59 => format!("{mins}m"),
2197 60..=1439 => format!("{}h{:02}m", mins / 60, mins % 60),
2198 _ => format!("{}d{}h", mins / 1440, (mins % 1440) / 60),
2199 }
2200}
2201
2202impl Quota {
2203 fn is_inactive_window(&self, window: &QuotaWindow) -> bool {
2204 self.agent == "antigravity" && window.name.starts_with("3p-")
2206 }
2207
2208 pub fn summary(&self, now_ms: u64) -> String {
2210 let parts: Vec<String> = self
2211 .windows
2212 .iter()
2213 .map(|w| match w.resets_at_ms {
2214 Some(r) if r <= now_ms => tr!("{name} 已重置", name = w.name),
2215 Some(r) => tr!(
2216 "{name} {pct}% (重置 {remaining})",
2217 name = w.name,
2218 pct = format!("{:.0}", w.used_percent),
2219 remaining = format_remaining(r.saturating_sub(now_ms))
2220 ),
2221 None => format!("{} {:.0}%", w.name, w.used_percent),
2222 })
2223 .collect();
2224 let reached = if self.is_reached(now_ms) {
2225 format!(" {}", tr!("✗額度已滿"))
2226 } else {
2227 String::new()
2228 };
2229 format!("{}{} {}", self.agent, reached, parts.join(" · "))
2230 }
2231
2232 pub fn is_reached(&self, now_ms: u64) -> bool {
2239 if self.windows.is_empty() {
2240 return self.reached;
2241 }
2242 let any_live_exhausted = self
2243 .windows
2244 .iter()
2245 .filter(|w| !self.is_inactive_window(w))
2246 .filter(|w| w.resets_at_ms.is_none_or(|r| r > now_ms))
2247 .any(|w| w.used_percent >= 100.0);
2248 if any_live_exhausted {
2249 return true;
2250 }
2251 if self.reached {
2252 let any_reset = self.windows.iter().any(|w| {
2253 !self.is_inactive_window(w) && w.resets_at_ms.is_some_and(|r| r <= now_ms)
2254 });
2255 if !any_reset {
2256 return true;
2257 }
2258 }
2259 false
2260 }
2261
2262 pub fn max_used(&self) -> f32 {
2264 self.windows
2265 .iter()
2266 .filter(|w| !self.is_inactive_window(w))
2267 .map(|w| w.used_percent)
2268 .fold(0.0, f32::max)
2269 }
2270
2271 pub fn max_used_live(&self, now_ms: u64) -> f32 {
2273 self.windows
2274 .iter()
2275 .filter(|w| !self.is_inactive_window(w))
2276 .filter(|w| w.resets_at_ms.is_none_or(|reset| reset > now_ms))
2277 .map(|w| w.used_percent)
2278 .fold(0.0, f32::max)
2279 }
2280}
2281
2282pub fn window_name(mins: u64) -> String {
2284 match mins {
2285 300 => "5h".into(),
2286 10080 => "7d".into(),
2287 43200 => "30d".into(),
2288 m if m % 1440 == 0 => format!("{}d", m / 1440),
2289 m if m % 60 == 0 => format!("{}h", m / 60),
2290 m => format!("{m}m"),
2291 }
2292}
2293
2294pub fn looks_like_limit(text: &str) -> bool {
2296 let t = text.to_ascii_lowercase();
2297 (t.contains("limit")
2298 && (t.contains("hit your")
2299 || t.contains("usage")
2300 || t.contains("rate")
2301 || t.contains("resets")))
2302 || t.contains("rate_limit")
2303 || t.contains("rate limit")
2304 || t.contains("insufficient_quota")
2305 || t.contains("quota exceeded")
2306 || t.contains("exceeded your current quota")
2307 || t.contains("429")
2308}
2309
2310#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
2313pub struct Attachment {
2314 pub name: String,
2316 pub mime: String,
2318 #[serde(default)]
2320 pub path: Option<String>,
2321 #[serde(default)]
2323 pub data: Option<String>,
2324 #[serde(default)]
2326 pub text: Option<String>,
2327 pub size: u64,
2328 #[serde(default, skip_serializing_if = "Option::is_none")]
2330 pub raw_prompt: Option<String>,
2331}
2332
2333pub const MAX_IMAGE_BYTES: u64 = 5 * 1024 * 1024;
2335pub const MAX_TEXT_BYTES: u64 = 256 * 1024;
2336
2337pub fn image_mime(path: &std::path::Path) -> Option<&'static str> {
2339 match path.extension()?.to_str()?.to_ascii_lowercase().as_str() {
2340 "png" => Some("image/png"),
2341 "jpg" | "jpeg" => Some("image/jpeg"),
2342 "gif" => Some("image/gif"),
2343 "webp" => Some("image/webp"),
2344 _ => None,
2345 }
2346}
2347
2348pub fn base64_encode(bytes: &[u8]) -> String {
2350 const T: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
2351 let mut out = String::with_capacity(bytes.len().div_ceil(3) * 4);
2352 for chunk in bytes.chunks(3) {
2353 let Some(&first) = chunk.first() else {
2354 continue;
2355 };
2356 let n = (u32::from(first) << 16)
2357 | (u32::from(*chunk.get(1).unwrap_or(&0)) << 8)
2358 | u32::from(*chunk.get(2).unwrap_or(&0));
2359 if let Some(&ch) = T.get((n >> 18) as usize & 63) {
2360 out.push(ch as char);
2361 }
2362 if let Some(&ch) = T.get((n >> 12) as usize & 63) {
2363 out.push(ch as char);
2364 }
2365 out.push(if chunk.len() > 1 {
2366 T.get((n >> 6) as usize & 63)
2367 .copied()
2368 .map(char::from)
2369 .unwrap_or('=')
2370 } else {
2371 '='
2372 });
2373 out.push(if chunk.len() > 2 {
2374 T.get(n as usize & 63)
2375 .copied()
2376 .map(char::from)
2377 .unwrap_or('=')
2378 } else {
2379 '='
2380 });
2381 }
2382 out
2383}
2384
2385impl Attachment {
2386 pub fn load(path: &std::path::Path) -> Result<Attachment, String> {
2389 let meta = std::fs::metadata(path)
2390 .map_err(|e| tr!("無法讀取 {path}:{e}", path = path.display(), e = e))?;
2391 if !meta.is_file() {
2392 return Err(tr!("{path} 不是檔案", path = path.display()));
2393 }
2394 let name = path
2395 .file_name()
2396 .map(|n| n.to_string_lossy().to_string())
2397 .unwrap_or_else(|| path.display().to_string());
2398 let abs = std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf());
2399 let mut att = Attachment {
2400 name,
2401 mime: "application/octet-stream".into(),
2402 path: Some(abs.to_string_lossy().to_string()),
2403 size: meta.len(),
2404 ..Default::default()
2405 };
2406 if let Some(mime) = image_mime(path) {
2407 if meta.len() > MAX_IMAGE_BYTES {
2408 return Err(tr!(
2409 "圖片 {name} 太大 ({size} KB,上限 {max} KB)",
2410 name = att.name,
2411 size = meta.len() / 1024,
2412 max = MAX_IMAGE_BYTES / 1024
2413 ));
2414 }
2415 let bytes = std::fs::read(path)
2416 .map_err(|e| tr!("讀取 {name} 失敗:{e}", name = att.name, e = e))?;
2417 att.mime = mime.into();
2418 att.data = Some(base64_encode(&bytes));
2419 return Ok(att);
2420 }
2421 if meta.len() <= MAX_TEXT_BYTES {
2422 let bytes = std::fs::read(path)
2423 .map_err(|e| tr!("讀取 {name} 失敗:{e}", name = att.name, e = e))?;
2424 if !bytes.contains(&0) {
2425 if let Ok(text) = String::from_utf8(bytes) {
2426 att.mime = "text/plain".into();
2427 att.text = Some(text);
2428 }
2429 }
2430 }
2431 Ok(att)
2432 }
2433
2434 pub fn is_image(&self) -> bool {
2435 self.mime.starts_with("image/")
2436 }
2437
2438 pub fn summary(&self) -> String {
2440 format!(
2441 "📎 {} ({}, {} KB)",
2442 self.name,
2443 self.mime,
2444 self.size.div_ceil(1024)
2445 )
2446 }
2447}
2448
2449pub fn compose_text(text: &str, atts: &[Attachment], images_as_text: bool) -> String {
2452 let mut out = text.to_string();
2453 for a in atts {
2454 if a.is_image() {
2455 if images_as_text {
2456 out.push_str(&format!(
2457 "\n\n[圖片附件:{}{}]",
2458 a.name,
2459 a.path
2460 .as_deref()
2461 .map(|p| format!(",路徑 {p}"))
2462 .unwrap_or_default()
2463 ));
2464 }
2465 } else if let Some(t) = &a.text {
2466 out.push_str(&format!(
2467 "\n\n[檔案:{}]\n```\n{}\n```",
2468 a.name,
2469 t.trim_end()
2470 ));
2471 } else {
2472 out.push_str(&format!(
2473 "\n\n[檔案附件:{}{} (內容未內嵌)]",
2474 a.name,
2475 a.path
2476 .as_deref()
2477 .map(|p| format!(",路徑 {p}"))
2478 .unwrap_or_default()
2479 ));
2480 }
2481 }
2482 out
2483}
2484
2485pub fn redact_secrets(input: &str) -> String {
2487 const PREFIXES: &[&str] = &[
2488 "github_pat_",
2489 "glpat-",
2490 "xoxb-",
2491 "xoxp-",
2492 "ghp_",
2493 "gho_",
2494 "ghu_",
2495 "AKIA",
2496 "AIza",
2497 "sk-",
2498 ];
2499 let mut out = String::with_capacity(input.len());
2500 let bytes = input.as_bytes();
2501 let mut i = 0;
2502 while i < bytes.len() {
2503 let Some(rest) = input.get(i..) else {
2504 break;
2505 };
2506 if let Some(pref) = PREFIXES.iter().find(|&&p| rest.starts_with(p)) {
2507 let after = &rest[pref.len()..];
2508 let token_len = after
2509 .bytes()
2510 .take_while(|b| b.is_ascii_alphanumeric() || *b == b'_' || *b == b'-')
2511 .count();
2512 if token_len >= 12 {
2513 out.push_str(pref);
2514 out.push_str("<REDACTED>");
2515 i += pref.len() + token_len;
2516 continue;
2517 }
2518 }
2519 let Some(ch) = rest.chars().next() else {
2520 break;
2521 };
2522 out.push(ch);
2523 i += ch.len_utf8();
2524 }
2525 out
2526}
2527
2528#[cfg(test)]
2529pub(crate) mod tests {
2530 use super::*;
2531
2532 fn rec(seq: u64, event: Event) -> Record {
2533 Record { seq, ts: 0, event }
2534 }
2535
2536 pub(crate) fn sample_session(id: &str) -> Session {
2537 Session {
2538 id: id.to_string(),
2539 kind: AgentKind::OpenCode,
2540 label: "worker".into(),
2541 cwd: "/tmp".into(),
2542 branch: None,
2543 role: Role::Worker,
2544 status: SessionStatus::Starting,
2545 model: None,
2546 cost: Cost::default(),
2547 parent: None,
2548 created_ms: 1,
2549 transport: "acp".into(),
2550 status_note: None,
2551 repo_root: None,
2552 context: None,
2553 native_id: None,
2554 permission: Default::default(),
2555 budget_usd: None,
2556 over_budget: false,
2557 handed_off_to: None,
2558 effort: None,
2559 slash_commands: Vec::new(),
2560 active_tools: Vec::new(),
2561 bg_procs: Vec::new(),
2562 tool_calls: 0,
2563 ended_ms: None,
2564 }
2565 }
2566
2567 #[test]
2568 fn output_append_continues_last_line() {
2569 let mut st = State::new();
2570 let mut seq = 0;
2571 let mut feed = |ev: Event| {
2572 seq += 1;
2573 st.apply(&rec(seq, ev));
2574 };
2575 let out = |text: &str| Event::Output {
2576 session: "s1".into(),
2577 text: text.into(),
2578 };
2579 let app = |text: &str| Event::OutputAppend {
2580 session: "s1".into(),
2581 text: text.into(),
2582 };
2583 feed(out("| a | b"));
2584 feed(app(" |\n| c"));
2585 feed(app(" | d |\n"));
2586 feed(out("next\n"));
2587 feed(out("tail"));
2589 feed(app("\n"));
2590 let lines: Vec<_> = st.transcripts["s1"].iter().cloned().collect();
2591 assert_eq!(lines, ["| a | b |", "| c | d |", "next", "tail"]);
2592 }
2593
2594 #[test]
2595 fn output_append_on_empty_transcript_starts_a_line() {
2596 let mut st = State::new();
2597 st.apply(&rec(
2598 1,
2599 Event::OutputAppend {
2600 session: "s1".into(),
2601 text: "x\n".into(),
2602 },
2603 ));
2604 let lines: Vec<_> = st.transcripts["s1"].iter().cloned().collect();
2605 assert_eq!(lines, ["x"]);
2606 }
2607
2608 #[test]
2609 fn fold_tracks_status_and_transcript() {
2610 let mut st = State::new();
2611 st.apply(&rec(
2612 1,
2613 Event::SessionStarted {
2614 session: crate::tests::sample_session("s1"),
2615 },
2616 ));
2617 st.apply(&rec(
2618 2,
2619 Event::Output {
2620 session: "s1".into(),
2621 text: "hello\nworld".into(),
2622 },
2623 ));
2624 st.apply(&rec(
2625 3,
2626 Event::SessionStatus {
2627 session: "s1".into(),
2628 status: SessionStatus::Busy,
2629 },
2630 ));
2631
2632 assert_eq!(st.seq, 3);
2633 assert_eq!(st.sessions["s1"].status, SessionStatus::Busy);
2634 let lines: Vec<_> = st.transcripts["s1"].iter().cloned().collect();
2635 assert_eq!(lines, vec!["hello".to_string(), "world".to_string()]);
2636 }
2637
2638 #[test]
2639 fn permission_lifecycle() {
2640 let mut st = State::new();
2641 st.apply(&rec(
2642 1,
2643 Event::SessionStarted {
2644 session: crate::tests::sample_session("s1"),
2645 },
2646 ));
2647 st.apply(&rec(
2648 2,
2649 Event::PermissionRequested {
2650 request: PermissionRequest {
2651 req: "r1".into(),
2652 session: "s1".into(),
2653 title: "Bash".into(),
2654 detail: "rm -rf /".into(),
2655 },
2656 },
2657 ));
2658 assert_eq!(st.sessions["s1"].status, SessionStatus::WaitingApproval);
2659 assert_eq!(st.pending_permissions.len(), 1);
2660
2661 st.apply(&rec(
2662 3,
2663 Event::PermissionResolved {
2664 session: "s1".into(),
2665 req: "r1".into(),
2666 decision: Decision::Allow,
2667 },
2668 ));
2669 assert!(st.pending_permissions.is_empty());
2670 }
2671
2672 #[test]
2673 fn question_requested_and_resolved() {
2674 let mut st = State::new();
2675 st.apply(&rec(
2676 1,
2677 Event::SessionStarted {
2678 session: crate::tests::sample_session("s1"),
2679 },
2680 ));
2681 st.apply(&rec(
2682 2,
2683 Event::QuestionRequested {
2684 question: UserQuestion {
2685 id: "q1".into(),
2686 session: "s1".into(),
2687 header: Some("Database".into()),
2688 question: "Which database?".into(),
2689 options: vec![
2690 QuestionOption::new("PostgreSQL", Some("Recommended")),
2691 QuestionOption::new("SQLite", None),
2692 ],
2693 multi_select: false,
2694 custom: true,
2695 group: None,
2696 },
2697 },
2698 ));
2699 assert_eq!(st.sessions["s1"].status, SessionStatus::WaitingApproval);
2700 assert_eq!(st.pending_questions.len(), 1);
2701 assert_eq!(st.pending_questions["q1"].options[0].label, "PostgreSQL");
2702
2703 st.apply(&rec(
2704 3,
2705 Event::QuestionResolved {
2706 session: "s1".into(),
2707 id: "q1".into(),
2708 answers: vec!["PostgreSQL".into()],
2709 },
2710 ));
2711 assert!(st.pending_questions.is_empty());
2712 }
2713
2714 #[test]
2715 fn session_exit_clears_pending_questions() {
2716 let mut st = State::new();
2717 st.apply(&rec(
2718 1,
2719 Event::SessionStarted {
2720 session: crate::tests::sample_session("s1"),
2721 },
2722 ));
2723 st.apply(&rec(
2724 2,
2725 Event::QuestionRequested {
2726 question: UserQuestion {
2727 id: "q1".into(),
2728 session: "s1".into(),
2729 header: None,
2730 question: "Pick one".into(),
2731 options: Vec::new(),
2732 multi_select: false,
2733 custom: true,
2734 group: None,
2735 },
2736 },
2737 ));
2738 assert_eq!(st.pending_questions.len(), 1);
2739
2740 st.apply(&rec(
2741 3,
2742 Event::SessionExited {
2743 session: "s1".into(),
2744 code: Some(0),
2745 },
2746 ));
2747 assert!(st.pending_questions.is_empty());
2748 }
2749
2750 #[test]
2751 fn session_cleared_resets_context_but_keeps_identity() {
2752 let mut st = State::new();
2753 let mut s = sample_session("s1");
2754 s.native_id = Some("nat".into());
2755 s.cost = Cost {
2756 usd: 1.5,
2757 input_tokens: 10,
2758 output_tokens: 20,
2759 };
2760 s.context = Some(ContextUsage {
2761 used: 5,
2762 window: None,
2763 });
2764 s.status_note = Some("note".into());
2765 s.tool_calls = 7;
2766 let label = s.label.clone();
2767 st.apply(&rec(1, Event::SessionStarted { session: s }));
2768 st.transcripts
2769 .entry("s1".into())
2770 .or_default()
2771 .push_back("❯ hi".into());
2772 st.apply(&rec(
2773 2,
2774 Event::SessionCleared {
2775 session: "s1".into(),
2776 },
2777 ));
2778 let s = &st.sessions["s1"];
2779 assert_eq!(s.native_id, None);
2780 assert_eq!(s.cost, Cost::default());
2781 assert_eq!(s.context, None);
2782 assert_eq!(s.status_note, None);
2783 assert_eq!(s.tool_calls, 0);
2784 assert_eq!(s.label, label, "label 應保留");
2785 assert!(!st.transcripts.contains_key("s1"));
2786 st.apply(&rec(
2788 3,
2789 Event::SessionNativeId {
2790 session: "s1".into(),
2791 native_id: "fresh".into(),
2792 },
2793 ));
2794 assert_eq!(st.sessions["s1"].native_id.as_deref(), Some("fresh"));
2795 }
2796
2797 #[test]
2798 fn agent_kind_roundtrip() {
2799 for k in AgentKind::builtins() {
2800 assert_eq!(AgentKind::parse(k.id()).as_ref(), Some(&k));
2801 }
2802 assert_eq!(
2803 AgentKind::parse("open_code").as_ref(),
2804 Some(&AgentKind::OpenCode)
2805 );
2806 assert_eq!(AgentKind::OpenCode.acp_command().unwrap().0, "opencode");
2807 assert!(AgentKind::Codex.acp_command().is_none());
2808 }
2809
2810 #[test]
2811 fn resolve_session_by_label_and_filter_inbox() {
2812 let mut st = State::new();
2813 let mut s1 = sample_session("ses_1");
2814 s1.label = "worker/impl".into();
2815 let mut s2 = sample_session("ses_2");
2816 s2.label = "worker/test".into();
2817 st.apply(&rec(1, Event::SessionStarted { session: s1 }));
2818 st.apply(&rec(2, Event::SessionStarted { session: s2 }));
2819
2820 assert_eq!(
2821 st.resolve_session_id("worker/impl"),
2822 Some("ses_1".to_string())
2823 );
2824 assert_eq!(
2825 st.resolve_session_id("@worker/test"),
2826 Some("ses_2".to_string())
2827 );
2828
2829 st.apply(&rec(
2830 3,
2831 Event::BusMessage {
2832 message: BusMessage {
2833 id: "m1".into(),
2834 from: "ses_2".into(),
2835 to: Target::Direct("worker/impl".into()),
2836 kind: MsgKind::Question,
2837 body: "API shape?".into(),
2838 reply_to: None,
2839 ts: 10,
2840 },
2841 },
2842 ));
2843 st.apply(&rec(
2844 4,
2845 Event::BusMessage {
2846 message: BusMessage {
2847 id: "m2".into(),
2848 from: "ses_1".into(),
2849 to: Target::Broadcast,
2850 kind: MsgKind::Chat,
2851 body: "ready".into(),
2852 reply_to: None,
2853 ts: 11,
2854 },
2855 },
2856 ));
2857
2858 let inbox1 = st.inbox_for("ses_1", None);
2859 assert_eq!(inbox1.len(), 1);
2860 assert_eq!(inbox1[0].id, "m1");
2861
2862 let inbox1_after = st.inbox_for("ses_1", Some("m1"));
2863 assert!(inbox1_after.is_empty());
2864
2865 let inbox2 = st.inbox_for("ses_2", None);
2866 assert_eq!(inbox2.len(), 1);
2867 assert_eq!(inbox2[0].id, "m2");
2868 }
2869
2870 #[test]
2871 fn policy_engine_and_secret_redaction() {
2872 let policy = PolicyEngine::default();
2873 assert_eq!(
2874 policy.evaluate("Bash", "rm -rf / --no-preserve-root"),
2875 Some(Decision::Deny)
2876 );
2877 assert_eq!(
2878 policy.evaluate("Read", "src/main.rs"),
2879 Some(Decision::Allow)
2880 );
2881 assert_eq!(policy.evaluate("Bash", "cargo test"), None);
2882
2883 let custom = PolicyEngine::parse_toml(
2884 r#"
2885 allow = ["cargo test", "Read"]
2886 deny = ["curl http"]
2887 "#,
2888 );
2889 assert_eq!(custom.evaluate("Bash", "cargo test"), Some(Decision::Allow));
2890 assert_eq!(
2891 custom.evaluate("Bash", "curl http://evil"),
2892 Some(Decision::Deny)
2893 );
2894
2895 let raw = "key is sk-1234567890abcdefghij and ghp_abcdefghijklmnopqrst1234";
2896 let scrubbed = redact_secrets(raw);
2897 assert!(scrubbed.contains("sk-<REDACTED>"));
2898 assert!(scrubbed.contains("ghp_<REDACTED>"));
2899 assert!(!scrubbed.contains("1234567890abcdefghij"));
2900 }
2901
2902 #[test]
2903 fn redact_secrets_tricky_input() {
2904 assert_eq!(redact_secrets(""), "");
2905 assert_eq!(redact_secrets("sk-short"), "sk-short");
2906 assert_eq!(
2907 redact_secrets("金鑰 sk-1234567890abcdefghij 結束"),
2908 "金鑰 sk-<REDACTED> 結束"
2909 );
2910 assert_eq!(
2911 redact_secrets("🦀 ghp_1234567890abcdefghij 🦀"),
2912 "🦀 ghp_<REDACTED> 🦀"
2913 );
2914 assert_eq!(redact_secrets("sk-"), "sk-");
2915 assert_eq!(redact_secrets("ghp_12345678901"), "ghp_12345678901");
2916 assert_eq!(redact_secrets("ghp_123456789012"), "ghp_<REDACTED>");
2917 assert_eq!(redact_secrets("xoxb-123456789012"), "xoxb-<REDACTED>");
2918 assert_eq!(
2919 redact_secrets("github_pat_123456789012"),
2920 "github_pat_<REDACTED>"
2921 );
2922 assert_eq!(redact_secrets("gho_123456789012"), "gho_<REDACTED>");
2923 assert_eq!(redact_secrets("ghu_123456789012"), "ghu_<REDACTED>");
2924 assert_eq!(redact_secrets("glpat-123456789012"), "glpat-<REDACTED>");
2925 assert_eq!(redact_secrets("xoxp-123456789012"), "xoxp-<REDACTED>");
2926 assert_eq!(redact_secrets("AIza123456789012"), "AIza<REDACTED>");
2927 assert_eq!(redact_secrets("AIzashort"), "AIzashort");
2928 }
2929
2930 #[test]
2931 fn session_model_event_updates_state() {
2932 let mut st = State::new();
2933 st.apply(&Record {
2934 seq: 1,
2935 ts: 0,
2936 event: Event::SessionStarted {
2937 session: crate::tests::sample_session("s1"),
2938 },
2939 });
2940 st.apply(&Record {
2941 seq: 2,
2942 ts: 0,
2943 event: Event::SessionModel {
2944 session: "s1".into(),
2945 model: "opus".into(),
2946 },
2947 });
2948 assert_eq!(st.sessions["s1"].model.as_deref(), Some("opus"));
2949 }
2950
2951 #[test]
2952 fn native_id_event_updates_state_and_old_json_parses_without_it() {
2953 let mut st = State::new();
2954 st.apply(&rec(
2955 1,
2956 Event::SessionStarted {
2957 session: sample_session("s1"),
2958 },
2959 ));
2960 assert_eq!(st.sessions["s1"].native_id, None);
2961 st.apply(&rec(
2962 2,
2963 Event::SessionNativeId {
2964 session: "s1".into(),
2965 native_id: "abc".into(),
2966 },
2967 ));
2968 assert_eq!(st.sessions["s1"].native_id.as_deref(), Some("abc"));
2969 st.apply(&rec(
2971 3,
2972 Event::SessionNativeId {
2973 session: "s1".into(),
2974 native_id: "def".into(),
2975 },
2976 ));
2977 assert_eq!(st.sessions["s1"].native_id.as_deref(), Some("def"));
2978
2979 let mut v = serde_json::to_value(sample_session("old")).unwrap();
2981 v.as_object_mut().unwrap().remove("native_id");
2982 let s: Session = serde_json::from_value(v).unwrap();
2983 assert_eq!(s.native_id, None);
2984 }
2985
2986 #[test]
2987 fn log_health_event_updates_state_and_defaults_to_true() {
2988 let mut st = State::new();
2989 assert!(st.log_ok);
2990 st.apply(&rec(1, Event::LogHealth { ok: false }));
2991 assert!(!st.log_ok);
2992 st.apply(&rec(2, Event::LogHealth { ok: true }));
2993 assert!(st.log_ok);
2994 }
2995
2996 #[test]
2997 fn old_session_json_without_permission_parses() {
2998 let mut v = serde_json::to_value(sample_session("s1")).unwrap();
2999 v.as_object_mut().unwrap().remove("permission");
3000 let s: Session = serde_json::from_value(v).unwrap();
3001 assert_eq!(s.permission, PermissionPolicy::Auto);
3002 }
3003
3004 #[test]
3005 fn allow_rules_match_whole_words_only() {
3006 let p = PolicyEngine::default();
3007 assert_eq!(
3009 p.evaluate("cat README.md", r#"{"command":"cat README.md"}"#),
3010 None
3011 );
3012 assert_eq!(p.evaluate("Read", "{}"), Some(Decision::Allow));
3013 assert_eq!(
3014 p.evaluate("bash", r#"{"command":"git status -s"}"#),
3015 Some(Decision::Allow)
3016 );
3017 assert_eq!(p.evaluate("bash", r#"{"command":"git statusx"}"#), None);
3018 }
3019
3020 #[test]
3021 fn deny_beats_allow_and_repo_cannot_remove_deny() {
3022 let p = PolicyEngine::default();
3023 assert_eq!(
3024 p.evaluate("bash", r#"{"command":"git status && git push --force"}"#),
3025 Some(Decision::Deny)
3026 );
3027 let local = PolicyEngine {
3028 allow: vec![],
3029 deny: vec!["curl".into()],
3030 };
3031 let m = p.merged_with(&local);
3032 assert!(m.deny.contains(&"git push --force".to_string()));
3033 assert!(m.deny.contains(&"curl".to_string()));
3034 }
3035
3036 #[test]
3037 fn tool_calls_render_readable_summary_and_results() {
3038 let mut st = State::new();
3039 st.apply(&rec(
3040 1,
3041 Event::SessionStarted {
3042 session: crate::tests::sample_session("s1"),
3043 },
3044 ));
3045 st.apply(&rec(
3046 2,
3047 Event::ToolCall {
3048 session: "s1".into(),
3049 name: "Bash".into(),
3050 input: r#"{"command":"git status\n -s","description":"x"}"#.into(),
3051 ok: None,
3052 output: None,
3053 },
3054 ));
3055 st.apply(&rec(
3056 3,
3057 Event::ToolCall {
3058 session: "s1".into(),
3059 name: String::new(),
3060 input: String::new(),
3061 ok: Some(false),
3062 output: Some("fatal: not a repo\nmore".into()),
3063 },
3064 ));
3065 let t: Vec<_> = st.transcripts["s1"].iter().cloned().collect();
3066 assert_eq!(t[0], "▸ Bash: git status -s");
3067 assert_eq!(t[1], " ✗ fatal: not a repo …(+1 行)");
3068 }
3069
3070 #[test]
3071 fn prompts_from_others_are_marked_with_source() {
3072 let mut st = State::new();
3073 st.apply(&rec(
3074 1,
3075 Event::UserPrompt {
3076 session: "w".into(),
3077 text: "do it".into(),
3078 from: Some("ghost".into()),
3079 },
3080 ));
3081 st.apply(&rec(
3082 2,
3083 Event::UserPrompt {
3084 session: "w".into(),
3085 text: "提醒\n第二行".into(),
3086 from: Some(PROMPT_FROM_ERTANGLE.into()),
3087 },
3088 ));
3089 st.apply(&rec(
3090 3,
3091 Event::UserPrompt {
3092 session: "w".into(),
3093 text: "mine".into(),
3094 from: None,
3095 },
3096 ));
3097 let t: Vec<&str> = st.transcripts["w"].iter().map(String::as_str).collect();
3098 assert_eq!(
3099 t,
3100 ["» [ghost] do it", "» [ertangle] 提醒", " 第二行", "❯ mine"]
3101 );
3102 assert_eq!(parse_prompt_line(t[0]), Some((Some("ghost"), "do it")));
3103 assert_eq!(parse_prompt_line(t[3]), Some((None, "mine")));
3104 assert_eq!(parse_prompt_line("» quote"), None);
3105 assert_eq!(parse_prompt_line("plain"), None);
3106 let old: Event =
3108 serde_json::from_str(r#"{"kind":"user_prompt","session":"w","text":"x"}"#).unwrap();
3109 assert!(matches!(old, Event::UserPrompt { from: None, .. }));
3110 }
3111
3112 #[test]
3113 fn record_wire_format_is_flat() {
3114 let r = Record {
3116 seq: 7,
3117 ts: 1,
3118 event: Event::Output {
3119 session: "s1".into(),
3120 text: "hi".into(),
3121 },
3122 };
3123 let v: serde_json::Value = serde_json::to_value(&r).unwrap();
3124 assert_eq!(v["seq"], 7);
3125 assert_eq!(v["kind"], "output");
3126 assert_eq!(v["session"], "s1");
3127 assert!(v.get("event").is_none());
3128 }
3129
3130 #[test]
3131 fn tool_calls_count_only_start_events() {
3132 let mut st = State::new();
3133 st.apply(&rec(
3134 1,
3135 Event::SessionStarted {
3136 session: sample_session("s1"),
3137 },
3138 ));
3139 let call = |ok: Option<bool>, name: &str| Event::ToolCall {
3140 session: "s1".into(),
3141 name: name.into(),
3142 input: String::new(),
3143 ok,
3144 output: None,
3145 };
3146 st.apply(&rec(2, call(None, "Bash")));
3147 st.apply(&rec(3, call(Some(true), "Bash")));
3148 st.apply(&rec(4, call(None, "Read")));
3149 st.apply(&rec(5, call(None, "")));
3151 assert_eq!(st.sessions["s1"].tool_calls, 2);
3152 }
3153
3154 #[test]
3155 fn active_tools_and_bg_procs_lifecycle() {
3156 assert!(is_subagent_tool("Task"));
3157 assert!(is_subagent_tool("Agent"));
3158 assert!(is_subagent_tool("invoke_subagent"));
3159 assert!(is_subagent_tool("spawn_agent"));
3160 assert!(!is_subagent_tool("Bash"));
3161
3162 let mut st = State::new();
3163 st.apply(&rec(
3164 1,
3165 Event::SessionStarted {
3166 session: sample_session("s1"),
3167 },
3168 ));
3169
3170 st.apply(&rec(
3172 2,
3173 Event::ToolCall {
3174 session: "s1".into(),
3175 name: "Bash".into(),
3176 input: r#"{"command":"cargo test"}"#.into(),
3177 ok: None,
3178 output: None,
3179 },
3180 ));
3181 assert_eq!(st.sessions["s1"].active_tools.len(), 1);
3182 assert_eq!(st.sessions["s1"].active_tools[0].name, "Bash");
3183 assert!(!st.sessions["s1"].active_tools[0].is_subagent);
3184
3185 st.apply(&rec(
3187 3,
3188 Event::ToolCall {
3189 session: "s1".into(),
3190 name: "Task".into(),
3191 input: r#"{"prompt":"review"}"#.into(),
3192 ok: None,
3193 output: None,
3194 },
3195 ));
3196 assert_eq!(st.sessions["s1"].active_tools.len(), 2);
3197 assert!(st.sessions["s1"].active_tools[1].is_subagent);
3198
3199 st.apply(&rec(
3201 4,
3202 Event::ToolCall {
3203 session: "s1".into(),
3204 name: "Bash".into(),
3205 input: String::new(),
3206 ok: Some(true),
3207 output: Some("ok".into()),
3208 },
3209 ));
3210 assert_eq!(st.sessions["s1"].active_tools.len(), 1);
3211 assert_eq!(st.sessions["s1"].active_tools[0].name, "Task");
3212
3213 st.apply(&rec(
3215 5,
3216 Event::SessionStatus {
3217 session: "s1".into(),
3218 status: SessionStatus::Idle,
3219 },
3220 ));
3221 assert!(st.sessions["s1"].active_tools.is_empty());
3222
3223 st.apply(&rec(
3225 6,
3226 Event::SessionBgProcs {
3227 session: "s1".into(),
3228 procs: vec![BgProc {
3229 pid: 1234,
3230 name: "node".into(),
3231 cmdline: "node server.js".into(),
3232 elapsed_secs: 15,
3233 }],
3234 },
3235 ));
3236 assert_eq!(st.sessions["s1"].bg_procs.len(), 1);
3237 assert_eq!(st.sessions["s1"].bg_procs[0].pid, 1234);
3238 }
3239
3240 #[test]
3241 fn export_markdown_includes_tree_tasks_cost_diff_and_redacts_secrets() {
3242 let mut st = State::new();
3243 let mut root = sample_session("root");
3244 root.label = "coord/main".into();
3245 root.role = Role::Coordinator;
3246 root.branch = Some("ertangle/main".into());
3247 root.status = SessionStatus::Exited;
3248 root.cost = Cost {
3249 usd: 1.25,
3250 input_tokens: 1000,
3251 output_tokens: 200,
3252 };
3253 st.apply(&rec(1, Event::SessionStarted { session: root }));
3254
3255 for (id, label, usd) in [("c1", "worker/impl", 0.5), ("c2", "reviewer/code", 0.25)] {
3256 let mut child = sample_session(id);
3257 child.label = label.into();
3258 child.parent = Some("root".into());
3259 child.role = if id == "c2" {
3260 Role::Reviewer
3261 } else {
3262 Role::Worker
3263 };
3264 child.status = SessionStatus::Exited;
3265 child.cost = Cost {
3266 usd,
3267 input_tokens: 100,
3268 output_tokens: 20,
3269 };
3270 st.apply(&rec(2, Event::SessionStarted { session: child }));
3271 }
3272 st.apply(&rec(
3273 3,
3274 Event::TaskChanged {
3275 task: Task {
3276 id: "task_1".into(),
3277 title: "完成匯出功能".into(),
3278 detail: String::new(),
3279 status: TaskStatus::Done,
3280 assignee: Some("c1".into()),
3281 created_by: Some("root".into()),
3282 depends_on: vec![],
3283 updated_ms: 0,
3284 },
3285 },
3286 ));
3287 st.apply(&rec(
3288 4,
3289 Event::UserPrompt {
3290 session: "root".into(),
3291 text: "API key: sk-1234567890abcdefghijklmnop".into(),
3292 from: None,
3293 },
3294 ));
3295 st.apply(&rec(
3296 5,
3297 Event::Output {
3298 session: "c1".into(),
3299 text: "done".into(),
3300 },
3301 ));
3302
3303 let md = st
3304 .export_markdown("coord/main", true, Some("diff --git a/x b/x\n+new"))
3305 .unwrap();
3306 assert!(md.starts_with("# 協作報告:coord/main"));
3307 assert!(md.contains("子 Session 階層"), "{md}");
3308 assert!(
3309 md.contains("worker/impl") && md.contains("reviewer/code"),
3310 "{md}"
3311 );
3312 assert!(md.contains("$2.0000"), "{md}"); assert!(md.contains("1200 in / 240 out"), "{md}");
3314 assert!(md.contains("task_1") && md.contains("完成匯出功能"), "{md}");
3315 assert!(md.contains("```diff") && md.contains("+new"), "{md}");
3316 assert!(md.contains("sk-<REDACTED>"), "{md}");
3317 assert!(!md.contains("sk-1234567890abcdefghijklmnop"), "{md}");
3318
3319 let md_flat = st.export_markdown("root", false, None).unwrap();
3321 assert!(!md_flat.contains("子 Session 階層"), "{md_flat}");
3322 assert!(!md_flat.contains("### worker/impl"), "{md_flat}");
3323 assert!(md_flat.contains("$1.2500"), "{md_flat}");
3324
3325 assert!(st.export_markdown("nope", true, None).is_err());
3326 }
3327}
3328
3329#[cfg(test)]
3330mod attachment_tests {
3331 use super::*;
3332
3333 #[test]
3334 fn limit_detection_matches_real_messages_but_not_normal_errors() {
3335 assert!(looks_like_limit(
3336 "You've hit your 5-hour limit · resets 4:30am (Asia/Taipei)"
3337 ));
3338 assert!(looks_like_limit("Error: 429 Too Many Requests"));
3339 assert!(looks_like_limit("exceeded your current quota"));
3340 assert!(!looks_like_limit("File not found: limits.rs"));
3341 assert!(!looks_like_limit("compile error"));
3342 }
3343
3344 #[test]
3345 fn quota_summary_and_reset_handling() {
3346 let q = Quota {
3347 agent: "claude".into(),
3348 windows: vec![
3349 QuotaWindow {
3350 name: "5h".into(),
3351 used_percent: 39.0,
3352 resets_at_ms: Some(10_000_000 + 80 * 60_000),
3353 },
3354 QuotaWindow {
3355 name: "7d".into(),
3356 used_percent: 22.0,
3357 resets_at_ms: Some(1),
3358 },
3359 ],
3360 reached: false,
3361 warning: false,
3362 updated_ms: 0,
3363 };
3364 let s = q.summary(10_000_000);
3365 assert!(s.contains("5h 39% (重置 1h20m)"), "{s}");
3366 assert!(s.contains("7d 已重置"));
3367 assert_eq!(window_name(300), "5h");
3368 assert_eq!(window_name(43200), "30d");
3369 assert_eq!(format_remaining(30_000), "<1m");
3370 assert_eq!(format_remaining(90 * 60_000), "1h30m");
3371 assert_eq!(format_remaining(50 * 3_600_000), "2d2h");
3372 }
3373
3374 #[test]
3375 fn quota_maxima_exclude_inactive_and_reset_windows() {
3376 let q = Quota {
3377 agent: "antigravity".into(),
3378 windows: vec![
3379 QuotaWindow {
3380 name: "3p-7d".into(),
3381 used_percent: 90.33,
3382 resets_at_ms: Some(300),
3383 },
3384 QuotaWindow {
3385 name: "7d".into(),
3386 used_percent: 61.0,
3387 resets_at_ms: Some(300),
3388 },
3389 QuotaWindow {
3390 name: "5h".into(),
3391 used_percent: 99.0,
3392 resets_at_ms: Some(100),
3393 },
3394 ],
3395 reached: false,
3396 warning: false,
3397 updated_ms: 0,
3398 };
3399
3400 assert_eq!(q.max_used(), 99.0);
3401 assert_eq!(q.max_used_live(200), 61.0);
3402 assert_eq!(q.max_used_live(300), 0.0);
3403 assert!(q.summary(0).contains("3p-7d 90%"));
3404 }
3405
3406 #[test]
3407 fn quota_is_reached_clears_after_exhausted_window_resets() {
3408 let mut q = Quota {
3409 agent: "claude".into(),
3410 windows: vec![
3411 QuotaWindow {
3412 name: "5h".into(),
3413 used_percent: 100.0,
3414 resets_at_ms: Some(100),
3415 },
3416 QuotaWindow {
3417 name: "7d".into(),
3418 used_percent: 51.0,
3419 resets_at_ms: Some(500),
3420 },
3421 ],
3422 reached: true,
3423 warning: false,
3424 updated_ms: 0,
3425 };
3426
3427 assert!(q.is_reached(50));
3429 let sum_before = q.summary(50);
3430 assert!(sum_before.contains("✗額度已滿"), "{sum_before}");
3431
3432 assert!(!q.is_reached(150));
3434 let sum_after = q.summary(150);
3435 assert!(!sum_after.contains("✗額度已滿"), "{sum_after}");
3436 assert!(sum_after.contains("5h 已重置"), "{sum_after}");
3437
3438 q.windows[1].used_percent = 100.0;
3440 assert!(q.is_reached(150));
3441 assert!(q.summary(150).contains("✗額度已滿"));
3442
3443 let empty_reached = Quota {
3445 agent: "claude".into(),
3446 windows: vec![],
3447 reached: true,
3448 warning: false,
3449 updated_ms: 0,
3450 };
3451 assert!(empty_reached.is_reached(150));
3452
3453 let empty_not_reached = Quota {
3454 agent: "claude".into(),
3455 windows: vec![],
3456 reached: false,
3457 warning: false,
3458 updated_ms: 0,
3459 };
3460 assert!(!empty_not_reached.is_reached(150));
3461 }
3462
3463 #[test]
3464 fn third_party_windows_remain_active_for_other_agents() {
3465 let q = Quota {
3466 agent: "claude".into(),
3467 windows: vec![QuotaWindow {
3468 name: "3p-7d".into(),
3469 used_percent: 90.0,
3470 resets_at_ms: None,
3471 }],
3472 reached: false,
3473 warning: false,
3474 updated_ms: 0,
3475 };
3476 assert_eq!(q.max_used(), 90.0);
3477 assert_eq!(q.max_used_live(0), 90.0);
3478 }
3479
3480 #[test]
3481 fn context_usage_formats_and_keeps_last_used_when_only_window_arrives() {
3482 assert_eq!(human_tokens(950), "950");
3483 assert_eq!(human_tokens(36_267), "36k");
3484 assert_eq!(human_tokens(1_000_000), "1M");
3485 assert_eq!(human_tokens(1_500_000), "1.5M");
3486 let c = ContextUsage {
3487 used: 36_000,
3488 window: Some(1_000_000),
3489 };
3490 assert_eq!(c.short(), "36k/1M 4%");
3491 assert_eq!(
3492 ContextUsage {
3493 used: 5_000,
3494 window: None
3495 }
3496 .short(),
3497 "5k"
3498 );
3499 let mut st = State::new();
3500 st.apply(&Record {
3501 seq: 1,
3502 ts: 0,
3503 event: Event::SessionStarted {
3504 session: crate::tests::sample_session("s1"),
3505 },
3506 });
3507 st.apply(&Record {
3508 seq: 2,
3509 ts: 0,
3510 event: Event::SessionContext {
3511 session: "s1".into(),
3512 used: 36_000,
3513 window: None,
3514 },
3515 });
3516 st.apply(&Record {
3517 seq: 3,
3518 ts: 0,
3519 event: Event::SessionContext {
3520 session: "s1".into(),
3521 used: 0,
3522 window: Some(200_000),
3523 },
3524 });
3525 let c = st.sessions["s1"].context.unwrap();
3526 assert_eq!((c.used, c.window), (36_000, Some(200_000)));
3527 st.apply(&Record {
3529 seq: 4,
3530 ts: 0,
3531 event: Event::SessionContext {
3532 session: "s1".into(),
3533 used: 50_000,
3534 window: None,
3535 },
3536 });
3537 assert_eq!(st.sessions["s1"].context.unwrap().window, Some(200_000));
3538 }
3539
3540 #[test]
3541 fn base64_matches_known_vectors() {
3542 assert_eq!(base64_encode(b""), "");
3543 assert_eq!(base64_encode(b"f"), "Zg==");
3544 assert_eq!(base64_encode(b"fo"), "Zm8=");
3545 assert_eq!(base64_encode(b"foo"), "Zm9v");
3546 assert_eq!(base64_encode(b"foobar"), "Zm9vYmFy");
3547 }
3548
3549 #[test]
3550 fn compose_text_embeds_files_and_notes_images() {
3551 let f = Attachment {
3552 name: "a.rs".into(),
3553 mime: "text/plain".into(),
3554 text: Some("fn main() {}\n".into()),
3555 ..Default::default()
3556 };
3557 let img = Attachment {
3558 name: "p.png".into(),
3559 mime: "image/png".into(),
3560 path: Some("/tmp/p.png".into()),
3561 data: Some("AAAA".into()),
3562 ..Default::default()
3563 };
3564 let t = compose_text("看", &[f.clone(), img.clone()], true);
3565 assert!(t.contains("```\nfn main() {}\n```") && t.contains("圖片附件:p.png"));
3566 let t2 = compose_text("看", &[f, img], false);
3567 assert!(!t2.contains("圖片附件"));
3568 }
3569
3570 #[test]
3571 fn old_session_json_without_budget_fields_parses() {
3572 let mut val = serde_json::to_value(crate::tests::sample_session("s1")).unwrap();
3573 let obj = val.as_object_mut().unwrap();
3574 obj.remove("budget_usd");
3575 obj.remove("over_budget");
3576 let parsed: Session = serde_json::from_value(val).unwrap();
3577 assert_eq!(parsed.budget_usd, None);
3578 assert!(!parsed.over_budget);
3579 }
3580
3581 #[test]
3582 fn old_session_json_without_handed_off_to_parses() {
3583 let mut val = serde_json::to_value(crate::tests::sample_session("s1")).unwrap();
3584 val.as_object_mut().unwrap().remove("handed_off_to");
3585 let parsed: Session = serde_json::from_value(val).unwrap();
3586 assert_eq!(parsed.handed_off_to, None);
3587 }
3588
3589 fn handoff(st: &mut State, seq: u64, from: &str, to: &str) {
3590 st.apply(&Record {
3591 seq,
3592 ts: 0,
3593 event: Event::SessionHandedOff {
3594 from: from.into(),
3595 to: to.into(),
3596 },
3597 });
3598 }
3599
3600 #[test]
3601 fn successor_follows_chain_and_survives_cycles() {
3602 let mut st = State::new();
3603 for (i, id) in ["a", "b", "c"].into_iter().enumerate() {
3604 st.apply(&Record {
3605 seq: i as u64,
3606 ts: 0,
3607 event: Event::SessionStarted {
3608 session: crate::tests::sample_session(id),
3609 },
3610 });
3611 }
3612 assert_eq!(st.successor_of("a"), "a");
3613 handoff(&mut st, 10, "a", "b");
3614 assert_eq!(st.successor_of("a"), "b");
3615 handoff(&mut st, 11, "b", "c");
3616 assert_eq!(st.successor_of("a"), "c");
3617 assert_eq!(st.successor_of("unknown"), "unknown");
3618 handoff(&mut st, 12, "c", "a");
3620 assert_eq!(st.successor_of("a"), "c");
3621 handoff(&mut st, 13, "a", "a");
3623 assert_eq!(st.successor_of("a"), "a");
3624 }
3625
3626 #[test]
3627 fn session_budget_formatting_and_state_events() {
3628 let mut s = crate::tests::sample_session("s1");
3629 s.cost.usd = 1.2;
3630 assert_eq!(s.format_budget(), None);
3631 s.budget_usd = Some(5.0);
3632 assert_eq!(s.format_budget().as_deref(), Some("$1.20/$5"));
3633 s.budget_usd = Some(2.5);
3634 assert_eq!(s.format_budget().as_deref(), Some("$1.20/$2.50"));
3635
3636 let mut st = State::new();
3637 st.apply(&Record {
3638 seq: 1,
3639 ts: 0,
3640 event: Event::SessionStarted { session: s },
3641 });
3642 st.apply(&Record {
3643 seq: 2,
3644 ts: 0,
3645 event: Event::SessionOverBudget {
3646 session: "s1".into(),
3647 spent: 2.5,
3648 limit: 2.5,
3649 },
3650 });
3651 assert!(st.sessions["s1"].over_budget);
3652
3653 st.apply(&Record {
3654 seq: 3,
3655 ts: 0,
3656 event: Event::SessionBudget {
3657 session: "s1".into(),
3658 budget_usd: Some(10.0),
3659 },
3660 });
3661 assert!(!st.sessions["s1"].over_budget);
3662 assert_eq!(st.sessions["s1"].budget_usd, Some(10.0));
3663 }
3664
3665 #[test]
3666 fn removed_resumable_session_is_archived_and_resolvable() {
3667 let mut st = State::new();
3668 let mut s = crate::tests::sample_session("ses_arch");
3669 s.label = "worker/arch".into();
3670 s.native_id = Some("nat-arch-1".into());
3671 st.apply(&Record {
3672 seq: 1,
3673 ts: 100,
3674 event: Event::SessionStarted { session: s },
3675 });
3676 st.apply(&Record {
3677 seq: 2,
3678 ts: 101,
3679 event: Event::UserPrompt {
3680 session: "ses_arch".into(),
3681 text: "請幫我檢查這份報表".into(),
3682 from: None,
3683 },
3684 });
3685 st.apply(&Record {
3686 seq: 3,
3687 ts: 102,
3688 event: Event::SessionRemoved {
3689 session: "ses_arch".into(),
3690 },
3691 });
3692 assert!(!st.sessions.contains_key("ses_arch"));
3693 let arch = st
3694 .archived_sessions
3695 .get("ses_arch")
3696 .expect("具備 native_id 的已移除 session 應被封存");
3697 assert_eq!(arch.status, SessionStatus::Exited);
3698 assert_eq!(arch.status_note.as_deref(), Some("請幫我檢查這份報表"));
3699 assert!(
3700 st.transcripts.contains_key("ses_arch"),
3701 "封存的 session 應保留逐字稿"
3702 );
3703
3704 for query in ["ses_arch", "worker/arch", "nat-arch-1"] {
3705 let (found, is_arch) = st
3706 .resolve_resumable_session(query)
3707 .unwrap_or_else(|| panic!("應能以 {query} 解析封存的 session"));
3708 assert!(is_arch);
3709 assert_eq!(found.id, "ses_arch");
3710 }
3711
3712 st.apply(&Record {
3714 seq: 4,
3715 ts: 103,
3716 event: Event::SessionStarted {
3717 session: arch.clone(),
3718 },
3719 });
3720 assert!(!st.archived_sessions.contains_key("ses_arch"));
3721 assert!(st.sessions.contains_key("ses_arch"));
3722 }
3723}
3724
3725#[cfg(test)]
3726mod inbox_cursor_tests {
3727 use super::*;
3728
3729 #[test]
3730 fn inbox_read_event_sets_cursor_and_roundtrips() {
3731 let mut st = State::new();
3732 st.apply(&Record {
3733 seq: 1,
3734 ts: 0,
3735 event: Event::InboxRead {
3736 session: "s1".into(),
3737 msg: "m9".into(),
3738 },
3739 });
3740 assert_eq!(st.inbox_cursors.get("s1").map(String::as_str), Some("m9"));
3741 let back: State = serde_json::from_str(&serde_json::to_string(&st).unwrap()).unwrap();
3742 assert_eq!(back.inbox_cursors, st.inbox_cursors);
3743 }
3744}
3745
3746#[cfg(test)]
3747mod archive_retention_tests {
3748 use super::*;
3749
3750 const DAY: u64 = 86_400_000;
3751
3752 fn archived(id: &str, ended_ms: Option<u64>, created_ms: u64) -> Session {
3753 let mut s = crate::tests::sample_session(id);
3754 s.created_ms = created_ms;
3755 s.ended_ms = ended_ms;
3756 s
3757 }
3758
3759 fn rec(seq: u64, ts: u64, event: Event) -> Record {
3760 Record { seq, ts, event }
3761 }
3762
3763 #[test]
3764 fn ended_ms_is_set_once_on_exit_and_cleared_when_live_again() {
3765 let mut st = State::new();
3766 st.apply(&rec(
3767 1,
3768 10,
3769 Event::SessionStarted {
3770 session: crate::tests::sample_session("a"),
3771 },
3772 ));
3773 st.apply(&rec(
3774 2,
3775 100,
3776 Event::SessionExited {
3777 session: "a".into(),
3778 code: Some(0),
3779 },
3780 ));
3781 assert_eq!(st.sessions["a"].ended_ms, Some(100));
3782 st.apply(&rec(
3783 3,
3784 200,
3785 Event::SessionStatus {
3786 session: "a".into(),
3787 status: SessionStatus::Failed,
3788 },
3789 ));
3790 assert_eq!(st.sessions["a"].ended_ms, Some(100), "first end time wins");
3791 st.apply(&rec(
3792 4,
3793 300,
3794 Event::SessionStatus {
3795 session: "a".into(),
3796 status: SessionStatus::Idle,
3797 },
3798 ));
3799 assert_eq!(st.sessions["a"].ended_ms, None);
3800 }
3801
3802 #[test]
3803 fn retention_drops_entries_older_than_max_days_by_ended_time() {
3804 let mut st = State::new();
3805 let now = 100 * DAY;
3806 st.archived_sessions
3808 .insert("fresh".into(), archived("fresh", Some(now - DAY), 0));
3809 st.archived_sessions
3810 .insert("old".into(), archived("old", Some(now - 31 * DAY), 0));
3811 st.archived_sessions
3813 .insert("legacy".into(), archived("legacy", None, now - 40 * DAY));
3814 let mut dropped = st.archived_to_prune(now, 100, 30);
3815 dropped.sort();
3816 assert_eq!(dropped, vec!["legacy".to_string(), "old".to_string()]);
3817 }
3818
3819 #[test]
3820 fn retention_keeps_newest_entries_within_count_limit() {
3821 let mut st = State::new();
3822 let now = 10 * DAY;
3823 for (i, id) in ["a", "b", "c"].into_iter().enumerate() {
3824 st.archived_sessions
3825 .insert(id.into(), archived(id, Some(now - 3 + i as u64), 0));
3826 }
3827 assert_eq!(st.archived_to_prune(now, 2, 30), vec!["a".to_string()]);
3828 assert!(st.archived_to_prune(now, 3, 30).is_empty());
3829 }
3830
3831 #[test]
3832 fn archive_pruned_event_removes_entries_and_transcripts() {
3833 let mut st = State::new();
3834 st.archived_sessions
3835 .insert("x".into(), archived("x", Some(1), 0));
3836 st.transcripts
3837 .insert("x".into(), VecDeque::from(["l".to_string()]));
3838 st.apply(&rec(
3839 1,
3840 2,
3841 Event::ArchivePruned {
3842 sessions: vec!["x".into()],
3843 },
3844 ));
3845 assert!(st.archived_sessions.is_empty());
3846 assert!(!st.transcripts.contains_key("x"));
3847 }
3848
3849 #[test]
3850 fn version_with_hash_starts_with_pkg_version() {
3851 assert!(VERSION_WITH_HASH.starts_with(env!("CARGO_PKG_VERSION")));
3852 }
3853}