Skip to content

Linger is An Open-Source Personal Agent That Runs Fully on Your PC. We aim to break Big Tech’s grip on AI by bringing powerful local AI to everyday computers through efficient model–harness co-design, so everyone can run their own.

feat(web): let controls tell Voice Mode what clicking them risks

Kilyn0c37de980dc8
diff --git a/apps/web/AGENTS.md b/apps/web/AGENTS.md
index bd937903..14ffb2da 100644
--- a/apps/web/AGENTS.md
+++ b/apps/web/AGENTS.md
@@ -263,6 +263,15 @@ build:assets` to check the initial JS budget.
`lib/date-format.ts` stays on `APP_LOCALE` for surfaces that are still
English, so one screen does not mix an English sentence with a Chinese
date.
+ - A translated control tells Voice Mode what clicking it does with a
+ marker, never with words in its label: `data-voice-risk="never"` for
+ deleting, removing, sending, leaving, signing out, paying, archiving or
+ discarding (spoken commands never click it, the live model asks first),
+ `data-voice-risk="confirm"` for other decisions such as approve, deny or
+ revoke (the live model asks first), and `data-voice-close` on the button
+ that closes its panel or dialog. An `ActionMenu` item takes `voiceRisk`.
+ `voice-risk-markers.test.ts` fails when a control named by such a message
+ lacks its marker.
- Names and text that come from TeamHub or from people (Agent names, message
previews, server error messages) are data and are shown as they are.
- Add a language: add it to `LANGUAGES` and `catalogLoaders` in
diff --git a/apps/web/src/components/ui/action-menu.tsx b/apps/web/src/components/ui/action-menu.tsx
index 62ec7777..2327014c 100644
--- a/apps/web/src/components/ui/action-menu.tsx
+++ b/apps/web/src/components/ui/action-menu.tsx
@@ -29,6 +29,12 @@ export interface ActionMenuItem {
label: string;
onSelect?: () => void;
separatorBefore?: boolean;
+ /**
+ * What Voice Mode risks by clicking the item, as `data-voice-risk` (see
+ * voice-ui-bridge): "confirm" asks the Human first, "never" also keeps it
+ * out of spoken commands.
+ */
+ voiceRisk?: "confirm" | "never";
}
export function ActionMenu({
@@ -412,6 +418,7 @@ function ActionMenuItemButton({
className={`${className} ${
item.danger ? "text-destructive" : "text-foreground"
}`}
+ data-voice-risk={item.voiceRisk}
disabled={item.disabled}
onClick={(event) => {
event.preventDefault();
@@ -490,6 +497,7 @@ function ActionSubmenu({
{items.map((child) => (
<button
className="flex min-h-[33px] w-full items-center gap-2 rounded-sm px-2 py-1.5 text-left text-sm text-foreground outline-none hover:bg-accent focus:bg-accent disabled:pointer-events-none disabled:opacity-50"
+ data-voice-risk={child.voiceRisk}
disabled={child.disabled}
key={child.label}
onClick={(event) => {
diff --git a/apps/web/src/components/ui/modal-dialog.tsx b/apps/web/src/components/ui/modal-dialog.tsx
index 009f0e87..975524c7 100644
--- a/apps/web/src/components/ui/modal-dialog.tsx
+++ b/apps/web/src/components/ui/modal-dialog.tsx
@@ -138,6 +138,7 @@ export function ModalDialog({
) : null}
</div>
<button
+ data-voice-close
aria-label={t(commonMessages.close)}
className="app-dialog-close"
ref={closeButtonRef}
diff --git a/apps/web/src/features/rooms/chat/voice-mode/live/voice-live-page-tools.test.ts b/apps/web/src/features/rooms/chat/voice-mode/live/voice-live-page-tools.test.ts
index 93f51cb9..24bc462e 100644
--- a/apps/web/src/features/rooms/chat/voice-mode/live/voice-live-page-tools.test.ts
+++ b/apps/web/src/features/rooms/chat/voice-mode/live/voice-live-page-tools.test.ts
@@ -2,6 +2,8 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import { createHttpTeamHubClient } from "@/features/teamhub/teamhub-client";
+import { commonMessages } from "@/i18n/common.messages";
+import { resetLanguageForTest, setLanguage, translate } from "@/i18n/language";
import {
TeamHubTestServer,
teamHubErrorResponse,
@@ -18,7 +20,14 @@ import {
} from "./voice-live-page-tools";
const page = vi.hoisted(() => ({
- elements: [] as Array<{ id: string; name: string }>,
+ elements: [] as Array<{
+ id: string;
+ name: string;
+ /** The control's `data-voice-risk` marker. */
+ risk?: string;
+ }>,
+ /** The element on screen behind each element id, made once per id. */
+ onScreen: new Map<string, HTMLElement>(),
rooms: [] as Array<{ id: string; name: string }>,
sections: [] as Array<{ id: string; name: string }>,
results: [] as Array<{ id: string; name: string }>,
@@ -63,11 +72,23 @@ const act = vi.hoisted(() => (name: string) => (...args: unknown[]) => {
page.ran.push([name, ...args]);
return page.works;
});
-vi.mock("../voice-ui-bridge", () => ({
+vi.mock("../voice-ui-bridge", async (importOriginal) => ({
+ voiceRiskyTarget: (
+ await importOriginal<typeof import("../voice-ui-bridge")>()
+ ).voiceRiskyTarget,
chatComposerName: "Chat composer",
// Each element id stands for one element on screen.
- offeredVoiceElement: (id: string) =>
- page.elements.some((element) => element.id === id) ? { id } : undefined,
+ offeredVoiceElement: (id: string) => {
+ const offered = page.elements.find((element) => element.id === id);
+ if (!offered) return undefined;
+ let element = page.onScreen.get(id);
+ if (!element) {
+ element = document.createElement("button");
+ if (offered.risk) element.dataset.voiceRisk = offered.risk;
+ page.onScreen.set(id, element);
+ }
+ return element;
+ },
voiceClick: (id: string) => {
if (!act("click")(id)) return undefined;
const toggled = page.toggles.get(id);
@@ -492,14 +513,57 @@ describe("model page tools", () => {
);
});
+ it("asks before marked clicks in either language, whatever their names say", async () => {
+ for (const language of ["en", "zh-CN"] as const) {
+ await setLanguage(language);
+ const retry = translate(commonMessages.tryAgain);
+ page.ran = [];
+ page.onScreen.clear();
+ page.elements = [
+ { ...element("el-1", retry), risk: "never" },
+ { ...element("el-2", "Copy"), risk: "confirm" },
+ element("el-3", retry),
+ ];
+ const lines = readPageTargets(context).split("\n");
+ const listed = (ref: string) =>
+ lines.find((line) => line.startsWith(`${ref} `)) ?? "";
+ expect(listed("e1"), language).toContain(retry);
+ expect(listed("e1"), language).toMatch(/\(needs confirmation\)$/);
+ expect(listed("e2"), language).toMatch(
+ /^e2 Copy.*\(needs confirmation\)$/,
+ );
+ expect(listed("e3"), language).not.toMatch(/needs confirmation/);
+ for (const target of ["e1", "e2"]) {
+ await expect(
+ runPageAction({ action: "click", target }, context),
+ ).resolves.toMatchObject({ status: "needs_confirmation" });
+ await expect(
+ runPageAction(
+ { action: "click", target, confirmed: "True" },
+ context,
+ ),
+ ).resolves.toMatchObject({ status: "done" });
+ }
+ await expect(
+ runPageAction({ action: "click", target: "e3" }, context),
+ ).resolves.toMatchObject({ status: "done" });
+ expect(page.ran, language).toEqual([
+ ["click", "el-1"],
+ ["click", "el-2"],
+ ["click", "el-3"],
+ ]);
+ }
+ resetLanguageForTest();
+ });
+
it("asks before risky clicks and runs them once confirmed", async () => {
- expect(riskyTarget("Delete message")).toBe(true);
- expect(riskyTarget("Leave room")).toBe(true);
- expect(riskyTarget("Pocket Note")).toBe(false);
+ expect(riskyTarget(undefined, "Delete message")).toBe(true);
+ expect(riskyTarget(undefined, "Leave room")).toBe(true);
+ expect(riskyTarget(undefined, "Pocket Note")).toBe(false);
// Approval decisions wait for the Human's yes too.
for (const name of ["Approve", "Approve and run", "Deny"])
- expect(riskyTarget(name)).toBe(true);
- expect(riskyTarget("Exit Voice Mode")).toBe(false);
+ expect(riskyTarget(undefined, name)).toBe(true);
+ expect(riskyTarget(undefined, "Exit Voice Mode")).toBe(false);
await expect(
runPageAction({ action: "click", target: "Delete message" }, context),
).resolves.toMatchObject({ status: "needs_confirmation" });
diff --git a/apps/web/src/features/rooms/chat/voice-mode/live/voice-live-page-tools.ts b/apps/web/src/features/rooms/chat/voice-mode/live/voice-live-page-tools.ts
index 0236f6c0..633bf1da 100644
--- a/apps/web/src/features/rooms/chat/voice-mode/live/voice-live-page-tools.ts
+++ b/apps/web/src/features/rooms/chat/voice-mode/live/voice-live-page-tools.ts
@@ -39,6 +39,7 @@ import {
voiceTextFields,
voiceFill,
voiceInPlaceState,
+ voiceRiskyTarget,
voiceWindowAction,
type VoiceScrollDirection,
type VoiceWindowAction,
@@ -73,15 +74,10 @@ const genericField = /^(?:input|textbox|text box|message box|composer)$/iu;
/**
* Deleting, sending, leaving, paying, approving or other decisions that
* cannot be undone: clicked only after the Human said yes to this click.
+ * The control says so with `data-voice-risk` (see voiceRiskyTarget).
*/
-const riskyName =
- /approve|deny|reject|decline|authori[sz]e|grant|accept|delete|remove|send|submit|leave|exit|quit|pay|purchase|buy|transfer|kick|ban|block|archive|reset|sign ?out|log ?out|discard|revoke|uninstall|destroy/iu;
-
-/** Leaving Voice Mode itself is never confirmed. */
-const leavesVoiceMode = /^(?:exit|leave|end|close) voice(?: mode)?$/iu;
-
-export function riskyTarget(name: string) {
- return !leavesVoiceMode.test(name.trim()) && riskyName.test(name);
+export function riskyTarget(element: HTMLElement | undefined, name: string) {
+ return voiceRiskyTarget(element, name);
}
function normalized(text: string) {
@@ -200,7 +196,7 @@ export function readPageTargets(context: VoiceCommandContext, focus = "") {
add(
"e",
{ kind: "element", element, name },
- `${name}${riskyTarget(name) ? " (needs confirmation)" : ""}`,
+ `${name}${riskyTarget(element, name) ? " (needs confirmation)" : ""}`,
);
}
for (const field of voiceTextFields().slice(0, pageTargetLimits.fields))
@@ -649,7 +645,7 @@ async function clickOrOpen(
if (room) return openRoom(context, room.id);
if (element) {
const name = label(element);
- if (riskyTarget(name) && !confirmed)
+ if (riskyTarget(offeredVoiceElement(element.id), name) && !confirmed)
return {
status: "needs_confirmation",
detail: `"${name}" may not be undoable. First ask the user in the first person whether to click it (e.g. "Should I click ${name} for you?"), and call again with confirmed=true only after they clearly agree to this click; no answer or a different question is not agreement.`,
diff --git a/apps/web/src/features/rooms/chat/voice-mode/voice-risk-markers.test.ts b/apps/web/src/features/rooms/chat/voice-mode/voice-risk-markers.test.ts
new file mode 100644
index 00000000..291e5731
--- /dev/null
+++ b/apps/web/src/features/rooms/chat/voice-mode/voice-risk-markers.test.ts
@@ -0,0 +1,284 @@
+import ts from "typescript";
+import { describe, expect, it } from "vitest";
+
+import type { Message } from "@/i18n/messages";
+import {
+ voiceClosesByEnglishName,
+ voiceRiskOfEnglishName,
+} from "./voice-ui-bridge";
+
+// A translated control is named in the language on screen, so Voice Mode
+// cannot tell from its name that clicking it deletes, sends or closes
+// something. The control says so with `data-voice-risk` or
+// `data-voice-close`; this test finds every control named by a message whose
+// English name Voice Mode would treat as risky or as a close button, and
+// fails when the control lacks the marker.
+
+const messageModules = import.meta.glob<
+ Record<string, Record<string, Message>>
+>("/src/**/*.messages.ts", { eager: true });
+const sourceFiles = import.meta.glob<string>(
+ ["/src/**/*.tsx", "!/src/**/*.test.tsx", "!/src/test/**"],
+ { eager: true, import: "default", query: "?raw" },
+);
+
+/** Messages by their exported group name and their own name. */
+const groups = new Map<string, Record<string, Message>>();
+for (const exports of Object.values(messageModules))
+ for (const [name, messages] of Object.entries(exports))
+ groups.set(name, messages);
+
+/**
+ * Controls named by a risky-sounding message that are not that action, by
+ * `file: namespace.name`, with the reason.
+ */
+const notActions: Record<string, string> = {};
+
+type Need = "confirm" | "never" | "close";
+
+interface Finding {
+ file: string;
+ message: string;
+ english: string;
+ need: Need;
+ line: number;
+}
+
+function needs(english: string): Need | undefined {
+ if (voiceClosesByEnglishName(english)) return "close";
+ return voiceRiskOfEnglishName(english);
+}
+
+const controlTag =
+ /^(?:button|a|summary)$|(?:Button|MenuItem|Item|Link|Trigger|Toggle|Action)$/u;
+const nameAttributes = new Set(["aria-label", "title", "label", "text"]);
+
+type JsxTag = ts.JsxOpeningElement | ts.JsxSelfClosingElement;
+
+function attribute(tag: JsxTag, name: string) {
+ return tag.attributes.properties.find(
+ (property): property is ts.JsxAttribute =>
+ ts.isJsxAttribute(property) && property.name.getText() === name,
+ );
+}
+
+function isControl(tag: JsxTag) {
+ return (
+ controlTag.test(tag.tagName.getText()) ||
+ attribute(tag, "onClick") !== undefined ||
+ attribute(tag, "onSelect") !== undefined
+ );
+}
+
+function hasMarker(tag: JsxTag, need: Need) {
+ const marker = attribute(
+ tag,
+ need === "close" ? "data-voice-close" : "data-voice-risk",
+ );
+ if (!marker) return false;
+ if (need === "close") return true;
+ const value = marker.initializer;
+ // A value worked out at render time is trusted; a literal must match.
+ return !value || !ts.isStringLiteral(value) || value.text === need;
+}
+
+/** The JSX tag a name inside it names: an attribute's tag or a text's control. */
+function namedTag(node: ts.Node): JsxTag | undefined {
+ for (let current = node.parent; current; current = current.parent) {
+ if (ts.isJsxAttribute(current)) {
+ const tag = current.parent.parent;
+ return nameAttributes.has(current.name.getText()) && isControl(tag)
+ ? tag
+ : undefined;
+ }
+ if (ts.isJsxElement(current) && isControl(current.openingElement))
+ return current.openingElement;
+ if (
+ ts.isFunctionLike(current) ||
+ ts.isVariableDeclaration(current) ||
+ ts.isPropertyAssignment(current)
+ )
+ return undefined;
+ }
+ return undefined;
+}
+
+/** A menu item described as an object: `{ label: t(m.delete), voiceRisk: "never" }`. */
+function namedItem(node: ts.Node) {
+ for (let current = node.parent; current; current = current.parent) {
+ if (ts.isPropertyAssignment(current))
+ return current.name.getText() === "label" &&
+ ts.isObjectLiteralExpression(current.parent)
+ ? current.parent
+ : undefined;
+ if (ts.isFunctionLike(current) || ts.isJsxAttribute(current))
+ return undefined;
+ }
+ return undefined;
+}
+
+function itemMarker(item: ts.ObjectLiteralExpression, need: Need) {
+ const key = need === "close" ? "voiceClose" : "voiceRisk";
+ const property = item.properties.find(
+ (entry) => entry.name?.getText() === key,
+ );
+ if (!property) return false;
+ if (need === "close" || !ts.isPropertyAssignment(property)) return true;
+ const value = property.initializer;
+ return !ts.isStringLiteral(value) || value.text === need;
+}
+
+/** `m` for `import { fooMessages as m }` or `const m = fooMessages`. */
+function aliases(file: ts.SourceFile) {
+ const names = new Map<string, string>();
+ const visit = (node: ts.Node) => {
+ if (
+ ts.isImportSpecifier(node) &&
+ groups.has(node.propertyName?.text ?? node.name.text)
+ )
+ names.set(node.name.text, node.propertyName?.text ?? node.name.text);
+ if (
+ ts.isVariableDeclaration(node) &&
+ ts.isIdentifier(node.name) &&
+ node.initializer &&
+ ts.isIdentifier(node.initializer) &&
+ groups.has(node.initializer.text)
+ )
+ names.set(node.name.text, node.initializer.text);
+ ts.forEachChild(node, visit);
+ };
+ visit(file);
+ return names;
+}
+
+/** The messages an expression may show: `m.name`, or either side of `a ? m.x : m.y`. */
+function messagesOf(
+ node: ts.Expression,
+ names: Map<string, string>,
+): Message[] {
+ if (ts.isParenthesizedExpression(node))
+ return messagesOf(node.expression, names);
+ if (ts.isConditionalExpression(node))
+ return [
+ ...messagesOf(node.whenTrue, names),
+ ...messagesOf(node.whenFalse, names),
+ ];
+ if (ts.isPropertyAccessExpression(node) && ts.isIdentifier(node.expression)) {
+ const group = groups.get(names.get(node.expression.text) ?? "");
+ const message = group?.[node.name.text];
+ return message ? [message] : [];
+ }
+ return [];
+}
+
+function forms(message: Message): string[] {
+ const source = message.source as unknown;
+ return typeof source === "string"
+ ? [source]
+ : Object.values(source as Record<string, string>);
+}
+
+/** Every place a variable holding a message's text is shown. */
+function uses(file: ts.SourceFile, name: string) {
+ const found: ts.Node[] = [];
+ const visit = (node: ts.Node) => {
+ const parent = node.parent;
+ if (
+ ts.isIdentifier(node) &&
+ node.text === name &&
+ !(
+ (ts.isVariableDeclaration(parent) ||
+ ts.isJsxAttribute(parent) ||
+ ts.isPropertyAccessExpression(parent) ||
+ ts.isPropertyAssignment(parent)) &&
+ parent.name === node
+ )
+ )
+ found.push(node);
+ ts.forEachChild(node, visit);
+ };
+ visit(file);
+ return found;
+}
+
+function missingMarkers(path: string, text: string): Finding[] {
+ const file = ts.createSourceFile(
+ path,
+ text,
+ ts.ScriptTarget.Latest,
+ true,
+ ts.ScriptKind.TSX,
+ );
+ const names = aliases(file);
+ if (names.size === 0) return [];
+ const findings: Finding[] = [];
+ const check = (place: ts.Node, message: Message, need: Need) => {
+ const key = `${path}: ${message.id}`;
+ if (key in notActions) return;
+ const tag = namedTag(place);
+ const item = tag ? undefined : namedItem(place);
+ if ((tag && hasMarker(tag, need)) || (item && itemMarker(item, need)))
+ return;
+ if (!tag && !item) return;
+ findings.push({
+ file: path,
+ message: message.id,
+ english: forms(message).join(" / "),
+ need,
+ line: file.getLineAndCharacterOfPosition(place.getStart()).line + 1,
+ });
+ };
+ const visit = (node: ts.Node) => {
+ if (ts.isCallExpression(node) && node.arguments[0]) {
+ for (const message of messagesOf(node.arguments[0], names)) {
+ const need = forms(message).map(needs).find(Boolean);
+ if (!need) continue;
+ check(node, message, need);
+ // `const label = t(m.delete)` shown later as `{label}`.
+ const holder = node.parent;
+ if (ts.isVariableDeclaration(holder) && ts.isIdentifier(holder.name))
+ for (const use of uses(file, holder.name.text))
+ check(use, message, need);
+ if (
+ ts.isBinaryExpression(holder) &&
+ ts.isVariableDeclaration(holder.parent) &&
+ ts.isIdentifier(holder.parent.name)
+ )
+ for (const use of uses(file, holder.parent.name.text))
+ check(use, message, need);
+ }
+ }
+ ts.forEachChild(node, visit);
+ };
+ visit(file);
+ return findings;
+}
+
+describe("Voice Mode markers on translated controls", () => {
+ it("reads the client's message modules and components", () => {
+ expect(groups.has("commonMessages")).toBe(true);
+ expect(Object.keys(sourceFiles).length).toBeGreaterThan(100);
+ });
+
+ it("marks every translated control Voice Mode must not click unasked or closes by", () => {
+ const findings = Object.entries(sourceFiles).flatMap(([path, text]) =>
+ missingMarkers(path, text),
+ );
+ expect(
+ findings.map(
+ ({ file, line, message, english, need }) =>
+ `${file}:${line} ${message} "${english}" needs ${
+ need === "close" ? "data-voice-close" : `data-voice-risk="${need}"`
+ }`,
+ ),
+ ).toEqual([]);
+ });
+
+ it("knows each exception by a control that still exists", () => {
+ for (const key of Object.keys(notActions)) {
+ const [path, id] = key.split(": ") as [string, string];
+ const name = id.split(".")[1]!;
+ expect(sourceFiles[path], key).toContain(`.${name}`);
+ }
+ });
+});
diff --git a/apps/web/src/features/rooms/chat/voice-mode/voice-ui-bridge.test.ts b/apps/web/src/features/rooms/chat/voice-mode/voice-ui-bridge.test.ts
index 79a12e61..51be4823 100644
--- a/apps/web/src/features/rooms/chat/voice-mode/voice-ui-bridge.test.ts
+++ b/apps/web/src/features/rooms/chat/voice-mode/voice-ui-bridge.test.ts
@@ -1,5 +1,8 @@
// @vitest-environment jsdom
import { afterEach, describe, expect, it, vi } from "vitest";
+import { settingsMessages } from "@/features/settings/settings.messages";
+import { commonMessages } from "@/i18n/common.messages";
+import { resetLanguageForTest, setLanguage, translate } from "@/i18n/language";
import { defineGlobalProperty } from "@/test/global-properties";
import {
@@ -24,6 +27,7 @@ import {
} from "./voice-ui-bridge";
afterEach(() => {
+ resetLanguageForTest();
resetVoiceUiForTest();
document.body.innerHTML = "";
window.history.replaceState(null, "", "/");
@@ -392,6 +396,47 @@ describe("Voice Mode screen actions", () => {
expect(voiceClick(file.id)).toBeUndefined();
});
+ it("keeps destructive and close buttons apart by their markers in either language", async () => {
+ for (const language of ["en", "zh-CN"] as const) {
+ await setLanguage(language);
+ const settings = translate(settingsMessages.title);
+ const retry = translate(commonMessages.tryAgain);
+ const close = translate(commonMessages.close);
+ // Marked controls are kept out whatever their names say; an unmarked
+ // one is still judged by its English name.
+ const names = [settings, retry, "Tidy up", "Delete room"];
+ document.body.innerHTML = `<main>
+ <button>${settings}</button>
+ <button data-voice-risk="never">${retry}</button>
+ <button data-voice-risk="never">Tidy up</button>
+ <button>Delete room</button>
+ </main>
+ <aside aria-label="Daily report" style="position: fixed">
+ <button aria-label="Pin"></button>
+ <button aria-label="${close}" data-voice-close></button>
+ </aside>`;
+ const box = { top: 100, left: 500, bottom: 120, right: 560 };
+ for (const element of document.querySelectorAll<HTMLElement>(
+ "button, aside",
+ ))
+ element.getBoundingClientRect = () =>
+ ({ ...box, width: 60, height: 20 }) as DOMRect;
+
+ const offered = (options?: { riskyTargets: boolean }) =>
+ collectVoiceElements(120, options)
+ .map(({ name }) => name)
+ .filter((name) => names.includes(name));
+ expect(offered(), language).toEqual([settings]);
+ expect(offered({ riskyTargets: true }), language).toEqual(names);
+ expect(voiceCanClose(), language).toBe(true);
+ // Without its marker the close button is found by its English name only.
+ document
+ .querySelector("[data-voice-close]")!
+ .removeAttribute("data-voice-close");
+ expect(voiceCanClose(), language).toBe(language === "en");
+ }
+ });
+
it("lists named text fields and fills one as typing would, never a password", () => {
document.body.innerHTML = `
<main>
diff --git a/apps/web/src/features/rooms/chat/voice-mode/voice-ui-bridge.ts b/apps/web/src/features/rooms/chat/voice-mode/voice-ui-bridge.ts
index 8e254778..4095f2f8 100644
--- a/apps/web/src/features/rooms/chat/voice-mode/voice-ui-bridge.ts
+++ b/apps/web/src/features/rooms/chat/voice-mode/voice-ui-bridge.ts
@@ -158,12 +158,58 @@ export interface VoiceElement {
const clickable =
'a[href], button, summary, [role="button"], [role="link"], [role="tab"], [role="option"], [role="menuitem"], [role="treeitem"], input[type="checkbox"], input[type="radio"], [role="switch"], [role="checkbox"], [role="radio"], [role="menuitemcheckbox"], [role="menuitemradio"]';
/**
- * Never clicked by the voice command pipeline: the Human does these
- * themselves. The live model may still list them, behind its spoken
- * confirmation (see collectVoiceElements' riskyTargets).
+ * What clicking a control risks, said by the control itself so it holds in
+ * every language: `data-voice-risk="confirm"` is clicked by the live model
+ * only after the Human agreed to that click; `data-voice-risk="never"` is
+ * that too, and the voice command pipeline never clicks it (deleting,
+ * removing, sending, leaving, signing out, paying, archiving, discarding).
+ * A control without the marker is judged by its English name, as before the
+ * interface had languages; a translated control always carries the marker.
*/
-const destructive =
+export type VoiceRisk = "confirm" | "never";
+
+/** Never clicked by the voice command pipeline: the Human does these themselves. */
+const destructiveName =
/delete|remove|send|log ?out|sign ?out|leave|pay|archive|discard/i;
+/** Clicked by the live model only after the Human said yes to this click. */
+const riskyName =
+ /approve|deny|reject|decline|authori[sz]e|grant|accept|delete|remove|send|submit|leave|exit|quit|pay|purchase|buy|transfer|kick|ban|block|archive|reset|sign ?out|log ?out|discard|revoke|uninstall|destroy/iu;
+/** Leaving Voice Mode itself is never confirmed. */
+const leavesVoiceMode = /^(?:exit|leave|end|close) voice(?: mode)?$/iu;
+
+function markedRisk(element: HTMLElement | undefined): VoiceRisk | undefined {
+ const risk = element?.dataset.voiceRisk;
+ return risk === "confirm" || risk === "never" ? risk : undefined;
+}
+
+/**
+ * Whether clicking this control needs the Human's yes first. `name` is the
+ * name the control was offered under; it decides only when the control has
+ * no marker or is no longer on screen.
+ */
+export function voiceRiskyTarget(
+ element: HTMLElement | undefined,
+ name: string,
+) {
+ if (markedRisk(element)) return true;
+ return !leavesVoiceMode.test(name.trim()) && riskyName.test(name);
+}
+
+/**
+ * The marker a control named `name` in English needs, so that it is treated
+ * in every language as its English name is treated without one.
+ */
+export function voiceRiskOfEnglishName(name: string): VoiceRisk | undefined {
+ if (destructiveName.test(name)) return "never";
+ if (!leavesVoiceMode.test(name.trim()) && riskyName.test(name))
+ return "confirm";
+ return undefined;
+}
+
+function destructive(element: HTMLElement, name: string) {
+ const risk = markedRisk(element);
+ return risk ? risk === "never" : destructiveName.test(name);
+}
const areaOrder: VoiceElementArea[] = [
"dialog",
"navigation",
@@ -339,7 +385,8 @@ export function collectVoiceElements(
)
continue;
const name = elementName(element);
- if (!name || (!options.riskyTargets && destructive.test(name))) continue;
+ if (!name || (!options.riskyTargets && destructive(element, name)))
+ continue;
found.push({
area: elementArea(element, rect),
element,
@@ -775,12 +822,21 @@ export function voiceScroll(
/** Floating panels and dialogs that can be closed, offered with the turn, by id. */
let offeredOverlays = new Map<string, HTMLElement>();
+/** An unmarked close button is told by its English name. */
const closeName = /^(close|dismiss|hide)\b|^×$/i;
+export function voiceClosesByEnglishName(name: string) {
+ return closeName.test(name);
+}
+/** The button marked `data-voice-close`, or else one named like a close button. */
function closeButton(overlay: HTMLElement) {
- return Array.from(
+ const buttons = Array.from(
overlay.querySelectorAll<HTMLElement>('button, [role="button"]'),
- ).find((button) => closeName.test(elementName(button)));
+ );
+ return (
+ buttons.find((button) => button.hasAttribute("data-voice-close")) ??
+ buttons.find((button) => closeName.test(elementName(button)))
+ );
}
function openOverlays() {