Files
alzeo/tests/test_uninstall_opencode.py
T
Hasan BasbunarandClaude Opus 5.5 ade00a01bb opencode 2: list opencode's hosted provider and its free models again (decision 1595)
From v1.56.0 the generated OpenCode 2 config denied opencode's own provider
("policies", provider.use on "opencode"), and a fresh install copied that deny
into the user's global config: the Agent tab's picker lost the free models
1.x lists beside the box's lanes, a choice nobody had made. The generated
config denies no provider now; the default and small model stay the box's
lane. An update takes the exact deny of v1.56.0 to v1.59.0 out of the global
config (oc-merge-limits.py --remove-provider-deny, after a backup); a policy
of the user's own stays, and disabled_providers is never touched.

Tests: test_oc_provider_deny.py (the tool, and install.sh's own lines on a
v1.59.0 copy), the generated config on both majors, the uninstall purge on
copies with and without the old deny. Red on the old code, green after.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 17:55:07 +01:00

226 lines
14 KiB
Python

#!/usr/bin/env python3
"""uninstall.sh --yes must not leave opencode unable to start.
The providers install.sh writes read the API key through a {file:} reference, and
opencode refuses to start at all, every provider included, while one points at a file
that is gone ("bad file reference", opencode 1.18.32, reference box 2026-09-23). --yes
deletes that file, and since v1.18.4 every fresh box gets such a config. These run the
uninstaller's own lines, as written, in a throwaway HOME."""
import json
import re
import os
import pathlib
import shutil
import subprocess
import tempfile
import unittest
REPO = pathlib.Path(__file__).resolve().parents[1]
UNINSTALL = REPO / "uninstall.sh"
def purge_block() -> str:
text = UNINSTALL.read_text()
start = text.index('if [ "$PURGE_CONFIG" -eq 1 ]; then\n # opencode refuses')
end = text.index("\nfi\n", text.index("they answer again after ./install.sh", start)) + 4
return text[start:end]
# what --deny-bash puts in the copy: the rules under their own key (oc-merge-limits.py deny_permission)
RULES = {"bash*": {"*aliyuncs.com*": "deny", "*169.254.169.254*": "deny", "*100.100.100.200*": "deny"},
"webfetch*": {"*aliyuncs.com*": "deny", "*169.254.169.254*": "deny", "*100.100.100.200*": "deny"}}
def box(key):
return {"npm": "@ai-sdk/openai-compatible",
"options": {"baseURL": "http://127.0.0.1:30001/v1", "apiKey": "{file:" + key + "}"},
"models": {"qwen3.8-27b": {"limit": {"context": 1000, "input": 1000, "output": 100}}}}
class UninstallLeavesOpencodeStartable(unittest.TestCase):
def run_it(self, user_cfg, purge):
home = pathlib.Path(tempfile.mkdtemp(prefix="un-oc-"))
cfg = home / ".config" / "qwen38"
cfg.mkdir(parents=True)
(cfg / "api-key").write_text("k\n")
oc = home / ".config" / "opencode" / "opencode.json"
if user_cfg is not None:
oc.parent.mkdir(parents=True)
oc.write_text(user_cfg(str(cfg / "api-key")))
cfgs = " ".join(f'"{oc.parent / n}"' for n in ("config.json", "opencode.json", "opencode.jsonc"))
script = (f'set -euo pipefail\nPURGE_CONFIG={purge}; CONFIG_DIR="{cfg}"; OC_USER_CFGS=({cfgs}); '
f'REPO_DIR="{REPO}"\n' + purge_block())
r = subprocess.run(["bash", "-c", script], capture_output=True, text=True, timeout=60,
env={"HOME": str(home), "PATH": "/usr/bin:/bin"})
self.assertEqual(r.returncode, 0, r.stdout + r.stderr)
return r.stdout + r.stderr, home, cfg, oc
def test_the_copy_install_sh_made_goes_with_the_key(self):
mine = lambda k: json.dumps({"$schema": "https://opencode.ai/config.json", "autoupdate": "notify",
"provider": {"qwen38": box(k)}, "model": "qwen38/qwen3.8-27b",
"small_model": "qwen38/qwen3.8-27b"}, indent=2)
out, home, cfg, oc = self.run_it(mine, purge=1)
self.assertFalse(cfg.exists())
self.assertFalse(oc.exists())
self.assertIn("held only this box's providers (qwen38): moved to", out)
self.assertEqual(len(list(oc.parent.glob("opencode.json.bak-*"))), 1, "no backup was kept")
def test_the_copy_with_the_rules_goes_with_the_key_too(self):
# v1.40.4 puts the bash rules in the copy: it stayed, its provider gone and autoupdate off for good
# (found in review, 2026-10-29). Rules of the user's own keep the file.
for rules, gone in ((RULES, True), ({"bash*": {**RULES["bash*"], "rm -rf *": "deny"}}, False)):
with self.subTest(gone=gone):
mine = lambda k: json.dumps({"$schema": "https://opencode.ai/config.json", "autoupdate": False,
"provider": {"qwen38": box(k)}, "model": "qwen38/qwen3.8-27b",
"permission": rules}, indent=2)
out, home, cfg, oc = self.run_it(mine, purge=1)
self.assertEqual(oc.exists(), not gone, out)
if gone:
self.assertIn("held only this box's providers (qwen38): moved to", out)
else:
self.assertEqual(json.loads(oc.read_text())["permission"], rules)
def test_the_copy_a_v2_install_made_goes_with_the_key_too(self):
# review of v1.56.0, finding 3: a fresh OpenCode 2 install copies the generated config, with
# its v2 keys (permissions, policies, share, websearch, update), as the user's global config;
# the purge did not count those keys as ours, so the copy stayed, emptied of its provider.
# A value the user changed keeps the file.
import importlib.util
spec = importlib.util.spec_from_file_location("ocm", REPO / "oc-merge-limits.py")
ocm = importlib.util.module_from_spec(spec)
spec.loader.exec_module(ocm)
# the values the purge counts as ours are the ones install.sh writes in the generated v2 config,
# and the deny on opencode's hosted provider that v1.56.0 to v1.59.0 wrote there too: a copy made
# then still holds it (decision 1595, 2026-11-25: no release writes it any more)
install = (REPO / "install.sh").read_text()
for line in ('doc["share"] = "disabled"', 'doc["websearch"] = False', 'doc["update"] = "disable"'):
self.assertIn(line, install, "install.sh and the purge must agree on the v2 keys")
self.assertNotIn('doc["policies"]', install)
self.assertEqual(ocm.PROVIDER_DENY_V156,
[{"action": "provider.use", "resource": "opencode", "effect": "deny"}])
for policies in (ocm.PROVIDER_DENY_V156, None):
for websearch, gone in ((False, True), (True, False)):
with self.subTest(policies=policies is not None, gone=gone):
doc = {"$schema": "https://opencode.ai/config.json",
"compaction": {"keep": {"tokens": 135000}, "background": True},
"model": "qwen38/qwen3.8-27b", "small_model": "qwen38/qwen3.8-27b",
"permission": RULES, "permissions": ocm.deny_permissions_v2(),
"share": "disabled", "websearch": websearch, "update": "disable"}
if policies is not None:
doc["policies"] = policies
mine = lambda k: json.dumps({**doc, "provider": {"qwen38": box(k)}}, indent=2)
out, home, cfg, oc = self.run_it(mine, purge=1)
self.assertEqual(oc.exists(), not gone, out)
if gone:
self.assertIn("held only this box's providers (qwen38): moved to", out)
else:
self.assertIs(json.loads(oc.read_text())["websearch"], True)
def test_the_copy_of_a_release_before_v157_goes_with_the_key_too(self):
# up to v1.56.0 the copy held the shell rules alone ("bash*" in 1.x, three shell rules in 2.x): a box
# uninstalled with this release's script, without an install of it in between, still holds that
# shape, and it is still this repo's copy, not the person's
import importlib.util
spec = importlib.util.spec_from_file_location("ocm", REPO / "oc-merge-limits.py")
ocm = importlib.util.module_from_spec(spec)
spec.loader.exec_module(ocm)
shell_only = {"bash*": dict.fromkeys(ocm.DENY_BASH, "deny")}
for extra in ({"permission": shell_only},
{"permission": shell_only, "permissions": ocm.deny_permissions_v2_before_v157()}):
with self.subTest(keys=sorted(extra)):
mine = lambda k: json.dumps({"$schema": "https://opencode.ai/config.json", "autoupdate": False,
"provider": {"qwen38": box(k)}, "model": "qwen38/qwen3.8-27b",
**extra}, indent=2)
out, home, cfg, oc = self.run_it(mine, purge=1)
self.assertFalse(oc.exists(), out)
self.assertIn("held only this box's providers (qwen38): moved to", out)
def test_a_users_own_config_keeps_everything_but_the_box(self):
theirs = lambda k: json.dumps({"model": "qwen38/qwen3.8-27b", "plugin": ["x.js"],
"provider": {"qwen38": box(k), "anthropic": {}}})
out, home, cfg, oc = self.run_it(theirs, purge=1)
self.assertFalse(cfg.exists())
self.assertEqual(json.loads(oc.read_text()), {"plugin": ["x.js"], "provider": {"anthropic": {}}})
self.assertIn("removed the qwen38 provider", out)
def test_kept_config_says_the_providers_wait_for_a_reinstall(self):
theirs = lambda k: json.dumps({"provider": {"qwen38": box(k)}})
out, home, cfg, oc = self.run_it(theirs, purge=0)
self.assertTrue((cfg / "api-key").exists())
self.assertIn('"qwen38"', oc.read_text())
self.assertIn("still lists this box's providers", out)
def test_a_block_pasted_into_opencodes_own_jsonc_goes_too(self):
# opencode writes opencode.jsonc itself on its first start, so that is where a
# user following "merge the qwen38 block" may well have put it.
home = pathlib.Path(tempfile.mkdtemp(prefix="un-oc-"))
cfg = home / ".config" / "qwen38"
cfg.mkdir(parents=True)
(cfg / "api-key").write_text("k\n")
jsonc = home / ".config" / "opencode" / "opencode.jsonc"
jsonc.parent.mkdir(parents=True)
jsonc.write_text('{\n // mine\n "provider": {"qwen38": ' + json.dumps(box(str(cfg / "api-key")))
+ ', "x": {}}\n}\n')
cfgs = " ".join(f'"{jsonc.parent / n}"' for n in ("config.json", "opencode.json", "opencode.jsonc"))
r = subprocess.run(["bash", "-c", f'set -euo pipefail\nPURGE_CONFIG=1; CONFIG_DIR="{cfg}"; '
f'OC_USER_CFGS=({cfgs}); REPO_DIR="{REPO}"\n' + purge_block()],
capture_output=True, text=True, env={"HOME": str(home), "PATH": "/usr/bin:/bin"})
self.assertEqual(r.returncode, 0, r.stdout + r.stderr)
self.assertNotIn("qwen38", jsonc.read_text())
self.assertIn("// mine", jsonc.read_text())
def test_a_cache_the_container_wrote_as_root_is_removed_quietly(self):
# A directory the user cannot write stands for the root-owned compile cache: the
# plain rm fails on it, and the fallback (a fake sudo here) removes the rest.
home = pathlib.Path(tempfile.mkdtemp(prefix="un-cache-"))
cfg = home / ".config" / "qwen38"
locked = cfg / "sglang-cache" / "inductor" / "yl"
locked.mkdir(parents=True)
(locked / "c.py").write_text("x")
locked.chmod(0o555)
fake = home / "bin"
fake.mkdir()
(fake / "sudo").write_text('#!/bin/sh\necho "sudo $*" >> "$HOME/sudo.log"\n'
'chmod -R u+w "$4" && exec "$@"\n')
(fake / "sudo").chmod(0o755)
cfgs = " ".join(f'"{home / ".config" / "opencode" / n}"' for n in ("config.json", "opencode.json", "opencode.jsonc"))
r = subprocess.run(["bash", "-c", f'set -euo pipefail\nPURGE_CONFIG=1; CONFIG_DIR="{cfg}"; '
f'OC_USER_CFGS=({cfgs}); REPO_DIR="{REPO}"\n' + purge_block()],
capture_output=True, text=True, env={"HOME": str(home), "PATH": f"{fake}:/usr/bin:/bin"})
self.assertEqual(r.returncode, 0, r.stdout + r.stderr)
self.assertFalse(cfg.exists())
self.assertNotIn("Permission", r.stdout + r.stderr)
self.assertEqual((home / "sudo.log").read_text(), f"sudo rm -rf --one-file-system {cfg}\n")
def test_no_opencode_config_is_no_opencode_line(self):
out, home, cfg, oc = self.run_it(None, purge=1)
self.assertEqual(out.strip(), "config removed.")
@unittest.skipUnless(shutil.which("opencode") or os.path.exists(os.path.expanduser("~/.opencode/bin/opencode")),
"needs a real opencode to show it starts")
def test_the_real_opencode_starts_after_the_purge(self):
theirs = lambda k: json.dumps({"provider": {"qwen38": box(k), "other": {"npm": "@ai-sdk/openai-compatible",
"options": {"baseURL": "http://127.0.0.1:9/v1"}, "models": {"m": {}}}}})
out, home, cfg, oc = self.run_it(theirs, purge=1)
binary = shutil.which("opencode") or os.path.expanduser("~/.opencode/bin/opencode")
# OpenCode 2 (the default since v1.56.0) takes no provider after `models` and prints its help
# for one; it lists every model, other/m among them. Without --standalone it starts its managed
# background service (`opencode serve --service`), which outlives the test and holds its port
# (measured on 2.3.2 the 2026-11-22); --standalone runs a server that ends with the command
# asked in the throwaway HOME too: OpenCode 2 writes its log file under HOME even for --version
# (measured on 2.3.2 the 2026-11-23), and asked with the suite's own HOME it left that file there:
# on a box that serves OpenCode 2, "The offline suite touches nothing outside itself" failed (the
# release CI of v1.56.0, on the reference box)
ver = subprocess.run([binary, "--version"], capture_output=True, text=True, timeout=60,
cwd=str(home), env={"HOME": str(home), "PATH": "/usr/bin:/bin"}).stdout
major = (re.findall(r"(\d+)\.\d+\.\d+", ver) or ["1"])[-1]
args = [binary, "models", "--standalone"] if major == "2" else [binary, "models", "other"]
r = subprocess.run(args, capture_output=True, text=True, timeout=120,
cwd=str(home), env={"HOME": str(home), "PATH": "/usr/bin:/bin"})
self.assertNotIn("bad file reference", r.stdout + r.stderr)
self.assertIn("other/m", r.stdout, r.stdout + r.stderr)
if __name__ == "__main__":
unittest.main(verbosity=2)