Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,24 @@ node --test scripts/guard/check.test.mjs

The gates still run everything before a pull request. Use these commands only to check your work as you go.

## Screenshots for a UI change

AGENTS.md asks every UI pull request for screenshots in both themes and both languages. The preview harness in `apps/mobile/preview` takes them for you: it renders the real screens in a browser with made-up data. It's dev-only, outside the pnpm workspace, and nothing in the app imports it. Run `pnpm install` at the root first, as in Set up: the bundle reads the app's `tsconfig.json`, which extends Expo's.

```sh
cd apps/mobile/preview
pnpm install --ignore-workspace # once: the harness has its own lockfile
pnpm build # bundles the screens into dist/
pnpm shoot about # the shots whose file name contains "about"; no filter shoots them all
```

- The filter matches file names in `shots.mjs`, such as `about` or `settings-x2`.
- The pictures land in `apps/mobile/preview/out/screens`, which git ignores, with `out/index.html` to look through them.
- To add a shot, add a line to `shots.mjs`: `core(...)` shoots light and dark in es-419 and English, `other(...)` light and dark in es-419 only.
- `pnpm compress` shrinks the pictures before you attach them. It's optional and needs Python with Pillow.

The harness drives a headless Chromium and never downloads one. It uses `HERMIT_PREVIEW_CHROMIUM` when that holds the path to a Chromium or `chrome-headless-shell` executable. Otherwise it takes the newest `chromium_headless_shell-*` in Playwright's cache: `PLAYWRIGHT_BROWSERS_PATH` when it's set, else `~/Library/Caches/ms-playwright` on macOS, `~/.cache/ms-playwright` on Linux (or under `$XDG_CACHE_HOME`) and `%LOCALAPPDATA%\ms-playwright` on Windows. If you have none, `pnpm exec playwright-core install chromium-headless-shell` in `apps/mobile/preview` puts one there. When it finds nothing, it stops with a message that names the variable.

## Make a change

1. Find the issue, or open one. A feature needs the `accepted` label first. A change to a non-negotiable needs an accepted RFC.
Expand Down
82 changes: 82 additions & 0 deletions apps/mobile/preview/browser.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
// Dev-only: finds the headless Chromium the preview scripts drive (shoot.mjs, clips.mjs, words.mjs). It only looks,
// never downloads: HERMIT_PREVIEW_CHROMIUM first, then Playwright's own cache for this system. mascot/proof.mjs films
// with a full Chrome and keeps its own lookup.
import { existsSync, readdirSync } from "node:fs";
import { createRequire } from "node:module";
import { homedir } from "node:os";
import { dirname, isAbsolute, join, resolve } from "node:path";

export const BROWSER_VAR = "HERMIT_PREVIEW_CHROMIUM";

/** The executable inside a chromium_headless_shell-<revision> folder, by system (as playwright-core names them). */
const SHELL = {
"darwin-arm64": ["chrome-headless-shell-mac-arm64", "chrome-headless-shell"],
"darwin-x64": ["chrome-headless-shell-mac-x64", "chrome-headless-shell"],
"linux-x64": ["chrome-headless-shell-linux64", "chrome-headless-shell"],
"linux-arm64": ["chrome-linux", "headless_shell"],
"win32-x64": ["chrome-headless-shell-win64", "chrome-headless-shell.exe"],
};
// playwright-core installs the x64 build on every Windows, ARM included.
const shellFor = (platform, arch) => SHELL[platform === "win32" ? "win32-x64" : `${platform}-${arch}`];

/** Where PLAYWRIGHT_BROWSERS_PATH=0 installs: .local-browsers inside the harness's own playwright-core. */
const playwrightLocalBrowsers = () =>
join(dirname(createRequire(import.meta.url).resolve("playwright-core/package.json")), ".local-browsers");

/** Playwright's browser cache, by the same rules playwright-core uses (PLAYWRIGHT_BROWSERS_PATH, then per system). */
export function playwrightCache({
env = process.env,
platform = process.platform,
home = homedir(),
cwd = process.cwd(),
localBrowsers = playwrightLocalBrowsers,
} = {}) {
const set = env.PLAYWRIGHT_BROWSERS_PATH;
let cache;
if (set === "0") cache = localBrowsers();
else if (set) cache = set;
else if (platform === "darwin") cache = join(home, "Library", "Caches", "ms-playwright");
else if (platform === "win32") cache = join(env.LOCALAPPDATA || join(home, "AppData", "Local"), "ms-playwright");
else cache = join(env.XDG_CACHE_HOME || join(home, ".cache"), "ms-playwright");
// A relative path counts from where pnpm was started (INIT_CWD), as playwright-core reads it.
return isAbsolute(cache) ? cache : resolve(env.INIT_CWD || cwd, cache);
}

