use std::borrow::Cow;
use std::collections::BTreeMap;
use std::fmt;
use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema};
use serde::de::{self, Deserializer, SeqAccess, Visitor};
use serde::ser::Serializer;
use serde::{Deserialize, Serialize};
use crate::error::ErrorCode;
use crate::model::validate::{Diagnostics, at, join};
use crate::model::{SCHEMA_VERSION, StoreModel};
pub const NATIVE_NAME_KEY: &str = "native_name";
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct KnownClient {
pub id: &'static str,
pub passthrough: &'static [&'static str],
}
const fn client(id: &'static str, passthrough: &'static [&'static str]) -> KnownClient {
KnownClient { id, passthrough }
}
pub const KNOWN_CLIENTS: &[KnownClient] = &[
client("claude-code", &[]),
client("omp", &["timeout", "instructions", "auth", "oauth"]),
client("pi", &["exposure", "timeout", "oauth"]),
client("codex", &["startup_timeout_sec", "tool_timeout_sec"]),
client("claude-desktop", &[]),
client("copilot", &["oauthClientId"]),
client("cursor", &["envFile"]),
client("gemini", &["timeout", "trust"]),
client("antigravity", &["timeoutSeconds"]),
client("opencode", &[]),
client("grok", &["startup_timeout_sec", "tool_timeout_sec"]),
client("vscode-legacy", &[]),
client("windsurf", &[]),
client("devin", &[]),
client("augment", &[]),
client("cline", &[]),
client("roo-code", &[]),
client("kilo-code", &[]),
client("kiro", &[]),
client("junie", &[]),
client("droid", &[]),
client("commandcode", &[]),
client("crush", &[]),
client("qoder", &[]),
client("trae", &[]),
client("trae-cn", &[]),
client("codebuddy", &[]),
client("iflow", &[]),
client("qwen-code", &["timeout", "trust"]),
client("zencoder", &[]),
client("openclaw", &[]),
client("mimo-code", &[]),
client("workbuddy", &[]),
client("zcode", &[]),
client("continue", &[]),
client("goose", &[]),
client("hermes", &[]),
client("intellij", &[]),
];
pub fn known_client(id: &str) -> Option<&'static KnownClient> {
KNOWN_CLIENTS.iter().find(|client| client.id == id)
}
pub const fn passthrough_of(id: &str) -> &'static [&'static str] {
let mut index = 0;
while index < KNOWN_CLIENTS.len() {
if const_str_eq(KNOWN_CLIENTS[index].id, id) {
return KNOWN_CLIENTS[index].passthrough;
}
index += 1;
}
panic!("passthrough_of: unknown client id");
}
const fn const_str_eq(a: &str, b: &str) -> bool {
let (a, b) = (a.as_bytes(), b.as_bytes());
if a.len() != b.len() {
return false;
}
let mut index = 0;
while index < a.len() {
if a[index] != b[index] {
return false;
}
index += 1;
}
true
}
const ALL_DETECTED: &str = "all-detected";
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ClientSelection {
AllDetected,
List(Vec<String>),
}
impl Serialize for ClientSelection {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
match self {
Self::AllDetected => serializer.serialize_str(ALL_DETECTED),
Self::List(ids) => ids.serialize(serializer),
}
}
}
impl<'de> Deserialize<'de> for ClientSelection {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
deserializer.deserialize_any(KeywordOrList {
keywords: &[ALL_DETECTED],
keyword: |_| ClientSelection::AllDetected,
list: ClientSelection::List,
})
}
}
impl JsonSchema for ClientSelection {
fn schema_name() -> Cow<'static, str> {
"ClientSelection".into()
}
fn json_schema(_: &mut SchemaGenerator) -> Schema {
json_schema!({
"description": "\"all-detected\" or a list of client ids",
"oneOf": [
{ "const": ALL_DETECTED },
{ "type": "array", "items": { "type": "string" } }
]
})
}
}
pub fn toggle_clients(
current: Option<&ClientSelection>,
here: impl FnOnce() -> Vec<String>,
clients: &[String],
enabled: bool,
) -> Option<Vec<String>> {
let start = match current {
Some(ClientSelection::List(ids)) => ids.clone(),
Some(ClientSelection::AllDetected) => here(),
None => Vec::new(),
};
let mut next = start.clone();
for client in clients {
if enabled && !next.contains(client) {
next.push(client.clone());
} else if !enabled {
next.retain(|id| id != client);
}
}
(next != start).then_some(next)
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ProfileSelection {
Default,
All,
List(Vec<String>),
}
impl Serialize for ProfileSelection {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
match self {
Self::Default => serializer.serialize_str("default"),
Self::All => serializer.serialize_str("all"),
Self::List(ids) => ids.serialize(serializer),
}
}
}
impl<'de> Deserialize<'de> for ProfileSelection {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
deserializer.deserialize_any(KeywordOrList {
keywords: &["default", "all"],
keyword: |keyword| match keyword {
"default" => ProfileSelection::Default,
_ => ProfileSelection::All,
},
list: ProfileSelection::List,
})
}
}
impl JsonSchema for ProfileSelection {
fn schema_name() -> Cow<'static, str> {
"ProfileSelection".into()
}
fn json_schema(_: &mut SchemaGenerator) -> Schema {
json_schema!({
"description": "\"default\", \"all\" or a list of profile ids",
"oneOf": [
{ "enum": ["default", "all"] },
{ "type": "array", "items": { "type": "string" } }
]
})
}
}
struct KeywordOrList<T> {
keywords: &'static [&'static str],
keyword: fn(&str) -> T,
list: fn(Vec<String>) -> T,
}
impl<'de, T> Visitor<'de> for KeywordOrList<T> {
type Value = T;
fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let keywords: Vec<String> = self.keywords.iter().map(|k| format!("{k:?}")).collect();
write!(f, "{} or a list of ids", keywords.join(", "))
}
fn visit_str<E: de::Error>(self, value: &str) -> Result<T, E> {
match self.keywords.iter().find(|keyword| **keyword == value) {
Some(keyword) => Ok((self.keyword)(keyword)),
None => Err(E::invalid_value(de::Unexpected::Str(value), &self)),
}
}
fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<T, A::Error> {
let mut ids = Vec::new();
while let Some(id) = seq.next_element::<String>()? {
ids.push(id);
}
Ok((self.list)(ids))
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[schemars(title = "Surjection client preferences (store/clients.toml)")]
pub struct ClientPrefsFile {
#[schemars(extend("const" = 1))]
pub schema: i64,
#[serde(flatten)]
pub clients: BTreeMap<String, ClientPrefs>,
}
impl StoreModel for ClientPrefsFile {
const SCHEMA_NAME: &'static str = "clients";
}
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, JsonSchema)]
pub struct ClientPrefs {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub enabled: Option<bool>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub native_disable: Option<bool>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub project_shared_target: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub project_local_target: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub profiles: Option<Vec<String>>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub import_variants: Option<Vec<String>>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub import_profiles: Option<ProfileSelection>,
#[serde(flatten)]
#[schemars(skip)]
pub extra: toml::Table,
}
pub const VSCODE_VARIANTS: [&str; 3] = ["Code", "Code - Insiders", "VSCodium"];
impl ClientPrefsFile {
pub fn new() -> Self {
Self {
schema: SCHEMA_VERSION,
clients: BTreeMap::new(),
}
}
pub fn validate(&self) -> Diagnostics {
let mut d = Diagnostics::new();
for (id, prefs) in &self.clients {
let base = join("", id);
if known_client(id).is_none() {
d.warning(
ErrorCode::UnknownClient,
&base,
format!("unknown client {id:?}; kept as written"),
);
}
for (index, variant) in prefs.import_variants.iter().flatten().enumerate() {
if !VSCODE_VARIANTS.contains(&variant.as_str()) {
d.error(
ErrorCode::InvalidValue,
at(&join(&base, "import_variants"), index),
format!(
"unknown VS Code variant {variant:?}; expected one of {VSCODE_VARIANTS:?}"
),
);
}
}
}
d
}
}
impl Default for ClientPrefsFile {
fn default() -> Self {
Self::new()
}
}
#[cfg(test)]
mod tests {
use super::*;
fn ids(list: &[&str]) -> Vec<String> {
list.iter().map(|id| (*id).to_owned()).collect()
}
#[test]
fn toggle_clients_edits_the_written_list() {
let here = || panic!("a list never asks what is detected");
let list = ClientSelection::List(ids(&["codex", "future-client"]));
assert_eq!(
toggle_clients(Some(&list), here, &ids(&["omp", "codex"]), true),
Some(ids(&["codex", "future-client", "omp"]))
);
assert_eq!(
toggle_clients(Some(&list), here, &ids(&["codex"]), false),
Some(ids(&["future-client"]))
);
assert_eq!(
toggle_clients(Some(&list), here, &ids(&["codex"]), true),
None
);
assert_eq!(
toggle_clients(Some(&list), here, &ids(&["omp"]), false),
None
);
assert_eq!(
toggle_clients(None, here, &ids(&["omp"]), true),
Some(ids(&["omp"]))
);
assert_eq!(toggle_clients(None, here, &ids(&["omp"]), false), None);
}
#[test]
fn toggle_clients_turns_all_detected_into_what_it_selects_here() {
let all = ClientSelection::AllDetected;
let here = || ids(&["claude-code", "codex"]);
assert_eq!(
toggle_clients(Some(&all), here, &ids(&["codex"]), false),
Some(ids(&["claude-code"]))
);
assert_eq!(
toggle_clients(Some(&all), here, &ids(&["omp"]), true),
Some(ids(&["claude-code", "codex", "omp"]))
);
assert_eq!(
toggle_clients(Some(&all), here, &ids(&["codex"]), true),
None
);
assert_eq!(
toggle_clients(Some(&all), here, &ids(&["omp"]), false),
None
);
}
}