Skip to content
Merged
7 changes: 3 additions & 4 deletions apps/mobile/src/app/bot-new.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,8 @@ import { useLocalSearchParams, useRouter } from "expo-router";
import { useEffect, useMemo, useState } from "react";
import { View } from "react-native";
import type { PermissionMode } from "@hermit/core";
import { MAX_BOT_NAME_CHARS } from "@hermit/core/bots";
import type { BotProposalView } from "@hermit/runtime";
import { BOT_TEMPLATES, fromProposal, fromTemplate, formNeedsFingerprint, formProblems, toNewBot, type BotForm, type BotTemplateId } from "../bot-form-view";
import { BOT_TEMPLATES, capBotName, fromProposal, fromTemplate, formNeedsFingerprint, formProblems, toNewBot, type BotForm, type BotTemplateId } from "../bot-form-view";
import { BLANK_LOOK, TEMPLATE_LOOKS } from "../bot-templates";
import { BotAvatar } from "../components/BotAvatar";
import { ModeSheet } from "../components/ModeSheet";
Expand Down Expand Up @@ -136,10 +135,10 @@ export default function BotNew() {
<Input
label={t("HM-BOT-03.name")}
value={f.name}
onChange={(name) => edit({ name })}
onChange={(name) => edit({ name: capBotName(name) })}
invalid={problems.includes("name_too_long")}
style={{ flex: 1 }}
field={{ autoCapitalize: "words", maxLength: MAX_BOT_NAME_CHARS }}
field={{ autoCapitalize: "words" }}
/>
</View>
{problems.includes("name_too_long") ? <Refusal reason="name_too_long" name={f.name.trim()} /> : null}
Expand Down
5 changes: 2 additions & 3 deletions apps/mobile/src/app/bot-settings.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,8 @@
import { useLocalSearchParams, useRouter } from "expo-router";
import { useCallback, useEffect, useState } from "react";
import { AccessibilityInfo, View } from "react-native";
import { MAX_BOT_NAME_CHARS } from "@hermit/core/bots";
import { HERMIT_BOT_ID, type Bot, type MemoryCursor, type Note as Fact, type PermissionMode } from "@hermit/core";
import { formNeedsFingerprint, formPatch, formProblems, fromBot, noteActions, settingsResult, type BotForm } from "../bot-form-view";
import { capBotName, formNeedsFingerprint, formPatch, formProblems, fromBot, noteActions, settingsResult, type BotForm } from "../bot-form-view";
import { forgetBotCaches } from "../adapters";
import { BotAvatar } from "../components/BotAvatar";
import { ConfirmSheet, ConnectorsList, GroupsList, LookPicker, Refusal, modeLine, useSourceChoices } from "../components/BotFormParts";
Expand Down Expand Up @@ -230,7 +229,7 @@ export default function BotSettings() {
{hermitBot ? (
<T v="body" color="soft" style={{ flex: 1 }}>{t("HM-BOT-04.hermitRole")}</T>
) : (
<Input label={t("HM-BOT-03.name")} value={form.name} onChange={(name) => edit({ name })} invalid={problems.includes("name_too_long") || problems.includes("name_empty")} style={{ flex: 1 }} field={{ autoCapitalize: "words", maxLength: MAX_BOT_NAME_CHARS }} />
<Input label={t("HM-BOT-03.name")} value={form.name} onChange={(name) => edit({ name: capBotName(name) })} invalid={problems.includes("name_too_long") || problems.includes("name_empty")} style={{ flex: 1 }} field={{ autoCapitalize: "words" }} />
)}
</View>
{problems.includes("name_empty") ? <Refusal reason="name_empty" name={bot.name} /> : null}
Expand Down
14 changes: 13 additions & 1 deletion apps/mobile/src/bot-form-view.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { readFileSync } from "node:fs";
import { RESERVED_GROUPS, SKILL_GROUPS, type BotLook } from "@hermit/core/bots";
import type { BotProposalView } from "../../../packages/runtime/src/bot-api.ts";
import { BOT_REFUSALS } from "../../../packages/runtime/src/bot-api.ts";
import { BOT_TEMPLATES, formPatch, fromBot, fromProposal, fromTemplate, formNeedsFingerprint, formProblems, noteActions, proposalCard, refusalLine, settingsResult, shownGroups, toNewBot, type BotForm } from "./bot-form-view.ts";
import { BOT_TEMPLATES, capBotName, formPatch, fromBot, fromProposal, fromTemplate, formNeedsFingerprint, formProblems, noteActions, proposalCard, refusalLine, settingsResult, shownGroups, toNewBot, type BotForm } from "./bot-form-view.ts";

const LOOK: BotLook = { shape: "whelk", color: "sand" };
const form = (over: Partial<BotForm> = {}): BotForm => ({ name: "Viajes", role: "Planeas los viajes de la familia Prueba.", look: LOOK, grants: ["web_read", "notes"], sites: "wikivoyage.org", connectors: [], mode: null, ...over });
Expand All @@ -18,6 +18,18 @@ test("HM-BOT-03: the form's problems match the runtime's limits", () => {
assert.deepEqual(formProblems(form({ name: "n".repeat(41), role: "r".repeat(801), sites: "wikivoyage.org, 192.168.0.1" })), ["name_too_long", "role_too_long", "bad_site"]);
assert.deepEqual(formProblems(form()), []);
});
test("HM-BOT-03: a bot name is capped at 40 code points, keeping emoji whole", () => {
assert.equal(capBotName("😀".repeat(40)), "😀".repeat(40));
assert.equal(capBotName("😀".repeat(41)), "😀".repeat(40));
assert.equal(capBotName("n".repeat(41)), "n".repeat(40));
assert.equal(capBotName("Viajes"), "Viajes");
});

test("HM-BOT-03: a role of 800 emoji passes, 801 does not", () => {
assert.deepEqual(formProblems(form({ role: "😀".repeat(800) })), []);
assert.deepEqual(formProblems(form({ role: "😀".repeat(801) })), ["role_too_long"]);
});

test("HM-BOT-03: the fingerprint for mail send, logins, pay or Don't ask, and only when newly granted", () => {
assert.equal(formNeedsFingerprint(form({ grants: ["mail_read"] })), false);
assert.equal(formNeedsFingerprint(form({ grants: ["mail_send"] })), true);
Expand Down
7 changes: 6 additions & 1 deletion apps/mobile/src/bot-form-view.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,16 @@ export function formProblems(f: BotForm): Array<"name_empty" | "name_too_long" |
const name = f.name.trim();
if (!name) out.push("name_empty");
else if ([...name].length > MAX_BOT_NAME_CHARS) out.push("name_too_long");
if (f.role.trim().length > MAX_ROLE_CHARS) out.push("role_too_long");
if ([...f.role.trim()].length > MAX_ROLE_CHARS) out.push("role_too_long");
if (siteWords(f.sites).some((w) => normalizeSite(w) === undefined)) out.push("bad_site");
return out;
}

/** Cap a typed bot name at MAX_BOT_NAME_CHARS code points, keeping emoji whole. React Native's `maxLength` counts UTF-16 units, so it stops a name of 40 emoji at 20; this caps by code point instead, like the store does. */
export function capBotName(text: string): string {
return [...text].slice(0, MAX_BOT_NAME_CHARS).join("");
}

/**
* Task 1's one rule as the runtime applies it: on the bot's own mode only. A null mode ("Como el resto") brings no Don't
* ask of its own, whatever the global mode is (the global took the word and the fingerprint when it was set), so
Expand Down
10 changes: 5 additions & 5 deletions apps/site/locales/es-419.json
Original file line number Diff line number Diff line change
Expand Up @@ -140,13 +140,13 @@
"HM-SITE-01.sourceBody": "Hermit es de código abierto bajo Apache 2.0. La jaula que revisa cada acción, los controles de privacidad que hacen fallar la compilación, las evaluaciones y este sitio viven en un solo repositorio público.",
"HM-SITE-01.sourceContribute": "Contribuir",
"HM-SITE-01.sourceCodeLabel": "Descarga el código y corre los controles de privacidad",
"HM-SITE-01.labKicker": "Laboratorio de dispositivos",
"HM-SITE-01.labKicker": "Laboratorio del teléfono",
"HM-SITE-01.labTitle": "Ayúdanos a que Hermit sea rápido en cada teléfono.",
"HM-SITE-01.labBody": "Hermit corre un modelo pequeño en el propio teléfono, y cada teléfono es distinto. Corre la prueba de rendimiento en el tuyo y comparte el reporte. Cada uno muestra dónde le falta trabajo a Hermit.",
"HM-SITE-01.labBody": "Hermit corre un modelo pequeño en el propio teléfono, y cada teléfono es distinto. Corre la prueba de rendimiento en el tuyo y comparte el informe. Cada uno muestra dónde le falta trabajo a Hermit.",
"HM-SITE-01.labStep1Title": "Corre la prueba",
"HM-SITE-01.labStep1Body": "Mide al modelo en tu teléfono y revisa sus respuestas.",
"HM-SITE-01.labStep2Title": "Lee el reporte",
"HM-SITE-01.labStep2Body": "Nada sale de tu teléfono por su cuenta. Tú ves el reporte antes que nadie.",
"HM-SITE-01.labStep2Title": "Lee el informe",
"HM-SITE-01.labStep2Body": "Nada sale de tu teléfono por su cuenta. Tú ves el informe antes que nadie.",
"HM-SITE-01.labStep3Title": "Compártelo",
"HM-SITE-01.labStep3Body": "Súbelo al repositorio, como explica la guía.",
"HM-SITE-01.labCta": "Leer la guía de dispositivos",
Expand All @@ -155,7 +155,7 @@
"HM-SITE-01.getKicker": "Consigue Hermit",
"HM-SITE-01.getTitleA": "Hecho a la vista de todos.",
"HM-SITE-01.getTitleB": "Rumbo a las tiendas.",
"HM-SITE-01.getBody": "Hermit está en pre-alfa y todavía no está en las tiendas. Los APK de vista previa para Android están en GitHub Releases: instala uno, corre el Laboratorio del teléfono y envía su reporte. Dale una estrella al repositorio para seguirlo, o compílalo desde el código.",
"HM-SITE-01.getBody": "Hermit está en pre-alfa y todavía no está en las tiendas. Los APK de vista previa para Android están en GitHub Releases: instala uno, corre el Laboratorio del teléfono y envía su informe. Dale una estrella al repositorio para seguirlo, o compílalo desde el código.",
"HM-SITE-01.getSource": "Compilarlo desde el código",
"HM-SITE-01.getApk": "Descargar el APK de vista previa",
"HM-SITE-01.peekAlt": "Hermit asomándose desde adentro de su concha",
Expand Down
13 changes: 13 additions & 0 deletions apps/site/test/locales.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import { describe, expect, test } from "vitest";
import en from "../locales/en.json";
import es from "../locales/es-419.json";
import appEn from "../../../packages/copy/locales/en.json";
import appEs from "../../../packages/copy/locales/es-419.json";
import { translator } from "../lib/i18n";

const KEY_PATTERN = /^(HM-SITE-\d{2}|common)\.[a-z][a-zA-Z0-9]*$/;
Expand Down Expand Up @@ -53,6 +55,17 @@ describe("site copy", () => {
}
});

test("the lab's kicker is the name the app gives the Device lab, in both languages", () => {
expect(en["HM-SITE-01.labKicker"]).toBe(appEn["HM-SET-10.title"]);
expect(es["HM-SITE-01.labKicker"]).toBe(appEs["HM-SET-10.title"]);
});

test("in Spanish the lab's report is an informe, as in the app, and the lab is never a laboratorio de dispositivos", () => {
for (const k of ["HM-SITE-01.labBody", "HM-SITE-01.labStep2Title", "HM-SITE-01.labStep2Body", "HM-SITE-01.getBody"] as const) {
expect(es[k], k).not.toMatch(/reporte|laboratorio de dispositivos/i);
}
});

test("USD₮ is the only money the copy names", () => {
for (const [k, v] of all) expect(v, k).not.toMatch(/\bUSDC\b|\bUSDT\b|stablecoin|\bETH\b|bitcoin/i);
});
Expand Down
39 changes: 39 additions & 0 deletions packages/copy/test/copy.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,45 @@ describe("locale files (CT-10)", () => {
});
});

// AGENTS.md rule 9: the app's Spanish uses tú. Only voseo forms that can't be read another way are listed, so
// "elegí" or "escribí" (also the first person past tense) stay out. \b doesn't count accented letters as letters,
// so the edges are (?<!\p{L}) and (?!\p{L}).
const VOSEO_FORMS = [
"podés", "tenés", "querés", "sabés", "hacés", "decís", "necesitás", "preferís", "tocá", "mirá", "probá", "activá", "revisá",
"volvé", "poné", "usá", "agregá", "cambiá", "guardá", "confirmá", "dejá", "buscá", "esperá", "fijate", "acordate", "decime",
"avisame", "mandale", "contame",
];
const VOSEO = new RegExp(`(?<!\\p{L})(?:${VOSEO_FORMS.join("|")})(?!\\p{L})`, "iu");

describe("tú, not vos (AGENTS.md rule 9)", () => {
test("the matcher flags voseo", () => {
for (const s of [
"Tocá el botón", "Si querés, te aviso", "¿Podés esperar?", "Ya tenés todo.", "Si sabés la hora, dime.", "¿Qué hacés?",
"Decís que sí.", "Si necesitás algo, escribe.", "Si preferís, después.", "Mirá esto.", "Probá de nuevo.", "Activá las notificaciones.",
"Revisá el correo.", "Volvé a la lista.", "Poné tu huella.", "Usá la otra cuenta.", "Agregá un recordatorio.", "Cambiá la hora.",
"Guardá el cambio.", "Confirmá el pago.", "Dejá un mensaje.", "Buscá el archivo.", "Esperá un momento.", "Fijate en la fecha.",
"Acordate del lunes.", "Decime cuándo.", "Avisame mañana.", "Mandale un saludo a Ana.", "Contame más.",
]) expect(s, s).toMatch(VOSEO);
});

test("the matcher ignores case, accented capitals included", () => {
expect("TOCÁ EL BOTÓN").toMatch(VOSEO);
expect("Querés").toMatch(VOSEO);
});

test("the matcher leaves tú and other words alone", () => {
for (const s of ["Toca el botón", "Si quieres, te aviso", "No abrí nada", "Elegí la primera.", "Le escribí a Luis."]) expect(s, s).not.toMatch(VOSEO);
});

test("the matcher counts accented letters as letters at both edges", () => {
for (const s of ["Antes tocábamos el timbre.", "Siempre dejábamos la llave.", "ñtocá", "étocá"]) expect(s, s).not.toMatch(VOSEO);
});

test("no value in es-419 uses voseo", () => {
for (const [k, v] of Object.entries(es)) expect(v, k).not.toMatch(VOSEO);
});
});

describe("translator", () => {
test("fills placeholders", () => {
expect(createTranslator(es)("HM-ACT-03.title", { index: 7 })).toBe("Cadena rota en la entrada 7");
Expand Down
6 changes: 5 additions & 1 deletion packages/mail/src/text.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,9 @@ export function base64ToBytes(text: string): Uint8Array {
return out.slice(0, o);
}

/** The smallest code point each sequence length may carry, by the number of continuation bytes. */
const MIN_CODE_POINT = [0, 0x80, 0x800, 0x10000];

/** UTF-8 bytes to text; a malformed sequence becomes U+FFFD instead of throwing. */
export function utf8Decode(bytes: Uint8Array): string {
let out = "";
Expand All @@ -46,7 +49,8 @@ export function utf8Decode(bytes: Uint8Array): string {
}
cp = (cp << 6) | (c & 0x3f);
}
if (!ok || cp > 0x10ffff) {
// Only the shortest form is UTF-8, and it never encodes the surrogates U+D800 to U+DFFF (RFC 3629).
if (!ok || cp < MIN_CODE_POINT[need]! || cp > 0x10ffff || (cp >= 0xd800 && cp <= 0xdfff)) {
out += "�";
i++;
continue;
Expand Down
137 changes: 137 additions & 0 deletions packages/mail/test/text.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
import { describe, expect, it } from "vitest";
import { base64ToBytes, clip, decodeBase64Text, decodeEntities, htmlToText, plainText, splitAddresses, utf8Decode } from "../src/text.ts";

// FR-MAIL-02: the helpers that turn Gmail, Outlook and IMAP bodies into plain text. Made-up people and example.com only.
const bytes = (...b: number[]) => new Uint8Array(b);

describe("base64ToBytes", () => {
it("reads plain base64", () => {
expect(base64ToBytes("SG9sYQ==")).toEqual(bytes(0x48, 0x6f, 0x6c, 0x61));
});

it("reads base64url, with - and _ in place of + and /", () => {
expect(base64ToBytes("-_8")).toEqual(bytes(0xfb, 0xff));
expect(base64ToBytes("-_8")).toEqual(base64ToBytes("+/8="));
});

it("skips padding and line breaks", () => {
expect(base64ToBytes("SG9s\r\nYSBB\nbmE=\n")).toEqual(base64ToBytes("SG9sYSBBbmE"));
expect(new TextDecoder().decode(base64ToBytes("SG9s\r\nYSBB\nbmE=\n"))).toBe("Hola Ana");
});
});

describe("utf8Decode and decodeBase64Text", () => {
it("decodes Spanish accents and ñ", () => {
expect(utf8Decode(bytes(0x61, 0xc3, 0xb1, 0x6f, 0x20, 0x63, 0x61, 0x6d, 0x69, 0xc3, 0xb3, 0x6e))).toBe("año camión");
expect(decodeBase64Text("TWHDsWFuYSB2ZW5nbyBhIGxhIHJldW5pw7NuLg==")).toBe("Mañana vengo a la reunión.");
});

it("decodes a four-byte character", () => {
expect(utf8Decode(bytes(0xf0, 0x9f, 0xa6, 0x80))).toBe("🦀");
expect(decodeBase64Text("8J+mgA")).toBe("🦀");
});

it("turns a broken sequence into U+FFFD instead of throwing", () => {
expect(utf8Decode(bytes(0x61, 0xc3, 0x28))).toBe("a�(");
expect(utf8Decode(bytes(0xff, 0x62))).toBe("�b");
});
});

describe("decodeEntities", () => {
it("decodes named references", () => {
expect(decodeEntities("Mar&iacute;a &amp; Jos&eacute;: ma&ntilde;ana a las 3")).toBe("María & José: mañana a las 3");
expect(decodeEntities("&aacute;rbol")).toBe("árbol");
});

it("decodes decimal and hex references", () => {
expect(decodeEntities("se&#241;or")).toBe("señor");
expect(decodeEntities("se&#xF1;or y se&#xf1;ora")).toBe("señor y señora");
});

it("leaves an unknown name as it is", () => {
expect(decodeEntities("&notaname; y &amp;")).toBe("&notaname; y &");
});
});

describe("htmlToText", () => {
it("drops script, style, head and title with their contents", () => {
const html =
"<html><head><title>Asunto</title><style>p { color: red }</style></head>" +
"<body><script>alert('hola')</script><p>Hola Ana</p></body></html>";
expect(htmlToText(html)).toBe("Hola Ana");
});

it("drops comments", () => {
expect(htmlToText("<p>Hola<!-- nota interna --> Luis</p>")).toBe("Hola Luis");
});

it("breaks lines at br, p, div, li and headings", () => {
const html = "<h1>Agenda</h1><p>Uno<br>Dos<br/>Tres</p><div>Cuatro</div><ul><li>Cinco</li><li>Seis</li></ul><h3>Fin</h3>";
expect(htmlToText(html)).toBe("Agenda\nUno\nDos\nTres\nCuatro\nCinco\nSeis\nFin");
});

it("leaves no blank lines", () => {
const text = htmlToText("<p>Hola</p>\n\n<p>&nbsp;</p><div> </div>\r\n<p>Chao</p>");
expect(text).toBe("Hola\nChao");
expect(text.split("\n").every((l) => l.trim())).toBe(true);
});
});

describe("plainText", () => {
it("turns CRLF into LF", () => {
expect(plainText("Hola\r\nAna\r\n")).toBe("Hola\nAna");
});

it("collapses runs of spaces", () => {
expect(plainText("Hola Ana,\t\tnos vemos")).toBe("Hola Ana, nos vemos");
});

it("keeps at most one blank line in a row", () => {
expect(plainText("Hola\n\n\n\nAna\n\n\nChao")).toBe("Hola\n\nAna\n\nChao");
expect(plainText("Hola\r\n\r\n\r\n\r\nAna")).toBe("Hola\n\nAna");
});
});

describe("clip", () => {
it("leaves text at or under the limit unchanged", () => {
expect(clip("Hola Ana", 8)).toBe("Hola Ana");
expect(clip("Hola", 8)).toBe("Hola");
});

it("cuts longer text and ends it with ...", () => {
const cut = clip("Nos vemos el lunes en la oficina", 12);
expect(cut).toBe("Nos vemos...");
expect(cut.length).toBeLessThanOrEqual(12);
});

it("leaves no space before the ...", () => {
expect(clip("uno dos tres", 7)).toBe("uno...");
expect(clip("uno dos tres", 7)).not.toMatch(/\s\.\.\.$/);
});
});

describe("splitAddresses", () => {
it("splits at commas between addresses", () => {
expect(splitAddresses("Ana Torres <ana@example.com>, luis@example.com")).toEqual(["Ana Torres <ana@example.com>", "luis@example.com"]);
});

it("doesn't split at a comma inside quotes", () => {
expect(splitAddresses("\"Pérez, Luis\" <luis@example.com>, Ana <ana@example.com>")).toEqual([
"\"Pérez, Luis\" <luis@example.com>",
"Ana <ana@example.com>",
]);
});

it("doesn't split at a comma inside angle brackets", () => {
expect(splitAddresses("Ana <ana,torres@example.com>, Luis <luis@example.com>")).toEqual([
"Ana <ana,torres@example.com>",
"Luis <luis@example.com>",
]);
});

it("gives an empty list for an empty or missing header", () => {
expect(splitAddresses("")).toEqual([]);
expect(splitAddresses(undefined)).toEqual([]);
expect(splitAddresses(" , ")).toEqual([]);
});
});
Loading
Loading