"""Show "openhop.cfd" as the wordmark on OpenCode Desktop's start screen (optional, on by default). Safety first: a working OpenCode always beats the visual change. - Only CSS is added (one ' # ---------------------------------------------------------------------------------------------- asar helpers def _read_header(fh) -> tuple[dict, int]: """Return (header json, offset where file data starts).""" fh.seek(0) raw = fh.read(16) if len(raw) < 16: raise ValueError("not an asar file") _, header_size, _, json_len = struct.unpack(" 64 * 1024 * 1024: raise ValueError("bad asar header size") header = json.loads(fh.read(json_len).decode("utf-8")) return header, 8 + header_size def _header_bytes(header: dict) -> bytes: js = json.dumps(header, separators=(",", ":"), ensure_ascii=False).encode("utf-8") pad = (4 - len(js) % 4) % 4 payload = 4 + len(js) + pad return struct.pack(" dict: node = header for part in path: node = node["files"][part] return node def _read_entry(fh, data_start: int, entry: dict) -> bytes: if entry.get("unpacked"): raise ValueError("entry is unpacked") fh.seek(data_start + int(entry["offset"])) return fh.read(int(entry["size"])) def _looks_rewritten(asar: Path) -> bool: """True when the data section holds bytes that no entry points at (this module appends changed files). A de-patched archive still has those appended copies and stale originals, so it's no longer a byte-for-byte copy of the file OpenCode shipped: it must not replace the pristine backup kept for uninstall. """ try: size = asar.stat().st_size with asar.open("rb") as fh: header, start = _read_header(fh) used, stack = 0, [header] while stack: for ent in stack.pop().get("files", {}).values(): if "files" in ent: stack.append(ent) elif not ent.get("unpacked"): used += int(ent.get("size", 0)) return size - start - used > 4096 except Exception: return True # can't tell: never overwrite the backup def _integrity(data: bytes) -> dict: block = 4 * 1024 * 1024 return { "algorithm": "SHA256", "hash": hashlib.sha256(data).hexdigest(), "blockSize": block, "blocks": [hashlib.sha256(data[i:i + block]).hexdigest() for i in range(0, max(len(data), 1), block)], } # ---------------------------------------------------------------------------------------------- finding OpenCode def desktop_dir() -> Path | None: for d in (LOCAL_APPDATA / "Programs" / "ai.opencode.desktop", LOCAL_APPDATA / "Programs" / "OpenCode", Path(r"C:\Program Files\OpenCode"), Path(r"C:\Program Files\ai.opencode.desktop")): if (d / "resources" / "app.asar").is_file() and (d / "OpenCode.exe").is_file(): return d return None def _asar_integrity_enabled(exe: Path) -> bool | None: """True/False from Electron's fuse wire in the exe; None if it can't be read (treated as 'don't patch').""" try: data = exe.read_bytes() i = data.find(_FUSE_SENTINEL) if i < 0: return None length = data[i + len(_FUSE_SENTINEL) + 1] fuses = data[i + len(_FUSE_SENTINEL) + 2: i + len(_FUSE_SENTINEL) + 2 + length] if len(fuses) <= _ASAR_INTEGRITY_FUSE: return False return fuses[_ASAR_INTEGRITY_FUSE:_ASAR_INTEGRITY_FUSE + 1] == b"1" except Exception: return None def desktop_running() -> bool: try: import psutil d = desktop_dir() exe = str(d / "OpenCode.exe").lower() if d else "" for p in psutil.process_iter(["name", "exe"]): try: if (p.info.get("name") or "").lower() == "opencode.exe" and (not exe or (p.info.get("exe") or "").lower() == exe): return True except Exception: pass except Exception: return True # can't tell: assume it is, never patch under it return False def setting_enabled() -> bool: try: data = json.loads((DEST_DIR / "app_settings.json").read_text(encoding="utf-8")) return bool(data.get(SETTING_KEY, True)) except Exception: return True # ---------------------------------------------------------------------------------------------- the free-limit banner # When OpenCode Desktop sees a free-limit error it stores a reset time (default: 1 hour) and, until then, shows a # "Free limit reached" card *instead of* the chat box. openhop has already switched to a new IP and sent "continue" # by then, so the card is wrong and it hides the prompt. The card's "is it active?" check gets a "false &&" in front: # the chat box always stays. Only that one expression changes, and it's put back exactly by removing our marker. BANNER_KEY = "hide_limit_banner" BANNER_MARK = "/*openhop-nobanner*/!1&&" _BANNER_ANCHOR = b"data-component=session-free-limit" _BANNER_RE = re.compile(r"(active:\(\)=>\{let ([\w$]+)=[\w$]+\(\);return)(![\w$]+\(\)&&\2!==null&&\2>[\w$]+\(\)\})") def banner_setting_enabled() -> bool: try: data = json.loads((DEST_DIR / "app_settings.json").read_text(encoding="utf-8")) return bool(data.get(BANNER_KEY, True)) except Exception: return True def _find_banner_chunk(fh, header: dict, start: int) -> tuple[tuple[str, ...], str] | None: """(asar path, text) of the renderer chunk that holds the free-limit card, or None.""" try: assets = _entry(header, ("out", "renderer", "assets"))["files"] except Exception: return None for name, ent in assets.items(): if not name.endswith(".js") or "files" in ent or ent.get("unpacked") or int(ent.get("size", 0)) < 50_000: continue data = _read_entry(fh, start, ent) if _BANNER_ANCHOR in data: return ("out", "renderer", "assets", name), data.decode("utf-8") return None def _banner_js(text: str, want: bool) -> str | None: """The chunk with the banner check switched off (want) or back to OpenCode's own; None if it can't be found.""" if want: if BANNER_MARK in text: return text # the check sits a few hundred characters after the stored `free-limit` state it reads hits = [m for m in _BANNER_RE.finditer(text) if "`free-limit`" in text[max(0, m.start() - 700):m.start()]] if len(hits) != 1: return None m = hits[0] return text[:m.end(1)] + BANNER_MARK + text[m.end(1):] return text.replace(BANNER_MARK, "") # ---------------------------------------------------------------------------------------------- status / apply / restore def _inspect(asar: Path) -> dict: """What's in the archive now: wordmark/banner patched?, and whether each can be patched.""" with asar.open("rb") as fh: header, start = _read_header(fh) html = _read_entry(fh, start, _entry(header, INDEX_PATH)).decode("utf-8", errors="replace") chunk = _find_banner_chunk(fh, header, start) wordmark = MARKER in html banner = bool(chunk and BANNER_MARK in chunk[1]) return { "wordmark": wordmark, "banner": banner, "wordmark_ok": wordmark or "" in html, "banner_ok": banner or bool(chunk and _banner_js(chunk[1], True)), } def status() -> dict: d = desktop_dir() if not d: return {"installed": False, "patched": False, "supported": False, "reason": "OpenCode Desktop not found"} try: info = _inspect(d / "resources" / "app.asar") except Exception as exc: return {"installed": True, "patched": False, "supported": False, "reason": f"unreadable: {exc}"} supported = info["wordmark"] or (info["wordmark_ok"] and "new-session-wordmark" in _renderer_text_hint(d)) return {"installed": True, "patched": info["wordmark"], "supported": supported, "reason": "", "banner_hidden": info["banner"], "banner_supported": info["banner_ok"], "running": desktop_running(), "backup": BACKUP_ASAR.is_file()} def _renderer_text_hint(d: Path) -> str: """Cheap check that this OpenCode build still has the start-screen wordmark we restyle.""" try: with (d / "resources" / "app.asar").open("rb") as fh: header, start = _read_header(fh) assets = _entry(header, ("out", "renderer", "assets"))["files"] for name, ent in assets.items(): if name.startswith("route-") and name.endswith(".js") and not ent.get("unpacked"): chunk = _read_entry(fh, start, ent) if b"new-session-wordmark" in chunk: return "new-session-wordmark" except Exception: pass return "" def _set_state(wordmark: bool | None = None, banner: bool | None = None) -> tuple[bool, str]: """Rewrite app.asar so the wordmark / banner patches match what's asked (None = leave as it is). Changed files are appended at the end of the archive and the header points at the new copies; every other byte stays identical. The result is checked before it replaces the original, and any failure leaves OpenCode as it was. """ d = desktop_dir() if not d: return False, "OpenCode Desktop isn't installed." if desktop_running(): return False, "OpenCode Desktop is open; it will be done the next time it's closed." if _asar_integrity_enabled(d / "OpenCode.exe") is not False: return False, "This OpenCode version protects its files, so openhop leaves it alone." asar = d / "resources" / "app.asar" tmp = asar.with_name("app.asar.openhop-new") try: changes: dict[tuple[str, ...], bytes] = {} with asar.open("rb") as fh: header, start = _read_header(fh) html = _read_entry(fh, start, _entry(header, INDEX_PATH)).decode("utf-8") chunk = _find_banner_chunk(fh, header, start) pristine = MARKER not in html and not (chunk and BANNER_MARK in chunk[1]) if wordmark is not None and wordmark != (MARKER in html): if wordmark: if "" not in html or not _renderer_text_hint(d): return False, "This OpenCode version looks different; nothing was changed." new_html = html.replace("", style_block() + "\n ", 1) else: new_html = re.sub(r'\n ', "", html, flags=re.S) changes[INDEX_PATH] = new_html.encode("utf-8") if banner is not None and chunk and banner != (BANNER_MARK in chunk[1]): new_js = _banner_js(chunk[1], banner) if new_js is None: return False, "This OpenCode version looks different; the limit card was left alone." changes[chunk[0]] = new_js.encode("utf-8") if not changes: return True, "Nothing to change." # 1. backup of the untouched original (refreshed after every OpenCode update) size = asar.stat().st_size if pristine and not _looks_rewritten(asar): BACKUP_DIR.mkdir(parents=True, exist_ok=True) shutil.copy2(asar, BACKUP_ASAR) if BACKUP_ASAR.stat().st_size != size: raise OSError("backup copy is incomplete") BACKUP_META.write_text(json.dumps({"size": size, "mtime": asar.stat().st_mtime, "from": str(asar), "at": time.strftime("%Y-%m-%d %H:%M:%S")}), encoding="utf-8") # 2. new archive: same data, changed files appended at the end and re-pointed in the header offset = size - start for path, data in changes.items(): _entry(header, path).update({"offset": str(offset), "size": len(data), "integrity": _integrity(data)}) offset += len(data) with asar.open("rb") as src, tmp.open("wb") as dst: dst.write(_header_bytes(header)) src.seek(start) shutil.copyfileobj(src, dst, 8 * 1024 * 1024) for data in changes.values(): dst.write(data) # 3. validate before swapping: header parses, our files read back, another file reads the same with tmp.open("rb") as fh, asar.open("rb") as orig: h2, s2 = _read_header(fh) for path, data in changes.items(): if _read_entry(fh, s2, _entry(h2, path)) != data: raise ValueError(f"{'/'.join(path)} didn't read back") h1, s1 = _read_header(orig) probe = ("package.json",) if _read_entry(fh, s2, _entry(h2, probe)) != _read_entry(orig, s1, _entry(h1, probe)): raise ValueError("other files moved") if tmp.stat().st_size != s2 + offset: raise ValueError("unexpected size") if desktop_running(): # it was opened meanwhile tmp.unlink(missing_ok=True) return False, "OpenCode Desktop was opened; trying again later." os.replace(tmp, asar) _log(f"updated {asar}: wordmark={wordmark} banner={banner}") return True, "Done: OpenCode Desktop picks this up the next time it opens." except Exception as exc: tmp.unlink(missing_ok=True) _log(f"update failed, left OpenCode as it was: {exc}") return False, "Couldn't change OpenCode Desktop; it was left as it was." def apply() -> tuple[bool, str]: """Add the openhop.cfd wordmark (and keep the banner patch in line with its setting).""" ok, msg = _set_state(wordmark=True, banner=banner_setting_enabled()) if ok and msg != "Nothing to change.": msg = "Done: OpenCode Desktop shows openhop.cfd the next time it opens." elif ok: msg = "Already showing openhop.cfd." return ok, msg def restore() -> tuple[bool, str]: """Take the wordmark out (the banner patch stays if its setting is on).""" ok, msg = _set_state(wordmark=False, banner=banner_setting_enabled()) if ok: return True, "OpenCode shows its own wordmark again (from the next time it opens)." return ok, msg def restore_all() -> tuple[bool, str]: """Put OpenCode back exactly as it was (uninstall): the original from the backup if it's good, else unpatch.""" d = desktop_dir() if not d: return True, "OpenCode Desktop isn't installed." asar = d / "resources" / "app.asar" try: info = _inspect(asar) if not info["wordmark"] and not info["banner"]: return True, "OpenCode is already as it was." if desktop_running(): return False, "OpenCode Desktop is open; it will be put back the next time it's closed." if BACKUP_ASAR.is_file(): b = _inspect(BACKUP_ASAR) if not b["wordmark"] and not b["banner"]: tmp = asar.with_name("app.asar.openhop-restore") shutil.copy2(BACKUP_ASAR, tmp) os.replace(tmp, asar) _log(f"restored {asar} from backup") return True, "OpenCode Desktop is back to how it was." except Exception as exc: _log(f"restore from backup failed: {exc}") return _set_state(wordmark=False, banner=False) def sync() -> str: """Bring OpenCode in line with the settings. Cheap when nothing needs doing; safe to call often.""" try: d = desktop_dir() if not d or desktop_running(): return "skip" info = _inspect(d / "resources" / "app.asar") want_w, want_b = setting_enabled(), banner_setting_enabled() w = want_w if want_w != info["wordmark"] and (not want_w or status().get("supported")) else None b = want_b if want_b != info["banner"] and (not want_b or info["banner_ok"]) else None if w is None and b is None: return "ok" ok, msg = _set_state(wordmark=w, banner=b) return f"wordmark={w} banner={b}: {msg}" except Exception as exc: _log(f"sync error: {exc}") return "ok" if __name__ == "__main__": import sys cmd = sys.argv[1] if len(sys.argv) > 1 else "status" if cmd == "apply": print(apply()) elif cmd == "restore": print(restore()) elif cmd == "restore-all": print(restore_all()) elif cmd == "sync": print(sync()) elif cmd == "css": print(style_block()) else: print(status())