diff --git a/.gitignore b/.gitignore index 8e0305251..1ba851ad5 100644 --- a/.gitignore +++ b/.gitignore @@ -7,6 +7,7 @@ /.claude/worktrees/ /target-snapshot __pycache__/ +.vscode/ # cargo-mutants output (docs/mutation-testing.md) mutants.out*/ diff --git a/apps/solidcraft/src/main.rs b/apps/solidcraft/src/main.rs index c63bc4811..7cbe44253 100644 --- a/apps/solidcraft/src/main.rs +++ b/apps/solidcraft/src/main.rs @@ -498,6 +498,18 @@ fn backend_preference() -> Option { graphics().and_then(|v| v.get("backend").and_then(serde_json::Value::as_str).map(str::to_string)) } +/// The viewport scene's sample count: the app's anti-aliasing (the window's pass is 1x), clamped +/// by the backend's policy (OpenGL renders 1x, see `effective_msaa_samples`). A count the device +/// cannot render with falls back to the supported default. +fn scene_samples(backend: eframe::wgpu::Backend, samples: u32, supported: &[u32]) -> u32 { + let requested = eframe::egui_wgpu::effective_msaa_samples(backend, samples.max(1)); + if requested <= 1 || supported.is_empty() || supported.contains(&requested) { + requested + } else { + supported.iter().copied().filter(|&n| n <= solidcraft_ui_egui::prefs::Prefs::default().msaa).max().unwrap_or(1) + } +} + /// Anti-aliasing samples from Preferences (4 when unset). fn msaa() -> u16 { graphics() @@ -697,16 +709,7 @@ fn main() -> eframe::Result { lost_at: None, }); if let Some(rs) = &cc.wgpu_render_state { - // The viewport's scene keeps the app's anti-aliasing; the window's pass is 1x. - // A count the device cannot render with falls back to the supported default. - let scene_samples = { - let requested = u32::from(samples).max(1); - if requested <= 1 || rs.msaa_supported.is_empty() || rs.msaa_supported.contains(&requested) { - requested - } else { - rs.msaa_supported.iter().copied().filter(|&n| n <= solidcraft_ui_egui::prefs::Prefs::default().msaa).max().unwrap_or(1) - } - }; + let scene_samples = scene_samples(rs.adapter.get_info().backend, u32::from(samples), &rs.msaa_supported); eprintln!("SolidCraft graphics: {:?}, MSAA {scene_samples}x (requested {}x)", rs.adapter.get_info().backend, samples); solidcraft_engine::crash::phase("viewport pipelines (shader compile)"); app.set_wgpu_split(rs, depth_bits, STENCIL_BITS, scene_samples); @@ -947,4 +950,13 @@ mod msaa_tests { } } } + + #[test] + fn the_scene_follows_the_backend_policy_too() { + use eframe::wgpu::Backend; + assert_eq!(super::scene_samples(Backend::Gl, 4, &[1, 4]), 1); + assert_eq!(super::scene_samples(Backend::Gl, 4, &[]), 1); + assert_eq!(super::scene_samples(Backend::Vulkan, 4, &[1, 4]), 4); + assert_eq!(super::scene_samples(Backend::Dx12, 8, &[1, 2, 4]), 4); + } } diff --git a/assets/locales/en.json b/assets/locales/en.json index 22bbb85e8..79c32e881 100644 --- a/assets/locales/en.json +++ b/assets/locales/en.json @@ -1402,6 +1402,9 @@ "thread.designation": "Designation", "thread.iso_metric": "ISO metric", "thread.select_size": "Select size", + "timeline.delete_after_marker_one": "Delete 1 Feature After History Marker", + "timeline.delete_after_marker_other": "Delete {count} Features After History Marker", + "timeline.delete_many": "Delete {count} Selected Features", "timeline.group": "New Feature Folder", "timeline.move_many": "Move Timeline Items", "timeline.move_to_group": "Move Features to Folder", @@ -1553,8 +1556,10 @@ "ui.ai_add": "Add", "ui.ai_add_agent": "Add agent…", "ui.ai_add_agent_title": "Add agent", + "ui.ai_add_anthropic": "Anthropic-compatible API", "ui.ai_add_api": "OpenAI-compatible API", "ui.ai_add_custom": "Custom command", + "ui.ai_add_endpoint": "API endpoint", "ui.ai_add_installed": "Installed agent", "ui.ai_add_installed_note": "An entry of your own for an installed agent, for example with other arguments. Installed agents are listed by themselves.", "ui.ai_added": "added", @@ -1583,6 +1588,7 @@ "ui.ai_key_needs_https": "A key is only sent over HTTPS, or to this computer.", "ui.ai_key_note": "Stored in the system keychain, never in SolidCraft's settings. Leave it empty for a local server.", "ui.ai_keychain_error": "The system keychain refused: {error}", + "ui.ai_kind": "Kind", "ui.ai_mode_all": "Allow everything", "ui.ai_mode_all_note": "Nothing asks first. Crash reports stay off limits and the folder limits still apply.", "ui.ai_mode_all_warning": "The agent can save, overwrite, export and replace your design without asking. Use this only with an agent you trust, on designs you have saved.", @@ -1604,6 +1610,7 @@ "ui.ai_panel": "Panel", "ui.ai_permissions": "Permissions", "ui.ai_preset": "Preset", + "ui.ai_protocol": "Protocol", "ui.ai_remove": "Remove", "ui.ai_request_limit": "stopped after 24 requests for one message; send another message to go on", "ui.ai_reset": "Reset", @@ -1614,6 +1621,8 @@ "ui.ai_test": "Test", "ui.ai_test_acp_ok": "Answers: {agent}", "ui.ai_test_acp_tip": "Starts the agent briefly and asks it for a session; ends it again", + "ui.ai_test_answered": "Reached: {model} answered", + "ui.ai_test_anthropic_tip": "Sends a short message to the endpoint", "ui.ai_test_api_tip": "Asks the endpoint for its models", "ui.ai_test_no_model": "Reached: {count} models, but not {model}", "ui.ai_test_ok": "Reached: {count} models", diff --git a/assets/locales/ja.json b/assets/locales/ja.json index 62fcea403..86af4e445 100644 --- a/assets/locales/ja.json +++ b/assets/locales/ja.json @@ -1402,6 +1402,9 @@ "thread.designation": "ねじの呼び", "thread.iso_metric": "ISOメートルねじ", "thread.select_size": "サイズを選択", + "timeline.delete_after_marker_one": "履歴マーカー以降の 1 個のフィーチャーを削除", + "timeline.delete_after_marker_other": "履歴マーカー以降の {count} 個のフィーチャーを削除", + "timeline.delete_many": "選択した {count} 個のフィーチャーを削除", "timeline.group": "フィーチャーフォルダを新規作成", "timeline.move_many": "タイムライン項目を移動", "timeline.move_to_group": "フィーチャーをフォルダへ移動", @@ -1553,8 +1556,10 @@ "ui.ai_add": "追加", "ui.ai_add_agent": "エージェントを追加…", "ui.ai_add_agent_title": "エージェントを追加", + "ui.ai_add_anthropic": "Anthropic 互換 API", "ui.ai_add_api": "OpenAI 互換 API", "ui.ai_add_custom": "カスタムコマンド", + "ui.ai_add_endpoint": "API エンドポイント", "ui.ai_add_installed": "インストール済みエージェント", "ui.ai_add_installed_note": "インストール済みエージェントの独自エントリ(例: 別の引数で起動)。インストール済みのエージェントは自動で一覧に表示されます。", "ui.ai_added": "追加済み", @@ -1583,6 +1588,7 @@ "ui.ai_key_needs_https": "キーは HTTPS 経由、またはこのコンピューター宛てにのみ送信されます。", "ui.ai_key_note": "システムのキーチェーンに保存され、SolidCraft の設定には保存されません。ローカルサーバーの場合は空欄のままにします。", "ui.ai_keychain_error": "システムのキーチェーンが拒否しました: {error}", + "ui.ai_kind": "種類", "ui.ai_mode_all": "すべて許可", "ui.ai_mode_all_note": "確認なしで実行します。クラッシュレポートは引き続き対象外で、フォルダー制限も有効です。", "ui.ai_mode_all_warning": "エージェントは確認なしでデザインの保存・上書き・エクスポート・置き換えができます。信頼できるエージェントで、保存済みのデザインに対してのみ使ってください。", @@ -1604,6 +1610,7 @@ "ui.ai_panel": "パネル", "ui.ai_permissions": "権限", "ui.ai_preset": "プリセット", + "ui.ai_protocol": "プロトコル", "ui.ai_remove": "削除", "ui.ai_request_limit": "1メッセージあたり24リクエストで停止しました。続けるには、もう一度メッセージを送ってください", "ui.ai_reset": "リセット", @@ -1614,6 +1621,8 @@ "ui.ai_test": "テスト", "ui.ai_test_acp_ok": "応答あり: {agent}", "ui.ai_test_acp_tip": "エージェントを短時間起動してセッションを要求し、終了します", + "ui.ai_test_answered": "接続成功: {model} が応答しました", + "ui.ai_test_anthropic_tip": "エンドポイントに短いメッセージを送信します", "ui.ai_test_api_tip": "エンドポイントにモデル一覧を問い合わせます", "ui.ai_test_no_model": "接続成功: {count} 個のモデル({model} はありません)", "ui.ai_test_ok": "接続成功: {count} 個のモデル", diff --git a/assets/locales/pl.json b/assets/locales/pl.json index 13f4c2d9a..430a22933 100644 --- a/assets/locales/pl.json +++ b/assets/locales/pl.json @@ -1284,6 +1284,9 @@ "thread.designation": "Oznaczenie", "thread.iso_metric": "Metryczny ISO", "thread.select_size": "Wybierz rozmiar", + "timeline.delete_after_marker_one": "Usuń 1 funkcję za znacznikiem historii", + "timeline.delete_after_marker_other": "Usuń funkcje za znacznikiem historii: {count}", + "timeline.delete_many": "Usuń zaznaczone funkcje: {count}", "timeline.group": "Nowy folder funkcji", "timeline.move_many": "Przenieś elementy osi czasu", "timeline.move_to_group": "Przenieś funkcje do folderu", diff --git a/assets/locales/zh.json b/assets/locales/zh.json index 9e134d106..409307fe8 100644 --- a/assets/locales/zh.json +++ b/assets/locales/zh.json @@ -1402,6 +1402,9 @@ "thread.designation": "螺纹标记", "thread.iso_metric": "ISO 公制", "thread.select_size": "选择尺寸", + "timeline.delete_after_marker_one": "删除历史标记之后的 1 个特征", + "timeline.delete_after_marker_other": "删除历史标记之后的 {count} 个特征", + "timeline.delete_many": "删除所选的 {count} 个特征", "timeline.group": "新建特征文件夹", "timeline.move_many": "移动时间线项目", "timeline.move_to_group": "将特征移至文件夹", @@ -1553,8 +1556,10 @@ "ui.ai_add": "添加", "ui.ai_add_agent": "添加智能体…", "ui.ai_add_agent_title": "添加智能体", + "ui.ai_add_anthropic": "Anthropic 兼容 API", "ui.ai_add_api": "OpenAI 兼容 API", "ui.ai_add_custom": "自定义命令", + "ui.ai_add_endpoint": "API 端点", "ui.ai_add_installed": "已安装的智能体", "ui.ai_add_installed_note": "为已安装的智能体添加一个自己的条目,例如使用其他参数。已安装的智能体会自动列出。", "ui.ai_added": "已添加", @@ -1583,6 +1588,7 @@ "ui.ai_key_needs_https": "密钥只会通过 HTTPS 发送,或发送到本机。", "ui.ai_key_note": "保存在系统钥匙串中,绝不保存在 SolidCraft 的设置里。本地服务器可留空。", "ui.ai_keychain_error": "系统钥匙串拒绝:{error}", + "ui.ai_kind": "类型", "ui.ai_mode_all": "全部允许", "ui.ai_mode_all_note": "不再询问。崩溃报告仍不可访问,文件夹限制仍然有效。", "ui.ai_mode_all_warning": "智能体可以不经询问保存、覆盖、导出和替换你的设计。只在你信任的智能体和已保存的设计上使用。", @@ -1604,6 +1610,7 @@ "ui.ai_panel": "面板", "ui.ai_permissions": "权限", "ui.ai_preset": "预设", + "ui.ai_protocol": "协议", "ui.ai_remove": "移除", "ui.ai_request_limit": "每条消息 24 次请求后已停止;再发送一条消息即可继续", "ui.ai_reset": "重置", @@ -1614,6 +1621,8 @@ "ui.ai_test": "测试", "ui.ai_test_acp_ok": "已响应:{agent}", "ui.ai_test_acp_tip": "短暂启动智能体并请求一个会话,然后结束它", + "ui.ai_test_answered": "已连接:{model} 已响应", + "ui.ai_test_anthropic_tip": "向端点发送一条简短消息", "ui.ai_test_api_tip": "向端点查询其模型列表", "ui.ai_test_no_model": "已连接:{count} 个模型,但没有 {model}", "ui.ai_test_ok": "已连接:{count} 个模型", diff --git a/crates/doc/src/eval.rs b/crates/doc/src/eval.rs index e1d8a57ec..d8a982a67 100644 --- a/crates/doc/src/eval.rs +++ b/crates/doc/src/eval.rs @@ -2156,8 +2156,10 @@ pub fn select_profiles(ss: &SolvedSketch, sel: &ProfileSel) -> Result { + // A design file may list a profile more than once; it is still one profile. + let mut seen = std::collections::BTreeSet::new(); let mut v = Vec::new(); - for i in indices { + for i in indices.iter().filter(|i| seen.insert(**i)) { v.push(ps.get(*i).ok_or_else(|| DocError::Unknown(format!("profile {i} of {}", ss.name)))?.region.clone()); } v diff --git a/crates/doc/src/eval_more.rs b/crates/doc/src/eval_more.rs index b60947b1d..5f450368a 100644 --- a/crates/doc/src/eval_more.rs +++ b/crates/doc/src/eval_more.rs @@ -1714,6 +1714,21 @@ fn offset_left(p: &[Vec2], d: f64) -> Vec { .collect() } +/// The smallest size a plastic feature's lengths may have, in millimetres. Thinner walls and +/// shorter arms than this are below what the solid booleans can resolve. +const PLASTIC_MIN_SIZE: f64 = 0.01; + +/// `v`, the feature's `what`, when it is at least [`PLASTIC_MIN_SIZE`]. +fn plastic_size(feature: &str, what: &str, v: f64) -> Result { + if v.is_finite() && v >= PLASTIC_MIN_SIZE { + Ok(v) + } else { + // Tiny values in exponent form: 1e-320 written out is hundreds of zeros. + let got = if v != 0.0 && v.abs() < 1e-3 { format!("{v:e}") } else { format!("{v}") }; + Err(DocError::Invalid(format!("the {feature}'s {what} must be at least {PLASTIC_MIN_SIZE} mm (got {got} mm)"))) + } +} + pub(super) fn plastic_eval(doc: &Document, vals: &BTreeMap, f: &Feature, st: &mut ModelState) -> Result<()> { let len = |e: &str| val(vals, e, Kind::Length); // The plastic rule of the body a feature goes on gives its defaults (draft, clearance). @@ -1738,10 +1753,8 @@ pub(super) fn plastic_eval(doc: &Document, vals: &BTreeMap, f: &F body, } => { let target = body_under(st, body, position.0)?; - let (r0, h) = (len(diameter)? / 2.0, len(height)?); - if !(r0 > 0.0 && h > 0.0) { - return Err(DocError::Invalid("the boss diameter and height must be positive".into())); - } + let r0 = plastic_size("boss", "diameter", len(diameter)?)? / 2.0; + let h = plastic_size("boss", "height", len(height)?)?; let dr = match draft { Some(e) => val(vals, e, Kind::Angle)?, None => rule(&target)?.map_or(0.0, |r| r.draft), @@ -1784,8 +1797,10 @@ pub(super) fn plastic_eval(doc: &Document, vals: &BTreeMap, f: &F None => 0.0, }; let hr = h - off; - if n > 0.0 && !(t > 0.0 && l > 0.0 && hr > 0.0) { - return Err(DocError::Invalid("ribs need a positive thickness, length and height".into())); + if n > 0.0 { + plastic_size("boss", "rib_thickness", t)?; + plastic_size("boss", "rib_length", l)?; + plastic_size("boss", "rib height (height less rib_offset)", hr)?; } for k in 0..n as usize { let a = std::f64::consts::TAU * k as f64 / n; @@ -1816,9 +1831,9 @@ pub(super) fn plastic_eval(doc: &Document, vals: &BTreeMap, f: &F } } if let Some(hd) = hole_diameter { - let rh = len(hd)? / 2.0; + let rh = plastic_size("boss", "hole_diameter", len(hd)?)? / 2.0; let depth = match hole_depth { - Some(e) => len(e)?, + Some(e) => plastic_size("boss", "hole_depth", len(e)?)?, None => h, }; if !(rh > 0.0 && rh < r_top && depth > 0.0) { @@ -1835,14 +1850,15 @@ pub(super) fn plastic_eval(doc: &Document, vals: &BTreeMap, f: &F let target = body_under(st, body, face.0)?; let mb = st.body(&target).cloned().ok_or_else(|| DocError::Invalid("body".into()))?; let n = planar_normal_at(&mb.body, face.0).ok_or_else(|| DocError::Invalid("pick the planar rim face".into()))?; - let (w, h) = (len(width)?, len(height)?); + let what = if *groove { "groove" } else { "lip" }; + let (w, h) = (plastic_size(what, "width", len(width)?)?, plastic_size(what, "height", len(height)?)?); let g = match gap { Some(e) => len(e)?, None if *groove => rule(&target)?.map_or(0.0, |r| r.clearance), None => 0.0, }; - if !(w > 0.0 && h > 0.0 && g >= 0.0) { - return Err(DocError::Invalid("the lip width and height must be positive".into())); + if !(g >= 0.0) { + return Err(DocError::Invalid("the groove's gap must not be negative".into())); } let plane = Plane::from_normal(face.0, n).ok_or_else(|| DocError::Invalid("rim plane".into()))?; let tol = (mb.body.size() * 1e-3).max(1e-3); @@ -1920,9 +1936,11 @@ pub(super) fn plastic_eval(doc: &Document, vals: &BTreeMap, f: &F } FeatureKind::SnapFit { position, direction, hook, length, thickness, width, catch_depth, catch_length, body } => { let target = body_under(st, body, position.0)?; - let (l, t, w, cd, cl) = (len(length)?, len(thickness)?, len(width)?, len(catch_depth)?, len(catch_length)?); - if !(l > 0.0 && t > 0.0 && w > 0.0 && cd > 0.0 && cl > 0.0 && cl < l) { - return Err(DocError::Invalid("the snap fit's sizes must be positive and the catch shorter than the arm".into())); + let size = |what: &str, e: &str| plastic_size("snap fit", what, len(e)?); + let (l, t, w) = (size("length", length)?, size("thickness", thickness)?, size("width", width)?); + let (cd, cl) = (size("catch_depth", catch_depth)?, size("catch_length", catch_length)?); + if !(cl < l) { + return Err(DocError::Invalid("the snap fit's catch must be shorter than its arm".into())); } let (x, y, z) = local_frame(direction.0, Some(hook.0))?; let delta = (l * 0.05).clamp(1e-3, 0.5); @@ -1943,15 +1961,16 @@ pub(super) fn plastic_eval(doc: &Document, vals: &BTreeMap, f: &F } FeatureKind::Rest { position, direction, along, width, length, height, draft, thickness, body } => { let target = body_under(st, body, position.0)?; - let (w, h) = (len(width)?, len(height)?); - let l = length.as_deref().map(len).transpose()?; + let size = |what: &str, e: &str| plastic_size("rest", what, len(e)?); + let (w, h) = (size("width", width)?, size("height", height)?); + let l = length.as_deref().map(|e| size("length", e)).transpose()?; let dr = match draft { Some(e) => val(vals, e, Kind::Angle)?, None => rule(&target)?.map_or(0.0, |r| r.draft), }; - let t = thickness.as_deref().map(len).transpose()?; - if !(w > 0.0 && h > 0.0 && l.is_none_or(|l| l > 0.0) && t.is_none_or(|t| t > 0.0 && 2.0 * t < w.min(l.unwrap_or(w)))) { - return Err(DocError::Invalid("the rest's sizes must be positive and its wall thinner than half its width".into())); + let t = thickness.as_deref().map(|e| size("thickness", e)).transpose()?; + if t.is_some_and(|t| 2.0 * t >= w.min(l.unwrap_or(w))) { + return Err(DocError::Invalid("the rest's wall must be thinner than half its width".into())); } if !(dr.abs() < 1.0) { return Err(DocError::Invalid("the rest's draft must be under 57°".into())); diff --git a/crates/doc/src/format.rs b/crates/doc/src/format.rs index c8838bd10..27afafc78 100644 --- a/crates/doc/src/format.rs +++ b/crates/doc/src/format.rs @@ -578,6 +578,7 @@ pub fn read(s: &str) -> Result { validate_body_transfers(&v)?; FORMATS.upgrade(&mut v, version, applied.as_deref())?; let mut d: Document = serde_json::from_value(v).map_err(|e| DocError::Invalid(format!("design file: {e}")))?; + check_typed_numbers(&d)?; let mut legacy_by_feature = std::collections::BTreeMap::>::new(); for (feature, wire) in legacy_wires { legacy_by_feature.entry(feature).or_default().push(wire); @@ -1046,6 +1047,16 @@ fn check_design_numbers(v: &Value) -> Result<()> { } } +/// The range check again, on the typed design: an integer such as `9223372036854775808` passes +/// [`check_numbers`] in the file (ids and counters are integers and may be large), but once it +/// lands in a coordinate or size it is a float, and floats are written as floats. Integer fields +/// (ids, counters, indexes) stay integers and are never limited, so the field's type decides +/// what is checked, not its name. +fn check_typed_numbers(d: &Document) -> Result<()> { + let typed = serde_json::to_value(d).map_err(|e| DocError::Invalid(format!("design file: {e}")))?; + check_design_numbers(&typed) +} + /// Every non-integer number in the file is finite and within ±`MAX_REAL` (a damaged or hostile /// file is refused instead of overflowing the geometry later). fn check_numbers(v: &Value, depth: usize) -> Result<()> { @@ -2095,6 +2106,38 @@ mod tests { } } + /// An integer-valued coordinate is range-checked like a float one, while ids and counters + /// may still be large integers (solidcraft#5021). + #[test] + fn integer_valued_coordinates_are_range_checked_and_large_ids_still_load() { + let mut sketch = solidcraft_sketch::Sketch::new(); + sketch.add_point(solidcraft_geom::Vec2::new(40.0, 0.0), None).unwrap(); + let mut d = Document::new("range"); + d.add_feature(crate::FeatureKind::Sketch { plane: crate::PlaneRef::Origin { name: "XY".into() }, sketch }, None).unwrap(); + let last = |v: &Value| v["features"][0]["sketch"]["points"].as_array().map_or(0, |a| a.len() - 1); + for huge in ["9223372036854775808", "4294967295", "2000000000", "-2000000000"] { + let json = edited(&d, |v| { + let i = last(v); + v["features"][0]["sketch"]["points"][i]["pos"][1] = serde_json::from_str(huge).unwrap(); + }); + let error = read(&json).unwrap_err().to_string(); + assert!(error.contains("damaged design") && error.contains("out of range"), "{huge}: {error}"); + } + // In range, an integer-valued coordinate is fine. + let json = edited(&d, |v| { + let i = last(v); + v["features"][0]["sketch"]["points"][i]["pos"][1] = 1_000_000_000u64.into(); + }); + assert!(read(&json).is_ok()); + // Ids and counters are integers and may be past the coordinate limit. + let json = edited(&d, |v| { + v["features"][0]["id"] = 5_000_000_000u64.into(); + v["next_id"] = 5_000_000_001u64.into(); + }); + let back = read(&json).unwrap(); + assert_eq!(back.features[0].id, 5_000_000_000); + } + #[test] fn exhausted_id_space_is_an_error_not_a_panic() { let d = two_components_one_occurrence(); diff --git a/crates/engine/src/cmd/features.rs b/crates/engine/src/cmd/features.rs index 4b0bfd393..216b12668 100644 --- a/crates/engine/src/cmd/features.rs +++ b/crates/engine/src/cmd/features.rs @@ -307,9 +307,30 @@ pub(super) fn stable_profiles(s: &Session, kind: &mut FeatureKind) -> Result<()> for (sketch, sel) in kind.profile_sels_mut() { let Some(ss) = st.sketch(sketch) else { continue }; let indices = match sel { - ProfileSel::Indices { .. } => solidcraft_doc::profile_selection_indices(ss, sel)?, + ProfileSel::Indices { indices } => { + let have = ss.profiles.len(); + if indices.len() > have { + return Err(EngineError::Other(format!("{} profiles are listed, but {} has {have}", indices.len(), ss.name))); + } + if let Some(i) = indices.iter().find(|i| **i >= have) { + return Err(EngineError::Other(format!("there is no profile {i} in {} (it has {have})", ss.name))); + } + solidcraft_doc::profile_selection_indices(ss, sel)? + } ProfileSel::Points { points } => { + if points.len() > ss.profiles.len() { + return Err(EngineError::Other(format!( + "{} profile points are given, but {} has {} profiles", + points.len(), + ss.name, + ss.profiles.len() + ))); + } let Some(indices) = points.iter().map(|point| profile_at_point(&ss.profiles, *point)).collect::>>() else { continue }; + let mut seen = std::collections::BTreeSet::new(); + if let Some(i) = indices.iter().find(|i| !seen.insert(**i)) { + return Err(EngineError::Other(format!("two profile points pick the same profile ({i}) in {}", ss.name))); + } indices } ProfileSel::Curves { loops } => { @@ -410,7 +431,17 @@ pub(crate) fn profiles(p: &Value, cmd: &str) -> Result { Value::Array(a) if a.len() > 10_000 => Err(bad(cmd, "too many profiles")), Value::Array(a) => { if a.iter().all(Value::is_u64) { - return Ok(ProfileSel::Indices { indices: a.iter().filter_map(Value::as_u64).map(|x| x as usize).collect() }); + // Each profile once: a repeat would build the same body again. + let mut seen = std::collections::BTreeSet::new(); + let mut indices = Vec::with_capacity(a.len()); + for i in a.iter().filter_map(Value::as_u64) { + let i = usize::try_from(i).map_err(|_| bad(cmd, format!("there is no profile {i}")))?; + if !seen.insert(i) { + return Err(bad(cmd, format!("profile {i} is listed twice"))); + } + indices.push(i); + } + return Ok(ProfileSel::Indices { indices }); } if a.iter().all(|x| x.get("point").is_some()) { let pts = diff --git a/crates/engine/src/cmd/features_more_tests.rs b/crates/engine/src/cmd/features_more_tests.rs index 0c1342308..56245159d 100644 --- a/crates/engine/src/cmd/features_more_tests.rs +++ b/crates/engine/src/cmd/features_more_tests.rs @@ -1719,3 +1719,33 @@ fn loft_through_coplanar_sections_is_refused() { assert!(e.contains("same plane"), "{e}"); assert!(s.model.state().bodies.is_empty()); } + +#[test] +fn duplicate_and_excess_profile_picks_are_refused_quickly() { + let mut s = Session::default(); + run(&mut s, "sketch.create", json!({"plane": "XY", "name": "Bottom"})); + run(&mut s, "sketch.circle.center", json!({"center": [2.5, 2.5], "radius": 2.5})); + run(&mut s, "sketch.finish", json!({})); + run(&mut s, "sketch.create", json!({"plane": "XY", "offset": 30, "name": "Top"})); + run(&mut s, "sketch.circle.center", json!({"center": [2.5, 2.5], "radius": 2})); + run(&mut s, "sketch.finish", json!({})); + let started = std::time::Instant::now(); + let many = vec![0; 10_000]; + let e = s.execute("solid.extrude", &json!({"sketch": "Bottom", "distance": 5, "profiles": many})).unwrap_err().to_string(); + assert!(e.contains("profile 0 is listed twice"), "{e}"); + let loft = json!({"sections": [{"sketch": "Bottom", "profiles": many}, {"sketch": "Top"}]}); + let e = s.execute("solid.loft", &loft).unwrap_err().to_string(); + assert!(e.contains("profile 0 is listed twice"), "{e}"); + // More profiles than the sketch has, or one it doesn't have. + let e = s.execute("solid.extrude", &json!({"sketch": "Bottom", "distance": 5, "profiles": [0, 1]})).unwrap_err().to_string(); + assert!(e.contains("2 profiles are listed, but Bottom has 1"), "{e}"); + let e = s.execute("solid.extrude", &json!({"sketch": "Bottom", "distance": 5, "profiles": [3]})).unwrap_err().to_string(); + assert!(e.contains("there is no profile 3 in Bottom"), "{e}"); + let points = json!([{"point": [1, 1]}, {"point": [2, 2]}]); + let e = s.execute("solid.extrude", &json!({"sketch": "Bottom", "distance": 5, "profiles": points})).unwrap_err().to_string(); + assert!(e.contains("2 profile points are given, but Bottom has 1"), "{e}"); + assert!(started.elapsed().as_secs_f64() < 5.0, "refusing took {:?}", started.elapsed()); + assert!(s.world_state().bodies.is_empty(), "nothing was built"); + // One pick of the profile still builds. + run(&mut s, "solid.loft", json!({"sections": [{"sketch": "Bottom", "profiles": [0]}, {"sketch": "Top"}]})); +} diff --git a/crates/engine/src/cmd/plastic.rs b/crates/engine/src/cmd/plastic.rs index 6675dcdc0..5a4e138b4 100644 --- a/crates/engine/src/cmd/plastic.rs +++ b/crates/engine/src/cmd/plastic.rs @@ -425,6 +425,40 @@ mod tests { assert!(s.execute("plastic.snap_fit", &json!({"position": [5, 5, 4], "direction": [0, 0, 1], "hook": [0, 0, 1], "length": 15, "thickness": 1.5, "width": 6, "catch_depth": 1, "catch_length": 3})).is_err()); } + #[test] + fn plastic_sizes_below_the_minimum_are_refused_by_name() { + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"length": 40, "width": 40, "height": 4})); + let v0 = volume(&mut s); + let snap = + json!({"position": [20, 20, 4], "hook": [1, 0, 0], "length": 15, "thickness": 1.5, "width": 6, "catch_depth": 1, "catch_length": 3}); + for (key, tiny) in + [("thickness", 1e-9), ("thickness", 1e-320), ("length", 1e-5), ("width", 0.005), ("catch_depth", 1e-9), ("catch_length", 1e-9)] + { + let mut p = snap.clone(); + p[key] = json!(tiny); + let e = s.execute("plastic.snap_fit", &p).unwrap_err().to_string(); + assert!(e.contains(&format!("snap fit's {key} must be at least 0.01 mm")), "{key}={tiny}: {e}"); + } + let boss = json!({"position": [20, 20, 4], "diameter": 6, "height": 5}); + for (key, tiny) in [("diameter", 1e-9), ("height", 1e-9), ("hole_diameter", 1e-9), ("rib_thickness", 1e-9)] { + let mut p = boss.clone(); + p[key] = json!(tiny); + if key == "rib_thickness" { + p["ribs"] = json!(4); + } + let e = s.execute("plastic.boss", &p).unwrap_err().to_string(); + assert!(e.contains(&format!("boss's {key} must be at least 0.01 mm")), "{key}={tiny}: {e}"); + } + let e = s.execute("plastic.rest", &json!({"position": [20, 20, 4], "width": 6, "height": 1e-9})).unwrap_err().to_string(); + assert!(e.contains("rest's height must be at least 0.01 mm"), "{e}"); + assert!(rel(volume(&mut s), v0) < 1e-9, "the refused features changed nothing"); + // The minimum itself still builds. + let mut p = snap.clone(); + p["thickness"] = json!(0.01); + run(&mut s, "plastic.snap_fit", p); + } + #[test] fn enclosure_snap_fit_follows_resized_front_wall() { let mut s = Session::default(); diff --git a/crates/engine/tests/sketch_drag_target.rs b/crates/engine/tests/sketch_drag_target.rs index a122b0611..0daef68b0 100644 --- a/crates/engine/tests/sketch_drag_target.rs +++ b/crates/engine/tests/sketch_drag_target.rs @@ -262,3 +262,81 @@ fn the_coupler_edge_follows_with_both_ends_free_to_rotate() { } } } + +/// Two parallelogram linkages, each held parallel and equal on both pairs of sides (two +/// redundant constraints each), the upper one hanging off the lower one's moving side and tied +/// to a fixed pivot by a 30 mm rod: one degree of freedom (#4585). +fn parallelograms() -> solidcraft_engine::Session { + let mut s = solidcraft_engine::Session::default(); + let run = |s: &mut solidcraft_engine::Session, id: &str, p: serde_json::Value| { + s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}")); + }; + run(&mut s, "sketch.create", json!({"plane":"XY"})); + let at = |deg: f64, r: f64| Vec2::new(deg.to_radians().cos(), deg.to_radians().sin()) * r; + let p1 = at(147.7, 80.0); + let m = p1 + Vec2::new(0.0, 20.0); + let r = m + at(20.0, 80.0); + let (c, t) = (m + Vec2::new(0.0, 20.0), r + Vec2::new(0.0, 20.0)); + let g = r + at(-70.0, 30.0); + let xy = |p: Vec2| [p.x, p.y]; + let (o, q) = (xy(Vec2::ZERO), xy(Vec2::new(0.0, 20.0))); + run(&mut s, "sketch.line", json!({"points":[o, xy(p1), xy(m), q, o],"ids":["bot","left","top","right"],"infer":false})); + run(&mut s, "sketch.line", json!({"points":["left.end", xy(r), xy(t), xy(c), "left.end"],"ids":["ubot","uright","utop","uleft"],"infer":false})); + run(&mut s, "sketch.line", json!({"points":["ubot.end", xy(g)],"ids":["rod"],"infer":false})); + run(&mut s, "sketch.constraint.fix", json!({"entities":["bot.start", "rod.end"]})); + run(&mut s, "sketch.constraint.horizontal_vertical", json!({"line":"right"})); + for (line, value) in [("right", 20.0), ("bot", 80.0), ("ubot", 80.0), ("uleft", 20.0), ("rod", 30.0)] { + run(&mut s, "sketch.dimension", json!({"entities":[line],"value":value})); + } + for (a, b) in [("top", "bot"), ("left", "right"), ("utop", "ubot"), ("uright", "uleft")] { + run(&mut s, "sketch.constraint.parallel", json!({"a":a,"b":b})); + run(&mut s, "sketch.constraint.equal", json!({"a":a,"b":b})); + } + run(&mut s, "sketch.constraint.parallel", json!({"a":"uleft","b":"left"})); + s +} + +/// The parallelograms' lengths, directions and fixed points, as the largest error. +fn parallelogram_error(s: &solidcraft_engine::Session) -> f64 { + let p = |name: &str| four_bar::point(s, name).unwrap(); + let side = |line: &str| p(&format!("{line}.end")) - p(&format!("{line}.start")); + let mut error = p("bot.start").len().max(p("right.start").dist(Vec2::new(0.0, 20.0))); + for (line, value) in [("bot", 80.0), ("ubot", 80.0), ("uleft", 20.0), ("rod", 30.0)] { + error = error.max((side(line).len() - value).abs()); + } + for (a, b) in [("top", "bot"), ("left", "right"), ("utop", "ubot"), ("uright", "uleft")] { + error = error.max((side(a).len() - side(b).len()).abs()).max(side(a).cross(side(b)).abs() / side(b).len()); + } + error +} + +#[test] +fn a_linkage_held_by_redundant_parallelograms_follows_the_cursor() { + // Each held parallelogram's parallel and equal sides are dependent only at an exact + // solution: a pose corrected to the solver's tolerance must still show the linkage's freedom. + for live in [true, false] { + let mut s = parallelograms(); + let report = s.execute("sketch.solve", &json!({})).unwrap(); + assert_eq!((&report["status"], &report["dof"]), (&json!("solved"), &json!(1)), "{report}"); + // The lower parallelogram's free corner, its moving sides and the upper one's side, each + // dragged in turn from where the last drag left the linkage, follows most of the way + // (the rest is off the path the linkage allows). + for (entity, along) in [("bot.end", None), ("bot", Some(0.5)), ("left", Some(0.5)), ("ubot", Some(0.5)), ("bot.end", None)] { + let from = along.map_or_else(|| four_bar::point(&s, entity).unwrap(), |f| grab(&s, entity, f)); + let to = from + Vec2::new(2.0, 2.0); + let r = s.execute("sketch.drag", &json!({"entity":entity,"from":[from.x,from.y],"to":[to.x,to.y],"live":live})).unwrap(); + let reached = r["reached"].as_f64().unwrap(); + assert!(reached > 0.8, "live {live}: {entity} reached {reached}: {r}"); + assert!(parallelogram_error(&s) < 1e-6, "live {live}: {entity}: {}", parallelogram_error(&s)); + assert_eq!(r["sketch"]["solved"], json!(true)); + } + // The lower parallelogram's free corner lands on its 80 mm circle, as close to the + // cursor as the circle allows. + let from = four_bar::point(&s, "bot.end").unwrap(); + let to = from + Vec2::new(1.0, 2.0); + s.execute("sketch.drag", &json!({"entity":"bot.end","from":[from.x,from.y],"to":[to.x,to.y],"live":live})).unwrap(); + let at = four_bar::point(&s, "bot.end").unwrap(); + assert!(at.dist(to * (80.0 / to.len())) < 1e-4, "live {live}: {at:?}"); + assert!(parallelogram_error(&s) < 1e-6); + } +} diff --git a/crates/mcp/src/server.rs b/crates/mcp/src/server.rs index 584f5b4f9..adfe1567a 100644 --- a/crates/mcp/src/server.rs +++ b/crates/mcp/src/server.rs @@ -65,22 +65,48 @@ impl Server { } /// Serve newline-delimited JSON-RPC until `input` closes. Only protocol messages go to - /// `output`; diagnostics belong on stderr. - pub fn serve(&mut self, input: impl BufRead, mut output: impl Write) -> std::io::Result<()> { - for line in input.lines() { - let line = match line { - Ok(l) => l, - // Not UTF-8: answer with a parse error and keep serving. - Err(e) if e.kind() == std::io::ErrorKind::InvalidData => { - let reply = error(Value::Null, PARSE_ERROR, "parse error: input is not UTF-8").to_string(); - output.write_all(reply.as_bytes())?; - output.write_all(b"\n")?; - output.flush()?; - continue; + /// `output`; diagnostics belong on stderr. Consume oversized lines in bounded space so an + /// agent cannot exhaust memory by sending an arbitrarily long request without a newline. + pub fn serve(&mut self, mut input: impl BufRead, mut output: impl Write) -> std::io::Result<()> { + loop { + let mut line = Vec::new(); + let mut oversized = false; + let mut received = false; + loop { + let chunk = input.fill_buf()?; + if chunk.is_empty() { + break; + } + let count = chunk.iter().position(|&byte| byte == b'\n').map_or(chunk.len(), |i| i + 1); + let newline = chunk[count - 1] == b'\n'; + let content_len = count - usize::from(newline); + if !oversized { + if line.len().saturating_add(content_len) > MAX_LINE { + oversized = true; + line.clear(); + } else { + line.extend_from_slice(&chunk[..content_len]); + } + } + input.consume(count); + received = true; + if newline { + break; + } + } + if !received { + break; + } + let reply = if oversized { + Some(error(Value::Null, INVALID_REQUEST, "request too large").to_string()) + } else { + match String::from_utf8(line) { + Ok(line) => self.handle_line(&line), + // Not UTF-8: answer with a parse error and keep serving. + Err(_) => Some(error(Value::Null, PARSE_ERROR, "parse error: input is not UTF-8").to_string()), } - Err(e) => return Err(e), }; - if let Some(reply) = self.handle_line(&line) { + if let Some(reply) = reply { output.write_all(reply.as_bytes())?; output.write_all(b"\n")?; output.flush()?; @@ -91,13 +117,14 @@ impl Server { /// One line in, at most one line out (notifications get no reply). pub fn handle_line(&mut self, line: &str) -> Option { + // Check the raw input before trimming: a huge whitespace prefix is still a huge line. + if line.len() > MAX_LINE { + return Some(error(Value::Null, INVALID_REQUEST, "request too large").to_string()); + } let line = line.trim(); if line.is_empty() { return None; } - if line.len() > MAX_LINE { - return Some(error(Value::Null, INVALID_REQUEST, "request too large").to_string()); - } let reply = match serde_json::from_str::(line) { Ok(Value::Array(batch)) if batch.is_empty() => Some(error(Value::Null, INVALID_REQUEST, "empty batch")), Ok(Value::Array(batch)) if batch.len() > MAX_BATCH => Some(error(Value::Null, INVALID_REQUEST, "batch too large")), diff --git a/crates/mcp/src/tests.rs b/crates/mcp/src/tests.rs index c17e332b6..fdd13a831 100644 --- a/crates/mcp/src/tests.rs +++ b/crates/mcp/src/tests.rs @@ -48,6 +48,46 @@ fn tool(s: &mut Server, name: &str, args: Value) -> Value { if c["type"] == "text" { serde_json::from_str(c["text"].as_str().unwrap()).unwrap_or(Value::Null) } else { c.clone() } } +/// A large whitespace prefix must not evade the raw 16 MiB JSON-RPC line limit. +#[test] +fn whitespace_does_not_bypass_mcp_request_limit() { + let mut s = server(); + let request = format!("{}{}", " ".repeat(solidcraft_engine::MAX_LINE), r#"{"jsonrpc":"2.0","id":1,"method":"ping"}"#); + let reply: Value = serde_json::from_str(&s.handle_line(&request).expect("size error")).unwrap(); + assert_eq!(reply["error"]["code"], -32600, "{reply}"); + assert!(reply["result"].is_null(), "oversized request must not execute: {reply}"); +} + +/// The transport must discard an oversized line in bounded space and resume on the next one. +#[test] +fn oversized_mcp_stdio_line_does_not_poison_the_next_request() { + let mut bytes = vec![b'X'; solidcraft_engine::MAX_LINE + 1]; + bytes.extend_from_slice(b"\n{\"jsonrpc\":\"2.0\",\"id\":2,\"method\":\"ping\"}\n"); + let input = std::io::BufReader::with_capacity(64, std::io::Cursor::new(bytes)); + let mut output = Vec::new(); + server().serve(input, &mut output).unwrap(); + let text = String::from_utf8(output).unwrap(); + let replies: Vec = text.lines().map(|line| serde_json::from_str(line).unwrap()).collect(); + assert_eq!(replies.len(), 2, "{text}"); + assert_eq!(replies[0]["error"]["code"], -32600, "{}", replies[0]); + assert_eq!(replies[1]["id"], 2, "{}", replies[1]); + assert_eq!(replies[1]["result"], json!({}), "{}", replies[1]); +} + +/// Preserve parse-error framing and accept an unterminated final line. +#[test] +fn mcp_stdio_recovers_after_invalid_utf8_and_accepts_eof() { + let input = b"\xff\n{\"jsonrpc\":\"2.0\",\"id\":3,\"method\":\"ping\"}"; + let mut output = Vec::new(); + server().serve(std::io::Cursor::new(input), &mut output).unwrap(); + let text = String::from_utf8(output).unwrap(); + let replies: Vec = text.lines().map(|line| serde_json::from_str(line).unwrap()).collect(); + assert_eq!(replies.len(), 2, "{text}"); + assert_eq!(replies[0]["error"]["code"], -32700); + assert_eq!(replies[1]["id"], 3); + assert_eq!(replies[1]["result"], json!({})); +} + #[test] fn crash_reports_are_listed_and_read_without_changing_the_design() { let mut s = server(); diff --git a/crates/sketch/src/cursor.rs b/crates/sketch/src/cursor.rs index 099d772c8..19649fa2a 100644 --- a/crates/sketch/src/cursor.rs +++ b/crates/sketch/src/cursor.rs @@ -15,6 +15,12 @@ const MAX_VARIABLES: usize = 400; const MAX_STEPS: usize = 96; const CORRECTION_ITERS: usize = 16; const TOTAL_CORRECTION_ITERS: usize = 256; +/// Pivot tolerance of the null space, on rows scaled to a largest entry of 1. Redundant +/// constraints (a parallelogram held both parallel and equal on each pair of sides) are +/// dependent only at an exact solution; a pose corrected to `TOL` leaves their rows independent +/// by about that much, and a tighter tolerance counts that as rank and finds no freedom (#4585). +/// The solver's rank analysis, which reports the sketch's degrees of freedom, uses 1e-7 too. +const NULL_SPACE_TOL: f64 = 1e-7; /// Move a point toward `target` using freedom left by the design constraints. `max_step` /// bounds the full variable displacement before constraint correction; `valid` can reject @@ -266,7 +272,7 @@ fn null_space(mut j: Mat) -> Vec> { } } } - let pivots = rref(&mut j, 1e-9); + let pivots = rref(&mut j, NULL_SPACE_TOL); let mut z: Vec> = Vec::new(); for free in (0..j.cols).filter(|c| !pivots.contains(c)) { let mut v = vec![0.0; j.cols]; diff --git a/crates/ui-egui/src/agent_chat/agents.rs b/crates/ui-egui/src/agent_chat/agents.rs index d2a65d198..1bcb01954 100644 --- a/crates/ui-egui/src/agent_chat/agents.rs +++ b/crates/ui-egui/src/agent_chat/agents.rs @@ -1,7 +1,8 @@ //! The agents the chat can use: the installed ones it finds by itself (Claude Code, Codex, //! Antigravity, OpenCode, …) and the ones the user adds (another ACP command, or an -//! OpenAI-compatible endpoint such as Ollama, LM Studio or OpenAI). Also the permission modes. -//! Preferences only: no design data, no keys (those are in the system keychain). +//! OpenAI-compatible endpoint such as Ollama, LM Studio or OpenAI, or an Anthropic-compatible +//! one). Also the permission modes. Preferences only: no design data, no keys (those are in the +//! system keychain). use serde::{Deserialize, Serialize}; @@ -47,6 +48,50 @@ pub enum Kind { Acp, /// An OpenAI-compatible chat completions endpoint. Api, + /// An Anthropic-compatible Messages endpoint. + Anthropic, +} + +impl Kind { + /// The id written in preferences and on the control channel. + pub fn id(self) -> &'static str { + match self { + Kind::Acp => "acp", + Kind::Api => "api", + Kind::Anthropic => "anthropic", + } + } + /// Whether the agent is an endpoint SolidCraft talks to itself (either protocol). + pub fn is_api(self) -> bool { + matches!(self, Kind::Api | Kind::Anthropic) + } + /// The wire protocol of an added endpoint; `None` for an ACP agent. + pub fn protocol(self) -> Option { + match self { + Kind::Acp => None, + Kind::Api => Some(Protocol::OpenAi), + Kind::Anthropic => Some(Protocol::Anthropic), + } + } +} + +/// The wire protocol of an endpoint the user added. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum Protocol { + /// `{base}/chat/completions`, as Ollama, LM Studio, OpenAI and their kin speak. + #[default] + OpenAi, + /// `{base}/v1/messages`, as the Anthropic Messages API and compatible endpoints speak. + Anthropic, +} + +impl Protocol { + pub fn kind(self) -> Kind { + match self { + Protocol::OpenAi => Kind::Api, + Protocol::Anthropic => Kind::Anthropic, + } + } } /// An agent the user added. @@ -101,7 +146,7 @@ impl Entry { /// A short line under the name: the version, the model, or the command. pub fn detail(&self) -> String { match self.kind { - Kind::Api => format!("{} · {}", self.model, self.base_url), + Kind::Api | Kind::Anthropic => format!("{} · {}", self.model, self.base_url), Kind::Acp => match &self.version { Some(v) => v.clone(), None => super::panel::short_command(&self.argv.join(" ")), @@ -162,13 +207,31 @@ pub fn new_id(p: &crate::prefs::Prefs, prefix: &str) -> String { (1..).map(|n| format!("{prefix}-{n}")).find(|id| !p.agents.iter().any(|a| &a.id == id)).unwrap_or_else(|| prefix.to_string()) } -/// OpenAI-compatible endpoints people use: name, base URL, whether it needs a key. -pub const API_PRESETS: &[(&str, &str, bool)] = &[ - ("Ollama", "http://localhost:11434/v1", false), - ("LM Studio", "http://localhost:1234/v1", false), - ("OpenAI", "https://api.openai.com/v1", true), +/// An endpoint people commonly add, with the base URL to start from. +pub struct ApiPreset { + pub name: &'static str, + pub base_url: &'static str, +} + +/// OpenAI-compatible endpoints people use. +pub const OPENAI_PRESETS: &[ApiPreset] = &[ + ApiPreset { name: "Ollama", base_url: "http://localhost:11434/v1" }, + ApiPreset { name: "LM Studio", base_url: "http://localhost:1234/v1" }, + ApiPreset { name: "OpenAI", base_url: "https://api.openai.com/v1" }, ]; +/// Anthropic-compatible endpoints people use. The base URL is the one their documentation calls +/// `ANTHROPIC_BASE_URL`: the `/v1` is added where needed. +pub const ANTHROPIC_PRESETS: &[ApiPreset] = &[ApiPreset { name: "Anthropic", base_url: "https://api.anthropic.com/v1" }]; + +/// The presets offered for an endpoint protocol. +pub fn presets(protocol: Protocol) -> &'static [ApiPreset] { + match protocol { + Protocol::OpenAi => OPENAI_PRESETS, + Protocol::Anthropic => ANTHROPIC_PRESETS, + } +} + /// Whether a key may be sent to `url`: only over HTTPS, or to this computer. pub fn key_safe_for(url: &str) -> bool { let u = url.trim().to_ascii_lowercase(); @@ -231,4 +294,19 @@ mod tests { assert_eq!(normalize_url(" http://localhost:11434/v1/ ").as_deref(), Ok("http://localhost:11434/v1")); assert!(normalize_url("localhost:11434").is_err()); } + + #[test] + fn endpoint_kinds_keep_their_protocol_and_presets() { + assert_eq!(serde_json::to_string(&Kind::Api).unwrap(), "\"api\""); + assert_eq!(serde_json::to_string(&Kind::Anthropic).unwrap(), "\"anthropic\""); + assert_eq!(serde_json::from_str::("\"anthropic\"").unwrap(), Kind::Anthropic); + assert!(Kind::Anthropic.is_api() && !Kind::Acp.is_api()); + assert!(Kind::Acp.protocol().is_none()); + assert_eq!(Kind::Anthropic.protocol(), Some(Protocol::Anthropic)); + assert_eq!(Protocol::Anthropic.kind(), Kind::Anthropic); + assert_eq!(Kind::Api.id(), "api"); + assert_eq!(Kind::Anthropic.id(), "anthropic"); + assert!(presets(Protocol::OpenAi).iter().all(|p| !p.name.is_empty() && p.base_url.starts_with("http"))); + assert!(presets(Protocol::Anthropic).iter().any(|p| p.base_url == "https://api.anthropic.com/v1")); + } } diff --git a/crates/ui-egui/src/agent_chat/api_client.rs b/crates/ui-egui/src/agent_chat/api_client.rs index 3fb584c5e..c3d074027 100644 --- a/crates/ui-egui/src/agent_chat/api_client.rs +++ b/crates/ui-egui/src/agent_chat/api_client.rs @@ -1,9 +1,10 @@ -//! The API backend (desktop only): a model behind an OpenAI-compatible chat completions endpoint -//! (Ollama, LM Studio, OpenAI, any URL the user gives). SolidCraft runs the tool loop itself, with -//! the same tools the ACP agents get: it starts the same MCP server (`solidcraft-cli mcp -//! --connect` to the chat's own endpoint) and is its client, so every tool call passes the same -//! gate, limits and folder checks. The key, when there is one, comes from the system keychain for -//! this connection only. +//! The API backend (desktop only): a model behind an endpoint SolidCraft talks to itself, either +//! OpenAI-compatible (Ollama, LM Studio, OpenAI, any URL the user gives) or Anthropic-compatible +//! (the Anthropic Messages API, or an endpoint that speaks it). SolidCraft runs the tool loop +//! itself, with the same tools the ACP agents get: it starts the same MCP server (`solidcraft-cli +//! mcp --connect` to the chat's own endpoint) and is its client, so every tool call passes the +//! same gate, limits and folder checks. The key, when there is one, comes from the system keychain +//! for this connection only. //! //! The loop runs on a thread of its own: a model request can take a while. @@ -15,6 +16,7 @@ use std::time::Duration; use serde_json::{Value, json}; use super::acp::ModelInfo; +use super::agents::Protocol; use super::backend::{ChatBackend, Event, HttpFn, HttpRequest, PromptPart, StartContext, ToolStatus}; use super::process::{AgentProcess, FromAgent, ProcessHandle}; @@ -30,12 +32,21 @@ const REQUEST_TIMEOUT_S: u64 = 300; const TOOL_TIMEOUT: Duration = Duration::from_secs(330); /// How often a waiting request or tool call looks at the cancel flag. const CANCEL_POLL: Duration = Duration::from_millis(40); +/// The Anthropic Messages API requires `max_tokens`; it caps one answer, which is plenty for a +/// chat reply and for the tool calls in it. +const ANTHROPIC_MAX_TOKENS: u64 = 8192; +/// The API version sent to Anthropic-compatible endpoints. It is the version every such endpoint +/// knows: DeepSeek ignores it, Qwen does not require it, and the Claude API still accepts it. +const ANTHROPIC_VERSION: &str = "2023-06-01"; +/// The connection test's own timeout: it asks for a token or two, not a whole answer. +const TEST_TIMEOUT_S: u64 = 60; /// Tools the model is not offered. const HIDDEN_TOOLS: &[&str] = &["crash_reports"]; pub struct ApiConfig { pub name: String, + pub protocol: Protocol, pub base_url: String, pub model: String, pub key: Option, @@ -80,6 +91,7 @@ impl ApiBackend { mcp, next: 0, tools: Vec::new(), + tool_names: Vec::new(), history: Vec::new(), events: ev_tx, wake, @@ -141,8 +153,11 @@ struct Worker { cfg: ApiConfig, mcp: Option, next: u64, - /// The MCP tools as OpenAI function tools. + /// The MCP tools in the endpoint's own shape (function tools, or `input_schema` tools). tools: Vec, + /// The tools' names, whichever shape `tools` has. + tool_names: Vec, + /// The conversation in the endpoint's shape, without the system note (sent separately). history: Vec, events: Sender, wake: Arc, @@ -161,10 +176,9 @@ impl Worker { if let Err(e) = self.start_mcp() { self.emit(Event::Error(e)); } - self.history.push(json!({"role": "system", "content": super::acp::SYSTEM_NOTE})); self.emit(Event::Ready { agent: format!("{} · {}", self.cfg.name, self.cfg.model), images: true }); // The endpoint's models for the picker; an endpoint that does not list them shows none. - if let Ok(list) = model_list(&self.cfg.http, &self.cfg.base_url, self.cfg.key.as_deref()) { + if let Ok(list) = self.model_list() { let mut available = list; if !self.cfg.model.is_empty() && !available.iter().any(|m| m.id == self.cfg.model) { available.insert(0, ModelInfo { id: self.cfg.model.clone(), name: self.cfg.model.clone(), description: String::new() }); @@ -178,7 +192,7 @@ impl Worker { Cmd::Prompt(parts) => self.turn(parts), Cmd::SetModel(m) => self.cfg.model = m, Cmd::NewChat => { - self.history.truncate(1); + self.history.clear(); self.cancel.store(false, Ordering::Relaxed); self.emit(Event::Ready { agent: format!("{} · {}", self.cfg.name, self.cfg.model), images: true }); } @@ -189,6 +203,14 @@ impl Worker { } } + /// The endpoint's models, in the shape its protocol lists them. + fn model_list(&self) -> Result, String> { + match self.cfg.protocol { + Protocol::OpenAi => model_list(&self.cfg.http, &self.cfg.base_url, self.cfg.key.as_deref()), + Protocol::Anthropic => anthropic_model_list(&self.cfg.http, &self.cfg.base_url, self.cfg.key.as_deref()), + } + } + /// One MCP request to the server; its `result`. fn mcp_call(&mut self, method: &str, params: Value) -> Result { let Some(m) = self.mcp.as_ref() else { return Err("no SolidCraft tools in this session".into()) }; @@ -233,19 +255,17 @@ impl Worker { m.send(&json!({"jsonrpc": "2.0", "method": "notifications/initialized"})); } let list = self.mcp_call("tools/list", json!({}))?; - self.tools = openai_tools(&list); + self.tools = match self.cfg.protocol { + Protocol::OpenAi => openai_tools(&list), + Protocol::Anthropic => anthropic_tools(&list), + }; + self.tool_names = tool_names(&list); Ok(()) } fn turn(&mut self, parts: Vec) { - self.history.push(user_message(&parts)); - // Keep the system note; drop the oldest messages, never leaving a reply first. - while self.history.len() > MAX_HISTORY { - self.history.remove(1); - } - while self.history.len() > 2 && self.history.get(1).is_some_and(|m| m["role"] != "user") { - self.history.remove(1); - } + self.history.push(user_message(self.cfg.protocol, &parts)); + self.trim_history(); for _ in 0..MAX_REQUESTS_PER_TURN { // The history as of here is complete (every tool call answered): a cancelled request // goes back to it, so no half-finished round is left to confuse the next message. @@ -272,27 +292,21 @@ impl Worker { return; } }; - let msg = reply.pointer("/choices/0/message").cloned().unwrap_or(Value::Null); - if let Some(text) = msg.get("content").and_then(Value::as_str).filter(|t| !t.is_empty()) { - self.emit(Event::Text { thought: false, text: text.to_string() }); + for (thought, text) in reply.text { + self.emit(Event::Text { thought, text }); } - let calls: Vec = msg.get("tool_calls").and_then(Value::as_array).cloned().unwrap_or_default(); - let mut kept = json!({"role": "assistant", "content": msg.get("content").cloned().unwrap_or(Value::Null)}); - if !calls.is_empty() { - kept["tool_calls"] = Value::Array(calls.clone()); - } - self.history.push(kept); - if calls.is_empty() { + self.history.push(reply.assistant); + if reply.calls.is_empty() { self.emit(Event::TurnEnded { reason: String::new() }); return; } - for (i, c) in calls.iter().enumerate().take(32) { - let id = c.get("id").and_then(Value::as_str).map_or_else(|| format!("call-{i}"), str::to_string); - let name = c.pointer("/function/name").and_then(Value::as_str).unwrap_or("").to_string(); - let parsed = tool_arguments(c.pointer("/function/arguments")); - let args = parsed.clone().unwrap_or_else(|_| json!({})); - let title = tool_title(&name, &args); - let tool_id = format!("{id}-{}", self.next); + // Anthropic takes every result of a round in one user message; OpenAI takes one + // `tool` message per call. + let mut results = Vec::new(); + for c in reply.calls.iter().take(32) { + let args = c.arguments.clone().unwrap_or_else(|_| json!({})); + let title = tool_title(&c.name, &args); + let tool_id = format!("{}-{}", c.id, self.next); self.emit(Event::Tool { id: tool_id.clone(), title: Some(title), @@ -302,15 +316,13 @@ impl Worker { }); let (text, failed) = if self.cancel.load(Ordering::Relaxed) { ("cancelled by the user".to_string(), true) - } else if let Err(e) = &parsed { + } else if let Err(e) = &c.arguments { // A call whose arguments do not parse is answered, never run with `{}`. (format!("Not run: {e}"), true) - } else if HIDDEN_TOOLS.contains(&name.as_str()) - || !self.tools.iter().any(|t| t.pointer("/function/name").and_then(Value::as_str) == Some(name.as_str())) - { - (format!("unknown tool `{name}`"), true) + } else if !self.tool_names.iter().any(|n| n == &c.name) { + (format!("unknown tool `{}`", c.name), true) } else { - match self.mcp_call("tools/call", json!({"name": name, "arguments": args})) { + match self.mcp_call("tools/call", json!({"name": c.name, "arguments": args})) { Ok(r) => tool_text(&r), Err(e) => (e, true), } @@ -323,50 +335,103 @@ impl Worker { status: Some(if failed { ToolStatus::Failed } else { ToolStatus::Completed }), output: Some(shown), }); - self.history.push(json!({"role": "tool", "tool_call_id": id, "content": text})); + match self.cfg.protocol { + Protocol::OpenAi => self.history.push(json!({"role": "tool", "tool_call_id": c.id, "content": text})), + Protocol::Anthropic => { + results.push(json!({"type": "tool_result", "tool_use_id": c.id, "content": text, "is_error": failed})); + } + } + } + if self.cfg.protocol == Protocol::Anthropic && !results.is_empty() { + self.history.push(json!({"role": "user", "content": results})); } } self.emit(Event::Text { thought: false, text: format!("\n({})", crate::i18n::tr("ui.ai_request_limit")) }); self.emit(Event::TurnEnded { reason: "max_turn_requests".into() }); } - fn request(&self) -> Result { - let mut body = json!({"model": self.cfg.model, "messages": self.history}); - if !self.tools.is_empty() { - body["tools"] = Value::Array(self.tools.clone()); - if self.no_reasoning.get() { - body["reasoning_effort"] = json!("none"); - } + /// Keep the conversation bounded and starting at a user message, so neither protocol sees a + /// reply or a tool result without the message it answers. + fn trim_history(&mut self) { + while self.history.len() > MAX_HISTORY { + self.history.remove(0); } + while self.history.first().is_some_and(|m| !starts_a_turn(m)) { + self.history.remove(0); + } + } + + fn request(&self) -> Result { + let mut body = self.body(); let (status, v) = self.post(&body)?; // Some OpenAI models refuse function tools on this endpoint unless the reasoning effort is // "none" (HTTP 400 naming `reasoning_effort`): ask again once with it, and keep it for the - // next requests. - let refused = status == 400 && !self.tools.is_empty() && !self.no_reasoning.get() && http_error(status, &v).contains("reasoning_effort"); + // next requests. Anthropic has no such parameter. + let refused = self.cfg.protocol == Protocol::OpenAi + && status == 400 + && !self.tools.is_empty() + && !self.no_reasoning.get() + && http_error(status, &v).contains("reasoning_effort"); if refused { self.no_reasoning.set(true); body["reasoning_effort"] = json!("none"); let (status, v) = self.post(&body)?; - return if status == 200 { Ok(v) } else { Err(http_error(status, &v)) }; + return if status == 200 { Ok(reply(self.cfg.protocol, &v)) } else { Err(http_error(status, &v)) }; } if status != 200 { return Err(http_error(status, &v)); } - Ok(v) + Ok(reply(self.cfg.protocol, &v)) + } + + /// The request body in the endpoint's shape: the system note is a message for OpenAI and a + /// top-level field for Anthropic. + fn body(&self) -> Value { + 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.extend(self.history.iter().cloned()); + let mut body = json!({"model": self.cfg.model, "messages": messages}); + if !self.tools.is_empty() { + body["tools"] = Value::Array(self.tools.clone()); + if self.no_reasoning.get() { + body["reasoning_effort"] = json!("none"); + } + } + body + } + Protocol::Anthropic => { + let mut body = json!({ + "model": self.cfg.model, + "max_tokens": ANTHROPIC_MAX_TOKENS, + "system": super::acp::SYSTEM_NOTE, + "messages": &self.history, + }); + if !self.tools.is_empty() { + body["tools"] = Value::Array(self.tools.clone()); + } + body + } + } } fn post(&self, body: &Value) -> Result<(u16, Value), String> { let mut headers = vec![("Content-Type".to_string(), "application/json".to_string())]; - if let Some(k) = &self.cfg.key { - headers.push(("Authorization".into(), format!("Bearer {k}"))); - } - let req = HttpRequest { - method: "POST", - url: format!("{}/chat/completions", self.cfg.base_url), - headers, - body: Some(body.to_string().into_bytes()), - timeout_s: REQUEST_TIMEOUT_S, + let url = match self.cfg.protocol { + Protocol::OpenAi => format!("{}/chat/completions", self.cfg.base_url), + Protocol::Anthropic => { + headers.push(("anthropic-version".to_string(), ANTHROPIC_VERSION.to_string())); + endpoint(&self.cfg.base_url, "messages") + } }; + if let Some(k) = &self.cfg.key { + match self.cfg.protocol { + Protocol::OpenAi => headers.push(("Authorization".into(), format!("Bearer {k}"))), + Protocol::Anthropic => headers.push(("x-api-key".into(), k.clone())), + } + } + let req = HttpRequest { method: "POST", url, headers, body: Some(body.to_string().into_bytes()), timeout_s: REQUEST_TIMEOUT_S }; // The request runs on a thread of its own so that Stop does not wait for the model: a // cancelled one is abandoned (the host's own timeout ends it) and its answer dropped. let (tx, rx) = channel(); @@ -424,8 +489,8 @@ fn tool_arguments(raw: Option<&Value>) -> Result { } } -/// The message for what the user typed (and the view, as a data URL). -fn user_message(parts: &[PromptPart]) -> Value { +/// The message for what the user typed (and the view, as the endpoint's own content blocks). +fn user_message(protocol: Protocol, parts: &[PromptPart]) -> Value { let images = parts.iter().any(|p| matches!(p, PromptPart::Image { .. })); if !images { let text: Vec<&str> = parts.iter().filter_map(|p| if let PromptPart::Text(t) = p { Some(t.as_str()) } else { None }).collect(); @@ -433,16 +498,129 @@ fn user_message(parts: &[PromptPart]) -> Value { } let content: Vec = parts .iter() - .filter_map(|p| match p { - PromptPart::Text(t) => Some(json!({"type": "text", "text": t})), - PromptPart::Image { mime, base64 } => Some(json!({"type": "image_url", "image_url": {"url": format!("data:{mime};base64,{base64}")}})), - // This endpoint takes no documents (the chat doesn't send any); the message names the file. - PromptPart::Document { .. } => None, + .filter_map(|p| match (protocol, p) { + (_, PromptPart::Text(t)) => Some(json!({"type": "text", "text": t})), + (Protocol::OpenAi, PromptPart::Image { mime, base64 }) => { + Some(json!({"type": "image_url", "image_url": {"url": format!("data:{mime};base64,{base64}")}})) + } + (Protocol::Anthropic, PromptPart::Image { mime, base64 }) => { + Some(json!({"type": "image", "source": {"type": "base64", "media_type": mime, "data": base64}})) + } + // These endpoints take no documents (the chat doesn't send any); the message names the file. + (_, PromptPart::Document { .. }) => None, }) .collect(); json!({"role": "user", "content": content}) } +/// Whether a history message starts a turn: a user message that is not only tool results. +fn starts_a_turn(message: &Value) -> bool { + message["role"] == "user" && !message["content"].as_array().is_some_and(|blocks| blocks.iter().any(|b| b["type"] == "tool_result")) +} + +/// One tool call the endpoint asked for. +#[derive(Debug)] +struct Call { + id: String, + name: String, + /// The arguments as an object, or why they cannot be used. + arguments: Result, +} + +/// An answer from the endpoint, in the protocol's shape. +#[derive(Debug)] +struct Reply { + /// Text to show: `(thought, text)` in the order it came. + text: Vec<(bool, String)>, + calls: Vec, + /// The assistant message to keep in the history, in the endpoint's own shape. Tool calls are + /// capped to the ones the loop answers, so every call kept here gets a result. + assistant: Value, +} + +/// The answer in the endpoint's shape. +fn reply(protocol: Protocol, body: &Value) -> Reply { + match protocol { + Protocol::OpenAi => openai_reply(body), + Protocol::Anthropic => anthropic_reply(body), + } +} + +fn openai_reply(body: &Value) -> Reply { + let message = body.pointer("/choices/0/message").cloned().unwrap_or(Value::Null); + let text = message.get("content").and_then(Value::as_str).filter(|t| !t.is_empty()).map(|t| vec![(false, t.to_string())]).unwrap_or_default(); + // No more than the loop answers: every call kept here must get a `tool` message. + let raw: Vec = message.get("tool_calls").and_then(Value::as_array).map(|a| a.iter().take(32).cloned().collect()).unwrap_or_default(); + let calls = raw + .iter() + .enumerate() + .map(|(i, c)| Call { + id: c.get("id").and_then(Value::as_str).map_or_else(|| format!("call-{i}"), str::to_string), + name: c.pointer("/function/name").and_then(Value::as_str).unwrap_or("").to_string(), + arguments: tool_arguments(c.pointer("/function/arguments")), + }) + .collect(); + let mut assistant = json!({"role": "assistant", "content": message.get("content").cloned().unwrap_or(Value::Null)}); + if !raw.is_empty() { + assistant["tool_calls"] = Value::Array(raw); + } + Reply { text, calls, assistant } +} + +fn anthropic_reply(body: &Value) -> Reply { + let content = body.get("content").cloned().unwrap_or(Value::Null); + let mut text = Vec::new(); + let mut calls = Vec::new(); + let assistant = match &content { + Value::Array(blocks) => { + // Keep the answer as it came (thinking blocks and signatures included), but leave out + // tool calls beyond the loop's cap so every `tool_use` kept gets its `tool_result`. + let mut kept = Vec::new(); + for (i, block) in blocks.iter().take(128).enumerate() { + match block.get("type").and_then(Value::as_str) { + Some("text") => { + if let Some(t) = block.get("text").and_then(Value::as_str).filter(|t| !t.trim().is_empty()) { + text.push((false, t.to_string())); + } + kept.push(block.clone()); + } + Some("thinking") => { + let thought = block.get("thinking").or_else(|| block.get("text")); + if let Some(t) = thought.and_then(Value::as_str).filter(|t| !t.trim().is_empty()) { + text.push((true, t.to_string())); + } + kept.push(block.clone()); + } + Some("tool_use") if calls.len() < 32 => { + calls.push(Call { + id: block.get("id").and_then(Value::as_str).map_or_else(|| format!("toolu-{i}"), str::to_string), + name: block.get("name").and_then(Value::as_str).unwrap_or("").to_string(), + arguments: match block.get("input") { + None | Some(Value::Null) => Ok(json!({})), + Some(v @ Value::Object(_)) => Ok(v.clone()), + Some(_) => Err("the tool arguments must be a JSON object".into()), + }, + }); + kept.push(block.clone()); + } + Some("tool_use") => {} + _ => kept.push(block.clone()), + } + } + json!({"role": "assistant", "content": kept}) + } + // An endpoint that answers with plain text instead of content blocks. + Value::String(s) => { + if !s.trim().is_empty() { + text.push((false, s.clone())); + } + json!({"role": "assistant", "content": content.clone()}) + } + _ => json!({"role": "assistant", "content": content.clone()}), + }; + Reply { text, calls, assistant } +} + /// MCP `tools/list` as OpenAI function tools (the hidden ones left out). pub fn openai_tools(list: &Value) -> Vec { list.get("tools") @@ -467,6 +645,116 @@ pub fn openai_tools(list: &Value) -> Vec { .unwrap_or_default() } +/// MCP `tools/list` as Anthropic tools (the hidden ones left out). +pub fn anthropic_tools(list: &Value) -> Vec { + list.get("tools") + .and_then(Value::as_array) + .map(|a| { + a.iter() + .take(128) + .filter_map(|t| { + let name = t.get("name")?.as_str()?; + if HIDDEN_TOOLS.contains(&name) { + return None; + } + let schema = t.get("inputSchema").cloned().filter(Value::is_object).unwrap_or(json!({"type": "object", "properties": {}})); + Some(json!({ + "name": name, + "description": t.get("description").and_then(Value::as_str).unwrap_or(""), + "input_schema": schema, + })) + }) + .collect() + }) + .unwrap_or_default() +} + +/// The offered tools' names, whichever shape the endpoint takes. +fn tool_names(list: &Value) -> Vec { + list.get("tools") + .and_then(Value::as_array) + .map(|a| { + a.iter() + .take(128) + .filter_map(|t| { + let name = t.get("name")?.as_str()?; + (!HIDDEN_TOOLS.contains(&name)).then(|| name.to_string()) + }) + .collect() + }) + .unwrap_or_default() +} + +/// `{base}/v1/{path}`, whether the user's base URL ends in `/v1` or in the endpoint root the +/// provider's documentation gives (Anthropic's `https://api.anthropic.com`, DeepSeek's +/// `https://api.deepseek.com/anthropic`). +fn endpoint(base_url: &str, path: &str) -> String { + let base = base_url.trim_end_matches('/'); + if base.to_ascii_lowercase().ends_with("/v1") { format!("{base}/{path}") } else { format!("{base}/v1/{path}") } +} + +/// Headers for an Anthropic-compatible request: the version, and the key when there is one (which +/// only goes over HTTPS or to this computer). +fn anthropic_headers(base_url: &str, key: Option<&str>) -> Result, String> { + let mut headers = vec![("anthropic-version".to_string(), ANTHROPIC_VERSION.to_string())]; + if let Some(k) = key { + if !super::agents::key_safe_for(base_url) { + return Err(crate::i18n::tr("ui.ai_key_needs_https").to_string()); + } + headers.push(("x-api-key".to_string(), k.to_string())); + } + Ok(headers) +} + +/// The endpoint's models for the picker. The Messages API has no models endpoint at every +/// compatible provider (Qwen's has none), so a failure here simply leaves the picker empty. +pub fn anthropic_model_list(http: &HttpFn, base_url: &str, key: Option<&str>) -> Result, String> { + let req = HttpRequest { method: "GET", url: endpoint(base_url, "models"), headers: anthropic_headers(base_url, key)?, body: None, timeout_s: 15 }; + let (status, bytes) = http(&req)?; + let v: Value = serde_json::from_slice(&bytes).unwrap_or(Value::Null); + if status != 200 { + return Err(http_error(status, &v)); + } + Ok(v.get("data") + .and_then(Value::as_array) + .map(|a| { + a.iter() + .take(500) + .filter_map(|m| { + let id = m.get("id").and_then(Value::as_str)?.to_string(); + let name = m.get("display_name").and_then(Value::as_str).map(str::to_string).unwrap_or_else(|| id.clone()); + Some(ModelInfo { id, name, description: String::new() }) + }) + .collect() + }) + .unwrap_or_default()) +} + +/// Test an Anthropic-compatible endpoint: send the smallest message there is, so the check covers +/// the path, the key and the model even where there is no models endpoint to ask. +pub fn test_anthropic_endpoint(http: &HttpFn, base_url: &str, key: Option<&str>, model: &str) -> Result { + let model = model.trim(); + if model.is_empty() { + return Err(crate::i18n::tr("ui.ai_need_model").to_string()); + } + let mut headers = anthropic_headers(base_url, key)?; + headers.push(("Content-Type".to_string(), "application/json".to_string())); + let body = json!({"model": model, "max_tokens": 16, "messages": [{"role": "user", "content": "Hello"}]}); + let req = HttpRequest { + method: "POST", + url: endpoint(base_url, "messages"), + headers, + body: Some(body.to_string().into_bytes()), + timeout_s: TEST_TIMEOUT_S, + }; + let (status, bytes) = http(&req)?; + let v: Value = serde_json::from_slice(&bytes).unwrap_or(Value::Null); + if status != 200 { + return Err(http_error(status, &v)); + } + Ok(crate::i18n::format("ui.ai_test_answered", &[("model", model)])) +} + /// A tool call's result as text for the model, and whether it failed. fn tool_text(r: &Value) -> (String, bool) { let failed = r.get("isError").and_then(Value::as_bool).unwrap_or(false); @@ -572,9 +860,17 @@ mod tests { #[test] fn pictures_go_as_data_urls_and_text_alone_as_a_string() { - assert_eq!(user_message(&[PromptPart::Text("hi".into())])["content"], "hi"); - let m = user_message(&[PromptPart::Text("hi".into()), PromptPart::Image { mime: "image/png".into(), base64: "AA==".into() }]); + assert_eq!(user_message(Protocol::OpenAi, &[PromptPart::Text("hi".into())])["content"], "hi"); + let m = + user_message(Protocol::OpenAi, &[PromptPart::Text("hi".into()), PromptPart::Image { mime: "image/png".into(), base64: "AA==".into() }]); assert_eq!(m["content"][1]["image_url"]["url"], "data:image/png;base64,AA=="); + let a = user_message( + Protocol::Anthropic, + &[PromptPart::Text("hi".into()), PromptPart::Image { mime: "image/png".into(), base64: "AA==".into() }], + ); + assert_eq!(a["content"][1]["type"], "image"); + assert_eq!(a["content"][1]["source"]["media_type"], "image/png"); + assert_eq!(a["content"][1]["source"]["data"], "AA=="); } /// A scripted endpoint: one answer with a tool call, then a plain answer. The loop runs the @@ -595,7 +891,14 @@ mod tests { let a = answers.lock().unwrap().pop().unwrap_or(json!({})); Ok((200, a.to_string().into_bytes())) }); - let cfg = ApiConfig { name: "Test".into(), base_url: "http://localhost:1/v1".into(), model: "m".into(), key: None, http }; + let cfg = ApiConfig { + name: "Test".into(), + protocol: Protocol::OpenAi, + base_url: "http://localhost:1/v1".into(), + model: "m".into(), + key: None, + http, + }; let ctx = StartContext { cwd: std::env::temp_dir(), bridge: None, tools: None, wake: Box::new(|| {}) }; let mut b = ApiBackend::start(cfg, ctx).unwrap(); b.prompt(&[PromptPart::Text("measure it".into())]); @@ -641,7 +944,14 @@ mod tests { } Ok((200, json!({"choices": [{"message": {"role": "assistant", "content": "Steered."}}]}).to_string().into_bytes())) }); - let cfg = ApiConfig { name: "Test".into(), base_url: "http://localhost:1/v1".into(), model: "m".into(), key: None, http }; + let cfg = ApiConfig { + name: "Test".into(), + protocol: Protocol::OpenAi, + base_url: "http://localhost:1/v1".into(), + model: "m".into(), + key: None, + http, + }; let ctx = StartContext { cwd: std::env::temp_dir(), bridge: None, tools: None, wake: Box::new(|| {}) }; let mut b = ApiBackend::start(cfg, ctx).unwrap(); let wait = |b: &mut ApiBackend, events: &mut Vec| { @@ -688,7 +998,14 @@ mod tests { log.lock().unwrap().push(serde_json::from_slice(r.body.as_deref().unwrap_or(b"null")).unwrap()); Ok((200, json!({"choices": [{"message": {"role": "assistant", "content": "ok"}}]}).to_string().into_bytes())) }); - let cfg = ApiConfig { name: "Test".into(), base_url: "http://localhost:1/v1".into(), model: "m".into(), key: None, http }; + let cfg = ApiConfig { + name: "Test".into(), + protocol: Protocol::OpenAi, + base_url: "http://localhost:1/v1".into(), + model: "m".into(), + key: None, + http, + }; let ctx = StartContext { cwd: std::env::temp_dir(), bridge: None, tools: None, wake: Box::new(|| {}) }; let mut b = ApiBackend::start(cfg, ctx).unwrap(); let run = |b: &mut ApiBackend, f: &dyn Fn(&mut ApiBackend), want: usize| { @@ -726,7 +1043,14 @@ mod tests { log.lock().unwrap().push(serde_json::from_slice(r.body.as_deref().unwrap_or(b"null")).unwrap()); Ok((200, json!({"choices": [{"message": {"role": "assistant", "content": "ok"}}]}).to_string().into_bytes())) }); - let cfg = ApiConfig { name: "Test".into(), base_url: "http://localhost:1/v1".into(), model: "local".into(), key: None, http }; + let cfg = ApiConfig { + name: "Test".into(), + protocol: Protocol::OpenAi, + base_url: "http://localhost:1/v1".into(), + model: "local".into(), + key: None, + http, + }; let ctx = StartContext { cwd: std::env::temp_dir(), bridge: None, tools: None, wake: Box::new(|| {}) }; let mut b = ApiBackend::start(cfg, ctx).unwrap(); let mut events = Vec::new(); @@ -775,7 +1099,14 @@ mod tests { log.lock().unwrap().push(serde_json::from_slice(r.body.as_deref().unwrap_or(b"null")).unwrap()); Ok((200, answers.lock().unwrap().pop().unwrap_or(json!({})).to_string().into_bytes())) }); - let cfg = ApiConfig { name: "Test".into(), base_url: "http://localhost:1/v1".into(), model: "m".into(), key: None, http }; + let cfg = ApiConfig { + name: "Test".into(), + protocol: Protocol::OpenAi, + base_url: "http://localhost:1/v1".into(), + model: "m".into(), + key: None, + http, + }; let ctx = StartContext { cwd: std::env::temp_dir(), bridge: None, tools: None, wake: Box::new(|| {}) }; let mut b = ApiBackend::start(cfg, ctx).unwrap(); b.prompt(&[PromptPart::Text("go".into())]); @@ -801,7 +1132,14 @@ mod tests { fn keys_never_go_over_plain_http_to_another_computer() { let http: HttpFn = Arc::new(|_: &HttpRequest| Ok((200, b"{}".to_vec()))); assert!(test_endpoint(&http, "http://10.0.0.2:11434/v1", Some("k"), "m").is_err()); - let cfg = ApiConfig { name: "x".into(), base_url: "http://10.0.0.2/v1".into(), model: "m".into(), key: Some("k".into()), http }; + let cfg = ApiConfig { + name: "x".into(), + protocol: Protocol::OpenAi, + base_url: "http://10.0.0.2/v1".into(), + model: "m".into(), + key: Some("k".into()), + http, + }; let ctx = StartContext { cwd: std::env::temp_dir(), bridge: None, tools: None, wake: Box::new(|| {}) }; assert!(ApiBackend::start(cfg, ctx).is_err()); } @@ -817,13 +1155,21 @@ mod tests { let (status, v) = answers.lock().unwrap().pop().expect("no request beyond the script"); Ok((status, v.to_string().into_bytes())) }); - let cfg = ApiConfig { name: "Test".into(), base_url: "http://localhost:1/v1".into(), model: "m".into(), key: Some("sk-secret".into()), http }; + let cfg = ApiConfig { + name: "Test".into(), + protocol: Protocol::OpenAi, + base_url: "http://localhost:1/v1".into(), + model: "m".into(), + key: Some("sk-secret".into()), + http, + }; let (events, _rx) = channel(); let w = Worker { cfg, mcp: None, next: 0, tools: vec![json!({"type": "function", "function": {"name": "measure"}})], + tool_names: vec!["measure".into()], history: vec![json!({"role": "user", "content": "hi"})], events, wake: Arc::new(|| {}), @@ -843,8 +1189,8 @@ mod tests { fn a_refusal_of_tools_with_reasoning_effort_is_replayed_once_with_none() { let ok = json!({"choices": [{"message": {"role": "assistant", "content": "Done."}}]}); let (w, seen) = scripted_worker(vec![refusal(), (200, ok.clone()), (200, ok.clone())]); - assert_eq!(w.request().unwrap(), ok); - assert_eq!(w.request().unwrap(), ok); + assert_eq!(w.request().unwrap().assistant, ok["choices"][0]["message"]); + assert_eq!(w.request().unwrap().assistant, ok["choices"][0]["message"]); let sent = seen.lock().unwrap(); assert_eq!(sent.len(), 3); assert!(sent[0].get("reasoning_effort").is_none()); @@ -864,4 +1210,126 @@ mod tests { assert!(w.request().unwrap_err().contains("context length")); assert_eq!(seen.lock().unwrap().len(), 1); } + + #[test] + fn mcp_tools_become_anthropic_tools_without_crash_reports() { + let list = json!({"tools": [ + {"name": "batch", "description": "Run commands", "inputSchema": {"type": "object", "properties": {"commands": {"type": "array"}}}}, + {"name": "crash_reports", "description": "x", "inputSchema": {"type": "object"}}, + {"name": "measure"}, + ]}); + let t = anthropic_tools(&list); + assert_eq!(t.len(), 2); + assert_eq!(t[0]["name"], "batch"); + assert_eq!(t[0]["input_schema"]["properties"]["commands"]["type"], "array"); + assert_eq!(t[1]["input_schema"]["type"], "object"); + assert_eq!(tool_names(&list), ["batch", "measure"]); + } + + #[test] + fn anthropic_answers_read_text_thought_and_tool_calls() { + let r = anthropic_reply(&json!({"content": [ + {"type": "thinking", "thinking": "checking", "signature": "s"}, + {"type": "text", "text": "Measuring."}, + {"type": "tool_use", "id": "t1", "name": "measure", "input": {"body": "b"}}, + ]})); + assert_eq!(r.text, [(true, "checking".to_string()), (false, "Measuring.".to_string())]); + assert_eq!(r.calls.len(), 1); + assert_eq!(r.calls[0].id, "t1"); + assert_eq!(r.calls[0].name, "measure"); + assert_eq!(r.calls[0].arguments, Ok(json!({"body": "b"}))); + assert_eq!(r.assistant["role"], "assistant"); + assert_eq!(r.assistant["content"][2]["type"], "tool_use"); + let broken = anthropic_reply(&json!({"content": [{"type": "tool_use", "name": "measure", "input": "no"}]})); + assert!(broken.calls[0].arguments.is_err()); + // Calls beyond the loop's cap are left out of the answer too: each kept one is answered. + let many: Vec = (0..40).map(|i| json!({"type": "tool_use", "id": format!("t{i}"), "name": "measure", "input": {}})).collect(); + let capped = anthropic_reply(&json!({"content": many})); + assert_eq!(capped.calls.len(), 32); + assert_eq!(capped.assistant["content"].as_array().unwrap().len(), 32); + } + + #[test] + fn anthropic_urls_take_the_base_with_or_without_v1() { + assert_eq!(endpoint("https://api.anthropic.com", "messages"), "https://api.anthropic.com/v1/messages"); + assert_eq!(endpoint("https://api.anthropic.com/v1", "messages"), "https://api.anthropic.com/v1/messages"); + assert_eq!(endpoint("https://api.anthropic.com/v1/", "messages"), "https://api.anthropic.com/v1/messages"); + assert_eq!(endpoint("https://api.deepseek.com/anthropic/", "models"), "https://api.deepseek.com/anthropic/v1/models"); + assert_eq!( + endpoint("https://dashscope.aliyuncs.com/apps/anthropic", "messages"), + "https://dashscope.aliyuncs.com/apps/anthropic/v1/messages" + ); + } + + /// A scripted Anthropic endpoint: one answer with a tool call, then a plain answer. The loop + /// runs the tool (here without SolidCraft tools: an unknown tool fails) and reports the end. + #[test] + fn the_anthropic_tool_loop_runs_calls_and_ends_the_turn() { + let answers = std::sync::Mutex::new(vec![ + json!({"content": [{"type": "text", "text": "Done."}]}), + json!({"content": [ + {"type": "text", "text": "Measuring."}, + {"type": "tool_use", "id": "t1", "name": "measure", "input": {}}, + ]}), + ]); + let seen = Arc::new(std::sync::Mutex::new(Vec::::new())); + let log = seen.clone(); + let http: HttpFn = Arc::new(move |r: &HttpRequest| { + if r.method == "GET" { + return Ok((200, b"{\"data\":[]}".to_vec())); + } + log.lock().unwrap().push(serde_json::from_slice(r.body.as_deref().unwrap_or(b"null")).unwrap()); + Ok((200, answers.lock().unwrap().pop().unwrap_or(json!({})).to_string().into_bytes())) + }); + let cfg = ApiConfig { + name: "Test".into(), + protocol: Protocol::Anthropic, + base_url: "http://localhost:1".into(), + model: "m".into(), + key: Some("sk-secret".into()), + http, + }; + let ctx = StartContext { cwd: std::env::temp_dir(), bridge: None, tools: None, wake: Box::new(|| {}) }; + let mut b = ApiBackend::start(cfg, ctx).unwrap(); + b.prompt(&[PromptPart::Text("measure it".into())]); + let mut events = Vec::new(); + let start = std::time::Instant::now(); + while !events.iter().any(|e| matches!(e, Event::TurnEnded { .. })) && start.elapsed() < Duration::from_secs(10) { + events.extend(b.poll()); + std::thread::sleep(Duration::from_millis(10)); + } + assert!(matches!(events.first(), Some(Event::Ready { .. })), "{events:?}"); + assert!(events.iter().any(|e| matches!(e, Event::Tool { status: Some(ToolStatus::Failed), .. })), "{events:?}"); + assert!(events.iter().any(|e| matches!(e, Event::Text { text, .. } if text == "Done.")), "{events:?}"); + assert!(matches!(events.last(), Some(Event::TurnEnded { reason }) if reason.is_empty()), "{events:?}"); + let sent = seen.lock().unwrap(); + assert_eq!(sent.len(), 2); + assert_eq!(sent[0]["system"], super::super::acp::SYSTEM_NOTE); + assert_eq!(sent[0]["max_tokens"], ANTHROPIC_MAX_TOKENS); + assert_eq!(sent[1]["messages"].as_array().unwrap().last().unwrap()["content"][0]["type"], "tool_result"); + assert_eq!(sent[1]["messages"].as_array().unwrap().last().unwrap()["content"][0]["tool_use_id"], "t1"); + b.shutdown(true); + } + + #[test] + fn the_anthropic_test_sends_one_small_message_and_checks_the_key_rule() { + let seen = Arc::new(std::sync::Mutex::new(Vec::::new())); + let log = seen.clone(); + let http: HttpFn = Arc::new(move |r: &HttpRequest| { + log.lock().unwrap().push(r.clone()); + Ok((200, json!({"content": [{"type": "text", "text": "Hi"}]}).to_string().into_bytes())) + }); + let message = test_anthropic_endpoint(&http, "https://api.anthropic.com/v1", Some("sk-k"), "claude-opus-5-5").unwrap(); + assert!(message.contains("claude-opus-5-5"), "{message}"); + let sent = seen.lock().unwrap(); + assert_eq!(sent[0].url, "https://api.anthropic.com/v1/messages"); + assert!(sent[0].headers.iter().any(|(k, v)| k == "anthropic-version" && v == ANTHROPIC_VERSION)); + assert!(sent[0].headers.iter().any(|(k, v)| k == "x-api-key" && v == "sk-k")); + let body: Value = serde_json::from_slice(sent[0].body.as_deref().unwrap()).unwrap(); + assert_eq!(body["max_tokens"], 16); + assert_eq!(body["messages"][0]["content"], "Hello"); + drop(sent); + assert!(test_anthropic_endpoint(&http, "http://10.0.0.2/anthropic", Some("k"), "m").is_err()); + assert!(test_anthropic_endpoint(&http, "https://api.anthropic.com", None, "").is_err()); + } } diff --git a/crates/ui-egui/src/agent_chat/mod.rs b/crates/ui-egui/src/agent_chat/mod.rs index e73f401fa..9b0d6a738 100644 --- a/crates/ui-egui/src/agent_chat/mod.rs +++ b/crates/ui-egui/src/agent_chat/mod.rs @@ -742,7 +742,7 @@ pub fn connect(app: &mut SolveApp, ctx: &egui::Context) { return; }; // An API agent's key comes from the keychain for this connection only. - let key = if entry.kind == agents::Kind::Api && entry.key { + let key = if entry.kind.is_api() && entry.key { match app.services.secrets.as_ref().map(|s| s.get(&entry.id)) { Some(Ok(k)) => k, Some(Err(e)) => { @@ -778,12 +778,22 @@ pub fn connect(app: &mut SolveApp, ctx: &egui::Context) { let started: Result, String> = match entry.kind { agents::Kind::Acp if entry.argv.is_empty() => Err(tr("ui.agent_chat_none_found").to_string()), agents::Kind::Acp => acp_client::AcpBackend::start(&entry.argv, start).map(|b| Box::new(b) as Box), - agents::Kind::Api => match http { - Some(http) => api_client::ApiBackend::start( - api_client::ApiConfig { name: entry.name.clone(), base_url: entry.base_url.clone(), model: entry.model.clone(), key, http }, - start, - ) - .map(|b| Box::new(b) as Box), + kind @ (agents::Kind::Api | agents::Kind::Anthropic) => match http { + Some(http) => { + let protocol = if kind == agents::Kind::Anthropic { agents::Protocol::Anthropic } else { agents::Protocol::OpenAi }; + api_client::ApiBackend::start( + api_client::ApiConfig { + name: entry.name.clone(), + protocol, + base_url: entry.base_url.clone(), + model: entry.model.clone(), + key, + http, + }, + start, + ) + .map(|b| Box::new(b) as Box) + } None => Err(tr("ui.ai_no_http").to_string()), }, }; @@ -796,7 +806,7 @@ pub fn connect(app: &mut SolveApp, ctx: &egui::Context) { chat.mode.clear(); chat.models.clear(); chat.model.clear(); - chat.running_endpoint = if entry.kind == agents::Kind::Api { entry.base_url.clone() } else { String::new() }; + chat.running_endpoint = if entry.kind.is_api() { entry.base_url.clone() } else { String::new() }; // An endpoint's models from the last time, until the new list arrives. if let Some(list) = chat.models_cache.get(&chat.running_endpoint) { chat.models = list.clone(); @@ -1487,7 +1497,7 @@ pub fn set_model(app: &mut SolveApp, model: &str) { } app.agent_chat.model = model.to_string(); let agent = app.agent_chat.running_id.clone(); - if let Some(a) = app.preferences.agents.iter_mut().find(|a| a.id == agent && a.kind == agents::Kind::Api) { + if let Some(a) = app.preferences.agents.iter_mut().find(|a| a.id == agent && a.kind.is_api()) { a.model = model.to_string(); } app.preferences.agent_models.insert(agent, model.to_string()); @@ -1537,7 +1547,7 @@ pub fn control(app: &mut SolveApp, ctx: &egui::Context, p: &Value) -> Result Result { - let kind = match k { - "installed" => settings::AddKind::Installed, - "custom" => settings::AddKind::Custom, - "api" => settings::AddKind::Api, - _ => return Err("add_dialog must be installed, custom, api or false".into()), + let (kind, protocol) = match k { + "installed" => (settings::AddKind::Installed, None), + "custom" => (settings::AddKind::Custom, None), + "api" => (settings::AddKind::Api, Some(agents::Protocol::OpenAi)), + "anthropic" => (settings::AddKind::Api, Some(agents::Protocol::Anthropic)), + _ => return Err("add_dialog must be installed, custom, api, anthropic or false".into()), }; settings::open_add(app); if let Some(a) = app.agent_chat.settings.add.as_mut() { @@ -1568,6 +1580,9 @@ pub fn control(app: &mut SolveApp, ctx: &egui::Context, p: &Value) -> Result app.agent_chat.settings.add = None, @@ -1700,7 +1715,7 @@ pub fn status(app: &SolveApp) -> Value { "features": app.preferences.ai_features, "toolbarButton": app.preferences.ai_toolbar_button, "permissions": app.preferences.ai_permissions.id(), - "agents": agents::entries(app).iter().map(|e| json!({"id": e.id, "name": e.name, "kind": if e.kind == agents::Kind::Api { "api" } else { "acp" }, "found": e.found, "version": e.version, "login": e.login})).collect::>(), + "agents": agents::entries(app).iter().map(|e| json!({"id": e.id, "name": e.name, "kind": e.kind.id(), "found": e.found, "version": e.version, "login": e.login})).collect::>(), "currentAgent": agents::current(app).map(|e| e.id), "models": c.models.iter().map(|m| json!({"id": m.id, "name": m.name, "description": m.description})).collect::>(), "model": c.model, diff --git a/crates/ui-egui/src/agent_chat/settings.rs b/crates/ui-egui/src/agent_chat/settings.rs index e997f7eeb..27cafaa0b 100644 --- a/crates/ui-egui/src/agent_chat/settings.rs +++ b/crates/ui-egui/src/agent_chat/settings.rs @@ -1,9 +1,9 @@ //! Settings → AI: the master switch, the agents (found and added, each with Test, Default and, //! for added ones, Remove), permissions (global and per agent, and the "always allow" answers), //! and the panel. Plus the Add agent dialog: an installed ACP agent, a custom command, or an -//! OpenAI-compatible endpoint (whose key goes to the system keychain). +//! endpoint (OpenAI-compatible or Anthropic-compatible, whose key goes to the system keychain). -use super::agents::{self, AgentConfig, Kind, Mode}; +use super::agents::{self, AgentConfig, Kind, Mode, Protocol}; use super::*; use crate::ui_kit; @@ -23,6 +23,7 @@ pub struct AddState { pub command: String, pub installed: usize, pub preset: usize, + pub protocol: Protocol, pub base_url: String, pub model: String, pub key: String, @@ -55,14 +56,28 @@ pub struct State { /// Open the Add agent dialog. pub fn open_add(app: &mut SolveApp) { - let preset = agents::API_PRESETS.first(); + let preset = agents::OPENAI_PRESETS.first(); app.agent_chat.settings.add = Some(AddState { - base_url: preset.map(|p| p.1.to_string()).unwrap_or_default(), - name: preset.map(|p| p.0.to_string()).unwrap_or_default(), + base_url: preset.map(|p| p.base_url.to_string()).unwrap_or_default(), + name: preset.map(|p| p.name.to_string()).unwrap_or_default(), ..Default::default() }); } +/// Take `index` from the protocol's presets, or make the URL empty for a custom endpoint. +pub(super) fn choose_preset(s: &mut AddState, protocol: Protocol, index: usize) { + s.protocol = protocol; + s.preset = index; + if let Some(preset) = agents::presets(protocol).get(index) { + s.base_url = preset.base_url.to_string(); + s.name = preset.name.to_string(); + } else { + s.base_url.clear(); + } + s.error = None; + s.test = None; +} + /// Run a connection test in the background (it starts the agent briefly, or asks the endpoint /// for its models). #[cfg(not(target_arch = "wasm32"))] @@ -82,6 +97,13 @@ fn start_test(app: &SolveApp, e: &agents::Entry, key: Option) -> Test { let _ = tx.send(super::api_client::test_endpoint(&http, &url, key.as_deref(), &model)); }); } + Kind::Anthropic => { + let Some(http) = app.services.agent_http.clone() else { return Test::Done(Err(tr("ui.ai_no_http").to_string())) }; + let (url, model) = (e.base_url.clone(), e.model.clone()); + std::thread::spawn(move || { + let _ = tx.send(super::api_client::test_anthropic_endpoint(&http, &url, key.as_deref(), &model)); + }); + } } Test::Running(rx) } @@ -282,8 +304,12 @@ fn agents_section(app: &mut SolveApp, ui: &mut egui::Ui) { } let test_button = ui_kit::button(ui, tr("ui.ai_test"), ui_kit::Button::Small); crate::scenario::publish_handle(&format!("prefs:ai_test:{}", entry.id), test_button.rect.center()); - if test_button.on_hover_text(tr(if entry.kind == Kind::Acp { "ui.ai_test_acp_tip" } else { "ui.ai_test_api_tip" })).clicked() - { + let tip = match entry.kind { + Kind::Acp => "ui.ai_test_acp_tip", + Kind::Api => "ui.ai_test_api_tip", + Kind::Anthropic => "ui.ai_test_anthropic_tip", + }; + if test_button.on_hover_text(tr(tip)).clicked() { test = Some(entry.clone()); } if !entry.found && ui_kit::button(ui, tr("ui.ai_remove"), ui_kit::Button::Ghost).clicked() { @@ -388,8 +414,8 @@ pub fn dialog(app: &mut SolveApp, ctx: &egui::Context) { if let Some(test) = s.test.as_mut() { test.poll(); } - let kinds = [(AddKind::Installed, "ui.ai_add_installed"), (AddKind::Custom, "ui.ai_add_custom"), (AddKind::Api, "ui.ai_add_api")]; - ui_kit::row(ui, tr("ui.ai_preset"), |ui| { + let kinds = [(AddKind::Installed, "ui.ai_add_installed"), (AddKind::Custom, "ui.ai_add_custom"), (AddKind::Api, "ui.ai_add_endpoint")]; + ui_kit::row(ui, tr("ui.ai_kind"), |ui| { let mut selected = kinds.iter().position(|(k, _)| *k == s.kind).unwrap_or(0); let labels = kinds.map(|(_, key)| tr(key)); if ui_kit::segmented(ui, &mut selected, &labels, ui_kit::Segments { compact: true, ..Default::default() }) @@ -400,7 +426,7 @@ pub fn dialog(app: &mut SolveApp, ctx: &egui::Context) { s.test = None; } for (_, key) in kinds { - if let Some(at) = crate::scenario::handle_at(&format!("dialog:{}:{}", tr("ui.ai_preset"), tr(key))) { + if let Some(at) = crate::scenario::handle_at(&format!("dialog:{}:{}", tr("ui.ai_kind"), tr(key))) { crate::scenario::publish_handle(&format!("ai_add:{key}"), at); } } @@ -447,21 +473,33 @@ pub fn dialog(app: &mut SolveApp, ctx: &egui::Context) { ui_kit::text(ui, tr("ui.agent_chat_custom_hint"), ui_kit::Text::Note("custom")); } AddKind::Api => { - let presets: Vec<_> = agents::API_PRESETS.iter().map(|p| p.0).chain(std::iter::once(tr("ui.ai_custom_url"))).collect(); + ui_kit::row(ui, tr("ui.ai_protocol"), |ui| { + let mut selected = if s.protocol == Protocol::Anthropic { 1 } else { 0 }; + let labels = [tr("ui.ai_add_api"), tr("ui.ai_add_anthropic")]; + if ui_kit::segmented(ui, &mut selected, &labels, ui_kit::Segments { compact: true, ..Default::default() }) + && let Some(protocol) = [Protocol::OpenAi, Protocol::Anthropic].get(selected) + { + choose_preset(s, *protocol, 0); + } + for (name, key) in [("openai", "ui.ai_add_api"), ("anthropic", "ui.ai_add_anthropic")] { + if let Some(at) = crate::scenario::handle_at(&format!("dialog:{}:{}", tr("ui.ai_protocol"), tr(key))) { + crate::scenario::publish_handle(&format!("ai_add:protocol:{name}"), at); + } + } + }); + let choices: Vec<&str> = + agents::presets(s.protocol).iter().map(|p| p.name).chain(std::iter::once(tr("ui.ai_custom_url"))).collect(); ui_kit::row(ui, tr("ui.ai_preset"), |ui| { - ui_kit::dropdown_menu(ui, "sc_ai_add_preset", presets.get(s.preset).copied().unwrap_or_default(), |ui| { - for (index, preset) in presets.iter().enumerate() { - if ui_kit::list_picker(ui, preset, preset, s.preset == index).clicked() { - s.preset = index; - if let Some((name, url, _)) = agents::API_PRESETS.get(index) { - s.base_url = url.to_string(); - s.name = name.to_string(); - } else { - s.base_url.clear(); - } + let picker = ui_kit::dropdown_menu(ui, "sc_ai_add_preset", choices.get(s.preset).copied().unwrap_or_default(), |ui| { + for (index, preset) in choices.iter().enumerate() { + let response = ui_kit::list_picker(ui, preset, preset, s.preset == index); + crate::scenario::publish_handle(&format!("ai_add:preset:{preset}"), response.rect.center()); + if response.clicked() { + choose_preset(s, s.protocol, index); } } }); + crate::scenario::publish_handle("ai_add:preset", picker.rect.center()); }); ui_kit::row(ui, tr("ui.ai_name"), |ui| { ui_kit::text_field(ui, &mut s.name, ""); @@ -501,7 +539,7 @@ pub fn dialog(app: &mut SolveApp, ctx: &egui::Context) { let e = agents::Entry { id: String::new(), name: s.name.clone(), - kind: Kind::Api, + kind: s.protocol.kind(), argv: Vec::new(), version: None, login: "", @@ -555,7 +593,7 @@ fn add_agent(app: &mut SolveApp) -> Result<(), String> { c.id = agents::new_id(&app.preferences, "custom"); } AddKind::Api => { - c.kind = Kind::Api; + c.kind = s.protocol.kind(); c.base_url = agents::normalize_url(&s.base_url)?; c.model = s.model.trim().to_string(); if c.model.is_empty() { @@ -565,7 +603,7 @@ fn add_agent(app: &mut SolveApp) -> Result<(), String> { if key.is_some() && !agents::key_safe_for(&c.base_url) { return Err(tr("ui.ai_key_needs_https").to_string()); } - c.id = agents::new_id(&app.preferences, "api"); + c.id = agents::new_id(&app.preferences, c.kind.id()); } } if c.name.is_empty() { @@ -607,10 +645,23 @@ mod card_tests { assert!(h.app.preferences.agents.iter().any(|e| e.name == "Local fixture")); open_add(&mut h.app); h.frames(3); - h.step(&json!({"click":{"handle":"ai_add:ui.ai_add_api"}})).unwrap(); + h.step(&json!({"click":{"handle":"ai_add:ui.ai_add_endpoint"}})).unwrap(); assert!(scenario::handle_at("ai_add:key").is_some()); assert!(h.app.services.secrets.is_none(), "this fixture has no keychain"); - h.step(&json!({"key":"Escape"})).unwrap(); + h.step(&json!({"click":{"handle":"ai_add:protocol:anthropic"}})).unwrap(); + { + let add = h.app.agent_chat.settings.add.as_ref().unwrap(); + assert_eq!(add.protocol, Protocol::Anthropic); + assert_eq!(add.base_url, "https://api.anthropic.com/v1"); + assert_eq!(add.name, "Anthropic"); + } + h.app.agent_chat.settings.add.as_mut().unwrap().model = "claude-opus-5-5".into(); + h.frames(3); + h.step(&json!({"click":{"handle":"ai_add:add"}})).unwrap(); assert!(h.app.agent_chat.settings.add.is_none()); + let saved = h.app.preferences.agents.last().unwrap(); + assert_eq!(saved.kind, Kind::Anthropic); + assert_eq!(saved.base_url, "https://api.anthropic.com/v1"); + assert_eq!(saved.model, "claude-opus-5-5"); } } diff --git a/crates/ui-egui/src/browser.rs b/crates/ui-egui/src/browser.rs index 1cbb00d07..caf16527f 100644 --- a/crates/ui-egui/src/browser.rs +++ b/crates/ui-egui/src/browser.rs @@ -104,6 +104,9 @@ pub struct TreeState { anchor: Option, /// Row keys in drawing order this frame (for Shift ranges). order: Vec, + /// The previous frame's complete row order: a Shift click resolves its range here, since + /// this frame's `order` does not yet hold the rows below the clicked one (#4991). + order_prev: Vec, } /// Moving an occurrence: the offsets typed so far (pending until Capture Position). @@ -478,10 +481,8 @@ fn click_select(app: &mut SolveApp, ui: &egui::Ui, key: String, sel: Option if mods.shift && let Some(a) = app.tree.anchor.clone() { - let order = app.tree.order.clone(); - if let (Some(i), Some(j)) = (order.iter().position(|k| *k == a), order.iter().position(|k| *k == key)) { - let (lo, hi) = (i.min(j), i.max(j)); - let items: Vec = order[lo..=hi].iter().filter_map(|k| sel_of_key(k)).collect(); + let items = shift_range(&app.tree.order_prev, &a, &key).or_else(|| shift_range(&app.tree.order, &a, &key)); + if let Some(items) = items { let _ = app.run("select.set", json!({ "items": items, "add": mods.command || mods.ctrl })); return; } @@ -502,6 +503,15 @@ fn click_select(app: &mut SolveApp, ui: &egui::Ui, key: String, sel: Option } } +/// The selectable rows from `anchor` to `key` (either way round) in a row order, or `None` +/// when the order lacks either of them. +fn shift_range(order: &[String], anchor: &str, key: &str) -> Option> { + let i = order.iter().position(|k| k == anchor)?; + let j = order.iter().position(|k| k == key)?; + let rows = order.get(i.min(j)..=i.max(j))?; + Some(rows.iter().filter_map(|k| sel_of_key(k)).collect()) +} + fn sel_of_key(k: &str) -> Option { if let Some((_, id)) = k.rsplit_once("/s:") { return id.parse().ok().map(|id| Sel::Feature { id }); @@ -693,7 +703,7 @@ pub(crate) fn resize_column(app: &mut SolveApp, ui: &egui::Ui, rect: Rect, width pub fn browser(app: &mut SolveApp, ui: &mut egui::Ui) { let available = ui.available_rect_before_wrap(); let t = Tokens::get(); - app.tree.order.clear(); + app.tree.order_prev = std::mem::take(&mut app.tree.order); DRAWN.with(|d| d.borrow_mut().clear()); OCCURRENCES.with(|d| d.borrow_mut().clear()); let mut acts = Actions::default(); diff --git a/crates/ui-egui/src/browser/features.rs b/crates/ui-egui/src/browser/features.rs index dd73cb438..8177fd11f 100644 --- a/crates/ui-egui/src/browser/features.rs +++ b/crates/ui-egui/src/browser/features.rs @@ -158,6 +158,37 @@ mod tests { assert_eq!(h.app.session.undo.len(), undo); } + #[test] + fn browser_feature_shift_click_selects_the_range_up_and_down() { + let mut h = Harness::new(); + let ids: Vec = (0..5) + .map(|i| { + h.app.run("solid.box", json!({"length":10,"width":10,"height":10,"body_name":format!("B{i}")})).unwrap()["feature"].as_u64().unwrap() + }) + .collect(); + h.app.tree.expanded.insert("c0/features".into()); + h.frames(2); + let row = |id: u64| json!({"handle": format!("row:browser-feature:c0:{id}")}); + let all: Vec = ids.iter().map(|&id| Sel::Feature { id }).collect(); + let sorted = |s: &[Sel]| { + let mut v = s.to_vec(); + v.sort_by_key(|x| format!("{x:?}")); + v + }; + // Up: anchor on the last row, Shift+click the first. + h.step(&json!({"click": row(ids[4])})).unwrap(); + h.frames(2); + h.step(&json!({"click": row(ids[0]), "shift": true})).unwrap(); + h.frames(2); + assert_eq!(sorted(&h.app.session.selection), sorted(&all), "Shift+click above the anchor"); + // Down: anchor on the first row, Shift+click the last. + h.step(&json!({"click": row(ids[0])})).unwrap(); + h.frames(2); + h.step(&json!({"click": row(ids[4]), "shift": true})).unwrap(); + h.frames(2); + assert_eq!(sorted(&h.app.session.selection), sorted(&all), "Shift+click below the anchor"); + } + fn find(app: &mut SolveApp, feature: u64, body: &str) { let state = app.session.world_state(); let model_body = state.body(body).unwrap(); diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 6d2b46833..0c4cf320a 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -353,7 +353,7 @@ pub struct Services { pub restore_file: Option>, /// Show the designs the browser keeps for itself; None: the host has no such store. pub browser_files: Option>, - /// HTTP for the agent chat's API agents (OpenAI-compatible endpoints); None: no API agents. + /// HTTP for the agent chat's API agents (OpenAI-compatible and Anthropic-compatible endpoints); None: no API agents. pub agent_http: Option, /// The system keychain, for API agents' keys; None: keys can't be stored. pub secrets: Option>, diff --git a/crates/ui-egui/src/timeline.rs b/crates/ui-egui/src/timeline.rs index 9002faa9c..6a418cda0 100644 --- a/crates/ui-egui/src/timeline.rs +++ b/crates/ui-egui/src/timeline.rs @@ -174,12 +174,22 @@ pub(crate) fn delete_features(app: &mut SolveApp, ids: Vec) { /// [`delete_features`] once each feature's `timeline.dependents` report is in. pub(crate) fn delete_checked_features(app: &mut SolveApp, ids: Vec, reports: &[Value]) { + // Each report is about one feature alone, so it names the others being deleted too: those + // go anyway and are left out of the confirmation. + let deleting: Vec<&str> = ids.iter().filter_map(|id| app.session.doc.feature(*id)).map(|f| f.name.as_str()).collect(); let mut with = std::collections::BTreeSet::new(); let mut fail = std::collections::BTreeSet::new(); for deps in reports { for (key, output) in [("deleted_with_it", &mut with), ("would_fail", &mut fail)] { - output - .extend(deps.get(key).and_then(|value| value.as_array()).into_iter().flatten().filter_map(|value| value.as_str().map(String::from))); + output.extend( + deps.get(key) + .and_then(|value| value.as_array()) + .into_iter() + .flatten() + .filter_map(|value| value.as_str()) + .filter(|name| !deleting.contains(name)) + .map(String::from), + ); } } if with.is_empty() && fail.is_empty() { @@ -202,17 +212,45 @@ pub(crate) fn selected_feature_ids(app: &SolveApp) -> Vec { .collect() } -/// What Copy in a feature's menu copies: the selected features when the right-clicked one is -/// among them, else that feature alone. -pub(crate) fn copy_targets(app: &SolveApp, id: u64) -> Vec { +/// What Copy and Delete in a feature's menu act on: the selected features when the +/// right-clicked one is among them, else that feature alone. +pub(crate) fn menu_targets(app: &SolveApp, id: u64) -> Vec { let selected = selected_feature_ids(app); if selected.contains(&id) { selected } else { vec![id] } } +/// The features from timeline position `from` to the end. +fn features_from(app: &SolveApp, from: usize) -> Vec { + app.session.doc.features.iter().skip(from).map(|f| f.id).collect() +} + +/// In the menu of a feature after the history marker (feature `id` at timeline position +/// `index`): delete every feature after the marker, labelled with how many, in one delete +/// through [`delete_features`] so the confirmation still lists what would fail. Not offered +/// before the marker, nor when the menu acts on several selected features: an entry that acts +/// partly on the selection and partly beyond it is hard to read. +pub(crate) fn delete_after_marker_button(app: &mut SolveApp, ui: &mut egui::Ui, id: u64, index: usize, marker: usize) { + if index < marker || menu_targets(app, id).len() > 1 { + return; + } + let ids = features_from(app, marker); + let key = if ids.len() == 1 { "timeline.delete_after_marker_one" } else { "timeline.delete_after_marker_other" }; + let label = crate::i18n::format(key, &[("count", &ids.len().to_string())]); + if crate::context_menu::button(ui, &label, "delete").clicked() { + delete_features(app, ids); + ui.close(); + } +} + +/// The timeline anchor of a feature: the last one clicked, where a Shift+click range starts. +pub(crate) fn anchor_key(id: u64) -> String { + format!("f:{id}") +} + /// Copy and Paste in a feature's timeline menu. Paste puts the copies at the history marker. pub(crate) fn clipboard_buttons(app: &mut SolveApp, ui: &mut egui::Ui, id: u64) { if crate::context_menu::button(ui, crate::i18n::tr_label("Copy"), "copy").clicked() { - let features = copy_targets(app, id); + let features = menu_targets(app, id); let _ = app.run("timeline.copy", json!({ "features": features })); ui.close(); } @@ -256,8 +294,32 @@ pub(crate) fn message_button(app: &SolveApp, ui: &mut egui::Ui, id: u64) { } } +/// Shift+click on a feature: select the features from the anchor (the last feature clicked, or +/// the last selected one) to this one. `order` is the timeline as drawn this frame, taken before +/// drawing so the range never mixes two orders. Ctrl as well adds the range to the selection. +fn select_range(app: &mut SolveApp, order: &[u64], id: u64, add: bool) { + let anchor = app.tree.timeline_anchor.clone().or_else(|| selected_feature_ids(app).last().map(|f| anchor_key(*f))); + let from = anchor.and_then(|key| order.iter().position(|f| anchor_key(*f) == key)); + let (Some(from), Some(to)) = (from, order.iter().position(|f| *f == id)) else { + select_one(app, id); + return; + }; + let range = order.get(from.min(to)..=from.max(to)).unwrap_or_default(); + let items: Vec<_> = range.iter().map(|f| json!({"type": "feature", "id": f})).collect(); + let _ = app.run("select.set", json!({ "items": items, "add": add })); +} + +/// A plain click on a feature: select it alone. +fn select_one(app: &mut SolveApp, id: u64) { + app.tree.picked_joints.clear(); + app.tree.picked_timeline_groups.clear(); + app.tree.timeline_anchor = Some(anchor_key(id)); + let _ = app.run("select.set", json!({"items": [{"type": "feature", "id": id}]})); +} + /// Ctrl+click on a feature: add it to the selection, or take it out. fn toggle_feature(app: &mut SolveApp, id: u64) { + app.tree.timeline_anchor = Some(anchor_key(id)); let selected = selected_feature_ids(app); if selected.contains(&id) { let rest: Vec<_> = @@ -353,6 +415,7 @@ fn timeline_contents(app: &mut SolveApp, ui: &mut egui::Ui, floating: bool) { .iter() .map(|f| (f.id, f.name.clone(), icon_of(&f.kind), f.suppressed, f.kind.type_name(), TimelineKind::of(&f.kind))) .collect(); + let order: Vec = feats.iter().map(|f| f.0).collect(); // The feature whose body is under the cursor in the viewport. let st = app.session.world_state(); let from_view = match &app.viewport.hover { @@ -416,12 +479,15 @@ fn timeline_contents(app: &mut SolveApp, ui: &mut egui::Ui, floating: bool) { d.pick(&app.session, solidcraft_engine::Sel::Feature { id: *id }); app.dialog = Some(d); } - } else if ui.input(|i| i.modifiers.command || i.modifiers.ctrl) { - toggle_feature(app, *id); } else { - app.tree.picked_joints.clear(); - app.tree.picked_timeline_groups.clear(); - let _ = app.run("select.set", json!({"items": [{"type": "feature", "id": id}]})); + let modifiers = ui.input(|i| i.modifiers); + if modifiers.shift { + select_range(app, &order, *id, modifiers.command || modifiers.ctrl); + } else if modifiers.command || modifiers.ctrl { + toggle_feature(app, *id); + } else { + select_one(app, *id); + } } } if resp.double_clicked() { @@ -459,10 +525,16 @@ fn timeline_contents(app: &mut SolveApp, ui: &mut egui::Ui, floating: bool) { clipboard_buttons(app, ui, *id); message_button(app, ui, *id); ui.separator(); - if crate::context_menu::button(ui, "Delete", "delete").clicked() { - delete_feature(app, *id); + let targets = menu_targets(app, *id); + let label = match targets.len() { + 1 => crate::i18n::tr_label("Delete").to_string(), + n => crate::i18n::format("timeline.delete_many", &[("count", &n.to_string())]), + }; + if crate::context_menu::button(ui, &label, "delete").clicked() { + delete_features(app, targets); ui.close(); } + delete_after_marker_button(app, ui, *id, i, marker); }); x += 32.0; } @@ -759,6 +831,124 @@ mod tests { let first = h.app.session.doc.find_feature("First").map(|f| f.id).unwrap(); assert_eq!(super::selected_feature_ids(&h.app), [first]); } + fn three_boxes(left: bool) -> Harness { + let mut h = two_boxes(left); + h.app + .run( + "solid.box", + json!({"length": 10, "width": 10, "height": 10, "corner": [40, 0, 0], "operation": "new_body", "name": "Third", "body_name": "Three"}), + ) + .unwrap(); + h.app.run("select.clear", json!({})).unwrap(); + h.frames(4); + h + } + + fn names(h: &Harness) -> Vec { + h.app.session.doc.features.iter().map(|f| f.name.clone()).collect() + } + + fn ids(h: &Harness, names: &[&str]) -> Vec { + names.iter().map(|name| h.app.session.doc.find_feature(name).map(|f| f.id).unwrap()).collect() + } + + /// Shift+click selects the range from the last feature clicked to this one, either way + /// round; with nothing clicked yet it starts at the last selected feature (#5005). + #[test] + fn shift_click_selects_a_range_of_features() { + let mut h = three_boxes(false); + h.step(&json!({"click": {"handle": "timeline:Third"}})).unwrap(); + h.step(&json!({"click": {"handle": "timeline:First"}, "shift": true})).unwrap(); + assert_eq!(super::selected_feature_ids(&h.app), ids(&h, &["First", "Second", "Third"])); + h.step(&json!({"click": {"handle": "timeline:Second"}, "shift": true})).unwrap(); + assert_eq!(super::selected_feature_ids(&h.app), ids(&h, &["Second", "Third"]), "the range starts at the anchor, Third"); + + h.app.tree.timeline_anchor = None; + h.app.run("select.set", json!({"items": [{"type": "feature", "id": ids(&h, &["First"])[0]}]})).unwrap(); + h.step(&json!({"click": {"handle": "timeline:Second"}, "shift": true})).unwrap(); + assert_eq!(super::selected_feature_ids(&h.app), ids(&h, &["First", "Second"])); + } + + /// Delete in the menu of a selected feature deletes the whole selection in one undo step, + /// and says how many; on a feature outside the selection it deletes that one (#5005). + #[test] + fn the_feature_menu_deletes_the_selected_features() { + let mut h = three_boxes(false); + h.step(&json!({"click": {"handle": "timeline:Third"}, "button": "right"})).unwrap(); + assert!(h.widget("Delete").is_some()); + h.step(&json!({"key": "Escape"})).unwrap(); + + h.step(&json!({"click": {"handle": "timeline:First"}})).unwrap(); + h.step(&json!({"click": {"handle": "timeline:Second"}, "ctrl": true})).unwrap(); + h.step(&json!({"click": {"handle": "timeline:Second"}, "button": "right"})).unwrap(); + h.step(&json!({"widget": "Delete 2 Selected Features"})).unwrap(); + h.settle(); + assert!(h.app.dialog.is_none(), "nothing else depends on them"); + assert_eq!(names(&h), ["Third"]); + h.app.run("edit.undo", json!({})).unwrap(); + assert_eq!(names(&h), ["First", "Second", "Third"]); + } + + /// The menu of a feature after the history marker deletes every feature after the marker, + /// and says how many; features before the marker, and a selection of several, don't offer + /// it. In both timelines (#5005). + #[test] + fn a_feature_after_the_marker_deletes_everything_after_the_marker() { + for left in [false, true] { + let mut h = three_boxes(left); + h.app.run("timeline.roll_to", json!({"position": 1})).unwrap(); + h.settle(); + h.step(&json!({"click": {"handle": "timeline:First"}, "button": "right"})).unwrap(); + assert!(h.widget("Delete 2 Features After History Marker").is_none(), "left: {left}"); + h.step(&json!({"key": "Escape"})).unwrap(); + h.step(&json!({"click": {"handle": "timeline:Second"}})).unwrap(); + h.step(&json!({"click": {"handle": "timeline:Third"}, "ctrl": true})).unwrap(); + h.step(&json!({"click": {"handle": "timeline:Third"}, "button": "right"})).unwrap(); + // (The history beside the browser has its own Delete Selected Features….) + assert!(left || h.widget("Delete 2 Selected Features").is_some()); + assert!(h.widget("Delete 2 Features After History Marker").is_none(), "left: {left}"); + h.step(&json!({"key": "Escape"})).unwrap(); + h.app.run("select.clear", json!({})).unwrap(); + h.frames(2); + + h.step(&json!({"click": {"handle": "timeline:Third"}, "button": "right"})).unwrap(); + h.step(&json!({"widget": "Delete 2 Features After History Marker"})).unwrap(); + h.settle(); + assert_eq!(names(&h), ["First"], "left: {left}"); + h.app.run("edit.undo", json!({})).unwrap(); + assert_eq!(names(&h), ["First", "Second", "Third"], "left: {left}"); + } + } + + /// Deleting a sketch together with the extrude that uses it asks nothing: the extrude is + /// one of the features deleted, not one that goes with it or fails. The Delete key, with + /// the features picked in the timeline, does the same (#5005). + #[test] + fn deleting_a_feature_with_its_dependents_does_not_ask() { + let mut h = Harness::new(); + h.app.run("sketch.create", json!({"plane": "XY", "name": "Base"})).unwrap(); + h.app.run("sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [10, 10]})).unwrap(); + h.app.run("sketch.finish", json!({})).unwrap(); + h.app.run("solid.extrude", json!({"sketch": "Base", "distance": 10, "operation": "new", "name": "Depth"})).unwrap(); + h.app.run("select.clear", json!({})).unwrap(); + h.frames(4); + h.step(&json!({"click": {"handle": "timeline:Base"}})).unwrap(); + h.step(&json!({"click": {"handle": "timeline:Depth"}, "shift": true})).unwrap(); + h.step(&json!({"click": {"handle": "timeline:Depth"}, "button": "right"})).unwrap(); + h.step(&json!({"widget": "Delete 2 Selected Features"})).unwrap(); + h.settle(); + assert!(h.app.dialog.is_none()); + assert!(names(&h).is_empty()); + + h.app.run("edit.undo", json!({})).unwrap(); + h.frames(4); + h.step(&json!({"click": {"handle": "timeline:Base"}})).unwrap(); + h.step(&json!({"click": {"handle": "timeline:Depth"}, "shift": true})).unwrap(); + h.step(&json!({"key": "Delete"})).unwrap(); + h.settle(); + assert!(names(&h).is_empty()); + } + #[test] fn both_strips_keep_selection_reorder_marker_and_transport() { use crate::scenario::{handle_at, rect_of}; diff --git a/crates/ui-egui/src/timeline_left.rs b/crates/ui-egui/src/timeline_left.rs index 3c5cd080d..6886d2d85 100644 --- a/crates/ui-egui/src/timeline_left.rs +++ b/crates/ui-egui/src/timeline_left.rs @@ -5,7 +5,9 @@ use egui::{Rect, Sense, Stroke, pos2, vec2}; use serde_json::json; use crate::theme::Tokens; -use crate::timeline::{TimelineKind, clipboard_buttons, delete_feature, delete_features, icon_of, message_button, selected_feature_ids}; +use crate::timeline::{ + TimelineKind, clipboard_buttons, delete_after_marker_button, delete_feature, delete_features, icon_of, message_button, selected_feature_ids, +}; use crate::{SolveApp, icons}; const FOLDER_INDENT: f32 = 14.0; @@ -51,7 +53,7 @@ impl TimelineItem { fn key(self) -> String { match self { TimelineItem::Group(id) => format!("g:{id}"), - TimelineItem::Feature(id) => format!("f:{id}"), + TimelineItem::Feature(id) => crate::timeline::anchor_key(id), } } } @@ -1088,6 +1090,7 @@ fn vertical_features(app: &mut SolveApp, ui: &mut egui::Ui, names: bool) { delete_feature(app, *id); ui.close(); } + delete_after_marker_button(app, ui, *id, index, marker); }); if names && has_patterns && patterns_open { let depth = group_id.map_or(1, |group| group_depth(&groups, group) + 2); diff --git a/docs/agent-chat.md b/docs/agent-chat.md index d8565a424..e17831886 100644 --- a/docs/agent-chat.md +++ b/docs/agent-chat.md @@ -1,11 +1,12 @@ # Agent chat Agent chat is a side panel where you talk to a coding agent you already use (Claude Code, -Codex, Google Antigravity, OpenCode, Grok Build and others), or to a model behind an OpenAI-compatible endpoint you -choose (Ollama or LM Studio on your computer, OpenAI, any other URL), and have it work on the -design that's open. A coding agent runs on your computer under **your own account** with that -agent: SolidCraft doesn't sell or proxy a model and needs no key for it. An endpoint's key, if -it needs one, goes into your system keychain, never into SolidCraft's settings. +Codex, Google Antigravity, OpenCode, Grok Build and others), or to a model behind an +OpenAI-compatible or Anthropic-compatible endpoint you choose (Ollama or LM Studio on your +computer, OpenAI, Anthropic, any other URL), and have it work on the design that's open. A +coding agent runs on your computer under **your own account** with that agent: SolidCraft +doesn't sell or proxy a model and needs no key for it. An endpoint's key, if it needs one, goes +into your system keychain, never into SolidCraft's settings. Desktop app only. @@ -199,11 +200,15 @@ Grok Build also supports `XAI_API_KEY` for users who choose API authentication. `my-agent --acp`. SolidCraft starts it directly, not through a shell. - **OpenAI-compatible API:** a preset (Ollama `http://localhost:11434/v1`, LM Studio `http://localhost:1234/v1`, OpenAI) or a custom URL, the model name, and an optional key. - The key goes into the system keychain (Keychain on macOS, Credential Manager on Windows, the - Secret Service on Linux) and is only ever sent over HTTPS or to this computer. **Test** asks the - endpoint for its models. For these agents SolidCraft runs the conversation itself, with the - same tools, limits and questions as for a coding agent, and at most 24 model requests per - message. +- **Anthropic-compatible API:** a preset (Anthropic) or a custom URL, for an endpoint that + speaks the Anthropic Messages API (`{base}/v1/messages`). This covers Anthropic itself and + providers that offer an Anthropic-compatible endpoint, such as DeepSeek and Qwen. +- The key goes into the system keychain (Keychain on macOS, Credential Manager on Windows, the + Secret Service on Linux) and is only ever sent over HTTPS or to this computer. **Test** asks an + OpenAI-compatible endpoint for its models; an Anthropic-compatible one gets a short message, + because not every such endpoint lists models (Qwen's has no model list). For these agents + SolidCraft runs the conversation itself, with the same tools, limits and questions as for a + coding agent, and at most 24 model requests per message. ## Signing in diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 8abeddc38..d36ee69ca 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -211,7 +211,7 @@ labels; `prefs:measure_axis_distances` identifies the checkbox. | `ui.agent_cursor` | `show` (bool), `speed`: a number from 1 to 5 (times the normal speed) or `"instant"` (no animation: the command runs at once and the pointer jumps to where it acted), `follow_camera` (bool); all optional | the settings. While the cursor is shown, `engine.execute` first glides to the command's toolbar button and to each pick, then runs and replies; later requests wait their turn. It also follows the pointer input sent with `ui.move`, `ui.click`, `ui.drag` and `ui.scroll`, as each event reaches the app, and a press leaves a ripple. `"animate": false` on a call skips it | | `engine.execute` → `view.layout` | `mode`: `floating` or `compact` | Apply and save the workspace layout without opening a dialog, changing the design, resetting the camera or cancelling its active tool. General preferences expose the same choice; `ui.prefs {"layout":"compact"}` also saves it. | | `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 height equally. One folded header gives the expanded card the rest; two folded headers stay at the top. | -| `ui.agent_chat` | `features?`, `toolbar_button?`, `permissions?` (`ask`, `edits`, `all`), `add_agent?` ({`name`, `kind`: `acp` or `api`, `command` or `base_url` + `model`}; no keys), `default_agent?`, `agent?` (the conversation's agent, by id), `mode?` (the agent's own mode), `model?` (one of its models), `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?`, `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), `popped`, `window` (its place and size), `agent`, `modes`, `mode`, `models`, `model`, `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?`, `permissions?` (`ask`, `edits`, `all`), `add_agent?` ({`name`, `kind`: `acp`, `api` or `anthropic` (`api` is OpenAI-compatible, `anthropic` Anthropic-compatible), `command` or `base_url` + `model`}; no keys), `add_dialog?` (`installed`, `custom`, `api`, `anthropic`, or `false` to close), `default_agent?`, `agent?` (the conversation's agent, by id), `mode?` (the agent's own mode), `model?` (one of its models), `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?`, `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), `popped`, `window` (its place and size), `agent`, `modes`, `mode`, `models`, `model`, `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) | diff --git a/docs/design/in-app-agent-chat.md b/docs/design/in-app-agent-chat.md index 8a0739543..c529f29c8 100644 --- a/docs/design/in-app-agent-chat.md +++ b/docs/design/in-app-agent-chat.md @@ -92,7 +92,7 @@ Code: `crates/ui-egui/src/agent_chat/`. |---|---| | `backend.rs` | The `ChatBackend` trait and its `Event`s: the only thing the panel talks to. | | `acp.rs`, `acp_client.rs` | The protocol messages, and `AcpBackend`, the first backend. | -| `api_client.rs` | `ApiBackend`: an OpenAI-compatible endpoint, with SolidCraft running the tool loop. | +| `api_client.rs` | `ApiBackend`: an OpenAI-compatible or Anthropic-compatible endpoint, with SolidCraft running the tool loop. | | `agents.rs` | The agents (found and added), permission modes, "always allow" answers. | | `settings.rs` | Preferences → AI and the Add agent dialog. | | `process.rs` | The agent as a child process in a process group of its own; stopping it ends the group. | @@ -112,13 +112,17 @@ requests, for a backend that runs tools in process). Two backends exist: - `AcpBackend` drives a coding agent the user already has (the default, and the point of the feature: the user's own account, no keys). - `ApiBackend` talks to an OpenAI-compatible chat completions endpoint (Ollama, LM Studio, - OpenAI, a custom URL) and runs the tool loop itself: it starts the same `solidcraft-cli mcp - --connect` server an ACP agent would get and is its MCP client (`tools/list` becomes the - function tools, `crash_reports` left out), so its calls pass the same gate, limits, questions - and undo as an ACP agent's. At most 24 model requests per message. The HTTP request is the - desktop host's (`Services::agent_http`, ureq with no redirects); the key comes from the system - keychain (`Services::secrets`, the keyring crate) for the connection only and is refused over - plain HTTP to another computer. + OpenAI, a custom URL) or an Anthropic-compatible Messages endpoint (Anthropic, or a provider + that speaks the Messages API), and runs the tool loop itself: it starts the same + `solidcraft-cli mcp --connect` server an ACP agent would get and is its MCP client + (`tools/list` becomes the endpoint's tools, `crash_reports` left out), so its calls pass the + same gate, limits, questions and undo as an ACP agent's. At most 24 model requests per + message. The HTTP request is the desktop host's (`Services::agent_http`, ureq with no + redirects); the key comes from the system keychain (`Services::secrets`, the keyring crate) + for the connection only and is refused over plain HTTP to another computer. The two protocols + differ only in their wire shape: OpenAI sends the system note as a message, function tools + and one `tool` message per result; Anthropic sends it as `system`, `input_schema` tools and + all of a round's `tool_result` blocks in one user message. Another kind of backend slots in the same way without reshaping the panel.