Files
loki/scripts/test/widget-voice.ts
CatoandMao Nakamoto 39aae9a651 fix(widget): don't offer a mic the site's policy forbids (#474)
Reported: "Microphone permission denied" on both FleetCrown and OrangeCat.
Measured in the browser rather than guessed:

  orangecat.ch  featurePolicyAllowsMic: false
                permissionState: "denied"   (not "prompt")
                getUserMedia -> NotAllowedError
  fleetcrown    featurePolicyAllowsMic: true
                permissionState: "prompt"   (works)

Two different situations behind one error message. OrangeCat sends
`permissions-policy: camera=(), microphone=(), geolocation=()` from
next.config.js. `microphone=()` is an EMPTY allowlist — denied for every
origin including the site itself — so the browser never shows a prompt at
all. There is nothing the visitor can allow.

The bug is ours: navigator.mediaDevices.getUserMedia still EXISTS in that
state, so isVoiceSupported() passed and we drew a "Speak" button that could
only ever fail, then blamed the visitor's permissions for it.

isVoiceSupported now consults document.featurePolicy, so a policy-blocked
site simply never sees the button — the same progressive enhancement the
function already applied to a missing MediaRecorder or an insecure origin.

An unknown answer means ALLOWED, deliberately: featurePolicy is
non-standard and absent in some browsers, and hiding a working mic there
would be a worse failure than a click that fails with a readable message.

This is the half that is centrally fixable — one bundle, every customer
site, including sites we will never see. The other half is not, and cannot
be: Permissions-Policy is the host document's decision by design and no
script can override it. So the customer-facing docs now say plainly that
the mic needs `microphone=(self)`, what the symptom looks like, and that
everything else in the widget works regardless.

Pinned by four assertions in scripts/test/widget-voice.ts covering denied,
allowed, API-absent and API-throwing. Proven by mutation: making the check
always return true turns exactly the "denies the microphone" assertion red.

Co-authored-by: Mao Nakamoto <41178744+maonakamoto@users.noreply.github.com>
2026-09-03 17:20:06 -07:00

115 lines
4.4 KiB
TypeScript

// Dictation must never eat what the visitor already typed.
//
// The mic appends into the same textarea the visitor was using, and people
// dictate in bursts — record, read it back, record more. Replacing instead of
// appending would silently destroy the sentence they just wrote, on someone
// else's site, with no undo. These pin the merge rules.
// Run: npx tsx scripts/test/widget-voice.ts
import { formatElapsed, isMicrophoneAllowedByPolicy, mergeTranscript } from "../../widget/voice";
let pass = 0;
let fail = 0;
function ok(cond: boolean, label: string) {
if (cond) {
pass++;
} else {
fail++;
console.error(`✗ ${label}`);
}
}
const MAX = 2000;
// ---- mergeTranscript ----
ok(
mergeTranscript("", "hello there", MAX) === "hello there",
"empty box takes the transcript as-is",
);
ok(
mergeTranscript("the button", "is broken", MAX) === "the button is broken",
"appends with a single joining space",
);
ok(
mergeTranscript("the button ", "is broken", MAX) === "the button is broken",
"does not double the space when the existing text already ends in one",
);
ok(
mergeTranscript("first line\n", "second", MAX) === "first line\nsecond",
"a trailing newline counts as whitespace — no space is inserted",
);
ok(mergeTranscript("kept", " ", MAX) === "kept", "a whitespace-only transcript changes nothing");
ok(mergeTranscript("kept", "", MAX) === "kept", "an empty transcript changes nothing");
ok(mergeTranscript("", " padded ", MAX) === "padded", "the incoming transcript is trimmed");
// The cap is the same 2000 the ingest zod schema enforces. Exceeding it client
// side would produce a submission the API rejects after the visitor spoke.
ok(mergeTranscript("a".repeat(1999), "bbb", MAX).length === MAX, "never exceeds the field cap");
ok(
mergeTranscript("", "x".repeat(2500), MAX).length === MAX,
"a single over-long transcript is clipped to the cap",
);
ok(
mergeTranscript("a".repeat(2100), "", MAX).length === MAX,
"an already-over-cap box is clipped rather than grown",
);
// ---- Permissions-Policy: the reason a "Speak" button could only ever fail ----
//
// orangecat.ch sends `permissions-policy: camera=(), microphone=(), geolocation=()`.
// An empty allowlist denies the mic to EVERY origin including the site itself,
// so getUserMedia rejects with NotAllowedError and no prompt is ever shown —
// measured there as permissionState "denied", not "prompt".
//
// The trap: navigator.mediaDevices.getUserMedia still EXISTS in that state. A
// support check that only looks for the API therefore passes, draws the
// button, and hands the visitor an error they cannot resolve — there is
// nothing for them to allow. Only the policy tells the truth.
const realDocument = (globalThis as { document?: unknown }).document;
function withFeaturePolicy(value: unknown, run: () => void) {
(globalThis as { document?: unknown }).document = value;
try {
run();
} finally {
if (realDocument === undefined) delete (globalThis as { document?: unknown }).document;
else (globalThis as { document?: unknown }).document = realDocument;
}
}
withFeaturePolicy({ featurePolicy: { allowsFeature: (f: string) => f !== "microphone" } }, () => {
ok(
isMicrophoneAllowedByPolicy() === false,
"a document whose policy denies the microphone reports it as blocked",
);
});
withFeaturePolicy({ featurePolicy: { allowsFeature: () => true } }, () => {
ok(isMicrophoneAllowedByPolicy() === true, "an allowing policy reports allowed");
});
// Unknown must mean allowed: featurePolicy is non-standard and missing in some
// browsers. Failing closed there would hide a WORKING mic, which is a worse
// error than a click that fails with a readable message.
withFeaturePolicy({}, () => {
ok(isMicrophoneAllowedByPolicy() === true, "no featurePolicy API — treated as allowed");
});
withFeaturePolicy(
{
featurePolicy: {
allowsFeature: () => {
throw new Error("boom");
},
},
},
() => {
ok(isMicrophoneAllowedByPolicy() === true, "a throwing featurePolicy is treated as allowed");
},
);
// ---- formatElapsed ----
ok(formatElapsed(0) === "0:00", "zero renders as 0:00");
ok(formatElapsed(7_000) === "0:07", "seconds are zero-padded");
ok(formatElapsed(62_000) === "1:02", "crosses into minutes");
ok(formatElapsed(600_000) === "10:00", "two-digit minutes");
ok(formatElapsed(-5_000) === "0:00", "negative clamps to zero rather than rendering 0:-5");
console.log(`${pass} passed, ${fail} failed`);
process.exit(fail === 0 ? 0 : 1);