/** The path to launch, or an Error that says how to point the harness at a browser. */
export function findChromium({
env = process.env,
platform = process.platform,
arch = process.arch,
home = homedir(),
cwd = process.cwd(),
localBrowsers = playwrightLocalBrowsers,
exists = existsSync,
list = (dir) => (existsSync(dir) ? readdirSync(dir) : []),
} = {}) {
const set = env[BROWSER_VAR];
if (set) return exists(set) ? set : new Error(`${BROWSER_VAR} is set to ${set}, but there is no file there.`);
const cache = playwrightCache({ env, platform, home, cwd, localBrowsers });
const shell = shellFor(platform, arch);
// Newest revision first: chromium_headless_shell-1255 before -999, so compare the numbers, not the text.
const revisions = list(cache)
.filter((d) => /^chromium_headless_shell-\d+$/.test(d))
.sort((a, b) => Number(b.split("-")[1]) - Number(a.split("-")[1]));
for (const dir of shell ? revisions : []) {
const path = join(cache, dir, ...shell);
if (exists(path)) return path;
}
return new Error(
`No headless Chromium found in ${cache}. Set ${BROWSER_VAR} to the path of a Chromium or chrome-headless-shell executable. ` +
"The preview scripts never download a browser (CONTRIBUTING.md, Screenshots for a UI change).",
);
}

/** For the scripts: the path, or stop with the message. */
export function chromiumPath() {
const found = findChromium();
if (found instanceof Error) {
console.error(found.message);
process.exit(1);
}
return found;
}
174 changes: 174 additions & 0 deletions apps/mobile/preview/browser.test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,174 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import { join, resolve } from "node:path";
import { BROWSER_VAR, findChromium, playwrightCache } from "./browser.mjs";

// A made-up disk: the folders in each directory, and the files that exist. Nothing here touches the real machine.
const disk = (dirs, files) => ({
list: (dir) => dirs[dir] ?? [],
exists: (path) => files.includes(path),
});

const home = join("/", "home", "ana");
const macCache = join(home, "Library", "Caches", "ms-playwright");
const linuxCache = join(home, ".cache", "ms-playwright");
// An absolute path on whatever system runs the test, standing in for C:\Users\ana\AppData\Local.
const winLocal = join("/", "Users", "ana", "AppData", "Local");
const winCache = join(winLocal, "ms-playwright");

const macArm = (rev) => join(macCache, `chromium_headless_shell-${rev}`, "chrome-headless-shell-mac-arm64", "chrome-headless-shell");

test("an Apple silicon Mac finds the shell where it always did, with no setting", () => {
const found = findChromium({ env: {}, platform: "darwin", arch: "arm64", home, ...disk({ [macCache]: ["chromium_headless_shell-1208"] }, [macArm(1208)]) });
assert.equal(found, macArm(1208));
});

test("the newest revision wins by number, not as text: 1000 before 999", () => {
const found = findChromium({
env: {},
platform: "darwin",
arch: "arm64",
home,
...disk({ [macCache]: ["chromium_headless_shell-999", "chromium_headless_shell-1000"] }, [macArm(999), macArm(1000)]),
});
assert.equal(found, macArm(1000));
});

test("a revision folder without the executable falls back to the one before it", () => {
const found = findChromium({
env: {},
platform: "darwin",
arch: "arm64",
home,
...disk({ [macCache]: ["chromium_headless_shell-1208", "chromium_headless_shell-1200"] }, [macArm(1200)]),
});
assert.equal(found, macArm(1200));
});

test("folders that aren't the headless shell are ignored", () => {
const found = findChromium({
env: {},
platform: "darwin",
arch: "arm64",
home,
...disk({ [macCache]: ["ffmpeg-1011", "chromium-1208", "chromium_headless_shell-1208"] }, [macArm(1208)]),
});
assert.equal(found, macArm(1208));
});

