Skip to content

Switchyard lets LLM applications route traffic across models and providers while preserving native OpenAI and Anthropic API compatibility - enabling flexible model selection, benchmarking, and cost/performance optimization.

Rust

feat(desktop): create, rename, duplicate, and delete routes in the terminal app (#1100)

Elyas Mehtabuddin00aa79898faa
diff --git a/crates/switchyard-desktop/src/controller.rs b/crates/switchyard-desktop/src/controller.rs
index a37aaee1e..f948ea70a 100644
--- a/crates/switchyard-desktop/src/controller.rs
+++ b/crates/switchyard-desktop/src/controller.rs
@@ -29,6 +29,12 @@ pub enum Action {
choices: Vec<Choice>,
revision: Option<String>,
},
+ Remove {
+ generation: u64,
+ route: String,
+ id: String,
+ revision: Option<String>,
+ },
PreviewRoute {
generation: u64,
route: String,
@@ -36,6 +42,25 @@ pub enum Action {
choices: Vec<Choice>,
revision: Option<String>,
},
+ PreviewRouteChange {
+ generation: u64,
+ operation: String,
+ route: String,
+ name: String,
+ id: String,
+ algorithm: Option<String>,
+ choices: Vec<Choice>,
+ },
+ RouteChange {
+ generation: u64,
+ operation: String,
+ route: String,
+ name: String,
+ id: String,
+ algorithm: Option<String>,
+ choices: Vec<Choice>,
+ preview_token: Option<String>,
+ },
Models {
client: String,
refresh: bool,
@@ -306,6 +331,7 @@ pub struct Controller {
// The generation ties a draft to the server config file selected by the settings.
generation: u64,
route_reviews: std::collections::HashMap<String, Review>,
+ route_change: Option<Review>,
update_review: Option<(String, Value)>,
}
impl Controller {
@@ -317,6 +343,7 @@ impl Controller {
reader: rollup::Reader::default(),
generation: 0,
route_reviews: Default::default(),
+ route_change: None,
update_review: None,
}
}
@@ -325,6 +352,7 @@ impl Controller {
if config.config_file != self.config.config_file {
self.generation += 1;
self.route_reviews.clear();
+ self.route_change = None;
}
self.config = config;
@@ -670,6 +698,82 @@ impl Controller {
)
.map(Reply::saved_edit)
}
+ Action::Remove {
+ generation,
+ route,
+ id,
+ revision,
+ } => {
+ self.check_generation(generation)?;
+ current_route(&self.routes()?, &route, Some(&id))?;
+ self.route_reviews
+ .get(&route)
+ .ok_or("Open the route editor before removing it.")?
+ .check(revision.as_deref(), &json!({"route":route}))?;
+ server::remove(
+ &self.config,
+ &route,
+ &id,
+ self.route_reviews[&route].original()?,
+ )
+ .map(Reply::saved_edit)
+ }
+ Action::PreviewRouteChange {
+ generation,
+ operation,
+ route,
+ name,
+ id,
+ algorithm,
+ choices,
+ } => {
+ self.check_generation(generation)?;
+ let inputs = json!({"operation":operation,"route":route,"name":name,"id":id,"algorithm":algorithm,"choices":choices});
+ let review = Review::capture(inputs, vec![self.config.config_file.clone()])?;
+ let edited = self.routes()?.change_route(
+ &operation,
+ &route,
+ &name,
+ &id,
+ algorithm.as_deref().map(algorithm_by_id).transpose()?,
+ &choices,
+ )?;
+ review.check(Some(&review.token), &review.inputs)?;
+ let data = json!({"notes":edited.notes,"file":self.config.config_file,"preview_token":review.token});
+ self.route_change = Some(review);
+ Ok(Reply {
+ message: String::new(),
+ data,
+ })
+ }
+ Action::RouteChange {
+ generation,
+ operation,
+ route,
+ name,
+ id,
+ algorithm,
+ choices,
+ preview_token,
+ } => {
+ self.check_generation(generation)?;
+ let inputs = json!({"operation":operation,"route":route,"name":name,"id":id,"algorithm":algorithm,"choices":choices});
+ let review = self
+ .route_change
+ .as_ref()
+ .ok_or("Review the route change first.")?;
+ review.check(preview_token.as_deref(), &inputs)?;
+ let edited = self.routes()?.change_route(
+ &operation,
+ &route,
+ &name,
+ &id,
+ algorithm.as_deref().map(algorithm_by_id).transpose()?,
+ &choices,
+ )?;
+ server::save_route_change(&self.config, review.original()?, edited)
+ .map(Reply::saved_edit)
+ }
Action::Models {
client,
refresh,
diff --git a/crates/switchyard-desktop/src/server.rs b/crates/switchyard-desktop/src/server.rs
index 7a9238cd4..c9b0d4968 100644
--- a/crates/switchyard-desktop/src/server.rs
+++ b/crates/switchyard-desktop/src/server.rs
@@ -41,8 +41,40 @@ pub fn apply(
choices: &[Choice],
expected: &str,
) -> Result<SaveResult, String> {
+ let text = read_reviewed(settings, expected)?;
+ let config = ServerConfig::parse(&text)?;
+ let edited = config.edit(route, algorithm, choices)?;
+ save_edit(settings, &text, edited, "Updated the route.")
+}
+
+pub fn remove(
+ settings: &Config,
+ route: &str,
+ id: &str,
+ expected: &str,
+) -> Result<SaveResult, String> {
+ let text = read_reviewed(settings, expected)?;
+ let config = ServerConfig::parse(&text)?;
+ if !config.routes().iter().any(|r| r.key == route && r.id == id) {
+ return Err("The route changed or was removed. Refresh and choose it again.".into());
+ }
+ let edited = config.remove(route)?;
+ save_edit(settings, &text, edited, "Removed the route.")
+}
+
+pub fn save_route_change(
+ settings: &Config,
+ expected: &str,
+ edited: crate::server_config::Edited,
+) -> Result<SaveResult, String> {
+ let text = read_reviewed(settings, expected)?;
+ save_edit(settings, &text, edited, "Changed the routes.")
+}
+
+/// This function reads the server config again, so an edit made while the review window was
+/// open is noticed, and checks that the file still matches the reviewed text.
+fn read_reviewed(settings: &Config, expected: &str) -> Result<String, String> {
let path = &settings.config_file;
- // Read the file again so an edit made while the window was open is kept.
let text = std::fs::read_to_string(path).map_err(|error| {
format!(
"Could not read {}: {error}. Check config_file in the app settings.",
@@ -50,9 +82,7 @@ pub fn apply(
)
})?;
check_original(&text, expected)?;
- let config = ServerConfig::parse(&text)?;
- let edited = config.edit(route, algorithm, choices)?;
- save_edit(settings, &text, edited, "Updated the route.")
+ Ok(text)
}
fn check_original(text: &str, expected: &str) -> Result<(), String> {
diff --git a/crates/switchyard-desktop/src/server_config.rs b/crates/switchyard-desktop/src/server_config.rs
index dd04d27a1..94285b8ec 100644
--- a/crates/switchyard-desktop/src/server_config.rs
+++ b/crates/switchyard-desktop/src/server_config.rs
@@ -418,6 +418,148 @@ impl ServerConfig {
.collect()
}
+ pub fn remove(&self, route: &str) -> Result<Edited, String> {
+ let mut doc = self.doc.clone();
+ let routes = doc
+ .get_mut("routes")
+ .and_then(Item::as_table_like_mut)
+ .ok_or("No routes are configured.")?;
+ let removed = routes
+ .remove(route)
+ .ok_or("The route was already removed. Refresh and choose it again.")?;
+ let emptied = routes.is_empty();
+ retain_block_markers(&mut doc, &removed);
+ // Files that use `[routes.name]` headers leave `[routes]` implicit, and an implicit table
+ // with no entries is not written. The server requires `routes`, so the last delete writes
+ // an explicit empty `[routes]` table.
+ if emptied && let Some(routes) = doc["routes"].as_table_mut() {
+ routes.set_implicit(false);
+ }
+ Ok(Edited {
+ text: doc.to_string(),
+ notes: vec![
+ "Removed the route. Its targets and endpoint settings are preserved.".into(),
+ ],
+ })
+ }
+
+ pub fn change_route(
+ &self,
+ operation: &str,
+ route: &str,
+ name: &str,
+ id: &str,
+ algorithm: Option<&Algorithm>,
+ choices: &[Choice],
+ ) -> Result<Edited, String> {
+ if id.trim().is_empty() || id.contains(['\n', '\r']) {
+ return Err("Enter a nonempty public route ID without line breaks.".into());
+ }
+ // A rename to the current ID would ask the user to save and restart for no change.
+ if operation == "rename"
+ && self
+ .routes()
+ .iter()
+ .any(|existing| existing.key == route && existing.id == id)
+ {
+ return Err("The route already uses that public ID.".into());
+ }
+ if self
+ .routes()
+ .iter()
+ .any(|existing| existing.id == id && !(operation == "rename" && existing.key == route))
+ {
+ return Err("That public route ID is already configured.".into());
+ }
+ let mut doc = self.doc.clone();
+ if operation == "rename" {
+ let table = doc
+ .get_mut("routes")
+ .and_then(Item::as_table_like_mut)
+ .and_then(|routes| routes.get_mut(route))
+ .and_then(Item::as_table_like_mut)
+ .ok_or("Choose an existing route.")?;
+ table.insert("id", toml_edit::value(id));
+ let mut notes = vec![
+ "Harnesses that select the old public route ID must choose the new ID.".into(),
+ ];
+ notes.extend(self.generated_note(route, &[]));
+ return Ok(Edited {
+ text: doc.to_string(),
+ notes,
+ });
+ }
+ if name.is_empty()
+ || name.len() > 64
+ || !name
+ .bytes()
+ .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_'))
+ {
+ return Err("Route names need 1–64 letters, numbers, hyphens, or underscores.".into());
+ }
+ if self.route(name).is_some() {
+ return Err("That route name is already configured.".into());
+ }
+ let mut table = match operation {
+ "duplicate" => self
+ .table("routes")
+ .and_then(|routes| routes.get(route))
+ .cloned()
+ .ok_or("Choose an existing route.")?,
+ "create" => {
+ let mut table = toml_edit::Table::new();
+ table.insert("type", toml_edit::value("passthrough"));
+ table.insert("target", toml_edit::value(""));
+ Item::Table(table)
+ }
+ _ => return Err("Choose Create, Duplicate, or Rename.".into()),
+ };
+ let mut copied = vec![&mut table];
+ while let Some(item) = copied.pop() {
+ if let Some(table) = item.as_table_mut() {
+ table.set_position(Some(-1));
+ if let Some(prefix) = table.decor().prefix().and_then(|prefix| prefix.as_str()) {
+ let prefix = prefix
+ .split_inclusive('\n')
+ .filter(|line| {
+ !line.trim().starts_with("# >>>") && !line.trim().starts_with("# <<<")
+ })
+ .collect::<String>();
+ table.decor_mut().set_prefix(prefix);
+ }
+ copied.extend(table.iter_mut().map(|(_, item)| item));
+ }
+ }
+ table
+ .as_table_like_mut()
+ .ok_or("Route must be a table.")?
+ .insert("id", toml_edit::value(id));
+ if doc.get("routes").is_none() {
+ doc["routes"] = Item::Table(toml_edit::Table::new());
+ }
+ doc["routes"]
+ .as_table_like_mut()
+ .ok_or("Routes must be a table.")?
+ .insert(name, table);
+ let candidate = ServerConfig::parse(&doc.to_string())?;
+ if operation == "create" {
+ candidate.edit(
+ name,
+ algorithm.ok_or("Choose a routing algorithm.")?,
+ choices,
+ )
+ } else {
+ Ok(Edited {
+ text: doc.to_string(),
+ notes: vec![
+ "The duplicate initially shares targets and endpoint settings \
+ with the source route."
+ .into(),
+ ],
+ })
+ }
+ }
+
pub fn clients(&self) -> Vec<Client> {
entries(self.table("llm_clients"))
.map(|(name, client)| Client {
@@ -1105,6 +1247,67 @@ fn login_hosts<'c>(clients: &'c [Client], choices: &[Choice]) -> Vec<&'c str> {
hosts
}
+// Generated-block markers can occur on nested route tables and still apply to retained targets.
+// Only the marker lines move to the next table; other comments describe the removed route and
+// leave with it.
+fn retain_block_markers(doc: &mut DocumentMut, removed: &Item) {
+ let mut markers = Vec::new();
+ let mut tables: Vec<_> = removed.as_table().into_iter().collect();
+ while let Some(table) = tables.pop() {
+ if let Some(position) = table.position()
+ && let Some(prefix) = table.decor().prefix().and_then(|value| value.as_str())
+ {
+ let kept: String = prefix
+ .split_inclusive('\n')
+ .filter(|line| line.trim().starts_with("# >>>") || line.trim().starts_with("# <<<"))
+ .collect();
+ if !kept.is_empty() {
+ markers.push((position, kept));
+ }
+ }
+ tables.extend(table.iter().filter_map(|(_, item)| item.as_table()));
+ }
+ markers.sort_by_key(|(position, _)| *position);
+ let mut positions = Vec::new();
+ let mut tables = vec![doc.as_table()];
+ while let Some(table) = tables.pop() {
+ positions.extend(table.position());
+ tables.extend(table.iter().filter_map(|(_, item)| item.as_table()));
+ }
+ let mut prefixes: HashMap<isize, String> = HashMap::new();
+ let mut trailing = String::new();
+ for (removed_position, prefix) in markers {
+ if let Some(next) = positions
+ .iter()
+ .copied()
+ .filter(|position| *position > removed_position)
+ .min()
+ {
+ prefixes.entry(next).or_default().push_str(&prefix);
+ } else {
+ trailing.push_str(&prefix);
+ }
+ }
+ let mut tables = vec![doc.as_table_mut()];
+ while let Some(table) = tables.pop() {
+ if let Some(position) = table.position()
+ && let Some(mut prefix) = prefixes.remove(&position)
+ {
+ prefix.push_str(
+ table
+ .decor()
+ .prefix()
+ .and_then(|value| value.as_str())
+ .unwrap_or_default(),
+ );
+ table.decor_mut().set_prefix(prefix);
+ }
+ tables.extend(table.iter_mut().filter_map(|(_, item)| item.as_table_mut()));
+ }
+ trailing.push_str(doc.trailing().as_str().unwrap_or_default());
+ doc.set_trailing(trailing);
+}
+
/// This function finds the route and target tables that sit inside blocks another tool
/// writes. A block starts at a line that begins with `# >>>` and ends at the
/// next line that begins with `# <<<`, the markers that the installer scripts
@@ -1143,3 +1346,32 @@ fn table_key(path: &str) -> Option<&str> {
}
path.split(['.', ']']).next().filter(|key| !key.is_empty())
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ // `[routes.name]` headers leave `[routes]` implicit. Deleting the last route must still
+ // write a `routes` table, or the server rejects the file with `missing field routes`.
+ #[test]
+ fn deleting_the_last_route_keeps_an_empty_routes_table() {
+ let config = ServerConfig::parse(
+ "schema_version = 1\n\
+ [llm_clients.c]\n\
+ format = 'openai_chat'\n\
+ base_url = 'https://example.test/v1'\n\
+ [targets.m]\n\
+ id = 'model'\n\
+ llm_client = 'c'\n\
+ [routes.only]\n\
+ id = 'only'\n\
+ type = 'passthrough'\n\
+ target = 'm'\n",
+ )
+ .expect("config");
+ let edited = config.remove("only").expect("remove");
+ let routes = switchyard_runner::route_targets(&edited.text)
+ .unwrap_or_else(|error| panic!("{error}\n{}", edited.text));
+ assert!(routes.is_empty(), "{}", edited.text);
+ }
+}
diff --git a/crates/switchyard-desktop/src/tui.rs b/crates/switchyard-desktop/src/tui.rs
index 1da19a0ec..7b7ddb32b 100644
--- a/crates/switchyard-desktop/src/tui.rs
+++ b/crates/switchyard-desktop/src/tui.rs
@@ -158,6 +158,38 @@ const ACTIONS: &[ActionRow] = &[
ActionKind::Apply,
],
),
+ (
+ Tab::Routes,
+ 'a',
+ "create",
+ "Creates a route from a public model ID, an algorithm, and its models. Type SAVE after \
+ the review.",
+ &[ActionKind::PreviewRouteChange, ActionKind::RouteChange],
+ ),
+ (
+ Tab::Routes,
+ 'n',
+ "rename",
+ "Changes the selected route's public model ID. Harnesses that send the old ID must \
+ change too. Type SAVE after the review.",
+ &[ActionKind::PreviewRouteChange, ActionKind::RouteChange],
+ ),
+ (
+ Tab::Routes,
+ 'c',
+ "duplicate",
+ "Copies the selected route under a new public model ID. The copy shares its targets. \
+ Type SAVE after the review.",
+ &[ActionKind::PreviewRouteChange, ActionKind::RouteChange],
+ ),
+ (
+ Tab::Routes,
+ 'd',
+ "delete",
+ "Deletes the selected route after you type its public model ID. Its targets and \
+ endpoints stay, and the server config is backed up.",
+ &[ActionKind::Remove],
+ ),
(
Tab::Routes,
'm',
@@ -431,8 +463,30 @@ enum FormKind {
algorithm: String,
revision: Option<String>,
},
+ /// The fields hold a new route's public model ID, config name, and algorithm.
+ NewRoute {
+ generation: u64,
+ },
+ NewRouteModels {
+ generation: u64,
+ name: String,
+ id: String,
+ algorithm: String,
+ },
+ /// The operation is `rename` or `duplicate`, and `route` is the selected route's config name.
+ RouteIdentity {
+ generation: u64,
+ operation: &'static str,
+ route: String,
+ },
/// The action is the one that the user reviewed. Typing SAVE submits it unchanged.
Save(Box<Action>),
+ Remove {
+ generation: u64,
+ route: String,
+ id: String,
+ revision: String,
+ },
Models,
/// This map holds each endpoint's base URL when the form opened. The controller refuses
/// the key if the chosen endpoint's URL no longer matches.
@@ -443,9 +497,11 @@ enum Choices {
Algorithms,
Endpoints,
}
-/// Submit is what a form sends: a controller action.
+/// Submit is what a form sends: a controller action, or the next form of a flow that needs
+/// more input before the controller can review it.
enum Submit {
Run(Action),
+ Next(Form),
}
/// Form holds the text fields for an action that needs input.
struct Form {
@@ -548,7 +604,10 @@ impl Form {
fn options(&self) -> Option<Choices> {
match self.kind {
FormKind::Algorithm { .. } => Some(Choices::Algorithms),
- FormKind::RouteModels { .. } if self.index.is_multiple_of(2) => {
+ FormKind::NewRoute { .. } if self.index == 2 => Some(Choices::Algorithms),
+ FormKind::RouteModels { .. } | FormKind::NewRouteModels { .. }
+ if self.index.is_multiple_of(2) =>
+ {
Some(Choices::Endpoints)
}
FormKind::Models | FormKind::ModelKey(_) if self.index == 0 => Some(Choices::Endpoints),
@@ -570,8 +629,9 @@ impl Form {
*field = names.nth(next).unwrap_or_default().to_string();
self.cursor = field.chars().count();
}
- /// This function builds what the form submits.
- fn action(&self) -> Result<Submit, String> {
+ /// This function builds what the form submits. The snapshot supplies the roles and
+ /// endpoints that a new route's models form starts with.
+ fn action(&self, data: &Snapshot) -> Result<Submit, String> {
let confirm = |word: &str, error: &str| {
if self.value(0) == word {
Ok(())
@@ -624,10 +684,89 @@ impl Form {
choices: self.choices(),
revision: revision.clone(),
},
+ FormKind::NewRoute { generation } => {
+ let id = self.value(0);
+ let algorithm = self.value(2);
+ let roles = &data
+ .algorithms
+ .iter()
+ .find(|known| known.kind == algorithm)
+ .ok_or("Unknown routing algorithm. Press ↑ or ↓ to choose one.")?
+ .roles;
+ let choice = Choice {
+ client: data
+ .clients
+ .first()
+ .map(|client| client.name.clone())
+ .unwrap_or_default(),
+ model: String::new(),
+ };
+ let fields = role_fields(roles.iter().map(|role| (&*role.label, choice.clone())));
+ let title = format!("Models for the new route {id}");
+ let kind = FormKind::NewRouteModels {
+ generation: *generation,
+ name: config_name(&id, &self.value(1)),
+ id,
+ algorithm,
+ };
+ return Ok(Submit::Next(Form::new(kind, title, fields)));
+ }
+ FormKind::NewRouteModels {
+ generation,
+ name,
+ id,
+ algorithm,
+ } => Action::PreviewRouteChange {
+ generation: *generation,
+ operation: "create".into(),
+ route: String::new(),
+ name: name.clone(),
+ id: id.clone(),
+ algorithm: Some(algorithm.clone()),
+ choices: self.choices(),
+ },
+ FormKind::RouteIdentity {
+ generation,
+ operation,
+ route,
+ } => {
+ let id = self.value(0);
+ // A rename keeps the config name, so its form has no config name field.
+ let name = match self.fields.get(1) {
+ Some((_, typed)) => config_name(&id, typed.trim()),
+ None => String::new(),
+ };
+ Action::PreviewRouteChange {
+ generation: *generation,
+ operation: operation.to_string(),
+ route: route.clone(),
+ name,
+ id,
+ algorithm: None,
+ choices: Vec::new(),
+ }
+ }
FormKind::Save(action) => {
confirm("SAVE", "Type SAVE to apply the reviewed changes.")?;
(**action).clone()
}
+ FormKind::Remove {
+ generation,
+ route,
+ id,
+ revision,
+ } => {
+ confirm(
+ id,
+ "The public model ID did not match. Nothing was deleted.",
+ )?;
+ Action::Remove {
+ generation: *generation,
+ route: route.clone(),
+ id: id.clone(),
+ revision: Some(revision.clone()),
+ }
+ }
FormKind::Models => Action::Models {
client: self.value(0),
refresh: true,
@@ -651,7 +790,11 @@ impl Form {
FormKind::Update(_) => "Starting the update",
FormKind::Algorithm { .. } => "Opening the route editor",
FormKind::RouteModels { .. } => "Reviewing the route",
+ FormKind::NewRoute { .. }
+ | FormKind::NewRouteModels { .. }
+ | FormKind::RouteIdentity { .. } => "Reviewing the route change",
FormKind::Save(_) => "Saving the route",
+ FormKind::Remove { .. } => "Deleting the route",
FormKind::Models => "Loading models",
FormKind::ModelKey(_) => "Saving the key and loading models",
}
@@ -675,6 +818,22 @@ fn role_fields<'a>(roles: impl Iterator<Item = (&'a str, Choice)>) -> Vec<(Strin
.collect()
}
+/// This function returns the typed config name, or one made from the public model ID the same
+/// way the desktop app fills a blank config name.
+fn config_name(id: &str, typed: &str) -> String {
+ if !typed.is_empty() {
+ return typed.to_string();
+ }
+ id.split(|c: char| !(c.is_ascii_alphanumeric() || c == '-' || c == '_'))
+ .filter(|part| !part.is_empty())
+ .collect::<Vec<_>>()
+ .join("-")
+ .trim_matches('-')
+ .chars()
+ .take(64)
+ .collect()
+}
+
/// This function opens the models form after the controller returns the roles of `algorithm`.
fn route_models_form(
generation: u64,
@@ -708,7 +867,7 @@ fn route_models_form(
/// This function returns the action that a preview's review window submits after the user
/// types SAVE: the previewed inputs, plus the token for a route change.
-fn reviewed(previewed: Action) -> Option<Action> {
+fn reviewed(previewed: Action, preview: &Value) -> Option<Action> {
Some(match previewed {
Action::PreviewRoute {
generation,
@@ -723,6 +882,24 @@ fn reviewed(previewed: Action) -> Option<Action> {
choices,
revision,
},
+ Action::PreviewRouteChange {
+ generation,
+ operation,
+ route,
+ name,
+ id,
+ algorithm,
+ choices,
+ } => Action::RouteChange {
+ generation,
+ operation,
+ route,
+ name,
+ id,
+ algorithm,
+ choices,
+ preview_token: preview["preview_token"].as_str().map(str::to_owned),
+ },
_ => return None,
})
}
@@ -1150,9 +1327,11 @@ impl App {
}
// The review window replaces the form that asked for the preview, so a form that
// the user closed meanwhile stays closed.
- (Some(ActionKind::PreviewRoute), Ok(reply)) if popup_matches => {
+ (Some(ActionKind::PreviewRoute | ActionKind::PreviewRouteChange), Ok(reply))
+ if popup_matches =>
+ {
if matches!(self.popup, Some(Popup::Form(_)))
- && let Some(reviewed) = action.and_then(reviewed)
+ && let Some(reviewed) = action.and_then(|action| reviewed(action, &reply.data))
{
self.set_popup(Some(Popup::review(
change_lines(self.theme, &reply.data),
@@ -1535,6 +1714,73 @@ impl App {
fields,
))
}
+ // The route form submits PreviewRouteChange, and the review window submits
+ // RouteChange. A new route also needs a models form before the review.
+ ActionKind::PreviewRouteChange | ActionKind::RouteChange => {
+ const CONFIG_NAME: &str = "Config name (blank uses the public model ID)";
+ let form = match key {
+ 'a' => {
+ let algorithm = self.data.algorithms.first().map(|a| a.kind);
+ Form::new(
+ FormKind::NewRoute { generation },
+ "Create a route",
+ vec![
+ ("Public model ID", String::new()),
+ (CONFIG_NAME, String::new()),
+ ("Algorithm", algorithm.unwrap_or_default().to_string()),
+ ],
+ )
+ }
+ 'n' => {
+ let route = self.selected_route()?;
+ Form::new(
+ FormKind::RouteIdentity {
+ generation,
+ operation: "rename",
+ route: route.key.clone(),
+ },
+ format!("Rename {}", route.id),
+ vec![("Public model ID", route.id.clone())],
+ )
+ }
+ 'c' => {
+ let route = self.selected_route()?;
+ Form::new(
+ FormKind::RouteIdentity {
+ generation,
+ operation: "duplicate",
+ route: route.key.clone(),
+ },
+ format!("Duplicate {}", route.id),
+ vec![
+ ("Public model ID", String::new()),
+ (CONFIG_NAME, String::new()),
+ ],
+ )
+ }
+ _ => return Err(format!("The {key} key does not start a route change.")),
+ };
+ self.open(form)
+ }
+ ActionKind::Remove => {
+ let route = self.selected_route()?;
+ let lines = remove_lines(self.theme, route, self.data.settings.as_ref());
+ let title = format!("Delete route {}?", route.id);
+ let kind = FormKind::Remove {
+ generation,
+ route: route.key.clone(),
+ id: route.id.clone(),
+ revision: route.revision.clone(),
+ };
+ self.set_popup(Some(Popup::review(
+ lines,
+ "Delete",
+ kind,
+ title,
+ "Type the public model ID to delete",
+ )));
+ Ok(None)
+ }
ActionKind::Models => {
let client = self.data.clients.first();
let client = client.map(|c| c.name.clone()).unwrap_or_default();
@@ -1633,8 +1879,9 @@ impl App {
Popup::Form(form) | Popup::Review { confirm: form, .. } => {
match key.code {
KeyCode::Esc => self.set_popup(None),
- KeyCode::Enter => match form.action() {
+ KeyCode::Enter => match form.action(&self.data) {
Ok(Submit::Run(action)) => return Some(Request::run(action, form.label())),
+ Ok(Submit::Next(next)) => self.set_popup(Some(Popup::Form(next))),
Err(error) => form.error = error,
},
// A field with choices cycles through them. Otherwise only the review
@@ -2728,7 +2975,7 @@ fn draw_route_table(frame: &mut Frame, app: &mut App, area: Rect) {
.title(Line::from(title));
if visible == 0 {
let text = if app.data.routes.is_empty() {
- "No routes in the server config."
+ "No routes in the server config. Press a to create one."
} else {
"No routes match the filter. Press Esc to clear it."
};
@@ -3304,6 +3551,19 @@ fn form_notes(app: &App, form: &Form) -> Vec<Line<'static>> {
lines.push(Line::default());
lines
};
+ let identity = |config_name: bool| {
+ let mut lines = vec![Line::from(
+ "Harnesses send the public model ID as the model. Each route needs its own ID.",
+ )];
+ if config_name {
+ lines.push(Line::from(
+ "The config name is the route's table name in the server config, as in \
+ [routes.team-router]. It uses 1–64 letters, digits, hyphens, or underscores.",
+ ));
+ }
+ lines.push(Line::default());
+ lines
+ };
match &form.kind {
FormKind::SaveKey | FormKind::ImportKey | FormKind::RemoveKey => {
let mut lines = vec![Line::styled("Server keys", theme.muted)];
@@ -3312,7 +3572,13 @@ fn form_notes(app: &App, form: &Form) -> Vec<Line<'static>> {
lines
}
FormKind::Algorithm { .. } => algorithms(&form.fields[0].1),
- FormKind::RouteModels { .. } => {
+ FormKind::NewRoute { .. } => {
+ let mut lines = identity(true);
+ lines.extend(algorithms(&form.fields[2].1));
+ lines
+ }
+ FormKind::RouteIdentity { operation, .. } => identity(*operation != "rename"),
+ FormKind::RouteModels { .. } | FormKind::NewRouteModels { .. } => {
let names: Vec<&str> = data.clients.iter().map(|c| c.name.as_str()).collect();
vec![
Line::styled(format!("Endpoints: {}", names.join(", ")), theme.muted),
@@ -3341,7 +3607,10 @@ fn form_notes(app: &App, form: &Form) -> Vec<Line<'static>> {
lines.push(Line::default());
lines
}
- FormKind::Preferences | FormKind::Update(_) | FormKind::Save(_) => Vec::new(),
+ FormKind::Preferences
+ | FormKind::Update(_)
+ | FormKind::Save(_)
+ | FormKind::Remove { .. } => Vec::new(),
}
}
@@ -3361,6 +3630,40 @@ fn change_lines(theme: Theme, preview: &Value) -> Vec<Line<'static>> {
lines
}
+/// This function explains what deleting a route keeps and who must change.
+fn remove_lines(
+ theme: Theme,
+ route: &RouteInfo,
+ settings: Option<&AppSettings>,
+) -> Vec<Line<'static>> {
+ let mut lines = vec![Line::from(format!(
+ "This removes the public model ID from the server. Targets and harness settings are \
+ kept. Any harness using {} must choose another route.",
+ route.id
+ ))];
+ if let Some(generated) = &route.generated {
+ lines.push(Line::default());
+ lines.push(Line::styled(
+ format!("Generated by {generated}. That tool can add the route back."),
+ theme.warn,
+ ));
+ }
+ if let Some(settings) = settings {
+ lines.push(Line::default());
+ lines.push(labeled(
+ theme,
+ "Changed file",
+ 13,
+ settings.config_file.display().to_string(),
+ ));
+ }
+ lines.push(Line::default());
+ lines.push(Line::from(
+ "Switchyard validates the config, saves a backup, and restarts the server.",
+ ));
+ lines
+}
+
fn update_lines(theme: Theme, preview: &Value) -> Vec<Line<'static>> {
// `git status --short` starts some lines with a space, so only trailing space is removed.
let field = |name: &str| {