Skip to content

Computer use CLI for AI agents

feat: make sessions the first-class trace container

Lahfir35fa914b52bb
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 97877e2bd..f57f8b62c 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,10 @@
## Unreleased
+### Refactor
+
+* make sessions the first-class trace container: `session start/end/list/gc`, manifest-gated automatic JSONL segments under `sessions/<id>/trace/`, and `--trace <path>` override preserved ([#89](https://github.com/lahfir/agent-desktop/pull/89))
+
## [0.4.5](https://github.com/lahfir/agent-desktop/compare/v0.4.4...v0.4.5) (2026-06-30)
diff --git a/CLAUDE.md b/CLAUDE.md
index f481eeef8..734fcffdf 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -160,7 +160,7 @@ Batch is not a second dispatcher. `src/batch/mod.rs` deserializes JSON entries i
### Additive Phase Model
-- **Phase 1:** Foundation + macOS MVP (54 commands, core engine, macOS adapter)
+- **Phase 1:** Foundation + macOS MVP (55 commands, core engine, macOS adapter)
- **Phase 2:** Windows + Linux adapters, 10+ new commands — core untouched
- **Phase 3:** MCP server mode via `--mcp` flag — wraps existing commands
- **Phase 4:** Daemon, sessions, enterprise quality gates
@@ -327,6 +327,8 @@ The `error` object may also carry an optional `details` object (e.g. the actiona
- Progressive traversal: `--skeleton` clamps depth to 3, annotates truncated containers with `children_count`. Named/described containers at boundary receive refs as drill-down targets
- Drill-down: `--root @ref` starts from a previously-discovered ref with scoped invalidation (only that ref's subtree refs are replaced on re-drill)
- RefMap size check: write-side guard prevents >1MB refmap files
+- **Sessions:** `session start` creates a manifest-gated session under `~/.agent-desktop/sessions/<id>/`, sets `current_session`, and (by default) enables automatic trace segments. Bare `--session <id>` without a manifest scopes only the snapshot namespace — no surprise trace files
+- **Trace:** manifest `trace: on` writes per-process JSONL segments under `<session>/trace/<pid>-<procTs>.jsonl`; `--trace <path>` overrides to one file; activation resolves `--session` > `AGENT_DESKTOP_SESSION` > `current_session`
## PlatformAdapter Trait
@@ -367,11 +369,11 @@ for the actionability preflight (`get_live_*`), and `is_protected_process`
## Commands
-54 commands spanning App/Window, Observation, Interaction, Scroll, Keyboard,
-Mouse, Notifications (macOS), Clipboard, Wait, System, and Batch. The full
-surface and per-command reference live in `skills/agent-desktop/`. All 54 are
-implemented on macOS (Phase 1); Windows/Linux (Phase 2/3) target the same
-surface. Adding a command: see the Extensibility Pattern above.
+55 commands spanning App/Window, Observation, Interaction, Scroll, Keyboard,
+Mouse, Notifications (macOS), Clipboard, Wait, System (including `session`), and
+Batch. The full surface and per-command reference live in `skills/agent-desktop/`.
+All 55 are implemented on macOS (Phase 1); Windows/Linux (Phase 2/3) target the
+same surface. Adding a command: see the Extensibility Pattern above.
## Non-Goals
diff --git a/CONCEPTS.md b/CONCEPTS.md
index 685ead4dc..d90f53b82 100644
--- a/CONCEPTS.md
+++ b/CONCEPTS.md
@@ -45,9 +45,19 @@ Strict ref resolution rejects missing, stale, and ambiguous matches instead of g
## Coordination
### Session
-A coordination key for one agent or a coordinated group of agents that share a latest-snapshot pointer.
+An on-disk container under `~/.agent-desktop/sessions/<id>/` that owns snapshot refmaps, an optional trace directory, and a `session.json` manifest.
-Use sessions when callers intentionally omit `--snapshot` and want a shared latest observation. Explicit snapshot IDs remain the deterministic path for pinned actions and can be resolved without also passing the session.
+`session start` writes the manifest (`trace: on` unless `--no-trace`), pre-creates `trace/` when tracing is on, and sets `~/.agent-desktop/current_session`. Activating a session (via pointer, `AGENT_DESKTOP_SESSION`, or `--session`) relocates the latest-snapshot namespace as well as the trace sink. Bare `--session <id>` without a manifest remains snapshot-namespace-only for backward compatibility.
+
+Use sessions when callers intentionally omit `--snapshot` and want a shared latest observation — typically after `session start` for a coordinated run. Explicit snapshot IDs remain the deterministic path for pinned actions and can be resolved without also passing the session.
+
+### Session Manifest
+The `session.json` file describing one session: id, optional name, created/ended timestamps, and `trace: on|off`.
+
+Structured file tracing activates only when the manifest has `trace: on`. FFI adapters and bare `--session` ids without this manifest do not write trace segments.
+
+### Trace Segment
+One append-only JSONL file per OS process under `<session>/trace/<pid>-<procStartTs>.jsonl`, written lazily with atomic lines (`ts_ms`, monotonic `seq`, redacted fields). Explicit `--trace <path>` overrides to a single file.
### Protected Process
A session-critical operating-system process that agent-desktop refuses to close on every surface, because terminating it would break the user's desktop session.
@@ -93,4 +103,4 @@ The requirement that language bindings using refs follow the same strict resolut
## Relationships
-A session owns one latest-snapshot pointer. A snapshot persists a ref map and can be selected directly by snapshot ID. A ref resolves through strict ref resolution into live native evidence, then actionability decides whether a headless ref action can safely dispatch, and the action chain executes that dispatch under its own deadline with the interaction policy gating its physical steps. FFI ref-action parity keeps that same relationship true for language bindings.
+A session owns one latest-snapshot pointer, an optional manifest-gated trace directory, and persisted snapshot refmaps. A snapshot persists a ref map and can be selected directly by snapshot ID. A ref resolves through strict ref resolution into live native evidence, then actionability decides whether a headless ref action can safely dispatch, and the action chain executes that dispatch under its own deadline with the interaction policy gating its physical steps. FFI ref-action parity keeps that same relationship true for language bindings.
diff --git a/README.md b/README.md
index f50e137c3..25a3b9e2a 100644
--- a/README.md
+++ b/README.md
@@ -41,7 +41,7 @@
- **Native Rust CLI**: Fast, single binary, no runtime dependencies
- **C-ABI cdylib** (`libagent_desktop_ffi`): Load once from Python / Swift / Go / Ruby / Node / C instead of forking the CLI per call
-- **54 commands**: Observation, interaction, keyboard, mouse, notifications, clipboard, window management, plus a bundled `skills` doc loader
+- **55 commands**: Observation, interaction, keyboard, mouse, notifications, clipboard, window management, session lifecycle, plus a bundled `skills` doc loader
- **Progressive skeleton traversal**: 78–96% token reduction on dense apps via shallow overview + targeted drill-down
- **Snapshot & refs**: AI-optimized workflow using compact snapshot IDs and deterministic element references (`@e1`, `@e2`)
- **Headless-by-default interactions**: Ref actions use accessibility APIs and block silent focus, cursor, keyboard, or pasteboard side effects
@@ -141,23 +141,20 @@ Agent loop: snapshot → decide → act → snapshot → decide → act → ...
### Shared sessions for multi-agent workflows
-Use the same `--session <id>` when multiple agents coordinate on one desktop task. A session owns a latest-snapshot pointer, not a security boundary. Each snapshot gets its own `snapshot_id`; pass `--snapshot <id>` when an agent must act on a specific observation. Explicit snapshot IDs can be used without repeating `--session`; keep `--session` when you omit `--snapshot` and want that session's latest snapshot.
+Run `session start` once per agent run to create a trace-enabled session (manifest `trace: on` by default) and set the active pointer. Subsequent commands in that run get automatic JSONL segments under `~/.agent-desktop/sessions/<id>/trace/` and share the session's latest-snapshot namespace — no `--trace` on every call.
-```mermaid
-flowchart LR
- S["--session release-fix"] --> A["snapshot -> s1"]
- S --> B["snapshot -> s2"]
- A --> C["Agent A: click @e4 --snapshot s1"]
- B --> D["Agent B: wait --element @e9 --predicate actionable"]
- S --> E["latest_snapshot_id points at newest snapshot"]
- C --> F["Explicit snapshot id works outside session too"]
-```
+For concurrent **independent** agents, set `AGENT_DESKTOP_SESSION=<id>` per process instead of relying on the global pointer. When multiple agents share one session id, each agent should act on the `snapshot_id` from its own `snapshot` call; implicit latest is a single-agent convenience.
+
+Bare `--session <id>` without a manifest (no `session start`) still scopes the snapshot namespace only and writes no trace files. Explicit `--snapshot <id>` resolves cross-session.
```bash
-agent-desktop --session release-fix snapshot --app Xcode -i --compact
-agent-desktop --session release-fix wait --element @e9 --predicate actionable --timeout 5000
-agent-desktop --session release-fix click @e9
-agent-desktop click @e9 --snapshot s2
+agent-desktop session start --name release-fix
+agent-desktop snapshot --app Xcode -i --compact # uses active session + tracing
+agent-desktop wait --element @e9 --predicate actionable --timeout 5000
+agent-desktop click @e9
+agent-desktop click @e9 --snapshot s2 # pin to a specific observation
+agent-desktop session end
+agent-desktop session gc
```
## Commands
@@ -291,10 +288,15 @@ agent-desktop --session run-a batch '[
### System
```bash
-agent-desktop status # platform, permission report, latest snapshot
+agent-desktop session start [--name LABEL] [--no-trace] # trace-enabled run (sets active pointer)
+agent-desktop session end [id]
+agent-desktop session list
+agent-desktop session gc [--older-than SECS] [--ended]
+agent-desktop status # platform, permissions, session_id, tracing, latest snapshot
agent-desktop permissions # check accessibility/screen-recording/automation
agent-desktop permissions --request # invoke platform request path
agent-desktop version # version string
+agent-desktop skills get desktop --full # bundled agent guidance
```
## Snapshot Options
@@ -374,13 +376,15 @@ Static elements (labels, groups, containers) appear in the tree for context but
Reliability contract:
-- `--session <id>` scopes the latest snapshot pointer to one caller or agent team; explicit `--snapshot <id>` resolves the saved snapshot directly.
+- `session start` creates a manifest-gated session with automatic trace segments and relocates the latest-snapshot namespace. Activation resolves `--session` > `AGENT_DESKTOP_SESSION` > `~/.agent-desktop/current_session` (pointer written only by `session start`).
+- Bare `--session <id>` without a manifest scopes snapshots only — no surprise trace files for existing callers.
+- Explicit `--snapshot <id>` resolves the saved snapshot directly, including across sessions.
- Ref actions re-identify targets at action time: a moved unique target can proceed, while missing or changed stable identity returns `STALE_REF`.
- Mutable value text is not treated as stable identity, so text fields and timers can keep resolving when the saved window, path, role, and bounds evidence still identify the same element.
- Multiple plausible targets return `AMBIGUOUS_TARGET` instead of choosing arbitrarily.
- Actions run an actionability preflight before dispatch: visibility, stability, enabled state, supported action, policy, and editability.
- `wait --element @e3 --predicate actionable` polls until the target can be acted on.
-- `--trace <path>` appends JSONL diagnostics outside stdout; `--trace-strict` fails on trace setup and pre-action trace writes, while post-action success traces are best-effort after the desktop mutation has already happened.
+- With an active trace-enabled session, JSONL segments land under `sessions/<id>/trace/<pid>-*.jsonl` automatically. `--trace <path>` overrides to one file; `--trace-strict` fails on setup and pre-action writes (post-action traces are best-effort).
Stale ref recovery:
@@ -425,7 +429,7 @@ No. The core workflow reads native accessibility trees and assigns refs to inter
|-----------|----------|
| **Native Rust CLI** | Fast, single binary, no runtime dependencies |
| **C-ABI cdylib** | Load once from Python, Swift, Go, Ruby, Node, or C instead of forking |
-| **54 Commands** | Observation, interaction, keyboard, mouse, notifications, clipboard, window management, and bundled `skills` docs |
+| **55 Commands** | Observation, interaction, keyboard, mouse, notifications, clipboard, window management, session lifecycle, and bundled `skills` docs |
| **Snapshot & Refs** | Compact snapshot IDs and deterministic element refs like `@e1`, `@e2` |
| **Structured JSON** | Machine-readable responses with error codes and recovery hints |
diff --git a/crates/core/src/commands/mod.rs b/crates/core/src/commands/mod.rs
index bff3080e9..8a40323fd 100644
--- a/crates/core/src/commands/mod.rs
+++ b/crates/core/src/commands/mod.rs
@@ -47,6 +47,7 @@ pub mod screenshot;
pub mod scroll;
pub mod scroll_to;
pub mod select;
+pub mod session;
pub mod set_value;
pub mod skills;
pub mod snapshot;
diff --git a/crates/core/src/commands/session.rs b/crates/core/src/commands/session.rs
new file mode 100644
index 000000000..6f4ddbe0c
--- /dev/null
+++ b/crates/core/src/commands/session.rs
@@ -0,0 +1,81 @@
+use crate::error::AppError;
+use crate::session::{
+ GcOptions, SessionTraceMode, StartSessionOptions, end_session, gc, list_sessions, start_session,
+};
+use serde_json::{Value, json};
+use std::time::Duration;
+
+#[derive(Debug, Clone)]
+pub enum SessionAction {
+ Start {
+ name: Option<String>,
+ no_trace: bool,
+ force: bool,
+ },
+ End {
+ id: Option<String>,
+ },
+ List,
+ Gc {
+ older_than_secs: Option<u64>,
+ ended_only: bool,
+ },
+}
+
+pub fn execute(action: SessionAction) -> Result<Value, AppError> {
+ match action {
+ SessionAction::Start {
+ name,
+ no_trace,
+ force,
+ } => {
+ let manifest = start_session(StartSessionOptions {
+ name,
+ trace: if no_trace {
+ SessionTraceMode::Off
+ } else {
+ SessionTraceMode::On
+ },
+ force,
+ })?;
+ Ok(json!({
+ "session_id": manifest.id,
+ "name": manifest.name,
+ "trace": manifest.trace,
+ "created_at": manifest.created_at,
+ }))
+ }
+ SessionAction::End { id } => {
+ let manifest = end_session(id.as_deref())?;
+ Ok(json!({
+ "session_id": manifest.id,
+ "ended_at": manifest.ended_at,
+ }))
+ }
+ SessionAction::List => {
+ let sessions: Vec<Value> = list_sessions()?
+ .into_iter()
+ .map(|manifest| {
+ json!({
+ "session_id": manifest.id,
+ "name": manifest.name,
+ "created_at": manifest.created_at,
+ "ended_at": manifest.ended_at,
+ "trace": manifest.trace,
+ })
+ })
+ .collect();
+ Ok(json!({ "sessions": sessions }))
+ }
+ SessionAction::Gc {
+ older_than_secs,
+ ended_only,
+ } => {
+ let report = gc(GcOptions {
+ ended_only,
+ older_than: older_than_secs.map(Duration::from_secs),
+ })?;
+ Ok(json!({ "removed": report.removed }))
+ }
+ }
+}
diff --git a/crates/core/src/commands/skills.rs b/crates/core/src/commands/skills.rs
index 914e22cce..5a9c1e0dc 100644
--- a/crates/core/src/commands/skills.rs
+++ b/crates/core/src/commands/skills.rs
@@ -98,7 +98,7 @@ const SKILLS: &[Skill] = &[
Skill {
canonical: "agent-desktop",
aliases: &["desktop", "agent-desktop"],
- summary: "Primary guide. Snapshot/ref loop, JSON envelope, 54 commands across observation, interaction, keyboard/mouse, app lifecycle, notifications, clipboard, wait.",
+ summary: "Primary guide. Snapshot/ref loop, JSON envelope, 55 commands including session lifecycle, observation, interaction, keyboard/mouse, app lifecycle, notifications, clipboard, wait.",
main: SKILL_DESKTOP_MAIN,
refs: skill_desktop_refs,
},
diff --git a/crates/core/src/commands/status.rs b/crates/core/src/commands/status.rs
index 2436d7e2b..4fca4806f 100644
--- a/crates/core/src/commands/status.rs
+++ b/crates/core/src/commands/status.rs
@@ -5,6 +5,7 @@ use crate::{
context::CommandContext,
error::AppError,
refs_store::RefStore,
+ session::read_current_session_pointer,
};
use serde_json::{Value, json};
@@ -22,13 +23,20 @@ pub fn execute_with_report_with_context(
.and_then(|s| s.load_latest().ok())
.map(|m| m.len());
let snapshot_id = store.and_then(|s| s.latest_snapshot_id());
+ let session_id = context
+ .session_id()
+ .map(str::to_string)
+ .or_else(|| read_current_session_pointer().ok().flatten());
+ let tracing = context.trace_enabled();
Ok(json!({
"platform": std::env::consts::OS,
"version": env!("CARGO_PKG_VERSION"),
"permissions": permissions,
"snapshot_id": snapshot_id,
- "ref_count": ref_count
+ "ref_count": ref_count,
+ "session_id": session_id,
+ "tracing": tracing,
}))
}
diff --git a/crates/core/src/commands/status_tests.rs b/crates/core/src/commands/status_tests.rs
index 82fa73881..866c0b1de 100644
--- a/crates/core/src/commands/status_tests.rs
+++ b/crates/core/src/commands/status_tests.rs
@@ -34,3 +34,30 @@ fn status_uses_precomputed_permission_report() {
assert_eq!(permissions["screen_recording"]["state"], "granted");
assert_eq!(permissions["automation"]["state"], "not_required");
}
+
+#[test]
+fn status_reports_tracing_false_when_writer_failed() {
+ let _guard = crate::refs_test_support::HomeGuard::new();
+ let session = crate::session::start_session(crate::session::StartSessionOptions {
+ name: None,
+ trace: crate::session::SessionTraceMode::On,
+ force: true,
+ })
+ .unwrap();
+ let unopenable = std::env::temp_dir()
+ .join("agent-desktop-status-nodir")
+ .join("trace.jsonl");
+ let context = CommandContext::new(Some(session.id), Some(unopenable), false).unwrap();
+ let report = PermissionReport {
+ accessibility: PermissionState::Granted,
+ screen_recording: PermissionState::Granted,
+ automation: PermissionState::NotRequired,
+ };
+
+ let value = execute_with_report_with_context(&DeniedAdapter, &report, &context).unwrap();
+
+ assert_eq!(
+ value["tracing"], false,
+ "a failed trace writer must not report tracing:true"
+ );
+}
diff --git a/crates/core/src/context.rs b/crates/core/src/context.rs
index bcaa37348..4654e2f6c 100644
--- a/crates/core/src/context.rs
+++ b/crates/core/src/context.rs
@@ -1,17 +1,10 @@
use crate::{
action::Action, action_request::ActionRequest, error::AppError,
- interaction_policy::InteractionPolicy, trace::TraceConfig,
+ interaction_policy::InteractionPolicy, session, trace::TraceConfig,
};
use serde_json::Value;
use std::path::PathBuf;
-#[derive(Debug, Clone)]
-pub struct WaitSelector {
- pub query_raw: String,
- pub gone: bool,
- pub timeout_ms: u64,
-}
-
#[derive(Debug, Clone, Default)]
pub struct CommandContext {
session_id: Option<String>,
@@ -20,6 +13,13 @@ pub struct CommandContext {
wait_selector: Option<WaitSelector>,
}
+#[derive(Debug, Clone)]
+pub struct WaitSelector {
+ pub query_raw: String,
+ pub gone: bool,
+ pub timeout_ms: u64,
+}
+
impl CommandContext {
pub fn new(
session_id: Option<String>,
@@ -29,18 +29,15 @@ impl CommandContext {
if let Some(id) = session_id.as_deref() {
validate_session_id(id)?;
}
+ let segment_dir = session_segment_dir(session_id.as_deref(), trace_path.is_some())?;
Ok(Self {
session_id,
- trace: TraceConfig::new(trace_path, trace_strict)?,
+ trace: TraceConfig::build(trace_path, segment_dir, trace_strict)?,
headed: false,
wait_selector: None,
})
}
- /// Selects headed interaction: ref actions may move the cursor and steal
- /// focus, unlocking the physical click/scroll/keypress fallbacks in the
- /// action chain. Off by default — the tool is headless-first (Playwright
- /// style: headless is the default, headed is opt-in via `--headed`).
pub fn with_headed(mut self, headed: bool) -> Self {
self.headed = headed;
self
@@ -55,11 +52,6 @@ impl CommandContext {
self.wait_selector.as_ref()
}
- /// Builds the action request for a ref command. Headless (default) uses the
- /// command's own `base` policy — its minimum viable policy with no cursor
- /// movement (most commands are pure-AX `headless`; `type` is `focus_fallback`
- /// because typing requires focus). `--headed` upgrades any base to `headed`,
- /// unlocking the cursor/OS-input fallbacks instead of failing closed.
pub fn request(&self, action: Action, base: InteractionPolicy) -> ActionRequest {
ActionRequest {
action,
@@ -67,18 +59,11 @@ impl CommandContext {
}
}
- /// Builds the action request using the action's canonical CLI base policy
- /// from `Action::base_interaction_policy()`, ensuring a single source of
- /// truth for the per-action minimum. `--headed` upgrades the base to
- /// `headed` exactly as `request()` does.
pub fn request_base(&self, action: Action) -> ActionRequest {
let base = action.base_interaction_policy();
self.request(action, base)
}
- /// Policy for raw physical-input commands (hover, drag, mouse-*). They
- /// have no semantic action chain, so headless denies both focus stealing
- /// and cursor movement unless `--headed` opts in.
pub fn physical_input_policy(&self) -> InteractionPolicy {
self.policy_with_base(InteractionPolicy::headless())
}
@@ -96,9 +81,15 @@ impl CommandContext {
if let Some(id) = session_id.as_deref() {
validate_session_id(id)?;
}
+ let trace = if self.trace.pending_file_path().is_some() || session_id == self.session_id {
+ self.trace.clone()
+ } else {
+ let segment_dir = session_segment_dir(session_id.as_deref(), false)?;
+ self.trace.clone_with_session_segment(segment_dir)?
+ };
Ok(Self {
session_id,
- trace: self.trace.clone(),
+ trace,
headed: self.headed,
wait_selector: None,
})
@@ -116,6 +107,26 @@ impl CommandContext {
pub fn session_id(&self) -> Option<&str> {
self.session_id.as_deref()
}
+
+ pub fn trace_enabled(&self) -> bool {
+ self.trace.has_sink()
+ }
+}
+
+fn session_segment_dir(
+ session_id: Option<&str>,
+ explicit_trace: bool,
+) -> Result<Option<PathBuf>, AppError> {
+ if explicit_trace {
+ return Ok(None);
+ }
+ let Some(session_id) = session_id else {
+ return Ok(None);
+ };
+ if !session::trace_enabled_for_session(session_id)? {
+ return Ok(None);
+ }
+ Ok(Some(session::trace_dir(session_id)?))
}
pub fn validate_session_id(id: &str) -> Result<(), AppError> {
@@ -134,235 +145,5 @@ pub fn validate_session_id(id: &str) -> Result<(), AppError> {
}
#[cfg(test)]
-mod tests {
- use super::*;
-
- #[test]
- fn accepts_filesystem_safe_session_ids() {
- assert!(validate_session_id("agent-1_A").is_ok());
- }
-
- #[test]
- fn rejects_path_like_session_ids() {
- assert!(validate_session_id("../agent").is_err());
- assert!(validate_session_id("agent/a").is_err());
- }
-
- #[test]
- fn trace_writes_jsonl_without_stdout_dependency() {
- let path = std::env::temp_dir().join(format!(
- "agent-desktop-trace-{}.jsonl",
- std::time::SystemTime::now()
- .duration_since(std::time::UNIX_EPOCH)
- .unwrap()
- .as_nanos()
- ));
- let context = CommandContext::new(None, Some(path.clone()), false).unwrap();
-
- context
- .trace("ref.resolve.ok", serde_json::json!({ "ref": "@e1" }))
- .unwrap();
-
- let body = std::fs::read_to_string(&path).unwrap();
- let event: serde_json::Value = serde_json::from_str(body.trim()).unwrap();
- assert_eq!(event["event"], "ref.resolve.ok");
- assert_eq!(event["ref"], "@e1");
- assert!(event["ts_ms"].as_u64().is_some());
- assert!(
- event.get("session_id").is_none(),
- "session_id must be absent when not set"
- );
- let _ = std::fs::remove_file(path);
- }
-
- #[test]
- fn trace_injects_session_id_as_top_level_unredacted_field() {
- let path = std::env::temp_dir().join(format!(
- "agent-desktop-session-trace-{}.jsonl",
- std::time::SystemTime::now()
- .duration_since(std::time::UNIX_EPOCH)
- .unwrap()
- .as_nanos()
- ));
- let context =
- CommandContext::new(Some("my-session".into()), Some(path.clone()), false).unwrap();
-
- context
- .trace("ref.resolve.ok", serde_json::json!({ "ref": "@e1" }))
- .unwrap();
-
- let body = std::fs::read_to_string(&path).unwrap();
- let event: serde_json::Value = serde_json::from_str(body.trim()).unwrap();
- assert_eq!(
- event["session_id"], "my-session",
- "session_id must be a top-level string"
- );
- assert_eq!(event["event"], "ref.resolve.ok");
- assert!(event["ts_ms"].as_u64().is_some());
- assert!(
- !body.contains("redacted"),
- "session_id must not be redacted"
- );
- let _ = std::fs::remove_file(path);
- }
-
- #[test]
- fn trace_write_failure_is_best_effort_unless_strict() {
- let missing = std::env::temp_dir()
- .join("agent-desktop-missing-dir")
- .join("trace.jsonl");
-
- let best_effort = CommandContext::new(None, Some(missing.clone()), false).unwrap();
- assert!(best_effort.trace("event", serde_json::json!({})).is_ok());
-
- assert!(CommandContext::new(None, Some(missing), true).is_err());
- }
-
- #[test]
- fn trace_lazy_does_not_build_fields_when_trace_is_disabled() {
- let context = CommandContext::default();
- let built = std::cell::Cell::new(false);
-
- context
- .trace_lazy("event", || {
- built.set(true);
- serde_json::json!({})
- })
- .unwrap();
-
- assert!(!built.get());
- }
-
- #[cfg(unix)]
- #[test]
- fn trace_file_is_private_on_create() {
- use std::os::unix::fs::PermissionsExt;
-
- let path = std::env::temp_dir().join(format!(
- "agent-desktop-private-trace-{}.jsonl",
- std::time::SystemTime::now()
- .duration_since(std::time::UNIX_EPOCH)
- .unwrap()
- .as_nanos()
- ));
- let context = CommandContext::new(None, Some(path.clone()), true).unwrap();
- context.trace("event", serde_json::json!({})).unwrap();
-
- let mode = std::fs::metadata(&path).unwrap().permissions().mode() & 0o777;
- assert_eq!(mode, 0o600);
- let _ = std::fs::remove_file(path);
- }
-
- #[cfg(unix)]
- #[test]
- fn trace_rejects_loose_existing_file_permissions() {
- use std::os::unix::fs::PermissionsExt;
-
- let path = std::env::temp_dir().join(format!(
- "agent-desktop-loose-trace-{}.jsonl",
- std::time::SystemTime::now()
- .duration_since(std::time::UNIX_EPOCH)
- .unwrap()
- .as_nanos()
- ));
- std::fs::write(&path, "").unwrap();
- std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o644)).unwrap();
-
- let err = CommandContext::new(None, Some(path.clone()), false).unwrap_err();
-
- assert_eq!(err.code(), "INVALID_ARGS");
- let _ = std::fs::remove_file(path);
- }
-
- #[test]
- fn trace_redacts_sensitive_text_and_value_fields() {
- let path = std::env::temp_dir().join(format!(
- "agent-desktop-redacted-trace-{}.jsonl",
- std::time::SystemTime::now()
- .duration_since(std::time::UNIX_EPOCH)
- .unwrap()
- .as_nanos()
- ));
- let context = CommandContext::new(None, Some(path.clone()), true).unwrap();
- context
- .trace(
- "event",
- serde_json::json!({
- "text": "secret",
- "value": "hidden",
- "name": "private label",
- "description": "private desc",
- "message": "diagnostic error",
- "post_state": { "value": "deep secret" },
- "target_label": "button secret",
- "nested": { "expected": "token" },
- "title": "private window title",
- "url": "https://internal.example/doc",
- "help": "private tooltip",
- "placeholder": "private placeholder"
- }),
- )
- .unwrap();
-
- let body = std::fs::read_to_string(&path).unwrap();
- let event: serde_json::Value = serde_json::from_str(body.trim()).unwrap();
- assert_eq!(event["text"]["redacted"], true);
- assert_eq!(event["value"]["redacted"], true);
- assert_eq!(event["name"]["redacted"], true);
- assert_eq!(event["description"]["redacted"], true);
- assert_eq!(event["message"], "diagnostic error");
- assert_eq!(event["post_state"]["value"]["redacted"], true);
- assert_eq!(event["target_label"]["redacted"], true);
- assert_eq!(event["nested"]["expected"]["redacted"], true);
- assert_eq!(event["title"]["redacted"], true);
- assert_eq!(event["url"]["redacted"], true);
- assert_eq!(event["help"]["redacted"], true);
- assert_eq!(event["placeholder"]["redacted"], true);
- assert!(!body.contains("secret"));
- assert!(!body.contains("hidden"));
- assert!(!body.contains("private label"));
- assert!(!body.contains("private desc"));
- assert!(!body.contains("token"));
- assert!(!body.contains("private window title"));
- assert!(!body.contains("internal.example"));
- assert!(!body.contains("private tooltip"));
- assert!(!body.contains("private placeholder"));
- let _ = std::fs::remove_file(path);
- }
-
- #[test]
- fn trace_strict_requires_trace_path() {
- let err = CommandContext::new(None, None, true).unwrap_err();
- assert_eq!(err.code(), "INVALID_ARGS");
- }
-
- #[test]
- fn batch_item_clears_wait_selector() {
- let parent = CommandContext::default().with_wait_selector(Some(WaitSelector {
- query_raw: "button:OK".into(),
- gone: false,
- timeout_ms: 5_000,
- }));
- let child = parent.for_batch_item(None).unwrap();
- assert!(child.wait_selector().is_none());
- }
-
- #[test]
- fn batch_item_inherits_or_overrides_session_without_trace_loss() {
- let path = std::env::temp_dir().join("agent-desktop-context-test.jsonl");
- let _ = std::fs::remove_file(&path);
- let parent = CommandContext::new(Some("parent".into()), Some(path.clone()), false).unwrap();
-
- let inherited = parent.for_batch_item(None).unwrap();
- let overridden = parent.for_batch_item(Some("child".into())).unwrap();
-
- assert_eq!(inherited.session_id(), Some("parent"));
- assert_eq!(overridden.session_id(), Some("child"));
- overridden
- .trace("batch.child", serde_json::json!({ "ok": true }))
- .unwrap();
- let body = std::fs::read_to_string(&path).unwrap();
- assert!(body.contains("batch.child"));
- let _ = std::fs::remove_file(path);
- }
-}
+#[path = "context_tests.rs"]
+mod tests;
diff --git a/crates/core/src/context_tests.rs b/crates/core/src/context_tests.rs
new file mode 100644
index 000000000..eea19276d
--- /dev/null
+++ b/crates/core/src/context_tests.rs
@@ -0,0 +1,345 @@
+use super::*;
+use crate::session::{
+ SessionTraceMode, StartSessionOptions, start_session, trace_enabled_for_session,
+};
+use serde_json::json;
+
+#[test]
+fn accepts_filesystem_safe_session_ids() {
+ assert!(validate_session_id("agent-1_A").is_ok());
+}
+
+#[test]
+fn rejects_path_like_session_ids() {
+ assert!(validate_session_id("../agent").is_err());
+ assert!(validate_session_id("agent/a").is_err());
+}
+
+#[test]
+fn trace_writes_jsonl_without_stdout_dependency() {
+ let path = std::env::temp_dir().join(format!(
+ "agent-desktop-trace-{}.jsonl",
+ std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap()
+ .as_nanos()
+ ));
+ let context = CommandContext::new(None, Some(path.clone()), false).unwrap();
+
+ context
+ .trace("ref.resolve.ok", json!({ "ref": "@e1" }))
+ .unwrap();
+
+ let body = std::fs::read_to_string(&path).unwrap();
+ let event: serde_json::Value = serde_json::from_str(body.trim()).unwrap();
+ assert_eq!(event["event"], "ref.resolve.ok");
+ assert_eq!(event["ref"], "@e1");
+ assert!(event["ts_ms"].as_u64().is_some());
+ assert!(event.get("session_id").is_none());
+ let _ = std::fs::remove_file(path);
+}
+
+#[test]
+fn trace_injects_session_id_as_top_level_unredacted_field() {
+ let path = std::env::temp_dir().join(format!(
+ "agent-desktop-session-trace-{}.jsonl",
+ std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap()
+ .as_nanos()
+ ));
+ let context =
+ CommandContext::new(Some("my-session".into()), Some(path.clone()), false).unwrap();
+
+ context
+ .trace("ref.resolve.ok", json!({ "ref": "@e1" }))
+ .unwrap();
+
+ let body = std::fs::read_to_string(&path).unwrap();
+ let event: serde_json::Value = serde_json::from_str(body.trim()).unwrap();
+ assert_eq!(event["session_id"], "my-session");
+ assert_eq!(event["event"], "ref.resolve.ok");
+ assert!(event["ts_ms"].as_u64().is_some());
+ assert!(!body.contains("redacted"));
+ let _ = std::fs::remove_file(path);
+}
+
+#[test]
+fn trace_write_failure_is_best_effort_unless_strict() {
+ let missing = std::env::temp_dir()
+ .join("agent-desktop-missing-dir")
+ .join("trace.jsonl");
+
+ let best_effort = CommandContext::new(None, Some(missing.clone()), false).unwrap();
+ assert!(best_effort.trace("event", json!({})).is_ok());
+ assert!(CommandContext::new(None, Some(missing), false).is_ok());
+}
+
+#[test]
+fn trace_lazy_does_not_build_fields_when_trace_is_disabled() {
+ let context = CommandContext::default();
+ let built = std::cell::Cell::new(false);
+
+ context
+ .trace_lazy("event", || {
+ built.set(true);
+ json!({})
+ })
+ .unwrap();
+
+ assert!(!built.get());
+}
+
+#[cfg(unix)]
+#[test]
+fn trace_file_is_private_on_create() {
+ use std::os::unix::fs::PermissionsExt;
+
+ let path = std::env::temp_dir().join(format!(
+ "agent-desktop-private-trace-{}.jsonl",
+ std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap()
+ .as_nanos()
+ ));
+ let context = CommandContext::new(None, Some(path.clone()), true).unwrap();
+ context.trace("event", json!({})).unwrap();
+
+ let mode = std::fs::metadata(&path).unwrap().permissions().mode() & 0o777;
+ assert_eq!(mode, 0o600);
+ let _ = std::fs::remove_file(path);
+}
+
+#[cfg(unix)]
+#[test]
+fn trace_rejects_loose_existing_file_permissions() {
+ use std::os::unix::fs::PermissionsExt;
+
+ let path = std::env::temp_dir().join(format!(
+ "agent-desktop-loose-trace-{}.jsonl",
+ std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap()
+ .as_nanos()
+ ));
+ std::fs::write(&path, "").unwrap();
+ std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o644)).unwrap();
+
+ let err = CommandContext::new(None, Some(path.clone()), false).unwrap_err();
+
+ assert_eq!(err.code(), "INVALID_ARGS");
+ let _ = std::fs::remove_file(path);
+}
+
+#[test]
+fn trace_redacts_sensitive_text_and_value_fields() {
+ let path = std::env::temp_dir().join(format!(
+ "agent-desktop-redacted-trace-{}.jsonl",
+ std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap()
+ .as_nanos()
+ ));
+ let context = CommandContext::new(None, Some(path.clone()), true).unwrap();
+ context
+ .trace(
+ "event",
+ json!({
+ "text": "secret",
+ "value": "hidden",
+ "name": "private label",
+ "description": "private desc",
+ "message": "diagnostic error",
+ "post_state": { "value": "deep secret" },
+ "target_label": "button secret",
+ "nested": { "expected": "token" },
+ "title": "private window title",
+ "url": "https://internal.example/doc",
+ "help": "private tooltip",
+ "placeholder": "private placeholder"
+ }),
+ )
+ .unwrap();
+
+ let body = std::fs::read_to_string(&path).unwrap();
+ let event: serde_json::Value = serde_json::from_str(body.trim()).unwrap();
+ assert_eq!(event["text"]["redacted"], true);
+ assert_eq!(event["value"]["redacted"], true);
+ assert_eq!(event["message"], "diagnostic error");
+ assert!(!body.contains("secret"));
+ let _ = std::fs::remove_file(path);
+}
+
+#[test]
+fn trace_strict_requires_trace_path_or_trace_session() {
+ let err = CommandContext::new(None, None, true).unwrap_err();
+ assert_eq!(err.code(), "INVALID_ARGS");
+}
+
+#[test]
+fn batch_item_clears_wait_selector() {
+ let parent = CommandContext::default().with_wait_selector(Some(WaitSelector {
+ query_raw: "button:OK".into(),
+ gone: false,
+ timeout_ms: 5_000,
+ }));
+ let child = parent.for_batch_item(None).unwrap();
+ assert!(child.wait_selector().is_none());
+}
+
+#[test]
+fn batch_item_inherits_or_overrides_session_without_trace_loss() {
+ let path = std::env::temp_dir().join("agent-desktop-context-test.jsonl");
+ let _ = std::fs::remove_file(&path);
+ let parent = CommandContext::new(Some("parent".into()), Some(path.clone()), false).unwrap();
+
+ let inherited = parent.for_batch_item(None).unwrap();
+ let overridden = parent.for_batch_item(Some("child".into())).unwrap();
+
+ assert_eq!(inherited.session_id(), Some("parent"));
+ assert_eq!(overridden.session_id(), Some("child"));
+ overridden
+ .trace("batch.child", json!({ "ok": true }))
+ .unwrap();
+ let body = std::fs::read_to_string(&path).unwrap();
+ assert!(body.contains("batch.child"));
+ let _ = std::fs::remove_file(path);
+}
+
+#[test]
+fn bare_session_without_manifest_does_not_trace() {
+ let _guard = crate::refs_test_support::HomeGuard::new();
+ let context = CommandContext::new(Some("legacy-session".into()), None, false).unwrap();
+ assert!(!context.trace_enabled());
+ context.trace("event", json!({})).unwrap();
+ let trace_dir = crate::refs_store::RefStore::for_session(Some("legacy-session"))
+ .unwrap()
+ .trace_dir();
+ assert!(!trace_dir.exists());
+}
+
+#[test]
+fn trace_on_session_writes_segment_without_explicit_trace_flag() {
+ let _guard = crate::refs_test_support::HomeGuard::new();
+ let manifest = start_session(StartSessionOptions {
+ name: None,
+ trace: SessionTraceMode::On,
+ force: false,
+ })
+ .unwrap();
+ let context = CommandContext::new(Some(manifest.id.clone()), None, false).unwrap();
+ assert!(context.trace_enabled());
+ context
+ .trace("session.event", json!({ "ok": true }))
+ .unwrap();
+ let trace_dir = crate::refs_store::RefStore::for_session(Some(&manifest.id))
+ .unwrap()
+ .trace_dir();
+ let entries: Vec<_> = std::fs::read_dir(trace_dir).unwrap().flatten().collect();
+ assert_eq!(entries.len(), 1);
+}
+
+#[test]
+fn no_trace_session_still_namespaces_snapshots() {
+ let _guard = crate::refs_test_support::HomeGuard::new();
+ let manifest = start_session(StartSessionOptions {
+ name: None,
+ trace: SessionTraceMode::Off,
+ force: false,
+ })
+ .unwrap();
+ assert!(!trace_enabled_for_session(&manifest.id).unwrap());
+ let context = CommandContext::new(Some(manifest.id.clone()), None, false).unwrap();
+ assert!(!context.trace_enabled());
+ assert_eq!(context.session_id(), Some(manifest.id.as_str()));
+}
+
+#[test]
+fn explicit_trace_overrides_session_sink() {
+ let _guard = crate::refs_test_support::HomeGuard::new();
+ let manifest = start_session(StartSessionOptions {
+ name: None,
+ trace: SessionTraceMode::On,
+ force: false,
+ })
+ .unwrap();
+ let path = std::env::temp_dir().join(format!(
+ "agent-desktop-override-{}.jsonl",
+ std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap()
+ .as_nanos()
+ ));
+ let context =
+ CommandContext::new(Some(manifest.id.clone()), Some(path.clone()), false).unwrap();
+ context.trace("override.event", json!({})).unwrap();
+ assert!(path.exists());
+ let trace_dir = crate::refs_store::RefStore::for_session(Some(&manifest.id))
+ .unwrap()
+ .trace_dir();
+ let segment_count = std::fs::read_dir(trace_dir)
+ .map(|entries| entries.flatten().count())
+ .unwrap_or(0);
+ assert_eq!(segment_count, 0);
+ let _ = std::fs::remove_file(path);
+}
+
+#[test]
+fn batch_item_session_override_uses_its_own_segment_dir() {
+ let _guard = crate::refs_test_support::HomeGuard::new();
+ let parent_session = start_session(StartSessionOptions {
+ name: None,
+ trace: SessionTraceMode::On,
+ force: false,
+ })
+ .unwrap();
+ let child_session = start_session(StartSessionOptions {
+ name: None,
+ trace: SessionTraceMode::On,
+ force: true,
+ })
+ .unwrap();
+ let parent = CommandContext::new(Some(parent_session.id.clone()), None, false).unwrap();
+ let child = parent
+ .for_batch_item(Some(child_session.id.clone()))
+ .unwrap();
+ child.trace("child.event", json!({})).unwrap();
+ let parent_trace = crate::refs_store::RefStore::for_session(Some(&parent_session.id))
+ .unwrap()
+ .trace_dir();
+ let parent_segments = std::fs::read_dir(&parent_trace)
+ .map(|entries| {
+ entries
+ .flatten()
+ .filter(|entry| entry.path().extension().is_some_and(|ext| ext == "jsonl"))
+ .count()
+ })
+ .unwrap_or(0);
+ assert_eq!(parent_segments, 0);
+ let child_trace = crate::refs_store::RefStore::for_session(Some(&child_session.id))
+ .unwrap()
+ .trace_dir();
+ assert!(child_trace.is_dir());
+}
+
+#[test]
+fn strict_parent_allows_no_trace_batch_override() {
+ let _guard = crate::refs_test_support::HomeGuard::new();
+ let traced = start_session(StartSessionOptions {
+ name: None,
+ trace: SessionTraceMode::On,
+ force: true,
+ })
+ .unwrap();
+ let untraced = start_session(StartSessionOptions {
+ name: None,
+ trace: SessionTraceMode::Off,
+ force: true,
+ })
+ .unwrap();
+ let parent = CommandContext::new(Some(traced.id.clone()), None, true).unwrap();
+ let child = parent
+ .for_batch_item(Some(untraced.id.clone()))
+ .expect("a no-trace session override must not fail under a strict parent");
+ assert_eq!(child.session_id(), Some(untraced.id.as_str()));
+}
diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs
index 3ef05bd9c..56ebad8d0 100644
--- a/crates/core/src/lib.rs
+++ b/crates/core/src/lib.rs
@@ -28,6 +28,7 @@ mod refs_test_support;
pub(crate) mod resolved_element;
pub mod roles;
pub(crate) mod search_text;
+pub mod session;
pub mod snapshot;
pub mod snapshot_ref;
pub(crate) mod trace;
diff --git a/crates/core/src/refs.rs b/crates/core/src/refs.rs
index 85da3cd28..6cd9648a5 100644
--- a/crates/core/src/refs.rs
+++ b/crates/core/src/refs.rs
@@ -215,7 +215,9 @@ pub(crate) fn write_private_file(path: &Path, bytes: &[u8]) -> Result<(), AppErr
#[cfg(not(unix))]
std::fs::create_dir_all(dir)?;
- let tmp = path.with_extension("tmp");
+ static TMP_COUNTER: AtomicU64 = AtomicU64::new(0);
+ let unique = TMP_COUNTER.fetch_add(1, Ordering::Relaxed);
+ let tmp = path.with_extension(format!("{}.{unique}.tmp", std::process::id()));
let written = write_tmp_then_rename(&tmp, path, bytes);
if written.is_err() {
let _ = std::fs::remove_file(&tmp);
diff --git a/crates/core/src/refs_lock.rs b/crates/core/src/refs_lock.rs
index 2e50cef5c..6be516f0a 100644
--- a/crates/core/src/refs_lock.rs
+++ b/crates/core/src/refs_lock.rs
@@ -186,6 +186,13 @@ fn process_is_alive(_pid: u32) -> Option<bool> {
None
}
+pub(crate) fn lock_holder_is_live(lock_path: &Path) -> bool {
+ match LockSnapshot::read(lock_path) {
+ Ok(Some(snapshot)) => !snapshot.is_stale(),
+ Ok(None) | Err(()) => false,
+ }
+}
+
impl Drop for RefStoreLock {
fn drop(&mut self) {
let should_remove = LockSnapshot::read(&self.path)
diff --git a/crates/core/src/refs_store.rs b/crates/core/src/refs_store.rs
index f2e832002..bf4e71711 100644
--- a/crates/core/src/refs_store.rs
+++ b/crates/core/src/refs_store.rs
@@ -226,6 +226,14 @@ impl RefStore {
.join("refmap.json")
}
+ pub(crate) fn base_dir(&self) -> &Path {
+ &self.base_dir
+ }
+
+ pub(crate) fn trace_dir(&self) -> PathBuf {
+ self.base_dir.join("trace")
+ }
+
fn snapshots_dir(&self) -> PathBuf {
self.base_dir.join("snapshots")
}
@@ -335,3 +343,7 @@ mod prune;
#[cfg(test)]
#[path = "refs_store_tests.rs"]
mod tests;
+
+#[cfg(test)]
+#[path = "refs_store_trace_tests.rs"]
+mod trace_tests;
diff --git a/crates/core/src/refs_store_tests.rs b/crates/core/src/refs_store_tests.rs
index 78889205c..0eb6ef151 100644
--- a/crates/core/src/refs_store_tests.rs
+++ b/crates/core/src/refs_store_tests.rs
@@ -367,3 +367,22 @@ fn duplicate_snapshot_id_across_sessions_is_rejected_on_load() {
assert_eq!(err.code(), "INVALID_ARGS");
assert!(err.to_string().contains("more than one session"));
}
+
+#[test]
+fn prune_never_removes_trace_segments() {
+ let _guard = HomeGuard::new();
+ let store = RefStore::for_session(Some("trace-retention")).unwrap();
+ let trace_dir = store.trace_dir();
+ std::fs::create_dir_all(&trace_dir).unwrap();
+ let segment = trace_dir.join("1234-5678.jsonl");
+ std::fs::write(&segment, b"{}\n").unwrap();
+ for index in 0..=MAX_SAVED_SNAPSHOTS {
+ let snapshot_id = format!("snap-{index:04}");
+ store
+ .save_snapshot(&snapshot_id, &map_with(&snapshot_id))
+ .unwrap();
+ store.set_latest(&snapshot_id).unwrap();
+ }
+ assert!(segment.is_file());
+ assert!(trace_dir.is_dir());
+}
diff --git a/crates/core/src/refs_store_trace_tests.rs b/crates/core/src/refs_store_trace_tests.rs
new file mode 100644
index 000000000..a5508a2f1
--- /dev/null
+++ b/crates/core/src/refs_store_trace_tests.rs
@@ -0,0 +1,20 @@
+use super::*;
+use crate::refs_test_support::HomeGuard;
+
+#[test]
+fn trace_dir_points_under_session_base() {
+ let _guard = HomeGuard::new();
+ let store = RefStore::for_session(Some("run-42")).unwrap();
+ assert_eq!(store.trace_dir(), store.base_dir().join("trace"));
+}
+
+#[test]
+fn trace_dir_accessors_create_no_directories() {
+ let _guard = HomeGuard::new();
+ let store = RefStore::for_session(Some("run-42")).unwrap();
+ let _ = store.trace_dir();
+ assert!(
+ !store.trace_dir().exists(),
+ "trace_dir accessor must not create directories"
+ );
+}
diff --git a/crates/core/src/refs_tests.rs b/crates/core/src/refs_tests.rs
index 35fed6509..9fa5cc9cf 100644
--- a/crates/core/src/refs_tests.rs
+++ b/crates/core/src/refs_tests.rs
@@ -266,7 +266,7 @@ fn test_save_oversize_preserves_previous_file() {
#[cfg(unix)]
#[test]
-fn test_write_private_file_rejects_tmp_symlink() {
+fn test_write_private_file_ignores_stale_predictable_tmp_symlink() {
let dir = std::env::temp_dir().join(format!(
"agent-desktop-ref-symlink-{}",
std::time::SystemTime::now()
@@ -277,13 +277,13 @@ fn test_write_private_file_rejects_tmp_symlink() {
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("refmap.json");
let target = dir.join("target.json");
- let tmp = path.with_extension("tmp");
+ let stale = path.with_extension("tmp");
std::fs::write(&target, b"existing").unwrap();
- std::os::unix::fs::symlink(&target, &tmp).unwrap();
+ std::os::unix::fs::symlink(&target, &stale).unwrap();
- let result = write_private_file(&path, b"new");
+ write_private_file(&path, b"new").unwrap();
- assert!(result.is_err());
+ assert_eq!(std::fs::read(&path).unwrap(), b"new");
assert_eq!(std::fs::read(&target).unwrap(), b"existing");
let _ = std::fs::remove_dir_all(dir);
}
diff --git a/crates/core/src/session/gc.rs b/crates/core/src/session/gc.rs
new file mode 100644
index 000000000..ad861dc90
--- /dev/null
+++ b/crates/core/src/session/gc.rs
@@ -0,0 +1,135 @@
+use super::{
+ SessionManifest, TRACE_LIVENESS_WINDOW, list_sessions, now_millis,
+ read_current_session_pointer, read_manifest,
+};
+use crate::{
+ context::validate_session_id,
+ error::AppError,
+ refs_lock::{RefStoreLock, lock_holder_is_live},
+ refs_store::RefStore,
+};
+use std::path::Path;
+use std::time::{Duration, SystemTime, UNIX_EPOCH};
+
+pub struct GcOptions {
+ pub ended_only: bool,
+ pub older_than: Option<Duration>,
+}
+
+#[derive(Debug)]
+pub struct GcReport {
+ pub removed: Vec<String>,
+}
+
+pub fn pointer_references_live_session() -> Result<bool, AppError> {
+ let Some(id) = read_current_session_pointer()? else {
+ return Ok(false);
+ };
+ is_live(&id)
+}
+
+pub fn is_live(session_id: &str) -> Result<bool, AppError> {
+ validate_session_id(session_id)?;
+ let store = RefStore::for_session(Some(session_id))?;
+ if lock_holder_is_live(&store.base_dir().join("refstore.lock")) {
+ return Ok(true);
+ }
+ let manifest = read_manifest(session_id)?;
+ Ok(has_recent_activity(&store, manifest.as_ref()))
+}
+
+fn has_recent_activity(store: &RefStore, manifest: Option<&SessionManifest>) -> bool {
+ if path_recently_modified(&store.base_dir().join("snapshots"))
+ || trace_dir_recently_written(&store.trace_dir())
+ {
+ return true;
+ }
+ manifest.is_some_and(|manifest| {
+ let age = Duration::from_millis(now_millis().saturating_sub(manifest.created_at));
+ manifest.ended_at.is_none() && age < TRACE_LIVENESS_WINDOW
+ })
+}
+
+pub fn gc(options: GcOptions) -> Result<GcReport, AppError> {
+ let pointer = read_current_session_pointer()?;
+ let mut removed = Vec::new();
+ for manifest in list_sessions()? {
+ if pointer.as_deref() == Some(manifest.id.as_str()) {
+ continue;
+ }
+ if is_live(&manifest.id)? {
+ continue;
+ }
+ if options.ended_only && manifest.ended_at.is_none() {
+ continue;
+ }
+ if let Some(older_than) = options.older_than {
+ let age_reference = manifest.ended_at.unwrap_or(manifest.created_at);
+ let age_ms = now_millis().saturating_sub(age_reference);
+ if Duration::from_millis(age_ms) < older_than {
+ continue;
+ }
+ } else if manifest.ended_at.is_none() {
+ continue;
+ }
+ let store = RefStore::for_session(Some(&manifest.id))?;
+ let dir = store.base_dir().to_path_buf();
+ let lock = match RefStoreLock::acquire(&dir.join("refstore.lock")) {
+ Ok(lock) => lock,
+ Err(_) => continue,
+ };
+ if has_recent_activity(&store, Some(&manifest)) {
+ drop(lock);
+ continue;
+ }
+ let did_remove = remove_session_dir(&dir)?;
+ drop(lock);
+ if did_remove {
+ removed.push(manifest.id);
+ }
+ }
+ Ok(GcReport { removed })
+}
+
+fn path_recently_modified(path: &Path) -> bool {
+ let cutoff = SystemTime::now()
+ .checked_sub(TRACE_LIVENESS_WINDOW)
+ .unwrap_or(UNIX_EPOCH);
+ std::fs::metadata(path)
+ .and_then(|metadata| metadata.modified())
+ .ok()
+ .is_some_and(|modified| modified >= cutoff)
+}
+
+fn trace_dir_recently_written(trace_dir: &Path) -> bool {
+ let Ok(entries) = std::fs::read_dir(trace_dir) else {
+ return false;
+ };
+ let cutoff = SystemTime::now()
+ .checked_sub(TRACE_LIVENESS_WINDOW)
+ .unwrap_or(UNIX_EPOCH);
+ entries.flatten().any(|entry| {
+ entry
+ .metadata()
+ .ok()
+ .and_then(|metadata| metadata.modified().ok())
+ .is_some_and(|modified| modified >= cutoff)
+ })
+}
+
+pub(crate) fn remove_session_dir(dir: &Path) -> Result<bool, AppError> {
+ if !dir.is_dir() {
+ return Ok(false);
+ }
+ if std::fs::symlink_metadata(dir)
+ .map(|meta| meta.file_type().is_symlink())
+ .unwrap_or(true)
+ {
+ return Err(AppError::invalid_input_with_suggestion(
+ "Refusing to remove a symlinked session directory",
+ "Remove the symlink manually before running session gc.",
+ ));
+ }
+ std::fs::remove_dir_all(dir)?;
+ Ok(true)
+}
diff --git a/crates/core/src/session/manifest.rs b/crates/core/src/session/manifest.rs
new file mode 100644
index 000000000..d5bbc8537
--- /dev/null
+++ b/crates/core/src/session/manifest.rs
@@ -0,0 +1,27 @@
+use serde::{Deserialize, Serialize};
+
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct SessionManifest {
+ pub id: String,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub name: Option<String>,
+ pub created_at: u64,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub ended_at: Option<u64>,
+ #[serde(default)]
+ pub trace: SessionTraceMode,
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
+#[serde(rename_all = "lowercase")]
+pub enum SessionTraceMode {
+ On,
+ #[default]
+ Off,
+}
+
+impl SessionManifest {
+ pub fn trace_enabled(&self) -> bool {
+ matches!(self.trace, SessionTraceMode::On) && self.ended_at.is_none()
+ }
+}
diff --git a/crates/core/src/session/mod.rs b/crates/core/src/session/mod.rs
new file mode 100644
index 000000000..97f23b3fa
--- /dev/null
+++ b/crates/core/src/session/mod.rs
@@ -0,0 +1,314 @@
+mod gc;
+mod manifest;
+
+pub use gc::{GcOptions, GcReport, gc, is_live, pointer_references_live_session};
+pub use manifest::{SessionManifest, SessionTraceMode};
+
+use crate::{
+ context::validate_session_id,
+ error::AppError,
+ refs::{home_dir, write_private_file},
+ refs_store::RefStore,
+};
+use serde_json;
+use std::io::{ErrorKind, Read};
+use std::path::{Path, PathBuf};
+use std::sync::atomic::{AtomicU64, Ordering};
+use std::time::{Duration, SystemTime, UNIX_EPOCH};
+
+const CURRENT_SESSION_FILE: &str = "current_session";
+const SESSION_MANIFEST_FILE: &str = "session.json";
+pub(super) const TRACE_LIVENESS_WINDOW: Duration = Duration::from_secs(300);
+static SESSION_COUNTER: AtomicU64 = AtomicU64::new(0);
+
+pub struct StartSessionOptions {
+ pub name: Option<String>,
+ pub trace: SessionTraceMode,
+ pub force: bool,
+}
+
+pub fn agent_desktop_dir() -> Result<PathBuf, AppError> {
+ let home = home_dir().ok_or_else(|| AppError::Internal("HOME directory not found".into()))?;
+ Ok(home.join(".agent-desktop"))
+}
+
+pub fn session_dir(session_id: &str) -> Result<PathBuf, AppError> {
+ validate_session_id(session_id)?;
+ Ok(agent_desktop_dir()?.join("sessions").join(session_id))
+}
+
+pub fn trace_dir(session_id: &str) -> Result<PathBuf, AppError> {
+ Ok(RefStore::for_session(Some(session_id))?.trace_dir())
+}
+
+pub fn current_session_path() -> Result<PathBuf, AppError> {
+ Ok(agent_desktop_dir()?.join(CURRENT_SESSION_FILE))
+}
+
+pub fn resolve_active_session(
+ explicit: Option<&str>,
+ env: Option<&str>,
+) -> Result<Option<String>, AppError> {
+ if let Some(id) = explicit {
+ validate_session_id(id)?;
+ return Ok(Some(id.to_string()));
+ }
+ if let Some(id) = env {
+ if id.is_empty() {
+ return Err(AppError::invalid_input_with_suggestion(
+ "AGENT_DESKTOP_SESSION must not be empty",
+ "Unset the variable or set it to a valid session id.",
+ ));
+ }
+ validate_session_id(id)?;
+ return Ok(Some(id.to_string()));
+ }
+ read_current_session_pointer()
+}
+
+pub fn read_current_session_pointer() -> Result<Option<String>, AppError> {
+ let path = current_session_path()?;
+ let mut file = match open_session_file(&path) {
+ Ok(file) => file,
+ Err(err) if err.kind() == ErrorKind::NotFound => return Ok(None),
+ Err(err) if is_symlinked(&path) => {
+ tracing::warn!(
+ "ignoring symlinked session pointer {}: {err}",
+ path.display()
+ );
+ return Ok(None);
+ }
+ Err(err) => return Err(err.into()),
+ };
+ let mut id = String::new();
+ file.read_to_string(&mut id)?;
+ let id = id.trim().to_string();
+ if id.is_empty() || validate_session_id(&id).is_err() {
+ return Ok(None);
+ }
+ Ok(Some(id))
+}
+
+pub fn write_current_session_pointer(session_id: &str) -> Result<(), AppError> {
+ validate_session_id(session_id)?;
+ write_private_file(&current_session_path()?, session_id.as_bytes())
+}
+
+pub fn clear_current_session_pointer() -> Result<(), AppError> {
+ match std::fs::remove_file(current_session_path()?) {
+ Ok(()) => Ok(()),
+ Err(err) if err.kind() == ErrorKind::NotFound => Ok(()),
+ Err(err) => Err(err.into()),
+ }
+}
+
+pub fn read_manifest(session_id: &str) -> Result<Option<SessionManifest>, AppError> {
+ let path = manifest_path(session_id)?;
+ let mut file = match open_session_file(&path) {
+ Ok(file) => file,
+ Err(err) if err.kind() == ErrorKind::NotFound => return Ok(None),
+ Err(err) => return Ok(ignore_unreadable_manifest(&path, &err)),
+ };
+ let mut json = String::new();
+ if let Err(err) = file.read_to_string(&mut json) {
+ return Ok(ignore_unreadable_manifest(&path, &err));
+ }
+ match serde_json::from_str(&json) {
+ Ok(manifest) => Ok(Some(manifest)),
+ Err(err) => Ok(ignore_unreadable_manifest(&path, &err)),
+ }
+}
+
+fn is_symlinked(path: &Path) -> bool {
+ std::fs::symlink_metadata(path)
+ .map(|meta| meta.file_type().is_symlink())
+ .unwrap_or(false)
+}
+
+fn ignore_unreadable_manifest<E: std::fmt::Display>(
+ path: &Path,
+ err: &E,
+) -> Option<SessionManifest> {
+ tracing::warn!(
+ "ignoring unreadable session manifest {}: {err}",
+ path.display()
+ );
+ None
+}
+
+pub fn write_manifest(manifest: &SessionManifest) -> Result<(), AppError> {
+ validate_session_id(&manifest.id)?;
+ let json = serde_json::to_string_pretty(manifest)?;
+ write_private_file(&manifest_path(&manifest.id)?, json.as_bytes())
+}
+
+pub fn trace_enabled_for_session(session_id: &str) -> Result<bool, AppError> {
+ Ok(read_manifest(session_id)?.is_some_and(|manifest| manifest.trace_enabled()))
+}
+
+pub fn new_session_id() -> String {
+ let n = SESSION_COUNTER.fetch_add(1, Ordering::Relaxed);
+ let pid = std::process::id();
+ format!("run-{}-{pid}-{n}", now_millis())
+}
+
+pub fn validate_session_name(name: &str) -> Result<String, AppError> {
+ if name.is_empty() {
+ return Err(AppError::invalid_input_with_suggestion(
+ "Session name must not be empty",
+ "Omit --name or provide a short descriptive label.",
+ ));
+ }
+ if name.len() > 128 {
+ return Err(AppError::invalid_input_with_suggestion(
+ "Session name must be at most 128 characters",
+ "Use a shorter session name.",
+ ));
+ }
+ if name.chars().any(char::is_control) {
+ return Err(AppError::invalid_input_with_suggestion(
+ "Session name must not contain control characters",
+ "Use printable ASCII or Unicode text for --name.",
+ ));
+ }
+ Ok(name.to_string())
+}
+
+pub fn list_sessions() -> Result<Vec<SessionManifest>, AppError> {
+ let sessions_root = agent_desktop_dir()?.join("sessions");
+ let Ok(entries) = std::fs::read_dir(sessions_root) else {
+ return Ok(Vec::new());
+ };
+ let mut manifests = Vec::new();
+ for entry in entries.flatten() {
+ let Ok(file_type) = entry.file_type() else {
+ continue;
+ };
+ if !file_type.is_dir() {
+ continue;
+ }
+ let name = entry.file_name();
+ let Some(name) = name.to_str() else {
+ continue;
+ };
+ if validate_session_id(name).is_err() {
+ continue;
+ }
+ if let Some(manifest) = read_manifest(name)? {
+ manifests.push(manifest);
+ }
+ }
+ manifests.sort_by_key(|manifest| manifest.created_at);
+ Ok(manifests)
+}
+
+pub fn start_session(options: StartSessionOptions) -> Result<SessionManifest, AppError> {
+ if !options.force && pointer_references_live_session()? {
+ return Err(AppError::invalid_input_with_suggestion(
+ "Refusing to clobber the current session pointer while it references a live session",
+ "Run `session end` first, set AGENT_DESKTOP_SESSION for concurrent work, or pass --force.",
+ ));
+ }
+ let id = new_session_id();
+ let name = options
+ .name
+ .map(|name| validate_session_name(&name))
+ .transpose()?;
+ let dir = session_dir(&id)?;
+ create_session_tree(&dir)?;
+ let manifest = SessionManifest {
+ id: id.clone(),
+ name,
+ created_at: now_millis(),
+ ended_at: None,
+ trace: options.trace,
+ };
+ write_manifest(&manifest)?;
+ write_current_session_pointer(&id)?;
+ Ok(manifest)
+}
+
+pub fn end_session(session_id: Option<&str>) -> Result<SessionManifest, AppError> {
+ let id = match session_id {
+ Some(id) => {
+ validate_session_id(id)?;
+ id.to_string()
+ }
+ None => read_current_session_pointer()?.ok_or_else(|| {
+ AppError::invalid_input_with_suggestion(
+ "No active session to end",
+ "Pass a session id or run `session start` first.",
+ )
+ })?,
+ };
+ let mut manifest = read_manifest(&id)?.ok_or_else(|| {
+ AppError::invalid_input_with_suggestion(
+ format!("Session '{id}' has no manifest"),
+ "Use `session list` to see known sessions.",
+ )
+ })?;
+ if manifest.ended_at.is_none() {
+ manifest.ended_at = Some(now_millis());
+ write_manifest(&manifest)?;
+ }
+ if read_current_session_pointer()?.as_deref() == Some(id.as_str()) {
+ clear_current_session_pointer()?;
+ }
+ Ok(manifest)
+}
+
+fn create_session_tree(dir: &Path) -> Result<(), AppError> {
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::DirBuilderExt;
+ std::fs::DirBuilder::new()
+ .recursive(true)
+ .mode(0o700)
+ .create(dir)?;
+ std::fs::DirBuilder::new()
+ .recursive(true)
+ .mode(0o700)
+ .create(dir.join("trace"))?;
+ }
+ #[cfg(not(unix))]
+ {
+ std::fs::create_dir_all(dir.join("trace"))?;
+ }
+ Ok(())
+}
+
+fn manifest_path(session_id: &str) -> Result<PathBuf, AppError> {
+ Ok(session_dir(session_id)?.join(SESSION_MANIFEST_FILE))
+}
+
+pub(super) fn now_millis() -> u64 {
+ SystemTime::now()
+ .duration_since(UNIX_EPOCH)
+ .map(|d| d.as_millis() as u64)
+ .unwrap_or(0)
+}
+
+fn open_session_file(path: &Path) -> std::io::Result<std::fs::File> {
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::OpenOptionsExt;
+ std::fs::OpenOptions::new()
+ .read(true)
+ .custom_flags(libc::O_NOFOLLOW)
+ .open(path)
+ }
+ #[cfg(not(unix))]
+ {
+ if std::fs::symlink_metadata(path)?.file_type().is_symlink() {
+ return Err(std::io::Error::new(
+ ErrorKind::PermissionDenied,
+ "session path must not be a symlink",
+ ));
+ }
+ std::fs::File::open(path)
+ }
+}
+
+#[cfg(test)]
+#[path = "session_tests.rs"]
+mod tests;
diff --git a/crates/core/src/session/session_tests.rs b/crates/core/src/session/session_tests.rs
new file mode 100644
index 000000000..7a3aaceca
--- /dev/null
+++ b/crates/core/src/session/session_tests.rs
@@ -0,0 +1,352 @@
+use super::*;
+use crate::refs_lock::RefStoreLock;
+use crate::refs_test_support::HomeGuard;
+use crate::session::SessionTraceMode;
+use std::fs;
+use std::time::Duration;
+
+#[test]
+fn resolve_prefers_explicit_over_env_and_pointer() {
+ let _guard = HomeGuard::new();
+ write_current_session_pointer("pointer").unwrap();
+ unsafe { std::env::set_var("AGENT_DESKTOP_SESSION", "env-session") };
+ let resolved = resolve_active_session(Some("explicit"), None).unwrap();
+ assert_eq!(resolved.as_deref(), Some("explicit"));
+ unsafe { std::env::remove_var("AGENT_DESKTOP_SESSION") };
+}
+
+#[test]
+fn resolve_prefers_env_over_pointer() {
+ let _guard = HomeGuard::new();
+ write_current_session_pointer("pointer").unwrap();
+ unsafe { std::env::set_var("AGENT_DESKTOP_SESSION", "env-session") };
+ let resolved = resolve_active_session(None, Some("env-session")).unwrap();
+ assert_eq!(resolved.as_deref(), Some("env-session"));
+ unsafe { std::env::remove_var("AGENT_DESKTOP_SESSION") };
+}
+
+#[test]
+fn resolve_falls_back_to_pointer() {
+ let _guard = HomeGuard::new();
+ write_current_session_pointer("pointer").unwrap();
+ let resolved = resolve_active_session(None, None).unwrap();
+ assert_eq!(resolved.as_deref(), Some("pointer"));
+}
+
+#[test]
+fn resolve_none_without_pointer() {
+ let _guard = HomeGuard::new();
+ let resolved = resolve_active_session(None, None).unwrap();
+ assert!(resolved.is_none());
+}
+
+#[test]
+fn manifest_round_trips_with_optional_fields() {
+ let _guard = HomeGuard::new();
+ let manifest = SessionManifest {
+ id: "run-1".into(),
+ name: Some("demo".into()),
+ created_at: 1,
+ ended_at: None,
+ trace: SessionTraceMode::On,
+ };
+ write_manifest(&manifest).unwrap();
+ let loaded = read_manifest("run-1").unwrap().expect("manifest");
+ assert_eq!(loaded, manifest);
+}
+
+#[test]
+fn validate_session_name_rejects_control_chars() {
+ let err = validate_session_name("bad\u{1}name").unwrap_err();
+ assert_eq!(err.code(), "INVALID_ARGS");
+}
+
+#[test]
+fn start_creates_tree_manifest_and_pointer() {
+ let _guard = HomeGuard::new();
+ let manifest = start_session(StartSessionOptions {
+ name: Some("demo".into()),
+ trace: SessionTraceMode::On,
+ force: false,
+ })
+ .unwrap();
+ assert!(session_dir(&manifest.id).unwrap().join("trace").is_dir());
+ assert_eq!(
+ read_current_session_pointer().unwrap().as_deref(),
+ Some(manifest.id.as_str())
+ );
+}
+
+#[test]
+fn start_refuses_live_pointer_without_force() {
+ let _guard = HomeGuard::new();
+ let first = start_session(StartSessionOptions {
+ name: None,
+ trace: SessionTraceMode::On,
+ force: false,
+ })
+ .unwrap();
+ let _lock = RefStoreLock::acquire(
+ &crate::refs_store::RefStore::for_session(Some(&first.id))
+ .unwrap()
+ .base_dir()
+ .join("refstore.lock"),
+ )
+ .unwrap();
+ let err = start_session(StartSessionOptions {
+ name: None,
+ trace: SessionTraceMode::On,
+ force: false,
+ })
+ .unwrap_err();
+ assert_eq!(err.code(), "INVALID_ARGS");
+}
+
+#[test]
+fn end_seals_manifest_and_clears_pointer() {
+ let _guard = HomeGuard::new();
+ let _manifest = start_session(StartSessionOptions {
+ name: None,
+ trace: SessionTraceMode::On,
+ force: false,
+ })
+ .unwrap();
+ let ended = end_session(None).unwrap();
+ assert!(ended.ended_at.is_some());
+ assert!(read_current_session_pointer().unwrap().is_none());
+}
+
+#[test]
+fn gc_removes_ended_sessions_but_not_pointer_or_live() {
+ let _guard = HomeGuard::new();
+ let live = start_session(StartSessionOptions {
+ name: None,
+ trace: SessionTraceMode::On,
+ force: false,
+ })
+ .unwrap();
+ let ended = start_session(StartSessionOptions {
+ name: None,
+ trace: SessionTraceMode::On,
+ force: true,
+ })
+ .unwrap();
+ end_session(Some(&ended.id)).unwrap();
+ let report = gc(GcOptions {
+ ended_only: false,
+ older_than: None,
+ })
+ .unwrap();
+ assert!(report.removed.contains(&ended.id));
+ assert!(!report.removed.contains(&live.id));
+ assert!(session_dir(&live.id).unwrap().is_dir());
+ assert!(!session_dir(&ended.id).unwrap().exists());
+}
+
+#[test]
+#[cfg(unix)]
+fn remove_session_dir_rejects_symlink() {
+ let _guard = HomeGuard::new();
+ let dir = session_dir("symlink-session").unwrap();
+ let target = dir.with_extension("target");
+ fs::create_dir_all(&target).unwrap();
+ std::os::unix::fs::symlink(&target, &dir).unwrap();
+ let err = super::gc::remove_session_dir(&dir).unwrap_err();
+ assert_eq!(err.code(), "INVALID_ARGS");
+}
+
+#[test]
+fn list_reports_manifest_fields_only() {
+ let _guard = HomeGuard::new();
+ let manifest = start_session(StartSessionOptions {
+ name: Some("listed".into()),
+ trace: SessionTraceMode::On,
+ force: false,
+ })
+ .unwrap();
+ let listed = list_sessions().unwrap();
+ assert!(listed.iter().any(|entry| entry.id == manifest.id));
+}
+
+#[test]
+fn trace_enabled_requires_manifest_on() {
+ let _guard = HomeGuard::new();
+ assert!(!trace_enabled_for_session("missing").unwrap());
+ let manifest = start_session(StartSessionOptions {
+ name: None,
+ trace: SessionTraceMode::Off,
+ force: false,
+ })
+ .unwrap();
+ assert!(!trace_enabled_for_session(&manifest.id).unwrap());
+}
+
+#[test]
+fn gc_respects_older_than_threshold() {
+ let _guard = HomeGuard::new();
+ let manifest = start_session(StartSessionOptions {
+ name: None,
+ trace: SessionTraceMode::Off,
+ force: false,
+ })
+ .unwrap();
+ end_session(Some(&manifest.id)).unwrap();
+ clear_current_session_pointer().unwrap();
+ let report = gc(GcOptions {
+ ended_only: false,
+ older_than: Some(Duration::from_secs(3600)),
+ })
+ .unwrap();
+ assert!(report.removed.is_empty());
+}
+
+#[test]
+fn new_session_id_includes_process_id() {
+ let id = new_session_id();
+ assert!(id.contains(&std::process::id().to_string()));
+ validate_session_id(&id).expect("new_session_id must always be a valid session id");
+}
+
+#[test]
+fn corrupt_manifest_is_ignored_not_fatal() {
+ let _guard = HomeGuard::new();
+ let good = start_session(StartSessionOptions {
+ name: None,
+ trace: SessionTraceMode::Off,
+ force: true,
+ })
+ .unwrap();
+ let bad_dir = session_dir("corruptsess").unwrap();
+ fs::create_dir_all(&bad_dir).unwrap();
+ fs::write(bad_dir.join("session.json"), b"{ not valid json").unwrap();
+
+ assert!(!trace_enabled_for_session("corruptsess").unwrap());
+ let listed: Vec<String> = list_sessions().unwrap().into_iter().map(|m| m.id).collect();
+ assert!(listed.contains(&good.id));
+ assert!(!listed.iter().any(|id| id == "corruptsess"));
+}
+
+#[cfg(unix)]
+#[test]
+fn unreadable_manifest_is_skipped_not_fatal_for_list_and_gc() {
+ use std::os::unix::fs::PermissionsExt;
+
+ if unsafe { libc::geteuid() } == 0 {
+ return;
+ }
+ let _guard = HomeGuard::new();
+ let good = start_session(StartSessionOptions {
+ name: None,
+ trace: SessionTraceMode::Off,
+ force: true,
+ })
+ .unwrap();
+ let bad_dir = session_dir("unreadablesess").unwrap();
+ fs::create_dir_all(&bad_dir).unwrap();
+ let manifest = bad_dir.join("session.json");
+ fs::write(&manifest, b"{}").unwrap();
+ fs::set_permissions(&manifest, fs::Permissions::from_mode(0o000)).unwrap();
+
+ let listed: Vec<String> = list_sessions().unwrap().into_iter().map(|m| m.id).collect();
+ assert!(listed.contains(&good.id));
+ assert!(!listed.iter().any(|id| id == "unreadablesess"));
+ assert!(read_manifest("unreadablesess").unwrap().is_none());
+
+ fs::set_permissions(&manifest, fs::Permissions::from_mode(0o600)).unwrap();
+}
+
+#[test]
+fn gc_leaves_recently_created_unended_session() {
+ let _guard = HomeGuard::new();
+ let started = start_session(StartSessionOptions {
+ name: None,
+ trace: SessionTraceMode::Off,
+ force: true,
+ })
+ .unwrap();
+ clear_current_session_pointer().unwrap();
+ let report = gc(GcOptions {
+ ended_only: false,
+ older_than: Some(Duration::from_secs(0)),
+ })
+ .unwrap();
+ assert!(!report.removed.contains(&started.id));
+ assert!(session_dir(&started.id).unwrap().is_dir());
+}
+
+#[test]
+fn start_with_force_overrides_live_pointer() {
+ let _guard = HomeGuard::new();
+ let first = start_session(StartSessionOptions {
+ name: None,
+ trace: SessionTraceMode::On,
+ force: false,
+ })
+ .unwrap();
+ let _lock = RefStoreLock::acquire(
+ &crate::refs_store::RefStore::for_session(Some(&first.id))
+ .unwrap()
+ .base_dir()
+ .join("refstore.lock"),
+ )
+ .unwrap();
+ let second = start_session(StartSessionOptions {
+ name: None,
+ trace: SessionTraceMode::On,
+ force: true,
+ })
+ .unwrap();
+ assert_ne!(first.id, second.id);
+ assert_eq!(
+ read_current_session_pointer().unwrap().as_deref(),
+ Some(second.id.as_str())
+ );
+}
+
+#[test]
+fn trace_enabled_false_once_session_ended() {
+ let _guard = HomeGuard::new();
+ let manifest = start_session(StartSessionOptions {
+ name: None,
+ trace: SessionTraceMode::On,
+ force: false,
+ })
+ .unwrap();
+ assert!(trace_enabled_for_session(&manifest.id).unwrap());
+ end_session(Some(&manifest.id)).unwrap();
+ assert!(!trace_enabled_for_session(&manifest.id).unwrap());
+}
+
+#[cfg(unix)]
+#[test]
+fn symlinked_manifest_is_ignored_not_fatal() {
+ let _guard = HomeGuard::new();
+ let good = start_session(StartSessionOptions {
+ name: None,
+ trace: SessionTraceMode::Off,
+ force: true,
+ })
+ .unwrap();
+ let dir = session_dir("symsess").unwrap();
+ fs::create_dir_all(&dir).unwrap();
+ let target = dir.with_extension("target");
+ fs::write(&target, b"{}").unwrap();
+ std::os::unix::fs::symlink(&target, dir.join("session.json")).unwrap();
+
+ assert!(!trace_enabled_for_session("symsess").unwrap());
+ let ids: Vec<String> = list_sessions().unwrap().into_iter().map(|m| m.id).collect();
+ assert!(ids.contains(&good.id));
+ assert!(!ids.iter().any(|id| id == "symsess"));
+}
+
+#[cfg(unix)]
+#[test]
+fn symlinked_session_pointer_degrades_to_none() {
+ let _guard = HomeGuard::new();
+ let target = agent_desktop_dir().unwrap().join("pointer-target");
+ fs::create_dir_all(target.parent().unwrap()).unwrap();
+ fs::write(&target, b"whatever").unwrap();
+ std::os::unix::fs::symlink(&target, current_session_path().unwrap()).unwrap();
+
+ assert!(read_current_session_pointer().unwrap().is_none());
+}
diff --git a/crates/core/src/trace.rs b/crates/core/src/trace.rs
index 171d9b85c..089200909 100644
--- a/crates/core/src/trace.rs
+++ b/crates/core/src/trace.rs
@@ -1,37 +1,78 @@
use crate::error::AppError;
use serde_json::{Map, Value, json};
+use std::io::Write;
use std::path::{Path, PathBuf};
-use std::sync::{Arc, Mutex};
+use std::sync::atomic::{AtomicU64, Ordering};
+use std::sync::{Arc, Mutex, OnceLock};
const MAX_TRACE_FILE_BYTES: u64 = 64 * 1024 * 1024;
+static EVENT_SEQ: AtomicU64 = AtomicU64::new(0);
+
+#[derive(Debug, Clone, Default)]
+enum TracePending {
+ #[default]
+ None,
+ File(PathBuf),
+ SegmentDir(PathBuf),
+}
+
+#[derive(Debug, Clone, Default)]
+enum WriterState {
+ #[default]
+ Unopened,
+ Open(Arc<Mutex<std::fs::File>>),
+ Failed,
+}
+
+#[derive(Debug, Clone, Default)]
+struct TraceState {
+ pending: TracePending,
+ writer: Arc<Mutex<WriterState>>,
+}
+
#[derive(Debug, Clone, Default)]
pub struct TraceConfig {
strict: bool,
- writer: Option<Arc<Mutex<std::fs::File>>>,
+ state: Arc<TraceState>,
}
impl TraceConfig {
- pub fn new(path: Option<PathBuf>, strict: bool) -> Result<Self, AppError> {
- if strict && path.is_none() {
+ pub fn build(
+ explicit_path: Option<PathBuf>,
+ session_segment_dir: Option<PathBuf>,
+ strict: bool,
+ ) -> Result<Self, AppError> {
+ if strict && explicit_path.is_none() && session_segment_dir.is_none() {
return Err(AppError::invalid_input_with_suggestion(
- "--trace-strict requires --trace",
- "Provide --trace <path> or remove --trace-strict.",
+ "--trace-strict requires --trace or an active trace-enabled session",
+ "Provide --trace <path>, start a session with tracing, or remove --trace-strict.",
));
}
- let writer = match path.as_deref() {
- Some(path) => match open_trace_file(path) {
- Ok(file) => Some(Arc::new(Mutex::new(file))),
- Err(err) if err.code() == "INVALID_ARGS" => return Err(err),
- Err(err) if strict => return Err(err),
+ let (pending, writer) = match explicit_path {
+ Some(path) => match open_trace_file(&path) {
+ Ok(file) => (
+ TracePending::File(path),
+ WriterState::Open(Arc::new(Mutex::new(file))),
+ ),
+ Err(err) if strict || err.code() == "INVALID_ARGS" => return Err(err),
Err(err) => {
tracing::warn!("trace open failed: {err}");
- None
+ (TracePending::File(path), WriterState::Failed)
}
},
- None => None,
+ None => match session_segment_dir {
+ Some(dir) => (TracePending::SegmentDir(dir), WriterState::Unopened),
+ None => (TracePending::None, WriterState::Unopened),
+ },
};
- Ok(Self { strict, writer })
+ Ok(Self {
+ strict,
+ state: Arc::new(TraceState {
+ pending,
+ writer: Arc::new(Mutex::new(writer)),
+ }),
+ })
}
pub fn emit(
@@ -49,8 +90,9 @@ impl TraceConfig {
session_id: Option<&str>,
fields: impl FnOnce() -> Value,
) -> Result<(), AppError> {
- let Some(writer) = self.writer.as_ref() else {
- return Ok(());
+ let writer = match self.ensure_writer()? {
+ Some(writer) => writer,
+ None => return Ok(()),
};
match writer
.lock()
@@ -65,6 +107,119 @@ impl TraceConfig {
}
}
}
+
+ fn ensure_writer(&self) -> Result<Option<Arc<Mutex<std::fs::File>>>, AppError> {
+ let mut writer = self
+ .state
+ .writer
+ .lock()
+ .map_err(|_| AppError::Internal("trace writer lock poisoned".into()))?;
+ match &*writer {
+ WriterState::Open(file) => return Ok(Some(file.clone())),
+ WriterState::Failed => return Ok(None),
+ WriterState::Unopened => {}
+ }
+ let open_result = match &self.state.pending {
+ TracePending::None => {
+ *writer = WriterState::Failed;
+ return Ok(None);
+ }
+ TracePending::File(path) => open_trace_file(path),
+ TracePending::SegmentDir(dir) => open_segment_trace_file(dir),
+ };
+ match open_result {
+ Ok(file) => {
+ let file = Arc::new(Mutex::new(file));
+ *writer = WriterState::Open(file.clone());
+ Ok(Some(file))
+ }
+ Err(err) if self.strict => Err(err),
+ Err(err) if err.code() == "INVALID_ARGS" => Err(err),
+ Err(err) => {
+ tracing::warn!("trace open failed: {err}");
+ *writer = WriterState::Failed;
+ Ok(None)
+ }
+ }
+ }
+
+ pub(crate) fn has_sink(&self) -> bool {
+ if matches!(self.state.pending, TracePending::None) {
+ return false;
+ }
+ match self.state.writer.lock() {
+ Ok(writer) => !matches!(*writer, WriterState::Failed),
+ Err(_) => true,
+ }
+ }
+
+ pub(crate) fn pending_file_path(&self) -> Option<&Path> {
+ match &self.state.pending {
+ TracePending::File(path) => Some(path),
+ _ => None,
+ }
+ }
+
+ pub(crate) fn clone_with_session_segment(
+ &self,
+ session_segment_dir: Option<PathBuf>,
+ ) -> Result<Self, AppError> {
+ if self.pending_file_path().is_some() {
+ return Ok(self.clone());
+ }
+ match session_segment_dir {
+ Some(dir) => Self::build(None, Some(dir), self.strict),
+ None => Ok(Self {
+ strict: self.strict,
+ state: Arc::new(TraceState::default()),
+ }),
+ }
+ }
+}
+
+fn process_segment_suffix() -> &'static str {
+ static SUFFIX: OnceLock<String> = OnceLock::new();
+ SUFFIX.get_or_init(|| {
+ let ts = std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .map(|d| d.as_millis())
+ .unwrap_or(0);
+ format!("{}-{ts}", std::process::id())
+ })
+}
+
+pub(crate) fn segment_path_for_dir(dir: &Path) -> PathBuf {
+ dir.join(format!("{}.jsonl", process_segment_suffix()))
+}
+
+fn open_segment_trace_file(dir: &Path) -> Result<std::fs::File, AppError> {
+ ensure_trace_dir(dir)?;
+ open_trace_file(&segment_path_for_dir(dir))
+}
+
+fn ensure_trace_dir(dir: &Path) -> Result<(), AppError> {
+ if let Ok(meta) = std::fs::symlink_metadata(dir) {
+ if meta.file_type().is_symlink() {
+ return Err(AppError::invalid_input_with_suggestion(
+ "Refusing to write trace segments through a symlinked trace directory",
+ "Remove the symlink under the session's trace/ directory.",
+ ));
+ }
+ }
+ if dir.is_dir() {
+ return Ok(());
+ }
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::DirBuilderExt;
+ std::fs::DirBuilder::new()
+ .recursive(true)
+ .mode(0o700)
+ .create(dir)?;
+ }
+ #[cfg(not(unix))]
+ std::fs::create_dir_all(dir)?;
+ Ok(())
}
fn open_trace_file(path: &Path) -> Result<std::fs::File, AppError> {
@@ -99,6 +254,10 @@ fn write_event(
.as_millis()
),
);
+ body.insert(
+ "seq".to_string(),
+ json!(EVENT_SEQ.fetch_add(1, Ordering::Relaxed)),
+ );
if let Value::Object(fields) = sanitize_trace_value(fields) {
for (key, value) in fields {
body.insert(key, value);
@@ -107,9 +266,10 @@ fn write_event(
if let Some(sid) = session_id {
body.insert("session_id".to_string(), json!(sid));
}
- serde_json::to_writer(&mut *file, &Value::Object(body))?;
- use std::io::Write;
- file.write_all(b"\n").map_err(AppError::from)
+ let mut line = Vec::new();
+ serde_json::to_writer(&mut line, &Value::Object(body))?;
+ line.push(b'\n');
+ file.write_all(&line).map_err(AppError::from)
}
fn reject_oversized_trace(file: &std::fs::File) -> Result<(), AppError> {
@@ -225,98 +385,5 @@ fn redacted_value(value: Value) -> Value {
}
#[cfg(test)]
-mod tests {
- use super::*;
-
- #[cfg(unix)]
- #[test]
- fn trace_open_rejects_symlink_paths() {
- let base = std::env::temp_dir().join(format!(
- "agent-desktop-trace-symlink-{}",
- std::time::SystemTime::now()
- .duration_since(std::time::UNIX_EPOCH)
- .unwrap()
- .as_nanos()
- ));
- let target = base.with_extension("target");
- let link = base.with_extension("link");
- std::fs::write(&target, b"existing").unwrap();
- std::os::unix::fs::symlink(&target, &link).unwrap();
-
- let result = open_trace_file(&link);
-
- assert!(result.is_err());
- let _ = std::fs::remove_file(&link);
- let _ = std::fs::remove_file(&target);
- }
-
- #[test]
- fn trace_redacts_sensitive_fields_but_preserves_messages() {
- let value = sanitize_trace_value(json!({
- "text": "secret",
- "message": "Target is not actionable: supported_action failed",
- "details": { "name": "Private Button" },
- "title": "Window"
- }));
-
- assert_eq!(value["text"]["redacted"], true);
- assert_eq!(value["details"]["name"]["redacted"], true);
- assert_eq!(value["title"]["redacted"], true);
- assert_eq!(
- value["message"],
- "Target is not actionable: supported_action failed"
- );
- }
-
- #[test]
- fn trace_redaction_covers_nested_shapes_and_substring_keys() {
- let value = sanitize_trace_value(json!({
- "action": {
- "typed_text": ["secret", "another"],
- "api_token": {"kind": "bearer"},
- "typedText": "secret",
- "apiToken": "secret",
- "targetLabel": "secret",
- "userName": "secret",
- "filename": "report.txt",
- "password": null,
- "counter": 3
- }
- }));
-
- assert_eq!(value["action"]["typed_text"]["redacted"], true);
- assert_eq!(value["action"]["api_token"]["redacted"], true);
- assert_eq!(value["action"]["typedText"]["redacted"], true);
- assert_eq!(value["action"]["apiToken"]["redacted"], true);
- assert_eq!(value["action"]["targetLabel"]["redacted"], true);
- assert_eq!(value["action"]["userName"]["redacted"], true);
- assert_eq!(value["action"]["filename"], "report.txt");
- assert!(value["action"]["password"].is_null());
- assert_eq!(value["action"]["counter"], 3);
- }
-
- #[test]
- fn trace_write_rejects_files_at_size_cap() {
- let path = std::env::temp_dir().join(format!(
- "agent-desktop-trace-cap-{}",
- std::time::SystemTime::now()
- .duration_since(std::time::UNIX_EPOCH)
- .unwrap()
- .as_nanos()
- ));
- let file = std::fs::File::create(&path).unwrap();
- file.set_len(MAX_TRACE_FILE_BYTES).unwrap();
- drop(file);
- #[cfg(unix)]
- {
- use std::os::unix::fs::PermissionsExt;
- std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)).unwrap();
- }
- let mut file = open_trace_file(&path).unwrap();
-
- let err = write_event(&mut file, "event", None, json!({})).unwrap_err();
-
- assert_eq!(err.code(), "INVALID_ARGS");
- let _ = std::fs::remove_file(path);
- }
-}
+#[path = "trace_tests.rs"]
+mod tests;
diff --git a/crates/core/src/trace_tests.rs b/crates/core/src/trace_tests.rs
new file mode 100644
index 000000000..2668cc478
--- /dev/null
+++ b/crates/core/src/trace_tests.rs
@@ -0,0 +1,287 @@
+use super::*;
+use crate::refs_test_support::HomeGuard;
+use serde_json::json;
+use std::fs;
+
+#[cfg(unix)]
+#[test]
+fn trace_open_rejects_symlink_paths() {
+ let base = std::env::temp_dir().join(format!(
+ "agent-desktop-trace-symlink-{}",
+ std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap()
+ .as_nanos()
+ ));
+ let target = base.with_extension("target");
+ let link = base.with_extension("link");
+ fs::write(&target, b"existing").unwrap();
+ std::os::unix::fs::symlink(&target, &link).unwrap();
+
+ let result = open_trace_file(&link);
+
+ assert!(result.is_err());
+ let _ = fs::remove_file(&link);
+ let _ = fs::remove_file(&target);
+}
+
+#[test]
+fn trace_redacts_sensitive_fields_but_preserves_messages() {
+ let value = sanitize_trace_value(json!({
+ "text": "secret",
+ "message": "Target is not actionable: supported_action failed",
+ "details": { "name": "Private Button" },
+ "title": "Window"
+ }));
+
+ assert_eq!(value["text"]["redacted"], true);
+ assert_eq!(value["details"]["name"]["redacted"], true);
+ assert_eq!(value["title"]["redacted"], true);
+ assert_eq!(
+ value["message"],
+ "Target is not actionable: supported_action failed"
+ );
+}
+
+#[test]
+fn trace_redaction_covers_nested_shapes_and_substring_keys() {
+ let value = sanitize_trace_value(json!({
+ "action": {
+ "typed_text": ["secret", "another"],
+ "api_token": {"kind": "bearer"},
+ "typedText": "secret",
+ "apiToken": "secret",
+ "targetLabel": "secret",
+ "userName": "secret",
+ "filename": "report.txt",
+ "password": null,
+ "counter": 3
+ }
+ }));
+
+ assert_eq!(value["action"]["typed_text"]["redacted"], true);
+ assert_eq!(value["action"]["api_token"]["redacted"], true);
+ assert_eq!(value["action"]["typedText"]["redacted"], true);
+ assert_eq!(value["action"]["apiToken"]["redacted"], true);
+ assert_eq!(value["action"]["targetLabel"]["redacted"], true);
+ assert_eq!(value["action"]["userName"]["redacted"], true);
+ assert_eq!(value["action"]["filename"], "report.txt");
+ assert!(value["action"]["password"].is_null());
+ assert_eq!(value["action"]["counter"], 3);
+}
+
+#[test]
+fn trace_write_rejects_files_at_size_cap() {
+ let path = std::env::temp_dir().join(format!(
+ "agent-desktop-trace-cap-{}",
+ std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap()
+ .as_nanos()
+ ));
+ let file = fs::File::create(&path).unwrap();
+ file.set_len(MAX_TRACE_FILE_BYTES).unwrap();
+ drop(file);
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+ fs::set_permissions(&path, fs::Permissions::from_mode(0o600)).unwrap();
+ }
+ let mut file = open_trace_file(&path).unwrap();
+
+ let err = write_event(&mut file, "event", None, json!({})).unwrap_err();
+
+ assert_eq!(err.code(), "INVALID_ARGS");
+ let _ = fs::remove_file(path);
+}
+
+#[test]
+fn segment_configs_in_same_process_share_filename() {
+ let dir_a = std::env::temp_dir().join(format!(
+ "agent-desktop-seg-a-{}",
+ std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap()
+ .as_nanos()
+ ));
+ let dir_b = dir_a.with_extension("b");
+ let path_a = segment_path_for_dir(&dir_a);
+ let path_b = segment_path_for_dir(&dir_b);
+ assert_eq!(path_a.file_name(), path_b.file_name());
+}
+
+#[test]
+fn explicit_trace_opens_eagerly_at_build() {
+ let path = std::env::temp_dir().join(format!(
+ "agent-desktop-eager-{}",
+ std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap()
+ .as_nanos()
+ ));
+ let _ = fs::remove_file(&path);
+ let config = TraceConfig::build(Some(path.clone()), None, false).unwrap();
+ assert!(
+ path.exists(),
+ "explicit --trace validates and opens the destination at build (fail-fast)"
+ );
+ config.emit("event", None, json!({})).unwrap();
+ assert!(path.exists());
+ let _ = fs::remove_file(path);
+}
+
+#[test]
+fn segment_lazy_open_creates_trace_dir_on_first_event() {
+ let _guard = HomeGuard::new();
+ let trace_dir = crate::refs_store::RefStore::for_session(Some("run-42"))
+ .unwrap()
+ .trace_dir();
+ assert!(!trace_dir.exists());
+ let config = TraceConfig::build(None, Some(trace_dir.clone()), false).unwrap();
+ config.emit("event", Some("run-42"), json!({})).unwrap();
+ assert!(trace_dir.is_dir());
+ let segment = segment_path_for_dir(&trace_dir);
+ assert!(segment.is_file());
+ assert!(segment.metadata().unwrap().len() > 0);
+}
+
+#[test]
+fn write_event_emits_single_atomic_jsonl_line_with_seq() {
+ let path = std::env::temp_dir().join(format!(
+ "agent-desktop-atomic-{}",
+ std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap()
+ .as_nanos()
+ ));
+ let config = TraceConfig::build(Some(path.clone()), None, false).unwrap();
+ config.emit("first", None, json!({})).unwrap();
+ config.emit("second", None, json!({})).unwrap();
+ let body = fs::read_to_string(&path).unwrap();
+ let lines: Vec<&str> = body.lines().collect();
+ assert_eq!(lines.len(), 2);
+ let first: serde_json::Value = serde_json::from_str(lines[0]).unwrap();
+ let second: serde_json::Value = serde_json::from_str(lines[1]).unwrap();
+ assert_eq!(first["event"], "first");
+ assert_eq!(second["event"], "second");
+ assert!(first["seq"].as_u64().is_some());
+ assert!(second["seq"].as_u64().is_some());
+ assert!(second["seq"].as_u64().unwrap() > first["seq"].as_u64().unwrap());
+ let _ = fs::remove_file(path);
+}
+
+#[test]
+fn truncated_final_line_leaves_prior_lines_parseable() {
+ let path = std::env::temp_dir().join(format!(
+ "agent-desktop-trunc-{}",
+ std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap()
+ .as_nanos()
+ ));
+ let config = TraceConfig::build(Some(path.clone()), None, false).unwrap();
+ config.emit("ok", None, json!({})).unwrap();
+ let mut bytes = fs::read(&path).unwrap();
+ bytes.extend_from_slice(b"{\"event\":\"partial");
+ fs::write(&path, bytes).unwrap();
+ let body = fs::read_to_string(&path).unwrap();
+ let mut parsed = 0usize;
+ for line in body.lines() {
+ if serde_json::from_str::<serde_json::Value>(line).is_ok() {
+ parsed += 1;
+ }
+ }
+ assert_eq!(parsed, 1);
+ let _ = fs::remove_file(path);
+}
+
+#[test]
+fn strict_missing_trace_path_fails_at_build() {
+ let missing = std::env::temp_dir()
+ .join("agent-desktop-missing-dir")
+ .join("trace.jsonl");
+ assert!(TraceConfig::build(Some(missing), None, true).is_err());
+}
+
+#[test]
+fn best_effort_missing_trace_path_succeeds_silently() {
+ let missing = std::env::temp_dir()
+ .join("agent-desktop-missing-dir-best-effort")
+ .join("trace.jsonl");
+ let config = TraceConfig::build(Some(missing), None, false).unwrap();
+ assert!(config.emit("event", None, json!({})).is_ok());
+}
+
+#[cfg(unix)]
+#[test]
+fn trace_file_is_private_on_create() {
+ use std::os::unix::fs::PermissionsExt;
+
+ let path = std::env::temp_dir().join(format!(
+ "agent-desktop-private-trace-{}.jsonl",
+ std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap()
+ .as_nanos()
+ ));
+ let config = TraceConfig::build(Some(path.clone()), None, true).unwrap();
+ config.emit("event", None, json!({})).unwrap();
+
+ let mode = fs::metadata(&path).unwrap().permissions().mode() & 0o777;
+ assert_eq!(mode, 0o600);
+ let _ = fs::remove_file(path);
+}
+
+#[cfg(unix)]
+#[test]
+fn trace_rejects_loose_existing_file_permissions() {
+ use std::os::unix::fs::PermissionsExt;
+
+ let path = std::env::temp_dir().join(format!(
+ "agent-desktop-loose-trace-{}.jsonl",
+ std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap()
+ .as_nanos()
+ ));
+ fs::write(&path, "").unwrap();
+ fs::set_permissions(&path, fs::Permissions::from_mode(0o644)).unwrap();
+
+ let err = TraceConfig::build(Some(path.clone()), None, false).unwrap_err();
+
+ assert_eq!(err.code(), "INVALID_ARGS");
+ let _ = fs::remove_file(path);
+}
+
+#[cfg(unix)]
+#[test]
+fn segment_open_rejects_symlinked_trace_dir() {
+ let base = std::env::temp_dir().join(format!(
+ "agent-desktop-symtrace-{}",
+ std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap()
+ .as_nanos()
+ ));
+ let real = base.with_extension("real");
+ fs::create_dir_all(&real).unwrap();
+ std::os::unix::fs::symlink(&real, &base).unwrap();
+
+ let err = super::open_segment_trace_file(&base).unwrap_err();
+ assert_eq!(err.code(), "INVALID_ARGS");
+
+ let _ = fs::remove_file(&base);
+ let _ = fs::remove_dir_all(&real);
+}
+
+#[test]
+fn failed_writer_reports_no_sink() {
+ let missing = std::env::temp_dir()
+ .join("agent-desktop-nodir-hassink")
+ .join("trace.jsonl");
+ let config = TraceConfig::build(Some(missing), None, false).unwrap();
+ assert!(
+ !config.has_sink(),
+ "a trace writer whose open failed must not report an active sink"
+ );
+}
diff --git a/crates/ffi/README.md b/crates/ffi/README.md
index 4a537981c..51d6fe9f5 100644
--- a/crates/ffi/README.md
+++ b/crates/ffi/README.md
@@ -29,9 +29,10 @@ returns `PLATFORM_NOT_SUPPORTED` for every adapter call.
| Group | Key symbols |
|-------|-------------|
| ABI handshake | `ad_abi_version()`, `ad_init(expected_major)` |
-| Adapter lifecycle | `ad_adapter_create()`, `ad_adapter_destroy()` |
+| Adapter lifecycle | `ad_adapter_create()`, `ad_adapter_create_with_session(id)`, `ad_adapter_destroy()` |
| Command-backed JSON entrypoints | `ad_snapshot`, `ad_execute_by_ref`, `ad_wait`, `ad_version`, `ad_status` |
-| Log callback | `ad_set_log_callback(fn(level, msg))` |
+| Log callback | `ad_set_log_callback(fn(level, msg))` — unstructured tracing to a callback |
+| Structured file trace | Same JSONL contract as CLI, gated by a `trace: on` session manifest (no ABI change); use `session start` before creating a session adapter |
| Errno last-error | `ad_last_error_code()`, `ad_last_error_message()`, `ad_last_error_suggestion()`, `ad_last_error_platform_detail()` |
| Type accessors / size getters | `ad_*_size()`, `ad_*_list_{count,get,free}()`, `ad_image_buffer_*()` |
| Free helpers | `ad_free_string()`, `ad_free_handle()`, `ad_free_tree()`, `ad_free_action_result()` |
diff --git a/crates/ffi/tests/c_abi_session_trace.rs b/crates/ffi/tests/c_abi_session_trace.rs
new file mode 100644
index 000000000..99658758c
--- /dev/null
+++ b/crates/ffi/tests/c_abi_session_trace.rs
@@ -0,0 +1,107 @@
+mod common;
+
+use agent_desktop_core::session::{
+ SessionTraceMode, StartSessionOptions, start_session, trace_dir,
+};
+use common::{ad_adapter_create_with_session, ad_adapter_destroy, ad_check_permissions};
+use std::ffi::CString;
+use std::fs;
+use std::sync::Mutex;
+
+static HOME_LOCK: Mutex<()> = Mutex::new(());
+
+struct TestHome {
+ _lock: std::sync::MutexGuard<'static, ()>,
+ dir: std::path::PathBuf,
+ prev: Option<std::ffi::OsString>,
+}
+
+impl TestHome {
+ fn new() -> Self {
+ let lock = HOME_LOCK.lock().unwrap();
+ let dir = std::env::temp_dir().join(format!(
+ "agent-desktop-ffi-session-trace-{}",
+ std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap()
+ .as_nanos()
+ ));
+ fs::create_dir_all(&dir).unwrap();
+ let prev = std::env::var_os("HOME");
+ unsafe { std::env::set_var("HOME", &dir) };
+ Self {
+ _lock: lock,
+ dir,
+ prev,
+ }
+ }
+}
+
+impl Drop for TestHome {
+ fn drop(&mut self) {
+ match self.prev.as_ref() {
+ Some(prev) => unsafe { std::env::set_var("HOME", prev) },
+ None => unsafe { std::env::remove_var("HOME") },
+ }
+ let _ = fs::remove_dir_all(&self.dir);
+ }
+}
+
+fn trace_dir_for(session_id: &str) -> std::path::PathBuf {
+ trace_dir(session_id).unwrap()
+}
+
+#[test]
+fn ffi_trace_on_session_writes_segment() {
+ let _home = TestHome::new();
+ let manifest = start_session(StartSessionOptions {
+ name: None,
+ trace: SessionTraceMode::On,
+ force: false,
+ })
+ .unwrap();
+ for call in 0..2 {
+ unsafe {
+ let session = CString::new(manifest.id.as_str()).unwrap();
+ let ptr = ad_adapter_create_with_session(session.as_ptr());
+ assert!(!ptr.is_null());
+ let ctx = (*ptr)
+ .command_context()
+ .expect("command_context must succeed");
+ ctx.trace("ffi.event", serde_json::json!({ "call": call }))
+ .unwrap();
+ ad_adapter_destroy(ptr);
+ }
+ }
+ let trace_dir = trace_dir_for(&manifest.id);
+ let segments: Vec<_> = fs::read_dir(trace_dir)
+ .unwrap()
+ .flatten()
+ .filter(|entry| entry.path().extension().is_some_and(|ext| ext == "jsonl"))
+ .collect();
+ assert_eq!(
+ segments.len(),
+ 1,
+ "a long-lived process must write one segment across many FFI calls"
+ );
+ let body = fs::read_to_string(segments[0].path()).unwrap();
+ assert!(body.contains("\"call\":0"));
+ assert!(body.contains("\"call\":1"));
+}
+
+#[test]
+fn ffi_plain_session_writes_no_trace_files() {
+ let _home = TestHome::new();
+ unsafe {
+ let session = CString::new("plain-session").unwrap();
+ let ptr = ad_adapter_create_with_session(session.as_ptr());
+ assert!(!ptr.is_null());
+ let ctx = (*ptr)
+ .command_context()
+ .expect("command_context must succeed");
+ ctx.trace("ffi.event", serde_json::json!({})).unwrap();
+ ad_check_permissions(ptr);
+ ad_adapter_destroy(ptr);
+ }
+ assert!(!trace_dir_for("plain-session").exists());
+}
diff --git a/docs/solutions/best-practices/playwright-grade-desktop-reliability-2026-06-02.md b/docs/solutions/best-practices/playwright-grade-desktop-reliability-2026-06-02.md
index 2fd2b915f..c67b3779f 100644
--- a/docs/solutions/best-practices/playwright-grade-desktop-reliability-2026-06-02.md
+++ b/docs/solutions/best-practices/playwright-grade-desktop-reliability-2026-06-02.md
@@ -165,6 +165,9 @@ safe for agents to use with machine-readable command output:
- let `--trace-strict` fail on setup and pre-action trace writes
- keep post-action success trace writes best-effort after the desktop mutation
has already happened
+- with a trace-enabled session manifest from `session start`, write per-process
+ JSONL segments under `sessions/<id>/trace/<pid>-*.jsonl` automatically;
+ `--trace <path>` still overrides to one file for CI or one-offs
Reporting a successful desktop mutation as failed because the final trace write
failed is worse than losing that final diagnostic event.
diff --git a/skills/agent-desktop-ffi/SKILL.md b/skills/agent-desktop-ffi/SKILL.md
index 2eb0e47bb..c6d6253f3 100644
--- a/skills/agent-desktop-ffi/SKILL.md
+++ b/skills/agent-desktop-ffi/SKILL.md
@@ -1,6 +1,6 @@
---
name: agent-desktop-ffi
-version: 0.4.0
+version: 0.4.1
tags: ffi, c-bindings, cdylib, python, swift, node, go, rust-ffi
requirements:
- agent-desktop-ffi
@@ -76,10 +76,20 @@ to `ad_execute_by_ref` to drive the CLI-semantics ref-action pipeline
symbols increment the major.
- **Session adapters.** `ad_adapter_create_with_session("session-id")` associates
- the adapter with a named session for refmap persistence. Passing the same session
- ID across adapter lifetimes lets `ad_execute_by_ref` with `snapshot_id=NULL`
- target the latest snapshot from that session. Session IDs: 1–64 chars, ASCII
- alphanumeric / `-` / `_`. Invalid IDs return null (check `ad_last_error_*`).
+ the adapter with a session namespace for refmap persistence — the same as CLI
+ `--session <id>`. Passing the same session ID across adapter lifetimes lets
+ `ad_execute_by_ref` with `snapshot_id=NULL` target the latest snapshot from
+ that session. Session IDs: 1–64 chars, ASCII alphanumeric / `-` / `_`.
+ Invalid IDs return null (check `ad_last_error_*`).
+
+- **Structured session trace (no ABI change).** File-based JSONL tracing activates
+ only when the session has a manifest with `trace: on` from `session start`
+ (CLI) or equivalent on-disk setup. `ad_adapter_create_with_session` alone does
+ **not** create trace files. When tracing is active, `command_context()`-backed
+ commands append to one segment per OS process under
+ `~/.agent-desktop/sessions/<id>/trace/<pid>-<procTs>.jsonl`. A long-lived host
+ reuses the same segment filename for all calls in that process. For unstructured
+ diagnostics regardless of session manifest, use `ad_set_log_callback` (below).
- **Main thread only (macOS).** Call every adapter-touching entrypoint
(`ad_snapshot`, `ad_execute_by_ref`, `ad_wait`, `ad_get_tree`, `ad_find`,
@@ -141,17 +151,24 @@ to `ad_execute_by_ref` to drive the CLI-semantics ref-action pipeline
for activation-chain actions. Each entry has `label` and `outcome` strings and
is owned by the result; release with `ad_free_action_result(&out)`.
-- **Tracing / log callback.** `ad_set_log_callback(cb)` installs a `tracing`
- subscriber layer that delivers events as JSON to your callback. `cb` receives an
- int32_t level (1=ERROR … 5=TRACE) and a `const char *msg` valid only for the
- duration of the call. Pass `NULL` to unregister. The layer is installed on the
- first non-null call; if a foreign global subscriber already owns the process at
- that point, the install fails with `AD_RESULT_ERR_INTERNAL` and no events are
- ever delivered. Sensitive field values (password, token, text, …) are replaced
- with `{"redacted":true}` before formatting. A panicking callback is caught and
- silently discarded. The callback may fire from threads other than the registering
- thread, and may still fire briefly after a `NULL` unregister — keep the callback
- and any data it captures valid for the process lifetime.
+- **Tracing / log callback.** Two tracing surfaces coexist:
+
+ 1. **Structured file trace** — same JSONL contract as CLI `--trace`, gated by a
+ `trace: on` session manifest. Segments include `event`, `ts_ms`, `seq`, and
+ redacted fields. Requires `session start` (or equivalent manifest on disk)
+ before creating the adapter; plain session-id adapters write nothing to disk.
+
+ 2. **`ad_set_log_callback(cb)`** — installs a `tracing` subscriber layer that
+ delivers events as JSON to your callback. `cb` receives an int32_t level
+ (1=ERROR … 5=TRACE) and a `const char *msg` valid only for the duration of
+ the call. Pass `NULL` to unregister. The layer is installed on the first
+ non-null call; if a foreign global subscriber already owns the process at
+ that point, the install fails with `AD_RESULT_ERR_INTERNAL` and no events are
+ ever delivered. Sensitive field values (password, token, text, …) are
+ replaced with `{"redacted":true}` before formatting. A panicking callback is
+ caught and silently discarded. The callback may fire from threads other than
+ the registering thread, and may still fire briefly after a `NULL` unregister
+ — keep the callback and any data it captures valid for the process lifetime.
- **Wait.** `ad_wait(adapter, args, &out)` runs the full CLI `wait` command
(element-appear, window-appear, text-appear, menu-open/close, notification,
diff --git a/skills/agent-desktop/SKILL.md b/skills/agent-desktop/SKILL.md
index 9e9ca1711..2a7c0b6ff 100644
--- a/skills/agent-desktop/SKILL.md
+++ b/skills/agent-desktop/SKILL.md
@@ -1,6 +1,6 @@
---
name: agent-desktop
-version: 0.3.0
+version: 0.4.0
tags: desktop-automation, accessibility, ai-agent, gui-automation, cli
requirements:
- agent-desktop
@@ -9,8 +9,8 @@ description: >
Use when an AI agent needs to observe, interact with, or automate desktop applications
(click buttons, fill forms, navigate menus, read UI state, toggle checkboxes, scroll,
drag, type text, take screenshots, manage windows, use clipboard, manage notifications).
- Covers 54 commands across observation, interaction, keyboard/mouse, app lifecycle,
- notifications (macOS), clipboard, wait, and a `skills` command that prints these
+ Covers 55 commands across observation, interaction, keyboard/mouse, app lifecycle,
+ notifications (macOS), clipboard, wait, session lifecycle, and a `skills` command
bundled docs straight from the binary.
Triggers on: "click button", "fill form", "open app", "read UI", "automate desktop",
"accessibility tree", "snapshot app", "type into field", "navigate menu", "toggle checkbox",
@@ -43,7 +43,7 @@ Detailed documentation is split into focused reference files. Read them as neede
|-----------|----------|
| `references/commands-observation.md` | snapshot, find, get, is, screenshot, list-surfaces — all flags, output examples |
| `references/commands-interaction.md` | click, type, set-value, select, toggle, scroll, drag, keyboard, mouse — choosing the right command |
-| `references/commands-system.md` | launch, close, windows, clipboard, wait, batch, status, permissions, version |
+| `references/commands-system.md` | launch, close, windows, clipboard, wait, batch, session, status, permissions, version |
| `references/workflows.md` | 12 common patterns: forms, menus, dialogs, scroll-find, drag-drop, async wait, anti-patterns |
| `references/macos.md` | macOS permissions/TCC, AX API internals, smart activation chain, surfaces, Notification Center, troubleshooting |
@@ -95,8 +95,7 @@ Use **progressive skeleton traversal** as the default approach. It reduces token
- **Strict resolution:** stale refs return `STALE_REF`; duplicate plausible targets return `AMBIGUOUS_TARGET` instead of choosing arbitrarily.
- **Actionability:** ref actions check live visibility, stability, enabled state, supported action, policy, and editability before dispatch.
- **Headless vs headed:** ref actions are headless by default (AX-only, no cursor) and fail closed when only a physical gesture would work. `type` uses a focus-fallback base policy because typing needs focus but never moves the cursor. Pass the global `--headed` flag to permit cursor movement and focus stealing so physical fallbacks can complete; the AX path is still tried first, so `--headed` never regresses headless-capable elements. Raw cursor commands (`hover`, `drag`, `mouse-*`) are physical and require `--headed`; keyboard commands (`press`, `key-down`, `key-up`) are explicit low-level input.
-- **Sessions:** use `--session <id>` for concurrent or multi-agent runs that share a latest snapshot pointer; batch entries may override with `"session": "id"`.
-- **Trace:** use `--trace <path>` for JSONL diagnostics outside stdout; `--trace-strict` fails on trace setup and pre-action writes. Post-action success traces are best-effort because the desktop mutation already happened. Trace fields with sensitive key tokens such as `text`, `value`, `expected`, `name`, `username`, `description`, `label`, `query`, `secret`, `token`, `password`, `title`, `url`, `help`, or `placeholder` are redacted to `{ "redacted": true }` at every nesting depth. Token matching handles snake_case, kebab-case, and camelCase keys (for example, `source_window_title`, `api_token`, and `typedText` redact, while `filename` stays readable). Top-level `--trace` is inherited by every `batch` entry, including entries with a `session` override.
+- **Sessions and tracing:** run `session start` once per agent run to create a manifest with `trace: on` (default). Subsequent commands in that run record JSONL automatically to per-process segments under `~/.agent-desktop/sessions/<id>/trace/<pid>-<procTs>.jsonl` — no `--trace` on every call. A session owns both its trace and its latest-snapshot namespace; activating it (via pointer, env, or flag) relocates implicit "latest" to that session. Explicit `--snapshot <id>` still resolves cross-session. **`--session <id>` alone** (no manifest from `session start`) selects only the snapshot namespace — existing callers see no surprise trace files. **`--trace <path>`** still overrides to one atomic file for CI or one-offs. Activation precedence: `--session` > `AGENT_DESKTOP_SESSION` > `~/.agent-desktop/current_session` (written only by `session start`). Concurrent independent agents set `AGENT_DESKTOP_SESSION` per process; the pointer is a single-active-session convenience. Multi-agent shared sessions: each agent acts on the `snapshot_id` from its own `snapshot` call — implicit latest is not a cross-agent guarantee. Run `status` to see `session_id` and `tracing`. Trace lines include `ts_ms`, monotonic per-process `seq`, and redacted sensitive fields (`text`, `value`, `expected`, `name`, `username`, `description`, `label`, `query`, `secret`, `token`, `password`, `title`, `url`, `help`, `placeholder` → `{ "redacted": true }`). `--trace-strict` fails on trace setup and pre-action writes; post-action success traces are best-effort.
## JSON Output Contract
@@ -131,7 +130,7 @@ Exit codes: `0` success, `1` structured error, `2` argument error.
`TIMEOUT` errors carry a `details` object whose `kind` field selects the schema. `kind: "wait_timeout"` includes `predicate`, `timeout_ms`, and `last_observed` or `last_error`, plus `ref`/`title`/`text_chars` depending on the wait mode. `kind: "chain_deadline"` includes `value_before`, `value_at_timeout`, `target`, and `mutated` (increment waits) or `wanted_expanded`/`observed_expanded` (disclosure waits). `mutated: true` — or an unknown `observed_expanded` state — means re-read the element before retrying; `mutated: false` means the state did not change and retrying directly is safe.
-## Command Quick Reference (54 commands)
+## Command Quick Reference (55 commands)
### Observation
```
@@ -229,7 +228,11 @@ agent-desktop wait --notification --app "App" # Wait for new notification
### System
```
-agent-desktop status # Health check
+agent-desktop session start [--name LABEL] [--no-trace] [--force] # Create trace-enabled session + pointer
+agent-desktop session end [id] # Seal manifest, clear pointer
+agent-desktop session list # List session manifests
+agent-desktop session gc [--older-than SECS] [--ended] # Reclaim ended/stale sessions
+agent-desktop status # Health, session_id, tracing, permissions
agent-desktop permissions # Check permission
agent-desktop permissions --request # Trigger permission dialog
agent-desktop version # Version info (always JSON envelope)
@@ -251,5 +254,5 @@ agent-desktop skills get desktop --full # Load this skill + all referenc
9. **Use surfaces for overlays.** `snapshot --surface menu` for menus, `--surface sheet` for dialogs. Never `--skeleton` for surfaces — they're already focused.
10. **Batch for performance.** Multiple commands in one invocation.
11. **Headless by default.** Ref actions use semantic AX paths and block silent focus stealing, cursor movement, keyboard synthesis, and pasteboard insertion. Use explicit `focus`, `press`, `hover`, `drag`, or `mouse-*` commands only when physical/headed interaction is intended.
-12. **Use sessions for parallel work.** Add `--session <id>` when multiple agents or batches can run at once.
-13. **Trace hard failures.** Add `--trace /tmp/agent-desktop.jsonl` when diagnosing stale, ambiguous, or actionability failures.
+12. **Start a session once per run.** `session start` enables automatic tracing and relocates the latest-snapshot namespace. Use `AGENT_DESKTOP_SESSION` for concurrent independent agents; use `--session <id>` to override the active pointer for a single command.
+13. **Trace hard failures.** With an active trace-enabled session, segments are written automatically. Add `--trace /tmp/agent-desktop.jsonl` only when you need a single override file (CI, one-offs). Check `status` when unsure whether tracing is active.
diff --git a/skills/agent-desktop/references/commands-interaction.md b/skills/agent-desktop/references/commands-interaction.md
index a71a0d96c..410122abd 100644
--- a/skills/agent-desktop/references/commands-interaction.md
+++ b/skills/agent-desktop/references/commands-interaction.md
@@ -55,7 +55,7 @@ The command surface is platform-agnostic: every ref action builds an `Action` an
| `drag` / drop | no | dragging *is* a cursor press-move-release; no general AX drag. Native cross-app drop needs the OS dragging-session/pasteboard protocol that synthetic events cannot start (works for same-view source-tracked gestures and web/Electron mouse-DnD) |
| menu bar (`--surface menubar`) | enumerate/open | the app menu bar is readable and openable; SwiftUI `CommandMenu` items accept AXPress but do not route to their action closure (a SwiftUI limitation, like its Slider) — native AppKit menu items fire. `.contextMenu` item selection works. |
-All ref-based interaction commands accept `--snapshot <snapshot_id>`. Omit it for the active session's latest saved snapshot, or pass the `snapshot_id` returned by `snapshot` to keep scripts pinned to the exact ref map they observed. Explicit snapshot IDs do not require also passing `--session`.
+All ref-based interaction commands accept `--snapshot <snapshot_id>`. Omit it for the active session's latest saved snapshot, or pass the `snapshot_id` returned by `snapshot` to keep scripts pinned to the exact ref map they observed. Explicit snapshot IDs do not require also passing `--session`. After `session start`, implicit latest resolves inside the new session; snapshots taken before the boundary need explicit `--snapshot <old-id>`.
Success responses for ref actions include a `steps` array when the activation chain recorded attempts: each entry is `{ "label": "AXPress", "outcome": "attempted" | "skipped" | "succeeded" }` in execution order, showing which activation path produced the result.
diff --git a/skills/agent-desktop/references/commands-system.md b/skills/agent-desktop/references/commands-system.md
index 16c54bfcd..878961c46 100644
--- a/skills/agent-desktop/references/commands-system.md
+++ b/skills/agent-desktop/references/commands-system.md
@@ -236,7 +236,9 @@ Execute multiple commands in sequence from a JSON array. Each entry has `command
Batch uses the same typed `Commands` enum, command policy preflight, permission report, and dispatch path as the CLI. Unknown fields are rejected instead of being silently ignored. Nested `batch` is rejected.
-Each entry may include `"session": "id"` beside `command` and `args`. If omitted, the entry inherits the top-level `--session`. Use per-entry sessions only when intentionally inspecting or coordinating separate agent runs. Top-level `--trace` is inherited by every entry — including entries with a `session` override — so one JSONL file captures the whole batch.
+Each entry may include `"session": "id"` beside `command` and `args`. If omitted, the entry inherits the top-level resolved session. Use per-entry sessions only when intentionally inspecting or coordinating separate agent runs.
+
+**Trace in batch:** when the top-level CLI passes `--trace <path>`, every entry writes to that single file (override). Without `--trace`, entries inherit the resolved session's manifest-gated segment sink; a per-entry `"session"` override re-derives the sink for that session (events never land in the parent session's segment). Session subcommands (`session start`, etc.) are also available in batch JSON via `"action": "start"|"end"|"list"|"gc"`.
| Flag | Default | Description |
|------|---------|-------------|
@@ -248,7 +250,8 @@ Each entry may include `"session": "id"` beside `command` and `args`. If omitted
{ "command": "click", "args": { "ref_id": "@e1", "snapshot": "<snapshot_id>" } },
{ "command": "wait", "args": { "ms": 500 } },
{ "command": "type", "args": { "ref_id": "@e2", "snapshot": "<snapshot_id>", "text": "hello" } },
- { "command": "status", "session": "other-agent", "args": {} }
+ { "command": "status", "session": "other-agent", "args": {} },
+ { "command": "session", "args": { "action": "start", "name": "batch-run" } }
]
```
@@ -276,13 +279,59 @@ Each entry may include `"session": "id"` beside `command` and `args`. If omitted
`skeleton: true` clamps depth to 3 and tags truncated containers with `children_count`. `root: "@eN"` starts traversal from that ref instead of the window root; it cannot be combined with `surface`.
+## Session lifecycle
+
+Sessions are on-disk containers under `~/.agent-desktop/sessions/<id>/` with a `session.json` manifest, snapshot refmaps, and (when tracing is on) a `trace/` directory. **`session start` is the only command that writes `~/.agent-desktop/current_session`.**
+
+### session start
+```bash
+agent-desktop session start
+agent-desktop session start --name "nightly-run"
+agent-desktop session start --no-trace # Namespace only — no automatic JSONL
+agent-desktop session start --force # Override pointer even if it references a live session
+```
+Creates the session directory, pre-creates `trace/` (when tracing is on), writes `session.json` (`trace: on` unless `--no-trace`), sets the current-session pointer, and prints `{ "session_id", "name", "trace", "created_at" }`.
+
+Refuses to clobber a pointer that still references a **live** session unless `--force`. Live means an active `refstore.lock` holder or recent writes under `trace/`.
+
+### session end
+```bash
+agent-desktop session end
+agent-desktop session end run-1719763200123-0
+```
+Seals the manifest with `ended_at` and clears the pointer when it still points at this session.
+
+### session list
+```bash
+agent-desktop session list
+```
+Returns manifest fields only (`session_id`, `name`, `created_at`, `ended_at`, `trace`) — no subtree walk.
+
+### session gc
+```bash
+agent-desktop session gc
+agent-desktop session gc --ended
+agent-desktop session gc --older-than 3600
+```
+Removes ended sessions that are not live and not pointer-referenced. Never reaps a session with a live lock holder or recent `trace/` activity. Refuses symlinked session directories.
+
+### Activation (all commands)
+
+| Source | Precedence |
+|--------|------------|
+| `--session <id>` | Highest |
+| `AGENT_DESKTOP_SESSION` env var | Middle |
+| `~/.agent-desktop/current_session` | Lowest (set only by `session start`) |
+
+Trace-on requires a manifest with `trace: on` from `session start`. Bare `--session` or FFI `ad_adapter_create_with_session` without that manifest selects the snapshot namespace only.
+
## System Health
### status
```bash
agent-desktop status
```
-Returns adapter health, platform info, permission report, and latest snapshot metadata (`snapshot_id`, `ref_count`) when available.
+Returns adapter health, platform info, permission report, latest snapshot metadata (`snapshot_id`, `ref_count`) when available, plus **`session_id`** (resolved active session, if any) and **`tracing`** (whether structured trace output is configured for this process — explicit `--trace`, or a trace-enabled session manifest).
### permissions
```bash
diff --git a/skills/agent-desktop/references/workflows.md b/skills/agent-desktop/references/workflows.md
index 86faf0330..d2ccadd57 100644
--- a/skills/agent-desktop/references/workflows.md
+++ b/skills/agent-desktop/references/workflows.md
@@ -15,6 +15,31 @@ agent-desktop permissions --request
For screenshots, also grant Screen Recording. `permissions` reports `accessibility`, `screen_recording`, and `automation` separately.
+## Pattern: Session-Scoped Tracing (Default for Multi-Step Runs)
+
+Start one session per agent run so tracing and the latest-snapshot namespace follow automatically — no `--trace` on every command.
+
+```bash
+# 1. Start once — creates manifest (trace: on), pointer, and trace/ directory
+agent-desktop session start --name "invoice-bot"
+# Note session_id from data.session_id (also written to ~/.agent-desktop/current_session)
+
+# 2. Observe-act loop — segments land under sessions/<id>/trace/<pid>-*.jsonl
+agent-desktop snapshot --app "Preview" -i --compact
+agent-desktop click @e3 --snapshot <snapshot_id>
+agent-desktop status # confirms session_id + tracing: true
+
+# 3. End and reclaim when finished
+agent-desktop session end
+agent-desktop session gc
+```
+
+**Concurrent independent agents:** set `AGENT_DESKTOP_SESSION=<id>` in each process instead of sharing the global pointer. Each agent still uses the `snapshot_id` from its own `snapshot` call when sharing a session id.
+
+**Namespace without tracing:** `session start --no-trace` or bare `--session legacy-id` (no manifest) — snapshots namespaced, no JSONL files.
+
+**Override file trace:** `--trace /tmp/run.jsonl` still forces a single file regardless of session manifest.
+
## Pattern: Progressive Skeleton Traversal (Default for Dense Apps)
The recommended approach for Electron apps (Slack, VS Code, Discord) and any app with 50+ interactive elements. Reduces token consumption 78-96%.
diff --git a/src/batch/mod.rs b/src/batch/mod.rs
index 681eea614..77f6f16a8 100644
--- a/src/batch/mod.rs
+++ b/src/batch/mod.rs
@@ -13,6 +13,7 @@ use serde_json::{Map, Value, json};
use crate::{
cli::Commands,
cli_args::{
+ session::{SessionAction, SessionArgs, SessionEndArgs, SessionGcArgs, SessionStartArgs},
skills::{SkillsAction, SkillsArgs, SkillsGetArgs},
system::BatchArgs,
},
@@ -29,11 +30,13 @@ pub(crate) fn execute(
for item in commands {
let command = item.command.clone();
- let item_context = context.for_batch_item(item.session.clone())?;
- let result = parse_command(item).and_then(|typed| {
- crate::command_policy::preflight(&typed, permission_report)?;
- crate::dispatch::dispatch(typed, adapter, permission_report, &item_context)
- });
+ let result = match context.for_batch_item(item.session.clone()) {
+ Ok(item_context) => parse_command(item).and_then(|typed| {
+ crate::command_policy::preflight(&typed, permission_report)?;
+ crate::dispatch::dispatch(typed, adapter, permission_report, &item_context)
+ }),
+ Err(err) => Err(err),
+ };
let ok = result.is_ok();
results.push(batch_entry(&command, result));
if !ok && args.stop_on_error {
@@ -102,6 +105,7 @@ pub(crate) fn parse_command(item: BatchCommand) -> Result<Commands, AppError> {
"permissions" => decode(command, item.args).map(Commands::Permissions),
"version" => no_args(command, item.args).map(|()| Commands::Version),
"skills" => parse_skills(item.args).map(Commands::Skills),
+ "session" => parse_session(item.args).map(Commands::Session),
"batch" => Err(AppError::invalid_input_with_suggestion(
"Batch commands cannot be nested",
"Flatten nested batches into one top-level batch array",
@@ -185,5 +189,44 @@ fn parse_skills(args: Value) -> Result<SkillsArgs, AppError> {
Ok(SkillsArgs { action })
}
+#[derive(Deserialize)]
+#[serde(deny_unknown_fields)]
+struct BatchSessionArgs {
+ #[serde(default)]
+ action: Option<String>,
+ name: Option<String>,
+ #[serde(default)]
+ no_trace: bool,
+ #[serde(default)]
+ force: bool,
+ id: Option<String>,
+ older_than: Option<u64>,
+ #[serde(default)]
+ ended: bool,
+}
+
+fn parse_session(args: Value) -> Result<SessionArgs, AppError> {
+ let args: BatchSessionArgs = decode("session", args)?;
+ let action = match args.action.as_deref() {
+ None | Some("list") => SessionAction::List,
+ Some("start") => SessionAction::Start(SessionStartArgs {
+ name: args.name,
+ no_trace: args.no_trace,
+ force: args.force,
+ }),
+ Some("end") => SessionAction::End(SessionEndArgs { id: args.id }),
+ Some("gc") => SessionAction::Gc(SessionGcArgs {
+ older_than: args.older_than,
+ ended: args.ended,
+ }),
+ Some(other) => {
+ return Err(AppError::invalid_input(format!(
+ "Unknown session action '{other}'"
+ )));
+ }
+ };
+ Ok(SessionArgs { action })
+}
+
#[cfg(test)]
mod tests;
diff --git a/src/batch/tests.rs b/src/batch/tests.rs
index 54577d3da..c0c174967 100644
--- a/src/batch/tests.rs
+++ b/src/batch/tests.rs
@@ -24,6 +24,20 @@ fn parses_optional_batch_session_scope() {
assert_eq!(commands[0].session.as_deref(), Some("agent-a"));
}
+#[test]
+fn session_batch_rejects_unknown_field() {
+ assert!(
+ parse_command(item("session", serde_json::json!({ "action": "start" }))).is_ok(),
+ "a valid session start must still parse"
+ );
+ let err = parse_command(item(
+ "session",
+ serde_json::json!({ "action": "start", "no_trce": true }),
+ ))
+ .expect_err("a misspelled session field must be rejected, not silently defaulted");
+ assert!(err.to_string().contains("no_trce"));
+}
+
#[test]
fn parses_ref_command_into_cli_enum() {
let command =
diff --git a/src/cli/contract_tests.rs b/src/cli/contract_tests.rs
index a706f7e43..ba57ee19d 100644
--- a/src/cli/contract_tests.rs
+++ b/src/cli/contract_tests.rs
@@ -28,6 +28,7 @@ const COMMAND_SPECIFIC_TESTS: &[&str] = &[
"list-apps",
"right-click",
"skills",
+ "session",
"snapshot",
"status",
"wait",
diff --git a/src/cli/help_after.txt b/src/cli/help_after.txt
index ee3c28204..6ba6d575d 100644
--- a/src/cli/help_after.txt
+++ b/src/cli/help_after.txt
@@ -73,10 +73,14 @@ WAIT
wait --notification Block until a new notification arrives (--text filters it)
SYSTEM
- status Adapter health, platform, and permission state
+ status Adapter health, platform, permission, session, and tracing state
permissions Check nested permission states: {state,...}
version Show version, target architecture, and OS
skills Bundled skill docs for AI agents (list, get, path)
+ session start Create a trace-enabled session and set the active pointer
+ session end Seal the session manifest and clear the active pointer
+ session list List session manifests
+ session gc Remove ended or provably-stale sessions
BATCH
batch <json> Run commands from a JSON array (--stop-on-error)
@@ -88,13 +92,16 @@ REF IDs
--snapshot <snapshot_id> to pin a command to a known snapshot; explicit
snapshot IDs do not require --session. When --snapshot is omitted, ref
commands use the active session's latest saved snapshot. Run snapshot again
- after UI changes. Use --session <id> as a shared latest-snapshot namespace
- for concurrent agents.
+ after UI changes. Use `session start` once per run for automatic JSONL tracing
+ under ~/.agent-desktop/sessions/<id>/trace/, or pass --session <id> for
+ snapshot namespace only (no trace without a session manifest). Set
+ AGENT_DESKTOP_SESSION for concurrent independent sessions. Explicit --session
+ overrides the env var and current-session pointer.
Ref actions use strict resolution: stale targets return STALE_REF; duplicate
plausible targets return AMBIGUOUS_TARGET instead of choosing arbitrarily.
Ref actions run actionability checks before dispatch. Use --trace <path> to
- write JSONL diagnostics outside stdout; --trace-strict fails on trace setup
- and pre-action writes. Post-action success traces are best-effort.
+ override the session trace sink; --trace-strict fails on trace setup and
+ pre-action writes. Post-action success traces are best-effort.
KEY COMBOS
Single keys: return, escape, tab, space, delete, up, down, left, right
@@ -120,16 +127,17 @@ EXAMPLES
agent-desktop wait --element @e5 --predicate actionable --timeout 5000
agent-desktop snapshot --app Finder -w "button:OK"
agent-desktop click @e5 -w ":Saved!"
- agent-desktop --session run-a --trace /tmp/ad.jsonl click @e5
+ agent-desktop session start --name run-a
+ agent-desktop click @e5
agent-desktop batch '[{"command":"click","args":{"ref_id":"@e1","snapshot":"<snapshot_id>"}}]'
- agent-desktop --session run-a batch '[{"command":"status","session":"run-b","args":{}}]'
+ agent-desktop --session run-b batch '[{"command":"status","session":"run-b","args":{}}]'
AGENT LOOP
1. Use `skills get desktop --full` when you need detailed guidance.
- 2. Use `--session <id>` when another agent or task may also run commands.
+ 2. Run `session start` once per agent run (or set AGENT_DESKTOP_SESSION).
3. Observe with `snapshot -i` or `snapshot --skeleton -i --compact`.
4. Keep `snapshot_id`; pass it to every ref-consuming action.
5. Use `wait --predicate actionable`, `wait --text`, or `wait --window`
instead of sleeping blindly.
6. On STALE_REF or AMBIGUOUS_TARGET, snapshot again and choose a fresh ref.
- 7. Add `--trace <path>` when diagnosing stale, ambiguous, or actionability failures.
+ 7. Check `status` for `tracing: true`, or add `--trace <path>` to override.
diff --git a/src/cli/help_before.txt b/src/cli/help_before.txt
index 80d868dd7..f9a55dd2c 100644
--- a/src/cli/help_before.txt
+++ b/src/cli/help_before.txt
@@ -2,9 +2,9 @@ For AI agents — read this first:
agent-desktop skills get desktop --full
Bundled skill docs travel with the binary, so they always match this
- exact version. They cover the snapshot-scoped ref loop, shared sessions,
- actionability, trace JSONL, error codes with recovery hints, and
- copy-paste patterns for forms, menus, dialogs, and async waits.
+ exact version. They cover the snapshot-scoped ref loop, session lifecycle,
+ manifest-gated trace JSONL, actionability, error codes with recovery hints,
+ and copy-paste patterns for forms, menus, dialogs, and async waits.
Specialized skills go deeper on macOS internals (TCC, AX API, surfaces,
Notification Center) and on embedding agent-desktop through its C ABI.
diff --git a/src/cli/mod.rs b/src/cli/mod.rs
index 37af62162..72770e9bb 100644
--- a/src/cli/mod.rs
+++ b/src/cli/mod.rs
@@ -11,6 +11,7 @@ use crate::cli_args::{
DismissAllNotificationsCliArgs, DismissNotificationCliArgs, ListNotificationsCliArgs,
NotificationActionCliArgs,
},
+ session::SessionArgs,
skills::SkillsArgs,
system::{
AppRefArgs, BatchArgs, ClipboardSetArgs, CloseAppArgs, FocusWindowArgs, LaunchArgs,
@@ -210,6 +211,8 @@ pub(crate) enum Commands {
Batch(BatchArgs),
#[command(about = "Bundled skill docs for AI agents (list, get, path)")]
Skills(SkillsArgs),
+ #[command(about = "Manage trace-enabled agent sessions (start, end, list, gc)")]
+ Session(SessionArgs),
}
impl Commands {
@@ -269,6 +272,7 @@ impl Commands {
Self::Version => "version",
Self::Batch(_) => "batch",
Self::Skills(_) => "skills",
+ Self::Session(_) => "session",
}
}
}
diff --git a/src/cli_args/mod.rs b/src/cli_args/mod.rs
index 5b8b9717e..9b1e26cda 100644
--- a/src/cli_args/mod.rs
+++ b/src/cli_args/mod.rs
@@ -3,6 +3,7 @@ use serde::Deserialize;
pub(crate) mod actions;
pub(crate) mod notifications;
+pub(crate) mod session;
pub(crate) mod skills;
pub(crate) mod system;
diff --git a/src/cli_args/session.rs b/src/cli_args/session.rs
new file mode 100644
index 000000000..6c19a9a09
--- /dev/null
+++ b/src/cli_args/session.rs
@@ -0,0 +1,49 @@
+use clap::{Args, Subcommand};
+
+#[derive(Args, Debug)]
+pub(crate) struct SessionArgs {
+ #[command(subcommand)]
+ pub action: SessionAction,
+}
+
+#[derive(Subcommand, Debug)]
+pub(crate) enum SessionAction {
+ #[command(about = "Create a session directory, manifest, and current-session pointer")]
+ Start(SessionStartArgs),
+ #[command(about = "Seal the session manifest and clear the current-session pointer")]
+ End(SessionEndArgs),
+ #[command(about = "List session manifests")]
+ List,
+ #[command(about = "Remove ended or provably-stale sessions")]
+ Gc(SessionGcArgs),
+}
+
+#[derive(Args, Debug)]
+pub(crate) struct SessionStartArgs {
+ #[arg(long, help = "Optional human-readable session label")]
+ pub name: Option<String>,
+ #[arg(long, help = "Create the session without automatic tracing")]
+ pub no_trace: bool,
+ #[arg(
+ long,
+ help = "Override the current-session pointer even when it references a live session"
+ )]
+ pub force: bool,
+}
+
+#[derive(Args, Debug)]
+pub(crate) struct SessionEndArgs {
+ #[arg(help = "Session id to end; defaults to the current-session pointer")]
+ pub id: Option<String>,
+}
+
+#[derive(Args, Debug)]
+pub(crate) struct SessionGcArgs {
+ #[arg(
+ long,
+ help = "Only remove sessions whose ended_at/created_at age exceeds this many seconds"
+ )]
+ pub older_than: Option<u64>,
+ #[arg(long, help = "Only consider sessions that already have ended_at set")]
+ pub ended: bool,
+}
diff --git a/src/command_policy/mod.rs b/src/command_policy/mod.rs
index 30fce0174..70a76711f 100644
--- a/src/command_policy/mod.rs
+++ b/src/command_policy/mod.rs
@@ -17,7 +17,7 @@ pub(crate) enum PermissionNeed {
pub(crate) fn policy_for(cmd: &Commands) -> PermissionNeed {
use PermissionNeed::{Accessibility, AccessibilityAndScreenRecording, None, ScreenRecording};
match cmd {
- Commands::Version | Commands::Skills(_) => None,
+ Commands::Version | Commands::Skills(_) | Commands::Session(_) => None,
Commands::Status | Commands::Permissions(_) => None,
Commands::ListWindows(_) | Commands::ListApps(_) => None,
Commands::ClipboardGet | Commands::ClipboardSet(_) | Commands::ClipboardClear => None,
@@ -192,7 +192,8 @@ fn validate_args(cmd: &Commands) -> Result<(), AppError> {
| Commands::Permissions(_)
| Commands::Version
| Commands::Batch(_)
- | Commands::Skills(_) => {}
+ | Commands::Skills(_)
+ | Commands::Session(_) => {}
}
Ok(())
}
diff --git a/src/command_policy/tests.rs b/src/command_policy/tests.rs
index e9fb4d052..69118fa51 100644
--- a/src/command_policy/tests.rs
+++ b/src/command_policy/tests.rs
@@ -74,6 +74,7 @@ fn command_name_is_covered(name: &str) -> bool {
| "version"
| "batch"
| "skills"
+ | "session"
)
}
diff --git a/src/dispatch/mod.rs b/src/dispatch/mod.rs
index db94cba24..304f1571a 100644
--- a/src/dispatch/mod.rs
+++ b/src/dispatch/mod.rs
@@ -9,8 +9,9 @@ use agent_desktop_core::{
double_click, drag, expand, find, focus, focus_window, get, helpers, hover, is_check,
key_down, key_up, launch, list_apps, list_surfaces, list_windows, maximize, minimize,
mouse_click, mouse_down, mouse_move, mouse_up, move_window, permissions, press,
- resize_window, restore, right_click, screenshot, scroll, scroll_to, select, set_value,
- skills, snapshot, status, toggle, triple_click, type_text, uncheck, version, wait,
+ resize_window, restore, right_click, screenshot, scroll, scroll_to, select, session,
+ set_value, skills, snapshot, status, toggle, triple_click, type_text, uncheck, version,
+ wait,
},
context::CommandContext,
error::AppError,
@@ -18,6 +19,7 @@ use agent_desktop_core::{
use serde_json::Value;
use crate::cli::Commands;
+use crate::cli_args::session::SessionAction;
use crate::cli_args::skills::SkillsAction;
use parse::{
parse_direction, parse_get_property, parse_is_property, parse_mouse_button, parse_xy,
@@ -364,6 +366,22 @@ pub(crate) fn dispatch(
}),
},
+ Commands::Session(a) => match a.action {
+ SessionAction::Start(s) => session::execute(session::SessionAction::Start {
+ name: s.name,
+ no_trace: s.no_trace,
+ force: s.force,
+ }),
+ SessionAction::End(e) => session::execute(session::SessionAction::End {
+ id: e.id.or_else(|| context.session_id().map(str::to_string)),
+ }),
+ SessionAction::List => session::execute(session::SessionAction::List),
+ SessionAction::Gc(g) => session::execute(session::SessionAction::Gc {
+ older_than_secs: g.older_than,
+ ended_only: g.ended,
+ }),
+ },
+
Commands::Batch(a) => crate::batch::execute(a, adapter, permission_report, context),
}
}
diff --git a/src/main.rs b/src/main.rs
index 21d903087..b1ba2f03e 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -9,6 +9,7 @@ use agent_desktop_core::{
context::{CommandContext, WaitSelector},
error::AppError,
output::{ENVELOPE_VERSION, ErrorPayload, Response},
+ session::resolve_active_session,
};
use clap::{CommandFactory, Parser};
use cli::{Cli, Commands};
@@ -36,7 +37,7 @@ const WAIT_SUPPORTED: &[&str] = &[
];
fn main() {
- let cli = match Cli::try_parse() {
+ let mut cli = match Cli::try_parse() {
Ok(c) => c,
Err(e) => {
if matches!(
@@ -56,18 +57,8 @@ fn main() {
};
init_tracing(cli.verbose);
- let wait_selector = build_wait_selector(&cli);
- let context = match CommandContext::new(cli.session, cli.trace, cli.trace_strict) {
- Ok(context) => context
- .with_headed(cli.headed)
- .with_wait_selector(wait_selector.clone()),
- Err(err) => {
- finish("unknown", Err(err));
- return;
- }
- };
- let cmd = match cli.command {
+ let cmd = match cli.command.take() {
Some(c) => c,
None => {
Cli::command().print_help().unwrap_or(());
@@ -77,17 +68,9 @@ fn main() {
let cmd_name = cmd.name();
- if let Some(wait) = wait_selector.as_ref() {
- if let Err(err) = validate_wait_for_command(cmd_name, wait) {
- finish(cmd_name, Err(err));
- return;
- }
- }
-
match cmd {
Commands::Version => {
- let result = agent_desktop_core::commands::version::execute();
- finish(cmd_name, result);
+ finish(cmd_name, agent_desktop_core::commands::version::execute());
}
Commands::Skills(a) => {
let result = match a.action.unwrap_or(SkillsAction::List) {
@@ -103,7 +86,35 @@ fn main() {
};
finish(cmd_name, result);
}
- cmd => run_with_adapter(cmd, cmd_name, &context),
+ cmd => {
+ let wait_selector = build_wait_selector(&cli);
+ let session_id = match resolve_active_session(
+ cli.session.as_deref(),
+ std::env::var("AGENT_DESKTOP_SESSION").ok().as_deref(),
+ ) {
+ Ok(session_id) => session_id,
+ Err(err) => {
+ finish(cmd_name, Err(err));
+ return;
+ }
+ };
+ let context = match CommandContext::new(session_id, cli.trace, cli.trace_strict) {
+ Ok(context) => context
+ .with_headed(cli.headed)
+ .with_wait_selector(wait_selector.clone()),
+ Err(err) => {
+ finish(cmd_name, Err(err));
+ return;
+ }
+ };
+ if let Some(wait) = wait_selector.as_ref() {
+ if let Err(err) = validate_wait_for_command(cmd_name, wait) {
+ finish(cmd_name, Err(err));
+ return;
+ }
+ }
+ run_with_adapter(cmd, cmd_name, &context);
+ }
}
}
diff --git a/tests/conformance/README.md b/tests/conformance/README.md
index 70d60e5f8..6a0309837 100644
--- a/tests/conformance/README.md
+++ b/tests/conformance/README.md
@@ -21,7 +21,8 @@ adapter-provided refs.
| Wait recovery | `wait --element` can poll the latest session refmap when no snapshot is pinned, honors the caller timeout while resolving, and reports the last observed predicate state |
| Session latest scope | Commands that omit `--snapshot` read and write only the active session's latest refmap |
| Explicit snapshot scope | Passing `--snapshot <id>` resolves that pinned snapshot even when the caller omits the original session |
-| Trace | `--trace <path>` writes JSONL diagnostics outside stdout and is best-effort unless strict |
+| Trace | With a `trace: on` session manifest (from `session start`), commands write per-process JSONL segments under the session directory; `--trace <path>` overrides to one file. Best-effort unless `--trace-strict`. |
+| Session lifecycle | `session start/end/list/gc` manage manifests, the current-session pointer, and trace directories |
| FFI parity | FFI ref actions use strict resolve and actionability checks before adapter dispatch |
## Platform Matrix