import { measureTextWrap } from '@evenrealities/pretext';
import { describe, expect, it } from 'vitest';
import { BODY_BOX, HUD, STATUS_BOX, renderHud } from '../src/core/hud.ts';
import { paginate, utf8Bytes, type MeasureLines } from '../src/core/paginate.ts';
import { toPlainText } from '../src/core/plaintext.ts';
import { initialState, type AppState, type Phase } from '../src/core/reducer.ts';
/**
* Layout tests use Even's own measurement library (@evenrealities/pretext),
* which mirrors the firmware's LVGL line breaking. That makes these
* measured-against-the-vendor-model tests, not device tests.
*/
const measure: MeasureLines = (text, width) => measureTextWrap(text, width).lineCount;
const box = { width: BODY_BOX.innerWidth, maxLines: HUD.bodyLines, maxBytes: HUD.pageMaxBytes };
const squash = (s: string) => s.replace(/\s+/g, '');
function expectValidPages(source: string, pages: string[]) {
for (const page of pages) {
expect(measure(page, box.width)).toBeLessThanOrEqual(box.maxLines);
expect(utf8Bytes(page)).toBeLessThanOrEqual(box.maxBytes);
expect(page.length).toBeGreaterThan(0);
}
// Nothing dropped, nothing duplicated, order preserved (whitespace at page breaks aside).
expect(squash(pages.join(' '))).toBe(squash(source));
}
describe('geometry', () => {
it('the two containers tile the 576x288 canvas exactly', () => {
expect(BODY_BOX.height + STATUS_BOX.height).toBe(HUD.height);
expect(STATUS_BOX.y).toBe(BODY_BOX.height);
expect(BODY_BOX.height - 2 * HUD.padding).toBe(HUD.bodyLines * HUD.lineHeight);
expect(STATUS_BOX.height - 2 * HUD.padding).toBeGreaterThanOrEqual(HUD.lineHeight);
});
});
describe('paginate', () => {
it('keeps a short answer on one page', () => {
expect(paginate('Paris.', box, measure)).toEqual(['Paris.']);
expect(paginate(' ', box, measure)).toEqual(['']);
});
it('splits a long answer into pages that each fit, losing nothing', () => {
const sentence = 'The quick brown fox jumps over the lazy dog near the riverbank at dawn. ';
const source = Array.from({ length: 80 }, (_, i) => `${i + 1}. ${sentence}`).join('').trim();
const pages = paginate(source, box, measure);
expect(pages.length).toBeGreaterThan(5);
expectValidPages(source, pages);
});
it('preserves line breaks inside a page', () => {
const source = 'First line\nSecond line\n\nNew paragraph';
expect(paginate(source, box, measure)).toEqual([source]);
});
it('handles many short lines (lists) by line count, not characters', () => {
const source = Array.from({ length: 40 }, (_, i) => `• item ${i + 1}`).join('\n');
const pages = paginate(source, box, measure);
expect(pages).toHaveLength(Math.ceil(40 / HUD.bodyLines));
expectValidPages(source, pages);
});
it('splits an unbroken run longer than a page without cutting a character in half', () => {
const url = 'https://example.com/' + 'a'.repeat(1500);
const pages = paginate(`See ${url} now`, box, measure);
expectValidPages(`See ${url} now`, pages);
});
it('keeps multi-byte text intact and within the byte budget', () => {
const cjk = '東京は日本の首都であり、世界でも有数の大都市です。'.repeat(40);
const accents = 'Voilà: café, naïve, façade, São Paulo, Zürich, Kraków, Ελληνικά, кириллица. '.repeat(30);
for (const source of [cjk, accents]) {
const pages = paginate(source, box, measure);
expect(pages.length).toBeGreaterThan(1);
expectValidPages(source, pages);
// Every page is still well-formed UTF-16 (no lone surrogates).
for (const page of pages) expect(page.isWellFormed()).toBe(true);
}
});
it('never splits a surrogate pair or a ZWJ sequence', () => {
const family = '👨👩👧👦';
const source = family.repeat(300);
const pages = paginate(source, box, measure);
expectValidPages(source, pages);
for (const page of pages) {
expect(page.isWellFormed()).toBe(true);
expect(page.length % family.length).toBe(0);
}
});
it('respects a byte budget tighter than the line budget', () => {
const source = 'é'.repeat(4000); // 2 bytes each
const pages = paginate(source, { ...box, maxLines: 1000 }, measure);
for (const page of pages) expect(utf8Bytes(page)).toBeLessThanOrEqual(box.maxBytes);
expect(pages.join('')).toBe(source);
});
it('a 20,000-character answer paginates quickly', () => {
const source = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. '.repeat(360);
const started = performance.now();
const pages = paginate(source, box, measure);
const elapsed = performance.now() - started;
expectValidPages(source, pages);
expect(elapsed).toBeLessThan(3000);
});
});
describe('plain text', () => {
it('removes Markdown markup but keeps every word', () => {
const md = [
'# Answer',
'',
'The **capital** of *France* is `Paris`. See [the docs](https://example.com/x) or [the anchor](#a).',
'',
'- one',
'* two',
'1. three',
'',
'> quoted',
'',
'```js',
'const a = b * c * d;',
'```',
'',
'| City | Country |',
'|------|---------|',
'| Paris | France |',
'',
'---',
'bold &
done',
].join('\n');
const out = toPlainText(md);
expect(out).not.toMatch(/[`#>]|\*\*|\]\(||\|/);
for (const word of ['Answer', 'capital', 'France', 'Paris', 'the docs (https://example.com/x)', 'or the anchor.', '• one', '• two', '1. three', 'quoted', 'const a = b * c * d;', 'City · Country', 'Paris · France', 'bold &\ndone']) {
expect(out).toContain(word);
}
});
it('leaves ordinary punctuation, maths and identifiers alone', () => {
for (const text of ['2 * 3 * 4 = 24', 'snake_case_name and another_one', 'a < b and b > c', 'Price: $5 * 2', 'Use the -v flag']) {
expect(toPlainText(text)).toBe(text);
}
});
it('preserves Unicode and normalises line endings', () => {
expect(toPlainText('Zürich — 東京 – naïve\r\nline two\r\n\r\n\r\n\r\nline three')).toBe('Zürich — 東京 – naïve\nline two\n\nline three');
// Decomposed input is composed, so the firmware sees one code point per accented letter.
expect(toPlainText('é')).toBe('é');
});
});
describe('HUD frames', () => {
const phases: Phase[] = ['unpaired', 'menu', 'ready', 'listening', 'transcribing', 'thinking', 'approval', 'answer', 'error', 'disconnected', 'cancelled'];
const variants = (phase: Phase): AppState[] => {
const base: AppState = { ...initialState, phase, captureStartedAt: 0, captureMaxSeconds: 120 };
if (phase === 'answer') {
return [
{ ...base, pages: ['x'], pageIndex: 0 },
{ ...base, pages: Array(99).fill('x'), pageIndex: 98, partial: true },
{ ...base, pages: Array(99).fill('x'), pageIndex: 98, partial: true, wakeListening: true, agents: [{ id: 'default', name: 'Pepper' }, { id: 'natalie', name: 'Natalie' }], agentId: 'natalie' },
];
}
if (phase === 'disconnected') {
return [
{ ...base, disconnectedFrom: 'glasses' },
{ ...base, disconnectedFrom: 'bridge', canResend: true },
{ ...base, disconnectedFrom: 'bridge', canResend: false },
{ ...base, disconnectedFrom: 'storage', canResend: true },
];
}
if (phase === 'error') {
return [
{ ...base, error: { code: 'outcome_unknown', hud: 'The outcome is unknown. Check the agent before asking again.', retryable: false } },
{ ...base, error: { code: 'agent_timeout', hud: 'The agent ran out of time and was stopped. Actions it had already taken are not undone.', retryable: true } },
{ ...base, wakeListening: true, error: { code: 'agent_timeout', hud: 'The agent ran out of time and was stopped.', retryable: true } },
];
}
// Listening for a name: sixteen agents with the longest names allowed, and none.
const many = Array.from({ length: 16 }, (_, i) => ({ id: `a${i}`, name: 'Wwwwwwwwwwwwwwwwwwwwwwww' }));
const few = [
{ id: 'default', name: 'Pepper' },
{ id: 'wendy', name: 'Wendy' },
{ id: 'cody', name: 'Cody' },
];
const wake = { wakeListening: true };
if (phase === 'menu') return [base, { ...base, handsFree: true }, { ...base, handsFree: true, menuIndex: 1 }];
if (phase === 'ready') {
return [{ ...base, menu: true }, { ...base, menu: true, ...wake, agents: few }, base, { ...base, notice: 'New conversation' }, { ...base, ...wake }, { ...base, ...wake, agents: few }, { ...base, ...wake, agents: many }, { ...base, ...wake, agents: few, notice: 'New conversation' }];
}
if (phase === 'listening') return [base, { ...base, captureAuto: true }, { ...base, captureAuto: true, agents: few }];
if (phase === 'thinking') return [base, { ...base, heard: 'W'.repeat(4000) }, { ...base, agents: few, heard: 'What is on my calendar tomorrow?' }];
if (phase === 'cancelled') return [base, { ...base, ...wake }];
if (phase === 'unpaired') return [base, { ...base, storageFault: true }];
return [base];
};
it('every status line fits on one HUD line and every body fits without scrolling', () => {
for (const phase of phases) {
for (const state of variants(phase)) {
const frame = renderHud(state, 119_000);
expect(measure(frame.status, STATUS_BOX.width - 2 * HUD.padding), `status of ${phase}: ${frame.status}`).toBe(1);
expect(measure(frame.body, BODY_BOX.innerWidth), `body of ${phase}`).toBeLessThanOrEqual(HUD.bodyLines);
expect(utf8Bytes(frame.body)).toBeLessThanOrEqual(999);
expect(frame.status.length).toBeGreaterThan(0);
}
}
});
it('the recording indicator and elapsed time are visible for the whole capture', () => {
const state: AppState = { ...initialState, phase: 'listening', captureStartedAt: 10_000, captureMaxSeconds: 30 };
expect(renderHud(state, 10_000).status).toContain('● REC 0:00 / 0:30');
expect(renderHud(state, 17_400).status).toContain('● REC 0:07 / 0:30');
expect(renderHud(state, 17_400).body).toContain('30 seconds');
for (const phase of phases.filter((p) => p !== 'listening')) {
expect(renderHud({ ...initialState, phase }, 0).status).not.toContain('REC');
}
});
it('an open microphone at rest is always marked, and never claimed while it is closed', () => {
for (const phase of ['ready', 'answer', 'error', 'cancelled'] as Phase[]) {
const state: AppState = { ...initialState, phase, pages: ['x'] };
expect(renderHud({ ...state, wakeListening: true }, 0).status.startsWith('● ')).toBe(true);
expect(renderHud(state, 0).status).not.toContain('●');
}
// In flight the microphone is closed, whatever the flag last said.
for (const phase of ['transcribing', 'thinking', 'approval', 'disconnected', 'unpaired'] as Phase[]) {
expect(renderHud({ ...initialState, phase, wakeListening: true }, 0).status).not.toContain('●');
}
const ready = renderHud({ ...initialState, phase: 'ready', wakeListening: true, agents: [{ id: 'default', name: 'Pepper' }, { id: 'wendy', name: 'Wendy' }] }, 0);
expect(ready.body).toBe('Pepper\n\nListening. Say a name, then your question:\nPepper · Wendy');
});
it('errors offer a recovery action and send detail to the phone', () => {
const frame = renderHud({ ...initialState, phase: 'error', error: { code: 'stt_empty', hud: 'No speech was recognised.', retryable: true } }, 0);
expect(frame.body).toContain('No speech was recognised.');
expect(frame.body).toContain('phone');
expect(frame.status).toContain('Tap');
});
});