* fix: Rate limiter returns retry after None instead of a duration
linter fix
* review fixes
* fix: rate limiter returns None for retry_after duration
Add regression test to src/llm/retry.rs that verifies RateLimited errors
always have a fallback duration (never None) due to the 60-second fallback
applied in all rate limit error creation sites (nearai_chat.rs,
anthropic_oauth.rs, embeddings.rs).
The production code fix adds `.or(Some(Duration::from_secs(60)))` to ensure
the error message never displays "retry after None" to the user.
[skip-regression-check]
Co-Authored-By: Claude Haiku 4.5 <[email protected]>
---------
Co-authored-by: Claude Haiku 4.5 <[email protected]>
- Remove duplicate build_nearai_model_fetch_config() definition from setup/wizard.rs
(function already exists in llm/models.rs and is imported)
- Add missing cheap_model and smart_routing_cascade fields to LlmConfig
initializer in build_nearai_model_fetch_config() (llm/models.rs)
- Pass request_timeout_secs to create_registry_provider() call
(llm/mod.rs:432)
All clippy checks pass with zero warnings (--no-default-features --features libsql).
Co-Authored-By: Claude Haiku 4.5 <[email protected]>
Resolved merge conflicts in 5 files:
1. src/agent/job_monitor.rs - Used is_internal flag approach (HEAD) for safe internal message marking. Removed metadata-based approach which could be spoofed by external channels.
2. src/agent/agent_loop.rs - Used is_internal check (HEAD) for routing internal messages, consistent with security model where is_internal field cannot be spoofed.
3. src/agent/dispatcher.rs - Included notify_metadata in job context (main), needed for job routing through JobMonitorRoute.
4. src/setup/wizard.rs - Added build_nearai_model_fetch_config() function (main) for model selection during setup.
5. src/tools/builtin/job.rs - Used both comments from HEAD (clarifying notify_channel and notify_user logic) while removing metadata field from JobMonitorRoute (consistent with job_monitor.rs).
All conflicts resolved with security-first approach: use is_internal boolean field for internal message marking (cannot be spoofed), while passing routing metadata through context.
Co-Authored-By: Claude Haiku 4.5 <[email protected]>
* feat: add LLM_CHEAP_MODEL for generic smart routing across all backends
Add generic cheap model support that works with any LLM backend, not just
NearAI. New env vars: LLM_CHEAP_MODEL (cheap model for any backend) and
SMART_ROUTING_CASCADE (top-level cascade flag).
Resolution order: LLM_CHEAP_MODEL > NEARAI_CHEAP_MODEL (backward compat).
Registry-based providers (OpenAI, Anthropic, Groq, etc.) clone their
RegistryProviderConfig with the cheap model swapped in. Bedrock returns
an explicit error (not yet supported). All error paths use ok_or_else
with proper LlmError variants -- no unwrap/expect in production code.
* refactor: address Gemini review — remove unnecessary async, extract cheap_model_name()
- Remove async from create_cheap_provider_for_backend() and
create_cheap_llm_provider() — neither contains .await calls
- Extract duplicated cheap model resolution logic into
LlmConfig::cheap_model_name() helper method (DRY)
- Revert tests from tokio::test async back to sync #[test]
- Add test_cheap_model_name_resolution() unit test for the helper
---------
Co-authored-by: SMKRV <[email protected]>
* feat(orchestrator): read ORCHESTRATOR_PORT env var for configurable API port
The orchestrator internal API port was hardcoded to 50051 in two places
(ContainerJobConfig and OrchestratorApi::start call), making it impossible
to run multiple IronClaw instances on the same host — the second instance
fails with "Address already in use".
NETWORK_SECURITY.md already documents ORCHESTRATOR_PORT as configurable,
and ContainerJobConfig.orchestrator_port is propagated to worker containers
via IRONCLAW_ORCHESTRATOR_URL, but the env var was never actually read.
Extract resolve_orchestrator_port() that reads ORCHESTRATOR_PORT and falls
back to 50051. Includes tests for valid, invalid, and out-of-range values.
* test: add ENV_LOCK mutex for env-var test serialization
Address Gemini review: add std::sync::Mutex to serialize env var access
across test threads. Keep unsafe blocks — required in Rust edition 2024
where std::env::set_var/remove_var are unsafe functions.
---------
Co-authored-by: SMKRV <[email protected]>
* feat(transcription): add Chat Completions API provider for audio transcription
The existing transcription pipeline only supports the OpenAI Whisper API
(/v1/audio/transcriptions with multipart upload). Providers like OpenRouter
expose audio transcription through the Chat Completions API instead, using
base64-encoded audio in the `input_audio` content type.
Add `ChatCompletionsTranscriptionProvider` that sends audio as base64 in
a chat completion request and extracts the transcript from the response.
Compatible with OpenRouter, OpenAI GPT-4o-audio, and any provider that
supports audio input via Chat Completions.
Config changes:
- TRANSCRIPTION_PROVIDER=chat_completions selects the new provider
- TRANSCRIPTION_API_KEY overrides provider-specific keys
- LLM_API_KEY used as fallback for chat_completions provider
- Default model per provider (whisper-1 for openai, gemini-2.0-flash for
chat_completions)
* style: address review feedback — formatting, idiomatic patterns
- Fix rustfmt formatting for provider constructor chain
- Use or_else for resolve_api_key priority chain (Gemini review)
- Use trim_end_matches('/') instead of while loop (Gemini review)
---------
Co-authored-by: SMKRV <[email protected]>
* fix(jobs): make completed->completed transition idempotent to prevent race errors
Both execution_loop and the worker wrapper in execute() can race to call
mark_completed(). Previously the second call hit "Cannot transition from
completed to completed" and errored the job despite successful completion.
This narrowly allows only the Completed->Completed self-transition as
idempotent (early return with debug log, no duplicate history entry).
All other self-transitions remain rejected to preserve state machine
strictness.
Co-Authored-By: Claude Opus 4.6 <[email protected]>
* style: fix assert! formatting in idempotent completion test
Co-Authored-By: Claude Opus 4.6 <[email protected]>
---------
Co-authored-by: Claude Opus 4.6 <[email protected]>
* fix(llm): persist refreshed Anthropic OAuth token after Keychain re-read (#1136)
The Anthropic OAuth provider stored its token as an immutable SecretString.
When a 401 triggered a Keychain re-read, the fresh token was used for a
single retry but never persisted — every subsequent request reused the
expired original token, causing repeated auth failures.
Changes:
- Wrap token in RwLock<SecretString> so it can be updated after refresh
- Persist refreshed token via update_token() on successful retry
- Add 500ms delay before Keychain re-read to give Claude Code time to
complete its async token refresh write (reduces race window)
- Add regression test verifying token updates persist across reads
Closes#1136
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
* style: fix formatting
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
---------
Co-authored-by: Claude Opus 4.6 (1M context) <[email protected]>
* fix(worker): prevent orphaned tool_results and fix parallel merging
Two fixes for tool result handling in the Worker:
1. Preserve reasoning text from select_tools() in the RespondResult
content field so it appears in the assistant_with_tool_calls message
pushed by execute_tool_calls. Without this, the LLM's reasoning
context was lost when using the select_tools path.
2. Merge consecutive tool_result messages into a single User message
in rig_adapter's convert_messages(). When parallel tools execute,
each produces a separate ChatMessage with role: Tool. Without
merging, these become consecutive User messages which Anthropic
rejects. Now consecutive tool results are merged into one User
message with multiple ToolResult content items.
Includes regression tests for both fixes.
Co-Authored-By: Claude Opus 4.6 <[email protected]>
* fix(worker): use find_map for first non-empty reasoning extraction
The previous code only checked the first ToolSelection's reasoning,
missing cases where the first selection has empty reasoning but
subsequent ones do not. Switch to find_map to get the first non-empty
reasoning across all selections.
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
---------
Co-authored-by: Claude Opus 4.6 <[email protected]>
* feat(heartbeat): fire_at time-of-day scheduling with IANA timezone support
- HEARTBEAT_FIRE_AT=HH:MM — fire heartbeat at a specific time of day instead
of on a rolling interval; format is 24h HH:MM (e.g. "14:00")
- HEARTBEAT_TIMEZONE=Region/City — IANA timezone name for fire_at (e.g.
"Pacific/Auckland", "America/New_York"). Defaults to UTC.
- When fire_at is set, interval_secs is ignored
- Config also readable from settings.toml [heartbeat] section
Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
* feat(heartbeat): wire fire_at + timezone into HeartbeatConfig runner
Missed file from heartbeat scheduling commit. HeartbeatConfig struct in
agent/heartbeat.rs now carries fire_at: Option<NaiveTime> and timezone: Tz
so the runner can schedule against a fixed time of day.
Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
* fix: add chrono-tz dependency for heartbeat fire_at timezone support
The chrono-tz crate was used in the heartbeat fire_at commits but
its Cargo.toml entry was lost during rebase conflict resolution.
Co-Authored-By: Claude Opus 4.6 <[email protected]>
* style: rustfmt fix for chained method call
Co-Authored-By: Claude Opus 4.6 <[email protected]>
* test(heartbeat): add fire_at scheduling and DST safety tests
- test_default_config_has_no_fire_at: interval-based default unchanged
- test_with_fire_at_builder: builder sets time and timezone
- test_duration_until_next_fire_is_bounded: result always 1s–24h
- test_duration_until_next_fire_dst_timezone_no_panic: US Eastern DST
- test_resolved_tz_defaults_to_utc: missing timezone falls back to UTC
- test_resolved_tz_parses_iana: IANA string resolves correctly
Co-Authored-By: Claude Opus 4.6 <[email protected]>
* fix(heartbeat): restore drift-free interval, add settings.json fallback for fire_at
- Interval path: restore tokio::time::interval (drift-free) instead of
tokio::time::sleep which drifts by loop body execution time
- fire_at config: fall back to settings.heartbeat.fire_at when
HEARTBEAT_FIRE_AT env var is not set, consistent with other settings
Addresses Gemini Code Assist review feedback.
Co-Authored-By: Claude Opus 4.6 <[email protected]>
---------
Co-authored-by: IronClaw <[email protected]>
Co-authored-by: Claude Sonnet 4.6 <[email protected]>
* feat: add Codex auth.json token reuse for LLM authentication
When LLM_USE_CODEX_AUTH=true, IronClaw reads the Codex CLI's auth.json
(default ~/.codex/auth.json) and extracts the API key or OAuth access
token. This lets IronClaw piggyback on a Codex login without
implementing its own OAuth flow.
New env vars:
- LLM_USE_CODEX_AUTH: enable Codex auth fallback (default: false)
- CODEX_AUTH_PATH: override path to auth.json
* fix: handle ChatGPT auth mode correctly
Switch base_url to chatgpt.com/backend-api/codex when auth.json
contains ChatGPT OAuth tokens. The access_token is a JWT that only
works against the private ChatGPT backend, not the public OpenAI API.
Refactored codex_auth.rs to return CodexCredentials (token +
is_chatgpt_mode) instead of just a string key.
* fix: Codex auth takes highest priority over secrets store
When LLM_USE_CODEX_AUTH=true, Codex credentials are now loaded before
checking env vars or the secrets store overlay. Previously the secrets
store key (injected during onboarding) would shadow the Codex token.
* feat: Responses API provider for ChatGPT backend
- New CodexChatGptProvider speaks the Responses API protocol
- Auto-detects model from /models endpoint (gpt-4o -> gpt-5.2-codex)
- Adds store=false (required by ChatGPT backend)
- Error handling with timeout for HTTP 400 responses
- Message format translation: Chat Completions -> Responses API
- SSE response parsing for text, tool calls, and usage stats
- 7 unit tests for message conversion and SSE parsing
* fix: SSE parser uses item_id instead of call_id for tool call deltas
The Responses API sends function_call_arguments.delta events with
item_id (e.g. fc_...) not call_id (e.g. call_...). The parser now
keys pending tool calls by item_id from output_item.added and
tracks call_id separately for result matching.
* fix: strip empty string values from tool call arguments
gpt-5.2-codex fills optional tool parameters with empty strings
(e.g. timestamp: ""), which IronClaw's tool validation rejects.
Strip them before passing to tool execution.
* fix: prevent apiKey mode fallback to ChatGPT token
When auth_mode is explicitly 'apiKey' but the key is missing/empty,
do not fall through to check for a ChatGPT access_token. This prevents
returning credentials with is_chatgpt_mode: true and routing to the
wrong LLM provider.
* refactor: reuse single reqwest::Client across model discovery and LLM calls
Create Client once in with_auto_model, pass &Client to
fetch_default_model, and move it into the provider struct.
Eliminates the redundant Client::new() that wasted a connection pool.
* fix: bump client_version to 1.0.0 to unlock gpt-5.3-codex and gpt-5.4
The /models endpoint gates newer models behind client_version.
Version 0.1.0 only returns up to gpt-5.2-codex, while 1.0.0+
also returns gpt-5.3-codex and gpt-5.4.
* feat: user-configured LLM_MODEL takes priority over auto-detection
Fetch the full model list from /models endpoint. If LLM_MODEL is set,
validate it against the supported list and warn with available models
if not found. If LLM_MODEL is not set, auto-detect the highest-priority
model. Also bumps client_version to 1.0.0 to unlock gpt-5.3/5.4.
* fix: add 10s timeout to model discovery HTTP request
Prevents startup from blocking indefinitely if chatgpt.com
is slow or unreachable. Uses reqwest per-request timeout.
* docs: add private API warning for ChatGPT backend endpoint
The chatgpt.com/backend-api/codex endpoint is private and
undocumented. Add warning in module docs and a runtime log
on first use to inform users of potential ToS implications.
* feat: implement OAuth 401 token refresh for Codex ChatGPT provider
On HTTP 401, if a refresh_token is available, the provider now
automatically refreshes the access token via auth.openai.com/oauth/token
(same protocol as Codex CLI) and retries the request once. Refreshed
tokens are persisted back to auth.json.
Changes:
- codex_auth: read refresh_token, add refresh_access_token() and
persist_refreshed_tokens()
- codex_chatgpt: RwLock for api_key, 401 detection + retry in
send_request, send_http_request helper
- config/llm: thread refresh_token/auth_path through RegistryProviderConfig
- llm/mod: pass refresh params to with_auto_model
* refactor: lazy model detection via OnceCell, remove block_in_place
Model is no longer resolved during provider construction. Instead,
resolve_model() uses tokio::sync::OnceCell to lazily fetch from
/models on the first LLM call. This eliminates the block_in_place
+ block_on workaround in create_codex_chatgpt_from_registry.
- with_auto_model (async) -> with_lazy_model (sync constructor)
- resolve_model() added with OnceCell-based lazy init
- build_request_body takes model as parameter
- model_name() returns resolved or configured_model as fallback
* feat: support multimodal content (images) in Codex ChatGPT provider
message_to_input_items now checks content_parts for user messages.
ContentPart::Text maps to input_text and ContentPart::ImageUrl maps
to input_image, matching the Responses API format used by Codex CLI.
Falls back to plain text when content_parts is empty.
Also updates client_version to 0.111.0 for /models endpoint.
Adds test: test_message_conversion_user_with_image
* refactor: move codex_auth module from src/ to src/llm/
codex_auth is only used by the LLM layer (codex_chatgpt provider
and config/llm). Moving it under src/llm/ reflects its actual scope.
- Remove pub mod codex_auth from lib.rs
- Add pub mod codex_auth to llm/mod.rs
- Update imports: super::codex_auth, crate::llm::codex_auth
* Fix codex provider style issues
* Use SecretString throughout codex auth refresh flow
* Use SecretString for codex access tokens
* Reuse provider client for codex token refresh
* Stream Codex SSE responses incrementally
* Fix Windows clippy and SQLite test linkage
* Trigger checks after regression skip label
* Tighten codex auth module handling
* refactor(setup): extract init logic from wizard into owning modules
Move database, LLM model discovery, and secrets initialization logic
out of the setup wizard and into their owning modules, following the
CLAUDE.md principle that module-specific initialization must live in
the owning module as a public factory function.
Database (src/db/mod.rs, src/config/database.rs):
- Add DatabaseConfig::from_postgres_url() and from_libsql_path()
- Add connect_without_migrations() for connectivity testing
- Add validate_postgres() returning structured PgDiagnostic results
LLM (src/llm/models.rs — new file):
- Extract 8 model-fetching functions from wizard.rs (~380 lines)
- fetch_anthropic_models, fetch_openai_models, fetch_ollama_models,
fetch_openai_compatible_models, build_nearai_model_fetch_config,
and OpenAI sorting/filtering helpers
Secrets (src/secrets/mod.rs):
- Add resolve_master_key() unifying env var + keychain resolution
- Add crypto_from_hex() convenience wrapper
Wizard restructuring (src/setup/wizard.rs):
- Replace cfg-gated db_pool/db_backend fields with generic
db: Option<Arc<dyn Database>> + db_handles: Option<DatabaseHandles>
- Delete 6 backend-specific methods (reconnect_postgres/libsql,
test_database_connection_postgres/libsql, run_migrations_postgres/
libsql, create_postgres/libsql_secrets_store)
- Simplify persist_settings, try_load_existing_settings,
persist_session_to_db, init_secrets_context to backend-agnostic
implementations using the new module factories
- Eliminate all references to deadpool_postgres, PoolConfig,
LibSqlBackend, Store::from_pool, refinery::embed_migrations
Net: -878 lines from wizard, +395 lines in owning modules, +378 new.
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
* test(settings): add wizard re-run regression tests
Add 10 tests covering settings preservation during wizard re-runs:
- provider_only rerun preserves channels/embeddings/heartbeat
- channels_only rerun preserves provider/model/embeddings
- quick mode rerun preserves prior channels and heartbeat
- full rerun same provider preserves model through merge
- full rerun different provider clears model through merge
- incremental persist doesn't clobber prior steps
- switching DB backend allows fresh connection settings
- merge preserves true booleans when overlay has default false
- embeddings survive rerun that skips step 5
These cover the scenarios where re-running the wizard would
previously risk resetting models, providers, or channel settings.
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
* refactor(setup): eliminate cfg(feature) gates from wizard methods
Replace compile-time #[cfg(feature)] dispatch in the wizard with
runtime dispatch via DatabaseBackend enum and cfg!() macro constants.
- Merge step_database_postgres + step_database_libsql into step_database
using runtime backend selection
- Rewrite auto_setup_database without feature gates
- Remove cfg(feature = "postgres") from mask_password_in_url (pure fn)
- Remove cfg(feature = "postgres") from test_mask_password_in_url
Only one internal #[cfg(feature = "postgres")] remains: guarding the
call to db::validate_postgres() which is itself feature-gated.
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
* refactor(db): fold PG validation into connect_without_migrations
Move PostgreSQL prerequisite validation (version >= 15, pgvector)
from the wizard into connect_without_migrations() in the db module.
The validation now returns DatabaseError directly with user-facing
messages, eliminating the PgDiagnostic enum and the last
#[cfg(feature)] gate from the wizard.
The wizard's test_database_connection() is now a 5-line method that
calls the db module factory and stores the result.
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
* fix: address PR review comments [skip-regression-check]
- Use .as_ref().map() to avoid partial move of db_config.libsql_path
(gemini-code-assist)
- Default to available backend when DATABASE_BACKEND is invalid, not
unconditionally to Postgres which may not be compiled (Copilot)
- Match DatabaseBackend::Postgres explicitly instead of _ => wildcard
in connect_with_handles, connect_without_migrations, and
create_secrets_store to avoid silently routing LibSql configs through
the Postgres path when libsql feature is disabled (Copilot)
- Upgrade Ollama connection failure log from info to warn with the
base URL for better visibility in wizard UX (Copilot)
- Clarify crypto_from_hex doc: SecretsCrypto validates key length,
not hex encoding (Copilot)
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
* fix: address zmanian's PR review feedback [skip-regression-check]
- Update src/setup/README.md to reflect Arc<dyn Database> flow
- Remove stale "Test PostgreSQL connection" doc comment
- Replace unwrap_or(0) in validate_postgres with descriptive error
- Add NearAiConfig::for_model_discovery() constructor
- Narrow pub to pub(crate) for internal model helpers
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
* fix: address Copilot review comments (quick-mode postgres gate, empty env vars) [skip-regression-check]
- Gate DATABASE_URL auto-detection on POSTGRES_AVAILABLE in quick mode
so libsql-only builds don't attempt a postgres connection
- Match empty-env-var filtering in key source detection to align with
resolve_master_key() behavior
- Filter empty strings to None in DatabaseConfig::from_libsql_path()
for turso_url/turso_token
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
---------
Co-authored-by: Claude Opus 4.6 (1M context) <[email protected]>
The `__internal_job_monitor` metadata key that bypassed the entire
agent pipeline (hooks, safety checks, LLM processing) was spoofable
by external channels — WASM channel plugins could inject arbitrary
metadata including this key, causing attacker-controlled content to be
forwarded directly as assistant responses.
Replace the metadata-based check with a dedicated `is_internal` field
on `IncomingMessage` that can only be set via `into_internal()` by
trusted in-process code. Both the field and setter are `pub(crate)` to
prevent external crates from spoofing the flag. Also remove
`notify_metadata` forwarding (the monitor only needs channel/user/thread
routing) and the unused `__job_monitor_job_id` metadata key.
Co-authored-by: Claude Opus 4.6 (1M context) <[email protected]>
When a tunnel provider (ngrok, cloudflare, tailscale, etc.) or static
TUNNEL_URL is configured, external traffic arrives through the tunnel,
so binding 0.0.0.0 is unnecessary attack surface. The webhook server
now defaults to 127.0.0.1 when a tunnel is active. Explicit HTTP_HOST
still overrides the default in all cases.
Co-authored-by: Claude Opus 4.6 <[email protected]>
* fix(auth): avoid false success and block chat while auth pending
* fix(web): clear stale auth UI on failure and add setup regression test
* Update src/agent/thread_ops.rs
Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
* fix(fmt): place auth activation comment on separate line
---------
Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
Co-authored-by: Illia Polosukhin <[email protected]>
ChannelsConfig::resolve() ignored most ChannelSettings fields, reading
exclusively from env vars. This made `config set` ineffective for gateway,
HTTP, CLI, and WASM channel settings — a prerequisite blocker for #86
(hot-reload) and CLI management commands.
- Add gateway and CLI fields to ChannelSettings with correct defaults
- Rewrite resolve() to fall back to settings when env var is unset
- Keep strict boolean validation via parse_bool_env for all bool fields
- Fix GATEWAY_PORT default divergence (3001 -> 3000) in extension manager
- Export DEFAULT_GATEWAY_PORT constant as single source of truth
- Add 8 tests: settings fallback, env override, DB roundtrip, invalid bool rejection
Part of #1119 (Phase 1: Channels pilot)
[skip-regression-check]
LLMs sometimes pass "" for optional parameters instead of omitting them.
Previously, passing url: "" to skill_install would match the explicit-URL
branch and attempt to fetch from an empty string, producing an invalid URL
error instead of falling back to the catalog lookup.
Fix by adding .filter(|s| !s.is_empty()) so an empty url is treated the
same as a missing field.
A unit test verifies the parameter filtering behaviour directly; the full
execute path (catalog lookup + install) requires a real catalog and database
and cannot be covered at the unit level.
* fix(mcp): cache oauth client init error as AuthError
* Update src/tools/mcp/auth.rs
Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
* fix(mcp): use AuthError::Http in oauth client cache and add regression test
* test(mcp): annotate test assert for no-panics CI matcher
---------
Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
* fix(web): handle Safari IME composition Enter key
Safari sets e.isComposing=false on the keydown event that ends IME
composition, unlike Chrome/Firefox. This caused pressing Enter to confirm
CJK input to immediately send the message.
Track composition state manually via compositionstart/compositionend and
guard the send condition with both e.isComposing and _isComposing.
Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
* fix(web): improve Safari IME comment with WebKit bug reference
Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
---------
Co-authored-by: Claude Sonnet 4.6 <[email protected]>
* fix(mcp): handle 400 auth errors, clear auth mode after OAuth, trim tokens
Three bugs prevented MCP server authentication (e.g. GitHub MCP) from
working correctly:
1. **400 treated as auth-required**: GitHub's MCP endpoint returns 400
"Authorization header is badly formatted" instead of 401 when auth
is missing. Broadened auth detection in activate_mcp, send_request,
and discover_via_401 to also match 400+authorization errors.
2. **Auth mode not cleared after OAuth callback**: The OAuth callback
handler and setup submit handler did not call clear_auth_mode(),
leaving pending_auth on the thread. The next user message was
intercepted as a token instead of triggering an LLM turn.
3. **Token trimming**: Tokens with leading/trailing whitespace or
newlines produced malformed Authorization headers. Now trimmed
before storage (configure) and before use (build_request_headers).
Adds E2E tests with a mock MCP server (JSON-RPC + OAuth discovery +
DCR + token exchange) covering install -> activate -> OAuth callback ->
LLM turn lifecycle, plus a GitHub-style 400 error variant.
[skip-regression-check]
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
* fix(mcp): add TTL to PendingAuth and clear auth mode on all failure paths
Auth mode (pending_auth on a Thread) had no timeout and several code
paths that failed to clear it, causing user messages to be swallowed
indefinitely. This adds defense-in-depth:
- Add created_at + 5-minute TTL to PendingAuth; auto-clear on next
message if expired (safety net for edge cases like user closing
browser mid-OAuth)
- Clear auth mode on OAuth callback failure paths (unknown/consumed
state, expired flow)
- Move clear_auth_mode before configure() match in setup_submit so
it runs on failure too (addresses Copilot review feedback)
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
* fix(ci): exclude test hunks from unwrap/assert pre-commit check
The pre-commit safety script only excluded files in tests/ but not
#[cfg(test)] mod tests blocks inside src/ files. Use the git diff @@
hunk header context (which includes the enclosing function name) to
detect and skip test hunks.
Also removes unnecessary // safety: comments from test assertions.
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
* fix: restore formatting in test assertions
The replace_all edit that removed // safety: comments collapsed
newlines. Restore proper line breaks.
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
* fix: address Copilot review - tighten pre-commit filter, document TTL sync
- pre-commit-safety.sh: only exclude `mod tests` hunks (not `fn test_*`)
to avoid hiding unwrap/assert in production functions like test_server()
- session.rs: extract AUTH_MODE_TTL_SECS constant and add doc comment
linking to OAUTH_FLOW_EXPIRY to prevent silent drift
[skip-regression-check]
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
* fix(mcp): return error on expired auth input, clear auth on all OAuth paths
- When auth mode TTL expires and the user sends a message (possibly a
pasted token), return an explicit "expired, please retry" response
instead of forwarding the content to the LLM/history
- Add clear_auth_mode() to all early-return paths in oauth_callback_handler
(provider error, missing state/code, no extension manager)
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
---------
Co-authored-by: Claude Opus 4.6 (1M context) <[email protected]>
* fix: eliminate panic paths in production code and document infallible operations
PolicyRule::new() now returns Result instead of panicking on invalid
caller-supplied regex. CreateJobTool returns ToolError when job_manager
is unconfigured instead of panicking. Remaining infallible unwrap/expect
calls (hardcoded regexes, compile-time constants, guarded accesses)
are annotated with SAFETY comments. Where possible, unwraps are replaced
with safer patterns: split_last(), if-let, match-destructure, and
reusing peek() values.
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
* fix: use inline lowercase safety comments to match CI pattern
The no-panics CI check greps for '// safety:' (lowercase, inline)
to suppress false positives. Switch from block SAFETY comments to
inline safety comments on the .unwrap() lines.
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
* test: add regression tests for panic-path fixes
- PolicyRule::new returns Err on invalid regex (not panic)
- CreateJobTool::execute_sandbox returns ToolError when job_manager is None
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
* fix: add inline // safety: comments on all infallible unwrap/expect lines
The CI no-panics check requires '// safety:' on the same line as
unwrap()/expect() to suppress false positives. Move safety annotations
from block comments to inline comments on every infallible production
unwrap/expect across all touched files.
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
* chore: trigger CI with skip-regression-check label
[skip-regression-check]
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
* refactor: remove redundant block-level SAFETY comments
Each unwrap/expect now carries its own inline // safety: annotation,
making the standalone block comments above them redundant.
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
---------
Co-authored-by: Claude Opus 4.6 (1M context) <[email protected]>
* fix(llm): add stop_sequences parity for tool completions
* refactor(web-openai): dedupe request builders and satisfy no-panics gate
* test(llm): mark multiline assert with safety comment for CI gate
* test(llm): make safety-marked assert formatting-stable