Files
kandev/apps/web/e2e/tests/chat/toolbar-overflow.spec.ts
T
João Salavisa 1fdeda904b feat: add voice mode for chat input (#1159)
* feat: add voice mode for chat input

Adds a voice input button to the chat composer with three transcription engines:
in-browser Web Speech API, in-browser Whisper via @huggingface/transformers, and
a server-side OpenAI Whisper fallback gated on KANDEV_VOICE_OPENAI_API_KEY.

User-configurable from a new /settings/voice-mode page:
- Master on/off toggle (defaults to on; opt-out, not opt-in)
- Engine preference (auto / Web Speech / Whisper Web / Whisper Server)
- Language hint (auto-detect or BCP-47 pinned)
- Activation mode (click-to-toggle or hold-to-talk)
- Auto-send after transcription
- Whisper Web model size (tiny / base / small)
- Editable Cmd+Shift+M keyboard shortcut

Voice settings live under user_settings.voice_mode as a nested JSON object —
no schema migration. Setting changes broadcast via the existing
user.settings.updated WS event so any open chat tab updates live.

The mic button is rendered on the right of the composer alongside the send
button (round primary fill; destructive fill with pulse ring while recording).
On browsers without a usable engine (e.g. iOS Chrome over HTTP) the button
stays visible as a muted greyed icon — tapping it surfaces a toast with the
reason (typically a missing secure context).

Whisper Web runs in a Web Worker with fp16 decoder weights (avoids the
MatMulNBits scale-missing crash that q4/q8 hit on WASM). Models are pulled
from the onnx-community/* mirror and cached by transformers.js in the Cache
Storage on first use.

* fix: address voice mode PR review feedback and E2E selector clash

Bot-review fixes from #1159:
- Map http.MaxBytesError from c.FormFile to 413 instead of bare 400.
- Strip BCP-47 region suffix before passing language hint to Whisper Web.
- Recover from worker crash: terminate + null worker + reset ready flag so
  next init/transcribe creates a fresh worker instead of hanging.
- Read live store state via storeApi.getState() in voice-mode settings
  savers to avoid stale-closure clobbering concurrent settings updates.
- Detach Web Speech callbacks before abort() so trailing onend/onerror
  events don't mutate hook state after cancel().
- Spread caller init before method/body in voice-api fetch so a caller-
  supplied init can't override the multipart POST.
- Replace t.Fatalf with t.Errorf+return inside test HTTP handler goroutine
  (FailNow from non-test goroutine is unsafe).
- Add Enabled/AutoSend zeroing assertions in partial-update test so the
  bool-overwrite-on-PATCH behavior is locked in explicitly.

E2E fix:
- toolbar-overflow spec used button.rounded-full which now matches both
  the send and voice buttons (strict-mode violation). Switched to the
  submit-message-button testid for an unambiguous locator.

* fix: scope voice settings rollback + whisper worker error to changed keys

Round 2 of PR review feedback on #1159:
- voice-mode settings rollback now restores only the keys patched by the
  failing request (not the whole snapshot), preserving concurrent edits
  to unrelated voiceMode fields.
- Shortcut rollback diffs previous vs next and reverts only the changed
  keys (restore prior value or delete if absent), preserving other
  concurrent shortcut edits.
- Whisper worker error handler captures the worker reference at attach
  time and only clears refs when this.worker still matches it — a stale
  error from a previously replaced worker no longer nukes the active one.
- Update stale whisper-web-models JSDoc that still pointed at Xenova
  mirrors.

* fix: voice mode progress scale, hold-mode race, race-aware rollback

Round 3 of PR review feedback on #1159:
- Normalise Whisper progress to 0–1 in ensureWhisperClient (transformers.js
  emits 0–100, the button's display + the `ready: 1` convention expect
  0–1 — fixes the 5000% mid-download display).
- Claim driverRef synchronously at the top of finishCapture so concurrent
  pointerup + pointerleave invocations early-return instead of racing and
  clobbering a freshly-started recording's ref.
- Race-aware rollback: voice-mode and shortcut catch branches now skip
  reverting a key when latest[key] !== next[key]. A failed earlier request
  no longer overwrites a later successful save to the same key.
- Update the Worker wire-protocol comment to show onnx-community/whisper-base
  instead of the stale Xenova/* example.

---------

Co-authored-by: Kandev Agent <agent@kandev.dev>
2026-06-01 14:32:39 +01:00

147 lines
5.5 KiB
TypeScript

import { type Page } from "@playwright/test";
import { test, expect } from "../../fixtures/test-base";
import type { SeedData } from "../../fixtures/test-base";
import type { ApiClient } from "../../helpers/api-client";
import { SessionPage } from "../../pages/session-page";
/**
* Seed a task + session and navigate to the session page.
* Waits for the mock agent to finish (idle input visible).
*/
async function seedAndNavigate(
testPage: Page,
apiClient: ApiClient,
seedData: SeedData,
): Promise<SessionPage> {
const task = await apiClient.createTaskWithAgent(
seedData.workspaceId,
"Toolbar Overflow Test",
seedData.agentProfileId,
{
description: "/e2e:simple-message",
workflow_id: seedData.workflowId,
workflow_step_id: seedData.startStepId,
repository_ids: [seedData.repositoryId],
},
);
await testPage.goto(`/t/${task.id}`);
const session = new SessionPage(testPage);
await session.waitForLoad();
await expect(session.idleInput()).toBeVisible({ timeout: 30_000 });
return session;
}
/** Force the toolbar container to a specific max-width via inline style. */
async function constrainToolbar(page: Page, maxWidth: string | null) {
await page.evaluate((mw) => {
const el = document.querySelector('[data-testid="chat-input-toolbar"]') as HTMLElement;
if (!el) return;
if (mw) {
el.style.maxWidth = mw;
} else {
el.style.removeProperty("max-width");
}
}, maxWidth);
// Allow ResizeObserver to fire
await page.waitForTimeout(200);
}
test.describe("Toolbar overflow menu", () => {
test.describe.configure({ retries: 1 });
test("collapses toolbar items and expands inline when toggled", async ({
testPage,
apiClient,
seedData,
}) => {
await seedAndNavigate(testPage, apiClient, seedData);
const toolbar = testPage.getByTestId("chat-input-toolbar");
await expect(toolbar).toBeVisible({ timeout: 10_000 });
// At default width, collapsible items should be visible inline
const modelItem = testPage.getByTestId("toolbar-item-model");
const mcpItem = testPage.getByTestId("toolbar-item-mcp");
const overflowBtn = testPage.getByTestId("toolbar-overflow-menu");
await expect(modelItem).toBeVisible({ timeout: 5_000 });
await expect(mcpItem).toBeVisible({ timeout: 5_000 });
await expect(overflowBtn).not.toBeVisible();
// Check context badge visibility: add a context item via the popover
const contextBtn = toolbar.locator("button", { has: testPage.locator("svg.tabler-icon-at") });
await contextBtn.click();
const searchInput = testPage.getByPlaceholder("Search files and prompts...");
await expect(searchInput).toBeVisible({ timeout: 5_000 });
// Toggle the Plan context checkbox to get contextCount > 0
const planCheckbox = testPage.getByText("Plan", { exact: true });
await planCheckbox.click();
// Close the popover
await testPage.locator("body").click({ position: { x: 10, y: 10 } });
// Badge should be visible at full width
const contextBadge = contextBtn.locator("span.rounded-full");
await expect(contextBadge).toBeVisible({ timeout: 3_000 });
// Constrain toolbar to a narrow width to force overflow
await constrainToolbar(testPage, "300px");
// Collapsible items should disappear and expand toggle should appear
await expect(overflowBtn).toBeVisible({ timeout: 5_000 });
await expect(modelItem).not.toBeVisible();
// Context badge should be hidden when collapsed to avoid clipping
await expect(contextBadge).not.toBeVisible();
// Submit button should remain visible (always-visible item). Target the
// submit testid specifically — the voice input button is also round, so a
// bare `button.rounded-full` locator now matches both and fails strict mode.
const submitBtn = toolbar.getByTestId("submit-message-button");
await expect(submitBtn).toBeVisible();
// Click expand toggle — items appear inline (scrollable)
await overflowBtn.click();
await expect(modelItem).toBeVisible({ timeout: 5_000 });
await expect(mcpItem).toBeVisible({ timeout: 5_000 });
// Collapse button should still be visible to toggle back
await expect(overflowBtn).toBeVisible();
// Click again to collapse back
await overflowBtn.click();
await expect(modelItem).not.toBeVisible({ timeout: 5_000 });
// Remove constraint — items should reappear inline normally
await constrainToolbar(testPage, null);
await expect(modelItem).toBeVisible({ timeout: 5_000 });
await expect(mcpItem).toBeVisible({ timeout: 5_000 });
await expect(overflowBtn).not.toBeVisible();
});
test("context popover opens when @ button is clicked", async ({
testPage,
apiClient,
seedData,
}) => {
await seedAndNavigate(testPage, apiClient, seedData);
const toolbar = testPage.getByTestId("chat-input-toolbar");
await expect(toolbar).toBeVisible({ timeout: 10_000 });
// Find the @ context button and click it
const contextBtn = toolbar.locator("button", { has: testPage.locator("svg.tabler-icon-at") });
await expect(contextBtn).toBeVisible({ timeout: 5_000 });
await contextBtn.click();
// The context popover should open with "Context" header and search input
const popoverContent = testPage.getByText("Select files and prompts to include");
await expect(popoverContent).toBeVisible({ timeout: 5_000 });
const searchInput = testPage.getByPlaceholder("Search files and prompts...");
await expect(searchInput).toBeVisible();
});
});