forked from Blendman974/faceclaw
Add calculator and microphone conversation apps
Add symbolic math and graphing tools, dual-microphone audio processing, live captions, translation, speaker diarization, sentiment analysis, and searchable conversation history. Extend Android voice and BLE support for microphone control, recording, transcoding, and on-device speaker identification, with coverage for calculator and microphone workflows.
This commit is contained in:
124 files changed
+22061
-58
No files matched your search
+2
-3
@@ -3,9 +3,8 @@
|
||||
Faceclaw's pairing logic (`app/g2/glasses-hardware-identity.ts`,
|
||||
`ble-proximity.ts`, `even-advertisement.ts`, `pairing-candidates.ts`,
|
||||
`glasses-artwork.ts`) is written without NativeScript imports so it can run
|
||||
under plain node. The tests here are ports of SybilSight's
|
||||
`GlassesHardwareIdentityTests` / `BLEProximityTests` plus coverage for the
|
||||
advertisement parsers and left↔right pair grouping.
|
||||
under plain node. The tests here cover hardware-identity decoding, proximity
|
||||
estimation, the advertisement parsers, and left↔right pair grouping.
|
||||
|
||||
Run with:
|
||||
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
// Ported from SybilSight's BLEProximityTests.
|
||||
//
|
||||
// These pin the parts the pairing screen depends on: that a stronger signal
|
||||
// always sorts first, that the absolute numbers stay inside a plausible band,
|
||||
// and that a missing signal degrades to "unknown" rather than to a fabricated
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
// These pin the Calculator app's own decisions: which utterances are
|
||||
// commands, which unprompted room speech is worth answering, and how the
|
||||
// modes map onto the shared maths session.
|
||||
const test = require("node:test");
|
||||
const assert = require("node:assert/strict");
|
||||
|
||||
const {
|
||||
CALCULATOR_MODES,
|
||||
cycleMode,
|
||||
isDictationCancellation,
|
||||
isWorthAnswering,
|
||||
modeBranch,
|
||||
modeCommand,
|
||||
modeSpokenCommands,
|
||||
} = require("../.test-build/app/apps/calculator/calculator-commands.js");
|
||||
|
||||
// Both the bare verb and the "it" form, because a wearer shown "Graph" says
|
||||
// both — and leaving the bare form out makes the feature look broken in
|
||||
// exactly the case the user was taught.
|
||||
test("every advertised command is recognised", () => {
|
||||
for (const mode of CALCULATOR_MODES) {
|
||||
for (const command of modeSpokenCommands(mode)) {
|
||||
assert.equal(modeCommand(command), mode, `"${command}" is advertised for ${mode} but is not recognised`);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test("commands survive punctuation and case", () => {
|
||||
assert.equal(modeCommand("Solve it."), "solve");
|
||||
assert.equal(modeCommand(" GRAPH IT "), "graph");
|
||||
assert.equal(modeCommand("Explain?"), "explain");
|
||||
});
|
||||
|
||||
test("listening cancellation commands are exact", () => {
|
||||
for (const command of ["cancel", "Cancel listening.", "STOP LISTENING", "never mind"]) {
|
||||
assert.ok(isDictationCancellation(command), command);
|
||||
}
|
||||
assert.ok(!isDictationCancellation("cancel the denominator"));
|
||||
assert.ok(!isDictationCancellation("I never mind the rain"));
|
||||
});
|
||||
|
||||
// A substring test would turn ordinary conversation into a command. This is
|
||||
// the sentence that motivated matching the whole utterance.
|
||||
test("conversation containing a command word is not a command", () => {
|
||||
assert.equal(modeCommand("I need to solve this with the tax people"), null);
|
||||
assert.equal(modeCommand("the graph in the report was wrong"), null);
|
||||
});
|
||||
|
||||
// In continuous mode the app sees every finalized utterance in the room.
|
||||
// Without a gate, every sentence becomes a failed calculation.
|
||||
test("ordinary speech is not answered unprompted", () => {
|
||||
assert.ok(!isWorthAnswering("I'll see you at four"));
|
||||
assert.ok(!isWorthAnswering("that was a lovely dinner"));
|
||||
});
|
||||
|
||||
test("real questions and commands are answered unprompted", () => {
|
||||
assert.ok(isWorthAnswering("what is two plus two"));
|
||||
assert.ok(isWorthAnswering("solve 2x + 7 = 19"));
|
||||
assert.ok(isWorthAnswering("graph it"));
|
||||
});
|
||||
|
||||
test("every mode maps to a branch mode", () => {
|
||||
assert.deepEqual(
|
||||
new Set(CALCULATOR_MODES.map(modeBranch)),
|
||||
new Set(["solve", "explain", "graph"]),
|
||||
);
|
||||
});
|
||||
|
||||
test("scrolling cycles the modes in both directions", () => {
|
||||
assert.equal(cycleMode("solve", true), "explain");
|
||||
assert.equal(cycleMode("explain", true), "graph");
|
||||
assert.equal(cycleMode("graph", true), "solve");
|
||||
assert.equal(cycleMode("solve", false), "graph");
|
||||
});
|
||||
@@ -0,0 +1,593 @@
|
||||
// The maths-engine behaviour the Calculator app depends on, pinned area by
|
||||
// area: exact numbers, the spoken normaliser,
|
||||
// parser precedence, simplification, solving with steps, rendering,
|
||||
// derivatives and integrals, plotting, the stateful session, digit searches,
|
||||
// and the advanced spoken-question router.
|
||||
const test = require("node:test");
|
||||
const assert = require("node:assert/strict");
|
||||
|
||||
const N = require("../.test-build/app/apps/calculator/math/math-number.js");
|
||||
const { normalizeSpoken } = require("../.test-build/app/apps/calculator/math/normalizer.js");
|
||||
const { parse, parseSpoken } = require("../.test-build/app/apps/calculator/math/parser.js");
|
||||
const { evaluateExact, evaluateValue } = require("../.test-build/app/apps/calculator/math/evaluator.js");
|
||||
const { simplify } = require("../.test-build/app/apps/calculator/math/simplifier.js");
|
||||
const { plain } = require("../.test-build/app/apps/calculator/math/text-renderer.js");
|
||||
const { solve, solutionHeadline } = require("../.test-build/app/apps/calculator/math/solver.js");
|
||||
const { differentiate, integrateNumeric } = require("../.test-build/app/apps/calculator/math/derivative.js");
|
||||
const { plot, axis } = require("../.test-build/app/apps/calculator/math/plotter.js");
|
||||
const { MathSession, parseCommand } = require("../.test-build/app/apps/calculator/math/session.js");
|
||||
const { fractionalDigits } = require("../.test-build/app/apps/calculator/math/constant-digits.js");
|
||||
const { findDigits, countDigits } = require("../.test-build/app/apps/calculator/math/digit-search.js");
|
||||
const { parseAdvanced, answerAdvanced } = require("../.test-build/app/apps/calculator/math/advanced.js");
|
||||
const { longRunOffer } = require("../.test-build/app/apps/calculator/math/workload.js");
|
||||
const { MathCoordinator } = require("../.test-build/app/apps/calculator/math/coordinator.js");
|
||||
|
||||
const near = (a, b, eps = 1e-9) => Math.abs(a - b) <= eps;
|
||||
|
||||
function evaluate(text, variables = {}) {
|
||||
const value = evaluateValue(parseSpoken(text), variables);
|
||||
assert.notEqual(value, null, `could not evaluate ${text}`);
|
||||
return value;
|
||||
}
|
||||
|
||||
function rootValues(text) {
|
||||
const solution = solve(parseSpoken(text));
|
||||
assert.equal(solution.kind.kind, "roots", `expected roots for ${text}`);
|
||||
return solution.kind.roots.map((root) => N.doubleValue(evaluateExact(root)));
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Numbers
|
||||
|
||||
test("thirds sum to exactly one", () => {
|
||||
const third = N.rational(1, 3);
|
||||
const sum = N.add(N.add(third, third), third);
|
||||
assert.deepEqual(sum, N.integer(1));
|
||||
});
|
||||
|
||||
test("rationals normalise", () => {
|
||||
assert.deepEqual(N.rational(2, 4), N.rational(1, 2));
|
||||
assert.deepEqual(N.rational(3, -6), { kind: "rational", n: -1, d: 2 });
|
||||
assert.deepEqual(N.rational(4, 2), N.integer(2));
|
||||
});
|
||||
|
||||
test("decimal literals recover their fraction", () => {
|
||||
assert.deepEqual(N.fromDecimal(0.25), N.rational(1, 4));
|
||||
assert.deepEqual(N.fromDecimal(0.5), N.rational(1, 2));
|
||||
assert.equal(N.fromDecimal(Math.PI).kind, "real");
|
||||
});
|
||||
|
||||
test("exact powers stay exact, irrational ones do not", () => {
|
||||
assert.deepEqual(N.raisedTo(N.integer(2), N.integer(10)), N.integer(1024));
|
||||
assert.deepEqual(N.raisedTo(N.rational(9, 4), N.rational(1, 2)), N.rational(3, 2));
|
||||
assert.equal(N.raisedTo(N.integer(2), N.rational(1, 2)).kind, "real");
|
||||
});
|
||||
|
||||
test("overflow falls back to a real instead of trapping", () => {
|
||||
const huge = N.integer(Number.MAX_SAFE_INTEGER);
|
||||
assert.equal(N.multiply(huge, huge).kind, "real");
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Spoken normalisation
|
||||
|
||||
test("number words become digits, including compounds", () => {
|
||||
assert.equal(normalizeSpoken("twenty five"), "25");
|
||||
assert.equal(normalizeSpoken("one hundred forty four"), "144");
|
||||
assert.equal(normalizeSpoken("two thousand ten"), "2010");
|
||||
assert.equal(normalizeSpoken("three hundred and five"), "305");
|
||||
});
|
||||
|
||||
test("operators and relations become symbols", () => {
|
||||
assert.equal(normalizeSpoken("two plus two"), "2 + 2");
|
||||
assert.equal(normalizeSpoken("x is less than or equal to five"), "x <= 5");
|
||||
});
|
||||
|
||||
test("powers spoken every way", () => {
|
||||
assert.equal(normalizeSpoken("x squared"), "x^2");
|
||||
assert.equal(normalizeSpoken("two to the power of five"), "2^5");
|
||||
assert.equal(normalizeSpoken("x cubed"), "x^3");
|
||||
assert.equal(normalizeSpoken("two to the fifth"), "2^5");
|
||||
});
|
||||
|
||||
test("command preambles are stripped", () => {
|
||||
assert.equal(normalizeSpoken("solve two x plus one equals five"), "2*x + 1 = 5");
|
||||
assert.equal(normalizeSpoken("what is two plus two"), "2 + 2");
|
||||
});
|
||||
|
||||
// Always-on transcription commonly finalizes a valid equation together with
|
||||
// the next conversational beat; that must not force an AI rewrite.
|
||||
test("terminal conversational filler does not break parsing", () => {
|
||||
assert.equal(evaluate("3 x plus 1. Thank you.", { x: 2 }), 7);
|
||||
});
|
||||
|
||||
test("implicit multiplication is made explicit", () => {
|
||||
assert.equal(normalizeSpoken("2x"), "2*x");
|
||||
assert.equal(normalizeSpoken("3(x+1)"), "3*(x+1)");
|
||||
});
|
||||
|
||||
// The repair that stops `sqrt(x)` from becoming `sqr*t*(x)` once implicit
|
||||
// multiplication has run over it.
|
||||
test("function names survive implicit multiplication", () => {
|
||||
const normalized = normalizeSpoken("square root of sixteen");
|
||||
assert.ok(normalized.includes("sqrt"), normalized);
|
||||
assert.ok(!normalized.includes("sqr*t"), normalized);
|
||||
assert.ok(near(evaluate("square root of sixteen"), 4));
|
||||
});
|
||||
|
||||
test("a full spoken quadratic parses to the right roots", () => {
|
||||
const roots = rootValues("two x squared plus three x minus five equals zero");
|
||||
assert.equal(roots.length, 2);
|
||||
assert.ok(near(roots[0], -2.5));
|
||||
assert.ok(near(roots[1], 1));
|
||||
});
|
||||
|
||||
test("percent is a hundredth, not a remainder", () => {
|
||||
assert.ok(near(evaluate("15 percent of 240"), 36));
|
||||
});
|
||||
|
||||
test("factorial spoken after the number", () => {
|
||||
assert.ok(near(evaluate("seven factorial"), 5040));
|
||||
});
|
||||
|
||||
test("fractions spoken as words", () => {
|
||||
assert.ok(near(evaluate("three over four"), 0.75));
|
||||
assert.ok(near(evaluate("two thirds"), 2 / 3));
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Parser
|
||||
|
||||
test("precedence: multiplication before addition", () => {
|
||||
assert.ok(near(evaluate("2 + 3 * 4"), 14));
|
||||
});
|
||||
|
||||
// `-x^2` is `-(x^2)` — the convention every textbook and every other
|
||||
// calculator uses. Getting it backwards silently changes the answer.
|
||||
test("unary minus binds looser than a power", () => {
|
||||
assert.ok(near(evaluate("-3^2"), -9));
|
||||
});
|
||||
|
||||
test("powers are right associative", () => {
|
||||
assert.ok(near(evaluate("2^3^2"), 512));
|
||||
});
|
||||
|
||||
test("negative exponents parse", () => {
|
||||
assert.ok(near(evaluate("2^-1"), 0.5));
|
||||
});
|
||||
|
||||
test("absolute value with pipes", () => {
|
||||
assert.ok(near(evaluate("|0 - 5|"), 5));
|
||||
});
|
||||
|
||||
test("modulo", () => {
|
||||
assert.ok(near(evaluate("10 % 3"), 1));
|
||||
assert.ok(near(evaluate("-1 % 3"), 2));
|
||||
});
|
||||
|
||||
test("adjacent single letters are a product, not one long name", () => {
|
||||
assert.ok(near(evaluate("xy", { x: 3, y: 4 }), 12));
|
||||
});
|
||||
|
||||
test("unbalanced brackets are reported, not guessed past", () => {
|
||||
assert.throws(() => parse("(1 + 2"));
|
||||
});
|
||||
|
||||
test("chained comparisons are refused rather than half-honoured", () => {
|
||||
assert.throws(() => parse("1 < x < 5"));
|
||||
});
|
||||
|
||||
test("a pathological nest fails instead of blowing the stack", () => {
|
||||
const nested = "(".repeat(500) + "1" + ")".repeat(500);
|
||||
assert.throws(() => parse(nested));
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Simplifier and renderer
|
||||
|
||||
const simplified = (text) => plain(simplify(parse(text)));
|
||||
|
||||
test("like terms collect", () => {
|
||||
assert.equal(simplified("2*x + 3*x"), "5*x");
|
||||
});
|
||||
|
||||
test("identity elements disappear", () => {
|
||||
assert.equal(simplified("x + 0"), "x");
|
||||
assert.equal(simplified("1 * x"), "x");
|
||||
assert.equal(simplified("x^1"), "x");
|
||||
});
|
||||
|
||||
test("powers of the same base combine", () => {
|
||||
assert.equal(simplified("x * x^2"), "x^3");
|
||||
});
|
||||
|
||||
// This is what keeps `sqrt(2)` symbolic while `sqrt(9)` becomes 3.
|
||||
test("irrational roots stay symbolic while perfect ones fold", () => {
|
||||
assert.equal(simplified("sqrt(9)"), "3");
|
||||
assert.equal(simplified("sqrt(2)"), "sqrt(2)");
|
||||
});
|
||||
|
||||
test("division renders as a fraction, not a negative power", () => {
|
||||
assert.equal(plain(simplify(parse("2 / x"))), "2/x");
|
||||
});
|
||||
|
||||
test("subtraction renders as a minus, not plus-negative", () => {
|
||||
const text = plain(parse("x - 3"));
|
||||
assert.ok(text.includes("- 3"), text);
|
||||
assert.ok(!text.includes("+ -"), text);
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Solver
|
||||
|
||||
test("linear equations solve exactly", () => {
|
||||
const solution = solve(parseSpoken("2x + 7 = 19"));
|
||||
assert.equal(solutionHeadline(solution), "x = 6");
|
||||
});
|
||||
|
||||
test("linear with a fractional answer stays exact", () => {
|
||||
const solution = solve(parseSpoken("2x = 3"));
|
||||
assert.equal(solutionHeadline(solution), "x = 3/2");
|
||||
});
|
||||
|
||||
test("quadratic with two rational roots", () => {
|
||||
const roots = rootValues("x^2 - 5x + 6 = 0");
|
||||
assert.ok(near(roots[0], 2));
|
||||
assert.ok(near(roots[1], 3));
|
||||
});
|
||||
|
||||
test("quadratic with a repeated root reports it once", () => {
|
||||
assert.equal(rootValues("x^2 - 2x + 1 = 0").length, 1);
|
||||
});
|
||||
|
||||
test("quadratic with no real roots", () => {
|
||||
const solution = solve(parseSpoken("x^2 + 1 = 0"));
|
||||
assert.equal(solutionHeadline(solution), "No real solution");
|
||||
});
|
||||
|
||||
// (−b ± √D) / 2a is the exact answer; collapsing it to decimals throws away
|
||||
// information the wearer may want to see.
|
||||
test("irrational quadratic roots keep their radical", () => {
|
||||
const solution = solve(parseSpoken("x^2 - 2 = 0"));
|
||||
assert.equal(solution.kind.kind, "roots");
|
||||
assert.equal(solution.kind.roots.length, 2);
|
||||
assert.ok(solutionHeadline(solution).includes("sqrt"), solutionHeadline(solution));
|
||||
const numeric = solution.kind.roots
|
||||
.map((root) => N.doubleValue(evaluateExact(root)))
|
||||
.sort((a, b) => a - b);
|
||||
assert.ok(near(numeric[0], -Math.SQRT2));
|
||||
assert.ok(near(numeric[1], Math.SQRT2));
|
||||
});
|
||||
|
||||
test("cubic via the rational root theorem", () => {
|
||||
const roots = rootValues("x^3 - 6x^2 + 11x - 6 = 0");
|
||||
assert.equal(roots.length, 3);
|
||||
assert.ok(near(roots[0], 1) && near(roots[1], 2) && near(roots[2], 3));
|
||||
});
|
||||
|
||||
test("an identity and a contradiction are distinguished", () => {
|
||||
assert.equal(solve(parseSpoken("x = x")).kind.kind, "identity");
|
||||
assert.equal(solve(parseSpoken("0 = 1")).kind.kind, "contradiction");
|
||||
});
|
||||
|
||||
test("a plain expression evaluates instead of solving", () => {
|
||||
const solution = solve(parseSpoken("2 + 2"));
|
||||
assert.equal(solution.kind.kind, "value");
|
||||
assert.equal(solutionHeadline(solution), "4");
|
||||
});
|
||||
|
||||
// The single most common mistake in this whole topic, so it gets its own
|
||||
// visible step — and its own test.
|
||||
test("dividing an inequality by a negative flips it", () => {
|
||||
const solution = solve(parseSpoken("-2x < 6"));
|
||||
assert.equal(solution.kind.kind, "interval");
|
||||
assert.equal(solution.kind.relation, ">");
|
||||
});
|
||||
|
||||
test("transcendental equations fall back to a numeric search", () => {
|
||||
const solution = solve(parseSpoken("sin(x) = 0"));
|
||||
assert.equal(solution.kind.kind, "roots");
|
||||
const values = solution.kind.roots.map((root) => N.doubleValue(evaluateExact(root)));
|
||||
assert.ok(values.some((value) => near(value, 0, 1e-4)));
|
||||
});
|
||||
|
||||
// Bisection happily converges onto tan's asymptote; the residual check is
|
||||
// what rejects it.
|
||||
test("a pole is not mistaken for a root", () => {
|
||||
const solution = solve(parseSpoken("tan(x) = 0"));
|
||||
assert.equal(solution.kind.kind, "roots");
|
||||
for (const root of solution.kind.roots) {
|
||||
const value = N.doubleValue(evaluateExact(root));
|
||||
assert.ok(Math.abs(Math.tan(value)) < 1e-4, `tan(${value}) is not near zero`);
|
||||
}
|
||||
});
|
||||
|
||||
test("a linear solve records usable steps", () => {
|
||||
const solution = solve(parseSpoken("2x + 7 = 19"));
|
||||
assert.ok(solution.steps.length >= 2);
|
||||
assert.ok(solution.steps.every((step) => step.title.length > 0 && step.detail.length > 0));
|
||||
});
|
||||
|
||||
test("a quadratic explains its discriminant", () => {
|
||||
const solution = solve(parseSpoken("x^2 - 5x + 6 = 0"));
|
||||
assert.ok(solution.steps.some((step) => step.title === "Discriminant"));
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Derivatives and integrals
|
||||
|
||||
const derivativeText = (text, variable = "x") => plain(differentiate(parseSpoken(text), variable));
|
||||
|
||||
test("power rule", () => {
|
||||
assert.equal(derivativeText("x^2"), "2*x");
|
||||
});
|
||||
|
||||
test("chain rule through a function", () => {
|
||||
assert.equal(derivativeText("sin(2*x)"), "2*cos(2*x)");
|
||||
});
|
||||
|
||||
test("derivatives agree with a finite difference", () => {
|
||||
for (const expression of ["x^3 + 2*x", "sin(x) * x", "exp(x) / (x + 2)", "ln(x^2 + 1)"]) {
|
||||
const parsed = parseSpoken(expression);
|
||||
const derived = differentiate(parsed, "x");
|
||||
for (const x of [0.5, 1.0, 2.0]) {
|
||||
const h = 1e-6;
|
||||
const left = evaluateValue(parsed, { x: x - h });
|
||||
const right = evaluateValue(parsed, { x: x + h });
|
||||
const expected = (right - left) / (2 * h);
|
||||
const actual = evaluateValue(derived, { x });
|
||||
assert.ok(near(actual, expected, 1e-4), `${expression} at ${x}: ${actual} vs ${expected}`);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test("definite integrals of known areas", () => {
|
||||
assert.ok(near(integrateNumeric(parseSpoken("x^2"), "x", 0, 3), 9, 1e-6));
|
||||
assert.ok(near(integrateNumeric(parseSpoken("sin(x)"), "x", 0, Math.PI), 2, 1e-6));
|
||||
});
|
||||
|
||||
test("reversing the limits negates the result", () => {
|
||||
const forward = integrateNumeric(parseSpoken("x^2"), "x", 0, 3);
|
||||
const backward = integrateNumeric(parseSpoken("x^2"), "x", 3, 0);
|
||||
assert.ok(near(forward, -backward, 1e-9));
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Plotter
|
||||
|
||||
test("a parabola samples and autoscales", () => {
|
||||
const graph = plot([parseSpoken("x^2")]);
|
||||
assert.equal(graph.plots.length, 1);
|
||||
assert.ok(graph.plots[0].segments.length >= 1);
|
||||
assert.ok(graph.viewport.yMax > 0);
|
||||
});
|
||||
|
||||
// The single most recognisable "bad graphing app" artefact: a vertical line
|
||||
// at every asymptote.
|
||||
test("tan breaks into segments at its asymptotes", () => {
|
||||
const graph = plot([parseSpoken("tan(x)")]);
|
||||
assert.ok(graph.plots[0].segments.length > 3);
|
||||
});
|
||||
|
||||
test("a function with a restricted domain only plots where it is defined", () => {
|
||||
const graph = plot([parseSpoken("sqrt(x)")]);
|
||||
for (const segment of graph.plots[0].segments) {
|
||||
for (const point of segment.points) {
|
||||
assert.ok(point.x >= 0);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test("axis ticks land on round numbers", () => {
|
||||
const ticks = axis(-10, 10).ticks;
|
||||
assert.ok(ticks.includes(0));
|
||||
assert.ok(ticks.every((tick) => near(tick % 2, 0, 1e-9) || near(Math.abs(tick % 2), 2, 1e-9)));
|
||||
});
|
||||
|
||||
test("roots are marked on the graph", () => {
|
||||
const graph = plot([parseSpoken("x^2 - 4")]);
|
||||
const markers = graph.plots[0].markers;
|
||||
assert.ok(markers.some((marker) => marker.kind === "root" && near(marker.point.x, 2, 1e-3)));
|
||||
assert.ok(markers.some((marker) => marker.kind === "root" && near(marker.point.x, -2, 1e-3)));
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Session and follow-ups
|
||||
|
||||
test("follow-up commands are recognised, bare and with it", () => {
|
||||
for (const utterance of ["graph it", "graph", "plot it", "show the graph"]) {
|
||||
assert.equal(parseCommand(utterance).kind, "graph", utterance);
|
||||
}
|
||||
for (const utterance of ["explain it", "explain", "show the steps", "step by step"]) {
|
||||
assert.equal(parseCommand(utterance).kind, "explain", utterance);
|
||||
}
|
||||
for (const utterance of ["solve it", "solve", "what is the answer"]) {
|
||||
assert.equal(parseCommand(utterance).kind, "restate", utterance);
|
||||
}
|
||||
});
|
||||
|
||||
test("ordinary conversation is not treated as math", () => {
|
||||
assert.equal(parseCommand("I'll see you at four"), null);
|
||||
assert.equal(parseCommand("that was a lovely dinner"), null);
|
||||
});
|
||||
|
||||
test("solve then graph then explain, without restating the problem", () => {
|
||||
const session = new MathSession();
|
||||
const solved = session.solve("x^2 - 4 = 0");
|
||||
assert.equal(solved.payload.kind, "solution");
|
||||
|
||||
const graphed = session.graph();
|
||||
assert.equal(graphed.payload.kind, "graph");
|
||||
|
||||
const explained = session.explain();
|
||||
assert.equal(explained.payload.kind, "step");
|
||||
assert.equal(explained.payload.index, 0);
|
||||
});
|
||||
|
||||
// A wearer scrolling past the end should land on the answer and stay there,
|
||||
// not loop back to the start.
|
||||
test("stepping clamps at both ends instead of wrapping", () => {
|
||||
const session = new MathSession();
|
||||
session.solve("2x + 7 = 19");
|
||||
session.explain();
|
||||
let last = null;
|
||||
for (let step = 0; step < 20; step++) last = session.execute({ kind: "nextStep" });
|
||||
assert.equal(last.payload.index, last.payload.total - 1);
|
||||
for (let step = 0; step < 20; step++) last = session.execute({ kind: "previousStep" });
|
||||
assert.equal(last.payload.index, 0);
|
||||
});
|
||||
|
||||
test("follow-ups before a problem fail with a usable message", () => {
|
||||
const session = new MathSession();
|
||||
const result = session.graph();
|
||||
assert.equal(result.payload.kind, "failure");
|
||||
assert.equal(result.headline, "No problem yet");
|
||||
});
|
||||
|
||||
test("a misheard problem reports what was said, not the normalised form", () => {
|
||||
const session = new MathSession();
|
||||
const result = session.solve("two plus plus plus");
|
||||
assert.equal(result.payload.kind, "failure");
|
||||
assert.ok(result.detail.includes("two plus plus plus"), result.detail);
|
||||
});
|
||||
|
||||
test("derivative as a follow-up", () => {
|
||||
const session = new MathSession();
|
||||
session.solve("x^3");
|
||||
const result = session.differentiate(null);
|
||||
assert.equal(result.headline, "d/dx = 3*x^2");
|
||||
});
|
||||
|
||||
test("trig in degrees is honoured", () => {
|
||||
const session = new MathSession(true);
|
||||
const result = session.solve("sin(90)");
|
||||
assert.equal(result.headline, "1");
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Constants and digit search
|
||||
|
||||
// The position convention: decimal places after the point, 1-based. The
|
||||
// first `11` in π is at 94–95.
|
||||
test("the first 11 in pi is at places 94 to 95", () => {
|
||||
const outcome = findDigits("11", "pi", 1);
|
||||
assert.equal(outcome.kind, "found");
|
||||
assert.equal(outcome.match.start, 94);
|
||||
assert.equal(outcome.match.end, 95);
|
||||
});
|
||||
|
||||
test("pi opens with the digits everyone knows", () => {
|
||||
assert.ok(fractionalDigits("pi", 10).startsWith("1415926535"));
|
||||
assert.ok(fractionalDigits("e", 10).startsWith("7182818284"));
|
||||
assert.ok(fractionalDigits("sqrt2", 10).startsWith("4142135623"));
|
||||
assert.ok(fractionalDigits("phi", 10).startsWith("6180339887"));
|
||||
});
|
||||
|
||||
// Overlapping matches count: "111" contains "11" twice.
|
||||
test("digit counting counts overlaps", () => {
|
||||
const counted = countDigits("1", "pi", 100);
|
||||
assert.ok(counted.occurrences >= 8, String(counted.occurrences));
|
||||
assert.equal(counted.searchedDigits, 100);
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Advanced router
|
||||
|
||||
test("number theory questions route and answer", () => {
|
||||
assert.equal(answerAdvanced(parseAdvanced("is 91 prime")).headline, "91 is not prime");
|
||||
assert.equal(answerAdvanced(parseAdvanced("factor 360")).headline, "360 = 2^3 × 3^2 × 5");
|
||||
assert.equal(answerAdvanced(parseAdvanced("gcd of 12 and 18")).headline, "gcd(12, 18) = 6");
|
||||
assert.equal(answerAdvanced(parseAdvanced("what is 5 choose 2")).headline, "C(5, 2) = 10");
|
||||
});
|
||||
|
||||
test("calculus questions route and answer", () => {
|
||||
assert.equal(answerAdvanced(parseAdvanced("the integral of x squared from 0 to 3")).headline, "∫ = 9");
|
||||
assert.equal(answerAdvanced(parseAdvanced("limit of sin(x)/x as x approaches 0")).headline, "limit = 1");
|
||||
});
|
||||
|
||||
// A trig equation's right answer is the FAMILY, not the twelve roots that
|
||||
// happen to fall in a search window.
|
||||
test("trig equations answer with solution families", () => {
|
||||
const answer = answerAdvanced(parseAdvanced("solve sin x = 0.5"));
|
||||
assert.ok(answer.headline.includes("pi/6"), answer.headline);
|
||||
assert.ok(answer.headline.includes("·n"), answer.headline);
|
||||
});
|
||||
|
||||
test("geometry questions route and answer", () => {
|
||||
const circle = answerAdvanced(parseAdvanced("area of a circle with radius 3"));
|
||||
assert.ok(circle.headline.includes("28.27"), circle.headline);
|
||||
const triangle = answerAdvanced(parseAdvanced("triangle with sides 3 4 5"));
|
||||
assert.ok(triangle.headline.includes("right"), triangle.headline);
|
||||
});
|
||||
|
||||
test("digit questions route through the advanced router", () => {
|
||||
const found = answerAdvanced(parseAdvanced("where does 11 first appear in pi"));
|
||||
assert.ok(found.headline.includes("94"), found.headline);
|
||||
// "area of a circle" contains pi implicitly and must NOT land here.
|
||||
assert.equal(parseAdvanced("area of a circle with radius 2").kind, "shapeArea");
|
||||
});
|
||||
|
||||
// A six-digit run needs ~10^6 places; the fast pass cannot settle it, so the
|
||||
// answer must be honest about depth and carry a long-run offer.
|
||||
test("a deep digit search reports its depth and offers a longer run", () => {
|
||||
const answer = answerAdvanced(parseAdvanced("where does 867530 appear in pi"));
|
||||
assert.ok(answer.headline.includes("Not in the first"), answer.headline);
|
||||
assert.notEqual(answer.unresolvedWorkload, null);
|
||||
const offer = longRunOffer(answer.unresolvedWorkload, "test");
|
||||
assert.notEqual(offer, null);
|
||||
assert.equal(offer.depth, 1_000_000);
|
||||
assert.ok(offer.estimatedSeconds > 0);
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Coordinator
|
||||
|
||||
test("coordinator follows up on the standing problem", () => {
|
||||
const coordinator = new MathCoordinator();
|
||||
const solved = coordinator.run("solve", "x^2 - 4 = 0");
|
||||
assert.equal(solved.kind, "value");
|
||||
|
||||
const graphed = coordinator.run("graph", "");
|
||||
assert.equal(graphed.kind, "value");
|
||||
assert.notEqual(coordinator.lastGraph, null);
|
||||
|
||||
const explained = coordinator.run("explain", "");
|
||||
assert.equal(explained.kind, "value");
|
||||
assert.deepEqual(coordinator.stepPosition, { index: 0, total: coordinator.explanationSteps.length });
|
||||
|
||||
const restated = coordinator.run("solve", "");
|
||||
assert.equal(restated.kind, "value");
|
||||
assert.equal(coordinator.lastGraph, null);
|
||||
});
|
||||
|
||||
test("coordinator surfaces a long-run offer for deep searches", async () => {
|
||||
const coordinator = new MathCoordinator();
|
||||
const outcome = await coordinator.answerSpoken("where does 314159 appear in pi");
|
||||
assert.equal(outcome.kind, "value");
|
||||
assert.notEqual(coordinator.pendingLongRun, null);
|
||||
// Declining leaves the shallow answer standing.
|
||||
coordinator.declineLongRun();
|
||||
assert.equal(coordinator.pendingLongRun, null);
|
||||
});
|
||||
|
||||
test("long-run accept phrases are recognised only while an offer stands", async () => {
|
||||
const coordinator = new MathCoordinator();
|
||||
assert.equal(coordinator.handleLongRunUtterance("keep going"), null);
|
||||
await coordinator.answerSpoken("where does 314159 appear in pi");
|
||||
assert.notEqual(coordinator.pendingLongRun, null);
|
||||
const declined = coordinator.handleLongRunUtterance("never mind");
|
||||
assert.equal(declined.kind, "failure");
|
||||
assert.equal(coordinator.pendingLongRun, null);
|
||||
});
|
||||
|
||||
test("the coordinator's gesture contract walks steps and clears", () => {
|
||||
const coordinator = new MathCoordinator();
|
||||
coordinator.run("solve", "2x + 7 = 19");
|
||||
coordinator.run("explain", "");
|
||||
const forward = coordinator.handleRingAction("forward");
|
||||
assert.equal(forward.kind, "value");
|
||||
assert.equal(coordinator.stepPosition.index, 1);
|
||||
const cleared = coordinator.handleRingAction("exit");
|
||||
assert.equal(cleared.kind, "value");
|
||||
assert.equal(coordinator.hasProblem, false);
|
||||
});
|
||||
@@ -1,4 +1,4 @@
|
||||
// Advertisement parsers, checked against the layouts SybilSight confirmed by
|
||||
// Advertisement parsers, checked against layouts confirmed by
|
||||
// HCI capture (G2: "ER"+SN(14)+MAC(6,LE)+flag) and on-disk forensics (R1:
|
||||
// "ER"+MAC(6,wire)+ASCII serial suffix on ring firmware 2.2.7.x).
|
||||
const test = require("node:test");
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
// Ported from SybilSight's GlassesHardwareIdentityTests.
|
||||
//
|
||||
// The reference mapping is the Even Realities app 2.2.0 (`_parseGlassesSku`,
|
||||
// `evenSNName`, `matchModel`). `S211GBBC180304` and `S211GCBC300403` are
|
||||
// serials observed on real hardware, so they are the anchors here rather than
|
||||
|
||||
@@ -0,0 +1,174 @@
|
||||
// These pin the DSP behaviours the microphones app depends on: fractional
|
||||
// delays interpolate rather than round, the per-temple beamformer actually
|
||||
// gains from coherent summation, the direct-correlation TDOA recovers known
|
||||
// delays (including sub-sample ones), the NLMS canceller removes correlated
|
||||
// noise without eating the signal, and the bearing math survives the ±π seam.
|
||||
const test = require("node:test");
|
||||
const assert = require("node:assert/strict");
|
||||
|
||||
const {
|
||||
G2_DEFAULT_GEOMETRY,
|
||||
bearingDegrees,
|
||||
bearingUnitVector,
|
||||
fractionalDelay,
|
||||
DelaySumBeamformer,
|
||||
InterMicNoiseCanceller,
|
||||
gccPhatDelaySamples,
|
||||
steerWorldToDevice,
|
||||
deviceToWorld,
|
||||
fuseBearings,
|
||||
TempleAudioPipeline,
|
||||
bearingFromTdoa,
|
||||
angleInArc,
|
||||
} = require("../.test-build/app/apps/microphones/dsp.js");
|
||||
|
||||
const near = (a, b, eps) => Math.abs(a - b) <= eps;
|
||||
const deg = (d) => (d * Math.PI) / 180;
|
||||
|
||||
const rms = (x, from = 0, to = x.length) => {
|
||||
let sum = 0;
|
||||
for (let i = from; i < to; i++) sum += x[i] * x[i];
|
||||
return Math.sqrt(sum / (to - from));
|
||||
};
|
||||
|
||||
// Deterministic white-ish noise (LCG), so failures reproduce.
|
||||
const makeNoise = (n, seed = 12345) => {
|
||||
const out = new Float32Array(n);
|
||||
let state = seed >>> 0;
|
||||
for (let i = 0; i < n; i++) {
|
||||
state = (state * 1664525 + 1013904223) >>> 0;
|
||||
out[i] = state / 0x80000000 - 1; // uniform in [-1, 1)
|
||||
}
|
||||
return out;
|
||||
};
|
||||
|
||||
test("fractional delay of a ramp by half a sample yields midpoint averages", () => {
|
||||
const ramp = Float32Array.from({ length: 32 }, (_, i) => i);
|
||||
const delayed = fractionalDelay(ramp, 0.5);
|
||||
for (let i = 1; i < ramp.length; i++) {
|
||||
assert.ok(near(delayed[i], (ramp[i] + ramp[i - 1]) / 2, 1e-5));
|
||||
}
|
||||
});
|
||||
|
||||
test("beamformer sums coherently when steered at the source", () => {
|
||||
const sampleRate = 16000;
|
||||
const beamformer = new DelaySumBeamformer(sampleRate);
|
||||
const geometry = G2_DEFAULT_GEOMETRY;
|
||||
const target = { azimuth: 0 };
|
||||
const d = bearingUnitVector(target);
|
||||
const c = geometry.speedOfSound;
|
||||
const pF = geometry.positions.left.front;
|
||||
const pR = geometry.positions.left.rear;
|
||||
// A wavefront from straight ahead reaches each mic early by dot(p, d)/c.
|
||||
const tauF = ((pF.x * d.x + pF.y * d.y) / c) * sampleRate;
|
||||
const tauR = ((pR.x * d.x + pR.y * d.y) / c) * sampleRate;
|
||||
// Frequency chosen so opposite-direction steering misaligns by half a
|
||||
// period — the misaligned beam should nearly cancel.
|
||||
const w = Math.PI / (2 * (tauF - tauR));
|
||||
const n = 2048;
|
||||
const front = new Float32Array(n);
|
||||
const rear = new Float32Array(n);
|
||||
for (let i = 0; i < n; i++) {
|
||||
front[i] = Math.sin(w * (i + tauF));
|
||||
rear[i] = Math.sin(w * (i + tauR));
|
||||
}
|
||||
const aligned = beamformer.beam("left", front, rear, target);
|
||||
const misaligned = beamformer.beam("left", front, rear, { azimuth: Math.PI });
|
||||
// Skip the edge the delay lines zero-fill.
|
||||
const alignedRms = rms(aligned, 32, n);
|
||||
const misalignedRms = rms(misaligned, 32, n);
|
||||
assert.ok(near(alignedRms, Math.SQRT1_2, 0.05)); // full-amplitude sinusoid
|
||||
assert.ok(alignedRms > 2 * misalignedRms);
|
||||
});
|
||||
|
||||
test("direct-correlation TDOA recovers an integer delay", () => {
|
||||
const a = makeNoise(2048);
|
||||
const k = 5;
|
||||
const b = new Float32Array(a.length);
|
||||
for (let i = k; i < a.length; i++) b[i] = a[i - k];
|
||||
assert.ok(near(gccPhatDelaySamples(a, b, 16), k, 0.15));
|
||||
});
|
||||
|
||||
test("direct-correlation TDOA resolves a fractional delay via parabolic interpolation", () => {
|
||||
const a = makeNoise(2048, 777);
|
||||
const k = 3.4;
|
||||
const b = fractionalDelay(a, k);
|
||||
assert.ok(near(gccPhatDelaySamples(a, b, 16), k, 0.3));
|
||||
});
|
||||
|
||||
test("NLMS canceller removes correlated noise and keeps the signal", () => {
|
||||
const n = 8000;
|
||||
const sampleRate = 16000;
|
||||
const tone = new Float32Array(n);
|
||||
for (let i = 0; i < n; i++) tone[i] = 0.5 * Math.sin((2 * Math.PI * 440 * i) / sampleRate);
|
||||
const reference = makeNoise(n, 424242);
|
||||
const primary = new Float32Array(n);
|
||||
// The primary hears the noise through a short path (2-sample lag, 0.8 gain).
|
||||
for (let i = 0; i < n; i++) {
|
||||
primary[i] = tone[i] + 0.8 * (i >= 2 ? reference[i - 2] : 0);
|
||||
}
|
||||
const anc = new InterMicNoiseCanceller();
|
||||
const out = anc.process(primary, reference);
|
||||
// Judge the converged tail only.
|
||||
const half = n / 2;
|
||||
const primaryRms = rms(primary, half, n);
|
||||
const outRms = rms(out, half, n);
|
||||
const toneRms = rms(tone, half, n);
|
||||
assert.ok(outRms < 0.8 * primaryRms); // noise reduced
|
||||
assert.ok(outRms > 0.5 * toneRms); // signal survives
|
||||
// Residual noise power (beyond the tone) drops substantially.
|
||||
const noiseInPower = primaryRms * primaryRms - toneRms * toneRms;
|
||||
const noiseOutPower = Math.max(0, outRms * outRms - toneRms * toneRms);
|
||||
assert.ok(noiseOutPower < 0.5 * noiseInPower);
|
||||
});
|
||||
|
||||
test("bearingFromTdoa is antisymmetric and clamps to ±90°", () => {
|
||||
const sampleRate = 16000;
|
||||
const spacing = 0.11;
|
||||
const positive = bearingFromTdoa(2, sampleRate, spacing);
|
||||
const negative = bearingFromTdoa(-2, sampleRate, spacing);
|
||||
assert.ok(positive > 0);
|
||||
assert.ok(near(positive, -negative, 1e-9));
|
||||
assert.ok(near(bearingFromTdoa(100, sampleRate, spacing), Math.PI / 2, 1e-9));
|
||||
assert.ok(near(bearingFromTdoa(-100, sampleRate, spacing), -Math.PI / 2, 1e-9));
|
||||
assert.equal(bearingFromTdoa(0, sampleRate, spacing), 0);
|
||||
});
|
||||
|
||||
test("angleInArc handles wraparound at ±180°", () => {
|
||||
const center = deg(170);
|
||||
const halfWidth = deg(30);
|
||||
assert.ok(angleInArc(deg(-175), center, halfWidth)); // 15° away, across the seam
|
||||
assert.ok(angleInArc(deg(150), center, halfWidth));
|
||||
assert.ok(!angleInArc(deg(130), center, halfWidth)); // 40° away
|
||||
assert.ok(!angleInArc(deg(-130), center, halfWidth)); // 60° away, across the seam
|
||||
});
|
||||
|
||||
test("fuseBearings takes the circular mean across the ±180° seam", () => {
|
||||
const fused = fuseBearings(deg(170), 1, deg(-170), 1);
|
||||
assert.ok(near(Math.abs(fused), Math.PI, 1e-6));
|
||||
assert.ok(near(fuseBearings(deg(10), 1, deg(20), 1), deg(15), 1e-6));
|
||||
// Weights pull the mean toward the more confident temple.
|
||||
const weighted = fuseBearings(0, 3, Math.PI / 2, 1);
|
||||
assert.ok(near(weighted, Math.atan2(0.25, 0.75), 1e-6));
|
||||
});
|
||||
|
||||
test("world and device frames round-trip through the head orientation", () => {
|
||||
const head = { compassHeading: deg(40), imuYaw: deg(5) };
|
||||
const world = deg(120);
|
||||
const steered = steerWorldToDevice(world, head);
|
||||
assert.ok(near(deviceToWorld(steered.azimuth, head), world, 1e-9));
|
||||
assert.ok(near(bearingDegrees(steered), 120 - 45, 1e-9));
|
||||
});
|
||||
|
||||
test("temple pipeline matches the raw beam with ANC disabled", () => {
|
||||
const pipeline = new TempleAudioPipeline("right", 16000);
|
||||
pipeline.enableANC = false;
|
||||
const beamformer = new DelaySumBeamformer(16000);
|
||||
const front = makeNoise(512, 1);
|
||||
const rear = makeNoise(512, 2);
|
||||
const target = { azimuth: deg(30) };
|
||||
const viaPipeline = pipeline.process(front, rear, target);
|
||||
const direct = beamformer.beam("right", front, rear, target);
|
||||
assert.equal(viaPipeline.length, direct.length);
|
||||
for (let i = 0; i < direct.length; i++) assert.equal(viaPipeline[i], direct[i]);
|
||||
});
|
||||
@@ -0,0 +1,81 @@
|
||||
// Introduction-based speaker naming: spoken "I'm Alice" / "this is Bob"
|
||||
// shapes rename auto-numbered speakers, with guardrails against common
|
||||
// non-name continuations.
|
||||
const test = require("node:test");
|
||||
const assert = require("node:assert/strict");
|
||||
|
||||
const {
|
||||
inferIntroducedName,
|
||||
isGenericSpeakerName,
|
||||
pendingApplies,
|
||||
PENDING_INTRODUCTION_TTL_MS,
|
||||
} = require("../.test-build/app/apps/microphones/name-guess.js");
|
||||
|
||||
test("self-introductions are recognized", () => {
|
||||
assert.deepEqual(inferIntroducedName("Hi, I'm Alice."), { name: "Alice", kind: "self" });
|
||||
assert.deepEqual(inferIntroducedName("Hello everyone, my name is Bob Smith and I work here."), {
|
||||
name: "Bob Smith",
|
||||
kind: "self",
|
||||
});
|
||||
assert.deepEqual(inferIntroducedName("You can call me Kai."), { name: "Kai", kind: "self" });
|
||||
assert.deepEqual(inferIntroducedName("Good morning, this is Alice speaking."), {
|
||||
name: "Alice",
|
||||
kind: "self",
|
||||
});
|
||||
});
|
||||
|
||||
test("third-party introductions are recognized", () => {
|
||||
assert.deepEqual(inferIntroducedName("Everyone, this is Bob."), { name: "Bob", kind: "third-party" });
|
||||
assert.deepEqual(inferIntroducedName("Come meet Carol!"), { name: "Carol", kind: "third-party" });
|
||||
assert.deepEqual(inferIntroducedName("Her name is Dana."), { name: "Dana", kind: "third-party" });
|
||||
});
|
||||
|
||||
test("common non-name continuations do not trigger", () => {
|
||||
assert.equal(inferIntroducedName("I'm not sure about that."), null);
|
||||
assert.equal(inferIntroducedName("I'm So excited."), null);
|
||||
assert.equal(inferIntroducedName("I'm Sorry about earlier."), null);
|
||||
assert.equal(inferIntroducedName("this is Fine, thanks"), null);
|
||||
assert.equal(inferIntroducedName("I'm Going to the store."), null);
|
||||
});
|
||||
|
||||
test("states, feelings, and progressive verbs are rejected even capitalized", () => {
|
||||
assert.equal(inferIntroducedName("I'm Hungry, let's eat."), null);
|
||||
assert.equal(inferIntroducedName("I'm Wanting to leave soon."), null);
|
||||
assert.equal(inferIntroducedName("I'm Exhausted after that."), null);
|
||||
assert.equal(inferIntroducedName("I'm Heading out now."), null);
|
||||
assert.equal(inferIntroducedName("I'm Nervous about the demo."), null);
|
||||
assert.equal(inferIntroducedName("I'm Married, by the way."), null);
|
||||
assert.equal(inferIntroducedName("this is Ridiculous... wait no, this is Awesome"), null);
|
||||
assert.equal(inferIntroducedName("I'm Waiting outside."), null);
|
||||
});
|
||||
|
||||
test("unusual but real names still pass the heuristic tier", () => {
|
||||
// The regex tier stays permissive here; the on-device LLM tier gets the
|
||||
// final say when it's available.
|
||||
assert.deepEqual(inferIntroducedName("Hi, I'm Ming."), { name: "Ming", kind: "self" });
|
||||
assert.deepEqual(inferIntroducedName("I'm Priya from the design team."), {
|
||||
name: "Priya",
|
||||
kind: "self",
|
||||
});
|
||||
});
|
||||
|
||||
test("lowercase candidates are rejected (ASR proper nouns are capitalized)", () => {
|
||||
assert.equal(inferIntroducedName("i'm alice"), null);
|
||||
});
|
||||
|
||||
test("generic speaker names are detected", () => {
|
||||
assert.equal(isGenericSpeakerName("Speaker 3"), true);
|
||||
assert.equal(isGenericSpeakerName("Alice"), false);
|
||||
assert.equal(isGenericSpeakerName("Speaker three"), false);
|
||||
});
|
||||
|
||||
test("pending third-party introduction applies to the right person", () => {
|
||||
const pending = { name: "Bob", bySpeakerId: 1, atMs: 1000 };
|
||||
assert.equal(pendingApplies(pending, 2, "Speaker 2", 2000), true);
|
||||
// Not the introducer themselves.
|
||||
assert.equal(pendingApplies(pending, 1, "Speaker 1", 2000), false);
|
||||
// Never overwrites a real name.
|
||||
assert.equal(pendingApplies(pending, 2, "Dana", 2000), false);
|
||||
// Expires.
|
||||
assert.equal(pendingApplies(pending, 2, "Speaker 2", 1000 + PENDING_INTRODUCTION_TTL_MS + 1), false);
|
||||
});
|
||||
@@ -0,0 +1,221 @@
|
||||
// Pins the mic_control wire codec against the firmware contract in g2flash's
|
||||
// patches/mic_control.c (microphone-configurations branch): field-103 control
|
||||
// records, the 21-byte field-104 status, and the 21-byte 'SM' stream header
|
||||
// with concatenated (not interleaved) channel payloads.
|
||||
const test = require("node:test");
|
||||
const assert = require("node:assert/strict");
|
||||
|
||||
const {
|
||||
MIC_CHANNEL_KEYS,
|
||||
micChannelKey,
|
||||
micChannelLabel,
|
||||
templeActive,
|
||||
encodeMicControl,
|
||||
decodeMicStatus,
|
||||
decodeMicStreamFrame,
|
||||
splitConcatenatedPcm16,
|
||||
defaultMicConfig,
|
||||
micEnabled,
|
||||
setMicEnabled,
|
||||
isStockAudioPacket,
|
||||
MIC_FLAG_BEAMFORM,
|
||||
MIC_FLAG_ARM_HW,
|
||||
SM_HEADER_BYTES,
|
||||
} = require("../.test-build/app/apps/microphones/mic-protocol.js");
|
||||
|
||||
test("configure record layout matches the firmware contract", () => {
|
||||
const config = {
|
||||
...defaultMicConfig(),
|
||||
source: "pdm",
|
||||
channelMask: 0b11,
|
||||
codec: "raw",
|
||||
format: "pcm16",
|
||||
sampleRateHz: 16000,
|
||||
lc3BitrateBps: 32000,
|
||||
beamform: true,
|
||||
armHardware: false,
|
||||
};
|
||||
const record = encodeMicControl("configure", config);
|
||||
assert.equal(record.length, 13);
|
||||
assert.deepEqual([...record.slice(0, 4)], [0x4d, 0x43, 1, 1]); // 'M','C',ver,CONFIGURE
|
||||
assert.equal(record[4], 1); // pdm
|
||||
assert.equal(record[5], 0b11);
|
||||
assert.equal(record[6], 1); // raw
|
||||
assert.equal(record[7], 0); // pcm16
|
||||
assert.equal(record[8] | (record[9] << 8), 160); // 16000/100
|
||||
assert.equal(record[10] | (record[11] << 8), 320); // 32000/100
|
||||
assert.equal(record[12], MIC_FLAG_BEAMFORM);
|
||||
});
|
||||
|
||||
test("ops encode as 1..4 and non-configure records carry no payload", () => {
|
||||
assert.equal(encodeMicControl("configure")[3], 1);
|
||||
assert.equal(encodeMicControl("query")[3], 2);
|
||||
assert.equal(encodeMicControl("stop")[3], 3);
|
||||
assert.equal(encodeMicControl("renew")[3], 4);
|
||||
assert.equal(encodeMicControl("query").length, 4);
|
||||
});
|
||||
|
||||
test("sample rate clamps to the firmware's 8-48 kHz window", () => {
|
||||
const low = encodeMicControl("configure", { ...defaultMicConfig(), sampleRateHz: 1000 });
|
||||
assert.equal(low[8] | (low[9] << 8), 80);
|
||||
const high = encodeMicControl("configure", { ...defaultMicConfig(), sampleRateHz: 96000 });
|
||||
assert.equal(high[8] | (high[9] << 8), 480);
|
||||
});
|
||||
|
||||
test("arm-hardware flag bit is 0x02", () => {
|
||||
const record = encodeMicControl("configure", { ...defaultMicConfig(), armHardware: true });
|
||||
assert.equal(record[12] & MIC_FLAG_ARM_HW, MIC_FLAG_ARM_HW);
|
||||
});
|
||||
|
||||
function buildStatus(overrides = {}) {
|
||||
const values = {
|
||||
active: 1,
|
||||
source: 1,
|
||||
chanMask: 0b11,
|
||||
codec: 1,
|
||||
format: 0,
|
||||
rateDiv: 160,
|
||||
brDiv: 0,
|
||||
flags: 0x03,
|
||||
hwArmed: 1,
|
||||
sideId: 2,
|
||||
frames: 123456,
|
||||
effRateDiv: 160,
|
||||
...overrides,
|
||||
};
|
||||
const body = new Uint8Array(21);
|
||||
body[0] = 0x4d;
|
||||
body[1] = 0x43;
|
||||
body[2] = 1;
|
||||
body[3] = values.active;
|
||||
body[4] = values.source;
|
||||
body[5] = values.chanMask;
|
||||
body[6] = values.codec;
|
||||
body[7] = values.format;
|
||||
body[8] = values.rateDiv & 0xff;
|
||||
body[9] = values.rateDiv >> 8;
|
||||
body[10] = values.brDiv & 0xff;
|
||||
body[11] = values.brDiv >> 8;
|
||||
body[12] = values.flags;
|
||||
body[13] = values.hwArmed;
|
||||
body[14] = values.sideId;
|
||||
body[15] = values.frames & 0xff;
|
||||
body[16] = (values.frames >> 8) & 0xff;
|
||||
body[17] = (values.frames >> 16) & 0xff;
|
||||
body[18] = (values.frames >> 24) & 0xff;
|
||||
body[19] = values.effRateDiv & 0xff;
|
||||
body[20] = values.effRateDiv >> 8;
|
||||
return body;
|
||||
}
|
||||
|
||||
test("status decode: sides, rates, frames, flags", () => {
|
||||
const status = decodeMicStatus(buildStatus());
|
||||
assert.ok(status);
|
||||
assert.equal(status.active, true);
|
||||
assert.equal(status.source, "pdm");
|
||||
assert.equal(status.side, "left"); // sideId 2 = left
|
||||
assert.equal(status.sampleRateHz, 16000);
|
||||
assert.equal(status.effectiveRateHz, 16000);
|
||||
assert.equal(status.framesEmitted, 123456);
|
||||
assert.equal(status.beamform, true);
|
||||
assert.equal(status.armHardware, true);
|
||||
assert.equal(decodeMicStatus(buildStatus({ sideId: 1 })).side, "right");
|
||||
});
|
||||
|
||||
test("status decode rejects short or foreign records", () => {
|
||||
assert.equal(decodeMicStatus(buildStatus().slice(0, 19)), null);
|
||||
const wrongMagic = buildStatus();
|
||||
wrongMagic[0] = 0x58;
|
||||
assert.equal(decodeMicStatus(wrongMagic), null);
|
||||
});
|
||||
|
||||
function buildSmFrame({ channels = 2, samplesPerChannel = 4, angle = -30, ssr = 500, truncated = false } = {}) {
|
||||
const payLen = channels * samplesPerChannel * 2;
|
||||
const data = new Uint8Array(SM_HEADER_BYTES + payLen);
|
||||
data[0] = 0x53;
|
||||
data[1] = 0x4d;
|
||||
data[2] = 1;
|
||||
data[3] = 0x01 | (truncated ? 0x80 : 0);
|
||||
data[4] = 0x39;
|
||||
data[5] = 0x05; // seq 1337
|
||||
data[6] = 0xa0;
|
||||
data[7] = 0x86;
|
||||
data[8] = 0x01;
|
||||
data[9] = 0x00; // tick 100000
|
||||
data[10] = channels;
|
||||
data[11] = 160 & 0xff;
|
||||
data[12] = 0;
|
||||
data[13] = 0; // pcm16
|
||||
data[14] = 1; // raw
|
||||
const angleU = angle < 0 ? angle + 0x10000 : angle;
|
||||
data[15] = angleU & 0xff;
|
||||
data[16] = angleU >> 8;
|
||||
data[17] = ssr & 0xff;
|
||||
data[18] = ssr >> 8;
|
||||
data[19] = payLen & 0xff;
|
||||
data[20] = payLen >> 8;
|
||||
// Channel blocks are CONCATENATED: channel 0 all-1000s, channel 1 all-(-2000)s.
|
||||
for (let c = 0; c < channels; c++) {
|
||||
const value = c === 0 ? 1000 : -2000;
|
||||
const unsigned = value < 0 ? value + 0x10000 : value;
|
||||
for (let s = 0; s < samplesPerChannel; s++) {
|
||||
const base = SM_HEADER_BYTES + c * samplesPerChannel * 2 + s * 2;
|
||||
data[base] = unsigned & 0xff;
|
||||
data[base + 1] = unsigned >> 8;
|
||||
}
|
||||
}
|
||||
return data;
|
||||
}
|
||||
|
||||
test("SM frame decode: header fields and negative angle", () => {
|
||||
const frame = decodeMicStreamFrame(buildSmFrame());
|
||||
assert.ok(frame);
|
||||
assert.equal(frame.sequence, 1337);
|
||||
assert.equal(frame.deviceTickMs, 100000);
|
||||
assert.equal(frame.channelCount, 2);
|
||||
assert.equal(frame.sampleRateHz, 16000);
|
||||
assert.equal(frame.codec, "raw");
|
||||
assert.equal(frame.angleDegrees, -30);
|
||||
assert.equal(frame.ssr, 500);
|
||||
assert.equal(frame.truncated, false);
|
||||
assert.equal(frame.payload.length, 16);
|
||||
assert.equal(decodeMicStreamFrame(buildSmFrame({ truncated: true })).truncated, true);
|
||||
});
|
||||
|
||||
test("SM payload splits as concatenated channel blocks", () => {
|
||||
const frame = decodeMicStreamFrame(buildSmFrame({ samplesPerChannel: 3 }));
|
||||
const channels = splitConcatenatedPcm16(frame);
|
||||
assert.ok(channels);
|
||||
assert.equal(channels.length, 2);
|
||||
assert.equal(channels[0].length, 3);
|
||||
for (const sample of channels[0]) assert.ok(Math.abs(sample - 1000 / 32768) < 1e-6);
|
||||
for (const sample of channels[1]) assert.ok(Math.abs(sample - -2000 / 32768) < 1e-6);
|
||||
});
|
||||
|
||||
test("stock packets are recognized by their fixed 205-byte size", () => {
|
||||
assert.equal(isStockAudioPacket(new Uint8Array(205)), true);
|
||||
assert.equal(isStockAudioPacket(new Uint8Array(204)), false);
|
||||
assert.equal(decodeMicStreamFrame(new Uint8Array(205)), null);
|
||||
});
|
||||
|
||||
test("host-side mic selection: four channels, temple activity derived", () => {
|
||||
assert.equal(MIC_CHANNEL_KEYS.length, 4);
|
||||
assert.equal(micChannelKey("left", "front"), "leftFront");
|
||||
assert.equal(micChannelKey("right", "rear"), "rightRear");
|
||||
assert.equal(micChannelLabel("leftRear"), "L rear");
|
||||
const config = defaultMicConfig();
|
||||
assert.equal(templeActive(config, "left"), true);
|
||||
config.hostMics = { leftFront: false, leftRear: false, rightFront: true, rightRear: false };
|
||||
assert.equal(templeActive(config, "left"), false);
|
||||
assert.equal(templeActive(config, "right"), true);
|
||||
});
|
||||
|
||||
test("channel mask helpers target front bit0 / rear bit1", () => {
|
||||
let config = { ...defaultMicConfig(), channelMask: 0b01 };
|
||||
assert.equal(micEnabled(config, "front"), true);
|
||||
assert.equal(micEnabled(config, "rear"), false);
|
||||
config = setMicEnabled(config, "rear", true);
|
||||
assert.equal(config.channelMask, 0b11);
|
||||
config = setMicEnabled(config, "front", false);
|
||||
assert.equal(config.channelMask, 0b10);
|
||||
});
|
||||
@@ -0,0 +1,114 @@
|
||||
// Speaker-dot tracking for the Sonic Radar: dots are world-frame, follow
|
||||
// their speaker as they wander (smooth for jitter, snap for real moves,
|
||||
// glide live while talking), and brightness-code active speech vs. silence
|
||||
// age. These pin the behaviours the radar display depends on.
|
||||
const test = require("node:test");
|
||||
const assert = require("node:assert/strict");
|
||||
|
||||
const {
|
||||
SPEAKER_DOT_TTL_MS,
|
||||
normalizeDeg,
|
||||
smoothAngleDeg,
|
||||
placeDotForUtterance,
|
||||
trackSpeakingDot,
|
||||
clearSpeaking,
|
||||
pruneDots,
|
||||
dotBrightness,
|
||||
} = require("../.test-build/app/apps/microphones/radar-dots.js");
|
||||
|
||||
const alice = { speakerId: 1, name: "Alice", color: "#ff0000" };
|
||||
const bob = { speakerId: 2, name: "Bob", color: "#00ff00" };
|
||||
|
||||
test("normalizeDeg wraps into (-180, 180]", () => {
|
||||
assert.equal(normalizeDeg(0), 0);
|
||||
assert.equal(normalizeDeg(180), 180);
|
||||
assert.equal(normalizeDeg(-180), 180);
|
||||
assert.equal(normalizeDeg(190), -170);
|
||||
assert.equal(normalizeDeg(-190), 170);
|
||||
assert.equal(normalizeDeg(720), 0);
|
||||
});
|
||||
|
||||
test("smoothAngleDeg follows the short way across the seam", () => {
|
||||
assert.equal(smoothAngleDeg(null, 400, 0.5), 40);
|
||||
// 170 -> -170 is 20 degrees the short way, not 340 the long way.
|
||||
const smoothed = smoothAngleDeg(170, -170, 0.5);
|
||||
assert.ok(Math.abs(normalizeDeg(smoothed - 180)) < 1e-9);
|
||||
});
|
||||
|
||||
test("an utterance creates a dot for a new speaker", () => {
|
||||
const dots = placeDotForUtterance([], alice, 30, 1000);
|
||||
assert.equal(dots.length, 1);
|
||||
assert.equal(dots[0].speakerId, 1);
|
||||
assert.equal(dots[0].worldAngleDeg, 30);
|
||||
assert.equal(dots[0].lastSpokenMs, 1000);
|
||||
assert.equal(dots[0].speaking, false);
|
||||
});
|
||||
|
||||
test("a nearby utterance smooths the dot instead of jumping", () => {
|
||||
let dots = placeDotForUtterance([], alice, 30, 1000);
|
||||
dots = placeDotForUtterance(dots, alice, 50, 2000);
|
||||
// Halfway with MOVE_SMOOTHING = 0.5.
|
||||
assert.equal(dots.length, 1);
|
||||
assert.equal(dots[0].worldAngleDeg, 40);
|
||||
assert.equal(dots[0].lastSpokenMs, 2000);
|
||||
});
|
||||
|
||||
test("a distant utterance snaps: the person actually moved", () => {
|
||||
let dots = placeDotForUtterance([], alice, 0, 1000);
|
||||
dots = placeDotForUtterance(dots, alice, 120, 2000);
|
||||
assert.equal(dots[0].worldAngleDeg, 120);
|
||||
});
|
||||
|
||||
test("trackSpeakingDot marks the nearest dot and glides it toward the live DOA", () => {
|
||||
let dots = placeDotForUtterance([], alice, 0, 1000);
|
||||
dots = placeDotForUtterance(dots, bob, 90, 1000);
|
||||
const matched = trackSpeakingDot(dots, 100, 2000);
|
||||
assert.equal(matched, true);
|
||||
const bobDot = dots.find((dot) => dot.speakerId === 2);
|
||||
const aliceDot = dots.find((dot) => dot.speakerId === 1);
|
||||
assert.equal(bobDot.speaking, true);
|
||||
assert.equal(bobDot.lastSpokenMs, 2000);
|
||||
// Glided a quarter of the way (LIVE_SMOOTHING = 0.25).
|
||||
assert.equal(bobDot.worldAngleDeg, 92.5);
|
||||
assert.equal(aliceDot.speaking, false);
|
||||
assert.equal(aliceDot.lastSpokenMs, 1000);
|
||||
});
|
||||
|
||||
test("trackSpeakingDot ignores voices far from every known dot", () => {
|
||||
const dots = placeDotForUtterance([], alice, 0, 1000);
|
||||
dots[0].speaking = true;
|
||||
const matched = trackSpeakingDot(dots, 90, 2000);
|
||||
assert.equal(matched, false);
|
||||
assert.equal(dots[0].speaking, false);
|
||||
assert.equal(dots[0].worldAngleDeg, 0);
|
||||
});
|
||||
|
||||
test("clearSpeaking silences every dot", () => {
|
||||
const dots = placeDotForUtterance([], alice, 0, 1000);
|
||||
trackSpeakingDot(dots, 5, 2000);
|
||||
assert.equal(dots[0].speaking, true);
|
||||
clearSpeaking(dots);
|
||||
assert.equal(dots[0].speaking, false);
|
||||
});
|
||||
|
||||
test("pruneDots drops speakers silent past the TTL", () => {
|
||||
let dots = placeDotForUtterance([], alice, 0, 0);
|
||||
dots = placeDotForUtterance(dots, bob, 90, SPEAKER_DOT_TTL_MS);
|
||||
const pruned = pruneDots(dots, SPEAKER_DOT_TTL_MS + 1);
|
||||
assert.equal(pruned.length, 1);
|
||||
assert.equal(pruned[0].speakerId, 2);
|
||||
});
|
||||
|
||||
test("brightness: full while speaking, fading with silence age", () => {
|
||||
const dots = placeDotForUtterance([], alice, 0, 0);
|
||||
const dot = dots[0];
|
||||
dot.speaking = true;
|
||||
assert.equal(dotBrightness(dot, 0), 255);
|
||||
dot.speaking = false;
|
||||
const fresh = dotBrightness(dot, 0);
|
||||
const halfway = dotBrightness(dot, SPEAKER_DOT_TTL_MS / 2);
|
||||
const expired = dotBrightness(dot, SPEAKER_DOT_TTL_MS);
|
||||
assert.equal(fresh, 220);
|
||||
assert.ok(halfway < fresh && halfway > expired);
|
||||
assert.equal(expired, 80);
|
||||
});
|
||||
@@ -0,0 +1,177 @@
|
||||
// These pin the parts the transcript UI depends on: keyword emotion hits with
|
||||
// negation scoping, lexicon polarity signs, the 5-bucket thresholds, the
|
||||
// summary rollup with its 60-point trend cap, and the search alias mappings.
|
||||
const test = require("node:test");
|
||||
const assert = require("node:assert/strict");
|
||||
|
||||
const {
|
||||
detectEmotion,
|
||||
scoreSentiment,
|
||||
sentimentBucket,
|
||||
analyzeLine,
|
||||
summarize,
|
||||
searchableMetadata,
|
||||
inferredEmotionFilter,
|
||||
} = require("../.test-build/app/apps/microphones/sentiment.js");
|
||||
|
||||
test("keyword emotion hits", () => {
|
||||
assert.equal(detectEmotion("this keeps failing").emotion, "frustrated");
|
||||
assert.equal(detectEmotion("I am so worried about tomorrow").emotion, "anxious");
|
||||
assert.equal(detectEmotion("what a relief, thank goodness").emotion, "relieved");
|
||||
assert.equal(detectEmotion("that's disgusting").emotion, "disgusted");
|
||||
assert.equal(detectEmotion("enough is enough, this is unacceptable").emotion, "angry");
|
||||
});
|
||||
|
||||
test("keyword hits carry the keyword source and calibrated confidence", () => {
|
||||
const single = detectEmotion("this keeps failing");
|
||||
assert.equal(single.source, "keyword");
|
||||
assert.equal(single.confidence, 0.7);
|
||||
|
||||
const double = detectEmotion("I am frustrated and annoyed");
|
||||
assert.equal(double.emotion, "frustrated");
|
||||
assert.equal(double.confidence, 0.88);
|
||||
});
|
||||
|
||||
test("whole words only: mad must not match made", () => {
|
||||
assert.equal(detectEmotion("we made a decision yesterday").emotion, "neutral");
|
||||
});
|
||||
|
||||
test("negated cues are ignored", () => {
|
||||
const detection = detectEmotion("I'm not happy about this");
|
||||
assert.notEqual(detection.emotion, "happy");
|
||||
assert.ok(scoreSentiment("I'm not happy about this") < 0);
|
||||
});
|
||||
|
||||
test("a contrast boundary ends the negation scope", () => {
|
||||
// "not happy, but angry" expresses anger: the negation before "but" must
|
||||
// not suppress the cue after it.
|
||||
assert.equal(detectEmotion("I am not happy, but angry").emotion, "angry");
|
||||
});
|
||||
|
||||
test("equal evidence for two emotions stays neutral", () => {
|
||||
const detection = detectEmotion("I am happy and sad");
|
||||
assert.equal(detection.emotion, "neutral");
|
||||
assert.equal(detection.confidence, 0.4);
|
||||
});
|
||||
|
||||
test("polarity signs", () => {
|
||||
assert.ok(scoreSentiment("This is great and wonderful") > 0);
|
||||
assert.ok(scoreSentiment("That was awful and terrible") < 0);
|
||||
assert.equal(scoreSentiment("The meeting starts at noon"), 0);
|
||||
assert.equal(scoreSentiment(""), 0);
|
||||
});
|
||||
|
||||
test("negation flips polarity in scoring", () => {
|
||||
assert.ok(scoreSentiment("This is not good") < 0);
|
||||
assert.ok(scoreSentiment("This is not bad") > 0);
|
||||
});
|
||||
|
||||
test("scores stay in [-1, 1]", () => {
|
||||
assert.ok(scoreSentiment("great great great great great great") <= 1);
|
||||
assert.ok(scoreSentiment("awful awful awful awful awful awful") >= -1);
|
||||
});
|
||||
|
||||
test("sentences are scored independently and averaged", () => {
|
||||
const mixed = scoreSentiment("This is wonderful! This is terrible.");
|
||||
assert.equal(mixed, 0);
|
||||
});
|
||||
|
||||
test("bucket edges", () => {
|
||||
assert.equal(sentimentBucket(0.31), "veryPositive");
|
||||
assert.equal(sentimentBucket(0.3), "positive");
|
||||
assert.equal(sentimentBucket(0.11), "positive");
|
||||
assert.equal(sentimentBucket(0.1), "neutral");
|
||||
assert.equal(sentimentBucket(0), "neutral");
|
||||
assert.equal(sentimentBucket(-0.1), "neutral");
|
||||
assert.equal(sentimentBucket(-0.11), "negative");
|
||||
assert.equal(sentimentBucket(-0.3), "negative");
|
||||
assert.equal(sentimentBucket(-0.31), "veryNegative");
|
||||
});
|
||||
|
||||
test("analyzeLine combines score and emotion", () => {
|
||||
const line = analyzeLine("this keeps failing");
|
||||
assert.equal(line.emotion, "frustrated");
|
||||
assert.ok(line.score < 0);
|
||||
assert.equal(line.emotionConfidence, 0.7);
|
||||
});
|
||||
|
||||
test("summarize counts buckets and emotions", () => {
|
||||
const lines = [
|
||||
{ score: 0.8, emotion: "happy", emotionConfidence: 0.9 },
|
||||
{ score: 0.2, emotion: "happy", emotionConfidence: 0.7 },
|
||||
{ score: 0, emotion: "neutral", emotionConfidence: 0.76 },
|
||||
{ score: -0.2, emotion: "frustrated", emotionConfidence: 0.7 },
|
||||
{ score: -0.8, emotion: "angry", emotionConfidence: 0.9 },
|
||||
];
|
||||
const summary = summarize(lines);
|
||||
assert.equal(summary.averageScore, 0);
|
||||
assert.equal(summary.bucket, "neutral");
|
||||
assert.deepEqual(summary.bucketCounts, {
|
||||
veryPositive: 1,
|
||||
positive: 1,
|
||||
neutral: 1,
|
||||
negative: 1,
|
||||
veryNegative: 1,
|
||||
});
|
||||
assert.deepEqual(summary.emotionDistribution, { happy: 2, neutral: 1, frustrated: 1, angry: 1 });
|
||||
assert.equal(summary.trend.length, 5);
|
||||
assert.deepEqual(summary.trend.map((p) => p.index), [0, 1, 2, 3, 4]);
|
||||
});
|
||||
|
||||
test("summarize of nothing is neutral and empty", () => {
|
||||
const summary = summarize([]);
|
||||
assert.equal(summary.averageScore, 0);
|
||||
assert.equal(summary.bucket, "neutral");
|
||||
assert.deepEqual(summary.trend, []);
|
||||
assert.deepEqual(summary.emotionDistribution, {});
|
||||
});
|
||||
|
||||
test("trend caps at 60 points and keeps the extreme emotion per chunk", () => {
|
||||
const lines = [];
|
||||
for (let i = 0; i < 200; i++) {
|
||||
lines.push({ score: 0.1, emotion: "calm", emotionConfidence: 0.7 });
|
||||
}
|
||||
// A spike inside a chunk must survive downsampling as that chunk's emotion.
|
||||
lines[10] = { score: -0.9, emotion: "angry", emotionConfidence: 0.9 };
|
||||
const summary = summarize(lines);
|
||||
assert.ok(summary.trend.length <= 60);
|
||||
assert.ok(summary.trend.length > 0);
|
||||
assert.ok(summary.trend.some((p) => p.emotion === "angry"));
|
||||
// Chunk averages must still reflect the spike rather than drop it.
|
||||
const spikeChunk = summary.trend.find((p) => p.emotion === "angry");
|
||||
assert.ok(spikeChunk.score < 0.1);
|
||||
});
|
||||
|
||||
test("searchableMetadata contains aliases and sentiment terms", () => {
|
||||
const angry = searchableMetadata("angry", -0.5);
|
||||
for (const alias of ["angry", "mad", "furious", "rage", "hostile"]) {
|
||||
assert.ok(angry.includes(alias), `missing alias: ${alias}`);
|
||||
}
|
||||
assert.ok(angry.includes("very negative"));
|
||||
assert.ok(angry.includes("negative sentiment"));
|
||||
|
||||
const sad = searchableMetadata("sad", -0.2);
|
||||
assert.ok(sad.includes("upset"));
|
||||
assert.ok(sad.includes("negative sentiment"));
|
||||
|
||||
const happy = searchableMetadata("happy", 0.5);
|
||||
assert.ok(happy.includes("joyful"));
|
||||
assert.ok(happy.includes("very positive"));
|
||||
});
|
||||
|
||||
test("inferredEmotionFilter parses natural-language queries", () => {
|
||||
assert.equal(inferredEmotionFilter("show me conversations where the speaker was angry"), "angry");
|
||||
assert.equal(inferredEmotionFilter("meetings where someone was fed up"), "frustrated");
|
||||
assert.equal(inferredEmotionFilter("find the joyful moments"), "happy");
|
||||
assert.equal(inferredEmotionFilter("what did we discuss about the budget"), null);
|
||||
});
|
||||
|
||||
test("inferredEmotionFilter rejects ambiguity and negation", () => {
|
||||
// Ambiguous aliases such as "mad" and "sure" must not hijack searches.
|
||||
assert.equal(inferredEmotionFilter("the mad scientist presentation"), null);
|
||||
assert.equal(inferredEmotionFilter("are you sure about the numbers"), null);
|
||||
// Two distinct emotions fall back to normal ranked retrieval.
|
||||
assert.equal(inferredEmotionFilter("happy or sad conversations"), null);
|
||||
// A negated emotion is not a request for that emotion.
|
||||
assert.equal(inferredEmotionFilter("the speaker was not angry"), null);
|
||||
});
|
||||
@@ -1,6 +1,5 @@
|
||||
// Left↔right pair grouping on the advertised serial, closest-first ordering,
|
||||
// the "Closest"/"Yours" disambiguators (ported from SybilSight's
|
||||
// PairingScanPresentation tests), and the row presentation.
|
||||
// the "Closest"/"Yours" disambiguators, and the row presentation.
|
||||
const test = require("node:test");
|
||||
const assert = require("node:assert/strict");
|
||||
const fs = require("node:fs");
|
||||
|
||||
+8
-1
@@ -15,6 +15,13 @@
|
||||
"../app/g2/ble-proximity.ts",
|
||||
"../app/g2/even-advertisement.ts",
|
||||
"../app/g2/glasses-artwork.ts",
|
||||
"../app/g2/pairing-candidates.ts"
|
||||
"../app/g2/pairing-candidates.ts",
|
||||
"../app/apps/calculator/math/*.ts",
|
||||
"../app/apps/microphones/mic-protocol.ts",
|
||||
"../app/apps/calculator/calculator-commands.ts",
|
||||
"../app/apps/microphones/sentiment.ts",
|
||||
"../app/apps/microphones/dsp.ts",
|
||||
"../app/apps/microphones/radar-dots.ts",
|
||||
"../app/apps/microphones/name-guess.ts"
|
||||
]
|
||||
}
|
||||
Reference in new issue
Block a user