test("an Intel Mac looks in the mac-x64 folder", () => {
const path = join(macCache, "chromium_headless_shell-1208", "chrome-headless-shell-mac-x64", "chrome-headless-shell");
const found = findChromium({ env: {}, platform: "darwin", arch: "x64", home, ...disk({ [macCache]: ["chromium_headless_shell-1208"] }, [path]) });
assert.equal(found, path);
});

test("Linux x64 looks in ~/.cache/ms-playwright, in the linux64 folder", () => {
const path = join(linuxCache, "chromium_headless_shell-1208", "chrome-headless-shell-linux64", "chrome-headless-shell");
const found = findChromium({ env: {}, platform: "linux", arch: "x64", home, ...disk({ [linuxCache]: ["chromium_headless_shell-1208"] }, [path]) });
assert.equal(found, path);
});

test("Linux arm64 uses Playwright's own build, chrome-linux/headless_shell", () => {
const path = join(linuxCache, "chromium_headless_shell-1208", "chrome-linux", "headless_shell");
const found = findChromium({ env: {}, platform: "linux", arch: "arm64", home, ...disk({ [linuxCache]: ["chromium_headless_shell-1208"] }, [path]) });
assert.equal(found, path);
});

test("Linux honors XDG_CACHE_HOME", () => {
const cache = join("/", "data", "cache");
assert.equal(playwrightCache({ env: { XDG_CACHE_HOME: cache }, platform: "linux", home }), join(cache, "ms-playwright"));
});

test("Windows looks under LOCALAPPDATA, in the win64 folder", () => {
const local = winLocal;
const path = join(winCache, "chromium_headless_shell-1208", "chrome-headless-shell-win64", "chrome-headless-shell.exe");
const found = findChromium({
env: { LOCALAPPDATA: local },
platform: "win32",
arch: "x64",
home,
...disk({ [winCache]: ["chromium_headless_shell-1208"] }, [path]),
});
assert.equal(found, path);
});

test("Windows on ARM uses the same win64 shell, as Playwright installs it there too", () => {
const path = join(winCache, "chromium_headless_shell-1208", "chrome-headless-shell-win64", "chrome-headless-shell.exe");
const found = findChromium({
env: { LOCALAPPDATA: winLocal },
platform: "win32",
arch: "arm64",
home,
...disk({ [winCache]: ["chromium_headless_shell-1208"] }, [path]),
});
assert.equal(found, path);
});

test("PLAYWRIGHT_BROWSERS_PATH replaces the cache folder on every system", () => {
const custom = join("/", "opt", "browsers");
for (const platform of ["darwin", "linux", "win32"]) {
assert.equal(playwrightCache({ env: { PLAYWRIGHT_BROWSERS_PATH: custom }, platform, home }), custom);
}
const path = join(custom, "chromium_headless_shell-1208", "chrome-headless-shell-linux64", "chrome-headless-shell");
const found = findChromium({
env: { PLAYWRIGHT_BROWSERS_PATH: custom },
platform: "linux",
arch: "x64",
home,
...disk({ [custom]: ["chromium_headless_shell-1208"] }, [path]),
});
assert.equal(found, path);
});

test("PLAYWRIGHT_BROWSERS_PATH=0 means the browsers inside playwright-core's own folder, as Playwright installs them", () => {
const local = join("/", "work", "hermit", "apps", "mobile", "preview", "node_modules", "playwright-core", ".local-browsers");
assert.equal(playwrightCache({ env: { PLAYWRIGHT_BROWSERS_PATH: "0" }, platform: "linux", home, localBrowsers: () => local }), local);
});

test("a relative PLAYWRIGHT_BROWSERS_PATH resolves against INIT_CWD, then the working folder", () => {
const project = join("/", "work", "hermit");
const preview = join(project, "apps", "mobile", "preview");
assert.equal(
playwrightCache({ env: { PLAYWRIGHT_BROWSERS_PATH: "browsers", INIT_CWD: project }, platform: "linux", home, cwd: preview }),
resolve(project, "browsers"),
);
assert.equal(playwrightCache({ env: { PLAYWRIGHT_BROWSERS_PATH: "browsers" }, platform: "linux", home, cwd: preview }), resolve(preview, "browsers"));
});

