mirror of
https://github.com/headroomlabs-ai/headroom.git
synced 2026-11-22 13:29:19 +08:00
feat(wrap): support 1m context in vscode claude (#3361)
## Description `headroom wrap vscode-claude` now supports an opt-in `--1m` path. It stores Claude Code's `[1m]` model selector in the existing top-level `model` setting and records the prior value in the reversible settings sidecar. Reconfiguration remains idempotent, malformed sidecars fail with a clear error, and user changes to Headroom-managed values remain protected. The branch also pins npm 11.16.0 in the shared Docker wrap test image. npm 10.9.8 crashed while installing the local OpenClaw plugin with `Cannot read properties of null (reading 'edgesOut')`. Closes #3360 ## Type of Change - [ ] Bug fix (non-breaking change that fixes an issue) - [x] New feature (non-breaking change that adds functionality) - [ ] Breaking change (fix or feature that would cause existing functionality to change) - [ ] Documentation update - [ ] Performance improvement - [ ] Code refactoring (no functional changes) ## Changes Made - Added `--1m` to `headroom wrap vscode-claude`. - Reused one Claude-specific resolver for standalone and VS Code model selection. - Extended the reversible VS Code sidecar to preserve, validate, and restore the top-level model. - Refreshes fallback-selected models when `HEADROOM_1M_MODEL` changes between repeated `--1m` runs. - Preserved exact prior values and refuses to overwrite user edits. - Added read-only `--no-configure --1m` output for manual settings setup. - Added focused tests for model persistence, fallback refresh, malformed state, conflict handling, and restoration. - Pinned npm 11.16.0 in `e2e/wrap/Dockerfile` for both Docker wrap jobs. - Updated the VS Code Claude documentation. ## Testing - [x] Focused unit and integration tests pass - [x] Linting and formatting checks pass for changed Python files - [ ] Type checking passes - [x] New tests added for the changed behavior - [ ] Manual testing performed ### Test Output ```text uv run pytest tests/test_cli/test_wrap_vscode_claude.py tests/test_provider_claude.py tests/test_provider_claude_vscode_config.py -q 48 passed in 1.15s uv run ruff check headroom/providers/claude/vscode.py headroom/cli/wrap.py tests/test_provider_claude_vscode_config.py All checks passed! uv run ruff format --check headroom/providers/claude/vscode.py headroom/cli/wrap.py tests/test_provider_claude_vscode_config.py 3 files already formatted ``` ## Real Behavior Proof - Environment: Windows, Python development environment, temporary Claude settings file. - Exact command / steps: run `headroom wrap vscode-claude --1m --settings-file <temporary-settings.json>`, inspect the settings and sidecar, then run `headroom unwrap vscode-claude --settings-file <temporary-settings.json>`. - Observed result: the `[1m]` model persisted, the sidecar recorded the prior model, and unwrap restored the exact prior value. Repeated `--1m` runs picked up a changed `HEADROOM_1M_MODEL` fallback when no user model existed. - GitHub CI result: `docker-wrap-e2e`, `docker-native-e2e`, and all other required checks passed after the npm pin. - Not tested: live Claude account entitlement for the 1M context window. ## Runtime Rollout Safety - Rollout-managed feature(s): none. - Minimum rollout channel: next release containing the VS Code Claude wrapper change. - Stable/default behavior changed: `--1m` remains opt-in; default VS Code Claude behavior is unchanged. - Kill switch / disable path: omit `--1m`, run `headroom unwrap vscode-claude`, or revert the change before release. - Unsafe override required: no. - Qualification impact: Claude account entitlement still controls access to the 1M context window. - Rollback path: run `headroom unwrap vscode-claude`, reload VS Code, and revert the release if needed. ## Review Readiness - [x] I have performed a self-review - [x] This PR is ready for human review ## Checklist - [x] My code follows the project's style guidelines - [x] I have performed a self-review of my code - [ ] I have commented my code, particularly in hard-to-understand areas - [x] I have made corresponding changes to the documentation - [x] My changes generate no new warnings - [x] I have added tests that prove the feature works - [x] Focused tests pass locally with my changes - [x] I did **not** edit `CHANGELOG.md`; release-please generates it from the conventional PR title. ## Additional Notes Claude Code and Anthropic control model support and account eligibility. Local tests prove persisted configuration and restoration, not access to a live 1M context window. --------- Co-authored-by: JerrettDavis <mxjerrett@gmail.com>
This commit is contained in:
@@ -322,6 +322,8 @@ project you will open in VS Code:
|
||||
```bash
|
||||
pip install "headroom-ai[proxy]"
|
||||
headroom wrap vscode-claude
|
||||
# Optional: persist Claude Code's client-owned 1M model selector
|
||||
headroom wrap vscode-claude --1m
|
||||
```
|
||||
|
||||
Reload the VS Code window on first run. Keep the wrapper terminal running while
|
||||
@@ -329,6 +331,16 @@ you use the Claude Code panel; the dashboard or proxy log printed at startup
|
||||
shows requests and savings. Your Anthropic authentication and selected model are
|
||||
preserved. `Ctrl+C` stops the proxy; `headroom unwrap vscode-claude` restores the
|
||||
settings that existed before setup.
|
||||
|
||||
With `--1m`, Headroom writes the resolved `[1m]` model selector to Claude Code's
|
||||
top-level user setting and restores the exact prior model on
|
||||
`headroom unwrap vscode-claude` or when setup runs again without `--1m`. Use
|
||||
`headroom wrap vscode-claude --no-configure --1m` to print the setting without
|
||||
writing files.
|
||||
|
||||
Claude Code and Anthropic own 1M model support and account eligibility. Local
|
||||
tests prove persisted settings and restoration, not a live entitled VS Code
|
||||
session or the resulting context window.
|
||||
[Full guide →](https://docs.headroomlabs.ai/docs/vscode-claude-code)
|
||||
|
||||
</details>
|
||||
|
||||
@@ -276,6 +276,24 @@ headroom wrap claude --1m
|
||||
|
||||
`HEADROOM_1M_MODEL` is a fallback only: an explicit `--model` or `ANTHROPIC_MODEL` always wins. The value may be given with or without the `[1m]` suffix; both `claude-opus-5` and `claude-opus-5[1m]` are accepted, and the suffix is added when absent.
|
||||
|
||||
For Claude Code's official VS Code extension, use the client-owned persisted
|
||||
setting instead of `ANTHROPIC_MODEL`:
|
||||
|
||||
```bash
|
||||
headroom wrap vscode-claude --1m
|
||||
```
|
||||
|
||||
This writes the resolved model with exactly one `[1m]` suffix to the top-level
|
||||
`model` setting in Claude Code's user settings and records the prior presence and
|
||||
value in Headroom's reversible sidecar. Running the command without `--1m`
|
||||
restores a model previously managed by Headroom; `headroom unwrap vscode-claude`
|
||||
restores the model and proxy environment values together. Use
|
||||
`--no-configure --1m` to print the setting without writing either file.
|
||||
|
||||
Claude Code and Anthropic own model support and account eligibility. Local tests
|
||||
prove settings persistence and restoration, not a live entitled VS Code session
|
||||
or a resulting 1M context window.
|
||||
|
||||
## Pipeline Extensions
|
||||
|
||||
Use a `headroom.pipeline_extension` entry point when you need to normalize or annotate requests before they leave Headroom. The `PRE_SEND` stage is the right place for provider-specific request cleanup, such as turning `content: null` into `content: ""` for upstreams that reject OpenAI-spec tool-call messages.
|
||||
|
||||
@@ -6,6 +6,8 @@ description: Route the official Claude Code extension through Headroom's local c
|
||||
The official Claude Code extension for VS Code embeds Claude Code. Headroom can
|
||||
route its Anthropic API requests through the same local compression proxy used by
|
||||
`headroom wrap claude`, without changing your Anthropic sign-in or selected model.
|
||||
Pass `--1m` when you want Headroom to persist Claude Code's client-owned 1M model
|
||||
selector.
|
||||
|
||||
<Callout type="info" title="Using Claude Code in a terminal instead?">
|
||||
Use `headroom wrap claude`. This page is specifically for Anthropic's official
|
||||
@@ -50,6 +52,26 @@ uses a custom endpoint. Existing settings and prior values for both variables ar
|
||||
preserved for restoration. Headroom does not store or replace your Anthropic
|
||||
credentials.
|
||||
|
||||
To opt into Claude Code's 1M context selector, run:
|
||||
|
||||
```bash
|
||||
headroom wrap vscode-claude --1m
|
||||
```
|
||||
|
||||
The command writes a top-level setting alongside `env`:
|
||||
|
||||
```json
|
||||
{
|
||||
"model": "claude-opus-5[1m]"
|
||||
}
|
||||
```
|
||||
|
||||
The selected model is trimmed and receives one `[1m]` suffix. When no model is
|
||||
selected, `HEADROOM_1M_MODEL` is used, followed by the built-in fallback. Headroom
|
||||
stores the exact prior model presence and value in its sidecar, preserves that
|
||||
snapshot across repeated runs, and restores it when you omit `--1m` or run
|
||||
`headroom unwrap vscode-claude`.
|
||||
|
||||
3. After the first configuration, run **Developer: Reload Window** from the VS
|
||||
Code Command Palette.
|
||||
4. Keep the wrapper terminal running and use the Claude Code panel normally.
|
||||
@@ -78,7 +100,9 @@ respected when set. To target another profile explicitly:
|
||||
headroom wrap vscode-claude --settings-file /path/to/.claude/settings.json
|
||||
```
|
||||
|
||||
Use `--no-configure` to print the settings without editing a file.
|
||||
Use `--no-configure` to print the settings without editing a file. With
|
||||
`--no-configure --1m`, the resolved top-level `model` is printed too and neither
|
||||
the settings file nor the sidecar is written.
|
||||
|
||||
The proxy URL includes the current directory as the project attribution name.
|
||||
Run the wrapper from the intended project directory. If you select another port,
|
||||
@@ -96,9 +120,10 @@ Restore the values that existed before Headroom configured the extension:
|
||||
headroom unwrap vscode-claude
|
||||
```
|
||||
|
||||
Headroom records only the two values it owns in a sidecar next to the Claude
|
||||
settings file. It refuses malformed settings or conflicting edits rather than
|
||||
overwriting them. Unrelated Claude settings are preserved.
|
||||
Headroom records the two environment values it owns and, when `--1m` is active,
|
||||
the model snapshot in a sidecar next to the Claude settings file. It refuses
|
||||
malformed settings or conflicting edits rather than overwriting them. Unrelated
|
||||
Claude settings are preserved.
|
||||
|
||||
If you used `--settings-file` during setup, pass the same option when undoing it:
|
||||
|
||||
@@ -125,3 +150,8 @@ automatic discovery does not match it.
|
||||
- If you use `CLAUDE_CONFIG_DIR`, launch Headroom from an environment where it is
|
||||
set to the same value used by Claude Code.
|
||||
- This integration is for the Claude Code extension, not the Claude desktop app.
|
||||
|
||||
Claude Code and Anthropic decide whether the selected model and account can use
|
||||
the 1M tier. Local settings tests prove persistence and restoration only; they do
|
||||
not prove a live entitled VS Code session, extension behavior, or a 1M context
|
||||
window.
|
||||
|
||||
+40
-22
@@ -75,6 +75,9 @@ from headroom.copilot_auth import (
|
||||
)
|
||||
from headroom.providers.aider import build_launch_env as _build_aider_launch_env
|
||||
from headroom.providers.claude import (
|
||||
CONTEXT_1M_SUFFIX,
|
||||
DEFAULT_1M_MODEL,
|
||||
HEADROOM_1M_MODEL_ENV,
|
||||
REMOTE_CONTROL_BASE_URL_ENV,
|
||||
TOOL_SEARCH_DEFAULT,
|
||||
TOOL_SEARCH_ENV,
|
||||
@@ -88,6 +91,9 @@ from headroom.providers.claude import (
|
||||
remote_control_gate_message,
|
||||
remote_control_sibling_gate_note,
|
||||
remove_vscode_claude_settings,
|
||||
resolve_1m_model,
|
||||
resolve_vscode_claude_model,
|
||||
resolve_vscode_claude_model_for_instructions,
|
||||
vscode_claude_proxy_url,
|
||||
)
|
||||
from headroom.providers.claude import (
|
||||
@@ -321,28 +327,15 @@ _AGENT_SAVINGS_WRAP_AGENTS = {"claude", "codex", "cursor", "grok", "grok_build"}
|
||||
# ANTHROPIC_BASE_URL (the proxy) its `/model` picker selection does not survive,
|
||||
# so `--1m` forces the suffix via ANTHROPIC_MODEL on the launched process.
|
||||
_ANTHROPIC_MODEL_ENV = "ANTHROPIC_MODEL"
|
||||
_CONTEXT_1M_SUFFIX = "[1m]"
|
||||
_1M_MODEL_ENV = "HEADROOM_1M_MODEL"
|
||||
# Fallback model for `--1m` when nothing else selects one (no ANTHROPIC_MODEL,
|
||||
# no explicit --model). Overridable via HEADROOM_1M_MODEL so it can track new
|
||||
# Opus releases without a code change and without pinning ANTHROPIC_MODEL
|
||||
# globally (which would also change non-`--1m` sessions and override Claude
|
||||
# Code's /model picker). #2937.
|
||||
_DEFAULT_1M_MODEL = "claude-opus-5"
|
||||
# Private aliases preserve the standalone wrapper's existing test and import
|
||||
# surface while the provider runtime owns the 1M selection contract.
|
||||
_CONTEXT_1M_SUFFIX = CONTEXT_1M_SUFFIX
|
||||
_1M_MODEL_ENV = HEADROOM_1M_MODEL_ENV
|
||||
_DEFAULT_1M_MODEL = DEFAULT_1M_MODEL
|
||||
_OPENCLAUDE_INSTRUCTIONS_FILE = "CONVENTIONS.md"
|
||||
|
||||
|
||||
def _resolve_1m_model(current: str | None) -> str:
|
||||
"""Return the model id that makes Claude Code request the 1M window (#1158).
|
||||
|
||||
Preserves a model the user already selected via ``ANTHROPIC_MODEL`` (only
|
||||
appending the ``[1m]`` suffix when missing). When none is set it falls back
|
||||
to ``HEADROOM_1M_MODEL`` if defined, else the built-in default Opus (#2937).
|
||||
Idempotent — a value already ending in ``[1m]`` is returned unchanged.
|
||||
"""
|
||||
fallback = (os.environ.get(_1M_MODEL_ENV) or "").strip() or _DEFAULT_1M_MODEL
|
||||
base = (current or "").strip() or fallback
|
||||
return base if base.endswith(_CONTEXT_1M_SUFFIX) else f"{base}{_CONTEXT_1M_SUFFIX}"
|
||||
_resolve_1m_model = resolve_1m_model
|
||||
|
||||
|
||||
def _apply_1m_to_claude_args(args: tuple[str, ...]) -> tuple[tuple[str, ...], str | None]:
|
||||
@@ -6127,34 +6120,59 @@ def unwrap_vscode_copilot(settings_file: Path | None) -> None:
|
||||
default=True,
|
||||
help="Safely add/update Claude Code's proxy environment settings",
|
||||
)
|
||||
@click.option(
|
||||
"--1m",
|
||||
"context_1m",
|
||||
is_flag=True,
|
||||
help=(
|
||||
"Persist Claude Code's [1m] model selector in settings for the 1M "
|
||||
"context window (issue #3360)."
|
||||
),
|
||||
)
|
||||
def vscode_claude(
|
||||
port: int,
|
||||
memory: bool,
|
||||
settings_file: Path | None,
|
||||
configure: bool,
|
||||
context_1m: bool,
|
||||
) -> None:
|
||||
"""Route VS Code's official Claude Code extension through Headroom.
|
||||
|
||||
Run this from your project, reload VS Code after first setup, and keep this
|
||||
command running while using Claude Code. Authentication and model selection
|
||||
remain unchanged. Run `headroom unwrap vscode-claude` to restore settings.
|
||||
remain unchanged. Use --1m to opt into Claude Code's client-owned 1M model
|
||||
selector. Run `headroom unwrap vscode-claude` to restore settings.
|
||||
"""
|
||||
target_settings = settings_file or claude_user_settings_path()
|
||||
|
||||
def _print_setup(actual_port: int) -> None:
|
||||
proxy_url = vscode_claude_proxy_url(actual_port, _project_name_from_cwd())
|
||||
if configure:
|
||||
action = configure_vscode_claude_settings(target_settings, proxy_url)
|
||||
action = configure_vscode_claude_settings(
|
||||
target_settings, proxy_url, context_1m=context_1m
|
||||
)
|
||||
click.echo(f" VS Code Claude Code proxy settings {action}: {target_settings}")
|
||||
if context_1m:
|
||||
click.echo(
|
||||
f" 1M context model persisted: {resolve_vscode_claude_model(target_settings)}"
|
||||
)
|
||||
click.echo(" Next: Reload VS Code, then use the Claude Code panel.")
|
||||
click.echo(" Keep this command running. Press Ctrl+C to stop the proxy.")
|
||||
click.echo(" Authentication and the selected Claude model are preserved.")
|
||||
if context_1m:
|
||||
click.echo(" Authentication is preserved; the 1M model selector is enabled.")
|
||||
else:
|
||||
click.echo(" Authentication and the selected Claude model are preserved.")
|
||||
click.echo(" Undo later with: headroom unwrap vscode-claude")
|
||||
click.echo(" Guide: https://docs.headroomlabs.ai/docs/vscode-claude-code")
|
||||
return
|
||||
click.echo(f" Add these values under 'env' in {target_settings}:")
|
||||
click.echo(f' "ANTHROPIC_BASE_URL": "{proxy_url}",')
|
||||
click.echo(f' "{_TOOL_SEARCH_ENV}": "{_TOOL_SEARCH_DEFAULT}"')
|
||||
if context_1m:
|
||||
click.echo(f" Add this top-level setting to {target_settings}:")
|
||||
click.echo(
|
||||
f' "model": "{resolve_vscode_claude_model_for_instructions(target_settings)}"'
|
||||
)
|
||||
|
||||
_run_proxy_only_watcher(
|
||||
agent_label="VS CODE CLAUDE",
|
||||
|
||||
@@ -2,7 +2,10 @@
|
||||
|
||||
from .runtime import (
|
||||
CLAUDE_AUTH_KEYS,
|
||||
CONTEXT_1M_SUFFIX,
|
||||
DEFAULT_1M_MODEL,
|
||||
DEFAULT_API_URL,
|
||||
HEADROOM_1M_MODEL_ENV,
|
||||
REMOTE_CONTROL_BASE_URL_ENV,
|
||||
REMOTE_CONTROL_GATED_MIN_VERSION,
|
||||
REMOTE_CONTROL_NON_SUBSCRIPTION_ENV,
|
||||
@@ -19,21 +22,29 @@ from .runtime import (
|
||||
remote_control_gate_active,
|
||||
remote_control_gate_message,
|
||||
remote_control_sibling_gate_note,
|
||||
resolve_1m_model,
|
||||
)
|
||||
from .vscode import (
|
||||
claude_user_settings_path,
|
||||
configure_vscode_claude_settings,
|
||||
remove_vscode_claude_settings,
|
||||
resolve_vscode_claude_model,
|
||||
resolve_vscode_claude_model_for_instructions,
|
||||
vscode_claude_proxy_url,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"CLAUDE_AUTH_KEYS",
|
||||
"CONTEXT_1M_SUFFIX",
|
||||
"claude_user_settings_path",
|
||||
"configure_vscode_claude_settings",
|
||||
"remove_vscode_claude_settings",
|
||||
"resolve_vscode_claude_model",
|
||||
"resolve_vscode_claude_model_for_instructions",
|
||||
"vscode_claude_proxy_url",
|
||||
"DEFAULT_API_URL",
|
||||
"DEFAULT_1M_MODEL",
|
||||
"HEADROOM_1M_MODEL_ENV",
|
||||
"REMOTE_CONTROL_BASE_URL_ENV",
|
||||
"REMOTE_CONTROL_GATED_MIN_VERSION",
|
||||
"REMOTE_CONTROL_NON_SUBSCRIPTION_ENV",
|
||||
@@ -46,6 +57,7 @@ __all__ = [
|
||||
"is_custom_anthropic_base_url",
|
||||
"parse_claude_code_version",
|
||||
"proxy_base_url",
|
||||
"resolve_1m_model",
|
||||
"remote_control_applies_to_auth",
|
||||
"remote_control_gate_active",
|
||||
"remote_control_gate_message",
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import re
|
||||
from collections.abc import Mapping
|
||||
from urllib.parse import urlparse
|
||||
@@ -20,6 +21,27 @@ REMOTE_CONTROL_BASE_URL_ENV = "ANTHROPIC_BASE_URL"
|
||||
REMOTE_CONTROL_FEATURE = "Remote Control"
|
||||
CLAUDE_AUTH_KEYS = ("ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN")
|
||||
|
||||
# Claude Code requests the 1M context tier when its client-owned model setting
|
||||
# carries this suffix. Keep the selector in the Claude provider runtime so the
|
||||
# standalone wrapper and the VS Code settings path use identical fallback and
|
||||
# idempotence rules.
|
||||
CONTEXT_1M_SUFFIX = "[1m]"
|
||||
HEADROOM_1M_MODEL_ENV = "HEADROOM_1M_MODEL"
|
||||
DEFAULT_1M_MODEL = "claude-opus-5"
|
||||
|
||||
|
||||
def resolve_1m_model(current: str | None) -> str:
|
||||
"""Return the selected model with exactly one Claude 1M suffix.
|
||||
|
||||
An explicit model wins over the configurable fallback. Blank values use
|
||||
``HEADROOM_1M_MODEL`` and then the built-in default. Existing suffixes are
|
||||
preserved so repeated setup is idempotent.
|
||||
"""
|
||||
fallback = (os.environ.get(HEADROOM_1M_MODEL_ENV) or "").strip() or DEFAULT_1M_MODEL
|
||||
base = (current or "").strip() or fallback
|
||||
return base if base.endswith(CONTEXT_1M_SUFFIX) else f"{base}{CONTEXT_1M_SUFFIX}"
|
||||
|
||||
|
||||
# GH #1779: Claude Code v2.1.196 added a client-side eligibility check that
|
||||
# DISABLES first-party Remote Control (`/remote-control` / `/rc`, which mirrors a
|
||||
# local CLI session to claude.ai/code and the mobile apps) whenever
|
||||
|
||||
@@ -12,6 +12,7 @@ from typing import Any
|
||||
import click
|
||||
|
||||
from headroom import fsutil
|
||||
from headroom.providers.claude.runtime import resolve_1m_model
|
||||
from headroom.proxy.project_context import with_project_prefix
|
||||
|
||||
_BASE_URL_KEY = "ANTHROPIC_BASE_URL"
|
||||
@@ -79,12 +80,104 @@ def _env_map(payload: dict[str, Any], path: Path) -> dict[str, Any]:
|
||||
return dict(env)
|
||||
|
||||
|
||||
def _model_value(payload: dict[str, Any], path: Path) -> str | None:
|
||||
if "model" not in payload:
|
||||
return None
|
||||
model = payload["model"]
|
||||
if not isinstance(model, str):
|
||||
raise click.ClickException(
|
||||
f"Claude settings {path} has a non-string top-level 'model' value; "
|
||||
"refusing to overwrite it."
|
||||
)
|
||||
return model
|
||||
|
||||
|
||||
def resolve_vscode_claude_model(path: Path) -> str:
|
||||
"""Resolve the 1M model from settings without writing settings or state."""
|
||||
payload = _read_settings(path)
|
||||
return resolve_1m_model(_model_value(payload, path))
|
||||
|
||||
|
||||
def resolve_vscode_claude_model_for_instructions(path: Path) -> str:
|
||||
"""Resolve a model for manual setup instructions, tolerating bad settings."""
|
||||
try:
|
||||
return resolve_vscode_claude_model(path)
|
||||
except click.ClickException:
|
||||
return resolve_1m_model(None)
|
||||
|
||||
|
||||
def _write_json(path: Path, payload: dict[str, Any]) -> None:
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
fsutil.write_text(path, json.dumps(payload, indent=2) + "\n")
|
||||
|
||||
|
||||
def configure_vscode_claude_settings(path: Path, proxy_url: str) -> str:
|
||||
def _validate_previous(previous: dict[str, Any], state_path: Path) -> None:
|
||||
for key in _MANAGED_KEYS:
|
||||
saved = previous.get(key)
|
||||
if (
|
||||
not isinstance(saved, dict)
|
||||
or not isinstance(saved.get("present"), bool)
|
||||
or "value" not in saved
|
||||
):
|
||||
raise click.ClickException(
|
||||
f"Headroom state {state_path} is incomplete; refusing to edit."
|
||||
)
|
||||
|
||||
|
||||
def _validate_model_record(state: dict[str, Any], state_path: Path) -> dict[str, Any] | None:
|
||||
if "model" not in state:
|
||||
return None
|
||||
model_state = state["model"]
|
||||
if not isinstance(model_state, dict):
|
||||
raise click.ClickException(
|
||||
f"Headroom state {state_path} has an incomplete model record; refusing to edit."
|
||||
)
|
||||
previous = model_state.get("previous")
|
||||
managed = model_state.get("managed")
|
||||
if (
|
||||
not isinstance(previous, dict)
|
||||
or not isinstance(previous.get("present"), bool)
|
||||
or "value" not in previous
|
||||
or not isinstance(managed, str)
|
||||
or (not previous["present"] and previous.get("value") is not None)
|
||||
or (previous["present"] and not isinstance(previous.get("value"), str))
|
||||
):
|
||||
raise click.ClickException(
|
||||
f"Headroom state {state_path} has an incomplete model record; refusing to edit."
|
||||
)
|
||||
return model_state
|
||||
|
||||
|
||||
def _validate_state(state: dict[str, Any], state_path: Path) -> dict[str, Any] | None:
|
||||
if state.get("version") != _STATE_VERSION or not isinstance(state.get("previous"), dict):
|
||||
raise click.ClickException(
|
||||
f"Headroom state {state_path} is unsupported or incomplete; refusing to edit."
|
||||
)
|
||||
previous = state["previous"]
|
||||
_validate_previous(previous, state_path)
|
||||
managed = state.get("managed")
|
||||
if not isinstance(managed, dict):
|
||||
raise click.ClickException(f"Headroom state {state_path} has no managed values.")
|
||||
if any(key not in managed or not isinstance(managed[key], str) for key in _MANAGED_KEYS):
|
||||
raise click.ClickException(f"Headroom state {state_path} is incomplete; refusing to edit.")
|
||||
return _validate_model_record(state, state_path)
|
||||
|
||||
|
||||
def _model_is_managed(payload: dict[str, Any], managed: str) -> bool:
|
||||
return "model" in payload and payload["model"] == managed
|
||||
|
||||
|
||||
def _restore_model(payload: dict[str, Any], model_state: dict[str, Any]) -> None:
|
||||
previous = model_state["previous"]
|
||||
if previous["present"]:
|
||||
payload["model"] = previous["value"]
|
||||
else:
|
||||
payload.pop("model", None)
|
||||
|
||||
|
||||
def configure_vscode_claude_settings(
|
||||
path: Path, proxy_url: str, *, context_1m: bool = False
|
||||
) -> str:
|
||||
"""Route Claude Code's VS Code process through Headroom, reversibly."""
|
||||
payload = _read_settings(path)
|
||||
env = _env_map(payload, path)
|
||||
@@ -97,20 +190,21 @@ def configure_vscode_claude_settings(path: Path, proxy_url: str) -> str:
|
||||
|
||||
if state_path.exists():
|
||||
state = _read_object(state_path, label="Headroom state")
|
||||
if state.get("version") != _STATE_VERSION or not isinstance(state.get("previous"), dict):
|
||||
raise click.ClickException(
|
||||
f"Headroom state {state_path} is unsupported or incomplete; refusing to edit."
|
||||
)
|
||||
old_managed = state.get("managed")
|
||||
if not isinstance(old_managed, dict) or any(
|
||||
env.get(key) != old_managed.get(key) for key in _MANAGED_KEYS
|
||||
):
|
||||
model_state = _validate_state(state, state_path)
|
||||
old_managed = state["managed"]
|
||||
if any(env.get(key) != old_managed[key] for key in _MANAGED_KEYS):
|
||||
raise click.ClickException(
|
||||
"Claude settings changed one of Headroom's managed values. Run "
|
||||
"`headroom unwrap vscode-claude` or resolve the conflict before retrying."
|
||||
)
|
||||
if model_state is not None and not _model_is_managed(payload, model_state["managed"]):
|
||||
raise click.ClickException(
|
||||
"Claude settings changed Headroom's managed model. Run "
|
||||
"`headroom unwrap vscode-claude` or resolve the conflict before retrying."
|
||||
)
|
||||
action = "updated"
|
||||
else:
|
||||
model_state = None
|
||||
state = {
|
||||
"version": _STATE_VERSION,
|
||||
"settings_existed": path.exists(),
|
||||
@@ -120,6 +214,28 @@ def configure_vscode_claude_settings(path: Path, proxy_url: str) -> str:
|
||||
}
|
||||
action = "added"
|
||||
|
||||
if context_1m:
|
||||
current_model = _model_value(payload, path)
|
||||
if model_state is None:
|
||||
resolved_model = resolve_1m_model(current_model)
|
||||
state["model"] = {
|
||||
"previous": {
|
||||
"present": "model" in payload,
|
||||
"value": current_model,
|
||||
},
|
||||
"managed": resolved_model,
|
||||
}
|
||||
else:
|
||||
previous_model = model_state["previous"]
|
||||
prior_value = previous_model["value"] if previous_model["present"] else None
|
||||
resolved_model = resolve_1m_model(prior_value)
|
||||
model_state["managed"] = resolved_model
|
||||
state["model"] = model_state
|
||||
payload["model"] = resolved_model
|
||||
elif model_state is not None:
|
||||
_restore_model(payload, model_state)
|
||||
state.pop("model", None)
|
||||
|
||||
env.update(managed)
|
||||
payload["env"] = env
|
||||
state["managed"] = managed
|
||||
@@ -134,29 +250,25 @@ def remove_vscode_claude_settings(path: Path) -> bool:
|
||||
if not state_path.exists():
|
||||
return False
|
||||
state = _read_object(state_path, label="Headroom state")
|
||||
previous = state.get("previous")
|
||||
managed = state.get("managed")
|
||||
if state.get("version") != _STATE_VERSION or not isinstance(previous, dict):
|
||||
raise click.ClickException(
|
||||
f"Headroom state {state_path} is unsupported or incomplete; refusing to edit."
|
||||
)
|
||||
if not isinstance(managed, dict):
|
||||
raise click.ClickException(f"Headroom state {state_path} has no managed values.")
|
||||
model_state = _validate_state(state, state_path)
|
||||
previous = state["previous"]
|
||||
managed = state["managed"]
|
||||
|
||||
payload = _read_settings(path)
|
||||
env = _env_map(payload, path)
|
||||
if any(env.get(key) != managed.get(key) for key in _MANAGED_KEYS):
|
||||
if any(env.get(key) != managed[key] for key in _MANAGED_KEYS):
|
||||
raise click.ClickException(
|
||||
"Claude settings changed one of Headroom's managed values; refusing to overwrite "
|
||||
f"the user's change. Resolve the conflict in {path}, then retry."
|
||||
)
|
||||
if model_state is not None and not _model_is_managed(payload, model_state["managed"]):
|
||||
raise click.ClickException(
|
||||
"Claude settings changed Headroom's managed model; refusing to overwrite the user's "
|
||||
f"change. Resolve the conflict in {path}, then retry."
|
||||
)
|
||||
|
||||
for key in _MANAGED_KEYS:
|
||||
saved = previous.get(key)
|
||||
if not isinstance(saved, dict) or not isinstance(saved.get("present"), bool):
|
||||
raise click.ClickException(
|
||||
f"Headroom state {state_path} is incomplete; refusing to edit."
|
||||
)
|
||||
if saved["present"]:
|
||||
env[key] = saved.get("value")
|
||||
else:
|
||||
@@ -166,6 +278,9 @@ def remove_vscode_claude_settings(path: Path) -> bool:
|
||||
else:
|
||||
payload.pop("env", None)
|
||||
|
||||
if model_state is not None:
|
||||
_restore_model(payload, model_state)
|
||||
|
||||
if payload or state.get("settings_existed"):
|
||||
_write_json(path, payload)
|
||||
elif path.exists():
|
||||
|
||||
@@ -6,6 +6,7 @@ import json
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
from click.testing import CliRunner
|
||||
|
||||
from headroom.cli.main import main
|
||||
@@ -30,6 +31,13 @@ def test_wrap_vscode_claude_configures_actual_port(tmp_path: Path) -> None:
|
||||
assert captured["agent_type"] == "claude"
|
||||
|
||||
|
||||
def test_wrap_vscode_claude_help_exposes_1m() -> None:
|
||||
result = CliRunner().invoke(main, ["wrap", "vscode-claude", "--help"])
|
||||
|
||||
assert result.exit_code == 0, result.output
|
||||
assert "--1m" in result.output
|
||||
|
||||
|
||||
def test_wrap_vscode_claude_no_configure_prints_settings(tmp_path: Path) -> None:
|
||||
path = tmp_path / "settings.json"
|
||||
|
||||
@@ -48,6 +56,104 @@ def test_wrap_vscode_claude_no_configure_prints_settings(tmp_path: Path) -> None
|
||||
assert "ENABLE_TOOL_SEARCH" in result.output
|
||||
|
||||
|
||||
def test_wrap_vscode_claude_1m_persists_model(tmp_path: Path) -> None:
|
||||
path = tmp_path / "settings.json"
|
||||
path.write_text(
|
||||
json.dumps({"model": "claude-sonnet-5", "custom": {"keep": True}}), encoding="utf-8"
|
||||
)
|
||||
|
||||
def fake_watcher(**kwargs): # noqa: ANN003, ANN202
|
||||
kwargs["print_setup_lines"](8787)
|
||||
|
||||
with patch("headroom.cli.wrap._run_proxy_only_watcher", side_effect=fake_watcher):
|
||||
result = CliRunner().invoke(
|
||||
main,
|
||||
["wrap", "vscode-claude", "--1m", "--settings-file", str(path)],
|
||||
)
|
||||
|
||||
assert result.exit_code == 0, result.output
|
||||
configured = json.loads(path.read_text(encoding="utf-8"))
|
||||
assert configured["model"] == "claude-sonnet-5[1m]"
|
||||
assert configured["custom"] == {"keep": True}
|
||||
assert "1M context model persisted: claude-sonnet-5[1m]" in result.output
|
||||
|
||||
|
||||
def test_wrap_vscode_claude_default_leaves_model_unchanged(tmp_path: Path) -> None:
|
||||
path = tmp_path / "settings.json"
|
||||
path.write_text(
|
||||
json.dumps({"model": "claude-sonnet-5", "custom": {"keep": True}}), encoding="utf-8"
|
||||
)
|
||||
|
||||
def fake_watcher(**kwargs): # noqa: ANN003, ANN202
|
||||
kwargs["print_setup_lines"](8787)
|
||||
|
||||
with patch("headroom.cli.wrap._run_proxy_only_watcher", side_effect=fake_watcher):
|
||||
result = CliRunner().invoke(
|
||||
main,
|
||||
["wrap", "vscode-claude", "--settings-file", str(path)],
|
||||
)
|
||||
|
||||
assert result.exit_code == 0, result.output
|
||||
assert json.loads(path.read_text(encoding="utf-8"))["model"] == "claude-sonnet-5"
|
||||
assert "1M context model persisted:" not in result.output
|
||||
|
||||
|
||||
def test_wrap_vscode_claude_no_configure_1m_is_write_free(tmp_path: Path) -> None:
|
||||
path = tmp_path / "settings.json"
|
||||
original = '{"model":"claude-opus-5","custom":{"keep":true}}'
|
||||
path.write_text(original, encoding="utf-8")
|
||||
state_path = tmp_path / ".headroom-vscode-claude.json"
|
||||
state_path.write_text('{"sentinel":true}', encoding="utf-8")
|
||||
|
||||
def fake_watcher(**kwargs): # noqa: ANN003, ANN202
|
||||
kwargs["print_setup_lines"](8787)
|
||||
|
||||
with patch("headroom.cli.wrap._run_proxy_only_watcher", side_effect=fake_watcher):
|
||||
result = CliRunner().invoke(
|
||||
main,
|
||||
["wrap", "vscode-claude", "--no-configure", "--1m", "--settings-file", str(path)],
|
||||
)
|
||||
|
||||
assert result.exit_code == 0, result.output
|
||||
assert '"model": "claude-opus-5[1m]"' in result.output
|
||||
assert (
|
||||
' "ENABLE_TOOL_SEARCH": "true"\n'
|
||||
f" Add this top-level setting to {path}:\n"
|
||||
' "model": "claude-opus-5[1m]"'
|
||||
) in result.output
|
||||
assert path.read_text(encoding="utf-8") == original
|
||||
assert state_path.read_text(encoding="utf-8") == '{"sentinel":true}'
|
||||
|
||||
|
||||
@pytest.mark.parametrize("contents", ["{broken", '{"model":{"name":"opus"}}'])
|
||||
def test_wrap_vscode_claude_no_configure_1m_falls_back_for_invalid_settings(
|
||||
tmp_path: Path, contents: str
|
||||
) -> None:
|
||||
path = tmp_path / "settings.json"
|
||||
path.write_text(contents, encoding="utf-8")
|
||||
state_path = tmp_path / ".headroom-vscode-claude.json"
|
||||
state_path.write_text('{"sentinel":true}', encoding="utf-8")
|
||||
|
||||
def fake_watcher(**kwargs): # noqa: ANN003, ANN202
|
||||
kwargs["print_setup_lines"](8787)
|
||||
|
||||
with patch("headroom.cli.wrap._run_proxy_only_watcher", side_effect=fake_watcher):
|
||||
result = CliRunner().invoke(
|
||||
main,
|
||||
["wrap", "vscode-claude", "--no-configure", "--1m", "--settings-file", str(path)],
|
||||
)
|
||||
|
||||
assert result.exit_code == 0, result.output
|
||||
assert (
|
||||
' "ENABLE_TOOL_SEARCH": "true"\n'
|
||||
f" Add this top-level setting to {path}:\n"
|
||||
' "model": "claude-opus-5[1m]"'
|
||||
) in result.output
|
||||
assert ' "ENABLE_TOOL_SEARCH": "true",\n' not in result.output
|
||||
assert path.read_text(encoding="utf-8") == contents
|
||||
assert state_path.read_text(encoding="utf-8") == '{"sentinel":true}'
|
||||
|
||||
|
||||
def test_unwrap_vscode_claude_restores_previous_settings(tmp_path: Path) -> None:
|
||||
path = tmp_path / "settings.json"
|
||||
original = {"env": {"KEEP": "1"}, "permissions": {"allow": ["Read"]}}
|
||||
|
||||
@@ -1,9 +1,42 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from headroom.providers.claude import DEFAULT_API_URL, proxy_base_url
|
||||
import pytest
|
||||
|
||||
from headroom.providers.claude import (
|
||||
CONTEXT_1M_SUFFIX,
|
||||
DEFAULT_1M_MODEL,
|
||||
DEFAULT_API_URL,
|
||||
HEADROOM_1M_MODEL_ENV,
|
||||
proxy_base_url,
|
||||
resolve_1m_model,
|
||||
)
|
||||
|
||||
|
||||
def test_claude_runtime_exposes_default_api_and_local_proxy_url() -> None:
|
||||
# Arrange / Act / Assert
|
||||
assert DEFAULT_API_URL == "https://api.anthropic.com"
|
||||
assert proxy_base_url(4321) == "http://127.0.0.1:4321"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("current", "fallback", "expected"),
|
||||
[
|
||||
(" claude-sonnet-5 ", None, "claude-sonnet-5[1m]"),
|
||||
("claude-opus-5[1m]", "ignored", "claude-opus-5[1m]"),
|
||||
(None, " claude-opus-9 ", "claude-opus-9[1m]"),
|
||||
(" ", None, f"{DEFAULT_1M_MODEL}{CONTEXT_1M_SUFFIX}"),
|
||||
],
|
||||
)
|
||||
def test_resolve_1m_model_contract_is_provider_owned(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
current: str | None,
|
||||
fallback: str | None,
|
||||
expected: str,
|
||||
) -> None:
|
||||
if fallback is None:
|
||||
monkeypatch.delenv(HEADROOM_1M_MODEL_ENV, raising=False)
|
||||
else:
|
||||
monkeypatch.setenv(HEADROOM_1M_MODEL_ENV, fallback)
|
||||
|
||||
assert resolve_1m_model(current) == expected
|
||||
assert resolve_1m_model(expected) == expected
|
||||
|
||||
@@ -13,6 +13,8 @@ from headroom.providers.claude.vscode import (
|
||||
claude_user_settings_path,
|
||||
configure_vscode_claude_settings,
|
||||
remove_vscode_claude_settings,
|
||||
resolve_vscode_claude_model,
|
||||
resolve_vscode_claude_model_for_instructions,
|
||||
vscode_claude_proxy_url,
|
||||
)
|
||||
|
||||
@@ -82,6 +84,165 @@ def test_reconfigure_updates_port_without_losing_original_values(tmp_path: Path)
|
||||
}
|
||||
|
||||
|
||||
def test_configure_1m_snapshots_selected_model_and_restores_exact_value(
|
||||
tmp_path: Path,
|
||||
) -> None:
|
||||
path = tmp_path / "settings.json"
|
||||
original = {
|
||||
"model": " claude-sonnet-5 ",
|
||||
"permissions": {"allow": ["Read"]},
|
||||
"env": {"KEEP": "yes"},
|
||||
}
|
||||
path.write_text(json.dumps(original), encoding="utf-8")
|
||||
|
||||
configure_vscode_claude_settings(path, "http://127.0.0.1:8787", context_1m=True)
|
||||
configured = json.loads(path.read_text(encoding="utf-8"))
|
||||
state = json.loads((tmp_path / ".headroom-vscode-claude.json").read_text(encoding="utf-8"))
|
||||
assert configured["model"] == "claude-sonnet-5[1m]"
|
||||
assert state["model"] == {
|
||||
"previous": {"present": True, "value": " claude-sonnet-5 "},
|
||||
"managed": "claude-sonnet-5[1m]",
|
||||
}
|
||||
|
||||
assert remove_vscode_claude_settings(path)
|
||||
assert json.loads(path.read_text(encoding="utf-8")) == original
|
||||
|
||||
|
||||
def test_configure_1m_is_idempotent_and_does_not_double_suffix(tmp_path: Path) -> None:
|
||||
path = tmp_path / "settings.json"
|
||||
path.write_text('{"model":"claude-opus-5[1m]"}', encoding="utf-8")
|
||||
|
||||
configure_vscode_claude_settings(path, "http://127.0.0.1:8787", context_1m=True)
|
||||
configure_vscode_claude_settings(path, "http://127.0.0.1:9999", context_1m=True)
|
||||
|
||||
configured = json.loads(path.read_text(encoding="utf-8"))
|
||||
state = json.loads((tmp_path / ".headroom-vscode-claude.json").read_text(encoding="utf-8"))
|
||||
assert configured["model"] == "claude-opus-5[1m]"
|
||||
assert state["model"]["previous"] == {"present": True, "value": "claude-opus-5[1m]"}
|
||||
assert remove_vscode_claude_settings(path)
|
||||
assert json.loads(path.read_text(encoding="utf-8"))["model"] == "claude-opus-5[1m]"
|
||||
|
||||
|
||||
def test_configure_1m_preserves_present_empty_model(tmp_path: Path) -> None:
|
||||
path = tmp_path / "settings.json"
|
||||
path.write_text('{"model":""}', encoding="utf-8")
|
||||
|
||||
configure_vscode_claude_settings(path, "http://127.0.0.1:8787", context_1m=True)
|
||||
state = json.loads((tmp_path / ".headroom-vscode-claude.json").read_text(encoding="utf-8"))
|
||||
assert state["model"]["previous"] == {"present": True, "value": ""}
|
||||
assert remove_vscode_claude_settings(path)
|
||||
assert json.loads(path.read_text(encoding="utf-8"))["model"] == ""
|
||||
|
||||
|
||||
def test_configure_1m_uses_fallback_and_disable_restores_missing_model(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
path = tmp_path / "settings.json"
|
||||
monkeypatch.setenv("HEADROOM_1M_MODEL", "claude-opus-9")
|
||||
|
||||
configure_vscode_claude_settings(path, "http://127.0.0.1:8787", context_1m=True)
|
||||
assert json.loads(path.read_text(encoding="utf-8"))["model"] == "claude-opus-9[1m]"
|
||||
|
||||
monkeypatch.setenv("HEADROOM_1M_MODEL", "claude-opus-10")
|
||||
configure_vscode_claude_settings(path, "http://127.0.0.1:8787", context_1m=True)
|
||||
assert json.loads(path.read_text(encoding="utf-8"))["model"] == "claude-opus-10[1m]"
|
||||
|
||||
assert configure_vscode_claude_settings(path, "http://127.0.0.1:9999") == "updated"
|
||||
configured = json.loads(path.read_text(encoding="utf-8"))
|
||||
state = json.loads((tmp_path / ".headroom-vscode-claude.json").read_text(encoding="utf-8"))
|
||||
assert "model" not in configured
|
||||
assert "model" not in state
|
||||
assert configured["env"]["ANTHROPIC_BASE_URL"] == "http://127.0.0.1:9999"
|
||||
|
||||
assert remove_vscode_claude_settings(path)
|
||||
assert not path.exists()
|
||||
|
||||
|
||||
def test_legacy_v1_sidecar_can_add_and_restore_model_state(tmp_path: Path) -> None:
|
||||
path = tmp_path / "settings.json"
|
||||
configure_vscode_claude_settings(path, "http://127.0.0.1:8787")
|
||||
configure_vscode_claude_settings(path, "http://127.0.0.1:8787", context_1m=True)
|
||||
|
||||
state = json.loads((tmp_path / ".headroom-vscode-claude.json").read_text(encoding="utf-8"))
|
||||
assert state["version"] == 1
|
||||
assert state["model"]["previous"] == {"present": False, "value": None}
|
||||
assert remove_vscode_claude_settings(path)
|
||||
assert not path.exists()
|
||||
|
||||
|
||||
def test_configure_1m_rejects_non_string_model_without_writes(tmp_path: Path) -> None:
|
||||
path = tmp_path / "settings.json"
|
||||
original = {"model": {"name": "opus"}, "env": {"KEEP": "yes"}}
|
||||
path.write_text(json.dumps(original), encoding="utf-8")
|
||||
|
||||
with pytest.raises(click.ClickException, match="non-string"):
|
||||
configure_vscode_claude_settings(path, "http://127.0.0.1:8787", context_1m=True)
|
||||
|
||||
assert json.loads(path.read_text(encoding="utf-8")) == original
|
||||
assert not (tmp_path / ".headroom-vscode-claude.json").exists()
|
||||
|
||||
|
||||
def test_configure_without_1m_preserves_unmanaged_model_and_nested_values(tmp_path: Path) -> None:
|
||||
path = tmp_path / "settings.json"
|
||||
original = {
|
||||
"model": "claude-sonnet-5",
|
||||
"permissions": {"allow": ["Read"]},
|
||||
"custom": {"nested": {"value": True}},
|
||||
}
|
||||
path.write_text(json.dumps(original), encoding="utf-8")
|
||||
|
||||
configure_vscode_claude_settings(path, "http://127.0.0.1:8787")
|
||||
configured = json.loads(path.read_text(encoding="utf-8"))
|
||||
assert configured["model"] == original["model"]
|
||||
assert configured["permissions"] == original["permissions"]
|
||||
assert configured["custom"] == original["custom"]
|
||||
|
||||
|
||||
def test_model_conflicts_fail_closed_on_configure_and_remove(tmp_path: Path) -> None:
|
||||
path = tmp_path / "settings.json"
|
||||
path.write_text('{"model":"claude-sonnet-5"}', encoding="utf-8")
|
||||
configure_vscode_claude_settings(path, "http://127.0.0.1:8787", context_1m=True)
|
||||
|
||||
payload = json.loads(path.read_text(encoding="utf-8"))
|
||||
payload["model"] = "user-selected-model"
|
||||
path.write_text(json.dumps(payload), encoding="utf-8")
|
||||
state_path = tmp_path / ".headroom-vscode-claude.json"
|
||||
state_before = state_path.read_text(encoding="utf-8")
|
||||
|
||||
with pytest.raises(click.ClickException, match="managed model"):
|
||||
configure_vscode_claude_settings(path, "http://127.0.0.1:9999", context_1m=True)
|
||||
with pytest.raises(click.ClickException, match="managed model"):
|
||||
remove_vscode_claude_settings(path)
|
||||
|
||||
assert json.loads(path.read_text(encoding="utf-8"))["model"] == "user-selected-model"
|
||||
assert state_path.read_text(encoding="utf-8") == state_before
|
||||
|
||||
|
||||
def test_resolve_vscode_claude_model_is_read_only(tmp_path: Path) -> None:
|
||||
path = tmp_path / "settings.json"
|
||||
path.write_text('{"model":"claude-opus-5"}', encoding="utf-8")
|
||||
|
||||
assert resolve_vscode_claude_model(path) == "claude-opus-5[1m]"
|
||||
assert path.read_text(encoding="utf-8") == '{"model":"claude-opus-5"}'
|
||||
assert not (tmp_path / ".headroom-vscode-claude.json").exists()
|
||||
|
||||
|
||||
def test_resolve_vscode_claude_model_for_instructions_falls_back_for_non_string(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
path = tmp_path / "settings.json"
|
||||
original = '{"model":{"name":"opus"}}'
|
||||
path.write_text(original, encoding="utf-8")
|
||||
monkeypatch.setenv("HEADROOM_1M_MODEL", "claude-opus-9")
|
||||
|
||||
with pytest.raises(click.ClickException, match="non-string"):
|
||||
resolve_vscode_claude_model(path)
|
||||
|
||||
assert resolve_vscode_claude_model_for_instructions(path) == "claude-opus-9[1m]"
|
||||
assert path.read_text(encoding="utf-8") == original
|
||||
assert not (tmp_path / ".headroom-vscode-claude.json").exists()
|
||||
|
||||
|
||||
def test_remove_deletes_settings_created_only_for_headroom(tmp_path: Path) -> None:
|
||||
path = tmp_path / "settings.json"
|
||||
configure_vscode_claude_settings(path, "http://127.0.0.1:8787/p/demo")
|
||||
@@ -94,7 +255,7 @@ def test_configure_refuses_malformed_settings(tmp_path: Path) -> None:
|
||||
path = tmp_path / "settings.json"
|
||||
path.write_text("{broken", encoding="utf-8")
|
||||
with pytest.raises(click.ClickException, match="not valid JSON"):
|
||||
configure_vscode_claude_settings(path, "http://127.0.0.1:8787")
|
||||
configure_vscode_claude_settings(path, "http://127.0.0.1:8787", context_1m=True)
|
||||
assert path.read_text(encoding="utf-8") == "{broken"
|
||||
|
||||
|
||||
@@ -135,6 +296,47 @@ def test_remove_without_headroom_state_is_noop(tmp_path: Path) -> None:
|
||||
({"version": 2}, "unsupported or incomplete"),
|
||||
({"managed": None}, "has no managed values"),
|
||||
({"previous": {"ANTHROPIC_BASE_URL": None}}, "is incomplete"),
|
||||
({"model": None}, "incomplete model record"),
|
||||
(
|
||||
{"model": {"previous": None, "managed": "claude-opus-5[1m]"}},
|
||||
"incomplete model record",
|
||||
),
|
||||
(
|
||||
{
|
||||
"model": {
|
||||
"previous": {"present": True},
|
||||
"managed": "claude-opus-5[1m]",
|
||||
}
|
||||
},
|
||||
"incomplete model record",
|
||||
),
|
||||
(
|
||||
{
|
||||
"model": {
|
||||
"previous": {"present": False, "value": "unexpected"},
|
||||
"managed": "claude-opus-5[1m]",
|
||||
}
|
||||
},
|
||||
"incomplete model record",
|
||||
),
|
||||
(
|
||||
{
|
||||
"model": {
|
||||
"previous": {"present": True, "value": 5},
|
||||
"managed": "claude-opus-5[1m]",
|
||||
}
|
||||
},
|
||||
"incomplete model record",
|
||||
),
|
||||
(
|
||||
{
|
||||
"model": {
|
||||
"previous": {"present": False, "value": None},
|
||||
"managed": None,
|
||||
}
|
||||
},
|
||||
"incomplete model record",
|
||||
),
|
||||
],
|
||||
)
|
||||
def test_remove_refuses_incomplete_state(
|
||||
@@ -168,6 +370,16 @@ def test_reconfigure_refuses_incomplete_or_conflicting_state(tmp_path: Path) ->
|
||||
configure_vscode_claude_settings(path, proxy_url)
|
||||
|
||||
|
||||
def test_remove_refuses_missing_state_keys(tmp_path: Path) -> None:
|
||||
path = tmp_path / "settings.json"
|
||||
configure_vscode_claude_settings(path, "http://127.0.0.1:8787")
|
||||
state_path = tmp_path / ".headroom-vscode-claude.json"
|
||||
state_path.write_text("{}", encoding="utf-8")
|
||||
|
||||
with pytest.raises(click.ClickException, match="unsupported or incomplete"):
|
||||
remove_vscode_claude_settings(path)
|
||||
|
||||
|
||||
def test_remove_refuses_to_overwrite_changed_managed_value(tmp_path: Path) -> None:
|
||||
path = tmp_path / "settings.json"
|
||||
configure_vscode_claude_settings(path, "http://127.0.0.1:8787/p/demo")
|
||||
|
||||
Reference in New Issue
Block a user