Commit Graph
119 Commits
Author SHA1 Message Date
TechBrewBossandGitHub ed7b6972f9 Feat: Add startup logo palette picker (#1072)
* Add startup logo palette picker

* Address logo picker review feedback
2026-05-09 00:01:53 +08:00
TechBrewBossandGitHub 16726399d8 fix plan mode branding and plan path (#1062) 2026-05-08 15:30:41 +08:00
0xfandomandGitHub feb5791320 fix(effort): persist xhigh and send reasoning_effort on chat_completions (#857)
* fix(effort): persist xhigh and send reasoning_effort on chat_completions

Fixes #853.

Persistence:
- EffortPicker.handleSelect normalizes the OpenAI-shaped `xhigh` to the
  standard `max` before writing AppState/settings. Previously `xhigh` fell
  through `toPersistableEffort` as undefined and the setting reverted on
  reload.
- `/effort xhigh` takes the same normalization path.
- `toPersistableEffort` maps `xhigh` -> `max` as a defensive backstop.
- EffortPicker initialFocus reflects the user's stored selection
  (`max` shown as `xhigh`) instead of always snapping to the alias default.

Payload:
- openaiShim chat_completions body now emits `reasoning_effort` from
  `request.reasoning.effort`. Previously only codex_responses transport
  forwarded it, so Custom API users on chat_completions got no effort.
- `getAnthropicClient` accepts `effortValue` and forwards it as
  `reasoningEffort` to `createOpenAIShimClient` (both providerOverride
  and direct-OpenAI paths) after converting `max` -> `xhigh` at the
  OpenAI boundary via `standardEffortToOpenAI`.
- `claude.ts` threads the resolved effort through main streaming and
  both non-streaming fallback call sites.

Tests:
- openaiShim.test.ts: reasoning_effort emitted when override is passed,
  omitted otherwise, falls back to codex alias default.
- effort.codex.test.ts: xhigh -> max normalization and
  standard<->OpenAI conversion.

* fix(effort): skip max→high clamp for OpenAI/Codex models

resolveAppliedEffort() unconditionally downgraded any non-Opus 'max'
to 'high'. OpenAI/Codex models use 'max' as the standard internal form
of 'xhigh' (the client shim converts on the wire), so the clamp was
silently turning xhigh selections into high.

The picker stored xhigh→max correctly and the shim emitted
reasoning_effort, but the resolver in between rewrote max→high before
the shim ever saw it. End result: UI showed xhigh, request sent high.

Skip the clamp when modelUsesOpenAIEffort(model). Anthropic non-Opus
clamp behavior unchanged.

Adds two e2e tests in effort.codex.test.ts walking the full chain
(persist → resolve → wire) so the regression can't recur silently.

* test(effort): keep mocked module surfaces compatible with downstream tests

bun:test's `mock.module()` is process-global and is not undone by
`mock.restore()` (see comment in user.test.ts). When this file mocked
`./auth.js`, `./thinking.js`, `../services/api/providerConfig.js`, etc.
with reduced surfaces, later test files that imported the missing
exports (refreshAndGetAwsCredentials, getRainbowColor, ...) crashed at
module load with `SyntaxError: Export named 'X' not found`.

Spread the real module exports into each mock factory so subsequent
imports keep the full surface, while the targeted overrides for this
file's tests still take effect.
2026-05-06 21:17:44 +08:00
094f04c803 fix(theme): remove stale memo wrappers from theme context hooks (#534)
* fix(theme): remove stale React Compiler memo wrappers from theme hooks

Rebase on current main (includes #589 reconciler fix).

The React Compiler memo caches (_c) in useTheme() and usePreviewTheme()
use referential equality checks on destructured context values. These
caches can return stale references when the ThemeProvider's useMemo
recreates the context value object but the individual property
references (setThemeSetting, setPreviewTheme, etc.) compare equal —
the memo short-circuits and returns a cached tuple/object that still
holds the old closure captures.

This is a distinct bug from #589 (which fixed the ink reconciler's
commitUpdate path for host prop updates). #589 ensures that when
React _does_ re-render a component with new props, those props actually
reach the DOM node. But the memo wrappers here prevent React from
_even seeing_ the new context value in the first place — the hook
returns the stale cached result.

Removing the memo wrappers ensures useTheme() and usePreviewTheme()
always read the current context value, eliminating the stale-reference
path entirely.

* test(theme): add regression tests for useTheme()/usePreviewTheme() stale-value bug

These tests verify that context hooks always return fresh values after
ThemeProvider re-renders, even when React Compiler memo caches are in play.

- useTheme() must reflect currentTheme changes immediately after
  setThemeSetting is called (not return a stale cached tuple).
- usePreviewTheme() must return functional actions after context
  re-renders (not stale closures from before the theme change).

On current main (with _c memo wrappers), these tests expose the bug:
the memo cache compares setThemeSetting by reference (stable across
renders via useMemo) and short-circuits, returning the old cached result
with stale currentTheme.

* fix(test): correct import paths for ThemeProvider.test.tsx

Fix relative paths for ink.js, KeybindingSetup, AppStateProvider,
useStdin mock, systemTheme mock, and config mock to account for
the test file being in src/components/design-system/ rather than
src/components/.

* fix(test): rewrite ThemeProvider tests using Ink renderer

Use Ink's createRoot instead of react-dom/client, matching the pattern
from ThemePicker.test.tsx. The tests now render through Ink's terminal
renderer and check frame output for theme values, which is the same
environment ThemeProvider actually runs in.

* fix(test): correct all relative import paths for design-system/ depth

- ink.js, KeybindingSetup, AppStateProvider: ../ → ../../
- StructuredDiff: same pattern as ThemePicker test adjusted for depth

---------

Co-authored-by: root <root@vm7508.lumadock.com>
2026-05-05 18:38:48 +08:00
7b02695b15 Feat/codex default provider (#1014)
* chore: add .openclaude/ to gitignore

The .openclaude/ directory contains auto-generated project-local files
(wiki pages, convention cache, local settings) that should not be
committed to the repository.

Co-Authored-By: OpenClaude <openclaude@gitlawb.com>

* feat: make Codex + GPT 5.5 the default provider and model

Changes the default provider to Codex and default model to GPT 5.5:

- package.json: dev script now uses provider-launch.ts codex
- providerRecommendation.ts: getGoalDefaultOpenAIModel returns gpt-5.5
  for coding and balanced goals (was gpt-4o)
- providerConfig.ts: fallback model changed from gpt-4o to codexplan
  (resolves to gpt-5.5)
- ProviderManager.tsx: Codex OAuth option now shows green
  "★ Recommended" badge in the provider picker

Co-Authored-By: OpenClaude <openclaude@gitlawb.com>

* fix: replace Box with nested Text in Codex label

Ink's <Text> component cannot contain <Box>. The label is rendered
inside a <Text> parent, so use nested <Text> elements instead.

Co-Authored-By: OpenClaude <openclaude@gitlawb.com>

* fix: default to Codex when no provider profile is saved

When no persisted provider profile exists (fresh install / first run),
buildStartupEnvFromProfile now injects Codex + GPT 5.5 env vars instead
of returning process.env unchanged. Falls back gracefully — if Codex
credentials are available (OAuth or existing), uses those; otherwise
injects base URL and model defaults so the provider picker shows
GPT 5.5 as the default.

This closes the gap where node dist/cli.mjs (production start) would
default to firstParty (Anthropic) when no profile or env vars were set.

Co-Authored-By: OpenClaude <openclaude@gitlawb.com>

* chore: resolve stash conflict markers from accidental stash pop

Cleans up merge conflict artifacts left by a git stash pop from an
unrelated branch (chore/add-atomic-chat-partner). Kept upstream
(current branch) version in all cases.

Co-Authored-By: OpenClaude <openclaude@gitlawb.com>

* fix: restore memoize import and cleanup stash artifacts

Restores the memoize import dropped during conflict resolution in
modelSupportOverrides.ts. Removes duplicate originalEnv declaration
and redundant delete statements in providerValidation.test.ts.

Co-Authored-By: OpenClaude <openclaude@gitlawb.com>

* revert change in package.json

* fix broken test

* fix color

---------

Co-authored-by: OpenClaude <openclaude@gitlawb.com>
2026-05-05 18:13:33 +08:00
TechBrewBossandGitHub a8f71f3ac0 Fix user agent loading from OpenClaude config dirs (#972)
* Load OpenClaude agents from config dir

* Address agent path review feedback
2026-05-04 16:26:06 +08:00
TechBrewBossandGitHub 884746dbe9 Provider: Add Hicap gateway provider (#979)
* Add Hicap provider and gateway auth presets

* Fix Hicap compatibility preset coverage

* Authenticate ripgrep download in PR checks

* Use Opus 4.7 as Hicap default

* Address Hicap review feedback

* Address provider review blockers

* Clarify gateway header UI docs

* Remove Hicap endpoint from README
2026-05-04 16:21:11 +08:00
JATMNandGitHub 3d791bf07f Disable feedback/mobile commands and refresh OpenClaude branding (#980)
- disable /feedback and /mobile from command availability while keeping implementation code in place
- remove or rewrite lingering user guidance that pointed to /feedback or /mobile
- switch HelpV2 to a public build version helper and fix the help dialog wrapper regression
- update OpenClaude-facing links and prompt copy for issue reporting and branding consistency
2026-05-04 16:18:17 +08:00
990a5a2afb fix(tests): resolve flakiness due to module leak and env state leakage (#988)
- StartupScreen.test.ts: Scope settings module mock to prevent process-global pollution.
- providerConfig.github.test.ts: Explicitly scrub environment variables before each test.
- providerProfiles.test.ts: Add beforeEach to clear RESTORED_KEYS and ensure fresh registry state.
- providerValidation.test.ts: Ensure integrations registry is loaded and scrub environment to prevent leakage from host shell.

This consolidates fixes from PR 944 and addresses additional failures found after rebasing onto main (v0.8.0).

Co-authored-by: Kevin Codex <kevin@gitlawb.com>
2026-05-03 07:19:16 +08:00
JATMNandGitHub d948769dd5 feat: rework release notes around GitHub releases (#981)
* feat: rework release notes around GitHub releases

- switch /release-notes from upstream changelog parsing to OpenClaude GitHub release data
- add a public build version helper and use it for release URL/seen-version tracking
- render release notes in-app with section headers like Features and Bug Fixes
- cache serialized GitHub release notes locally for startup and command fallback paths
- preserve snake_case identifiers while sanitizing markdown content
- keep LogoV2 whats-new output within its display budget
- add focused tests for parsing, formatting, version tags, and display slicing

* Normalize release-please changelog versions

Use normalizePublicVersion when parsing cached changelog headings so release-please markdown headings like ## [0.8.0](...) (2026-05-02) map to the expected version key.

Also normalize direct version lookups consistently and add a regression test covering getReleaseNotesForVersion and getRecentReleaseNotes against the new CHANGELOG.md format.
2026-05-02 20:26:58 +08:00
35f86a9580 fix(startup): make CLAUDE logo D distinct (#986)
* fix(startup): make CLAUDE logo D distinct

Adjust the startup ASCII logo so the D in CLAUDE no longer reads as an O, and add a focused regression test for the rendered shape.

Co-authored-by: Cursor <cursoragent@cursor.com>

* test(startup): clear CI flag for logo rendering assertion

Ensure the startup logo regression test exercises the interactive render path under GitHub Actions, where CI is set by default.

Co-authored-by: Cursor <cursoragent@cursor.com>

---------

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-02 20:20:20 +08:00
95a817fdb0 fix(provider): apply Codex OAuth session switch correctly (#974)
* fix(provider): apply Codex OAuth session switch correctly

Ensure Codex OAuth activation in an existing session does not briefly apply an empty OpenAI API key, preventing missing Authorization headers until restart.

Co-Authored-By: OpenClaude <openclaude@gitlawb.com>

* fix(provider): preserve explicit env for Codex API profiles

Limit the Codex session-switch override to OAuth profiles so explicit OpenAI environment settings keep taking precedence for regular Codex profiles.

Co-Authored-By: OpenClaude <openclaude@gitlawb.com>

* fix(provider): isolate Codex OAuth env from ambient credentials

Keep Codex OAuth profile activation from inheriting ambient Codex API credentials so CI and user shells cannot poison the in-session OAuth regression path.

Co-Authored-By: OpenClaude <openclaude@gitlawb.com>

---------

Co-authored-by: OpenClaude <openclaude@gitlawb.com>
2026-05-02 10:24:13 +08:00
a46b31c3ec feat: SDK Core — Permission System, Async Context, and Engine Extensions (#951)
* feat(sdk): add SDK foundation — type declarations, errors, and utilities

Adds standalone SDK building blocks with no SDK source dependencies:
- sdk.d.ts: ambient type declarations for SDK bundle
- coreSchemas.ts + coreTypes.generated.ts: Zod schemas and generated types
- errors.ts: SDK-specific error classes
- validation.ts: input validation utilities
- messageFilters.ts: extracted message filter logic
- handlePromptSubmit.ts: imports from messageFilters
- 16 generated-types tests

* fix(sdk): narrow assertFunction type from broad Function to callable signature

Code review finding: assertFunction used `asserts value is Function` which
accepts any function-like value without narrowing. Changed to
`(...args: any[]) => any` for better type safety.

* fix(sdk): update sdk.d.ts header — manually maintained, not generated

Reviewer noted the header said "Generated from index.ts" but no generator
produces this file. Updated to "Manually maintained — keep in sync with
index.ts". Drift detection added in validate-externals.ts (PR 3).

* fix(sdk): align sdk.d.ts types with canonical coreTypes.generated.ts

Tighten SDK public type contract to resolve reviewer blockers:

- PermissionResult: unknown[] → precise 6-shape discriminated union
  (addRules/replaceRules/removeRules/setMode/addDirectories/removeDirectories)
- SDKSessionInfo: snake_case → camelCase (sessionId, lastModified, etc.)
- ForkSessionResult: session_id → sessionId
- SDKPermissionRequestMessage: uuid + session_id now required
- SDKPermissionTimeoutMessage: added uuid + session_id
- SessionMessage: parent_uuid → parentUuid
- SDKMessage/SDKUserMessage/SDKResultMessage: replaced loose inline
  definitions with re-exports from coreTypes.generated.ts

* feat(sdk): wire existing code modules + SDK shared utilities

Modifies core modules for SDK integration:
- QueryEngine, tools, state, commands: SDK type hooks
- SDK shared utilities (shared.ts, permissions.ts)
- 21 SDK tests (shared-utils, permissions)

Stack: main ← pr1-foundation ← pr2-sdk-core

* feat(sdk): add snake_case ↔ camelCase key mapping utilities

casing.ts provides recursive key transformation for the SDK boundary
layer. Internal runtime uses snake_case; public API exposes camelCase.
Will be used by shared.ts, sessions.ts, query.ts at export boundaries.

* test(sdk): add tests for snake_case ↔ camelCase mapping utilities

Covers snakeToCamel, camelToSnake, mapKeysToCamel, mapKeysToSnake
including nested objects, arrays, null/undefined, and round-trips.

* fix(sdk): prevent permission timeout race condition with once-only resolve wrapper

Add createOnceOnlyResolve utility to prevent double-resolution of promises
when timeout and host response happen simultaneously. This ensures
deterministic behavior in the permission handling flow.

* fix(sdk): improve race condition test robustness

* fix(sdk): handle consecutive underscores in snakeToCamel conversion

Changes:
- Use _+([a-z]) regex to match multiple consecutive underscores before letters
- Add lookahead (?=. ) to preserve underscore-letter pairs at string end
- Handle dunder names (__proto__, __typename) by stripping wrapper and capitalizing
- Add tests for consecutive underscores and trailing underscore preservation

* fix(sdk): include original error message in permission callback denial

When a canUseTool callback throws an error, the catch block now
includes the original error message in the denial message, making
debugging easier for SDK consumers.

* feat(sdk): add optional timeout to env mutex for deadlock prevention

Add timeout parameter to acquireEnvMutex() to prevent infinite waits
in deadlock scenarios. The timeout is optional and defaults to no timeout
(wait forever) for backward compatibility.

Returns a MutexAcquireResult object with acquired status and optional
timeout reason for failed acquisitions.

* fix(sdk): remove timed-out callback from mutex queue to prevent deadlock

* test(sdk): add missing error path and timeout scenario tests

Add tests for timeout scenarios when host doesn't respond to permission
requests, fallback behavior when no onPermissionRequest callback, and
MCP connection edge cases for undefined/empty config.

* fix(sdk): address code review issues - race conditions, validation, error handling

- Add createPermissionTarget() factory that applies onceOnlyResolve at
  registration time, fixing race condition where timeout and host response
  could both try to resolve the same promise
- Add try-catch to releaseEnvMutex() to prevent permanent lock if callback throws
- Extract DEFAULT_PERMISSION_TIMEOUT_MS constant (30 seconds)
- Add MCP config validation rejecting null, non-objects, and arrays
- Preserve error stack traces in MCP connection failures
- Add runtime validation to mapMessageToSDK for null/non-object/invalid type
- Update tests to use createPermissionTarget and add validation tests

* test(sdk): add sequential timeout-then-host-response race condition tests

Adds two tests addressing reviewer request for proof that host response
after SDK timeout is safely handled with no double-resolve or leaked listener:

1. Integration test: stale host resolve called after timeout deny —
   verifies no error, no mutation, map cleanup
2. Unit test: raw resolve called exactly once when timeout wins —
   directly proves createOnceOnlyResolve prevents second execution

* fix: restore openclaude.json comment in REPL.tsx

Reviewer caught that the comment was incorrectly changed to
~/.claude.json during merge — project has already migrated to
~/.openclaude.json.

* fix(sdk): register pending permission before emitting onPermissionRequest

The previous code emitted onPermissionRequest before calling
registerPendingPermission, so a host responding synchronously from
the callback would find an empty map and its response was lost.
Swap the order so registration happens first.

Adds a regression test for the synchronous host response path.

* fix(sdk): make state setters context-aware for SDK isolation

When running inside runWithSdkContext(), setter functions (regenerateSessionId,
switchSession, setCwdState, setOriginalCwd) now write to the AsyncLocalStorage
context instead of global STATE. This prevents cross-session state leakage in
multi-session SDK scenarios.

Reads were already context-aware; this completes the isolation by making writes
consistent. Outside of SDK context, behavior is unchanged — all writes go to
global STATE as before.

* test(sdk): add context-aware state isolation tests

Tests verify that setters within runWithSdkContext() write to the SDK
context (not global STATE) and that parallel async contexts do not leak
state between sessions. Covers setCwdState, setOriginalCwd,
regenerateSessionId, switchSession, and an end-to-end parallel session
scenario.

* fix(sdk): selective tool schema cache invalidation for multi-engine isolation

Replace global clearToolSchemaCache() in QueryEngine.updateTools() with
selective invalidation that only removes cache entries for tools no longer
in the tool set. This preserves cached schemas for tools that remain,
avoiding unnecessary recomputation for concurrent QueryEngine instances
in multi-session SDK scenarios.

New function invalidateRemovedToolSchemas() handles both simple tool name
keys and schema-variant keys (format: "toolName:{...schemaJSON...}").

* docs(sdk): address PR2 non-blocking documentation and logging issues

- Document request_id vs tool_use_id relationship in shared.ts
  (request_id for response correlation, tool_use_id for tracking)
- Add injectable SDKLogger interface to permissions.ts, replacing
  direct console.warn calls with logger.warn (hosts can control noise)
- Document Node.js-only AsyncLocalStorage requirement in state.ts
  (requires Node.js 12.17.0+ or 14.0.0+)
- Clarify env-mutex is host utility (SDK doesn't mutate process.env)

* fix(sdk): handle throwing onPermissionRequest and fix permission request shape

- Wrap onPermissionRequest in try-catch to clean up pending resolver on throw
- Add uuid and session_id to permission_request message to match SDK schema
- Add regression tests for throwing callback and message shape validation

* fix(sdk): use explicit no-session placeholder for standalone permission prompts

- Add NO_SESSION_PLACEHOLDER constant ('no-session') for permission requests
- Update SDKPermissionRequestMessage doc to explain session_id semantics
- Replace empty string fallback with explicit placeholder
- Add test verifying placeholder behavior when sessionId omitted

* docs(sdk): add example code to permission denial warning

Include canUseTool example in warning message to improve developer
experience and make SDK usage more discoverable for new users.

* fix(sdk): scope parentSessionId to SDK context for parallel isolation

regenerateSessionId({ setCurrentAsParent: true }) was writing to the
process-global STATE.parentSessionId even inside runWithSdkContext(),
allowing one SDK context to overwrite another's parent-session metadata.

Add parentSessionId to the SdkContext type and update both
regenerateSessionId and getParentSessionId to read/write from the
active context when one exists, using an explicit if-else pattern
rather than ?? to avoid undefined fallback leaking across contexts.

The non-SDK CLI path (no active context) continues to use STATE
directly, preserving existing behavior.

---------

Co-authored-by: Ali Alakbarli <ali.alakbarli@users.noreply.github.com>
2026-05-02 08:32:50 +08:00
b471745fb1 Registry-Based Integration Architecture for Providers, Gateways, and Models (#910)
* setting up

* updated plan with missing notes for discovery cache

* build out inital checklist and planning adjustments

* Phase 1A-1D

* Fix descriptor-backed provider profile routing

- preserve GitHub, Bedrock, and Vertex runtime flags during profile activation\n- serialize descriptor-backed startup profiles into legacy-compatible persisted kinds\n- add regression coverage for activation, restart round-trip, and saved-profile switching\n- guard integration registration so repeated imports stay idempotent in tests

* feat: finish phase 1 provider descriptor routing

Complete the Phase 1E CLI/usage migration work and the Phase 1F verification pass for descriptor-backed providers.

Details:

- derive valid --provider values from descriptor registry and compatibility mappings instead of a fixed list

- preserve special CLI semantics for ollama and minimax while allowing descriptor-backed OpenAI-compatible routes such as deepseek and openrouter to pick up descriptor base URLs

- add getUsageDescriptor() so /usage resolves vendor/gateway metadata and follows usage delegation

- switch Settings Usage rendering to descriptor-backed usage resolution for Anthropic, MiniMax, and neutral unsupported fallbacks

- make integration loading idempotent via ensureIntegrationsLoaded() so registry-backed helpers survive tests that clear the registry

- fix compatibility mapping for mistral so the preset routes through vendorId=openai with gatewayId=mistral rather than a nonexistent direct vendor route

- harden provider profile and startup tests so descriptor-backed providers, legacy OpenAI startup files, and unknown stored providers round-trip correctly

- remove a stale ollama model mock that was leaking across the full model test suite

- update plan/progress.md with the current 1E complete / 1F in-progress verification state and the note that repo-wide typecheck failures are pre-existing outside this migration slice

Verification:

- bun test src/commands/usage/index.test.ts src/integrations/compatibility.test.ts src/utils/providerFlag.test.ts src/utils/providerProfiles.test.ts src/utils/providerProfile.test.ts src/utils/model/modelCache.test.ts src/integrations/index.test.ts src/integrations/registry.test.ts

- filtered bun run typecheck output for the files changed in this branch is clean

* Phase 2 planning

* feat: complete phase 2A validation and discovery cache

* fix: address review findings for phase 2 cache and validation

Fixes the follow-up review issues from the Phase 2A / 2A.5 work.

Completed work:

- made discovery cache stale entries reachable through getCachedModels(..., { includeStale: true }) while keeping fresh-by-default behavior unchanged

- kept recordDiscoveryError stale-data preservation useful to later /model consumers by exposing stale and error-only entries through the public helper API

- extended descriptor-backed validation routing metadata with host alias matching support

- updated MiniMax validation routing to recognize both api.minimax.io and api.minimax.chat endpoints

- added regression coverage for stale cache reads, error-only cache entries, and MiniMax chat-host validation

- updated progress.md notes so the recorded 2A.5 helper behavior matches the implementation

* feat: complete phase 2B discovery and readiness migration

Implement descriptor-backed discovery and readiness routing for Phase 2B.

Highlights:

- add src/integrations/discoveryService.ts to execute declarative catalog.discovery configs with shared discovery-cache integration

- add hybrid merge behavior so curated descriptor catalog entries stay ahead of discovered duplicates

- add typed startup readiness metadata via ReadinessProbeKind and wire gateway descriptors for ollama, atomic-chat, lmstudio, and openrouter

- export probeOllamaModelCatalog() so discovery can distinguish unreachable Ollama from reachable-but-empty catalogs

- migrate ProviderManager and /provider flows to probeRouteReadiness() while preserving existing Ollama messaging

- route bootstrap local model discovery through descriptor-backed discovery for recognized local routes, while keeping legacy fallback for generic custom endpoints

- add resolveDiscoveryRouteIdFromBaseUrl() so bootstrap can share descriptor-backed discovery and local provider labels

- preserve explicit provider env precedence during applySavedProfileToCurrentSession() after focused verification exposed the regression

- update plan/progress.md to mark Phase 2B complete and record the verification notes

Verification:

- bun test src/integrations/discoveryService.test.ts

- bun test src/components/ProviderManager.test.tsx

- bun test src/commands/provider/provider.test.tsx

- bun test src/utils/providerDiscovery.test.ts src/integrations/registry.test.ts src/integrations/index.test.ts

- filtered bun run typecheck for the touched 2B files returned FILTER_CLEAN

* feat: complete phase 2c provider metadata migration

Finish the Phase 2C runtime metadata adoption work on cheeky-cooking-moon.

Provider UI metadata:

- add shared route metadata and provider preset UI metadata helpers

- move preset labels/defaults, route type labels, and custom-header capability checks onto descriptor-backed lookups

- update ProviderManager and /provider summaries/setup copy to read shared descriptor metadata instead of bespoke switches

- extend local gateway descriptors with default model metadata used by the shared UI helpers

Model discovery UX:

- add route catalog option builders for descriptor-backed /model rendering

- update /model to resolve the active route, read cached route catalogs before rendering, and trigger background refresh when cached discovery is stale

- add /model refresh plus in-picker refresh via modelPicker:refresh and the r keybinding

- clear discovery cache on manual refresh and surface non-blocking loading/success/stale-error states in ModelPicker

- keep descriptor-backed dynamic and hybrid routes on the shared discovery cache service

Verification and hardening:

- fix combined test pollution by isolating /model test module imports and using real OpenRouter descriptor metadata during shared runs

- update progress.md to mark Phase 2C complete with verification notes

- verified with bun test for provider profiles, ProviderManager, /provider, /model, discovery cache, and provider validation suites

* feat: complete phase 2d runtime provider alignment

Align descriptor-backed runtime provider behavior with the legacy APIProvider surface so active routes, OpenAI shim behavior, and resume handling all resolve through the same metadata path.

Add runtimeMetadata.ts to centralize active route detection, OpenAI shim overrides, and native-format inference. Update provider resolution to map descriptor-backed routes onto legacy provider categories while preserving existing compatibility fallbacks for Foundry, NVIDIA NIM, MiniMax, GitHub, Bedrock, and Vertex.

Move request-shaping rules onto descriptor metadata for DeepSeek, Moonshot, Kimi Code, Gemini, Mistral, GitHub, and local gateways, including reasoning_content preservation, deepseek-compatible thinking payloads, max_tokens field selection, and store field stripping. Treat GitHub Claude native transport as Anthropic-native during conversation recovery so thinking blocks survive resume flows.

Extend focused tests for provider resolution, OpenAI shim request shaping, and conversation recovery, and update phase tracking notes in progress.md to mark 2D complete with verification details.

* feat: complete phase 2e drift audit

Complete the Phase 2E verification and drift-audit packet for the descriptor migration branch.

Add representative provider-summary coverage for descriptor-backed OpenRouter routing plus Gemini and Mistral current-provider summaries in src/commands/provider/provider.test.tsx. Extend ProviderManager coverage with first-run Atomic Chat discovery-backed setup and a regression test proving the set-active picker now uses descriptor-backed provider-type labels.

Replace stale saved-profile picker wording in ProviderManager so saved profiles no longer collapse to a coarse anthropic/openai-compatible split and instead render the route's descriptor-backed provider type label.

Add plan/phase-2e-drift-audit.md documenting the remaining intentional switch sites and non-switch provider branches across provider summaries, active-route detection, OpenAI shim env remapping, auth/header exceptions, and conversation recovery. Update plan/progress.md to mark Phase 2 and 2E complete on-branch, record focused verification, and note the follow-up hardening completed during audit review.

Verification completed during this packet: bun test src/components/ProviderManager.test.tsx src/commands/provider/provider.test.tsx src/utils/providerValidation.test.ts src/integrations/discoveryService.test.ts src/commands/model/model.test.tsx and bun test src/utils/providerDiscovery.test.ts src/utils/model/providers.test.ts src/services/api/openaiShim.test.ts src/utils/conversationRecovery.test.ts. Filtered typecheck output still shows pre-existing baseline noise in src/services/api/openaiShim.ts and src/utils/conversationRecovery.ts only.

* fix: close phase 2 provider parity follow-through

Complete the skipped provider-surface follow-up discovered during the post-Phase-2 review.

- add focused status coverage for NVIDIA NIM and MiniMax sessions

- add Mistral entries to legacy teammate/model compatibility configs

- fill deprecation placeholders for the widened APIProvider surface

- add focused regression tests for status and teammate fallbacks

- update the Phase 2 drift audit and progress tracker with the compatibility-bridge notes and Phase 3 staging context

* phase 3 planning

* refactor: start phase 3a dead-switch cleanup

Begin the Phase 3 cleanup pass with the metadata-only dead-switch removals that are safe to land independently on cheeky-cooking-moon.

Completed work:

- updated plan/progress.md to move Phase 3 and Phase 3A into IN_PROGRESS, added slice-level checklists, and recorded what remains intentionally deferred to later packets

- removed duplicated OpenAI-compatible status-display branches in src/utils/status.tsx by routing openai/codex/nvidia-nim/minimax through shared metadata helpers

- replaced the pure transport-kind label switch in src/integrations/routeMetadata.ts with shared label metadata

- replaced the pure provider-label switch in src/components/CostThresholdDialog.tsx with a shared provider-label map

- added focused regression coverage in src/utils/status.test.ts, src/integrations/routeMetadata.test.ts, and src/components/CostThresholdDialog.test.ts

Verification:

- bun test src/utils/status.test.ts src/utils/swarm/teammateModel.test.ts src/utils/model/providers.test.ts

- bun test src/integrations/routeMetadata.test.ts src/utils/status.test.ts src/components/CostThresholdDialog.test.ts src/utils/model/providers.test.ts

- filtered bun run typecheck for the touched status/routeMetadata/CostThresholdDialog files returned FILTER_CLEAN

* refactor: complete phase 3b and 3c cleanup

Complete the uncommitted Phase 3B compatibility rename work and the Phase 3C env-shaping consolidation on cheeky-cooking-moon.

Phase 3B:
- introduce LegacyAPIProvider while keeping APIProvider as the public compatibility alias
- introduce LegacyProviderModelConfig and LEGACY_PROVIDER_MODEL_CONFIGS while keeping ModelConfig and ALL_MODEL_CONFIGS as compatibility exports
- switch modelStrings, deprecation helpers, and provider profile compatibility naming onto the legacy/compatibility terminology

Phase 3C:
- add shared managed-env clear/apply helpers in providerProfile.ts and route buildLaunchEnv through the shared compatibility env shaper
- route applyProviderProfileToProcessEnv through the same compatibility env shaper so config-backed profiles and startup/session env construction stay aligned
- preserve explicit exception behavior for github, mistral, bedrock, vertex, bankr aliasing, MiniMax fallback detection, and NVIDIA NIM mode markers
- reduce createOpenAIShimClient to the remaining credential alias hydration that resolveProviderRequest does not already cover
- fix applySavedProfileToCurrentSession so saved-profile switching can move away from stale GitHub env selections
- add regression coverage for NVIDIA NIM env stamping and stale Codex-managed env clearing
- update progress.md to mark Phase 3B and 3C complete on branch and record the verification notes

Verification:
- bun test src/utils/model/providers.test.ts src/utils/providerProfiles.test.ts src/utils/swarm/teammateModel.test.ts src/utils/status.test.ts
- bun test src/utils/providerProfile.test.ts src/utils/providerProfiles.test.ts src/services/api/openaiShim.test.ts
- filtered bun run typecheck confirmed no new hits in providerProfile.ts or providerProfiles.ts; remaining openaiShim.ts hits are existing repo baseline debt

* docs: complete phase 3d audit and architecture note

Complete the Phase 3D final audit/documentation packet on cheeky-cooking-moon.

Work completed:
- add plan/phase-3d-final-audit.md with the final post-Phase-3 inventory of remaining provider-specific runtime branches
- classify the remaining exceptions as intentional long-term runtime differences or temporary env/config compatibility bridges
- confirm the audit did not uncover new missed runtime migration work that requires additional Phase 3 code changes
- add docs/architecture/integrations.md to document the descriptor-first architecture, current constraints, known exceptions, and follow-on guidance for future cleanup
- update plan/progress.md to mark Phase 3D complete on branch, mark 3C merged on branch, and point the tracker at Phase 4A next

Key exception categories documented:
- github dual-mode transport behavior
- mistral dedicated route/runtime shaping
- bedrock/vertex/foundry native Anthropic-family paths
- Azure and Bankr request-auth/header differences
- Gemini, DeepSeek, and Moonshot/Kimi OpenAI-shim quirks
- MiniMax dedicated usage handling
- native web-search gating
- env-only MiniMax and NVIDIA NIM compatibility fallbacks
- env/config compatibility bridges such as route detection, --provider shaping, and startup/provider summaries

Notes:
- this packet is branch-local audit/documentation work only; no runtime code paths were changed
- no new tests were required for the audit/doc pass

* docs: stage phase 4 tracker and codex profile guard

Add the Phase 4 documentation/reference-samples plan to progress.md in the same packet/checkpoint structure as earlier phases, and reconcile the Phase 3 tracker summary with the completed cleanup state. Also fix applySavedProfileToCurrentSession so Codex saved-profile activation does not overwrite an already explicit live provider selection, while still clearing stale profile-managed markers when needed.

* docs: complete phase 4a and 4b guides

Expand the integrations architecture note with descriptor authoring, routing-contract, transport-boundary, and compatibility-layer guidance. Add overview and glossary docs under docs/integrations/, plus new how-to guides for adding vendors and gateways with one-file and two-file patterns, discovery cache guidance, token-field guidance, and compatibility follow-through. Update progress.md to mark Phase 4 in progress, Phase 4A complete, and Phase 4B complete with notes about the new docs structure and guide outputs.

* docs: complete phase 4 integration docs

Add the remaining descriptor contributor guides for models, anthropic proxies, and /usage support.

Add a reference sample pack and a common-pitfalls checklist, update the integrations overview, and reconcile plan/progress.md so Phase 4 is marked complete on cheeky-cooking-moon with the current implementation boundaries called out explicitly.

* docs: reconcile tracker waivers and checkpoints

Update plan/progress.md to formally waive the remaining repo-wide typecheck item for Phase 1F as pre-existing debt outside the descriptor migration scope, and mark the Phase 4 branch-local checkpoints as landed on cheeky-cooking-moon with the corresponding commit references.

* Align Z.AI merge fallout with descriptors

Reviewed the upstream main merge against plan/cheeky-cooking-moon.md and removed drift from the old switch/helper-based Z.AI provider path.

Moved Z.AI reasoning, context-window, and max-output metadata into the descriptor route catalog so thinking support can read catalog capabilities instead of URL/model helper checks.

Removed the standalone src/utils/zaiProvider.ts helper and updated startup/provider-discovery labeling to resolve known direct routes through descriptor route metadata.

Simplified --provider handling for Z.AI by letting descriptor defaults provide the base URL and default model through the generic OpenAI-compatible provider branch.

Updated startup and provider-discovery tests for descriptor-backed labels, added Z.AI descriptor-label coverage, and documented the post-main-merge reconciliation in plan/progress.md.

Verification before commit: bun test src/utils/providerFlag.test.ts src/utils/providerProfiles.test.ts src/utils/thinking.test.ts src/components/StartupScreen.test.ts src/utils/providerDiscovery.test.ts; bun test src/integrations/compatibility.test.ts src/integrations/index.test.ts src/integrations/registry.test.ts src/services/api/openaiShim.test.ts; git diff --check.

* fix: restore descriptor migration behavior and isolate provider tests

Restore the descriptor-era Anthropic/OpenAI boundary during conversation recovery by threading the legacy provider category into usesAnthropicNativeMessageFormat instead of relying on ambient env-only route detection.

Harden branch-added provider-facing tests so they do not inherit leaked bun mock.module state from neighboring suites. Status, thinking, teammate fallback, and GitHub model options tests now restore mocks and/or import fresh modules under explicit provider context.

Update bugfix assertions to validate the descriptor-backed openaiShim contract for removeBodyFields/store stripping instead of the pre-refactor inline conditionals.

Validation:
- focused status/thinking/conversationRecovery/bugfix suites pass
- full bun test --max-concurrency=1 is down to the existing conversationArc perf benchmark failure only
- bun run smoke
- bun run build
- npm pack

* fix: close descriptor review drift and provider regressions

Address the follow-up review against plan/cheeky-cooking-moon.md by fixing the remaining runtime drift and locking the behavior with focused coverage.

Completed work:

- make NVIDIA NIM descriptor-backed auth consistent across validation, --provider env shaping, and openaiShim request auth so NVIDIA_API_KEY works without requiring OPENAI_API_KEY

- resolve /usage from the active descriptor route instead of collapsing most OpenAI-compatible providers into the legacy openai bucket

- honor discoveryRefreshMode in /model so manual, on-open, background-if-stale, and startup catalogs no longer behave identically

- clarify docs/progress notes so the branch no longer overstates one-file additive onboarding while loader and preset/UI compatibility surfaces are still manual

Verification:

- bun test src/services/api/openaiShim.test.ts src/utils/providerValidation.test.ts src/utils/providerFlag.test.ts src/utils/model/providers.test.ts src/commands/usage/index.test.ts src/commands/model/model.test.tsx

* docs(plan): require descriptor-native gateway onboarding closure

Investigated the current descriptor onboarding flow and documented the remaining manual choke points in the loader, preset compatibility mapping, provider UI metadata, and handwritten preset typing.

Tighten cheeky-cooking-moon so additive onboarding is a hard requirement, add Phase 3E for descriptor-native onboarding closure, and update the progress tracker to reflect that follow-up work instead of treating the branch as fully complete.

* feat(integrations): close descriptor-native onboarding

Implement the Phase 3E generated-artifact workflow for integration onboarding.

- add integration artifact generation and check scripts

- generate loader inventory, preset manifest, and preset type from descriptors

- move preset participation onto descriptor preset metadata for preset-facing vendors and gateways

- derive compatibility and provider UI metadata from the generated manifest

- remove descriptor-level preset ordering and sort presets by description with standard alphanumeric ordering

- pin the custom preset to the bottom automatically in generated ordering

- add validation for duplicate preset ids and incomplete preset metadata

- add generator tests for representative gateway and direct-vendor onboarding

- refresh ProviderManager tests for generated preset ordering

- update architecture/how-to/reference docs and progress tracking for the new regeneration workflow

* Fix provider profile and discovery drift

Honor route-specific auth env vars across descriptor-backed OpenAI-compatible routes by centralizing credential resolution and using it in validation, bootstrap, discovery, and the OpenAI shim.

Persist Anthropic startup fallbacks as native anthropic profiles and restore them correctly at startup so the legacy startup file stays aligned with the active provider.

Wire discoveryRefreshMode='startup' into startup and provider activation flows, with LM Studio as a live startup-refresh example, and add regression coverage for validation, startup env shaping, discovery refresh, and shim auth handling.

* Pin Anthropic provider preset to the top

Keep the existing custom gateway preset pinned to the bottom while moving the Anthropic preset ahead of the description-sorted remainder.

Regenerate the integration preset manifest/order and extend the artifact generator coverage to lock in both ordering rules.

Validation: bun test src/integrations/artifactGenerator.test.ts src/components/ConsoleOAuthFlow.test.tsx; bun run build

* docs: refresh integration and setup guides

Update the new descriptor-era integration docs so they read as current contributor guidance instead of rollout notes, and align the authoring examples with the actual runtime metadata flow.

Highlights:

- add a CONTRIBUTING.md pointer to the integration overview and focused how-to guides

- remove branch/phase-specific wording from the integration docs

- fix OpenAI-compatible header guidance to use transportConfig.openaiShim headers and custom-header flags

- clarify anthropic proxy onboarding around generated loader support

- refresh advanced setup with current Codex, Gemini, Mistral, and profile-launch details

- fix LiteLLM /provider instructions and clarify local no-auth behavior

- tighten quick-start and non-technical cross-links so users can find the advanced provider docs

* fix: close descriptor integration drift

Apply descriptor-backed static headers to OpenAI-compatible request execution and model discovery, preserving request-specific header precedence.

Allow Gemini profile launch with API key, access-token, or ADC credentials, and align Gemini fallback defaults with the descriptor/docs default model.

Add regression coverage for descriptor header propagation, Gemini defaults, and discovery auth/header behavior.

* post-phase follow-up task added

* Fix xAI merge follow-ups

Route env-only XAI_API_KEY sessions through the OpenAI-compatible shim using descriptor-backed xAI defaults, and map the xAI key into OPENAI_API_KEY for shim auth.

Hydrate legacy profile: xai startup env with xAI descriptor defaults, preserving XAI_API_KEY and OpenAI-compatible launch behavior.

Update progress tracking for post-merge xAI descriptor inventory and clarify that profile-owned custom headers remain open despite adjacent auth/static-header plumbing.

Add regression coverage for env-only xAI client routing, legacy xAI launch env, shell key precedence, and the Gemini/OpenAI client test isolation issue.

* Complete profile custom headers follow-up

Add persisted provider-profile customHeaders support with shared parsing and sanitization for compact Name: value input. Reject malformed and reserved auth/internal headers before saving or applying profile-owned headers.

Expose a descriptor-gated /provider custom headers step, preserve headers during profile edit/update, and apply supported profile headers through ANTHROPIC_CUSTOM_HEADERS for active env and startup fallback profiles.

Propagate profile headers into descriptor discovery refresh and bootstrap model discovery while preserving descriptor/profile/auth merge order. Add focused regression coverage and mark the progress tracker packet complete.

* Allow api-key custom provider headers

Permit api-key in /provider custom header input and preserve it when OpenAI-compatible shim requests are built. This is intentional for gateway providers that require an api-key header in addition to, or instead of, standard bearer auth.

Keep managed credential headers protected by continuing to reject/strip authorization and x-api-key, plus Anthropic/Claude-owned headers. Add parser, profile env, and outgoing request coverage for the intended behavior.

* fix: restore API mode picker for OpenAI-compatible profiles

Use descriptor transport metadata instead of the legacy provider id when deciding whether provider profiles support OpenAI-compatible options. This restores the Chat Completions vs Responses picker for the Custom OpenAI-compatible preset after it moved to the descriptor-backed custom route.

Preserve apiFormat and custom auth header profile fields for all routes whose transportConfig.kind is openai-compatible, so selecting Responses is saved and applied as OPENAI_API_FORMAT=responses.

Tests: bun test src/components/ProviderManager.test.tsx; bun test src/utils/providerProfiles.test.ts; bun run build; bun run smoke

* fix: respect explicit provider routing with xAI env

Ensure env-only XAI_API_KEY fallback does not take over when Bedrock, Vertex, or Foundry has been explicitly selected. This preserves native transport routing while still allowing bare xAI env setup to use the OpenAI-compatible shim.

Restore api-key to the managed custom-header blocklist now that /provider exposes the API mode/auth-header controls for OpenAI-compatible profiles. The shim and provider override paths strip api-key again, while OPENAI_AUTH_HEADER=api-key remains available for explicit auth configuration.

Tests: bun test src/services/api/client.test.ts src/utils/providerCustomHeaders.test.ts src/utils/providerProfiles.test.ts src/services/api/openaiShim.test.ts; bun run build; bun run integrations:check; bun run smoke

* docs: fix integration drift

Align integration and setup docs with the current implementation.

- show model descriptor examples as array default exports, matching the generated MODEL_DESCRIPTOR_GROUPS loader contract

- document provider-scoped model env vars instead of implying OPENAI_MODEL globally overrides ANTHROPIC_MODEL

- clarify generated provider preset ordering: anthropic first, custom last, description-sorted middle entries

- update LiteLLM examples and /provider guidance to use the /v1 OpenAI-compatible base URL

Verification: bun run integrations:check

* Fix provider discovery cache isolation

* Stabilize provider env tests

* Stabilize provider test isolation

Completed work:

- Isolated GitHub model option tests from cached availableModels settings.

- Isolated startup discovery tests from live process.env provider flag races.

- Mocked teammate provider fallback tests at the provider helper boundary.

- Moved cost threshold provider labels into a pure helper for deterministic tests while preserving runtime active-provider behavior.

Validation:

- bun test src/components/CostThresholdDialog.test.ts src/integrations/discoveryService.test.ts src/utils/model src/utils/swarm

- bun run build

- bun run smoke

* test: isolate startup screen model settings

Clear the session settings cache and persisted global model around StartupScreen provider-detection tests.

This prevents earlier provider/model suites from leaking saved non-Anthropic models into the default Anthropic startup assertions.

Verified with: bun test src/components/StartupScreen.test.ts src/integrations/discoveryService.test.ts src/utils/model/modelOptions.github.test.ts

Full bun test now only fails the unrelated Conversation Arc sub-millisecond performance benchmark.

* test: isolate route discovery and github model options

Restore Bun module mocks around discoveryService tests before loading fresh route-discovery modules.

Pin the GitHub model-options test to a complete providers.js mock so cached provider mocks from other suites cannot hide Copilot options.

Verified with: bun test src/integrations/discoveryService.test.ts src/utils/model/modelOptions.github.test.ts

Also ran full bun test; only the unrelated Conversation Arc sub-millisecond performance benchmark fails locally.

* test: avoid startup discovery cache collision

Use the 127.0.0.1 LM Studio alias in refreshStartupDiscoveryForActiveRoute so it still resolves the active route from env but does not share the cache partition with the preceding startup refresh test.

This keeps the assertion on network refresh stable under Bun 1.3.11 serialized runs.

Verified with: bun test --max-concurrency=1 src/integrations/discoveryService.test.ts src/utils/model/modelOptions.github.test.ts

Also ran full bun test --max-concurrency=1; only the unrelated Conversation Arc perf benchmark fails locally.

* fix: isolate OpenAI-compatible route credentials

Restrict OpenAI-compatible shim auth to provider overrides, resolved route credentials, or explicit OPENAI_API_KEY instead of ambient provider-specific secrets.

Remove NVIDIA and Bankr compatibility fallbacks that could promote provider-specific API keys into unrelated OpenAI-compatible routes. Preserve Bankr base URL/model compatibility before route credential resolution so Bankr still resolves through descriptor credentials.

Clear stale NVIDIA_NIM and copied OPENAI_API_KEY values when switching away from NVIDIA NIM, Bankr, or xAI provider flags to avoid carrying provider secrets across route boundaries.

Add regressions for stale NVIDIA, MiniMax, and Bankr keys not leaking into OpenRouter-style routes, plus provider-flag cleanup for copied NVIDIA/Bankr/xAI keys.

Validation: bun test src/services/api/openaiShim.test.ts; bun test src/utils/providerFlag.test.ts; bun run build; bun run smoke.

* fix: guard model discovery privacy paths

Suppress descriptor and legacy model discovery while essential-only traffic mode is active.

Use the partitioned discovery cache key for /model cache reads, stale checks, and manual refresh clears, including route-specific credentials and custom headers.

Partition legacy local OpenAI additional model caches by credentials and routing headers to avoid catalog reuse across profiles.

Add coverage for OpenRouter route credentials, descriptor privacy suppression, legacy discovery privacy suppression, and local cache scope partitioning.

* Fix artifact checks and knowledge graph persistence

Normalize generated integration artifact comparisons so Windows line endings do not make checked-in artifacts appear stale.

Skip knowledge graph entity persistence when re-adding an existing entity with identical attributes, avoiding repeated disk writes during automatic fact extraction and restoring the conversation arc performance benchmark.

Verified with bun test src/integrations/artifactGenerator.test.ts --max-concurrency=1, bun test src/utils/conversationArc.perf.test.ts --max-concurrency=1, and bun test --max-concurrency=1.

* test: isolate privacy discovery cache path

The descriptor discovery privacy test could observe stale OpenRouter cache data populated by an earlier test and receive source=stale-cache instead of static. Use a test-specific API key so the privacy assertion gets its own discovery cache partition while still verifying that nonessential traffic disables network discovery.

Verified with bun test src/integrations/discoveryService.test.ts --max-concurrency=1 and bun test --max-concurrency=1.

* test: accept cached privacy discovery result

* test: set privacy gate before discovery import

* test: prevent discovery privacy mock bleed

Guard descriptor model discovery directly on CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC so nonessential traffic stays disabled even if the privacyLevel module is mocked in-process.

Reduce broad fastMode test mocks for shared modules and use real state/config test hooks, preventing Bun module mock namespaces from leaking into discovery and /model tests.

Verified with bun test src/utils/fastMode.test.ts src/utils/model/openaiModelDiscovery.test.ts src/integrations/discoveryService.test.ts src/commands/model/model.test.tsx --max-concurrency=1 and bun test --max-concurrency=1.

* test: prevent discovery privacy mock bleed

Add an env-level fallback guard to descriptor model discovery so disabled nonessential traffic cannot be bypassed by stale mocked privacy helpers.

Tighten the fastMode regression tests by setting real bootstrap/config state only after the tested module is imported, avoiding broad module mocks that can leak into unrelated discovery tests or behave differently under Bun in CI.

Verified with focused discovery/fastMode/model suites and the full serial bun test suite.

* fix: harden fast mode test isolation

Ignore non-string GrowthBook values when resolving the fast mode unavailable reason so boolean flag payloads cannot surface as false.

Make the affected regression tests install explicit provider mocks for their own scenarios and reset env state, preventing stale provider mocks from changing fastMode and conversation recovery behavior across the serial Bun test run.

* test: harden fast mode module mocks

Expand the fastMode GrowthBook and provider test mocks so later imports in the same Bun test process can resolve the named exports they expect. This prevents order-sensitive failures when model command tests run after fast mode tests.\n\nVerified with: bun test --max-concurrency=1

* feat: consolidate integration runtime metadata

Move OpenAI-compatible model runtime limits into descriptor-backed brand and model metadata, adding Gemini, GLM, MiniMax, Mistral, Nemotron, xAI, and OpenAI-compatible alias descriptor groups. Update generated integration artifacts, route catalog option handling, thinking capability lookup, and docs to use modelDescriptorId-backed runtime metadata.

Split OpenAI shim capability flags into supportsApiFormatSelection and supportsAuthHeaders, and update provider profile sanitization, ProviderManager forms, descriptor validation, and integration authoring docs so fixed routes do not preserve unsupported API format or auth-header settings.

Harden env-only MiniMax and xAI routing. Resolve shared route intent before client setup, reject conflicting OpenAI base URLs, preserve provider-specific base overrides, sanitize stale OpenAI shim knobs, copy provider credentials intentionally, and keep legacy provider labels, context windows, max output limits, model lists, and provider switching aligned.

Refresh MiniMax defaults and catalog entries, add descriptor-backed runtime limits for migrated models, preserve external OpenAI limit overrides, and add regression coverage for env-only MiniMax/xAI, provider-profile capability stripping, route catalog options, copied credential cleanup, and context/runtime limit detection.

Verification performed: bun test src/utils/providerFlag.test.ts; bun test src/services/api/client.test.ts src/utils/model/providers.test.ts src/integrations/routeMetadata.test.ts; bun test src/utils/context.test.ts src/utils/thinking.test.ts src/services/compact/autoCompact.test.ts; bun test src/integrations/routeMetadata.test.ts src/services/api/client.test.ts src/utils/model/providers.test.ts src/utils/providerValidation.test.ts src/integrations/index.test.ts src/utils/status.test.ts; bun run build; bun run smoke.

* test: isolate provider env in conversation recovery

Snapshot and restore all provider-selection environment variables used by the GitHub native Claude resume test instead of only restoring the GitHub flag and OPENAI_MODEL.

The full single-concurrency suite exposed that earlier tests can leave higher-priority provider flags in process.env, causing deserializeMessages to resolve a non-GitHub provider and strip thinking blocks even though the test intended to exercise GitHub native Claude transport.

The test now clears provider routing env before setting CLAUDE_CODE_USE_GITHUB=1 and OPENAI_MODEL=claude-sonnet-4-6, then restores the original env values in afterEach.

Verification: bun test src/utils/conversationRecovery.test.ts; bun test --max-concurrency=1.

* test: isolate conversation recovery provider state

* test: pin conversation recovery provider mock

* test: isolate knowledge graph persistence

* fix: make knowledge graph reset synchronous

* test: restore integration registry after unit tests

* remove plans dir

* delete plans

* Fix provider routing test failures

Restore the missing first-party Anthropic auth routing imports used by getAnthropicClient so OpenAI-compatible provider client creation no longer throws at runtime.

Keep GitHub provider resolution from inheriting OPENAI_API_FORMAT=responses so GitHub GPT-4 and gpt-5-mini models continue to use chat completions while Codex-flavored models still route to responses.

Reset OPENAI_API_FORMAT in the affected API provider tests to prevent environment leakage across serial Bun test runs.

Verified with: bun test --max-concurrency=1

* fix: restore provider-specific model routing

Resolve generic OpenAI-compatible profiles by their known descriptor base URLs so saved MiniMax, xAI, NVIDIA NIM, OpenRouter, and DeepSeek profiles use the correct route catalogs instead of the generic OpenAI model list.

Fix MiniMax defaults and display handling so provider-specific model IDs are not rendered as Claude Opus defaults, add current MiniMax M2.7 options, and cover the regressions with focused route/model tests.

Also clean up descriptor follow-ups from review: remove the dead OpenAI shim store-strip fallback list, preserve gateway vendor IDs for Bedrock/Vertex/GitHub profile resolution, and keep the ModelPicker compiled-form changes in this PR.

* test: cover provider precedence review fixes

Remove import-time ANTHROPIC_BASE_URL and ANTHROPIC_MODEL reads from the Anthropic descriptor so descriptor defaults stay static and live env handling remains in preset metadata.

Add getAPIProvider precedence coverage documenting that explicit Gemini/OpenAI flags beat env-only MiniMax API key inference.

Add a regression check to keep the removed openaiShim hardcoded descriptor route fallback list from returning.

---------

Co-authored-by: TechBrewBoss <dash@hicap.ai>
2026-05-02 08:29:26 +08:00
KRATOSandGitHub 5943c5c269 fix(input): strip leading ! when entering bash mode (#947)
The PromptInput onChange handler had two branches for entering bash
mode: a single-char path that just toggled the mode and a multi-char
paste path that also stripped the leading `!` from the buffer. The
single-char path returned without stripping, so typing a bare `!` into
empty input switched modes but left the literal `!` visible.

Consolidated both paths through a new pure helper `detectModeEntry`
that returns the new mode plus the stripped buffer value, so there is
no longer a branch where the mode character can leak into the buffer.

Fixes #662
2026-04-29 10:29:59 +08:00
46a9d3eec4 chore: rebrand user-facing copy to OpenClaude (#851)
* chore: rebrand user-facing copy to OpenClaude

Replace lingering Claude Code branding in CLI, tips, and runtime UI with OpenClaude/openclaude, including the startup tip Gitlawb mention.

Co-Authored-By: Claude GPT-5.4 <noreply@openclaude.dev>

* chore: address branding-sweep review feedback

- PermissionRequest.tsx: rebrand the two remaining "Claude needs your
  approval/permission" notifications to OpenClaude (review-artifact and
  generic tool permission paths).
- main.tsx, teleport.tsx, session.tsx, WebFetchTool/utils.ts,
  skills/bundled/{debug,updateConfig}.ts: replace leftover `claude --…`
  CLI hints and "Claude Code" labels missed by the original sweep.
- main.tsx: drop the inline gitlawb.com marketing copy from the
  stale-prompt tip; keep it a pure rebrand.
- auth.ts: finish the half-rename so both `claude setup-token` and
  `claude auth login` references in the same error block now read
  `openclaude …`.
- mcp/client.ts: keep `name: 'claude-code'` for MCP server allowlist
  compatibility (now explicit via comment) and replace the
  "Anthropic's agentic coding tool" description with an OpenClaude one.
- MCPSettings.tsx: point the empty-server-list hint at
  https://github.com/Gitlawb/openclaude instead of code.claude.com.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* chore: replace help link with OpenClaude repo URL

Replace https://code.claude.com/docs/en/overview with
https://github.com/Gitlawb/openclaude in the help screen.

Co-Authored-By: OpenClaude <openclaude@gitlawb.com>

---------

Co-authored-by: Claude GPT-5.4 <noreply@openclaude.dev>
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Co-authored-by: OpenClaude <openclaude@gitlawb.com>
2026-04-26 22:14:36 +08:00
2586a9cddb feat: add xAI as official provider (#865)
* feat: add xAI as official provider

- Add xAI preset to ProviderManager (alphabetical order)
- Add xAI provider detection via XAI_API_KEY
- Add xAI startup screen heuristic (x.ai base URL or grok model)
- Add xAI status display properties
- Add grok-4 and grok-3 context windows
- Add xAI model fallbacks across all tiers
- Fix JSDoc priority order in providerAutoDetect

Co-Authored-By: Claude Opus 4.6 <noreply@openclaude.dev>

* fix(xai): persist relaunch classification for xAI profiles

Addresses reviewer feedback on feat/xai-official-provider:
- isProcessEnvAlignedWithProfile now validates XAI_API_KEY for x.ai
  base URLs, mirroring the Bankr pattern. Without this, relaunch
  skips re-applying the profile, XAI_API_KEY stays unset, and
  getAPIProvider() falls back to 'openai'.
- buildOpenAICompatibleStartupEnv now sets XAI_API_KEY when syncing
  active xAI profile to the legacy fallback file.
- Adds 'xai' to VALID_PROVIDERS and --provider xai CLI flag support.
- Adds xAI detection to providerDiscovery label heuristics.
- Adds 'xai' to legacy ProviderProfile type/isProviderProfile guard.
- Adds targeted tests for relaunch alignment, flag application, and
  discovery labeling.

Co-Authored-By: OpenClaude <openclaude@gitlawb.com>

---------

Co-authored-by: Claude Opus 4.6 <noreply@openclaude.dev>
Co-authored-by: OpenClaude <openclaude@gitlawb.com>
2026-04-26 21:26:44 +08:00
Rayan AlkhelaiwiandGitHub d45628c413 fix(startup): show --model flag override on startup screen (#898)
The startup screen was only reading model from env vars and settings,
ignoring the --model CLI flag since it's parsed by Commander.js after
the banner prints. Now eagerly parses --model from argv before rendering
so the displayed model matches what the session will actually use.
2026-04-26 20:24:44 +08:00
TechBrewBossandGitHub 6dedffe5ff Add OpenAI responses mode and custom auth headers (#906)
* Add OpenAI profile responses and custom auth header support

* Fix knowledge graph config reference in query loop

* Address OpenAI profile review edge cases

* Remove unused getGlobalConfig import

Delete an unused import of getGlobalConfig from src/query.ts. This cleans up dead code and avoids unused-import lint warnings; no functional behavior changes.

* Address follow-up OpenAI profile review comments

* Refine OpenAI responses auth review fixes

* Fix custom auth header default scheme
2026-04-26 20:24:03 +08:00
Kevin CodexandGitHub d9ae56bc58 fix provider switch not presistingin session (#903)
* fix provider switch not presistingin session

* fix broken tests
2026-04-26 11:15:25 +08:00
a0d657ee18 feat(zai): add Z.AI GLM Coding Plan provider preset (#896)
* feat(zai): add Z.AI GLM Coding Plan provider preset

Add dedicated Z.AI provider support for the GLM Coding Plan, enabling
use of GLM-5.1, GLM-5-Turbo, GLM-4.7, and GLM-4.5-Air models through
the OpenAI-compatible shim with proper thinking mode (reasoning_content),
max_tokens handling, and context window sizing.

* fix(zai): unify GLM max output token limits across casing variants

glm-5/glm-4.7 had conservative 16K max output while GLM-5/GLM-4.7
had 131K. Use consistent Z.AI coding plan limits for all GLM variants.

* fix(zai): restore DashScope GLM limits, enable GLM thinking support

- Restore lowercase glm-5/glm-4.7 to 16_384 max output (DashScope limits)
  while keeping Z.AI coding plan high limits on uppercase GLM-* keys only
- Add GLM model support to modelSupportsThinking() so reasoning_content
  is enabled when using GLM-5.x/GLM-4.7 models on Z.AI

* fix(zai): tighten GLM regexes, fix misleading context window comment

- Use precise regex in thinking.ts: exact GLM model matches only,
  no false positives on glm-50/glm-4, includes glm-4.5-air
- Use uppercase-only match in StartupScreen rawModel fallback so
  DashScope lowercase glm-* models aren't mislabeled as Z.AI
- Clarify context window comment: lowercase glm-5.1/glm-5-turbo/
  glm-4.5-air are Z.AI-specific aliases, not DashScope

* fix(zai): scope GLM detection to Z.AI

* improve readability of max_completion_tokens check

Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>

---------

Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
2026-04-26 08:18:59 +08:00
viudesandGitHub 9e23c2bec4 feat(api): expose cache metrics in REPL + normalize across providers (#813)
* feat(api): expose cache metrics in REPL + /cache-stats command

* fix(api): normalize Kimi/DeepSeek/Gemini cache fields through shim layer

* test(api): cover /cache-stats rendering + fix CacheMetrics docstring drift

* fix(api): always reset cache turn counter + include date in /cache-stats rows

* refactor(api): unify shim usage builder + add cost-tracker wiring test

* fix(api): classify private-IP/self-hosted OpenAI endpoints as N/A instead of cold

* fix(api): require colon guard on IPv6 ULA prefix to avoid public-host over-match

* perf(api): ring buffer for cache history + hit rate clamp + .localhost TLD

* fix(api): null guards on formatters + document Codex Responses API shape

* fix(api): defensive start-of-turn reset + config gate fallback + env var docs

* fix(api): trust forwarded cache data on self-hosted URLs (data-driven)

* refactor(api): delegate streaming Responses usage to shared makeUsage helper
2026-04-25 12:38:25 +08:00
9070220292 Add Kimi Code provider preset and rename Moonshot API preset (#862)
* Add Kimi Code provider preset

* fix desc.

Co-authored-by: Copilot <copilot@github.com>

* more desc. fixes.

* Fix release validation tests

---------

Co-authored-by: Copilot <copilot@github.com>
2026-04-25 12:36:54 +08:00
JATMNandGitHub 26413f6d30 feat(minimax): add /usage support and fix MiniMax quota parsing (#869)
* Add MiniMax usage UI and API support

* Fix MiniMax usage parsing and refresh UI

* Refactor MiniMax usage handling
2026-04-25 12:33:22 +08:00
JATMNandGitHub c4cb98a4f0 fix: normalize /provider multi-model selection and semicolon parsing (#841)
* fix provider multi-model selection

* fix provider manager multi-model save path
2026-04-25 02:28:14 +08:00
64b1014b9a Feat/bankr provider (#888)
* feat(provider): add Bankr LLM Gateway support

Add Bankr as an OpenAI-compatible provider preset with dedicated env vars:
- BNKR_API_KEY, BANKR_BASE_URL, BANKR_MODEL
- Uses X-API-Key header instead of Authorization Bearer
- Base URL: https://llm.bankr.bot/v1
- Default model: claude-opus-4.6

Changes:
- Add 'bankr' to VALID_PROVIDERS and provider flag handling
- Add buildBankrProfileEnv() with env key registration
- Add Bankr detection in startup screen and provider discovery
- Map Bankr env vars to OpenAI-compatible vars in shim
- Add Bankr preset to ProviderManager (alphabetical order)
- Update PRESET_ORDER test to include Bankr

Co-Authored-By: OpenClaude <openclaude@gitlawb.com>

* fixup(provider): address Bankr PR review feedback

1. Map BNKR_API_KEY → OPENAI_API_KEY in providerFlag.ts so
   --provider bankr works with BNKR_API_KEY in non-interactive startup.

2. Remove unconditional BANKR_MODEL read from model.ts; it maps to
   OPENAI_MODEL via providerFlag.ts and openaiShim.ts, preventing
   cross-provider leakage.

3. Use X-API-Key for Bankr model discovery in openaiModelDiscovery.ts
   and providerDiscovery.ts, matching chat request auth.

Co-Authored-By: OpenClaude <openclaude@gitlawb.com>

---------

Co-authored-by: OpenClaude <openclaude@gitlawb.com>
2026-04-24 23:03:45 +08:00
TechBrewBossandGitHub 5a21d05741 Persist active provider profile across restarts (#833)
* Persist active provider profile across restarts

* Clear stale startup provider overrides

* Fix provider profile restart fallback

* Fix provider profile restart fallback

* Omit empty OpenAI API key from startup env

* Fix startup override settings typing
2026-04-24 19:36:21 +08:00
0xfandomandGitHub e346b8d5ec fix(startup): url authoritative over model name in banner provider detect (#864)
The banner provider branch tested model-name substrings (`/deepseek/`, `/kimi/`,
`/mistral/`, `/llama/`) before aggregator base-URL substrings (`/openrouter/`,
`/together/`, `/groq/`, `/azure/`). When running OpenRouter/Together/Groq with
vendor-prefixed model IDs (e.g. `deepseek/deepseek-chat`, `moonshotai/kimi-k2`,
`deepseek-r1-distill-llama-70b`), the banner mislabelled the provider.

Reorder: explicit env flags (NVIDIA_NIM, MINIMAX_API_KEY) and codex transport
win first; base-URL host checks run before rawModel fallback; rawModel only
fires when the base URL is generic/custom. Add unit tests covering the
aggregator × vendor-prefixed-model matrix plus direct-vendor regressions.

Closes #855
2026-04-24 01:52:27 +08:00
MikeandGitHub ee19159c17 feat(provider): expose Atomic Chat in /provider picker with autodetect (#810)
Adds Atomic Chat as a first-class preset inside the in-session /provider
slash command, mirroring the Ollama auto-detect flow. Picking it probes
127.0.0.1:1337/v1/models, lists loaded models for direct selection, and
falls back to "Enter manually" / "Back" when the server is unreachable
or no models are loaded. README updated to reflect the new setup path.

Made-with: Cursor
2026-04-22 07:55:53 +08:00
b95d2221df Feat/kimi moonshot support (#805)
* feat(provider): first-class Moonshot (Kimi) direct-API support

Moonshot's direct API (api.moonshot.ai/v1) is OpenAI-compatible and works
today via the generic OpenAI shim, including the reasoning_content channel
that Kimi returns alongside the user-visible content. But the UX was rough:
unknown context window triggered the conservative 128k fallback + a warning,
and the provider displayed as "Local OpenAI-compatible".

Makes Moonshot a recognized provider:

- src/utils/model/openaiContextWindows.ts: add the Kimi K2 family and
  moonshot-v1-* variants to both the context-window and max-output tables.
  Values from Moonshot's model card — K2.6 and K2-thinking are 256K,
  K2/K2-instruct are 128K, moonshot-v1 sizes are embedded in the model id.
- src/utils/providerDiscovery.ts: recognize the api.moonshot.ai hostname
  and label it "Moonshot (Kimi)" in the startup banner and provider UI.

Users can now launch with:

  CLAUDE_CODE_USE_OPENAI=1 \
  OPENAI_BASE_URL=https://api.moonshot.ai/v1 \
  OPENAI_API_KEY=sk-... \
  OPENAI_MODEL=kimi-k2.6 \
  openclaude

and get accurate compaction + correct labeling + correct max_tokens out
of the box.

Co-Authored-By: OpenClaude <openclaude@gitlawb.com>

* fix(openai-shim): Moonshot API compatibility — max_tokens + strip store

Moonshot's direct API (api.moonshot.ai and api.moonshot.cn) uses the
classic OpenAI `max_tokens` parameter, not the newer `max_completion_tokens`
that the shim defaults to. It also hasn't published support for `store`
and may reject it on strict-parse — same class of error as Gemini's
"Unknown name 'store': Cannot find field" 400.

- Adds isMoonshotBaseUrl() that recognizes both .ai and .cn hosts.
- Converts max_completion_tokens → max_tokens for Moonshot requests
  (alongside GitHub / Mistral / local providers).
- Strips body.store for Moonshot requests (alongside Mistral / Gemini).

Two shim tests cover both the .ai and .cn hostnames.

Co-Authored-By: OpenClaude <openclaude@gitlawb.com>

* fix: null-safe access on getCachedMCConfig() in external builds

External builds stub src/services/compact/cachedMicrocompact.ts so
getCachedMCConfig() returns null, but two call sites still dereferenced
config.supportedModels directly. The ?. operator was in the wrong place
(config.supportedModels? instead of config?.supportedModels), so the null
config threw "Cannot read properties of null (reading 'supportedModels')"
on every request.

Reproduces with any external-build provider (notably Kimi/Moonshot just
enabled in the sibling commits, but equally DeepSeek, Mistral, Groq,
Ollama, etc.):

  ❯ hey
  ⏺ Cannot read properties of null (reading 'supportedModels')

- prompts.ts: early-return from getFunctionResultClearingSection() when
  config is null, before touching .supportedModels.
- claude.ts: guard the debug-log jsonStringify with ?. so the log line
  never throws.

Co-Authored-By: OpenClaude <openclaude@gitlawb.com>

* fix(startup): show "Moonshot (Kimi)" on the startup banner

The startup-screen provider detector had regex branches for OpenRouter,
DeepSeek, Groq, Together, Azure, etc., but nothing for Moonshot. Remote
Moonshot sessions fell through to the generic "OpenAI" label —
getLocalOpenAICompatibleProviderLabel() only runs for local URLs, and
api.moonshot.ai / api.moonshot.cn are not local.

Adds a Moonshot branch matching /moonshot/ in the base URL OR /kimi/ in
the model id. Now launches with:

  OPENAI_BASE_URL=https://api.moonshot.ai/v1 OPENAI_MODEL=kimi-k2.6

display the Provider row as "Moonshot (Kimi)" instead of "OpenAI".

Co-Authored-By: OpenClaude <openclaude@gitlawb.com>

* refactor(provider): sort preset picker alphabetically; Custom at end

The /provider preset picker was in ad-hoc order (Anthropic, Ollama,
OpenAI, then a jumble of third-party / local / codex / Alibaba / custom /
nvidia / minimax). Hard to scan when you know the provider name you want.

Sorts the list alphabetically by label A→Z. Pins "Custom" to the end —
it's the catch-all / escape hatch so it's scanned last, not shuffled into
the alphabetical run where a user looking for a named provider might
grab it by mistake. First-run-only "Skip for now" stays at the very
bottom, after Custom.

Test churn:
- ProviderManager.test.tsx: four tests hardcoded press counts (1 or 3 'j'
  presses) that broke when targets moved. Replaces them with a
  navigateToPreset(stdin, label) helper driven from a declared
  PRESET_ORDER array, so future list edits only update the array.
- ConsoleOAuthFlow.test.tsx: the 13-row test frame only renders the first
  ~13 providers. "Ollama", "OpenAI", "LM Studio" sentinels moved below
  the fold; swap them for alphabetically-early providers still visible
  in-frame ("Azure OpenAI", "DeepSeek", "Google Gemini"). Test intent
  (picker opened with providers listed) is preserved.

Co-Authored-By: OpenClaude <openclaude@gitlawb.com>

---------

Co-authored-by: OpenClaude <openclaude@gitlawb.com>
2026-04-21 21:20:54 +08:00
viudesandGitHub a6a3de5ac1 feat(api): compress old tool_result content for small-context providers (#801)
* feat(api): compress old tool_result content for small-context providers

Adds a shim-layer pass that tiers tool_result content by age on
providers
  with small effective context windows (Copilot gpt-4o 128k, Mistral,
  Ollama). Recent turns remain full; mid-tier results are truncated to
2k
  chars; older results are replaced with a stub that preserves tool name
  and arguments so the model can re-invoke if needed.

  Tier sizes auto-tune via getEffectiveContextWindowSize, same
calculation
  used by auto-compact. Reuses COMPACTABLE_TOOLS and
  TOOL_RESULT_CLEARED_MESSAGE to complement (not duplicate)
microCompact.
  Configurable via /config toolHistoryCompressionEnabled.

  Addresses active-session context accumulation on Copilot where
  microCompact's time-based trigger never fires, which surfaces as
  "tools appearing in a loop" and prompt_too_long errors after ~15
turns.

* fix: config tool history
2026-04-21 17:36:26 +08:00
85eab2751e fix(ui): prevent provider manager lag by deferring sync I/O (#803)
ProviderManager was blocking the main thread with synchronous file I/O
on mount (useState initializer), activation (setActiveProviderProfile),
and refresh (getProviderProfiles). This caused noticeable lag on Windows
where disk I/O can be slow due to antivirus scans, NTFS metadata, or
cache misses.

Changes to ProviderManager:
- Deferred initialization: useState now starts empty, loads via queueMicrotask
- Added isInitializing state with loading UI
- refreshProfiles() now defers reads via queueMicrotask
- activateSelectedProvider() now defers writes via queueMicrotask
- Memoized menuOptions array to prevent re-renders during navigation

Note: ProviderChooser useMemo change was reverted as it's dead code
(ProviderWizard is not used in production - /provider uses ProviderManager).

Co-authored-by: Ali Alakbarli <ali.alakbarli@users.noreply.github.com>
2026-04-21 17:00:58 +08:00
4cb963e660 feat(api): improve local provider reliability with readiness and self-healing (#738)
* feat(api): classify openai-compatible provider failures

* Update src/services/api/providerConfig.ts

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* Update src/services/api/errors.ts

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* feat(api): harden openai-compatible diagnostics and env fallback

* Update src/services/api/openaiShim.ts

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* Update src/services/api/openaiShim.ts

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* Update src/services/api/errors.ts

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* Update src/services/api/errors.ts

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* Apply suggestion from @Copilot

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* fix openaiShim duplicate requests and diagnostics

* remove unused url from http failure classifier

* dedupe env diagnostic warnings

* Remove hardcoded URLs from OpenAI error tests

Removed hardcoded URLs from network failure classification tests.

* Update providerConfig.envDiagnostics.test.ts

* fix(openai-shim): return successful responses and restore localhost classifier tests

* Update src/services/api/openaiShim.ts

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* Update src/services/api/openaiShim.ts

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* Update src/services/api/openaiShim.ts

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* feat(provider): add truthful local generation readiness checks

Implement Phase 2 provider readiness behavior by adding structured Ollama generation probes, wiring setup flows to readiness states, extending system-check with generation readiness output, and updating focused tests.

* feat(api): add local self-healing fallback retries

Implement Phase 3 self-healing behavior for local OpenAI-compatible providers: retry base URL fallbacks for localhost resolution and endpoint mismatches, plus capability-gated toolless retry for tool-incompatible local models; include diagnostics and focused tests.

* fix(api): address review blockers for local provider reliability

* Update src/utils/providerDiscovery.ts

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* Update src/services/api/openaiShim.ts

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* fix: harden readiness probes and cross-platform test stability

* fix: refresh toolless retry payload and stabilize osc clipboard test

* fix: harden Ollama readiness parsing and redact provider URLs

---------

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2026-04-20 16:24:02 +08:00
Kevin CodexandGitHub 13e9f22a83 feat: mask provider api key input (#772) 2026-04-20 08:25:22 +08:00
lunamonkeandGitHub b0d9fe7112 Provider loading fix (#623)
* add mistral and gemini provider type for profile provider field

* load latest locally selected

* env variables take precedence over json save

* add gemini context windows and fix gemini defaulting for env

* load on startup fix

* fix failing tests

* clarify test message

* fix variable mismatches

* fix failing test

* delete keys and set profile.apiKey for mistral and gemini

* switch model as well when switching provider

* set model when adding a new model
2026-04-18 01:46:20 +08:00
34246635fb fix(ui): show correct endpoint URL in intro screen for custom Anthropic endpoints (#735)
Previously, the startup intro screen always displayed
'https://api.anthropic.com' as the endpoint for Anthropic provider,
even when a custom endpoint was configured via ANTHROPIC_BASE_URL.

This fix reads ANTHROPIC_BASE_URL from environment and displays the
actual configured endpoint, providing accurate information to users
about where their API requests will be sent (proxy gateways, staging,
custom Anthropic-compatible APIs).

Also adds isLocal detection for local endpoints to show appropriate
visual indicator in the startup banner.

Co-authored-by: Ali Alakbarli <ali.alakbarli@users.noreply.github.com>
2026-04-17 19:06:47 +08:00
regiskscandGitHub 43ac6dba75 feat: add Alibaba Coding Plan (DashScope) provider support (#509)
* feat: add Alibaba Coding Plan provider presets

* fix: add DashScope presets to ProviderManager UI selection list

* feat: read DASHSCOPE_API_KEY env var for DashScope provider presets

* adds regression testing for alibaba models

* docs: add time descriptive comment

* feat(dashscope): add qwen3.6-plus model support

* fix(dashscope): remove MiniMax-M2.5 entries to prevent future key conflicts
2026-04-17 19:06:21 +08:00
d6f5130c20 fix: focus "Done" option after completing provider manager actions (#718)
When returning to the provider manager menu after completing an action
(add, edit, delete, set active, etc.), the cursor now lands on "Done"
instead of the first option ("Add provider"). This prevents accidental
re-entry into the same action if the user presses Enter quickly.

On initial /provider invocation, the cursor still starts on the first
option ("Add provider") as expected.

Co-authored-by: Ali Alakbarli <ali.alakbarli@users.noreply.github.com>
2026-04-16 21:39:13 +08:00
b66633ea4d Feat/multi model provider support (#692)
* test: add tests for provider model env updates and multi-model profiles

Add comprehensive tests covering:
- OPENAI_MODEL/ANTHROPIC_MODEL env updates on provider activation
- Cross-provider type switches (openai ↔ anthropic) clearing stale env
- Multi-model profile activation using only the first model for env vars
- Model options cache population from comma-separated model lists
- getProfileModelOptions generating correct ModelOption arrays

* feat: multi-model provider support and model auto-switch

Support comma-separated model names in provider profiles (e.g.
"glm-4.7, glm-4.7-flash"). The first model is used as default on
activation; all models appear in the /model picker for easy switching.

When switching active providers, the session model now automatically
updates to the new provider's first model. The multi-model list is
preserved across switches and /model selections.

Changes:
- Add parseModelList, getPrimaryModel, hasMultipleModels utilities
  with full test coverage (19 tests)
- Use getPrimaryModel when applying profiles to process.env so only
  the primary model is set in OPENAI_MODEL/ANTHROPIC_MODEL
- Update ProviderManager UI to hint at multi-model syntax and show
  model count in provider list summaries
- Populate model options cache from multi-model profiles on activation
  so all models appear in /model picker regardless of base URL type
- Guard persistActiveProviderProfileModel against overwriting
  comma-separated lists: models already in the profile are session
  selections, not profile edits
- Set AppState.mainLoopModel to the actual model string on provider
  switch so Anthropic profiles use the configured model instead of
  falling back to the built-in default

* fix: only show profile models when provider profile env is applied

Guard the profile model picker options behind a
PROFILE_ENV_APPLIED check. getActiveProviderProfile() has a
?? profiles[0] fallback that returns the first profile even when
no profile is explicitly active, causing users with inactive
profiles to lose all standard model options (Opus, Haiku, etc.)
from the /model picker.

* fix: show all model names for profiles with 3 or fewer models

Instead of a summary format for multi-model profiles, display all
model names when there are 3 or fewer. Only use the "+ N more"
format for profiles with 4+ models.

* fix: preserve standard model options in picker alongside profile models

The previous implementation used an early return that replaced all
standard picker options (Opus, Haiku, Sonnet for Anthropic; Codex/GPT
models for OpenAI) with only the profile's custom models.

Changes:
- Collect profile models into a shared array instead of early returning
- Append profile models to firstParty path (Opus + Haiku + Sonnet + custom)
- Append profile models to PAYG 3P path (Codex + Sonnet + Opus + Haiku + custom)
- Guard collection behind PROFILE_ENV_APPLIED to avoid ?? profiles[0] fallback

Fixes review feedback: standard models are no longer hidden when a
provider profile with custom models is active. Users see both the
standard options and their profile's models.

---------

Co-authored-by: Ali Alakbarli <ali.alakbarli@users.noreply.github.com>
2026-04-16 05:01:55 +08:00
ArkhAngelLifeJiggyandGitHub 51191d6132 feat: add NVIDIA NIM and MiniMax provider support (#552)
* feat: add NVIDIA NIM and MiniMax provider support

- Add nvidia-nim and minimax to --provider CLI flag
- Add model discovery for NVIDIA NIM (160+ models) and MiniMax
- Update /model picker to show provider-specific models
- Fix provider detection in startup banner
- Update .env.example with new provider options

Supported providers:
- NVIDIA NIM: https://integrate.api.nvidia.com/v1
- MiniMax: https://api.minimax.io/v1

* fix: resolve conflict in StartupScreen (keep NVIDIA/MiniMax + add Codex detection)

* fix: resolve providerProfile conflict (add imports from main, keep NVIDIA/MiniMax)

* fix: revert providerSecrets to match main (NVIDIA/MiniMax handled elsewhere)

* fix: add context window entries for NVIDIA NIM and new MiniMax models

* fix: use GLM-5 as NVIDIA NIM default and MiniMax-M2.5 for consistency

* fix: address remaining review items - add GLM/Kimi context entries, max output tokens, fix .env.example, revert to Nemotron default

* fix: filter NVIDIA NIM picker to chat/instruct models only, set provider-specific API keys from saved profiles

* chore: add more NVIDIA NIM context window entries for popular models

* fix: address remaining non-blocking items - fix base model, clear provider API keys on profile switch
2026-04-15 20:26:13 +08:00
Henrique FernandesandGitHub fc7dc9ca0d Add Codex OAuth provider flow for ChatGPT account sign-in (#503)
* feat: add Codex OAuth provider flow

* fix: harden Codex OAuth storage, session activation, and UI
2026-04-13 22:34:16 +08:00
Nourrisse FlorianandGitHub b818dd5958 feat: implement Monitor tool for streaming shell output (#649)
* feat: implement Monitor tool for streaming shell output

Add the Monitor tool that executes shell commands in the background and
streams stdout line-by-line as notifications to the model. This enables
real-time monitoring of logs, builds, and long-running processes.

Implementation:
- MonitorTool (src/tools/MonitorTool/) — spawns LocalShellTask with
  kind='monitor', returns immediately with task ID
- MonitorMcpTask (src/tasks/MonitorMcpTask/) — task lifecycle management
  and agent cleanup via killMonitorMcpTasksForAgent()
- MonitorPermissionRequest — permission dialog component

The codebase already had all integration points wired (tools.ts, tasks.ts,
PermissionRequest.tsx, LocalShellTask kind='monitor', BashTool prompt).
This PR provides the missing implementations.

* fix: command-specific permission rule + architecture docs

- MonitorPermissionRequest: "don't ask again" now creates a
  command-prefix rule (like BashTool) instead of a blanket
  tool-name-only rule that would auto-allow all Monitor commands
- MonitorMcpTask: clarify architecture comments explaining why
  monitor_mcp type exists as a registry stub while actual tasks
  are local_bash with kind='monitor'

* fix: address Copilot review feedback

- Fix permission rule field: expression → ruleContent (Copilot #1)
- Handle empty command prefix: skip rule creation (Copilot #2)
- Remove unused useTheme() import (Copilot #3)
- Save permission rules under 'Bash' toolName so bashToolHasPermission
  can match them — Monitor delegates to Bash permission system (Copilot #4)
- Remove unused logError import from MonitorMcpTask (Copilot #6)
- Copilot #5 (getAppState throws): same pattern as BashTool:915, not a bug
2026-04-13 21:39:07 +08:00
Meetpatel006andGitHub 7c8bdcc3e2 fix: route OpenAI Codex shortcuts to correct endpoint (#566)
* feat: enhance codex provider resolution with shortcut aliases and improved base URL handling

* fix: enhance codex alias resolution to include shell model

* feat: enhance Codex provider resolution to support new aliases and base URL handling

* fix: update base URL resolution logic for Codex models in GitHub mode

* fix: update provider transport logic to enforce Codex responses and adjust base URL handling

* fix: update provider request resolution to respect custom base URLs and adjust transport logic

* fix: restore OPENAI_MODEL environment variable handling in tests and provider config
2026-04-13 18:31:15 +08:00
b3f3dc4e66 Prefer AGENTS.md over CLAUDE.md for project instructions (#439)
* Prefer AGENTS.md over CLAUDE.md for project instructions

* fix: preserve CLAUDE.md fallback behavior

* fix: isolate onboarding tests and preserve legacy init

* fix: restore full fsOperations exports in test mock and align compact cwd

* Fix onboarding test isolation and init migration guidance

* Tighten init prompt coverage and onboarding copy

* Handle nested project instruction paths consistently

* Fix NEW_INIT feature gate for Bun build

---------

Co-authored-by: 赵小落 <zhaoxiaoluo@zhaoxiaoluodeMac-mini.local>
Co-authored-by: zhaomo01 <zhaomo01@baidu.com>
2026-04-12 21:31:33 +08:00
lunamonkeandGitHub 4c50977f3c Decouple and fix mistral (#595)
* decouple and fix mistral

* fix wrong variable for currentBaseUrl and buildAPIProviderProperties
2026-04-12 15:26:14 +08:00
euxaristiaandGitHub b126e38b1a fix: display selected model in startup screen instead of hardcoded sonnet 4.6 (#587) 2026-04-11 21:20:00 +08:00
692471850f fix: update theme preview on focus change (#562)
Treat default select focus as initial state so /theme and first-run previews follow keyboard navigation again.

Co-authored-by: anandh8x <test@example.com>
2026-04-10 21:55:15 +08:00
68c296833d fix: restore Ollama auto-detect in first-run setup (#561)
Co-authored-by: anandh8x <test@example.com>
2026-04-10 21:53:30 +08:00
Kevin CodexandGitHub 42b121bd0d Fix/openclaude diagnostics settings (#483)
* fix: use openclaude paths in diagnostics and settings

* fix: strip leaked reasoning from assistant output

* fix: preserve legacy claude config compatibility

* fix: tighten path and reasoning compatibility

* fix: buffer streamed reasoning leak preambles

* test: cover openclaude migration and reasoning fixes

* test: isolate execFileNoThrow from cross-file mocks
2026-04-09 20:42:51 +08:00
soothandGitHub e30ad17ae0 fix(tui): restore prompt rendering on startup (#498)
* fix(tui): restore prompt rendering on startup

* test(tui): document render-time command split

* fix(tui): reduce ghostty prompt repaint scope
2026-04-09 20:40:06 +08:00