diff --git a/assets/locales/pending/agent-custom-instructions.json b/assets/locales/pending/agent-custom-instructions.json new file mode 100644 index 000000000..82a3705f5 --- /dev/null +++ b/assets/locales/pending/agent-custom-instructions.json @@ -0,0 +1,26 @@ +{ + "en": { + "ai.prefs.instructions": "Custom instructions", + "ai.prefs.instructions_note": "Sent to the agent at the start of every chat, after SolidCraft's own instructions: how you like to work, rules to keep to. A change applies from the next chat (Connect or New chat)." + }, + "ar": { + "ai.prefs.instructions": "تعليمات مخصصة", + "ai.prefs.instructions_note": "تُرسَل إلى الوكيل في بداية كل محادثة، بعد تعليمات SolidCraft الخاصة: طريقتك المفضلة في العمل والقواعد التي يجب الالتزام بها. يسري أي تغيير من المحادثة التالية (اتصال أو محادثة جديدة)." + }, + "he": { + "ai.prefs.instructions": "הוראות מותאמות אישית", + "ai.prefs.instructions_note": "נשלחות לסוכן בתחילת כל צ'אט, אחרי ההוראות של SolidCraft עצמה: דרך העבודה המועדפת עליך וכללים שיש להקפיד עליהם. שינוי חל מהצ'אט הבא (התחברות או צ'אט חדש)." + }, + "ja": { + "ai.prefs.instructions": "カスタム指示", + "ai.prefs.instructions_note": "各チャットの開始時に、SolidCraft 自身の指示の後に続けてエージェントへ送られます。作業の進め方や守ってほしいルールを書いてください。変更は次のチャット(接続または新しいチャット)から適用されます。" + }, + "vi": { + "ai.prefs.instructions": "Hướng dẫn tùy chỉnh", + "ai.prefs.instructions_note": "Được gửi cho agent khi bắt đầu mỗi cuộc trò chuyện, sau hướng dẫn riêng của SolidCraft: cách bạn muốn làm việc, các quy tắc cần tuân theo. Thay đổi có hiệu lực từ cuộc trò chuyện tiếp theo (Kết nối hoặc Cuộc trò chuyện mới)." + }, + "zh": { + "ai.prefs.instructions": "自定义指令", + "ai.prefs.instructions_note": "在每次对话开始时发送给代理,位于 SolidCraft 自身的指令之后:你喜欢的工作方式、需要遵守的规则。更改从下一次对话(连接或新对话)起生效。" + } +} diff --git a/crates/ui-egui/src/agent_chat/acp.rs b/crates/ui-egui/src/agent_chat/acp.rs index 1584f7cf5..8d7760aa7 100644 --- a/crates/ui-egui/src/agent_chat/acp.rs +++ b/crates/ui-egui/src/agent_chat/acp.rs @@ -235,6 +235,21 @@ each stage compare `measure` with them. Prefer one `batch` over many small calls the chat, and each message allows a limited number of changes. Don't use shell or file tools: work through the SolidCraft tools. \ Keep answers short."; +/// The most of the user's custom instructions (#8220) a session gets, in characters: the +/// Preferences field takes no more, and a longer text from an edited settings file is cut here. +pub const INSTRUCTIONS_LIMIT: usize = 4000; + +/// [`SYSTEM_NOTE`] with the user's custom instructions (#8220) after it. Blank instructions leave +/// the note as it is. +pub fn system_note(instructions: &str) -> String { + let text: String = instructions.trim().chars().take(INSTRUCTIONS_LIMIT).collect(); + let text = text.trim_end(); + if text.is_empty() { + return SYSTEM_NOTE.to_string(); + } + format!("{SYSTEM_NOTE}\n\nThe user's custom instructions, set in SolidCraft's preferences:\n{text}") +} + /// The Claude Code adapter's own tools that reach the computer rather than the design: turned off /// for the session (`_meta.claudeCode.options.disallowedTools`), so it works through SolidCraft's. pub const CLAUDE_DISALLOWED_TOOLS: &[&str] = @@ -242,11 +257,12 @@ pub const CLAUDE_DISALLOWED_TOOLS: &[&str] = /// The `session/new` parameters. `init` is the agent's `initialize` reply: agents read the system /// note from different places (#9811), and the standard field may only go to an agent offering it. -pub fn session_new_params(cwd: &std::path::Path, bridge: Option<&McpBridge>, init: &Value) -> Value { +/// `note` is the system note ([`system_note`]). +pub fn session_new_params(cwd: &std::path::Path, bridge: Option<&McpBridge>, init: &Value, note: &str) -> Value { let servers: Vec = bridge.map(McpBridge::to_json).into_iter().collect(); let mut meta = json!({ // The Claude adapter's own key, for its versions without the standard field. - "systemPrompt": {"append": SYSTEM_NOTE}, + "systemPrompt": {"append": note}, // Hosts may opt a session out of "bypass permissions" (the Claude adapter reads it): // every tool call the agent asks about reaches the panel. // Its own shell and file tools are off: the agent works through SolidCraft's tools. @@ -255,7 +271,7 @@ pub fn session_new_params(cwd: &std::path::Path, bridge: Option<&McpBridge>, ini if takes_antigravity_note(init) && let Some(meta) = meta.as_object_mut() { - meta.insert("antigravity".into(), json!({"systemPrompt": {"append": SYSTEM_NOTE}})); + meta.insert("antigravity".into(), json!({"systemPrompt": {"append": note}})); } let mut params = json!({ "cwd": cwd.to_string_lossy(), @@ -265,7 +281,7 @@ pub fn session_new_params(cwd: &std::path::Path, bridge: Option<&McpBridge>, ini if takes_standard_note(init) && let Some(params) = params.as_object_mut() { - params.insert("systemPrompt".into(), json!({"mode": "append", "content": [{"type": "text", "text": SYSTEM_NOTE}]})); + params.insert("systemPrompt".into(), json!({"mode": "append", "content": [{"type": "text", "text": note}]})); } params } @@ -770,29 +786,31 @@ mod tests { #[test] fn the_session_gets_the_bridged_mcp_server_without_a_token_or_any_path() { let b = McpBridge { cli: "/opt/solidcraft/solidcraft-cli".into(), port: 41234 }; - let p = session_new_params(std::path::Path::new("/home/u/designs"), Some(&b), &json!({})); + let p = session_new_params(std::path::Path::new("/home/u/designs"), Some(&b), &json!({}), SYSTEM_NOTE); let s = &p["mcpServers"][0]; assert_eq!(s["name"], BRIDGE_NAME); assert_eq!(s["args"], json!(["mcp", "--connect", "127.0.0.1:41234"])); let text = p.to_string(); assert!(!text.contains("allow-any-path") && !text.contains("TOKEN") && !text.contains("token"), "{text}"); assert!(p["_meta"]["claudeCode"]["options"]["disallowedTools"].as_array().is_some_and(|t| t.iter().any(|x| x == "Bash"))); - assert_eq!(session_new_params(std::path::Path::new("/tmp"), None, &json!({}))["mcpServers"], json!([])); + assert_eq!(session_new_params(std::path::Path::new("/tmp"), None, &json!({}), SYSTEM_NOTE)["mcpServers"], json!([])); } /// #9811: the note goes by the routes an agent's `initialize` reply offers, and the standard /// field never goes to an agent that doesn't offer it, as the protocol asks. #[test] fn the_system_note_takes_every_route_the_agent_offers() { - let params = |init: Value| session_new_params(std::path::Path::new("/tmp"), None, &init); - let standard = json!({"mode": "append", "content": [{"type": "text", "text": SYSTEM_NOTE}]}); + // With the user's custom instructions (#8220), which go wherever the note goes. + let note = system_note("Sketch on XZ with explicit plane vectors."); + let params = |init: Value| session_new_params(std::path::Path::new("/tmp"), None, &init, ¬e); + let standard = json!({"mode": "append", "content": [{"type": "text", "text": note}]}); let offers_standard = params(json!({"agentCapabilities": {"sessionCapabilities": {"systemPrompt": {}}}})); assert_eq!(offers_standard["systemPrompt"], standard); assert!(offers_standard["_meta"].get("antigravity").is_none()); let offers_antigravity = params(json!({"agentCapabilities": {"_meta": {"antigravity": {"systemPrompt": {"append": true}}}}})); - assert_eq!(offers_antigravity["_meta"]["antigravity"]["systemPrompt"]["append"], SYSTEM_NOTE); + assert_eq!(offers_antigravity["_meta"]["antigravity"]["systemPrompt"]["append"], note); assert!(offers_antigravity.get("systemPrompt").is_none()); for none in [ @@ -808,11 +826,24 @@ mod tests { // Every session keeps the key older Claude adapters read, and the tools they turn off. for init in [json!({}), json!({"agentCapabilities": {"sessionCapabilities": {"systemPrompt": {}}}})] { let p = params(init); - assert_eq!(p["_meta"]["systemPrompt"]["append"], SYSTEM_NOTE); + assert_eq!(p["_meta"]["systemPrompt"]["append"], note); assert!(p["_meta"]["claudeCode"]["options"]["disallowedTools"].is_array()); } } + /// #8220: the user's custom instructions follow the note, trimmed and cut at the limit; blank + /// ones leave the note as it is. + #[test] + fn custom_instructions_follow_the_note_trimmed_and_capped() { + assert_eq!(system_note(""), SYSTEM_NOTE); + assert_eq!(system_note(" \n\t "), SYSTEM_NOTE); + let note = system_note("\n Use M3 screws.\nPrint flat side down. \n"); + assert!(note.starts_with(SYSTEM_NOTE), "{note}"); + assert!(note.ends_with("preferences:\nUse M3 screws.\nPrint flat side down."), "{note}"); + let note = system_note(&"ż".repeat(INSTRUCTIONS_LIMIT + 10)); + assert_eq!(note.chars().filter(|c| *c == 'ż').count(), INSTRUCTIONS_LIMIT); + } + /// #5546: an agent started through `wsl.exe` gets the session's paths as WSL shows them. #[test] fn an_agent_inside_wsl_gets_wsl_paths() { @@ -833,7 +864,7 @@ mod tests { assert_eq!(wsl(r"\\server\share\x"), r"\\server\share\x"); let b = McpBridge { cli: r"C:\Program Files\SolidCraft\solidcraft-cli.exe".into(), port: 41234 }; - let p = session_new_params(&wsl_path(std::path::Path::new(r"C:\Users\u\work")), Some(&b.in_wsl()), &json!({})); + let p = session_new_params(&wsl_path(std::path::Path::new(r"C:\Users\u\work")), Some(&b.in_wsl()), &json!({}), SYSTEM_NOTE); assert_eq!(p["cwd"], "/mnt/c/Users/u/work"); assert_eq!(p["mcpServers"][0]["command"], "/mnt/c/Program Files/SolidCraft/solidcraft-cli.exe"); assert_eq!(p["mcpServers"][0]["args"], json!(["mcp", "--connect", "127.0.0.1:41234"])); diff --git a/crates/ui-egui/src/agent_chat/acp_client.rs b/crates/ui-egui/src/agent_chat/acp_client.rs index 7255dab25..53b765d68 100644 --- a/crates/ui-egui/src/agent_chat/acp_client.rs +++ b/crates/ui-egui/src/agent_chat/acp_client.rs @@ -35,6 +35,8 @@ pub struct AcpBackend { bridge: Option, /// The agent's `initialize` reply: which routes the system note can take into a session. init: Value, + /// The system note the next session gets ([`acp::system_note`]). + note: String, next_id: u64, pending: HashMap, session: Option, @@ -64,6 +66,7 @@ impl AcpBackend { cwd, bridge, init: Value::Null, + note: acp::SYSTEM_NOTE.to_string(), next_id: 0, pending: HashMap::new(), session: None, @@ -91,7 +94,7 @@ impl AcpBackend { fn new_session(&mut self) { self.config_pending = None; self.pending.retain(|_, request| *request != Pending::SetConfig); - let params = acp::session_new_params(&self.cwd, self.bridge.as_ref(), &self.init); + let params = acp::session_new_params(&self.cwd, self.bridge.as_ref(), &self.init, &self.note); self.request(Pending::SessionNew, "session/new", params); } @@ -288,6 +291,10 @@ impl ChatBackend for AcpBackend { self.new_session(); } + fn set_instructions(&mut self, text: &str) { + self.note = acp::system_note(text); + } + fn answer_permission(&mut self, key: u64, option: Option<&str>) { if let Some(rpc) = self.permissions.remove(&key) { self.proc.send(&acp::permission_reply(rpc, option)); @@ -362,7 +369,7 @@ pub fn test_agent(argv: &[String], cwd: &std::path::Path) -> Result, /// The conversation in the endpoint's shape, without the system note (sent separately). history: Vec, + /// The system note every request carries ([`super::acp::system_note`]). + note: String, /// OpenCode Go's stable session ID for this chat (one per chat, not per request). session_id: String, /// Thought signatures of Gemini function-call parts, by kept call id, for the @@ -828,6 +837,7 @@ impl Worker { // the endpoint's, not the user's, and must not silently override the choice. self.no_reasoning.set(false); } + Cmd::SetInstructions(text) => self.note = super::acp::system_note(&text), Cmd::NewChat => { self.history.clear(); // A new conversation gets a fresh Go session ID for routing and caching. @@ -1135,7 +1145,7 @@ impl Worker { match protocol { GoProtocol::Chat => self.body(), GoProtocol::Responses => { - let mut body = json!({"model": self.cfg.model, "input": go_responses_input(super::acp::SYSTEM_NOTE, &self.history)}); + let mut body = json!({"model": self.cfg.model, "input": go_responses_input(&self.note, &self.history)}); if let Some(tools) = self.go_tools(protocol) { body["tools"] = tools; } @@ -1145,7 +1155,7 @@ impl Worker { let mut body = json!({ "model": self.cfg.model, "max_tokens": ANTHROPIC_MAX_TOKENS, - "system": super::acp::SYSTEM_NOTE, + "system": self.note, "messages": go_anthropic_messages(&self.history), }); if let Some(tools) = self.go_tools(protocol) { @@ -1155,7 +1165,7 @@ impl Worker { } GoProtocol::Gemini => { let mut body = json!({"contents": go_gemini_contents(&self.history, &self.gemini_sigs.borrow())}); - body["systemInstruction"] = json!({"parts": [{"text": super::acp::SYSTEM_NOTE}]}); + body["systemInstruction"] = json!({"parts": [{"text": self.note}]}); if let Some(tools) = self.go_tools(protocol) { body["tools"] = tools; } @@ -1180,7 +1190,7 @@ impl Worker { match self.cfg.protocol { Protocol::OpenAi => { let mut messages = Vec::with_capacity(self.history.len() + 1); - messages.push(json!({"role": "system", "content": super::acp::SYSTEM_NOTE})); + messages.push(json!({"role": "system", "content": self.note})); messages.extend(self.history.iter().cloned()); let mut body = json!({"model": self.cfg.model, "messages": messages}); if let Some(effort) = self.reasoning_effort() { @@ -1200,7 +1210,7 @@ impl Worker { let mut body = json!({ "model": self.cfg.model, "max_tokens": ANTHROPIC_MAX_TOKENS, - "system": super::acp::SYSTEM_NOTE, + "system": self.note, "messages": &self.history, }); if !self.tools.is_empty() { @@ -1998,7 +2008,8 @@ mod tests { } /// New chat resets the model's history to the system note: the next request carries nothing - /// of the conversation before it. + /// of the conversation before it. The note carries the custom instructions set for each + /// conversation (#8220): the first one's, then none after they were cleared. #[test] fn a_new_chat_resets_the_history_to_the_system_note() { let seen = Arc::new(std::sync::Mutex::new(Vec::::new())); @@ -2033,12 +2044,16 @@ mod tests { std::thread::sleep(Duration::from_millis(10)); } }; + b.set_instructions("Use M3 screws."); run(&mut b, &|b| b.prompt(&[PromptPart::Text("one".into())]), 2); + b.set_instructions(""); run(&mut b, &|b| b.new_session(), 1); run(&mut b, &|b| b.prompt(&[PromptPart::Text("two".into())]), 1); let sent = seen.lock().unwrap(); + assert_eq!(sent[0]["messages"][0]["content"], super::super::acp::system_note("Use M3 screws.")); let roles: Vec<&str> = sent[1]["messages"].as_array().unwrap().iter().map(|m| m["role"].as_str().unwrap_or("")).collect(); assert_eq!(roles, ["system", "user"]); + assert_eq!(sent[1]["messages"][0]["content"], super::super::acp::SYSTEM_NOTE); assert_eq!(sent[1]["messages"][1]["content"], "two"); b.shutdown(true); } @@ -2767,6 +2782,7 @@ mod tests { tools: vec![json!({"type": "function", "function": {"name": "measure"}})], tool_names: vec!["measure".into()], history: vec![json!({"role": "user", "content": "hi"})], + note: super::super::acp::SYSTEM_NOTE.to_string(), session_id: "test-session".to_string(), gemini_sigs: Default::default(), events, diff --git a/crates/ui-egui/src/agent_chat/backend.rs b/crates/ui-egui/src/agent_chat/backend.rs index 51d88f0e4..ae24a7167 100644 --- a/crates/ui-egui/src/agent_chat/backend.rs +++ b/crates/ui-egui/src/agent_chat/backend.rs @@ -144,6 +144,9 @@ pub trait ChatBackend { /// Start a fresh conversation on the running backend (no restart); [`Event::Ready`] follows. /// A message being answered is cancelled first. fn new_session(&mut self); + /// The user's custom instructions (#8220), added to the system note of every session that + /// starts after this call. The panel sets them before the first session and before New chat. + fn set_instructions(&mut self, _text: &str) {} /// Answer an [`Event::Permission`] with one of its options (`None`: cancelled). fn answer_permission(&mut self, key: u64, option: Option<&str>); /// Ask the backend to sign in by itself with one of its methods (it opens the browser). diff --git a/crates/ui-egui/src/agent_chat/mod.rs b/crates/ui-egui/src/agent_chat/mod.rs index 8ec1f9002..2dbf03d49 100644 --- a/crates/ui-egui/src/agent_chat/mod.rs +++ b/crates/ui-egui/src/agent_chat/mod.rs @@ -1041,7 +1041,8 @@ pub fn connect(app: &mut SolveApp, ctx: &egui::Context) { }, }; match started { - Ok(b) => { + Ok(mut b) => { + b.set_instructions(&app.preferences.agent_instructions); app.preferences.agent_last = entry.id.clone(); chat.backend = Some(b); chat.argv = entry.argv.clone(); @@ -1489,6 +1490,8 @@ pub fn new_chat(app: &mut SolveApp) { chat.restore_mode = Some(chat.mode.clone()).filter(|m| !m.is_empty()); chat.state = Some(State::Starting); if let Some(b) = chat.backend.as_mut() { + // Instructions edited since the last session apply from this one on. + b.set_instructions(&app.preferences.agent_instructions); b.new_session(); } } @@ -2361,7 +2364,8 @@ fn set_config_option_checked(app: &mut SolveApp, id: &str, value: &str, listed_o } /// `ui.agent_chat` on the control channel (tests and screenshots): `enabled`, `command`, -/// `connect_at_start` and `open_at_start` (the launch preferences), `open`, +/// `connect_at_start` and `open_at_start` (the launch preferences), `instructions` (the custom +/// instructions, #8220), `open`, /// `side`, `minimized`, `width`, `refresh`, `connect`, `stop`, `attach` (a file's path, for the /// next message), `remove_file` (index), `send`, `attach_view`, `attach_selection`, `pick`, /// `permission` (an option id, or `"cancel"`), `approve` (`true`/`false`, the oldest held @@ -2379,6 +2383,10 @@ pub fn control(app: &mut SolveApp, ctx: &egui::Context, p: &Value) -> Result Value { if let Some(state) = state.as_object_mut() { state.insert("modelsNote".into(), json!(c.models_note)); state.insert("customModels".into(), json!(custom_models_accepted(app))); + state.insert("instructions".into(), json!(app.preferences.agent_instructions)); } state } diff --git a/crates/ui-egui/src/agent_chat/settings.rs b/crates/ui-egui/src/agent_chat/settings.rs index 0ddbdda92..5cfbfd63d 100644 --- a/crates/ui-egui/src/agent_chat/settings.rs +++ b/crates/ui-egui/src/agent_chat/settings.rs @@ -471,6 +471,7 @@ pub fn page(app: &mut SolveApp, ui: &mut egui::Ui) { } agents_section(app, ui); } + instructions_section(app, ui); panel_section(app, ui); connecting_section(app, ui); }); @@ -496,6 +497,21 @@ fn connecting_section(app: &mut SolveApp, ui: &mut egui::Ui) { }); } +/// Custom instructions (#8220): text every new chat's system note carries. +fn instructions_section(app: &mut SolveApp, ui: &mut egui::Ui) { + ui_kit::settings_section(ui, "instructions", tr("ai.prefs.instructions"), |ui| { + let id = egui::Id::new("prefs_agent_instructions"); + let text = &mut app.preferences.agent_instructions; + let response = ui_kit::text_area(ui, tr("ai.prefs.instructions"), id, text, 6, acp::INSTRUCTIONS_LIMIT); + if response.has_focus() { + // Typed text belongs to the field, not to Preferences search. + crate::prefs_search::note_key_sink(ui.ctx()); + } + crate::scenario::publish_target("prefs:agent_instructions", response.rect); + ui_kit::text(ui, tr("ai.prefs.instructions_note"), ui_kit::Text::Hint("instructions")); + }); +} + fn permissions_section(app: &mut SolveApp, ui: &mut egui::Ui) { ui_kit::settings_section(ui, "permissions", tr("ui.ai_permissions"), |ui| { let mut selected = Mode::ALL.iter().position(|mode| *mode == app.preferences.ai_permissions).unwrap_or(0); @@ -1355,7 +1371,7 @@ mod card_tests { assert!(scope_visible, "the full localized permission scope remains visible without hovering, including with AI off"); assert!(privacy_visible, "the localized privacy note remains visible without hovering, including with AI off"); let mut previous: Option = None; - for key in ["assistant_availability", "permissions", "agents", "panel", "assistant_connecting", "agent_pointer"] { + for key in ["assistant_availability", "permissions", "agents", "instructions", "panel", "assistant_connecting", "agent_pointer"] { let section = scenario::rect_of(&format!("prefs:section:{key}")).unwrap(); assert!((section.left() - body.left()).abs() <= 1.0 && (section.right() - body.right()).abs() <= 1.0); assert!((section.height() - (crate::theme::Tokens::get().control_height + crate::theme::Tokens::get().space_2)).abs() <= 1.0); diff --git a/crates/ui-egui/src/agent_chat/tests.rs b/crates/ui-egui/src/agent_chat/tests.rs index b5d362916..659a9ec96 100644 --- a/crates/ui-egui/src/agent_chat/tests.rs +++ b/crates/ui-egui/src/agent_chat/tests.rs @@ -1614,7 +1614,7 @@ done } /// #9811: an agent that offers the standard `systemPrompt` field gets the note in it, on the first -/// session and on the one New chat opens. +/// session and on the one New chat opens, with the custom instructions set before it (#8220). #[cfg(unix)] #[test] fn an_acp_agent_offering_the_standard_field_gets_the_system_note_in_every_session() { @@ -1647,6 +1647,7 @@ done } }; until(&mut app, &|a| a.agent_chat.state() == State::Ready); + app.preferences.agent_instructions = "Print flat side down.".into(); new_chat(&mut app); until(&mut app, &|a| a.agent_chat.state() == State::Ready); let sessions: Vec = std::fs::read_to_string(&log) @@ -1656,13 +1657,88 @@ done .filter(|v| v["method"] == "session/new") .collect(); assert_eq!(sessions.len(), 2); - for session in &sessions { - assert_eq!(session.pointer("/params/systemPrompt/content/0/text").and_then(Value::as_str), Some(acp::SYSTEM_NOTE)); + let notes = [acp::SYSTEM_NOTE.to_string(), acp::system_note("Print flat side down.")]; + for (session, note) in sessions.iter().zip(¬es) { + assert_eq!(session.pointer("/params/systemPrompt/content/0/text").and_then(Value::as_str), Some(note.as_str())); } disconnect(&mut app); let _ = std::fs::remove_dir_all(&dir); } +/// #8220: Preferences → AI shows the Custom instructions field; `ui.agent_chat` sets them (cut at +/// the limit) and reports them; Connect sends them in the endpoint's system note, and an edit +/// reaches the conversation New chat opens. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn custom_instructions_reach_the_system_note_of_each_new_session() { + let seen = Arc::new(std::sync::Mutex::new(Vec::::new())); + let log = seen.clone(); + let http: backend::HttpFn = Arc::new(move |r: &backend::HttpRequest| { + if r.url.ends_with("/chat/completions") { + log.lock().unwrap().push(serde_json::from_slice(r.body.as_deref().unwrap_or(b"null")).unwrap()); + return Ok((200, json!({"choices": [{"message": {"role": "assistant", "content": "ok"}}]}).to_string().into_bytes())); + } + Ok((200, b"{\"data\":[]}".to_vec())) + }); + let mut h = crate::scenario::Harness::new(); + h.app.home.open = false; + h.app.services.agent_http = Some(http); + crate::prefs::open_at(&mut h.app, crate::prefs::PAGE_ASSISTANT); + h.frames(4); + assert!(crate::scenario::rect_of("prefs:agent_instructions").is_some(), "the field is on the AI page"); + h.app.preferences.ai_features = true; + h.ctx.memory_mut(|m| m.request_focus(egui::Id::new("prefs_agent_instructions"))); + h.frames(2); + h.step(&json!({"text": "M3"})).unwrap(); + h.frames(2); + assert_eq!(h.app.preferences.agent_instructions, "M3", "typed text lands in the field"); + assert!(h.app.prefs_window.filter.is_empty(), "Preferences search does not take the typing"); + let long = "x".repeat(acp::INSTRUCTIONS_LIMIT + 5); + assert_eq!( + h.call("ui.agent_chat", json!({"instructions": long}))["result"]["instructions"].as_str().map(str::len), + Some(acp::INSTRUCTIONS_LIMIT) + ); + assert!(!h.call("ui.agent_chat", json!({"instructions": 3}))["error"].is_null()); + assert_eq!(h.call("ui.agent_chat", json!({"instructions": "Use M3 screws."}))["result"]["instructions"], "Use M3 screws."); + + h.app.preferences.agents.push(agents::AgentConfig { + id: "api-1".into(), + kind: agents::Kind::Api, + base_url: "http://localhost:11434/v1".into(), + model: "m".into(), + ..Default::default() + }); + h.app.agent_chat.agent_id = Some("api-1".into()); + let ctx = crate::fonts::test_context(); + let until = |app: &mut SolveApp, done: &dyn Fn(&SolveApp) -> bool| { + let t = std::time::Instant::now(); + while !done(app) { + assert!(t.elapsed() < std::time::Duration::from_secs(20), "timed out"); + poll(app, &ctx); + std::thread::sleep(std::time::Duration::from_millis(10)); + } + }; + let sent = |n: usize| { + let seen = seen.clone(); + move |a: &SolveApp| a.agent_chat.state() == State::Ready && seen.lock().unwrap().len() == n + }; + connect(&mut h.app, &ctx); + until(&mut h.app, &|a| a.agent_chat.state() == State::Ready); + send(&mut h.app, &ctx, "one".into()); + until(&mut h.app, &sent(1)); + // Editing the field leaves the running conversation's note alone. + h.app.preferences.agent_instructions = "Print flat side down.".into(); + send(&mut h.app, &ctx, "two".into()); + until(&mut h.app, &sent(2)); + new_chat(&mut h.app); + until(&mut h.app, &|a| a.agent_chat.state() == State::Ready); + send(&mut h.app, &ctx, "three".into()); + until(&mut h.app, &sent(3)); + let notes: Vec = seen.lock().unwrap().iter().map(|body| body["messages"][0]["content"].clone()).collect(); + assert_eq!(notes, [acp::system_note("Use M3 screws."), acp::system_note("Use M3 screws."), acp::system_note("Print flat side down.")]); + disconnect(&mut h.app); +} + fn models_reply(current: &str) -> Event { let m = |id: &str| acp::ModelInfo { id: id.into(), name: id.to_uppercase(), description: String::new() }; Event::Models { current: current.into(), available: vec![m("fast"), m("smart")] } diff --git a/crates/ui-egui/src/prefs.rs b/crates/ui-egui/src/prefs.rs index 738fc5751..cdee926a5 100644 --- a/crates/ui-egui/src/prefs.rs +++ b/crates/ui-egui/src/prefs.rs @@ -1557,6 +1557,9 @@ preference_settings! { agent_chat_window: Option<[f32; 4]> = None, PAGE_ASSISTANT; /// Changes the agent may make for one message; 0 is no limit. agent_chat_turn_limit: u32 = crate::agent_chat::gate::DEFAULT_TURN_LIMIT, PAGE_ASSISTANT; + /// Custom instructions (#8220): text the agent chat adds to its system note when a session + /// starts (`agent_chat::acp::system_note`). No page reset discards this user-authored text. + agent_instructions: String = String::new(); // ---- Sketch / selection modifier bindings (classic defaults; alternate mapping is opt-in) ---- /// Modifier that suppresses sketch auto-snap while drawing or dragging a sketch point. diff --git a/docs/agent-chat.md b/docs/agent-chat.md index 207d9d7e2..91ed744ed 100644 --- a/docs/agent-chat.md +++ b/docs/agent-chat.md @@ -428,6 +428,19 @@ The agent reaches the open design only through SolidCraft's own tools (the an attached selection (and are shown the same way), and the box is empty again afterwards. **Cancel** keeps what was picked before. +## Custom instructions + +Preferences → AI → **Custom instructions** holds your own text for the agent: how you like to +work, rules to keep to ("don't start a new design from the chat", "sketch on XZ with explicit +plane vectors"). Every chat starts with it, after SolidCraft's own note about where the agent +is, by the same route that note takes: the system prompt of an endpoint's requests, or the +session an ACP agent opens. An agent that reads neither doesn't get it. A change applies from +the next chat (**Connect** or **New chat**), not to the one running. Blank text adds nothing; +at most 4000 characters are kept. + +They are for this chat only: an MCP client you run yourself keeps its own instruction files, +and one text applies to every design. + ## Permissions Preferences → AI → **Permissions** decides what the agent may do without asking, for every agent; diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 6619d3abb..88b029b2c 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -653,7 +653,7 @@ no box selection. | `engine.execute` → `browser.expand_all` | `path?`: occurrence ids; `component?`: id; omit both for the whole tree | Open every Browser row under that scope, including folders that start closed (Origin, Named Views, Features). Display only: not saved in the design, not an undo step. | | `engine.execute` → `browser.collapse_all` | same | Close those rows. The design row stays open when the whole tree is collapsed. | | `engine.execute` → `view.history_layout` | `width?`, `dock?`: `bottom`, `left`, `under_browser`, `collapsed?` | Resize/dock the history without opening a dialog or changing the design. Contents respond to measured width; browser-stacked history shares its width and splits the height at the remembered share (`browser_share`, half until the seam between the two cards is dragged). One folded header gives the expanded card the rest; two folded headers stay at the top. | -| `ui.agent_chat` | `features?`, `toolbar_button?`, `connect_at_start?` and `open_at_start?` (connect the agent started last, and open the panel, when SolidCraft starts; both off by default, never with `--control`), `permissions?` (`ask`, `edits`, `all`), `add_agent?` ({`name`, `kind`: `acp`, `api` or `anthropic` (`api` is OpenAI-compatible, `anthropic` Anthropic-compatible), `command` or `base_url` + `model` + `request_timeout_s?` (seconds one model request may take, 300 by default, rounded and clamped to 30 to 3600)}; no keys), `add_dialog?` (`installed`, `custom`, `api`, `anthropic`, or `false` to close), `edit_dialog?` (the id of an agent you added: the same dialog filled with what it holds, as its **Edit** button opens it; the key is never shown), `default_agent?`, `agent?` (the conversation's agent, by id), `mode?` (the agent's own mode), `provider?` (which provider's group the model picker opens first, when the models come from several), `model?` (one of its models, or see below), `open?`, `side?` (`left`, `right`), `minimized?`, `popped?` (in its own window), `width?`, `picker?`, `refresh?`, `connect?`, `stop?`, `attach?`: a file's path (a picture, a text file or a CAD file, for the next message; CAD files are imported at once), `remove_file?` (index of a file on the next message), `send?`: text (files alone make a message too), `attach_view?`, `attach_selection?`, `pick?` (true: open the context picker), `permission?`: an option id or `"cancel"` (the newest question of the agent's own), `approve?`: true, false or `"always"` (the oldest request held for Allow/Deny), `cancel?` (Stop: the queue stays), `send_now?` (stop the running step, then send the queued messages), `remove_pending?` (index), `new_chat?` (clear the chat, new session), `undo?` (the last message's changes) | the chat's state: `features`, `agents` (found and added), `currentAgent`, `state` (off, starting, ready, busy, auth, exited, failed: the agent never got ready, and Connect reads Retry), `connectAtStart`, `openAtStart`, `lastAgent` (the agent started last), `popped`, `window` (its place and size), `agent`, `modes`, `mode`, `models`, `model`, `modelWarning` (the model capability warning text, or `null` when unknown or tool support is reported; checked asynchronously and never blocks sending), `turnWarning` (the latest completed turn's no-tool notice, otherwise `null`; cleared on the next turn or new chat), `providers` (`name` and `count` of each, empty with one provider), `provider` (the one listed), `authMethods`, `toolsPort`, `pid`, `waiting`, `turn`, `pending` (queued messages, with their `files`), `attachments` (the files on the next message, by name), `loading` (pictures still being read for it, by name), `stopped`, `detection` and the conversation (`items`). With `features` off only the settings apply. Desktop only; see [Agent chat](agent-chat.md) | +| `ui.agent_chat` | `features?`, `toolbar_button?`, `connect_at_start?` and `open_at_start?` (connect the agent started last, and open the panel, when SolidCraft starts; both off by default, never with `--control`), `instructions?` (the custom instructions every new chat's system note carries, Preferences → AI; at most 4000 characters are kept), `permissions?` (`ask`, `edits`, `all`), `add_agent?` ({`name`, `kind`: `acp`, `api` or `anthropic` (`api` is OpenAI-compatible, `anthropic` Anthropic-compatible), `command` or `base_url` + `model` + `request_timeout_s?` (seconds one model request may take, 300 by default, rounded and clamped to 30 to 3600)}; no keys), `add_dialog?` (`installed`, `custom`, `api`, `anthropic`, or `false` to close), `edit_dialog?` (the id of an agent you added: the same dialog filled with what it holds, as its **Edit** button opens it; the key is never shown), `default_agent?`, `agent?` (the conversation's agent, by id), `mode?` (the agent's own mode), `provider?` (which provider's group the model picker opens first, when the models come from several), `model?` (one of its models, or see below), `open?`, `side?` (`left`, `right`), `minimized?`, `popped?` (in its own window), `width?`, `picker?`, `refresh?`, `connect?`, `stop?`, `attach?`: a file's path (a picture, a text file or a CAD file, for the next message; CAD files are imported at once), `remove_file?` (index of a file on the next message), `send?`: text (files alone make a message too), `attach_view?`, `attach_selection?`, `pick?` (true: open the context picker), `permission?`: an option id or `"cancel"` (the newest question of the agent's own), `approve?`: true, false or `"always"` (the oldest request held for Allow/Deny), `cancel?` (Stop: the queue stays), `send_now?` (stop the running step, then send the queued messages), `remove_pending?` (index), `new_chat?` (clear the chat, new session), `undo?` (the last message's changes) | the chat's state: `features`, `agents` (found and added), `currentAgent`, `state` (off, starting, ready, busy, auth, exited, failed: the agent never got ready, and Connect reads Retry), `connectAtStart`, `openAtStart`, `instructions`, `lastAgent` (the agent started last), `popped`, `window` (its place and size), `agent`, `modes`, `mode`, `models`, `model`, `modelWarning` (the model capability warning text, or `null` when unknown or tool support is reported; checked asynchronously and never blocks sending), `turnWarning` (the latest completed turn's no-tool notice, otherwise `null`; cleared on the next turn or new chat), `providers` (`name` and `count` of each, empty with one provider), `provider` (the one listed), `authMethods`, `toolsPort`, `pid`, `waiting`, `turn`, `pending` (queued messages, with their `files`), `attachments` (the files on the next message, by name), `loading` (pictures still being read for it, by name), `stopped`, `detection` and the conversation (`items`). With `features` off only the settings apply. Desktop only; see [Agent chat](agent-chat.md) | | `ui.resize` | `width`, `height` | | | `app.quit` | `force?` (quit without asking about unsaved designs) | `quitting` (the window closes), `asking` (a "save changes?" prompt is open) |