1fdeda904b
* 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>
336 lines
11 KiB
TypeScript
336 lines
11 KiB
TypeScript
"use client";
|
|
|
|
import { useState, useCallback } from "react";
|
|
import { Tooltip, TooltipContent, TooltipTrigger } from "@kandev/ui/tooltip";
|
|
import { cn } from "@/lib/utils";
|
|
import { TipTapInput } from "./tiptap-input";
|
|
import { ChatInputFocusHint } from "./chat-input-focus-hint";
|
|
import { ResizeHandle } from "./resize-handle";
|
|
import { ChatInputToolbar } from "./chat-input-toolbar";
|
|
import { ContextZone } from "./context-items/context-zone";
|
|
import type { ContextItem } from "@/lib/types/context";
|
|
import type { ContextFile } from "@/lib/state/context-files-store";
|
|
|
|
export type ChatInputEditorAreaProps = {
|
|
inputRef: React.RefObject<import("./tiptap-input").TipTapInputHandle | null>;
|
|
value: string;
|
|
handleChange: (val: string) => void;
|
|
handleSubmitWithReset: () => void;
|
|
inputPlaceholder: string;
|
|
isDisabled: boolean;
|
|
submitDisabled: boolean;
|
|
submitDisabledReason?: string;
|
|
hasClarification: boolean;
|
|
planModeEnabled: boolean;
|
|
planModeAvailable: boolean;
|
|
mcpServers: string[];
|
|
submitKey: "enter" | "cmd_enter";
|
|
setIsInputFocused: (focused: boolean) => void;
|
|
sessionId: string | null;
|
|
taskId: string | null;
|
|
onAddContextFile?: (file: ContextFile) => void;
|
|
onToggleContextFile?: (file: ContextFile) => void;
|
|
planContextEnabled: boolean;
|
|
handleAgentCommand: (command: string) => void;
|
|
addFiles: (files: File[]) => Promise<void>;
|
|
fileInputRef: React.RefObject<HTMLInputElement | null>;
|
|
showRequestChangesTooltip: boolean;
|
|
hideSessionsDropdown?: boolean;
|
|
minimalToolbar?: boolean;
|
|
hidePlanMode?: boolean;
|
|
isAgentBusy: boolean;
|
|
onPlanModeChange: (enabled: boolean) => void;
|
|
taskTitle?: string;
|
|
taskDescription: string;
|
|
isSending: boolean;
|
|
onCancel: () => void;
|
|
contextCount: number;
|
|
contextPopoverOpen: boolean;
|
|
setContextPopoverOpen: (open: boolean) => void;
|
|
contextFiles: ContextFile[];
|
|
onImplementPlan?: (fresh: boolean) => void;
|
|
onEnhancePrompt?: () => void;
|
|
isEnhancingPrompt?: boolean;
|
|
isUtilityConfigured?: boolean;
|
|
/** Inserts a voice transcript into the editor at the current cursor. */
|
|
onVoiceTranscript?: (text: string) => void;
|
|
/** Submit the message after a voice transcript is inserted (when auto-send is on). */
|
|
onVoiceAutoSend?: () => void;
|
|
};
|
|
|
|
function EditorWithTooltip({
|
|
showTooltip,
|
|
isEnhancingPrompt,
|
|
children,
|
|
}: {
|
|
showTooltip: boolean;
|
|
isEnhancingPrompt?: boolean;
|
|
children: React.ReactNode;
|
|
}) {
|
|
return (
|
|
<Tooltip open={showTooltip}>
|
|
<TooltipTrigger asChild>
|
|
<div
|
|
className={cn(
|
|
"flex-1 min-h-0 transition-opacity",
|
|
isEnhancingPrompt && "opacity-50 pointer-events-none",
|
|
)}
|
|
>
|
|
{children}
|
|
</div>
|
|
</TooltipTrigger>
|
|
<TooltipContent side="top" className="bg-orange-600 text-white border-orange-700">
|
|
<p className="font-medium">Write your changes here</p>
|
|
</TooltipContent>
|
|
</Tooltip>
|
|
);
|
|
}
|
|
|
|
function FileInput({
|
|
fileInputRef,
|
|
addFiles,
|
|
}: {
|
|
fileInputRef: React.RefObject<HTMLInputElement | null>;
|
|
addFiles: (files: File[]) => Promise<void>;
|
|
}) {
|
|
const handleChange = useCallback(
|
|
(e: React.ChangeEvent<HTMLInputElement>) => {
|
|
const files = e.target.files;
|
|
if (files && files.length > 0) {
|
|
void addFiles(Array.from(files));
|
|
}
|
|
// Reset so re-selecting the same file triggers onChange
|
|
e.target.value = "";
|
|
},
|
|
[addFiles],
|
|
);
|
|
|
|
return (
|
|
<input
|
|
ref={fileInputRef}
|
|
type="file"
|
|
multiple
|
|
className="hidden"
|
|
onChange={handleChange}
|
|
tabIndex={-1}
|
|
/>
|
|
);
|
|
}
|
|
|
|
export function ChatInputEditorArea(p: ChatInputEditorAreaProps) {
|
|
const { inputRef, value, handleChange, handleSubmitWithReset, inputPlaceholder } = p;
|
|
const { isDisabled, hasClarification, planModeEnabled, planModeAvailable, mcpServers } = p;
|
|
const { submitKey, setIsInputFocused, sessionId, taskId, planContextEnabled } = p;
|
|
const { onAddContextFile, onToggleContextFile, handleAgentCommand, addFiles, fileInputRef } = p;
|
|
const { showRequestChangesTooltip, isAgentBusy, onPlanModeChange, taskTitle, taskDescription } =
|
|
p;
|
|
const { isSending, onCancel, contextCount, contextPopoverOpen, setContextPopoverOpen } = p;
|
|
const { contextFiles, onImplementPlan, onEnhancePrompt, isEnhancingPrompt } = p;
|
|
const { isUtilityConfigured, hideSessionsDropdown, minimalToolbar, hidePlanMode } = p;
|
|
const { onVoiceTranscript, onVoiceAutoSend } = p;
|
|
// Exclude auto-added plan context from the count — it's always present in plan mode
|
|
// and shouldn't by itself enable the send button.
|
|
const userContextCount = planContextEnabled ? Math.max(0, contextCount - 1) : contextCount;
|
|
const hasContent = value.trim().length > 0 || userContextCount > 0;
|
|
// Block submit while enhancing prompt, but keep editor editable for programmatic updates
|
|
const wrappedSubmit = isEnhancingPrompt || p.submitDisabled ? () => {} : handleSubmitWithReset;
|
|
const handleAttachFiles = useCallback(() => fileInputRef.current?.click(), [fileInputRef]);
|
|
return (
|
|
<div className="flex flex-col flex-1 min-h-0 overflow-hidden">
|
|
<EditorWithTooltip
|
|
showTooltip={showRequestChangesTooltip}
|
|
isEnhancingPrompt={isEnhancingPrompt}
|
|
>
|
|
<TipTapInput
|
|
ref={inputRef}
|
|
value={value}
|
|
onChange={handleChange}
|
|
onSubmit={wrappedSubmit}
|
|
placeholder={inputPlaceholder}
|
|
disabled={isDisabled || hasClarification}
|
|
planModeEnabled={planModeEnabled}
|
|
submitKey={submitKey}
|
|
onFocus={() => setIsInputFocused(true)}
|
|
onBlur={() => setIsInputFocused(false)}
|
|
sessionId={sessionId}
|
|
taskId={taskId}
|
|
onAddContextFile={onAddContextFile}
|
|
onToggleContextFile={onToggleContextFile}
|
|
planContextEnabled={planContextEnabled}
|
|
onAgentCommand={handleAgentCommand}
|
|
onImagePaste={addFiles}
|
|
onPlanModeChange={onPlanModeChange}
|
|
/>
|
|
</EditorWithTooltip>
|
|
<FileInput fileInputRef={fileInputRef} addFiles={addFiles} />
|
|
<ChatInputToolbar
|
|
planModeEnabled={planModeEnabled}
|
|
planModeAvailable={planModeAvailable}
|
|
mcpServers={mcpServers}
|
|
onPlanModeChange={onPlanModeChange}
|
|
sessionId={sessionId}
|
|
taskId={taskId}
|
|
taskTitle={taskTitle}
|
|
taskDescription={taskDescription}
|
|
isAgentBusy={isAgentBusy}
|
|
hasContent={hasContent}
|
|
isDisabled={p.submitDisabled}
|
|
submitDisabledReason={p.submitDisabledReason}
|
|
isSending={isSending}
|
|
onCancel={onCancel}
|
|
onSubmit={wrappedSubmit}
|
|
submitKey={submitKey}
|
|
contextCount={contextCount}
|
|
contextPopoverOpen={contextPopoverOpen}
|
|
onContextPopoverOpenChange={setContextPopoverOpen}
|
|
planContextEnabled={planContextEnabled}
|
|
contextFiles={contextFiles}
|
|
onToggleFile={onToggleContextFile}
|
|
onImplementPlan={onImplementPlan}
|
|
onEnhancePrompt={onEnhancePrompt}
|
|
isEnhancingPrompt={isEnhancingPrompt}
|
|
isUtilityConfigured={isUtilityConfigured}
|
|
onAttachFiles={handleAttachFiles}
|
|
onVoiceTranscript={onVoiceTranscript}
|
|
onVoiceAutoSend={onVoiceAutoSend}
|
|
hideSessionsDropdown={hideSessionsDropdown}
|
|
minimalToolbar={minimalToolbar}
|
|
hidePlanMode={hidePlanMode}
|
|
/>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
export type ChatInputContextAreaProps = {
|
|
hasContextZone: boolean;
|
|
allItems: ContextItem[];
|
|
sessionId: string | null;
|
|
};
|
|
|
|
export function ChatInputContextArea({
|
|
hasContextZone,
|
|
allItems,
|
|
sessionId,
|
|
}: ChatInputContextAreaProps) {
|
|
if (!hasContextZone) return null;
|
|
return <ContextZone items={allItems} sessionId={sessionId} />;
|
|
}
|
|
|
|
export type ChatInputBodyProps = {
|
|
containerRef: React.RefObject<HTMLDivElement | null>;
|
|
height: React.CSSProperties["height"];
|
|
resizeHandleProps: { onMouseDown: (e: React.MouseEvent) => void; onDoubleClick: () => void };
|
|
isStarting: boolean;
|
|
isAgentBusy: boolean;
|
|
hasClarification: boolean;
|
|
showRequestChangesTooltip: boolean;
|
|
hasPendingComments: boolean;
|
|
planModeEnabled: boolean;
|
|
showFocusHint: boolean;
|
|
needsRecovery: boolean;
|
|
addFiles: (files: File[]) => Promise<void>;
|
|
contextAreaProps: ChatInputContextAreaProps;
|
|
editorAreaProps: ChatInputEditorAreaProps;
|
|
};
|
|
|
|
export function ChatInputBody({
|
|
containerRef,
|
|
height,
|
|
resizeHandleProps,
|
|
isStarting,
|
|
isAgentBusy,
|
|
hasClarification,
|
|
showRequestChangesTooltip,
|
|
hasPendingComments,
|
|
planModeEnabled,
|
|
showFocusHint,
|
|
needsRecovery,
|
|
addFiles,
|
|
contextAreaProps,
|
|
editorAreaProps,
|
|
}: ChatInputBodyProps) {
|
|
const [isDragging, setIsDragging] = useState(false);
|
|
|
|
const handleDragOver = useCallback((e: React.DragEvent) => {
|
|
e.preventDefault();
|
|
e.stopPropagation();
|
|
}, []);
|
|
|
|
const handleDragEnter = useCallback((e: React.DragEvent) => {
|
|
e.preventDefault();
|
|
e.stopPropagation();
|
|
if (e.dataTransfer.types.includes("Files")) {
|
|
setIsDragging(true);
|
|
}
|
|
}, []);
|
|
|
|
const handleDragLeave = useCallback((e: React.DragEvent) => {
|
|
e.preventDefault();
|
|
e.stopPropagation();
|
|
// Only set false when leaving the container (not entering a child)
|
|
const rect = e.currentTarget.getBoundingClientRect();
|
|
const { clientX, clientY } = e;
|
|
if (
|
|
clientX <= rect.left ||
|
|
clientX >= rect.right ||
|
|
clientY <= rect.top ||
|
|
clientY >= rect.bottom
|
|
) {
|
|
setIsDragging(false);
|
|
}
|
|
}, []);
|
|
|
|
const handleDrop = useCallback(
|
|
(e: React.DragEvent) => {
|
|
e.preventDefault();
|
|
e.stopPropagation();
|
|
setIsDragging(false);
|
|
const files = Array.from(e.dataTransfer.files).filter((f) => f.size > 0 || f.type !== "");
|
|
if (files.length > 0) {
|
|
void addFiles(files);
|
|
}
|
|
},
|
|
[addFiles],
|
|
);
|
|
|
|
return (
|
|
<div className="relative">
|
|
<ResizeHandle
|
|
planModeEnabled={planModeEnabled}
|
|
isAgentBusy={isAgentBusy}
|
|
isStarting={isStarting}
|
|
{...resizeHandleProps}
|
|
/>
|
|
<div
|
|
className={cn(
|
|
"flex flex-col overflow-hidden border rounded ",
|
|
"bg-background border-border",
|
|
needsRecovery && "opacity-40 pointer-events-none border-red-500/30",
|
|
isStarting && !isAgentBusy && "chat-input-starting",
|
|
isAgentBusy && !planModeEnabled && "chat-input-running",
|
|
isAgentBusy && planModeEnabled && "chat-input-running-plan",
|
|
planModeEnabled && !isAgentBusy && "border-violet-400/50",
|
|
hasClarification && "border-sky-400/50",
|
|
showRequestChangesTooltip && "animate-pulse border-orange-500",
|
|
hasPendingComments && "border-amber-500/50",
|
|
isDragging && "border-primary ring-1 ring-primary/30",
|
|
)}
|
|
onDragOver={handleDragOver}
|
|
onDragEnter={handleDragEnter}
|
|
onDragLeave={handleDragLeave}
|
|
onDrop={handleDrop}
|
|
>
|
|
<ChatInputFocusHint visible={showFocusHint} />
|
|
<ChatInputContextArea {...contextAreaProps} />
|
|
<div
|
|
ref={containerRef}
|
|
style={{ height }}
|
|
className="flex flex-col min-h-0 overflow-hidden"
|
|
>
|
|
<ChatInputEditorArea {...editorAreaProps} />
|
|
</div>
|
|
</div>
|
|
</div>
|
|
);
|
|
}
|