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>
385 lines
14 KiB
TypeScript
385 lines
14 KiB
TypeScript
"use client";
|
|
|
|
import { useCallback, useState } from "react";
|
|
import { useAppStore } from "@/components/state-provider";
|
|
import { useEditors } from "@/hooks/domains/settings/use-editors";
|
|
import { createEditor, deleteEditor, updateEditor, updateUserSettings } from "@/lib/api";
|
|
import { useRequest } from "@/lib/http/use-request";
|
|
import type { EditorOption } from "@/lib/types/http";
|
|
import { type ComboboxOption } from "@/components/combobox";
|
|
import { parseTerminalLinkBehavior, parseVoiceMode } from "@/lib/ssr/user-settings";
|
|
import { fromApiSidebarView } from "@/lib/state/slices/ui/sidebar-view-wire";
|
|
import {
|
|
type EditorFormState,
|
|
buildConfig,
|
|
resolveAvailableEditors,
|
|
resolveDefaultEditorId,
|
|
getCustomKindLabel,
|
|
isCustomEditor,
|
|
} from "@/components/settings/editor-form";
|
|
import { Badge } from "@kandev/ui/badge";
|
|
|
|
export function useEditorsSettingsState() {
|
|
const setEditors = useAppStore((state) => state.setEditors);
|
|
const setUserSettings = useAppStore((state) => state.setUserSettings);
|
|
const currentUserSettings = useAppStore((state) => state.userSettings);
|
|
const { editors: storeEditors } = useEditors();
|
|
const [editors, setEditorItems] = useState<EditorOption[]>(() => storeEditors ?? []);
|
|
const initialDefaultId = resolveDefaultEditorId(
|
|
editors ?? [],
|
|
currentUserSettings.defaultEditorId ?? "",
|
|
);
|
|
const [defaultEditorId, setDefaultEditorId] = useState(initialDefaultId);
|
|
const [baselineDefaultId, setBaselineDefaultId] = useState(initialDefaultId);
|
|
const [isAdding, setIsAdding] = useState(false);
|
|
const [editingId, setEditingId] = useState<string | null>(null);
|
|
const [lspAutoStartLanguages, setLspAutoStartLanguages] = useState<string[]>(
|
|
() => currentUserSettings.lspAutoStartLanguages ?? [],
|
|
);
|
|
const [lspAutoInstallLanguages, setLspAutoInstallLanguages] = useState<string[]>(
|
|
() => currentUserSettings.lspAutoInstallLanguages ?? [],
|
|
);
|
|
const [baselineLspAutoStart, setBaselineLspAutoStart] = useState<string[]>(
|
|
() => currentUserSettings.lspAutoStartLanguages ?? [],
|
|
);
|
|
const [baselineLspAutoInstall, setBaselineLspAutoInstall] = useState<string[]>(
|
|
() => currentUserSettings.lspAutoInstallLanguages ?? [],
|
|
);
|
|
|
|
const initConfigStrings = useCallback((): Record<string, string> => {
|
|
const configs = currentUserSettings.lspServerConfigs ?? {};
|
|
const result: Record<string, string> = {};
|
|
for (const [lang, config] of Object.entries(configs)) {
|
|
if (config && Object.keys(config).length > 0) result[lang] = JSON.stringify(config, null, 2);
|
|
}
|
|
return result;
|
|
}, [currentUserSettings.lspServerConfigs]);
|
|
const [lspConfigStrings, setLspConfigStrings] =
|
|
useState<Record<string, string>>(initConfigStrings);
|
|
const [baselineLspConfigStrings, setBaselineLspConfigStrings] =
|
|
useState<Record<string, string>>(initConfigStrings);
|
|
const [expandedConfigLang, setExpandedConfigLang] = useState<string | null>(null);
|
|
const [lspConfigErrors, setLspConfigErrors] = useState<Record<string, string>>({});
|
|
|
|
return {
|
|
setEditors,
|
|
setUserSettings,
|
|
currentUserSettings,
|
|
editors,
|
|
setEditorItems,
|
|
defaultEditorId,
|
|
setDefaultEditorId,
|
|
baselineDefaultId,
|
|
setBaselineDefaultId,
|
|
isAdding,
|
|
setIsAdding,
|
|
editingId,
|
|
setEditingId,
|
|
lspAutoStartLanguages,
|
|
setLspAutoStartLanguages,
|
|
lspAutoInstallLanguages,
|
|
setLspAutoInstallLanguages,
|
|
baselineLspAutoStart,
|
|
setBaselineLspAutoStart,
|
|
baselineLspAutoInstall,
|
|
setBaselineLspAutoInstall,
|
|
lspConfigStrings,
|
|
setLspConfigStrings,
|
|
baselineLspConfigStrings,
|
|
setBaselineLspConfigStrings,
|
|
expandedConfigLang,
|
|
setExpandedConfigLang,
|
|
lspConfigErrors,
|
|
setLspConfigErrors,
|
|
};
|
|
}
|
|
|
|
export type EditorsSettingsState = ReturnType<typeof useEditorsSettingsState>;
|
|
|
|
export function useLspConfigActions(
|
|
setLspConfigStrings: (updater: (prev: Record<string, string>) => Record<string, string>) => void,
|
|
setLspConfigErrors: (updater: (prev: Record<string, string>) => Record<string, string>) => void,
|
|
) {
|
|
const clearLspConfigError = useCallback(
|
|
(langId: string) => {
|
|
setLspConfigErrors((prev) => {
|
|
const next = { ...prev };
|
|
delete next[langId];
|
|
return next;
|
|
});
|
|
},
|
|
[setLspConfigErrors],
|
|
);
|
|
|
|
const updateLspConfigString = useCallback(
|
|
(langId: string, value: string) => {
|
|
setLspConfigStrings((prev) => {
|
|
if (!value.trim()) {
|
|
const next = { ...prev };
|
|
delete next[langId];
|
|
return next;
|
|
}
|
|
return { ...prev, [langId]: value };
|
|
});
|
|
if (!value.trim()) {
|
|
clearLspConfigError(langId);
|
|
return;
|
|
}
|
|
try {
|
|
const parsed = JSON.parse(value);
|
|
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
|
|
setLspConfigErrors((prev) => ({ ...prev, [langId]: "Must be a JSON object" }));
|
|
} else {
|
|
clearLspConfigError(langId);
|
|
}
|
|
} catch {
|
|
setLspConfigErrors((prev) => ({ ...prev, [langId]: "Invalid JSON" }));
|
|
}
|
|
},
|
|
[setLspConfigStrings, setLspConfigErrors, clearLspConfigError],
|
|
);
|
|
|
|
return { updateLspConfigString };
|
|
}
|
|
|
|
export function parseLspConfigStrings(
|
|
lspConfigStrings: Record<string, string>,
|
|
): Record<string, Record<string, unknown>> | null {
|
|
const result: Record<string, Record<string, unknown>> = {};
|
|
for (const [lang, str] of Object.entries(lspConfigStrings)) {
|
|
if (!str.trim()) continue;
|
|
try {
|
|
const parsed = JSON.parse(str);
|
|
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return null;
|
|
result[lang] = parsed as Record<string, unknown>;
|
|
} catch {
|
|
return null;
|
|
}
|
|
}
|
|
return result;
|
|
}
|
|
|
|
export function buildDefaultEditorOptions(
|
|
availableEditors: EditorOption[],
|
|
defaultEditorId: string,
|
|
): ComboboxOption[] {
|
|
if (availableEditors.length === 0) return [];
|
|
const selected = defaultEditorId ? availableEditors.filter((e) => e.id === defaultEditorId) : [];
|
|
const rest = availableEditors.filter((e) => e.id !== defaultEditorId);
|
|
const ordered = [...selected, ...rest];
|
|
return ordered.map((editor) => ({
|
|
value: editor.id,
|
|
label: editor.name,
|
|
renderLabel: () => (
|
|
<div className="flex min-w-0 flex-1 items-center gap-2">
|
|
<span className="truncate">{editor.name}</span>
|
|
{editor.kind === "built_in" ? (
|
|
<Badge variant={editor.installed ? "secondary" : "outline"} className="ml-auto">
|
|
{editor.installed ? "Installed" : "Not installed"}
|
|
</Badge>
|
|
) : (
|
|
<Badge variant="secondary" className="ml-auto">
|
|
{getCustomKindLabel(editor.kind)}
|
|
</Badge>
|
|
)}
|
|
</div>
|
|
),
|
|
}));
|
|
}
|
|
|
|
type UserSettingsState = ReturnType<typeof useEditorsSettingsState>["currentUserSettings"];
|
|
type UpdateUserSettingsResponse = Awaited<ReturnType<typeof updateUserSettings>>;
|
|
type SetUserSettingsFn = ReturnType<typeof useEditorsSettingsState>["setUserSettings"];
|
|
|
|
function buildSettingsPayload(
|
|
s: UserSettingsState,
|
|
defaultEditorId: string,
|
|
lspAutoStartLanguages: string[],
|
|
lspAutoInstallLanguages: string[],
|
|
parsedConfigs: Record<string, Record<string, unknown>>,
|
|
): Parameters<typeof updateUserSettings>[0] {
|
|
return {
|
|
workspace_id: s.workspaceId ?? "",
|
|
repository_ids: s.repositoryIds ?? [],
|
|
default_editor_id: defaultEditorId || undefined,
|
|
lsp_auto_start_languages: lspAutoStartLanguages,
|
|
lsp_auto_install_languages: lspAutoInstallLanguages,
|
|
lsp_server_configs: parsedConfigs,
|
|
};
|
|
}
|
|
|
|
function mapEditorSettingsFields(
|
|
s: NonNullable<NonNullable<UpdateUserSettingsResponse>["settings"]>,
|
|
) {
|
|
return {
|
|
chatSubmitKey: s.chat_submit_key ?? "cmd_enter",
|
|
reviewAutoMarkOnScroll: s.review_auto_mark_on_scroll ?? true,
|
|
showReleaseNotification: s.show_release_notification ?? true,
|
|
releaseNotesLastSeenVersion: (s.release_notes_last_seen_version as string) || null,
|
|
lspAutoStartLanguages: s.lsp_auto_start_languages ?? [],
|
|
lspAutoInstallLanguages: s.lsp_auto_install_languages ?? [],
|
|
lspServerConfigs: s.lsp_server_configs ?? {},
|
|
savedLayouts: s.saved_layouts ?? [],
|
|
sidebarViews: (s.sidebar_views ?? []).map(fromApiSidebarView),
|
|
loaded: true as const,
|
|
};
|
|
}
|
|
|
|
function buildUserSettingsFromResponse(
|
|
s: NonNullable<UpdateUserSettingsResponse>["settings"],
|
|
shellOptions: Array<{ value: string; label: string }> | null | undefined,
|
|
) {
|
|
if (!s) return null;
|
|
return {
|
|
workspaceId: s.workspace_id || null,
|
|
workflowId: s.workflow_filter_id || null,
|
|
kanbanViewMode: s.kanban_view_mode || null,
|
|
repositoryIds: s.repository_ids ?? [],
|
|
preferredShell: s.preferred_shell || null,
|
|
shellOptions: shellOptions ?? [],
|
|
defaultEditorId: s.default_editor_id || null,
|
|
enablePreviewOnClick: s.enable_preview_on_click ?? false,
|
|
defaultUtilityAgentId: s.default_utility_agent_id || null,
|
|
keyboardShortcuts: s.keyboard_shortcuts ?? {},
|
|
terminalLinkBehavior: parseTerminalLinkBehavior(s.terminal_link_behavior),
|
|
terminalFontFamily: s.terminal_font_family || null,
|
|
terminalFontSize: s.terminal_font_size || null,
|
|
changesPanelLayout: s.changes_panel_layout === "tree" ? ("tree" as const) : ("flat" as const),
|
|
voiceMode: parseVoiceMode(s.voice_mode),
|
|
...mapEditorSettingsFields(s),
|
|
};
|
|
}
|
|
|
|
function applySettingsResponseToStore(
|
|
response: UpdateUserSettingsResponse,
|
|
shellOptions: Array<{ value: string; label: string }> | null | undefined,
|
|
setUserSettings: SetUserSettingsFn,
|
|
) {
|
|
if (!response?.settings) return;
|
|
const settings = buildUserSettingsFromResponse(response.settings, shellOptions);
|
|
if (settings) setUserSettings(settings);
|
|
}
|
|
|
|
export function useApplyEditors(state: EditorsSettingsState) {
|
|
const { defaultEditorId, setEditorItems, setDefaultEditorId, setBaselineDefaultId } = state;
|
|
return useCallback(
|
|
(updater: EditorOption[] | ((prev: EditorOption[]) => EditorOption[])) => {
|
|
setEditorItems((prev) => {
|
|
const next = typeof updater === "function" ? updater(prev) : updater;
|
|
const resolvedDefault = resolveDefaultEditorId(next, defaultEditorId);
|
|
if (resolvedDefault !== defaultEditorId) {
|
|
setDefaultEditorId(resolvedDefault);
|
|
setBaselineDefaultId(resolvedDefault);
|
|
}
|
|
return next;
|
|
});
|
|
},
|
|
[defaultEditorId, setEditorItems, setDefaultEditorId, setBaselineDefaultId],
|
|
);
|
|
}
|
|
|
|
export function useEditorRequests(
|
|
state: EditorsSettingsState,
|
|
applyEditors: (updater: EditorOption[] | ((prev: EditorOption[]) => EditorOption[])) => void,
|
|
) {
|
|
const {
|
|
setIsAdding,
|
|
defaultEditorId,
|
|
setDefaultEditorId,
|
|
setBaselineDefaultId,
|
|
setUserSettings,
|
|
currentUserSettings,
|
|
} = state;
|
|
|
|
const createRequest = useRequest(async (editorState: EditorFormState) => {
|
|
const created = await createEditor(
|
|
{
|
|
name: editorState.name,
|
|
kind: editorState.kind,
|
|
config: buildConfig(editorState),
|
|
enabled: editorState.enabled,
|
|
},
|
|
{ cache: "no-store" },
|
|
);
|
|
applyEditors((prev: EditorOption[]) => [...prev, created]);
|
|
setIsAdding(false);
|
|
});
|
|
|
|
const updateRequest = useRequest(async (editorId: string, editorState: EditorFormState) => {
|
|
const updated = await updateEditor(
|
|
editorId,
|
|
{
|
|
name: editorState.name,
|
|
kind: editorState.kind,
|
|
config: buildConfig(editorState),
|
|
enabled: editorState.enabled,
|
|
},
|
|
{ cache: "no-store" },
|
|
);
|
|
applyEditors((prev: EditorOption[]) =>
|
|
prev.map((editor: EditorOption) => (editor.id === editorId ? updated : editor)),
|
|
);
|
|
});
|
|
|
|
const deleteRequest = useRequest(async (editorId: string) => {
|
|
await deleteEditor(editorId, { cache: "no-store" });
|
|
applyEditors((prev: EditorOption[]) =>
|
|
prev.filter((editor: EditorOption) => editor.id !== editorId),
|
|
);
|
|
if (defaultEditorId === editorId) {
|
|
setDefaultEditorId("");
|
|
setBaselineDefaultId("");
|
|
setUserSettings({ ...currentUserSettings, defaultEditorId: null, loaded: true });
|
|
}
|
|
});
|
|
|
|
return { createRequest, updateRequest, deleteRequest };
|
|
}
|
|
|
|
export function useSaveRequest(state: EditorsSettingsState) {
|
|
const {
|
|
setUserSettings,
|
|
currentUserSettings,
|
|
defaultEditorId,
|
|
setBaselineDefaultId,
|
|
lspAutoStartLanguages,
|
|
setBaselineLspAutoStart,
|
|
lspAutoInstallLanguages,
|
|
setBaselineLspAutoInstall,
|
|
lspConfigStrings,
|
|
setBaselineLspConfigStrings,
|
|
} = state;
|
|
return useRequest(async () => {
|
|
const parsedConfigs = parseLspConfigStrings(lspConfigStrings);
|
|
if (parsedConfigs === null) return;
|
|
const payload = buildSettingsPayload(
|
|
currentUserSettings,
|
|
defaultEditorId,
|
|
lspAutoStartLanguages,
|
|
lspAutoInstallLanguages,
|
|
parsedConfigs,
|
|
);
|
|
const response = await updateUserSettings(payload, { cache: "no-store" });
|
|
setBaselineDefaultId(defaultEditorId);
|
|
setBaselineLspAutoStart([...lspAutoStartLanguages]);
|
|
setBaselineLspAutoInstall([...lspAutoInstallLanguages]);
|
|
setBaselineLspConfigStrings({ ...lspConfigStrings });
|
|
applySettingsResponseToStore(response, currentUserSettings.shellOptions, setUserSettings);
|
|
});
|
|
}
|
|
|
|
export function sortCustomEditors(items: EditorOption[]): EditorOption[] {
|
|
return items.slice().sort((a, b) => {
|
|
const createdA = a.created_at ? Date.parse(a.created_at) : 0;
|
|
const createdB = b.created_at ? Date.parse(b.created_at) : 0;
|
|
if (createdA !== createdB) return createdB - createdA;
|
|
const nameA = (a.name || "").toLowerCase();
|
|
const nameB = (b.name || "").toLowerCase();
|
|
if (nameA < nameB) return -1;
|
|
if (nameA > nameB) return 1;
|
|
return a.id.localeCompare(b.id);
|
|
});
|
|
}
|
|
|
|
export { resolveAvailableEditors, isCustomEditor };
|