From 7d166c39c5230a391b6804db63a928e4e988cfcd Mon Sep 17 00:00:00 2001 From: aditya9515 Date: Sun, 6 Dec 2026 12:33:17 +0530 Subject: [PATCH 1/8] fix(mobile): hide Android-only erase lines on iOS (#212) --- apps/mobile/src/app/delete.tsx | 12 +++++++----- apps/mobile/src/delete-view.test.ts | 25 +++++++++++++++++++++++++ apps/mobile/src/delete-view.ts | 16 ++++++++++++++++ 3 files changed, 48 insertions(+), 5 deletions(-) create mode 100644 apps/mobile/src/delete-view.test.ts create mode 100644 apps/mobile/src/delete-view.ts diff --git a/apps/mobile/src/app/delete.tsx b/apps/mobile/src/app/delete.tsx index 148a2d1..e761627 100644 --- a/apps/mobile/src/app/delete.tsx +++ b/apps/mobile/src/app/delete.tsx @@ -7,12 +7,13 @@ 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"; @@ -20,7 +21,6 @@ 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; @@ -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": @@ -126,11 +127,12 @@ function Body(props: { screen: EraseScreen; hasLock: boolean; notifAccess: boole return ( {t("HM-SET-03.body")} - {/* 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. */} - {LIST.map((k) => )} + {lines.list.map((k) => )} - + {lines.permissionsStay ? : null} {props.notifAccess ? : null} { + 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); + } +}); diff --git a/apps/mobile/src/delete-view.ts b/apps/mobile/src/delete-view.ts new file mode 100644 index 0000000..6c3af99 --- /dev/null +++ b/apps/mobile/src/delete-view.ts @@ -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, + }; +} From ff1a6a22aa9018ef2f3c861e729f115de756f5be Mon Sep 17 00:00:00 2001 From: viditjain25 Date: Sun, 6 Dec 2026 12:57:29 +0530 Subject: [PATCH 2/8] test(connectors): cover MCP JSON field readers and withoutTrailingSlash (#265) --- packages/connectors/test/mcp-url.test.ts | 47 ++++++++++++++++++++++++ 1 file changed, 47 insertions(+) diff --git a/packages/connectors/test/mcp-url.test.ts b/packages/connectors/test/mcp-url.test.ts index a6d0373..95e97d2 100644 --- a/packages/connectors/test/mcp-url.test.ts +++ b/packages/connectors/test/mcp-url.test.ts @@ -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)", () => { @@ -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, "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, "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, "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/"); + }); +}); From bd13ab9451808c7d7cf05a372e1189422e010314 Mon Sep 17 00:00:00 2001 From: Saurabh Bhoir <63059109+saurabhbhoir456@users.noreply.github.com> Date: Sun, 6 Dec 2026 14:01:30 +0530 Subject: [PATCH 3/8] test(core): cover how a bot's read kinds are kept (#261) --- packages/core/test/bots.test.ts | 47 ++++++++++++++++++++++++++++++--- 1 file changed, 44 insertions(+), 3 deletions(-) diff --git a/packages/core/test/bots.test.ts b/packages/core/test/bots.test.ts index 757b0cf..541dda0 100644 --- a/packages/core/test/bots.test.ts +++ b/packages/core/test/bots.test.ts @@ -1,7 +1,7 @@ -import { expect, test } from "vitest"; +import { describe, expect, test } from "vitest"; import { - FINGERPRINT_GROUPS, HERMIT_BOT_ID, MAX_BOT_NAME_CHARS, MAX_BOTS, MAX_PINS, MAX_ROLE_CHARS, PRIVATE_GROUPS, SKILL_GROUPS, - heldGroups, needsFingerprint, normalizeSite, readKind, tierOf, + FINGERPRINT_GROUPS, HERMIT_BOT_ID, MAX_BOT_NAME_CHARS, MAX_BOTS, MAX_PINS, MAX_ROLE_CHARS, PRIVATE_GROUPS, READ_KINDS, SKILL_GROUPS, + decodeReadKinds, encodeReadKinds, heldGroups, needsFingerprint, normalizeReadKinds, normalizeSite, readKind, tierOf, } from "../src/bots.ts"; test("the contract's values", () => { @@ -37,3 +37,44 @@ test("the fingerprint for a newly held mail send, login or pay group, or for Don expect(needsFingerprint({ grants: ["notes"], mode: "dont_ask" }, { grants: ["notes"], mode: "auto" })).toBe(true); expect(needsFingerprint({ grants: ["notes"], mode: "dont_ask" }, { grants: ["notes"], mode: "dont_ask" })).toBe(false); }); + +describe("read kinds", () => { + test("normalize keeps the canonical order and drops duplicates and non-kinds", () => { + expect([...READ_KINDS]).toEqual(["private", "web"]); + expect(normalizeReadKinds(["web", "private"])).toEqual(["private", "web"]); + expect(normalizeReadKinds(["web", "web", "private"])).toEqual(["private", "web"]); + expect(normalizeReadKinds(["Web", " web", "web ", "mail", ""])).toEqual([]); + expect(normalizeReadKinds([])).toEqual([]); + }); + + test("encode joins the normalized kinds with a comma", () => { + expect(encodeReadKinds(["web", "private", "web"])).toBe("private,web"); + expect(encodeReadKinds(["web"])).toBe("web"); + expect(encodeReadKinds(["private"])).toBe("private"); + expect(encodeReadKinds([])).toBe(""); + }); + + test("every subset, in every order, encodes to a value the kinds CHECK allows", () => { + const allowed = ["", "private", "web", "private,web"]; + const subsets: string[][] = [[]]; + for (const kind of READ_KINDS) subsets.push(...subsets.map((s) => [...s, kind])); + const lists: string[][] = [...subsets, ...subsets.map((s) => [...s].reverse()), ["web", "web"], ["mail", "web", "private"], ["", "private"]]; + for (const list of lists) expect(allowed).toContain(encodeReadKinds(list)); + }); + + test("decode reads a column back, and empty or unknown values give no kinds", () => { + expect(decodeReadKinds(null)).toEqual([]); + expect(decodeReadKinds(undefined)).toEqual([]); + expect(decodeReadKinds("")).toEqual([]); + expect(decodeReadKinds("web,private")).toEqual(["private", "web"]); + expect(decodeReadKinds("web,,mail")).toEqual(["web"]); + expect(decodeReadKinds("web,web")).toEqual(["web"]); + expect(decodeReadKinds("mail")).toEqual([]); + }); + + test("a round trip through encode and decode is the normalized list", () => { + for (const list of [[], ["web"], ["private", "web"], ["web", "private", "web"], ["mail", "web"], [""]]) { + expect(decodeReadKinds(encodeReadKinds(list))).toEqual(normalizeReadKinds(list)); + } + }); +}); From 107cf6bb97b9818f70d588f2c8e969609c65553b Mon Sep 17 00:00:00 2001 From: Saurabh Bhoir <63059109+saurabhbhoir456@users.noreply.github.com> Date: Sun, 6 Dec 2026 14:06:06 +0530 Subject: [PATCH 4/8] test(payments): cover EVM address helpers with the EIP-55 vectors (#259) --- packages/payments/test/eip712.test.ts | 76 +++++++++++++++++++++++++++ 1 file changed, 76 insertions(+) diff --git a/packages/payments/test/eip712.test.ts b/packages/payments/test/eip712.test.ts index 8d88027..c3b7093 100644 --- a/packages/payments/test/eip712.test.ts +++ b/packages/payments/test/eip712.test.ts @@ -1,4 +1,6 @@ import { describe, expect, test } from "vitest"; +import { checksumAddress, isAddress, sameAddress } from "../src/eip712.ts"; +import { X402Error } from "../src/errors.ts"; import { domainSeparator, localKeySigner, recoverTypedDataSigner, transferWithAuthorizationDigest, TESTNET_ASSETS } from "../src/index.ts"; import { MERCHANT, ONCHAIN_DOMAIN_SEPARATOR, USDT0_TOKEN } from "./fixtures.ts"; @@ -55,3 +57,77 @@ describe("a local secp256k1 key signs TransferWithAuthorization the way the toke expect(transferWithAuthorizationDigest({ ...typedData, domain: { ...typedData.domain, chainId: 9745 } })).not.toBe(base); }); }); + +describe("EVM addresses", () => { + // The published EIP-55 test vectors. Public examples, not anyone's wallet. + const vectors = [ + "0x52908400098527886E0F7030069857D2E4169EE7", + "0x8617E340B3D01FA5F11F306F4090FD50E238070D", + "0xde709f2102306220921060314715629080e2fb77", + "0x27b1fdb04752bbc536007a920d24acb045561c26", + "0x5aAeb6053F3E94C9b9A09f33669435E7Ef1BeAed", + "0xfB6916095ca1df60bB79Ce92cE3Ea74c37c5d359", + "0xdbF03B407c01E7cD3CBea99509d93f8DDDC8C6FB", + "0xD1220A0cf47c7B9Be7A2E6BA89F429762e7b9aDb", + ]; + const reason = (fn: () => unknown) => { + try { + fn(); + } catch (e) { + return e instanceof X402Error ? e.code : String(e); + } + return "no error"; + }; + + test("isAddress accepts only 0x and exactly 40 hex digits, in any case", () => { + expect(isAddress("0x" + "a".repeat(40))).toBe(true); + expect(isAddress("0x" + "A".repeat(40))).toBe(true); + expect(isAddress("0x" + "aB".repeat(20))).toBe(true); + expect(isAddress(vectors[0]!)).toBe(true); + expect(isAddress(vectors[0]!.slice(2))).toBe(false); + expect(isAddress("0X" + "a".repeat(40))).toBe(false); + expect(isAddress("0x" + "a".repeat(39))).toBe(false); + expect(isAddress("0x" + "a".repeat(41))).toBe(false); + expect(isAddress(" 0x" + "a".repeat(40))).toBe(false); + expect(isAddress("0x" + "a".repeat(40) + " ")).toBe(false); + expect(isAddress("0x" + "a".repeat(39) + "g")).toBe(false); + expect(isAddress("")).toBe(false); + }); + + test("checksumAddress gives the published EIP-55 vectors from the lower case form", () => { + for (const vector of vectors) expect(checksumAddress("0x" + vector.slice(2).toLowerCase())).toBe(vector); + }); + + test("checksumAddress is stable on the checksummed form and on all upper case after 0x", () => { + for (const vector of vectors) { + expect(checksumAddress(vector)).toBe(vector); + expect(checksumAddress("0x" + vector.slice(2).toUpperCase())).toBe(vector); + } + }); + + test("checksumAddress throws bad_input for anything isAddress refuses", () => { + for (const bad of ["", "0x12", "0X" + "a".repeat(40), "0x" + "a".repeat(39), "0x" + "a".repeat(41), "0x" + "a".repeat(39) + "g"]) { + expect(reason(() => checksumAddress(bad))).toBe("bad_input"); + } + expect(() => checksumAddress("0x12")).toThrow(X402Error); + }); + + // Pinned current behavior: a mixed case input with a wrong checksum is rewritten, not refused. + test("checksumAddress rewrites a wrong mixed case checksum instead of refusing it", () => { + const vector = vectors[0]!; + const wrong = "0x" + vector.slice(2).replace("E", "e"); + expect(wrong).not.toBe(vector); + expect(isAddress(wrong)).toBe(true); + expect(checksumAddress(wrong)).toBe(vector); + }); + + test("sameAddress compares addresses ignoring case, and refuses non-addresses", () => { + const vector = vectors[4]!; + expect(sameAddress(vector, "0x" + vector.slice(2).toLowerCase())).toBe(true); + expect(sameAddress(vector, "0x" + vector.slice(2).toUpperCase())).toBe(true); + expect(sameAddress(vectors[0]!, vectors[1]!)).toBe(false); + expect(sameAddress("0x12", "0x12")).toBe(false); + expect(sameAddress(vector, "0x12")).toBe(false); + expect(sameAddress("0x12", vector)).toBe(false); + }); +}); From c5dccaac53f882a53e339d251cde07b939335ef2 Mon Sep 17 00:00:00 2001 From: mir-ashiq Date: Sun, 6 Dec 2026 08:37:42 +0000 Subject: [PATCH 5/8] test(site): check each page's metadata and the translator (#267) --- apps/site/test/meta.test.ts | 88 +++++++++++++++++++++++++++++++++++++ 1 file changed, 88 insertions(+) create mode 100644 apps/site/test/meta.test.ts diff --git a/apps/site/test/meta.test.ts b/apps/site/test/meta.test.ts new file mode 100644 index 0000000..b469de1 --- /dev/null +++ b/apps/site/test/meta.test.ts @@ -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> = { 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); + }); + }); +}); From d4b0ed90328f4ad4effa32b8258e8f355cc45702 Mon Sep 17 00:00:00 2001 From: Saurabh Bhoir <63059109+saurabhbhoir456@users.noreply.github.com> Date: Sun, 6 Dec 2026 14:10:20 +0530 Subject: [PATCH 6/8] test(boost): cover every error code, its notice and codeOfWire (#260) --- packages/boost/test/errors.test.ts | 68 ++++++++++++++++++++++++++++++ 1 file changed, 68 insertions(+) create mode 100644 packages/boost/test/errors.test.ts diff --git a/packages/boost/test/errors.test.ts b/packages/boost/test/errors.test.ts new file mode 100644 index 0000000..ed69911 --- /dev/null +++ b/packages/boost/test/errors.test.ts @@ -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(); + 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; + 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"); + }); +}); From 4f18d820cbd693306f6b23e57a53cc90af3017cb Mon Sep 17 00:00:00 2001 From: Saurabh Bhoir <63059109+saurabhbhoir456@users.noreply.github.com> Date: Sun, 6 Dec 2026 14:14:52 +0530 Subject: [PATCH 7/8] test(runtime): cover runEnd, rosterStatus and isModeSetting (#262) --- packages/runtime/test/bots-rules.test.ts | 87 ++++++++++++++++++++++++ 1 file changed, 87 insertions(+) create mode 100644 packages/runtime/test/bots-rules.test.ts diff --git a/packages/runtime/test/bots-rules.test.ts b/packages/runtime/test/bots-rules.test.ts new file mode 100644 index 0000000..9206743 --- /dev/null +++ b/packages/runtime/test/bots-rules.test.ts @@ -0,0 +1,87 @@ +import { describe, expect, test } from "vitest"; +import type { AloneTurnResult } from "../src/alone-turns.ts"; +import { ROUTINE_RUN_REASONS, ROSTER_STATUSES } from "../src/bot-api.ts"; +import { isModeSetting, rosterStatus, runEnd } from "../src/bots.ts"; + +const turn = (over: Partial): AloneTurnResult => ({ + kind: "final", + sessionId: "s1", + modelCalls: 1, + executed: [], + blocked: [], + untrusted: false, + reads: [], + ...over, +}); + +describe("runEnd", () => { + test("a final turn is done, with no reason", () => { + expect(runEnd(turn({ kind: "final" }))).toEqual({ state: "done", changed: false }); + }); + + test("changed is true when a step ran ok or a step is blocked, and false when every step failed", () => { + expect(runEnd(turn({ executed: [{ skill: "notes_save", ok: true }] })).changed).toBe(true); + expect(runEnd(turn({ executed: [{ skill: "notes_save", ok: false }, { skill: "mail_read", ok: false }] })).changed).toBe(false); + expect(runEnd(turn({ blocked: [{ skill: "mail_send", reason: "needs your approval" }] })).changed).toBe(true); + expect(runEnd(turn({ kind: "error", code: "model_error", executed: [{ skill: "notes_save", ok: true }] }))).toEqual({ + state: "failed", + reason: "model_error", + changed: true, + }); + }); + + test("an error turn fails with its code as the reason, or error when it has none", () => { + for (const code of ["max_steps", "repair_failed", "model_error"] as const) { + expect(runEnd(turn({ kind: "error", code }))).toEqual({ state: "failed", reason: code, changed: false }); + } + expect(runEnd(turn({ kind: "error" }))).toEqual({ state: "failed", reason: "error", changed: false }); + }); + + test("needs_user, budget and stopped fail with their own kind as the reason", () => { + for (const kind of ["needs_user", "budget", "stopped"] as const) { + expect(runEnd(turn({ kind }))).toEqual({ state: "failed", reason: kind, changed: false }); + } + }); + + test("every reason runEnd returns is a routine run reason", () => { + const cases: AloneTurnResult[] = [ + turn({ kind: "final" }), + turn({ kind: "error", code: "max_steps" }), + turn({ kind: "error", code: "repair_failed" }), + turn({ kind: "error", code: "model_error" }), + turn({ kind: "error" }), + turn({ kind: "needs_user" }), + turn({ kind: "budget" }), + turn({ kind: "stopped" }), + ]; + for (const out of cases) { + const { reason } = runEnd(out); + if (reason !== undefined) expect(ROUTINE_RUN_REASONS).toContain(reason); + } + }); +}); + +describe("rosterStatus", () => { + test("the most pressing status wins, in ROSTER_STATUSES order", () => { + expect(rosterStatus({ waiting: 2, results: 3, working: true })).toBe("needs_ok"); + expect(rosterStatus({ waiting: 0, results: 1, working: true })).toBe("new_result"); + expect(rosterStatus({ waiting: 0, results: 0, working: true })).toBe("working"); + expect(rosterStatus({ waiting: 0, results: 0, working: false })).toBeUndefined(); + expect([ + rosterStatus({ waiting: 1, results: 1, working: true }), + rosterStatus({ waiting: 0, results: 1, working: true }), + rosterStatus({ waiting: 0, results: 0, working: true }), + ]).toEqual([...ROSTER_STATUSES]); + }); +}); + +describe("isModeSetting", () => { + test("only the global mode and per-bot mode keys are mode settings", () => { + expect(isModeSetting("bots.mode")).toBe(true); + expect(isModeSetting("bots.mode.b1")).toBe(true); + expect(isModeSetting("bots.modes")).toBe(false); + expect(isModeSetting("bots")).toBe(false); + expect(isModeSetting("bots.mode_x")).toBe(false); + expect(isModeSetting("appearance.theme")).toBe(false); + }); +}); From f7d2794fd4355b67345af3fe22ff463084ff103b Mon Sep 17 00:00:00 2001 From: Saurabh Bhoir <63059109+saurabhbhoir456@users.noreply.github.com> Date: Sun, 6 Dec 2026 14:20:39 +0530 Subject: [PATCH 8/8] test(runtime): cover which cards post a notification (#263) --- packages/runtime/test/bot-notices.test.ts | 162 ++++++++++++++++++++++ 1 file changed, 162 insertions(+) create mode 100644 packages/runtime/test/bot-notices.test.ts diff --git a/packages/runtime/test/bot-notices.test.ts b/packages/runtime/test/bot-notices.test.ts new file mode 100644 index 0000000..6dbe303 --- /dev/null +++ b/packages/runtime/test/bot-notices.test.ts @@ -0,0 +1,162 @@ +import { readFileSync } from "node:fs"; +import type { Bot, BotCard, BotCardKind, BotCardsStore, NewBotCard, NotifierPort } from "@hermit/core"; +import { describe, expect, test } from "vitest"; +import { NOTICE_KEYS, noticeFor, withNotices, type BotNotice } from "../src/bot-notices.ts"; + +const NOW = 1700000000000; +const BOT = { id: "b1", name: "Noticias" }; + +describe("noticeFor", () => { + // Every BotCardKind in packages/core/src/bot-cards-store.ts: the kinds that wait for the user and a result + // tell the user; the folds and check_in stay in the chat. + test("each card kind gives the notice it should, or none", () => { + const expected: Array<[BotCardKind, BotNotice | undefined]> = [ + ["suggestion", "needs_ok"], + ["result", "result"], + ["money_note", "needs_ok"], + ["login_note", "needs_ok"], + ["handoff_fold", undefined], + ["routine_fold", undefined], + ["check_in", undefined], + ]; + for (const [kind, want] of expected) expect(noticeFor(kind), kind).toBe(want); + }); + + test("every NOTICE_KEYS value exists in both locales", () => { + 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; + for (const key of Object.values(NOTICE_KEYS)) expect(copy[key], `${locale} has ${key}`).toBeTypeOf("string"); + } + }); +}); + +function fakeCards(): BotCardsStore { + const cards = new Map(); + return { + async add(card) { + const made: BotCard = { ...card, kinds: [...card.kinds], status: "open", createdAt: NOW, updatedAt: NOW }; + cards.set(card.id, made); + return made; + }, + async get(id) { + return cards.get(id); + }, + async open(botId) { + return [...cards.values()].filter((c) => c.status === "open" && (botId === undefined || c.botId === botId)); + }, + async close(id, status) { + const card = cards.get(id); + if (!card || card.status !== "open") return false; + cards.set(id, { ...card, status }); + return true; + }, + async update(id, fields) { + const card = cards.get(id); + if (!card || card.status !== "open") return false; + cards.set(id, { ...card, fields }); + return true; + }, + }; +} + +interface Scheduled { + id: string; + at: number; + title: string; +} + +function harness(opts: { notify?: boolean; found?: boolean; botThrows?: boolean; scheduleThrows?: boolean } = {}) { + const scheduled: Scheduled[] = []; + const sayCalls: Array<[string, Record]> = []; + const notifier: NotifierPort = { + async schedule(input) { + if (opts.scheduleThrows) throw new Error("notifier down"); + scheduled.push(input); + return input.id; + }, + async cancel() {}, + }; + const bot = { ...BOT, notify: opts.notify ?? true } as unknown as Bot; + const wrapped = withNotices(fakeCards(), { + async bot(id) { + if (opts.botThrows) throw new Error("bot lookup down"); + return opts.found === false || id !== BOT.id ? undefined : bot; + }, + notifier, + say(key, vars) { + sayCalls.push([key, vars]); + return `${key} (${vars.name})`; + }, + now: () => NOW, + }); + return { wrapped, scheduled, sayCalls }; +} + +const card = (kind: BotCardKind, fields: Record = {}): NewBotCard => ({ + id: "c1", + botId: BOT.id, + sessionId: "s1", + kind, + fields, + kinds: [], +}); + +describe("withNotices", () => { + test("a result card schedules one result notice, titled by say from the bot's name only", async () => { + const { wrapped, scheduled, sayCalls } = harness(); + const made = await wrapped.add(card("result", { text: "mensaje secreto de la tarjeta" })); + expect(made.id).toBe("c1"); + expect(scheduled).toEqual([{ id: `bot-${BOT.id}-result`, at: NOW, title: `${NOTICE_KEYS.result} (${BOT.name})` }]); + expect(sayCalls).toEqual([[NOTICE_KEYS.result, { name: BOT.name }]]); + expect(scheduled[0]!.title).not.toContain("mensaje secreto"); + }); + + test("a suggestion card schedules a needs-ok notice", async () => { + const { wrapped, scheduled, sayCalls } = harness(); + await wrapped.add(card("suggestion")); + expect(scheduled).toEqual([{ id: `bot-${BOT.id}-needs-ok`, at: NOW, title: `${NOTICE_KEYS.needs_ok} (${BOT.name})` }]); + expect(sayCalls).toEqual([[NOTICE_KEYS.needs_ok, { name: BOT.name }]]); + }); + + test("a fold card schedules nothing", async () => { + const { wrapped, scheduled, sayCalls } = harness(); + await wrapped.add(card("handoff_fold")); + expect(scheduled).toEqual([]); + expect(sayCalls).toEqual([]); + }); + + test("a bot with notifications off, or one that cannot be found, schedules nothing", async () => { + const off = harness({ notify: false }); + await off.wrapped.add(card("result")); + expect(off.scheduled).toEqual([]); + + const missing = harness({ found: false }); + await missing.wrapped.add(card("result")); + expect(missing.scheduled).toEqual([]); + }); + + test("a failing notifier or bot lookup never fails the card", async () => { + const scheduleBoom = harness({ scheduleThrows: true }); + await expect(scheduleBoom.wrapped.add(card("result"))).resolves.toMatchObject({ id: "c1" }); + expect(scheduleBoom.scheduled).toEqual([]); + + const botBoom = harness({ botThrows: true }); + await expect(botBoom.wrapped.add(card("suggestion"))).resolves.toMatchObject({ id: "c1" }); + expect(botBoom.scheduled).toEqual([]); + }); + + test("the other store methods still reach the store under the wrapper", async () => { + const { wrapped } = harness(); + await wrapped.add(card("result")); + expect(await wrapped.get("c1")).toMatchObject({ id: "c1", status: "open" }); + expect(await wrapped.open()).toHaveLength(1); + expect(await wrapped.open(BOT.id)).toHaveLength(1); + expect(await wrapped.open("other-bot")).toEqual([]); + expect(await wrapped.update("c1", { state: "done" })).toBe(true); + expect((await wrapped.get("c1"))!.fields).toEqual({ state: "done" }); + expect(await wrapped.close("c1", "done")).toBe(true); + expect(await wrapped.get("c1")).toMatchObject({ status: "done" }); + expect(await wrapped.open()).toEqual([]); + expect(await wrapped.close("c1", "done")).toBe(false); + }); +});