test(`${BROWSER_VAR} wins over the cache when the file exists`, () => {
const own = join("/", "usr", "bin", "chromium");
const found = findChromium({
env: { [BROWSER_VAR]: own },
platform: "darwin",
arch: "arm64",
home,
...disk({ [macCache]: ["chromium_headless_shell-1208"] }, [own, macArm(1208)]),
});
assert.equal(found, own);
});

test(`${BROWSER_VAR} pointing at nothing stops with a message, without falling back to the cache`, () => {
const found = findChromium({
env: { [BROWSER_VAR]: "/no/such/chromium" },
platform: "darwin",
arch: "arm64",
home,
...disk({ [macCache]: ["chromium_headless_shell-1208"] }, [macArm(1208)]),
});
assert.ok(found instanceof Error);
assert.match(found.message, new RegExp(`${BROWSER_VAR} is set to /no/such/chromium`));
});

test(`an empty cache stops with a message that names ${BROWSER_VAR} and says nothing is downloaded`, () => {
const found = findChromium({ env: {}, platform: "linux", arch: "x64", home, ...disk({}, []) });
assert.ok(found instanceof Error);
assert.ok(found.message.includes(linuxCache), found.message);
assert.ok(found.message.includes(BROWSER_VAR), found.message);
assert.match(found.message, /never download a browser/);
});

