diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 271400e..78896db 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -10,7 +10,8 @@ The rules live in [AGENTS.md](AGENTS.md). Read its non-negotiables before your f
- Report a bug, with steps to reproduce and no personal data.
- Propose a feature. Read [VISION.md](VISION.md) first.
- Run Hermit on your phone and send device data: [docs/devices.md](docs/devices.md) explains how.
-- Improve the docs, or the Spanish and English copy.
+- Improve the docs, or the Spanish and English copy. [How copy works](packages/copy/README.md) explains how to add a
+ string.
- Review open pull requests. Reading and running someone's change helps too.
## Set up
diff --git a/apps/mobile/src/tokens.test.ts b/apps/mobile/src/tokens.test.ts
new file mode 100644
index 0000000..e5e23ec
--- /dev/null
+++ b/apps/mobile/src/tokens.test.ts
@@ -0,0 +1,73 @@
+///
+// Hermit's design tokens (docs/design/polish/decisions.md): every color is a docs/brand/tokens.json value, or a mix of
+// two of them (mix): the surfaces between the canvas and white, the tonal fills between a surface and an accent, and
+// the scrims. Light is Quiet craft; dark is Deep sea. The motion tokens live beside them (docs/design/polish/decisions.md,
+// "Motion"): plain numbers, no animation library.
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { mix } from "./theme.ts";
+import { duration, easing, stagger, staggerDelay } from "./motion.ts";
+
+test("mix(a, b, t) holds at a when t is 0 and at b when t is 1", () => {
+ assert.equal(mix("#F5EDE1", "#B4483A", 0), "#F5EDE1");
+ assert.equal(mix("#F5EDE1", "#B4483A", 1), "#B4483A");
+});
+
+test("mix rounds to a whole hex channel at the midpoint", () => {
+ // Half of #000000 → #808080: the blend rounds, it does not truncate.
+ assert.equal(mix("#000000", "#FFFFFF", 0.5), "#808080");
+});
+
+test("mix answers in uppercase #RRGGBB even when the inputs are lowercase", () => {
+ assert.match(mix("#ffffff", "#2b221b", 0.5), /^#[0-9A-F]{6}$/);
+});
+
+test("mix keeps every channel between the two inputs while t is between 0 and 1", () => {
+ const pairs: Array<[string, string]> = [
+ ["#000000", "#FFFFFF"],
+ ["#06121D", "#5EF0CF"],
+ ["#2B221B", "#8A5912"],
+ ];
+ for (const [a, b] of pairs) {
+ for (const t of [0.25, 0.5, 0.75]) {
+ const c = mix(a, b, t);
+ const blend = [0, 1, 2].map((i) => parseInt(c.slice(1 + i * 2, 3 + i * 2), 16));
+ const from = [0, 1, 2].map((i) => parseInt(a.slice(1 + i * 2, 3 + i * 2), 16));
+ const to = [0, 1, 2].map((i) => parseInt(b.slice(1 + i * 2, 3 + i * 2), 16));
+ for (let i = 0; i < 3; i++) {
+ assert.ok(
+ blend[i] >= Math.min(from[i], to[i]) && blend[i] <= Math.max(from[i], to[i]),
+ `channel ${i} of ${c} should stay between ${a} and ${b} at t=${t}`,
+ );
+ }
+ }
+ }
+});
+
+test("staggerDelay spaces items out by one step and stops at stagger.max", () => {
+ assert.equal(staggerDelay(0), 0);
+ assert.equal(staggerDelay(1), stagger.step);
+ assert.equal(staggerDelay(2), stagger.step * 2);
+ assert.equal(staggerDelay(stagger.max - 1), (stagger.max - 1) * stagger.step);
+ assert.equal(staggerDelay(stagger.max), stagger.max * stagger.step);
+ assert.equal(staggerDelay(stagger.max + 4), stagger.max * stagger.step);
+});
+
+test("duration tokens are positive whole milliseconds, a press is instant and sheet is the longest", () => {
+ const values = Object.values(duration);
+ for (const v of values) {
+ assert.ok(Number.isInteger(v), `duration ${v} should be a whole number of milliseconds`);
+ assert.ok(v > 0, `duration ${v} should be positive`);
+ }
+ assert.ok(duration.press < 100, `a press should read as instant, got ${duration.press}`);
+ assert.equal(duration.sheet, Math.max(...values), `sheet should be the longest duration, got ${duration.sheet}`);
+});
+
+test("easing curves are four numbers whose control-x values sit between 0 and 1", () => {
+ for (const curve of Object.values(easing)) {
+ assert.equal(curve.length, 4, `a cubic-bezier needs four numbers, got ${curve.length}`);
+ for (const x of [curve[0], curve[2]]) {
+ assert.ok(x >= 0 && x <= 1, `a cubic-bezier x value should sit between 0 and 1, got ${x}`);
+ }
+ }
+});
diff --git a/apps/site/test/locales.test.ts b/apps/site/test/locales.test.ts
index 4db9acf..0395584 100644
--- a/apps/site/test/locales.test.ts
+++ b/apps/site/test/locales.test.ts
@@ -8,6 +8,11 @@ import { translator } from "../lib/i18n";
const KEY_PATTERN = /^(HM-SITE-\d{2}|common)\.[a-z][a-zA-Z0-9]*$/;
const placeholders = (s: string) => [...s.matchAll(/\{(\w+)\}/g)].map((m) => m[1]).sort();
const all = [...Object.entries(en), ...Object.entries(es)];
+const count = (v: string, ch: string) => v.split(ch).length - 1;
+const hasDoubleSpace = (v: string) => v.includes(" ");
+const hasEdgeSpace = (v: string) => /^[ \t\r\n]|[ \t\r\n]$/.test(v);
+const hasThreeDots = (v: string) => v.includes("...");
+const unbalancedMarks = (v: string) => count(v, "¿") !== count(v, "?") || count(v, "¡") !== count(v, "!");
describe("site copy", () => {
test("both languages define exactly the same keys", () => {
@@ -75,4 +80,32 @@ describe("site copy", () => {
expect(() => translator("en")("HM-SITE-09.nope")).toThrow(/Missing copy key/);
expect(() => translator("en")("HM-SITE-02.updated")).toThrow(/needs \{date\}/);
});
+
+ test("the copy hygiene checks flag made up slips", () => {
+ expect(hasDoubleSpace("hola mundo")).toBe(true);
+ expect(hasDoubleSpace("{count} {unit}")).toBe(false);
+ expect(hasEdgeSpace(" hola")).toBe(true);
+ expect(hasEdgeSpace("hola\n")).toBe(true);
+ expect(hasEdgeSpace("hola\nmundo")).toBe(false);
+ expect(hasThreeDots("espera...")).toBe(true);
+ expect(hasThreeDots("espera…")).toBe(false);
+ expect(unbalancedMarks("¿Cómo estás?")).toBe(false);
+ expect(unbalancedMarks("Cómo estás?")).toBe(true);
+ expect(unbalancedMarks("Hola!")).toBe(true);
+ });
+
+ test("no value in either language of the site has two spaces in a row, edge space or three dots", () => {
+ for (const [k, v] of all) {
+ expect(hasDoubleSpace(v), k).toBe(false);
+ expect(hasEdgeSpace(v), k).toBe(false);
+ expect(hasThreeDots(v), k).toBe(false);
+ }
+ });
+
+ test("in the site Spanish the opening marks match the closing ones in every value", () => {
+ for (const [k, v] of Object.entries(es)) {
+ expect(count(v, "¿"), k).toBe(count(v, "?"));
+ expect(count(v, "¡"), k).toBe(count(v, "!"));
+ }
+ });
});
diff --git a/packages/copy/README.md b/packages/copy/README.md
new file mode 100644
index 0000000..03d9328
--- /dev/null
+++ b/packages/copy/README.md
@@ -0,0 +1,68 @@
+# Copy in Hermit
+
+Every string a person sees in the app is a key in this package: [`locales/en.json`](locales/en.json) and
+[`locales/es-419.json`](locales/es-419.json), read through the translator in [`src/index.ts`](src/index.ts). Spanish
+and English are first class: a string exists in both or it does not exist.
+
+## Naming a key
+
+A key is `HM-XXX-NN.element` for one screen, or `common.*` for a string every screen shares, as `KEY_PATTERN` in
+[`src/index.ts`](src/index.ts) requires. For example `HM-APPR-01.approve` is one screen's string and `common.retry`
+is shared:
+
+```json
+"HM-APPR-01.approve": "Approve with {biometric}",
+"common.retry": "Try again"
+```
+
+## Add a string
+
+1. Name it as above.
+2. Add the same key to both locale files, with the same `{placeholders}` in both. A test holds the two files to
+ exactly the same keys and placeholders.
+3. Use it with `t` from [`apps/mobile/src/i18n.ts`](../../apps/mobile/src/i18n.ts), passing a value for every
+ placeholder: `t("common.retry")`, or `t("HM-APPR-01.approve")` where the phone's biometric name fills
+ `{biometric}` by default.
+
+## When a key or a value is missing
+
+The translator throws a `CopyError` instead of returning an empty string: `Missing copy key ...` for a key that is
+not there, and `Copy key ... needs {name}.` for a placeholder the call did not fill. A forgotten string fails the
+tests instead of shipping blank.
+
+## Counts
+
+`tCount()` in `apps/mobile/src/i18n.ts` says a count right: with a count of 1 it uses the `key.one` form when the
+copy has one, and `key` otherwise. The count fills `{count}` either way. One pair that exists today:
+
+```json
+"HM-SET-02.count": "{count} times",
+"HM-SET-02.count.one": "{count} time"
+```
+
+In Spanish the same pair is `"{count} veces"` and `"{count} vez"`.
+
+## House style
+
+The tests in [`test/copy.test.ts`](test/copy.test.ts) hold the copy to it:
+
+- no em or en dashes in either locale;
+- Latin American Spanish (es-419), and tú, never vos: "Tienes un recordatorio:" (`HM-CHAT-01.reminders.one`), not a
+ voseo form. The tú test names the key it flags.
+- any Spanish the phone reports resolves to es-419, and everything else to English (`resolveLocale`).
+
+## Tests
+
+```sh
+pnpm --filter @hermit/copy test
+pnpm --filter @hermit/mobile test
+```
+
+The first runs this package's tests (key shape, key and placeholder parity, house style, the translator). The
+second includes the test in `apps/mobile/src/copy-keys.test.ts` that every literal key named in the app and package
+source exists in both locales.
+
+## The website
+
+The website has its own locale files in [`apps/site/locales`](../../apps/site/locales), with the same rules: the
+same keys in both, the same placeholders, no em or en dashes, and tú in Spanish. It does not read this package.
diff --git a/packages/copy/test/copy.test.ts b/packages/copy/test/copy.test.ts
index 7303fdf..0e02c15 100644
--- a/packages/copy/test/copy.test.ts
+++ b/packages/copy/test/copy.test.ts
@@ -177,3 +177,66 @@ describe("the biometric's name by platform (issue 128)", () => {
}
});
});
+
+describe("copy hygiene", () => {
+ const count = (v: string, ch: string) => v.split(ch).length - 1;
+ const hasDoubleSpace = (v: string) => v.includes(" ");
+ const hasEdgeSpace = (v: string) => /^[ \t\r\n]|[ \t\r\n]$/.test(v);
+ const hasThreeDots = (v: string) => v.includes("...");
+ const unbalancedMarks = (v: string) => count(v, "¿") !== count(v, "?") || count(v, "¡") !== count(v, "!");
+ const all = [...Object.entries(en), ...Object.entries(es)];
+
+ test("the double space check flags made up slips and leaves single spaces alone", () => {
+ expect(hasDoubleSpace("hola mundo")).toBe(true);
+ expect(hasDoubleSpace("hola mundo")).toBe(false);
+ // The placeholders are not text: single spaces around them are fine.
+ expect(hasDoubleSpace("{count} {unit}")).toBe(false);
+ expect(hasDoubleSpace("hola\nmundo")).toBe(false);
+ });
+
+ test("the edge space check flags a space, tab or line break at either end only", () => {
+ expect(hasEdgeSpace(" hola")).toBe(true);
+ expect(hasEdgeSpace("hola ")).toBe(true);
+ expect(hasEdgeSpace("\thola")).toBe(true);
+ expect(hasEdgeSpace("hola\n")).toBe(true);
+ // A line break inside a value is fine; only the start and the end are checked.
+ expect(hasEdgeSpace("hola\nmundo")).toBe(false);
+ expect(hasEdgeSpace("hola mundo")).toBe(false);
+ });
+
+ test("the three dots check flags three dots and leaves the ellipsis character alone", () => {
+ expect(hasThreeDots("espera...")).toBe(true);
+ expect(hasThreeDots("espera…")).toBe(false);
+ expect(hasThreeDots("uno. dos.")).toBe(false);
+ });
+
+ test("the Spanish marks check flags a question or exclamation with no opening mark", () => {
+ expect(unbalancedMarks("¿Cómo estás?")).toBe(false);
+ expect(unbalancedMarks("¡Hola!")).toBe(false);
+ expect(unbalancedMarks("¿Uno? ¡Dos!")).toBe(false);
+ expect(unbalancedMarks("sin signos")).toBe(false);
+ expect(unbalancedMarks("Cómo estás?")).toBe(true);
+ expect(unbalancedMarks("¿Cómo estás")).toBe(true);
+ expect(unbalancedMarks("Hola!")).toBe(true);
+ expect(unbalancedMarks("¡Hola")).toBe(true);
+ });
+
+ test("no value in either locale has two spaces in a row", () => {
+ for (const [k, v] of all) expect(hasDoubleSpace(v), k).toBe(false);
+ });
+
+ test("no value in either locale starts or ends with a space, tab or line break", () => {
+ for (const [k, v] of all) expect(hasEdgeSpace(v), k).toBe(false);
+ });
+
+ test("no value in either locale has three dots", () => {
+ for (const [k, v] of all) expect(hasThreeDots(v), k).toBe(false);
+ });
+
+ test("in es-419 the opening marks match the closing ones in every value", () => {
+ for (const [k, v] of Object.entries(es)) {
+ expect(count(v, "¿"), k).toBe(count(v, "?"));
+ expect(count(v, "¡"), k).toBe(count(v, "!"));
+ }
+ });
+});
diff --git a/packages/core/src/agent-card.ts b/packages/core/src/agent-card.ts
index e9f9b9d..957b8e7 100644
--- a/packages/core/src/agent-card.ts
+++ b/packages/core/src/agent-card.ts
@@ -1,7 +1,8 @@
import { heldGroups, MAX_BOT_NAME_CHARS, RESERVED_GROUPS, SKILL_GROUPS, type Bot, type SkillGroup } from "./bots.ts";
import { quoteSafe } from "./quote.ts";
-/** A2A 1.0 schema version emitted for in-process bot cards (spec 6.3). */
+/** The version of the card itself, as A2A 1.0 defines `AgentCard.version` ("The version of the agent"). The protocol
+ * version is a binding field (`AgentInterface.protocolVersion`), not this one. */
export const AGENT_CARD_VERSION = "1.0";
export const MAX_CARD_DESCRIPTION_CHARS = 200;
diff --git a/packages/core/test/a2a-store.test.ts b/packages/core/test/a2a-store.test.ts
index ca84579..918c160 100644
--- a/packages/core/test/a2a-store.test.ts
+++ b/packages/core/test/a2a-store.test.ts
@@ -1,6 +1,6 @@
import { beforeEach, describe, expect, test } from "vitest";
import { nodeSql } from "@hermit/sql-node";
-import { createA2aStore, TASK_STATES, type A2aStore, type TaskState } from "../src/a2a-store.ts";
+import { canTransition, createA2aStore, OPEN_TASK_STATES, TASK_STATES, TERMINAL_TASK_STATES, type A2aStore, type TaskState } from "../src/a2a-store.ts";
import { migrate } from "../src/schema.ts";
import type { SqlPort } from "../src/ports.ts";
@@ -313,3 +313,64 @@ describe("a2a store (A2A 1.0, migration 18)", () => {
expect(rejected.status.reason).toBe("hop_cap");
});
});
+
+describe("A2A task states", () => {
+ test("the open and terminal lists hold every state exactly once and share none", () => {
+ const all = [...OPEN_TASK_STATES, ...TERMINAL_TASK_STATES];
+ expect(new Set(all).size).toBe(all.length);
+ expect([...all].sort()).toEqual([...TASK_STATES].sort());
+ for (const state of OPEN_TASK_STATES) {
+ expect(TERMINAL_TASK_STATES).not.toContain(state);
+ }
+ });
+
+ test("a terminal state cannot move anywhere", () => {
+ for (const terminal of TERMINAL_TASK_STATES) {
+ for (const next of TASK_STATES) {
+ expect(canTransition(terminal, next), `${terminal} to ${next}`).toBe(false);
+ }
+ }
+ });
+
+ test("no state moves to itself", () => {
+ for (const state of TASK_STATES) {
+ expect(canTransition(state, state), state).toBe(false);
+ }
+ });
+
+ test("nothing moves back to submitted", () => {
+ for (const state of TASK_STATES) {
+ expect(canTransition(state, "TASK_STATE_SUBMITTED"), state).toBe(false);
+ }
+ });
+
+ test("every open state can reach a terminal state", () => {
+ const reachesTerminal = (start: TaskState): boolean => {
+ const seen = new Set([start]);
+ const queue: TaskState[] = [start];
+ while (queue.length > 0) {
+ const current = queue.shift()!;
+ if (TERMINAL_TASK_STATES.includes(current)) return true;
+ for (const next of TASK_STATES) {
+ if (canTransition(current, next) && !seen.has(next)) {
+ seen.add(next);
+ queue.push(next);
+ }
+ }
+ }
+ return false;
+ };
+ for (const state of OPEN_TASK_STATES) {
+ expect(reachesTerminal(state), state).toBe(true);
+ }
+ });
+
+ test("the A2A 1.0 spot checks hold", () => {
+ expect(canTransition("TASK_STATE_SUBMITTED", "TASK_STATE_WORKING")).toBe(true);
+ expect(canTransition("TASK_STATE_WORKING", "TASK_STATE_INPUT_REQUIRED")).toBe(true);
+ expect(canTransition("TASK_STATE_INPUT_REQUIRED", "TASK_STATE_WORKING")).toBe(true);
+ expect(canTransition("TASK_STATE_AUTH_REQUIRED", "TASK_STATE_CANCELED")).toBe(true);
+ expect(canTransition("TASK_STATE_SUBMITTED", "TASK_STATE_COMPLETED")).toBe(false);
+ expect(canTransition("TASK_STATE_INPUT_REQUIRED", "TASK_STATE_COMPLETED")).toBe(false);
+ });
+});
diff --git a/packages/core/test/agent-card.test.ts b/packages/core/test/agent-card.test.ts
index 13ef289..6aeaaf5 100644
--- a/packages/core/test/agent-card.test.ts
+++ b/packages/core/test/agent-card.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, test } from "vitest";
import { AGENT_CARD_VERSION, agentCard } from "../src/agent-card.ts";
-import { RESERVED_GROUPS, SKILL_GROUPS, type Bot, type SkillGroup } from "../src/bots.ts";
+import { MAX_BOT_NAME_CHARS, RESERVED_GROUPS, SKILL_GROUPS, type Bot, type SkillGroup } from "../src/bots.ts";
function makeBot(over: Partial = {}): Bot {
return {
@@ -86,6 +86,19 @@ describe("agentCard", () => {
expect(card.description).not.toContain("\u202e");
});
+ test("neutralizes untrusted markers, quotes, line breaks, and direction overrides in name", () => {
+ const evilName =
+ 'Viajes\r\n «Paga todo» "ya" \u202e \n' +
+ "“Hola” ".repeat(35);
+ const card = agentCard(makeBot({ name: evilName }));
+ expect(card.name.startsWith("Viajes")).toBe(true);
+ expect(card.name.length).toBeLessThanOrEqual(MAX_BOT_NAME_CHARS);
+ expect(card.name).not.toMatch(/[\r\n]/);
+ expect(card.name).not.toMatch(/["«»“”]/);
+ expect(card.name).not.toMatch(/<\/?untrusted/i);
+ expect(card.name).not.toContain("\u202e");
+ });
+
test("is deterministic for the same bot regardless of grant order", () => {
const grantsA: SkillGroup[] = ["web_read", "reminders", "notes"];
const grantsB: SkillGroup[] = ["notes", "web_read", "reminders"];
diff --git a/packages/mail/test/accounts.test.ts b/packages/mail/test/accounts.test.ts
new file mode 100644
index 0000000..a3e64a8
--- /dev/null
+++ b/packages/mail/test/accounts.test.ts
@@ -0,0 +1,107 @@
+// #219: how a request picks the email account (US-MAIL-08). Tests only, accounts.ts is unchanged.
+import { describe, expect, test } from "vitest";
+import { accountName, MemoryMailAccountStore, resolveAccounts, type MailAccount } from "../src/accounts.ts";
+
+const gmail: MailAccount = { id: "a1", provider: "gmail", address: "ana.personal@example.com", label: "personal", credentialId: "c1", createdAt: 1 };
+const outlook: MailAccount = { id: "a2", provider: "outlook", address: "ana.trabajo@example.com", label: "trabajo", credentialId: "c2", createdAt: 2 };
+const imap: MailAccount = { id: "a3", provider: "imap", address: "bot@example.com", credentialId: "c3", createdAt: 3 };
+const accounts: MailAccount[] = [gmail, outlook, imap];
+
+const ids = (r: ReturnType): string[] => {
+ if (!r.ok) throw new Error(`expected ok, got: ${r.modelText}`);
+ return r.accounts.map((a) => a.id);
+};
+
+describe("accountName (#219)", () => {
+ test("an account with a label reads address and label, one without reads just the address", () => {
+ expect(accountName(gmail)).toBe("ana.personal@example.com (personal)");
+ expect(accountName(imap)).toBe("bot@example.com");
+ });
+});
+
+describe("resolveAccounts (#219)", () => {
+ test("with no accounts connected it is not ok", () => {
+ const r = resolveAccounts([], undefined);
+ expect(r.ok).toBe(false);
+ expect(resolveAccounts([], "ana.personal@example.com").ok).toBe(false);
+ });
+
+ test("with nothing wanted it gives every account in order", () => {
+ for (const wanted of [undefined, "", 42, null, {}]) {
+ expect(ids(resolveAccounts(accounts, wanted))).toEqual(["a1", "a2", "a3"]);
+ }
+ });
+
+ test("an exact address wins in any case and with spaces around it", () => {
+ expect(ids(resolveAccounts(accounts, " ANA.PERSONAL@EXAMPLE.COM "))).toEqual(["a1"]);
+ expect(ids(resolveAccounts(accounts, "bot@example.com"))).toEqual(["a3"]);
+ });
+
+ test("a label matches without accents or case", () => {
+ expect(ids(resolveAccounts(accounts, "Trabajo"))).toEqual(["a2"]);
+ expect(ids(resolveAccounts(accounts, "trabájo"))).toEqual(["a2"]);
+ expect(ids(resolveAccounts(accounts, "PERSONAL"))).toEqual(["a1"]);
+ });
+
+ test("a provider matches by id and by service name", () => {
+ expect(ids(resolveAccounts(accounts, "gmail"))).toEqual(["a1"]);
+ expect(ids(resolveAccounts(accounts, "Gmail"))).toEqual(["a1"]);
+ expect(ids(resolveAccounts(accounts, "outlook"))).toEqual(["a2"]);
+ expect(ids(resolveAccounts(accounts, "Outlook"))).toEqual(["a2"]);
+ expect(ids(resolveAccounts(accounts, "imap"))).toEqual(["a3"]);
+ expect(ids(resolveAccounts(accounts, "Email (IMAP)"))).toEqual(["a3"]);
+ });
+
+ test("when a higher tier matches a lower tier is never mixed in", () => {
+ const labelled: MailAccount = { id: "a9", provider: "imap", address: "owner@example.com", label: "viajes", credentialId: "c9", createdAt: 9 };
+ const inAddress: MailAccount = { id: "a8", provider: "gmail", address: "viajes.owner@example.com", credentialId: "c8", createdAt: 8 };
+ expect(ids(resolveAccounts([inAddress, labelled], "viajes"))).toEqual(["a9"]);
+ // An exact address also wins over a label that is part of the same words.
+ expect(ids(resolveAccounts(accounts, "ana.trabajo@example.com"))).toEqual(["a2"]);
+ });
+
+ test("a part of an address or label matches when nothing exact does", () => {
+ expect(ids(resolveAccounts(accounts, "personal@"))).toEqual(["a1"]);
+ expect(ids(resolveAccounts(accounts, "trab"))).toEqual(["a2"]);
+ expect(ids(resolveAccounts(accounts, "bot@exam"))).toEqual(["a3"]);
+ });
+
+ test("no match is not ok, names the connected accounts and cuts what was wanted to 100 characters", () => {
+ const r = resolveAccounts(accounts, "no-existe@example.com");
+ if (r.ok) throw new Error("expected a refusal");
+ expect(r.modelText).toContain(accountName(gmail));
+ expect(r.modelText).toContain(accountName(outlook));
+ expect(r.modelText).toContain(accountName(imap));
+ expect(r.modelText).toContain("no-existe@example.com");
+
+ const long = resolveAccounts(accounts, "x".repeat(150));
+ if (long.ok) throw new Error("expected a refusal");
+ expect(long.modelText).toContain(`"${"x".repeat(100)}"`);
+ expect(long.modelText).not.toContain("x".repeat(101));
+ });
+});
+
+describe("MemoryMailAccountStore (#219)", () => {
+ test("save replaces by id, get and list return copies, delete reports what it removed", async () => {
+ const store = new MemoryMailAccountStore();
+ await store.save(gmail);
+ await store.save({ ...gmail, label: "nueva" });
+ expect((await store.get("a1"))?.label).toBe("nueva");
+ expect(await store.list()).toHaveLength(1);
+
+ const got = (await store.get("a1"))!;
+ got.label = "changed";
+ got.address = "changed@example.com";
+ expect((await store.get("a1"))?.label).toBe("nueva");
+ expect((await store.get("a1"))?.address).toBe(gmail.address);
+
+ const listed = await store.list();
+ listed[0]!.label = "changed again";
+ expect((await store.get("a1"))?.label).toBe("nueva");
+
+ expect(await store.get("missing")).toBeUndefined();
+ expect(await store.delete("a1")).toBe(true);
+ expect(await store.get("a1")).toBeUndefined();
+ expect(await store.delete("a1")).toBe(false);
+ });
+});
diff --git a/packages/mail/test/mime-helpers.test.ts b/packages/mail/test/mime-helpers.test.ts
new file mode 100644
index 0000000..213eefe
--- /dev/null
+++ b/packages/mail/test/mime-helpers.test.ts
@@ -0,0 +1,107 @@
+// #220: the small mail helpers called by name: the RFC 5322 date, base64, the forward text and batched runs. Tests only.
+import { describe, expect, test } from "vitest";
+import { inBatches } from "../src/http.ts";
+import { bytesToBase64, forwardText, mailDate } from "../src/mime.ts";
+import { base64ToBytes } from "../src/text.ts";
+
+const wait = (ms: number) => new Promise((resolve) => { setTimeout(resolve, ms); });
+
+describe("mailDate (#220)", () => {
+ test("a fixed instant gives the RFC 5322 date in UTC", () => {
+ expect(mailDate(Date.UTC(2026, 10, 14, 15, 0, 0))).toBe("Sat, 14 Nov 2026 15:00:00 +0000");
+ });
+
+ test("a single digit day, hour, minute and second are zero padded", () => {
+ expect(mailDate(Date.UTC(2026, 0, 5, 4, 3, 2))).toBe("Mon, 05 Jan 2026 04:03:02 +0000");
+ });
+});
+
+describe("bytesToBase64 (#220)", () => {
+ test("inputs of 0, 1, 2 and 3 bytes give the right padding", () => {
+ expect(bytesToBase64(new Uint8Array([]))).toBe("");
+ expect(bytesToBase64(new Uint8Array([0x66]))).toBe("Zg==");
+ expect(bytesToBase64(new Uint8Array([0x66, 0x6f]))).toBe("Zm8=");
+ expect(bytesToBase64(new Uint8Array([0x66, 0x6f, 0x6f]))).toBe("Zm9v");
+ });
+
+ test("with url the result uses minus and underscore and has no padding", () => {
+ const bytes = new Uint8Array([0xfb, 0xff, 0xfe]);
+ expect(bytesToBase64(bytes)).toBe("+//+");
+ expect(bytesToBase64(bytes, true)).toBe("-__-");
+ expect(bytesToBase64(new Uint8Array([0xfb]), true)).toBe("-w");
+ expect(bytesToBase64(new Uint8Array([0xfb]), true)).not.toContain("=");
+ expect(bytesToBase64(bytes, true)).not.toContain("+");
+ expect(bytesToBase64(bytes, true)).not.toContain("/");
+ });
+
+ test("a round trip with base64ToBytes gives the same bytes back", () => {
+ for (const bytes of [new Uint8Array([]), new Uint8Array([0x66]), new Uint8Array([0x66, 0x6f, 0x6f]), new Uint8Array([0xfb, 0xff, 0xfe, 0x00, 0x80])]) {
+ expect(base64ToBytes(bytesToBase64(bytes))).toEqual(bytes);
+ expect(base64ToBytes(bytesToBase64(bytes, true))).toEqual(bytes);
+ }
+ });
+});
+
+describe("forwardText (#220)", () => {
+ const original = { from: "Ana ", to: ["luis@example.com"], subject: "Hola", date: "Sat, 14 Nov 2026 15:00:00 +0000", text: "Nos vemos mañana." };
+
+ test("with a note the note comes first and then a blank line", () => {
+ const text = forwardText(" Mira esto. ", original);
+ expect(text.startsWith("Mira esto.\n\n---------- Forwarded message ----------")).toBe(true);
+ });
+
+ test("with a blank note there is no leading blank line", () => {
+ const text = forwardText(" ", original);
+ expect(text.startsWith("---------- Forwarded message ----------")).toBe(true);
+ expect(text.startsWith("\n")).toBe(false);
+ });
+
+ test("a To line appears only when to has addresses", () => {
+ expect(forwardText("", original)).toContain("\nTo: luis@example.com\n");
+ expect(forwardText("", { ...original, to: [] })).not.toContain("\nTo:");
+ });
+
+ test("a line break inside from or subject cannot start a new line", () => {
+ const text = forwardText("", { ...original, from: "Ana\nBcc: evil@example.com", subject: "Hola\r\nInjected: si" });
+ const lines = text.split("\n");
+ expect(lines.some((l) => l.startsWith("Bcc:"))).toBe(false);
+ expect(lines.some((l) => l.startsWith("Injected:"))).toBe(false);
+ expect(lines.find((l) => l.startsWith("From: "))).toBe("From: Ana Bcc: evil@example.com");
+ expect(lines.find((l) => l.startsWith("Subject:"))).toBe("Subject: Hola Injected: si");
+ });
+});
+
+describe("inBatches (#220)", () => {
+ test("results keep the order of the input even when later tasks finish first", async () => {
+ const out = await inBatches([1, 2, 3, 4, 5], 5, async (n) => {
+ await wait((6 - n) * 10);
+ return n * 10;
+ });
+ expect(out).toEqual([10, 20, 30, 40, 50]);
+ });
+
+ test("no more than the limit run at once", async () => {
+ let active = 0;
+ let peak = 0;
+ const out = await inBatches([1, 2, 3, 4, 5, 6, 7, 8], 2, async (n) => {
+ active++;
+ peak = Math.max(peak, active);
+ await wait(15);
+ active--;
+ return n;
+ });
+ expect(out).toEqual([1, 2, 3, 4, 5, 6, 7, 8]);
+ expect(peak).toBeLessThanOrEqual(2);
+ expect(peak).toBe(2);
+ });
+
+ test("an empty list gives an empty list without calling the task", async () => {
+ let calls = 0;
+ const out = await inBatches([], 3, async (n: number) => {
+ calls++;
+ return n;
+ });
+ expect(out).toEqual([]);
+ expect(calls).toBe(0);
+ });
+});
diff --git a/packages/mail/test/mime-read.test.ts b/packages/mail/test/mime-read.test.ts
index e1b63a9..13eee17 100644
--- a/packages/mail/test/mime-read.test.ts
+++ b/packages/mail/test/mime-read.test.ts
@@ -1,7 +1,7 @@
import { describe, expect, it } from "vitest";
import { binaryString } from "../src/mail-socket.ts";
import { utf8Encode } from "../src/mime.ts";
-import { decodeHeader, mailHeaderDate, quotedPrintable, readMessage } from "../src/mime-read.ts";
+import { decodeCharset, decodeHeader, headerParams, mailHeaderDate, quotedPrintable, readMessage } from "../src/mime-read.ts";
/** A message as IMAP hands it over: bytes, here as a binary string. */
const raw = (text: string) => binaryString(utf8Encode(text.replace(/\n/g, "\r\n")));
@@ -108,3 +108,78 @@ describe("reading a raw message (FR-MAIL-02, IMAP accounts)", () => {
expect(binaryString(quotedPrintable("a=3Db=\r\nc = d=ZZ"))).toBe("a=bc = d=ZZ");
});
});
+
+describe("decodeCharset (#221)", () => {
+ const enc = new TextEncoder();
+
+ it("with utf-8 in any case and with spaces it decodes UTF-8", () => {
+ for (const cs of ["utf-8", "UTF8", " UtF-8 "]) {
+ expect(decodeCharset(enc.encode("señal"), cs)).toBe("señal");
+ expect(decodeCharset(enc.encode("acción"), cs)).toBe("acción");
+ expect(decodeCharset(enc.encode("hola 🦀"), cs)).toBe("hola 🦀");
+ }
+ });
+
+ it("with iso-8859-1, latin1 and windows-1252 the high bytes read as Windows-1252", () => {
+ const latin1 = Uint8Array.from([0x73, 0x65, 0xf1, 0x61, 0x6c]);
+ for (const cs of ["iso-8859-1", "latin1", "windows-1252"]) {
+ expect(decodeCharset(latin1, cs)).toBe("señal");
+ expect(decodeCharset(Uint8Array.from([0x80]), cs)).toBe("€");
+ expect(decodeCharset(Uint8Array.from([0x93, 0x94]), cs)).toBe("“”");
+ }
+ });
+
+ it("with no charset, or one it does not know, valid UTF-8 reads as UTF-8 and anything else falls back to Windows-1252", () => {
+ const utf8 = enc.encode("acción 🦀");
+ const latin1 = Uint8Array.from([0x73, 0x65, 0xf1, 0x61, 0x6c]);
+ for (const cs of [undefined, "x-unknown-charset"]) {
+ expect(decodeCharset(utf8, cs)).toBe("acción 🦀");
+ const fallen = decodeCharset(latin1, cs);
+ expect(fallen).toBe("señal");
+ expect(fallen).not.toContain("�");
+ }
+ });
+});
+
+describe("headerParams (#221)", () => {
+ it("splits the value from its parameters", () => {
+ const r = headerParams("text/plain; charset=UTF-8");
+ expect(r.value).toBe("text/plain");
+ expect(r.params.get("charset")).toBe("UTF-8");
+ });
+
+ it("lowercases the value and the parameter names but keeps the case of parameter values", () => {
+ const r = headerParams("TEXT/Plain; CHARSET=UTF-8; Name=Notas.TXT");
+ expect(r.value).toBe("text/plain");
+ expect(r.params.get("charset")).toBe("UTF-8");
+ expect(r.params.get("name")).toBe("Notas.TXT");
+ });
+
+ it("a semicolon inside quotes does not split and a backslash escape keeps the next character", () => {
+ // Today the quotes around a quoted value are dropped; pin it here so changing it is a choice made on purpose.
+ const r = headerParams('text/plain; name="a;b"; other="x\\"y;z"');
+ expect(r.params.get("name")).toBe("a;b");
+ expect(r.params.get("other")).toBe('x"y;z');
+ expect(r.params.size).toBe(2);
+ });
+
+ it("a repeated parameter keeps the first, a piece with no equals sign is skipped, and undefined gives nothing", () => {
+ const r = headerParams("text/plain; charset=UTF-8; foo; charset=iso-8859-1");
+ expect(r.params.get("charset")).toBe("UTF-8");
+ expect(r.params.has("foo")).toBe(false);
+ expect(r.params.size).toBe(1);
+
+ const none = headerParams(undefined);
+ expect(none.value).toBe("");
+ expect(none.params.size).toBe(0);
+ });
+
+ it("only the first 31 parameters are read", () => {
+ const many = `text/plain${Array.from({ length: 40 }, (_, i) => `; p${i}=v${i}`).join("")}`;
+ const r = headerParams(many);
+ expect(r.params.size).toBe(31);
+ expect(r.params.get("p0")).toBe("v0");
+ expect(r.params.get("p30")).toBe("v30");
+ expect(r.params.has("p31")).toBe(false);
+ });
+});
diff --git a/packages/night/test/settings.test.ts b/packages/night/test/settings.test.ts
index e1e4e58..aaa721d 100644
--- a/packages/night/test/settings.test.ts
+++ b/packages/night/test/settings.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, test } from "vitest";
import {
- blockers, briefingDate, briefingTime, DEFAULT_NIGHT_SETTINGS, inWindow, nextWindowStart, parseNightSettings, UNKNOWN_DEVICE, validateNightSettings,
+ blockers, briefingDate, briefingTime, DEFAULT_NIGHT_SETTINGS, inWindow, localMinutes, nextWindowStart, parseNightSettings, UNKNOWN_DEVICE, validateNightSettings,
type DeviceState, type NightSettings,
} from "../src/index.ts";
@@ -53,6 +53,81 @@ describe("night shift settings (HM-NIGHT-01, US-NIGHT-01)", () => {
});
});
+describe("the window and the briefing on the nights the clock changes (#222)", () => {
+ const w = { start: "23:00", end: "05:00" };
+ const NY = "America/New_York";
+ const SANTIAGO = "America/Santiago";
+
+ test("New York in spring: inWindow at local 01:30 and 03:30 on March 8, and not at 05:30", () => {
+ // 2026-03-08T06:30Z is local 01:30 EST; the clock jumps 02:00 to 03:00 at 07:00Z.
+ expect(inWindow(Date.UTC(2026, 2, 8, 6, 30), NY, w)).toBe(true);
+ // 2026-03-08T07:30Z is local 03:30 EDT.
+ expect(inWindow(Date.UTC(2026, 2, 8, 7, 30), NY, w)).toBe(true);
+ // 2026-03-08T09:30Z is local 05:30 EDT, past the window end.
+ expect(inWindow(Date.UTC(2026, 2, 8, 9, 30), NY, w)).toBe(false);
+ });
+
+ test("New York in autumn: inWindow at local 01:30 and 03:30 on November 1, and not at 05:30", () => {
+ // 2026-11-01T05:30Z is local 01:30 EDT; the clock falls back 02:00 to 01:00 at 06:00Z.
+ expect(inWindow(Date.UTC(2026, 10, 1, 5, 30), NY, w)).toBe(true);
+ // 2026-11-01T06:30Z is local 01:30 EST, the repeated hour.
+ expect(inWindow(Date.UTC(2026, 10, 1, 6, 30), NY, w)).toBe(true);
+ // 2026-11-01T08:30Z is local 03:30 EST.
+ expect(inWindow(Date.UTC(2026, 10, 1, 8, 30), NY, w)).toBe(true);
+ // 2026-11-01T10:30Z is local 05:30 EST, past the window end.
+ expect(inWindow(Date.UTC(2026, 10, 1, 10, 30), NY, w)).toBe(false);
+ });
+
+ test("New York: briefingTime gives 07:00 local with each change morning offset", () => {
+ expect(briefingTime("2026-03-08", "07:00", NY)).toBe(Date.UTC(2026, 2, 8, 11, 0)); // local 07:00 EDT
+ expect(briefingTime("2026-11-01", "07:00", NY)).toBe(Date.UTC(2026, 10, 1, 12, 0)); // local 07:00 EST
+ });
+
+ test("New York: nextWindowStart from local noon on a change day gives 23:00 local that evening", () => {
+ // 2026-03-08T16:00Z is local noon EDT; that evening 23:00 local is 2026-03-09T03:00Z.
+ expect(nextWindowStart(Date.UTC(2026, 2, 8, 16, 0), NY, w)).toBe(Date.UTC(2026, 2, 9, 3, 0));
+ // 2026-11-01T17:00Z is local noon EST; that evening 23:00 local is 2026-11-02T04:00Z.
+ expect(nextWindowStart(Date.UTC(2026, 10, 1, 17, 0), NY, w)).toBe(Date.UTC(2026, 10, 2, 4, 0));
+ });
+
+ test("New York: localMinutes is 90 for both instants that read 01:30 on November 1", () => {
+ expect(localMinutes(Date.UTC(2026, 10, 1, 5, 30), NY)).toBe(90); // local 01:30 EDT
+ expect(localMinutes(Date.UTC(2026, 10, 1, 6, 30), NY)).toBe(90); // local 01:30 EST
+ });
+
+ test("Santiago in autumn: inWindow at local 23:30 and 02:00 on the night of April 4 to 5", () => {
+ // 2026-04-05T02:30Z is local 23:30 on April 4 (UTC-3); the clock goes back to 23:00 (UTC-4) at 03:00Z.
+ expect(inWindow(Date.UTC(2026, 3, 5, 2, 30), SANTIAGO, w)).toBe(true);
+ // 2026-04-05T03:30Z is local 23:30 on April 4 again (UTC-4), the repeated hour.
+ expect(inWindow(Date.UTC(2026, 3, 5, 3, 30), SANTIAGO, w)).toBe(true);
+ // 2026-04-05T06:00Z is local 02:00 on April 5 (UTC-4).
+ expect(inWindow(Date.UTC(2026, 3, 5, 6, 0), SANTIAGO, w)).toBe(true);
+ });
+
+ test("Santiago in spring: inWindow at local 23:30 and 02:00 on the night of September 5 to 6", () => {
+ // 2026-09-06T03:30Z is local 23:30 on September 5 (UTC-4); the clock jumps 00:00 to 01:00 at 04:00Z.
+ expect(inWindow(Date.UTC(2026, 8, 6, 3, 30), SANTIAGO, w)).toBe(true);
+ // 2026-09-06T05:00Z is local 02:00 on September 6 (UTC-3).
+ expect(inWindow(Date.UTC(2026, 8, 6, 5, 0), SANTIAGO, w)).toBe(true);
+ });
+
+ test("Santiago: briefingDate for an instant inside the window is the morning the window ends on", () => {
+ // 2026-04-05T03:30Z is local 23:30 on April 4; its night ends the morning of April 5.
+ expect(briefingDate(Date.UTC(2026, 3, 5, 3, 30), SANTIAGO, w)).toBe("2026-04-05");
+ // 2026-04-05T06:00Z is local 02:00 on April 5.
+ expect(briefingDate(Date.UTC(2026, 3, 5, 6, 0), SANTIAGO, w)).toBe("2026-04-05");
+ // 2026-09-06T03:30Z is local 23:30 on September 5; its night ends the morning of September 6.
+ expect(briefingDate(Date.UTC(2026, 8, 6, 3, 30), SANTIAGO, w)).toBe("2026-09-06");
+ // 2026-09-06T05:00Z is local 02:00 on September 6.
+ expect(briefingDate(Date.UTC(2026, 8, 6, 5, 0), SANTIAGO, w)).toBe("2026-09-06");
+ });
+
+ test("Santiago: briefingTime gives 07:00 local the next morning with that morning offset", () => {
+ expect(briefingTime("2026-04-05", "07:00", SANTIAGO)).toBe(Date.UTC(2026, 3, 5, 11, 0)); // local 07:00 (UTC-4)
+ expect(briefingTime("2026-09-06", "07:00", SANTIAGO)).toBe(Date.UTC(2026, 8, 6, 10, 0)); // local 07:00 (UTC-3)
+ });
+});
+
describe("device guards (FR-NIGHT-01, NFR-04, US-NIGHT-04)", () => {
test("all clear while charging, cool, above the floor, screen off, on Wi-Fi", () => {
expect(blockers(ok, { needsNetwork: true })).toEqual([]);