fix(copilot): warn when a VS Code profile cannot see the proxy settings

`wrap vscode` writes its endpoint overrides into the Default profile's
settings.json. A VS Code window using a profile that keeps its own settings
reads only `User/profiles/<id>/settings.json`, and Copilot takes these
overrides from user settings alone, so in that window Copilot keeps talking
to GitHub directly. Setup still reports success and Headroom sees nothing.

Read the profiles VS Code records in `User/globalStorage/storage.json` and,
for each one with its own settings that lacks Headroom's block, print a
warning with the exact `--settings-file` command that routes it. Nothing is
written to profile files automatically; the docs already scope profiles to
`--settings-file`, and the block persists and fails closed after the proxy
stops.

Refs #3716
This commit is contained in:
Ayushraj06-bit
2026-10-02 13:51:47 +05:30
parent d5318ac235
commit c887cbab15
6 changed files with 159 additions and 0 deletions
+3
View File
@@ -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/remote
port 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.
+8
View File
@@ -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,
)
@@ -6641,6 +6642,13 @@ def vscode_copilot(
vscode_proxy_url(actual_port, _project_name_from_cwd()),
)
click.echo(f" VS Code Copilot proxy settings {action}: {target_settings}")
if settings_file is None:
for name, profile_settings in unrouted_vscode_profiles():
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."
)
+2
View File
@@ -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",
+40
View File
@@ -59,6 +59,46 @@ def vscode_settings_path(
return vscode_user_dir(platform=platform, environ=environ) / "settings.json"
def unrouted_vscode_profiles(
*, platform: str | None = None, environ: Mapping[str, str] | None = None
) -> list[tuple[str, Path]]:
"""Return ``(name, settings.json)`` for profiles that cannot see Headroom's block.
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 the block in the Default profile's file never reaches it.
"""
user_dir = vscode_user_dir(platform=platform, environ=environ)
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:
if _MARKER_START in _read_settings(path):
continue
except (OSError, ValueError):
pass
name = profile.get("name")
unrouted.append((name if isinstance(name, str) else location, path))
return unrouted
def vscode_proxy_url(port: int, project: str | None = None) -> str:
"""Return the transparent Copilot endpoint override for a Headroom proxy."""
return str(with_project_prefix(f"http://127.0.0.1:{port}", project))
+51
View File
@@ -2,9 +2,11 @@
from __future__ import annotations
import json
from pathlib import Path
from unittest.mock import patch
import pytest
from click.testing import CliRunner
from headroom.cli.main import main
@@ -46,6 +48,55 @@ def test_wrap_vscode_configures_actual_port_and_seeds_subscription(tmp_path: Pat
assert captured["copilot_api_token"] == "copilot-token"
def test_wrap_vscode_names_profiles_that_ignore_default_settings(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
for var in ("APPDATA", "HOME", "USERPROFILE", "XDG_CONFIG_HOME"):
monkeypatch.setenv(var, str(tmp_path))
from headroom.providers.copilot.vscode import vscode_user_dir
user_dir = vscode_user_dir()
storage = user_dir / "globalStorage" / "storage.json"
storage.parent.mkdir(parents=True)
storage.write_text(
json.dumps(
{
"userDataProfiles": [
{"location": "6c87cdb4", "name": "Work"},
{"location": "1a2b", "name": "Shared", "useDefaultFlags": {"settings": True}},
]
}
),
encoding="utf-8",
)
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"])
# Naming a file explicitly is the remedy itself, so it must not warn.
explicit = CliRunner().invoke(
main, ["wrap", "vscode", "--settings-file", str(tmp_path / "chosen.json")]
)
assert explicit.exit_code == 0, explicit.output
assert "Warning" not in explicit.output
assert result.exit_code == 0, result.output
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 result.output
assert str(user_dir / "profiles" / "6c87cdb4" / "settings.json") in result.output
# A profile that shares the Default profile's settings already sees the block.
assert "Shared" not in result.output
def test_wrap_vscode_no_configure_prints_transparent_settings(tmp_path: Path) -> None:
path = tmp_path / "settings.json"
@@ -1,5 +1,6 @@
from __future__ import annotations
import json
from pathlib import Path
import click
@@ -8,8 +9,10 @@ import pytest
from headroom.providers.copilot.vscode import (
configure_vscode_proxy_settings,
remove_vscode_proxy_settings,
unrouted_vscode_profiles,
vscode_proxy_url,
vscode_settings_path,
vscode_user_dir,
)
@@ -107,3 +110,55 @@ 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) -> tuple[dict[str, str], Path]:
env = {"APPDATA": str(tmp_path)}
user_dir = vscode_user_dir(platform="win32", environ=env)
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 env, user_dir
def test_unrouted_profiles_lists_only_profiles_with_their_own_settings(tmp_path: Path) -> None:
env, 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(platform="win32", environ=env) == [
("Work", user_dir / "profiles" / "6c87cdb4" / "settings.json"),
("Negative hash", user_dir / "profiles" / "-1f2e3d" / "settings.json"),
]
def test_unrouted_profiles_skips_a_profile_already_configured(tmp_path: Path) -> None:
env, 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)
configure_vscode_proxy_settings(profile_settings, "http://127.0.0.1:8787")
assert unrouted_vscode_profiles(platform="win32", environ=env) == []
@pytest.mark.parametrize("state", ["{not json", [], {"userDataProfiles": {"a": 1}}, {}])
def test_unrouted_profiles_tolerates_unexpected_vscode_state(tmp_path: Path, state: object) -> None:
env, _ = _write_profiles(tmp_path, state)
assert unrouted_vscode_profiles(platform="win32", environ=env) == []
def test_unrouted_profiles_without_vscode_state(tmp_path: Path) -> None:
assert unrouted_vscode_profiles(platform="win32", environ={"APPDATA": str(tmp_path)}) == []