Skip to content

armgit / cua

Public Imported from GitHub
0

Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.

fix(cua-driver): finalize the previous recording when a new one starts (#6794)

injaneity5e2cb4714749
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/models/recording.cfg b/libs/cua-driver/rust/crates/cua-driver-core/models/recording.cfg
new file mode 100644
index 0000000000..a5a7ef42ef
--- /dev/null
+++ b/libs/cua-driver/rust/crates/cua-driver-core/models/recording.cfg
@@ -0,0 +1,8 @@
+\* SPDX-License-Identifier: MIT
+SPECIFICATION Spec
+CONSTANTS MaxStarts = 3
+ FinalizeOnRestart = TRUE
+ DirFirst = TRUE
+ IdleByGen = TRUE
+INVARIANTS RC1 RC2 RC3 RC4 RC5
+CHECK_DEADLOCK FALSE
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/models/recording.tla b/libs/cua-driver/rust/crates/cua-driver-core/models/recording.tla
new file mode 100644
index 0000000000..80750bb870
--- /dev/null
+++ b/libs/cua-driver/rust/crates/cua-driver-core/models/recording.tla
@@ -0,0 +1,95 @@
+\* SPDX-License-Identifier: MIT
+\* Copyright (c) 2026 Cua AI, Inc.
+---- MODULE recording ----
+\* The runtime's trajectory recorder, RecordingSession in src/recording.rs.
+\* Two sessions A and B share one recorder. Directories are numbered by start.
+\* The cursor sampler (and video, when it started) is the recording's media.
+\*
+\* Three switches select the code. All TRUE is src/recording.rs; each FALSE is
+\* the old behaviour it replaced:
+\* FinalizeOnRestart a start over a live recording finalizes the old one
+\* DirFirst the new directory is created before the old one is torn down
+\* IdleByGen the idle-TTL stop names the generation it read
+\*
+\* Check with TLC (tla2tools.jar):
+\* java -cp tla2tools.jar tlc2.TLC -config recording.cfg recording.tla
+\* the code: every invariant holds
+\* ... -config recording_restart.cfg RC3 fails: A starts, B starts
+\* ... -config recording_dirfail.cfg RC4 fails: a start whose directory fails
+\* ... -config recording_idle.cfg RC5 fails: idle read, restart, idle stop
+EXTENDS Naturals
+CONSTANTS MaxStarts, FinalizeOnRestart, DirFirst, IdleByGen
+S == {"A", "B"}
+VARIABLES enabled, owner, gen, media, ended, hooked, dirs, turn, idle
+vars == <<enabled, owner, gen, media, ended, hooked, dirs, turn, idle>>
+\* dirs[g]: "none" | "open" (initial session.json) | "final" (rewritten at finalize)
+\* media: "none" (idle) | "running" | "stopped" (stopped while the recording stays live)
+\* idle: the TTL check reads the live generation, then stops; hit is what it stopped
+Init == /\ enabled = FALSE /\ owner = "none" /\ gen = 0 /\ media = "none"
+ /\ ended = [s \in S |-> FALSE] /\ hooked = [s \in S |-> FALSE] /\ dirs = [g \in 1..MaxStarts |-> "none"]
+ /\ turn = [g |-> 0, into |-> 0, phase |-> "none"]
+ /\ idle = [phase |-> "none", read |-> 0, hit |-> 0]
+
+\* start refuses a dead owner, then replaces any live recording with a new one.
+Start(s) ==
+ /\ gen < MaxStarts /\ ~ended[s]
+ /\ gen' = gen + 1
+ /\ dirs' = [g \in 1..MaxStarts |->
+ IF g = gen + 1 THEN "open"
+ ELSE IF g = gen /\ enabled /\ FinalizeOnRestart THEN "final" ELSE dirs[g]]
+ /\ enabled' = TRUE /\ owner' = s /\ media' = "running"
+ /\ UNCHANGED <<ended, hooked, turn, idle>>
+\* create_dir_all fails. The old code had already stopped the live media.
+DirFail(s) ==
+ /\ ~ended[s]
+ /\ media' = IF enabled /\ ~DirFirst THEN "stopped" ELSE media
+ /\ UNCHANGED <<enabled, owner, gen, ended, hooked, dirs, turn, idle>>
+Stop == /\ enabled' = FALSE /\ owner' = "none" /\ media' = "none"
+ /\ dirs' = [dirs EXCEPT ![gen] = "final"]
+\* stop(StopBy::Anyone): manual stop and runtime shutdown
+StopAnyone == enabled /\ Stop /\ UNCHANGED <<gen, ended, hooked, turn, idle>>
+\* session end: tombstone first, then the "recording" hook runs stop(StopBy::Owner(s))
+SessionEnds(s) == /\ ~ended[s] /\ ended' = [ended EXCEPT ![s] = TRUE]
+ /\ UNCHANGED <<enabled, owner, gen, media, hooked, dirs, turn, idle>>
+EndHook(s) == /\ ended[s] /\ ~hooked[s] /\ hooked' = [hooked EXCEPT ![s] = TRUE]
+ /\ IF enabled /\ owner = s THEN Stop ELSE UNCHANGED <<enabled, owner, media, dirs>>
+ /\ UNCHANGED <<gen, ended, turn, idle>>
+\* The idle-TTL thread reads the state, then stops in a separate call.
+IdleRead == /\ enabled /\ idle.phase = "none"
+ /\ idle' = [phase |-> "read", read |-> gen, hit |-> 0]
+ /\ UNCHANGED <<enabled, owner, gen, media, ended, hooked, dirs, turn>>
+IdleStop(readGen) ==
+ /\ idle.phase = "read" /\ idle.read = readGen
+ /\ IF enabled /\ (IdleByGen => gen = readGen)
+ THEN Stop /\ idle' = [idle EXCEPT !.phase = "done", !.hit = gen]
+ ELSE idle' = [idle EXCEPT !.phase = "done"] /\ UNCHANGED <<enabled, owner, media, dirs>>
+ /\ UNCHANGED <<gen, ended, hooked, turn>>
+IdleReset == /\ idle.phase = "done" /\ idle' = [phase |-> "none", read |-> 0, hit |-> 0]
+ /\ UNCHANGED <<enabled, owner, gen, media, ended, hooked, dirs, turn>>
+\* begin_turn reserves under the live generation; finish_turn drops it if the generation moved
+BeginTurn == /\ enabled /\ turn.phase = "none"
+ /\ turn' = [g |-> gen, into |-> 0, phase |-> "pending"]
+ /\ UNCHANGED <<enabled, owner, gen, media, ended, hooked, dirs, idle>>
+FinishTurn == /\ turn.phase = "pending"
+ /\ turn' = [g |-> turn.g, into |-> gen,
+ phase |-> IF enabled /\ gen = turn.g THEN "written" ELSE "discarded"]
+ /\ UNCHANGED <<enabled, owner, gen, media, ended, hooked, dirs, idle>>
+ResetTurn == /\ turn.phase \in {"written", "discarded"} /\ turn' = [g |-> 0, into |-> 0, phase |-> "none"]
+ /\ UNCHANGED <<enabled, owner, gen, media, ended, hooked, dirs, idle>>
+
+Next == \/ \E s \in S : Start(s) \/ DirFail(s) \/ SessionEnds(s) \/ EndHook(s)
+ \/ StopAnyone \/ IdleRead \/ \E g \in 1..MaxStarts : IdleStop(g) \/ IdleReset
+ \/ BeginTurn \/ FinishTurn \/ ResetTurn
+Spec == Init /\ [][Next]_vars
+
+\* RC1. A turn is written only into the recording it was reserved under.
+RC1 == turn.phase = "written" => turn.into = turn.g
+\* RC2. Once a session's end hook has run, no live recording belongs to it.
+RC2 == ~(enabled /\ owner # "none" /\ hooked[owner])
+\* RC3. Every recording directory that is no longer live has a final session.json.
+RC3 == \A g \in 1..MaxStarts : (dirs[g] = "open") => (enabled /\ g = gen)
+\* RC4. A live recording's media is running: a failed start leaves no half-torn recording.
+RC4 == enabled <=> media = "running"
+\* RC5. An idle stop never stops a later generation than the one it read.
+RC5 == idle.hit # 0 => idle.hit = idle.read
+====
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/models/recording_dirfail.cfg b/libs/cua-driver/rust/crates/cua-driver-core/models/recording_dirfail.cfg
new file mode 100644
index 0000000000..720b7daeb4
--- /dev/null
+++ b/libs/cua-driver/rust/crates/cua-driver-core/models/recording_dirfail.cfg
@@ -0,0 +1,8 @@
+\* SPDX-License-Identifier: MIT
+SPECIFICATION Spec
+CONSTANTS MaxStarts = 3
+ FinalizeOnRestart = TRUE
+ DirFirst = FALSE
+ IdleByGen = TRUE
+INVARIANTS RC4
+CHECK_DEADLOCK FALSE
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/models/recording_idle.cfg b/libs/cua-driver/rust/crates/cua-driver-core/models/recording_idle.cfg
new file mode 100644
index 0000000000..767d66e055
--- /dev/null
+++ b/libs/cua-driver/rust/crates/cua-driver-core/models/recording_idle.cfg
@@ -0,0 +1,8 @@
+\* SPDX-License-Identifier: MIT
+SPECIFICATION Spec
+CONSTANTS MaxStarts = 3
+ FinalizeOnRestart = TRUE
+ DirFirst = TRUE
+ IdleByGen = FALSE
+INVARIANTS RC5
+CHECK_DEADLOCK FALSE
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/models/recording_restart.cfg b/libs/cua-driver/rust/crates/cua-driver-core/models/recording_restart.cfg
new file mode 100644
index 0000000000..2a82d3b65d
--- /dev/null
+++ b/libs/cua-driver/rust/crates/cua-driver-core/models/recording_restart.cfg
@@ -0,0 +1,8 @@
+\* SPDX-License-Identifier: MIT
+SPECIFICATION Spec
+CONSTANTS MaxStarts = 3
+ FinalizeOnRestart = FALSE
+ DirFirst = TRUE
+ IdleByGen = TRUE
+INVARIANTS RC3
+CHECK_DEADLOCK FALSE
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/recording.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/recording.rs
index bd161bbf29..b5d4e67a60 100644
--- a/libs/cua-driver/rust/crates/cua-driver-core/src/recording.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/recording.rs
@@ -576,6 +576,19 @@ impl RecordingCaller<'_> {
}
}
+/// Which recording a stop applies to.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum StopBy<'a> {
+ /// Manual stop and runtime shutdown: whatever recording is live.
+ Anyone,
+ /// Session end: only a recording this session owns. An anonymous
+ /// recording is owned by nobody, so only [`StopBy::Anyone`] reaches it.
+ Owner(&'a str),
+ /// Idle TTL: only the generation the caller read from
+ /// [`RecordingState::generation`], never a recording started after it.
+ Generation(u64),
+}
+
/// Persistent recording session state owned by one tool registry.
pub struct RecordingSession {
inner: Mutex<RecordingInner>,
@@ -583,50 +596,86 @@ pub struct RecordingSession {
}
struct RecordingInner {
- enabled: bool,
+ /// Bumped by every start; a turn or idle stop names the one it read.
generation: u64,
- /// Session that owns the live recording, stamped on every successful
- /// `start()` from the daemon-injected `_session_id`. The daemon-global
- /// recorder is a singleton, so when session A starts a recording and
- /// session B later starts another (clobbering A's), A's disconnect must
- /// NOT stop B's recording. The proxy-exit `session_end` hook passes its
- /// own session id to `stop_owner()`, which no-ops when the live owner has
- /// moved on. `None` means the recording was started anonymously (CLI
- /// one-shot) and is owned by nobody — only an
- /// unconditional `stop_owner(None)` can tear it down. Supersedes the
- /// #1775 generation token: a session id is a stable owner identity rather
- /// than a monotonic counter, and it doubles as the config-override key.
- owner: Option<String>,
- output_dir: Option<PathBuf>,
+ recorder: Recorder,
/// Per-turn application-state budget, or `None` when the caller disabled
/// state capture with `include_accessibility_tree: false`.
state_budget: Option<StateCaptureBudget>,
- next_turn: u32,
- session_start_ms: u64,
- /// Monotonic clock anchor for the cursor sampler so its `t_ms`
- /// matches the action-timeline anchor in `action.json`.
- session_monotonic_start: Option<Instant>,
last_error: Option<String>,
- /// Live video backend when capture is active. Recreated per
- /// session. The concrete type is platform-determined (SCKit on
- /// macOS, ffmpeg subprocess elsewhere).
+}
+
+enum Recorder {
+ /// `last_video` is the finalized video of the previous recording, if any.
+ Idle {
+ last_video: Option<VideoMetadata>,
+ },
+ Live(Live),
+}
+
+struct Live {
+ /// Session that owns the recording, from the daemon-injected
+ /// `_session_id`; `None` for an anonymous (CLI one-shot) start. The
+ /// recorder is shared, so the latest start owns it and an earlier owner's
+ /// session end no-ops in [`RecordingSession::stop`].
+ owner: Option<String>,
+ dir: PathBuf,
+ next_turn: u32,
+ started_at_ms: u64,
+ /// SCKit on macOS, an ffmpeg subprocess elsewhere.
video: Option<Box<dyn VideoBackend>>,
- /// Recorded after `stop()` until the next start — exposed in
- /// `current_state()` so callers can read the finalized video info
- /// after stopping.
- last_video: Option<VideoMetadata>,
- /// Cursor sampler thread. Runs alongside video so the renderer has
- /// per-frame cursor positions for smooth pan-between-clicks
- /// behavior. Stopped on `stop()` along with video.
cursor: Option<CursorSampler>,
- /// Sample count from the last finalized cursor sampler; exposed in
- /// `session.json` after stop so the renderer can confirm the
- /// sampler ran.
- last_cursor_samples: usize,
- /// Secret values scrubbed from every turn of the live recording.
+ /// Secret values scrubbed from every turn of this recording.
redactions: Redactions,
}
+impl RecordingInner {
+ fn is_live(&self, generation: u64) -> bool {
+ matches!(self.recorder, Recorder::Live(_)) && self.generation == generation
+ }
+
+ /// Stop the live recording's media and rewrite its `session.json` with
+ /// what landed. Leaves the recorder idle; a no-op when already idle.
+ fn finalize(&mut self) -> anyhow::Result<()> {
+ let idle = Recorder::Idle { last_video: None };
+ let Recorder::Live(live) = std::mem::replace(&mut self.recorder, idle) else {
+ return Ok(());
+ };
+ let (video_meta, stop_error) = match live.video.map(|rec| rec.stop()) {
+ Some(Ok(meta)) => match validate_video_metadata(meta) {
+ Ok(meta) => (Some(meta), None),
+ Err(error) => (None, Some(error.to_string())),
+ },
+ Some(Err(error)) => (None, Some(error.to_string())),
+ None => (None, None),
+ };
+ let cursor_samples = live.cursor.map(|c| c.stop()).unwrap_or(0);
+ if let Some(error) = &stop_error {
+ self.last_error = Some(error.clone());
+ } else if video_meta.is_some() {
+ self.last_error = None;
+ }
+ let video_block = match &video_meta {
+ Some(meta) => video_session_payload(true, None, Some(meta)),
+ None => video_session_payload(false, self.last_error.as_deref(), None),
+ };
+ let session_payload = serde_json::json!({
+ "schema_version": 1,
+ "started_at_monotonic_ms": live.started_at_ms,
+ "video": video_block,
+ "cursor": { "present": cursor_samples > 0, "sample_count": cursor_samples }
+ });
+ let _ = write_json_atomic(&live.dir.join("session.json"), &session_payload);
+ self.recorder = Recorder::Idle {
+ last_video: video_meta,
+ };
+ match stop_error {
+ Some(error) => anyhow::bail!("video finalization failed: {error}"),
+ None => Ok(()),
+ }
+ }
+}
+
/// Snapshot of the current recording state (cheap to clone).
#[derive(Debug, Clone)]
pub struct RecordingState {
@@ -639,13 +688,12 @@ pub struct RecordingState {
/// Path to the most recently finalized video file, if any. Populated
/// after a stop; cleared on next start.
pub last_video_path: Option<String>,
- /// Session id that owns the current (or most recent) recording, stamped on
- /// `start()` from the daemon-injected `_session_id`. `None` for an
- /// anonymously-started recording (CLI one-shot). Surfaced so
- /// callers can see who owns the live recording; the proxy-exit teardown
- /// drives ownership via `session_end` (it already knows its own id) rather
- /// than reading this back.
+ /// Session id that owns the live recording, stamped on `start()` from the
+ /// daemon-injected `_session_id`. `None` for an anonymous recording (CLI
+ /// one-shot) or when idle.
pub owner: Option<String>,
+ /// Generation of the live recording, for [`StopBy::Generation`].
+ pub generation: Option<u64>,
}
impl RecordingSession {
@@ -653,20 +701,10 @@ impl RecordingSession {
Self {
pixel_point_fn: OnceLock::new(),
inner: Mutex::new(RecordingInner {
- enabled: false,
generation: 0,
- owner: None,
- output_dir: None,
+ recorder: Recorder::Idle { last_video: None },
state_budget: Some(StateCaptureBudget::default()),
- next_turn: 1,
- session_start_ms: 0,
- session_monotonic_start: None,
last_error: None,
- video: None,
- last_video: None,
- cursor: None,
- last_cursor_samples: 0,
- redactions: Redactions::default(),
}),
}
}
@@ -684,7 +722,7 @@ impl RecordingSession {
}
/// Enable recording at `output_dir`, optionally with video capture.
- /// Counterpart to `stop()`. Returns the resulting state.
+ /// Counterpart to [`Self::stop`]. Returns the resulting state.
///
/// `record_video=true` spawns ffmpeg writing `<output_dir>/recording.mp4`
/// for the lifetime of the session. NOTE: the MCP `start_recording` tool
@@ -696,8 +734,9 @@ impl RecordingSession {
/// the caller can surface it.
///
/// `owner` stamps the session that owns this recording (the daemon-injected
- /// `_session_id`). `None` marks an anonymous start (CLI one-shot) owned by nobody. See `stop_owner()` for how this
- /// gates teardown.
+ /// `_session_id`). `None` marks an anonymous start (CLI one-shot) owned by nobody. See [`StopBy`] for how this
+ /// gates teardown. A start over a live recording finalizes that recording
+ /// first, as [`Self::stop`] does.
pub fn start(
&self,
output_dir: &str,
@@ -744,13 +783,13 @@ impl RecordingSession {
) -> anyhow::Result<()> {
let mut inner = self.inner.lock().unwrap();
// Write-boundary resurrection guard — checked INSIDE the lock so the
- // is_session_ended test is atomic with the enabled/owner write below.
+ // is_session_ended test is atomic with the recorder write below.
// An in-flight start_recording that lands after its owning session ended
// (passed the dispatch gate, then the proxy died) must not create a
// recording owned by a dead session — a leaked ffmpeg/SCStream. The
// teardown sites call `fire_session_end` (which marks ENDED_SESSIONS)
- // BEFORE `stop_owner`, so either the mark is already set and we bail
- // here, or we win the lock first and the reaper's later stop_owner(owner)
+ // BEFORE `stop(StopBy::Owner)`, so either the mark is already set and we bail
+ // here, or we win the lock first and the reaper's later stop
// reaps what we started. Anonymous starts (owner = None: CLI one-shot) are never gated.
if let Some(o) = owner {
if crate::session::is_session_ended(o) {
@@ -759,32 +798,25 @@ impl RecordingSession {
);
}
}
- // If a previous session is still open, gracefully tear it down
- // first so the caller doesn't accidentally leak an ffmpeg process.
- if let Some(rec) = inner.video.take() {
- let _ = rec.stop();
- }
- if let Some(cur) = inner.cursor.take() {
- let _ = cur.stop();
- }
-
let dir = expand_tilde(output_dir);
+ // Create the new directory while the live recording still runs, so a
+ // failure leaves it untouched.
std::fs::create_dir_all(&dir)?;
+ // Finalize the recording this start replaces; its error stays in
+ // `last_error` and does not fail the new start.
+ let _ = inner.finalize();
// Single monotonic anchor shared by video, cursor sampler, and
// per-turn `t_ms_from_session_start` math in `finish_turn()` — so all
// three timelines line up at the millisecond.
let monotonic_start = Instant::now();
- let mut video_present = false;
+ let mut video = None;
let mut video_error: Option<String> = None;
if record_video {
let path = dir.join("recording.mp4");
match video::start_video(&path) {
- Ok(rec) => {
- inner.video = Some(rec);
- video_present = true;
- }
+ Ok(rec) => video = Some(rec),
Err(e) => {
video_error = Some(e.to_string());
tracing::warn!(target: "recording",
@@ -801,15 +833,11 @@ impl RecordingSession {
// post-hoc analysis, so we run it anyway — the cost is one
// background thread + a small jsonl file.
let cursor_path = dir.join("cursor.jsonl");
- match CursorSampler::start(cursor_path, monotonic_start) {
- Ok(s) => {
- inner.cursor = Some(s);
- }
- Err(e) => {
- tracing::warn!(target: "recording",
- "Cursor sampler failed to start: {e}");
- }
- }
+ let cursor = CursorSampler::start(cursor_path, monotonic_start)
+ .inspect_err(
+ |e| tracing::warn!(target: "recording", "Cursor sampler failed to start: {e}"),
+ )
+ .ok();
// Write initial session.json — final video metadata is rewritten on
// stop. We mark `present` based on whether ffmpeg actually started,
@@ -818,130 +846,63 @@ impl RecordingSession {
let session_payload = serde_json::json!({
"schema_version": 1,
"started_at_monotonic_ms": started_at_ms,
- "video": video_session_payload(video_present, video_error.as_deref(), None),
- "cursor": { "present": inner.cursor.is_some(), "sample_count": 0 }
+ "video": video_session_payload(video.is_some(), video_error.as_deref(), None),
+ "cursor": { "present": cursor.is_some(), "sample_count": 0 }
});
let _ = write_json_atomic(&dir.join("session.json"), &session_payload);
- // Stamp the owning session on every successful start (reached only on
- // the success path — start() returns early via `?` on `create_dir_all`
- // failure above). `owner` clobbers any previous owner, which is correct:
- // the daemon-global recorder is a singleton, so the latest start() owns
- // it. The previous owner's disconnect then no-ops in stop_owner().
- inner.owner = owner.map(str::to_owned);
inner.generation = inner.generation.wrapping_add(1);
- inner.enabled = true;
- inner.output_dir = Some(dir);
inner.state_budget = state_budget;
- inner.redactions = redactions;
- inner.next_turn = 1;
- inner.session_start_ms = started_at_ms;
- inner.session_monotonic_start = Some(monotonic_start);
inner.last_error = video_error;
- inner.last_video = None;
- inner.last_cursor_samples = 0;
+ inner.recorder = Recorder::Live(Live {
+ owner: owner.map(str::to_owned),
+ dir,
+ next_turn: 1,
+ started_at_ms,
+ video,
+ cursor,
+ redactions,
+ });
Ok(())
}
- /// Disable recording. Idempotent — calling stop on an already-stopped
- /// session is a no-op. If a video subprocess is running, it's
- /// gracefully terminated and the finalized metadata is folded into
- /// `session.json`.
- ///
- /// `requester` is the ownership guard for session-driven teardown
- /// (`session_end` / proxy-exit). Semantics:
- /// - `None` — unconditional stop. Manual `stop_recording`, the CLI
- /// one-shot path, and the idle-TTL backstop all pass `None` to preserve today's manual-stop behavior.
- /// - `Some(sid)` where `sid` owns the live recording — stop + clear owner.
- /// - `Some(sid)` where `sid` does NOT own it (a disconnecting session
- /// whose recording was already clobbered by a newer `start()`, or which
- /// never started a recording) — silent no-op, leaving the current
- /// owner's recording running.
- ///
- /// The guard lives inside the lock so it is race-free against a concurrent
- /// `start()`. Supersedes the #1775 generation-token `stop()`.
- pub fn stop_owner(&self, requester: Option<&str>) -> anyhow::Result<()> {
+ /// Finalize the recording `by` selects: stop its video and cursor sampler
+ /// and rewrite `session.json` with what landed. A no-op when idle or when
+ /// `by` selects a recording other than the live one, so a stale session
+ /// end or idle check never stops a newer recording. The check runs under
+ /// the lock, so it is race-free against a concurrent `start()`.
+ pub fn stop(&self, by: StopBy<'_>) -> anyhow::Result<()> {
let mut inner = self.inner.lock().unwrap();
- if !inner.enabled {
+ let Recorder::Live(live) = &inner.recorder else {
return Ok(());
- }
- if let Some(req) = requester {
- // A targeted stop only acts when the requester owns the live
- // recording. An anonymously-owned recording (owner == None) is
- // never torn down by a session-scoped stop — only an unconditional
- // `stop_owner(None)` reaches it.
- if inner.owner.as_deref() != Some(req) {
- return Ok(());
- }
- }
- inner.owner = None;
- let dir = inner.output_dir.clone();
- let started_at_ms = inner.session_start_ms;
- let (video_meta, stop_error) = match inner.video.take().map(|rec| rec.stop()) {
- Some(Ok(meta)) => match validate_video_metadata(meta) {
- Ok(meta) => (Some(meta), None),
- Err(error) => (None, Some(error.to_string())),
- },
- Some(Err(error)) => (None, Some(error.to_string())),
- None => (None, None),
};
- let cursor_samples = inner.cursor.take().map(|c| c.stop()).unwrap_or(0);
-
- inner.enabled = false;
- inner.output_dir = None;
- inner.redactions = Redactions::default();
- inner.next_turn = 1;
- inner.session_start_ms = 0;
- inner.session_monotonic_start = None;
- if let Some(error) = &stop_error {
- inner.last_error = Some(error.clone());
- } else if video_meta.is_some() {
- inner.last_error = None;
- }
- inner.last_video = video_meta.clone();
- inner.last_cursor_samples = cursor_samples;
- let final_video_error = inner.last_error.clone();
-
- // Rewrite session.json with final video metadata + cursor count
- // so the renderer (and any external analysis) sees what actually
- // landed.
- if let Some(dir) = dir {
- let video_block = if let Some(ref m) = video_meta {
- video_session_payload(true, None, Some(m))
- } else {
- video_session_payload(false, final_video_error.as_deref(), None)
- };
- let session_payload = serde_json::json!({
- "schema_version": 1,
- "started_at_monotonic_ms": started_at_ms,
- "video": video_block,
- "cursor": { "present": cursor_samples > 0, "sample_count": cursor_samples }
- });
- let _ = write_json_atomic(&dir.join("session.json"), &session_payload);
- }
- if let Some(error) = stop_error {
- anyhow::bail!("video finalization failed: {error}");
+ let selected = match by {
+ StopBy::Anyone => true,
+ StopBy::Owner(session) => live.owner.as_deref() == Some(session),
+ StopBy::Generation(generation) => inner.generation == generation,
+ };
+ if !selected {
+ return Ok(());
}
- Ok(())
+ inner.finalize()
}
/// Return a snapshot of the current state (non-blocking).
pub fn current_state(&self) -> RecordingState {
let inner = self.inner.lock().unwrap();
+ let (live, last_video) = match &inner.recorder {
+ Recorder::Live(live) => (Some(live), None),
+ Recorder::Idle { last_video } => (None, last_video.as_ref()),
+ };
RecordingState {
- enabled: inner.enabled,
- output_dir: inner
- .output_dir
- .as_ref()
- .map(|p| p.to_string_lossy().into_owned()),
- next_turn: inner.next_turn,
+ enabled: live.is_some(),
+ output_dir: live.map(|l| l.dir.to_string_lossy().into_owned()),
+ next_turn: live.map_or(1, |l| l.next_turn),
last_error: inner.last_error.clone(),
- video_active: inner.video.is_some(),
- last_video_path: inner
- .last_video
- .as_ref()
- .map(|m| m.path.to_string_lossy().into_owned()),
- owner: inner.owner.clone(),
+ video_active: live.is_some_and(|l| l.video.is_some()),
+ last_video_path: last_video.map(|m| m.path.to_string_lossy().into_owned()),
+ owner: live.and_then(|l| l.owner.clone()),
+ generation: live.map(|_| inner.generation),
}
}
@@ -1006,23 +967,23 @@ impl RecordingSession {
) -> Option<PendingTurn> {
let (turn_dir, session_start_ms, generation, state_budget, redactions) = {
let mut inner = self.inner.lock().unwrap();
- if !inner.enabled {
+ let (generation, state_budget) = (inner.generation, inner.state_budget);
+ let Recorder::Live(live) = &mut inner.recorder else {
return None;
- }
- if let Some(owner) = inner.owner.as_deref() {
+ };
+ if let Some(owner) = live.owner.as_deref() {
if !caller.within(owner) {
return None;
}
}
- let out = inner.output_dir.clone()?;
- let idx = inner.next_turn;
- inner.next_turn += 1;
+ let idx = live.next_turn;
+ live.next_turn += 1;
(
- out.join(format!("turn-{idx:05}")),
- inner.session_start_ms,
- inner.generation,
- inner.state_budget,
- inner.redactions.clone(),
+ live.dir.join(format!("turn-{idx:05}")),
+ live.started_at_ms,
+ generation,
+ state_budget,
+ live.redactions.clone(),
)
};
@@ -1067,7 +1028,7 @@ impl RecordingSession {
};
let mut inner = self.inner.lock().unwrap();
- if !inner.enabled || inner.generation != generation {
+ if !inner.is_live(generation) {
return None;
}
if let Some(state) = before.state.bytes.as_mut() {
@@ -1139,7 +1100,7 @@ impl RecordingSession {
result_is_error: bool,
) {
let is_live = |inner: &RecordingInner| {
- let live = inner.enabled && inner.generation == pending.generation;
+ let live = inner.is_live(pending.generation);
if !live {
tracing::warn!(
target: "recording",
@@ -1711,6 +1672,18 @@ fn validate_video_metadata(meta: VideoMetadata) -> anyhow::Result<VideoMetadata>
mod tests {
use super::*;
+ fn live_at(dir: &Path) -> Live {
+ Live {
+ owner: None,
+ dir: dir.to_path_buf(),
+ next_turn: 1,
+ started_at_ms: now_ms(),
+ video: None,
+ cursor: None,
+ redactions: Redactions::default(),
+ }
+ }
+
#[test]
fn pixel_mappers_follow_registry_lifetimes_and_concurrent_runtime_state() {
use std::sync::atomic::{AtomicU32, Ordering};
@@ -1721,8 +1694,7 @@ mod tests {
let output = tempfile::tempdir().unwrap();
{
let mut inner = registry.recording.inner.lock().unwrap();
- inner.enabled = true;
- inner.output_dir = Some(output.path().to_owned());
+ inner.recorder = Recorder::Live(live_at(output.path()));
}
let ratio = Arc::downgrade(ratio);
registry.recording.set_pixel_point_fn(move |_, _, _, x, y| {
@@ -1842,8 +1814,7 @@ mod tests {
.is_none());
{
let mut inner = session.inner.lock().unwrap();
- inner.enabled = true;
- inner.output_dir = Some(root.path().to_path_buf());
+ inner.recorder = Recorder::Live(live_at(root.path()));
}
let private = session
.begin_private_turn("click", &pending.args, 0, RecordingCaller::default())
@@ -1921,8 +1892,7 @@ mod tests {
let session = RecordingSession::new();
{
let mut inner = session.inner.lock().unwrap();
- inner.enabled = true;
- inner.output_dir = Some(root.path().to_path_buf());
+ inner.recorder = Recorder::Live(live_at(root.path()));
}
let pending = session
.begin_turn(
@@ -2353,9 +2323,7 @@ mod tests {
let session = RecordingSession::new();
{
let mut inner = session.inner.lock().expect("recording lock");
- inner.enabled = true;
- inner.output_dir = Some(output_dir.clone());
- inner.session_start_ms = now_ms();
+ inner.recorder = Recorder::Live(live_at(&output_dir));
}
let pending = session
.begin_turn(
@@ -2564,10 +2532,8 @@ mod tests {
let session = RecordingSession::new();
{
let mut inner = session.inner.lock().expect("recording lock");
- inner.enabled = true;
inner.generation = 1;
- inner.output_dir = Some(output_dir.clone());
- inner.session_start_ms = now_ms();
+ inner.recorder = Recorder::Live(live_at(&output_dir));
}
let pending = session
.begin_turn(
@@ -2798,10 +2764,10 @@ mod tests {
let session = RecordingSession::new();
{
let mut inner = session.inner.lock().unwrap();
- inner.enabled = true;
- inner.output_dir = Some(root.path().join("session"));
- inner.session_start_ms = now_ms();
- inner.redactions = redactions.clone();
+ inner.recorder = Recorder::Live(Live {
+ redactions: redactions.clone(),
+ ..live_at(&root.path().join("session"))
+ });
}
let pending = session
.begin_private_turn(
@@ -2837,8 +2803,8 @@ mod tests {
assert!(action.get("redacted").is_none());
// Stopping forgets the values.
- session.stop_owner(None).unwrap();
- assert!(session.inner.lock().unwrap().redactions.is_empty());
+ session.stop(StopBy::Anyone).unwrap();
+ assert!(!session.current_state().enabled);
// Before/after accessibility state, including JSON-escaped values.
let state = serde_json::to_vec(&serde_json::json!({
@@ -2898,9 +2864,7 @@ mod tests {
let session = RecordingSession::new();
{
let mut inner = session.inner.lock().expect("recording lock");
- inner.enabled = true;
- inner.output_dir = Some(output_dir.clone());
- inner.session_start_ms = now_ms();
+ inner.recorder = Recorder::Live(live_at(&output_dir));
}
let pending = session
.begin_private_turn(
@@ -2946,7 +2910,7 @@ mod tests {
}
#[test]
- fn stop_owner_surfaces_video_finalization_failure() {
+ fn stop_surfaces_video_finalization_failure() {
let output_dir = std::env::temp_dir().join(format!(
"cua-recording-stop-failure-{}-{}",
std::process::id(),
@@ -2956,13 +2920,14 @@ mod tests {
let session = RecordingSession::new();
{
let mut inner = session.inner.lock().expect("recording lock");
- inner.enabled = true;
- inner.output_dir = Some(output_dir.clone());
- inner.video = Some(Box::new(FailingVideo));
+ inner.recorder = Recorder::Live(Live {
+ video: Some(Box::new(FailingVideo)),
+ ..live_at(&output_dir)
+ });
}
let error = session
- .stop_owner(None)
+ .stop(StopBy::Anyone)
.expect_err("video finalization failure must reach the caller");
assert!(error.to_string().contains("recorder did not finalize"));
let state = session.current_state();
@@ -3068,7 +3033,7 @@ mod tests {
)
.expect("the owning session's call reserves a turn");
session.finish_turn(pending, "clicked");
- session.stop_owner(None).expect("stop owned recording");
+ session.stop(StopBy::Anyone).expect("stop owned recording");
let action: Value = serde_json::from_slice(
&std::fs::read(output_dir.join("turn-00001").join("action.json"))
@@ -3102,7 +3067,7 @@ mod tests {
.expect("start timestamp is an integer");
std::thread::sleep(Duration::from_millis(100));
- session.stop_owner(None).expect("stop recording");
+ session.stop(StopBy::Anyone).expect("stop recording");
assert_eq!(
read_manifest()["started_at_monotonic_ms"],
@@ -3154,7 +3119,7 @@ mod tests {
.expect("a named session on the owning transport reserves a turn");
session.finish_turn(pending, "clicked");
session
- .stop_owner(None)
+ .stop(StopBy::Anyone)
.expect("stop transport-owned recording");
assert!(output_dir.join("turn-00001").join("action.json").exists());
@@ -3184,7 +3149,9 @@ mod tests {
.expect("an anonymous recording records every caller");
session.finish_turn(pending, "clicked");
}
- session.stop_owner(None).expect("stop anonymous recording");
+ session
+ .stop(StopBy::Anyone)
+ .expect("stop anonymous recording");
assert!(output_dir.join("turn-00001").join("action.json").exists());
assert!(output_dir.join("turn-00002").join("action.json").exists());
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/recording_tools.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/recording_tools.rs
index b8d6141507..be651a2cbe 100644
--- a/libs/cua-driver/rust/crates/cua-driver-core/src/recording_tools.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/recording_tools.rs
@@ -23,7 +23,7 @@ use serde_json::{json, Value};
use crate::{
protocol::ToolResult,
- recording::{RecordingSession, RecordingState},
+ recording::{RecordingSession, RecordingState, StopBy},
tool::{Tool, ToolDef, ToolRegistry},
};
@@ -289,10 +289,9 @@ impl Tool for StopRecordingTool {
}
async fn invoke(&self, _args: Value) -> ToolResult {
- // Manual stop is unconditional — `None` requester tears down whatever
- // recording is active. Session-scoped teardown is driven by the
- // registry-owned session-end hook, which calls `stop_owner(sid)`.
- match self.session.stop_owner(None) {
+ // Manual stop tears down whatever recording is live. Session-scoped
+ // teardown is the registry-owned session-end hook's `StopBy::Owner`.
+ match self.session.stop(StopBy::Anyone) {
Ok(()) => {
let state = self.session.current_state();
let video_note = state
@@ -777,7 +776,7 @@ mod tests {
expected,
"{args}"
);
- session.stop_owner(None).unwrap();
+ session.stop(StopBy::Anyone).unwrap();
}
}
@@ -824,7 +823,7 @@ mod tests {
let text = serde_json::to_string(&result.content).unwrap()
+ &serde_json::to_string(&result.structured_content).unwrap_or_default();
assert!(!text.contains("hunter2-Secret"), "{text}");
- session.stop_owner(None).unwrap();
+ session.stop(StopBy::Anyone).unwrap();
for entry in std::fs::read_dir(directory.path()).unwrap() {
let path = entry.unwrap().path();
if path.is_file() {
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/tests/recording_action_timestamp.rs b/libs/cua-driver/rust/crates/cua-driver-core/tests/recording_action_timestamp.rs
index dfd6ba31b3..2d633f1205 100644
--- a/libs/cua-driver/rust/crates/cua-driver-core/tests/recording_action_timestamp.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-core/tests/recording_action_timestamp.rs
@@ -3,7 +3,7 @@
use cua_driver_core::recording::{
now_ms, set_ax_snapshot_fn, set_element_bounds_fn, set_screenshot_fn, RecordingCaller,
- RecordingSession,
+ RecordingSession, StopBy,
};
use serde_json::{json, Value};
use std::time::Duration;
@@ -39,7 +39,7 @@ fn action_json_timestamp_is_the_documented_iso_8601_wall_clock_time() {
.unwrap();
std::thread::sleep(Duration::from_millis(5));
recording.finish_turn_with_outcome(pending, "Pressed a", None, false);
- recording.stop_owner(None).unwrap();
+ recording.stop(StopBy::Anyone).unwrap();
let latest = OffsetDateTime::now_utc().unix_timestamp_nanos() / 1_000_000;
let recorded: Value = serde_json::from_slice(
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/tests/recording_restart.rs b/libs/cua-driver/rust/crates/cua-driver-core/tests/recording_restart.rs
new file mode 100644
index 0000000000..be39632886
--- /dev/null
+++ b/libs/cua-driver/rust/crates/cua-driver-core/tests/recording_restart.rs
@@ -0,0 +1,111 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+//! A start over a live recording, and the idle stop, through the public
+//! recorder API. models/recording.tla checks the same rules.
+
+use std::path::{Path, PathBuf};
+
+use cua_driver_core::recording::{RecordingSession, StopBy};
+use cua_driver_core::video::{
+ set_video_backend_factory, VideoBackend, VideoBackendFactory, VideoMetadata,
+};
+use serde_json::Value;
+
+struct FakeFactory;
+/// Writes its file only when stopped, so a missing file means still running.
+struct FakeVideo(PathBuf);
+
+impl VideoBackendFactory for FakeFactory {
+ fn start(&self, output_path: &Path) -> anyhow::Result<Box<dyn VideoBackend>> {
+ Ok(Box::new(FakeVideo(output_path.to_path_buf())))
+ }
+}
+
+impl VideoBackend for FakeVideo {
+ fn stop(self: Box<Self>) -> anyhow::Result<VideoMetadata> {
+ std::fs::write(&self.0, b"fixture video")?;
+ Ok(VideoMetadata {
+ path: self.0,
+ duration_ms: 1,
+ finalized: true,
+ })
+ }
+}
+
+fn manifest(dir: &Path) -> Value {
+ serde_json::from_slice(&std::fs::read(dir.join("session.json")).unwrap()).unwrap()
+}
+
+fn utf8(path: &Path) -> &str {
+ path.to_str().unwrap()
+}
+
+#[test]
+fn restart_finalizes_the_previous_recording() {
+ set_video_backend_factory(Box::new(FakeFactory));
+ let root = tempfile::tempdir().unwrap();
+ let (first, second) = (root.path().join("first"), root.path().join("second"));
+ let session = RecordingSession::new();
+ session.start(utf8(&first), true, Some("a")).unwrap();
+ session.start(utf8(&second), true, Some("b")).unwrap();
+
+ let old = manifest(&first);
+ assert_eq!(old["video"]["finalized"], true, "{old}");
+ assert_eq!(
+ old["video"]["absolute_path"],
+ utf8(&first.join("recording.mp4"))
+ );
+ assert!(first.join("recording.mp4").exists());
+
+ let state = session.current_state();
+ assert!(state.enabled && state.video_active);
+ assert_eq!(state.owner.as_deref(), Some("b"));
+ assert_eq!(state.output_dir.as_deref(), Some(utf8(&second)));
+ session.stop(StopBy::Anyone).unwrap();
+ assert_eq!(manifest(&second)["video"]["finalized"], true);
+}
+
+#[test]
+fn restart_into_an_unusable_directory_keeps_the_live_recording() {
+ set_video_backend_factory(Box::new(FakeFactory));
+ let root = tempfile::tempdir().unwrap();
+ let live = root.path().join("live");
+ let blocker = root.path().join("file");
+ std::fs::write(&blocker, b"not a directory").unwrap();
+ let session = RecordingSession::new();
+ session.start(utf8(&live), true, None).unwrap();
+
+ assert!(session
+ .start(utf8(&blocker.join("child")), true, None)
+ .is_err());
+
+ assert!(!live.join("recording.mp4").exists(), "video kept running");
+ let state = session.current_state();
+ assert!(state.enabled && state.video_active);
+ assert_eq!(state.output_dir.as_deref(), Some(utf8(&live)));
+ session.stop(StopBy::Anyone).unwrap();
+ assert_eq!(manifest(&live)["video"]["finalized"], true);
+}
+
+#[test]
+fn a_stop_for_an_earlier_generation_leaves_the_newer_recording_running() {
+ let root = tempfile::tempdir().unwrap();
+ let session = RecordingSession::new();
+ session
+ .start(utf8(&root.path().join("first")), false, None)
+ .unwrap();
+ let read = session.current_state().generation.unwrap();
+ session
+ .start(utf8(&root.path().join("second")), false, None)
+ .unwrap();
+
+ session.stop(StopBy::Generation(read)).unwrap();
+ assert!(session.current_state().enabled, "newer recording survives");
+
+ let now = session.current_state().generation.unwrap();
+ session.stop(StopBy::Generation(now)).unwrap();
+ let state = session.current_state();
+ assert!(!state.enabled);
+ assert_eq!(state.generation, None);
+}
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/tests/recording_semantic_evidence.rs b/libs/cua-driver/rust/crates/cua-driver-core/tests/recording_semantic_evidence.rs
index 269164b568..711ed4d509 100644
--- a/libs/cua-driver/rust/crates/cua-driver-core/tests/recording_semantic_evidence.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-core/tests/recording_semantic_evidence.rs
@@ -5,7 +5,8 @@ use cua_driver_core::action_record::{
ActionEffect, ActionExecutionRecord, ActionTransport, ActualDelivery, RequestedDelivery,
};
use cua_driver_core::recording::{
- set_ax_snapshot_fn, set_element_bounds_fn, set_screenshot_fn, RecordingCaller, RecordingSession,
+ set_ax_snapshot_fn, set_element_bounds_fn, set_screenshot_fn, RecordingCaller,
+ RecordingSession, StopBy,
};
use serde_json::{json, Value};
@@ -40,7 +41,7 @@ fn macos_semantic_activation_without_a_point_preserves_truth_without_a_marker()
.begin_turn("click", &args, 0, RecordingCaller::default())
.unwrap();
recording.finish_turn_with_outcome(pending, "Performed AXPress", Some(&action), false);
- recording.stop_owner(None).unwrap();
+ recording.stop(StopBy::Anyone).unwrap();
let turn = directory.path().join("turn-00001");
let read_json = |name: &str| -> Value {
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/tests/recording_turn_latency.rs b/libs/cua-driver/rust/crates/cua-driver-core/tests/recording_turn_latency.rs
index 0eb35c94ea..1f55106439 100644
--- a/libs/cua-driver/rust/crates/cua-driver-core/tests/recording_turn_latency.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-core/tests/recording_turn_latency.rs
@@ -15,7 +15,7 @@ use std::time::{Duration, Instant};
use async_trait::async_trait;
use cua_driver_core::protocol::ToolResult;
use cua_driver_core::recording::{
- set_budgeted_ax_snapshot_fn, set_screenshot_fn, StateCaptureBudget,
+ set_budgeted_ax_snapshot_fn, set_screenshot_fn, StateCaptureBudget, StopBy,
};
use cua_driver_core::tool::{Tool, ToolDef, ToolRegistry};
use serde_json::{json, Value};
@@ -208,5 +208,5 @@ async fn recorded_actions_stay_bounded_with_a_slow_accessibility_provider() {
assert!(turn.join(format!("{phase}_state.json")).is_file());
}
- registry.recording.stop_owner(None).unwrap();
+ registry.recording.stop(StopBy::Anyone).unwrap();
}
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/tests/session_lifecycle.rs b/libs/cua-driver/rust/crates/cua-driver-core/tests/session_lifecycle.rs
index 29f495eff1..0679e7a835 100644
--- a/libs/cua-driver/rust/crates/cua-driver-core/tests/session_lifecycle.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-core/tests/session_lifecycle.rs
@@ -78,7 +78,7 @@ fn unique_id(tag: &str) -> String {
/// production `register_session_end_hook` registration:
/// - `cursor_removed` → `platform-macos`: `CursorRegistry::remove` + overlay.
/// - `config_cleared` → `platform-macos`: `SessionConfigRegistry::clear`.
-/// - `recording_stopped`→ `serve.rs`: `RecordingSession::stop_owner(Some(sid))`.
+/// - `recording_stopped`→ `serve.rs`: `RecordingSession::stop(StopBy::Owner(sid))`.
///
/// Each counts fires for ONE specific session id (hooks are process-global, so we
/// filter). A correctly-disposed session shows all three == 1.
diff --git a/libs/cua-driver/rust/crates/cua-driver-sdk/src/runtime.rs b/libs/cua-driver/rust/crates/cua-driver-sdk/src/runtime.rs
index 6922b94c93..540ae0d6e0 100644
--- a/libs/cua-driver/rust/crates/cua-driver-sdk/src/runtime.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-sdk/src/runtime.rs
@@ -11,6 +11,7 @@ use crate::{DriverActivityEvent, DriverActivityKind, DriverActivityObserver};
use cua_driver_core::{
authorization::PermissionMode,
protocol::ToolResult as CoreToolResult,
+ recording::StopBy,
session_authorization::{
AuthenticatedActionConnection, DelegatedSessionRequest, EffectiveAuthorizationContext,
SessionAuthorizationError, SessionAuthorizationRegistry, SessionModeCeiling,
@@ -246,7 +247,7 @@ impl DriverRuntime {
&self.compatibility_context.runtime_scope_key(),
);
let recording = self.registry.recording.clone();
- let _ = tokio::task::spawn_blocking(move || recording.stop_owner(None)).await;
+ let _ = tokio::task::spawn_blocking(move || recording.stop(StopBy::Anyone)).await;
}
fn stop_lifecycle_maintenance(&self) {
@@ -400,7 +401,8 @@ impl DriverRuntime {
// `end_session` is a lifecycle boundary: do not report completion
// until any recording owned by the session has finalized.
let recording = self.registry.recording.clone();
- let _ = tokio::task::spawn_blocking(move || recording.stop_owner(Some(&session))).await;
+ let _ =
+ tokio::task::spawn_blocking(move || recording.stop(StopBy::Owner(&session))).await;
}
Some(result)
}
@@ -474,7 +476,7 @@ impl Drop for DriverRuntime {
// another generation.
if was_running {
let recording = self.registry.recording.clone();
- let _ = recording.stop_owner(None);
+ let _ = recording.stop(StopBy::Anyone);
}
}
}
@@ -542,9 +544,15 @@ fn spawn_lifecycle_maintenance(runtime: &Arc<DriverRuntime>) -> LifecycleMainten
);
}
let idle = now_unix_secs().saturating_sub(runtime.last_activity.load(Ordering::Relaxed));
- if idle >= recording_ttl && runtime.registry.recording.current_state().enabled {
+ if idle < recording_ttl {
+ continue;
+ }
+ if let Some(generation) = runtime.registry.recording.current_state().generation {
tracing::warn!("recording idle {idle}s ≥ {recording_ttl}s TTL; auto-stopping");
- let _ = runtime.registry.recording.stop_owner(None);
+ let _ = runtime
+ .registry
+ .recording
+ .stop(StopBy::Generation(generation));
}
});
LifecycleMaintenance { shutdown, thread }
@@ -622,7 +630,7 @@ fn build_registry(options: &RuntimeOptions) -> ToolRegistry {
return Ok(());
};
recording
- .stop_owner(Some(session))
+ .stop(StopBy::Owner(session))
.map_err(|error| error.to_string())
},
);
diff --git a/libs/cua-driver/rust/crates/platform-macos/src/tools/mod.rs b/libs/cua-driver/rust/crates/platform-macos/src/tools/mod.rs
index 3e6f338940..94901cf96d 100644
--- a/libs/cua-driver/rust/crates/platform-macos/src/tools/mod.rs
+++ b/libs/cua-driver/rust/crates/platform-macos/src/tools/mod.rs
@@ -1451,7 +1451,7 @@ mod pixel_focus_readback_tests {
#[cfg(test)]
mod recording_start_guard_tests {
- use cua_driver_core::recording::RecordingSession;
+ use cua_driver_core::recording::{RecordingSession, StopBy};
use cua_driver_core::session::fire_session_end;
#[test]
@@ -1483,7 +1483,7 @@ mod recording_start_guard_tests {
let ok = rec.start(dir.to_str().unwrap(), false, Some(sid));
assert!(ok.is_ok(), "start for a live session owner must succeed");
assert!(rec.current_state().enabled);
- let _ = rec.stop_owner(Some(sid));
+ let _ = rec.stop(StopBy::Owner(sid));
}
#[test]
@@ -1494,7 +1494,7 @@ mod recording_start_guard_tests {
let ok = rec.start(dir.to_str().unwrap(), false, None);
assert!(ok.is_ok(), "anonymous start must never be gated");
assert!(rec.current_state().enabled);
- let _ = rec.stop_owner(None);
+ let _ = rec.stop(StopBy::Anyone);
}
}