Skip to content

Commit 707abbf

Browse files
authored
fix(cli-rs): port provider order and the service.json refusal, and fix CI-only test races (#66776)
1 parent b40acc9 commit 707abbf

26 files changed

Lines changed: 705 additions & 162 deletions

File tree

‎packages/cli-rs/crates/api-types/src/client.rs‎

Lines changed: 8 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1908,22 +1908,19 @@ pub fn experimental_push_settings_set(
19081908
call
19091909
}
19101910

1911-
/// `POST /api/experimental/space/:space/write` (`space.write`)
1911+
/// `POST /api/experimental/space/write` (`space.write`)
19121912
pub fn experimental_space_write(input: &ExperimentalSpaceWriteInput) -> Call<ExperimentalSpaceWriteOutput> {
1913-
let mut call = Call::new("POST", String::new(), Reply::Json, 200, &[400, 401]);
1914-
call.path = format!("/api/experimental/space/{}/write", call.param(&input.space));
1913+
let mut call = Call::new("POST", "/api/experimental/space/write".to_owned(), Reply::Json, 200, &[400, 401]);
19151914
call.object();
19161915
call.field("changes", &input.changes);
19171916
call
19181917
}
19191918

1920-
/// `GET /api/experimental/space/:space` (`space.sync`)
1919+
/// `POST /api/experimental/space/sync` (`space.sync`)
19211920
pub fn experimental_space_sync(input: &ExperimentalSpaceSyncInput) -> Call<ExperimentalSpaceSyncOutput> {
1922-
let mut call = Call::new("GET", String::new(), Reply::Json, 200, &[400, 401]);
1923-
call.path = format!("/api/experimental/space/{}", call.param(&input.space));
1924-
if let Some(value) = &input.cursor {
1925-
call.query("cursor", value);
1926-
}
1921+
let mut call = Call::new("POST", "/api/experimental/space/sync".to_owned(), Reply::Json, 200, &[400, 401]);
1922+
call.object();
1923+
call.field("spaces", &input.spaces);
19271924
call
19281925
}
19291926

@@ -3231,18 +3228,10 @@ pub fn probe(name: &str, input: &serde_json::Value) -> Option<Result<Call<serde_
32313228
.cast())
32323229
})()),
32333230
"experimental.space.write" => Some((|| {
3234-
Ok(experimental_space_write(&ExperimentalSpaceWriteInput {
3235-
space: field(input, "space")?,
3236-
changes: field(input, "changes")?,
3237-
})
3238-
.cast())
3231+
Ok(experimental_space_write(&ExperimentalSpaceWriteInput { changes: field(input, "changes")? }).cast())
32393232
})()),
32403233
"experimental.space.sync" => Some((|| {
3241-
Ok(experimental_space_sync(&ExperimentalSpaceSyncInput {
3242-
space: field(input, "space")?,
3243-
cursor: field(input, "cursor")?,
3244-
})
3245-
.cast())
3234+
Ok(experimental_space_sync(&ExperimentalSpaceSyncInput { spaces: field(input, "spaces")? }).cast())
32463235
})()),
32473236
"experimental.space.subscribe" => Some((|| {
32483237
Ok(experimental_space_subscribe(&ExperimentalSpaceSubscribeInput {

‎packages/cli-rs/crates/api-types/src/types.rs‎

Lines changed: 20 additions & 6 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎packages/cli-rs/crates/api/src/generated/methods.rs‎

Lines changed: 2 additions & 2 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎packages/cli-rs/crates/cli/src/commands/auth.rs‎

Lines changed: 43 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -566,7 +566,8 @@ pub(super) fn resolve_integration<'a>(
566566
// ---------------------------------------------------------------------------------------------------------------
567567

568568
// Picker order under “Popular”.
569-
const PRIORITY: [&str; 6] = ["opencode-go", "opencode", "openai", "github-copilot", "anthropic", "google"];
569+
const PRIORITY: [&str; 7] =
570+
["opencode-go", "opencode", "openai", "anthropic", "claude-agent", "github-copilot", "google"];
570571

571572
fn login(context: &Context, args: &AuthLoginArgs) -> error::Result<()> {
572573
if args.target.is_none() {
@@ -1673,6 +1674,47 @@ mod tests {
16731674
assert_eq!(entries[0].value.to_string(), r#"{"type":"key","key":"k","metadata":{"a":1,"b":3}}"#);
16741675
}
16751676

1677+
#[test]
1678+
fn login_choices_group_and_order_like_connect() {
1679+
let integration = |id: &str, name: &str, metadata: Option<&str>, connection: &str| -> IntegrationInfo {
1680+
let metadata = metadata.map(|value| format!(r#","metadata":{value}"#)).unwrap_or_default();
1681+
serde_json::from_str(&format!(
1682+
r#"{{"id":"{id}","name":"{name}"{metadata},"methods":[{{"type":"key"}}],"connections":[{connection}]}}"#
1683+
))
1684+
.unwrap()
1685+
};
1686+
let go = r#"{"type":"credential","id":"go","label":"Go","method":"key"}"#;
1687+
let choices = login_choices(&[
1688+
integration("mistral", "Mistral", None, ""),
1689+
integration("github-copilot", "GitHub Copilot", None, ""),
1690+
integration("claude-agent", "Claude Agent", None, ""),
1691+
integration("anthropic", "Anthropic", None, ""),
1692+
integration("google", "Google", None, ""),
1693+
integration("openai", "OpenAI", None, ""),
1694+
integration("linear", "Linear", Some(r#"{"source":"mcp"}"#), ""),
1695+
integration("github", "GitHub", Some(r#"{"source":"mcp"}"#), ""),
1696+
integration("opencode", "OpenCode Console", None, ""),
1697+
integration("opencode-go", "OpenCode Go", None, go),
1698+
]);
1699+
let actual: Vec<(&str, &str, bool)> =
1700+
choices.iter().map(|choice| (choice.value.as_str(), choice.category, choice.connected)).collect();
1701+
assert_eq!(
1702+
actual,
1703+
[
1704+
("github", "MCP", false),
1705+
("linear", "MCP", false),
1706+
("opencode-go", "Popular", true),
1707+
("opencode", "Popular", false),
1708+
("openai", "Popular", false),
1709+
("anthropic", "Popular", false),
1710+
("claude-agent", "Popular", false),
1711+
("github-copilot", "Popular", false),
1712+
("google", "Popular", false),
1713+
("mistral", "Services", false),
1714+
]
1715+
);
1716+
}
1717+
16761718
#[test]
16771719
fn login_choices_hide_opencode_go_until_a_go_key_is_saved() {
16781720
let integration = |id: &str, connection: &str| -> IntegrationInfo {

‎packages/cli-rs/crates/cli/src/commands/machine.rs‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -84,8 +84,7 @@ async fn client(context: &Context) -> error::Result<Connected> {
8484
if context.server.standalone {
8585
bail!("--standalone starts a server for this command only; a machine needs one that keeps running.");
8686
}
87-
let disabled = Local::from_env()?.config().read()?.disabled == Some(true);
88-
if context.server.server.is_none() && disabled {
87+
if context.server.server.is_none() && Local::from_env()?.config().read()?.disabled == Some(true) {
8988
bail!("Managing machines requires the background service; run `opencode service unset disabled` first.");
9089
}
9190
connect(context).await

‎packages/cli-rs/crates/cli/src/commands/service.rs‎

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -24,8 +24,14 @@ pub fn run(_context: &Context, args: &ServiceArgs) -> error::Result<()> {
2424
let Some(command) = &args.command else { return crate::help::print(&["service"]) };
2525
let local = Local::from_env()?;
2626
match command {
27-
ServiceCommand::Start => print(&(block_on(local.ensure())??.service.endpoint.url + "\n")),
28-
ServiceCommand::Restart => print(&(block_on(local.restart())?? + "\n")),
27+
ServiceCommand::Start => {
28+
local.config().read()?;
29+
print(&(block_on(local.ensure())??.service.endpoint.url + "\n"))
30+
}
31+
ServiceCommand::Restart => {
32+
local.config().read()?;
33+
print(&(block_on(local.restart())?? + "\n"))
34+
}
2935
ServiceCommand::Status => {
3036
let found = block_on(local.discover())?;
3137
print(&(found.map_or("stopped".into(), |found| found.service.endpoint.url) + "\n"))
@@ -35,6 +41,7 @@ pub fn run(_context: &Context, args: &ServiceArgs) -> error::Result<()> {
3541
ServiceCommand::Set(set) => {
3642
let edit = Edit::set(&set.key, &set.value, set.env_value.as_deref())?;
3743
if edit.needs_tunnel() {
44+
local.config().read()?;
3845
// The TS command creates the tunnel in the foreground, then stops the service and writes
3946
// the route; a tunnel that cannot be created leaves remote access off.
4047
let child = delegate::enable_remote(&TsCommand::from_env())?;
@@ -107,9 +114,10 @@ impl Local {
107114
Ok(self.ensure().await?.service.endpoint.url)
108115
}
109116

110-
/// `ServiceConfig.set` or `unset` for every key but `remote true`: stops the service first when TS
111-
/// does, then writes the file.
117+
/// `ServiceConfig.set` or `unset` for every key but `remote true`: validates the existing config first,
118+
/// stops the service when TS does, then writes the file.
112119
pub fn edit(&self, edit: &Edit) -> error::Result<()> {
120+
self.config().read()?;
113121
if edit.stops_service() {
114122
block_on(self.stop())??;
115123
}

‎packages/cli-rs/crates/cli/src/output.rs‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,12 @@ pub fn fail(error: error::Error) -> u8 {
3030
if let Some(exit) = error.downcast_ref::<Exit>() {
3131
return exit.0;
3232
}
33-
eprintln!("Error: {}", opencode_ui::terminal_text(&format!("{error:#}")));
33+
let tag = match error.downcast_ref::<opencode_local::service_config::Error>() {
34+
Some(opencode_local::service_config::Error::InvalidConfig { .. }) => {
35+
opencode_local::service_config::INVALID_ERROR_TAG
36+
}
37+
_ => error.downcast_ref::<opencode_service::connect::Error>().and_then(|error| error.tag).unwrap_or("Error"),
38+
};
39+
eprintln!("{tag}: {}", opencode_ui::terminal_text(&format!("{error:#}")));
3440
1
3541
}

‎packages/cli-rs/crates/cli/tests/service.rs‎

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -222,6 +222,53 @@ fn start_status_stop_and_restart() {
222222
assert_eq!(text(&sandbox.run(&["service", "status"], &[]).stdout), "stopped\n");
223223
}
224224

225+
#[test]
226+
fn invalid_service_config_is_not_overwritten_while_status_and_stop_still_work() {
227+
let Some(sandbox) = Sandbox::new() else { return };
228+
let start = sandbox.run(&["service", "start"], &[]);
229+
assert!(start.status.success(), "{}", text(&start.stderr));
230+
let url = text(&start.stdout);
231+
let registration_before = std::fs::read_to_string(sandbox.path("state/opencode/service-local.json")).unwrap();
232+
233+
let file = sandbox.path("config/opencode/service-local.json");
234+
let raw = "{\"hostname\":\"127.0.0.1\",\"port\":\"4096\",\"password\":\"keep-me\",\"env\":{\"KEEP\":\"1\"}}\n";
235+
std::fs::write(&file, raw).unwrap();
236+
237+
for args in [
238+
&["service", "get"][..],
239+
&["service", "get", "password"][..],
240+
&["service", "set", "port", "4097"][..],
241+
&["service", "set", "remote", "true"][..],
242+
&["service", "unset", "port"][..],
243+
&["service", "start"][..],
244+
&["service", "restart"][..],
245+
] {
246+
let output = sandbox.run(args, &[]);
247+
assert_eq!(output.status.code(), Some(1), "{args:?}");
248+
let stderr = text(&output.stderr);
249+
assert!(
250+
stderr.contains(&format!("ServiceConfig.InvalidError: Invalid service config at {}", file.display())),
251+
"{args:?}: {stderr}"
252+
);
253+
assert!(stderr.contains(r#"["port"]"#), "{args:?}: {stderr}");
254+
assert_eq!(std::fs::read_to_string(&file).unwrap(), raw, "{args:?}");
255+
assert_eq!(
256+
std::fs::read_to_string(sandbox.path("state/opencode/service-local.json")).unwrap(),
257+
registration_before,
258+
"{args:?}"
259+
);
260+
}
261+
262+
let status = sandbox.run(&["service", "status"], &[]);
263+
assert!(status.status.success(), "{}", text(&status.stderr));
264+
assert_eq!(text(&status.stdout), url);
265+
266+
let stop = sandbox.run(&["service", "stop"], &[]);
267+
assert!(stop.status.success(), "{}", text(&stop.stderr));
268+
assert!(sandbox.registration().is_none());
269+
assert_eq!(std::fs::read_to_string(&file).unwrap(), raw);
270+
}
271+
225272
#[test]
226273
fn set_stops_the_service_without_ending_terminals() {
227274
let Some(sandbox) = Sandbox::new() else { return };

0 commit comments

Comments
 (0)