Merge pull request #1345 from ludovic111/feat/agent-connect-launcher
🤖 Agent: merged after verify passed and the agent-control-2 integration of all six PRs on the Mac mini. agent_control_e2e passes in CLI and MCP (one known survival flake), launcher_mcp_e2e passes, No AI is refused, and the options, screen_layout, menu_click and world_options parity harnesses pass. Ludovic asked for this on 2026-10-23.
This commit is contained in:
@@ -86,6 +86,73 @@ pub fn clients(exe: &Path) -> Vec<Client> {
|
||||
]
|
||||
}
|
||||
|
||||
/// Where a client's CLI is: on the PATH, else in the folders installers use (a launcher started
|
||||
/// from the desktop gets a short PATH on macOS). The bare name when it is nowhere.
|
||||
pub fn locate(program: &str) -> std::path::PathBuf {
|
||||
let home = dirs::home_dir().unwrap_or_default();
|
||||
let names: Vec<String> = if cfg!(windows) {
|
||||
["exe", "cmd"]
|
||||
.iter()
|
||||
.map(|e| format!("{program}.{e}"))
|
||||
.collect()
|
||||
} else {
|
||||
vec![program.to_owned()]
|
||||
};
|
||||
let extra = [
|
||||
home.join(".local/bin"),
|
||||
home.join(".claude/local"),
|
||||
home.join(".npm-global/bin"),
|
||||
home.join(".bun/bin"),
|
||||
home.join(".cargo/bin"),
|
||||
"/opt/homebrew/bin".into(),
|
||||
"/usr/local/bin".into(),
|
||||
home.join("AppData/Roaming/npm"),
|
||||
];
|
||||
std::env::var_os("PATH")
|
||||
.map(|p| std::env::split_paths(&p).collect::<Vec<_>>())
|
||||
.unwrap_or_default()
|
||||
.into_iter()
|
||||
.chain(extra)
|
||||
.flat_map(|dir| names.iter().map(move |n| dir.join(n)))
|
||||
.find(|p| p.is_file())
|
||||
.unwrap_or_else(|| program.into())
|
||||
}
|
||||
|
||||
/// Starts `exe mcp` as a client would, lists its tools and returns how many answered: the
|
||||
/// Settings page's "Test the connection".
|
||||
pub fn self_test(exe: &Path) -> Result<usize, String> {
|
||||
use std::io::Write;
|
||||
use std::process::{Command, Stdio};
|
||||
let mut child = Command::new(exe)
|
||||
.arg("mcp")
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
.spawn()
|
||||
.map_err(|e| format!("Could not start {}: {e}", exe.display()))?;
|
||||
let lines = [
|
||||
json!({ "jsonrpc": "2.0", "id": 1, "method": "initialize", "params": { "protocolVersion": "2025-06-18", "capabilities": {}, "clientInfo": { "name": "horizon-launcher-test", "version": "1" } } }),
|
||||
json!({ "jsonrpc": "2.0", "method": "notifications/initialized" }),
|
||||
json!({ "jsonrpc": "2.0", "id": 2, "method": "tools/list", "params": {} }),
|
||||
];
|
||||
if let Some(mut stdin) = child.stdin.take() {
|
||||
for line in &lines {
|
||||
writeln!(stdin, "{line}").map_err(|e| e.to_string())?;
|
||||
}
|
||||
// Dropping stdin ends the session: the server answers, then exits.
|
||||
}
|
||||
let out = child.wait_with_output().map_err(|e| e.to_string())?;
|
||||
if !out.status.success() {
|
||||
return Err(String::from_utf8_lossy(&out.stderr).trim().to_owned());
|
||||
}
|
||||
String::from_utf8_lossy(&out.stdout)
|
||||
.lines()
|
||||
.filter_map(|l| serde_json::from_str::<Value>(l).ok())
|
||||
.find(|r| r["id"] == 2)
|
||||
.and_then(|r| r["result"]["tools"].as_array().map(Vec::len))
|
||||
.ok_or_else(|| "The MCP server did not list its tools.".into())
|
||||
}
|
||||
|
||||
/// `program args...` quoted for a POSIX shell where a word needs it.
|
||||
pub fn shell_line(program: &str, args: &[String]) -> String {
|
||||
let quote = |w: &str| {
|
||||
|
||||
@@ -0,0 +1,240 @@
|
||||
//! Settings' AI rows: the No AI switch (`horizon_core::no_ai`, shared with the game) and "Connect
|
||||
//! an AI agent", the ready-made MCP config of each common client with Copy buttons, a one-click
|
||||
//! add where the client has a CLI (run only on that click, its command shown first), and a test
|
||||
//! that starts the MCP server and lists its tools. With No AI on, only the switch shows.
|
||||
use super::*;
|
||||
use horizon_launcher::agents;
|
||||
|
||||
#[derive(Default)]
|
||||
pub(crate) struct AgentsUi {
|
||||
/// The client shown, an index into `agents::clients`.
|
||||
client: usize,
|
||||
/// Which Copy button just copied.
|
||||
copied: Option<&'static str>,
|
||||
/// A command or test running.
|
||||
busy: bool,
|
||||
/// What the last add or test said, and whether it went well.
|
||||
status: Option<(bool, String)>,
|
||||
}
|
||||
|
||||
impl Launcher {
|
||||
/// The No AI row: always shown, so it can be turned off again.
|
||||
pub(crate) fn no_ai_row(&mut self, n: usize, cx: &mut Context<Self>) -> Div {
|
||||
let t = self.theme;
|
||||
let on = backend::no_ai();
|
||||
let toggle =
|
||||
switch("no-ai", on, &t).on_click(cx.listener(move |this, _: &ClickEvent, _, cx| {
|
||||
this.agents.status = backend::set_no_ai(!on).err().map(|e| (false, e));
|
||||
cx.notify();
|
||||
}));
|
||||
index_row(
|
||||
n,
|
||||
"No AI",
|
||||
Some(
|
||||
div()
|
||||
.child(if on {
|
||||
"On: every AI feature is hidden and off. The game opens no control socket, and horizon-ctl and the MCP servers refuse."
|
||||
} else {
|
||||
"Hides and turns off every AI feature: agent control of the launcher and the game, horizon-ctl and the MCP servers."
|
||||
})
|
||||
.into_any_element(),
|
||||
),
|
||||
Some(toggle.into_any_element()),
|
||||
&t,
|
||||
)
|
||||
}
|
||||
|
||||
/// "Connect an AI agent"; None while No AI is on.
|
||||
pub(crate) fn agents_section(&mut self, cx: &mut Context<Self>) -> Option<Div> {
|
||||
if backend::no_ai() {
|
||||
return None;
|
||||
}
|
||||
let t = self.theme;
|
||||
let exe = backend::exe_path();
|
||||
let clients = agents::clients(exe);
|
||||
let pick = self.agents.client.min(clients.len() - 1);
|
||||
let client = &clients[pick];
|
||||
let this = cx.entity().downgrade();
|
||||
let options: Vec<(usize, &'static str)> = clients
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, c)| (i, c.name))
|
||||
.collect();
|
||||
let picker = segments("agent-client", &options, pick, &t, move |i, _, cx| {
|
||||
let _ = this.update(cx, |this, cx| {
|
||||
this.agents.client = i;
|
||||
this.agents.copied = None;
|
||||
this.agents.status = None;
|
||||
cx.notify();
|
||||
});
|
||||
});
|
||||
let copy = |id: &'static str, text: String, cx: &mut Context<Self>| {
|
||||
let copied = self.agents.copied == Some(id);
|
||||
button(
|
||||
id,
|
||||
if copied { "Copied" } else { "Copy" },
|
||||
Kind::Secondary,
|
||||
&t,
|
||||
)
|
||||
.on_click(cx.listener(move |this, _: &ClickEvent, _, cx| {
|
||||
cx.write_to_clipboard(gpui::ClipboardItem::new_string(text.clone()));
|
||||
this.agents.copied = Some(id);
|
||||
cx.notify();
|
||||
}))
|
||||
};
|
||||
let code = |s: &str| {
|
||||
div()
|
||||
.p(px(10.))
|
||||
.bg(t.well)
|
||||
.border_2()
|
||||
.border_color(t.outline)
|
||||
.font_family(theme::MONO)
|
||||
.text_size(px(12.))
|
||||
.line_height(px(18.))
|
||||
.text_color(t.ink)
|
||||
.children(s.lines().map(|l| div().child(l.to_owned())))
|
||||
};
|
||||
let mut section = plate(&t)
|
||||
.flex()
|
||||
.flex_col()
|
||||
.gap(px(12.))
|
||||
.p(px(24.))
|
||||
.text_size(px(theme::UI.px))
|
||||
.line_height(px(21.))
|
||||
.child(text(theme::HEADING).text_color(t.ink).child("Connect an AI agent"))
|
||||
.child(div().max_w(px(640.)).text_color(t.muted).child(
|
||||
"Your own agent (Claude Code, Codex, Cursor or any MCP client) can drive the launcher and the game it starts, with the same commands as the terminal. It runs on your computer and talks to Horizon there; it asks before deleting anything.",
|
||||
))
|
||||
.child(picker);
|
||||
if let Some((program, args)) = client.add.clone() {
|
||||
let line = client.add_line().unwrap_or_default();
|
||||
let label = format!("Add to {}", client.name);
|
||||
let busy = self.agents.busy;
|
||||
let add = button(
|
||||
"agent-add",
|
||||
if busy { "Running…".to_owned() } else { label },
|
||||
Kind::Primary,
|
||||
&t,
|
||||
)
|
||||
.on_click(cx.listener(move |this, _: &ClickEvent, _, cx| {
|
||||
if this.agents.busy {
|
||||
return;
|
||||
}
|
||||
this.agents.busy = true;
|
||||
this.agents.status = None;
|
||||
let (program, args) = (program, args.clone());
|
||||
let task = cx
|
||||
.background_executor()
|
||||
.spawn(async move { run_add(program, &args) });
|
||||
cx.spawn(async move |this, cx| {
|
||||
let result = task.await;
|
||||
let _ = this.update(cx, |this, cx| {
|
||||
this.agents.busy = false;
|
||||
this.agents.status = Some(result);
|
||||
cx.notify();
|
||||
});
|
||||
})
|
||||
.detach();
|
||||
cx.notify();
|
||||
}));
|
||||
section = section
|
||||
.child(div().text_color(t.muted).child(format!(
|
||||
"{} adds it with this command (it runs only when you click):",
|
||||
client.name
|
||||
)))
|
||||
.child(code(&line))
|
||||
.child(div().flex().gap(px(8.)).child(add).child(copy(
|
||||
"agent-copy-command",
|
||||
line.clone(),
|
||||
cx,
|
||||
)));
|
||||
}
|
||||
section = section
|
||||
.child(div().text_color(t.muted).child(format!(
|
||||
"{} {}:",
|
||||
if client.add.is_some() { "Or put this in" } else { "Put this in" },
|
||||
client.file
|
||||
)))
|
||||
.child(code(&client.config))
|
||||
.child(div().flex().gap(px(8.)).child(copy("agent-copy-config", client.config.clone(), cx)).child(
|
||||
button("agent-test", "Test the connection", Kind::Secondary, &t).on_click(cx.listener(
|
||||
|this, _: &ClickEvent, _, cx| {
|
||||
if this.agents.busy {
|
||||
return;
|
||||
}
|
||||
this.agents.busy = true;
|
||||
this.agents.status = None;
|
||||
let exe = backend::exe_path().to_path_buf();
|
||||
let task = cx.background_executor().spawn(async move {
|
||||
match agents::self_test(&exe) {
|
||||
Ok(n) => (true, format!("The MCP server answered with {n} tools. Now ask your agent: \"Say hello from Horizon\".")),
|
||||
Err(e) => (false, format!("The MCP server did not answer: {e}")),
|
||||
}
|
||||
});
|
||||
cx.spawn(async move |this, cx| {
|
||||
let result = task.await;
|
||||
let _ = this.update(cx, |this, cx| {
|
||||
this.agents.busy = false;
|
||||
this.agents.status = Some(result);
|
||||
cx.notify();
|
||||
});
|
||||
})
|
||||
.detach();
|
||||
cx.notify();
|
||||
},
|
||||
)),
|
||||
));
|
||||
if let Some((ok, message)) = &self.agents.status {
|
||||
section = section.child(
|
||||
div()
|
||||
.text_color(if *ok { t.ink } else { t.danger })
|
||||
.child(message.clone()),
|
||||
);
|
||||
}
|
||||
Some(
|
||||
section.child(
|
||||
div()
|
||||
.id("agent-docs")
|
||||
.text_color(t.accent)
|
||||
.cursor_pointer()
|
||||
.hover(|s| s.opacity(0.8))
|
||||
.child("What an agent can do, and the commands")
|
||||
.on_click(|_, _, cx| cx.open_url(backend::AGENT_DOCS_URL)),
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs a client's add command; (went well, what it said).
|
||||
fn run_add(program: &str, args: &[String]) -> (bool, String) {
|
||||
match std::process::Command::new(agents::locate(program))
|
||||
.args(args)
|
||||
.output()
|
||||
{
|
||||
Ok(out) if out.status.success() => (
|
||||
true,
|
||||
format!(
|
||||
"Added. Restart {program} if it is open, then ask it: \"Say hello from Horizon\"."
|
||||
),
|
||||
),
|
||||
Ok(out) => (
|
||||
false,
|
||||
format!(
|
||||
"{program} said: {}",
|
||||
String::from_utf8_lossy(if out.stderr.is_empty() {
|
||||
&out.stdout
|
||||
} else {
|
||||
&out.stderr
|
||||
})
|
||||
.trim()
|
||||
),
|
||||
),
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => (
|
||||
false,
|
||||
format!(
|
||||
"{program} is not installed here (or not on the PATH): copy the config instead."
|
||||
),
|
||||
),
|
||||
Err(e) => (false, format!("Could not run {program}: {e}")),
|
||||
}
|
||||
}
|
||||
@@ -11,6 +11,8 @@ use std::sync::{Arc, Mutex};
|
||||
|
||||
pub const REPO: &str = "ludovic111/horizon";
|
||||
pub const README_URL: &str = "https://github.com/ludovic111/horizon/blob/main/launcher/README.md";
|
||||
/// The players' page on connecting an AI agent (website/docs/agents.md).
|
||||
pub const AGENT_DOCS_URL: &str = "https://playhorizon.dev/docs/agents";
|
||||
/// This launcher's version: the release workflow sets `HORIZON_LAUNCHER_VERSION` from the
|
||||
/// tag it builds (no version-bump commits); other builds say Cargo.toml's.
|
||||
pub const VERSION: &str = version_or(option_env!("HORIZON_LAUNCHER_VERSION"));
|
||||
|
||||
+12
-1
@@ -368,6 +368,9 @@ enum Cmd {
|
||||
/// Only this client
|
||||
#[arg(long, value_parser = ["claude-code", "codex", "cursor", "generic"])]
|
||||
client: Option<String>,
|
||||
/// Start the MCP server as a client would and say whether it answered
|
||||
#[arg(long)]
|
||||
test: bool,
|
||||
},
|
||||
/// Show or set No AI: on hides and turns off every AI feature (the companion, agent control,
|
||||
/// horizon-ctl and both MCP servers); off, the default, makes them available
|
||||
@@ -673,7 +676,15 @@ fn execute(command: Cmd, as_json: bool) -> Result<(), String> {
|
||||
println!("No AI is off: AI features are available.");
|
||||
}
|
||||
}
|
||||
Cmd::AgentConfig { client } => {
|
||||
Cmd::AgentConfig { test: true, .. } => {
|
||||
let tools = horizon_launcher::agents::self_test(backend::exe_path())?;
|
||||
if as_json {
|
||||
json(serde_json::json!({ "answered": true, "tools": tools }));
|
||||
} else {
|
||||
println!("The MCP server answered with {tools} tools.");
|
||||
}
|
||||
}
|
||||
Cmd::AgentConfig { client, .. } => {
|
||||
use horizon_launcher::agents;
|
||||
let exe = backend::exe_path();
|
||||
if as_json {
|
||||
|
||||
+7
-31
@@ -1,6 +1,7 @@
|
||||
//! Horizon launcher: installs Horizon builds, prepares them from the player's own Minecraft,
|
||||
//! and starts the client or a dedicated server.
|
||||
|
||||
mod agents_page;
|
||||
mod art;
|
||||
mod blocks;
|
||||
mod cli;
|
||||
@@ -180,6 +181,8 @@ struct Launcher {
|
||||
args_focus: FocusHandle,
|
||||
/// Opt-in data collection: the player's answer and Settings' section (`collection`).
|
||||
collection: collection::Collection,
|
||||
/// Settings' "Connect an AI agent" (`agents_page`).
|
||||
agents: agents_page::AgentsUi,
|
||||
/// How many play Horizon now, while the server answers ("N playing now" on the Play page).
|
||||
playing: Option<u64>,
|
||||
tx: Sender<Msg>,
|
||||
@@ -307,6 +310,7 @@ impl Launcher {
|
||||
friend_focus: cx.focus_handle(),
|
||||
joining: None,
|
||||
collection: collection::Collection::load(),
|
||||
agents: agents_page::AgentsUi::default(),
|
||||
playing: None,
|
||||
tx,
|
||||
rx,
|
||||
@@ -2433,36 +2437,6 @@ impl Launcher {
|
||||
};
|
||||
let mono = |s: String| div().font_family(theme::MONO).child(s).into_any_element();
|
||||
let plain = |s: &str| div().child(s.to_string()).into_any_element();
|
||||
let agents = plate(&t)
|
||||
.flex()
|
||||
.flex_col()
|
||||
.gap(px(10.))
|
||||
.p(px(24.))
|
||||
.text_size(px(theme::UI.px))
|
||||
.line_height(px(21.))
|
||||
.child(
|
||||
text(theme::HEADING)
|
||||
.text_color(t.ink)
|
||||
.child("Use from the command line or AI agents"),
|
||||
)
|
||||
.child(div().max_w(px(600.)).text_color(t.muted).child(
|
||||
"The launcher is also a command-line tool and an MCP server. Everything here works from a terminal, or from an agent such as Claude Code:",
|
||||
))
|
||||
.child(
|
||||
text(theme::CAPTION)
|
||||
.font_family(theme::MONO)
|
||||
.text_color(t.ink)
|
||||
.child("claude mcp add horizon -- horizon-launcher mcp"),
|
||||
)
|
||||
.child(
|
||||
div()
|
||||
.id("readme")
|
||||
.text_color(t.accent)
|
||||
.cursor_pointer()
|
||||
.hover(|s| s.opacity(0.8))
|
||||
.child("Commands and tools, in the README")
|
||||
.on_click(|_, _, cx| cx.open_url(backend::README_URL)),
|
||||
);
|
||||
let (accounts, n) = self.account_rows(cx);
|
||||
let appearance = segments(
|
||||
"appearance",
|
||||
@@ -2546,6 +2520,8 @@ impl Launcher {
|
||||
))
|
||||
.child(group("Game", "gamepad"))
|
||||
.child(self.game_args_row(n + 4, cx))
|
||||
.child(group("AI", "terminal"))
|
||||
.child(self.no_ai_row(n + 4, cx))
|
||||
.child(group("About", "info-box"))
|
||||
.child(index_row(n + 5, "Horizon", Some(plain(&horizon)), horizon_action, &t))
|
||||
.child(index_row(
|
||||
@@ -2595,7 +2571,7 @@ impl Launcher {
|
||||
}),
|
||||
)
|
||||
.child(self.collection_section(cx))
|
||||
.child(agents)
|
||||
.children(self.agents_section(cx))
|
||||
}
|
||||
|
||||
/// Settings' Game arguments row: the extra arguments the game starts with, kept in
|
||||
|
||||
@@ -122,6 +122,8 @@ def no_ai_scenario(launcher, env, home):
|
||||
config = json.loads(run('agent-config', '--json').stdout)
|
||||
assert config['server']['args'] == ['mcp'] and len(config['clients']) == 4, config
|
||||
assert 'agent-config' in run('--help').stdout
|
||||
test = json.loads(run('agent-config', '--test', '--json').stdout)
|
||||
assert test['answered'] and test['tools'] > 100, test
|
||||
m = Mcp(launcher, env)
|
||||
m.rpc('initialize', {'protocolVersion': '2025-06-18', 'capabilities': {},
|
||||
'clientInfo': {'name': 'launcher_mcp_e2e', 'version': '1'}})
|
||||
|
||||
Reference in New Issue
Block a user