diff --git a/AGENTS.md b/AGENTS.md index 09aa0f2..0e15d92 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -202,6 +202,11 @@ are chosen per session in a box in the right-hand panel's footer, reachable from the collapsed rail; a provider change needs the native confirmation, and each turn re-checks the session's recorded endpoint (ADR-0071, [ADR-0089](docs/adr/0089-choose-the-provider-and-model-in-the-side-panel-footer.md)). +An **Effort** dropdown in the same box records a per-session reasoning effort, +which the CLI sets with `chat --reasoning-effort`; it is sent only to endpoints +whose provider documents the field, nothing is sent by default, and no +request with an effort was made to a real provider +([ADR-0102](docs/adr/0102-choose-a-reasoning-effort-per-session.md)). A status bar at the bottom of the `main` window shows the open session's workspace and Git branch, read from `HEAD` without a Git process, and the approvals count; it offers no connection choice diff --git a/CHANGELOG.md b/CHANGELOG.md index 2853785..8afa469 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,35 @@ Changes are recorded here before a release version is assigned. ### Added +- Version 0.67.0 adds a per-session reasoning effort (ADR-0102). The desktop + model box has an **Effort** dropdown under **Model** with "Default", which + sends nothing, and None, Minimal, Low, Medium, High, Extra high, and Max. It + is recorded per session by the new `main` command `session_effort_select`, + without a dialog but as one settings change (`settings_change_running` + while another runs), as an optional `reasoning_effort` in + `session-connections.json` (still version 1); a provider choice clears it + and a model choice keeps it. The desktop shell has 63 commands: 31 in + `main`, 3 in `approvals`, and 29 in `settings`. `connection_status` + reports the session's effort and `reasoning_efforts`, the values its + connection takes, and + `chat_send` takes `reasoning_effort` in its settings. The CLI adds + `chat --reasoning-effort`. Chat Completions requests carry it as + `reasoning_effort`, and the ChatGPT plan route as + `"reasoning": {"effort": ...}`; the field's bytes count in the client's + checks, the pre-turn compaction trigger, and the **Context** tab's framing + part, and compaction summary requests send none. Core allows it only for + loopback endpoints, a typed `openai_compatible` address, and the fixed + Ollama Cloud, OpenAI, Google, Moonshot, MiniMax, OpenRouter, Z.ai, and xAI + endpoints; Anthropic, DeepSeek, Tencent, Meta, and Thinking Machines Lab + refuse it before any request, and the dropdown is disabled there with a + note. The endpoint decides, not the profile kind, so a typed address that + is exactly one of those refusing endpoints refuses it too. A version-3 + `request.manifest` records the effort that was sent as an optional + `reasoning_effort`; 0.66.0 and earlier refuse a journal that has + it, and a version 1 or 2 session refuses an effort before anything is + recorded. Values are not adjusted per model, so a model that refuses one + answers with its provider's HTTP error. No request with an effort was made + to a real provider. - Version 0.66.0 makes every section divider in the desktop windows movable (ADR-0101). The `approvals` queue, 300 pixels wide, now widens or narrows from 200 to 640 beside the review pane, and below 720 pixels wide, where @@ -285,6 +314,12 @@ Changes are recorded here before a release version is assigned. ### Fixed +- The CLI test `a_filtered_listing_is_truncated_when_newer_calls_fill_the_search_window` + no longer fails now and then on Linux with `action journal: Busy`. It + dropped the seeded action journal's writer and opened it again, and a + sibling test's CLI child, between fork and exec, could still share the + descriptor and its `flock`. The test now appends with the seeding writer. + Tests only; no application code changed. - Version 0.61.0 opens the ChatGPT sign-in page in the default browser on Windows (ADR-0094). Sign-in ran `explorer.exe` with the authorization address, which opened a File Explorer window instead of a browser. A new diff --git a/Cargo.lock b/Cargo.lock index 91914c3..a8e0f8d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3622,7 +3622,7 @@ dependencies = [ [[package]] name = "omgcode-app" -version = "0.66.0" +version = "0.67.0" dependencies = [ "directories", "omgcode-core", @@ -3638,7 +3638,7 @@ dependencies = [ [[package]] name = "omgcode-cli" -version = "0.66.0" +version = "0.67.0" dependencies = [ "clap", "omgcode-app", @@ -3651,7 +3651,7 @@ dependencies = [ [[package]] name = "omgcode-core" -version = "0.66.0" +version = "0.67.0" dependencies = [ "base64 0.23.1", "bytes", @@ -3675,7 +3675,7 @@ dependencies = [ [[package]] name = "omgcode-desktop" -version = "0.66.0" +version = "0.67.0" dependencies = [ "omgcode-app", "rfd", @@ -3688,7 +3688,7 @@ dependencies = [ [[package]] name = "omgcode-platform" -version = "0.66.0" +version = "0.67.0" dependencies = [ "libc", "rustix", diff --git a/Cargo.toml b/Cargo.toml index f855e4b..8a15830 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -3,7 +3,7 @@ resolver = "3" members = ["crates/omgcode-core", "crates/omgcode-cli", "crates/omgcode-platform", "crates/omgcode-app", "crates/omgcode-desktop"] [workspace.package] -version = "0.66.0" +version = "0.67.0" edition = "2024" rust-version = "1.99.1" license = "Apache-2.0" diff --git a/crates/omgcode-app/src/chat.rs b/crates/omgcode-app/src/chat.rs index 841867b..0ee6397 100644 --- a/crates/omgcode-app/src/chat.rs +++ b/crates/omgcode-app/src/chat.rs @@ -17,7 +17,7 @@ use std::path::Path; use omgcode_core::context::DEFAULT_COMPACT_THRESHOLD; use omgcode_core::prompt::{self, BASE_PROMPT, BASE_PROMPT_VERSION, SkillPrompt}; -use omgcode_core::provider::{LocalModelClient, LocalModelConfig}; +use omgcode_core::provider::{LocalModelClient, LocalModelConfig, ReasoningEffort}; use omgcode_core::session::{ManifestSkill, RequestManifest, SessionJournal}; use omgcode_core::skills::SkillName; use omgcode_core::turn::{ @@ -67,6 +67,10 @@ pub struct ChatSettings { pub compact_threshold: u64, /// Whether to compact at the effective trigger before a turn. pub auto_compact: bool, + /// The reasoning effort every chat request of the turn sends, or `None` + /// for none (ADR-0102). Compaction requests never send one. A connection + /// that takes no effort refuses a turn that names one before any request. + pub reasoning_effort: Option, } impl ChatSettings { @@ -82,6 +86,7 @@ impl ChatSettings { instructions: String::new(), compact_threshold: DEFAULT_COMPACT_THRESHOLD, auto_compact: false, + reasoning_effort: None, } } } @@ -193,9 +198,12 @@ pub struct ChatClients { impl ChatClients { /// Validate `settings` and build the chat client and the summary client. /// + /// Only the chat client sends the settings' reasoning effort; the summary + /// client sends none (ADR-0102). + /// /// Returns `configuration` for an out-of-range turn budget and - /// `provider` for an unusable endpoint, model budget, or token. No network - /// request is made. + /// `provider` for an unusable endpoint, model budget, or token, or for an + /// effort the endpoint does not take. No network request is made. pub fn new(settings: &ChatSettings, token: Option<&str>) -> Result { validate_turn_budgets(settings.max_tool_calls, settings.turn_timeout_seconds) .map_err(|message| AppError::new(ErrorKind::Configuration, message))?; @@ -209,6 +217,7 @@ impl ChatClients { // The client owns its header; the caller keeps one copy for redaction. token.map(str::to_owned), ) + .and_then(|client| client.with_reasoning_effort(settings.reasoning_effort)) .map_err(AppError::provider)?; let summary = LocalModelClient::new( LocalModelConfig { @@ -240,7 +249,7 @@ impl ChatClients { }; validate_turn_budgets(settings.max_tool_calls, settings.turn_timeout_seconds) .map_err(|message| AppError::new(ErrorKind::Configuration, message))?; - let build = |max_output_tokens| { + let build = |max_output_tokens, reasoning_effort| { LocalModelClient::chatgpt( LocalModelConfig { base_url: settings.endpoint.clone(), @@ -250,11 +259,13 @@ impl ChatClients { }, plan.tokens(), ) + .and_then(|client| client.with_reasoning_effort(reasoning_effort)) .map_err(AppError::provider) }; Ok(Self { - chat: build(settings.max_output_tokens)?, - summary: build(summary_output_tokens(settings.context_tokens))?, + chat: build(settings.max_output_tokens, settings.reasoning_effort)?, + // Compaction sends no effort (ADR-0102 decision 6). + summary: build(summary_output_tokens(settings.context_tokens), None)?, }) } } @@ -340,6 +351,14 @@ pub fn run_chat_turn_with_clients( tools::ACTIVE_TURN_MESSAGE, )); } + // An older journal cannot record an effort in its manifest (ADR-0102), so + // a turn that would send one is refused before anything is recorded. + if clients.chat.reasoning_effort().is_some() && !journal.supports_reasoning_effort() { + return Err(AppError::new( + ErrorKind::Session, + "A reasoning effort can be chosen only in a version 3 session", + )); + } // The front end can cancel from here on, which covers the compaction // requests below as well as the turn's own requests. if let Some(hook) = hooks.on_cancel_token.as_deref_mut() { @@ -352,14 +371,19 @@ pub fn run_chat_turn_with_clients( turn.skills = &loaded_skills; let tools_enabled = matches!(mode, ToolMode::Enabled { .. }); let skill_extra = skills::context_bytes(&loaded_skills); - let tool_extra = skill_extra - + if tools_enabled { + // The effort field is sent with every request of the turn, so the trigger + // counts it as the client's own checks do (ADR-0102). + let fixed_extra = skill_extra + .saturating_add(if tools_enabled { TOOL_SCHEMA_ESTIMATE_BYTES } else { 0 - }; + }) + .saturating_add(preflight::effort_extra_bytes( + clients.chat.reasoning_effort(), + )); let meter = - preflight::preflight_context(journal, &turn, &clients.summary, tool_extra, tools_enabled)?; + preflight::preflight_context(journal, &turn, &clients.summary, fixed_extra, tools_enabled)?; // Compaction requests can take long; a selection withdrawn meanwhile // stops the turn before its first request. skills::recheck(data_root, journal, &loaded_skills)?; @@ -382,6 +406,8 @@ pub fn run_chat_turn_with_clients( skill_md_sha256: skill.skill_md_sha256.clone(), }) .collect(), + // What the chat client sends, not what was asked for. + reasoning_effort: clients.chat.reasoning_effort(), }; // Live settings decide whether this turn offers the workspace tools. match mode { diff --git a/crates/omgcode-app/src/chat/preflight.rs b/crates/omgcode-app/src/chat/preflight.rs index 361ac2f..d70d9ce 100644 --- a/crates/omgcode-app/src/chat/preflight.rs +++ b/crates/omgcode-app/src/chat/preflight.rs @@ -6,7 +6,7 @@ use omgcode_core::context::{ ContextBudget, MESSAGE_OVERHEAD, estimate_history_input_tokens, estimate_history_parts, }; use omgcode_core::prompt::{self, BASE_PROMPT, ConversationMessage, ConversationRole, PromptError}; -use omgcode_core::provider::LocalModelClient; +use omgcode_core::provider::{LocalModelClient, ReasoningEffort, effort_field_bytes}; use omgcode_core::session::SessionJournal; use omgcode_core::turn::replay_active; @@ -142,8 +142,9 @@ pub(crate) fn active_history( /// Every field is in estimated tokens and the fields add up to the estimate /// that [`preflight_context`] computes for the same state without the turn's /// new user message (`total`, from the same core arithmetic). The message -/// overhead of the system and instruction messages, and the instructions -/// label, belong to no part, so they are reported as `framing`. +/// overhead of the system and instruction messages, the instructions label, +/// and the reasoning effort field belong to no part, so they are reported as +/// `framing`. #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub(crate) struct NextTurnParts { /// The compiled base prompt and its message overhead. @@ -162,7 +163,8 @@ pub(crate) struct NextTurnParts { pub history_messages: u64, /// Their content and message overhead. pub history: u64, - /// The instructions label and the instruction message's overhead. + /// The instructions label, the instruction message's overhead, and the + /// reasoning effort field when an effort is chosen (ADR-0102). pub framing: u64, /// The estimate: the sum of the parts above. pub total: u64, @@ -173,7 +175,9 @@ pub(crate) struct NextTurnParts { /// `instructions` is the composed custom instruction text a turn would send /// and `global_bytes` the bytes of it that belong to the global part, never /// more than `instructions.len()`. `tools_enabled` is whether the turn would -/// offer the workspace tools. Skills are loaded per turn and are not counted. +/// offer the workspace tools, and `reasoning_effort` the effort the turn +/// would send, whose field counts as framing. Skills are loaded per turn and +/// are not counted. /// /// # Errors /// @@ -184,15 +188,24 @@ pub(crate) fn estimate_next_turn_parts( instructions: &str, global_bytes: usize, tools_enabled: bool, + reasoning_effort: Option, ) -> Result { let history = active_history(journal, data_root, tools_enabled); - let extra = if tools_enabled { + let tools = if tools_enabled { TOOL_SCHEMA_ESTIMATE_BYTES } else { 0 }; - let parts = estimate_history_parts(BASE_PROMPT.len(), instructions, &history, extra) - .map_err(|error| AppError::new(ErrorKind::Context, error.to_string()))?; + // Both are fixed extra bytes to core, so the total is the trigger's own + // sum; the effort is then reported under framing, not tools. + let parts = estimate_history_parts( + BASE_PROMPT.len(), + instructions, + &history, + tools.saturating_add(effort_extra_bytes(reasoning_effort)), + ) + .map_err(|error| AppError::new(ErrorKind::Context, error.to_string()))?; + let effort = effort_field_bytes(reasoning_effort); let total = parts .total() .map_err(|error| AppError::new(ErrorKind::Context, error.to_string()))?; @@ -214,18 +227,28 @@ pub(crate) fn estimate_next_turn_parts( system: parts.base_prompt.saturating_add(overhead), global_instructions: global, workspace_instructions: parts.custom_instructions - global, - tools: parts.fixed_extra, + tools: parts.fixed_extra.saturating_sub(effort), summary: has_summary.then(|| summary_bytes.saturating_add(overhead)), history_messages: kept, history: parts .history_content .saturating_sub(summary_bytes) .saturating_add(kept.saturating_mul(overhead)), - framing: parts.instructions_label.saturating_add(overhead), + framing: parts + .instructions_label + .saturating_add(overhead) + .saturating_add(effort), total, }) } +/// The bytes the reasoning effort field adds to the next request, as fixed +/// extra bytes for the estimate (ADR-0102). The client counts the same figure +/// in its own checks. +pub(crate) fn effort_extra_bytes(effort: Option) -> usize { + usize::try_from(effort_field_bytes(effort)).unwrap_or(usize::MAX) +} + /// The input-only estimate and any assembly limit that compaction can relieve. fn estimate_with_user( journal: &SessionJournal, @@ -319,7 +342,12 @@ mod tests { /// The parts add up to the trigger's own estimate, once the new message /// the trigger counts is added (its content and one message overhead). - fn assert_parts_match_preflight(compacted: bool, tools_enabled: bool) { + /// The trigger's fixed extra bytes are those `run_turn` passes. + fn assert_parts_match_preflight( + compacted: bool, + tools_enabled: bool, + effort: Option, + ) -> NextTurnParts { let directory = tempfile::tempdir().expect("data root"); let journal = journal(directory.path(), compacted); let instructions = "Global instructions:\nbe brief\n\nWorkspace instructions:\nuse tabs"; @@ -335,11 +363,12 @@ mod tests { cancel: &cancel, skills: &[], }; - let extra = if tools_enabled { + let tools = if tools_enabled { TOOL_SCHEMA_ESTIMATE_BYTES } else { 0 }; + let extra = tools + effort_extra_bytes(effort); let (preflight, _) = estimate_with_user(&journal, &turn, extra, tools_enabled).expect("preflight"); @@ -350,6 +379,7 @@ mod tests { instructions, global, tools_enabled, + effort, ) .expect("parts"); @@ -371,22 +401,40 @@ mod tests { parts.global_instructions + parts.workspace_instructions, u64::try_from(instructions.len()).expect("length") ); + parts } #[test] fn the_parts_sum_to_the_preflight_estimate_without_a_compaction() { - assert_parts_match_preflight(false, false); + assert_parts_match_preflight(false, false, None); } #[test] fn the_parts_sum_to_the_preflight_estimate_with_a_compaction_summary() { - assert_parts_match_preflight(true, false); + assert_parts_match_preflight(true, false, None); } #[test] fn the_tool_definitions_are_a_part_only_when_tools_are_offered() { - assert_parts_match_preflight(false, true); - assert_parts_match_preflight(true, true); + assert_parts_match_preflight(false, true, None); + assert_parts_match_preflight(true, true, None); + } + + /// A chosen effort adds its field's fixed bytes to the trigger's estimate + /// and to the parts, under framing; the tools part is unchanged. + #[test] + fn a_chosen_effort_counts_as_framing_in_the_trigger_estimate() { + let field = effort_field_bytes(Some(ReasoningEffort::High)); + assert!(field > 0); + assert_eq!(effort_extra_bytes(None), 0); + for tools_enabled in [false, true] { + let without = assert_parts_match_preflight(false, tools_enabled, None); + let with = + assert_parts_match_preflight(false, tools_enabled, Some(ReasoningEffort::High)); + assert_eq!(with.total, without.total + field); + assert_eq!(with.framing, without.framing + field); + assert_eq!(with.tools, without.tools); + } } /// Without live tool authority a summary built over tool results is sent @@ -397,8 +445,8 @@ mod tests { fn a_withheld_summary_is_counted_as_its_notice_and_keeps_every_retained_message() { let directory = tempfile::tempdir().expect("data root"); let journal = journal_with(directory.path(), true, true); - let parts = - estimate_next_turn_parts(&journal, directory.path(), "", 0, false).expect("parts"); + let parts = estimate_next_turn_parts(&journal, directory.path(), "", 0, false, None) + .expect("parts"); let overhead = u64::try_from(MESSAGE_OVERHEAD).expect("overhead"); let notice = u64::try_from(omgcode_core::turn::WITHHELD_COMPACTION_SUMMARY.len()).expect("length"); diff --git a/crates/omgcode-app/src/desktop.rs b/crates/omgcode-app/src/desktop.rs index a655c22..4056251 100644 --- a/crates/omgcode-app/src/desktop.rs +++ b/crates/omgcode-app/src/desktop.rs @@ -153,12 +153,13 @@ pub use self::wire::{ EntryKind, GitIndexState, GitPathView, GitStatusState, GitStatusView, GitWorktreeState, MessageRoleDto, ModelChoice, NewConnectionKind, PackageProfileView, PermissionFlags, PermissionsChangeRequest, PreferencesSource, ProviderProfileView, SearchHit, SearchRequest, - SearchResult, SearchRoleDto, SessionContext, SessionCreateRequest, SessionModelSelectRequest, - SessionRequest, SessionSkills, SessionStatus, SessionSummary, SessionTree, SettingsOverview, - SettingsRevisionRequest, SettingsScope, SkillOverrideView, SkillSettingView, SnippetPart, - ToolOutcomeDto, ToolchainProfileView, ToolsMode, TranscriptEntry, TranscriptPage, - TranscriptRequest, TreeRequest, TreeSort, TreeView, WorkspaceChoice, WorkspaceGroup, - WorkspaceInstructionsRequest, WorkspaceList, WorkspaceRevisionRequest, WorkspaceSettingsView, + SearchResult, SearchRoleDto, SessionContext, SessionCreateRequest, SessionEffortSelectRequest, + SessionModelSelectRequest, SessionRequest, SessionSkills, SessionStatus, SessionSummary, + SessionTree, SettingsOverview, SettingsRevisionRequest, SettingsScope, SkillOverrideView, + SkillSettingView, SnippetPart, ToolOutcomeDto, ToolchainProfileView, ToolsMode, + TranscriptEntry, TranscriptPage, TranscriptRequest, TreeRequest, TreeSort, TreeView, + WorkspaceChoice, WorkspaceGroup, WorkspaceInstructionsRequest, WorkspaceList, + WorkspaceRevisionRequest, WorkspaceSettingsView, }; pub use self::workspace_entries::WorkspaceEntriesRequest; use crate::credential_source::resolve_connection_and_kind; @@ -166,6 +167,9 @@ use crate::{ AppError, ErrorKind, LmToken, LocalConnection, LocalEndpoint, TokenSource, resolve_local_endpoint, }; +/// The reasoning effort the wire types carry (ADR-0102), for the shell's +/// command arguments. +pub use omgcode_core::provider::ReasoningEffort; pub use omgcode_core::workspace_entries::{EntryClass, WorkspaceEntry, WorkspaceListing}; /// Fixed settings of one desktop process. diff --git a/crates/omgcode-app/src/desktop/chat.rs b/crates/omgcode-app/src/desktop/chat.rs index d46f871..40a06f1 100644 --- a/crates/omgcode-app/src/desktop/chat.rs +++ b/crates/omgcode-app/src/desktop/chat.rs @@ -14,7 +14,7 @@ use super::instructions; use super::preferences::{ self, COMPACT_THRESHOLD_MAX, COMPACT_THRESHOLD_MIN, COMPACT_THRESHOLD_STEP, }; -use super::session_connections::SessionConnection; +use super::session_connections::{SessionConnection, reasoning_efforts}; use super::turns::{MAX_RUNNING_TURNS, ShutdownReport, SlotState, TurnJob, spawn_turn}; use super::wire::{ ChatDefaults, ChatModels, ChatPreferencesSaveRequest, ChatSendRequest, ChatSettingsDto, @@ -66,6 +66,8 @@ impl DesktopService { instructions: preferences.instructions, compact_threshold: preferences.compact_threshold, auto_compact: preferences.auto_compact, + // The effort is a per-session choice, never a saved default. + reasoning_effort: None, }, tool_call_limit_max: MAX_TOOL_CALLS, turn_timeout_seconds_max: MAX_TURN_DEADLINE.as_secs(), @@ -264,6 +266,17 @@ impl DesktopService { if connection.endpoint != turn_settings.endpoint { return Err(DesktopError::connection_changed()); } + // An effort the resolved connection does not take is refused here, + // with a message, rather than as the client's configuration error + // (ADR-0102). + if turn_settings + .reasoning_effort + .is_some_and(|effort| !reasoning_efforts(&connection.endpoint).contains(&effort)) + { + return Err(DesktopError::invalid_request( + "This connection does not take a reasoning effort.", + )); + } let settings = chat_settings(turn_settings, connection.endpoint.clone()); let clients = ChatClients::for_connection(&settings, &connection) .map_err(|error| DesktopError::from_app(&error))?; @@ -433,6 +446,7 @@ fn chat_settings(settings: ChatSettingsDto, endpoint: String) -> ChatSettings { instructions: settings.instructions, compact_threshold: settings.compact_threshold, auto_compact: settings.auto_compact, + reasoning_effort: settings.reasoning_effort, } } diff --git a/crates/omgcode-app/src/desktop/context_breakdown.rs b/crates/omgcode-app/src/desktop/context_breakdown.rs index ea282ba..cb22fbd 100644 --- a/crates/omgcode-app/src/desktop/context_breakdown.rs +++ b/crates/omgcode-app/src/desktop/context_breakdown.rs @@ -3,9 +3,10 @@ //! [`DesktopService::session_context_breakdown`] serves the `main` window's //! Context tab. It resolves everything from trusted state by session id: the //! journal through the index, the saved chat budgets and global instructions, -//! the session workspace's saved instructions, and live settings for the tool -//! decision. It sends nothing to a model, records nothing in any journal, and -//! returns names and numbers only, never instruction or message text. +//! the session workspace's saved instructions, the session's recorded +//! reasoning effort, and live settings for the tool decision. It sends nothing +//! to a model, records nothing in any journal, and returns names and numbers +//! only, never instruction or message text. //! //! The arithmetic is the pre-turn trigger's own (`estimate_history_parts` in //! core, applied by the chat module), so the parts add up to the estimate the @@ -31,12 +32,13 @@ impl DesktopService { /// The parts are the base prompt, the global and the workspace custom /// instructions, the tool definitions (only when live settings would offer /// tools), the active compaction summary, the retained conversation, and - /// the fixed framing no part owns; skills are listed as not included - /// because they are chosen for one turn. The totals are those of the - /// composer's meter: the estimate, the output reserve, the effective - /// trigger, the saved capacity (`null` when none is saved), and whether - /// auto-compaction is on. They come from the saved chat budgets, the same - /// source the composer sends with a turn. + /// the fixed framing no part owns, which includes the reasoning effort + /// field when the session records an effort (ADR-0102); skills are listed + /// as not included because they are chosen for one turn. The totals are + /// those of the composer's meter: the estimate, the output reserve, the + /// effective trigger, the saved capacity (`null` when none is saved), and + /// whether auto-compaction is on. They come from the saved chat budgets, + /// the same source the composer sends with a turn. /// /// A session whose workspace is no longer registered is not an error. As in /// `chat_send`, its workspace instructions are not sent, even when a saved @@ -102,12 +104,19 @@ impl DesktopService { ToolMode::Enabled { .. } => (true, None), ToolMode::Disabled { reason } => (false, Some(reason)), }; + // The effort the composer sends with the next turn is the one the + // session records; an unreadable choices file records none. + let (records, _) = inner.session_records(); + let reasoning_effort = records + .get(&session_id) + .and_then(|record| record.reasoning_effort); let parts = estimate_next_turn_parts( &journal, &inner.data_root, &composed, global_bytes, tools_enabled, + reasoning_effort, ) .map_err(|error| DesktopError::from_app(&error))?; drop(journal); diff --git a/crates/omgcode-app/src/desktop/session_connections.rs b/crates/omgcode-app/src/desktop/session_connections.rs index 8a4f178..e6d28cf 100644 --- a/crates/omgcode-app/src/desktop/session_connections.rs +++ b/crates/omgcode-app/src/desktop/session_connections.rs @@ -1,16 +1,17 @@ //! The connection and model chosen for each session (ADR-0071). //! //! The file is `/desktop-v1/session-connections.json`. It maps a -//! session identifier to the provider the operator chose for that session and -//! the model chosen for it. It holds no secret, no credential, and no -//! permission: a profile name, the endpoint the operator confirmed, and a -//! model name. +//! session identifier to the provider the operator chose for that session, the +//! model chosen for it, and the reasoning effort chosen for it (ADR-0102). It +//! holds no secret, no credential, and no permission: a profile name, the +//! endpoint the operator confirmed, a model name, and an effort name. //! //! # Trust //! //! Only this process writes the file, and only after a native confirmation of -//! the provider (`connection_select`) or for a model name that grants nothing -//! (`session_model_select`). The file is **not tamper-evident**: a process +//! the provider (`connection_select`) or for a model name or effort that +//! grants nothing (`session_model_select`, `session_effort_select`). The file +//! is **not tamper-evident**: a process //! running as the same user can edit it, as it can edit the settings journal. //! The edit cannot widen what a turn reaches, because every turn resolves the //! session's profile through core again and refuses the turn with @@ -46,7 +47,7 @@ use std::sync::atomic::{AtomicU64, Ordering}; use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; use omgcode_core::control::{ControlStore, ProviderKind}; -use omgcode_core::provider::ModelEndpoint; +use omgcode_core::provider::{ModelEndpoint, ReasoningEffort}; use serde::{Deserialize, Serialize}; use uuid::Uuid; @@ -103,6 +104,22 @@ pub(super) struct SessionRecord { pub(super) connection: ChosenConnection, /// The model; empty when none is chosen. pub(super) model: String, + /// The reasoning effort; `None` sends none (ADR-0102). Omitted from the + /// file when none is chosen, so a file without efforts keeps the version + /// 1 shape that earlier builds read. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub(super) reasoning_effort: Option, +} + +/// The reasoning efforts a request to `endpoint` may carry (ADR-0102): every +/// documented value, or none when the endpoint takes no effort or is not a +/// valid endpoint. The server still decides which values its model accepts. +pub(super) fn reasoning_efforts(endpoint: &str) -> Vec { + if ModelEndpoint::parse(endpoint).is_ok_and(|parsed| parsed.takes_reasoning_effort()) { + ReasoningEffort::ALL.to_vec() + } else { + Vec::new() + } } /// Every recorded choice, by session. @@ -539,6 +556,7 @@ mod tests { endpoint: "https://ollama.com/v1".to_owned(), }, model: model.to_owned(), + reasoning_effort: None, } } @@ -554,6 +572,7 @@ mod tests { endpoint: "http://127.0.0.1:1234/v1".to_owned(), }, model: String::new(), + reasoning_effort: None, }, ); records.insert( @@ -561,6 +580,7 @@ mod tests { SessionRecord { connection: ChosenConnection::Follow {}, model: "qwen".to_owned(), + reasoning_effort: Some(ReasoningEffort::XHigh), }, ); assert_eq!(load(&root), Ok(None)); @@ -569,6 +589,74 @@ mod tests { fs::remove_dir_all(root).expect("cleanup"); } + #[test] + fn an_effort_is_omitted_when_none_and_a_file_without_one_still_loads() { + // ADR-0102: a record without an effort keeps the shape earlier builds + // wrote and read, and a file they wrote loads with no effort. + let root = scratch("effort-shape"); + let mut records = Records::new(); + records.insert(Uuid::from_u128(1), profile_record("m")); + save(&root, &records).expect("save"); + let text = fs::read_to_string(file_path(&root)).expect("read"); + assert!(!text.contains("reasoning_effort"), "{text}"); + fs::write( + file_path(&root), + r#"{"version":1,"sessions":{"00000000-0000-0000-0000-000000000002":{"connection":{"kind":"follow"},"model":"qwen"}}}"#, + ) + .expect("write an earlier build's file"); + let loaded = load(&root).expect("load").expect("records"); + assert_eq!( + loaded + .get(&Uuid::from_u128(2)) + .map(|record| record.reasoning_effort), + Some(None) + ); + // A recorded effort is its wire name; any other name makes the file + // unreadable, never partly applied. + let mut records = Records::new(); + records.insert( + Uuid::from_u128(3), + SessionRecord { + reasoning_effort: Some(ReasoningEffort::Max), + ..profile_record("m") + }, + ); + save(&root, &records).expect("save"); + let text = fs::read_to_string(file_path(&root)).expect("read"); + assert!(text.contains(r#""reasoning_effort": "max""#), "{text}"); + fs::write(file_path(&root), text.replace(r#""max""#, r#""maximum""#)) + .expect("write an unknown effort"); + assert_eq!(load(&root), Err(LoadError::Format)); + fs::remove_dir_all(root).expect("cleanup"); + } + + #[test] + fn only_endpoints_that_take_an_effort_offer_one() { + assert_eq!( + reasoning_efforts("http://127.0.0.1:1234/v1"), + ReasoningEffort::ALL.to_vec() + ); + assert_eq!( + reasoning_efforts("https://api.openai.com/v1"), + ReasoningEffort::ALL.to_vec() + ); + // A typed `openai_compatible` address takes one, unless its text is a + // named provider's fixed endpoint: that rule wins (ADR-0102). + assert_eq!( + reasoning_efforts("https://llm.example.com/v1"), + ReasoningEffort::ALL.to_vec() + ); + for endpoint in [ + "https://api.anthropic.com/v1", + "https://api.anthropic.com/v1/", + "https://api.deepseek.com", + "not an endpoint", + "", + ] { + assert!(reasoning_efforts(endpoint).is_empty(), "{endpoint}"); + } + } + #[test] fn a_damaged_file_reads_as_empty_and_is_reported() { let root = scratch("damaged"); diff --git a/crates/omgcode-app/src/desktop/settings.rs b/crates/omgcode-app/src/desktop/settings.rs index 0b5c119..bbd257c 100644 --- a/crates/omgcode-app/src/desktop/settings.rs +++ b/crates/omgcode-app/src/desktop/settings.rs @@ -30,7 +30,7 @@ use omgcode_core::turn::display_safe_line; use super::error::DesktopError; use super::instructions; use super::preferences; -use super::session_connections::{ChosenConnection, recorded_endpoint}; +use super::session_connections::{ChosenConnection, reasoning_efforts, recorded_endpoint}; use super::settings_chat::{ chat_defaults_view, global_for_room, longest_for_room, workspace_instructions_view, }; @@ -437,10 +437,15 @@ impl DesktopService { _ => Vec::new(), }; drop(store); + // The efforts of the connection shown; a turn re-checks its own + // resolved endpoint (ADR-0102). + let reasoning_efforts = reasoning_efforts(&connection.endpoint); Ok(ConnectionStatus { connection, origin, model, + reasoning_effort: record.and_then(|record| record.reasoning_effort), + reasoning_efforts, stale, session_choices_unreadable: unreadable, choices, diff --git a/crates/omgcode-app/src/desktop/settings_changes.rs b/crates/omgcode-app/src/desktop/settings_changes.rs index b194524..97634ff 100644 --- a/crates/omgcode-app/src/desktop/settings_changes.rs +++ b/crates/omgcode-app/src/desktop/settings_changes.rs @@ -62,8 +62,8 @@ use super::state::folder_of_directory; use super::wire::{ ApiKeySetRequest, ConnectionAddRequest, ConnectionChooseRequest, ConnectionRemoveRequest, ConnectionSelectRequest, ConnectionStatus, ConnectionStatusRequest, PermissionFlags, - PermissionsChangeRequest, SessionModelSelectRequest, SettingsOverview, SettingsRevisionRequest, - WorkspaceRevisionRequest, + PermissionsChangeRequest, SessionEffortSelectRequest, SessionModelSelectRequest, + SettingsOverview, SettingsRevisionRequest, WorkspaceRevisionRequest, }; /// What the operator is asked to choose a folder for. The shell uses it for @@ -897,8 +897,8 @@ impl DesktopService { /// a hosted service, that prompts and tool output leave this computer for /// its host), which /// no webview can answer. Only on Yes is the choice recorded for the - /// session, and its model is cleared because model ids belong to one - /// server. The settings store is read again after Yes, so a profile + /// session, and its model and reasoning effort are cleared because model + /// ids belong to one server. The settings store is read again after Yes, so a profile /// removed, or given another endpoint, while the dialog was open records /// nothing. No settings revision is involved: the global selection is not /// changed. @@ -948,9 +948,12 @@ impl DesktopService { if again != (choice.clone(), confirmation) { return Err(DesktopError::stale_revision()); } + // The model and effort are cleared: model ids belong to one server, + // and the efforts a model accepts depend on it (ADR-0102). inner.update_session_record(session_id, |_| SessionRecord { connection: choice.record(&inner.endpoint), model: String::new(), + reasoning_effort: None, })?; self.connection_status(ConnectionStatusRequest { session_id: Some(session_id), @@ -980,12 +983,68 @@ impl DesktopService { record.connection.clone() }), model: request.model, + reasoning_effort: existing.and_then(|record| record.reasoning_effort), })?; self.connection_status(ConnectionStatusRequest { session_id: Some(request.session_id), }) } + /// `main` only: record the reasoning effort chosen for one session + /// (ADR-0102), or `None` to send none. No dialog is shown: an effort + /// grants nothing, and the server still decides whether its model takes + /// the value. An effort is refused unless the session's connection, as + /// `connection_status` reports it now, takes one. The session's provider + /// and model are kept. Like a model choice, a session with no record gets + /// one that follows the default connection; it records the model the + /// status showed (the saved preference's), so the model shown does not + /// change. + /// + /// It holds the one-change-at-a-time guard, as a provider choice does, + /// so the connection it checks the effort against is the one the record + /// keeps: a provider choice cannot land between the check and the save. + /// + /// # Errors + /// + /// `invalid_request` for an effort the session's connection does not + /// take; `settings_change_running` while another settings change, such + /// as a provider choice awaiting its confirmation, runs; `not_found`; + /// `busy`, `control`, or `internal` while reading the connection; + /// `session_choices` when the choice cannot be saved. + pub fn session_effort_select( + &self, + request: SessionEffortSelectRequest, + ) -> Result { + let _guard = ChangeGuard::take(&self.inner.settings_change)?; + let session_id = request.session_id; + let status = self.connection_status(ConnectionStatusRequest { + session_id: Some(session_id), + })?; + if request + .reasoning_effort + .is_some_and(|effort| !status.reasoning_efforts.contains(&effort)) + { + return Err(DesktopError::invalid_request( + "This connection does not take a reasoning effort.", + )); + } + self.inner + .update_session_record(session_id, |existing| match existing { + Some(record) => SessionRecord { + reasoning_effort: request.reasoning_effort, + ..record.clone() + }, + None => SessionRecord { + connection: ChosenConnection::Follow {}, + model: status.model, + reasoning_effort: request.reasoning_effort, + }, + })?; + self.connection_status(ConnectionStatusRequest { + session_id: Some(session_id), + }) + } + /// `settings` only. Record a connection through the same core call as the /// CLI's `provider-profile-add`: a local LM Studio or Ollama connection /// with no credential and a typed loopback endpoint, a named hosted diff --git a/crates/omgcode-app/src/desktop/wire.rs b/crates/omgcode-app/src/desktop/wire.rs index ef5c56e..791e065 100644 --- a/crates/omgcode-app/src/desktop/wire.rs +++ b/crates/omgcode-app/src/desktop/wire.rs @@ -14,6 +14,7 @@ use omgcode_core::control::{ApprovalOperation, ApprovalState}; use omgcode_core::policy::{Access, WriteToolAccess}; +use omgcode_core::provider::ReasoningEffort; use omgcode_core::session::{MessageRole, MessageSource, ToolOutcome}; use omgcode_core::turn::DEFAULT_MAX_TOOL_CALLS; use serde::{Deserialize, Serialize}; @@ -125,6 +126,12 @@ pub struct ChatSettingsDto { pub compact_threshold: u64, /// Whether to compact at the effective trigger before a turn. pub auto_compact: bool, + /// The reasoning effort the turn's chat requests send, or `null` (or + /// absent) for none (ADR-0102). Only the seven documented names are + /// accepted. `chat_send` refuses one the session's connection does not + /// take. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub reasoning_effort: Option, } /// Arguments of `chat_send`. @@ -1118,6 +1125,12 @@ pub struct ConnectionStatus { /// The model chosen for the session, or the saved chat preference's model /// when the session has none. Empty when neither exists. pub model: String, + /// The reasoning effort chosen for the session, or `null` for none + /// (ADR-0102). + pub reasoning_effort: Option, + /// The efforts `connection` takes, from the least reasoning to the most: + /// every documented value, or none when the connection takes no effort. + pub reasoning_efforts: Vec, /// Whether the session's recorded connection can no longer be used as /// recorded (its profile is gone, not selectable, or has another /// endpoint). The next turn is refused with `session_connection_stale` @@ -1197,6 +1210,16 @@ pub struct SessionModelSelectRequest { pub model: String, } +/// Arguments of `session_effort_select` (ADR-0102). +#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq)] +#[serde(deny_unknown_fields)] +pub struct SessionEffortSelectRequest { + /// The session the effort is for. + pub session_id: Uuid, + /// One of the seven documented names, or `null` to send no effort. + pub reasoning_effort: Option, +} + /// What the status bar shows about a session's workspace (ADR-0064). #[derive(Clone, Debug, Eq, PartialEq, Serialize)] pub struct SessionContext { diff --git a/crates/omgcode-app/tests/chat_turn.rs b/crates/omgcode-app/tests/chat_turn.rs index 641e2db..a61bce0 100644 --- a/crates/omgcode-app/tests/chat_turn.rs +++ b/crates/omgcode-app/tests/chat_turn.rs @@ -22,7 +22,7 @@ use omgcode_app::{ use omgcode_core::context::ContextBudget; use omgcode_core::control::ControlStore; use omgcode_core::policy::{Access, PermissionSet, WriteToolAccess}; -use omgcode_core::provider::{LocalModelClient, LocalModelConfig}; +use omgcode_core::provider::{LocalModelClient, LocalModelConfig, ReasoningEffort}; use omgcode_core::session::{MessageRole, SessionJournal}; use omgcode_core::turn::CancelToken; use serde_json::{Value, json}; @@ -894,6 +894,115 @@ fn a_turn_without_a_stream_hook_sends_stream_false() { } } +/// A chosen reasoning effort is sent as `reasoning_effort` and recorded in the +/// turn's request manifest; without one neither carries the field (ADR-0102). +#[test] +fn a_chosen_reasoning_effort_is_sent_and_recorded_in_the_manifest() { + for tools_enabled in [false, true] { + for (effort, expected) in [(None, None), (Some(ReasoningEffort::XHigh), Some("xhigh"))] { + let fixture = Fixture::new(tools_enabled); + let mut journal = fixture.journal(); + let server = + common::MockServer::start(vec![common::Step::reply(common::text("plain"))]); + let mut chosen = settings(&server.endpoint); + chosen.reasoning_effort = effort; + turn( + &mut journal, + &fixture.data, + &chosen, + None, + "hello", + &mut ChatHooks::default(), + ) + .expect("turn"); + let (served, recorded) = server.finish_recorded(); + assert_eq!(served, 1); + let request = request_body(&recorded[0]); + assert_eq!( + request.get("reasoning_effort").and_then(Value::as_str), + expected, + "tools_enabled={tools_enabled}" + ); + let events = close_and_read(journal); + let manifests: Vec<&Value> = events + .iter() + .filter(|event| event["type"] == "request.manifest") + .map(|event| &event["payload"]["manifest"]) + .collect(); + assert_eq!(manifests.len(), 1); + assert_eq!( + manifests[0].get("reasoning_effort").and_then(Value::as_str), + expected, + "tools_enabled={tools_enabled}" + ); + } + } +} + +/// An endpoint whose provider documents no `reasoning_effort` refuses one +/// before anything is sent or recorded (ADR-0102 decision 3). +#[test] +fn an_effort_for_an_endpoint_that_takes_none_is_refused_before_any_request() { + let fixture = Fixture::new(false); + let mut journal = fixture.journal(); + let mut chosen = settings("https://api.deepseek.com"); + chosen.reasoning_effort = Some(ReasoningEffort::Low); + let error = turn( + &mut journal, + &fixture.data, + &chosen, + Some(SECRET), + "hello", + &mut ChatHooks::default(), + ) + .expect_err("DeepSeek takes no effort field"); + assert_eq!(error.code(), "provider"); + assert!(!error.message().contains(SECRET)); + let events = close_and_read(journal); + assert!( + events + .iter() + .all(|event| event["type"] != "turn.started" && event["type"] != "request.manifest") + ); +} + +/// A version 2 session cannot record an effort, so a turn that would send one +/// is refused before anything is recorded or requested (ADR-0102 decision 5). +#[test] +fn an_effort_in_a_version_2_session_is_refused_before_anything_is_recorded() { + let fixture = Fixture::new(false); + let journal = fixture.journal(); + let path = journal.path().to_owned(); + drop(journal); + let rewritten: String = fs::read_to_string(&path) + .expect("journal file") + .lines() + .map(|line| { + let mut event: Value = serde_json::from_str(line).expect("journal event"); + event["schema_version"] = json!(2); + serde_json::to_string(&event).expect("event JSON") + "\n" + }) + .collect(); + fs::write(&path, rewritten).expect("rewrite journal"); + let mut journal = SessionJournal::open(&path).expect("open schema-v2 journal"); + let server = common::NoCallServer::start(); + let mut chosen = settings(&server.endpoint); + chosen.reasoning_effort = Some(ReasoningEffort::Medium); + let error = turn( + &mut journal, + &fixture.data, + &chosen, + None, + "hello", + &mut ChatHooks::default(), + ) + .expect_err("a version 2 session cannot record an effort"); + assert_eq!(error.code(), "session"); + let events = close_and_read(journal); + assert!(events.iter().all(|event| event["type"] != "turn.started")); + server.assert_untouched(); +} + // ---- Cancelling a streamed turn (ADR-0050) ---- /// The slowest acceptable cancellation, timed from the moment the token is diff --git a/crates/omgcode-app/tests/desktop_context_breakdown.rs b/crates/omgcode-app/tests/desktop_context_breakdown.rs index 522190a..db47d12 100644 --- a/crates/omgcode-app/tests/desktop_context_breakdown.rs +++ b/crates/omgcode-app/tests/desktop_context_breakdown.rs @@ -8,6 +8,7 @@ use std::path::Path; use omgcode_app::create_session; use omgcode_app::desktop::{ContextBreakdown, ContextPartDto, ContextPartId, DesktopService}; use omgcode_core::control::ControlStore; +use omgcode_core::provider::{ReasoningEffort, effort_field_bytes}; use omgcode_core::session::{CompactionRecord, MessageRole, SessionJournal}; use serde_json::json; use sha2::{Digest, Sha256}; @@ -357,3 +358,48 @@ fn an_unknown_session_is_a_controlled_error() { .expect_err("unknown session"); assert_eq!(error.code(), "not_found"); } + +/// The effort a session records is sent with its next turn, so its field is +/// counted under framing and in the total, as the turn's own trigger counts +/// it (ADR-0102). Clearing the effort removes it again. +#[test] +fn a_recorded_effort_is_counted_as_framing() { + let fixture = Fixture::new(); + let workspace = fixture.workspace("plain", text_only()); + let (id, journal) = session(&fixture.data, &workspace.path, false); + drop(journal); + let service = fixture.service(NO_ENDPOINT); + let choose = |effort: Option<&str>| { + service + .session_effort_select(wire( + json!({ "session_id": id, "reasoning_effort": effort }), + )) + .expect("effort recorded"); + }; + let without = breakdown(&service, id); + + choose(Some("high")); + let with = breakdown(&service, id); + + let field = effort_field_bytes(Some(ReasoningEffort::High)); + assert!(field > 0); + assert_eq!(sum(&with), with.estimated_input_tokens); + assert_eq!( + with.estimated_input_tokens, + without.estimated_input_tokens + field + ); + assert_eq!( + part(&with, ContextPartId::Framing).tokens, + part(&without, ContextPartId::Framing).tokens + field + ); + assert_eq!( + part(&with, ContextPartId::Tools).tokens, + part(&without, ContextPartId::Tools).tokens + ); + + choose(None); + assert_eq!( + breakdown(&service, id).estimated_input_tokens, + without.estimated_input_tokens + ); +} diff --git a/crates/omgcode-app/tests/desktop_session_connection.rs b/crates/omgcode-app/tests/desktop_session_connection.rs index 1fe7f80..f7b6337 100644 --- a/crates/omgcode-app/tests/desktop_session_connection.rs +++ b/crates/omgcode-app/tests/desktop_session_connection.rs @@ -13,7 +13,8 @@ use std::path::PathBuf; use omgcode_app::TokenSource; use omgcode_app::desktop::{ ChatState, ChatStatus, Confirmation, ConnectionOrigin, ConnectionStatus, DesktopConfig, - DesktopError, DesktopService, FolderPurpose, SettingsPrompt, + DesktopError, DesktopService, FolderPurpose, ReasoningEffort, SessionEffortSelectRequest, + SettingsPrompt, }; use omgcode_core::control::ControlStore; use serde_json::json; @@ -96,7 +97,7 @@ fn choose( service: &DesktopService, session: Uuid, profile: Option<&str>, - prompt: &Answers, + prompt: &dyn SettingsPrompt, ) -> Result { service.connection_select( wire(json!({ "session_id": session, "profile": profile })), @@ -112,6 +113,16 @@ fn model( service.session_model_select(wire(json!({ "session_id": session, "model": model }))) } +fn effort( + service: &DesktopService, + session: Uuid, + effort: Option<&str>, +) -> Result { + service.session_effort_select(wire( + json!({ "session_id": session, "reasoning_effort": effort }), + )) +} + fn send( service: &DesktopService, session: Uuid, @@ -649,6 +660,182 @@ fn a_model_is_validated_and_never_pins_a_provider() { default.assert_untouched(); } +/// An effort is recorded per session without a dialog, kept by a model +/// choice, omitted from the file when none is chosen, and sent with the +/// session's turn (ADR-0102 decisions 7 and 8). +#[test] +fn an_effort_is_recorded_per_session_and_sent_with_its_turn() { + let fixture = Fixture::new(); + let workspace = fixture.workspace("project", text_only()); + let default = MockServer::start(vec![Step::reply(text("thought hard"))]); + let service = active(&fixture, &default.endpoint); + let id = session(&service, workspace.id); + let other = session(&service, workspace.id); + + // A loopback connection takes every effort; none is chosen yet. + let before = status(&service, Some(id)); + assert_eq!(before.reasoning_effort, None); + assert_eq!(before.reasoning_efforts, ReasoningEffort::ALL); + + let chosen = effort(&service, id, Some("high")).expect("effort"); + assert_eq!(chosen.reasoning_effort, Some(ReasoningEffort::High)); + assert_eq!(chosen.origin, ConnectionOrigin::Default); + assert_eq!(chosen.model, "", "an effort leaves the model as it was"); + let on_disk = fs::read_to_string(record_file(&fixture)).expect("record file"); + assert!( + on_disk.contains("\"reasoning_effort\": \"high\""), + "{on_disk}" + ); + assert_eq!(status(&service, Some(other)).reasoning_effort, None); + + // A model choice keeps the effort; clearing it removes the field. + let kept = model(&service, id, "fixture").expect("model"); + assert_eq!(kept.reasoning_effort, Some(ReasoningEffort::High)); + assert_eq!( + effort(&service, id, Some("xhigh")) + .expect("change") + .reasoning_effort, + Some(ReasoningEffort::XHigh) + ); + + // Only the seven names, and no other field, are accepted. + for request in [ + json!({ "session_id": id, "reasoning_effort": "extreme" }), + json!({ "session_id": id, "reasoning_effort": "High" }), + json!({ "session_id": id, "reasoning_effort": "low", "endpoint": "x" }), + ] { + assert!( + serde_json::from_value::(request.clone()).is_err(), + "{request}" + ); + } + assert_eq!( + code(effort(&service, Uuid::new_v4(), Some("low"))), + "not_found" + ); + + // The turn sends the effort the composer names. + let mut settings = settings_json(&default.endpoint); + settings["reasoning_effort"] = json!("xhigh"); + service + .chat_send(wire(json!({ + "session_id": id, + "message": "hello", + "settings": settings, + "skills": [], + }))) + .expect("turn starts"); + let done = wait_finished(&service, id); + assert!(matches!(done.state, ChatState::Completed), "{done:?}"); + let (served, recorded) = default.finish_recorded(); + assert_eq!(served, 1); + let request: serde_json::Value = + serde_json::from_str(&recorded[0].body).expect("chat request body"); + assert_eq!(request["reasoning_effort"], "xhigh"); + + let cleared = effort(&service, id, None).expect("clear"); + assert_eq!(cleared.reasoning_effort, None); + let on_disk = fs::read_to_string(record_file(&fixture)).expect("record file"); + assert!(!on_disk.contains("reasoning_effort"), "{on_disk}"); +} + +/// A connection whose provider documents no effort offers none and refuses +/// one, on save and on send; choosing a provider clears the session's effort +/// (ADR-0102 decisions 2, 7, and 8). +#[test] +fn a_connection_without_effort_refuses_one_and_a_provider_change_clears_it() { + let fixture = Fixture::new(); + let workspace = fixture.workspace("project", text_only()); + let default = NoCallServer::start(); + let service = active(&fixture, &default.endpoint); + let mut vault = Vault::new(&fixture.data); + vault.add_profile_at("deep", "deepseek", "api_key", "https://api.deepseek.com"); + vault.bind("deep", b"fake-deepseek-key-for-the-test"); + let id = session(&service, workspace.id); + effort(&service, id, Some("medium")).expect("effort on the default"); + + let prompt = Answers::with(&[true]); + let chosen = choose(&service, id, Some("deep"), &prompt).expect("choose deepseek"); + assert_eq!(chosen.reasoning_effort, None, "a provider choice clears it"); + assert!(chosen.reasoning_efforts.is_empty()); + assert_eq!(code(effort(&service, id, Some("low"))), "invalid_request"); + assert_eq!( + effort(&service, id, None).expect("none").reasoning_effort, + None + ); + + // The send is refused before the turn starts; nothing reaches the network. + let mut settings = settings_json(&chosen.connection.endpoint); + settings["reasoning_effort"] = json!("low"); + let refused = service.chat_send(wire(json!({ + "session_id": id, + "message": "hello", + "settings": settings, + "skills": [], + }))); + assert_eq!(code(refused), "invalid_request"); + assert_eq!( + status(&service, Some(id)).reasoning_effort, + None, + "a refused send records nothing" + ); + default.assert_untouched(); +} + +/// Answers Yes, but first tries an effort choice for the same session while +/// the provider confirmation is open, and keeps what that returned. +struct EffortDuringConfirmation<'a> { + service: &'a DesktopService, + session: Uuid, + refused: RefCell>, +} + +impl SettingsPrompt for EffortDuringConfirmation<'_> { + fn pick_folder( + &self, + _purpose: FolderPurpose, + _start: Option<&std::path::Path>, + ) -> Option { + panic!("no folder dialog is expected"); + } + + fn confirm(&self, _confirmation: &Confirmation) -> bool { + let attempt = effort(self.service, self.session, Some("high")); + self.refused.replace(Some(code(attempt))); + true + } +} + +/// An effort choice runs as one settings change, as a provider choice does, +/// so a provider choice cannot land between its check and its save: while a +/// confirmation is open it is refused with `settings_change_running`, and it +/// works again once the provider choice ends (ADR-0102). +#[test] +fn an_effort_choice_is_refused_while_a_provider_choice_runs() { + let fixture = Fixture::new(); + let workspace = fixture.workspace("project", text_only()); + let default = NoCallServer::start(); + let service = active(&fixture, &default.endpoint); + let mut vault = Vault::new(&fixture.data); + vault.add_profile_at("deep", "deepseek", "api_key", "https://api.deepseek.com"); + vault.bind("deep", b"fake-deepseek-key-for-the-test"); + let id = session(&service, workspace.id); + + let prompt = EffortDuringConfirmation { + service: &service, + session: id, + refused: RefCell::new(None), + }; + let chosen = choose(&service, id, Some("deep"), &prompt).expect("choose deepseek"); + assert_eq!(prompt.refused.take(), Some("settings_change_running")); + assert_eq!(chosen.reasoning_effort, None); + assert!(chosen.reasoning_efforts.is_empty()); + // The guard is released: the next choice is checked against DeepSeek. + assert_eq!(code(effort(&service, id, Some("high"))), "invalid_request"); + assert_eq!(status(&service, Some(id)).reasoning_effort, None); + default.assert_untouched(); +} + /// An unreadable file is reported, treated as empty, and replaced by the next /// recorded choice; chat is never blocked by it. #[test] diff --git a/crates/omgcode-app/tests/desktop_sessions.rs b/crates/omgcode-app/tests/desktop_sessions.rs index abaa5a1..62925d1 100644 --- a/crates/omgcode-app/tests/desktop_sessions.rs +++ b/crates/omgcode-app/tests/desktop_sessions.rs @@ -65,6 +65,7 @@ fn manifest() -> RequestManifest { tool_schema_version: Some("1".into()), tools: Some(vec!["workspace_read_file".into()]), skills: Vec::new(), + reasoning_effort: None, } } diff --git a/crates/omgcode-app/tests/desktop_wire.rs b/crates/omgcode-app/tests/desktop_wire.rs index b3b5092..65036ed 100644 --- a/crates/omgcode-app/tests/desktop_wire.rs +++ b/crates/omgcode-app/tests/desktop_wire.rs @@ -9,11 +9,11 @@ use omgcode_app::desktop::{ ApprovalDecideRequest, ApprovalDetail, ApprovalField, ApprovalList, ApprovalOperationDto, ApprovalRequest, ApprovalStateDto, ApprovalView, ApprovalsSummary, Binding, ChatEvent, ChatOutcome, ChatSendRequest, ChatSettingsDto, ChatState, ChatStatus, ContextMeterDto, - Decision, DesktopError, EntryKind, MessageRoleDto, SearchHit, SearchRequest, SearchResult, - SearchRoleDto, SessionCreateRequest, SessionRequest, SessionStatus, SessionSummary, - SessionTree, SnippetPart, ToolOutcomeDto, ToolsMode, TranscriptEntry, TranscriptPage, - TranscriptRequest, TreeRequest, TreeSort, TreeView, WorkspaceChoice, WorkspaceGroup, - WorkspaceList, + Decision, DesktopError, EntryKind, MessageRoleDto, ReasoningEffort, SearchHit, SearchRequest, + SearchResult, SearchRoleDto, SessionCreateRequest, SessionRequest, SessionStatus, + SessionSummary, SessionTree, SnippetPart, ToolOutcomeDto, ToolsMode, TranscriptEntry, + TranscriptPage, TranscriptRequest, TreeRequest, TreeSort, TreeView, WorkspaceChoice, + WorkspaceGroup, WorkspaceList, }; use omgcode_core::policy::Access; use serde_json::{Value, json}; @@ -658,6 +658,9 @@ fn every_serialized_interface_has_exactly_the_fields_types_ts_declares() { instructions: String::new(), compact_threshold: 1, auto_compact: false, + // An effort is omitted when none is chosen (ADR-0102); a chosen one + // shows the optional key `types.ts` declares. + reasoning_effort: Some(ReasoningEffort::High), }); let workspaces = json_of(&WorkspaceList { development_root_set: false, @@ -735,6 +738,10 @@ fn closed_unions_serialize_to_the_values_types_ts_declares() { .map(|value| value.as_str().expect("string").to_owned()) .collect() }; + assert_eq!( + union("ReasoningEffort"), + strings(ReasoningEffort::ALL.iter().map(json_of).collect()) + ); assert_eq!( union("SessionStatus"), strings( diff --git a/crates/omgcode-cli/src/main.rs b/crates/omgcode-cli/src/main.rs index c074aad..f423872 100644 --- a/crates/omgcode-cli/src/main.rs +++ b/crates/omgcode-cli/src/main.rs @@ -22,7 +22,7 @@ use omgcode_app::{ use omgcode_core::context::{ContextBudget, DEFAULT_COMPACT_THRESHOLD}; use omgcode_core::control::ProviderKind; use omgcode_core::prompt::{self, BASE_PROMPT, BASE_PROMPT_VERSION}; -use omgcode_core::provider::{ListedModel, LocalModelClient, LocalModelConfig}; +use omgcode_core::provider::{ListedModel, LocalModelClient, LocalModelConfig, ReasoningEffort}; use omgcode_core::run::{InterruptWatch, watch_interrupt}; use omgcode_core::session::{NativePath, SessionJournal}; use omgcode_core::skills::SkillName; @@ -191,6 +191,12 @@ struct ChatArgs { context_tokens: u64, #[arg(long, default_value_t = 1024)] max_output_tokens: u32, + /// Ask the model for this reasoning effort: none, minimal, low, medium, + /// high, xhigh, or max (ADR-0102). Without it no effort field is sent and + /// the provider's default applies. The model decides which values it + /// accepts; a connection that takes no effort refuses the flag. + #[arg(long, value_parser = reasoning_effort)] + reasoning_effort: Option, /// Maximum tool calls per turn (1–256). #[arg(long, default_value_t = DEFAULT_MAX_TOOL_CALLS)] max_tool_calls: usize, @@ -275,6 +281,13 @@ fn non_empty_name(value: &str) -> Result { } } +/// Parse `--reasoning-effort` through core's closed list of names (ADR-0102). +fn reasoning_effort(value: &str) -> Result { + ReasoningEffort::parse(value).ok_or_else(|| { + "the reasoning effort must be none, minimal, low, medium, high, xhigh, or max".to_owned() + }) +} + #[derive(Serialize)] struct CliError { code: &'static str, @@ -514,6 +527,7 @@ fn chat(data_dir: Option, mut args: ChatArgs) -> Result<(), CliError> { instructions: args.instructions, compact_threshold: args.compact_threshold, auto_compact: args.auto_compact, + reasoning_effort: args.reasoning_effort, }; let clients = ChatClients::for_connection(&settings, &connection)?; let title = redact_known_secret(&args.title, token_text); diff --git a/crates/omgcode-cli/tests/actions_listing.rs b/crates/omgcode-cli/tests/actions_listing.rs index 9c984d8..13dd70b 100644 --- a/crates/omgcode-cli/tests/actions_listing.rs +++ b/crates/omgcode-cli/tests/actions_listing.rs @@ -58,6 +58,16 @@ fn start( } fn seeded() -> Seeded { + let (seeded, journal) = seeded_open(); + drop(journal); + seeded +} + +/// The seeded journal with its writer still open, for a test that appends +/// more. Dropping the writer and opening it again is racy on Linux: a sibling +/// test's CLI child, between fork and exec, briefly shares the descriptor and +/// so its `flock`, and the reopen then fails with `Busy`. +fn seeded_open() -> (Seeded, ActionJournal) { let fixture = Fixture::new(b"note"); let workspace = fixture.workspace_id; let fetching = Uuid::new_v4(); @@ -131,12 +141,12 @@ fn seeded() -> Seeded { &[""], false, ); - drop(journal); - Seeded { + let seeded = Seeded { fixture, fetching, quiet, - } + }; + (seeded, journal) } fn list(seeded: &Seeded, extra: &[&str]) -> Vec { @@ -263,8 +273,7 @@ fn a_filtered_listing_reports_whether_it_may_be_incomplete() { /// and the listing says so instead of looking complete. #[test] fn a_filtered_listing_is_truncated_when_newer_calls_fill_the_search_window() { - let seeded = seeded(); - let mut journal = ActionJournal::open(&seeded.fixture.data).expect("action journal"); + let (seeded, mut journal) = seeded_open(); for index in 0..1000 { let call_id = format!("later-{index}"); journal diff --git a/crates/omgcode-core/src/provider.rs b/crates/omgcode-core/src/provider.rs index a609601..a3b40a1 100644 --- a/crates/omgcode-core/src/provider.rs +++ b/crates/omgcode-core/src/provider.rs @@ -1,15 +1,19 @@ pub mod chatgpt; +mod effort; mod hosted; mod models; mod responses; mod stream; +pub use effort::ReasoningEffort; pub use hosted::{ ANTHROPIC_ENDPOINT, DEEPSEEK_ENDPOINT, GOOGLE_ENDPOINT, META_ENDPOINT, MINIMAX_ENDPOINT, MOONSHOT_ENDPOINT, OLLAMA_CLOUD_ENDPOINT, OPENAI_ENDPOINT, OPENROUTER_ENDPOINT, OutputLimitField, TENCENT_ENDPOINT, THINKING_MACHINES_ENDPOINT, XAI_ENDPOINT, Z_AI_ENDPOINT, }; -pub(crate) use hosted::{disables_thinking, fixed_endpoint, matches_fixed, validate_custom_url}; +pub(crate) use hosted::{ + disables_thinking, fixed_endpoint, fixed_takes_effort, matches_fixed, validate_custom_url, +}; pub use models::{ListedModel, MAX_LISTED_MODELS, list_local_models, list_subscription_models}; pub use responses::ResponseFailure; @@ -59,6 +63,24 @@ const MESSAGE_OVERHEAD_ESTIMATE: u64 = 256; const PROMPT_HEADROOM_ESTIMATE: u64 = 512; /// Upper bound on advertised tool definitions in one request. const MAX_TOOL_DEFINITIONS: usize = 10; +/// Upper bound on the encoded bytes of the effort field, either shape: the +/// longest is `,"reasoning":{"effort":"minimal"}` (33 bytes). +const EFFORT_FIELD_BYTES: u64 = 48; + +/// The encoded bytes the effort field adds to one request: a fixed upper bound +/// when an effort is chosen, and zero when none is sent (ADR-0102). +/// +/// The client counts it in its own size and context checks; a caller that +/// estimates a request before it is built adds the same figure, so the two +/// estimates agree. +pub const fn effort_field_bytes(effort: Option) -> u64 { + if effort.is_some() { + EFFORT_FIELD_BYTES + } else { + 0 + } +} + /// Upper bound on raw tool calls accepted from one response before validation. /// The turn runtime applies its own, smaller per-round limit. const MAX_RESPONSE_TOOL_CALLS: usize = 64; @@ -87,11 +109,13 @@ enum EndpointRule { Loopback(Url), /// An HTTPS base URL: a fixed provider endpoint, or one that passed the /// operator-typed rule. `field` names the output budget field it takes, - /// and `thinking_off` whether requests switch the provider's thinking off. + /// `thinking_off` whether requests switch the provider's thinking off, and + /// `effort` whether a request may carry a reasoning effort (ADR-0102). Hosted { url: Url, field: OutputLimitField, thinking_off: bool, + effort: bool, }, } @@ -109,6 +133,7 @@ impl ModelEndpoint { url, field, thinking_off: disables_thinking(text), + effort: fixed_takes_effort(text), })); } if text.starts_with("https://") { @@ -117,6 +142,9 @@ impl ModelEndpoint { url, field: OutputLimitField::MaxTokens, thinking_off: false, + // The operator's own server; its documentation cannot be + // checked here, and the server decides (ADR-0102). + effort: true, }) }); } @@ -171,6 +199,16 @@ impl ModelEndpoint { } } + /// Whether a request to this endpoint may carry a reasoning effort + /// (ADR-0102): every loopback server and operator-typed endpoint, and the + /// fixed endpoints whose provider documents the field. + pub const fn takes_reasoning_effort(&self) -> bool { + match self.0 { + EndpointRule::Loopback(_) => true, + EndpointRule::Hosted { effort, .. } => effort, + } + } + /// The URL of one resource below the base URL, such as `/models`. The /// suffix is appended to the base path, so `https://api.z.ai/api/paas/v4` /// gives `/api/paas/v4/models` and `http://127.0.0.1:1234/v1` gives @@ -223,6 +261,10 @@ pub struct LocalModelClient { https_only: bool, output_field: OutputLimitField, thinking: Option, + /// Whether the endpoint takes a reasoning effort (ADR-0102). + takes_effort: bool, + /// The effort every request sends; `None` sends no field. + reasoning_effort: Option, model: String, context_tokens: u64, max_output_tokens: u32, @@ -361,6 +403,9 @@ struct ChatRequest<'a> { limit: OutputLimit, #[serde(skip_serializing_if = "Option::is_none")] thinking: Option, + /// Sent only when the operator chose an effort (ADR-0102). + #[serde(skip_serializing_if = "Option::is_none")] + reasoning_effort: Option, } /// The text request plus the advertised function tools. @@ -373,6 +418,8 @@ struct ToolChatRequest<'a> { limit: OutputLimit, #[serde(skip_serializing_if = "Option::is_none")] thinking: Option, + #[serde(skip_serializing_if = "Option::is_none")] + reasoning_effort: Option, tools: &'a [WireTool<'a>], tool_choice: &'static str, } @@ -441,6 +488,8 @@ impl LocalModelClient { thinking: model_endpoint .disables_thinking() .then_some(Thinking { kind: "disabled" }), + takes_effort: model_endpoint.takes_reasoning_effort(), + reasoning_effort: None, model: config.model, context_tokens: config.context_tokens, max_output_tokens: config.max_output_tokens, @@ -498,6 +547,9 @@ impl LocalModelClient { authorization: None, // A Chat Completions switch (ADR-0092); the Responses body has no such field. thinking: None, + // The Responses API takes `reasoning.effort` (ADR-0102). + takes_effort: model_endpoint.takes_reasoning_effort(), + reasoning_effort: None, request_timeout, protocol: Protocol::Responses(tokens), }) @@ -513,6 +565,36 @@ impl LocalModelClient { &self.model } + /// Send `effort` with every request of this client, or no effort field + /// for `None` (ADR-0102). The value is not checked against the model: + /// the server decides, and refuses a value its model does not take. + /// + /// # Errors + /// + /// `InvalidConfiguration` for an effort on an endpoint that takes none. + /// Nothing is sent. + pub fn with_reasoning_effort( + mut self, + effort: Option, + ) -> Result { + if effort.is_some() && !self.takes_effort { + return Err(ProviderError::InvalidConfiguration); + } + self.reasoning_effort = effort; + Ok(self) + } + + /// The effort every request sends, or `None` when no field is sent. + pub const fn reasoning_effort(&self) -> Option { + self.reasoning_effort + } + + /// The encoded bytes the effort field adds to a request, counted in the + /// size and context estimates. + const fn effort_bytes(&self) -> u64 { + effort_field_bytes(self.reasoning_effort) + } + /// Send one bounded, non-streaming Chat Completions request. /// /// The adapter sends only model, role-tagged messages, `stream=false`, and @@ -620,13 +702,14 @@ impl LocalModelClient { messages: &[ModelMessage], streaming: bool, ) -> Result, ProviderError> { - self.check_messages(messages, 0)?; + self.check_messages(messages, self.effort_bytes())?; serde_json::to_vec(&ChatRequest { model: &self.model, messages, stream: streaming, limit: self.output_limit(), thinking: self.thinking, + reasoning_effort: self.reasoning_effort, }) .map_err(|_| ProviderError::MalformedResponse) } @@ -717,7 +800,10 @@ impl LocalModelClient { let tool_bytes = serde_json::to_vec(&tools).map_err(|_| ProviderError::RequestTooLarge)?; self.check_messages( messages, - u64::try_from(tool_bytes.len()).map_err(|_| ProviderError::RequestTooLarge)?, + u64::try_from(tool_bytes.len()) + .map_err(|_| ProviderError::RequestTooLarge)? + .checked_add(self.effort_bytes()) + .ok_or(ProviderError::RequestTooLarge)?, )?; serde_json::to_vec(&ToolChatRequest { model: &self.model, @@ -725,6 +811,7 @@ impl LocalModelClient { stream: streaming, limit: self.output_limit(), thinking: self.thinking, + reasoning_effort: self.reasoning_effort, tools: &tools, tool_choice: "auto", }) @@ -914,7 +1001,7 @@ impl LocalModelClient { on_text: &mut dyn FnMut(&str), cancel: &CancelToken, ) -> Result { - let extra_bytes = match tools { + let tool_bytes = match tools { None => 0, Some(tools) => { if tools.is_empty() || tools.len() > MAX_TOOL_DEFINITIONS { @@ -930,8 +1017,11 @@ impl LocalModelClient { .ok_or(ProviderError::RequestTooLarge)? } }; + let extra_bytes = tool_bytes + .checked_add(self.effort_bytes()) + .ok_or(ProviderError::RequestTooLarge)?; self.check_messages(messages, extra_bytes)?; - let body = responses::request_body(&self.model, messages, tools)?; + let body = responses::request_body(&self.model, self.reasoning_effort, messages, tools)?; if body.len() > MAX_REQUEST_BYTES { return Err(ProviderError::RequestTooLarge); } @@ -1879,6 +1969,164 @@ mod tests { } } + /// The endpoints that take an effort (ADR-0102): every loopback and + /// operator-typed endpoint, and only the fixed ones whose provider + /// documents `reasoning_effort`. + #[test] + fn only_documented_endpoints_take_a_reasoning_effort() { + for (base, takes) in [ + ("http://127.0.0.1:1234/v1", true), + ("http://127.0.0.1:11434/v1", true), + ("https://provider-api.example.org/v1", true), + (OLLAMA_CLOUD_ENDPOINT, true), + (OPENAI_ENDPOINT, true), + ("https://api.openai.com/v1/", true), + (GOOGLE_ENDPOINT, true), + (MOONSHOT_ENDPOINT, true), + (MINIMAX_ENDPOINT, true), + (OPENROUTER_ENDPOINT, true), + (Z_AI_ENDPOINT, true), + (XAI_ENDPOINT, true), + (ANTHROPIC_ENDPOINT, false), + (DEEPSEEK_ENDPOINT, false), + (TENCENT_ENDPOINT, false), + (META_ENDPOINT, false), + (THINKING_MACHINES_ENDPOINT, false), + ] { + let endpoint = ModelEndpoint::parse(base).expect(base); + assert_eq!(endpoint.takes_reasoning_effort(), takes, "{base}"); + let client = LocalModelClient::new( + LocalModelConfig { + base_url: base.to_owned(), + ..cloud_config() + }, + Some("not-a-real-key".to_owned()), + ) + .unwrap_or_else(|error| panic!("{base}: {error}")); + let result = client.with_reasoning_effort(Some(ReasoningEffort::High)); + if takes { + assert_eq!( + result.expect(base).reasoning_effort(), + Some(ReasoningEffort::High) + ); + } else { + assert_eq!(result.err(), Some(ProviderError::InvalidConfiguration)); + } + } + // No effort is always accepted, including where none can be sent. + let client = LocalModelClient::new( + LocalModelConfig { + base_url: DEEPSEEK_ENDPOINT.to_owned(), + ..cloud_config() + }, + Some("not-a-real-key".to_owned()), + ) + .expect("deepseek client") + .with_reasoning_effort(None) + .expect("no effort"); + assert_eq!(client.reasoning_effort(), None); + } + + /// A chosen effort is one top-level `reasoning_effort` field on every + /// Chat Completions body; without one the body is exactly as before. + #[test] + fn a_chosen_effort_is_sent_as_reasoning_effort_on_chat_completions() { + let history = [ + ModelMessage { + role: ModelRole::System, + content: BASE_PROMPT.to_owned(), + }, + ModelMessage { + role: ModelRole::User, + content: "hello".to_owned(), + }, + ]; + let tools = crate::turn::tool_definitions(); + for base in [ + "http://127.0.0.1:1234/v1", + OPENAI_ENDPOINT, + "https://provider-api.example.org/v1", + ] { + let plain = LocalModelClient::new( + LocalModelConfig { + base_url: base.to_owned(), + ..cloud_config() + }, + Some("not-a-real-key".to_owned()), + ) + .expect(base); + for effort in ReasoningEffort::ALL { + let chosen = LocalModelClient::new( + LocalModelConfig { + base_url: base.to_owned(), + ..cloud_config() + }, + Some("not-a-real-key".to_owned()), + ) + .and_then(|client| client.with_reasoning_effort(Some(effort))) + .expect(base); + for streaming in [false, true] { + let pairs = [ + ( + chosen.text_body(&history, streaming).expect("text"), + plain.text_body(&history, streaming).expect("text"), + ), + ( + chosen + .tool_body(&history, &tools, streaming) + .expect("tools"), + plain.tool_body(&history, &tools, streaming).expect("tools"), + ), + ]; + for (with, without) in pairs { + let with: Value = serde_json::from_slice(&with).expect("json"); + let mut without: Value = serde_json::from_slice(&without).expect("json"); + assert_eq!(with["reasoning_effort"], effort.as_str(), "{base}"); + assert!(with.get("reasoning").is_none(), "{base}"); + assert!(without.get("reasoning_effort").is_none(), "{base}"); + without["reasoning_effort"] = with["reasoning_effort"].clone(); + assert_eq!(with, without, "{base}"); + } + } + } + } + } + + /// The effort field counts in the context estimate, so a request that + /// fits exactly without one is refused with one rather than sent over + /// the budget. + #[test] + fn the_effort_field_counts_in_the_context_estimate() { + let history = [ + ModelMessage { + role: ModelRole::System, + content: BASE_PROMPT.to_owned(), + }, + ModelMessage { + role: ModelRole::User, + content: "hello".to_owned(), + }, + ]; + let exact = estimate_context(&history, 64).expect("estimate"); + let client = |effort| { + LocalModelClient::new( + LocalModelConfig { + base_url: "http://127.0.0.1:1234/v1".to_owned(), + context_tokens: exact, + ..cloud_config() + }, + None, + ) + .and_then(|client| client.with_reasoning_effort(effort)) + .expect("client") + }; + assert!(client(None).text_body(&history, false).is_ok()); + assert_eq!( + client(Some(ReasoningEffort::Low)).text_body(&history, false), + Err(ProviderError::ContextLimit) + ); + } + use std::net::TcpListener; use std::sync::mpsc; use std::thread; diff --git a/crates/omgcode-core/src/provider/effort.rs b/crates/omgcode-core/src/provider/effort.rs new file mode 100644 index 0000000..507d350 --- /dev/null +++ b/crates/omgcode-core/src/provider/effort.rs @@ -0,0 +1,95 @@ +//! The reasoning effort a request may ask for (ADR-0102). +//! +//! The names are the ones OpenAI documents for Chat Completions +//! `reasoning_effort` and Responses `reasoning.effort`; the other providers +//! that take an effort document subsets of the same names. Which names a model +//! accepts is the server's decision, so no value is adjusted here. + +use serde::{Deserialize, Serialize}; + +/// One documented reasoning effort. "No effort" is `Option::None`, which +/// sends no field at all; [`ReasoningEffort::None`] is the provider's own +/// `none` value, which asks a model to skip reasoning where it can. +/// +/// The enum is closed: serde accepts exactly the seven wire names and refuses +/// any other text, so no other value reaches a request or a record. +#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum ReasoningEffort { + /// `none`: skip reasoning where the model allows it. + None, + /// `minimal`. + Minimal, + /// `low`. + Low, + /// `medium`. + Medium, + /// `high`. + High, + /// `xhigh`. + #[serde(rename = "xhigh")] + XHigh, + /// `max`. + Max, +} + +impl ReasoningEffort { + /// Every value, from the least reasoning to the most. + pub const ALL: [Self; 7] = [ + Self::None, + Self::Minimal, + Self::Low, + Self::Medium, + Self::High, + Self::XHigh, + Self::Max, + ]; + + /// The wire name, as sent and recorded. + pub const fn as_str(self) -> &'static str { + match self { + Self::None => "none", + Self::Minimal => "minimal", + Self::Low => "low", + Self::Medium => "medium", + Self::High => "high", + Self::XHigh => "xhigh", + Self::Max => "max", + } + } + + /// The value with this wire name, if any. + pub fn parse(text: &str) -> Option { + Self::ALL.into_iter().find(|effort| effort.as_str() == text) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn every_value_round_trips_through_its_wire_name() { + for effort in ReasoningEffort::ALL { + let json = serde_json::to_string(&effort).expect("encode"); + assert_eq!(json, format!("\"{}\"", effort.as_str())); + assert_eq!( + serde_json::from_str::(&json).expect("decode"), + effort + ); + assert_eq!(ReasoningEffort::parse(effort.as_str()), Some(effort)); + } + assert_eq!(ReasoningEffort::XHigh.as_str(), "xhigh"); + } + + #[test] + fn other_text_is_refused() { + for text in ["", "x_high", "XHIGH", "High", "ultra", "medium ", "default"] { + assert_eq!(ReasoningEffort::parse(text), None, "{text:?}"); + assert!( + serde_json::from_str::(&format!("\"{text}\"")).is_err(), + "{text:?}" + ); + } + } +} diff --git a/crates/omgcode-core/src/provider/hosted.rs b/crates/omgcode-core/src/provider/hosted.rs index 7b5a36b..5722583 100644 --- a/crates/omgcode-core/src/provider/hosted.rs +++ b/crates/omgcode-core/src/provider/hosted.rs @@ -92,6 +92,30 @@ pub(crate) fn disables_thinking(text: &str) -> bool { .any(|fixed| matches_fixed(text, fixed)) } +/// Fixed endpoints whose provider documents a top-level `reasoning_effort` on +/// its OpenAI-compatible Chat Completions API (ADR-0102, checked 2026-11-26). +/// It is an allowlist: a fixed endpoint added later takes no effort until its +/// documentation is checked. Anthropic's compatibility layer documents the +/// field as ignored, DeepSeek's `thinking` field (sent as disabled) overrides +/// it, and Tencent, Meta, and Tinker document none. +const EFFORT_ENDPOINTS: &[&str] = &[ + OLLAMA_CLOUD_ENDPOINT, + OPENAI_ENDPOINT, + GOOGLE_ENDPOINT, + MOONSHOT_ENDPOINT, + MINIMAX_ENDPOINT, + OPENROUTER_ENDPOINT, + Z_AI_ENDPOINT, + XAI_ENDPOINT, +]; + +/// Whether the fixed endpoint `text` takes a reasoning effort. +pub(crate) fn fixed_takes_effort(text: &str) -> bool { + EFFORT_ENDPOINTS + .iter() + .any(|fixed| matches_fixed(text, fixed)) +} + /// Longest endpoint text either hosted rule reads, checked before parsing. const MAX_ENDPOINT_BYTES: usize = 256; diff --git a/crates/omgcode-core/src/provider/responses.rs b/crates/omgcode-core/src/provider/responses.rs index 2110f77..addee3f 100644 --- a/crates/omgcode-core/src/provider/responses.rs +++ b/crates/omgcode-core/src/provider/responses.rs @@ -7,7 +7,10 @@ //! from the finished output items once `response.completed` arrives, and //! every other ending fails the request. -use super::{MAX_RESPONSE_TOOL_CALLS, MAX_STREAM_BYTES, ProviderError, Usage, json_string_len}; +use super::{ + MAX_RESPONSE_TOOL_CALLS, MAX_STREAM_BYTES, ProviderError, ReasoningEffort, Usage, + json_string_len, +}; use crate::prompt::{ModelMessage, ModelRole}; use crate::storage::parse_strict_json; use crate::turn::ToolDefinition; @@ -118,6 +121,15 @@ struct ResponsesRequest<'a> { tools: Option<[Namespace<'a>; 1]>, #[serde(skip_serializing_if = "Option::is_none")] tool_choice: Option<&'static str>, + /// Sent only when the operator chose an effort (ADR-0102). + #[serde(skip_serializing_if = "Option::is_none")] + reasoning: Option, +} + +/// The Responses API's reasoning options: the effort only. +#[derive(Serialize)] +struct Reasoning { + effort: ReasoningEffort, } /// One input item. A tool result in tools mode becomes the model's own call @@ -172,10 +184,12 @@ struct FunctionTool<'a> { /// text (ADR-0097). Every other message, and a tool result in a request /// without tools, becomes a message item; a tool result is `user` text there. /// `store` is `false` and `stream` is `true`, as the route requires. Tools, -/// when given, go in one namespace. No output limit, sampling, reasoning, or -/// conversation field is sent. +/// when given, go in one namespace. An `effort` is sent as +/// `reasoning.effort` (ADR-0102); `None` sends no `reasoning` field. No output +/// limit, sampling, reasoning summary, or conversation field is sent. pub(super) fn request_body( model: &str, + effort: Option, messages: &[ModelMessage], tools: Option<&[ToolDefinition]>, ) -> Result, ProviderError> { @@ -234,6 +248,7 @@ pub(super) fn request_body( stream: true, tools, tool_choice, + reasoning: effort.map(|effort| Reasoning { effort }), }) .map_err(|_| ProviderError::RequestTooLarge) } diff --git a/crates/omgcode-core/src/provider/responses/tests.rs b/crates/omgcode-core/src/provider/responses/tests.rs index c1ccf7a..11f3760 100644 --- a/crates/omgcode-core/src/provider/responses/tests.rs +++ b/crates/omgcode-core/src/provider/responses/tests.rs @@ -355,7 +355,7 @@ fn a_stream_over_the_byte_limit_is_refused() { #[test] fn the_request_body_uses_instructions_input_items_and_one_namespace() { let tools = tool_definitions(); - let body = request_body("gpt-test", &messages(), Some(&tools)).expect("body"); + let body = request_body("gpt-test", None, &messages(), Some(&tools)).expect("body"); let value: Value = serde_json::from_slice(&body).expect("json"); assert_eq!(value["model"], "gpt-test"); assert_eq!(value["instructions"], BASE_PROMPT); @@ -393,7 +393,7 @@ fn the_request_body_uses_instructions_input_items_and_one_namespace() { assert!(value.get(field).is_none(), "{field}"); } - let text = request_body("gpt-test", &messages(), None).expect("text body"); + let text = request_body("gpt-test", None, &messages(), None).expect("text body"); let value: Value = serde_json::from_slice(&text).expect("json"); assert!(value.get("tools").is_none()); assert!(value.get("tool_choice").is_none()); @@ -404,11 +404,37 @@ fn the_request_body_uses_instructions_input_items_and_one_namespace() { content: "late".to_owned(), }); assert_eq!( - request_body("gpt-test", &second_system, None), + request_body("gpt-test", None, &second_system, None), Err(ProviderError::InvalidConfiguration) ); } +#[test] +fn a_chosen_effort_is_sent_as_reasoning_effort_and_nothing_else_changes() { + // ADR-0102: the effort is the only reasoning option sent; with none, the + // body is exactly as before. + let tools = tool_definitions(); + for effort in ReasoningEffort::ALL { + for tools in [None, Some(tools.as_slice())] { + let with: Value = serde_json::from_slice( + &request_body("gpt-test", Some(effort), &messages(), tools).expect("body"), + ) + .expect("json"); + assert_eq!( + with["reasoning"], + serde_json::json!({ "effort": effort.as_str() }) + ); + let mut without: Value = serde_json::from_slice( + &request_body("gpt-test", None, &messages(), tools).expect("body"), + ) + .expect("json"); + assert!(without.get("reasoning").is_none()); + without["reasoning"] = with["reasoning"].clone(); + assert_eq!(with, without); + } + } +} + /// A tool turn after one call: the request, the model's interim text, and the /// source-labelled result of `list-1` (ADR-0097). fn tool_turn_messages(arguments: &str, result: &str) -> Vec { @@ -429,6 +455,7 @@ fn with_tools_a_tool_result_is_sent_as_its_call_and_output_items() { let tools = tool_definitions(); let body = request_body( "gpt-test", + None, &tool_turn_messages("{\"path\":\".\"}", "Tool result [call call_list_1]:\n[]"), Some(&tools), ) @@ -460,6 +487,7 @@ fn without_tools_a_tool_result_stays_a_labelled_user_message() { // No call item may name a function the request does not advertise. let body = request_body( "gpt-test", + None, &tool_turn_messages("{\"path\":\".\"}", "Tool result [call call_list_1]:\n[]"), None, ) @@ -490,10 +518,10 @@ fn a_tool_results_size_estimate_covers_its_encoded_items() { let content = "Tool result [call call_list_1]:\nok"; let with = tool_turn_messages(&arguments, content); let without = messages(); - let added_body = request_body("gpt-test", &with, Some(&tools)) + let added_body = request_body("gpt-test", None, &with, Some(&tools)) .expect("body") .len() - - request_body("gpt-test", &without, Some(&tools)) + - request_body("gpt-test", None, &without, Some(&tools)) .expect("body") .len(); let shared = |messages: &[ModelMessage]| { @@ -910,7 +938,7 @@ fn a_rejected_calls_placeholder_arguments_and_result_are_sent_as_a_paired_call_a content: "Tool error [call call_odd_1; source core_observed; untrusted workspace data]:\n{\"error\":\"unsupported_tool\"}".to_owned(), }); - let body = request_body("gpt-test", &messages, Some(&tools)).expect("body"); + let body = request_body("gpt-test", None, &messages, Some(&tools)).expect("body"); let value: Value = serde_json::from_slice(&body).expect("json"); let items = value["input"].as_array().expect("input items"); @@ -1008,7 +1036,7 @@ fn ten_tool_definitions() -> Vec { fn ten_tool_definitions_build_one_namespace_and_an_eleventh_is_refused_before_a_token_is_read() { let tools = ten_tool_definitions(); assert_eq!(tools.len(), 10); - let body = request_body("gpt-test", &messages(), Some(&tools)).expect("body"); + let body = request_body("gpt-test", None, &messages(), Some(&tools)).expect("body"); let value: Value = serde_json::from_slice(&body).expect("json"); let functions = value["tools"][0]["tools"].as_array().expect("functions"); assert_eq!(functions.len(), 10); diff --git a/crates/omgcode-core/src/session.rs b/crates/omgcode-core/src/session.rs index b247742..8fb31c3 100644 --- a/crates/omgcode-core/src/session.rs +++ b/crates/omgcode-core/src/session.rs @@ -16,6 +16,7 @@ use time::format_description::well_known::Rfc3339; use time::{OffsetDateTime, UtcOffset}; use uuid::Uuid; +use crate::provider::ReasoningEffort; use crate::storage::{self, StorageError}; mod discovery; @@ -444,6 +445,12 @@ impl SessionJournal { self.schema_version >= SCHEMA_VERSION } + /// Report whether this journal may record a request's reasoning effort + /// (ADR-0102). Only a version 3 journal may, as for a skill selection. + pub const fn supports_reasoning_effort(&self) -> bool { + self.schema_version >= SCHEMA_VERSION + } + /// Return the last fully validated durable snapshot. pub fn snapshot(&self) -> &SessionSnapshot { &self.snapshot @@ -1121,6 +1128,11 @@ pub struct RequestManifest { /// bytes. An older build refuses a journal that contains it. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub skills: Vec, + /// The reasoning effort the turn's model requests sent (ADR-0102). The + /// field is omitted when no effort was sent, so journals without one keep + /// their bytes. An older build refuses a journal that contains it. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub reasoning_effort: Option, } /// One skill the operator selected for a request: identity and digest only. @@ -1217,6 +1229,13 @@ fn validate_manifest(manifest: &RequestManifest, schema_version: u32) -> Result< "request manifest skills need a version 3 session", )); } + // The same holds for an effort (ADR-0102): a build that reads only an + // older journal's subset must never meet the field there. + if manifest.reasoning_effort.is_some() && schema_version < SCHEMA_VERSION { + return Err(SessionError::InvalidValue( + "request manifest reasoning effort needs a version 3 session", + )); + } if manifest.skills.len() > crate::skills::MAX_SELECTED_SKILLS { return Err(SessionError::InvalidValue( "request manifest lists more than 4 skills", diff --git a/crates/omgcode-core/tests/approval_review.rs b/crates/omgcode-core/tests/approval_review.rs index 8e0ec30..98f0f68 100644 --- a/crates/omgcode-core/tests/approval_review.rs +++ b/crates/omgcode-core/tests/approval_review.rs @@ -245,6 +245,7 @@ fn manifest() -> RequestManifest { tool_schema_version: None, tools: None, skills: Vec::new(), + reasoning_effort: None, } } diff --git a/crates/omgcode-core/tests/session_index.rs b/crates/omgcode-core/tests/session_index.rs index 27b60f2..7c9bed8 100644 --- a/crates/omgcode-core/tests/session_index.rs +++ b/crates/omgcode-core/tests/session_index.rs @@ -47,6 +47,7 @@ fn manifest() -> RequestManifest { tool_schema_version: Some("1".into()), tools: Some(vec!["workspace_read_file".into()]), skills: Vec::new(), + reasoning_effort: None, } } diff --git a/crates/omgcode-core/tests/session_inspection.rs b/crates/omgcode-core/tests/session_inspection.rs index 29fdf6a..9bb3fcd 100644 --- a/crates/omgcode-core/tests/session_inspection.rs +++ b/crates/omgcode-core/tests/session_inspection.rs @@ -40,6 +40,7 @@ fn manifest() -> RequestManifest { tool_schema_version: Some("1".into()), tools: Some(vec!["workspace_read_file".into(), "workspace_list".into()]), skills: Vec::new(), + reasoning_effort: None, } } diff --git a/crates/omgcode-core/tests/session_lifecycle.rs b/crates/omgcode-core/tests/session_lifecycle.rs index dc08fcf..3b63ecb 100644 --- a/crates/omgcode-core/tests/session_lifecycle.rs +++ b/crates/omgcode-core/tests/session_lifecycle.rs @@ -30,6 +30,7 @@ fn manifest() -> RequestManifest { tool_schema_version: None, tools: None, skills: Vec::new(), + reasoning_effort: None, } } diff --git a/crates/omgcode-core/tests/session_tool_events.rs b/crates/omgcode-core/tests/session_tool_events.rs index e499e75..4992514 100644 --- a/crates/omgcode-core/tests/session_tool_events.rs +++ b/crates/omgcode-core/tests/session_tool_events.rs @@ -1,6 +1,7 @@ use std::fs; use std::path::{Path, PathBuf}; +use omgcode_core::provider::ReasoningEffort; use omgcode_core::session::{ ManifestSkill, MessageRole, RequestManifest, SessionError, SessionJournal, ToolOutcome, }; @@ -547,6 +548,7 @@ fn a_schema_v2_journal_keeps_recording_and_replaying_tool_manifests() { tool_schema_version: Some("1".into()), tools: Some(vec!["workspace_read_file".into()]), skills: Vec::new(), + reasoning_effort: None, }; let mut journal = SessionJournal::open(&path).expect("open schema-v2 journal"); @@ -590,6 +592,7 @@ fn given_a_version_2_journal_when_a_skill_manifest_is_recorded_or_replayed_then_ tool_schema_version: None, tools: None, skills, + reasoning_effort: None, }; // The journal API refuses the field on a writable version 2 journal. @@ -644,6 +647,97 @@ fn given_a_version_2_journal_when_a_skill_manifest_is_recorded_or_replayed_then_ .expect("schema v3 accepts a skill manifest"); } +/// A reasoning effort (ADR-0102) follows the skills rule: only a version 3 +/// journal records or replays it, and a manifest without one omits the field. +#[test] +fn given_a_version_2_journal_when_an_effort_manifest_is_recorded_or_replayed_then_it_is_refused() { + let manifest = RequestManifest { + base_prompt: "base instructions".into(), + prompt_version: "1".into(), + prompt_sha256: "a".repeat(64), + custom_instructions: String::new(), + model: "local-model".into(), + base_url: "http://127.0.0.1:1234/v1".into(), + context_tokens: 32_000, + max_output_tokens: 2_000, + tool_schema_version: None, + tools: None, + skills: Vec::new(), + reasoning_effort: Some(ReasoningEffort::High), + }; + let without = RequestManifest { + reasoning_effort: None, + ..manifest.clone() + }; + assert!( + serde_json::to_value(&without) + .expect("manifest JSON") + .get("reasoning_effort") + .is_none() + ); + + // The journal API refuses the field on a writable version 2 journal. + let (_temporary, path, session_id) = setup(); + let first = rewrite_first_event_schema(&path, 2); + let mut journal = SessionJournal::open(&path).expect("open schema-v2 journal"); + assert!(!journal.supports_reasoning_effort()); + let request_id = journal.start_turn().expect("start turn"); + journal + .record_message(MessageRole::User, "think") + .expect("user message"); + assert!(matches!( + journal.record_manifest(request_id, manifest.clone()), + Err(SessionError::InvalidValue(_)) + )); + drop(journal); + + // Replay refuses a version 2 line that carries it. + let payload = json!({ + "request_id": Uuid::nil(), + "manifest": serde_json::to_value(&manifest).expect("manifest JSON"), + }); + assert_eq!(payload["manifest"]["reasoning_effort"], "high"); + write_events( + &path, + &[ + first, + event( + session_id, + 1, + 2, + "turn.started", + json!({"request_id": Uuid::nil()}), + ), + event(session_id, 2, 2, "request.manifest", payload), + ], + ); + assert!(matches!( + SessionJournal::open(&path), + Err(SessionError::InvalidJournal(_)) + )); + + // A version 3 journal records it and replays it. + let (_temporary, path, _session_id) = setup(); + let mut journal = SessionJournal::open(&path).expect("open schema-v3 journal"); + assert!(journal.supports_reasoning_effort()); + let request_id = journal.start_turn().expect("start turn"); + journal + .record_message(MessageRole::User, "think") + .expect("user message"); + journal + .record_manifest(request_id, manifest) + .expect("schema v3 accepts an effort"); + journal.complete_turn(request_id).expect("complete turn"); + drop(journal); + SessionJournal::open(&path).expect("replay a schema-v3 effort"); + let recorded = read_events(&path); + assert!( + recorded + .iter() + .any(|event| event["payload"]["manifest"]["reasoning_effort"] == "high") + ); +} + /// Argument JSON of exactly `bytes` bytes whose second JSON escaping inside the /// `tool.requested` event is as large as the strict-JSON grammar allows. fn worst_case_arguments(shape: &str, bytes: usize) -> String { diff --git a/crates/omgcode-core/tests/turn_runtime.rs b/crates/omgcode-core/tests/turn_runtime.rs index 3ac7079..8ca710b 100644 --- a/crates/omgcode-core/tests/turn_runtime.rs +++ b/crates/omgcode-core/tests/turn_runtime.rs @@ -312,6 +312,7 @@ fn manifest() -> RequestManifest { tool_schema_version: None, tools: None, skills: Vec::new(), + reasoning_effort: None, } } @@ -2937,6 +2938,7 @@ fn an_older_schema_session_replays_and_accepts_a_new_turn(version: &str, tools: tool_schema_version: Some(version.into()), tools: Some(tools.iter().map(|name| (*name).to_owned()).collect()), skills: Vec::new(), + reasoning_effort: None, ..manifest() }, ) diff --git a/crates/omgcode-core/tests/web_fetch_tool.rs b/crates/omgcode-core/tests/web_fetch_tool.rs index 1f2ca9c..63562b9 100644 --- a/crates/omgcode-core/tests/web_fetch_tool.rs +++ b/crates/omgcode-core/tests/web_fetch_tool.rs @@ -424,6 +424,7 @@ fn manifest() -> RequestManifest { tool_schema_version: None, tools: None, skills: Vec::new(), + reasoning_effort: None, } } diff --git a/crates/omgcode-desktop/capabilities/main.json b/crates/omgcode-desktop/capabilities/main.json index 885c208..80a251b 100644 --- a/crates/omgcode-desktop/capabilities/main.json +++ b/crates/omgcode-desktop/capabilities/main.json @@ -33,6 +33,7 @@ "allow-connection-status", "allow-connection-select", "allow-session-model-select", + "allow-session-effort-select", "allow-chat-models", "allow-session-context-breakdown", "allow-session-processes", diff --git a/crates/omgcode-desktop/src/command_names.rs b/crates/omgcode-desktop/src/command_names.rs index f883e45..86510d5 100644 --- a/crates/omgcode-desktop/src/command_names.rs +++ b/crates/omgcode-desktop/src/command_names.rs @@ -33,6 +33,7 @@ pub const COMMAND_NAMES: &[&str] = &[ "connection_status", "connection_select", "session_model_select", + "session_effort_select", "chat_models", "session_context_breakdown", "settings_overview", diff --git a/crates/omgcode-desktop/src/commands/chat.rs b/crates/omgcode-desktop/src/commands/chat.rs index 2b72140..512ebef 100644 --- a/crates/omgcode-desktop/src/commands/chat.rs +++ b/crates/omgcode-desktop/src/commands/chat.rs @@ -4,8 +4,8 @@ use omgcode_app::desktop::{ ChatDefaults, ChatEvent, ChatEventSink, ChatModels, ChatPreferencesSaveRequest, ChatSendRequest, ChatSettingsDto, ChatStatus, ComposerPreferencesDto, ConnectionChooseRequest, - ConnectionStatus, ConnectionStatusRequest, ContextBreakdown, SessionContext, - SessionModelSelectRequest, SessionRequest, SessionSkills, + ConnectionStatus, ConnectionStatusRequest, ContextBreakdown, ReasoningEffort, SessionContext, + SessionEffortSelectRequest, SessionModelSelectRequest, SessionRequest, SessionSkills, }; use tauri::Webview; use tauri::ipc::Channel; @@ -154,6 +154,34 @@ pub async fn session_model_select( blocking(&state, move |service| service.session_model_select(request)).await } +/// `main` only. Records the reasoning effort chosen for one session, or none +/// for `null` (ADR-0102). No dialog: an effort grants nothing, and the server +/// still decides whether its model takes the value. Only the seven documented +/// names deserialize. +/// +/// # Errors +/// +/// `forbidden_window`, or the service's error (`invalid_request` for an +/// effort the session's connection does not take, `not_found`, +/// `session_choices`). +#[tauri::command(rename_all = "snake_case")] +pub async fn session_effort_select( + webview: Webview, + state: Service<'_>, + session_id: Uuid, + reasoning_effort: Option, +) -> Result { + authorize(Command::SessionEffortSelect, webview.label())?; + let request = SessionEffortSelectRequest { + session_id, + reasoning_effort, + }; + blocking(&state, move |service| { + service.session_effort_select(request) + }) + .await +} + /// `main` only. Lists the models a session's connection reports, for the /// composer's model choice (ADR-0066, ADR-0071). Ids only; the list grants /// nothing. diff --git a/crates/omgcode-desktop/src/lib.rs b/crates/omgcode-desktop/src/lib.rs index caf12bd..2e8feb9 100644 --- a/crates/omgcode-desktop/src/lib.rs +++ b/crates/omgcode-desktop/src/lib.rs @@ -176,6 +176,7 @@ fn run_app(service: Arc) -> ExitCode { commands::chat::connection_status, commands::chat::connection_select, commands::chat::session_model_select, + commands::chat::session_effort_select, commands::chat::chat_models, commands::chat::session_context_breakdown, commands::settings::settings_overview, diff --git a/crates/omgcode-desktop/src/policy.rs b/crates/omgcode-desktop/src/policy.rs index 0085b7c..26c5302 100644 --- a/crates/omgcode-desktop/src/policy.rs +++ b/crates/omgcode-desktop/src/policy.rs @@ -68,6 +68,7 @@ pub enum Command { ConnectionStatus, ConnectionSelect, SessionModelSelect, + SessionEffortSelect, ChatModels, SessionContextBreakdown, SettingsOverview, @@ -105,7 +106,7 @@ pub enum Command { impl Command { /// All commands, in the order of `command_names.rs`. - pub const ALL: [Self; 62] = [ + pub const ALL: [Self; 63] = [ Self::AppInfo, Self::SessionTree, Self::SessionSearch, @@ -135,6 +136,7 @@ impl Command { Self::ConnectionStatus, Self::ConnectionSelect, Self::SessionModelSelect, + Self::SessionEffortSelect, Self::ChatModels, Self::SessionContextBreakdown, Self::SettingsOverview, @@ -203,6 +205,7 @@ impl Command { Self::ConnectionStatus => "connection_status", Self::ConnectionSelect => "connection_select", Self::SessionModelSelect => "session_model_select", + Self::SessionEffortSelect => "session_effort_select", Self::ChatModels => "chat_models", Self::SessionContextBreakdown => "session_context_breakdown", Self::SettingsOverview => "settings_overview", @@ -301,6 +304,7 @@ impl Command { | Self::ConnectionStatus | Self::ConnectionSelect | Self::SessionModelSelect + | Self::SessionEffortSelect | Self::ChatModels | Self::SessionContextBreakdown | Self::SessionProcesses @@ -342,8 +346,8 @@ mod tests { #[test] fn every_command_has_exactly_one_window_and_the_counts_match() { - assert_eq!(Command::ALL.len(), 62); - assert_eq!(with_window(WindowLabel::Main).len(), 30); + assert_eq!(Command::ALL.len(), 63); + assert_eq!(with_window(WindowLabel::Main).len(), 31); assert_eq!(with_window(WindowLabel::Approvals).len(), 3); assert_eq!(with_window(WindowLabel::Settings).len(), 29); } @@ -449,8 +453,8 @@ mod tests { #[test] fn shared_name_list_has_unique_names_matching_the_enum() { let shared: BTreeSet<&str> = COMMAND_NAMES.iter().copied().collect(); - assert_eq!(COMMAND_NAMES.len(), 62); - assert_eq!(shared.len(), 62); + assert_eq!(COMMAND_NAMES.len(), 63); + assert_eq!(shared.len(), 63); let from_enum: Vec<&str> = Command::ALL.iter().map(|c| c.name()).collect(); assert_eq!(from_enum, COMMAND_NAMES); } diff --git a/crates/omgcode-desktop/tests/layers.rs b/crates/omgcode-desktop/tests/layers.rs index 499e4c4..c107484 100644 --- a/crates/omgcode-desktop/tests/layers.rs +++ b/crates/omgcode-desktop/tests/layers.rs @@ -248,15 +248,15 @@ fn build_script_declares_the_shared_command_list() { assert!(build.contains("include!(\"src/command_names.rs\")")); assert!(build.contains(".commands(COMMAND_NAMES)")); - // And the shared list holds the 62 unique policy names. + // And the shared list holds the 63 unique policy names. let listed: Vec<&str> = COMMAND_NAMES_SOURCE .lines() .filter_map(|line| line.trim().strip_prefix('"')) .filter_map(|rest| rest.strip_suffix("\",")) .collect(); let unique: BTreeSet<&str> = listed.iter().copied().collect(); - assert_eq!(listed.len(), 62); - assert_eq!(unique.len(), 62); + assert_eq!(listed.len(), 63); + assert_eq!(unique.len(), 63); let policy: Vec<&str> = Command::ALL.into_iter().map(Command::name).collect(); assert_eq!(listed, policy); } @@ -344,13 +344,13 @@ fn frontend_clients_call_only_commands_the_policy_gives_their_window() { ); let main_calls: BTreeSet = main_calls.union(&channel_calls).cloned().collect(); - // Then the main side uses a subset of the main commands (all 30 today)... + // Then the main side uses a subset of the main commands (all 31 today)... let main_commands: BTreeSet = commands_for(WindowLabel::Main) .into_iter() .map(str::to_owned) .collect(); assert!(main_calls.is_subset(&main_commands), "{main_calls:?}"); - assert_eq!(main_calls.len(), 30); + assert_eq!(main_calls.len(), 31); assert_eq!(main_calls, main_commands); // ...the approvals client uses exactly the three approval commands... @@ -367,7 +367,7 @@ fn frontend_clients_call_only_commands_the_policy_gives_their_window() { .collect(); assert_eq!(settings_calls, settings_commands); - // ...and together they cover all 62 policy commands. + // ...and together they cover all 63 policy commands. let union: BTreeSet = main_calls .union(&approval_calls) .cloned() @@ -625,10 +625,10 @@ fn generate_handler_registers_exactly_the_policy_commands() { .map(|entry| entry.rsplit("::").next().expect("segment")) .collect(); - // Then they are the 62 shared names, once each. + // Then they are the 63 shared names, once each. let unique: BTreeSet<&str> = registered.iter().copied().collect(); - assert_eq!(registered.len(), 62); - assert_eq!(unique.len(), 62); + assert_eq!(registered.len(), 63); + assert_eq!(unique.len(), 63); let shared: BTreeSet<&str> = COMMAND_NAMES_SOURCE .lines() .filter_map(|line| line.trim().strip_prefix('"')) @@ -645,7 +645,7 @@ fn generate_handler_registers_exactly_the_policy_commands() { #[test] fn every_handler_authorizes_its_own_command_before_touching_the_service() { let handlers = all_handlers(); - assert_eq!(handlers.len(), 62); + assert_eq!(handlers.len(), 63); for handler in handlers { // Given the command the function name denotes. let command = Command::ALL @@ -779,7 +779,7 @@ fn handler_parameters_match_the_keys_the_frontend_passes() { } assert_eq!( expected.len(), - 62, + 63, "all commands are called by the frontend" ); diff --git a/crates/omgcode-desktop/ui/src/ipc/client.ts b/crates/omgcode-desktop/ui/src/ipc/client.ts index 8f4e92c..692b66d 100644 --- a/crates/omgcode-desktop/ui/src/ipc/client.ts +++ b/crates/omgcode-desktop/ui/src/ipc/client.ts @@ -10,6 +10,7 @@ import type { ConnectionStatus, ContextBreakdown, GitStatusView, + ReasoningEffort, SearchResult, SessionContext, SessionProcesses, @@ -148,6 +149,11 @@ export const api = { /** Records the session's model. No dialog: a model grants nothing. */ sessionModelSelect: (sessionId: string, model: string) => invokeCommand("session_model_select", { session_id: sessionId, model }), + sessionEffortSelect: (sessionId: string, effort: ReasoningEffort | null) => + invokeCommand("session_effort_select", { + session_id: sessionId, + reasoning_effort: effort, + }), chatStatus: (sessionId: string) => invokeCommand("chat_status", { session_id: sessionId }), chatCancel: (sessionId: string) => diff --git a/crates/omgcode-desktop/ui/src/ipc/types.ts b/crates/omgcode-desktop/ui/src/ipc/types.ts index 3793993..5eb34b7 100644 --- a/crates/omgcode-desktop/ui/src/ipc/types.ts +++ b/crates/omgcode-desktop/ui/src/ipc/types.ts @@ -114,8 +114,16 @@ export interface ChatSettings { instructions: string; compact_threshold: number; auto_compact: boolean; + /** The reasoning effort the turn sends; `null` or absent sends none (ADR-0102). */ + reasoning_effort?: ReasoningEffort | null; } +/** + * A documented reasoning effort (ADR-0102), from the least reasoning to the most. Rust refuses + * any other name. "No effort" is `null`, which is not the provider's own `none`. + */ +export type ReasoningEffort = "none" | "minimal" | "low" | "medium" | "high" | "xhigh" | "max"; + export interface ContextMeter { estimated_tokens: number; trigger_tokens: number; @@ -384,6 +392,10 @@ export interface ConnectionStatus { origin: ConnectionOrigin; /** The model chosen for the session, or the saved chat preference's model when it has none. */ model: string; + /** The reasoning effort chosen for the session, or `null` for none (ADR-0102). */ + reasoning_effort: ReasoningEffort | null; + /** The efforts the connection takes; empty when it takes none (ADR-0102). */ + reasoning_efforts: ReasoningEffort[]; /** The recorded choice no longer holds; the next turn is refused until the operator chooses again. */ stale: boolean; /** The per-session choices file could not be read and is treated as empty. */ diff --git a/crates/omgcode-desktop/ui/src/main/composer.ts b/crates/omgcode-desktop/ui/src/main/composer.ts index 704e6a4..c4aebfd 100644 --- a/crates/omgcode-desktop/ui/src/main/composer.ts +++ b/crates/omgcode-desktop/ui/src/main/composer.ts @@ -270,6 +270,7 @@ export function createComposer( return { endpoint: fixedEndpoint, model: modelBox.model(), + reasoning_effort: modelBox.effort(), context_tokens: budgets?.context_tokens ?? 0, max_output_tokens: budgets?.max_output_tokens ?? 0, max_tool_calls: budgets?.max_tool_calls ?? 0, diff --git a/crates/omgcode-desktop/ui/src/main/connection_state.ts b/crates/omgcode-desktop/ui/src/main/connection_state.ts index eb70229..4b34513 100644 --- a/crates/omgcode-desktop/ui/src/main/connection_state.ts +++ b/crates/omgcode-desktop/ui/src/main/connection_state.ts @@ -1,6 +1,6 @@ import { api } from "../ipc/client"; import { CANCELLED_CODE, toIpcError } from "../ipc/errors"; -import type { ConnectionStatus } from "../ipc/types"; +import type { ConnectionStatus, ReasoningEffort } from "../ipc/types"; /** Shown when the operator closes the confirmation or answers No. */ export const CONNECTION_UNCHANGED = "The model provider was not changed."; @@ -8,10 +8,17 @@ export const CONNECTION_UNCHANGED = "The model provider was not changed."; /** * Why the connection state changed. `opening` means a different session was named and its * status has not arrived; `read` is a status read; `selected` is a confirmed provider choice - * (Rust cleared the session's model); `model` is a model choice, or its failure; `busy` and - * `message` change only what the dropdowns show. + * (Rust cleared the session's model and effort); `model` is a model choice and `effort` an + * effort choice (ADR-0102); `busy` and `message` change only what the dropdowns show. */ -export type ConnectionChange = "opening" | "read" | "selected" | "model" | "busy" | "message"; +export type ConnectionChange = + | "opening" + | "read" + | "selected" + | "model" + | "effort" + | "busy" + | "message"; export interface ConnectionModel { /** The open session, or `null` when none is open. */ @@ -35,6 +42,8 @@ export interface ConnectionModel { select(profile: string | null): Promise; /** Records the model for the open session. */ chooseModel(model: string): Promise; + /** Records the reasoning effort for the open session, or none for `null` (ADR-0102). */ + chooseEffort(effort: ReasoningEffort | null): Promise; dispose(): void; } @@ -51,19 +60,22 @@ export function createConnectionModel(): ConnectionModel { let note = ""; /** Counts reads; an answer is used only when no later read or choice began. */ let generation = 0; - /** Counts model choices; only the latest one's answer is used, so the operator's last pick wins. */ - let modelCalls = 0; - /** Counts accepted provider choices; a model answer from before one is stale. */ + /** + * Counts model and effort choices together; only the latest one's answer is used, so the + * operator's last pick wins. Writes run in order, so the latest answer holds every earlier one. + */ + let saveCalls = 0; + /** Counts accepted provider choices; a model or effort answer from before one is stale. */ let providerCalls = 0; /** - * Model saves not yet answered, by session. While one is pending a status read could still - * hold the old model, so its answer is dropped: the save's own answer is the newer truth. + * Model and effort saves not yet answered, by session. While one is pending a status read could + * still hold the old choice, so its answer is dropped: the save's own answer is the newer truth. */ - const pendingModels = new Map(); + const pendingSaves = new Map(); /** - * Sessions whose status read was dropped for a pending model save. The read is repeated once - * the last save settles, even when that save's own answer is discarded, so the session never - * stays without a status. + * Sessions whose status read was dropped for a pending save. The read is repeated once the + * last save settles, even when that save's own answer is discarded, so the session never stays + * without a status. */ const droppedReads = new Set(); /** @@ -94,18 +106,18 @@ export function createConnectionModel(): ConnectionModel { return run; } - function modelSavePending(id: string | null): boolean { - return id !== null && (pendingModels.get(id) ?? 0) > 0; + function savePending(id: string | null): boolean { + return id !== null && (pendingSaves.get(id) ?? 0) > 0; } - /** Settles one model save; true when it was the session's last and a read was dropped. */ - function settleModelSave(id: string): boolean { - const left = (pendingModels.get(id) ?? 1) - 1; + /** Settles one save; true when it was the session's last and a read was dropped. */ + function settleSave(id: string): boolean { + const left = (pendingSaves.get(id) ?? 1) - 1; if (left > 0) { - pendingModels.set(id, left); + pendingSaves.set(id, left); return false; } - pendingModels.delete(id); + pendingSaves.delete(id); return droppedReads.delete(id); } @@ -118,7 +130,7 @@ export function createConnectionModel(): ConnectionModel { if (disposed || mine !== generation || session !== id) { return; } - if (id !== null && modelSavePending(id)) { + if (id !== null && savePending(id)) { droppedReads.add(id); return; } @@ -172,6 +184,55 @@ export function createConnectionModel(): ConnectionModel { emit("selected"); } + /** + * Records a model or effort choice for the open session without a dialog. `write` is the IPC + * call; `change` is emitted with its answer. + */ + async function saveChoice( + write: (id: string) => Promise, + change: "model" | "effort", + ): Promise { + const id = session; + if (id === null) { + return; + } + saveCalls += 1; + const mine = saveCalls; + const provider = providerCalls; + const stale = (): boolean => + disposed || session !== id || mine !== saveCalls || provider !== providerCalls; + note = ""; + // A status read already in flight may hold the old choice; it must not undo this one. + generation += 1; + pendingSaves.set(id, (pendingSaves.get(id) ?? 0) + 1); + let status: ConnectionStatus | null = null; + let failure: unknown = null; + try { + status = await enqueue(() => write(id)); + } catch (reason) { + failure = reason; + } + const repeatRead = settleSave(id); + if (stale()) { + // This answer is discarded, but a read dropped while it was pending must still happen, + // or a reopened session would stay without a status. + if (repeatRead && !disposed && session === id) { + await read(); + } + return; + } + if (status !== null) { + current = status; + generation += 1; + emit(change); + return; + } + note = describe(failure); + emit("message"); + // The recorded choice decides what the dropdown shows after a failure. + await read(); + } + return { sessionId: () => session, status: () => current, @@ -200,47 +261,8 @@ export function createConnectionModel(): ConnectionModel { } }, select: chooseProvider, - async chooseModel(model) { - const id = session; - if (id === null) { - return; - } - modelCalls += 1; - const mine = modelCalls; - const provider = providerCalls; - const stale = (): boolean => - disposed || session !== id || mine !== modelCalls || provider !== providerCalls; - note = ""; - // A status read already in flight may hold the old model; it must not undo this choice. - generation += 1; - pendingModels.set(id, (pendingModels.get(id) ?? 0) + 1); - let status: ConnectionStatus | null = null; - let failure: unknown = null; - try { - status = await enqueue(() => api.sessionModelSelect(id, model)); - } catch (reason) { - failure = reason; - } - const repeatRead = settleModelSave(id); - if (stale()) { - // This answer is discarded, but a read dropped while it was pending must still happen, - // or a reopened session would stay without a status. - if (repeatRead && !disposed && session === id) { - await read(); - } - return; - } - if (status !== null) { - current = status; - generation += 1; - emit("model"); - return; - } - note = describe(failure); - emit("message"); - // The recorded model decides what the dropdown shows after a failure. - await read(); - }, + chooseModel: (model) => saveChoice((id) => api.sessionModelSelect(id, model), "model"), + chooseEffort: (effort) => saveChoice((id) => api.sessionEffortSelect(id, effort), "effort"), dispose() { disposed = true; listeners.clear(); diff --git a/crates/omgcode-desktop/ui/src/main/effort_select.ts b/crates/omgcode-desktop/ui/src/main/effort_select.ts new file mode 100644 index 0000000..82703d4 --- /dev/null +++ b/crates/omgcode-desktop/ui/src/main/effort_select.ts @@ -0,0 +1,95 @@ +import { el } from "../dom"; +import type { ReasoningEffort } from "../ipc/types"; +import type { ConnectionModel } from "./connection_state"; + +/** The value of the entry that sends no effort, so the provider's own default applies. */ +export const DEFAULT_EFFORT = ""; + +/** Shown under the dropdown when the session's connection takes no effort (ADR-0102). */ +export const EFFORT_NOT_TAKEN = "This connection does not take an effort setting."; + +/** The label of each effort the core accepts, in the order the dropdown lists them. */ +export const EFFORT_LABELS: Readonly> = { + none: "None", + minimal: "Minimal", + low: "Low", + medium: "Medium", + high: "High", + xhigh: "Extra high", + max: "Max", +}; + +const EFFORT_ORDER = Object.keys(EFFORT_LABELS) as ReasoningEffort[]; + +export interface EffortSelect { + element: HTMLSelectElement; + /** The note shown when the connection takes no effort; hidden otherwise. */ + note: HTMLElement; + /** Draws the options from the connection state. Called on every change. */ + render(): void; + /** Keeps the dropdown disabled while `locked`, for example while a turn runs. */ + setLocked(locked: boolean): void; + /** The chosen effort, or `null` for the provider's default or a connection that takes none. */ + value(): ReasoningEffort | null; +} + +/** + * The reasoning effort dropdown of the open session (ADR-0102). It offers only what Rust reports + * the session's connection accepts; Rust refuses anything else again on save and on send. The + * values are a closed list, so no server text reaches an option. + */ +export function createEffortSelect(connection: ConnectionModel): EffortSelect { + const element = el("select", { class: "status-provider", attrs: { "aria-label": "Effort" } }); + element.disabled = true; + const note = el("span", { class: "muted", text: EFFORT_NOT_TAKEN, attrs: { role: "status" } }); + note.hidden = true; + let baseDisabled = true; + let locked = false; + + function offered(): readonly ReasoningEffort[] { + const accepted = connection.status()?.reasoning_efforts ?? []; + return EFFORT_ORDER.filter((effort) => accepted.includes(effort)); + } + + function apply(): void { + element.disabled = baseDisabled || locked; + } + + function render(): void { + const status = connection.status(); + const efforts = offered(); + element.replaceChildren(el("option", { text: "Default", attrs: { value: DEFAULT_EFFORT } })); + for (const effort of efforts) { + element.append(el("option", { text: EFFORT_LABELS[effort], attrs: { value: effort } })); + } + const chosen = status?.reasoning_effort ?? null; + element.value = chosen !== null && efforts.includes(chosen) ? chosen : DEFAULT_EFFORT; + note.hidden = status === null || efforts.length > 0; + baseDisabled = + status === null || + efforts.length === 0 || + connection.busy() || + connection.sessionId() === null; + apply(); + } + + element.addEventListener("change", () => { + const chosen = EFFORT_ORDER.find((effort) => effort === element.value) ?? null; + void connection.chooseEffort(chosen); + }); + + return { + element, + note, + render, + setLocked(next) { + locked = next; + apply(); + }, + value() { + const efforts = offered(); + const chosen = EFFORT_ORDER.find((effort) => effort === element.value) ?? null; + return chosen !== null && efforts.includes(chosen) ? chosen : null; + }, + }; +} diff --git a/crates/omgcode-desktop/ui/src/main/model_box.ts b/crates/omgcode-desktop/ui/src/main/model_box.ts index f621a2f..0d52ec0 100644 --- a/crates/omgcode-desktop/ui/src/main/model_box.ts +++ b/crates/omgcode-desktop/ui/src/main/model_box.ts @@ -1,6 +1,8 @@ import { el, replaceChildren } from "../dom"; +import type { ReasoningEffort } from "../ipc/types"; import { isHostedKind } from "../providers"; import type { ConnectionChange, ConnectionModel } from "./connection_state"; +import { createEffortSelect } from "./effort_select"; import { createModelPicker } from "./model_picker"; import { createProviderSelect } from "./provider_select"; @@ -18,6 +20,8 @@ export interface ModelBox { element: HTMLElement; /** The chosen model id, or an empty string when none is chosen. */ model(): string; + /** The chosen reasoning effort, or `null` to send none (ADR-0102). */ + effort(): ReasoningEffort | null; /** Disabled while no session accepts a message or a turn runs; the composer sets it. */ setEnabled(enabled: boolean): void; /** Called when the chosen model or the listed models change; returns the unsubscribe function. */ @@ -30,7 +34,8 @@ export interface ModelBox { * controls and the same shared connection the composer used to hold: only the place changed. A * different session, a confirmed provider choice, or a changed connection clears the model and * lists the new session's models; the model shown is always the one the connection holds. The - * composer asks `model()` for each send, so a send uses what the box shows. + * Effort dropdown offers what the connection accepts (ADR-0102). The composer asks `model()` and + * `effort()` for each send, so a send uses what the box shows. */ export function createModelBox(connection: ConnectionModel): ModelBox { const listeners = new Set<() => void>(); @@ -57,6 +62,7 @@ export function createModelBox(connection: ConnectionModel): ModelBox { (id) => void connection.chooseModel(id), ); const providerSelect = createProviderSelect(connection, "Provider"); + const effortSelect = createEffortSelect(connection); /** What the model list was last requested for, so only a real change reloads it. */ let loadedKey: string | null = null; let enabled = false; @@ -64,6 +70,7 @@ export function createModelBox(connection: ConnectionModel): ModelBox { function refresh(): void { picker.setDisabled(!enabled || connection.busy()); providerSelect.setLocked(!enabled); + effortSelect.setLocked(!enabled); replaceChildren(providerNote, connection.message()); providerNote.hidden = connection.message() === ""; choicesNote.hidden = connection.status()?.session_choices_unreadable !== true; @@ -71,6 +78,7 @@ export function createModelBox(connection: ConnectionModel): ModelBox { function onConnection(change: ConnectionChange): void { providerSelect.render(); + effortSelect.render(); const status = connection.status(); const id = connection.sessionId(); if (change === "opening") { @@ -78,6 +86,8 @@ export function createModelBox(connection: ConnectionModel): ModelBox { picker.reset(); picker.setHosted(false); } else if (status !== null && id !== null && change !== "busy" && change !== "message") { + // An effort answer can be a reopened session's first status (its read was dropped while + // the save was pending), so it loads the list like a read; the key stops a needless reload. picker.setHosted(isHostedKind(status.connection.kind)); const key = [ id, @@ -99,6 +109,7 @@ export function createModelBox(connection: ConnectionModel): ModelBox { } const unsubscribe = connection.subscribe(onConnection); providerSelect.render(); + effortSelect.render(); refresh(); const element = el( @@ -112,11 +123,13 @@ export function createModelBox(connection: ConnectionModel): ModelBox { providerSelect.element, ), el("div", { class: "model-box-field" }, el("span", { text: "Model" }), picker.element), + el("label", { class: "model-box-field" }, el("span", { text: "Effort" }), effortSelect.element), el( "div", { class: "model-box-status" }, picker.note, picker.warning, + effortSelect.note, providerNote, choicesNote, ), @@ -125,6 +138,7 @@ export function createModelBox(connection: ConnectionModel): ModelBox { return { element, model: () => picker.value(), + effort: () => effortSelect.value(), setEnabled(next) { if (next !== enabled) { enabled = next; diff --git a/crates/omgcode-desktop/ui/src/mock/backend.ts b/crates/omgcode-desktop/ui/src/mock/backend.ts index d592534..35a8e2b 100644 --- a/crates/omgcode-desktop/ui/src/mock/backend.ts +++ b/crates/omgcode-desktop/ui/src/mock/backend.ts @@ -17,8 +17,10 @@ import type { ContextBreakdown, ContextPart, ContextPartId, + FixedHostedKind, PermissionFlags, ProcessEntry, + ReasoningEffort, SearchHit, SessionProcesses, SessionSummary, @@ -55,6 +57,27 @@ const TOKEN_LIFETIME_MS = 120_000; const MOCK_ENDPOINT = "http://127.0.0.1:1234/v1"; /** A mock session's record that follows the global default (a model chosen, no provider). */ const FOLLOW = Symbol("follow"); +/** Every effort core accepts, in its order (ADR-0102). */ +const REASONING_EFFORTS: readonly ReasoningEffort[] = [ + "none", + "minimal", + "low", + "medium", + "high", + "xhigh", + "max", +]; +/** The fixed hosted kinds whose documented endpoint takes `reasoning_effort`: core's `EFFORT_ENDPOINTS` (ADR-0102). */ +const EFFORT_KINDS: ReadonlySet = new Set([ + "ollama_cloud", + "openai", + "google", + "moonshot", + "minimax", + "open_router", + "z_ai", + "xai", +]); interface Fail { code: string; @@ -263,7 +286,12 @@ export function createMockBackend(now: () => number = Date.now): { invoke: Invok */ const sessionChoices = new Map< string, - { profile: string | null | typeof FOLLOW; endpoint: string | null; model: string } + { + profile: string | null | typeof FOLLOW; + endpoint: string | null; + model: string; + effort: ReasoningEffort | null; + } >(); /** The workspace each session created here belongs to, as core records it. */ const sessionWorkspaces = new Map(); @@ -533,6 +561,10 @@ export function createMockBackend(now: () => number = Date.now): { invoke: Invok if (message.trim() === "" || settings.model.trim() === "") { fail("invalid_argument", "A message and a model are required."); } + const effort = settings.reasoning_effort ?? null; + if (effort !== null && !acceptedEfforts(id).includes(effort)) { + fail("invalid_request", "This connection does not take a reasoning effort."); + } appendManifest(item, settings.model); append(item, "user", message); item.summary.status = "running"; @@ -1129,10 +1161,12 @@ export function createMockBackend(now: () => number = Date.now): { invoke: Invok if (!staleChoice(id) && (effectiveConnection(id).profile ?? null) === wanted) { fail("control", "this is already the connection of this session"); } + // Accepted efforts depend on the provider, so the choice clears it with the model. sessionChoices.set(id, { profile: wanted, endpoint: profile === null ? MOCK_ENDPOINT : profile.endpoint, model: "", + effort: null, }); return connectionStatus(id); } @@ -1149,6 +1183,30 @@ export function createMockBackend(now: () => number = Date.now): { invoke: Invok profile: existing === undefined ? FOLLOW : existing.profile, endpoint: existing === undefined ? null : existing.endpoint, model, + effort: existing?.effort ?? null, + }); + return connectionStatus(id); + } + // One session's reasoning effort (ADR-0102). Like Rust: only the seven names, and only for + // a connection that takes one. + case "session_effort_select": { + const id = str(args, "session_id"); + session(id); + const wanted = args.reasoning_effort ?? null; + const effort = + wanted === null ? null : (REASONING_EFFORTS.find((each) => each === wanted) ?? undefined); + if (effort === undefined) { + fail("invalid_argument", "Bad reasoning effort."); + } + if (effort !== null && !acceptedEfforts(id).includes(effort)) { + fail("invalid_request", "This connection does not take a reasoning effort."); + } + const existing = sessionChoices.get(id); + sessionChoices.set(id, { + profile: existing === undefined ? FOLLOW : existing.profile, + endpoint: existing === undefined ? null : existing.endpoint, + model: existing === undefined ? chatDefaults().settings.model : existing.model, + effort, }); return connectionStatus(id); } @@ -1635,6 +1693,13 @@ export function createMockBackend(now: () => number = Date.now): { invoke: Invok }; } + /** The efforts a session's connection takes: all, or none where core's endpoint rule takes none. */ + function acceptedEfforts(sessionId: string | null): ReasoningEffort[] { + return endpointTakesEffort(effectiveConnection(sessionId).endpoint) + ? [...REASONING_EFFORTS] + : []; + } + /** What the composer reads for a session (ADR-0071). */ function connectionStatus(sessionId: string | null): ConnectionStatus { const choice = sessionId === null ? undefined : sessionChoices.get(sessionId); @@ -1656,6 +1721,8 @@ export function createMockBackend(now: () => number = Date.now): { invoke: Invok connection: view, origin: !settings.connection.selectable ? "launch" : own ? "session" : "default", model: choice === undefined ? chatDefaults().settings.model : choice.model, + reasoning_effort: choice?.effort ?? null, + reasoning_efforts: acceptedEfforts(sessionId), stale, session_choices_unreadable: false, choices, @@ -1811,6 +1878,22 @@ export function isLocalEndpoint(endpoint: string): boolean { return isLocalEndpointText(endpoint); } +/** + * The mock's copy of core's effort rule (`ModelEndpoint::takes_reasoning_effort`, ADR-0102), in + * core's parse order. The endpoint decides, not the profile kind: a fixed endpoint, with or without + * one trailing `/`, takes an effort only where its provider documents one, even when typed as an + * `openai_compatible` address; any other typed address and a loopback endpoint take one; anything + * else takes none. + */ +export function endpointTakesEffort(endpoint: string): boolean { + for (const [kind, fixed] of Object.entries(FIXED_ENDPOINTS) as [FixedHostedKind, string][]) { + if (endpoint === fixed || endpoint === `${fixed}/`) { + return EFFORT_KINDS.has(kind); + } + } + return isCustomEndpoint(endpoint) || isLocalEndpoint(endpoint); +} + /** * The mock's copy of core's typed-endpoint rule for `openai_compatible` (`validate_custom_url`, * ADR-0092), step by step. The browser's `URL` follows the same WHATWG standard as the `url` crate, diff --git a/crates/omgcode-desktop/ui/tests/connection_writes.test.ts b/crates/omgcode-desktop/ui/tests/connection_writes.test.ts index ee240f3..147ebb3 100644 --- a/crates/omgcode-desktop/ui/tests/connection_writes.test.ts +++ b/crates/omgcode-desktop/ui/tests/connection_writes.test.ts @@ -224,4 +224,62 @@ describe("serialized connection writes", () => { await choosingB; expect(model.status()?.model).toBe("a-new"); }); + + // An effort choice (ADR-0102) shares the model save's queue and counters. + it("sends an effort save after a pending model save, and keeps the effort's answer", async () => { + const writes = install(); + const model = createConnectionModel(); + await model.open("s-a"); + const changes: string[] = []; + model.subscribe((change) => changes.push(change)); + + const savingModel = model.chooseModel("m1"); + const savingEffort = model.chooseEffort("high"); + await flush(); + expect(writes.map((write) => write.command)).toEqual(["session_model_select"]); + + writes[0]?.resolve(status("m1")); + await flush(); + expect(writes.map((write) => write.command)).toEqual([ + "session_model_select", + "session_effort_select", + ]); + expect(writes[1]?.args).toEqual({ session_id: "s-a", reasoning_effort: "high" }); + // The model save's answer is older than the effort pick, so it is not shown. + expect(model.status()?.model).toBe("read"); + + writes[1]?.resolve({ ...status("m1"), reasoning_effort: "high" }); + await Promise.all([savingModel, savingEffort]); + expect(model.status()?.model).toBe("m1"); + expect(model.status()?.reasoning_effort).toBe("high"); + expect(changes).toEqual(["effort"]); + }); + + it("drops a status read that answers while the session's effort save is pending", async () => { + const calls = installDeferred(); + const model = createConnectionModel(); + const opening = model.open("s-a"); + await flush(); + calls[0]?.resolve(status("m")); + await opening; + let reads = 0; + model.subscribe((change) => { + if (change === "read") { + reads += 1; + } + }); + + const choosing = model.chooseEffort(null); + await flush(); + expect(calls[1]?.args).toEqual({ session_id: "s-a", reasoning_effort: null }); + const refreshing = model.refresh(); + await flush(); + calls[2]?.resolve({ ...status("m"), reasoning_effort: "low" }); + await refreshing; + expect(reads).toBe(0); + + calls[1]?.resolve(status("m")); + await choosing; + expect(model.status()?.reasoning_effort).toBeNull(); + }); }); diff --git a/crates/omgcode-desktop/ui/tests/effort_select.test.ts b/crates/omgcode-desktop/ui/tests/effort_select.test.ts new file mode 100644 index 0000000..836446a --- /dev/null +++ b/crates/omgcode-desktop/ui/tests/effort_select.test.ts @@ -0,0 +1,323 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { setInvoker } from "../src/ipc/client"; +import type { ConnectionStatus, ReasoningEffort } from "../src/ipc/types"; +import { type MainApp, startMain } from "../src/main/app"; +import { EFFORT_NOT_TAKEN } from "../src/main/effort_select"; +import { + ALL_EFFORTS, + buttonByText, + choose, + connectionStatus, + type FakeIpc, + type Handler, + installFakeIpc, + mainHandlers, + modelSelect, + mountRoot, + page, + rejection, + SETTINGS, + session, + settle, + tree, + userMessage, +} from "./helpers"; + +// The model box's Effort dropdown chooses one session's reasoning effort (ADR-0102). + +const LMS = "http://127.0.0.1:1234/v1"; +const ANTHROPIC = "https://api.anthropic.com/v1"; + +const a = session({ session_id: "s-a", title: "Alpha" }); +const b = session({ session_id: "s-b", title: "Beta" }); + +let app: MainApp | null = null; +let root: HTMLElement; +let ipc: FakeIpc; + +/** What each session has chosen, as Rust records it. */ +interface Choice { + profile: string | null; + effort: ReasoningEffort | null; + /** A record that still follows the default connection, as an effort alone creates. */ + follow?: boolean; +} + +const PROFILES = [ + { name: "lms", kind: "lm_studio", endpoint: LMS }, + { name: "claude", kind: "anthropic", endpoint: ANTHROPIC }, +]; + +/** A stateful fake of the per-session commands; the Anthropic connection takes no effort. */ +function backend(initial: Record = {}, selectable = true): Record { + const choices = new Map(Object.entries(initial)); + const find = (id: string): Choice => choices.get(id) ?? { profile: null, effort: null }; + const status = (id: string): ConnectionStatus => { + const choice = find(id); + const profile = PROFILES.find((each) => each.name === choice.profile); + return connectionStatus({ + connection: { + endpoint: profile?.endpoint ?? LMS, + source: "active", + profile: profile?.name ?? null, + kind: profile?.kind ?? null, + selectable, + }, + // Like Rust, a record that follows the default reports the default origin. + origin: !selectable ? "launch" : choices.has(id) && !choice.follow ? "session" : "default", + reasoning_effort: choice.effort, + reasoning_efforts: profile?.kind === "anthropic" ? [] : [...ALL_EFFORTS], + choices: selectable + ? PROFILES.map((each) => ({ ...each, active: each.name === choice.profile })) + : [], + }); + }; + return { + session_tree: () => tree([{ id: "g1", folder: "C:\\work", sessions: [a, b] }]), + session_transcript: (args) => page(args.session_id === "s-b" ? b : a, [userMessage(1, "hi")]), + connection_status: (args) => status((args.session_id as string | null) ?? ""), + // Like Rust, a provider choice clears the effort with the model. + connection_select: (args) => { + const id = args.session_id as string; + choices.set(id, { profile: args.profile as string | null, effort: null }); + return status(id); + }, + // Like Rust, an effort alone creates a record that follows the default connection. + session_effort_select: (args) => { + const id = args.session_id as string; + const existing = choices.get(id) ?? { profile: null, effort: null, follow: true }; + choices.set(id, { ...existing, effort: args.reasoning_effort as ReasoningEffort | null }); + return status(id); + }, + chat_send: () => ({ session_id: "s-a", state: "running", outcome: null, error: null }), + chat_status: () => ({ session_id: "s-a", state: "running", outcome: null, error: null }), + }; +} + +async function start(handlers: Record): Promise { + ipc = installFakeIpc(mainHandlers(handlers)); + root = mountRoot(); + app = startMain(root); + await settle(); +} + +async function open(id: string): Promise { + const node = Array.from(root.querySelectorAll("[data-session-id]")).find( + (item) => item.dataset.sessionId === id, + ); + node?.click(); + await settle(); +} + +function effortSelect(): HTMLSelectElement { + return root.querySelector('.model-box select[aria-label="Effort"]') as HTMLSelectElement; +} + +function boxProvider(): HTMLSelectElement { + return root.querySelector('.model-box select[aria-label="Provider"]') as HTMLSelectElement; +} + +function effortLabels(): string[] { + return Array.from(effortSelect().options).map((option) => option.textContent ?? ""); +} + +function note(): HTMLElement | undefined { + return Array.from(root.querySelectorAll(".model-box-status [role=status]")).find( + (node) => node.textContent === EFFORT_NOT_TAKEN, + ); +} + +async function send(): Promise { + const box = root.querySelector(".message-box") as HTMLTextAreaElement; + box.value = "hello"; + box.dispatchEvent(new Event("input", { bubbles: true })); + buttonByText(root, "Send").click(); + await settle(); +} + +beforeEach(() => { + vi.useFakeTimers(); +}); + +afterEach(() => { + app?.dispose(); + app = null; + setInvoker(null); + vi.useRealTimers(); +}); + +describe("effort dropdown", () => { + it("sits under Model and offers Default and every effort the connection takes", async () => { + await start(backend()); + await open("s-a"); + const box = root.querySelector(".model-box") as HTMLElement; + const labels = Array.from(box.querySelectorAll(".model-box-field > span")).map( + (node) => node.textContent, + ); + expect(labels).toEqual(["Provider", "Model", "Effort"]); + expect(effortSelect().closest(".model-box")).toBe(box); + expect(effortLabels()).toEqual([ + "Default", + "None", + "Minimal", + "Low", + "Medium", + "High", + "Extra high", + "Max", + ]); + expect(Array.from(effortSelect().options).map((option) => option.value)).toEqual([ + "", + ...ALL_EFFORTS, + ]); + expect(effortSelect().value).toBe(""); + expect(effortSelect().disabled).toBe(false); + expect(note()?.hidden).toBe(true); + }); + + it("records a chosen effort for the session, and Default records none", async () => { + await start(backend()); + await open("s-a"); + choose(effortSelect(), "xhigh"); + await settle(); + expect(ipc.callsTo("session_effort_select").map((call) => call.args)).toEqual([ + { session_id: "s-a", reasoning_effort: "xhigh" }, + ]); + expect(effortSelect().value).toBe("xhigh"); + expect(effortSelect().selectedOptions[0]?.textContent).toBe("Extra high"); + + choose(effortSelect(), ""); + await settle(); + expect(ipc.callsTo("session_effort_select")[1]?.args).toEqual({ + session_id: "s-a", + reasoning_effort: null, + }); + expect(effortSelect().value).toBe(""); + // An effort choice is not a model choice: the model list is not read again. + expect(ipc.callsTo("chat_models")).toHaveLength(1); + expect(ipc.callsTo("session_model_select")).toHaveLength(0); + }); + + it("shows each session's recorded effort when it opens", async () => { + await start( + backend({ + "s-a": { profile: "lms", effort: "low" }, + "s-b": { profile: "lms", effort: "max" }, + }), + ); + await open("s-a"); + expect(effortSelect().value).toBe("low"); + await open("s-b"); + expect(effortSelect().value).toBe("max"); + await open("s-a"); + expect(effortSelect().value).toBe("low"); + expect(ipc.callsTo("session_effort_select")).toHaveLength(0); + }); + + it("sends the effort the box shows, and none for Default", async () => { + await start(backend({ "s-a": { profile: "lms", effort: "medium" } })); + await open("s-a"); + await send(); + expect(ipc.callsTo("chat_send")[0]?.args).toMatchObject({ + settings: { endpoint: LMS, model: SETTINGS.model, reasoning_effort: "medium" }, + }); + }); + + it("sends no effort by default", async () => { + await start(backend()); + await open("s-a"); + await send(); + const settings = ipc.callsTo("chat_send")[0]?.args.settings as Record; + expect(settings.reasoning_effort).toBeNull(); + }); + + it("is disabled with a note when the connection takes no effort, and sends none", async () => { + await start(backend({ "s-a": { profile: "claude", effort: null } })); + await open("s-a"); + expect(effortSelect().disabled).toBe(true); + expect(effortLabels()).toEqual(["Default"]); + expect(note()?.hidden).toBe(false); + // The model is still chosen as before. + expect(modelSelect(root).disabled).toBe(false); + await send(); + const settings = ipc.callsTo("chat_send")[0]?.args.settings as Record; + expect(settings.reasoning_effort).toBeNull(); + }); + + it("clears the effort when the operator chooses another provider", async () => { + await start(backend({ "s-a": { profile: "lms", effort: "high" } })); + await open("s-a"); + expect(effortSelect().value).toBe("high"); + choose(boxProvider(), "claude"); + await settle(); + expect(effortSelect().value).toBe(""); + expect(effortSelect().disabled).toBe(true); + expect(note()?.hidden).toBe(false); + }); + + it("is disabled while no session is open and while a turn runs", async () => { + await start(backend()); + expect(effortSelect().disabled).toBe(true); + // No session is open, so the note about the connection is not shown either. + expect(note()?.hidden).toBe(true); + await open("s-a"); + expect(effortSelect().disabled).toBe(false); + await send(); + expect(effortSelect().disabled).toBe(true); + }); + + it("stays enabled when a launch argument fixed the connection", async () => { + await start(backend({}, false)); + await open("s-a"); + expect(boxProvider().disabled).toBe(true); + expect(effortSelect().disabled).toBe(false); + }); + + // Reopening resets the model list, and the reopened session's status read is dropped while the + // save is pending; the save's own answer must then load the list. + it("loads the model list when an effort save settles after the session was reopened", async () => { + const handlers = backend({ "s-a": { profile: "lms", effort: null } }); + const record = handlers.session_effort_select; + // A no-op until the held save replaces it, so its type stays a function for the checker. + let answer: () => void = () => undefined; + await start({ + ...handlers, + session_effort_select: (args) => + new Promise((resolve) => { + answer = () => resolve(record?.(args)); + }), + }); + await open("s-a"); + choose(effortSelect(), "high"); + await settle(); + await open("s-b"); + await open("s-a"); + const loads = (): number => + ipc.callsTo("chat_models").filter((call) => call.args.session_id === "s-a").length; + const before = loads(); + expect(ipc.callsTo("session_effort_select")).toHaveLength(1); + + answer(); + await settle(); + + expect(loads()).toBe(before + 1); + expect(Array.from(modelSelect(root).options).map((option) => option.value)).toContain( + SETTINGS.model, + ); + expect(effortSelect().value).toBe("high"); + }); + + it("shows a refused save and returns to the recorded effort", async () => { + const handlers = backend({ "s-a": { profile: "lms", effort: "low" } }); + await start({ + ...handlers, + session_effort_select: () => + rejection("invalid_request", "This connection does not take a reasoning effort."), + }); + await open("s-a"); + choose(effortSelect(), "max"); + await settle(); + expect(root.querySelector(".model-box-status")?.textContent).toContain("invalid_request"); + expect(effortSelect().value).toBe("low"); + }); +}); diff --git a/crates/omgcode-desktop/ui/tests/helpers.ts b/crates/omgcode-desktop/ui/tests/helpers.ts index 22ab92f..0d094f2 100644 --- a/crates/omgcode-desktop/ui/tests/helpers.ts +++ b/crates/omgcode-desktop/ui/tests/helpers.ts @@ -4,6 +4,7 @@ import type { ChatDefaultsView, ChatSettings, ConnectionStatus, + ReasoningEffort, SessionSummary, SessionTree, TranscriptEntry, @@ -100,6 +101,9 @@ export function connectionStatus(overrides: Partial = {}): Con }, origin: "default", model: SETTINGS.model, + // A loopback connection takes every effort core accepts (ADR-0102); none is chosen. + reasoning_effort: null, + reasoning_efforts: [...ALL_EFFORTS], stale: false, session_choices_unreadable: false, choices: [], @@ -107,6 +111,17 @@ export function connectionStatus(overrides: Partial = {}): Con }; } +/** Every reasoning effort core accepts, in its order (ADR-0102). */ +export const ALL_EFFORTS: readonly ReasoningEffort[] = [ + "none", + "minimal", + "low", + "medium", + "high", + "xhigh", + "max", +]; + /** Handlers every main-window test needs. */ export function mainHandlers(overrides: Record = {}): Record { return { @@ -133,6 +148,8 @@ export function mainHandlers(overrides: Record = {}): Record connectionStatus(), // Records nothing; the status read back keeps the fixture model. session_model_select: (args) => connectionStatus({ model: args.model as string }), + session_effort_select: (args) => + connectionStatus({ reasoning_effort: args.reasoning_effort as ReasoningEffort | null }), session_context: () => ({ workspace_registered: true, branch: { state: "branch", name: "main", note: null }, diff --git a/crates/omgcode-desktop/ui/tests/mock.test.ts b/crates/omgcode-desktop/ui/tests/mock.test.ts index ac34f60..1666afc 100644 --- a/crates/omgcode-desktop/ui/tests/mock.test.ts +++ b/crates/omgcode-desktop/ui/tests/mock.test.ts @@ -1,6 +1,11 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import type { ChatDefaults, ChatEvent, SettingsOverview, WorkspaceList } from "../src/ipc/types"; -import { createMockBackend, isCustomEndpoint, isLocalEndpoint } from "../src/mock/backend"; +import { + createMockBackend, + endpointTakesEffort, + isCustomEndpoint, + isLocalEndpoint, +} from "../src/mock/backend"; import { OMGCODE_MOCK_FIXTURE_MARKER } from "../src/mock/fixtures"; interface Detail { @@ -204,6 +209,85 @@ describe("mock backend", () => { }); }); + it("records a session's reasoning effort only where its connection takes one, like core", async () => { + const { invoke } = createMockBackend(); + const id = "00000000-0000-4000-8000-000000000001"; + type Status = { + model: string; + reasoning_effort: string | null; + reasoning_efforts: string[]; + }; + const before = (await invoke("connection_status", { session_id: id })) as Status; + expect(before.reasoning_effort).toBeNull(); + expect(before.reasoning_efforts).toEqual([ + "none", + "minimal", + "low", + "medium", + "high", + "xhigh", + "max", + ]); + + // An effort alone keeps the session following the default, with its model. + const chosen = (await invoke("session_effort_select", { + session_id: id, + reasoning_effort: "xhigh", + })) as Status; + expect(chosen.reasoning_effort).toBe("xhigh"); + expect(chosen.model).toBe(before.model); + // A model choice keeps it; only the seven names are accepted. + await expect( + invoke("session_model_select", { session_id: id, model: "other" }), + ).resolves.toMatchObject({ reasoning_effort: "xhigh" }); + await expect( + invoke("session_effort_select", { session_id: id, reasoning_effort: "extreme" }), + ).rejects.toMatchObject({ code: "invalid_argument" }); + + // An Anthropic connection takes none, and choosing it clears the session's effort. + const { revision } = (await invoke("settings_overview", {})) as SettingsOverview; + await invoke("settings_add_connection", { + revision, + name: "claude", + kind: "anthropic", + endpoint: null, + api_key: "test-key-not-real", + }); + const switched = (await invoke("connection_select", { + session_id: id, + profile: "claude", + })) as Status; + expect(switched.reasoning_effort).toBeNull(); + expect(switched.reasoning_efforts).toEqual([]); + await expect( + invoke("session_effort_select", { session_id: id, reasoning_effort: "low" }), + ).rejects.toMatchObject({ code: "invalid_request" }); + await expect( + invoke("session_effort_select", { session_id: id, reasoning_effort: null }), + ).resolves.toMatchObject({ reasoning_effort: null }); + + // The endpoint decides, not the kind: a typed address that is exactly the Anthropic endpoint + // takes the Anthropic rule, and any other typed address takes an effort. + for (const [name, endpoint, takes] of [ + ["typed-anthropic", "https://api.anthropic.com/v1", false], + ["typed-other", "https://llm.example.com/v1", true], + ] as const) { + const current = (await invoke("settings_overview", {})) as SettingsOverview; + await invoke("settings_add_connection", { + revision: current.revision, + name, + kind: "openai_compatible", + endpoint, + api_key: "test-key-not-real", + }); + const typed = (await invoke("connection_select", { + session_id: id, + profile: name, + })) as Status; + expect(typed.reasoning_efforts.length > 0, endpoint).toBe(takes); + } + }); + // The cases core's `validate_base_url` decides (crates/omgcode-core/src/provider.rs tests). it.each([ ["http://127.0.0.1:1234/v1", true], @@ -278,6 +362,33 @@ describe("mock backend", () => { expect(isCustomEndpoint(endpoint)).toBe(accepted); }); + // Core's `EFFORT_ENDPOINTS` and parse order (ADR-0102): an allowlist, so an endpoint core does + // not name, or cannot parse, takes none. + it.each([ + ["http://127.0.0.1:1234/v1", true], + ["https://ollama.com/v1", true], + ["https://api.openai.com/v1", true], + ["https://api.openai.com/v1/", true], + ["https://generativelanguage.googleapis.com/v1beta/openai", true], + ["https://api.moonshot.ai/v1", true], + ["https://api.minimax.io/v1", true], + ["https://openrouter.ai/api/v1", true], + ["https://api.z.ai/api/paas/v4", true], + ["https://api.x.ai/v1", true], + ["https://llm.example.com/v1", true], + ["https://api.anthropic.com/v1", false], + ["https://api.anthropic.com/v1/", false], + ["https://api.deepseek.com", false], + ["https://api.hunyuan.cloud.tencent.com/v1", false], + ["https://api.llama.com/compat/v1", false], + ["https://tinker.thinkingmachines.dev/services/tinker-prod/oai/api/v1", false], + ["http://llm.example.com/v1", false], + ["not an endpoint", false], + ["", false], + ])("decides whether %s takes a reasoning effort as core does", (endpoint, takes) => { + expect(endpointTakesEffort(endpoint)).toBe(takes); + }); + it("records an IPv6 loopback connection and refuses port 0", async () => { const { invoke } = createMockBackend(); let { revision } = (await invoke("settings_overview", {})) as SettingsOverview; diff --git a/docs/adr/0087-show-a-per-part-context-estimate-for-the-open-session.md b/docs/adr/0087-show-a-per-part-context-estimate-for-the-open-session.md index 1a157f1..d1a4bad 100644 --- a/docs/adr/0087-show-a-per-part-context-estimate-for-the-open-session.md +++ b/docs/adr/0087-show-a-per-part-context-estimate-for-the-open-session.md @@ -1,6 +1,6 @@ # 0087: Show a per-part context estimate for the open session -- Status: Accepted +- Status: Accepted; amended by [ADR-0102](0102-choose-a-reasoning-effort-per-session.md) - Date: 2026-11-24 - Implemented: the command, and the view as the right-hand panel's **Context** tab diff --git a/docs/adr/0089-choose-the-provider-and-model-in-the-side-panel-footer.md b/docs/adr/0089-choose-the-provider-and-model-in-the-side-panel-footer.md index 77a8c8c..e8243c6 100644 --- a/docs/adr/0089-choose-the-provider-and-model-in-the-side-panel-footer.md +++ b/docs/adr/0089-choose-the-provider-and-model-in-the-side-panel-footer.md @@ -1,6 +1,6 @@ # 0089: Choose the provider and model in the side panel footer -- Status: Accepted +- Status: Accepted; amended by [ADR-0102](0102-choose-a-reasoning-effort-per-session.md) - Date: 2026-11-24 - Amends: [ADR-0071](0071-choose-the-provider-and-model-per-session-and-add-ollama-cloud.md) decisions 6 to 11, for the placement only diff --git a/docs/adr/0102-choose-a-reasoning-effort-per-session.md b/docs/adr/0102-choose-a-reasoning-effort-per-session.md new file mode 100644 index 0000000..d664f56 --- /dev/null +++ b/docs/adr/0102-choose-a-reasoning-effort-per-session.md @@ -0,0 +1,176 @@ +# 0102: Choose a reasoning effort per session + +- Status: Accepted +- Date: 2026-11-26 +- Amends: [ADR-0089](0089-choose-the-provider-and-model-in-the-side-panel-footer.md) decision 1, for the box's contents only; + [ADR-0087](0087-show-a-per-part-context-estimate-for-the-open-session.md) decision 3, for what framing counts + +## Context + +The operator asked for a way to set the reasoning effort ("Medium, High, +Extra High etc.") in the provider and model settings, as a dedicated +dropdown. OMGCode sent no effort field, so every reasoning model ran at its +provider's default. + +Facts established from each provider's official documentation on +2026-11-26, before the decision: + +- OpenAI's Chat Completions reference documents `reasoning_effort` with the + values `none`, `minimal`, `low`, `medium`, `high`, `xhigh`, and `max`, and + says the accepted values are model-dependent; some models answer a value + they do not support with HTTP 400. The Responses API takes the same values + as `reasoning.effort`. OpenAI's open-source Codex client, which uses the + ChatGPT plan route, sends `reasoning: {"effort": …}` with the same names. +- Ollama's OpenAI compatibility page lists `reasoning_effort` for + `/v1/chat/completions`, with model-defined values and aliases. Ollama + Cloud serves the same API; its effort handling was not checked separately. +- LM Studio's 0.4.8 release notes add `reasoning_effort` to its + OpenAI-compatible `/v1/chat/completions`. Older LM Studio versions are not + documented to accept it. +- Google's Gemini OpenAI compatibility, xAI, OpenRouter, Z.ai, Moonshot, and + MiniMax document a top-level `reasoning_effort`, each with a + model-dependent subset of the same names; several say an unsupported + value or `none` on a model that always reasons is answered with HTTP 400. +- Anthropic's OpenAI SDK compatibility layer lists `reasoning_effort` as + ignored. DeepSeek documents `reasoning_effort`, but a `thinking` field + takes precedence, and this client sends `thinking: {"type": "disabled"}` + to DeepSeek (ADR-0092), so an effort would have no effect. +- Tencent Hunyuan, Meta's Llama API, and Thinking Machines' Tinker document + no effort field. ADR-0092 records that Tinker ignores fields it does not + list. +- An operator-typed `openai_compatible` server and a loopback server can be + any software; their documentation cannot be checked in advance. + +No provider's effort handling was exercised with a real request. + +## Decision + +1. **Core owns the values.** `omgcode_core::provider::ReasoningEffort` has + the seven documented names: `none`, `minimal`, `low`, `medium`, `high`, + `xhigh`, and `max`. It is a closed enum: no other text reaches a request, + and serde refuses any other name on every interface that reads it. "No + effort" is `Option::None`, which sends no field and leaves the provider's + default in force; it is not the provider's `none` value. +2. **Core decides which endpoints take an effort.** `ModelEndpoint` reports + whether it accepts one: every loopback endpoint and every operator-typed + HTTPS endpoint; of the fixed endpoints, those whose provider documents the + field (Ollama Cloud, OpenAI, Google, Moonshot, MiniMax, OpenRouter, Z.ai, + and xAI). Anthropic, DeepSeek, Tencent, Meta, and Tinker do not. The list + is an allowlist, so a provider added later takes no effort until its + documentation is checked. The endpoint text decides, not the profile + kind: `ModelEndpoint::parse` matches the fixed table first, so an + `openai_compatible` address typed as exactly a fixed endpoint (one + trailing `/` allowed) takes that endpoint's rule. One typed as the + Anthropic or DeepSeek endpoint therefore takes no effort either. +3. **The client sends the effort only when one is chosen.** + `LocalModelClient::with_reasoning_effort` sets it after construction and + refuses an effort for an endpoint that does not take one with + `InvalidConfiguration`, before anything is sent. A Chat Completions request + then carries `"reasoning_effort": ""`; a plan-route Responses + request carries `"reasoning": {"effort": ""}`. With no effort, + both bodies are byte-for-byte as before. The field's bytes (a fixed upper + bound, `effort_field_bytes`) count in the client's request size and + context checks, in the turn's pre-turn compaction trigger, and in the + desktop **Context** tab, where they are part of framing (amending ADR-0087 + decision 3), so the parts still add up to the trigger's estimate. +4. **The value is not adjusted to the model.** Accepted values depend on the + model, which core cannot know. The server decides, and a refusal is the + existing `provider` failure with its HTTP status. No value is rewritten, + retried, or silently dropped. +5. **The request manifest records the effort.** `RequestManifest` gains an + optional `reasoning_effort`, omitted when no effort was sent, so journals + without one keep their bytes and session schema version 3 is unchanged. As + with `skills`, a build older than this one refuses a journal that contains + it. +6. **Only the chat requests use it.** The compaction summary client sends no + effort. A summary is a bounded utility request that the manifest does not + describe, and a high effort on the plan route can use most of its 120-second + request deadline. +7. **The desktop records it per session.** `SessionRecord` in + `desktop-v1/session-connections.json` gains an optional + `reasoning_effort`, omitted when none is chosen, so files written before + this change still load and version 1 is kept. An older build reads a file + that holds an effort as unreadable, reports it, and treats it as empty, + as ADR-0071 decision 6 already requires. The new `main` command + `session_effort_select` records it without a dialog, like + `session_model_select`: an effort grants nothing. An effort the + session's connection does not take is refused with `invalid_request`; + `null`, which records no effort ("Default"), is accepted on any + connection, including one that takes none. It holds + the one-change-at-a-time guard that a provider choice holds, so the + connection it checks is the one the record keeps, and it is refused with + `settings_change_running` while another settings change runs. Choosing + another provider clears it with the model, because accepted values depend + on the provider and model. +8. **Rust tells the window what to offer.** `connection_status` returns the + session's recorded `reasoning_effort` and `reasoning_efforts`, the values + its connection accepts: all seven, or none. `chat_send` takes the effort in + its settings beside the model, as the composer already sends the model it + reads from the box. Rust refuses an effort the turn's connection does not + take before the turn starts. +9. **The model box has an Effort dropdown.** Under **Model**, a dedicated + **Effort** dropdown offers "Default" and the accepted values, labelled + None, Minimal, Low, Medium, High, Extra high, and Max. It is disabled with + the other dropdowns (no session that accepts a message, a turn running, or + a choice in flight) and when the connection takes no effort, where a note + says so. A launch argument that fixes the connection does not disable it, + as it does not disable the model. +10. **The trusted CLI matches.** `omgcode chat --reasoning-effort ` + sends the same field through the same client; without the flag nothing is + sent. + +## Alternatives considered + +- **Send `reasoning_effort` to every endpoint.** Rejected: Anthropic ignores + it and DeepSeek overrides it, so the dropdown would claim an effect that + does not happen. Refusing it there tells the operator the truth. +- **Per-provider value lists.** Rejected for now: every provider's list is + model-dependent, so a per-provider list would still offer values a model + refuses, and would go stale with each model release. The server's HTTP + error names the problem. +- **Map unsupported values to the nearest supported one.** Rejected: a + silently changed setting is worse than a refused one, and core does not + know the model's list. +- **Read the effort from the session record in `chat_send`.** It would avoid + a field in the send settings. Rejected for consistency: the model is sent + in the settings, and ADR-0089 decision 3 makes the box the composer's + source for each send. Rust still validates the value and the connection. +- **Keep the effort when the provider changes.** Rejected: the next + provider may take none, or not that value, and the model is cleared anyway. +- **Use the effort for compaction.** Rejected for decision 6's reasons; it + can be revisited if summaries prove too shallow. +- **Raise the session schema version.** Rejected: an omitted optional field + keeps every existing journal valid, as `skills` did. + +## Consequences + +- The operator can choose an effort for any session whose connection + documents one. "Default" keeps the previous behaviour exactly. +- A value the model does not support fails the turn with the provider's + HTTP status, before any reply; the operator chooses another value. +- Ollama Cloud's and LM Studio's handling, and every hosted provider's, were + not observed with a real request. LM Studio before 0.4.8 may ignore or + refuse the field. +- An older build refuses a journal with a recorded effort and reads a + session-connections file with an effort as unreadable. + +## References + +- [Desktop interface](../desktop-interface.md#right-hand-panel) +- [OpenAI: Create chat completion](https://developers.openai.com/api/reference/resources/chat/subresources/completions/methods/create/) +- [OpenAI: Reasoning models](https://developers.openai.com/api/docs/guides/reasoning) +- [openai/codex `ReasoningEffort`](https://github.com/openai/codex/blob/main/codex-rs/protocol/src/openai_models.rs) +- [Ollama OpenAI compatibility](https://docs.ollama.com/api/openai-compatibility) +- [LM Studio 0.4.8 changelog](https://lmstudio.ai/changelog/lmstudio/lmstudio-v0.4.8) +- [Gemini OpenAI compatibility](https://ai.google.dev/gemini-api/docs/openai) +- [Anthropic OpenAI SDK compatibility](https://docs.anthropic.com/en/api/openai-sdk) +- [xAI reasoning](https://docs.x.ai/developers/model-capabilities/text/reasoning) +- [OpenRouter reasoning tokens](https://openrouter.ai/docs/guides/best-practices/reasoning-tokens) +- [DeepSeek thinking mode](https://api-docs.deepseek.com/guides/thinking_mode/) +- [Z.ai chat completion](https://docs.z.ai/api-reference/llm/chat-completion) +- [Moonshot quickstart](https://platform.moonshot.ai/docs/api/chat.en-US) +- [MiniMax chat completion](https://platform.minimax.io/docs/api-reference/text-chat-openai) +- [ADR-0071](0071-choose-the-provider-and-model-per-session-and-add-ollama-cloud.md), + [ADR-0089](0089-choose-the-provider-and-model-in-the-side-panel-footer.md), + [ADR-0092](0092-add-hosted-providers-and-an-openai-compatible-connection.md), + [ADR-0093](0093-sign-in-with-chatgpt-and-use-the-plan-through-the-responses-api.md) diff --git a/docs/adr/index.md b/docs/adr/index.md index 199b2d9..1436e62 100644 --- a/docs/adr/index.md +++ b/docs/adr/index.md @@ -101,9 +101,9 @@ meaningful alternative does not need an ADR. | [0084: Drop the status bar connection choice](0084-drop-the-status-bar-connection-choice.md) | Accepted, amended by ADR-0089 | 2026-11-23 | | [0085: Read Git status with gix without running programs](0085-read-git-status-with-gix-without-running-programs.md) | Accepted | 2026-11-24 | | [0086: Show the session's subprocesses in the main window](0086-show-the-sessions-subprocesses-in-the-main-window.md) | Accepted | 2026-11-24 | -| [0087: Show a per-part context estimate for the open session](0087-show-a-per-part-context-estimate-for-the-open-session.md) | Accepted | 2026-11-24 | +| [0087: Show a per-part context estimate for the open session](0087-show-a-per-part-context-estimate-for-the-open-session.md) | Accepted; amended by ADR-0102 | 2026-11-24 | | [0088: Change execution settings in the settings window](0088-change-execution-settings-in-the-settings-window.md) | Accepted | 2026-11-24 | -| [0089: Choose the provider and model in the side panel footer](0089-choose-the-provider-and-model-in-the-side-panel-footer.md) | Accepted | 2026-11-24 | +| [0089: Choose the provider and model in the side panel footer](0089-choose-the-provider-and-model-in-the-side-panel-footer.md) | Accepted; amended by ADR-0102 | 2026-11-24 | | [0090: Set every file-write tool limit at once](0090-set-every-file-write-tool-limit-at-once.md) | Accepted | 2026-11-24 | | [0091: Compact automatically at 400K by default in the desktop](0091-compact-automatically-at-400k-by-default-in-the-desktop.md) | Accepted | 2026-11-24 | | [0092: Add hosted providers and an OpenAI-compatible connection](0092-add-hosted-providers-and-an-openai-compatible-connection.md) | Accepted | 2026-11-24 | @@ -116,3 +116,4 @@ meaningful alternative does not need an ADR. | [0099: Recover from rejected tool calls and raise write-tool argument limits](0099-recover-from-rejected-tool-calls-and-raise-write-tool-argument-limits.md) | Accepted | 2026-11-25 | | [0100: List the recorded toolchain profiles in the command tool](0100-list-the-recorded-toolchain-profiles-in-the-command-tool.md) | Accepted | 2026-11-26 | | [0101: Make every section divider movable](0101-make-every-section-divider-movable.md) | Accepted | 2026-11-26 | +| [0102: Choose a reasoning effort per session](0102-choose-a-reasoning-effort-per-session.md) | Accepted | 2026-11-26 | diff --git a/docs/desktop-interface.md b/docs/desktop-interface.md index c795275..a119742 100644 --- a/docs/desktop-interface.md +++ b/docs/desktop-interface.md @@ -274,7 +274,7 @@ has not been run, so how it behaves in a delegated cgroup is unverified. ## Windows and commands -The shell has three webview windows and 62 commands (30 in `main`, 3 in `approvals`, and 29 in `settings`). No other command exists. +The shell has three webview windows and 63 commands (31 in `main`, 3 in `approvals`, and 29 in `settings`). No other command exists. No command accepts a host path. Sessions are addressed by UUID, workspaces by their registered identifier, and approvals by identifier. @@ -299,9 +299,10 @@ their registered identifier, and approvals by identifier. | `session_processes` | main | List a session's model command-tool calls, newest first, at most 100, read-only (ADR-0086) | | `session_web_audit` | main | List a session's `web_fetch` calls and every model action marked `after_web_content`, newest first, at most 100, read-only (ADR-0098) | | `workspace_git_status` | main | Report the Git branch and a bounded list of changed paths for a session's registered workspace, read in process by `gix` with no program run (ADR-0085); takes the session id | -| `connection_status` | main | Return a session's connection, where it comes from, its model, and the connections that may be chosen; takes the session id or `null` | +| `connection_status` | main | Return a session's connection, where it comes from, its model, its reasoning effort and the efforts its connection takes, and the connections that may be chosen; takes the session id or `null` | | `connection_select` | main | Request the default or a recorded profile as one session's provider; Rust shows a native confirmation | | `session_model_select` | main | Record the model chosen for one session; no dialog | +| `session_effort_select` | main | Record the reasoning effort chosen for one session, or no effort (Default) for `null`; no dialog; an effort the session's connection does not take is refused; `null` is accepted on any connection (ADR-0102) | | `chat_send` | main | Start one chat turn on a supervised thread | | `chat_status` | main | Report the state and outcome of a session's turn | | `chat_cancel` | main | Request cooperative cancellation of a running turn | @@ -569,8 +570,10 @@ The right-hand column (ADR-0072, ADR-0083) is one panel with tabs built by (see [section dividers](#section-dividers)). - **The model box** (`ui/src/main/model_box.ts`, ADR-0089): a "Model" heading, the **Provider** dropdown, the **Model** dropdown with its **Refresh** - button, and the status notes (list status, off-machine warning, connection - message, unreadable saved choices), stacked vertically. It does not scroll + button, the **Effort** dropdown (`ui/src/main/effort_select.ts`, + ADR-0102), and the status notes (list status, off-machine warning, no + effort setting, connection message, unreadable saved choices), stacked + vertically. It does not scroll with the tab content and stays when the tab changes. A collapsed panel hides it, so the rail's **Model** icon button (named and tooltipped "Model") expands the panel. The controls are the ones ADR-0071 placed in @@ -872,6 +875,26 @@ untouched controls take the returned values. at launch", and the model is still chosen from that connection's list. `chat_send` keeps sending the endpoint of the shared connection and the model the model box shows; Send is disabled without a model and while the session's provider is being read or has gone stale. +- **Reasoning effort per session** (ADR-0102). Under **Model**, the + **Effort** dropdown offers "Default", which sends no effort field, and the + efforts `connection_status` reports in `reasoning_efforts`: None, Minimal, + Low, Medium, High, Extra high (`xhigh`), and Max. Loopback connections, an + operator-typed `openai_compatible` address, and the fixed Ollama Cloud, + OpenAI, Google, Moonshot, MiniMax, OpenRouter, Z.ai, and xAI endpoints take + all seven; the fixed Anthropic, DeepSeek, Tencent, Meta, and Thinking + Machines Lab endpoints take none, and there the dropdown is disabled with + the note "This connection does not take an effort setting." The endpoint + decides, not the kind: an `openai_compatible` address typed as exactly one + of the fixed endpoints takes that endpoint's rule. Choosing an + effort calls `session_effort_select`, which shows no dialog and shares the + model choice's serialized writes. A provider choice clears the effort with + the model; a model choice keeps it. It is disabled with the other dropdowns + (no session that accepts a message, a turn running, or a provider choice in + flight), but not by a launch argument that fixes the connection. + `chat_send` sends the effort the box shows in its settings as + `reasoning_effort`, and Rust refuses one the turn's connection does not + take. The server still decides whether its model accepts the value; a + refusal arrives as the provider's error. - **Saved preferences.** Two windows save one file, each its own fields, under one service lock, so neither overwrites the other's (ADR-0080). The composer's **Save as defaults** sends the compaction threshold, the @@ -1031,7 +1054,8 @@ changes while it is shown, and again when a turn settles; see resolves everything from trusted state by session id: the journal through the index, the saved chat budgets and global instructions, the session workspace's saved instructions (read under the preferences lock, as - `chat_send` reads them), and live settings for the tool decision. It + `chat_send` reads them), the session's recorded reasoning effort, and live + settings for the tool decision. It sends nothing to a model, appends nothing to any journal, and returns no instruction or message text, only numbers and fixed codes. It runs on a blocking task. @@ -1041,8 +1065,10 @@ changes while it is shown, and again when a turn settles; see the conversation history after the compaction boundary (with its message count; the boundary is named only when a summary is sent), selected skills, and message framing. Framing is the fixed overhead - no part owns (the instructions label and the instruction message's - overhead), reported as its own part so the parts add up to the estimate. + no part owns (the instructions label, the instruction message's + overhead, and the reasoning effort field when the session records an + effort, ADR-0102), reported as its own part so the parts add up to the + estimate. Tool definitions count only when live settings would offer tools (the same rule a turn applies); otherwise the part is not included and carries a fixed reason such as `preference_disabled`. Skills are loaded only when selected @@ -1556,6 +1582,17 @@ applies the rule `chat_send` applies (at most 256 bytes, no control character; an empty id clears the choice). A session with no record gets one that follows the default connection, so choosing a model never pins a provider the operator did not confirm. +`session_effort_select` records a session's reasoning effort the same way, +with no dialog (ADR-0102). It deserializes only the seven names and `null`, +refuses an effort the session's connection does not take with +`invalid_request`, and keeps the session's model. `null` records no effort +(Default, which is not the `none` effort) and is accepted on any connection. +It runs as one settings change, so +a provider choice cannot land between its check and its save; while another +change runs, such as a provider choice awaiting its confirmation, it is +refused with `settings_change_running`. The per-session record stores it as +an optional `reasoning_effort`, omitted when none is chosen, so +`session-connections.json` keeps version 1. `connection_select` clears it. The `settings` window's `settings_select_connection` keeps choosing the **global default**, which sessions without their own choice follow; it uses the same checks and dialog. The `settings` connection commands call diff --git a/docs/development.md b/docs/development.md index 3d10ec0..5beb2f0 100644 --- a/docs/development.md +++ b/docs/development.md @@ -769,6 +769,15 @@ the command with the code `interrupt` before any model request. omgcode --data-dir C:\omgcode-data chat --stream --journal --model google/gemma-4-e4b --context-tokens 131072 "Summarise README.md." ``` +Since 0.67.0 `chat --reasoning-effort ` +sends that reasoning effort with every chat request of the turn (compaction +summary requests send none) and records it in the turn's request manifest +(ADR-0102). Without the flag nothing is sent and +the provider's default applies. A connection whose provider documents no +effort field refuses the flag with the code `provider` before any request, +and a version 1 or 2 session refuses it with `session`. See +[reasoning effort](provider-authentication.md). + Each text-only invocation sends one request, which is not streamed unless `--stream` is given. A tool-enabled turn sends at most one request more than its tool-call budget. When `--auto-compact` diff --git a/docs/provider-authentication.md b/docs/provider-authentication.md index 2e0f14e..0b5ec13 100644 --- a/docs/provider-authentication.md +++ b/docs/provider-authentication.md @@ -445,10 +445,31 @@ validation, no proxy, redirect, or retry, and the same timeouts and limits. `reasoning_content` back. This client keeps no reasoning text, so every request to the DeepSeek endpoint sends `"thinking": {"type": "disabled"}`. DeepSeek turns therefore run without thinking. +- **Reasoning effort.** Since 0.67.0 a turn may send a reasoning effort + ([ADR-0102](adr/0102-choose-a-reasoning-effort-per-session.md)): `none`, + `minimal`, `low`, `medium`, `high`, `xhigh`, or `max`, chosen per session in + the desktop model box or with CLI `chat --reasoning-effort`. Chat + Completions sends it as the top-level `reasoning_effort`; the ChatGPT plan + route sends `"reasoning": {"effort": ...}`. Nothing is sent without a + choice, so the provider's default applies. Core allows it only where the + provider documents the field: loopback `lm_studio` and `ollama_local` + endpoints, a typed `openai_compatible` address, and the fixed `ollama_cloud`, + `openai`, `google`, `moonshot`, `minimax`, `open_router`, `z_ai`, and `xai` + endpoints. The fixed `anthropic`, `deepseek`, `tencent`, `meta`, and + `thinking_machines` endpoints refuse one as an invalid configuration before + any request: Anthropic documents the field as ignored and DeepSeek as + overridden. The endpoint text decides, not the profile kind: a typed + `openai_compatible` address that is exactly one of the fixed endpoints (one + trailing `/` allowed) takes that endpoint's rule, so one typed as the + Anthropic or DeepSeek endpoint refuses an effort too. The field's bytes + count in the pre-turn context estimate. Values are not adjusted per model, + and each provider's model + decides which it accepts; a refused value arrives as that provider's HTTP + error. No request with an effort was made to any provider. - **Not covered.** Native provider APIs (for example Anthropic Messages), subscription sign-in (ChatGPT sign-in came later, with ADR-0093), provider-specific parameters such as OpenRouter - routing or reasoning settings, and reasoning text, which is ignored. + routing or its `reasoning` object, and reasoning text, which is ignored. Thinking Machines Lab documents no model list, and the desktop model box chooses only a listed model, so a Tinker model can be named only with CLI `chat --model`. diff --git a/docs/session-storage.md b/docs/session-storage.md index 654b232..650d92d 100644 --- a/docs/session-storage.md +++ b/docs/session-storage.md @@ -143,6 +143,15 @@ selection in such a session with `skill_session_version` before any request. Skill messages are never recorded, so replay and compaction never see them. A recorded assistant reply can still repeat skill text. +Since 0.67.0 a version-3 `request.manifest` may also carry `reasoning_effort`: +one of `none`, `minimal`, `low`, `medium`, `high`, `xhigh`, or `max`, the +effort the chat client sent with the turn's requests (ADR-0102). It is written +only when an effort was sent, so other journals keep their bytes, and 0.66.0 +and earlier refuse a journal that has it; the schema version did not change. +A version-1 or version-2 journal refuses the field, and chat refuses an effort +in such a session with `session` before anything is recorded. Compaction +summary requests send no effort. + | Event type | Payload in v3 | State rule | | --- | --- | --- | | `context.compacted` | `summary`, `compacted_messages`, `includes_tool_results`, `summary_sha256`, `model`, optional `prompt_tokens`, optional `completion_tokens` | Requires an idle, unarchived session. The summary is at most 16 KiB minus a fixed untrusted-source label, and the digest is the lowercase SHA-256 of the summary. The boundary is within the message history, later than any prior compaction, and followed by a user message when any message is retained. The original messages remain. |