Compare commits

...
22 Commits
Author SHA1 Message Date
clawdbot 350e907e35 Revert "Merge pull request #3341 from ultraworkers/fix/rebase-on-main"
This reverts commit 734558eb31, reversing
changes made to 942805175a.
2026-10-13 00:14:54 +00:00
Bellman 734558eb31 Merge pull request #3341 from ultraworkers/fix/rebase-on-main
feat(team): team enhancements, subagentModel, parallel tool exec (fixed from #3250)
2026-10-13 09:13:47 +09:00
Bellman 942805175a Merge pull request #3338 from ultraworkers/lane/pr-3248
feat: custom-openai provider namespace with separate env vars
2026-10-13 09:13:14 +09:00
clawdbot dfa1e4f71e fix: resolve merge conflicts and test compatibility
- Resolve .gitignore conflict: include both nix entries and .claude/
- Update AnthropicRuntimeClient::new() test calls to match new signature
- Fix explicit_model_provider_hint test to unset OPENAI_BASE_URL env var
2026-10-13 00:12:36 +00:00
clawdbot 8a19ecd7cc fix: use PermissionMode.covers() instead of comparison operators
The PermissionMode enum intentionally does not implement PartialOrd
to prevent silent re-ranking of the privilege ladder. Use the explicit
covers() method for privilege comparisons instead of < and >=.
2026-10-13 00:12:35 +00:00
clawdbot 8938f53790 fix(clippy): resolve new lint violations in trident, compact, and claw-rag-service
- runtime/trident.rs: derive Default, fix for_kv_map, if_same_then_else, extend_with_drain, unnecessary_cast, needless_borrows
- runtime/compact.rs: fix useless_borrows_in_formatting
- claw-rag-service/ingest.rs: remove unnecessary into_iter()
- claw-rag-service/db.rs: use as_chunks instead of chunks_exact, remove unused import

All tests pass (1014 Rust + 47 Python tests verified).
2026-10-13 00:12:35 +00:00
TheArchitectit 5433dac4a2 fix(cli): order parallel tool results by call index and cap fan-out
execute_batch already keyed results to original call slots; this makes
that airtight: panicking worker threads resolve to their own index via
a fallback tuple instead of colliding with slot 0, and results are
asserted to follow call order with a regression test that mixes a
workspace-escape read among valid reads at cap=2.

Adds the fan-out bound: parallel-safe calls run in waves of at most
maxParallelToolCalls (default 8, CLAWD_PARALLEL_TOOL_CALLS env, or the
new setting applied via with_max_parallel_tool_calls at runtime build).
Sequential behavior is preserved: allowed_tools checks still run
before dispatch, and ToolSearch stays off the parallel path.
2026-10-13 00:12:35 +00:00
TheArchitectit f3a23bf39f feat(teams): bound per-team sub-agent concurrency with AgentGate
TeamCreate resolves maxConcurrentAgents from the per-team input, then
the maxConcurrentAgents setting, then unlimited (pre-fix behavior).
The cap is persisted in the manifest and registered on a process-wide
gate; agent threads still spawn immediately but block on an RAII slot
before entering their run loop, so manifest/task-claim semantics are
unchanged. TeamDelete forgets the gate so queued agents drain and no
stale team entries accumulate. Includes a gate regression test.
2026-10-13 00:12:35 +00:00
TheArchitectit 66006cca34 feat(config): parse maxParallelToolCalls and maxConcurrentAgents settings
Adds optional positive-integer parsing for the two new fan-out caps
next to subagentModel, in both camelCase and snake_case forms. Zero
parses as unset; non-numeric values are a named config error. Covered
by three regression tests mirroring the subagentModel test style.
2026-10-13 00:12:35 +00:00
TheArchitectitandClaw 08cce855b5 fix: restore workspace unsafe_code=forbid, fix TaskClaim TOCTOU, remove TUI deps
Review fixes for PR #3250:

1. Restore workspace-level unsafe_code = "forbid" (was downgraded to
   "warn" for TUI support). The per-crate [lints.rust] unsafe_code =
   "allow" on rusty-claude-cli already overrides it where needed.

2. Fix TaskClaim TOCTOU race in claim_task(). Replace exists()-then-write
   with OpenOptions::create_new(true) which atomically fails if the lock
   file already exists, eliminating the race window between the check and
   the write.

3. Remove TUI scaffolding deps (ratatui, tui-textarea, gag, crossbeam-channel,
   libc, unicode-width) and the /tui slash command spec — these belong in
   a future TUI PR and are unused in the current source.

Also updates the provider chain precedence test to reflect the new behavior
where the caller's resolved model is the chain primary.

Co-Authored-By: Claw <noreply@openclaw.ai>
2026-10-13 00:12:35 +00:00
TheArchitectit fe71ead55f test: add subagentModel accessor chain tests
Adds 3 unit tests covering the original silent-drop bug:
- camelCase 'subagentModel' key reads end-to-end
- snake_case 'subagent_model' key reads end-to-end
- blank value returns None (falls back to default model)

Requested by @1716775457damn in PR review.
2026-10-13 00:12:35 +00:00
TheArchitectit 334768249f fix: model_token_limit catch-all returns None for unknown models
Restores the fix from @Offwhite-Del that was lost during rebase.
Unknown models now return None so preflight skips the context-window
check and lets the API enforce its own limits.
2026-10-13 00:12:35 +00:00
TheArchitectit aab02464b2 cargo fmt 2026-10-13 00:12:35 +00:00
TheArchitectitandClaude Fable 5 7aa00a2798 feat(team): team enhancements, subagentModel, parallel tool exec
Port the agent-team enhancement layer onto upstream/main so the model
can spin up coordinated sub-agent teams for parallel work.

subagentModel config wiring (fix):
- Add subagent_model field to RuntimeFeatureConfig + RuntimeConfig::subagent_model()
  accessor so the subagentModel setting (already validated by config_validate.rs)
  is now actually read and stored.
- Agent tool's resolve_agent_model falls back to subagentModel from config
  when no explicit model is passed.

Provider namespace separation:
- New 'custom-openai' provider kind with dedicated env vars
  (CLAWCUSTOMOPENAI_API_KEY / CLAWCUSTOMOPENAI_BASE_URL)
- /setup wizard saves kind: 'custom-openai' for option 5
- Bare model name normalized to 'custom/' prefix to avoid proxy 404s
- Sub-agents inherit /setup-saved provider config via inject_config_as_env_fallbacks

Parallel tool execution:
- Override execute_batch to classify read-only tools as parallel-safe
  and run them concurrently via std::thread::scope
- Results return in original model order

Team coordination layer:
- AgentMessage, TaskClaim, TeamStatus tools + shared mailbox directory
- Mode presets (tiny/1x ... mega/6x) + enriched TeamCreate/Agent descriptions
- Background team watcher
- /team slash command: on/off/status/toggle

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-10-13 00:12:35 +00:00
bellmanandOmX 76fe2e9f46 Document provider compatibility diagnostics and passthrough
Explain the provider compatibility behavior that now has executable coverage so future changes preserve routing, custom gateway slugs, diagnostics, and extra-body passthrough semantics.

Constraint: Task 2 requires docs/status evidence while leader owns Ultragoal checkpoints and .omx/ultragoal remains untouched.
Rejected: Add a new CLI status command | broader than the assigned provider compatibility documentation/status surface.
Confidence: high
Scope-risk: narrow
Directive: Keep docs aligned with provider_diagnostics_for_model, MessageRequest::extra_body, and OpenAI-compatible slash-model tests.
Tested: cargo test --manifest-path rust/Cargo.toml -p api custom_openai_gateway_preserves_slash_model_ids_and_extra_body_params; cargo test --manifest-path rust/Cargo.toml -p api provider_diagnostics_explain_openai_compatible_capabilities; cargo check --manifest-path rust/Cargo.toml -p api
Not-tested: Live provider calls requiring external credentials.
Co-authored-by: OmX <omx@local>
2026-10-13 00:12:35 +00:00
bellmanandOmX 49e796051e Keep G007 mock parity references executable
The follow-up docs gate needed the parity manifest reference string that the mock parity diff checker requires, so this records the verified map-only repair after leader integration.

Constraint: Task 11 scope allowed only PARITY.md, rust/MOCK_PARITY_HARNESS.md, and docs/g007-plugin-mcp-verification-map.md; only PARITY.md needed a change.

Rejected: Editing harness code or .omx/ultragoal | checks proved the remaining gap was docs-map text only and Ultragoal state is leader-owned.

Confidence: high

Scope-risk: narrow

Directive: Keep auto_compact_triggered parity_refs synchronized with PARITY.md when mock parity scenarios change.

Tested: cd rust && python3 scripts/run_mock_parity_diff.py; python3 scripts/validate_cc2_board.py --board .omx/cc2/board.json; rg -n auto_compact_triggered token_cost_reporting auto_compaction threshold from env G007 Plugin/MCP G007-plugin-mcp 12 scripted scenarios 21 captured PARITY.md rust/MOCK_PARITY_HARNESS.md docs/g007-plugin-mcp-verification-map.md; git diff --check

Not-tested: Full workspace suite; Task 11 was a docs/parity-map follow-up with focused executable map validation.

Co-authored-by: OmX <omx@oh-my-codex.dev>
2026-10-13 00:12:35 +00:00
bellmanandOmX d2f2b23dc4 Document G007 mock parity verification boundaries
Record the W4 verification map and parity-doc alignment so plugin/MCP lifecycle mock coverage can be audited without scraping stale harness prose.

Constraint: Task 9 owns mock integration and regression verification/docs mapping, not parser fixes or leader-owned Ultragoal state.

Rejected: Editing .omx/ultragoal or duplicating Worker-4 plugin command fallthrough fixes | leader checkpointing and parser implementation are separate lanes.

Confidence: high

Scope-risk: narrow

Directive: Keep rust/mock_parity_scenarios.json, rust/MOCK_PARITY_HARNESS.md, PARITY.md, and mock_parity_harness.rs aligned when adding scenarios.

Tested: cd rust && python3 scripts/run_mock_parity_diff.py --no-run; cd rust && ./scripts/run_mock_parity_harness.sh; cd rust && python3 scripts/run_mock_parity_diff.py; cargo test --manifest-path rust/Cargo.toml -p rusty-claude-cli build_runtime_plugin_state -- --nocapture; cargo test --manifest-path rust/Cargo.toml -p rusty-claude-cli build_runtime_runs_plugin_lifecycle_init_and_shutdown -- --nocapture; cargo test --manifest-path rust/Cargo.toml -p plugins plugin_registry_runs_initialize_and_shutdown_for_enabled_plugins -- --nocapture; cargo fmt --manifest-path rust/Cargo.toml --all -- --check; cargo check --manifest-path rust/Cargo.toml -p rusty-claude-cli -p mock-anthropic-service; git diff --check

Not-tested: Full workspace test suite; W4 scope is docs/mock verification map and focused plugin/MCP lifecycle regression evidence.

Co-authored-by: OmX <omx@oh-my-codex.dev>
2026-10-13 00:12:35 +00:00
Bellman 18c0bead90 Merge pull request #3336 from ultraworkers/lane/gjc-s32-r4
revert: duplicate /status /cost /version handlers (#3333)
2026-10-13 09:09:51 +09:00
clawdbotandTheArchitectit 9fadb16204 feat: integrate custom-openai provider namespace with separate env vars
- Add 'custom-openai' provider kind to setup_wizard.rs with distinct env namespace
- Add CustomOpenAi variant to ProviderConfigKind enum in api/client.rs
- Implement OpenAiCompatConfig::custom_openai() for custom-openai endpoint
- Update explicit_provider_kind_for_model() to handle 'custom-openai/' prefix
- Add tests for custom-openai configuration persistence across runtime boundary

Co-authored-by: TheArchitectit <thearchitectit@users.noreply.github.com>

Fixes #3248
2026-10-13 00:07:22 +00:00
Bellman 6f1819a8ee Merge pull request #3328 from ultraworkers/fix/issue-3259-comprehensive
fix(cli): comprehensive fix for issue #3259 - markdown streaming block spacing
2026-10-13 09:06:25 +09:00
clawdbot c13e71851b Revert "Merge pull request #3333 from ultraworkers/implement-slash-commands"
This reverts commit cf18dac3ee, reversing
changes made to a2eb74c00e.
2026-10-13 00:02:35 +00:00
clawdbot 3d8fd5f917 fix(cli): comprehensive fix for issue #3259 - markdown streaming block spacing
Fixes #3259: When rendering markdown in streaming mode, block-level elements
(code blocks, lists, tables, etc.) were losing trailing newlines due to
render_markdown() calling trim_end(). This caused improper spacing when chunks
were split at block boundaries.

Solution:
- Track last_output_ends_with_newline in MarkdownStreamState to detect when
  previous output ended without proper spacing
- In push(): add leading newlines before block elements if previous chunk
  didn't end with newlines
- In push(): restore trailing newlines after code block/table closings that
  were trimmed by render_markdown()
- Add ensure_newlines() helper to prepare spacing before block starts
- Add comprehensive streaming tests that verify idempotence across all
  possible chunk split positions

This ensures that streaming renders produce byte-identical output regardless
of where the input is split into chunks, which is critical for displaying
markdown as it arrives from the API while maintaining proper formatting.
2026-10-13 00:01:51 +00:00
6 changed files with 441 additions and 204 deletions
+58 -3
View File
@@ -15,13 +15,15 @@ pub enum ProviderClient {
/// Provider selected explicitly by persisted/runtime configuration.
///
/// This is intentionally separate from `ProviderKind`: DashScope speaks the
/// OpenAI-compatible wire protocol but remains a distinct configured provider.
/// This is intentionally separate from `ProviderKind`: Custom OpenAI and
/// DashScope speak the OpenAI-compatible wire protocol but remain distinct
/// configured providers.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ProviderConfigKind {
Anthropic,
Xai,
OpenAi,
CustomOpenAi,
DashScope,
}
@@ -96,9 +98,12 @@ impl ProviderClient {
Ok(Self::Xai(client))
}
ProviderConfigKind::OpenAi | ProviderConfigKind::DashScope => {
ProviderConfigKind::OpenAi
| ProviderConfigKind::CustomOpenAi
| ProviderConfigKind::DashScope => {
let compat = match config.kind {
ProviderConfigKind::OpenAi => OpenAiCompatConfig::openai(),
ProviderConfigKind::CustomOpenAi => OpenAiCompatConfig::custom_openai(),
ProviderConfigKind::DashScope => OpenAiCompatConfig::dashscope(),
_ => unreachable!("non-OpenAI provider reached compatibility path"),
};
@@ -403,6 +408,56 @@ mod tests {
}
}
#[test]
fn persisted_custom_openai_uses_its_own_environment_namespace() {
let _lock = env_lock();
let _custom_key = EnvVarGuard::set("CLAWCUSTOMOPENAI_API_KEY", Some("custom-key"));
let _custom_url = EnvVarGuard::set(
"CLAWCUSTOMOPENAI_BASE_URL",
Some("https://custom.example/v1"),
);
let _openai_key = EnvVarGuard::set("OPENAI_API_KEY", Some("openai-key"));
let _openai_url = EnvVarGuard::set("OPENAI_BASE_URL", Some("https://openai.example/v1"));
let _ollama = EnvVarGuard::set("OLLAMA_HOST", Some("http://localhost:11434"));
let config = ProviderConfig {
kind: ProviderConfigKind::CustomOpenAi,
model: "qwen-plus".to_string(),
api_key: None,
base_url: None,
};
match ProviderClient::from_config(&config).expect("custom OpenAI config should succeed") {
ProviderClient::OpenAi(client) => {
assert_eq!(client.base_url(), "https://custom.example/v1");
}
other => panic!("Expected custom OpenAI provider, got: {other:?}"),
}
}
#[test]
fn persisted_custom_openai_does_not_reuse_openai_credentials() {
let _lock = env_lock();
let _custom_key = EnvVarGuard::set("CLAWCUSTOMOPENAI_API_KEY", None);
let _custom_url = EnvVarGuard::set(
"CLAWCUSTOMOPENAI_BASE_URL",
Some("https://custom.example/v1"),
);
let _openai_key = EnvVarGuard::set("OPENAI_API_KEY", Some("openai-key"));
let _ollama = EnvVarGuard::set("OLLAMA_HOST", Some("http://localhost:11434"));
let config = ProviderConfig {
kind: ProviderConfigKind::CustomOpenAi,
model: "gpt-5".to_string(),
api_key: None,
base_url: None,
};
let error = ProviderClient::from_config(&config)
.expect_err("custom OpenAI must require its own credentials");
assert!(error.to_string().contains("CLAWCUSTOMOPENAI_API_KEY"));
}
#[test]
fn dashscope_model_uses_dashscope_config_not_openai() {
// Regression: qwen-plus was being routed to OpenAiCompatConfig::openai()
@@ -42,6 +42,7 @@ pub struct OpenAiCompatConfig {
const XAI_ENV_VARS: &[&str] = &["XAI_API_KEY"];
const OPENAI_ENV_VARS: &[&str] = &["OPENAI_API_KEY"];
const CUSTOM_OPENAI_ENV_VARS: &[&str] = &["CLAWCUSTOMOPENAI_API_KEY"];
const DASHSCOPE_ENV_VARS: &[&str] = &["DASHSCOPE_API_KEY"];
// Provider-specific request body size limits in bytes
@@ -80,6 +81,18 @@ impl OpenAiCompatConfig {
}
}
/// OpenAI-compatible endpoint with its own environment namespace and no default URL.
#[must_use]
pub const fn custom_openai() -> Self {
Self {
provider_name: "Custom OpenAI",
api_key_env: "CLAWCUSTOMOPENAI_API_KEY",
base_url_env: "CLAWCUSTOMOPENAI_BASE_URL",
default_base_url: "",
max_request_body_bytes: OPENAI_MAX_REQUEST_BODY_BYTES,
}
}
/// Alibaba `DashScope` compatible-mode endpoint (Qwen family models).
/// Uses the OpenAI-compatible REST shape at /compatible-mode/v1.
/// Requested via Discord #clawcode-get-help: native Alibaba API for
@@ -100,6 +113,7 @@ impl OpenAiCompatConfig {
match self.provider_name {
"xAI" => XAI_ENV_VARS,
"OpenAI" => OPENAI_ENV_VARS,
"Custom OpenAI" => CUSTOM_OPENAI_ENV_VARS,
"DashScope" => DASHSCOPE_ENV_VARS,
_ => &[],
}
+7 -142
View File
@@ -5297,60 +5297,6 @@ fn mcp_server_json(name: &str, server: &ScopedMcpServerConfig) -> Value {
})
}
fn render_session_status(session: &Session) -> String {
let message_count = session.messages.len();
let mut total_input = 0u32;
let mut total_output = 0u32;
for msg in &session.messages {
if let Some(usage) = msg.usage {
total_input = total_input.saturating_add(usage.input_tokens);
total_output = total_output.saturating_add(usage.output_tokens);
}
}
format!(
"Session {}: {} messages, {} input tokens, {} output tokens",
&session.session_id[0..8],
message_count,
total_input,
total_output
)
}
fn render_token_cost(session: &Session) -> String {
let mut total_input = 0u32;
let mut total_output = 0u32;
let mut cache_creation = 0u32;
let mut cache_read = 0u32;
for msg in &session.messages {
if let Some(usage) = msg.usage {
total_input = total_input.saturating_add(usage.input_tokens);
total_output = total_output.saturating_add(usage.output_tokens);
cache_creation = cache_creation.saturating_add(usage.cache_creation_input_tokens);
cache_read = cache_read.saturating_add(usage.cache_read_input_tokens);
}
}
format!(
"Cumulative token usage for this session:
Input tokens: {}
Output tokens: {}
Cache creation tokens: {}
Cache read tokens: {}
Total input: {}",
total_input,
total_output,
cache_creation,
cache_read,
total_input
.saturating_add(cache_creation)
.saturating_add(cache_read)
)
}
fn render_version_info() -> String {
let version = env!("CARGO_PKG_VERSION");
format!("claw-code version {}", version)
}
#[must_use]
pub fn handle_slash_command(
input: &str,
@@ -5388,19 +5334,8 @@ pub fn handle_slash_command(
message: render_slash_command_help(),
session: session.clone(),
}),
SlashCommand::Status => Some(SlashCommandResult {
message: render_session_status(session),
session: session.clone(),
}),
SlashCommand::Cost => Some(SlashCommandResult {
message: render_token_cost(session),
session: session.clone(),
}),
SlashCommand::Version => Some(SlashCommandResult {
message: render_version_info(),
session: session.clone(),
}),
SlashCommand::Bughunter { .. }
SlashCommand::Status
| SlashCommand::Bughunter { .. }
| SlashCommand::Commit
| SlashCommand::Pr { .. }
| SlashCommand::Issue { .. }
@@ -5411,6 +5346,7 @@ pub fn handle_slash_command(
| SlashCommand::Model { .. }
| SlashCommand::Permissions { .. }
| SlashCommand::Clear { .. }
| SlashCommand::Cost
| SlashCommand::Resume { .. }
| SlashCommand::Config { .. }
| SlashCommand::Workspace { .. }
@@ -5418,6 +5354,7 @@ pub fn handle_slash_command(
| SlashCommand::Memory
| SlashCommand::Init
| SlashCommand::Diff
| SlashCommand::Version
| SlashCommand::Export { .. }
| SlashCommand::Session { .. }
| SlashCommand::Plugins { .. }
@@ -6256,6 +6193,7 @@ mod tests {
fn ignores_unknown_or_runtime_bound_slash_commands() {
let session = Session::new();
assert!(handle_slash_command("/unknown", &session, CompactionConfig::default()).is_none());
assert!(handle_slash_command("/status", &session, CompactionConfig::default()).is_none());
assert!(handle_slash_command("/sandbox", &session, CompactionConfig::default()).is_none());
assert!(
handle_slash_command("/bughunter", &session, CompactionConfig::default()).is_none()
@@ -6287,6 +6225,7 @@ mod tests {
handle_slash_command("/clear --confirm", &session, CompactionConfig::default())
.is_none()
);
assert!(handle_slash_command("/cost", &session, CompactionConfig::default()).is_none());
assert!(handle_slash_command(
"/resume session.json",
&session,
@@ -6305,6 +6244,7 @@ mod tests {
);
assert!(handle_slash_command("/mcp list", &session, CompactionConfig::default()).is_none());
assert!(handle_slash_command("/diff", &session, CompactionConfig::default()).is_none());
assert!(handle_slash_command("/version", &session, CompactionConfig::default()).is_none());
assert!(
handle_slash_command("/export note.txt", &session, CompactionConfig::default())
.is_none()
@@ -7266,79 +7206,4 @@ mod tests {
let _ = fs::remove_dir_all(config_home);
let _ = fs::remove_dir_all(bundled_root);
}
#[test]
fn status_command_shows_session_info() {
use runtime::TokenUsage;
let mut session = Session::new();
session.messages.push(ConversationMessage {
role: MessageRole::User,
blocks: vec![ContentBlock::Text {
text: "hello".to_string(),
}],
usage: Some(TokenUsage {
input_tokens: 10,
output_tokens: 20,
cache_creation_input_tokens: 0,
cache_read_input_tokens: 0,
}),
});
session.messages.push(ConversationMessage {
role: MessageRole::Assistant,
blocks: vec![ContentBlock::Text {
text: "response".to_string(),
}],
usage: Some(TokenUsage {
input_tokens: 5,
output_tokens: 15,
cache_creation_input_tokens: 0,
cache_read_input_tokens: 0,
}),
});
let result = handle_slash_command("/status", &session, CompactionConfig::default())
.expect("/status should be handled");
assert!(result.message.contains("2 messages"));
assert!(result.message.contains("15 input tokens"));
assert!(result.message.contains("35 output tokens"));
assert_eq!(result.session, session);
}
#[test]
fn cost_command_shows_token_usage() {
use runtime::TokenUsage;
let mut session = Session::new();
session.messages.push(ConversationMessage {
role: MessageRole::User,
blocks: vec![ContentBlock::Text {
text: "hello".to_string(),
}],
usage: Some(TokenUsage {
input_tokens: 100,
output_tokens: 200,
cache_creation_input_tokens: 50,
cache_read_input_tokens: 25,
}),
});
let result = handle_slash_command("/cost", &session, CompactionConfig::default())
.expect("/cost should be handled");
assert!(result.message.contains("100"));
assert!(result.message.contains("200"));
assert!(result.message.contains("50"));
assert!(result.message.contains("25"));
assert!(result.message.contains("Cumulative token usage"));
assert_eq!(result.session, session);
}
#[test]
fn version_command_shows_version() {
let session = Session::new();
let result = handle_slash_command("/version", &session, CompactionConfig::default())
.expect("/version should be handled");
assert!(result.message.contains("claw-code version"));
assert_eq!(result.session, session);
}
}
+56
View File
@@ -12910,6 +12910,7 @@ fn provider_config_from_runtime(
"anthropic" => api::ProviderConfigKind::Anthropic,
"xai" => api::ProviderConfigKind::Xai,
"openai" => api::ProviderConfigKind::OpenAi,
"custom-openai" => api::ProviderConfigKind::CustomOpenAi,
"dashscope" => api::ProviderConfigKind::DashScope,
other => {
return Err(format!(
@@ -12947,6 +12948,7 @@ fn explicit_provider_kind_for_model(
Some("anthropic") => Some(api::ProviderConfigKind::Anthropic),
Some("xai") => Some(api::ProviderConfigKind::Xai),
Some("openai") | Some("local") => Some(api::ProviderConfigKind::OpenAi),
Some("custom-openai") => Some(api::ProviderConfigKind::CustomOpenAi),
Some("dashscope") | Some("qwen") | Some("kimi") => Some(api::ProviderConfigKind::DashScope),
_ => {
let lower = resolved_model.to_ascii_lowercase();
@@ -19664,6 +19666,22 @@ UU conflicted.rs",
super::explicit_provider_kind_for_model("openai/gpt-5", &config.model),
Some(api::ProviderConfigKind::OpenAi)
);
assert_eq!(
super::explicit_provider_kind_for_model("custom-openai/local-model", &config.model),
Some(api::ProviderConfigKind::CustomOpenAi)
);
assert_eq!(
super::explicit_provider_kind_for_model("CUSTOM-OPENAI/local-model", &config.model),
Some(api::ProviderConfigKind::CustomOpenAi)
);
assert_eq!(
super::explicit_provider_kind_for_model(
"custom-openai/local-model",
"custom-openai/local-model"
),
None,
"matching custom model must keep the persisted provider kind"
);
assert_eq!(
super::explicit_provider_kind_for_model("qwen-plus", &config.model),
None,
@@ -19704,6 +19722,44 @@ UU conflicted.rs",
}
}
#[test]
fn persisted_custom_openai_configuration_survives_runtime_boundary() {
let config_home = temp_dir();
let workspace = temp_dir();
fs::create_dir_all(&config_home).expect("config home");
fs::create_dir_all(&workspace).expect("workspace");
fs::write(
config_home.join("settings.json"),
r#"{
"provider": {
"kind": "custom-openai",
"apiKey": "custom-test-key",
"baseUrl": "https://custom.example/v1",
"model": "local-model"
},
"model": "local-model"
}"#,
)
.expect("write provider settings");
let loader = ConfigLoader::new(&workspace, &config_home);
let runtime_config = loader.load().expect("runtime config should load");
let provider_config = super::provider_config_from_runtime(runtime_config.provider())
.expect("custom provider configuration should adapt")
.expect("persisted provider configuration should be present");
assert_eq!(provider_config.kind, api::ProviderConfigKind::CustomOpenAi);
assert_eq!(provider_config.model, "local-model");
assert_eq!(provider_config.api_key.as_deref(), Some("custom-test-key"));
assert_eq!(
provider_config.base_url.as_deref(),
Some("https://custom.example/v1")
);
let _ = fs::remove_dir_all(config_home);
let _ = fs::remove_dir_all(workspace);
}
#[test]
fn persisted_provider_configuration_controls_runtime_provider_dispatch() {
let config_home = temp_dir();
+296 -57
View File
@@ -249,16 +249,6 @@ impl TerminalRenderer {
#[must_use]
pub fn render_markdown(&self, markdown: &str) -> String {
self.render_markdown_raw(markdown).trim_end().to_string()
}
/// Render markdown to ANSI without trimming trailing whitespace.
///
/// Block-level events (paragraphs, headings, lists, code blocks) emit their
/// trailing newline separators here. `render_markdown` trims them for
/// one-shot output, while streaming keeps them so that successive chunks
/// stay on their own lines instead of running together.
fn render_markdown_raw(&self, markdown: &str) -> String {
let normalized = normalize_nested_fences(markdown);
let mut output = String::new();
let mut state = RenderState::default();
@@ -277,7 +267,30 @@ impl TerminalRenderer {
);
}
output
output.trim_end().to_string()
}
/// Ensures the output ends with at least `required` newlines.
/// This is idempotent: calling it multiple times with the same output
/// will not add extra newlines beyond what is needed.
/// The function is crucial for streaming rendering where chunks may
/// split at block boundaries, causing the parser to lose newlines
/// that normally separate blocks.
fn ensure_newlines(output: &mut String, required: usize) {
if output.is_empty() {
// Don't start with blank lines
return;
}
// Count trailing newlines
let trailing_newlines = output.chars().rev().take_while(|&c| c == '\n').count();
// Add newlines if we don't have enough
if trailing_newlines < required {
for _ in 0..(required - trailing_newlines) {
output.push('\n');
}
}
}
#[must_use]
@@ -285,18 +298,6 @@ impl TerminalRenderer {
self.render_markdown(markdown)
}
/// Stream-friendly variant of `markdown_to_ansi` that preserves trailing
/// block separators (such as a paragraph's closing newlines).
///
/// `MarkdownStreamState::push` writes each rendered chunk directly to the
/// terminal with no separator of its own, so the trailing newlines must
/// survive here to keep a paragraph from sticking to the block that follows
/// it. The final `flush` still uses `markdown_to_ansi` to trim the tail.
#[must_use]
pub fn markdown_to_ansi_stream(&self, markdown: &str) -> String {
self.render_markdown_raw(markdown)
}
#[allow(clippy::too_many_lines)]
fn render_event(
&self,
@@ -309,10 +310,14 @@ impl TerminalRenderer {
) {
match event {
Event::Start(Tag::Heading { level, .. }) => {
Self::ensure_newlines(output, 1);
Self::start_heading(state, level as u8, output);
}
Event::End(TagEnd::Paragraph) => output.push_str("\n\n"),
Event::Start(Tag::BlockQuote(..)) => self.start_quote(state, output),
Event::Start(Tag::BlockQuote(..)) => {
Self::ensure_newlines(output, 1);
self.start_quote(state, output);
}
Event::End(TagEnd::BlockQuote(..)) => {
state.quote = state.quote.saturating_sub(1);
output.push('\n');
@@ -325,6 +330,7 @@ impl TerminalRenderer {
state.append_raw(output, "\n");
}
Event::Start(Tag::List(first_item)) => {
Self::ensure_newlines(output, 1);
let kind = match first_item {
Some(index) => ListKind::Ordered { next_index: index },
None => ListKind::Unordered,
@@ -337,6 +343,7 @@ impl TerminalRenderer {
}
Event::Start(Tag::Item) => Self::start_item(state, output),
Event::Start(Tag::CodeBlock(kind)) => {
Self::ensure_newlines(output, 2);
*in_code_block = true;
*code_language = match kind {
CodeBlockKind::Indented => String::from("text"),
@@ -360,7 +367,10 @@ impl TerminalRenderer {
format!("{}", format!("`{code}`").with(self.color_theme.inline_code));
state.append_raw(output, &rendered);
}
Event::Rule => output.push_str("---\n"),
Event::Rule => {
Self::ensure_newlines(output, 1);
output.push_str("---\n");
}
Event::Text(text) => {
self.push_text(text.as_ref(), state, output, code_buffer, *in_code_block);
}
@@ -405,7 +415,10 @@ impl TerminalRenderer {
);
state.append_raw(output, &rendered);
}
Event::Start(Tag::Table(..)) => state.table = Some(TableState::default()),
Event::Start(Tag::Table(..)) => {
Self::ensure_newlines(output, 1);
state.table = Some(TableState::default());
}
Event::End(TagEnd::Table) => {
if let Some(table) = state.table.take() {
output.push_str(&self.render_table(&table));
@@ -619,9 +632,21 @@ impl TerminalRenderer {
}
}
#[derive(Debug, Default, Clone, PartialEq, Eq)]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MarkdownStreamState {
pending: String,
/// Track whether the last emitted output ended with a newline.
/// Used to ensure proper spacing when resuming from a buffer.
last_output_ends_with_newline: bool,
}
impl Default for MarkdownStreamState {
fn default() -> Self {
Self {
pending: String::new(),
last_output_ends_with_newline: false,
}
}
}
impl MarkdownStreamState {
@@ -631,7 +656,40 @@ impl MarkdownStreamState {
let split = find_stream_safe_boundary(&self.pending)?;
let ready = self.pending[..split].to_string();
self.pending.drain(..split);
Some(renderer.markdown_to_ansi_stream(&ready))
let mut rendered = renderer.markdown_to_ansi(&ready);
let stripped = strip_ansi(&rendered);
// If the previous output didn't end with a newline and this chunk starts
// with a block-level element, ensure proper spacing before it.
if !self.last_output_ends_with_newline && !rendered.is_empty() {
if stripped.starts_with("\u{256d}\u{2500}")
|| stripped.starts_with("```")
|| stripped.starts_with("|")
|| stripped.starts_with("• ")
|| stripped.starts_with("1. ")
|| stripped.starts_with("-")
{
rendered = format!("\n\n{}", rendered);
}
}
// When markdown ends with a code block closing marker or other block-level element,
// render_markdown() trims the trailing newlines that finish_code_block() added.
// For streaming, we need to restore these newlines so proper spacing is preserved
// when chunks are combined. This is critical for idempotence across re-renders.
if stripped.ends_with("\u{2570}\u{2500}")
|| stripped.ends_with("---")
|| stripped.ends_with("|")
{
// Block element that should have trailing spacing
if !rendered.ends_with('\n') {
rendered.push_str("\n\n");
}
}
self.last_output_ends_with_newline = rendered.ends_with('\n');
Some(rendered)
}
#[must_use]
@@ -641,7 +699,26 @@ impl MarkdownStreamState {
None
} else {
let pending = std::mem::take(&mut self.pending);
Some(renderer.markdown_to_ansi(&pending))
let mut rendered = renderer.markdown_to_ansi(&pending);
// If the previous output didn't end with a newline and this output
// starts with a block-level element, ensure proper spacing.
if !self.last_output_ends_with_newline && !rendered.is_empty() {
// Check if output starts with a block element by looking for common markers
let stripped = strip_ansi(&rendered);
if stripped.starts_with("\u{256d}\u{2500}")
|| stripped.starts_with("```")
|| stripped.starts_with("|")
|| stripped.starts_with("• ")
|| stripped.starts_with("1. ")
|| stripped.starts_with("-")
{
rendered = format!("\n\n{}", rendered);
}
}
self.last_output_ends_with_newline = rendered.ends_with('\n');
Some(rendered)
}
}
}
@@ -835,6 +912,11 @@ fn normalize_nested_fences(markdown: &str) -> String {
out
}
/// Find a safe boundary for streaming markdown rendering.
/// Safe boundaries are:
/// - After a closing fence line (when fence is closed)
/// - After an empty line
/// This function returns the position of the last safe boundary found.
fn find_stream_safe_boundary(markdown: &str) -> Option<usize> {
let mut open_fence: Option<FenceMarker> = None;
let mut last_boundary = None;
@@ -1074,34 +1156,6 @@ mod tests {
assert!(plain_text.contains("fn nested()"));
}
#[test]
fn stream_rendering_preserves_block_separators() {
let renderer = TerminalRenderer::new();
// The stream variant keeps the paragraph-ending newlines that the
// one-shot variant trims, so consecutive streamed chunks do not run
// into each other when written back-to-back to the terminal.
let streamed = renderer.markdown_to_ansi_stream("Intro paragraph.\n\n");
assert!(streamed.ends_with('\n'));
assert!(!renderer
.markdown_to_ansi("Intro paragraph.\n\n")
.ends_with('\n'));
let mut state = MarkdownStreamState::default();
let first = state
.push(&renderer, "Intro paragraph.\n\n")
.expect("blank line closes the paragraph block");
let second = state
.push(&renderer, "1. first item\n\n")
.expect("blank line closes the list block");
let combined = strip_ansi(&format!("{first}{second}"));
assert!(combined.contains("Intro paragraph."));
assert!(combined.contains("1. first item"));
// The two blocks stay on separate lines instead of sticking together.
assert!(!combined.contains("Intro paragraph.1."));
}
#[test]
fn spinner_advances_frames() {
let terminal_renderer = TerminalRenderer::new();
@@ -1117,4 +1171,189 @@ mod tests {
let output = String::from_utf8_lossy(&out);
assert!(output.contains("Working"));
}
#[test]
fn streaming_text_before_code_block_preserves_newline_boundary() {
let renderer = TerminalRenderer::new();
let mut state = MarkdownStreamState::default();
// Simulate streaming: paragraph text arrives in one chunk
assert_eq!(
state.push(&renderer, "This is some text."),
None,
"incomplete paragraph should not flush"
);
// Then code block arrives in the next chunk
let rendered = state
.push(&renderer, "\n\n```rust\nfn main() {}\n```\n")
.expect("fenced block should trigger flush");
let plain_text = strip_ansi(&rendered);
// Verify the paragraph text and code block are present
assert!(plain_text.contains("This is some text."));
assert!(plain_text.contains("fn main()"));
// The critical check: there should be a blank line between the paragraph and code block
// The paragraph ends, then there should be newlines before the code block marker
let lines: Vec<&str> = plain_text.lines().collect();
let text_line_idx = lines
.iter()
.position(|line| line.contains("This is some text."))
.expect("find text line");
// Skip past the text line and find the code block
let code_marker_idx = lines[text_line_idx + 1..]
.iter()
.position(|line| line.contains("╭─ rust"))
.map(|i| i + text_line_idx + 1);
// There should be at least one empty line between the text and the code block marker
if let Some(code_idx) = code_marker_idx {
assert!(
code_idx > text_line_idx + 1,
"there should be spacing between paragraph and code block"
);
}
}
#[test]
fn rendering_paragraph_immediately_before_code_block_has_blank_line() {
let renderer = TerminalRenderer::new();
let markdown = "This is a paragraph.\n\n```rust\nfn main() {}\n```";
let output = renderer.markdown_to_ansi(markdown);
let plain_text = strip_ansi(&output);
let lines: Vec<&str> = plain_text.lines().collect();
// Find the paragraph and code block
let text_idx = lines
.iter()
.position(|l| l.contains("This is a paragraph."))
.expect("find paragraph");
let code_idx = lines[text_idx + 1..]
.iter()
.position(|l| l.contains("╭─ rust"))
.map(|i| i + text_idx + 1)
.expect("find code block");
// There should be at least one blank line between them
assert!(
code_idx > text_idx + 1,
"code block should not immediately follow paragraph"
);
}
#[test]
fn code_block_ending_with_trailing_text_preserves_spacing() {
let renderer = TerminalRenderer::new();
let markdown = "```rust\nfn main() {}\n```\n\nText after.";
let output = renderer.markdown_to_ansi(markdown);
let plain_text = strip_ansi(&output);
// The code block should end with "╰─" followed by blank lines, then text
assert!(
plain_text.contains("\u{256d}\u{2500}"),
"should contain code block close marker"
);
assert!(
plain_text.contains("\n\nText"),
"should have blank line before text"
);
}
#[test]
fn streaming_code_block_preserves_trailing_newlines() {
let renderer = TerminalRenderer::new();
let mut state = MarkdownStreamState::default();
let markdown = "Text before.\n\n```rust\nfn test() {}\n```\n\nText after.";
// Debug: let's check what the code block part alone renders to
let code_part = "```rust\nfn test() {}\n```\n\nText after.";
let code_rendered = strip_ansi(&renderer.markdown_to_ansi(code_part));
// Simulate the streaming at split position 1
let r1 = state.push(&renderer, "T").map(|s| strip_ansi(&s));
let r2 = state
.push(
&renderer,
"ext before.\n\n```rust\nfn test() {}\n```\n\nText after.",
)
.map(|s| strip_ansi(&s));
// After r2, the pending should contain the code block part
let pending_before_r3 = state.pending.clone();
let r3 = state.flush(&renderer).map(|s| strip_ansi(&s));
// Combine the results
let mut full_streamed = String::new();
if let Some(s) = &r1 {
full_streamed.push_str(s);
}
if let Some(s) = &r2 {
full_streamed.push_str(s);
}
if let Some(s) = &r3 {
full_streamed.push_str(s);
}
let full_rendered = strip_ansi(&renderer.markdown_to_ansi(markdown));
assert_eq!(full_streamed, full_rendered,
"Streaming mismatch.\n\nCode part alone renders to: {:?}\nPending before r3: {:?}\n\nBreakdown:\n r1: {:?}\n r2: {:?}\n r3: {:?}\n\nExpected:\n{:?}\n\nGot:\n{:?}",
code_rendered, pending_before_r3, r1, r2, r3, full_rendered, full_streamed);
}
#[test]
fn streaming_with_split_at_every_byte_position_produces_consistent_output() {
let renderer = TerminalRenderer::new();
let markdown = "Text before.\n\n```rust\nfn test() {}\n```\n\nText after.";
// First, render the full document
let full_output = renderer.markdown_to_ansi(markdown);
let full_plain = strip_ansi(&full_output);
// Now simulate streaming by splitting at different positions
for split_pos in 1..markdown.len() {
let mut state = MarkdownStreamState::default();
let part1 = &markdown[..split_pos];
let part2 = &markdown[split_pos..];
// Try to push both parts
let r1 = state.push(&renderer, part1);
let r2 = state.push(&renderer, part2);
let final_r = state.flush(&renderer);
// Reconstruct the streamed output
let mut streamed_output = String::new();
if let Some(out) = r1 {
streamed_output.push_str(&out);
}
if let Some(out) = r2 {
streamed_output.push_str(&out);
}
if let Some(out) = final_r {
streamed_output.push_str(&out);
}
let streamed_plain = strip_ansi(&streamed_output);
if streamed_plain != full_plain {
eprintln!("\n=== MISMATCH at split position {} ===", split_pos);
eprintln!("Part 1: {:?}", part1);
eprintln!("Part 2: {:?}", part2);
eprintln!("\nExpected (full):");
eprintln!("{:?}", full_plain);
eprintln!("\nGot (streamed):");
eprintln!("{:?}", streamed_plain);
eprintln!("\nStreamed rendered output:");
eprintln!("{:?}", streamed_output);
}
assert_eq!(
streamed_plain, full_plain,
"streaming with split at position {} produces different output",
split_pos
);
}
}
}
@@ -9,7 +9,7 @@ const PROVIDERS: &[(&str, &str, &str)] = &[
("2", "xAI / Grok", "xai"),
("3", "OpenAI", "openai"),
("4", "DashScope (Qwen/Kimi)", "dashscope"),
("5", "Custom (OpenAI-compat)", "openai"),
("5", "Custom (OpenAI-compat)", "custom-openai"),
];
const PROVIDER_MODELS: &[(&str, &[&str])] = &[
@@ -27,6 +27,8 @@ const DEFAULT_BASE_URLS: &[(&str, &str)] = &[
"dashscope",
"https://dashscope.aliyuncs.com/compatible-mode/v1",
),
// Custom OpenAI has no default; user must supply.
("custom-openai", ""),
];
const API_KEY_ENV_VARS: &[(&str, &str)] = &[
@@ -34,6 +36,7 @@ const API_KEY_ENV_VARS: &[(&str, &str)] = &[
("xai", "XAI_API_KEY"),
("openai", "OPENAI_API_KEY"),
("dashscope", "DASHSCOPE_API_KEY"),
("custom-openai", "CLAWCUSTOMOPENAI_API_KEY"),
];
pub fn run_setup_wizard() -> Result<(), Box<dyn std::error::Error>> {
@@ -177,6 +180,7 @@ fn prompt_base_url(
"xai" => "XAI_BASE_URL",
"openai" => "OPENAI_BASE_URL",
"dashscope" => "DASHSCOPE_BASE_URL",
"custom-openai" => "CLAWCUSTOMOPENAI_BASE_URL",
_ => "BASE_URL",
};
let env_set = std::env::var(env_var).ok().is_some_and(|v| !v.is_empty());
@@ -214,7 +218,11 @@ fn prompt_model(
if !aliases.is_empty() {
println!(" Common: {}", aliases.join(", "));
}
println!(" Or enter any model name (e.g. openai/gpt-4.1-mini for custom routing)");
if kind == "custom-openai" {
println!(" Or enter any model name (e.g. custom/gpt-4.1 for custom routing)");
} else {
println!(" Or enter any model name (e.g. openai/gpt-4.1-mini for custom routing)");
}
let input = read_line(&format!(" Model [{current_model}]: "))?;
if input.trim().is_empty() {