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
73 changes: 73 additions & 0 deletions apps/mobile/src/tokens.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
/// <reference types="node" />
// 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}`);
}
}
});
63 changes: 62 additions & 1 deletion packages/core/test/a2a-store.test.ts
Original file line number Diff line number Diff line change
@@ -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";

Expand Down Expand Up @@ -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<TaskState>([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);
});
});
107 changes: 107 additions & 0 deletions packages/mail/test/accounts.test.ts
Original file line number Diff line number Diff line change
@@ -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<typeof resolveAccounts>): 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);
});
});
107 changes: 107 additions & 0 deletions packages/mail/test/mime-helpers.test.ts
Original file line number Diff line number Diff line change
@@ -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<void>((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 <ana@example.com>", 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);
});
});
Loading