Skip to content

Commit 3919a12

Browse files
authored
Merge pull request #12 from payne0420/fix/preserve-global-model
Keep in-session /model picks from leaking into the global default
2 parents 53ed029 + 9e907c2 commit 3919a12

3 files changed

Lines changed: 141 additions & 2 deletions

File tree

‎bin/ultracode‎

Lines changed: 59 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,16 @@ PID_FILE="$BASE_STATE/proxy.pid"
2828
LOG_FILE="$BASE_STATE/proxy.log"
2929
REF_DIR="$BASE_STATE/refs"
3030
OWNER_REF="$REF_DIR/$$"
31+
SAVED_MODEL_FILE="$BASE_STATE/saved_global_model.json"
32+
33+
# Claude Code persists an in-session `/model` pick (Enter in the picker) to the
34+
# user-global settings file as the `model` key (v2.1.153+). Under UltraCode that
35+
# means picking a proxy-only id (e.g. claude-composer) becomes your global
36+
# default and breaks a plain `claude` run outside the proxy. We snapshot that key
37+
# before launch and restore it on exit (ref-count-safe across sessions), so
38+
# /model picks stay session-scoped. Disable with UC_PRESERVE_GLOBAL_MODEL=0.
39+
CFG_DIR="${CLAUDE_CONFIG_DIR:-$HOME/.claude}"
40+
UC_PRESERVE_GLOBAL_MODEL="${UC_PRESERVE_GLOBAL_MODEL:-1}"
3141

3242
PY="$(command -v python3 || command -v python || true)"
3343
[[ -n "$PY" ]] || { echo "Python 3 not found." >&2; exit 1; }
@@ -118,6 +128,53 @@ refs_active() {
118128
[[ -d "$REF_DIR" ]] && [[ -n "$(ls -A "$REF_DIR" 2>/dev/null)" ]]
119129
}
120130

