You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@maka.apache.org by wy...@apache.org on 2026/09/25 05:27:39 UTC
(maka) 01/02: fix(rust): harden catalog decoding and stream ownership
This is an automated email from the ASF dual-hosted git repository.
M4n5ter pushed a commit to branch feat/runtime-host-rust
in repository https://gitbox.apache.org/repos/asf/maka.git
commit 33b9fde5995b48640c35ebc70402705b1f35beee
Author: Wang <m4...@gmail.com>
AuthorDate: Fri Sep 25 13:25:33 2026 +0800
fix(rust): harden catalog decoding and stream ownership
Share typed catalog validation so supported model overrides survive decoding. Isolate nested setup cancellation and require confirmed cleanup. Remove redundant tests and color forwarding wrappers, and fix fixture readiness and notification consumption.
Generated-by: Codex
---
crates/acp/src/content.rs | 15 +--
crates/cli/src/args.rs | 8 --
crates/cli/tests/integration/tui.rs | 4 +
crates/cli/tests/integration/tui/projects.rs | 14 +-
crates/config/src/model_catalog.rs | 3 +-
crates/config/src/model_catalog/entry.rs | 85 +-----------
crates/config/src/projection.rs | 4 +-
crates/config/tests/catalog_projection.rs | 2 +-
crates/external-agent/src/driver/v2.rs | 19 ---
crates/external-agent/src/plugin/terminal.rs | 2 +-
crates/external-agent/src/setup.rs | 21 +--
crates/protocol/src/configuration_pages.rs | 141 ++------------------
crates/protocol/tests/configuration_pages.rs | 44 ++++++-
crates/runtime-host/tests/external_agents.rs | 20 ++-
.../tests/integration/client_write/workflow.rs | 3 +-
.../tests/integration/large_outputs/workflow.rs | 13 +-
crates/runtime/src/configuration.rs | 2 +
crates/runtime/src/configuration/model_catalog.rs | 142 +++++++++++++++++++++
crates/runtime/src/configuration/validation.rs | 73 +++++------
crates/tui/src/pages/chat/render.rs | 2 +-
.../pages/manage/enabled_models/profile/view.rs | 4 +-
crates/tui/src/theme.rs | 7 +-
crates/tui/src/view.rs | 8 +-
crates/tui/src/view/form.rs | 4 +-
crates/tui/src/view/session.rs | 6 +-
crates/tui/src/view/tone.rs | 36 +-----
26 files changed, 302 insertions(+), 380 deletions(-)
diff --git a/crates/acp/src/content.rs b/crates/acp/src/content.rs
index db5d5b7e0d..466c8b6aa1 100644
--- a/crates/acp/src/content.rs
+++ b/crates/acp/src/content.rs
@@ -246,11 +246,15 @@ mod tests {
serde_json::from_value(value).unwrap()
}
#[test]
- fn text_and_remote_links_are_explicit_context() {
- let (content, files) = validate(vec!["hello".into(), block(serde_json::json!({"type":"resource_link", "uri":"https://example.com/doc", "name":"guide"}))]).unwrap();
+ fn text_links_and_embedded_resources_preserve_explicit_context() {
+ let (content, files) = validate(vec![
+ "hello".into(),
+ block(serde_json::json!({"type":"resource_link", "uri":"https://example.com/doc", "name":"guide"})),
+ block(serde_json::json!({"type":"resource", "resource":{"uri":"memory://context", "text":"actual content"}})),
+ ]).unwrap();
assert_eq!(
content.text,
- "hello\n\nResource: guide\nhttps://example.com/doc"
+ "hello\n\nResource: guide\nhttps://example.com/doc\n\nResource: memory://context\nactual content"
);
assert!(files.is_empty());
}
@@ -269,9 +273,4 @@ mod tests {
assert!(validate(vec![link; 9]).is_err());
assert!(validate(vec![block(serde_json::json!({"type":"resource_link", "uri":"file:///tmp/a?query", "name":"file"}))]).is_err());
}
- #[test]
- fn embedded_text_keeps_uri_and_content() {
- let (content, _) = validate(vec![block(serde_json::json!({"type":"resource", "resource":{"uri":"memory://context", "text":"actual content"}}))]).unwrap();
- assert!(content.text.contains("memory://context\nactual content"));
- }
}
diff --git a/crates/cli/src/args.rs b/crates/cli/src/args.rs
index bd692e12d3..49235444d7 100644
--- a/crates/cli/src/args.rs
+++ b/crates/cli/src/args.rs
@@ -366,12 +366,4 @@ mod tests {
Some(Command::Tui(Tui {profile: Some(profile), ..})) if profile == "second")
);
}
-
- #[test]
- fn help_keeps_tui_and_existing_commands_discoverable() {
- let help = Cli::command().render_long_help().to_string();
- for command in ["tui", "host", "code", "inspect", "sandbox"] {
- assert!(help.contains(command));
- }
- }
}
diff --git a/crates/cli/tests/integration/tui.rs b/crates/cli/tests/integration/tui.rs
index 27d4f81bee..42cc5055dd 100644
--- a/crates/cli/tests/integration/tui.rs
+++ b/crates/cli/tests/integration/tui.rs
@@ -331,6 +331,10 @@ fn real_host_catalog_subscription_and_remote_updates_reach_clients() {
Some(directory.path()),
);
tui.wait_for(&first[0].name);
+ // Plugin pages pin below the list and change its viewport when they arrive.
+ for page in ["WorkHub", "Scheduled tasks", "Recall"] {
+ tui.wait_for(page);
+ }
// The sidebar keeps loading older sessions at the end of its list.
tui.wheel_at(&first[0].name, true, 12);
tui.wait_for("Load more…");
diff --git a/crates/cli/tests/integration/tui/projects.rs b/crates/cli/tests/integration/tui/projects.rs
index 3413bdada2..5ae118bfde 100644
--- a/crates/cli/tests/integration/tui/projects.rs
+++ b/crates/cli/tests/integration/tui/projects.rs
@@ -143,7 +143,6 @@ fn project_catalog_notifications_and_creation_use_host_project_identity() {
tui.wait_until(|text| text.contains("Renamed project") && !text.contains("Archived"));
tui.click_text("ⓘ");
tui.wait_for("Preferred Host directory");
- tui.wait_for(project_path.to_str().unwrap());
runtime
.block_on(client.request(
Operation::ProjectCatalogMutate,
@@ -151,9 +150,7 @@ fn project_catalog_notifications_and_creation_use_host_project_identity() {
))
.unwrap();
tui.wait_until(|text| {
- text.contains("Observed project")
- && text.contains("Preferred Host directory")
- && text.contains(project_path.to_str().unwrap())
+ text.contains("Observed project") && text.contains("Preferred Host directory")
});
runtime
.block_on(client.request(
@@ -357,15 +354,6 @@ fn project_catalog_notifications_and_creation_use_host_project_identity() {
tui.click_text("Project locations");
tui.wait_for("Preferred Host directory");
// The location dialog wraps long paths; canonical identity is checked above.
- tui.wait_for(
- browse_target
- .parent()
- .unwrap()
- .canonicalize()
- .unwrap()
- .to_str()
- .unwrap(),
- );
tui.wait_for("目标");
tui.send(b"\x1b");
tui.wait_until(|text| !text.contains("Preferred Host directory") && text.contains("TUI 项目"));
diff --git a/crates/config/src/model_catalog.rs b/crates/config/src/model_catalog.rs
index f80496f719..c7f47237ee 100644
--- a/crates/config/src/model_catalog.rs
+++ b/crates/config/src/model_catalog.rs
@@ -20,9 +20,8 @@
use crate::Result;
mod entry;
mod limits;
-pub use entry::ModelCatalogEntry;
pub(crate) use limits::validate_overrides;
-use maka_runtime::configuration::{ConnectionCatalogEntry, ModelInfo};
+use maka_runtime::configuration::{ConnectionCatalogEntry, ModelCatalogEntry, ModelInfo};
use std::collections::HashSet;
/// Project persisted provider facts and explicit user declarations without resolving plugins.
diff --git a/crates/config/src/model_catalog/entry.rs b/crates/config/src/model_catalog/entry.rs
index 6869ab60eb..516f5cf35e 100644
--- a/crates/config/src/model_catalog/entry.rs
+++ b/crates/config/src/model_catalog/entry.rs
@@ -18,90 +18,9 @@
*/
use super::wire_limit;
-use crate::{ConfigError, Result};
-use maka_runtime::{
- configuration::{ConnectionCatalogEntry, ModelInfo, ModelModality, validation},
- execution::ThinkingLevel,
+use maka_runtime::configuration::{
+ ConnectionCatalogEntry, ModelCatalogEntry, ModelInfo, ModelModality,
};
-use serde::{Deserialize, Serialize};
-
-#[derive(Debug, Clone, Default, Serialize, Deserialize)]
-#[serde(rename_all = "camelCase", deny_unknown_fields)]
-pub struct ModelCatalogEntry {
- /// Effective facts for execution; the catalog's metadata remains the wire authority.
- #[serde(skip)]
- pub capabilities: maka_runtime::configuration::ModelCapabilities,
- pub id: String,
- pub can_use_as_chat_default: bool,
- pub is_default: bool,
- pub supports_vision: bool,
- pub thinking_levels: Vec<ThinkingLevel>,
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub default_thinking_level: Option<ThinkingLevel>,
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub default_supports_vision: Option<bool>,
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub default_context_window: Option<u64>,
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub default_input_limit: Option<u64>,
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub input_limit: Option<u64>,
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub compaction_threshold: Option<u64>,
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub display_name: Option<String>,
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub description: Option<String>,
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub context_window: Option<u64>,
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub knowledge_cutoff: Option<String>,
-}
-
-impl ModelCatalogEntry {
- pub fn new(id: impl Into<String>) -> Self {
- Self {
- id: id.into(),
- can_use_as_chat_default: true,
- ..Self::default()
- }
- }
-
- pub(crate) fn validate(&self) -> Result<()> {
- validation::text(&self.id, 512, true).map_err(ConfigError::Invalid)?;
- for (value, max) in [
- (self.display_name.as_deref(), 512),
- (self.description.as_deref(), 2048),
- (self.knowledge_cutoff.as_deref(), 2048),
- ] {
- if let Some(value) = value {
- validation::text(value, max, false).map_err(ConfigError::Invalid)?;
- }
- }
- for value in [self.context_window, self.input_limit]
- .into_iter()
- .flatten()
- {
- validation::revision(value, true).map_err(ConfigError::Invalid)?;
- }
- for (index, level) in self.thinking_levels.iter().enumerate() {
- if self.thinking_levels[..index].contains(level) {
- return Err(ConfigError::Invalid(
- "duplicate catalog thinking level".into(),
- ));
- }
- }
- if self
- .default_thinking_level
- .is_some_and(|level| !self.thinking_levels.contains(&level))
- {
- return Err(ConfigError::Invalid(
- "unsupported default thinking level".into(),
- ));
- }
- Ok(())
- }
-}
pub(super) fn resolve(
row: &ConnectionCatalogEntry,
diff --git a/crates/config/src/projection.rs b/crates/config/src/projection.rs
index 690b9c7008..cbe6b3d036 100644
--- a/crates/config/src/projection.rs
+++ b/crates/config/src/projection.rs
@@ -20,8 +20,6 @@ use crate::{ConfigError, Result};
use maka_runtime::configuration::*;
use serde_json::{Value, json};
-pub use crate::model_catalog::ModelCatalogEntry;
-
/// Produces a 128-item / 128 KiB wire page; the cursor identifies
/// the next item, and only belongs to the revision that produced it.
pub fn project(
@@ -47,7 +45,7 @@ pub fn project(
.map(|target| target.model_id.as_str());
let entries = resolve(row, default)?;
for entry in &entries {
- entry.validate()?;
+ entry.validate().map_err(ConfigError::Invalid)?;
}
let mut header = json!({"kind":"connection", "connectionIndex":connection_index,
"connectionId":row.connection_id,"revision":row.revision,"slug":row.slug,
diff --git a/crates/config/tests/catalog_projection.rs b/crates/config/tests/catalog_projection.rs
index 56b6a32017..107a520f63 100644
--- a/crates/config/tests/catalog_projection.rs
+++ b/crates/config/tests/catalog_projection.rs
@@ -16,7 +16,7 @@
* specific language governing permissions and limitations
* under the License.
*/
-use maka_config::{Result, model_catalog::ModelCatalogEntry, projection::project};
+use maka_config::{Result, projection::project};
use maka_runtime::configuration::*;
use maka_runtime::execution::ThinkingLevel;
use serde_json::json;
diff --git a/crates/external-agent/src/driver/v2.rs b/crates/external-agent/src/driver/v2.rs
index 90ce9f06b1..98eefbfc61 100644
--- a/crates/external-agent/src/driver/v2.rs
+++ b/crates/external-agent/src/driver/v2.rs
@@ -257,22 +257,3 @@ impl Driver<'_> {
Ok(())
}
}
-
-#[cfg(test)]
-mod tests {
- use super::*;
- #[test]
- fn config_values_use_v2_discriminated_config_id_wire_shape() {
- let input = acp::SetSessionConfigOptionRequest::new(
- "s",
- "model",
- acp::SessionConfigOptionValue::Id {
- value: "choice".into(),
- },
- );
- let value = serde_json::to_value(input).unwrap();
- assert_eq!(value["configId"], "model");
- assert_eq!(value["type"], "id");
- assert_eq!(value["value"], "choice");
- }
-}
diff --git a/crates/external-agent/src/plugin/terminal.rs b/crates/external-agent/src/plugin/terminal.rs
index 137c26a683..ae414c0dba 100644
--- a/crates/external-agent/src/plugin/terminal.rs
+++ b/crates/external-agent/src/plugin/terminal.rs
@@ -122,7 +122,7 @@ impl Agents {
})
.await;
stream.cancel();
- let _ = stream.close().await;
+ stream.close().await?;
answer.map_err(|_| Error::Provider("The agent did not answer in time".into()))?
}
}
diff --git a/crates/external-agent/src/setup.rs b/crates/external-agent/src/setup.rs
index 38146bcde4..cae125bd26 100644
--- a/crates/external-agent/src/setup.rs
+++ b/crates/external-agent/src/setup.rs
@@ -93,8 +93,10 @@ impl remote::StreamProvider for Provider {
{
return Err(Error::Invalid("Invalid authentication method".into()));
}
- // Views captured this same request token; cancel also withdraws pending consent.
- let cancellation = caller.cancellation.clone();
+ // This stream owns only its work. The authorized scope below settles
+ // pending consent/processes; closing a nested stream must not cancel
+ // the Remote method that is consuming its result.
+ let cancellation = caller.cancellation.child_token();
let worker_cancel = cancellation.clone();
let (send, receive) = mpsc::channel(8);
let done = context
@@ -345,18 +347,3 @@ async fn emit(send: &mpsc::Sender<Result<Value, Error>>, event: Value) -> Result
fn provider(error: impl std::fmt::Display) -> Error {
Error::Provider(error.to_string())
}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- #[test]
- fn setup_actions_require_explicit_authentication_method() {
- let mut input = json!({"agentId":"agent", "operationId":Uuid::nil(), "kind":"check"});
- assert!(serde_json::from_value::<Input>(input.clone()).is_ok());
- input["kind"] = json!("authenticate");
- assert!(serde_json::from_value::<Input>(input.clone()).is_err());
- input["methodId"] = json!("offered-method");
- assert!(serde_json::from_value::<Input>(input).is_ok());
- }
-}
diff --git a/crates/protocol/src/configuration_pages.rs b/crates/protocol/src/configuration_pages.rs
index 3d240c54a1..a89c8659c4 100644
--- a/crates/protocol/src/configuration_pages.rs
+++ b/crates/protocol/src/configuration_pages.rs
@@ -16,11 +16,12 @@
* specific language governing permissions and limitations
* under the License.
*/
-//! Epoch 141 catalog output boundary, independent of the catalog producer.
+//! Catalog output boundary using the shared public configuration types.
use crate::codec::{count, exact, record, shaped, string};
use crate::{ProtocolError, Result};
-use maka_runtime::configuration::{ConnectionCatalogEntry, ConnectionTarget, validation as v};
-use maka_runtime::execution::ThinkingLevel;
+use maka_runtime::configuration::{
+ ConnectionCatalogEntry, ConnectionTarget, ModelCatalogEntry, ModelOverride, validation as v,
+};
use serde_json::{Value, json};
// Stored inventory + independent overrides + enabled IDs + fallback + default.
@@ -133,7 +134,6 @@ pub fn decode_catalog_query_result(value: &Value) -> Result<Value> {
fn decode_item(value: &Value) -> Result<Value> {
let o = record(value, "catalog item")?;
- let mut output = value.clone();
match value["kind"].as_str().unwrap_or("") {
"connection" => return header(value),
"enabled_model_id" => {
@@ -150,137 +150,18 @@ fn decode_item(value: &Value) -> Result<Value> {
&["kind", "connectionIndex", "itemIndex", "entry"],
&["modelOverride"],
)?;
- model_entry(&value["entry"])?;
+ let entry: ModelCatalogEntry =
+ serde_json::from_value(value["entry"].clone()).map_err(|_| invalid())?;
+ domain(entry.validate())?;
if let Some(profile) = o.get("modelOverride") {
- output["modelOverride"] = model_override(profile)?;
+ let profile: ModelOverride =
+ serde_json::from_value(profile.clone()).map_err(|_| invalid())?;
+ domain(v::model_override(&entry.id, &profile))?;
}
}
_ => return Err(invalid()),
}
- Ok(output)
-}
-
-fn model_entry(value: &Value) -> Result<()> {
- let o = record(value, "model catalog entry")?;
- shaped(
- o,
- &[
- "id",
- "canUseAsChatDefault",
- "isDefault",
- "supportsVision",
- "thinkingLevels",
- ],
- &[
- "displayName",
- "description",
- "contextWindow",
- "inputLimit",
- "compactionThreshold",
- "defaultContextWindow",
- "defaultInputLimit",
- "defaultSupportsVision",
- "knowledgeCutoff",
- ],
- )?;
- let mut shared = json!({"id":value["id"]});
- for field in [
- "displayName",
- "description",
- "contextWindow",
- "inputLimit",
- "knowledgeCutoff",
- ] {
- if let Some(v) = o.get(field) {
- shared[field] = v.clone();
- }
- }
- domain(v::connection_model(&shared))?;
- for field in ["canUseAsChatDefault", "isDefault", "supportsVision"] {
- if !value[field].is_boolean() {
- return Err(invalid());
- }
- }
- if o.get("defaultSupportsVision")
- .is_some_and(|v| !v.is_boolean())
- {
- return Err(invalid());
- }
- for field in [
- "compactionThreshold",
- "defaultContextWindow",
- "defaultInputLimit",
- ] {
- if let Some(value) = o.get(field)
- && count(value, field)? == 0
- {
- return Err(invalid());
- }
- }
- let levels = value["thinkingLevels"].as_array().ok_or_else(invalid)?;
- let mut seen = std::collections::BTreeSet::new();
- for level in levels {
- let level = level.as_str().ok_or_else(invalid)?;
- if serde_json::from_value::<ThinkingLevel>(json!(level)).is_err() || !seen.insert(level) {
- return Err(invalid());
- }
- }
- Ok(())
-}
-
-fn model_override(value: &Value) -> Result<Value> {
- record(value, "model override")?;
- let mut result = json!({});
- if let Some(levels) = value["thinkingLevels"].as_array() {
- let selected: Vec<ThinkingLevel> = levels
- .iter()
- .filter_map(|level| serde_json::from_value(level.clone()).ok())
- .collect();
- let levels: Vec<_> = ThinkingLevel::ALL
- .into_iter()
- .filter(|level| selected.contains(level))
- .collect();
- if !levels.is_empty() {
- result["thinkingLevels"] = json!(levels);
- }
- }
- for field in ["vision", "codeMode", "applyPatch"] {
- if value[field].is_boolean() {
- result[field] = value[field].clone();
- }
- }
- for field in [
- "contextWindow",
- "inputLimit",
- "compactionThreshold",
- "maxOutputTokens",
- ] {
- if let Ok(n) = count(&value[field], field)
- && n > 0
- {
- result[field] = json!(n);
- }
- }
- for field in ["displayName", "description", "knowledgeCutoff"] {
- if value[field].is_string() {
- result[field] = value[field].clone();
- }
- }
- for field in ["capabilities", "modalities"] {
- if value[field].is_object() {
- result[field] = value[field].clone();
- }
- }
- if matches!(
- value["apiProtocol"].as_str(),
- Some("openai-chat" | "openai-responses" | "anthropic-messages")
- ) {
- result["apiProtocol"] = value["apiProtocol"].clone();
- }
- if value["serviceTier"] == "fast" {
- result["serviceTier"] = json!("fast");
- }
- Ok(result)
+ Ok(value.clone())
}
fn header(value: &Value) -> Result<Value> {
diff --git a/crates/protocol/tests/configuration_pages.rs b/crates/protocol/tests/configuration_pages.rs
index 019e4bcb82..ef94585b01 100644
--- a/crates/protocol/tests/configuration_pages.rs
+++ b/crates/protocol/tests/configuration_pages.rs
@@ -34,11 +34,11 @@ fn mixed_page() -> Value {
{"kind":"model","connectionIndex":0,"itemIndex":0,
"model":{"id":"model","contextWindow":128000,"capabilities":{"chat":true}}},
{"kind":"catalog_entry","connectionIndex":0,"itemIndex":0,
- "modelOverride":{"thinkingLevels":["low","high"],"vision":false},
+ "modelOverride":{"adapter":"external.responses","defaultThinkingLevel":"high","thinkingLevels":["low","high"],"vision":false},
"entry":{"id":"model","displayName":"Model","description":"A model",
"contextWindow":128000,"knowledgeCutoff":"2025-01","canUseAsChatDefault":true,
"isDefault":false,"supportsVision":false,"thinkingLevels":["off","low","high"],
- "defaultSupportsVision":false}}
+ "defaultSupportsVision":false,"defaultThinkingLevel":"high"}}
]})
}
@@ -127,10 +127,13 @@ fn strict_public_shapes_reject_nulls_private_fields_and_invalid_models() {
json!(["contextWindow"]),
),
("/items/3/entry", "apiProtocol", json!("openai-chat")),
+ ("/items/3/entry", "capabilities", json!({"chat":true})),
("/items/3/entry", "thinkingLevels", json!(["low", "low"])),
("/items/3/entry", "thinkingLevels", json!(["unknown"])),
("/items/3/entry", "thinkingLevels", Value::Null),
("/items/3/entry", "supportsVision", json!(1)),
+ ("/items/3/entry", "defaultThinkingLevel", json!("medium")),
+ ("/items/3/entry", "defaultThinkingLevel", Value::Null),
] {
let mut value = page.clone();
value.pointer_mut(pointer).unwrap()[key] = bad;
@@ -139,6 +142,19 @@ fn strict_public_shapes_reject_nulls_private_fields_and_invalid_models() {
"{pointer}/{key}"
);
}
+ for field in [
+ "contextWindow",
+ "inputLimit",
+ "compactionThreshold",
+ "defaultContextWindow",
+ "defaultInputLimit",
+ ] {
+ for bad in [Value::Null, json!(0), json!(9007199254740992_u64)] {
+ let mut value = page.clone();
+ value["items"][3]["entry"][field] = bad;
+ assert!(decode_catalog_query_result(&value).is_err(), "{field}");
+ }
+ }
}
#[test]
@@ -184,15 +200,13 @@ fn pages_enforce_bounds_and_forward_progress_without_requiring_whole_connections
}
#[test]
-fn model_override_sanitization_matches_source_and_empty_overlay_is_omitted() {
+fn model_overrides_are_preserved_or_rejected_and_empty_overlay_is_omitted() {
let mut page = mixed_page();
- page["items"][3]["modelOverride"] = json!({"thinkingLevels":["high","off","low","low"],
- "vision":null,"contextWindow":-1,"serviceTier":"fast","unknown":true});
page["items"][0]["requestBodyOverlay"] = json!({});
let result = decode_catalog_query_result(&page).unwrap();
assert_eq!(
result["items"][3]["modelOverride"],
- json!({"thinkingLevels":["off","low","high"],"serviceTier":"fast"})
+ page["items"][3]["modelOverride"]
);
assert!(result["items"][0].get("requestBodyOverlay").is_none());
page["items"][3]["modelOverride"] = json!({"thinkingLevels":["off"]});
@@ -205,6 +219,24 @@ fn model_override_sanitization_matches_source_and_empty_overlay_is_omitted() {
decode_catalog_query_result(&page).unwrap()["items"][3]["modelOverride"],
json!({})
);
+ for profile in [
+ json!({"thinkingLevels":["low","low"]}),
+ json!({"thinkingLevels":["unknown"]}),
+ json!({"thinkingLevels":[]}),
+ json!({"vision":null}),
+ json!({"adapter":""}),
+ json!({"adapter":"unsafe\nname"}),
+ json!({"defaultThinkingLevel":"unknown"}),
+ json!({"contextWindow":-1}),
+ json!({"inputLimit":0}),
+ json!({"maxOutputTokens":9007199254740992_u64}),
+ json!({"capabilities":{"chat":"yes"}}),
+ json!({"modalities":{"input":["text"],"output":["unknown"]}}),
+ json!({"unknown":true}),
+ ] {
+ page["items"][3]["modelOverride"] = profile;
+ assert!(decode_catalog_query_result(&page).is_err());
+ }
}
#[test]
diff --git a/crates/runtime-host/tests/external_agents.rs b/crates/runtime-host/tests/external_agents.rs
index 2c38e8691b..e6c5451dad 100644
--- a/crates/runtime-host/tests/external_agents.rs
+++ b/crates/runtime-host/tests/external_agents.rs
@@ -766,11 +766,29 @@ async fn acp_setup_stream_authenticates_filters_urls_and_closes_cancelled_proces
success(running.peer.rpc("plugin.remote", json!({"kind":"close","document":document,"stream":stream})).await);
process_closed(&mut process).await;
}
+ // The terminal action consumes the setup stream inside a live Remote
+ // method. Closing that child must not cancel the containing action.
+ let terminal = json!({"packageId":"acceptance.acp-package","method":"terminal"});
+ let terminal_target = success(running.peer.rpc("plugin.remote",
+ json!({"kind":"bind","binding":terminal})).await)["target"].clone();
+ let view = success(running.peer.rpc("plugin.remote", json!({
+ "kind":"call","binding":terminal,"target":terminal_target,"document":document,
+ "input":{"kind":"read","route":{"agent":"test.acp"},"locale":"en"}
+ })).await)["value"]["view"].clone();
+ let checked = success(running.peer.rpc("plugin.remote", json!({
+ "kind":"call","binding":terminal,"target":terminal_target,"document":document,
+ "input":{"kind":"submit","route":{"agent":"test.acp"},"revision":view["revision"],
+ "action":"check","fields":{},"locale":"en"}
+ })).await)["value"].clone();
+ assert_eq!(checked["kind"], "applied", "{checked}");
+ assert!(checked["route"]["checked"].as_str().is_some_and(|text| !text.is_empty()));
+ let mut process = fixture.process().await;
+ process_closed(&mut process).await;
success(running.peer.rpc("plugin.remote", json!({"kind":"close_document","document":document})).await);
running.close().await;
let records = fixture.records();
let versions = records.iter().filter(|row| row["method"] == "initialize").map(|row| row["params"]["protocolVersion"].clone()).collect::<Vec<_>>();
- assert_eq!(versions, if protocol != 2 { [json!(2), json!(1)].into_iter().cycle().take(8).collect::<Vec<_>>() } else { vec![json!(2); 4] });
+ assert_eq!(versions, if protocol != 2 { [json!(2), json!(1)].into_iter().cycle().take(10).collect::<Vec<_>>() } else { vec![json!(2); 5] });
assert_eq!(records.iter().filter(|row| row["method"] == "spawn").count(), versions.len());
assert_eq!(records.iter().filter(|row| row["method"] == if protocol != 2 { "authenticate" } else { "auth/login" }).count(), 3);
assert!(!records.iter().any(|row| row["method"] == "session/new" || row["method"] == "session/prompt"));
diff --git a/crates/runtime-host/tests/integration/client_write/workflow.rs b/crates/runtime-host/tests/integration/client_write/workflow.rs
index 622f1ddbc3..5b81a62339 100644
--- a/crates/runtime-host/tests/integration/client_write/workflow.rs
+++ b/crates/runtime-host/tests/integration/client_write/workflow.rs
@@ -52,7 +52,8 @@ pub(super) async fn run(fixture: &ClientFixture, reopened: bool) -> (Vec<Value>,
Host::open_with_global_instructions(fixture.owner(), Some(fixture.workspace.join(".maka")))
.await
.unwrap();
- let (peer, hello) = Peer::handshake(host.clone(), "write-identity").await;
+ let (mut peer, hello) = Peer::handshake(host.clone(), "write-identity").await;
+ peer.wait_for_plugins().await;
peer.close().await;
#[cfg(unix)]
let endpoint = fixture.workspace.parent().unwrap().join("h.sock");
diff --git a/crates/runtime-host/tests/integration/large_outputs/workflow.rs b/crates/runtime-host/tests/integration/large_outputs/workflow.rs
index 4f8f7c98eb..589bd91855 100644
--- a/crates/runtime-host/tests/integration/large_outputs/workflow.rs
+++ b/crates/runtime-host/tests/integration/large_outputs/workflow.rs
@@ -130,7 +130,18 @@ pub(super) async fn verify(
.unwrap();
live = Some(open.subscription_id);
}
- let terminal = support::completed(client, &turn).await;
+ // This is an active subscriber. Drain live frames while polling the
+ // Turn so the bounded client queue does not fail as a slow consumer.
+ let terminal = {
+ let completed = support::completed(client, &turn);
+ tokio::pin!(completed);
+ loop {
+ tokio::select! {
+ result = &mut completed => break result,
+ notice = native.notices.recv() => assert!(notice.is_some(), "client disconnected during the Turn"),
+ }
+ }
+ };
if case == "control" {
capacity(client, &session, live.as_deref()).await;
let basis = client
diff --git a/crates/runtime/src/configuration.rs b/crates/runtime/src/configuration.rs
index bc6b1a3caf..4ddf12e99f 100644
--- a/crates/runtime/src/configuration.rs
+++ b/crates/runtime/src/configuration.rs
@@ -24,8 +24,10 @@ pub mod headers;
pub mod onboarding;
pub use catalog_wire::*;
pub use effects::*;
+mod model_catalog;
mod model_info;
mod model_override;
+pub use model_catalog::ModelCatalogEntry;
pub use model_info::{ModelCapabilities, ModelInfo};
mod model_validation;
pub mod policy;
diff --git a/crates/runtime/src/configuration/model_catalog.rs b/crates/runtime/src/configuration/model_catalog.rs
new file mode 100644
index 0000000000..dc3737276d
--- /dev/null
+++ b/crates/runtime/src/configuration/model_catalog.rs
@@ -0,0 +1,142 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+use super::{ModelCapabilities, present, validation};
+use crate::execution::ThinkingLevel;
+use serde::{Deserialize, Serialize};
+
+#[derive(Debug, Clone, Default, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase", deny_unknown_fields)]
+pub struct ModelCatalogEntry {
+ /// Effective facts for execution; the catalog's metadata remains the wire authority.
+ #[serde(skip)]
+ pub capabilities: ModelCapabilities,
+ pub id: String,
+ pub can_use_as_chat_default: bool,
+ pub is_default: bool,
+ pub supports_vision: bool,
+ pub thinking_levels: Vec<ThinkingLevel>,
+ #[serde(
+ default,
+ skip_serializing_if = "Option::is_none",
+ deserialize_with = "present"
+ )]
+ pub default_thinking_level: Option<ThinkingLevel>,
+ #[serde(
+ default,
+ skip_serializing_if = "Option::is_none",
+ deserialize_with = "present"
+ )]
+ pub default_supports_vision: Option<bool>,
+ #[serde(
+ default,
+ skip_serializing_if = "Option::is_none",
+ deserialize_with = "present"
+ )]
+ pub default_context_window: Option<u64>,
+ #[serde(
+ default,
+ skip_serializing_if = "Option::is_none",
+ deserialize_with = "present"
+ )]
+ pub default_input_limit: Option<u64>,
+ #[serde(
+ default,
+ skip_serializing_if = "Option::is_none",
+ deserialize_with = "present"
+ )]
+ pub input_limit: Option<u64>,
+ #[serde(
+ default,
+ skip_serializing_if = "Option::is_none",
+ deserialize_with = "present"
+ )]
+ pub compaction_threshold: Option<u64>,
+ #[serde(
+ default,
+ skip_serializing_if = "Option::is_none",
+ deserialize_with = "present"
+ )]
+ pub display_name: Option<String>,
+ #[serde(
+ default,
+ skip_serializing_if = "Option::is_none",
+ deserialize_with = "present"
+ )]
+ pub description: Option<String>,
+ #[serde(
+ default,
+ skip_serializing_if = "Option::is_none",
+ deserialize_with = "present"
+ )]
+ pub context_window: Option<u64>,
+ #[serde(
+ default,
+ skip_serializing_if = "Option::is_none",
+ deserialize_with = "present"
+ )]
+ pub knowledge_cutoff: Option<String>,
+}
+
+impl ModelCatalogEntry {
+ pub fn new(id: impl Into<String>) -> Self {
+ Self {
+ id: id.into(),
+ can_use_as_chat_default: true,
+ ..Self::default()
+ }
+ }
+
+ pub fn validate(&self) -> validation::ValidationResult {
+ validation::text(&self.id, 512, true)?;
+ for (value, max) in [
+ (self.display_name.as_deref(), 512),
+ (self.description.as_deref(), 2048),
+ (self.knowledge_cutoff.as_deref(), 2048),
+ ] {
+ if let Some(value) = value {
+ validation::text(value, max, false)?;
+ }
+ }
+ for value in [
+ self.context_window,
+ self.input_limit,
+ self.compaction_threshold,
+ self.default_context_window,
+ self.default_input_limit,
+ ]
+ .into_iter()
+ .flatten()
+ {
+ validation::revision(value, true)?;
+ }
+ for (index, level) in self.thinking_levels.iter().enumerate() {
+ if self.thinking_levels[..index].contains(level) {
+ return Err("duplicate catalog thinking level".into());
+ }
+ }
+ if self
+ .default_thinking_level
+ .is_some_and(|level| !self.thinking_levels.contains(&level))
+ {
+ return Err("unsupported default thinking level".into());
+ }
+ Ok(())
+ }
+}
diff --git a/crates/runtime/src/configuration/validation.rs b/crates/runtime/src/configuration/validation.rs
index f927381d9a..ed8200a4a8 100644
--- a/crates/runtime/src/configuration/validation.rs
+++ b/crates/runtime/src/configuration/validation.rs
@@ -112,47 +112,44 @@ pub fn profiles(values: &BTreeMap<String, ModelOverride>) -> ValidationResult {
return Err("too many model overrides".into());
}
for (id, p) in values {
- text(id, 512, true)?;
- if let Some(adapter) = &p.adapter {
- text(adapter, 256, true)?;
- if adapter.chars().any(char::is_control) {
- return Err("invalid model adapter name".into());
- }
- }
- if let Some(levels) = &p.thinking_levels
- && (levels.is_empty()
- || levels
- .iter()
- .enumerate()
- .any(|(index, level)| levels[..index].contains(level)))
- {
- return Err("invalid relay thinking levels".into());
+ model_override(id, p)?;
+ }
+ Ok(())
+}
+
+pub fn model_override(id: &str, p: &ModelOverride) -> ValidationResult {
+ text(id, 512, true)?;
+ if let Some(adapter) = &p.adapter {
+ text(adapter, 256, true)?;
+ if adapter.chars().any(char::is_control) {
+ return Err("invalid model adapter name".into());
}
- for n in [
- p.context_window,
- p.input_limit,
- p.compaction_threshold,
- p.max_output_tokens,
- ]
+ }
+ if let Some(levels) = &p.thinking_levels
+ && (levels.is_empty()
+ || levels
+ .iter()
+ .enumerate()
+ .any(|(index, level)| levels[..index].contains(level)))
+ {
+ return Err("invalid relay thinking levels".into());
+ }
+ for n in [
+ p.context_window,
+ p.input_limit,
+ p.compaction_threshold,
+ p.max_output_tokens,
+ ]
+ .into_iter()
+ .flatten()
+ {
+ revision(n, true)?;
+ }
+ for value in [&p.display_name, &p.description, &p.knowledge_cutoff]
.into_iter()
.flatten()
- {
- revision(n, true)?;
- }
- for value in [&p.display_name, &p.description].into_iter().flatten() {
- text(value, 2048, false)?;
- }
- let mut facts = serde_json::json!({"id":id});
- if let Some(value) = &p.knowledge_cutoff {
- facts["knowledgeCutoff"] = serde_json::json!(value);
- }
- if let Some(value) = &p.capabilities {
- facts["capabilities"] = serde_json::to_value(value).map_err(|e| e.to_string())?;
- }
- if let Some(value) = &p.modalities {
- facts["modalities"] = serde_json::to_value(value).map_err(|e| e.to_string())?;
- }
- connection_model(&facts)?;
+ {
+ text(value, 2048, false)?;
}
Ok(())
}
diff --git a/crates/tui/src/pages/chat/render.rs b/crates/tui/src/pages/chat/render.rs
index b9d11c52c9..2d36e00d92 100644
--- a/crates/tui/src/pages/chat/render.rs
+++ b/crates/tui/src/pages/chat/render.rs
@@ -1008,7 +1008,7 @@ impl Transcript {
Kind::Thinking | Kind::Steps => {
let mut line = line;
for span in &mut line.spans {
- span.style.fg = Some(crate::view::tone::thinking(self.colors));
+ span.style.fg = Some(self.colors.thinking);
span.style = span.style.remove_modifier(Modifier::BOLD);
}
line
diff --git a/crates/tui/src/pages/manage/enabled_models/profile/view.rs b/crates/tui/src/pages/manage/enabled_models/profile/view.rs
index 7347a73b99..81135d6dbe 100644
--- a/crates/tui/src/pages/manage/enabled_models/profile/view.rs
+++ b/crates/tui/src/pages/manage/enabled_models/profile/view.rs
@@ -23,7 +23,7 @@ use crate::{
app::{Action, App},
pages::manage::Dialog,
ui::{Node, On, Role, Sheet, Size, Tone},
- view::{safe, tone},
+ view::safe,
};
use crossterm::event::{Event, KeyCode, KeyEventKind, KeyModifiers, MouseButton, MouseEventKind};
use ratatui::{
@@ -282,7 +282,7 @@ pub(in crate::pages::manage::enabled_models) fn draw(frame: &mut Frame<'_>, app:
frame.buffer_mut().set_style(label, colors.base());
frame.render_widget(
Paragraph::new(labels[index].as_str()).style(Style::default().fg(if here {
- tone::accent(colors)
+ colors.accent
} else {
colors.muted
})),
diff --git a/crates/tui/src/theme.rs b/crates/tui/src/theme.rs
index 41d086fb2d..d763cfdf32 100644
--- a/crates/tui/src/theme.rs
+++ b/crates/tui/src/theme.rs
@@ -314,15 +314,18 @@ mod tests {
(a.max(b) + 0.05) / (a.min(b) + 0.05)
}
#[test]
- fn shipped_rgb_palettes_keep_body_status_syntax_and_selection_readable() {
+ fn shipped_palettes_keep_text_readable_and_motion_appropriate() {
let mut choice = Choice::default();
for expected in [Choice::Maka, Choice::Dusk, Choice::Paper, Choice::Terminal] {
assert_eq!(choice, expected);
choice = choice.next();
+ let c = expected.colors();
if expected == Choice::Terminal {
+ assert_eq!(c.breath(true, Some(0.0)), c.breath(true, Some(1.0)));
continue;
}
- let c = expected.colors();
+ assert_ne!(c.breath(true, Some(0.0)), c.breath(true, Some(1.0)));
+ assert_eq!(c.breath(true, Some(1.0)), c.accent);
for color in [
c.foreground,
c.muted,
diff --git a/crates/tui/src/view.rs b/crates/tui/src/view.rs
index 1cab35d725..aad5f1bc00 100644
--- a/crates/tui/src/view.rs
+++ b/crates/tui/src/view.rs
@@ -169,7 +169,7 @@ pub fn draw(frame: &mut Frame<'_>, app: &mut App) {
let color = if activity == activity::Activity::Waiting {
app.theme.colors().warning
} else {
- tone::accent(app.theme.colors())
+ app.theme.colors().accent
};
Line::from(vec![
ratatui::text::Span::styled(face, Style::default().fg(color)),
@@ -797,12 +797,12 @@ fn control(
.fg(app.theme.colors().subtle)
.add_modifier(Modifier::DIM)
} else if focused || app.hover.as_ref() == Some(&action) {
- tone::selection(app.theme.colors()).fg(if destructive {
+ app.theme.colors().focused().fg(if destructive {
app.theme.colors().error
} else if caution {
app.theme.colors().warning
} else {
- tone::accent(app.theme.colors())
+ app.theme.colors().accent
})
} else if destructive {
Style::default().fg(app.theme.colors().error)
@@ -812,7 +812,7 @@ fn control(
action,
Action::SendMessage | Action::SteerMessage | Action::StopTurn(_)
) {
- Style::default().fg(tone::accent(app.theme.colors()))
+ Style::default().fg(app.theme.colors().accent)
} else {
Style::default().fg(app.theme.colors().muted)
};
diff --git a/crates/tui/src/view/form.rs b/crates/tui/src/view/form.rs
index 333bc6cc35..a2cc139e33 100644
--- a/crates/tui/src/view/form.rs
+++ b/crates/tui/src/view/form.rs
@@ -20,7 +20,7 @@
//! Labelled text rows of a form sheet. Each whole row is one kernel slot,
//! so a form's rows share a focus group and the arrows walk them; the
//! label and the editor are painted here, over the drawn sheet.
-use crate::{editor::Editor, theme::Palette, view::tone};
+use crate::{editor::Editor, theme::Palette};
use ratatui::{Frame, layout::Rect, style::Style, widgets::Paragraph};
/// The label column for labels this wide, on a terminal this wide.
@@ -52,7 +52,7 @@ pub(crate) fn draw(
frame.buffer_mut().set_style(label, colors.base());
frame.render_widget(
Paragraph::new(row.label).style(Style::default().fg(if row.focused {
- tone::accent(colors)
+ colors.accent
} else {
colors.muted
})),
diff --git a/crates/tui/src/view/session.rs b/crates/tui/src/view/session.rs
index de7830c711..bb144bf8d0 100644
--- a/crates/tui/src/view/session.rs
+++ b/crates/tui/src/view/session.rs
@@ -236,7 +236,7 @@ pub(super) fn draw(frame: &mut Frame<'_>, app: &mut App, area: Rect, id: &str) {
BorderType::Rounded
})
.padding(Padding::new(4, control_width, 0, 0))
- .border_style(Style::default().fg(tone::border(app.theme.colors(), focused, breath)));
+ .border_style(Style::default().fg(app.theme.colors().breath(focused, breath)));
let mut input = border.inner(parts[3]);
frame.render_widget(border, parts[3]);
frame.render_widget(Paragraph::new(metadata), metadata_area);
@@ -496,7 +496,7 @@ mod tests {
assert_eq!(button, " ■ ");
assert_eq!(
terminal.backend().buffer()[(area.x, area.y - 1)].fg,
- tone::border(app.theme.colors(), true, Some(0.45))
+ app.theme.colors().breath(true, Some(0.45))
);
assert!(!app.drafts["chat"].contains(Position::new(area.x, area.y)));
assert_eq!(
@@ -593,7 +593,7 @@ mod tests {
.unwrap();
assert_ne!(
terminal.backend().buffer()[(send.area.x, send.area.y - 1)].fg,
- tone::border(app.theme.colors(), true, Some(0.45))
+ app.theme.colors().breath(true, Some(0.45))
);
app.chat.snapshot = Some(snapshot.clone());
app.chat
diff --git a/crates/tui/src/view/tone.rs b/crates/tui/src/view/tone.rs
index 8de6be4edc..1ce89baac8 100644
--- a/crates/tui/src/view/tone.rs
+++ b/crates/tui/src/view/tone.rs
@@ -17,18 +17,9 @@
* under the License.
*/
-//! Shared semantic colors; no process-global theme or terminal-cell recoloring.
+//! Stable session identity hues from the selected palette.
use crate::theme::Palette;
-use ratatui::style::{Color, Style};
-pub fn accent(colors: Palette) -> Color {
- colors.accent
-}
-pub fn thinking(colors: Palette) -> Color {
- colors.thinking
-}
-pub fn selection(colors: Palette) -> Style {
- colors.focused()
-}
+use ratatui::style::Color;
/// Stable identity hue index for a session ID (FNV-1a), never its position.
pub fn session_hue(id: &str) -> u8 {
let hash = id.bytes().fold(0xcbf29ce484222325_u64, |h, b| {
@@ -50,26 +41,3 @@ pub fn hue(index: u8, colors: Palette) -> Color {
];
variants[usize::from(index) % variants.len()]
}
-pub fn border(colors: Palette, focused: bool, breath: Option<f32>) -> Color {
- colors.breath(focused, breath)
-}
-#[cfg(test)]
-mod tests {
- use super::*;
- use crate::theme::Choice;
- #[test]
- fn working_border_has_visible_blue_breath_without_flashing_or_changing_terminal_palette() {
- let palette = Choice::Maka.colors();
- let Color::Rgb(r, g, b) = border(palette, true, Some(0.0)) else {
- panic!("RGB");
- };
- assert!(b > g && g > r && b >= 100);
- assert_eq!(border(palette, true, Some(1.0)), palette.accent);
- assert!(253 - b >= 100);
- let terminal = Choice::Terminal.colors();
- assert_eq!(
- border(terminal, true, Some(0.0)),
- border(terminal, true, Some(1.0))
- );
- }
-}
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org