Skip to content

Craft Anything: understand how any software works, and craft your own.

Rust

Builder limits, OpenRouter tools, a software-renderer fallback, calmer spinners, lean local builders, lldb calls and LM Studio ports (#657)

BFlat9fd46b818be4
diff --git a/Cargo.lock b/Cargo.lock
index f29e9b0b..b640c700 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1132,6 +1132,7 @@ dependencies = [
"eframe",
"log",
"rfd",
+ "tempfile",
"winresource",
]
diff --git a/apps/craft-anything/Cargo.toml b/apps/craft-anything/Cargo.toml
index 5a9a25f3..bf38a769 100644
--- a/apps/craft-anything/Cargo.toml
+++ b/apps/craft-anything/Cargo.toml
@@ -28,3 +28,6 @@ wasm-plugins = ["craft-anything-engine/wasm-plugins"]
[build-dependencies]
# Icon + VERSIONINFO for craft-anything.exe; build.rs only uses it when targeting Windows.
winresource = "0.1"
+
+[dev-dependencies]
+tempfile = "3"
diff --git a/apps/craft-anything/src/main.rs b/apps/craft-anything/src/main.rs
index 4bdf345d..8c10131e 100644
--- a/apps/craft-anything/src/main.rs
+++ b/apps/craft-anything/src/main.rs
@@ -8,6 +8,13 @@ use craft_anything_ui_egui::CraftApp;
use std::path::PathBuf;
use std::sync::Arc;
+mod start_guard;
+
+/// Set when the last start never opened its window (see [`start_guard`]): the software renderer
+/// (WARP) is asked for, as with `CRAFT_ANYTHING_RENDERER=software`, for this start only.
+#[cfg(windows)]
+static RETRY_IN_SOFTWARE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
+
fn main() -> eframe::Result {
let args: Vec<String> = std::env::args().skip(1).collect();
if args.iter().any(|a| a == "--version" || a == "-V") {
@@ -20,6 +27,15 @@ fn main() -> eframe::Result {
// desktop.log beside the settings, so a start that shows nothing leaves a trace.
log_to_file();
log::info!("starting {} (pid {})", env!("CARGO_PKG_VERSION"), std::process::id());
+ // A driver that crashes natively leaves nothing behind but this mark (#74): the start after it
+ // draws without the graphics card, and the one after that is back to normal.
+ let config = craft_anything_engine::settings::config_dir();
+ if start_guard::last_start_failed(&config) {
+ log::warn!("the last start never opened its window; drawing without the graphics card this time");
+ #[cfg(windows)]
+ RETRY_IN_SOFTWARE.store(true, std::sync::atomic::Ordering::Relaxed);
+ }
+ start_guard::begin(&config);
let settings = Settings::load();
let mut session = Session::new(settings);
@@ -63,6 +79,9 @@ fn main() -> eframe::Result {
log::info!("window open");
CraftApp::setup_context(&cc.egui_ctx);
let mut app = CraftApp::new(engine, hub);
+ // The window is built hidden and its first frame is drawn afterwards, where a graphics
+ // driver may still crash: the mark stays until frames have been shown (#74).
+ app.after_first_frames(move || start_guard::opened(&config));
app.load_prefs(cc.storage);
if let Some(p) = open {
app.open_path(p);
@@ -122,7 +141,7 @@ fn graphics_advice(error: &str) -> &'static str {
/// (#33). `WGPU_BACKEND` still narrows the choice.
#[cfg(windows)]
fn pick_adapter(adapters: &[eframe::wgpu::Adapter], surface: Option<&eframe::wgpu::Surface<'_>>) -> Result<eframe::wgpu::Adapter, String> {
- let software = wants_software(std::env::var("CRAFT_ANYTHING_RENDERER").ok().as_deref());
+ let software = wants_software(std::env::var("CRAFT_ANYTHING_RENDERER").ok().as_deref()) || RETRY_IN_SOFTWARE.load(std::sync::atomic::Ordering::Relaxed);
let picked = adapters.iter().filter(|a| surface.is_none_or(|s| a.is_surface_supported(s))).min_by_key(|a| {
let info = a.get_info();
// Asked for software: WARP first, and the usual order among the rest.
diff --git a/apps/craft-anything/src/start_guard.rs b/apps/craft-anything/src/start_guard.rs
new file mode 100644
index 00000000..514ae977
--- /dev/null
+++ b/apps/craft-anything/src/start_guard.rs
@@ -0,0 +1,66 @@
+//! A start that never reached a window (#74, #104, #33).
+//!
+//! A graphics driver that crashes natively as the window opens takes the whole process with it:
+//! no Rust code runs afterwards, so no dialog and no log line can say what happened, and the app
+//! just vanishes. What can be done is to leave a mark before trying and remove it once the window
+//! is open and has shown its first frames (the driver may crash while presenting them, after
+//! eframe's setup callback has run); a mark found at the next start means the last one never got
+//! there, and the app draws without the graphics card that time (see `main`). A start that does
+//! open the window clears the mark, so the next one is back to normal.
+
+use std::path::{Path, PathBuf};
+
+/// Beside the settings, with `desktop.log`.
+const MARKER: &str = "starting";
+
+fn marker(dir: &Path) -> PathBuf {
+ dir.join(MARKER)
+}
+
+/// Whether the last start ended before its window opened.
+pub fn last_start_failed(dir: &Path) -> bool {
+ marker(dir).exists()
+}
+
+/// Called right before the window is asked for. Best effort: a folder that can't be written to
+/// only means no fallback.
+pub fn begin(dir: &Path) {
+ let _ = std::fs::create_dir_all(dir);
+ let _ = std::fs::write(marker(dir), std::process::id().to_string());
+}
+
+/// Called once the window is open.
+pub fn opened(dir: &Path) {
+ let _ = std::fs::remove_file(marker(dir));
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ /// #74: a start that dies before its window leaves the mark; one that opens it doesn't.
+ #[test]
+ fn a_start_that_never_opened_a_window_is_seen_by_the_next_one() {
+ let d = tempfile::tempdir().unwrap();
+ let dir = d.path().join("config");
+ assert!(!last_start_failed(&dir), "a first start has nothing to retry");
+ begin(&dir);
+ assert!(last_start_failed(&dir), "the process died before opened()");
+ begin(&dir);
+ assert!(last_start_failed(&dir), "a second start in a row still sees it");
+ opened(&dir);
+ assert!(!last_start_failed(&dir), "a window that opened clears it");
+ opened(&dir);
+ assert!(!last_start_failed(&dir), "clearing twice is fine");
+ }
+
+ #[test]
+ fn a_folder_that_cannot_be_written_means_no_fallback_and_no_crash() {
+ let d = tempfile::tempdir().unwrap();
+ let file = d.path().join("not-a-folder");
+ std::fs::write(&file, "").unwrap();
+ begin(&file);
+ assert!(!last_start_failed(&file));
+ opened(&file);
+ }
+}
diff --git a/crates/ai/src/agent.rs b/crates/ai/src/agent.rs
index d732a488..3e7e9b98 100644
--- a/crates/ai/src/agent.rs
+++ b/crates/ai/src/agent.rs
@@ -26,6 +26,14 @@ pub const DEFAULT_MAX_TURNS: u32 = 40;
/// Steps one builder message may take (writing, building and fixing a project takes many).
pub const BUILDER_MAX_TURNS: u32 = 400;
+/// The build tool whose result says whether the command succeeded (`succeeded`, typed).
+const BUILD_COMMAND_TOOL: &str = "build_command_run";
+
+/// Build commands that fail one after another, with none succeeding in between, before a step
+/// stops (#399: a model wrote code against APIs that don't exist, never got it to compile, and
+/// spent 9.4M tokens in one stage). Each failed build sends the whole conversation again.
+pub const MAX_FAILED_BUILDS: u32 = 25;
+
/// What the loop needs from the engine (a trait so tests can inject behaviour).
pub trait ToolHost: Send + Sync {
/// Tool definitions for the enabled toolsets (without the meta-tools).
@@ -256,6 +264,33 @@ pub struct LoopConfig {
/// Override the input tokens the conversation may grow to before it's trimmed. Zero uses
/// the active backend's budget, or its local/cloud default (see [`crate::context`]).
pub context_tokens: u64,
+ /// A builder on a local model is offered the tools for building, not the whole Core set (see
+ /// [`lean_for_local`]).
+ pub lean_for_local: bool,
+}
+
+/// The Core tools a builder on a local model keeps. The Core set is 25-odd tools for studying a
+/// target (evidence, unknowns, hypotheses, reports…) that make a building model explore instead
+/// of writing; their descriptions alone take about 5,000 tokens, more than Ollama's default
+/// context holds (#417). Kept are the Build tools, every other enabled toolset, and the Core tools
+/// the builder's brief names: asking the person, the check, the generated assets and the unknowns.
+const LOCAL_BUILDER_CORE: &[&str] = &[
+ "core_person_ask",
+ "rebuild_check",
+ "rebuild_words",
+ "assets_image_generate",
+ "assets_model_generate",
+ "assets_spent",
+ "assets_note",
+ "core_unknowns_show",
+ "core_unknown_add",
+ "core_unknown_edit",
+];
+
+/// Drop the Core tools a local builder doesn't need (the models that can take them all don't pass
+/// through here).
+fn lean_for_local(tools: Vec<ToolDef>, host: &dyn ToolHost) -> Vec<ToolDef> {
+ tools.into_iter().filter(|t| host.toolset_of(&t.name) != Some(Toolset::Core) || LOCAL_BUILDER_CORE.contains(&t.name.as_str())).collect()
}
/// The state the worker keeps between user messages.
@@ -277,6 +312,8 @@ pub struct AgentLoop {
/// Estimated history size sent with that turn, before its reply and tool results were added.
last_history_estimate: u64,
failure: Arc<Mutex<Option<TurnFailure>>>,
+ /// Build commands that failed in a row in this step (see [`MAX_FAILED_BUILDS`]).
+ failed_builds: u32,
}
impl AgentLoop {
@@ -286,6 +323,9 @@ impl AgentLoop {
fn tool_defs(&self) -> Vec<ToolDef> {
let mut tools = self.host.tools(&self.enabled);
+ if self.cfg.lean_for_local && self.chain.get(self.current).is_some_and(|s| s.local) {
+ tools = lean_for_local(tools, self.host.as_ref());
+ }
tools.push(ToolDef {
name: "list_toolsets".into(),
description: "List the groups of tools (toolsets), which are enabled, and what each covers.".into(),
@@ -327,6 +367,7 @@ impl AgentLoop {
let mut msg_usage = Usage::default();
let mut msg_cost: Option<f64> = Some(0.0);
let mut turns = 0u32;
+ self.failed_builds = 0;
loop {
if self.stop.is_stopped() {
self.emit(AgentEvent::Status { text: "Stopped.".into() });
@@ -388,6 +429,16 @@ impl AgentLoop {
let results = self.run_tools(&uses);
self.history.push(Msg { role: Speaker::User, blocks: results });
self.save_transcript();
+ if self.failed_builds >= MAX_FAILED_BUILDS {
+ self.emit(AgentEvent::Error {
+ message: format!("The build command failed {} times in a row, so this step stopped before spending more.", self.failed_builds),
+ remediation: Some(
+ "Ask for a fix (say what to change), or try a stronger model. Try again carries on from the project as it is.".into(),
+ ),
+ log: None,
+ });
+ break;
+ }
}
StopReason::MaxTokens if !uses.is_empty() => {
// Tool input may be cut off: don't run anything, tell the model.
@@ -657,6 +708,16 @@ impl AgentLoop {
}
match r {
Ok(out) => {
+ // A build that ran and failed is still an Ok result: `succeeded` says which.
+ if name == BUILD_COMMAND_TOOL
+ && let ToolOutput::Value(v) = &out
+ {
+ match v.get("succeeded").and_then(Value::as_bool) {
+ Some(true) => self.failed_builds = 0,
+ Some(false) => self.failed_builds = self.failed_builds.saturating_add(1),
+ None => {}
+ }
+ }
let (text, summary, ev) = compact(&out);
(text, true, summary, ev)
}
@@ -744,6 +805,7 @@ impl ApiConversation {
last_input: 0,
last_history_estimate: 0,
failure: failure.clone(),
+ failed_builds: 0,
};
let busy2 = busy.clone();
std::thread::Builder::new()
@@ -879,6 +941,60 @@ pub(crate) mod tests {
assert_eq!(bad.len(), 1);
}
+ /// #417: a builder on a local model gets the Build tools and the question tool, not the whole
+ /// Core set; other toolsets stay.
+ #[test]
+ fn a_local_builder_is_not_offered_the_study_tools() {
+ let host = FakeHost { calls: Mutex::default(), journal: Mutex::default() };
+ let all = host.tools(&BTreeSet::from([Toolset::Core, Toolset::Runtime]));
+ let names = |v: &[ToolDef]| v.iter().map(|t| t.name.clone()).collect::<Vec<_>>();
+ assert_eq!(names(&all), ["look", "danger"]);
+ // `look` is a Core tool that isn't kept; `danger` belongs to another toolset.
+ assert_eq!(names(&lean_for_local(all, &host)), ["danger"]);
+ let ask = vec![ToolDef { name: "core_person_ask".into(), description: "d".into(), schema: json!({"type":"object"}) }];
+ struct CoreHost;
+ impl ToolHost for CoreHost {
+ fn tools(&self, _: &BTreeSet<Toolset>) -> Vec<ToolDef> {
+ Vec::new()
+ }
+ fn toolset_of(&self, _: &str) -> Option<Toolset> {
+ Some(Toolset::Core)
+ }
+ fn call(&self, _: &str, _: Value, _: bool, _: CancelToken) -> Result<ToolOutput, ToolError> {
+ Err(ToolError::internal("unused"))
+ }
+ fn journal(&self, _: &str, _: Value) {}
+ fn investigation(&self) -> String {
+ "{}".into()
+ }
+ fn clean_room(&self) -> bool {
+ true
+ }
+ fn title(&self, id: &str) -> String {
+ id.into()
+ }
+ }
+ assert_eq!(names(&lean_for_local(ask, &CoreHost)), ["core_person_ask"], "the question tool stays");
+ }
+
+ /// #417, with the real tools: the tool descriptions a local builder is sent in Clean room fell
+ /// from 33-41 tools (23,000-30,000 characters) to 13 (about 10,000).
+ #[test]
+ fn the_real_local_builder_tool_list_is_small_and_can_write_files() {
+ let engine = craft_anything_engine::Engine::shared(craft_anything_engine::testing::session(), crate::tools());
+ let host = EngineHost(engine);
+ let enabled = BTreeSet::from([Toolset::Core, Toolset::Build]);
+ let all = host.tools(&enabled);
+ let lean = lean_for_local(all.clone(), &host);
+ let names: Vec<&str> = lean.iter().map(|t| t.name.as_str()).collect();
+ let size = |v: &[ToolDef]| v.iter().map(|t| t.description.len() + t.schema.to_string().len()).sum::<usize>();
+ for needed in ["build_file_write", "build_file_edit", "build_file_read", "build_files_list", "build_command_run", "core_person_ask", "rebuild_check"] {
+ assert!(names.contains(&needed), "{needed} in {names:?}");
+ }
+ assert!(!names.contains(&"core_journal_read") && !names.contains(&"core_session_show"), "{names:?}");
+ assert!(lean.len() <= 20 && size(&lean) * 2 < size(&all), "{} tools, {} of {} characters", lean.len(), size(&lean), size(&all));
+ }
+
/// A scripted model: returns canned turns and records requests.
pub struct Scripted {
pub turns: VecDeque<Result<TurnResult, ToolError>>,
@@ -931,6 +1047,7 @@ pub(crate) mod tests {
fn toolset_of(&self, id: &str) -> Option<Toolset> {
match id {
"look" => Some(Toolset::Core),
+ "build_command_run" => Some(Toolset::Core),
"danger" => Some(Toolset::Runtime),
_ => None,
}
@@ -940,6 +1057,11 @@ pub(crate) mod tests {
if id == "danger" && !consent {
return Err(ToolError::new(ErrorCode::ConsentRequired, "needs your OK"));
}
+ if id == "build_command_run" {
+ return Ok(ToolOutput::Value(
+ json!({"command": "cargo build", "exit_code": 0, "succeeded": input.get("ok").and_then(Value::as_bool) == Some(true)}),
+ ));
+ }
if id == "look" && input.get("large").and_then(Value::as_bool) == Some(true) {
return Ok(ToolOutput::Value(json!({"content": "n".repeat(8000)})));
}
@@ -1033,6 +1155,47 @@ pub(crate) mod tests {
assert!(matches!(events.last(), Some(AgentEvent::TurnDone { cost_usd: Some(_), .. })));
}
+ /// #399: a model that never gets its code to compile kept going for 400 steps and 9.4M tokens.
+ /// A step stops after [`MAX_FAILED_BUILDS`] failed build commands in a row, says why, and keeps
+ /// what was done; a build that succeeds starts the count again.
+ #[test]
+ fn a_step_stops_after_many_failed_builds_in_a_row() {
+ let build = |ok: bool, n: usize| {
+ turn(vec![Block::ToolUse { id: format!("b{n}"), name: BUILD_COMMAND_TOOL.into(), input: json!({"ok": ok}) }], StopReason::ToolUse)
+ };
+ let run = |turns: Vec<Result<TurnResult, ToolError>>| {
+ let host = Arc::new(FakeHost { calls: Mutex::default(), journal: Mutex::default() });
+ let script = Scripted { turns: VecDeque::from(turns), seen: Arc::default() };
+ let slot = ModelSlot { name: "Fake".into(), model: Box::new(script), local: false, effort: None, max_turns: 400, context_tokens: 0 };
+ let mut c = ApiConversation::start(host, vec![slot], LoopConfig { beginner: true, ..LoopConfig::default() }).unwrap();
+ c.send("build it");
+ drain_until_done(&mut c, |_, _| {})
+ };
+ let n = MAX_FAILED_BUILDS as usize;
+ // All failing: stopped at the limit with a reason, not by running out of script.
+ let events = run((0..n + 5).map(|i| build(false, i)).collect());
+ let stopped = events.iter().find_map(|e| match e {
+ AgentEvent::Error { message, .. } => Some(message.clone()),
+ _ => None,
+ });
+ assert!(stopped.as_deref().is_some_and(|m| m.contains(&format!("failed {n} times in a row"))), "{stopped:?}");
+ assert_eq!(events.iter().filter(|e| matches!(e, AgentEvent::ToolFinished { .. })).count(), n, "no more builds after the limit");
+ // A success in between starts the count again: the same number of failures, split, goes on.
+ let mut turns: Vec<_> = (0..n - 1).map(|i| build(false, i)).collect();
+ turns.push(build(true, 99));
+ turns.extend((0..n - 1).map(|i| build(false, 100 + i)));
+ turns.push(turn(vec![Block::Text { text: "done".into() }], StopReason::EndTurn));
+ let events = run(turns);
+ assert!(!events.iter().any(|e| matches!(e, AgentEvent::Error { .. })), "{events:?}");
+ assert!(events.iter().any(|e| matches!(e, AgentEvent::TextDelta { text } if text == "done")));
+ }
+
+ #[test]
+ fn the_build_tool_the_limit_counts_exists() {
+ let e = craft_anything_engine::Engine::new(craft_anything_engine::testing::session());
+ assert!(e.registry().get(BUILD_COMMAND_TOOL).is_some_and(|s| !s.effects.is_empty()));
+ }
+
#[test]
fn a_long_conversation_is_summarised_kept_and_resumed() {
let d = tempfile::tempdir().unwrap();
diff --git a/crates/ai/src/detect.rs b/crates/ai/src/detect.rs
index 470fef41..33a86b20 100644
--- a/crates/ai/src/detect.rs
+++ b/crates/ai/src/detect.rs
@@ -165,13 +165,43 @@ pub(crate) fn on_this_network(url: &str) -> bool {
}
}
-/// Every local server to probe: the usual addresses, then those OpenCode names elsewhere.
+/// The ports just above LM Studio's 1234, where its server goes when 1234 is taken or the person
+/// moved it (#73: 1235). Whatever answers there is checked like any other server: it must speak
+/// the OpenAI API and list models.
+const LM_STUDIO_NEARBY: std::ops::RangeInclusive<u16> = 1235..=1239;
+
+/// Where LM Studio keeps its server settings, under the home folder (newer, then older versions).
+/// Taken from LM Studio's own folders as they were seen, not from its documentation.
+const LM_STUDIO_SETTINGS: &[&str] = &[".lmstudio/.internal/http-server-config.json", ".cache/lm-studio/.internal/http-server-config.json"];
+
+/// The server port in LM Studio's settings file (`"port": 1235`).
+pub(crate) fn lmstudio_port(text: &str) -> Option<u16> {
+ let doc = craft_anything_formats::jsonc::parse(text, false).ok()?.to_value();
+ doc.get("port").and_then(serde_json::Value::as_u64).and_then(|p| u16::try_from(p).ok()).filter(|p| *p != 0)
+}
+
+/// Every local server to probe: the usual addresses, the port LM Studio's settings name, those
+/// OpenCode names elsewhere, then the ports next to LM Studio's. Each address once, under the most
+/// specific name.
fn local_servers() -> Vec<(String, String)> {
+ let read = |p: &std::path::Path| std::fs::metadata(p).ok().filter(|m| m.len() <= 1024 * 1024).and_then(|_| std::fs::read_to_string(p).ok());
+ let home = dirs::home_dir();
+ let lm_port = home.iter().flat_map(|h| LM_STUDIO_SETTINGS.iter().map(move |f| h.join(f))).find_map(|p| read(&p).as_deref().and_then(lmstudio_port));
+ let opencode = opencode_config(|v| std::env::var(v).ok(), home).and_then(|p| read(&p)).as_deref().map(opencode_servers).unwrap_or_default();
+ servers_to_probe(lm_port, opencode)
+}
+
+/// [`local_servers`] without the files: `lm_port` is the port LM Studio's settings name, and
+/// `opencode` the servers OpenCode's settings name.
+fn servers_to_probe(lm_port: Option<u16>, opencode: Vec<(String, String)>) -> Vec<(String, String)> {
let mut all: Vec<(String, String)> = LOCAL_SERVERS.iter().map(|(l, b)| (l.to_string(), b.to_string())).collect();
- let config = opencode_config(|v| std::env::var(v).ok(), dirs::home_dir());
- let text = config.filter(|p| std::fs::metadata(p).is_ok_and(|m| m.len() <= 1024 * 1024)).and_then(|p| std::fs::read_to_string(p).ok());
- for (label, base) in text.as_deref().map(opencode_servers).unwrap_or_default() {
- if !all.iter().any(|(_, b)| b.trim_end_matches('/') == base) {
+ let extra = lm_port
+ .map(|p| ("LM Studio".to_string(), format!("http://127.0.0.1:{p}/v1")))
+ .into_iter()
+ .chain(opencode)
+ .chain(LM_STUDIO_NEARBY.map(|p| (format!("AI server on port {p}"), format!("http://127.0.0.1:{p}/v1"))));
+ for (label, base) in extra {
+ if !all.iter().any(|(_, b)| b.trim_end_matches('/') == base.trim_end_matches('/')) {
all.push((label, base));
}
}
@@ -359,6 +389,32 @@ mod tests {
assert_eq!(probe_local(label, base).unwrap().suggestion.name, "LM Studio from OpenCode (local)");
}
+ /// #73: LM Studio on another port was missed: its settings name the port, and the ports next to
+ /// 1234 are probed too. Each address is probed once, under the most specific name.
+ #[test]
+ fn lm_studio_on_another_port_is_probed() {
+ assert_eq!(lmstudio_port(r#"{"port": 1235, "networkInterface": "127.0.0.1", "cors": false}"#), Some(1235));
+ for bad in ["", "not json", r#"{"port": 0}"#, r#"{"port": 70000}"#, r#"{"port": "1235"}"#, r#"{"cors": true}"#] {
+ assert_eq!(lmstudio_port(bad), None, "{bad}");
+ }
+ let bases = |v: &[(String, String)]| v.iter().map(|(_, b)| b.clone()).collect::<Vec<_>>();
+ let plain = servers_to_probe(None, Vec::new());
+ let base_count = LOCAL_SERVERS.len();
+ assert_eq!(plain.len(), base_count + LM_STUDIO_NEARBY.count(), "the usual servers, then the ports next to 1234");
+ assert!(bases(&plain).contains(&"http://127.0.0.1:1235/v1".to_string()));
+ // A port from LM Studio's settings, away from 1234, is probed as LM Studio.
+ let moved = servers_to_probe(Some(4321), Vec::new());
+ assert!(moved.contains(&("LM Studio".to_string(), "http://127.0.0.1:4321/v1".to_string())), "{moved:?}");
+ // The usual port named again adds nothing; OpenCode's name for 1235 wins over the generic one.
+ assert_eq!(servers_to_probe(Some(1234), Vec::new()).len(), plain.len());
+ let from_opencode = servers_to_probe(None, vec![("LM Studio from OpenCode".into(), "http://127.0.0.1:1235/v1".into())]);
+ assert_eq!(from_opencode.len(), plain.len(), "no address twice");
+ assert!(from_opencode.contains(&("LM Studio from OpenCode".to_string(), "http://127.0.0.1:1235/v1".to_string())));
+ // What answers on one of those ports is found like a server at a usual address.
+ let url = crate::tests::serve("200 OK", r#"{"object":"list","data":[{"id":"gemma"}]}"#);
+ assert_eq!(probe_local("LM Studio", &url).unwrap().suggestion.model, "gemma");
+ }
+
#[test]
fn only_addresses_on_this_computer_or_network_count() {
for url in [
diff --git a/crates/ai/src/lib.rs b/crates/ai/src/lib.rs
index 7dca3f29..e67e1e1c 100644
--- a/crates/ai/src/lib.rs
+++ b/crates/ai/src/lib.rs
@@ -702,13 +702,13 @@ impl AiHub {
use craft_anything_engine::Toolset;
let deep = !self.engine.session().clean_room();
let toolsets = if deep { self.engine.registry().toolsets() } else { vec![Toolset::Core, Toolset::Build] };
- self.start_loop(entry, beginner, transcript, &toolsets)
+ self.start_loop(entry, beginner, transcript, &toolsets, true)
}
/// Start the asset extractor: our agent loop with the Build tools and the game archive tools.
pub fn start_extractor(&self, entry: &BackendEntry, beginner: bool, transcript: Option<PathBuf>) -> Result<ApiConversation, ToolError> {
use craft_anything_engine::Toolset;
- self.start_loop(entry, beginner, transcript, &[Toolset::Core, Toolset::Build, Toolset::Formats])
+ self.start_loop(entry, beginner, transcript, &[Toolset::Core, Toolset::Build, Toolset::Formats], false)
}
fn start_loop(
@@ -717,6 +717,7 @@ impl AiHub {
beginner: bool,
transcript: Option<PathBuf>,
toolsets: &[craft_anything_engine::Toolset],
+ lean_for_local: bool,
) -> Result<ApiConversation, ToolError> {
let mut slot = self.build_model(entry)?;
slot.max_turns = slot.max_turns.max(agent::BUILDER_MAX_TURNS);
@@ -724,7 +725,7 @@ impl AiHub {
ApiConversation::start_with(
host,
vec![slot],
- LoopConfig { beginner, prices: self.config().prices.clone(), transcript, ..LoopConfig::default() },
+ LoopConfig { beginner, prices: self.config().prices.clone(), transcript, lean_for_local, ..LoopConfig::default() },
toolsets.iter().copied().collect(),
)
}
diff --git a/crates/ai/src/openai.rs b/crates/ai/src/openai.rs
index b2a5f483..a534eb5d 100644
--- a/crates/ai/src/openai.rs
+++ b/crates/ai/src/openai.rs
@@ -40,6 +40,8 @@ pub struct OpenAi {
pub react: bool,
/// Recover JSON text calls automatically, and switch to ReAct when the server rejects tools.
pub auto_react: bool,
+ /// Talking to OpenRouter, which routes each request to one of several upstream providers.
+ pub openrouter: bool,
}
impl OpenAi {
@@ -50,6 +52,7 @@ impl OpenAi {
pub fn openrouter(base: Option<&str>, key: String, model: &str) -> Self {
let mut o = Self::compatible("OpenRouter", base.unwrap_or(OPENROUTER_BASE), Some(key), if model.is_empty() { OPENROUTER_DEFAULT_MODEL } else { model });
o.extra_headers = vec![("HTTP-Referer", APP_REFERER.to_string()), ("X-Title", APP_TITLE.to_string())];
+ o.openrouter = true;
o
}
@@ -62,6 +65,7 @@ impl OpenAi {
extra_headers: Vec::new(),
react: false,
auto_react: true,
+ openrouter: false,
}
}
@@ -103,6 +107,12 @@ impl OpenAi {
.collect();
o.insert("tools".into(), Value::Array(tools));
o.insert("tool_choice".into(), json!("auto"));
+ // OpenRouter picks an upstream provider per request, and one that can't do tool calls
+ // answers "400: Provider returned error" (#369). Only a provider that supports every
+ // parameter in the request is used.
+ if self.openrouter {
+ o.insert("provider".into(), json!({"require_parameters": true}));
+ }
}
body
}
@@ -142,7 +152,7 @@ fn rejects_tools(e: &ToolError) -> bool {
impl ChatModel for OpenAi {
fn turn(&mut self, req: &TurnRequest<'_>, on_delta: &mut dyn FnMut(Delta), stop: &Stop) -> Result<TurnResult, ToolError> {
match self.stream_once(req, on_delta, stop) {
- Err(e) if !self.react && self.auto_react && !req.tools.is_empty() && rejects_tools(&e) => {
+ Err(e) if !self.react && self.auto_react && !req.tools.is_empty() && (rejects_tools(&e) || self.no_provider_for_tools(&e)) => {
log::info!("{} rejected tool calling; switching to the text protocol", self.label);
self.react = true;
self.stream_once(req, on_delta, stop)
@@ -156,6 +166,14 @@ impl ChatModel for OpenAi {
}
}
+impl OpenAi {
+ /// OpenRouter answers 404 when no provider supports all the request's parameters (see
+ /// [`OpenAi::body`]): tool calling isn't available for this model, so the text protocol is.
+ fn no_provider_for_tools(&self, e: &ToolError) -> bool {
+ self.openrouter && e.details.as_ref().and_then(|d| d.get("status")).and_then(Value::as_u64) == Some(404)
+ }
+}
+
/// Wire messages for one neutral message (a user message with several tool results becomes
/// several `tool` messages).
pub fn messages_json(m: &Msg, react: bool) -> Vec<Value> {
@@ -643,6 +661,27 @@ mod tests {
}
}
+ /// #369: OpenRouter routes to an upstream provider per request, and one without tool calling
+ /// answered "400: Provider returned error". With tools in the request, only providers that
+ /// support every parameter are used; nothing else changes.
+ #[test]
+ fn openrouter_only_routes_a_tool_request_to_providers_that_support_tools() {
+ use crate::model::{Effort, ToolDef, TurnRequest};
+ let tools = [ToolDef { name: "look".into(), description: "d".into(), schema: json!({"type": "object"}) }];
+ let messages = [Msg::user_text("hi")];
+ let with_tools = TurnRequest { system: "S", messages: &messages, tools: &tools, effort: Effort::Low, max_tokens: 100 };
+ let without = TurnRequest { system: "S", messages: &messages, tools: &[], effort: Effort::Low, max_tokens: 100 };
+ let router = OpenAi::openrouter(None, "k".into(), "moonshotai/kimi-k3");
+ assert_eq!(router.body(&with_tools)["provider"], json!({"require_parameters": true}));
+ assert!(router.body(&without).get("provider").is_none(), "nothing to require without tools");
+ let mut text_protocol = router.clone();
+ text_protocol.react = true;
+ assert!(text_protocol.body(&with_tools).get("provider").is_none(), "the text protocol sends no tools");
+ let other = OpenAi::compatible("Ollama", "http://127.0.0.1:11434/v1", None, "llama3");
+ assert!(other.body(&with_tools).get("provider").is_none(), "only OpenRouter knows `provider`");
+ assert_eq!(router.body(&with_tools)["tool_choice"], "auto");
+ }
+
#[test]
fn wire_messages() {
let o = OpenAi::openrouter(None, "k".into(), "");
diff --git a/crates/ai/src/tests.rs b/crates/ai/src/tests.rs
index 182c15f0..81228310 100644
--- a/crates/ai/src/tests.rs
+++ b/crates/ai/src/tests.rs
@@ -937,3 +937,25 @@ fn hub_config_keys_and_test_backend() {
}
assert!(h.compare("Local", "Local", true).is_err());
}
+
+/// #369: when OpenRouter has no provider that supports tools for a model (404 once only those are
+/// asked for), the turn goes on with the text protocol instead of failing; the first request
+/// required parameters, the second sends no tools.
+#[test]
+fn openrouter_with_no_provider_for_tools_falls_back_to_the_text_protocol() {
+ use crate::model::{Effort, Msg, Stop, ToolDef, TurnRequest};
+ let tools = [ToolDef { name: "look".into(), description: "Look at a file".into(), schema: json!({"type":"object"}) }];
+ let messages = [Msg::user_text("hi")];
+ let request = TurnRequest { system: "S", messages: &messages, tools: &tools, effort: Effort::Low, max_tokens: 100 };
+ let none = json!({"error": {"code": 404, "message": "No endpoints found that can handle the requested parameters."}}).to_string();
+ let reply = chat_sse(&[json!({"choices":[{"delta":{"content":"hello"},"finish_reason":"stop"}]})]);
+ let (url, seen) = mock(vec![(404, "application/json", none), (200, "text/event-stream", reply)]);
+ let mut model = openai::OpenAi::openrouter(Some(&url), "k".into(), "moonshotai/kimi-k3");
+ let result = model.turn(&request, &mut |_| {}, &Stop::default()).unwrap();
+ assert_eq!(result.message.text(), "hello");
+ let seen = seen.lock().unwrap();
+ assert_eq!(seen.len(), 2, "one retry");
+ assert_eq!(seen[0].body["provider"], json!({"require_parameters": true}));
+ assert!(seen[0].body.get("tools").is_some());
+ assert!(seen[1].body.get("provider").is_none() && seen[1].body.get("tools").is_none(), "the second asks in text: {}", seen[1].body);
+}
diff --git a/crates/engine/src/tools/apple_runtime.rs b/crates/engine/src/tools/apple_runtime.rs
index 49160419..d70613cb 100644
--- a/crates/engine/src/tools/apple_runtime.rs
+++ b/crates/engine/src/tools/apple_runtime.rs
@@ -234,6 +234,41 @@ fn apple_calls_observe(ctx: &mut Ctx<'_>, params: Value) -> Result<ToolOutput, T
}
}
+/// What a breakpoint's command prints before the function's name; each such line is one hit.
+const HIT_MARK: &str = "CRAFT_HIT";
+
+/// The command file takes one command per line, so a line break in a name or argument would add a
+/// command of the caller's choosing (lldb can run Python and shell commands).
+#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
+fn single_line(p: &ObserveCallsParams) -> Result<(), ToolError> {
+ let bad = |s: &str| s.chars().any(char::is_control);
+ let names = p.breakpoints.iter().flat_map(|b| match b {
+ Breakpoint::Function { name, module } => vec![name.as_str(), module.as_deref().unwrap_or_default()],
+ Breakpoint::ObjcMethod { class_name, selector } => vec![class_name.as_str(), selector.as_str()],
+ });
+ let text = names.chain(p.arguments.iter().map(String::as_str)).chain([p.executable.as_str()]);
+ if text.into_iter().any(bad) {
+ return Err(ToolError::invalid("The executable, arguments and breakpoint names must not contain line breaks or other control characters."));
+ }
+ Ok(())
+}
+
+/// A failed debugger run is not an observation: lldb exits non-zero when it rejects its command
+/// file, and a run that never launched the program says nothing about what it calls (#251).
+#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
+fn lldb_failure(success: bool, code: Option<i32>, stderr: &str) -> Option<ToolError> {
+ if success {
+ return None;
+ }
+ let tail: String = stderr.chars().rev().take(600).collect::<Vec<_>>().into_iter().rev().collect();
+ let how = code.map_or_else(|| "was stopped by the system".to_string(), |c| format!("exited with code {c}"));
+ Some(
+ ToolError::new(ErrorCode::ProgramFailed, format!("lldb {how} before the call observation finished, so nothing was observed. {}", tail.trim()))
+ .with_remediation("Check that the program runs on its own and that lldb (Xcode's command-line tools) can debug it; a program with the hardened runtime needs `codesign` to allow debugging.")
+ .with_details(serde_json::json!({"exit_code": code, "stderr_tail": tail})),
+ )
+}
+
/// Build an lldb Python command that sets breakpoints, runs, and prints each hit as JSON.
#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
fn lldb_script(p: &ObserveCallsParams) -> String {
@@ -252,8 +287,14 @@ fn lldb_script(p: &ObserveCallsParams) -> String {
}
}
}
- // A breakpoint command that records the argument registers and continues.
- setup.push_str("breakpoint command add --script-type python -o 'frame = bp_loc.GetThread().GetSelectedFrame() if bp_loc else None\\nprint(\"CRAFT_HIT\", frame.GetFunctionName() if frame else \"?\")\\nreturn False' 1\n");
+ // A breakpoint command on every breakpoint set above that prints the function and continues
+ // (`return False` doesn't stop). lldb wraps the text in a function whose arguments include
+ // `frame`, and a command line can't hold line breaks, so the statements are separated by `;`:
+ // a literal backslash and `n` between them was a Python `SyntaxError` that stopped lldb before
+ // it launched anything (#251).
+ let breakpoints: usize = p.breakpoints.iter().map(|b| if matches!(b, Breakpoint::ObjcMethod { .. }) { 2 } else { 1 }).sum();
+ let ids = (1..=breakpoints).map(|i| i.to_string()).collect::<Vec<_>>().join(" ");
+ setup.push_str(&format!("breakpoint command add --script-type python -o 'print(\"{HIT_MARK}\", frame.GetFunctionName()); return False' {ids}\n"));
let args = p.arguments.iter().map(|a| a.replace('"', "\\\"")).map(|a| format!("\"{a}\"")).collect::<Vec<_>>().join(" ");
setup.push_str(&format!("process launch -- {args}\n"));
setup
@@ -288,6 +329,7 @@ mod macos {
.with_remediation("Install the macOS command-line developer tools (xcode-select --install).")
})?;
+ single_line(&p)?;
let setup = lldb_script(&p);
let root = private_root()?;
@@ -306,11 +348,19 @@ mod macos {
if let Some(wd) = &p.working_directory {
cmd = cmd.cwd(wd);
}
- let out = cmd.run()?;
+ let out = cmd.run();
let _ = std::fs::remove_dir_all(&root);
+ let out = out?;
+ if let Some(e) = lldb_failure(out.success, out.code, &out.stderr_text()) {
+ return Err(e);
+ }
- let hits: Vec<Value> =
- out.stdout_text().lines().filter_map(|l| l.strip_prefix("CRAFT_HIT ").map(|f| json!({"function": f.trim()}))).take(p.max_events).collect();
+ let hits: Vec<Value> = out
+ .stdout_text()
+ .lines()
+ .filter_map(|l| l.strip_prefix(HIT_MARK).and_then(|r| r.strip_prefix(' ')).map(|f| json!({"function": f.trim()})))
+ .take(p.max_events)
+ .collect();
let truncated = hits.len() >= p.max_events;
let summary = format!(
"Observed {} call(s) under lldb while running {}.",
@@ -655,6 +705,61 @@ mod tests {
assert_eq!(err.code, craft_anything_evidence::ErrorCode::ConsentRequired);
}
+ /// #251: the callback had a literal backslash and `n` between its Python statements, which lldb
+ /// rejected before it launched anything; and only breakpoint 1 got it.
+ #[test]
+ fn the_breakpoint_callback_is_one_valid_line_and_covers_every_breakpoint() {
+ use super::{Breakpoint, ObserveCallsParams, lldb_script};
+ let p = ObserveCallsParams {
+ executable: "/tmp/probe".into(),
+ arguments: Vec::new(),
+ working_directory: None,
+ breakpoints: vec![
+ Breakpoint::Function { name: "alpha".into(), module: None },
+ Breakpoint::ObjcMethod { class_name: "NSApplication".into(), selector: "run".into() },
+ ],
+ duration_ms: 10_000,
+ max_events: 100,
+ };
+ let script = lldb_script(&p);
+ let callback = script.lines().find(|l| l.starts_with("breakpoint command add")).unwrap();
+ assert!(!callback.contains("\\n"), "no literal backslash-n: {callback}");
+ assert!(callback.contains("print(\"CRAFT_HIT\", frame.GetFunctionName()); return False' 1 2 3"), "alpha plus both Objective-C forms: {callback}");
+ // The command comes after every breakpoint it names and before the launch.
+ let at = |needle: &str| script.find(needle).unwrap();
+ assert!(
+ at("breakpoint set --name \"+[NSApplication run]\"") < at("breakpoint command add") && at("breakpoint command add") < at("process launch"),
+ "{script}"
+ );
+ }
+
+ #[test]
+ fn a_failed_debugger_run_is_an_error_not_zero_calls() {
+ use super::lldb_failure;
+ assert!(lldb_failure(true, Some(0), "").is_none());
+ let e = lldb_failure(false, Some(1), "SyntaxError('unexpected character after line continuation character')").unwrap();
+ assert_eq!(e.code, craft_anything_evidence::ErrorCode::ProgramFailed);
+ assert!(e.message.contains("exited with code 1") && e.message.contains("SyntaxError") && e.message.contains("nothing was observed"), "{}", e.message);
+ assert!(lldb_failure(false, None, "").unwrap().message.contains("stopped by the system"));
+ }
+
+ /// A line break in a name or argument would add a command to the command file.
+ #[test]
+ fn names_and_arguments_cannot_add_debugger_commands() {
+ use super::{Breakpoint, ObserveCallsParams, single_line};
+ let with = |name: &str, arg: &str| ObserveCallsParams {
+ executable: "/tmp/probe".into(),
+ arguments: vec![arg.into()],
+ working_directory: None,
+ breakpoints: vec![Breakpoint::Function { name: name.into(), module: None }],
+ duration_ms: 1000,
+ max_events: 1,
+ };
+ assert!(single_line(&with("alpha", "--flag")).is_ok());
+ assert!(single_line(&with("alpha\nscript import os", "x")).is_err());
+ assert!(single_line(&with("alpha", "x\r\nquit")).is_err());
+ }
+
#[test]
fn module_filtered_function_breakpoints_omit_unsupported_name_mask() {
use super::{Breakpoint, ObserveCallsParams, lldb_script};
diff --git a/crates/ui-egui/src/builders.rs b/crates/ui-egui/src/builders.rs
index 7e9c70fc..a6076343 100644
--- a/crates/ui-egui/src/builders.rs
+++ b/crates/ui-egui/src/builders.rs
@@ -22,7 +22,7 @@ pub struct AgentModelPicker {
pub fn agent_model_picker(ui: &mut Ui, picker: &mut AgentModelPicker) -> bool {
let t = Tokens::get(ui.ctx());
let Some(result) = &picker.result else {
- ui.add(egui::Spinner::new().size(theme::CAPTION));
+ ui.add(crate::widgets::Spinner::new().size(theme::CAPTION));
ui.label(tr("Asking for its models…"));
return false;
};
@@ -327,7 +327,7 @@ pub fn need_builder_modal(app: &mut CraftApp, ui: &mut Ui, start: bool, close: &
let found: Vec<BackendConfig> = app.found_agents().cloned().collect();
if app.detecting {
ui.horizontal(|ui| {
- ui.add(egui::Spinner::new().color(t.accent));
+ ui.add(crate::widgets::Spinner::new().color(t.accent));
ui.label(RichText::new(tr("Looking on this computer…")).color(t.text_dim));
});
} else if found.is_empty() {
diff --git a/crates/ui-egui/src/engine_ui.rs b/crates/ui-egui/src/engine_ui.rs
index c80acaa3..7e349c2b 100644
--- a/crates/ui-egui/src/engine_ui.rs
+++ b/crates/ui-egui/src/engine_ui.rs
@@ -657,7 +657,7 @@ fn status_line(app: &mut CraftApp, ui: &mut Ui, b: Builder, offer: bool) {
let inv = app.game_engines.clone();
ui.horizontal_wrapped(|ui| match &inv {
None => {
- ui.add(egui::Spinner::new().size(14.0).color(t.accent));
+ ui.add(crate::widgets::Spinner::new().size(14.0).color(t.accent));
ui.label(RichText::new(tr("Looking for game engines on this computer…")).color(t.text_dim).size(theme::SMALL));
}
Some(inv) if inv.ready(b) => {
@@ -775,7 +775,7 @@ pub fn modal(app: &mut CraftApp, ui: &mut Ui, b: Builder, close: &mut bool) {
ui.set_width(520.0);
let Some(inv) = app.game_engines.clone() else {
ui.horizontal(|ui| {
- ui.add(egui::Spinner::new().size(16.0).color(t.accent));
+ ui.add(crate::widgets::Spinner::new().size(16.0).color(t.accent));
ui.label(tr("Looking for game engines on this computer…"));
});
app.refresh_game_engines();
diff --git a/crates/ui-egui/src/first_run.rs b/crates/ui-egui/src/first_run.rs
index 182dcfa1..babd523c 100644
--- a/crates/ui-egui/src/first_run.rs
+++ b/crates/ui-egui/src/first_run.rs
@@ -125,7 +125,7 @@ fn brain(app: &mut CraftApp, ui: &mut Ui, width: f32) {
ui.set_width(width);
if app.detecting {
ui.horizontal(|ui| {
- ui.add(egui::Spinner::new().color(t.accent));
+ ui.add(crate::widgets::Spinner::new().color(t.accent));
ui.label(RichText::new(tr("Looking for AI on this computer…")).color(t.text_dim));
});
ui.add_space(8.0);
diff --git a/crates/ui-egui/src/fr.tsv b/crates/ui-egui/src/fr.tsv
index ae56e7bc..99b98782 100644
--- a/crates/ui-egui/src/fr.tsv
+++ b/crates/ui-egui/src/fr.tsv
@@ -671,7 +671,7 @@ Builds and answers may use it again. Les constructions et les réponses peuvent
Remove it and its key La retirer avec sa clé
Off Désactivé
Detect Détecter
-Nothing found yet. We look for API keys, local model servers (Ollama, LM Studio) and agent apps you already have. Rien trouvé pour l'instant. Nous cherchons les clés d'API, les serveurs de modèles locaux (Ollama, LM Studio) et les applications d'agent que vous avez déjà.
+Nothing found yet. We look for API keys, local model servers (Ollama, LM Studio) and agent apps you already have. One on another port or computer can be added by its address below. Rien trouvé pour l'instant. Nous cherchons les clés d'API, les serveurs de modèles locaux (Ollama, LM Studio) et les applications d'agent que vous avez déjà. Un serveur sur un autre port ou un autre ordinateur peut être ajouté par son adresse ci-dessous.
Added Ajouté
Add Ajouter
API key (stored in your system keychain) Clé d'API (stockée dans le trousseau de votre système)
diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv
index 72f78a0b..d6fa1350 100644
--- a/crates/ui-egui/src/i18n/ru.tsv
+++ b/crates/ui-egui/src/i18n/ru.tsv
@@ -712,7 +712,7 @@ Not now Не сейчас
Nothing allowed yet. Пока ничего не разрешено.
Nothing can build yet: install Claude Code (and sign in to it once), or add an AI with an API key below. Пока ничего нельзя собрать: установите Claude Code (и один раз войдите в него) или добавьте ИИ с ключом API ниже.
Nothing found Ничего не найдено
-Nothing found yet. We look for API keys, local model servers (Ollama, LM Studio) and agent apps you already have. Пока ничего не найдено. Мы ищем ключи API, локальные серверы моделей (Ollama, LM Studio) и приложения-агенты, которые у вас уже есть.
+Nothing found yet. We look for API keys, local model servers (Ollama, LM Studio) and agent apps you already have. One on another port or computer can be added by its address below. Пока ничего не найдено. Мы ищем ключи API, локальные серверы моделей (Ollama, LM Studio) и приложения-агенты, которые у вас уже есть. Сервер на другом порту или другом компьютере можно добавить по адресу ниже.
Nothing inside it is read. Внутри ничего не читается.
Nothing inside it is read; Craft Anything works from what you can see. Your version gets its own art. Внутри ничего не читается; Craft Anything работает с тем, что вы можете увидеть. Ваша версия получит собственную графику.
Nothing inside the original is read: not its code, files or page source. Craft Anything works from what you can see: pictures, the page as a visitor sees it, and watching it run. Внутри оригинала ничего не читается: ни код, ни файлы, ни исходник страницы. Craft Anything работает с тем, что вы можете увидеть: изображениями, страницей глазами посетителя и наблюдением за её работой.
diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv
index 69f9f95f..d07129cc 100644
--- a/crates/ui-egui/src/i18n/zh-hans.tsv
+++ b/crates/ui-egui/src/i18n/zh-hans.tsv
@@ -720,7 +720,7 @@ Not now 暂时不要
Nothing allowed yet. 尚未允许任何操作。
Nothing can build yet: install Claude Code (and sign in to it once), or add an AI with an API key below. 尚无可用的构建助手:请安装 Claude Code (并先登录一次),或在下方添加配置了 API 密钥的 AI。
Nothing found 未找到内容
-Nothing found yet. We look for API keys, local model servers (Ollama, LM Studio) and agent apps you already have. 尚未找到。我们会查找你已有的 API 密钥、本地模型服务器 (Ollama、LM Studio) 和智能体应用。
+Nothing found yet. We look for API keys, local model servers (Ollama, LM Studio) and agent apps you already have. One on another port or computer can be added by its address below. 尚未找到。我们会查找你已有的 API 密钥、本地模型服务器 (Ollama、LM Studio) 和智能体应用。其他端口或其他电脑上的服务器可以在下方按地址添加。
Nothing inside it is read. 不会读取其内部内容。
Nothing inside it is read; Craft Anything works from what you can see. Your version gets its own art. 不会读取其内部内容;Craft Anything 仅依据你能看到的内容工作。你的版本会使用自己的美术素材。
Nothing inside the original is read: not its code, files or page source. Craft Anything works from what you can see: pictures, the page as a visitor sees it, and watching it run. 不会读取原作的内部内容,包括代码、文件和网页源码。Craft Anything 仅根据可见内容工作:图片、访客所见的网页以及运行时的表现。
diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv
index 2c60ac39..5d0c91b7 100644
--- a/crates/ui-egui/src/i18n/zh-hant.tsv
+++ b/crates/ui-egui/src/i18n/zh-hant.tsv
@@ -720,7 +720,7 @@ Not now 暫時不要
Nothing allowed yet. 尚未允許任何操作。
Nothing can build yet: install Claude Code (and sign in to it once), or add an AI with an API key below. 尚無可用的建置助手:請安裝 Claude Code (並先登入一次),或在下方新增設定了 API 金鑰的 AI。
Nothing found 未找到內容
-Nothing found yet. We look for API keys, local model servers (Ollama, LM Studio) and agent apps you already have. 尚未找到。我們會尋找你已有的 API 金鑰、本機模型伺服器 (Ollama、LM Studio) 和代理程式應用程式。
+Nothing found yet. We look for API keys, local model servers (Ollama, LM Studio) and agent apps you already have. One on another port or computer can be added by its address below. 尚未找到。我們會尋找你已有的 API 金鑰、本機模型伺服器 (Ollama、LM Studio) 和代理程式應用程式。其他連接埠或其他電腦上的伺服器可以在下方依位址新增。
Nothing inside it is read. 不會讀取其內部內容。
Nothing inside it is read; Craft Anything works from what you can see. Your version gets its own art. 不會讀取其內部內容;Craft Anything 僅依據你能看到的內容工作。你的版本會使用自己的美術素材。
Nothing inside the original is read: not its code, files or page source. Craft Anything works from what you can see: pictures, the page as a visitor sees it, and watching it run. 不會讀取原作的內部內容,包括程式碼、檔案和網頁原始碼。Craft Anything 僅根據可見內容工作:圖片、訪客所見的網頁以及執行時的表現。
diff --git a/crates/ui-egui/src/ja.tsv b/crates/ui-egui/src/ja.tsv
index fc5e3ae3..eb7715da 100644
--- a/crates/ui-egui/src/ja.tsv
+++ b/crates/ui-egui/src/ja.tsv
@@ -413,7 +413,7 @@ Not now 後で
Nothing allowed yet. まだ何も許可されていません。
Nothing can build yet: install Claude Code (and sign in to it once), or add an AI with an API key below. まだビルドできません。Claude Code をインストールして一度サインインするか、下で API キーを使って AI を追加してください。
Nothing found 何も見つかりません
-Nothing found yet. We look for API keys, local model servers (Ollama, LM Studio) and agent apps you already have. まだ見つかっていません。API キー、ローカルのモデルサーバー(Ollama、LM Studio)、すでにあるエージェントアプリを探します。
+Nothing found yet. We look for API keys, local model servers (Ollama, LM Studio) and agent apps you already have. One on another port or computer can be added by its address below. まだ見つかっていません。API キー、ローカルのモデルサーバー(Ollama、LM Studio)、すでにあるエージェントアプリを探します。別のポートや別のコンピュータにあるサーバーは、下でアドレスを指定して追加できます。
Nothing inside it is read. 中身は一切読みません。
Nothing inside it is read; we work from what you can see. Your version gets its own art. 中身は読みません。見えるものから作業し、あなたの版には独自のアートを使います。
Nothing made yet. What you make shows up here. まだ何も作っていません。作ったものがここに並びます。
diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs
index 62f44edb..7ed32e0d 100644
--- a/crates/ui-egui/src/lib.rs
+++ b/crates/ui-egui/src/lib.rs
@@ -347,12 +347,22 @@ pub struct Prefs {
pub const PREFS_KEY: &str = "craft-anything-ui";
const LEDGER_VIEW_CAP: usize = 300;
+/// Frames that must have been shown before [`CraftApp::after_first_frames`] runs its callback.
+const FIRST_FRAMES: u32 = 2;
+
+struct FirstFrames {
+ drawn: u32,
+ done: Box<dyn FnOnce() + Send>,
+}
+
pub struct CraftApp {
pub engine: Arc<Engine>,
pub hub: Arc<AiHub>,
pub state: UiState,
/// The UI's copy of the settings; pushed into the session (and saved) when changed.
pub settings: Settings,
+ /// Run once after the first frames have been drawn and shown (see [`CraftApp::after_first_frames`]).
+ first_frames: Option<FirstFrames>,
/// Write settings to disk (off in tests and snapshots).
pub persist: bool,
/// Never open native dialogs (tests and snapshots).
@@ -464,6 +474,7 @@ impl CraftApp {
hub,
state: UiState::default(),
settings,
+ first_frames: None,
persist: true,
headless: false,
view: SessionView::default(),
@@ -527,6 +538,13 @@ impl CraftApp {
egui_extras::install_image_loaders(ctx);
}
+ /// Call `done` once [`FIRST_FRAMES`] frames have been drawn and shown: the window is really up by
+ /// then. eframe opens the window hidden and draws its first frame after the app is built, so
+ /// a graphics driver that crashes while presenting does so after that (#74).
+ pub fn after_first_frames(&mut self, done: impl FnOnce() + Send + 'static) {
+ self.first_frames = Some(FirstFrames { drawn: 0, done: Box::new(done) });
+ }
+
/// Restore remembered preferences.
pub fn load_prefs(&mut self, storage: Option<&dyn eframe::Storage>) {
let Some(text) = storage.and_then(|s| s.get_string(PREFS_KEY)) else { return };
@@ -1742,6 +1760,18 @@ pub fn guard_ui(ui: &mut egui::Ui, what: &str, f: impl FnOnce(&mut egui::Ui)) {
impl eframe::App for CraftApp {
fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) {
+ // This frame is being built, so the ones before it have been shown.
+ if let Some(f) = self.first_frames.as_mut() {
+ f.drawn += 1;
+ if f.drawn > FIRST_FRAMES
+ && let Some(f) = self.first_frames.take()
+ {
+ (f.done)();
+ } else {
+ // egui only draws when something changed; keep drawing until the frames have been shown.
+ ui.ctx().request_repaint();
+ }
+ }
self.show(ui);
}
@@ -1752,6 +1782,10 @@ impl eframe::App for CraftApp {
}
fn on_exit(&mut self) {
+ // Closed before the frames were counted: the window opened, so nothing crashed.
+ if let Some(f) = self.first_frames.take() {
+ (f.done)();
+ }
// A running build saves the project's conversation itself (rebuild::feed).
if let Some(c) = self.conversation.as_mut() {
c.stop();
diff --git a/crates/ui-egui/src/project.rs b/crates/ui-egui/src/project.rs
index d6c04ce1..8fbb4498 100644
--- a/crates/ui-egui/src/project.rs
+++ b/crates/ui-egui/src/project.rs
@@ -481,7 +481,7 @@ fn checklist(ui: &mut Ui, steps: &[PlanStep], t: &Tokens, began: Option<std::tim
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
if let Some(b) = began {
ui.label(RichText::new(crate::usage::duration_words(b.elapsed())).font(theme::mono(12.0)).color(t.text_faint));
- ui.add(egui::Spinner::new().size(12.0).color(t.accent));
+ ui.add(crate::widgets::Spinner::new().size(12.0).color(t.accent));
ui.ctx().request_repaint_after(std::time::Duration::from_secs(1));
}
ui.label(
diff --git a/crates/ui-egui/src/settings_ui.rs b/crates/ui-egui/src/settings_ui.rs
index 5d566c3c..b160376d 100644
--- a/crates/ui-egui/src/settings_ui.rs
+++ b/crates/ui-egui/src/settings_ui.rs
@@ -410,7 +410,7 @@ fn ai(app: &mut CraftApp, ui: &mut Ui) {
}
}
Some((_, None)) => {
- ui.add(egui::Spinner::new().size(theme::CAPTION).color(t.accent));
+ ui.add(crate::widgets::Spinner::new().size(theme::CAPTION).color(t.accent));
ui.label(RichText::new(tr("Asking for its models…")).color(t.text_faint).size(theme::CAPTION));
}
Some((_, Some(models))) => {
@@ -546,7 +546,7 @@ fn ai(app: &mut CraftApp, ui: &mut Ui) {
widgets::caption(ui, "Found on this computer");
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
if app.detecting {
- ui.add(egui::Spinner::new().color(t.accent));
+ ui.add(crate::widgets::Spinner::new().color(t.accent));
} else if widgets::secondary(ui, Some("radar"), "Detect").clicked() {
app.detect_backends();
}
@@ -556,7 +556,7 @@ fn ai(app: &mut CraftApp, ui: &mut Ui) {
let detected = app.detected.clone().unwrap_or_default();
if detected.is_empty() && !app.detecting {
ui.label(
- RichText::new(tr("Nothing found yet. We look for API keys, local model servers (Ollama, LM Studio) and agent apps you already have."))
+ RichText::new(tr("Nothing found yet. We look for API keys, local model servers (Ollama, LM Studio) and agent apps you already have. One on another port or computer can be added by its address below."))
.color(t.text_faint),
);
}
diff --git a/crates/ui-egui/src/titlebar.rs b/crates/ui-egui/src/titlebar.rs
index 2bbc3a58..8cb453e2 100644
--- a/crates/ui-egui/src/titlebar.rs
+++ b/crates/ui-egui/src/titlebar.rs
@@ -186,7 +186,8 @@ pub fn show(app: &mut CraftApp, ui: &mut Ui) {
usage_pill(app, ui);
if app.jobs.busy() {
let n = app.jobs.running().filter(|j| j.visible).count();
- ui.add(egui::Spinner::new().size(14.0).color(t.accent)).on_hover_text(crate::i18n::trf("{n} job(s) running", &[("n", &n.to_string())]));
+ ui.add(crate::widgets::Spinner::new().size(14.0).color(t.accent))
+ .on_hover_text(crate::i18n::trf("{n} job(s) running", &[("n", &n.to_string())]));
}
});
});
diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs
index 68c2ec22..83849692 100644
--- a/crates/ui-egui/src/widgets.rs
+++ b/crates/ui-egui/src/widgets.rs
@@ -384,6 +384,59 @@ pub fn animate(ui: &Ui, every: std::time::Duration) {
/// One frame of an animation at the usual pace.
pub const FRAME: std::time::Duration = std::time::Duration::from_millis(66);
+/// A spinning arc for "working", drawn like egui's own `Spinner` but asking for its next frame at
+/// [`animate`]'s pace. egui's asks to be drawn again at once, every frame, for as long as it's on
+/// screen: a build or a page capture can run for an hour, and redrawing the whole window at the
+/// display's rate for it kept a CPU core (or, drawing in software, all of them) busy (#579).
+#[must_use = "put it in a ui with `ui.add(widget);`"]
+#[derive(Default)]
+pub struct Spinner {
+ size: Option<f32>,
+ color: Option<Color32>,
+}
+
+impl Spinner {
+ pub fn new() -> Self {
+ Self::default()
+ }
+
+ pub fn size(mut self, size: f32) -> Self {
+ self.size = Some(size);
+ self
+ }
+
+ pub fn color(mut self, color: Color32) -> Self {
+ self.color = Some(color);
+ self
+ }
+}
+
+impl egui::Widget for Spinner {
+ fn ui(self, ui: &mut Ui) -> Response {
+ let size = self.size.unwrap_or_else(|| ui.style().spacing.interact_size.y);
+ let (rect, response) = ui.allocate_exact_size(Vec2::splat(size), Sense::hover());
+ response.widget_info(|| egui::WidgetInfo::new(egui::WidgetType::ProgressIndicator));
+ if ui.is_rect_visible(rect) {
+ let color = self.color.unwrap_or_else(|| ui.visuals().strong_text_color());
+ let radius = (rect.height().min(rect.width()) / 2.0) - 2.0;
+ let n_points = (radius.round() as u32).clamp(8, 128);
+ let time = ui.input(|i| i.time);
+ let start = time * std::f64::consts::TAU;
+ let end = start + 240f64.to_radians() * time.sin();
+ let points: Vec<egui::Pos2> = (0..n_points)
+ .map(|i| {
+ let angle = start + (end - start) * (i as f64 / n_points as f64);
+ let (sin, cos) = angle.sin_cos();
+ rect.center() + radius * egui::vec2(cos as f32, sin as f32)
+ })
+ .collect();
+ ui.painter().add(egui::Shape::line(points, Stroke::new(3.0, color)));
+ animate(ui, FRAME);
+ }
+ response
+ }
+}
+
/// A spinner-ish dot row for "thinking".
pub fn thinking(ui: &mut Ui) {
let t = Tokens::get(ui.ctx());
@@ -483,6 +536,50 @@ mod tests {
use super::*;
use std::time::Duration;
+ /// #579: egui's `Spinner` asks to be redrawn at once, every frame, for as long as it shows;
+ /// ours waits for the animation's own pace, so an hour-long build isn't drawn at the display's
+ /// rate. Both are drawn here for comparison.
+ #[test]
+ fn a_spinner_on_screen_does_not_ask_for_a_frame_at_once() {
+ let wait_after = |add: &dyn Fn(&mut Ui)| {
+ let ctx = egui::Context::default();
+ let mut raw = egui::RawInput::default();
+ raw.viewports.entry(egui::ViewportId::ROOT).or_default().focused = Some(true);
+ // The first frames always ask for another (layout settles); look at a settled one.
+ let mut out = egui::FullOutput::default();
+ for _ in 0..4 {
+ out = ctx.run_ui(raw.clone(), |ui| add(ui));
+ out.textures_delta.clear();
+ }
+ out.viewport_output.get(&egui::ViewportId::ROOT).map(|v| v.repaint_delay).unwrap_or_default()
+ };
+ let egui_spinner = wait_after(&|ui| {
+ ui.add(egui::Spinner::new());
+ });
+ assert!(egui_spinner < Duration::from_millis(10), "egui's own asks for the next frame at once: {egui_spinner:?}");
+ let ours = wait_after(&|ui| {
+ ui.add(Spinner::new().size(16.0));
+ });
+ assert!(ours >= Duration::from_millis(30), "ours waits for the animation's pace: {ours:?}");
+ }
+
+ /// #579: every screen uses our spinner; egui's own would bring the redraw-every-frame back.
+ #[test]
+ fn no_screen_uses_eguis_own_spinner() {
+ let src = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src");
+ let mut used = Vec::new();
+ for entry in std::fs::read_dir(&src).unwrap().flatten() {
+ let path = entry.path();
+ if path.extension().is_some_and(|e| e == "rs") && path.file_name().is_some_and(|n| n != "widgets.rs") {
+ let text = std::fs::read_to_string(&path).unwrap();
+ if text.lines().any(|l| !l.trim_start().starts_with("//") && l.contains("egui::Spinner")) {
+ used.push(path.file_name().unwrap().to_string_lossy().into_owned());
+ }
+ }
+ }
+ assert!(used.is_empty(), "use `widgets::Spinner`, which doesn't ask for a frame every frame: {used:?}");
+ }
+
#[test]
fn the_wait_note_says_when_nothing_is_happening() {
let quiet = wait_note(4000, Some(Duration::from_secs(150))).unwrap();
diff --git a/crates/ui-egui/src/workbench.rs b/crates/ui-egui/src/workbench.rs
index 279bed96..d24ca533 100644
--- a/crates/ui-egui/src/workbench.rs
+++ b/crates/ui-egui/src/workbench.rs
@@ -224,11 +224,11 @@ fn rail_list(app: &mut CraftApp, ui: &mut Ui, kind: RailKind, fill: &Fill) {
match fill {
Fill::Idle => {
app.ensure_rail_loaded();
- ui.add(egui::Spinner::new().color(t.accent));
+ ui.add(crate::widgets::Spinner::new().color(t.accent));
}
Fill::Loading => {
ui.horizontal(|ui| {
- ui.add(egui::Spinner::new().color(t.accent));
+ ui.add(crate::widgets::Spinner::new().color(t.accent));
ui.label(RichText::new(tr("Loading…")).color(t.text_dim));
});
}
@@ -467,7 +467,7 @@ fn tool_view(app: &mut CraftApp, ui: &mut Ui, tab: CenterTab) {
}
Fill::Loading => {
ui.horizontal(|ui| {
- ui.add(egui::Spinner::new().color(Tokens::get(ui.ctx()).accent));
+ ui.add(crate::widgets::Spinner::new().color(Tokens::get(ui.ctx()).accent));
ui.label(tr("Working…"));
});
}
@@ -691,7 +691,7 @@ fn result_view(app: &mut CraftApp, ui: &mut Ui) {
match (fill, selected) {
(Some(Fill::Loading), _) => {
ui.horizontal(|ui| {
- ui.add(egui::Spinner::new().color(t.accent));
+ ui.add(crate::widgets::Spinner::new().color(t.accent));
ui.label(tr("Working…"));
});
}
diff --git a/crates/ui-egui/tests/headless_parity.rs b/crates/ui-egui/tests/headless_parity.rs
index 338bd3b6..4f0801b8 100644
--- a/crates/ui-egui/tests/headless_parity.rs
+++ b/crates/ui-egui/tests/headless_parity.rs
@@ -143,7 +143,7 @@ const PLUMBING: &[(&str, &str)] = &[
("acted", "shows a button tool's result (toast, open the preview)"),
("engines_found", "a job's result"), ("engine_got", "a job's result"), ("ghidra_got", "a job's result"),
("ghidra_ready", "a query"), ("ghidra_missing", "a query"),
- ("load_prefs", "startup"), ("log", "the log panel"), ("toast", "a message"),
+ ("load_prefs", "startup"), ("after_first_frames", "startup"), ("log", "the log panel"), ("toast", "a message"),
("settings_changed", "marks settings dirty; each setting has its row"), ("flush_settings", "saves settings"),
("refresh_view", "redraw data"), ("resolve_chat_evidence", "redraw data"), ("mark_dirty", "redraw data"),
("poll_conversation", "polling"), ("allow_for_project", "part of answer_consent"),
diff --git a/crates/ui-egui/tests/smoke.rs b/crates/ui-egui/tests/smoke.rs
index 2119c683..f8f63da2 100644
--- a/crates/ui-egui/tests/smoke.rs
+++ b/crates/ui-egui/tests/smoke.rs
@@ -2279,3 +2279,25 @@ fn a_narrow_window_folds_the_sidebar_and_puts_the_project_details_above_the_feed
let send = h.get_by_label("Send (Enter)").rect();
assert!(send.max.x <= 760.0 && send.max.y <= 820.0, "the prompt box fits: {send:?}");
}
+
+/// #74: a graphics driver can crash while the first frames are presented, so the start's mark is
+/// cleared only after frames were shown; the callback runs once, keeps frames coming until then,
+/// and also runs when the window is closed before that.
+#[test]
+fn the_first_frames_callback_runs_once_after_frames_were_shown() {
+ use std::sync::Arc;
+ use std::sync::atomic::{AtomicUsize, Ordering};
+ let calls = Arc::new(AtomicUsize::new(0));
+ let seen = calls.clone();
+ let mut h = harness(move || {
+ let mut app = demo::app(demo::engine(Mode::Beginner, false));
+ app.after_first_frames(move || {
+ seen.fetch_add(1, Ordering::SeqCst);
+ });
+ app
+ });
+ h.run_steps(8);
+ assert_eq!(calls.load(Ordering::SeqCst), 1, "once the frames were shown, and only once");
+ h.run_steps(8);
+ assert_eq!(calls.load(Ordering::SeqCst), 1);
+}
diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md
index 3b9d3860..145e9933 100644
--- a/docs/ROADMAP.md
+++ b/docs/ROADMAP.md
@@ -126,6 +126,17 @@ cheapest help we can give anyone, so nothing below should hold it up for long.
path, not its name
- [ ] Live-check #152 on Windows 11 with OpenCode from npm, and on a machine with the agent but no
Node.js
+- [x] A start that dies before its window (a native driver crash leaves no dialog or log, #74, #104,
+ #33) is remembered: `starting` beside `desktop.log` is written before the window is asked for
+ and removed once it's open, and a start that finds it draws with WARP that once
+ (`apps/craft-anything/src/start_guard.rs`)
+- [ ] Live-check the start fallback on Windows: make a start die before its window (kill the
+ process at launch), start again, and see `desktop.log` say it drew without the graphics card
+ and log `drawing with` an adapter of type `Cpu` (WARP), and that the window opens
+- [ ] The software retry still lets wgpu start every DX12 adapter before `pick_adapter` runs, so a
+ driver that crashes while its device is created crashes the retry too. wgpu has no way to
+ skip hardware adapters; needs a different route (another renderer, or a helper that starts
+ the app with only WARP visible)
- [ ] Add to `docs/releasing.md`: before publishing, a Deep build through Claude Code from the
finished package, on a Mac and on Windows. Starting the CLI from the package (#91) doesn't
show whether Claude Code accepts its tools
@@ -166,6 +177,11 @@ only when it's green and a maintainer has fully reviewed it, code as well as wor
here any more: every job calls `storytold/craft-common-actions@main`, so a fix belongs there
- [ ] STATUS.md's "Known limits" still says the project feed, game-engine and Ghidra installs and
launching exist only in the desktop app, which R1.6 ended: update it
+- [x] A spinner on screen no longer makes the window redraw at the display's rate: egui's own asks
+ for a frame at once every frame, ours at the animation's pace (`widgets::Spinner`, #579)
+- [ ] Measure #579 on Windows 11 (0.3.0 portable): the app's CPU while idle, while a build runs and
+ during a website capture, before and after; and why a website capture is slow and sits for a
+ long time (no details were given, so nothing was changed for it)
### R5.3 A builder that can't make progress stops
Owner: open · Status: todo
@@ -190,8 +206,12 @@ Every round spends the person's money or quota. One that can't do anything shoul
`agent.session_id()` is set, which API backends and OpenCode's plain adapter never set (read
in the code, not run). So #148 didn't reach #142, which was OpenCode. Wait and send the turn
again for them too, then close #142 — commit `f80a16a66834`
-- [ ] **decision** Whether a build gets a token or cost limit of its own, beyond rounds: #399 used
- 9.4M tokens in 19 minutes of the first stage, then failed to compile
+- [x] A builder step on an API backend stops after 25 failed build commands in a row (none
+ succeeding between), says so and keeps the project (`MAX_FAILED_BUILDS` in `agent.rs`, #399:
+ 9.4M tokens in 19 minutes of the first stage, never compiled). Try again carries on
+- [ ] **decision** Whether a build gets a token or cost limit of its own, beyond rounds and that
+ stop (#399): a model that changes code without ever running a build isn't caught by it
+- [ ] Check live that the stop fires on a real API-backend build and the message reads well
### R5.4 Local models can build
Owner: open · Status: todo
@@ -200,6 +220,12 @@ The built-in agent loop assumes a capable tool-calling model. Reports #24, #44,
been run live.
- [ ] A live local build through Ollama, small target, to Ready or to a clear stop, and note in
STATUS.md which models it worked with. Do this first: it shows which of the lines below matter
+- [x] A builder on a local model is offered 13 tools (about 10,000 characters of descriptions)
+ instead of 33-41 (23,000-30,000): the Build tools and the Core tools the brief names, not the
+ study set a model explores with instead of writing (#417, `LOCAL_BUILDER_CORE`). Measured as
+ text, not on a model; Ollama's default context (4k) was too small for the old list alone
+- [ ] Run #417's case live (Ollama, `qwen2.5-coder:14b`, "a scientific calculator") before and
+ after this: does it call `build_file_write` now? If it still doesn't, the model can't build
- [ ] An assistant turn with no text sends `content: null` (`openai.rs`), which likely causes #403's
`invalid message content type: <nil>`: send an empty string
- [x] Understand a tool call a model writes as JSON in its text (#417; implementation `dfe9a4db2dcb3e27edbd67311cbb4202584e7af6`). The fallback protocol reads
@@ -215,7 +241,11 @@ been run live.
may ignore anyway; LM Studio refused a 12.6k prompt on its 8k default (#73)
- [x] A per-backend context budget in `[[ai.backends]]` (`LoopConfig::context_tokens` exists), for
services whose real window differs from 150k (#374) — implementation: `6bd94b84828ec89b805cb8a246f557d0a778c037`
-- [ ] Find LM Studio on another port (#73)
+- [x] Find LM Studio on another port (#73): the port in its settings file (when it is there) and
+ the ports 1235-1239 are probed like the usual servers; OpenCode's own `baseURL`s were already
+ read (#83)
+- [ ] Check live that LM Studio on `--port 1235` is offered, and where its settings file is on
+ Windows, macOS and Linux (`LM_STUDIO_SETTINGS` is from memory of its folders, not verified)
- [ ] See why Bionic or LM Studio can't be picked (#140)
- [x] Do not select an embedding, ranking or transcription model as a chat backend when a local server has no chat models — claimed: Afloat16, branch bugfix/r5.4-nonchat-model-detection-20261103
@@ -226,6 +256,12 @@ Owner: open · Status: todo
— claimed: Afloat16, branch bugfix/r5.5-bounded-sse-events-20261103
- [x] Show the provider's own reason: #369 bought $10 of credit and got only "OpenRouter answered
400: Provider returned error". Find the reason in the response body and show it — PR #542
+- [x] OpenRouter picks an upstream provider per request, and one without tool calling answered
+ "400: Provider returned error" (#369): a request with tools now sets
+ `provider.require_parameters`, and a 404 "no provider for these parameters" falls back to the
+ text protocol like any server that rejects tools
+- [ ] Check #369 live with Kimi K3 and a key limited to Kimi/Moonshot models (needs the person's
+ OpenRouter key): that the build starts, or that the error now names the provider's reason
- [ ] A live API-key build (needs a key on the test machine)
- [ ] Failure logs for the other ways an AI stops (API backends, MCP server start-up), like the
ones agent CLIs write to `logs/` in the config folder
@@ -435,6 +471,13 @@ Owner: open · Status: in progress
### R2.4 Runtime study for apps and games (with consent)
Owner: maintainers · Status: in progress
- [ ] UI tree on Linux (AT-SPI)
+- [x] `apple_calls_observe`: the breakpoint callback is one valid line (it had a literal backslash
+ and `n` between statements, so lldb stopped before launching, #251), covers every breakpoint
+ instead of only the first, a failed lldb run is an error and not "0 calls", and names or
+ arguments with line breaks are refused (they'd add commands to lldb's command file). The
+ callback body was compiled with Python; lldb itself was not run
+- [ ] Run `apple_calls_observe` on a Mac against a small program with `lldb` (the #251 probe):
+ the hit for `alpha` is recorded, and a program lldb can't debug says so
- [ ] Window capture tried on macOS and Linux (only Windows so far); games behind a launcher
- [ ] Short scripted input sessions (enigo) to record screens of the original
diff --git a/docs/pitfalls.md b/docs/pitfalls.md
index b061a339..68cfba9e 100644
--- a/docs/pitfalls.md
+++ b/docs/pitfalls.md
@@ -194,6 +194,45 @@ that runs code read only `allow`, so "Always" was dropped and the same tool (a s
was asked about every time (#563). When a card offers a choice, whoever reads the answer handles
every field of it, and a test answers it each way and asks again.
+**A loop that only ends at its step cap.** A builder on an API backend may take 400 steps in one
+step of the run, and each step sends the whole conversation again: one stage spent 9.4M tokens on
+code that never compiled (#399). A failed build command is an `Ok` tool result (`succeeded: false`),
+so counting tool errors misses it. Cap a loop on what it is stuck on (build commands failing in a
+row, read from the typed `succeeded` field), not only on its total steps.
+
+**A router that picks the provider for you.** OpenRouter sends each request to one of several
+upstream providers, and a provider without tool calling answered 400 "Provider returned error"
+(#369), which said nothing the person could act on. For a service that routes, say in the request
+what the provider must support (`provider.require_parameters` for tools), and show the provider's
+own reason when it still fails (#542).
+
+**A crash that no code can report.** Three Windows tickets (#33, #104, #74) said the app "does
+nothing": a graphics driver crashed natively as the window opened, so no dialog, panic hook or log
+line ever ran, and each fix only covered the driver already seen. When a failure can't be caught,
+leave a mark before the risky step and clear it after (`start_guard.rs`); a mark found at the next
+start is the report, and that start takes the safer path (WARP). Not run on Windows here.
+
+**A spinner that kept the window drawing at full speed.** egui's `Spinner` asks to be redrawn at
+once, every frame, while it's on screen. A build or a page capture can run for an hour, so the
+window was redrawn at the display's rate the whole time (a core busy, or every core when drawing in
+software), and a person reported "my CPU is fully used" (#579). Animations ask for their next frame
+at their own pace (`widgets::animate`, `widgets::Spinner`); check a library widget for
+`request_repaint` before using it for something long. Not measured on Windows here.
+
+**Every tool offered to a model that can only use a few.** The builder on an API backend was sent
+all 33-41 Core and Build tools, about 23,000-30,000 characters of descriptions. A local 14B model
+(#417) called the study tools (`core_session_show`, `core_journal_read`) 35 times and never
+`build_file_write`, and Ollama's default context is smaller than the list. Offer a model the tools
+the job needs (`LOCAL_BUILDER_CORE`), measure the list's size with the real registry, and run a
+small local model before saying it works. Not run live here.
+
+**A debugger failure reported as an observation.** `apple_calls_observe` built a Python callback
+with `\n` between statements in a Rust string, so lldb rejected it and exited 1 before launching
+anything; the tool ignored the exit status and returned "Observed 0 call(s)" with confidence
+observed (#251). A run that never started the thing it observes is a failure, not a count of zero:
+check the exit status before building evidence, and compile generated code (here, with Python)
+before trusting it. lldb itself was not run here.
+
**A Mac app that couldn't find Claude Code, and offered a GitHub key instead.** An app opened from
the Dock gets the system's short `PATH`, not the shell's, so `claude` in `~/.local/bin` wasn't
found; "Built by" then fell back to "Claude Code on github.com-work", an `~/.ssh/config` alias