Compress tool outputs, logs, files, and RAG chunks before they reach the LLM. 20% fewer tokens for coding agents, 60-95% fewer tokens for JSON, same answers. Library, proxy, MCP server.
Python agentaianthropicclaude-codecompressioncontext-engineeringcontext-windowcursorfastapilangchainllmmcpopenaiprompt-engineeringproxypythonragtoken-optimizationtokenstypescript
fix(copilot): warn when a VS Code profile cannot see the proxy settings (#3919)
Ayush Kumar Jha7b68fc263a92
diff --git a/docs/content/docs/vscode-copilot.mdx b/docs/content/docs/vscode-copilot.mdxindex 41a8c3299..28ca276e1 100644--- a/docs/content/docs/vscode-copilot.mdx+++ b/docs/content/docs/vscode-copilot.mdx@@ -159,6 +159,9 @@ both `copilot-auth login` and `wrap vscode`.does not add or rename models.- If connection is refused, keep the wrapper running and check loopback/remoteport reachability.+- If Headroom records no requests while Copilot keeps working, the window is+ probably using a VS Code profile with its own settings. `wrap vscode` warns+ about each such profile and prints the `--settings-file` path to configure it.- Use `--port 8788` when the default port is occupied; settings update safely.- If Headroom refuses settings, repair the reported JSONC/marker conflict or use`--no-configure` and apply the printed settings manually.diff --git a/headroom/cli/wrap.py b/headroom/cli/wrap.pyindex e7a017662..2c09e9f72 100644--- a/headroom/cli/wrap.py+++ b/headroom/cli/wrap.py@@ -116,6 +116,7 @@ from headroom.providers.copilot import (from headroom.providers.copilot import (configure_vscode_proxy_settings,remove_vscode_proxy_settings,+ unrouted_vscode_profiles,vscode_proxy_url,vscode_settings_path,)@@ -6688,6 +6689,12 @@ def vscode_copilot(vscode_proxy_url(actual_port, _project_name_from_cwd()),)click.echo(f" VS Code Copilot proxy settings {action}: {target_settings}")+ for name, profile_settings in unrouted_vscode_profiles(target_settings.parent):+ click.echo(+ f" Warning: VS Code profile '{name}' keeps its own settings, so Copilot "+ "there still bypasses Headroom. Route it with: headroom wrap vscode "+ f'--settings-file "{profile_settings}"'+ )click.echo(" Keep using Copilot's normal model picker; the selected model is preserved.")diff --git a/headroom/providers/copilot/__init__.py b/headroom/providers/copilot/__init__.pyindex d35a375a4..7fac88a8d 100644--- a/headroom/providers/copilot/__init__.py+++ b/headroom/providers/copilot/__init__.py@@ -3,6 +3,7 @@from .vscode import (configure_vscode_proxy_settings,remove_vscode_proxy_settings,+ unrouted_vscode_profiles,vscode_proxy_url,vscode_settings_path,vscode_user_dir,@@ -37,6 +38,7 @@ __all__ = ["validate_configuration","configure_vscode_proxy_settings","remove_vscode_proxy_settings",+ "unrouted_vscode_profiles","vscode_proxy_url","vscode_settings_path","vscode_user_dir",diff --git a/headroom/providers/copilot/vscode.py b/headroom/providers/copilot/vscode.pyindex 28fa8418b..2723f36d4 100644--- a/headroom/providers/copilot/vscode.py+++ b/headroom/providers/copilot/vscode.py@@ -108,13 +108,16 @@ def _strip_jsonc_comments(value: str) -> str:return "".join(result)-def _validate_settings(raw: str, path: Path) -> None:+def _parse_settings(raw: str) -> object:candidate = _strip_jsonc_comments(raw)if candidate.startswith("\ufeff"):candidate = candidate[1:]- candidate = re.sub(r",\s*([}\]])", r"\1", candidate)+ return json.loads(re.sub(r",\s*([}\]])", r"\1", candidate))+++def _validate_settings(raw: str, path: Path) -> None:try:- parsed = json.loads(candidate)+ parsed = _parse_settings(raw)except json.JSONDecodeError as exc:raise click.ClickException(f"Could not safely parse {path}: {exc}. Headroom did not overwrite it."@@ -198,3 +201,43 @@ def configure_vscode_proxy_settings(path: Path, proxy_url: str) -> str:_validate_settings(updated, path)fsutil.write_text(path, updated)return "updated" if had_managed_block else "added"+++def unrouted_vscode_profiles(user_dir: Path) -> list[tuple[str, Path]]:+ """Return ``(name, settings.json)`` for profiles that ignore ``user_dir/settings.json``.++ A window in a profile with its own settings reads only that profile's+ settings.json, and Copilot takes its endpoint overrides from user settings+ alone, so overrides in the user directory's settings.json never reach it.+ A directory that is not a VS Code user directory has no profiles.+ """+ try:+ state = json.loads(+ (user_dir / "globalStorage" / "storage.json").read_text(encoding="utf-8")+ )+ except (OSError, ValueError):+ return []+ profiles = state.get("userDataProfiles") if isinstance(state, dict) else None+ unrouted: list[tuple[str, Path]] = []+ for profile in profiles if isinstance(profiles, list) else []:+ if not isinstance(profile, dict):+ continue+ flags = profile.get("useDefaultFlags")+ location = profile.get("location")+ # VS Code names local profile folders hash(uuid).toString(16); any other+ # location (a remote URI) is not a folder under profiles/.+ if (isinstance(flags, dict) and flags.get("settings")) or not (+ isinstance(location, str) and re.fullmatch(r"[\w-]+", location)+ ):+ continue+ path = user_dir / "profiles" / location / "settings.json"+ try:+ settings = _parse_settings(_read_settings(path))+ except (OSError, ValueError, click.ClickException):+ settings = None+ # Only live settings count: the managed-block marker is itself a comment.+ if isinstance(settings, dict) and _PROXY_KEY in settings and _CAPI_KEY in settings:+ continue+ name = profile.get("name")+ unrouted.append((name if isinstance(name, str) else location, path))+ return unrouteddiff --git a/tests/test_cli/test_wrap_vscode.py b/tests/test_cli/test_wrap_vscode.pyindex 01a7daa7b..fc7b457f9 100644--- a/tests/test_cli/test_wrap_vscode.py+++ b/tests/test_cli/test_wrap_vscode.py@@ -2,9 +2,11 @@from __future__ import annotations+import jsonfrom pathlib import Pathfrom unittest.mock import patch+import pytestfrom click.testing import CliRunnerfrom headroom.cli.main import main@@ -46,6 +48,78 @@ def test_wrap_vscode_configures_actual_port_and_seeds_subscription(tmp_path: Patassert captured["copilot_api_token"] == "copilot-token"+def _run_wrap_vscode(*args: str) -> str:+ def fake_watcher(**kwargs): # noqa: ANN003, ANN202+ kwargs["print_setup_lines"](8787)++ with (+ patch(+ "headroom.cli.wrap._require_copilot_subscription_resolution", return_value=_resolution()+ ),+ patch("headroom.cli.wrap._run_proxy_only_watcher", side_effect=fake_watcher),+ ):+ result = CliRunner().invoke(main, ["wrap", "vscode", *args])+ assert result.exit_code == 0, result.output+ return result.output+++def _write_profiles(user_dir: Path, *profiles: dict[str, object]) -> None:+ storage = user_dir / "globalStorage" / "storage.json"+ storage.parent.mkdir(parents=True)+ storage.write_text(json.dumps({"userDataProfiles": list(profiles)}), encoding="utf-8")+++def _default_user_dir(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:+ for var in ("APPDATA", "HOME", "USERPROFILE", "XDG_CONFIG_HOME"):+ monkeypatch.setenv(var, str(tmp_path))+ from headroom.providers.copilot.vscode import vscode_user_dir++ return vscode_user_dir()+++def test_wrap_vscode_names_profiles_that_ignore_default_settings(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ user_dir = _default_user_dir(tmp_path, monkeypatch)+ _write_profiles(+ user_dir,+ {"location": "6c87cdb4", "name": "Work"},+ {"location": "1a2b", "name": "Shared", "useDefaultFlags": {"settings": True}},+ )+ work_settings = user_dir / "profiles" / "6c87cdb4" / "settings.json"++ implicit = _run_wrap_vscode()+ assert "overrideCapiUrl" in (user_dir / "settings.json").read_text(encoding="utf-8")+ # A window in the "Work" profile reads only its own settings.json, so the+ # block above never reaches it; say so instead of reporting plain success.+ assert "VS Code profile 'Work'" in implicit+ assert str(work_settings) in implicit+ # A profile that shares the Default profile's settings already sees the block.+ assert "Shared" not in implicit+ # Naming the Default file explicitly configures the same file, so it warns too.+ explicit = _run_wrap_vscode("--settings-file", str(user_dir / "settings.json"))+ assert "VS Code profile 'Work'" in explicit+ # Following the advice routes the profile, and nothing is left to warn about.+ assert "Warning" not in _run_wrap_vscode("--settings-file", str(work_settings))+ assert "Warning" not in _run_wrap_vscode()+++def test_wrap_vscode_checks_the_profiles_of_the_user_dir_it_configures(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ _write_profiles(+ _default_user_dir(tmp_path, monkeypatch), {"location": "6c87cdb4", "name": "Work"}+ )+ # e.g. VS Code Insiders, VSCodium, or a portable install with its own profiles.+ other_user_dir = tmp_path / "Code - Insiders" / "User"+ _write_profiles(other_user_dir, {"location": "-2b3c4d", "name": "Beta"})++ output = _run_wrap_vscode("--settings-file", str(other_user_dir / "settings.json"))++ assert "VS Code profile 'Beta'" in output+ assert "Work" not in output++def test_wrap_vscode_no_configure_prints_transparent_settings(tmp_path: Path) -> None:path = tmp_path / "settings.json"diff --git a/tests/test_provider_copilot_vscode_config.py b/tests/test_provider_copilot_vscode_config.pyindex a90d30da1..d290dfe4e 100644--- a/tests/test_provider_copilot_vscode_config.py+++ b/tests/test_provider_copilot_vscode_config.py@@ -1,5 +1,6 @@from __future__ import annotations+import jsonfrom pathlib import Pathimport click@@ -8,6 +9,7 @@ import pytestfrom headroom.providers.copilot.vscode import (configure_vscode_proxy_settings,remove_vscode_proxy_settings,+ unrouted_vscode_profiles,vscode_proxy_url,vscode_settings_path,)@@ -107,3 +109,102 @@ def test_configure_refuses_duplicate_managed_markers(tmp_path: Path) -> None:with pytest.raises(click.ClickException, match="marker block"):configure_vscode_proxy_settings(path, "http://127.0.0.1:8787")assert path.read_text(encoding="utf-8") == original+++def _write_profiles(tmp_path: Path, state: object) -> Path:+ user_dir = tmp_path / "User"+ storage = user_dir / "globalStorage" / "storage.json"+ storage.parent.mkdir(parents=True)+ storage.write_text(state if isinstance(state, str) else json.dumps(state), encoding="utf-8")+ return user_dir+++def test_unrouted_profiles_lists_only_profiles_with_their_own_settings(tmp_path: Path) -> None:+ user_dir = _write_profiles(+ tmp_path,+ {+ "userDataProfiles": [+ {"location": "6c87cdb4", "name": "Work"},+ {"location": "-1f2e3d", "name": "Negative hash"},+ {"location": "aa11", "name": "Shared", "useDefaultFlags": {"settings": True}},+ {"location": "../escape", "name": "Traversal"},+ {"location": {"scheme": "vscode-remote", "path": "/p"}, "name": "Remote"},+ "not-a-profile",+ ]+ },+ )++ assert unrouted_vscode_profiles(user_dir) == [+ ("Work", user_dir / "profiles" / "6c87cdb4" / "settings.json"),+ ("Negative hash", user_dir / "profiles" / "-1f2e3d" / "settings.json"),+ ]++[email protected]("managed", [True, False])+def test_unrouted_profiles_skips_a_profile_that_overrides_both_endpoints(+ tmp_path: Path, managed: bool+) -> None:+ user_dir = _write_profiles(+ tmp_path, {"userDataProfiles": [{"location": "6c87cdb4", "name": "Work"}]}+ )+ profile_settings = user_dir / "profiles" / "6c87cdb4" / "settings.json"+ profile_settings.parent.mkdir(parents=True)+ if managed:+ configure_vscode_proxy_settings(profile_settings, "http://127.0.0.1:8787")+ else:+ profile_settings.write_text(+ """{+ "github.copilot.advanced.debug.overrideProxyUrl": "http://127.0.0.1:8787",+ "github.copilot.advanced.debug.overrideCapiUrl": "http://127.0.0.1:8787",+}+""",+ encoding="utf-8",+ )++ assert unrouted_vscode_profiles(user_dir) == []+++ "settings",+ [+ # The marker is itself a comment, so on its own it proves nothing.+ """{+ // --- Headroom Copilot proxy ---+}+""",+ """{+ // --- Headroom Copilot proxy ---+ // "github.copilot.advanced.debug.overrideProxyUrl": "http://127.0.0.1:8787",+ // "github.copilot.advanced.debug.overrideCapiUrl": "http://127.0.0.1:8787"+ // --- end Headroom Copilot proxy ---+}+""",+ """{+ "note": "// --- Headroom Copilot proxy ---",+ "github.copilot.advanced.debug.overrideCapiUrl": "http://127.0.0.1:8787"+}+""",+ '{ "github.copilot.advanced.debug.overrideCapiUrl": ',+ ],+ ids=["marker-only", "commented-out-keys", "one-key", "unparseable"],+)+def test_unrouted_profiles_counts_only_live_override_settings(+ tmp_path: Path, settings: str+) -> None:+ user_dir = _write_profiles(+ tmp_path, {"userDataProfiles": [{"location": "6c87cdb4", "name": "Work"}]}+ )+ profile_settings = user_dir / "profiles" / "6c87cdb4" / "settings.json"+ profile_settings.parent.mkdir(parents=True)+ profile_settings.write_text(settings, encoding="utf-8")++ assert unrouted_vscode_profiles(user_dir) == [("Work", profile_settings)]++[email protected]("state", ["{not json", [], {"userDataProfiles": {"a": 1}}, {}])+def test_unrouted_profiles_tolerates_unexpected_vscode_state(tmp_path: Path, state: object) -> None:+ assert unrouted_vscode_profiles(_write_profiles(tmp_path, state)) == []+++def test_unrouted_profiles_without_vscode_state(tmp_path: Path) -> None:+ assert unrouted_vscode_profiles(tmp_path) == []