Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 6 additions & 4 deletions crates/agentdeck-client/src/generated.rs
Original file line number Diff line number Diff line change
Expand Up @@ -429,12 +429,12 @@ pub mod types {
pub argv: ::std::vec::Vec<::std::string::String>,
///When the pane was created.
pub created_at: ::std::string::String,
///The working directory it was launched in.
///The working directory its process was launched in: by `POST /v1/panes`, or by its last `POST /v1/panes/{id}/respawn`. A respawn resumes its agent's session here, since the session started here (spec §4).
pub cwd: ::std::string::String,
///The exit code, once the process has exited.
#[serde(skip_serializing_if = "::std::option::Option::is_none")]
pub exit_code: ::std::option::Option<i64>,
///Its current folder (spec §6): the folder its shell last reported with OSC 7, else its process's working directory, else `cwd`, the folder it launched in, as the daemon last read them. Kept after it exits; a pane resumed after a restart starts there.
///Its current folder (spec §6): the folder its shell last reported with OSC 7, else its process's working directory, else `cwd`, the folder it launched in, as the daemon last read them. Kept after it exits; a pane resumed after a restart starts there, and so do Open shell and a fresh Restart agent (spec §4).
pub folder: ::std::string::String,
///The agent a shell pane hosts: `claude` or `codex` while the user's own is its foreground process, else null. Its kind stays `shell`; it runs that agent's state rules meanwhile (spec §3, §7).
#[serde(skip_serializing_if = "::std::option::Option::is_none")]
Expand Down Expand Up @@ -4293,9 +4293,11 @@ impl Client {
pub fn pane_input(&self) -> builder::PaneInput<'_> {
builder::PaneInput::new(self)
}
///Starts an exited pane again in place, keeping its id, its place in the tab's layout and
///Starts an exited pane again in place, keeping its id and its place in the layout
///
///its `cwd` (spec §4). `run: "agent"`, for an agent pane only (`unsupported_kind`), runs its agent again: claude and codex resume their session when it is known, else start fresh with a new session; an `other` agent runs its argv again. A resume that exits non-zero within 10 s, as one of a session the agent can no longer find does, is followed by a fresh start, once. `run: "shell"` turns the pane into a shell pane running `$SHELL`, with hosting on. The state starts over. `running` (409) while its process hasn't exited; `invalid_dir` when its `cwd` is gone; `invalid_argv` when the program can't start, and the pane stays exited.
///`run: "agent"`, for an agent pane only (`unsupported_kind`), runs its agent again: claude and codex resume their session when it is known, else start fresh with a new session; an `other` agent runs its argv again. A resume that exits non-zero within 10 s, as one of a session the agent can no longer find does, is followed by a fresh start, once. `run: "shell"` turns the pane into a shell pane running `$SHELL`, with hosting on (spec §4).
///
///A resume runs in the pane's `cwd`, the folder its session started in, which Claude Code and Codex need; once that folder is gone, the agent starts fresh instead. Anything else starts in the pane's last known folder, else its `cwd`, else `~`. The folder it starts in becomes its `cwd` and its `folder`, and the state starts over. `running` (409) while its process hasn't exited; `invalid_dir` when none of those folders is there; `invalid_argv` when the program can't start, and the pane stays exited.
///
///Sends a `POST` request to `/v1/panes/{id}/respawn`
///
Expand Down
2 changes: 1 addition & 1 deletion crates/agentdeck-core/src/daemon.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ use serde::{Deserialize, Serialize};
/// fails when `openapi.json` changes without a bump.
///
/// `0` is every daemon from before it existed, whose `daemon.json` has no `api_version`.
pub const API_VERSION: u32 = 28;
pub const API_VERSION: u32 = 29;

/// What `$XDG_RUNTIME_DIR/agentdeck/daemon.json` holds. The daemon writes it once it serves;
/// the GUI and the CLI read it to reach the daemon.
Expand Down
205 changes: 193 additions & 12 deletions crates/agentdeckd/src/agents/restart.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
//! Starting an exited pane's process again in place (spec §4, §6): its agent's session
//! resumed, its agent afresh with a new session, or a shell. A Claude Code
//! resumed, its agent afresh with a new session, or a shell, and where each starts
//! ([`place`]). A Claude Code
//! or Codex resume, by `POST /v1/panes/{id}/respawn` or after a restart, that exits non-zero
//! within [`FAILED_RESUME_WITHIN`] is taken for a session the agent can no longer find, and
//! the agent starts afresh, once (#237).

use std::fmt;
use std::path::PathBuf;
use std::path::{Path, PathBuf};
use std::time::Duration;

use agentdeck_core::ws::{Entity, ServerMessage};
Expand All @@ -28,16 +29,61 @@ use crate::terminal::pane::{Launch, SpawnError};
pub const FAILED_RESUME_WITHIN: Duration = Duration::from_secs(10);

/// What a respawn runs in a pane, decided from its row.
#[derive(Debug, PartialEq, Eq)]
pub enum Respawn {
/// Its agent's resume command on its session, or an `other` agent's argv: the row's
/// `argv` and `session_id` stay.
/// Claude Code's or Codex's resume command on its session: the row's `argv` and
/// `session_id` stay.
Resume(Agent, Vec<String>),
/// An `other` agent's argv, run again: the row's `argv` stays.
Again(Agent, Vec<String>),
/// Claude Code or Codex with no known session: a fresh launch, as a new pane's.
Fresh(Agent),
/// A shell, which the pane becomes.
Shell,
}

/// Where a respawn of a pane launched in `launched_in` (its `cwd`), whose last known folder
/// is `folder`, starts, and what it runs there (spec §4):
/// - a resume runs where its session started, `launched_in`: Claude Code finds a session by
/// the folder it started in, and Codex, which finds one anywhere, asks which folder to
/// work in when it isn't the one the session recorded. Once `launched_in` is gone, the
/// session can't be resumed there, so the agent starts afresh where a fresh start does;
/// - anything else (a fresh start, an `other` agent again, a shell) starts in `folder`, else
/// `launched_in`, else `home`.
///
/// `None` when none of them is an existing directory.
pub fn place(
respawn: Respawn,
launched_in: &Path,
folder: &Path,
home: Option<&Path>,
) -> Option<(Respawn, PathBuf)> {
let elsewhere = || existing_dir([Some(folder), Some(launched_in), home]);
match respawn {
Respawn::Resume(agent, argv) => match existing_dir([Some(launched_in)]) {
Some(dir) => Some((Respawn::Resume(agent, argv), dir)),
None => Some((Respawn::Fresh(agent), elsewhere()?)),
},
respawn => Some((respawn, elsewhere()?)),
}
}

/// The first of `folders` that is an existing absolute directory.
pub fn existing_dir<'a>(folders: impl IntoIterator<Item = Option<&'a Path>>) -> Option<PathBuf> {
folders
.into_iter()
.flatten()
.find(|dir| dir.is_absolute() && dir.is_dir())
.map(Path::to_path_buf)
}

