From e5e034acb39b37c40ccece8725040bf7689787a3 Mon Sep 17 00:00:00 2001 From: bRRRITSCOLD Date: Mon, 23 Nov 2026 18:46:01 -0700 Subject: [PATCH] fix(panes): Open shell and a fresh Restart agent start in the last known folder (#376) POST /v1/panes/{id}/respawn started every process in the Pane's launch folder (cwd) and refused with invalid_dir once it was gone. Now a claude or codex resume runs in cwd, the folder its session started in (Claude Code finds a session only from there; Codex asks which folder to use when they differ), and starts fresh once cwd is gone. Open shell, a fresh start and an `other` agent run again start in the last known folder, else cwd, else ~. The folder a respawn starts in becomes the Pane's cwd too, so a later resume finds a session started fresh elsewhere. API_VERSION 29. Co-Authored-By: Claude Opus 5.5 --- crates/agentdeck-client/src/generated.rs | 10 +- crates/agentdeck-core/src/daemon.rs | 2 +- crates/agentdeckd/src/agents/restart.rs | 205 +++++++++- crates/agentdeckd/src/agents/resume.rs | 15 +- crates/agentdeckd/src/api/mod.rs | 2 +- crates/agentdeckd/src/api/panes.rs | 58 ++- crates/agentdeckd/src/db/panes.rs | 6 +- crates/agentdeckd/src/model.rs | 7 +- .../agentdeckd/tests/integration/folders.rs | 350 +++++++++++++++++- .../tests/integration/support/agents.rs | 17 +- docs/spec.md | 12 +- openapi.json | 8 +- 12 files changed, 622 insertions(+), 70 deletions(-) diff --git a/crates/agentdeck-client/src/generated.rs b/crates/agentdeck-client/src/generated.rs index 478d648..3f909fb 100644 --- a/crates/agentdeck-client/src/generated.rs +++ b/crates/agentdeck-client/src/generated.rs @@ -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, - ///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")] @@ -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` /// diff --git a/crates/agentdeck-core/src/daemon.rs b/crates/agentdeck-core/src/daemon.rs index 530a5d2..1199983 100644 --- a/crates/agentdeck-core/src/daemon.rs +++ b/crates/agentdeck-core/src/daemon.rs @@ -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. diff --git a/crates/agentdeckd/src/agents/restart.rs b/crates/agentdeckd/src/agents/restart.rs index 0ee7da6..8f1bb5c 100644 --- a/crates/agentdeckd/src/agents/restart.rs +++ b/crates/agentdeckd/src/agents/restart.rs @@ -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}; @@ -28,9 +29,12 @@ 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), + /// An `other` agent's argv, run again: the row's `argv` stays. Again(Agent, Vec), /// Claude Code or Codex with no known session: a fresh launch, as a new pane's. Fresh(Agent), @@ -38,6 +42,48 @@ pub enum Respawn { 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>) -> Option { + 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 { + 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 { @@ -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 { - 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(); @@ -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?; @@ -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())) + ); + } + } +} diff --git a/crates/agentdeckd/src/agents/resume.rs b/crates/agentdeckd/src/agents/resume.rs index 68e3eb5..d1a3764 100644 --- a/crates/agentdeckd/src/agents/resume.rs +++ b/crates/agentdeckd/src/agents/resume.rs @@ -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; @@ -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 { - [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 { - std::env::var_os("HOME") - .filter(|home| !home.is_empty()) - .map(PathBuf::from) + existing_dir([Some(folder), home]) } #[cfg(test)] diff --git a/crates/agentdeckd/src/api/mod.rs b/crates/agentdeckd/src/api/mod.rs index 9bc384a..7e74f3e 100644 --- a/crates/agentdeckd/src/api/mod.rs +++ b/crates/agentdeckd/src/api/mod.rs @@ -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 { diff --git a/crates/agentdeckd/src/api/panes.rs b/crates/agentdeckd/src/api/panes.rs index f0e23cd..bb11979 100644 --- a/crates/agentdeckd/src/api/panes.rs +++ b/crates/agentdeckd/src/api/panes.rs @@ -1,7 +1,7 @@ //! Panes: `/v1/panes` and `/v1/panes/{id}` (spec §4, §6). use std::collections::HashSet; -use std::path::PathBuf; +use std::path::{Path as FsPath, PathBuf}; use agentdeck_core::ws::Entity; use agentdeck_core::{Agent, AgentState, PaneId, PaneKind}; @@ -12,7 +12,7 @@ use dropshot::{ }; use super::{ApiContext, Authorized, IdPath, client_error}; -use crate::agents::restart::{Respawn, RestartError, Restarter}; +use crate::agents::restart::{self, Respawn, RestartError, Restarter}; use crate::agents::{self, codex}; use crate::db; use crate::model::{ @@ -202,14 +202,20 @@ pub(crate) async fn pane_get( Ok(HttpResponseOk(with_live_status(context, pane))) } -/// Starts an exited pane again in place, keeping its id, its place in the tab's layout and -/// 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. +/// Starts an exited pane again in place, keeping its id and its place in the layout. +/// +/// `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. #[endpoint { method = POST, path = "/v1/panes/{id}/respawn" }] pub(crate) async fn pane_respawn( rqctx: RequestContext, @@ -221,23 +227,19 @@ pub(crate) async fn pane_respawn( let id = path.into_inner().id; let run = body.into_inner().run; let row = context.db.call(move |c| db::panes::get(c, id)).await?; - let state = context - .terminals - .get(id) - .map_or(row.state, |live| live.status().state); - if state != AgentState::Exited { + let row = with_live_status(context, row); + if row.state != AgentState::Exited { return Err(client_error( ClientErrorStatusCode::CONFLICT, "running", format!("pane {id}'s process is still running"), )); } - let cwd = check_cwd(&row.cwd)?; let respawn = match (run, row.kind, row.agent) { (PaneRun::Shell, ..) => Respawn::Shell, (PaneRun::Agent, PaneKind::Agent, Some(agent)) => { match agents::resume_argv(Some(agent), row.session_id.as_deref()) { - Some(argv) => Respawn::Again(agent, argv), + Some(argv) => Respawn::Resume(agent, argv), None if agent == Agent::Other => Respawn::Again(agent, row.argv.clone()), None => Respawn::Fresh(agent), } @@ -250,13 +252,33 @@ pub(crate) async fn pane_respawn( )); } }; + let resume = matches!(respawn, Respawn::Resume(..)); + let home = restart::home(); + let (cwd, folder) = (FsPath::new(&row.cwd), FsPath::new(&row.folder)); + let Some((respawn, start_in)) = restart::place(respawn, cwd, folder, home.as_deref()) else { + return Err(client_error( + ClientErrorStatusCode::BAD_REQUEST, + "invalid_dir", + format!( + "none of {}, {} and ~ is an existing directory", + row.folder, row.cwd + ), + )); + }; + if resume && matches!(respawn, Respawn::Fresh(_)) { + tracing::info!( + "pane {id}'s session started in {}, which is gone: starting it afresh in {}", + row.cwd, + start_in.display() + ); + } let restarter = Restarter { db: context.db.clone(), terminals: context.terminals.clone(), events: context.events.clone(), }; let pane = restarter - .respawn(id, respawn, cwd) + .respawn(id, respawn, start_in) .await .map_err(|err| match err { RestartError::Db(err) => err.into(), diff --git a/crates/agentdeckd/src/db/panes.rs b/crates/agentdeckd/src/db/panes.rs index 605e0ff..f498734 100644 --- a/crates/agentdeckd/src/db/panes.rs +++ b/crates/agentdeckd/src/db/panes.rs @@ -242,7 +242,8 @@ pub fn become_shell(conn: &Connection, id: PaneId, argv: &[String]) -> Result)>, ) -> Result<(), DbError> { conn.execute( - "UPDATE panes SET state = 'unknown', exit_code = NULL, hosted_agent = NULL, folder = ?2 + "UPDATE panes SET state = 'unknown', exit_code = NULL, hosted_agent = NULL, cwd = ?2, + folder = ?2 WHERE id = ?1", params![id.to_string(), folder], )?; diff --git a/crates/agentdeckd/src/model.rs b/crates/agentdeckd/src/model.rs index 64d4936..657e420 100644 --- a/crates/agentdeckd/src/model.rs +++ b/crates/agentdeckd/src/model.rs @@ -472,11 +472,14 @@ pub struct Pane { /// The command as first launched. A resumed pane runs its /// agent's resume command, or a fresh shell, instead. pub argv: Vec, - /// 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: String, /// 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. + /// 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: String, /// The agent's session id: chosen at launch for `claude`, found after launch for `codex` /// (null until Codex has written its session file). diff --git a/crates/agentdeckd/tests/integration/folders.rs b/crates/agentdeckd/tests/integration/folders.rs index ba1bd24..1a5ad2a 100644 --- a/crates/agentdeckd/tests/integration/folders.rs +++ b/crates/agentdeckd/tests/integration/folders.rs @@ -1,16 +1,18 @@ //! A Pane's current folder (spec §6): the folder its shell last reported with OSC 7, else its //! process's working directory, else the folder it launched in; kept after it exits, sent as -//! `changed` when it moves, and where it resumes after a restart. Panes run `sh`, which sends -//! no OSC 7 of its own. +//! `changed` when it moves, and where it resumes after a restart and starts again on Open +//! shell or a fresh Restart agent (spec §4). Panes run `sh`, which sends no OSC 7 of its own, +//! and the stub agents in `support::agents`. use std::path::{Path, PathBuf}; use agentdeck_client::Client; -use agentdeck_client::types::{InputWhen, Pane, PaneInput}; +use agentdeck_client::types::{InputWhen, Pane, PaneInput, PaneRespawn, PaneRun}; use agentdeck_core::ws::{Entity, ServerMessage}; -use agentdeck_core::{AgentState, PaneId}; +use agentdeck_core::{Agent, AgentState, PaneId}; use crate::support::TestDaemon; +use crate::support::agents::{args, launch_folders, launches}; use crate::support::terminal::{Place, eventually, in_state, printed, sh}; use crate::support::ws::{Frame, Ws}; @@ -240,3 +242,343 @@ mod resume_after_restart { assert_eq!(resumed.cwd, place.folder(), "the launch folder stays"); } } + +mod post_v1_panes_id_respawn { + use super::*; + + /// Respawns `pane` to run `run`; the pane as it is now. + async fn respawn(client: &Client, pane: PaneId, run: PaneRun) -> Pane { + client + .pane_respawn() + .id(pane) + .body(PaneRespawn { run }) + .send() + .await + .expect("respawn") + .into_inner() + } + + /// Types `text` into the pane and Enter after it, at once. + async fn submit_now(client: &Client, id: PaneId, text: &str) { + client + .pane_input() + .id(id) + .body(PaneInput { + text: text.into(), + when: InputWhen::Now, + submit: true, + }) + .send() + .await + .expect("submit to the pane"); + } + + /// Prints the folder the pane's shell is in, once it starts reading; its output. + async fn shell_folder(client: &Client, id: PaneId) -> String { + type_now(client, id, "pwd; echo back-$((40+2))\r").await; + printed(client, id, "back-42").await + } + + /// Asserts the shell printed `dir` as its folder. + fn printed_folder(text: &str, dir: &Path) { + assert!(text.contains(&format!("{}\r\n", dir.display())), "{text}"); + } + + /// An interactive `sh` pane that moved into `app` in the place's folder, then exited. + async fn exited_moved_shell(daemon: &TestDaemon, place: &Place) -> (Pane, PathBuf) { + let sub = sub_dir(place, "app"); + let pane = place.spawn(&daemon.client, &["sh"]).await; + printed(&daemon.client, pane.id, "$ ").await; + type_now(&daemon.client, pane.id, "cd app\r").await; + in_folder(&daemon.client, pane.id, &sub).await; + type_now(&daemon.client, pane.id, "exit\r").await; + let exited = in_state(&daemon.client, pane.id, AgentState::Exited).await; + assert_eq!(Path::new(&exited.folder), sub, "where it exited"); + (pane, sub) + } + + /// Launches `agent` and has it exit at its prompt, once a codex has its session. + async fn exited_agent(daemon: &TestDaemon, place: &Place, agent: Agent) -> Pane { + let pane = place.launch(&daemon.client, agent).await; + let title = match agent { + Agent::Claude => "\u{1b}]0;\u{2733} Claude Code", + _ => "\u{1b}]0;codex", + }; + printed(&daemon.client, pane.id, title).await; + eventually("the agent's session", || async { + read(&daemon.client, pane.id).await.session_id + }) + .await; + submit_now(&daemon.client, pane.id, "/exit").await; + in_state(&daemon.client, pane.id, AgentState::Exited).await + } + + /// Restarts the daemon with exited `pane`'s last known folder set to `folder`, as for an + /// agent whose folder moved, and its session forgotten when `forget_session`, as for a + /// Codex pane whose session file never turned up. An exited pane stays exited. + async fn with_last_known_folder( + daemon: TestDaemon, + pane: PaneId, + folder: &Path, + forget_session: bool, + ) -> TestDaemon { + let (_, dirs) = daemon.terminate(); + let db = rusqlite::Connection::open(dirs.path().join("data/agentdeck/agentdeck.db")) + .expect("opening the database"); + let folder = folder.to_str().expect("a UTF-8 path"); + db.execute( + "UPDATE panes SET folder = ?2 WHERE id = ?1", + [pane.to_string().as_str(), folder], + ) + .expect("moving the pane"); + if forget_session { + db.execute( + "UPDATE panes SET session_id = NULL WHERE id = ?1", + [pane.to_string()], + ) + .expect("forgetting the session"); + } + TestDaemon::start_in(dirs).await + } + + /// Waits for the pane's stub agent's `n`th launch; its argv and the folder it started in. + async fn launch(daemon: &TestDaemon, pane: PaneId, n: usize) -> (Vec, PathBuf) { + eventually(&format!("launch {n} of the stub agent"), || async { + let argv = launches(daemon, pane).into_iter().nth(n - 1)?; + let folder = launch_folders(daemon, pane).into_iter().nth(n - 1)?; + Some((argv, folder)) + }) + .await + } + + mod open_shell { + use super::*; + + #[tokio::test] + async fn should_start_in_the_last_known_folder_200() { + let daemon = TestDaemon::start().await; + let place = Place::new(&daemon).await; + let (pane, sub) = exited_moved_shell(&daemon, &place).await; + + let shell = respawn(&daemon.client, pane.id, PaneRun::Shell).await; + + printed_folder(&shell_folder(&daemon.client, pane.id).await, &sub); + assert_eq!( + (Path::new(&shell.cwd), Path::new(&shell.folder)), + (&*sub, &*sub) + ); + } + + #[tokio::test] + async fn should_start_in_the_launch_folder_once_the_last_known_one_is_gone_200() { + let daemon = TestDaemon::start().await; + let place = Place::new(&daemon).await; + let (pane, sub) = exited_moved_shell(&daemon, &place).await; + std::fs::remove_dir(&sub).expect("removing the pane's folder"); + + let shell = respawn(&daemon.client, pane.id, PaneRun::Shell).await; + + printed_folder(&shell_folder(&daemon.client, pane.id).await, &place.dir); + assert_eq!(shell.folder, place.folder()); + } + + #[tokio::test] + async fn should_start_in_home_once_the_launch_folder_is_gone_too_200() { + let daemon = TestDaemon::start().await; + let place = Place::new(&daemon).await; + let (pane, _) = exited_moved_shell(&daemon, &place).await; + std::fs::remove_dir_all(&place.dir).expect("removing both folders"); + + let shell = respawn(&daemon.client, pane.id, PaneRun::Shell).await; + + printed_folder(&shell_folder(&daemon.client, pane.id).await, &daemon.home()); + assert_eq!(Path::new(&shell.folder), daemon.home()); + } + + #[tokio::test] + async fn should_start_an_exited_agent_pane_in_its_last_known_folder_200() { + let daemon = TestDaemon::start().await; + let place = Place::new(&daemon).await; + let pane = exited_agent(&daemon, &place, Agent::Claude).await; + let elsewhere = daemon.new_dir("elsewhere"); + let daemon = with_last_known_folder(daemon, pane.id, &elsewhere, false).await; + + respawn(&daemon.client, pane.id, PaneRun::Shell).await; + + printed_folder(&shell_folder(&daemon.client, pane.id).await, &elsewhere); + } + } + + mod restart_agent { + use super::*; + + mod fresh { + use super::*; + + #[tokio::test] + async fn should_start_in_the_last_known_folder_200() { + let daemon = TestDaemon::start().await; + let place = Place::new(&daemon).await; + let pane = exited_agent(&daemon, &place, Agent::Codex).await; + let elsewhere = daemon.new_dir("elsewhere"); + let daemon = with_last_known_folder(daemon, pane.id, &elsewhere, true).await; + + let fresh = respawn(&daemon.client, pane.id, PaneRun::Agent).await; + + let (argv, folder) = launch(&daemon, pane.id, 2).await; + assert!(argv.is_empty(), "afresh, with no prompt: {argv:?}"); + assert_eq!(folder, elsewhere); + assert_eq!( + (Path::new(&fresh.cwd), Path::new(&fresh.folder)), + (&*elsewhere, &*elsewhere), + "the folder its new session needs" + ); + } + + #[tokio::test] + async fn should_start_in_the_launch_folder_once_the_last_known_one_is_gone_200() { + let daemon = TestDaemon::start().await; + let place = Place::new(&daemon).await; + let pane = exited_agent(&daemon, &place, Agent::Codex).await; + let gone = daemon.root().join("gone"); + let daemon = with_last_known_folder(daemon, pane.id, &gone, true).await; + + respawn(&daemon.client, pane.id, PaneRun::Agent).await; + + assert_eq!(launch(&daemon, pane.id, 2).await.1, place.dir); + } + + #[tokio::test] + async fn should_start_in_home_once_the_launch_folder_is_gone_too_200() { + let daemon = TestDaemon::start().await; + let place = Place::new(&daemon).await; + let pane = exited_agent(&daemon, &place, Agent::Codex).await; + let gone = daemon.root().join("gone"); + let daemon = with_last_known_folder(daemon, pane.id, &gone, true).await; + std::fs::remove_dir_all(&place.dir).expect("removing the launch folder"); + + let fresh = respawn(&daemon.client, pane.id, PaneRun::Agent).await; + + assert_eq!(launch(&daemon, pane.id, 2).await.1, daemon.home()); + assert_eq!(Path::new(&fresh.cwd), daemon.home()); + } + + #[tokio::test] + async fn should_run_an_other_agent_again_in_its_last_known_folder_200() { + let daemon = TestDaemon::start().await; + let place = Place::new(&daemon).await; + let sub = sub_dir(&place, "app"); + let script = "echo \"in:$PWD\"; cd app 2>/dev/null; read line"; + let pane = (daemon.client.pane_create()) + .body(agentdeck_client::types::NewPane { + argv: Some(sh(script).iter().map(|arg| (*arg).to_owned()).collect()), + ..place.new_agent(Agent::Other) + }) + .send() + .await + .expect("launch an other agent") + .into_inner(); + in_folder(&daemon.client, pane.id, &sub).await; + type_now(&daemon.client, pane.id, "\r").await; + in_state(&daemon.client, pane.id, AgentState::Exited).await; + + respawn(&daemon.client, pane.id, PaneRun::Agent).await; + + printed( + &daemon.client, + pane.id, + &format!("in:{}\r\n", sub.display()), + ) + .await; + } + } + + mod resume { + use super::*; + + #[tokio::test] + async fn should_resume_claude_in_its_launch_folder_not_its_last_known_one_200() { + let daemon = TestDaemon::start().await; + let place = Place::new(&daemon).await; + let pane = exited_agent(&daemon, &place, Agent::Claude).await; + let session = pane.session_id.clone().expect("a claude session"); + let elsewhere = daemon.new_dir("elsewhere"); + let daemon = with_last_known_folder(daemon, pane.id, &elsewhere, false).await; + + let resumed = respawn(&daemon.client, pane.id, PaneRun::Agent).await; + + let (argv, folder) = launch(&daemon, pane.id, 2).await; + assert_eq!(argv, args(&["--resume", &session])); + assert_eq!( + folder, place.dir, + "the folder Claude Code keys its session by" + ); + assert_eq!( + (resumed.cwd.as_str(), resumed.folder.as_str()), + (place.folder().as_str(), place.folder().as_str()) + ); + } + + #[tokio::test] + async fn should_resume_codex_in_its_launch_folder_not_its_last_known_one_200() { + let daemon = TestDaemon::start().await; + let place = Place::new(&daemon).await; + let pane = exited_agent(&daemon, &place, Agent::Codex).await; + let session = pane.session_id.clone().expect("a codex session"); + let elsewhere = daemon.new_dir("elsewhere"); + let daemon = with_last_known_folder(daemon, pane.id, &elsewhere, false).await; + + respawn(&daemon.client, pane.id, PaneRun::Agent).await; + + let (argv, folder) = launch(&daemon, pane.id, 2).await; + assert_eq!(argv, args(&["resume", &session])); + assert_eq!( + folder, place.dir, + "the folder Codex recorded its session in" + ); + } + + #[tokio::test] + async fn should_start_afresh_in_the_last_known_folder_once_the_launch_folder_is_gone_200() + { + let daemon = TestDaemon::start().await; + let place = Place::new(&daemon).await; + let pane = exited_agent(&daemon, &place, Agent::Claude).await; + let old = pane.session_id.clone().expect("a claude session"); + let elsewhere = daemon.new_dir("elsewhere"); + let daemon = with_last_known_folder(daemon, pane.id, &elsewhere, false).await; + std::fs::remove_dir_all(&place.dir).expect("removing the launch folder"); + + let fresh = respawn(&daemon.client, pane.id, PaneRun::Agent).await; + + let (argv, folder) = launch(&daemon, pane.id, 2).await; + assert_eq!(argv[0], "--session-id", "afresh: {argv:?}"); + assert_ne!(argv[1], old); + assert_eq!(folder, elsewhere); + assert_eq!(fresh.session_id.as_deref(), Some(argv[1].as_str())); + assert_eq!(Path::new(&fresh.cwd), elsewhere); + } + + #[tokio::test] + async fn should_resume_a_session_started_afresh_where_it_started_200() { + let daemon = TestDaemon::start().await; + let place = Place::new(&daemon).await; + let pane = exited_agent(&daemon, &place, Agent::Claude).await; + let elsewhere = daemon.new_dir("elsewhere"); + let daemon = with_last_known_folder(daemon, pane.id, &elsewhere, false).await; + std::fs::remove_dir_all(&place.dir).expect("removing the launch folder"); + let fresh = respawn(&daemon.client, pane.id, PaneRun::Agent).await; + let session = fresh.session_id.clone().expect("its new session"); + printed(&daemon.client, pane.id, "\u{1b}]0;\u{2733} Claude Code").await; + submit_now(&daemon.client, pane.id, "/exit").await; + in_state(&daemon.client, pane.id, AgentState::Exited).await; + + respawn(&daemon.client, pane.id, PaneRun::Agent).await; + + let (argv, folder) = launch(&daemon, pane.id, 3).await; + assert_eq!(argv, args(&["--resume", &session])); + assert_eq!(folder, elsewhere); + } + } + } +} diff --git a/crates/agentdeckd/tests/integration/support/agents.rs b/crates/agentdeckd/tests/integration/support/agents.rs index 87270a1..1b65adf 100644 --- a/crates/agentdeckd/tests/integration/support/agents.rs +++ b/crates/agentdeckd/tests/integration/support/agents.rs @@ -1,6 +1,6 @@ //! Stub `claude` and `codex` CLIs on the daemon's `PATH`, ahead of any real one, so no test -//! ever runs a real agent. Each records what it was launched with (its argv) and what is -//! typed into it under `/agents//`. +//! ever runs a real agent. Each records what it was launched with (its argv), the folder it +//! started in and what is typed into it under `/agents//`. use std::os::unix::fs::PermissionsExt; use std::path::{Path, PathBuf}; @@ -9,7 +9,7 @@ use agentdeck_core::PaneId; use super::TestDaemon; -/// Records its argv; then sets the idle title and reads what is typed as +/// Records its folder and argv; then sets the idle title and reads what is typed as /// [`READ_LIKE_A_TUI`] does. It stays in the foreground (no `exec`), so the pane's foreground /// process is `claude` and the claude rules apply. /// @@ -19,6 +19,7 @@ use super::TestDaemon; const STUB_CLAUDE: &str = r#"#!/bin/sh log="$(dirname "$0")/../agents/$AGENTDECK_PANE" mkdir -p "$log" +pwd >> "$log/cwd" { for arg in "$@"; do printf '%s\0' "$arg"; done; printf '\036'; } >> "$log/argv" session=; previous= for arg in "$@"; do [ "$previous" = --resume ] && session=$arg; previous=$arg; done @@ -30,7 +31,7 @@ stty raw -echo printf '\033[?2004h\033]0;\342\234\263 Claude Code\007> ' "#; -/// Records its argv; unless resuming (a `resume` argument), writes a +/// Records its folder and argv; unless resuming (a `resume` argument), writes a /// session file as Codex does, under `$CODEX_HOME/sessions` (default `$HOME/.codex/sessions`), /// and records the id in `session`; then reads what is typed as [`READ_LIKE_A_TUI`] does. /// @@ -40,6 +41,7 @@ printf '\033[?2004h\033]0;\342\234\263 Claude Code\007> ' const STUB_CODEX: &str = r#"#!/bin/sh log="$(dirname "$0")/../agents/$AGENTDECK_PANE" mkdir -p "$log" +pwd >> "$log/cwd" { for arg in "$@"; do printf '%s\0' "$arg"; done; printf '\036'; } >> "$log/argv" resuming=; session=; previous= for arg in "$@"; do @@ -116,6 +118,13 @@ fn argv_records(text: &str) -> Vec> { .collect() } +/// The folder the pane's stub agent started in at each launch, oldest first. Each stub +/// records it before its argv, so it is there for every launch [`launches`] returns. +pub fn launch_folders(daemon: &TestDaemon, pane: PaneId) -> Vec { + let text = std::fs::read_to_string(log(daemon, pane).join("cwd")).unwrap_or_default(); + text.lines().map(PathBuf::from).collect() +} + /// Every prompt the pane's stub agent submitted, each ended by `\n`. pub fn typed(daemon: &TestDaemon, pane: PaneId) -> String { std::fs::read_to_string(log(daemon, pane).join("stdin")).unwrap_or_default() diff --git a/docs/spec.md b/docs/spec.md index 40ce61d..433f9b2 100644 --- a/docs/spec.md +++ b/docs/spec.md @@ -111,9 +111,9 @@ A **Workspace** is a name, the Repositories it links (possibly none) and its Pan A shell pane **hosts** an agent while one the user started in it by hand (`claude`, `codex`) is its foreground process (§7). `kind` stays `shell`; `hosted_agent` names the agent while it runs and is NULL again once it leaves the foreground, when the daemon starts, and when the pane exits. An agent pane never hosts one. Wherever this spec speaks of a pane's agent, a hosting shell pane's is its `hosted_agent`, and "an agent pane" includes it while it hosts one, unless it says otherwise. -A pane's **current folder** is where it works now (§6): `cwd` stays the folder it launched in, and `folder` holds the last folder the daemon read for it, kept after its process exits. Every pane in a response carries it as `folder`, `cwd` when `folder` is NULL. +A pane's **current folder** is where it works now (§6): `cwd` is the folder its process launched in, by `POST /v1/panes` or by its last respawn (§4), and so the folder its agent's session started in; `folder` holds the last folder the daemon read for it, kept after its process exits. A resume after a restart leaves `cwd` as it was (§6). Every pane in a response carries it as `folder`, `cwd` when `folder` is NULL. -An agent pane runs its agent only until its process exits. An exited agent pane keeps `kind` and `agent`, so it can be restarted (`POST /v1/panes/{id}/respawn`, §4). An agent pane that comes back as a shell (§6), or that the user turns into one, **becomes a shell pane**: `kind` `shell`, `agent` and `session_id` NULL, `argv` the shell. It keeps its `cwd`. +An agent pane runs its agent only until its process exits. An exited agent pane keeps `kind` and `agent`, so it can be restarted (`POST /v1/panes/{id}/respawn`, §4). An agent pane that comes back as a shell (§6), or that the user turns into one, **becomes a shell pane**: `kind` `shell`, `agent` and `session_id` NULL, `argv` the shell. Coming back after a restart, it keeps its `cwd`; turned into one (`run: "shell"`, §4), its `cwd` is the folder the shell starts in. A **Repository** is a GitHub repository a Workspace links or a kept PR belongs to, named for good by GitHub's id: a rename or a transfer changes its `full_name` and `url`, never which Repository it is, so its PRs and every Link follow its name (§8). It holds only what GitHub says of it, and `unreachable_at`, set while GitHub doesn't show it to the sign-in and cleared once GitHub shows it again (§8). An Unreachable Repository keeps its Links and its PRs. @@ -137,6 +137,8 @@ v1.1 adds `channels`, `channel_members` and `messages` in their own migration. Every pane in a response (`POST` and `GET` on `/v1/panes`) carries `hosted_agent`: `claude` or `codex` while a shell pane hosts that agent (§3, §7), else null. It came with `API_VERSION` 6. Every pane also carries `folder`, its current folder (§3, §6), an absolute path; it came with `API_VERSION` 18. +`API_VERSION` 29 moved where `POST /v1/panes/{id}/respawn` starts (§4, #376): Open shell and a fresh Restart agent start in the pane's last known `folder`, else its `cwd`, else `~`, and a resume whose `cwd` is gone starts fresh instead of answering `invalid_dir`; the folder a respawn starts in becomes the pane's `cwd` as well as its `folder`. No route or field changed shape. An older daemon starts each in the pane's `cwd` and refuses with `invalid_dir` once it is gone; the GUI's Restart banner (§2) comes first. + `API_VERSION` 28 added why each Pull request is yours (§3, §8): every `PullRequest` carries `yours`, and `GET /v1/prs` lists the PRs where your review is requested and those assigned to you beside the ones you authored. An older daemon sends no `yours`, which the client reads as empty, and keeps only the PRs you authored; an older client ignores the field, and lists the new PRs as it lists any. `API_VERSION` 27 added the GitHub repository list (§8) for the Link picker's All your repositories (§11): `GET /v1/github/repositories`, `POST /v1/github/repositories/refresh` and the `github_repositories` change event (§5). An older daemon answers both routes with its code-less 404, so the GUI's picker reads "Couldn't load your repositories." until its Restart banner (§2) is followed; an older client skips the event. @@ -164,7 +166,7 @@ Every pane in a response (`POST` and `GET` on `/v1/panes`) carries `hosted_agent | `GET/POST /v1/workspaces/{id}/tabs`, `PATCH/DELETE /v1/tabs/{id}` | tabs and their layout tree, listed in `position` order | | `POST /v1/panes` | spawn: `{tab_id, kind, agent?, argv?, cwd}`; see §6. `cwd` must be an existing absolute dir (`invalid_dir`); a shell without `argv` runs `$SHELL`, else `/bin/sh`; a program that can't start is `invalid_argv`. An agent pane names its `agent` and a shell names none (`unsupported_kind`); `other` needs `argv`, `claude` and `codex` take none (`invalid_argv`). The PTY starts at 80×24. The client places the pane in the tab's `layout` | | `GET /v1/panes/{id}`, `DELETE /v1/panes/{id}` | read (live title, state, exit code and `hosted_agent` while the process runs in this daemon, and `folder`, read again as it answers: a pane that moved is saved there first and gets `changed`, §6); kill (SIGHUP to its process group and the foreground one, then SIGKILL after 3 s) and delete. Deleting a tab or workspace kills its panes too | -| `POST /v1/panes/{id}/respawn` | start an exited pane again in place: same id, row, layout and `cwd`, in its `cwd`, which becomes its `folder`. `{run: "agent"\|"shell"}`. `agent`, for an agent pane only (`unsupported_kind` otherwise), runs its agent again: `claude` and `codex` resume their session when `session_id` is known (as after a restart, §6), else start fresh as a new pane does, on a new session with no prompt (§6); a resume that fails at once starts fresh instead, once (§6, from `API_VERSION` 11); `other` runs its `argv` again. `shell` turns the pane into a shell pane (§3) running `$SHELL`, else `/bin/sh`, with the `shell` rules and hosting on (§7). The pane's state starts over (`unknown`, no exit code). 409 `running` while its process hasn't exited; `invalid_dir` when its `cwd` is gone; a program that can't start is `invalid_argv`, and the pane stays exited. Sends `changed` for the pane and answers with it. It came with `API_VERSION` 7 | +| `POST /v1/panes/{id}/respawn` | start an exited pane again in place: same id, row and layout. `{run: "agent"\|"shell"}`. `agent`, for an agent pane only (`unsupported_kind` otherwise), runs its agent again: `claude` and `codex` resume their session when `session_id` is known (as after a restart, §6), else start fresh as a new pane does, on a new session with no prompt (§6); a resume that fails at once starts fresh instead, once (§6, from `API_VERSION` 11); `other` runs its `argv` again. `shell` turns the pane into a shell pane (§3) running `$SHELL`, else `/bin/sh`, with the `shell` rules and hosting on (§7). **Where it starts** (from `API_VERSION` 29, #376): a `claude` or `codex` resume runs in the pane's `cwd`, the folder its session started in. Claude Code keeps a session under the folder it started in (`~/.claude/projects/`, one dir per project folder) and finds it only from there, and Codex, which finds one by id from any folder, stops before resuming to ask whether to work in the session's folder or the current one when they differ ("Use session directory" / "Use current directory", codex-cli 0.171.0, checked on 2026-11-23), so a resume anywhere else either fails or waits on a question. Once `cwd` is gone, the session can't be resumed there, so the agent starts fresh instead, where a fresh start does, and the daemon logs it at info. Everything else (a fresh start, `other` again, `shell`) carries no session, so it starts where the user left the pane: its last known `folder` (§6), else, once that is gone, its `cwd`, else the daemon's `$HOME` (`~`). An agent's own folder never moves, so for an agent pane the two are the same until a folder is removed; a shell's moves with every `cd`. The folder it starts in becomes the pane's `cwd` and its `folder`, so a later resume runs where its session started. The pane's state starts over (`unknown`, no exit code). 409 `running` while its process hasn't exited; `invalid_dir` when none of those folders is an existing directory; a program that can't start is `invalid_argv`, and the pane stays exited. Sends `changed` for the pane and answers with it. It came with `API_VERSION` 7 | | `POST /v1/panes/{id}/stop` | stop the pane's agent and keep the pane: its row, layout place and `session_id` stay. In an agent pane, its process gets the kill `DELETE` sends (SIGHUP to its process group and the foreground one, then SIGKILL after 3 s), and the pane reads `exited` once it has exited (§7), so **Restart agent** (`respawn` with `run: "agent"`) resumes its session later and a restarting daemon doesn't resume it (§6). In a shell pane hosting an agent (§7), only the hosted agent stops: its process group, the foreground one, gets SIGHUP, then SIGKILL after 3 s if it is still in the foreground; the shell keeps running and `hosted_agent` goes back to null. 204 once the signal is sent; the `state` and `exit` events (or `changed` for the hosted agent) follow. 409 `exited` when the process has already exited, 409 `no_agent` for a shell pane hosting no agent (the shell isn't stopped). It came with `API_VERSION` 12 | | `POST /v1/panes/{id}/input` | `{text, when: "now"|"idle", submit}` (`now` and `false` by default): without `submit`, typed into the PTY as is. With `submit: true`, `text` is a message, typed in two writes: `text` (trailing newlines are the caller's to trim) as one bracketed paste (`ESC[200~…ESC[201~`, any ESC in it removed) when the pane's program has bracketed paste on (DECSET 2004, as the daemon's `Term` tracks it), else as is; then Enter (`\r`) as a write of its own, 200 ms later, followed by another 200 ms before anything else is typed. Claude Code and Codex take text arriving with its Enter in one read as a paste and keep the Enter as a newline, so `text` ending in `\r` without `submit` is never submitted there. `idle` queues until the pane is idle, done or blocked, and is typed at once if it already is. 202 `{queued}`. Queued text is dropped if the process exits, or when an agent starts or stops being hosted in a shell pane (§7) | | `GET /v1/panes/{id}/tail?bytes=` | raw output tail (256 KiB ring) for `agentdeck tail`, as `application/octet-stream`; all of it without `bytes` | @@ -228,7 +230,7 @@ The message types are `agentdeck_core::ws::{ClientMessage, ServerMessage}`. - **Environment:** built from an allowlist: `PATH HOME USER SHELL LANG LC_* TERM COLORTERM XDG_* SSH_AUTH_SOCK GH_* EDITOR CODEX_HOME CLAUDE_CONFIG_DIR`, plus `TERM=xterm-256color` and `COLORTERM=truecolor`. Nothing else from the daemon's own environment is passed on, and that rule is tested. On top: `AGENTDECK_PANE` and `AGENTDECK_WORKSPACE` in every pane, and nothing else of agentdeck's (`AGENTDECK_TASK` went with tasks). - **`PATH`:** every Pane's `PATH` is the daemon's, with the folder holding the running `agentdeckd` (its executable's folder, from `/proc/self/exe`) appended at the end, so `agentdeck`, installed beside `agentdeckd`, resolves in every Pane without shadowing anything earlier on the user's `PATH`. With no `PATH` of its own the daemon gives Panes that folder alone; a folder holding a `:` can't be a `PATH` entry, so the daemon logs it at warn and leaves `PATH` as it was. Agents learn about agentdeck through this CLI, not an MCP server. -- **Where a pane starts:** in the folder the client names (`POST /v1/panes` `cwd`), since a Workspace has none (§3): the GUI's is the focused Pane's current folder, else `~` when the Workspace has no Pane (§11); `agent new`'s is `--cwd` or the CLI's own current folder (§10). A resumed pane starts in its last known folder (below). +- **Where a pane starts:** in the folder the client names (`POST /v1/panes` `cwd`), since a Workspace has none (§3): the GUI's is the focused Pane's current folder, else `~` when the Workspace has no Pane (§11); `agent new`'s is `--cwd` or the CLI's own current folder (§10). A resumed pane starts in its last known folder (below); a respawned one (`POST /v1/panes/{id}/respawn`, §4) resumes its session in its `cwd`, and otherwise starts in its last known folder, else its `cwd`, else `~`. - **Argv by agent:** `claude` and `codex` are looked up on the pane's `PATH`, so tests put stubs first. - **A program that can't start** is refused with 400 `invalid_argv` and the pane row is dropped. When `argv[0]` is a bare name in none of the pane's `PATH` directories, the message is only what to do: "`codex` isn't on agentdeckd's PATH. Install it, or start agentdeckd from a shell where it's found."; the lookup's whole error, which lists every `PATH` directory, goes to `agentdeckd.log` at warn. Any other spawn error keeps its text. The GUI's toast and `agentdeck agent new` show an `invalid_argv` refusal as that message alone. - `claude`: `claude --session-id `, with a UUIDv4 agentdeck chooses. @@ -436,7 +438,7 @@ Built on `brrritscold-core-gpui` (`init`, `Root`, theme preference, toasts). Scr - **Hosted agent** (Penpot "Screens · Main" → "Pane · hosted agent"): while a shell pane hosts an agent, its header follows that agent: its title (Claude Code's `✳ Claude Code`), its state from the agent's rules, and "in shell" (xs, `muted-foreground`) after the title, `space.2` from it, saying the shell comes back when it exits. Its agent is named in notifications, as an agent pane's. Once the agent leaves, the header is a shell's again. The title the header showed by then is the agent's, so it no longer shows, live or as read: the header reads the shell's own title once the shell sets one, else the program's name, until the pane hosts an agent again. - **Hosted agent's tab** (Penpot "Screens · Main" → "Pane · hosted agent · shell tab"): a tab whose title is still the default "shell" reads as the agent a pane in it hosts, the first hosting pane in layout order, lowercase as `agent new` titles a tab (`claude`, `codex`). This is display only: the saved title stays "shell", and the tab reads "shell" again once no pane in it hosts an agent. A tab the user renamed, or one titled after a launched agent, keeps its title. A `+` after the tabs opens a shell tab where a new pane starts (below); a workspace with no tabs when shown gets one, there too: in `~`. - **Where a new pane starts:** in the focused pane's current folder (§6), as the GUI last read it: the pane with the keyboard, else the pane in the workspace that last had it, whatever tab it is in; in `~` (the home folder) when the workspace has no such pane, as a new GNOME Terminal tab does. A new shell tab and New agent's preset Folder start there; Split right and Split down start in the current folder of the pane they split. The daemon is still told an explicit folder (`POST /v1/panes` `cwd`). - - **Agent exited** (Penpot "Screens · Main" → "Pane · agent exited"): the header names an agent only while it runs. Once an agent pane's process has exited, its title is "Agent exited" whatever the agent last set, its state the exited badge ("exited 0", "exited 1"), and the header offers two outline xs buttons before the `…` menu, `space.2` apart (PaneHeader's `Actions` part): **Restart agent**, which runs the same agent again in the pane (`POST /v1/panes/{id}/respawn` with `run: "agent"`: its session resumed when known, else a fresh start; a resume that exits at once, as one of a session the agent can no longer find does, is followed by a fresh start, so the header shows the running agent again rather than staying exited, §6), and **Open shell**, which turns the pane into a shell in its `cwd` (`run: "shell"`). Either keeps the pane's place in the layout, attaches the new process and focuses it; a failure toasts "Couldn't restart " or "Couldn't open a shell" with the daemon's reason. An exited shell pane offers neither. + - **Agent exited** (Penpot "Screens · Main" → "Pane · agent exited"): the header names an agent only while it runs. Once an agent pane's process has exited, its title is "Agent exited" whatever the agent last set, its state the exited badge ("exited 0", "exited 1"), and the header offers two outline xs buttons before the `…` menu, `space.2` apart (PaneHeader's `Actions` part): **Restart agent**, which runs the same agent again in the pane (`POST /v1/panes/{id}/respawn` with `run: "agent"`: its session resumed when known, else a fresh start; a resume that exits at once, as one of a session the agent can no longer find does, is followed by a fresh start, so the header shows the running agent again rather than staying exited, §6), and **Open shell**, which turns the pane into a shell in its last known folder, else the folder it launched in, else `~` (`run: "shell"`, §4). Either keeps the pane's place in the layout, attaches the new process and focuses it; a failure toasts "Couldn't restart " or "Couldn't open a shell" with the daemon's reason. An exited shell pane offers neither. - **Edit workspace**, first in the `…` menu (Penpot "Screens · Main" → "Workspace menu"; the menu opens 4px below its button, their right edges lined up), opens the edit workspace dialog (Dialogs, below). - **Mute notifications**, next in the `…` menu, mutes the workspace's notifications with `PATCH /v1/workspaces/{id}` `{muted: true}`: its Pane alerts, and the PR alerts of each Repository that only Muted workspaces link (Notifications, below); once muted it reads **Unmute notifications**. A failure toasts "Couldn't mute " (or unmute) with why. A muted workspace's sidebar row shows a 12px `BellOff` in `muted-foreground` before its counts; an archived row shows none. - **Archive workspace**, in the `…` menu, archives at once, with no dialog, since it can be undone. The daemon refuses while a pane runs, and a toast "Can't archive " gives its reason ("Close its 2 running panes first"). Otherwise the toast "Archived " says "Its panes and linked Repositories are kept." and offers **Undo**, which unarchives. The workspace stays selected, now archived. diff --git a/openapi.json b/openapi.json index 023ced4..7fe751d 100644 --- a/openapi.json +++ b/openapi.json @@ -595,7 +595,7 @@ "type": "string" }, "cwd": { - "description": "The working directory it was launched in.", + "description": "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).", "type": "string" }, "exit_code": { @@ -605,7 +605,7 @@ "type": "integer" }, "folder": { - "description": "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.", + "description": "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).", "type": "string" }, "hosted_agent": { @@ -1933,7 +1933,7 @@ }, "/v1/panes/{id}/respawn": { "post": { - "description": "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.", + "description": "`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).\n\nA 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.", "operationId": "pane_respawn", "parameters": [ { @@ -1974,7 +1974,7 @@ "$ref": "#/components/responses/Error" } }, - "summary": "Starts an exited pane again in place, keeping its id, its place in the tab's layout and" + "summary": "Starts an exited pane again in place, keeping its id and its place in the layout." } }, "/v1/panes/{id}/stop": {