test("a system with no known shell folder stops with the same message", () => {
const found = findChromium({ env: {}, platform: "freebsd", arch: "x64", home, ...disk({ [linuxCache]: ["chromium_headless_shell-1208"] }, []) });
assert.ok(found instanceof Error);
assert.ok(found.message.includes(BROWSER_VAR), found.message);
});
2 changes: 1 addition & 1 deletion apps/mobile/preview/build.mjs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
// Dev-only: bundles the real apps/mobile screens for a browser. react-native resolves to react-native-web; native
// modules, adapters and the runtime's ports resolve to the stubs in src/stubs (see README in docs/preview).
// modules, adapters and the runtime's ports resolve to the stubs in src/stubs (CONTRIBUTING.md, Screenshots for a UI change).
import { build } from "esbuild";
import { copyFileSync, existsSync, readFileSync, writeFileSync, mkdirSync } from "node:fs";
import { basename, dirname, join, resolve } from "node:path";
Expand Down
7 changes: 1 addition & 6 deletions apps/mobile/preview/clips.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import { existsSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, s
import { dirname, extname, join, resolve, sep } from "node:path";
import { fileURLToPath } from "node:url";
import { chromium } from "playwright-core";
import { chromiumPath } from "./browser.mjs";

const here = dirname(fileURLToPath(import.meta.url));
const dist = join(here, "dist");
Expand All @@ -31,12 +32,6 @@ const server = createServer((req, res) => {
await new Promise((r) => server.listen(0, "127.0.0.1", r));
const base = `http://127.0.0.1:${server.address().port}/`;

function chromiumPath() {
const cache = join(process.env.HOME, "Library/Caches/ms-playwright");
const shell = readdirSync(cache).filter((d) => d.startsWith("chromium_headless_shell-")).sort().pop();
return join(cache, shell, "chrome-headless-shell-mac-arm64", "chrome-headless-shell");
}

// The chat is its own route since the roster became home (HM-BOT-01): "index" here still means Hermit's chat.
const url = (screen, { theme = "light", lang = "es-419", variant = "", params = {} } = {}) =>
`${base}?${new URLSearchParams({ screen: screen === "index" ? "chat" : screen, theme, lang, variant, params: JSON.stringify(screen === "index" ? { bot: "hermit", ...params } : params) })}`;
Expand Down
11 changes: 2 additions & 9 deletions apps/mobile/preview/shoot.mjs
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
// Dev-only: serves dist/ and captures every shot in shots.mjs with headless Chromium at a 412x915 phone viewport,
// into out/screens, then writes out/index.html (both gitignored). Usage: node shoot.mjs [filter]
import { createServer } from "node:http";
import { readFileSync, writeFileSync, mkdirSync, existsSync, readdirSync, statSync } from "node:fs";
import { readFileSync, writeFileSync, mkdirSync, existsSync, statSync } from "node:fs";
import { dirname, extname, join, resolve, sep } from "node:path";
import { fileURLToPath } from "node:url";
import { chromium } from "playwright-core";
import { chromiumPath } from "./browser.mjs";
import { shots } from "./shots.mjs";
import { audit, words } from "./audit.mjs";

Expand All @@ -28,14 +29,6 @@ const server = createServer((req, res) => {
await new Promise((r) => server.listen(0, "127.0.0.1", r));
const base = `http://127.0.0.1:${server.address().port}/`;

/** The Chromium already on this Mac (Playwright's cache); nothing is downloaded. */
function chromiumPath() {
const cache = join(process.env.HOME, "Library/Caches/ms-playwright");
const shell = readdirSync(cache).filter((d) => d.startsWith("chromium_headless_shell-")).sort().pop();
if (!shell) throw new Error("no headless Chromium in ~/Library/Caches/ms-playwright");
return join(cache, shell, "chrome-headless-shell-mac-arm64", "chrome-headless-shell");
}

const filter = process.argv[2];
const browser = await chromium.launch({ executablePath: chromiumPath() });
const results = [];
Expand Down
3 changes: 3 additions & 0 deletions apps/mobile/preview/src/stubs/adapters.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ export const floorFacts = ok(scene.variant === "below"
: { platform: "android" as const, apiLevel: 36, abis: ["arm64-v8a"], totalRamBytes: 11.2 * 1024 ** 3, isLowRamDevice: false, dotprod: true, manufacturer: "samsung", model: "SM-S942B", soc: "SM8850" });
export const nightConditions = ok({ charging: true, batteryLevel: 0.82, network: "wifi", screenOn: false, idleMinutes: 45 });
export const onReconnect = off;
export const pauseDownloadWhenLeaving = off;
export const openStorageSettings = ok(undefined);
export const modelFile = () => ({ exists: false, uri: "file:///model.gguf", size: 0 });
export const verifiedSha256 = () => undefined;
Expand Down Expand Up @@ -90,6 +91,8 @@ export const actOnPermission = ok(undefined);
// App lock and fingerprint.
export const appLockEnabled = () => scene.variant === "locked";
export const saveAppLock = ok(undefined);
// The copy keeps its default biometric name: an Android phone's fingerprint.
export const applyBiometricName = ok(undefined);
export const phoneSecurity = ok("biometric" as const);
// The lock screen's shot waits at its own prompt, as on the phone before the fingerprint.
export const confirmOwner = () => (scene.variant === "locked" ? new Promise<boolean>(() => {}) : Promise.resolve(true));
Expand Down
7 changes: 3 additions & 4 deletions apps/mobile/preview/words.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,11 @@
// preview bundle, for the copy diet's before and after. Usage: node words.mjs <dist dir> <out.json>
// (build the bundle of the commit to compare with its own build.mjs first).
import { createServer } from "node:http";
import { existsSync, readFileSync, readdirSync, statSync, writeFileSync } from "node:fs";
import { existsSync, readFileSync, statSync, writeFileSync } from "node:fs";
import { extname, join, resolve, sep } from "node:path";
import { chromium } from "playwright-core";
import { words } from "./audit.mjs";
import { chromiumPath } from "./browser.mjs";

const [distArg, outArg] = process.argv.slice(2);
if (!distArg || !outArg) throw new Error("usage: node words.mjs <dist dir> <out.json>");
Expand All @@ -23,8 +24,6 @@ const server = createServer((req, res) => {
});
await new Promise((r) => server.listen(0, "127.0.0.1", r));
const base = `http://127.0.0.1:${server.address().port}/`;
const cache = join(process.env.HOME, "Library/Caches/ms-playwright");
const shell = readdirSync(cache).filter((d) => d.startsWith("chromium_headless_shell-")).sort().pop();

/** The hero states, as in shots.mjs. */
export const HERO = [
Expand All @@ -36,7 +35,7 @@ export const HERO = [
{ key: "welcome", screen: "welcome", variant: "" },
];

const browser = await chromium.launch({ executablePath: join(cache, shell, "chrome-headless-shell-mac-arm64", "chrome-headless-shell") });
const browser = await chromium.launch({ executablePath: chromiumPath() });
const out = {};
for (const h of HERO) {
const ctx = await browser.newContext({ viewport: { width: 412, height: 915 }, deviceScaleFactor: 1, locale: "es-419" });
Expand Down
Loading
Loading