Skip to content
Closed
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
17 changes: 11 additions & 6 deletions crates/cli/src/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5131,7 +5131,7 @@ async fn run_with_socket_initial_selection(
let sessions = client.list().await.unwrap_or_default();
let groups = client.list_projects().await.unwrap_or_default();
let mut services = client.list_services().await.unwrap_or_default();
services.sort_by(|a, b| a.name.cmp(&b.name));
services.sort_by(|a, b| a.position.cmp(&b.position).then_with(|| a.name.cmp(&b.name)));
let mut service_channel_catalog = client
.list_service_channel_catalog()
.await
Expand Down Expand Up @@ -8120,11 +8120,10 @@ impl App {
let mut out: Vec<ListItem> = Vec::new();

// Services are ordinary top-level list rows rather than a separate
// sidebar section. Keep their order stable even if a notification
// arrives with an unsorted service vector. Their routed sessions are
// inserted below each row after the session-tree indexes exist.
// sidebar section, ordered like projects by `position` (stable fallback
// to name for legacy definitions with identical positions).
let mut services = self.services.clone();
services.sort_by(|a, b| a.name.cmp(&b.name));
services.sort_by(|a, b| a.position.cmp(&b.position).then_with(|| a.name.cmp(&b.name)));

let orch_id = self.orchestrator_id.as_deref();
let mut subagents_by_parent: HashMap<&str, Vec<&SessionSummary>> = HashMap::new();
Expand Down Expand Up @@ -8975,7 +8974,12 @@ impl App {
self.set_status(format!("move failed: {e}"));
}
}
Selection::Service(_) => {}
Selection::Service(name) => {
match self.client.move_service(&name, dir).await {
Ok(()) => self.refresh_services().await,
Err(e) => self.set_status(format!("move failed: {e}")),
}
}
Selection::None => self.set_status("nothing selected".into()),
// The "N archived" disclosure row isn't reorderable.
Selection::ArchivedRow(_) => {}
Expand Down Expand Up @@ -41597,6 +41601,7 @@ mod tests {
cwd: "/tmp".to_string(),
routing: "session-key".to_string(),
paused: false,
position: 0,
channels: vec![construct_protocol::ServiceChannelSummary {
id: "http".to_string(),
kind: "http".to_string(),
Expand Down
3 changes: 2 additions & 1 deletion crates/cli/src/app/service_dialog.rs
Original file line number Diff line number Diff line change
Expand Up @@ -484,6 +484,7 @@ fn default_service(app: &App, suggested: String) -> ServiceSummary {
.unwrap_or_else(|| ".".to_string()),
routing: "session-key".to_string(),
paused: false,
position: 0,
channels: Vec::new(),
}
}
Expand All @@ -502,7 +503,7 @@ impl App {
pub async fn refresh_services(&mut self) {
match self.client.list_services().await {
Ok(mut services) => {
services.sort_by(|a, b| a.name.cmp(&b.name));
services.sort_by(|a, b| a.position.cmp(&b.position).then_with(|| a.name.cmp(&b.name)));
self.services = services;
}
Err(error) => self.set_status(format!("services refresh failed: {error}")),
Expand Down
12 changes: 12 additions & 0 deletions crates/client/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1478,6 +1478,18 @@ impl Client {
.await?;
Ok(())
}
pub async fn move_service(&self, name: &str, direction: MoveDirection) -> Result<()> {
let _: serde_json::Value = self
.request(
ipc_method::SERVICE_MOVE,
&construct_protocol::ServiceMoveParams {
service_name: name.to_string(),
direction,
},
)
.await?;
Ok(())
}
pub async fn diff(&self, id: &str) -> Result<DiffResult> {
self.request(
ipc_method::SESSION_DIFF,
Expand Down
10 changes: 10 additions & 0 deletions crates/daemon/src/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1989,6 +1989,16 @@ pub(crate) async fn dispatch(
Err(e) => Response::err(req.id.clone(), ErrorObject::internal(e.to_string())),
}
});
dispatch_entry!(ipc_method::SERVICE_MOVE, {
let p = params!(req, construct_protocol::ServiceMoveParams);
let dir = p.direction;
let name = p.service_name.clone();
let service_dir = construct_protocol::paths::Paths::discover().services_dir();
match crate::service::move_service(&service_dir, &name, dir) {
Ok(()) => Response::ok(req.id.clone(), serde_json::Value::Null),
Err(e) => Response::err(req.id.clone(), ErrorObject::internal(e.to_string())),
}
});
dispatch_entry!(ipc_method::SESSION_DIFF, {
let p = params!(req, SessionIdParams);
match manager.diff(&p.session_id).await {
Expand Down
133 changes: 131 additions & 2 deletions crates/daemon/src/service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,10 @@ use std::path::PathBuf;
use std::sync::Arc;
use uuid::Uuid;

fn is_zero_i64(v: &i64) -> bool {
*v == 0
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ServiceConfig {
#[serde(default)]
Expand All @@ -39,6 +43,8 @@ pub struct ServiceConfig {
pub routing: ServiceRouting,
#[serde(default)]
pub paused: bool,
#[serde(default, skip_serializing_if = "is_zero_i64")]
pub position: i64,
/// Seconds to hold a turn stopped at an approval before denying it on the
/// caller's behalf. `0` waits indefinitely, which keeps the operator as
/// the only one who can decide.
Expand Down Expand Up @@ -298,10 +304,69 @@ pub fn load_definitions(dir: &std::path::Path) -> Result<BTreeMap<String, Servic
}

pub fn list_summaries(dir: &std::path::Path) -> Result<Vec<construct_protocol::ServiceSummary>> {
Ok(load_definitions(dir)?
let mut out: Vec<construct_protocol::ServiceSummary> = load_definitions(dir)?
.into_iter()
.map(|(name, config)| summary(name, &config))
.collect())
.collect();
out.sort_by(|a, b| a.position.cmp(&b.position).then_with(|| a.name.cmp(&b.name)));
Ok(out)
}

pub fn move_service(dir: &std::path::Path, name: &str, direction: construct_protocol::MoveDirection) -> Result<()> {
validate_service_name(name)?;
let mut services = load_definitions(dir)?;
let mut sorted: Vec<(String, i64)> = services
.iter()
.map(|(n, c)| (n.clone(), c.position))
.collect();
sorted.sort_by(|a, b| a.1.cmp(&b.1).then_with(|| a.0.cmp(&b.0)));
let idx = sorted
.iter()
.position(|(n, _)| n == name)
.ok_or_else(|| anyhow!("service `{name}` not found"))?;
let neighbor_idx = match direction {
construct_protocol::MoveDirection::Up => {
if idx == 0 {
return Ok(());
}
idx - 1
}
construct_protocol::MoveDirection::Down => {
if idx + 1 >= sorted.len() {
return Ok(());
}
idx + 1
}
};
let a_name = sorted[idx].0.clone();
let b_name = sorted[neighbor_idx].0.clone();
let a_pos = services.get(&a_name).map(|c| c.position).unwrap_or(0);
let b_pos = services.get(&b_name).map(|c| c.position).unwrap_or(0);
if a_pos == b_pos {
for (i, (n, _)) in sorted.iter().enumerate() {
if let Some(cfg) = services.get_mut(n) {
cfg.position = i as i64;
}
}
let a_pos = services.get(&a_name).map(|c| c.position).unwrap_or(0);
let b_pos = services.get(&b_name).map(|c| c.position).unwrap_or(0);
if let Some(cfg) = services.get_mut(&a_name) {
cfg.position = b_pos;
}
if let Some(cfg) = services.get_mut(&b_name) {
cfg.position = a_pos;
}
} else {
if let Some(cfg) = services.get_mut(&a_name) {
cfg.position = b_pos;
}
if let Some(cfg) = services.get_mut(&b_name) {
cfg.position = a_pos;
}
}
write_definition(dir, &a_name, services.get(&a_name).unwrap())?;
write_definition(dir, &b_name, services.get(&b_name).unwrap())?;
Ok(())
}

pub fn put_definition(
Expand Down Expand Up @@ -333,6 +398,18 @@ pub fn put_definition(
};
let session_mode =
parse_service_session_mode(&params.service.harness, &params.service.session_mode)?;
let position = existing
.as_ref()
.map(|config| config.position)
.unwrap_or_else(|| {
let mut max_pos: Option<i64> = None;
if let Ok(defs) = load_definitions(dir) {
for cfg in defs.values() {
max_pos = Some(max_pos.map_or(cfg.position, |m| m.max(cfg.position)));
}
}
max_pos.map(|p| p + 1).unwrap_or(0)
});
let config = ServiceConfig {
instruction: params.service.instruction,
harness: params.service.harness,
Expand All @@ -341,6 +418,7 @@ pub fn put_definition(
cwd: params.service.cwd,
routing,
paused: params.service.paused,
position,
approval_timeout_secs: existing
.as_ref()
.map(|config| config.approval_timeout_secs)
Expand Down Expand Up @@ -932,6 +1010,7 @@ fn summary(name: String, config: &ServiceConfig) -> construct_protocol::ServiceS
}
.to_string(),
paused: config.paused,
position: config.position,
channels: config
.channels
.iter()
Expand Down Expand Up @@ -1100,6 +1179,7 @@ mod tests {
cwd: ".".into(),
routing: ServiceRouting::SessionKey,
paused,
position: 0,
approval_timeout_secs: 0,
sandbox: ServiceSandboxConfig::default(),
channels: BTreeMap::from([(
Expand Down Expand Up @@ -1396,6 +1476,7 @@ mod tests {
cwd: ".".into(),
routing: ServiceRouting::SessionKey,
paused: false,
position: 0,
approval_timeout_secs: 0,
sandbox: ServiceSandboxConfig::default(),
channels: BTreeMap::new(),
Expand All @@ -1417,6 +1498,7 @@ mod tests {
cwd: ".".into(),
routing: "session-key".into(),
paused: false,
position: 0,
channels: Vec::new(),
},
},
Expand Down Expand Up @@ -1636,6 +1718,7 @@ mod tests {
cwd: ".".into(),
routing: "session-key".into(),
paused: false,
position: 0,
channels: Vec::new(),
};
let first = put_definition(
Expand Down Expand Up @@ -1724,6 +1807,7 @@ mod tests {
cwd: ".".into(),
routing: "session-key".into(),
paused: false,
position: 0,
channels: Vec::new(),
},
},
Expand Down Expand Up @@ -1795,6 +1879,7 @@ mod tests {
cwd: ".".into(),
routing: "session-key".into(),
paused: false,
position: 0,
channels: Vec::new(),
},
},
Expand Down Expand Up @@ -1863,6 +1948,7 @@ mod tests {
cwd: ".".into(),
routing: "session-key".into(),
paused: false,
position: 0,
channels: Vec::new(),
},
},
Expand Down Expand Up @@ -1951,6 +2037,7 @@ mod tests {
cwd: ".".into(),
routing: "session-key".into(),
paused: false,
position: 0,
channels: Vec::new(),
},
},
Expand Down Expand Up @@ -2210,6 +2297,7 @@ mod tests {
cwd: ".".into(),
routing: "session-key".into(),
paused: false,
position: 0,
channels: Vec::new(),
},
},
Expand Down Expand Up @@ -2255,4 +2343,45 @@ mod tests {
assert!(validate_slack_token("bot", Some("xoxp-user"), "xoxb-").is_err());
assert!(validate_slack_token("bot", None, "xoxb-").is_err());
}

#[test]
fn service_move_reorders_like_project() {
let dir = tempfile::tempdir().unwrap();
let services = dir.path().join("services");
std::fs::create_dir_all(&services).unwrap();
for name in ["alpha", "beta"] {
put_definition(
&services,
construct_protocol::ServicePutParams {
service: construct_protocol::ServiceSummary {
name: name.into(),
instruction: String::new(),
harness: "smith".into(),
model: None,
session_mode: "headless".into(),
cwd: ".".into(),
routing: "session-key".into(),
paused: false,
position: 0,
channels: Vec::new(),
},
},
)
.unwrap();
}
let list = list_summaries(&services).unwrap();
assert_eq!(list[0].name, "alpha");
assert_eq!(list[1].name, "beta");
move_service(&services, "beta", construct_protocol::MoveDirection::Up).unwrap();
let list = list_summaries(&services).unwrap();
assert_eq!(list[0].name, "beta");
assert_eq!(list[1].name, "alpha");
move_service(&services, "beta", construct_protocol::MoveDirection::Down).unwrap();
let list = list_summaries(&services).unwrap();
assert_eq!(list[0].name, "alpha");
assert_eq!(list[1].name, "beta");
move_service(&services, "alpha", construct_protocol::MoveDirection::Up).unwrap();
let list = list_summaries(&services).unwrap();
assert_eq!(list[0].name, "alpha");
}
}
2 changes: 2 additions & 0 deletions crates/daemon/src/service/ingress.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1101,6 +1101,7 @@ pub(super) mod tests {
cwd: ".".into(),
routing: ServiceRouting::SessionKey,
paused: false,
position: 0,
approval_timeout_secs: 0,
sandbox: super::super::ServiceSandboxConfig::default(),
channels: Default::default(),
Expand Down Expand Up @@ -1602,6 +1603,7 @@ pub(super) mod tests {
cwd: ".".into(),
routing: ServiceRouting::SessionKey,
paused: false,
position: 0,
approval_timeout_secs: 0,
sandbox: super::super::ServiceSandboxConfig::default(),
channels: Default::default(),
Expand Down
2 changes: 2 additions & 0 deletions crates/daemon/src/service_supervisor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -747,6 +747,7 @@ mod tests {
cwd: ".".into(),
routing: ServiceRouting::SessionKey,
paused,
position: 0,
approval_timeout_secs: 0,
sandbox: ServiceSandboxConfig::default(),
channels: channels
Expand Down Expand Up @@ -804,6 +805,7 @@ mod tests {
cwd: ".".into(),
routing: ServiceRouting::SessionKey,
paused,
position: 0,
approval_timeout_secs: 0,
sandbox: ServiceSandboxConfig::default(),
channels: BTreeMap::from([(
Expand Down
Loading
Loading