hop
Hop: a small native macOS launcher. Clipboard history, find, on-device dictation and your coding agent behind one key.
Brought by drakestapleton
hop / Linux / tests / apps_check.py
| 1 | #!/usr/bin/env python3 |
| 2 | """Independent Linux desktop-entry fixtures. Python is a verifier only.""" |
| 3 | from __future__ import annotations |
| 4 | |
| 5 | import argparse |
| 6 | import json |
| 7 | import os |
| 8 | from pathlib import Path |
| 9 | import shutil |
| 10 | import subprocess |
| 11 | import tempfile |
| 12 | |
| 13 | ROOT = Path(__file__).resolve().parents[2] |
| 14 | HEADER = """om2 |
| 15 | global lx_query uchar * |
| 16 | global lx_rows uchar * |
| 17 | global lx_qn ulong 1 |
| 18 | global lx_rn ulong 1 |
| 19 | global lx_pick ulong 1 |
| 20 | """ |
| 21 | MAIN = """ |
| 22 | fn main to int |
| 23 | if ne hp_start 0 |
| 24 | ret 10 |
| 25 | end |
| 26 | x = ha_init |
| 27 | if gt argcnt 1 |
| 28 | n = argread 1 ha_env 0 len ha_env |
| 29 | if lt n 0 |
| 30 | ret 8 |
| 31 | end |
| 32 | r = enlarge lx_query ulong n |
| 33 | if lt r 0 |
| 34 | ret 9 |
| 35 | end |
| 36 | for i ulong ulong n bound 9223372036854775807 |
| 37 | c = get ha_env i |
| 38 | put lx_query i c |
| 39 | end |
| 40 | put lx_qn 0 ulong n |
| 41 | end |
| 42 | ha_query |
| 43 | if gt argcnt 2 |
| 44 | x = ha_activate |
| 45 | if eq x 0 |
| 46 | hp_stop |
| 47 | ret 7 |
| 48 | end |
| 49 | else |
| 50 | y = write 1 lx_rows 0 get lx_rn 0 |
| 51 | end |
| 52 | hp_stop |
| 53 | ret 0 |
| 54 | end |
| 55 | """ |
| 56 | |
| 57 | |
| 58 | def compile_one(omc: Path, source: str, path: Path) -> None: |
| 59 | result = subprocess.run([str(omc)], input=source.encode(), capture_output=True, check=False) |
| 60 | if result.returncode: |
| 61 | raise AssertionError(f"compile failed {result.returncode}: {result.stderr.decode()}") |
| 62 | path.write_bytes(result.stdout) |
| 63 | path.chmod(0o755) |
| 64 | |
| 65 | |
| 66 | def entry(path: Path, name: str, extra: str = "", command: str = "/usr/bin/true") -> None: |
| 67 | path.parent.mkdir(parents=True, exist_ok=True) |
| 68 | path.write_text(f"[Desktop Entry]\nType=Application\nName={name}\nExec={command}\n{extra}") |
| 69 | |
| 70 | |
| 71 | def main() -> None: |
| 72 | parser = argparse.ArgumentParser() |
| 73 | parser.add_argument("omc", type=Path) |
| 74 | parser.add_argument("--core", type=Path, default=ROOT / "build/linux/hopcore") |
| 75 | args = parser.parse_args() |
| 76 | source = (ROOT / "Linux/apps.om").read_text() |
| 77 | core_source = (ROOT / "Linux/core.om").read_text() |
| 78 | passed = 0 |
| 79 | |
| 80 | def check(condition: bool, name: str) -> None: |
| 81 | nonlocal passed |
| 82 | if not condition: |
| 83 | raise AssertionError(name) |
| 84 | passed += 1 |
| 85 | print(f"PASS {name}") |
| 86 | |
| 87 | with tempfile.TemporaryDirectory(prefix="hop-apps-") as folder: |
| 88 | tmp = Path(folder) |
| 89 | exe = tmp / "apps" |
| 90 | if not args.core.is_file(): |
| 91 | raise AssertionError("Build the unchanged Linux matching helper first with sh build.sh") |
| 92 | shutil.copy2(args.core, tmp / "hopcore") |
| 93 | compile_one(args.omc.resolve(), HEADER + source + core_source + MAIN, exe) |
| 94 | home, user, system, second = (tmp / name for name in ("home", "user data", "system", "second")) |
| 95 | for root in (user, system, second): |
| 96 | (root / "applications").mkdir(parents=True) |
| 97 | env = dict(PATH=os.defpath, HOME=str(home), XDG_DATA_HOME=str(user), |
| 98 | XDG_DATA_DIRS=f"{system}:relative:{second}", XDG_CURRENT_DESKTOP="test:GNOME") |
| 99 | env["DESKTOP_SESSION_TEST"] = "kept exactly = $() ; π" + "x" * 10000 |
| 100 | env["HOP_API_KEY"] = "fixture-private-hop-key-never-forward" |
| 101 | env["HOP_MODEL_URL"] = "http://fixture-model.invalid/v1" |
| 102 | |
| 103 | def listing(query: str = "", program: Path = exe, run_env: dict[str, str] = env) -> list[str]: |
| 104 | result = subprocess.run([str(program), query], env=run_env, capture_output=True, timeout=15) |
| 105 | check(result.returncode == 0, |
| 106 | f"listing completed {query!r} (exit={result.returncode}, stderr={result.stderr.decode(errors='replace')!r})") |
| 107 | return result.stdout.decode().splitlines() |
| 108 | |
| 109 | entry(system / "applications/system.desktop", "System App") |
| 110 | entry(second / "applications/second.desktop", "Second App") |
| 111 | entry(user / "applications/plain.desktop", "Alpha App", "[Desktop Action Other]\nName=Wrong Action\n") |
| 112 | entry(system / "applications/override.desktop", "Stale System Name") |
| 113 | entry(user / "applications/override.desktop", "User Override") |
| 114 | entry(system / "applications/deleted.desktop", "Must Stay Hidden") |
| 115 | (user / "applications/deleted.desktop").write_text("[Desktop Entry]\nHidden=true\n") |
| 116 | entry(system / "applications/foo-bar.desktop", "Stale Nested Name") |
| 117 | entry(user / "applications/foo/bar.desktop", "Nested Override") |
| 118 | entry(user / "applications/private.desktop", "Private App", "NoDisplay=true\n") |
| 119 | entry(user / "applications/link.desktop", "Link App", "Type=Link\n") |
| 120 | entry(user / "applications/only.desktop", "GNOME Only", "OnlyShowIn=KDE;GNOME;\n") |
| 121 | entry(user / "applications/not.desktop", "Not GNOME", "NotShowIn=GNOME;\n") |
| 122 | entry(user / "applications/missing.desktop", "Missing Executable", "TryExec=/hop-does-not-exist\n") |
| 123 | entry(user / "applications/directory.desktop", "Directory Executable", "TryExec=/tmp\n") |
| 124 | entry(user / "applications/try.desktop", "Try Found", "TryExec=true\n") |
| 125 | entry(user / "applications/escaped.desktop", "Escaped\\sName") |
| 126 | entry(user / "applications/long.desktop", "Long Line", "Comment=" + "x" * 15000 + "\n") |
| 127 | entry(user / "applications/unicode.desktop", "Café π") |
| 128 | os.mkfifo(user / "applications/pipe.desktop") |
| 129 | names = set(listing()) |
| 130 | check(names == {"Alpha App", "User Override", "Nested Override", "System App", "Second App", |
| 131 | "GNOME Only", "Try Found", "Escaped Name", "Long Line", "Café π"}, |
| 132 | "XDG precedence, hidden tombstones, recursive ids, visibility, group and escaped-name rules") |
| 133 | check(listing("aLPHa") == ["Alpha App"], "ASCII case-insensitive matching") |
| 134 | check(listing("π") == ["Café π"], "UTF-8 bytes survive names and matching") |
| 135 | check(listing("unmatched query") == [], "no app selected for unmatched query") |
| 136 | entry(user / "applications/vscode.desktop", "Visual Studio Code") |
| 137 | entry(user / "applications/firefox.desktop", "Firefox") |
| 138 | entry(user / "applications/bonfire.desktop", "Bonfire") |
| 139 | check(listing("vsc") == ["Visual Studio Code"], "shared Hop helper matches app initials") |
| 140 | check(listing("firefx") == ["Firefox"], "shared Hop helper matches a missing-letter typo") |
| 141 | check(listing("fire") == ["Firefox", "Bonfire"], "higher shared-core score is shown first") |
| 142 | long_name = "q" * 200 |
| 143 | entry(user / "applications/long-name.desktop", long_name) |
| 144 | check(listing("q" * 100) == [long_name], "long names and queries are matched in full without truncation") |
| 145 | check(listing("q" * 201) == [], "long query is never truncated to create a match") |
| 146 | for i in range(400): |
| 147 | entry(user / f"applications/bulk-{i}.desktop", f"Bulk {i}") |
| 148 | check(len(listing("Bulk ")) == 400, "tables grow beyond hundreds of applications") |
| 149 | |
| 150 | default = home / ".local/share/applications" |
| 151 | entry(default / "fallback.desktop", "Home Fallback") |
| 152 | relative_env = dict(env, XDG_DATA_HOME="relative") |
| 153 | check("Home Fallback" in listing(run_env=relative_env), "relative XDG_DATA_HOME falls back to HOME") |
| 154 | |
| 155 | marker = tmp / "launch-result.json" |
| 156 | helper = tmp / "launch helper.py" |
| 157 | helper.write_text("#!/usr/bin/python3\nimport os,sys,json\n" |
| 158 | "result={'args':sys.argv[1:],'env':dict(os.environ)," |
| 159 | "'cmdline':open('/proc/self/cmdline','rb').read().decode()}\n" |
| 160 | f"open({str(marker)!r},'w').write(json.dumps(result))\n") |
| 161 | helper.chmod(0o755) |
| 162 | dangerous = "$(touch SHOULD_NOT_EXIST); literal.desktop" |
| 163 | entry(user / "applications" / dangerous, "Launch Probe", |
| 164 | command=f'"{helper}" "one spaced argument" "π" %f') |
| 165 | result = subprocess.run([str(exe), "Launch Probe", "launch"], env=env, capture_output=True, timeout=15) |
| 166 | check(result.returncode == 0, "gio launch completed") |
| 167 | for _ in range(100): |
| 168 | if marker.exists(): |
| 169 | break |
| 170 | import time |
| 171 | time.sleep(.01) |
| 172 | check(marker.exists(), "real desktop activation executed fixture") |
| 173 | launched = json.loads(marker.read_text()) |
| 174 | check(launched['args'] == ["one spaced argument", "π"] and |
| 175 | launched['env']['DESKTOP_SESSION_TEST'] == env['DESKTOP_SESSION_TEST'], |
| 176 | "Exec quoting and field codes, UTF-8 and unrelated desktop environment retained") |
| 177 | check(not any(k.startswith('HOP_') for k in launched['env']) and |
| 178 | env['HOP_API_KEY'] not in launched['cmdline'] and |
| 179 | env['HOP_API_KEY'] not in marker.read_text(), |
| 180 | "private Hop settings reach neither launched app environment nor command line") |
| 181 | check(not (ROOT / "SHOULD_NOT_EXIST").exists(), "desktop pathname receives no shell evaluation") |
| 182 | |
| 183 | entry(user / "applications/broken.desktop", "Broken Launch", command="/hop-no-such-executable") |
| 184 | result = subprocess.run([str(exe), "Broken Launch", "launch"], env=env, capture_output=True, timeout=15) |
| 185 | check(result.returncode == 7 and b"could not launch" in result.stderr, |
| 186 | "failed desktop activation stays a failure") |
| 187 | |
| 188 | mutant = tmp / "mutant" |
| 189 | changed = source.replace("if or ha_lineeq 0 k ha_hidden ha_lineeq 0 k ha_nodisp", "if false") |
| 190 | check(changed != source, "visibility negative control applied") |
| 191 | compile_one(args.omc.resolve(), HEADER + changed + core_source + MAIN, mutant) |
| 192 | check("Private App" in listing(program=mutant), "negative control exposes forbidden entry") |
| 193 | ignored = core_source.replace("ret hp_le hp_rep 9 2", "ret 0") |
| 194 | check(ignored != core_source, "search-helper-output negative control applied") |
| 195 | compile_one(args.omc.resolve(), HEADER + source + ignored + MAIN, mutant) |
| 196 | check(listing("vsc", program=mutant) == [], "discarded shared-helper answer loses initials match") |
| 197 | print(f"HOP-LINUX-APPS PASS checks={passed}") |
| 198 | |
| 199 | |
| 200 | if __name__ == "__main__": |
| 201 | main() |