131+
snapshot_global_model() {
132+
# Record the current user-global `model` so an in-session /model pick can't
133+
# leave a proxy-only id as your default. On a clean start (no other live
134+
# UltraCode session) take a fresh snapshot; if a session is already running,
135+
# keep its snapshot so we don't capture a mid-session pick as the "original".
136+
[[ "$UC_PRESERVE_GLOBAL_MODEL" == "0" ]] && return 0
137+
refs_active && [[ -f "$SAVED_MODEL_FILE" ]] && return 0
138+
"$PY" - "$CFG_DIR/settings.json" "$SAVED_MODEL_FILE" <<'PY' 2>/dev/null || true
139+
import json,sys
140+
src,dst=sys.argv[1],sys.argv[2]
141+
try:
142+
s=json.load(open(src))
143+
except Exception:
144+
s={}
145+
json.dump({"had":"model" in s,"model":s.get("model")},open(dst,"w"))
146+
PY
147+
}
148+
149+
restore_global_model() {
150+
# Last session out restores the saved `model` key (or removes it if there was
151+
# none), undoing any /model pick that Claude Code persisted globally.
152+
[[ "$UC_PRESERVE_GLOBAL_MODEL" == "0" ]] && return 0
153+
[[ -f "$SAVED_MODEL_FILE" ]] || return 0
154+
refs_active && return 0
155+
"$PY" - "$CFG_DIR/settings.json" "$SAVED_MODEL_FILE" <<'PY' 2>/dev/null || true
156+
import json,sys
157+
settings_f,saved_f=sys.argv[1],sys.argv[2]
158+
try:
159+
saved=json.load(open(saved_f))
160+
except Exception:
161+
saved={}
162+
try:
163+
s=json.load(open(settings_f))
164+
except Exception:
165+
s=None
166+
if isinstance(s,dict):
167+
if saved.get("had"):
168+
s["model"]=saved.get("model")
169+
else:
170+
s.pop("model",None)
171+
with open(settings_f,"w") as f:
172+
json.dump(s,f,indent=2)
173+
f.write("\n")
174+
PY
175+
rm -f "$SAVED_MODEL_FILE"
176+
}
177+
121178
start_proxy() {
122179
mkdir -p "$REF_DIR"
123180
: > "$OWNER_REF"
@@ -137,18 +194,19 @@ start_proxy() {
137194

138195
stop_proxy() {
139196
rm -f "$OWNER_REF"
197+
restore_global_model
140198
if refs_active; then return 0; fi
141199
[[ -f "$PID_FILE" ]] && kill "$(cat "$PID_FILE" 2>/dev/null)" 2>/dev/null || true
142200
rm -f "$PID_FILE"
143201
}
144202
trap stop_proxy EXIT
145203

204+
snapshot_global_model
146205
start_proxy
147206

148207
# Seed Claude Code's gateway-models cache from the live proxy so the stock Claude
149208
# models, your configured models, and the synthesized Worker -> entries all show
150209
# on the very first /model open (before Claude Code re-fetches /v1/models).
151-
CFG_DIR="${CLAUDE_CONFIG_DIR:-$HOME/.claude}"
152210
"$PY" - "$CFG_DIR/cache/gateway-models.json" "$BASE_URL" <<'PY' || true
153211
import json,os,sys,time,urllib.request
154212
cache_f, base = sys.argv[1], sys.argv[2]

‎docs/TROUBLESHOOTING.md‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,30 @@ caches them, so a new Opus normally appears on its own. If it hasn't:
5757
- **Reset the learned cache.** Delete the file shown at `/healthz` →
5858
`stock_learning.cache` and relaunch.
5959

60+
### A `/model` pick leaked into my global default (plain `claude` now errors on the model)
61+
62+
Claude Code persists an in-session `/model` pick (pressing Enter in the picker) to
63+
your **user-global** settings (`~/.claude/settings.json`, the `model` key) as of
64+
v2.1.153. Under UltraCode that means picking a proxy-only id (e.g.
65+
`claude-composer`, `claude-gpt-5.5-codex`) becomes your global default — and a
66+
plain `claude` run **outside** the proxy then fails, because the real Anthropic
67+
API doesn't know that id.
68+
69+
The launchers guard against this: `bin/ultracode` (and
70+
`windows\Start-UltraCode.ps1`) snapshot the `model` key before launch and restore
71+
it on exit, so `/model` picks stay session-scoped. It's ref-count-safe across
72+
concurrent sessions (the last one out restores) and only touches the `model` key —
73+
the rest of `settings.json` is left intact.
74+
75+
- **Already polluted?** Set `"model"` in `~/.claude/settings.json` back to a real
76+
id (e.g. `"claude-opus-4-8"`), or run `/model` once in a plain `claude` session
77+
and pick a real Claude model.
78+
- **Want a `/model` pick to persist for plain `claude` too?** Disable the guard
79+
with `UC_PRESERVE_GLOBAL_MODEL=0` before launching — in-session picks then save
80+
globally as Claude Code normally does.
81+
- **Keep a pick for this session only without saving (even with the guard off):**
82+
press `s` in the `/model` picker instead of Enter.
83+
6084
### The pre-launch selector doesn't open / says it cannot reach `/uc/select`
6185

6286
- **Proxy not healthy yet or wrong port.** The launcher starts the proxy before

‎windows/Start-UltraCode.ps1‎

Lines changed: 58 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -130,6 +130,61 @@ $RefDir = Join-Path $StateDir "refs"
130130
$PidFile = Join-Path $StateDir "proxy.pid"
131131
$OwnerRef = Join-Path $RefDir "$PID"
132132

133+
# Preserve the user-global model across the session. Claude Code persists an
134+
# in-session /model pick (Enter in the picker) to settings.json as the `model`
135+
# key (v2.1.153+), so picking a proxy-only id would become your global default
136+
# and break a plain `claude` run outside the proxy. We snapshot that key before
137+
# launch and restore it on exit (ref-count-safe). The JSON edit is done via
138+
# Python (not ConvertTo-Json) so the rest of settings.json is left byte-for-key
139+
# intact. Disable with UC_PRESERVE_GLOBAL_MODEL=0.
140+
$CfgDir = if ($env:CLAUDE_CONFIG_DIR) { $env:CLAUDE_CONFIG_DIR } else { Join-Path $HOME ".claude" }
141+
$GlobalSettings = Join-Path $CfgDir "settings.json"
142+
$SavedModelFile = Join-Path $StateDir "saved_global_model.json"
143+
$PreserveGlobalModel = ($env:UC_PRESERVE_GLOBAL_MODEL -ne "0")
144+
$SnapPy = @'
145+
import json,sys
146+
src,dst=sys.argv[1],sys.argv[2]
147+
try: s=json.load(open(src))
148+
except Exception: s={}
149+
json.dump({"had":"model" in s,"model":s.get("model")},open(dst,"w"))
150+
'@
151+
$RestorePy = @'
152+
import json,sys
153+
settings_f,saved_f=sys.argv[1],sys.argv[2]
154+
try: saved=json.load(open(saved_f))
155+
except Exception: saved={}
156+
try: s=json.load(open(settings_f))
157+
except Exception: s=None
158+
if isinstance(s,dict):
159+
if saved.get("had"): s["model"]=saved.get("model")
160+
else: s.pop("model",None)
161+
f=open(settings_f,"w"); json.dump(s,f,indent=2); f.write("\n"); f.close()
162+
'@
163+
164+
function Invoke-UcPy {
165+
param([string]$Code, [string[]]$Rest)
166+
$a = @()
167+
if ($PyCmd.Count -gt 1) { $a += $PyCmd[1..($PyCmd.Count-1)] }
168+
$a += @("-c", $Code) + $Rest
169+
& $PyCmd[0] @a 2>$null
170+
}
171+
172+
function Save-GlobalModel {
173+
if (-not $PreserveGlobalModel) { return }
174+
# Clean start: refresh the snapshot. Other session live: keep theirs so we
175+
# never capture a mid-session pick as the "original".
176+
if ((Test-RefsActive) -and (Test-Path $SavedModelFile)) { return }
177+
try { Invoke-UcPy $SnapPy @($GlobalSettings, $SavedModelFile) } catch {}
178+
}
179+
180+
function Restore-GlobalModel {
181+
if (-not $PreserveGlobalModel) { return }
182+
if (-not (Test-Path $SavedModelFile)) { return }
183+
if (Test-RefsActive) { return } # other sessions live; last one out restores
184+
try { Invoke-UcPy $RestorePy @($GlobalSettings, $SavedModelFile) } catch {}
185+
Remove-Item $SavedModelFile -Force -ErrorAction SilentlyContinue
186+
}
187+
133188
function Test-ProxyHealthy {
134189
try { return (Invoke-WebRequest -Uri "$BaseUrl/healthz" -UseBasicParsing -TimeoutSec 2).StatusCode -eq 200 }
135190
catch { return $false }
@@ -152,6 +207,7 @@ function Test-RefsActive {
152207

153208
function Stop-ProxyIfLast {
154209
Remove-Item $OwnerRef -Force -ErrorAction SilentlyContinue
210+
Restore-GlobalModel
155211
if (Test-RefsActive) { return }
156212
if (Test-Path $PidFile) {
157213
$stopId = Get-Content $PidFile -ErrorAction SilentlyContinue | Select-Object -First 1
@@ -161,6 +217,7 @@ function Stop-ProxyIfLast {
161217
}
162218

163219
New-Item -ItemType Directory -Force -Path $RefDir | Out-Null
220+
Save-GlobalModel
164221
New-Item -ItemType File -Force -Path $OwnerRef | Out-Null
165222

166223
if (Test-ProxyHealthy) {
@@ -190,7 +247,6 @@ if (Test-ProxyHealthy) {
190247
# ----- seed Claude Code's gateway-models cache (first-launch visibility) -----
191248
# Seed stock Claude + your configured models so real Claude and your picks all
192249
# show on the very first /model open (before Claude Code re-fetches /v1/models).
193-
$CfgDir = if ($env:CLAUDE_CONFIG_DIR) { $env:CLAUDE_CONFIG_DIR } else { Join-Path $HOME ".claude" }
194250
$GwCache = Join-Path (Join-Path $CfgDir "cache") "gateway-models.json"
195251
try {
196252
New-Item -ItemType Directory -Force -Path (Split-Path $GwCache) | Out-Null
@@ -217,6 +273,7 @@ try {
217273

218274
if ($ProxyOnly) {
219275
Remove-Item $OwnerRef -Force -ErrorAction SilentlyContinue
276+
Restore-GlobalModel
220277
$shownPid = if (Test-Path $PidFile) { Get-Content $PidFile -ErrorAction SilentlyContinue | Select-Object -First 1 } else { "<pid>" }
221278
Write-Host ""
222279
Write-Host "Proxy running. Connect Claude Code with:"

0 commit comments

Comments
 (0)