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
12 changes: 7 additions & 5 deletions apps/mobile/src/app/delete.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,20 +7,20 @@
import { reloadAppAsync } from "expo";
import { Stack } from "expo-router";
import { useCallback, useEffect, useReducer, useRef, useState } from "react";
import { BackHandler, View } from "react-native";
import { BackHandler, Platform, View } from "react-native";
import { eraseReducer, initialErase, confirmationMatches, type EraseScreen } from "@hermit/runtime";
import { notificationAccessEnabled, openNotificationAccessSettings } from "../adapters";
import { confirmErase, eraseEverything, phoneHasLock, walletBalance } from "../adapters/erase";
import { Icon } from "../components/Icon";
import { Btn, Card, Empty, Failed, Input, Note as NoteLine, Notice, Page, T } from "../components/kit";
import { eraseLines } from "../delete-view";
import { useHermit } from "../hermit-context";
import { t } from "../i18n";
import { radius, s } from "../theme";
import { usePalette } from "../use-palette";

// Read at use, not at import: the word follows the app language (HM-SET-05).
const word = () => t("HM-SET-03.confirmWord");
const LIST = ["listData", "listMessages", "listKeys", "listCache", "listModel"] as const;

interface Facts {
initial: EraseScreen;
Expand Down Expand Up @@ -103,6 +103,7 @@ function Flow({ initial, hasLock, notifAccess }: Facts) {

function Body(props: { screen: EraseScreen; hasLock: boolean; notifAccess: boolean; onType(text: string): void; onSubmit(): void; onWalletAck(): void; onRetry(): void }) {
const p = usePalette();
const lines = eraseLines(Platform.OS);
const { screen } = props;
switch (screen.kind) {
case "wallet_warning":
Expand All @@ -126,11 +127,12 @@ function Body(props: { screen: EraseScreen; hasLock: boolean; notifAccess: boole
return (
<View style={{ gap: s.lg }}>
<T v="body">{t("HM-SET-03.body")}</T>
{/* What goes, on the page color with coral marks. */}
{/* What goes, on the page color with coral marks. On iOS the captured-messages line is not there:
capture is Android-only, and so is the permissions note under the list. */}
<View style={{ gap: s.sm }}>
{LIST.map((k) => <NoteLine key={k} icon="trash-2" tone="coral" text={t(`HM-SET-03.${k}`)} textColor="text" v="body" />)}
{lines.list.map((k) => <NoteLine key={k} icon="trash-2" tone="coral" text={t(`HM-SET-03.${k}`)} textColor="text" v="body" />)}
</View>
<NoteLine icon="info" text={t("HM-SET-03.permissionsStay")} />
{lines.permissionsStay ? <NoteLine icon="info" text={t("HM-SET-03.permissionsStay")} /> : null}
{props.notifAccess ? <Btn label={t("HM-SET-03.openNotificationAccess")} kind="secondary" icon="settings" small onPress={openNotificationAccessSettings} /> : null}
<Input
label={t("HM-SET-03.typePrompt", { word: word() })}
Expand Down
25 changes: 25 additions & 0 deletions apps/mobile/src/delete-view.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
// HM-SET-03 (#212): the erase screen's list and notes on each OS. The WhatsApp capture line and the Android
// permissions note only apply where capture exists, which is Android; iOS has no capture.
import { test } from "node:test";
import assert from "node:assert/strict";
import { eraseLines } from "./delete-view.ts";

test("on Android the list keeps every line and the permissions note shows", () => {
const lines = eraseLines("android");
assert.deepEqual(lines.list, ["listData", "listMessages", "listKeys", "listCache", "listModel"]);
assert.equal(lines.permissionsStay, true);
});

test("on iOS the list leaves out the captured messages line and the permissions note is gone", () => {
const lines = eraseLines("ios");
assert.deepEqual(lines.list, ["listData", "listKeys", "listCache", "listModel"]);
assert.equal(lines.permissionsStay, false);
});

test("only Android gets the Android lines", () => {
for (const os of ["web", "macos", "windows"]) {
const lines = eraseLines(os);
assert.ok(!lines.list.includes("listMessages"), os);
assert.equal(lines.permissionsStay, false, os);
}
});
16 changes: 16 additions & 0 deletions apps/mobile/src/delete-view.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
// HM-SET-03: which of the erase screen's lines apply on this OS. Pure: tested under Node with node --test
// (delete-view.test.ts). WhatsApp capture reads Android notifications, so its line and the Android permissions
// note only apply on Android; iOS has no capture and no such permissions to mention.

export const ERASE_LIST = ["listData", "listMessages", "listKeys", "listCache", "listModel"] as const;

export type EraseListKey = (typeof ERASE_LIST)[number];

/** The "what goes" list keys and whether the permissions note shows, for React Native's `Platform.OS` (or any OS string). */
export function eraseLines(os: string): { list: readonly EraseListKey[]; permissionsStay: boolean } {
const android = os === "android";
return {
list: android ? ERASE_LIST : ERASE_LIST.filter((k) => k !== "listMessages"),
permissionsStay: android,
};
}
88 changes: 88 additions & 0 deletions apps/site/test/meta.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
// #267: the metadata of every page, without a build. pageMetadata and chooserMetadata (lib/meta.ts) give each page its
// title, description, canonical address, hreflang alternates and link preview, on the copy translator (lib/i18n.ts)
// returns, so these tests ask the translator too and a copy change doesn't break them. Tests only: lib/meta.ts, the
// locale files and everything else under apps/site stay as they are.
import { describe, expect, test } from "vitest";
import { BRAND_FILES } from "../lib/brand.mjs";
import { href, isLang, LANGS, LOCALE, translator, type Lang, type Page } from "../lib/i18n";
import { chooserMetadata, OG_IMAGE, pageMetadata } from "../lib/meta";
import { SITE_URL } from "../lib/site-config.mjs";

/** Open Graph's locale names (language_TERRITORY): es_LA is the one link previews know for Latin American Spanish. */
const OG_LOCALE: Readonly<Record<Lang, string>> = { en: "en_US", es: "es_LA" };

/** The three pages of the site: the home, the privacy policy and the download page. */
const PAGES: ReadonlyArray<["HM-SITE-01" | "HM-SITE-02" | "HM-SITE-03", Page]> = [
["HM-SITE-01", ""],
["HM-SITE-02", "privacy/"],
["HM-SITE-03", "download/"],
];

describe("lib/meta.ts", () => {
describe("pageMetadata", () => {
for (const lang of LANGS) {
for (const [screen, page] of PAGES) {
test(`${screen} in ${lang} carries the copy, the addresses and the preview`, () => {
const t = translator(lang);
const m = pageMetadata(lang, screen, page);
// The copy comes from the translator, so a copy change moves both together.
expect(m.title).toBe(t(`${screen}.metaTitle`));
expect(m.description).toBe(t(`${screen}.metaDescription`));
// The canonical address is the page's own in this language, and the alternates point at the same page in
// each language, with the chooser at the root as the default.
expect(m.alternates?.canonical).toBe(href(lang, page));
expect(m.alternates?.languages).toEqual({
"es-419": href("es", page),
en: href("en", page),
"x-default": "/",
});
// The link preview: the same copy and address in Open Graph and in the Twitter card, one image from
// OG_IMAGE with the common alt text, and the locale of the page's language plus the other one.
const image = { url: OG_IMAGE.url, width: OG_IMAGE.width, height: OG_IMAGE.height, alt: t("common.ogAlt") };
expect(m.openGraph?.title).toBe(m.title);
expect(m.openGraph?.description).toBe(m.description);
expect(m.openGraph?.url).toBe(href(lang, page));
expect(m.openGraph?.images).toEqual([image]);
expect(m.twitter?.images).toEqual(m.openGraph?.images);
expect(m.openGraph?.locale).toBe(OG_LOCALE[lang]);
expect(m.openGraph?.alternateLocale).toEqual([OG_LOCALE[LOCALE[lang].other]]);
// Relative paths resolve against the site's address.
expect(String(m.metadataBase)).toBe(new URL(SITE_URL).href);
});
}
}

test("chooserMetadata points at the chooser, with the home page's alternates, in Spanish", () => {
const m = chooserMetadata();
expect(m.alternates?.canonical).toBe("/");
expect(m.alternates?.languages).toEqual({
"es-419": href("es", ""),
en: href("en", ""),
"x-default": "/",
});
expect(m.openGraph?.locale).toBe("es_LA");
});

test("the preview image is a brand file the build copies from docs/brand", () => {
expect(OG_IMAGE.url.startsWith("/brand/")).toBe(true);
expect(BRAND_FILES, `OG_IMAGE.url ${OG_IMAGE.url}`).toContain(OG_IMAGE.url.slice("/brand/".length));
});
});

describe("lib/i18n.ts", () => {
test("a missing key is named with its language", () => {
expect(() => translator("es")("HM-SITE-99.nope")).toThrow(/Missing copy key HM-SITE-99\.nope \(es\)/);
});

test("a placeholder with no value is named in the error", () => {
expect(() => translator("en")("HM-SITE-02.updated")).toThrow(/needs \{date\}/);
});

test("isLang accepts only the two URL segments, es and en", () => {
expect([...LANGS]).toEqual(["es", "en"]);
for (const lang of LANGS) expect(isLang(lang), lang).toBe(true);
expect(isLang("es-419")).toBe(false);
expect(isLang("EN")).toBe(false);
});
});
});
68 changes: 68 additions & 0 deletions packages/boost/test/errors.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
import { readFileSync } from "node:fs";
import { outcomeCopyKey } from "@hermit/core";
import { describe, expect, test } from "vitest";
import { BOOST_CODES, BoostError, boostNotice, type BoostCode } from "../src/errors.ts";
import { codeOfWire, WIRE_ERRORS, type WireErrorCode } from "../src/wire.ts";

const UPDATE_CODES: readonly BoostCode[] = ["version_mismatch", "model_mismatch", "profile_mismatch"];

describe("BoostError codes", () => {
test("every code round-trips through the error, with its name and a message starting with the code", () => {
for (const code of BOOST_CODES) {
const err = new BoostError(code);
expect(err).toBeInstanceOf(Error);
expect(err.code).toBe(code);
expect(err.name).toBe("BoostError");
expect(err.message.startsWith(`${code}: `)).toBe(true);
}
});

test("the outcome is stopped only for stopped, and boost_unavailable for every other code", () => {
for (const code of BOOST_CODES) expect(new BoostError(code).outcome).toBe(code === "stopped" ? "stopped" : "boost_unavailable");
});

test("update is true for exactly the three mismatch codes", () => {
for (const code of BOOST_CODES) expect(new BoostError(code).update).toBe(UPDATE_CODES.includes(code));
});
});

describe("boostNotice", () => {
test("an update code asks to update Hermit Boost, stopped retries, and every other code runs on the phone", () => {
for (const code of BOOST_CODES) {
const notice = boostNotice(new BoostError(code));
if (UPDATE_CODES.includes(code)) {
expect(notice).toEqual({ text: "common.boost.updateNeeded", action: "common.boost.update" });
} else if (code === "stopped") {
expect(notice).toEqual({ text: outcomeCopyKey("stopped"), action: "common.retry" });
} else {
expect(notice).toEqual({ text: outcomeCopyKey("boost_unavailable"), action: "common.boost.runOnPhone" });
}
}
});

test("every key boostNotice can return exists in both locales", () => {
const keys = new Set<string>();
for (const code of BOOST_CODES) {
const notice = boostNotice(new BoostError(code));
keys.add(notice.text);
keys.add(notice.action);
}
for (const locale of ["en", "es-419"] as const) {
const copy = JSON.parse(readFileSync(new URL(`../../copy/locales/${locale}.json`, import.meta.url), "utf8")) as Record<string, string>;
for (const key of keys) expect(copy[key], `${locale} has ${key}`).toBeTypeOf("string");
}
});
});

describe("codeOfWire", () => {
test("cancelled is stopped, and every other wire code gives itself", () => {
expect(codeOfWire("cancelled")).toBe("stopped");
for (const code of WIRE_ERRORS) {
if (code !== "cancelled") expect(codeOfWire(code)).toBe(code);
}
});

test("a code that is not a Boost code gives protocol", () => {
expect(codeOfWire("made_up" as unknown as WireErrorCode)).toBe("protocol");
});
});
74 changes: 74 additions & 0 deletions packages/connectors/test/connect-derive.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { describe, expect, it } from "vitest";
import { deriveSafety, docPaths, docTokens, docUrls, excerptProblem, guardSideEffects, MAX_EXCERPT_CHARS, signInToAuth } from "../src/index.ts";
import { docSection, methodLines, snakeId } from "../src/connect/derive.ts";
import { BASIC_DOC, COBROS_DOC, TASKS_DOC } from "./connect-fixtures.ts";

describe("the keyword guard (EN and ES)", () => {
Expand Down Expand Up @@ -77,3 +78,76 @@ describe("the sign-in is a fixed choice; a name or prefix only from the doc's wo
expect(signInToAuth({ kind: "header_key", name: "Cookie" }, ["Cookie"])).toBeUndefined();
});
});

describe("methodLines", () => {
const DOC = "# Items\n## List\nGET /v1/items.\nReturns items.\n## Create\nPOST /v1/items\nMakes one.";

it("finds every METHOD /path line, with the trailing punctuation dropped from the path", () => {
expect(methodLines(DOC)).toEqual([
{ method: "GET", path: "/v1/items" },
{ method: "POST", path: "/v1/items" },
]);
});

it("skips a lower case method, a method in the middle of a sentence and a method it doesn't know", () => {
expect(methodLines("get /v1/x")).toEqual([]);
expect(methodLines("We GET /v1/x")).toEqual([]);
expect(methodLines("HEAD /v1/x")).toEqual([]);
});

it("accepts spaces before the method", () => {
expect(methodLines(" GET /v1/x")).toEqual([{ method: "GET", path: "/v1/x" }]);
});
});

describe("docSection", () => {
const DOC = "# Items\n## List\nGET /v1/items.\nReturns items.\n## Create\nPOST /v1/items\nMakes one.";

it("gives the heading line before the method, the method line and what follows, and stops before the next endpoint", () => {
expect(docSection(DOC, "GET", ["/v1/items"])).toBe("## List\nGET /v1/items.\nReturns items.");
});

it("the last endpoint's section runs to the end of the doc", () => {
expect(docSection(DOC, "POST", ["/v1/items"])).toBe("## Create\nPOST /v1/items\nMakes one.");
});

it("a method or a path that isn't there gives an empty string", () => {
expect(docSection(DOC, "PUT", ["/v1/items"])).toBe("");
expect(docSection(DOC, "GET", ["/v1/nope"])).toBe("");
});

it("a method line on the first line of the doc has no heading line before it", () => {
expect(docSection("GET /a\nx\nPOST /b", "GET", ["/a"])).toBe("GET /a");
});

it("the line just before the next method line is always treated as that endpoint's heading, so it stays out of this section", () => {
// Pin of today's behaviour: the "x" line is read as the heading of "POST /b", not as part of "GET /a".
expect(docSection("GET /a\nx\nPOST /b", "GET", ["/a"])).toBe("GET /a");
});
});

describe("snakeId", () => {
it("turns names into snake case, with accents dropped", () => {
expect(snakeId("listItems", "made_up")).toBe("list_items");
expect(snakeId("Crear Pedido", "made_up")).toBe("crear_pedido");
expect(snakeId("Café Ñandú", "made_up")).toBe("cafe_nandu");
});

it("a name that starts with something else than a letter gets a c_ prefix", () => {
expect(snakeId("123abc", "made_up")).toBe("c_123abc");
});

it("a name with no letters at all gives the fallback", () => {
expect(snakeId("!!!", "made_up")).toBe("made_up");
});

it("a one letter id is padded to two", () => {
expect(snakeId("a", "made_up")).toBe("a_x");
});

it("a long name is cut to 40 characters, with no underscore at the end", () => {
expect(snakeId("a".repeat(50), "made_up")).toBe("a".repeat(40));
// The cut lands on the underscore after 39 letters, and the underscore is dropped.
expect(snakeId(`${"a".repeat(39)} b c`, "made_up")).toBe("a".repeat(39));
});
});
47 changes: 47 additions & 0 deletions packages/connectors/test/mcp-url.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { describe, expect, it } from "vitest";
import { getChecked, parseHttpsUrl, parseJsonObject, postChecked, resolveRedirect } from "../src/index.ts";
import { bool, str, strArr } from "../src/mcp/json.ts";
import { withoutTrailingSlash } from "../src/mcp/url.ts";
import { fakeNet, json } from "./mcp-fixtures.ts";

describe("parseHttpsUrl: every URL the MCP client touches (FR-CONN-02)", () => {
Expand Down Expand Up @@ -133,3 +135,48 @@ describe("getChecked and postChecked: the URL check runs before every hop", () =
expect(net.sent[0]!.maxResponseBytes).toBe(10);
});
});

describe("MCP JSON field readers (str, strArr, bool)", () => {
it("str returns non-empty own string fields and undefined otherwise", () => {
expect(str({ name: "hermit" }, "name")).toBe("hermit");
expect(str({ name: "" }, "name")).toBeUndefined();
expect(str({ name: 123 }, "name")).toBeUndefined();
expect(str({ name: null }, "name")).toBeUndefined();
expect(str({ name: ["hermit"] }, "name")).toBeUndefined();
expect(str({}, "name")).toBeUndefined();
expect(str(Object.create({ name: "x" }) as Record<string, unknown>, "name")).toBeUndefined();
});

it("strArr keeps only string items from own array fields and returns undefined otherwise", () => {
expect(strArr({ items: ["a", 1, null, "b"] }, "items")).toEqual(["a", "b"]);
expect(strArr({ items: [] }, "items")).toEqual([]);
expect(strArr({ items: "abc" }, "items")).toBeUndefined();
expect(strArr({ items: { a: "1" } }, "items")).toBeUndefined();
expect(strArr({}, "items")).toBeUndefined();
expect(strArr(Object.create({ items: ["x"] }) as Record<string, unknown>, "items")).toBeUndefined();
});

it("bool returns own boolean fields and undefined otherwise", () => {
expect(bool({ enabled: true }, "enabled")).toBe(true);
expect(bool({ enabled: false }, "enabled")).toBe(false);
expect(bool({ enabled: "true" }, "enabled")).toBeUndefined();
expect(bool({ enabled: 1 }, "enabled")).toBeUndefined();
expect(bool({}, "enabled")).toBeUndefined();
expect(bool(Object.create({ enabled: true }) as Record<string, unknown>, "enabled")).toBeUndefined();
});
});

describe("withoutTrailingSlash", () => {
it("strips at most one trailing path slash while preserving query strings", () => {
expect(withoutTrailingSlash(parseHttpsUrl("https://mcp.example.com/")!)).toBe("https://mcp.example.com");
expect(withoutTrailingSlash(parseHttpsUrl("https://mcp.example.com/mcp/")!)).toBe("https://mcp.example.com/mcp");
expect(withoutTrailingSlash(parseHttpsUrl("https://mcp.example.com/mcp")!)).toBe("https://mcp.example.com/mcp");
expect(withoutTrailingSlash(parseHttpsUrl("https://mcp.example.com/mcp/?a=1")!)).toBe(
"https://mcp.example.com/mcp?a=1",
);
expect(withoutTrailingSlash(parseHttpsUrl("https://mcp.example.com/?a=1")!)).toBe(
"https://mcp.example.com?a=1",
);
expect(withoutTrailingSlash(parseHttpsUrl("https://mcp.example.com/mcp//")!)).toBe("https://mcp.example.com/mcp/");
});
});
Loading
Loading