merge-fwe: FW16 E6: AgentsPage, the Agents page of Preferences over the agent settings in the draft (launcher switch line, link status, Control Port, folders through PathSetting, closed-app choice)

This commit is contained in:
aiongg
2026-11-16 12:47:42 +00:00
parent 6e7c1d4e7c
commit 42be2bc26c
5 changed files with 363 additions and 1 deletions
+173
View File
@@ -0,0 +1,173 @@
//! `AgentsPage`: the Agents page of Preferences, over the agent settings in the Preferences draft.
#[cfg(feature = "screen-testing")]
mod stories;
mod words;
pub use words::AgentsWords;
use craft_behavior::NumberCodec;
use craft_host::{PickId, PickRequest};
use craft_theme::variant::Tone;
use craft_ui::choice::Checkbox;
use craft_ui::contract::{Bind, Entry, FieldLayout, NoValue, Outcome, Props as _, Show as _, ShowContainer as _};
use craft_ui::display::{Shade, Text};
use craft_ui::form::{Field, Help};
use craft_ui::layout_components::Stack;
use craft_ui::notices::{Notice, NoticeLayout};
use craft_ui::patterns::preferences::{PathSetting, SettingsDraft};
use craft_ui::pickers::Select;
use craft_ui::runtime::env::{Env, Label};
use craft_ui::text::NumberField;
use egui::{Response, Ui};
use crate::agents::{AgentLinkStatus, AgentSettings, WhenAppClosed};
/// The purpose the folder picks are filed under.
const PICK_PURPOSE: &str = "agents";
/// What the page reported this pass.
#[derive(Debug)]
#[non_exhaustive]
pub struct AgentsPageOutput {
/// The page's response.
pub response: Response,
/// The draft changed this pass (the window's Apply becomes enabled).
pub changed: bool,
/// A folder row's Browse filed this pick through the host's file service; its answer lands in the draft.
pub browsing: Option<PickId>,
}
impl Outcome for AgentsPageOutput {
type Value = NoValue;
fn response(&self) -> &Response {
&self.response
}
}
/// The Agents page of Preferences, drawn whole by the app as a custom page (`SettingsDocument::custom_page`) over the
/// [`AgentSettings`] saved under `page` (`"integrations"`): the keys `<page>.controlPort`, `<page>.readRoot`,
/// `<page>.writeRoot`, `<page>.whenAppClosed` and `<page>.allowAgentControl`. Each edit writes only its own key into
/// the draft, so Apply writes just that setting.
///
/// With the suite's `AI-MCP` flag, top to bottom: the line naming the ArtCraft Launcher's switch (the page has none of
/// its own), the link's status (the launch options manage it; its problem as an error; the port agents connect on; or
/// off), Control Port with its help, the two folders agents may open from and save to (typed, or picked with Browse…
/// through the host's file service, [`PathSetting`]), and what the app's CLI does while the app is closed. Without the
/// flag: Allow Agent Control and Control Port, the settings the app had before the switch. Labels name the app by the
/// host's app name.
#[must_use = "show the page with `show`"]
#[derive(craft_ui::contract::Pattern, craft_ui::contract::Props)]
pub struct AgentsPage<'a> {
page: &'a str,
draft: &'a mut SettingsDraft,
status: &'a AgentLinkStatus,
/// The suite's `AI-MCP` flag is on: the launcher's switch decides, and the page shows the folders and the closed-app
/// choice.
#[prop]
mcp_flag: bool,
}
impl<'a> AgentsPage<'a> {
/// The page over the settings under `page` in the Preferences `draft`, showing the link's `status`.
pub fn new(page: &'a str, draft: &'a mut SettingsDraft, status: &'a AgentLinkStatus) -> Self {
AgentsPage { page, draft, status, mcp_flag: false }
}
/// Shows the page.
pub fn show(self, ui: &mut Ui) -> AgentsPageOutput {
let AgentsPage { page, draft, status, mcp_flag } = self;
let env = Env::of(ui);
let words = env.words::<AgentsWords>();
let units = env.units();
let app = env.host().map_or("", |host| host.app().name);
let key = |name: &str| format!("{page}.{name}");
let defaults = AgentSettings::default();
let mut changed = false;
let mut browsing = None;
let shown = Stack::new().show(ui, |ui, _| {
if mcp_flag {
Text::new(words.intro.clone()).shade(Shade::Muted).show(ui);
status_line(ui, &words, status, app);
} else {
let allow_key = key("allowAgentControl");
let allowed = draft.get(&allow_key).unwrap_or(defaults.allow_agent_control);
let mut next = None;
Field::new(words.allow_agent_control.clone()).id_salt("allow").layout(FieldLayout::After).show(ui, |ui, _| {
next = Checkbox::new(Bind::given(allowed)).show(ui).events.landed().cloned();
});
if let Some(next) = next.filter(|next| *next != allowed) {
draft.set(&allow_key, &next);
changed = true;
}
}
let port_key = key("controlPort");
let port = draft.get::<i64>(&port_key).unwrap_or(i64::from(defaults.control_port));
let mut next = None;
let mut field = Field::new(words.control_port.clone()).id_salt("port");
if mcp_flag {
field = field.help(Help::Text(words.port_hint.clone().into()));
}
field.show(ui, |ui, _| {
let number = NumberField::new(words.control_port.clone(), Bind::given(Some(port as f64)))
.codec(NumberCodec::new(units.reader(None), 0))
.range(0.0..=f64::from(u16::MAX))
.step(1.0);
next = number.show(ui).edit.events.landed().cloned().flatten();
});
if let Some(next) = next.map(|v| v.round() as i64).filter(|next| *next != port) {
draft.set(&port_key, &next);
changed = true;
}
if !mcp_flag {
return;
}
for (name, label) in [("readRoot", &words.read_root), ("writeRoot", &words.write_root)] {
let folder_key = key(name);
let out = PathSetting::new(label.clone(), &folder_key, draft, PickRequest::folder(PICK_PURPOSE)).placeholder(words.none.clone()).show(ui);
changed |= out.changed;
browsing = browsing.or(out.browsing);
}
let closed_key = key("whenAppClosed");
let current = draft.get::<String>(&closed_key).and_then(|name| WhenAppClosed::parse(&name)).unwrap_or(defaults.when_app_closed);
let choices: Vec<Entry<WhenAppClosed>> = WhenAppClosed::ALL
.into_iter()
.map(|choice| {
let label: Label = match choice {
WhenAppClosed::Launch => words.launch.fill(&[("app", app)]).into(),
WhenAppClosed::Headless => words.headless.clone().into(),
WhenAppClosed::Error => words.ask.fill(&[("app", app)]).into(),
};
Entry::new(choice, label)
})
.collect();
let label: Label = words.when_closed.fill(&[("app", app)]).into();
let mut picked = None;
Field::new(label.clone()).id_salt("closed").show(ui, |ui, _| {
picked = Select::new(label.clone(), Bind::given(current), &choices).id_salt("closed").show(ui).value().copied();
});
if let Some(picked) = picked.filter(|picked| *picked != current) {
draft.set(&closed_key, &picked.name());
changed = true;
}
});
AgentsPageOutput { response: shown.output, changed, browsing }
}
}
/// One line on where the link stands: the launch options manage it, its problem, the port agents connect on, or off.
fn status_line(ui: &mut Ui, words: &AgentsWords, status: &AgentLinkStatus, app: &str) {
if status.launch_flags {
Text::new(words.managed.clone()).shade(Shade::Muted).show(ui);
} else if let Some(problem) = &status.problem {
Notice::new(Tone::Bad, Label::from(words.problem(problem, app))).layout(NoticeLayout::Inline).show(ui);
} else if let Some(port) = status.port {
Text::new(words.listening.fill(&[("port", &port.to_string())])).show(ui);
} else {
Text::new(words.off.clone()).shade(Shade::Faint).show(ui);
}
}
@@ -0,0 +1,42 @@
//! Stories of the Agents page.
use super::AgentsPage;
use crate::agents::{AgentLinkStatus, LinkProblem};
use craft_ui::patterns::preferences::SettingsDraft;
use craft_ui::testing::{Drive, StoryData, StoryOutput, story};
use egui::Ui;
fn draft() -> SettingsDraft {
let mut draft = SettingsDraft::default();
draft.set("integrations.controlPort", &0_i64);
draft.set("integrations.readRoot", &"/photos/agents");
draft
}
fn status(port: Option<u16>, problem: Option<LinkProblem>) -> AgentLinkStatus {
AgentLinkStatus { port, launch_flags: false, problem }
}
#[story(AgentsPage<'static>, covers = [Default], drive = Drive::Never)]
fn agents_page_listening(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let status = status(Some(4321), None);
AgentsPage::new("integrations", data.value("listening", draft()), &status).mcp_flag(true).show(ui).into()
}
#[story(AgentsPage<'static>, covers = [], drive = Drive::Never)]
fn agents_page_off(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let status = status(None, None);
AgentsPage::new("integrations", data.value("off", draft()), &status).mcp_flag(true).show(ui).into()
}
#[story(AgentsPage<'static>, covers = [], drive = Drive::Never)]
fn agents_page_problem(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let status = status(None, Some(LinkProblem::Listen { port: 7878, error: "Address already in use".into() }));
AgentsPage::new("integrations", data.value("problem", draft()), &status).mcp_flag(true).show(ui).into()
}
#[story(AgentsPage<'static>, covers = [], drive = Drive::Never)]
fn agents_page_without_the_flag(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let status = status(None, None);
AgentsPage::new("integrations", data.value("legacy", draft()), &status).show(ui).into()
}
+50
View File
@@ -0,0 +1,50 @@
//! `AgentsWords`: every user-visible word of the Agents page (`agents.*`).
use crate::agents::LinkProblem;
craft_ui::words! {
/// The Agents page's words, English by default. `{app}` is the app's name, `{port}` a port number and `{error}` the
/// system's reason.
#[non_exhaustive]
pub struct AgentsWords {
/// The line over the page: where the switch is.
intro: "agents.intro" = "AI apps such as Claude can open, edit and save documents in this window while ArtCraft Launcher › Settings › AI agents › Let AI agents use Craft apps is on. Only programs on this computer can connect.";
/// The status while the launch options run the control server.
managed: "agents.managed" = "Managed by the launch options (--control).";
/// The status while agents can connect.
listening: template "agents.listening" = "Agents can connect on 127.0.0.1:{port}.";
/// The status while agents can't connect and nothing went wrong.
off: "agents.off" = "Off: turn on AI agents in ArtCraft Launcher › Settings › AI agents.";
control_port: "agents.controlPort" = "Control Port";
/// Help under the Control Port field.
port_hint: "agents.portHint" = "0 picks a free port; AI apps find it by themselves";
read_root: "agents.readRoot" = "Folder agents can open from";
write_root: "agents.writeRoot" = "Folder agents can save to";
/// An empty folder field.
none: "agents.none" = "None";
when_closed: template "agents.whenClosed" = "When {app} is closed";
launch: template "agents.launch" = "Open {app}";
headless: "agents.headless" = "Work without a window";
ask: template "agents.ask" = "Ask to open {app}";
allow_agent_control: "agents.allowAgentControl" = "Allow Agent Control";
not_allowed: "agents.notAllowed" = "Agents can't connect: Allow Agent Control is off in the preferences file.";
no_settings_folder: template "agents.noSettingsFolder" = "Agents can't connect: {app} has no settings folder (no home folder).";
token_file: template "agents.tokenFile" = "Agents can't connect: the token file could not be written: {error}";
listen: template "agents.listen" = "Couldn't listen on 127.0.0.1:{port}: {error}";
publish: template "agents.publish" = "Couldn't publish the agent connection: {error}";
}
}
impl AgentsWords {
/// The sentence for `problem`; `app` is the app's name. The app's own note is shown as it wrote it.
pub fn problem(&self, problem: &LinkProblem, app: &str) -> String {
match problem {
LinkProblem::NotAllowed => self.not_allowed.as_str().to_owned(),
LinkProblem::NoSettingsFolder => self.no_settings_folder.fill(&[("app", app)]),
LinkProblem::TokenFile(error) => self.token_file.fill(&[("error", error)]),
LinkProblem::Listen { port, error } => self.listen.fill(&[("port", &port.to_string()), ("error", error)]),
LinkProblem::Publish(error) => self.publish.fill(&[("error", error)]),
LinkProblem::App(note) => note.clone(),
}
}
}
+3
View File
@@ -1,5 +1,8 @@
//! The automation widgets. Every target.
//!
//! - [`actions`]: the Actions panel.
//! - [`agents`]: the Agents page of Preferences (desktop, feature `agents`).
pub mod actions;
#[cfg(all(feature = "agents", not(target_arch = "wasm32")))]
pub mod agents;
+95 -1
View File
@@ -2,6 +2,7 @@
//! Agents page.
use std::net::TcpListener;
use std::path::PathBuf;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::time::Duration;
@@ -10,8 +11,15 @@ use craft_automation::agents::{
AgentLink, AgentSettings, AgentSwitch, CONNECTION_FILE, Connection, LinkProblem, PROBE_TIMEOUT, TOKEN_FILE, agents_allowed, probe, read_connection,
remove_connection, remove_stale_connection, write_connection,
};
use craft_automation::agents::AgentLinkStatus;
use craft_automation::server;
use craft_host::Wake;
use craft_automation::ui::agents::AgentsPage;
use craft_host::{AppInfo, Host, PickId, Picked, ScriptedFiles, Wake};
use craft_ui::contract::Role;
use craft_ui::patterns::preferences::SettingsDraft;
use craft_ui::testing::Fixture;
use std::cell::{Cell, RefCell};
use std::rc::Rc;
use craft_ui::runtime::motion;
use craft_ui::runtime::windows::WindowHost;
use craft_ui::testing::trial;
@@ -297,3 +305,89 @@ fn from_launch_reports_the_launch_flags() {
assert_eq!(link.status().port, Some(port));
assert_eq!(serde_json::to_value(link.status()).unwrap(), serde_json::json!({"port": port, "launchFlags": true, "error": null}));
}
/// The page over a draft, in a fixture whose host is named `"Studio"` and answers picks when the test says.
struct Page {
fixture: Fixture,
draft: Rc<RefCell<SettingsDraft>>,
files: Arc<ScriptedFiles>,
browsing: Rc<Cell<Option<PickId>>>,
}
fn page(mcp_flag: bool, status: AgentLinkStatus) -> Page {
let files = Arc::new(ScriptedFiles::held());
let draft = Rc::new(RefCell::new(SettingsDraft::default()));
let browsing = Rc::new(Cell::new(None));
let (held, issued) = (Rc::clone(&draft), Rc::clone(&browsing));
let mut fixture = Fixture::new(move |ui| {
let out = AgentsPage::new("integrations", &mut held.borrow_mut(), &status).mcp_flag(mcp_flag).show(ui);
if out.browsing.is_some() {
issued.set(out.browsing);
}
});
fixture.host(Arc::new(Host::builder(AppInfo { id: "studio", name: "Studio", version: "1.0" }).files(files.clone()).build()));
fixture.settle();
Page { fixture, draft, files, browsing }
}
fn shows(fixture: &Fixture, text: &str) -> bool {
fixture.by_label(text).is_some()
}
/// With the flag the page names the launcher's switch, has no switch of its own, and says where the link stands.
#[trial]
fn with_the_flag_the_page_points_to_the_launcher() {
let intro_part = "ArtCraft Launcher › Settings › AI agents › Let AI agents use Craft apps";
let off = page(true, AgentLinkStatus::default());
let intro = off.fixture.tree().keys().into_iter().filter_map(|node| off.fixture.tree().name_of(node).map(str::to_owned)).find(|name| name.contains(intro_part));
assert!(intro.is_some(), "the intro names the launcher's switch");
assert!(shows(&off.fixture, "Off: turn on AI agents in ArtCraft Launcher › Settings › AI agents."));
assert!(shows(&off.fixture, "Folder agents can open from") && shows(&off.fixture, "Folder agents can save to"));
assert!(!shows(&off.fixture, "Allow Agent Control"), "no switch of its own");
assert!(!shows(&off.fixture, "Let AI agents connect (MCP)"));
let on = page(true, AgentLinkStatus { port: Some(4321), ..AgentLinkStatus::default() });
assert!(shows(&on.fixture, "Agents can connect on 127.0.0.1:4321."));
}
/// Without the flag only the settings the app had before the switch show.
#[trial]
fn without_the_flag_only_the_earlier_settings_show() {
let legacy = page(false, AgentLinkStatus::default());
assert!(shows(&legacy.fixture, "Allow Agent Control") && shows(&legacy.fixture, "Control Port"));
assert!(!shows(&legacy.fixture, "Folder agents can open from"));
assert!(!shows(&legacy.fixture, "Off: turn on AI agents in ArtCraft Launcher › Settings › AI agents."));
}
/// Browse on the open-from folder asks the host for a folder; the answer lands in that key of the draft only.
#[trial]
fn browse_puts_the_chosen_folder_in_the_draft() {
let mut page = page(true, AgentLinkStatus::default());
let browse: Vec<_> =
page.fixture.by_role(Role::BUTTON).into_iter().filter(|button| page.fixture.tree().name_of(button.node) == Some("Browse…")).collect();
assert_eq!(browse.len(), 2, "one Browse per folder");
page.fixture.click(&browse[0]);
page.fixture.settle();
let id = page.browsing.get().expect("Browse filed a pick");
assert!(page.files.answer_to(id, Picked::Paths(vec![PathBuf::from("/work/in")])), "the pick is open");
page.fixture.idle(3);
let draft = page.draft.borrow();
assert_eq!(draft.get::<String>("integrations.readRoot").as_deref(), Some("/work/in"));
assert_eq!(draft.get::<String>("integrations.writeRoot"), None, "the other folder is untouched");
}
/// The closed-app choice names the host's app, and a pick writes its saved name.
#[trial]
fn the_closed_app_choice_names_the_app() {
let mut page = page(true, AgentLinkStatus::default());
assert!(shows(&page.fixture, "When Studio is closed"));
let field = page.fixture.by_role(Role::COMBO_BOX).first().copied().expect("the choice shows");
assert_eq!(page.fixture.tree().value_of(field.node), Some("Open Studio"));
page.fixture.click(&field);
page.fixture.idle(3);
assert!(shows(&page.fixture, "Ask to open Studio"));
let headless = page.fixture.by_label("Work without a window").expect("the menu lists the choices");
page.fixture.click(&headless);
page.fixture.idle(3);
assert_eq!(page.draft.borrow().get::<String>("integrations.whenAppClosed").as_deref(), Some("headless"));
}