/// The daemon's `$HOME`, which a pane's environment passes on too.
pub fn home() -> Option<PathBuf> {
std::env::var_os("HOME")
.filter(|home| !home.is_empty())
.map(PathBuf::from)
}

/// Why a pane couldn't start again.
#[derive(Debug)]
pub enum RestartError {
Expand Down Expand Up @@ -74,19 +120,21 @@ pub struct Restarter {
}

impl Restarter {
/// Runs `respawn` in exited pane `id`, in `cwd`, and returns its row as it is now. Its
/// state starts over; `changed` goes out for it. A resume that fails at once is followed
/// by a fresh start ([`Restarter::fall_back_if_resume_fails`]).
/// Runs `respawn` in exited pane `id`, in `cwd` ([`place`]), and returns its row as it is
/// now. `cwd` becomes its `cwd` and its `folder`, and its state starts over; `changed`
/// goes out for it. A resume that fails at once is followed by a fresh start
/// ([`Restarter::fall_back_if_resume_fails`]).
pub async fn respawn(
&self,
id: PaneId,
respawn: Respawn,
cwd: PathBuf,
) -> Result<Pane, RestartError> {
let (agent, argv) = match respawn {
let (agent, argv, resumed) = match respawn {
Respawn::Fresh(agent) => return self.fresh(id, agent, cwd).await,
Respawn::Shell => (None, vec![default_shell()]),
Respawn::Again(agent, argv) => (Some(agent), argv),
Respawn::Shell => (None, vec![default_shell()], None),
Respawn::Resume(agent, argv) => (Some(agent), argv, Some(agent)),
Respawn::Again(agent, argv) => (Some(agent), argv, None),
};
let shell = agent.is_none().then(|| argv.clone());
let folder = cwd.to_string_lossy().into_owned();
Expand All @@ -100,8 +148,6 @@ impl Restarter {
Ok((db::panes::get(c, id)?, db::panes::workspace_of(c, id)?))
})
.await?;
// `Again` for Claude Code or Codex is always a resume of its session.
let resumed = agent.filter(|agent| *agent != Agent::Other);
let feed = self.events.subscribe();
self.start(&pane, workspace, agent, argv, cwd.clone(), false)
.await?;
Expand Down Expand Up @@ -237,3 +283,138 @@ impl Restarter {
}
}
}

#[cfg(test)]
mod tests {
use super::*;

mod place {
use super::*;

/// A launch folder, a last known folder and a home, each a real dir.
struct Dirs {
launched_in: tempfile::TempDir,
folder: tempfile::TempDir,
home: tempfile::TempDir,
}

impl Dirs {
fn new() -> Dirs {
let dir = || tempfile::tempdir().expect("a temp dir");
Dirs {
launched_in: dir(),
folder: dir(),
home: dir(),
}
}

fn place(&self, respawn: Respawn) -> Option<(Respawn, PathBuf)> {
place(
respawn,
self.launched_in.path(),
self.folder.path(),
Some(self.home.path()),
)
}
}

fn resume() -> Respawn {
Respawn::Resume(Agent::Claude, vec!["claude".into(), "--resume".into()])
}

#[test]
fn should_resume_in_the_launch_folder_not_the_last_known_one() {
let dirs = Dirs::new();

let placed = dirs.place(resume());

assert_eq!(placed, Some((resume(), dirs.launched_in.path().into())));
}

#[test]
fn should_start_afresh_in_the_last_known_folder_once_the_launch_folder_is_gone() {
let dirs = Dirs::new();
let gone = dirs.launched_in.path().join("gone");

let placed = place(resume(), &gone, dirs.folder.path(), Some(dirs.home.path()));

assert_eq!(
placed,
Some((Respawn::Fresh(Agent::Claude), dirs.folder.path().into()))
);
}

#[test]
fn should_start_a_shell_in_the_last_known_folder() {
let dirs = Dirs::new();

let placed = dirs.place(Respawn::Shell);

assert_eq!(placed, Some((Respawn::Shell, dirs.folder.path().into())));
}

#[test]
fn should_start_afresh_in_the_last_known_folder() {
let dirs = Dirs::new();

let placed = dirs.place(Respawn::Fresh(Agent::Codex));

assert_eq!(
placed,
Some((Respawn::Fresh(Agent::Codex), dirs.folder.path().into()))
);
}

#[test]
fn should_fall_back_to_the_launch_folder_once_the_last_known_one_is_gone() {
let dirs = Dirs::new();
let gone = dirs.folder.path().join("gone");

let placed = place(
Respawn::Shell,
dirs.launched_in.path(),
&gone,
Some(dirs.home.path()),
);

assert_eq!(
placed,
Some((Respawn::Shell, dirs.launched_in.path().into()))
);
}

#[test]
fn should_fall_back_to_home_once_both_are_gone() {
let dirs = Dirs::new();
let gone = dirs.home.path().join("gone");

let placed = place(Respawn::Shell, &gone, &gone, Some(dirs.home.path()));

assert_eq!(placed, Some((Respawn::Shell, dirs.home.path().into())));
}

#[test]
fn should_be_none_once_every_folder_is_gone() {
let gone = Path::new("/no/such/dir");

assert_eq!(place(resume(), gone, gone, None), None);
}

#[test]
fn should_skip_a_relative_folder() {
let dirs = Dirs::new();

let placed = place(
Respawn::Shell,
dirs.launched_in.path(),
Path::new("."),
None,
);

assert_eq!(
placed,
Some((Respawn::Shell, dirs.launched_in.path().into()))
);
}
}
}
15 changes: 2 additions & 13 deletions crates/agentdeckd/src/agents/resume.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ use std::path::{Path, PathBuf};

use agentdeck_core::PaneKind;

use crate::agents::restart::Restarter;
use crate::agents::restart::{Restarter, existing_dir, home};
use crate::agents::resume_argv;
use crate::db::{self, DbError};
use crate::terminal::env::default_shell;
Expand Down Expand Up @@ -82,18 +82,7 @@ pub async fn resume_panes(restarter: &Restarter) -> Result<(), DbError> {
/// Where a pane resumes (spec §6): its last known `folder` while it is a directory, else
/// `home` while that is; `None` when neither is.
fn restore_folder(folder: &Path, home: Option<&Path>) -> Option<PathBuf> {
[Some(folder), home]
.into_iter()
.flatten()
.find(|dir| dir.is_absolute() && dir.is_dir())
.map(Path::to_path_buf)
}

/// The daemon's `$HOME`, which a pane's environment passes on too.
fn home() -> Option<PathBuf> {
std::env::var_os("HOME")
.filter(|home| !home.is_empty())
.map(PathBuf::from)
existing_dir([Some(folder), home])
}

#[cfg(test)]
Expand Down
2 changes: 1 addition & 1 deletion crates/agentdeckd/src/api/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -240,7 +240,7 @@ mod tests {
/// `openapi.json`'s fingerprint when [`agentdeck_core::API_VERSION`] was last set,
/// and that version. Clients tell an older daemon by its API version, so a route or
/// field added without a bump would go unnoticed: they would call it and get a 404.
const FINGERPRINT_AT_API_VERSION: (u64, u32) = (0x3450_2b0c_1cb3_87cf, 28);
const FINGERPRINT_AT_API_VERSION: (u64, u32) = (0x6ab6_d523_f114_9a81, 29);

/// FNV-1a: stable across Rust releases, unlike `DefaultHasher`.
fn fingerprint(text: &str) -> u64 {
Expand Down
Loading