payout.py review; sign-in URI and expiry checks; installer undo keeps your own Firefox pref
Browse files- payout.py review shows each claiming wallet's work, with flags to check before paying: strikes, a day near the ceiling, short answers, many uncredited jobs, never cross-checked, or a large first day. The router now records strikes in strikes.jsonl, by wallet only.
- Sign-in: the URI's host must match the domain, and an Expiration Time in the past is refused.
- Installers: undo leaves prefs.js alone when dom.webgpu.enabled was already set before install (the user.js block records this as had-pref). The bash installer also detects running Flatpak browsers with flatpak ps.
- Tests: 54 Python tests (and a flaky tie-break test fixed) plus the PowerShell checks, now including the no-BOM and user's-own-pref cases.
Co-Authored-By: Professor Codephreak <codephreak@pythai.net>
Files changed (8)
57 unmodified lines585960616263641 unmodified line66676869707157 unmodified lines## login333 · drAIML sign-in, earnings and payouts- `GET /auth/nonce?address=0x…` issues a one-time code, valid for 5 minutes.- `POST /auth/verify {message, signature}` checks the Sign-In with Ethereum message (EIP-4361) and itspersonal_sign signature (EIP-191).- Recovery runs offline in `siwe.py`: keccak-256 and secp256k1, standard library only, about 30 ms of CPU.- The message must be for drAIML's domain and chain 1, and the code must be unused.- It returns a 7-day token.1 unmodified line- `GET /sharedcpu/me` (token) shows LUV earned, claimed, paid and available.- `POST /sharedcpu/claim` (token) records a payout claim for everything available.- `payout.py` is the operator's side. It holds no key and sends nothing: the operator pays from their own wallet.- `list` shows open claims.- `batch` writes a CSV (address, amount in wei).- `mark ID 0xTX` records a payment, which donors then see in the panel with its transaction link.57 unmodified lines58596061626364651 unmodified line67686970717273747557 unmodified lines## login333 · drAIML sign-in, earnings and payouts- `GET /auth/nonce?address=0x…` issues a one-time code, valid for 5 minutes.- `POST /auth/verify {message, signature}` checks the Sign-In with Ethereum message (EIP-4361) and itspersonal_sign signature (EIP-191). The domain, the URI's host, chain 1, the issue time (within 10 minutes) and anyexpiry are all checked.- Recovery runs offline in `siwe.py`: keccak-256 and secp256k1, standard library only, about 30 ms of CPU.- The message must be for drAIML's domain and chain 1, and the code must be unused.- It returns a 7-day token.1 unmodified line- `GET /sharedcpu/me` (token) shows LUV earned, claimed, paid and available.- `POST /sharedcpu/claim` (token) records a payout claim for everything available.- `payout.py` is the operator's side. It holds no key and sends nothing: the operator pays from their own wallet.- `review` shows each claiming wallet's work with flags to look at before paying: strikes, a day near the ceiling,short answers, many uncredited jobs, never cross-checked, or a large first day. The router records strikes in`strikes.jsonl`, by wallet only.- `list` shows open claims.- `batch` writes a CSV (address, amount in wei).- `mark ID 0xTX` records a payment, which donors then see in the panel with its transaction link.
188 unmodified lines189190191192193194195196197198143 unmodified lines34234334434534634734843 unmodified lines392393394395396397398102 unmodified lines5015025035045055065072 unmodified lines510511512513514515188 unmodified linesdef _barred(self, w: Worker) -> bool:return self.strikes["ip:" + w.ip] >= STRIKES_BAR or (bool(w.wallet) and self.strikes["w:" + w.wallet.lower()] >= STRIKES_BAR)def _strike(self, wallet: str, ip: str) -> None:self.strikes["ip:" + ip] += 1if wallet:self.strikes["w:" + wallet.lower()] += 1def _credit(self, w: Worker, j: Job, text: str, claimed) -> tuple[int, str]:"""Tokens to credit for an accepted answer, and why fewer than claimed. A receipt proves only that the text143 unmodified linesand str(rc.get("model_sha256", "")).lower() == MODELS[j.model]["sha256"])if not good:w.strikes += 1self._strike(w.wallet, w.ip)self._requeue(j, "receipt did not match")self.stats["receipts_bad"] += 1return {"ok": False, "reason": "the receipt does not match the text or the pinned model"}43 unmodified linesif agreed and len(texts) == 3:for s, t in j.compare.items():if t != majority:self._strike(j.who[s][0], j.who[s][1])if s in self.workers:self.workers[s].strikes += 1self.jobs.pop(j.id, None)102 unmodified linesf = siwe.parse_siwe(msg)except ValueError as e:return {"ok": False, "reason": str(e)}if f["domain"] not in SIWE_DOMAINS or f["chain"] != "1":return {"ok": False, "reason": "this sign-in is for another site or chain"}held = self.nonces.pop(f["nonce"], None)if not held or held[0] != f["address"].lower() or held[1] < now():2 unmodified linesissued = datetime.fromisoformat(f["issued"].replace("Z", "+00:00"))if abs((datetime.now(timezone.utc) - issued).total_seconds()) > 600:return {"ok": False, "reason": "the sign-in message is too old"}signer = siwe.personal_signer(msg, sig)except ValueError as e:return {"ok": False, "reason": f"the signature does not check: {e}"}188 unmodified lines189190191192193194195196197198199200201143 unmodified lines34534634734834935035143 unmodified lines395396397398399400401102 unmodified lines5045055065075085095102 unmodified lines513514515516517518519520188 unmodified linesdef _barred(self, w: Worker) -> bool:return self.strikes["ip:" + w.ip] >= STRIKES_BAR or (bool(w.wallet) and self.strikes["w:" + w.wallet.lower()] >= STRIKES_BAR)def _strike(self, wallet: str, ip: str, why: str = "") -> None:self.strikes["ip:" + ip] += 1if wallet:self.strikes["w:" + wallet.lower()] += 1# for the operator's payout review (payout.py); the wallet only, no IPwith open(os.path.join(os.path.dirname(self.claims_path), "strikes.jsonl"), "a") as f:f.write(json.dumps({"t": int(time.time()), "wallet": wallet.lower(), "why": why}, separators=(",", ":")) + "\n")def _credit(self, w: Worker, j: Job, text: str, claimed) -> tuple[int, str]:"""Tokens to credit for an accepted answer, and why fewer than claimed. A receipt proves only that the text143 unmodified linesand str(rc.get("model_sha256", "")).lower() == MODELS[j.model]["sha256"])if not good:w.strikes += 1self._strike(w.wallet, w.ip, "bad receipt")self._requeue(j, "receipt did not match")self.stats["receipts_bad"] += 1return {"ok": False, "reason": "the receipt does not match the text or the pinned model"}43 unmodified linesif agreed and len(texts) == 3:for s, t in j.compare.items():if t != majority:self._strike(j.who[s][0], j.who[s][1], "lost a cross-check tie-break")if s in self.workers:self.workers[s].strikes += 1self.jobs.pop(j.id, None)102 unmodified linesf = siwe.parse_siwe(msg)except ValueError as e:return {"ok": False, "reason": str(e)}if f["domain"] not in SIWE_DOMAINS or f["chain"] != "1" or urlsplit(f["uri"]).netloc != f["domain"]:return {"ok": False, "reason": "this sign-in is for another site or chain"}held = self.nonces.pop(f["nonce"], None)if not held or held[0] != f["address"].lower() or held[1] < now():2 unmodified linesissued = datetime.fromisoformat(f["issued"].replace("Z", "+00:00"))if abs((datetime.now(timezone.utc) - issued).total_seconds()) > 600:return {"ok": False, "reason": "the sign-in message is too old"}if f.get("expires") and datetime.fromisoformat(f["expires"].replace("Z", "+00:00")) < datetime.now(timezone.utc):return {"ok": False, "reason": "the sign-in message has expired"}signer = siwe.personal_signer(msg, sig)except ValueError as e:return {"ok": False, "reason": f"the signature does not check: {e}"}
6 unmodified lines7891011121 unmodified line14151617181918 unmodified lines383940414243444546474849505152535455566 unmodified linesrecords each payment's transaction hash once the operator has made it. It holds no key and sends nothing: movingLUV is a step the operator takes in their own wallet.payout.py list --state /var/lib/draiml-dmindpayout.py batch --state /var/lib/draiml-dmind --out batch.csv # address,amount_wei (SHAMBA LUV, 18 decimals)payout.py mark --state /var/lib/draiml-dmind CLAIM_ID 0xTXHASH # after paying it1 unmodified linefrom __future__ import annotationsimport argparseimport csvimport jsonimport os18 unmodified linesreturn rowsdef f18(wei: int) -> str:return f"{wei // 10**18}.{wei % 10**18:018d}"def main() -> int:ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])ap.add_argument("cmd", choices=["list", "batch", "mark"])ap.add_argument("args", nargs="*")ap.add_argument("--state", default="/var/lib/draiml-dmind")ap.add_argument("--out", default="batch.csv")a = ap.parse_args()open_ = {k: c for k, c in claims(a.state).items() if c.get("status") == "requested"}if a.cmd == "list":total = 0for c in sorted(open_.values(), key=lambda c: c["t"]):total += int(c["luv_wei"])6 unmodified lines789101112131 unmodified line1516171819202118 unmodified lines4041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191206 unmodified linesrecords each payment's transaction hash once the operator has made it. It holds no key and sends nothing: movingLUV is a step the operator takes in their own wallet.payout.py review --state /var/lib/draiml-dmind # each claiming wallet's work, with flagspayout.py list --state /var/lib/draiml-dmindpayout.py batch --state /var/lib/draiml-dmind --out batch.csv # address,amount_wei (SHAMBA LUV, 18 decimals)payout.py mark --state /var/lib/draiml-dmind CLAIM_ID 0xTXHASH # after paying it1 unmodified linefrom __future__ import annotationsimport argparseimport collectionsimport csvimport jsonimport os18 unmodified linesreturn rowsdef rows(state: str, name: str) -> list[dict]:out, path = [], os.path.join(state, name)if os.path.exists(path):with open(path) as f:for line in f:try:out.append(json.loads(line))except ValueError:continuereturn outDAILY = 150_000 # the router's DAILY_TOKENSdef review(state: str, wallets: set[str]) -> list[tuple[str, dict, list[str]]]:"""What each wallet did, and what looks off. A receipt cannot prove work (the worker computes it), so this is thehuman check: someone asking and answering their own questions from two connections shows up as steady volume,short answers, many uncredited or disagreeing jobs, or strikes."""led, strikes = rows(state, "ledger.jsonl"), rows(state, "strikes.jsonl")out = []for w in sorted(wallets):mine = [e for e in led if str(e.get("wallet", "")).lower() == w]jobs = len(mine)tok = sum(int(e.get("tokens", 0)) for e in mine)days = {int(e.get("t", 0)) // 86400 for e in mine} or {0}per_day = {d: sum(int(e.get("tokens", 0)) for e in mine if int(e.get("t", 0)) // 86400 == d) for d in days}unc = collections.Counter(e.get("uncredited") for e in mine if e.get("uncredited"))checks = [e for e in mine if e.get("check")]st = [x for x in strikes if x.get("wallet") == w]first = min((int(e.get("t", 0)) for e in mine), default=0)s = {"jobs": jobs, "tokens": tok, "days": len(days), "max_day": max(per_day.values()),"avg_tokens": round(tok / jobs, 1) if jobs else 0, "uncredited": dict(unc), "checks": len(checks),"strikes": len(st), "first": time.strftime("%Y-%m-%d", time.gmtime(first)) if first else "-"}flags = []if st:flags.append(f"{len(st)} strike(s): " + ", ".join(sorted({x.get('why', '?') for x in st})))if s["max_day"] >= 0.8 * DAILY:flags.append(f"near the daily ceiling ({s['max_day']:,} tokens in one day)")if jobs >= 20 and s["avg_tokens"] < 20:flags.append(f"short answers (average {s['avg_tokens']} tokens over {jobs} jobs)")if jobs and sum(unc.values()) / jobs > 0.3:flags.append(f"{sum(unc.values())} of {jobs} jobs not or partly credited {dict(unc)}")if jobs >= 50 and not checks:flags.append("never cross-checked")if s["days"] == 1 and tok >= 50_000:flags.append("large first-day volume")out.append((w, s, flags))return outdef f18(wei: int) -> str:return f"{wei // 10**18}.{wei % 10**18:018d}"def main() -> int:ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])ap.add_argument("cmd", choices=["review", "list", "batch", "mark"])ap.add_argument("args", nargs="*")ap.add_argument("--state", default="/var/lib/draiml-dmind")ap.add_argument("--out", default="batch.csv")a = ap.parse_args()open_ = {k: c for k, c in claims(a.state).items() if c.get("status") == "requested"}if a.cmd == "review":wallets = {str(c["wallet"]).lower() for c in open_.values()}if not wallets:print("no open claims")for w, s, flags in review(a.state, wallets):owed = sum(int(c["luv_wei"]) for c in open_.values() if str(c["wallet"]).lower() == w)print(f"{w} claims {f18(owed)} LUV")print(f" {s['jobs']} jobs · {s['tokens']:,} tokens · avg {s['avg_tokens']} · {s['days']} day(s) since {s['first']}"f" · busiest day {s['max_day']:,} · {s['checks']} cross-check(s) · {s['strikes']} strike(s)")print(" " + ("⚠ " + "\n ⚠ ".join(flags) if flags else "no flags"))print("Flags are hints, not verdicts: look before paying, and pay only what you are satisfied with.")elif a.cmd == "list":total = 0for c in sorted(open_.values(), key=lambda c: c["t"]):total += int(c["luv_wei"])
203 unmodified lines20420520620720820921056 unmodified lines267268269203 unmodified linesassert res["credited_tokens"] == 5 and res["uncredited"] == "daily ceiling"def test_cross_check_tie_break_strikes_the_odd_one_out(tmp_path):r = _router(tmp_path)honest, liar, judge = (_worker(r, ip, wal) for ip, wal in(("10.0.0.1", "0xa1"), ("10.0.0.2", "0xb2"), ("10.0.0.3", "0xc3")))56 unmodified linesr = _router(tmp_path)got = [r.join({"model_sha256": R.BONSAI_SHA256}, "10.0.0.9")["ok"] for _ in range(R.WORKERS_PER_IP + 3)]assert got.count(True) == R.WORKERS_PER_IP203 unmodified lines20420520620720820921021156 unmodified lines268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301203 unmodified linesassert res["credited_tokens"] == 5 and res["uncredited"] == "daily ceiling"def test_cross_check_tie_break_strikes_the_odd_one_out(tmp_path, monkeypatch):monkeypatch.setattr(R, "CROSS_CHECK", 0.0) # only the copy this test queues, no random extra checksr = _router(tmp_path)honest, liar, judge = (_worker(r, ip, wal) for ip, wal in(("10.0.0.1", "0xa1"), ("10.0.0.2", "0xb2"), ("10.0.0.3", "0xc3")))56 unmodified linesr = _router(tmp_path)got = [r.join({"model_sha256": R.BONSAI_SHA256}, "10.0.0.9")["ok"] for _ in range(R.WORKERS_PER_IP + 3)]assert got.count(True) == R.WORKERS_PER_IPdef test_payout_review_flags(tmp_path):import payout as Pt = int(R.time.time())led = [{"t": t, "wallet": "0xbad", "job": f"j{i}", "tokens": 3, "uncredited": "self-served" if i % 2 else None} for i in range(30)]led += [{"t": t - 86400 * d, "wallet": "0xgood", "job": f"g{d}", "tokens": 200, "check": d == 3} for d in range(5)](tmp_path / "ledger.jsonl").write_text("\n".join(json.dumps({k: v for k, v in e.items() if v is not None}) for e in led) + "\n")(tmp_path / "strikes.jsonl").write_text(json.dumps({"t": t, "wallet": "0xbad", "why": "lost a cross-check tie-break"}) + "\n")out = {w: (s, flags) for w, s, flags in P.review(str(tmp_path), {"0xbad", "0xgood"})}bad = " ".join(out["0xbad"][1])assert "strike" in bad and "short answers" in bad and "not or partly credited" in badassert out["0xgood"][1] == [] and out["0xgood"][0]["days"] == 5 and out["0xgood"][0]["checks"] == 1@pytest.mark.skipif(not Path(CAST).exists(), reason="needs Foundry's cast to sign")def test_signin_uri_and_expiry(tmp_path):r = R.Router(str(tmp_path / "ledger.jsonl"))addr = "0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266"now_ = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")def msg(uri, extra=""):n = r.nonce(addr)["nonce"]return (f"pythai-draiml.static.hf.space wants you to sign in with your Ethereum account:\n{addr}\n\nSign in.\n\n"f"URI: {uri}\nVersion: 1\nChain ID: 1\nNonce: {n}\nIssued At: {now_}{extra}")m = msg("https://evil.example")assert r.verify({"message": m, "signature": cast_sign(m)})["ok"] is Falsem = msg("https://pythai-draiml.static.hf.space", "\nExpiration Time: 2020-01-01T00:00:00Z")assert "expired" in r.verify({"message": m, "signature": cast_sign(m)})["reason"]m = msg("https://pythai-draiml.static.hf.space")assert r.verify({"message": m, "signature": cast_sign(m)})["ok"] is True
40 unmodified lines41424344454647484940 unmodified linesdef test_firefox_profile(tmp_path):os.symlink("127.0.1.1:+999999999", tmp_path / "lock") # Firefox's lock format; a pid that is not running(tmp_path / "prefs.js").write_text('user_pref("dom.webgpu.enabled", true);\nuser_pref("other", 1);\n')run("--dir", str(tmp_path))assert 'user_pref("dom.webgpu.enabled", true);' in (tmp_path / "user.js").read_text()run("--dir", str(tmp_path), "--undo")assert "dom.webgpu" not in (tmp_path / "user.js").read_text() and "dom.webgpu" not in (tmp_path / "prefs.js").read_text()assert 'user_pref("other", 1);' in (tmp_path / "prefs.js").read_text()40 unmodified lines4142434445464748495051525354555657585940 unmodified linesdef test_firefox_profile(tmp_path):os.symlink("127.0.1.1:+999999999", tmp_path / "lock") # Firefox's lock format; a pid that is not running(tmp_path / "prefs.js").write_text('user_pref("other", 1);\n')run("--dir", str(tmp_path))assert 'user_pref("dom.webgpu.enabled", true);' in (tmp_path / "user.js").read_text()with open(tmp_path / "prefs.js", "a") as f: # Firefox copies the value into prefs.js on exitf.write('user_pref("dom.webgpu.enabled", true);\n')run("--dir", str(tmp_path), "--undo")assert "dom.webgpu" not in (tmp_path / "user.js").read_text() and "dom.webgpu" not in (tmp_path / "prefs.js").read_text()assert 'user_pref("other", 1);' in (tmp_path / "prefs.js").read_text()def test_firefox_undo_keeps_a_pref_that_was_yours(tmp_path):(tmp_path / "prefs.js").write_text('user_pref("dom.webgpu.enabled", true);\n')run("--dir", str(tmp_path))run("--dir", str(tmp_path), "--undo")assert "dom.webgpu" not in (tmp_path / "user.js").read_text()assert 'user_pref("dom.webgpu.enabled", true);' in (tmp_path / "prefs.js").read_text()
28 unmodified lines2930313233343536373839404128 unmodified linesWrite-Host "2. Firefox profile (-Dir)"$f = "/work/ff"; New-Item -ItemType Directory -Force $f | Out-NullSet-Content "$f/prefs.js" @('user_pref("dom.webgpu.enabled", true);', 'user_pref("other", 1);')$r = Run @("-Dir", $f); Check ((Get-Content "$f/user.js" -Raw) -match 'user_pref\("dom.webgpu.enabled", true\);') "user.js gets the pref"$r = Run @("-Dir", $f); Check ($r.out -match "unchanged") "second run is unchanged"$r = Run @("-Dir", $f, "-Undo")Check (-not ((Get-Content "$f/user.js" -Raw) -match "webgpu")) "undo clears user.js"Check (-not ((Get-Content "$f/prefs.js" -Raw) -match "webgpu") -and ((Get-Content "$f/prefs.js" -Raw) -match '"other"')) "undo clears only the pref from prefs.js"Write-Host "3. Default search (Windows-style LOCALAPPDATA / APPDATA)"$env:LOCALAPPDATA = "/work/L"; $env:APPDATA = "/work/R"foreach ($d in @("/work/L/Google/Chrome/User Data", "/work/L/BraveSoftware/Brave-Browser/User Data", "/work/R/Opera Software/Opera Stable")) {28 unmodified lines293031323334353637383940414243444546474828 unmodified linesWrite-Host "2. Firefox profile (-Dir)"$f = "/work/ff"; New-Item -ItemType Directory -Force $f | Out-NullSet-Content "$f/prefs.js" @('user_pref("other", 1);')$r = Run @("-Dir", $f); Check ((Get-Content "$f/user.js" -Raw) -match 'user_pref\("dom.webgpu.enabled", true\);') "user.js gets the pref"$r = Run @("-Dir", $f); Check ($r.out -match "unchanged") "second run is unchanged"Check ([IO.File]::ReadAllBytes("$f/user.js")[0] -ne 0xEF) "user.js has no BOM"Add-Content "$f/prefs.js" 'user_pref("dom.webgpu.enabled", true);' # Firefox copies the value on exit$r = Run @("-Dir", $f, "-Undo")Check (-not ((Get-Content "$f/user.js" -Raw) -match "webgpu")) "undo clears user.js"Check (-not ((Get-Content "$f/prefs.js" -Raw) -match "webgpu") -and ((Get-Content "$f/prefs.js" -Raw) -match '"other"')) "undo clears only the pref from prefs.js"$g = "/work/ff2"; New-Item -ItemType Directory -Force $g | Out-NullSet-Content "$g/prefs.js" @('user_pref("dom.webgpu.enabled", true);')$r = Run @("-Dir", $g); $r = Run @("-Dir", $g, "-Undo")Check ((Get-Content "$g/prefs.js" -Raw) -match "dom.webgpu.enabled") "undo keeps a pref that was the user's own"Write-Host "3. Default search (Windows-style LOCALAPPDATA / APPDATA)"$env:LOCALAPPDATA = "/work/L"; $env:APPDATA = "/work/R"foreach ($d in @("/work/L/Google/Chrome/User Data", "/work/L/BraveSoftware/Brave-Browser/User Data", "/work/R/Opera Software/Opera Stable")) {
98 unmodified lines9910010110210310410510610710810911011198 unmodified linesif ($Undo) {if (-not $has) { Write-Host "* $prof - unchanged"; return }Write-Host "* $prof - $(if ($DryRun) { 'would ' })remove dom.webgpu.enabled"; if ($DryRun) { return }$keep = $true; $out = foreach ($ln in Get-Content $uj) { if ($ln -eq $A) { $keep = $false } elseif ($ln -eq $B) { $keep = $true } elseif ($keep) { $ln } }[IO.File]::WriteAllLines($uj, [string[]]@($out), $utf8)$p = Join-Path $prof "prefs.js"; [IO.File]::WriteAllLines($p, [string[]]@(Get-Content $p | Where-Object { $_ -notmatch '"dom\.webgpu\.enabled"' }), $utf8)} else {if ($has) { Write-Host "* $prof - unchanged"; return }Write-Host "* $prof - $(if ($DryRun) { 'would ' })add dom.webgpu.enabled = true"; if ($DryRun) { return }[IO.File]::AppendAllText($uj, "$A`nuser_pref(`"dom.webgpu.enabled`", true);`n$B`n", $utf8)}$script:changed++}98 unmodified lines9910010110210310410510610710810911011111211311498 unmodified linesif ($Undo) {if (-not $has) { Write-Host "* $prof - unchanged"; return }Write-Host "* $prof - $(if ($DryRun) { 'would ' })remove dom.webgpu.enabled"; if ($DryRun) { return }$had = (Get-Content $uj) -contains "// had-pref: yes"$keep = $true; $out = foreach ($ln in Get-Content $uj) { if ($ln -eq $A) { $keep = $false } elseif ($ln -eq $B) { $keep = $true } elseif ($keep) { $ln } }[IO.File]::WriteAllLines($uj, [string[]]@($out), $utf8)$p = Join-Path $prof "prefs.js"if (-not $had) { [IO.File]::WriteAllLines($p, [string[]]@(Get-Content $p | Where-Object { $_ -notmatch '"dom\.webgpu\.enabled"' }), $utf8) }} else {if ($has) { Write-Host "* $prof - unchanged"; return }Write-Host "* $prof - $(if ($DryRun) { 'would ' })add dom.webgpu.enabled = true"; if ($DryRun) { return }$had = if ((Get-Content (Join-Path $prof "prefs.js") -Raw) -match '"dom\.webgpu\.enabled"') { "yes" } else { "no" }[IO.File]::AppendAllText($uj, "$A`n// had-pref: $had`nuser_pref(`"dom.webgpu.enabled`", true);`n$B`n", $utf8)}$script:changed++}
56 unmodified lines575859606162636465666732 unmodified lines10010110210310410510610710810911011111211311411511611711811956 unmodified lineskill -0 "$pid" 2>/dev/null}changed=0 skipped=0chromium() {local dir="$1" state="$1/Local State"[ -f "$state" ] || return 0if running "$dir/SingletonLock"; then echo "• $dir — browser is running: close it and run this again"; skipped=$((skipped+1)); return 0; filocal outout=$(python3 - "$state" "$UNDO" "$DRY" "${FLAGS[@]}" <<'PY'import json, os, shutil, sys, time32 unmodified lineslocal prof="$1" uj="$1/user.js"[ -f "$prof/prefs.js" ] || return 0# Linux: the "lock" symlink names the PID. macOS uses .parentlock (no PID), so there any running Firefox countsif running "$prof/lock" || { [ "$OS" = Darwin ] && pgrep -xq firefox; }; thenecho "• $prof — Firefox is running: close it and run this again"; skipped=$((skipped+1)); return 0fiif [ "$UNDO" = 1 ]; thengrep -qF "$MARK_A" "$uj" 2>/dev/null || { echo "• $prof — unchanged"; return 0; }echo "• $prof — $([ "$DRY" = 1 ] && echo "would remove" || echo "remove") dom.webgpu.enabled"[ "$DRY" = 1 ] && return 0sed -i.bak-webgpu "/$(printf '%s' "$MARK_A" | sed 's/[\/&]/\\&/g')/,/$(printf '%s' "$MARK_B" | sed 's/[\/&]/\\&/g')/d" "$uj"sed -i.bak-webgpu '/"dom\.webgpu\.enabled"/d' "$prof/prefs.js" # Firefox copied it there; back to the defaultelsegrep -qF "$MARK_A" "$uj" 2>/dev/null && { echo "• $prof — unchanged"; return 0; }echo "• $prof — $([ "$DRY" = 1 ] && echo "would add" || echo "add") dom.webgpu.enabled = true"[ "$DRY" = 1 ] && return 0printf '%s\nuser_pref("dom.webgpu.enabled", true);\n%s\n' "$MARK_A" "$MARK_B" >> "$uj"fichanged=$((changed+1))}56 unmodified lines57585960616263646566676869707172737432 unmodified lines10710810911011111211311411511611711811912012112212312412512612712812913013156 unmodified lineskill -0 "$pid" 2>/dev/null}# a Flatpak browser's lock names a PID inside its sandbox, so ask flatpak which apps are runningflatpak_running() {local appcase "$1" in "$HOME/.var/app/"*) app=${1#"$HOME/.var/app/"}; app=${app%%/*} ;; *) return 1 ;; esaccommand -v flatpak >/dev/null && flatpak ps --columns=application 2>/dev/null | grep -qx "$app"}changed=0 skipped=0chromium() {local dir="$1" state="$1/Local State"[ -f "$state" ] || return 0if running "$dir/SingletonLock" || flatpak_running "$dir"; then echo "• $dir — browser is running: close it and run this again"; skipped=$((skipped+1)); return 0; filocal outout=$(python3 - "$state" "$UNDO" "$DRY" "${FLAGS[@]}" <<'PY'import json, os, shutil, sys, time32 unmodified lineslocal prof="$1" uj="$1/user.js"[ -f "$prof/prefs.js" ] || return 0# Linux: the "lock" symlink names the PID. macOS uses .parentlock (no PID), so there any running Firefox countsif running "$prof/lock" || flatpak_running "$prof" || { [ "$OS" = Darwin ] && pgrep -xq firefox; }; thenecho "• $prof — Firefox is running: close it and run this again"; skipped=$((skipped+1)); return 0fiif [ "$UNDO" = 1 ]; thengrep -qF "$MARK_A" "$uj" 2>/dev/null || { echo "• $prof — unchanged"; return 0; }echo "• $prof — $([ "$DRY" = 1 ] && echo "would remove" || echo "remove") dom.webgpu.enabled"[ "$DRY" = 1 ] && return 0local had=nogrep -q "^// had-pref: yes" "$uj" && had=yessed -i.bak-webgpu "/$(printf '%s' "$MARK_A" | sed 's/[\/&]/\\&/g')/,/$(printf '%s' "$MARK_B" | sed 's/[\/&]/\\&/g')/d" "$uj"# Firefox copied our value into prefs.js; drop it there too, unless the setting was already yours before[ "$had" = no ] && sed -i.bak-webgpu '/"dom\.webgpu\.enabled"/d' "$prof/prefs.js"elsegrep -qF "$MARK_A" "$uj" 2>/dev/null && { echo "• $prof — unchanged"; return 0; }echo "• $prof — $([ "$DRY" = 1 ] && echo "would add" || echo "add") dom.webgpu.enabled = true"[ "$DRY" = 1 ] && return 0local had=nogrep -q '"dom\.webgpu\.enabled"' "$prof/prefs.js" && had=yesprintf '%s\n// had-pref: %s\nuser_pref("dom.webgpu.enabled", true);\n%s\n' "$MARK_A" "$had" "$MARK_B" >> "$uj"fichanged=$((changed+1))}