mirror of
https://github.com/open-webui/computer.git
synced 2026-11-25 14:57:45 -05:00
refac
This commit is contained in:
1 parent
5ad9072764
commit
ab6047d0fc
25 files changed
+1194
-198
No files matched your search
@@ -41,6 +41,13 @@ export interface SendMessageResult {
|
||||
assistant_message?: ChatMessageRow;
|
||||
}
|
||||
|
||||
export interface ChatSendParams {
|
||||
tool_approval_mode?: string;
|
||||
plan_mode?: boolean;
|
||||
request_params?: Record<string, unknown>;
|
||||
voice_mode?: boolean;
|
||||
}
|
||||
|
||||
// ── Queries ─────────────────────────────────────────────────
|
||||
|
||||
export const getChats = (
|
||||
@@ -67,7 +74,7 @@ export const sendMessage = (
|
||||
workspace: string,
|
||||
chatId?: string,
|
||||
parentId?: string | null,
|
||||
params: { tool_approval_mode?: string; plan_mode?: boolean; request_params?: Record<string, unknown> } = {},
|
||||
params: ChatSendParams = {},
|
||||
regenerationPrompt?: string,
|
||||
files?: { id: string; name: string; url: string; type: string }[]
|
||||
) =>
|
||||
|
||||
@@ -18,6 +18,16 @@
|
||||
let sttApiKey = $state('');
|
||||
let sttModel = $state('whisper-1');
|
||||
let hasExistingKey = $state(false);
|
||||
let ttsBaseUrl = $state('https://api.openai.com/v1');
|
||||
let ttsEnabled = $state(false);
|
||||
let ttsApiKey = $state('');
|
||||
let ttsModel = $state('tts-1');
|
||||
let ttsVoice = $state('alloy');
|
||||
let ttsFormat = $state('mp3');
|
||||
let hasExistingTtsKey = $state(false);
|
||||
let voiceModeSystemPrompt = $state('');
|
||||
const VOICE_MODE_SYSTEM_PROMPT_PLACEHOLDER =
|
||||
'You are in voice mode. Keep responses brief, conversational, and easy to hear aloud. Prefer one or two short paragraphs. Ask at most one focused follow-up question when needed. Avoid long lists, code blocks, tables, and verbose explanations unless the user explicitly asks.';
|
||||
|
||||
onMount(async () => {
|
||||
try {
|
||||
@@ -30,6 +40,13 @@
|
||||
sttBaseUrl = (config['audio.stt_base_url'] as string) || 'https://api.openai.com/v1';
|
||||
sttModel = (config['audio.stt_model'] as string) || 'whisper-1';
|
||||
hasExistingKey = !!config['audio.stt_api_key'];
|
||||
ttsBaseUrl = (config['audio.tts_base_url'] as string) || 'https://api.openai.com/v1';
|
||||
ttsEnabled = config['audio.tts_enabled'] === true;
|
||||
ttsModel = (config['audio.tts_model'] as string) || 'tts-1';
|
||||
ttsVoice = (config['audio.tts_voice'] as string) || 'alloy';
|
||||
ttsFormat = (config['audio.tts_format'] as string) || 'mp3';
|
||||
hasExistingTtsKey = !!config['audio.tts_api_key'];
|
||||
voiceModeSystemPrompt = (config['audio.voice_mode_system_prompt'] as string) || '';
|
||||
} catch {}
|
||||
loading = false;
|
||||
});
|
||||
@@ -42,13 +59,23 @@
|
||||
'audio.transcribe_enabled': transcribeEnabled,
|
||||
'audio.recording_quality': quality,
|
||||
'audio.stt_base_url': sttBaseUrl,
|
||||
'audio.stt_model': sttModel
|
||||
'audio.stt_model': sttModel,
|
||||
'audio.tts_enabled': ttsEnabled,
|
||||
'audio.tts_base_url': ttsBaseUrl,
|
||||
'audio.tts_model': ttsModel,
|
||||
'audio.tts_voice': ttsVoice,
|
||||
'audio.tts_format': ttsFormat,
|
||||
'audio.voice_mode_system_prompt': voiceModeSystemPrompt
|
||||
};
|
||||
if (sttApiKey) {
|
||||
cfg['audio.stt_api_key'] = sttApiKey;
|
||||
}
|
||||
if (ttsApiKey) {
|
||||
cfg['audio.tts_api_key'] = ttsApiKey;
|
||||
}
|
||||
await updateConfig(cfg);
|
||||
if (sttApiKey) hasExistingKey = true;
|
||||
if (ttsApiKey) hasExistingTtsKey = true;
|
||||
toast.success($t('settings.saved'));
|
||||
refreshAudioState();
|
||||
} catch {
|
||||
@@ -140,6 +167,97 @@
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<!-- Text-to-Speech -->
|
||||
<h3 class="text-xs text-gray-400 dark:text-gray-600 mb-2 mt-5">{$t('admin.audio.tts')}</h3>
|
||||
|
||||
<div class="flex flex-col gap-2.5">
|
||||
<label class="flex items-center justify-between cursor-pointer">
|
||||
<span class="text-xs text-gray-600 dark:text-gray-400">{$t('admin.audio.enableTts')}</span>
|
||||
<ToggleSwitch value={ttsEnabled} onchange={(v) => { ttsEnabled = v; }} />
|
||||
</label>
|
||||
<p class="text-[11px] text-gray-400 dark:text-gray-600 -mt-1">
|
||||
{$t('admin.audio.ttsEnabledHint')}
|
||||
</p>
|
||||
<div>
|
||||
<label class="text-xs text-gray-600 dark:text-gray-400" for="tts-base-url">{$t('connections.baseUrl')}</label>
|
||||
<input
|
||||
id="tts-base-url"
|
||||
type="text"
|
||||
bind:value={ttsBaseUrl}
|
||||
placeholder="https://api.openai.com/v1"
|
||||
class="w-full mt-1 h-7 px-2 rounded-lg text-xs bg-gray-100 dark:bg-white/6 text-gray-700 dark:text-gray-300 border border-gray-200 dark:border-white/8 outline-none focus:border-blue-400 dark:focus:border-blue-500 transition-colors"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label class="text-xs text-gray-600 dark:text-gray-400" for="tts-api-key">{$t('connections.apiKey')}</label>
|
||||
<input
|
||||
id="tts-api-key"
|
||||
type="password"
|
||||
bind:value={ttsApiKey}
|
||||
placeholder={hasExistingTtsKey ? '••••••••' : $t('admin.audio.ttsKeyPlaceholder')}
|
||||
class="w-full mt-1 h-7 px-2 rounded-lg text-xs bg-gray-100 dark:bg-white/6 text-gray-700 dark:text-gray-300 border border-gray-200 dark:border-white/8 outline-none focus:border-blue-400 dark:focus:border-blue-500 transition-colors"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label class="text-xs text-gray-600 dark:text-gray-400" for="tts-model">{$t('automations.model')}</label>
|
||||
<input
|
||||
id="tts-model"
|
||||
type="text"
|
||||
bind:value={ttsModel}
|
||||
placeholder="tts-1"
|
||||
class="w-full mt-1 h-7 px-2 rounded-lg text-xs bg-gray-100 dark:bg-white/6 text-gray-700 dark:text-gray-300 border border-gray-200 dark:border-white/8 outline-none focus:border-blue-400 dark:focus:border-blue-500 transition-colors"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label class="text-xs text-gray-600 dark:text-gray-400" for="tts-voice">{$t('admin.audio.ttsVoice')}</label>
|
||||
<input
|
||||
id="tts-voice"
|
||||
type="text"
|
||||
bind:value={ttsVoice}
|
||||
placeholder="alloy"
|
||||
class="w-full mt-1 h-7 px-2 rounded-lg text-xs bg-gray-100 dark:bg-white/6 text-gray-700 dark:text-gray-300 border border-gray-200 dark:border-white/8 outline-none focus:border-blue-400 dark:focus:border-blue-500 transition-colors"
|
||||
/>
|
||||
</div>
|
||||
<div class="flex items-center justify-between">
|
||||
<span class="text-xs text-gray-600 dark:text-gray-400">{$t('admin.audio.ttsFormat')}</span>
|
||||
<select
|
||||
bind:value={ttsFormat}
|
||||
class="bg-transparent text-xs text-gray-600 dark:text-gray-400 outline-none cursor-pointer"
|
||||
>
|
||||
<option value="mp3">MP3</option>
|
||||
<option value="opus">Opus</option>
|
||||
<option value="aac">AAC</option>
|
||||
<option value="flac">FLAC</option>
|
||||
<option value="wav">WAV</option>
|
||||
<option value="pcm">PCM</option>
|
||||
</select>
|
||||
</div>
|
||||
<p class="text-[11px] text-gray-400 dark:text-gray-600">
|
||||
{$t('admin.audio.ttsHint')}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<!-- Voice Mode -->
|
||||
<h3 class="text-xs text-gray-400 dark:text-gray-600 mb-2 mt-5">{$t('admin.audio.voiceMode')}</h3>
|
||||
|
||||
<div class="flex flex-col gap-2.5">
|
||||
<div>
|
||||
<label class="text-xs text-gray-600 dark:text-gray-400" for="voice-mode-system-prompt">
|
||||
{$t('admin.audio.voiceModeSystemPrompt')}
|
||||
</label>
|
||||
<textarea
|
||||
id="voice-mode-system-prompt"
|
||||
bind:value={voiceModeSystemPrompt}
|
||||
rows="5"
|
||||
placeholder={VOICE_MODE_SYSTEM_PROMPT_PLACEHOLDER}
|
||||
class="w-full mt-1 px-2 py-1.5 rounded-lg text-xs bg-gray-100 dark:bg-white/6 text-gray-700 dark:text-gray-300 border border-gray-200 dark:border-white/8 outline-none focus:border-blue-400 dark:focus:border-blue-500 transition-colors resize-y min-h-24"
|
||||
></textarea>
|
||||
</div>
|
||||
<p class="text-[11px] text-gray-400 dark:text-gray-600">
|
||||
{$t('admin.audio.voiceModeSystemPromptHint')}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<!-- Save -->
|
||||
<div class="mt-auto pt-6 flex justify-end">
|
||||
<button
|
||||
|
||||
@@ -374,6 +374,10 @@
|
||||
<path d="M5 10V12C5 15.866 8.13401 19 12 19C15.866 19 19 15.866 19 12V10" />
|
||||
<line x1="12" y1="19" x2="12" y2="23" />
|
||||
<line x1="8" y1="23" x2="16" y2="23" />
|
||||
{:else if name === 'speaker'}
|
||||
<path d="M4 9V15H8L13 20V4L8 9H4Z" />
|
||||
<path d="M16 9C16.6254 9.81968 17 10.8637 17 12C17 13.1363 16.6254 14.1803 16 15" />
|
||||
<path d="M18.5 6.5C20.0645 7.86634 21 9.82395 21 12C21 14.176 20.0645 16.1337 18.5 17.5" />
|
||||
{:else if name === 'stop'}
|
||||
<rect x="6" y="6" width="12" height="12" rx="1" fill="currentColor" />
|
||||
{/if}
|
||||
|
||||
@@ -173,6 +173,7 @@
|
||||
try {
|
||||
const tf = new FormData();
|
||||
tf.append('file', new File([audioBlob], audioName, { type: audioBlob.type }));
|
||||
tf.append('workspace', workspace);
|
||||
const res = await fetchJSON<{ text: string }>('/api/audio/transcribe', {
|
||||
method: 'POST',
|
||||
body: tf
|
||||
|
||||
@@ -7,6 +7,8 @@
|
||||
import ReasoningCollapsible from './ReasoningCollapsible.svelte';
|
||||
import ToolCallCollapsible from './ToolCallCollapsible.svelte';
|
||||
import { currentWorkspace, openFileTab } from '$lib/stores';
|
||||
import { ttsConfigured, ttsEnabled } from '$lib/stores/audio';
|
||||
import Icon from '../Icon.svelte';
|
||||
import { t } from '$lib/i18n';
|
||||
|
||||
interface Props {
|
||||
@@ -18,10 +20,12 @@
|
||||
messageId: string;
|
||||
siblingIndex?: number;
|
||||
siblingTotal?: number;
|
||||
speaking?: boolean;
|
||||
onapprove: (messageId: string, callId: string, approved: boolean) => void;
|
||||
onnavigate?: (direction: -1 | 1) => void;
|
||||
onregenerate?: () => void;
|
||||
onedit?: (content: string, output: any[] | null, submit: boolean) => void;
|
||||
onspeak?: () => void;
|
||||
}
|
||||
let {
|
||||
content,
|
||||
@@ -32,10 +36,12 @@
|
||||
messageId,
|
||||
siblingIndex = 0,
|
||||
siblingTotal = 1,
|
||||
speaking = false,
|
||||
onapprove,
|
||||
onnavigate,
|
||||
onregenerate,
|
||||
onedit
|
||||
onedit,
|
||||
onspeak
|
||||
}: Props = $props();
|
||||
|
||||
let edit = $state(false);
|
||||
@@ -535,6 +541,19 @@
|
||||
{/if}
|
||||
</button>
|
||||
{/if}
|
||||
{#if done && $ttsEnabled && $ttsConfigured}
|
||||
<button
|
||||
class="p-0.5 rounded transition-colors duration-100
|
||||
{speaking
|
||||
? 'text-gray-700 dark:text-gray-200 bg-gray-100 dark:bg-white/10'
|
||||
: 'text-gray-400 dark:text-gray-600 hover:text-gray-600 dark:hover:text-gray-300'}"
|
||||
onclick={onspeak}
|
||||
aria-label={speaking ? $t('chat.stopSpeaking') : $t('chat.speakResponses')}
|
||||
title={speaking ? $t('chat.stopSpeaking') : $t('chat.speakResponses')}
|
||||
>
|
||||
<Icon name="speaker" size={14} />
|
||||
</button>
|
||||
{/if}
|
||||
{#if done && onregenerate}
|
||||
<button
|
||||
class="p-0.5 rounded text-gray-400 dark:text-gray-600 hover:text-gray-600 dark:hover:text-gray-300 transition-colors duration-100"
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<script lang="ts">
|
||||
import { onMount, onDestroy } from 'svelte';
|
||||
import { onMount, onDestroy, tick } from 'svelte';
|
||||
import { mount, unmount } from 'svelte';
|
||||
import { Editor } from '@tiptap/core';
|
||||
import StarterKit from '@tiptap/starter-kit';
|
||||
@@ -22,6 +22,7 @@
|
||||
import QueuedMessageItem from './QueuedMessageItem.svelte';
|
||||
import Icon from '../Icon.svelte';
|
||||
import { planMode } from '$lib/stores';
|
||||
import { ttsConfigured, ttsEnabled, voiceModeEnabled } from '$lib/stores/audio';
|
||||
import Spinner from '$lib/components/common/Spinner.svelte';
|
||||
import { t } from '$lib/i18n';
|
||||
|
||||
@@ -56,6 +57,21 @@
|
||||
|
||||
let editorEl: HTMLDivElement | undefined = $state();
|
||||
let editor: Editor | null = $state(null);
|
||||
let voiceListening = $state(false);
|
||||
let voiceWaitingForResponse = $state(false);
|
||||
let voiceSawStreaming = $state(false);
|
||||
let voiceRecognition: any = null;
|
||||
let voiceRestartTimer = 0;
|
||||
let voiceStopRequested = false;
|
||||
let voiceRearming = $state(false);
|
||||
const voiceModeAvailable = $derived($ttsEnabled && $ttsConfigured);
|
||||
const voiceStatusLabel = $derived(
|
||||
voiceWaitingForResponse || streaming || sending
|
||||
? $t('chat.voiceWaiting')
|
||||
: voiceListening || voiceRearming || $voiceModeEnabled
|
||||
? $t('chat.voiceListening')
|
||||
: $t('chat.voiceModeOn')
|
||||
);
|
||||
|
||||
// ── Lowlight setup ──────────────────────────────
|
||||
const lowlight = createLowlight(all);
|
||||
@@ -485,6 +501,8 @@
|
||||
});
|
||||
|
||||
onDestroy(() => {
|
||||
stopVoiceRecognition();
|
||||
if (voiceRestartTimer) clearTimeout(voiceRestartTimer);
|
||||
destroyPopup();
|
||||
destroySkillPopup();
|
||||
editor?.destroy();
|
||||
@@ -525,8 +543,161 @@
|
||||
return extractMentionedSkills(editor.getJSON());
|
||||
}
|
||||
|
||||
function clearVoiceRestartTimer(resetRearming = true) {
|
||||
if (voiceRestartTimer) {
|
||||
clearTimeout(voiceRestartTimer);
|
||||
voiceRestartTimer = 0;
|
||||
}
|
||||
if (resetRearming) voiceRearming = false;
|
||||
}
|
||||
|
||||
function scheduleVoiceRestart(delay = 350) {
|
||||
clearVoiceRestartTimer();
|
||||
if (
|
||||
!voiceModeAvailable ||
|
||||
!$voiceModeEnabled ||
|
||||
voiceWaitingForResponse ||
|
||||
voiceListening ||
|
||||
voiceRecognition ||
|
||||
streaming ||
|
||||
sending ||
|
||||
inputText.trim()
|
||||
) return;
|
||||
voiceRearming = true;
|
||||
voiceRestartTimer = window.setTimeout(() => {
|
||||
voiceRestartTimer = 0;
|
||||
voiceRearming = false;
|
||||
startVoiceRecognition();
|
||||
}, delay);
|
||||
}
|
||||
|
||||
function stopVoiceRecognition() {
|
||||
clearVoiceRestartTimer();
|
||||
const recognition = voiceRecognition;
|
||||
voiceRecognition = null;
|
||||
voiceStopRequested = true;
|
||||
try {
|
||||
recognition?.stop();
|
||||
} catch {}
|
||||
voiceListening = false;
|
||||
}
|
||||
|
||||
function startVoiceRecognition() {
|
||||
clearVoiceRestartTimer(false);
|
||||
if (
|
||||
!voiceModeAvailable ||
|
||||
!$voiceModeEnabled ||
|
||||
voiceWaitingForResponse ||
|
||||
voiceListening ||
|
||||
voiceRecognition ||
|
||||
streaming ||
|
||||
sending ||
|
||||
inputText.trim()
|
||||
) {
|
||||
voiceRearming = false;
|
||||
return;
|
||||
}
|
||||
|
||||
const SpeechRecognition =
|
||||
(window as any).SpeechRecognition || (window as any).webkitSpeechRecognition;
|
||||
if (!SpeechRecognition) {
|
||||
alert($t('chat.dictate.unsupported'));
|
||||
voiceModeEnabled.set(false);
|
||||
voiceRearming = false;
|
||||
return;
|
||||
}
|
||||
|
||||
const recognition = new SpeechRecognition();
|
||||
voiceRecognition = recognition;
|
||||
voiceStopRequested = false;
|
||||
recognition.continuous = true;
|
||||
recognition.interimResults = true;
|
||||
recognition.lang = navigator.language || 'en-US';
|
||||
|
||||
recognition.onresult = async (event: any) => {
|
||||
let text = '';
|
||||
for (let i = event.resultIndex; i < event.results.length; i++) {
|
||||
const result = event.results[i];
|
||||
if (result?.isFinal) text += ` ${result[0]?.transcript || ''}`;
|
||||
}
|
||||
text = text.trim();
|
||||
if (!text) return;
|
||||
inputText = text;
|
||||
voiceWaitingForResponse = true;
|
||||
voiceSawStreaming = false;
|
||||
stopVoiceRecognition();
|
||||
await tick();
|
||||
onsend();
|
||||
};
|
||||
|
||||
recognition.onerror = (event: any) => {
|
||||
voiceListening = false;
|
||||
if (event?.error === 'not-allowed' || event?.error === 'service-not-allowed') {
|
||||
voiceModeEnabled.set(false);
|
||||
stopVoiceRecognition();
|
||||
}
|
||||
};
|
||||
|
||||
recognition.onend = () => {
|
||||
if (voiceRecognition !== recognition) return;
|
||||
voiceRecognition = null;
|
||||
voiceListening = false;
|
||||
if (!voiceStopRequested) scheduleVoiceRestart(1200);
|
||||
voiceStopRequested = false;
|
||||
};
|
||||
|
||||
try {
|
||||
recognition.start();
|
||||
voiceListening = true;
|
||||
voiceRearming = false;
|
||||
} catch {
|
||||
voiceRecognition = null;
|
||||
voiceListening = false;
|
||||
voiceRearming = false;
|
||||
scheduleVoiceRestart(1500);
|
||||
}
|
||||
}
|
||||
|
||||
function toggleVoiceMode() {
|
||||
if (!voiceModeAvailable) {
|
||||
alert($t('chat.ttsNotConfigured'));
|
||||
return;
|
||||
}
|
||||
const next = !$voiceModeEnabled;
|
||||
voiceModeEnabled.set(next);
|
||||
if (next) {
|
||||
voiceWaitingForResponse = false;
|
||||
voiceSawStreaming = false;
|
||||
startVoiceRecognition();
|
||||
} else {
|
||||
voiceWaitingForResponse = false;
|
||||
voiceSawStreaming = false;
|
||||
stopVoiceRecognition();
|
||||
}
|
||||
}
|
||||
|
||||
$effect(() => {
|
||||
if (!voiceModeAvailable && $voiceModeEnabled) {
|
||||
voiceModeEnabled.set(false);
|
||||
stopVoiceRecognition();
|
||||
}
|
||||
if (!$voiceModeEnabled) return;
|
||||
if (streaming) voiceSawStreaming = true;
|
||||
if (voiceSawStreaming && !streaming && !sending) {
|
||||
voiceWaitingForResponse = false;
|
||||
voiceSawStreaming = false;
|
||||
scheduleVoiceRestart(500);
|
||||
}
|
||||
});
|
||||
|
||||
$effect(() => {
|
||||
if ($voiceModeEnabled && inputText.trim()) {
|
||||
stopVoiceRecognition();
|
||||
}
|
||||
});
|
||||
|
||||
// Allow sending during streaming (message will be enqueued server-side)
|
||||
const canSend = $derived(inputText.trim() && selectedModel && !sending);
|
||||
const canSend = $derived(!!(inputText.trim() && selectedModel && !sending));
|
||||
</script>
|
||||
|
||||
<div
|
||||
@@ -600,6 +771,15 @@
|
||||
{/if}
|
||||
<!-- Editor area -->
|
||||
<div class="px-2.5">
|
||||
{#if $voiceModeEnabled}
|
||||
<div class="pt-2 flex items-center gap-2 text-[11px] font-medium text-gray-600 dark:text-gray-300">
|
||||
<span class="relative flex size-2">
|
||||
<span class="absolute inline-flex h-full w-full rounded-full bg-emerald-400 opacity-70 {voiceListening ? 'animate-ping' : ''}"></span>
|
||||
<span class="relative inline-flex size-2 rounded-full bg-emerald-500"></span>
|
||||
</span>
|
||||
<span>{voiceStatusLabel}</span>
|
||||
</div>
|
||||
{/if}
|
||||
<div
|
||||
bind:this={editorEl}
|
||||
class="chat-editor-mount scrollbar-hidden"
|
||||
@@ -666,7 +846,14 @@
|
||||
inputText += text;
|
||||
}}
|
||||
/>
|
||||
<SendButton {canSend} {streaming} {onsend} {oncancel} />
|
||||
<SendButton
|
||||
{canSend}
|
||||
{streaming}
|
||||
{onsend}
|
||||
{oncancel}
|
||||
onvoice={voiceModeAvailable ? toggleVoiceMode : undefined}
|
||||
voiceActive={$voiceModeEnabled || voiceListening}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -12,6 +12,7 @@
|
||||
queueSendNow as apiQueueSendNow,
|
||||
queueDelete as apiQueueDelete,
|
||||
type ChatMessageRow,
|
||||
type ChatSendParams,
|
||||
type ChatInfo
|
||||
} from '$lib/apis/chat';
|
||||
import {
|
||||
@@ -32,6 +33,14 @@
|
||||
selectedModelId,
|
||||
requestParams
|
||||
} from '$lib/stores';
|
||||
import {
|
||||
ttsEnabled,
|
||||
ttsConfigured,
|
||||
ttsFormat,
|
||||
ttsPlaybackEnabled,
|
||||
ttsVoice,
|
||||
voiceModeEnabled
|
||||
} from '$lib/stores/audio';
|
||||
|
||||
import ChatInput from './ChatInput.svelte';
|
||||
import UserMessage from './UserMessage.svelte';
|
||||
@@ -60,6 +69,20 @@
|
||||
let autoScroll = $state(true);
|
||||
let cancelledMessageId: string | null = null;
|
||||
let loading = $state(!!initialChatId);
|
||||
let ttsQueue: string[] = [];
|
||||
let ttsBuffer = '';
|
||||
let ttsInsideCodeFence = false;
|
||||
let ttsPlaying = false;
|
||||
let ttsGeneration = 0;
|
||||
let ttsAbort: AbortController | null = null;
|
||||
let ttsAudio: HTMLAudioElement | null = null;
|
||||
let ttsObjectUrl: string | null = null;
|
||||
let ttsErrorShown = false;
|
||||
let speakingMessageId = $state<string | null>(null);
|
||||
let ttsStopRequested = false;
|
||||
let ttsAudioCacheBytes = 0;
|
||||
const ttsAudioCache = new Map<string, Blob>();
|
||||
const TTS_AUDIO_CACHE_LIMIT_BYTES = 20 * 1024 * 1024;
|
||||
|
||||
// ── Windowed rendering ──────────────────────────────────────
|
||||
// Only render the last N turns to keep the DOM light for long chats.
|
||||
@@ -216,6 +239,7 @@
|
||||
let loadGeneration = 0;
|
||||
|
||||
async function loadChat(id: string) {
|
||||
if (chatId && chatId !== id) stopTtsPlayback();
|
||||
chatId = id;
|
||||
const gen = ++loadGeneration;
|
||||
// Only show loading spinner on initial load (no messages yet).
|
||||
@@ -356,8 +380,13 @@
|
||||
if (data.delta) {
|
||||
msg.content += data.delta;
|
||||
allMessages = [...allMessages];
|
||||
handleTtsDelta(data.message_id, data.delta);
|
||||
}
|
||||
if (data.output) {
|
||||
if (data.output.type === 'function_call') {
|
||||
if (data.output.status === 'pending') stopTtsPlayback();
|
||||
else resetTtsBuffer();
|
||||
}
|
||||
// Merge by call_id to avoid duplicates and update status of existing items
|
||||
const existing = msg.output || [];
|
||||
const callId = data.output.call_id;
|
||||
@@ -395,6 +424,7 @@
|
||||
toast.error(data.error, { duration: 8000 });
|
||||
}
|
||||
if (data.done) {
|
||||
flushTtsBuffer();
|
||||
// Clear streaming indicator for this tab
|
||||
if (tabId) {
|
||||
streamingChatTabs.update((s) => {
|
||||
@@ -450,6 +480,7 @@
|
||||
});
|
||||
|
||||
onDestroy(() => {
|
||||
stopTtsPlayback();
|
||||
const socket = socketStore.getSocket();
|
||||
if (socket) {
|
||||
socket.off('events:chat', handleSocketEvent);
|
||||
@@ -461,6 +492,16 @@
|
||||
// spinner persists even when the chat tab is not active.
|
||||
});
|
||||
|
||||
$effect(() => {
|
||||
if (!$ttsEnabled || !$ttsConfigured) {
|
||||
voiceModeEnabled.set(false);
|
||||
ttsPlaybackEnabled.set(false);
|
||||
stopTtsPlayback();
|
||||
} else if ((!$ttsPlaybackEnabled && !$voiceModeEnabled) || !$ttsConfigured) {
|
||||
stopTtsPlayback();
|
||||
}
|
||||
});
|
||||
|
||||
// ── Persist model selection ─────────────────────────────────
|
||||
|
||||
$effect(() => {
|
||||
@@ -528,10 +569,21 @@
|
||||
|
||||
// ── Actions ─────────────────────────────────────────────────
|
||||
|
||||
function getChatSendParams(): ChatSendParams {
|
||||
const params: ChatSendParams = {
|
||||
tool_approval_mode: get(toolApprovalMode),
|
||||
plan_mode: get(planMode),
|
||||
request_params: get(requestParams)
|
||||
};
|
||||
if (get(voiceModeEnabled)) params.voice_mode = true;
|
||||
return params;
|
||||
}
|
||||
|
||||
async function send() {
|
||||
let text = inputText.trim();
|
||||
if (!text || !selectedModel) return;
|
||||
if (sending) return;
|
||||
stopTtsPlayback();
|
||||
sending = true;
|
||||
const files = chatInputEl?.getFiles() ?? [];
|
||||
// Transform TipTap mention format to markdown file links
|
||||
@@ -565,18 +617,13 @@
|
||||
}
|
||||
} else {
|
||||
try {
|
||||
const mode = get(toolApprovalMode);
|
||||
const result = await apiSendMessage(
|
||||
text,
|
||||
selectedModel,
|
||||
workspace,
|
||||
chatId,
|
||||
parentId,
|
||||
{
|
||||
tool_approval_mode: mode,
|
||||
plan_mode: get(planMode),
|
||||
request_params: get(requestParams)
|
||||
},
|
||||
getChatSendParams(),
|
||||
undefined,
|
||||
files
|
||||
);
|
||||
@@ -634,14 +681,13 @@
|
||||
}
|
||||
|
||||
try {
|
||||
const mode = get(toolApprovalMode);
|
||||
const result = await apiSendMessage(
|
||||
text,
|
||||
selectedModel,
|
||||
workspace,
|
||||
chatId ?? undefined,
|
||||
parentId,
|
||||
{ tool_approval_mode: mode, plan_mode: get(planMode), request_params: get(requestParams) },
|
||||
getChatSendParams(),
|
||||
undefined,
|
||||
files
|
||||
);
|
||||
@@ -711,6 +757,7 @@
|
||||
async function handleCancel() {
|
||||
const active = allMessages.find((m) => m.role === 'assistant' && !m.done);
|
||||
if (!active || !chatId) return;
|
||||
stopTtsPlayback();
|
||||
|
||||
// Tell the socket handler to skip the reload for this message
|
||||
cancelledMessageId = active.id;
|
||||
@@ -799,12 +846,14 @@
|
||||
if (!msg?.parent_id || !chatId || !selectedModel) return;
|
||||
|
||||
try {
|
||||
const mode = get(toolApprovalMode);
|
||||
const result = await apiSendMessage('', selectedModel, workspace, chatId, msg.parent_id, {
|
||||
tool_approval_mode: mode,
|
||||
plan_mode: get(planMode),
|
||||
request_params: get(requestParams)
|
||||
});
|
||||
const result = await apiSendMessage(
|
||||
'',
|
||||
selectedModel,
|
||||
workspace,
|
||||
chatId,
|
||||
msg.parent_id,
|
||||
getChatSendParams()
|
||||
);
|
||||
if (result.assistant_message) {
|
||||
allMessages = [...allMessages, result.assistant_message];
|
||||
currentMessageId = result.message_id;
|
||||
@@ -846,11 +895,7 @@
|
||||
workspace,
|
||||
chatId,
|
||||
msg.parent_id,
|
||||
{
|
||||
tool_approval_mode: get(toolApprovalMode),
|
||||
plan_mode: get(planMode),
|
||||
request_params: get(requestParams)
|
||||
}
|
||||
getChatSendParams()
|
||||
);
|
||||
if (result.user_message && result.assistant_message) {
|
||||
allMessages = [...allMessages, result.user_message, result.assistant_message];
|
||||
@@ -888,6 +933,244 @@
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
function shouldUseTts() {
|
||||
return $ttsEnabled && $ttsConfigured && ($ttsPlaybackEnabled || $voiceModeEnabled);
|
||||
}
|
||||
|
||||
function resetTtsBuffer() {
|
||||
ttsBuffer = '';
|
||||
ttsInsideCodeFence = false;
|
||||
}
|
||||
|
||||
function stopTtsPlayback() {
|
||||
ttsStopRequested = true;
|
||||
ttsGeneration += 1;
|
||||
ttsQueue = [];
|
||||
resetTtsBuffer();
|
||||
ttsAbort?.abort();
|
||||
ttsAbort = null;
|
||||
if (ttsAudio) {
|
||||
ttsAudio.pause();
|
||||
ttsAudio.src = '';
|
||||
ttsAudio = null;
|
||||
}
|
||||
if (ttsObjectUrl) {
|
||||
URL.revokeObjectURL(ttsObjectUrl);
|
||||
ttsObjectUrl = null;
|
||||
}
|
||||
ttsPlaying = false;
|
||||
speakingMessageId = null;
|
||||
}
|
||||
|
||||
function stripCodeFenceDelta(delta: string): string {
|
||||
let out = '';
|
||||
for (let i = 0; i < delta.length; i++) {
|
||||
if (delta.startsWith('```', i)) {
|
||||
ttsInsideCodeFence = !ttsInsideCodeFence;
|
||||
i += 2;
|
||||
continue;
|
||||
}
|
||||
if (!ttsInsideCodeFence) out += delta[i];
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function cleanSpeechText(text: string): string {
|
||||
return text
|
||||
.replace(/```[\s\S]*?```/g, ' ')
|
||||
.replace(/\[([^\]]+)\]\([^)]+\)/g, '$1')
|
||||
.replace(/`([^`]+)`/g, '$1')
|
||||
.replace(/^#{1,6}\s+/gm, '')
|
||||
.replace(/^\s*[-*+]\s+/gm, '')
|
||||
.replace(/\s+/g, ' ')
|
||||
.trim();
|
||||
}
|
||||
|
||||
function findSpeechBoundary(text: string): number {
|
||||
if (text.length < 60) return -1;
|
||||
for (let i = 40; i < text.length; i++) {
|
||||
const ch = text[i];
|
||||
const next = text[i + 1] || '';
|
||||
if ((ch === '.' || ch === '!' || ch === '?' || ch === '\n') && (!next || /\s/.test(next))) {
|
||||
return i + 1;
|
||||
}
|
||||
}
|
||||
if (text.length > 220) {
|
||||
const idx = text.lastIndexOf(' ', 220);
|
||||
return idx > 80 ? idx : 220;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
function handleTtsDelta(messageId: string, delta: string) {
|
||||
if (!shouldUseTts()) return;
|
||||
if (!delta.trim()) return;
|
||||
|
||||
const active = allMessages.find((m) => m.id === messageId);
|
||||
if (!active || active.role !== 'assistant') return;
|
||||
|
||||
const speakable = stripCodeFenceDelta(delta);
|
||||
if (!speakable.trim()) return;
|
||||
|
||||
ttsBuffer += speakable;
|
||||
let boundary = findSpeechBoundary(ttsBuffer);
|
||||
while (boundary > 0) {
|
||||
const chunk = cleanSpeechText(ttsBuffer.slice(0, boundary));
|
||||
ttsBuffer = ttsBuffer.slice(boundary);
|
||||
if (chunk.length > 1) enqueueSpeech(chunk);
|
||||
boundary = findSpeechBoundary(ttsBuffer);
|
||||
}
|
||||
}
|
||||
|
||||
function flushTtsBuffer() {
|
||||
if (!shouldUseTts()) return;
|
||||
const chunk = cleanSpeechText(ttsBuffer);
|
||||
resetTtsBuffer();
|
||||
if (chunk.length > 1) enqueueSpeech(chunk);
|
||||
}
|
||||
|
||||
function enqueueSpeech(text: string) {
|
||||
ttsQueue = [...ttsQueue, text];
|
||||
if (!ttsPlaying) void playTtsQueue(ttsGeneration);
|
||||
}
|
||||
|
||||
function chunkSpeechText(text: string): string[] {
|
||||
const chunks: string[] = [];
|
||||
let remaining = cleanSpeechText(text);
|
||||
while (remaining) {
|
||||
const boundary = findSpeechBoundary(remaining);
|
||||
const end = boundary > 0 ? boundary : remaining.length;
|
||||
const chunk = cleanSpeechText(remaining.slice(0, end));
|
||||
if (chunk.length > 1) chunks.push(chunk);
|
||||
remaining = remaining.slice(end).trimStart();
|
||||
}
|
||||
return chunks;
|
||||
}
|
||||
|
||||
function getAssistantSpeechText(msg: ChatMessageRow): string {
|
||||
const outputText = (msg.output || [])
|
||||
.filter((item: any) => item.type === 'message')
|
||||
.flatMap((item: any) => item.content || [])
|
||||
.map((part: any) => part.text || part.content || '')
|
||||
.join(' ');
|
||||
return cleanSpeechText(outputText || msg.content || '');
|
||||
}
|
||||
|
||||
function speakMessage(messageId: string) {
|
||||
const msg = allMessages.find((m) => m.id === messageId && m.role === 'assistant');
|
||||
if (!msg || !$ttsEnabled || !$ttsConfigured) return;
|
||||
const text = getAssistantSpeechText(msg);
|
||||
if (!text) return;
|
||||
if (speakingMessageId === messageId && ttsPlaying && $ttsPlaybackEnabled) {
|
||||
ttsPlaybackEnabled.set(false);
|
||||
stopTtsPlayback();
|
||||
return;
|
||||
}
|
||||
stopTtsPlayback();
|
||||
speakingMessageId = messageId;
|
||||
ttsPlaybackEnabled.set(true);
|
||||
ttsErrorShown = false;
|
||||
for (const chunk of chunkSpeechText(text)) enqueueSpeech(chunk);
|
||||
}
|
||||
|
||||
function ttsCacheKey(text: string): string {
|
||||
return [$ttsVoice, $ttsFormat, text].join('\u001f');
|
||||
}
|
||||
|
||||
function getCachedTtsAudio(key: string): Blob | null {
|
||||
const cached = ttsAudioCache.get(key);
|
||||
if (!cached) return null;
|
||||
ttsAudioCache.delete(key);
|
||||
ttsAudioCache.set(key, cached);
|
||||
return cached;
|
||||
}
|
||||
|
||||
function cacheTtsAudio(key: string, blob: Blob) {
|
||||
if (blob.size > TTS_AUDIO_CACHE_LIMIT_BYTES) return;
|
||||
const existing = ttsAudioCache.get(key);
|
||||
if (existing) {
|
||||
ttsAudioCacheBytes -= existing.size;
|
||||
ttsAudioCache.delete(key);
|
||||
}
|
||||
while (ttsAudioCacheBytes + blob.size > TTS_AUDIO_CACHE_LIMIT_BYTES) {
|
||||
const oldest = ttsAudioCache.entries().next().value;
|
||||
if (!oldest) break;
|
||||
ttsAudioCache.delete(oldest[0]);
|
||||
ttsAudioCacheBytes -= oldest[1].size;
|
||||
}
|
||||
ttsAudioCache.set(key, blob);
|
||||
ttsAudioCacheBytes += blob.size;
|
||||
}
|
||||
|
||||
async function playTtsQueue(generation: number) {
|
||||
ttsPlaying = true;
|
||||
try {
|
||||
while (generation === ttsGeneration && ttsQueue.length > 0) {
|
||||
if (!shouldUseTts()) break;
|
||||
const text = ttsQueue.shift();
|
||||
if (!text) continue;
|
||||
|
||||
const cacheKey = ttsCacheKey(text);
|
||||
let blob = getCachedTtsAudio(cacheKey);
|
||||
if (!blob) {
|
||||
ttsAbort = new AbortController();
|
||||
const response = await fetch('/api/audio/speech', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ text, voice: $ttsVoice, workspace }),
|
||||
signal: ttsAbort.signal
|
||||
});
|
||||
if (!response.ok) {
|
||||
if (!ttsErrorShown) {
|
||||
ttsErrorShown = true;
|
||||
let detail = `${response.status}`;
|
||||
try {
|
||||
const data = await response.json();
|
||||
detail = data?.detail || data?.error || detail;
|
||||
} catch {}
|
||||
toast.error($t('admin.audio.tts') + ': ' + detail);
|
||||
}
|
||||
ttsPlaybackEnabled.set(false);
|
||||
voiceModeEnabled.set(false);
|
||||
break;
|
||||
}
|
||||
blob = await response.blob();
|
||||
cacheTtsAudio(cacheKey, blob);
|
||||
}
|
||||
|
||||
if (generation !== ttsGeneration) break;
|
||||
if (ttsObjectUrl) URL.revokeObjectURL(ttsObjectUrl);
|
||||
ttsObjectUrl = URL.createObjectURL(blob);
|
||||
ttsAudio = new Audio(ttsObjectUrl);
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
const audio = ttsAudio!;
|
||||
audio.onended = () => resolve();
|
||||
audio.onerror = () => {
|
||||
if (ttsStopRequested || generation !== ttsGeneration) resolve();
|
||||
else reject(new Error('audio playback failed'));
|
||||
};
|
||||
const started = audio.play();
|
||||
if (started) started.catch(reject);
|
||||
});
|
||||
if (ttsObjectUrl) {
|
||||
URL.revokeObjectURL(ttsObjectUrl);
|
||||
ttsObjectUrl = null;
|
||||
}
|
||||
ttsAudio = null;
|
||||
ttsAbort = null;
|
||||
}
|
||||
} catch (err: any) {
|
||||
if (!ttsStopRequested && err?.name !== 'AbortError' && !ttsErrorShown) {
|
||||
ttsErrorShown = true;
|
||||
toast.error($t('admin.audio.tts') + ': playback failed');
|
||||
}
|
||||
} finally {
|
||||
if (generation === ttsGeneration) ttsPlaying = false;
|
||||
if (generation === ttsGeneration) speakingMessageId = null;
|
||||
if (generation === ttsGeneration) ttsStopRequested = false;
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="flex flex-col h-full bg-white dark:bg-black">
|
||||
@@ -965,9 +1248,11 @@
|
||||
messageId={msg.id}
|
||||
{siblingIndex}
|
||||
siblingTotal={siblingIds.length}
|
||||
speaking={speakingMessageId === msg.id}
|
||||
onnavigate={(dir) => handleNavigate(msg.id, dir)}
|
||||
onregenerate={() => handleRegenerate(msg.id)}
|
||||
onedit={(c, o, submit) => handleEditMessage(msg.id, c, o, submit)}
|
||||
onspeak={() => speakMessage(msg.id)}
|
||||
onapprove={handleApprove}
|
||||
/>
|
||||
{/if}
|
||||
|
||||
@@ -4,12 +4,15 @@
|
||||
streaming: boolean;
|
||||
onsend: () => void;
|
||||
oncancel?: () => void;
|
||||
onvoice?: () => void;
|
||||
voiceActive?: boolean;
|
||||
}
|
||||
let { canSend, streaming, onsend, oncancel }: Props = $props();
|
||||
let { canSend, streaming, onsend, oncancel, onvoice, voiceActive = false }: Props = $props();
|
||||
|
||||
// Show send when there's sendable text, even during streaming (enqueue).
|
||||
// Show stop only when streaming with nothing to send.
|
||||
const showStop = $derived(streaming && !canSend && !!oncancel);
|
||||
const showVoice = $derived(!streaming && !canSend && !!onvoice);
|
||||
</script>
|
||||
|
||||
{#if showStop}
|
||||
@@ -25,6 +28,33 @@
|
||||
/>
|
||||
</svg>
|
||||
</button>
|
||||
{:else if showVoice}
|
||||
<button
|
||||
class="flex items-center justify-center rounded-full p-1 transition
|
||||
{voiceActive
|
||||
? 'bg-gray-900 text-white dark:bg-white dark:text-black'
|
||||
: 'bg-gray-100 text-gray-800 hover:bg-gray-200 dark:bg-white/90 dark:text-black dark:hover:bg-white'}"
|
||||
onclick={onvoice}
|
||||
aria-label="Voice mode"
|
||||
title="Voice mode"
|
||||
>
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-width="2"
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
class="size-4 {voiceActive ? 'animate-pulse' : ''}"
|
||||
>
|
||||
<path d="M4 14V10" />
|
||||
<path d="M8 18V6" />
|
||||
<path d="M12 21V3" />
|
||||
<path d="M16 18V6" />
|
||||
<path d="M20 14V10" />
|
||||
</svg>
|
||||
</button>
|
||||
{:else}
|
||||
<button
|
||||
class="{canSend
|
||||
|
||||
@@ -475,6 +475,16 @@
|
||||
"admin.audio.qualityHintLow": "Kleinste Dateien, optimiert für Sprache.",
|
||||
"admin.audio.stt": "Sprache-zu-Text",
|
||||
"admin.audio.sttHint": "Kompatibel mit OpenAIs Audio-/Transkriptions-API.",
|
||||
"admin.audio.tts": "Text-to-Speech",
|
||||
"admin.audio.enableTts": "Text-to-Speech aktivieren",
|
||||
"admin.audio.ttsEnabledHint": "Aktiviert den Sprachmodus und die Vorlesen-Schaltflächen, wenn ein TTS-Schlüssel verfügbar ist.",
|
||||
"admin.audio.ttsKeyPlaceholder": "Leave blank to reuse STT key",
|
||||
"admin.audio.ttsVoice": "Voice",
|
||||
"admin.audio.ttsFormat": "Format",
|
||||
"admin.audio.ttsHint": "Compatible with OpenAI's audio/speech API. If no TTS key is set, the STT key is reused.",
|
||||
"admin.audio.voiceMode": "Voice Mode",
|
||||
"admin.audio.voiceModeSystemPrompt": "System prompt",
|
||||
"admin.audio.voiceModeSystemPromptHint": "Applied only while voice mode is on. Keep it short to make spoken replies useful.",
|
||||
"admin.audio.saveFailed": "Audioeinstellungen konnten nicht gespeichert werden",
|
||||
"sqlite.loadError": "Datenbank konnte nicht geladen werden.",
|
||||
"sqlite.null": "NULL",
|
||||
@@ -556,6 +566,12 @@
|
||||
"chat.edit.tool": "Werkzeug",
|
||||
"chat.edit.item": "Element",
|
||||
"chat.dictate.unsupported": "Spracherkennung wird in diesem Browser nicht unterstützt.",
|
||||
"chat.voiceModeOn": "Sprachmodus aktiv",
|
||||
"chat.voiceListening": "Hört zu...",
|
||||
"chat.voiceWaiting": "Wartet auf Antwort...",
|
||||
"chat.ttsNotConfigured": "Text-to-Speech ist nicht aktiviert oder konfiguriert.",
|
||||
"chat.speakResponses": "Speak responses",
|
||||
"chat.stopSpeaking": "Stop speaking",
|
||||
"chat.fallbackTitle": "Chat",
|
||||
"admin.gateway.copied": "In die Zwischenablage kopiert",
|
||||
"admin.gateway.createError": "Schlüssel konnte nicht erstellt werden",
|
||||
|
||||
@@ -590,6 +590,16 @@
|
||||
"admin.audio.qualityHintLow": "Smallest files, optimized for speech.",
|
||||
"admin.audio.stt": "Speech-to-Text",
|
||||
"admin.audio.sttHint": "Compatible with OpenAI's audio/transcriptions API.",
|
||||
"admin.audio.tts": "Text-to-Speech",
|
||||
"admin.audio.enableTts": "Enable Text-to-Speech",
|
||||
"admin.audio.ttsEnabledHint": "Enables voice mode and assistant speak buttons when a TTS key is available.",
|
||||
"admin.audio.ttsKeyPlaceholder": "Leave blank to reuse STT key",
|
||||
"admin.audio.ttsVoice": "Voice",
|
||||
"admin.audio.ttsFormat": "Format",
|
||||
"admin.audio.ttsHint": "Compatible with OpenAI's audio/speech API. If no TTS key is set, the STT key is reused.",
|
||||
"admin.audio.voiceMode": "Voice Mode",
|
||||
"admin.audio.voiceModeSystemPrompt": "System prompt",
|
||||
"admin.audio.voiceModeSystemPromptHint": "Applied only while voice mode is on. Keep it short to make spoken replies useful.",
|
||||
"admin.audio.saveFailed": "Failed to save audio settings",
|
||||
|
||||
"sqlite.loadError": "Failed to load database.",
|
||||
@@ -684,6 +694,12 @@
|
||||
"chat.edit.item": "Item",
|
||||
|
||||
"chat.dictate.unsupported": "Speech recognition not supported in this browser.",
|
||||
"chat.voiceModeOn": "Voice mode on",
|
||||
"chat.voiceListening": "Listening...",
|
||||
"chat.voiceWaiting": "Waiting for response...",
|
||||
"chat.ttsNotConfigured": "Text-to-Speech is not enabled or configured.",
|
||||
"chat.speakResponses": "Speak responses",
|
||||
"chat.stopSpeaking": "Stop speaking",
|
||||
"chat.fallbackTitle": "Chat",
|
||||
"chat.greeting": "What can I help you with?",
|
||||
|
||||
@@ -775,4 +791,3 @@
|
||||
"onboarding.connectAiNudge": "Connect an AI provider to start chatting.",
|
||||
"onboarding.goToConnections": "Settings → Connections"
|
||||
}
|
||||
|
||||
@@ -475,6 +475,16 @@
|
||||
"admin.audio.qualityHintLow": "Archivos más pequeños, optimizado para voz.",
|
||||
"admin.audio.stt": "Voz a texto",
|
||||
"admin.audio.sttHint": "Compatible con la API de audio/transcripciones de OpenAI.",
|
||||
"admin.audio.tts": "Text-to-Speech",
|
||||
"admin.audio.enableTts": "Enable Text-to-Speech",
|
||||
"admin.audio.ttsEnabledHint": "Enables voice mode and assistant speak buttons when a TTS key is available.",
|
||||
"admin.audio.ttsKeyPlaceholder": "Leave blank to reuse STT key",
|
||||
"admin.audio.ttsVoice": "Voice",
|
||||
"admin.audio.ttsFormat": "Format",
|
||||
"admin.audio.ttsHint": "Compatible with OpenAI's audio/speech API. If no TTS key is set, the STT key is reused.",
|
||||
"admin.audio.voiceMode": "Voice Mode",
|
||||
"admin.audio.voiceModeSystemPrompt": "System prompt",
|
||||
"admin.audio.voiceModeSystemPromptHint": "Applied only while voice mode is on. Keep it short to make spoken replies useful.",
|
||||
"admin.audio.saveFailed": "No se pudieron guardar los ajustes de audio",
|
||||
"sqlite.loadError": "No se pudo cargar la base de datos.",
|
||||
"sqlite.null": "NULL",
|
||||
@@ -556,6 +566,12 @@
|
||||
"chat.edit.tool": "Herramienta",
|
||||
"chat.edit.item": "Elemento",
|
||||
"chat.dictate.unsupported": "El reconocimiento de voz no es compatible con este navegador.",
|
||||
"chat.voiceModeOn": "Voice mode on",
|
||||
"chat.voiceListening": "Listening...",
|
||||
"chat.voiceWaiting": "Waiting for response...",
|
||||
"chat.ttsNotConfigured": "Text-to-Speech is not enabled or configured.",
|
||||
"chat.speakResponses": "Speak responses",
|
||||
"chat.stopSpeaking": "Stop speaking",
|
||||
"chat.fallbackTitle": "Chat",
|
||||
"admin.gateway.copied": "Copiado al portapapeles",
|
||||
"admin.gateway.createError": "Error al crear la clave",
|
||||
|
||||
@@ -474,6 +474,16 @@
|
||||
"admin.audio.qualityHintLow": "Fichiers les plus petits, optimisé pour la parole.",
|
||||
"admin.audio.stt": "Reconnaissance vocale",
|
||||
"admin.audio.sttHint": "Compatible avec l'API audio/transcriptions d'OpenAI.",
|
||||
"admin.audio.tts": "Text-to-Speech",
|
||||
"admin.audio.enableTts": "Enable Text-to-Speech",
|
||||
"admin.audio.ttsEnabledHint": "Enables voice mode and assistant speak buttons when a TTS key is available.",
|
||||
"admin.audio.ttsKeyPlaceholder": "Leave blank to reuse STT key",
|
||||
"admin.audio.ttsVoice": "Voice",
|
||||
"admin.audio.ttsFormat": "Format",
|
||||
"admin.audio.ttsHint": "Compatible with OpenAI's audio/speech API. If no TTS key is set, the STT key is reused.",
|
||||
"admin.audio.voiceMode": "Voice Mode",
|
||||
"admin.audio.voiceModeSystemPrompt": "System prompt",
|
||||
"admin.audio.voiceModeSystemPromptHint": "Applied only while voice mode is on. Keep it short to make spoken replies useful.",
|
||||
"admin.audio.saveFailed": "Échec de la sauvegarde des paramètres audio",
|
||||
"sqlite.loadError": "Impossible de charger la base de données.",
|
||||
"sqlite.null": "NULL",
|
||||
@@ -555,6 +565,12 @@
|
||||
"chat.edit.tool": "Outil",
|
||||
"chat.edit.item": "Élément",
|
||||
"chat.dictate.unsupported": "La reconnaissance vocale n'est pas prise en charge dans ce navigateur.",
|
||||
"chat.voiceModeOn": "Voice mode on",
|
||||
"chat.voiceListening": "Listening...",
|
||||
"chat.voiceWaiting": "Waiting for response...",
|
||||
"chat.ttsNotConfigured": "Text-to-Speech is not enabled or configured.",
|
||||
"chat.speakResponses": "Speak responses",
|
||||
"chat.stopSpeaking": "Stop speaking",
|
||||
"chat.fallbackTitle": "Chat",
|
||||
"admin.gateway.copied": "Copié dans le presse-papiers",
|
||||
"admin.gateway.createError": "Échec de la création de la clé",
|
||||
|
||||
@@ -475,6 +475,16 @@
|
||||
"admin.audio.qualityHintLow": "最小ファイル、音声に最適化。",
|
||||
"admin.audio.stt": "音声テキスト変換",
|
||||
"admin.audio.sttHint": "OpenAIのaudio/transcriptions APIと互換性があります。",
|
||||
"admin.audio.tts": "Text-to-Speech",
|
||||
"admin.audio.enableTts": "Enable Text-to-Speech",
|
||||
"admin.audio.ttsEnabledHint": "Enables voice mode and assistant speak buttons when a TTS key is available.",
|
||||
"admin.audio.ttsKeyPlaceholder": "Leave blank to reuse STT key",
|
||||
"admin.audio.ttsVoice": "Voice",
|
||||
"admin.audio.ttsFormat": "Format",
|
||||
"admin.audio.ttsHint": "Compatible with OpenAI's audio/speech API. If no TTS key is set, the STT key is reused.",
|
||||
"admin.audio.voiceMode": "Voice Mode",
|
||||
"admin.audio.voiceModeSystemPrompt": "System prompt",
|
||||
"admin.audio.voiceModeSystemPromptHint": "Applied only while voice mode is on. Keep it short to make spoken replies useful.",
|
||||
"admin.audio.saveFailed": "オーディオ設定の保存に失敗しました",
|
||||
"sqlite.loadError": "データベースの読み込みに失敗しました。",
|
||||
"sqlite.null": "NULL",
|
||||
@@ -556,6 +566,12 @@
|
||||
"chat.edit.tool": "ツール",
|
||||
"chat.edit.item": "項目",
|
||||
"chat.dictate.unsupported": "このブラウザでは音声認識がサポートされていません。",
|
||||
"chat.voiceModeOn": "Voice mode on",
|
||||
"chat.voiceListening": "Listening...",
|
||||
"chat.voiceWaiting": "Waiting for response...",
|
||||
"chat.ttsNotConfigured": "Text-to-Speech is not enabled or configured.",
|
||||
"chat.speakResponses": "Speak responses",
|
||||
"chat.stopSpeaking": "Stop speaking",
|
||||
"chat.fallbackTitle": "チャット",
|
||||
"admin.gateway.copied": "クリップボードにコピーしました",
|
||||
"admin.gateway.createError": "キーの作成に失敗しました",
|
||||
|
||||
@@ -475,6 +475,16 @@
|
||||
"admin.audio.qualityHintLow": "가장 작은 파일, 음성에 최적화.",
|
||||
"admin.audio.stt": "음성-텍스트 변환",
|
||||
"admin.audio.sttHint": "OpenAI의 audio/transcriptions API와 호환됩니다.",
|
||||
"admin.audio.tts": "Text-to-Speech",
|
||||
"admin.audio.enableTts": "Enable Text-to-Speech",
|
||||
"admin.audio.ttsEnabledHint": "Enables voice mode and assistant speak buttons when a TTS key is available.",
|
||||
"admin.audio.ttsKeyPlaceholder": "Leave blank to reuse STT key",
|
||||
"admin.audio.ttsVoice": "Voice",
|
||||
"admin.audio.ttsFormat": "Format",
|
||||
"admin.audio.ttsHint": "Compatible with OpenAI's audio/speech API. If no TTS key is set, the STT key is reused.",
|
||||
"admin.audio.voiceMode": "Voice Mode",
|
||||
"admin.audio.voiceModeSystemPrompt": "System prompt",
|
||||
"admin.audio.voiceModeSystemPromptHint": "Applied only while voice mode is on. Keep it short to make spoken replies useful.",
|
||||
"admin.audio.saveFailed": "오디오 설정 저장에 실패했습니다",
|
||||
"sqlite.loadError": "데이터베이스를 불러오지 못했습니다.",
|
||||
"sqlite.null": "NULL",
|
||||
@@ -556,6 +566,12 @@
|
||||
"chat.edit.tool": "도구",
|
||||
"chat.edit.item": "항목",
|
||||
"chat.dictate.unsupported": "이 브라우저에서는 음성 인식이 지원되지 않습니다.",
|
||||
"chat.voiceModeOn": "Voice mode on",
|
||||
"chat.voiceListening": "Listening...",
|
||||
"chat.voiceWaiting": "Waiting for response...",
|
||||
"chat.ttsNotConfigured": "Text-to-Speech is not enabled or configured.",
|
||||
"chat.speakResponses": "Speak responses",
|
||||
"chat.stopSpeaking": "Stop speaking",
|
||||
"chat.fallbackTitle": "채팅",
|
||||
"admin.gateway.copied": "클립보드에 복사됨",
|
||||
"admin.gateway.createError": "키 생성에 실패했습니다",
|
||||
|
||||
@@ -475,6 +475,16 @@
|
||||
"admin.audio.qualityHintLow": "Arquivos menores, otimizado para voz.",
|
||||
"admin.audio.stt": "Voz para texto",
|
||||
"admin.audio.sttHint": "Compatível com a API audio/transcriptions da OpenAI.",
|
||||
"admin.audio.tts": "Text-to-Speech",
|
||||
"admin.audio.enableTts": "Enable Text-to-Speech",
|
||||
"admin.audio.ttsEnabledHint": "Enables voice mode and assistant speak buttons when a TTS key is available.",
|
||||
"admin.audio.ttsKeyPlaceholder": "Leave blank to reuse STT key",
|
||||
"admin.audio.ttsVoice": "Voice",
|
||||
"admin.audio.ttsFormat": "Format",
|
||||
"admin.audio.ttsHint": "Compatible with OpenAI's audio/speech API. If no TTS key is set, the STT key is reused.",
|
||||
"admin.audio.voiceMode": "Voice Mode",
|
||||
"admin.audio.voiceModeSystemPrompt": "System prompt",
|
||||
"admin.audio.voiceModeSystemPromptHint": "Applied only while voice mode is on. Keep it short to make spoken replies useful.",
|
||||
"admin.audio.saveFailed": "Falha ao salvar as configurações de áudio",
|
||||
"sqlite.loadError": "Falha ao carregar o banco de dados.",
|
||||
"sqlite.null": "NULL",
|
||||
@@ -556,6 +566,12 @@
|
||||
"chat.edit.tool": "Ferramenta",
|
||||
"chat.edit.item": "Item",
|
||||
"chat.dictate.unsupported": "O reconhecimento de voz não é suportado neste navegador.",
|
||||
"chat.voiceModeOn": "Voice mode on",
|
||||
"chat.voiceListening": "Listening...",
|
||||
"chat.voiceWaiting": "Waiting for response...",
|
||||
"chat.ttsNotConfigured": "Text-to-Speech is not enabled or configured.",
|
||||
"chat.speakResponses": "Speak responses",
|
||||
"chat.stopSpeaking": "Stop speaking",
|
||||
"chat.fallbackTitle": "Chat",
|
||||
"admin.gateway.copied": "Copiado para a área de transferência",
|
||||
"admin.gateway.createError": "Falha ao criar a chave",
|
||||
|
||||
@@ -475,6 +475,16 @@
|
||||
"admin.audio.qualityHintLow": "Наименьшие файлы, оптимизировано для речи.",
|
||||
"admin.audio.stt": "Распознавание речи",
|
||||
"admin.audio.sttHint": "Совместимо с API audio/transcriptions OpenAI.",
|
||||
"admin.audio.tts": "Text-to-Speech",
|
||||
"admin.audio.enableTts": "Enable Text-to-Speech",
|
||||
"admin.audio.ttsEnabledHint": "Enables voice mode and assistant speak buttons when a TTS key is available.",
|
||||
"admin.audio.ttsKeyPlaceholder": "Leave blank to reuse STT key",
|
||||
"admin.audio.ttsVoice": "Voice",
|
||||
"admin.audio.ttsFormat": "Format",
|
||||
"admin.audio.ttsHint": "Compatible with OpenAI's audio/speech API. If no TTS key is set, the STT key is reused.",
|
||||
"admin.audio.voiceMode": "Voice Mode",
|
||||
"admin.audio.voiceModeSystemPrompt": "System prompt",
|
||||
"admin.audio.voiceModeSystemPromptHint": "Applied only while voice mode is on. Keep it short to make spoken replies useful.",
|
||||
"admin.audio.saveFailed": "Не удалось сохранить настройки аудио",
|
||||
"sqlite.loadError": "Не удалось загрузить базу данных.",
|
||||
"sqlite.null": "NULL",
|
||||
@@ -556,6 +566,12 @@
|
||||
"chat.edit.tool": "Инструмент",
|
||||
"chat.edit.item": "Элемент",
|
||||
"chat.dictate.unsupported": "Распознавание речи не поддерживается в этом браузере.",
|
||||
"chat.voiceModeOn": "Voice mode on",
|
||||
"chat.voiceListening": "Listening...",
|
||||
"chat.voiceWaiting": "Waiting for response...",
|
||||
"chat.ttsNotConfigured": "Text-to-Speech is not enabled or configured.",
|
||||
"chat.speakResponses": "Speak responses",
|
||||
"chat.stopSpeaking": "Stop speaking",
|
||||
"chat.fallbackTitle": "Чат",
|
||||
"admin.gateway.copied": "Скопировано в буфер обмена",
|
||||
"admin.gateway.createError": "Не удалось создать ключ",
|
||||
|
||||
@@ -475,6 +475,16 @@
|
||||
"admin.audio.qualityHintLow": "最小文件,针对语音优化。",
|
||||
"admin.audio.stt": "语音转文字",
|
||||
"admin.audio.sttHint": "兼容 OpenAI 的 audio/transcriptions API。",
|
||||
"admin.audio.tts": "Text-to-Speech",
|
||||
"admin.audio.enableTts": "Enable Text-to-Speech",
|
||||
"admin.audio.ttsEnabledHint": "Enables voice mode and assistant speak buttons when a TTS key is available.",
|
||||
"admin.audio.ttsKeyPlaceholder": "Leave blank to reuse STT key",
|
||||
"admin.audio.ttsVoice": "Voice",
|
||||
"admin.audio.ttsFormat": "Format",
|
||||
"admin.audio.ttsHint": "Compatible with OpenAI's audio/speech API. If no TTS key is set, the STT key is reused.",
|
||||
"admin.audio.voiceMode": "Voice Mode",
|
||||
"admin.audio.voiceModeSystemPrompt": "System prompt",
|
||||
"admin.audio.voiceModeSystemPromptHint": "Applied only while voice mode is on. Keep it short to make spoken replies useful.",
|
||||
"admin.audio.saveFailed": "保存音频设置失败",
|
||||
"sqlite.loadError": "无法加载数据库。",
|
||||
"sqlite.null": "NULL",
|
||||
@@ -556,6 +566,12 @@
|
||||
"chat.edit.tool": "工具",
|
||||
"chat.edit.item": "项目",
|
||||
"chat.dictate.unsupported": "此浏览器不支持语音识别。",
|
||||
"chat.voiceModeOn": "Voice mode on",
|
||||
"chat.voiceListening": "Listening...",
|
||||
"chat.voiceWaiting": "Waiting for response...",
|
||||
"chat.ttsNotConfigured": "Text-to-Speech is not enabled or configured.",
|
||||
"chat.speakResponses": "Speak responses",
|
||||
"chat.stopSpeaking": "Stop speaking",
|
||||
"chat.fallbackTitle": "聊天",
|
||||
"admin.gateway.copied": "已复制到剪贴板",
|
||||
"admin.gateway.createError": "创建密钥失败",
|
||||
|
||||
@@ -475,6 +475,16 @@
|
||||
"admin.audio.qualityHintLow": "最小檔案,針對語音最佳化。",
|
||||
"admin.audio.stt": "語音轉文字",
|
||||
"admin.audio.sttHint": "相容 OpenAI 的 audio/transcriptions API。",
|
||||
"admin.audio.tts": "Text-to-Speech",
|
||||
"admin.audio.enableTts": "Enable Text-to-Speech",
|
||||
"admin.audio.ttsEnabledHint": "Enables voice mode and assistant speak buttons when a TTS key is available.",
|
||||
"admin.audio.ttsKeyPlaceholder": "Leave blank to reuse STT key",
|
||||
"admin.audio.ttsVoice": "Voice",
|
||||
"admin.audio.ttsFormat": "Format",
|
||||
"admin.audio.ttsHint": "Compatible with OpenAI's audio/speech API. If no TTS key is set, the STT key is reused.",
|
||||
"admin.audio.voiceMode": "Voice Mode",
|
||||
"admin.audio.voiceModeSystemPrompt": "System prompt",
|
||||
"admin.audio.voiceModeSystemPromptHint": "Applied only while voice mode is on. Keep it short to make spoken replies useful.",
|
||||
"admin.audio.saveFailed": "儲存音訊設定失敗",
|
||||
"sqlite.loadError": "無法載入資料庫。",
|
||||
"sqlite.null": "NULL",
|
||||
@@ -556,6 +566,12 @@
|
||||
"chat.edit.tool": "工具",
|
||||
"chat.edit.item": "項目",
|
||||
"chat.dictate.unsupported": "此瀏覽器不支援語音辨識。",
|
||||
"chat.voiceModeOn": "Voice mode on",
|
||||
"chat.voiceListening": "Listening...",
|
||||
"chat.voiceWaiting": "Waiting for response...",
|
||||
"chat.ttsNotConfigured": "Text-to-Speech is not enabled or configured.",
|
||||
"chat.speakResponses": "Speak responses",
|
||||
"chat.stopSpeaking": "Stop speaking",
|
||||
"chat.fallbackTitle": "聊天",
|
||||
"admin.gateway.copied": "已複製到剪貼簿",
|
||||
"admin.gateway.createError": "建立金鑰失敗",
|
||||
|
||||
@@ -16,18 +16,42 @@ export const voiceMemosEnabled = writable<boolean>(false);
|
||||
export const transcribeEnabled = writable<boolean>(true);
|
||||
export const recordingQuality = writable<RecordingQuality>('high');
|
||||
export const showVoiceMemo = writable<boolean>(false);
|
||||
export const ttsEnabled = writable<boolean>(false);
|
||||
export const ttsConfigured = writable<boolean>(false);
|
||||
export const ttsVoice = writable<string>('alloy');
|
||||
export const ttsFormat = writable<string>('mp3');
|
||||
export const voiceModeEnabled = writable<boolean>(false);
|
||||
export const ttsPlaybackEnabled = writable<boolean>(
|
||||
typeof localStorage !== 'undefined' ? localStorage.getItem('ttsPlaybackEnabled') === 'true' : false
|
||||
);
|
||||
|
||||
ttsPlaybackEnabled.subscribe((v) => {
|
||||
if (typeof localStorage !== 'undefined') localStorage.setItem('ttsPlaybackEnabled', String(v));
|
||||
});
|
||||
|
||||
export async function refreshAudioState() {
|
||||
try {
|
||||
const data = await fetchJSON<{ config: Record<string, unknown> }>(
|
||||
'/api/admin/config/audio'
|
||||
);
|
||||
voiceMemosEnabled.set(data.config?.['audio.voice_memos_enabled'] === true);
|
||||
transcribeEnabled.set(data.config?.['audio.transcribe_enabled'] !== false);
|
||||
const q = data.config?.['audio.recording_quality'];
|
||||
const data = await fetchJSON<{
|
||||
voice_memos_enabled: boolean;
|
||||
transcribe_enabled: boolean;
|
||||
recording_quality: string;
|
||||
tts_enabled: boolean;
|
||||
tts_configured: boolean;
|
||||
tts_voice: string;
|
||||
tts_format: string;
|
||||
}>('/api/audio/state');
|
||||
voiceMemosEnabled.set(data.voice_memos_enabled === true);
|
||||
transcribeEnabled.set(data.transcribe_enabled !== false);
|
||||
const q = data.recording_quality;
|
||||
if (q === 'medium' || q === 'low') recordingQuality.set(q);
|
||||
else recordingQuality.set('high');
|
||||
ttsEnabled.set(data.tts_enabled === true);
|
||||
ttsConfigured.set(data.tts_configured === true);
|
||||
ttsVoice.set(data.tts_voice || 'alloy');
|
||||
ttsFormat.set(data.tts_format || 'mp3');
|
||||
} catch {
|
||||
voiceMemosEnabled.set(false);
|
||||
ttsEnabled.set(false);
|
||||
ttsConfigured.set(false);
|
||||
}
|
||||
}
|
||||
+15
-6
@@ -7,8 +7,10 @@ from fastapi.responses import JSONResponse
|
||||
from pydantic import BaseModel
|
||||
from typing import Optional
|
||||
|
||||
from cptr.utils.config import AuthResult, check_access, hash_password, now_ms
|
||||
from cptr.routers.chat import invalidate_model_cache
|
||||
from cptr.models import User, Auth, Config
|
||||
from cptr.utils.config import AuthResult, _get_jwt_secret, check_access, hash_password, now_ms
|
||||
from cptr.utils.crypto import decrypt_key, encrypt_key, mask_key
|
||||
|
||||
router = APIRouter(prefix="/api/admin", tags=["admin"])
|
||||
|
||||
@@ -128,20 +130,27 @@ async def get_config_namespace(namespace: str, request: Request):
|
||||
return {"config": await Config.get_namespace(namespace)}
|
||||
|
||||
|
||||
def _prepare_config_updates(updates: dict) -> dict:
|
||||
"""Normalize sensitive config values before persisting them."""
|
||||
prepared = dict(updates)
|
||||
secret = _get_jwt_secret()
|
||||
for key in ("audio.stt_api_key", "audio.tts_api_key"):
|
||||
value = prepared.get(key)
|
||||
if isinstance(value, str) and value and not value.startswith("encrypted:"):
|
||||
prepared[key] = encrypt_key(value, secret)
|
||||
return prepared
|
||||
|
||||
|
||||
@router.put("/config")
|
||||
async def put_config(body: ConfigUpdateRequest, request: Request):
|
||||
"""Update config keys. Upserts each key."""
|
||||
require_admin(request)
|
||||
await Config.upsert(body.config)
|
||||
await Config.upsert(_prepare_config_updates(body.config))
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
# ── Connections ──────────────────────────────────────────────
|
||||
|
||||
from cptr.utils.crypto import encrypt_key, decrypt_key, mask_key
|
||||
from cptr.utils.config import _get_jwt_secret
|
||||
from cptr.routers.chat import invalidate_model_cache
|
||||
|
||||
|
||||
async def _get_connections() -> list[dict]:
|
||||
"""Get all connections from config store."""
|
||||
|
||||
+256
-3
@@ -7,17 +7,21 @@ If pydub is not installed, raw audio is sent directly (works for < 25MB files).
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import hashlib
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
import httpx
|
||||
from fastapi import APIRouter, HTTPException, Request, UploadFile
|
||||
from fastapi import APIRouter, Form, HTTPException, Request, Response, UploadFile
|
||||
from pydantic import BaseModel
|
||||
|
||||
from cptr.models import Config
|
||||
from cptr.utils.config import _get_jwt_secret, check_access
|
||||
from cptr.utils.crypto import decrypt_key
|
||||
from cptr.utils.workspace import ensure_cptr_gitignored
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -35,6 +39,22 @@ COOKIE_NAME = "cptr_session"
|
||||
MAX_FILE_SIZE = 25 * 1024 * 1024 # 25MB Whisper API limit
|
||||
|
||||
|
||||
class SpeechRequest(BaseModel):
|
||||
text: str
|
||||
voice: str | None = None
|
||||
workspace: str | None = None
|
||||
|
||||
|
||||
class AudioStateResponse(BaseModel):
|
||||
voice_memos_enabled: bool
|
||||
transcribe_enabled: bool
|
||||
recording_quality: str
|
||||
tts_enabled: bool
|
||||
tts_configured: bool
|
||||
tts_voice: str
|
||||
tts_format: str
|
||||
|
||||
|
||||
def _get_user(request: Request) -> str:
|
||||
"""Extract user_id from cookie, raise 401 if not authenticated."""
|
||||
token = request.cookies.get(COOKIE_NAME)
|
||||
@@ -45,6 +65,58 @@ def _get_user(request: Request) -> str:
|
||||
return auth.user_id
|
||||
|
||||
|
||||
def _workspace_audio_cache_dir(workspace: str | None, kind: str) -> Path | None:
|
||||
if not workspace:
|
||||
return None
|
||||
ws = Path(workspace).expanduser().resolve()
|
||||
if not ws.is_dir():
|
||||
return None
|
||||
cache_dir = ws / ".cptr" / "cache" / "audio" / kind
|
||||
cache_dir.mkdir(parents=True, exist_ok=True)
|
||||
ensure_cptr_gitignored(ws)
|
||||
return cache_dir
|
||||
|
||||
|
||||
def _cache_key(payload: dict, data: bytes | None = None) -> str:
|
||||
h = hashlib.sha256()
|
||||
h.update(json.dumps(payload, sort_keys=True, separators=(",", ":")).encode())
|
||||
if data is not None:
|
||||
h.update(b"\0")
|
||||
h.update(data)
|
||||
return h.hexdigest()
|
||||
|
||||
|
||||
def _write_bytes_atomic(path: Path, data: bytes) -> None:
|
||||
tmp = path.with_suffix(path.suffix + ".tmp")
|
||||
tmp.write_bytes(data)
|
||||
tmp.replace(path)
|
||||
|
||||
|
||||
def _write_json_atomic(path: Path, data: dict) -> None:
|
||||
_write_bytes_atomic(
|
||||
path,
|
||||
json.dumps(data, ensure_ascii=False, indent=2, sort_keys=True).encode(),
|
||||
)
|
||||
|
||||
|
||||
def _audio_extension(filename: str, content_type: str, fallback: str = ".webm") -> str:
|
||||
ext = Path(filename).suffix.lower()
|
||||
if ext and len(ext) <= 10 and ext[1:].replace("-", "").isalnum():
|
||||
return ext
|
||||
return {
|
||||
"audio/mpeg": ".mp3",
|
||||
"audio/mp3": ".mp3",
|
||||
"audio/webm": ".webm",
|
||||
"audio/ogg": ".ogg",
|
||||
"audio/opus": ".opus",
|
||||
"audio/aac": ".aac",
|
||||
"audio/flac": ".flac",
|
||||
"audio/wav": ".wav",
|
||||
"audio/x-wav": ".wav",
|
||||
"audio/mp4": ".m4a",
|
||||
}.get(content_type.split(";")[0].lower(), fallback)
|
||||
|
||||
|
||||
# ── Audio processing (optional, requires pydub + ffmpeg) ─────────
|
||||
|
||||
|
||||
@@ -109,6 +181,28 @@ def split_audio(file_path: str, max_bytes: int) -> list[str]:
|
||||
# ── Transcription ────────────────────────────────────────────────
|
||||
|
||||
|
||||
@router.get("/state", response_model=AudioStateResponse)
|
||||
async def audio_state(request: Request):
|
||||
"""Return non-sensitive audio feature state for the authenticated UI."""
|
||||
_get_user(request)
|
||||
|
||||
tts_key = await Config.get("audio.tts_api_key")
|
||||
stt_key = await Config.get("audio.stt_api_key")
|
||||
quality = await Config.get("audio.recording_quality")
|
||||
if quality not in ("high", "medium", "low"):
|
||||
quality = "high"
|
||||
|
||||
return AudioStateResponse(
|
||||
voice_memos_enabled=await Config.get("audio.voice_memos_enabled") is True,
|
||||
transcribe_enabled=await Config.get("audio.transcribe_enabled") is not False,
|
||||
recording_quality=str(quality),
|
||||
tts_enabled=await Config.get("audio.tts_enabled") is True,
|
||||
tts_configured=bool(tts_key or stt_key),
|
||||
tts_voice=str((await Config.get("audio.tts_voice")) or "alloy"),
|
||||
tts_format=str((await Config.get("audio.tts_format")) or "mp3"),
|
||||
)
|
||||
|
||||
|
||||
async def _transcribe_chunk(
|
||||
data: bytes,
|
||||
filename: str,
|
||||
@@ -130,7 +224,7 @@ async def _transcribe_chunk(
|
||||
|
||||
|
||||
@router.post("/transcribe")
|
||||
async def transcribe(file: UploadFile, request: Request):
|
||||
async def transcribe(file: UploadFile, request: Request, workspace: str | None = Form(None)):
|
||||
"""Send audio to a Whisper-compatible STT API, return transcript text.
|
||||
|
||||
If pydub + ffmpeg are available and the file is large, it will be
|
||||
@@ -152,11 +246,48 @@ async def transcribe(file: UploadFile, request: Request):
|
||||
raw_data = await file.read()
|
||||
filename = file.filename or "audio.webm"
|
||||
content_type = file.content_type or "audio/webm"
|
||||
cache_dir = _workspace_audio_cache_dir(workspace, "stt")
|
||||
cache_json_path: Path | None = None
|
||||
cache_audio_path: Path | None = None
|
||||
if cache_dir:
|
||||
key = _cache_key(
|
||||
{
|
||||
"type": "stt",
|
||||
"base_url": str(base_url).rstrip("/"),
|
||||
"model": model,
|
||||
"filename": filename,
|
||||
"content_type": content_type,
|
||||
},
|
||||
raw_data,
|
||||
)
|
||||
audio_ext = _audio_extension(filename, content_type)
|
||||
cache_json_path = cache_dir / f"{key}.json"
|
||||
cache_audio_path = cache_dir / f"{key}{audio_ext}"
|
||||
if cache_json_path.exists():
|
||||
try:
|
||||
cached = json.loads(cache_json_path.read_text(encoding="utf-8"))
|
||||
return {"text": str(cached.get("text") or ""), "cached": True}
|
||||
except (OSError, json.JSONDecodeError):
|
||||
pass
|
||||
|
||||
# Small file: send directly, no temp files needed
|
||||
if len(raw_data) <= MAX_FILE_SIZE or not HAS_PYDUB:
|
||||
try:
|
||||
text = await _transcribe_chunk(raw_data, filename, content_type, base_url, api_key, model)
|
||||
if cache_json_path and cache_audio_path:
|
||||
_write_bytes_atomic(cache_audio_path, raw_data)
|
||||
_write_json_atomic(
|
||||
cache_json_path,
|
||||
{
|
||||
"type": "stt",
|
||||
"text": text,
|
||||
"audio_file": cache_audio_path.name,
|
||||
"filename": filename,
|
||||
"content_type": content_type,
|
||||
"base_url": str(base_url).rstrip("/"),
|
||||
"model": model,
|
||||
},
|
||||
)
|
||||
return {"text": text}
|
||||
except httpx.HTTPStatusError as exc:
|
||||
detail = f"STT API error: {exc.response.status_code}"
|
||||
@@ -190,7 +321,22 @@ async def transcribe(file: UploadFile, request: Request):
|
||||
# Use gather to preserve order (as_completed doesn't guarantee it)
|
||||
results = await asyncio.gather(*tasks)
|
||||
|
||||
return {"text": " ".join(r for r in results if r)}
|
||||
text = " ".join(r for r in results if r)
|
||||
if cache_json_path and cache_audio_path:
|
||||
_write_bytes_atomic(cache_audio_path, raw_data)
|
||||
_write_json_atomic(
|
||||
cache_json_path,
|
||||
{
|
||||
"type": "stt",
|
||||
"text": text,
|
||||
"audio_file": cache_audio_path.name,
|
||||
"filename": filename,
|
||||
"content_type": content_type,
|
||||
"base_url": str(base_url).rstrip("/"),
|
||||
"model": model,
|
||||
},
|
||||
)
|
||||
return {"text": text}
|
||||
|
||||
except httpx.HTTPStatusError as exc:
|
||||
logger.warning("[transcribe] STT API error %s: %s", exc.response.status_code, exc.response.text[:500])
|
||||
@@ -218,3 +364,110 @@ async def transcribe(file: UploadFile, request: Request):
|
||||
os.rmdir(tmp_dir)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
def _audio_media_type(fmt: str) -> str:
|
||||
return {
|
||||
"mp3": "audio/mpeg",
|
||||
"opus": "audio/ogg",
|
||||
"aac": "audio/aac",
|
||||
"flac": "audio/flac",
|
||||
"wav": "audio/wav",
|
||||
"pcm": "audio/L16",
|
||||
}.get(fmt, "audio/mpeg")
|
||||
|
||||
|
||||
@router.post("/speech")
|
||||
async def speech(body: SpeechRequest, request: Request):
|
||||
"""Generate speech audio using an OpenAI-compatible TTS API."""
|
||||
_get_user(request)
|
||||
|
||||
text = body.text.strip()
|
||||
if not text:
|
||||
raise HTTPException(400, "Text-to-speech requires non-empty text.")
|
||||
|
||||
if await Config.get("audio.tts_enabled") is not True:
|
||||
raise HTTPException(400, "Text-to-speech is disabled in Settings → Audio.")
|
||||
|
||||
api_key_encrypted = await Config.get("audio.tts_api_key")
|
||||
if not api_key_encrypted:
|
||||
api_key_encrypted = await Config.get("audio.stt_api_key")
|
||||
if not api_key_encrypted:
|
||||
raise HTTPException(
|
||||
400,
|
||||
"Text-to-speech not configured. Set up a TTS or STT API key in Settings → Audio.",
|
||||
)
|
||||
|
||||
api_key = decrypt_key(api_key_encrypted, _get_jwt_secret())
|
||||
base_url = ((await Config.get("audio.tts_base_url")) or "https://api.openai.com/v1").rstrip("/")
|
||||
model = (await Config.get("audio.tts_model")) or "tts-1"
|
||||
voice = body.voice or (await Config.get("audio.tts_voice")) or "alloy"
|
||||
fmt = str((await Config.get("audio.tts_format")) or "mp3").lower()
|
||||
|
||||
payload = {
|
||||
"model": model,
|
||||
"input": text,
|
||||
"voice": voice,
|
||||
"response_format": fmt,
|
||||
}
|
||||
cache_dir = _workspace_audio_cache_dir(body.workspace, "tts")
|
||||
cache_audio_path: Path | None = None
|
||||
cache_json_path: Path | None = None
|
||||
if cache_dir:
|
||||
key = _cache_key(
|
||||
{
|
||||
"type": "tts",
|
||||
"base_url": base_url,
|
||||
"model": model,
|
||||
"voice": voice,
|
||||
"format": fmt,
|
||||
"text": text,
|
||||
}
|
||||
)
|
||||
cache_audio_path = cache_dir / f"{key}.{fmt}"
|
||||
cache_json_path = cache_dir / f"{key}.json"
|
||||
if cache_audio_path.exists():
|
||||
try:
|
||||
return Response(
|
||||
content=cache_audio_path.read_bytes(),
|
||||
media_type=_audio_media_type(str(fmt)),
|
||||
headers={"X-CPTR-Audio-Cache": "hit"},
|
||||
)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=httpx.Timeout(120)) as client:
|
||||
resp = await client.post(
|
||||
f"{base_url}/audio/speech",
|
||||
headers={"Authorization": f"Bearer {api_key}"},
|
||||
json=payload,
|
||||
)
|
||||
resp.raise_for_status()
|
||||
except httpx.HTTPStatusError as exc:
|
||||
logger.warning(
|
||||
"[speech] TTS API error %s: %s",
|
||||
exc.response.status_code,
|
||||
exc.response.text[:500],
|
||||
)
|
||||
raise HTTPException(502, f"TTS API error: {exc.response.status_code}")
|
||||
except httpx.ConnectError:
|
||||
raise HTTPException(502, "Could not connect to TTS API")
|
||||
|
||||
if cache_audio_path and cache_json_path:
|
||||
_write_bytes_atomic(cache_audio_path, resp.content)
|
||||
_write_json_atomic(
|
||||
cache_json_path,
|
||||
{
|
||||
"type": "tts",
|
||||
"text": text,
|
||||
"audio_file": cache_audio_path.name,
|
||||
"base_url": base_url,
|
||||
"model": model,
|
||||
"voice": voice,
|
||||
"format": fmt,
|
||||
"content_type": _audio_media_type(str(fmt)),
|
||||
},
|
||||
)
|
||||
|
||||
return Response(content=resp.content, media_type=_audio_media_type(str(fmt)))
|
||||
+2
-28
@@ -8,12 +8,12 @@ from pathlib import Path
|
||||
from typing import List, Optional
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Query, Request
|
||||
from fastapi.responses import JSONResponse
|
||||
from pydantic import BaseModel
|
||||
|
||||
from cptr.models import Chat, ChatMessage, Config
|
||||
from cptr.utils.config import check_access, now_ms, _get_jwt_secret
|
||||
from cptr.utils.crypto import decrypt_key
|
||||
from cptr.utils.workspace import ensure_cptr_gitignored
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
@@ -22,32 +22,6 @@ router = APIRouter(prefix="/api/chats", tags=["chats"])
|
||||
COOKIE_NAME = "cptr_session"
|
||||
|
||||
|
||||
def _ensure_gitignore(workspace: str) -> None:
|
||||
"""If workspace is a git repo, ensure .cptr is listed in .gitignore."""
|
||||
ws = Path(workspace)
|
||||
if not (ws / ".git").exists():
|
||||
return
|
||||
|
||||
gitignore = ws / ".gitignore"
|
||||
entry = ".cptr"
|
||||
|
||||
# Check if already ignored
|
||||
if gitignore.exists():
|
||||
content = gitignore.read_text(encoding="utf-8", errors="replace")
|
||||
# Match .cptr as a standalone line (not a substring of something else)
|
||||
for line in content.splitlines():
|
||||
stripped = line.strip()
|
||||
if stripped == entry or stripped == entry + "/":
|
||||
return
|
||||
# Append with a preceding newline if file doesn't end with one
|
||||
if content and not content.endswith("\n"):
|
||||
content += "\n"
|
||||
content += f"{entry}\n"
|
||||
gitignore.write_text(content, encoding="utf-8")
|
||||
else:
|
||||
gitignore.write_text(f"{entry}\n", encoding="utf-8")
|
||||
|
||||
|
||||
def _get_user(request: Request) -> str:
|
||||
"""Extract user_id from cookie, raise 401 if not authenticated."""
|
||||
token = request.cookies.get(COOKIE_NAME)
|
||||
@@ -389,7 +363,7 @@ async def send_message(body: SendMessageRequest, request: Request):
|
||||
await asyncio.to_thread(lambda: chats_dir.mkdir(parents=True, exist_ok=True))
|
||||
|
||||
# Auto-add .cptr to .gitignore if this is a git repo
|
||||
await asyncio.to_thread(_ensure_gitignore, body.workspace)
|
||||
await asyncio.to_thread(ensure_cptr_gitignored, body.workspace)
|
||||
|
||||
# Check if the chat has an in-progress assistant message.
|
||||
# If so, queue this message instead of starting a new task.
|
||||
|
||||
+26
-6
@@ -8,7 +8,10 @@ from __future__ import annotations
|
||||
import asyncio
|
||||
import json
|
||||
import logging
|
||||
import platform
|
||||
import re
|
||||
import uuid
|
||||
from datetime import date
|
||||
from pathlib import Path
|
||||
|
||||
from cptr.env import CHAT_MAX_ITERATIONS, CHAT_TOOL_MAX_CHARS
|
||||
@@ -317,10 +320,6 @@ def _load_instruction_files(workspace: str, max_bytes: int = 32_000) -> str:
|
||||
|
||||
# ── Template engine ─────────────────────────────────────────
|
||||
|
||||
import platform
|
||||
import re
|
||||
from datetime import date
|
||||
|
||||
_TEMPLATE_RE = re.compile(r"\{\{(\w+)\}\}")
|
||||
|
||||
DEFAULT_SYSTEM_PROMPT = (
|
||||
@@ -438,6 +437,24 @@ async def _load_system_prompt(workspace: str, model: str = "") -> str:
|
||||
return _render_template(template, variables)
|
||||
|
||||
|
||||
VOICE_MODE_SYSTEM_PROMPT = (
|
||||
"You are in voice mode. Keep responses brief, conversational, and easy to hear aloud. "
|
||||
"Prefer one or two short paragraphs. Ask at most one focused follow-up question when needed. "
|
||||
"Avoid long lists, code blocks, tables, and verbose explanations unless the user explicitly asks."
|
||||
)
|
||||
|
||||
|
||||
async def _apply_voice_mode_system_prompt(system: str, chat_params: dict) -> str:
|
||||
if chat_params.get("voice_mode") is not True:
|
||||
return system
|
||||
prompt = str(
|
||||
(await Config.get("audio.voice_mode_system_prompt")) or VOICE_MODE_SYSTEM_PROMPT
|
||||
).strip()
|
||||
if not prompt:
|
||||
return system
|
||||
return f"{system}\n\n[VOICE MODE]\n{prompt}"
|
||||
|
||||
|
||||
# ── Title generation ────────────────────────────────────────
|
||||
|
||||
|
||||
@@ -1156,6 +1173,8 @@ async def run_chat_task(
|
||||
api_key = decrypt_key(connection.get("api_key", ""), _get_jwt_secret())
|
||||
base_url = connection.get("base_url") or _default_base_url(provider)
|
||||
|
||||
chat_obj = await Chat.get_by_id(chat_id)
|
||||
chat_params = (chat_obj.meta or {}).get("params", {}) if chat_obj else {}
|
||||
system = await _load_system_prompt(workspace, model)
|
||||
messages, loaded_summary = await _load_message_history(chat_id, message_id)
|
||||
if loaded_summary:
|
||||
@@ -1170,12 +1189,10 @@ async def run_chat_task(
|
||||
tools = [t for t in tools if t["name"] != "view_skill"]
|
||||
|
||||
# Strip delegate_task from sub-agent chats (depth limit = 1)
|
||||
chat_obj = await Chat.get_by_id(chat_id)
|
||||
if chat_obj and (chat_obj.meta or {}).get("subagent"):
|
||||
tools = [t for t in tools if t["name"] != "delegate_task"]
|
||||
|
||||
# Parse $skill-name mentions from the user message to auto-activate skills
|
||||
chat_params = (chat_obj.meta or {}).get("params", {}) if chat_obj else {}
|
||||
attached_skill_ids: list[str] = []
|
||||
if skills and messages:
|
||||
# Find the last user message
|
||||
@@ -1200,6 +1217,8 @@ async def run_chat_task(
|
||||
if skill_blocks:
|
||||
system += "\n\n" + "\n\n".join(skill_blocks)
|
||||
|
||||
system = await _apply_voice_mode_system_prompt(system, chat_params)
|
||||
|
||||
# Plan mode: strip write tools, inject prompt as user message (not system, to preserve cache)
|
||||
plan_mode = chat_params.get("plan_mode", False)
|
||||
if plan_mode:
|
||||
@@ -1271,6 +1290,7 @@ async def run_chat_task(
|
||||
skill_blocks.append(format_skill_content(skill))
|
||||
if skill_blocks:
|
||||
system += "\n\n" + "\n\n".join(skill_blocks)
|
||||
system = await _apply_voice_mode_system_prompt(system, chat_params)
|
||||
messages = keep_zone
|
||||
last_usage = None # reset after compaction
|
||||
new_messages_since = 0
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
"""Workspace filesystem helpers."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def ensure_cptr_gitignored(workspace: str | Path) -> None:
|
||||
"""If workspace is a git repo, ensure .cptr is listed in .gitignore."""
|
||||
ws = Path(workspace)
|
||||
if not (ws / ".git").exists():
|
||||
return
|
||||
|
||||
gitignore = ws / ".gitignore"
|
||||
entry = ".cptr"
|
||||
|
||||
if gitignore.exists():
|
||||
content = gitignore.read_text(encoding="utf-8", errors="replace")
|
||||
for line in content.splitlines():
|
||||
stripped = line.strip()
|
||||
if stripped == entry or stripped == entry + "/":
|
||||
return
|
||||
if content and not content.endswith("\n"):
|
||||
content += "\n"
|
||||
content += f"{entry}\n"
|
||||
gitignore.write_text(content, encoding="utf-8")
|
||||
else:
|
||||
gitignore.write_text(f"{entry}\n", encoding="utf-8")
|
||||
@@ -1,122 +0,0 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
|
||||
|
||||
def _reload_logging_modules(env: dict[str, str]):
|
||||
with patch.dict(os.environ, env, clear=False):
|
||||
import cptr.env
|
||||
import cptr.utils.audit
|
||||
import cptr.utils.logger
|
||||
|
||||
importlib.reload(cptr.env)
|
||||
importlib.reload(cptr.utils.logger)
|
||||
importlib.reload(cptr.utils.audit)
|
||||
return cptr.utils.logger, cptr.utils.audit
|
||||
|
||||
|
||||
class LoggingTests(unittest.TestCase):
|
||||
def test_loguru_sinks_keep_streams_separate(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
env = {
|
||||
"CPTR_DATA_DIR": tmp,
|
||||
"CPTR_AUDIT_LOG_LEVEL": "METADATA",
|
||||
"CPTR_AUDIT_LOG_PATH": str(Path(tmp) / "logs" / "audit.jsonl"),
|
||||
"CPTR_LOG_UPSTREAM_REQUESTS": "true",
|
||||
"CPTR_UPSTREAM_REQUEST_LOG_PATH": str(
|
||||
Path(tmp) / "logs" / "upstream-requests.jsonl"
|
||||
),
|
||||
}
|
||||
logger_mod, _ = _reload_logging_modules(env)
|
||||
logger_mod.setup_logging()
|
||||
|
||||
logging.getLogger("cptr.test").info("normal app log")
|
||||
logger_mod.audit_logger().bind(
|
||||
id="audit-id",
|
||||
audit_level="METADATA",
|
||||
user={"id": "user-1"},
|
||||
method="POST",
|
||||
path="/api/admin/config",
|
||||
status_code=200,
|
||||
source_ip="127.0.0.1",
|
||||
user_agent="test",
|
||||
request_body=None,
|
||||
response_body=None,
|
||||
).info("")
|
||||
body = {"model": "claude-sonnet", "messages": [{"role": "user", "content": "hi"}]}
|
||||
logger_mod.log_upstream_request(
|
||||
provider="anthropic",
|
||||
endpoint="https://api.anthropic.com/v1/messages",
|
||||
model="claude-sonnet",
|
||||
api_type="messages",
|
||||
body=body,
|
||||
)
|
||||
|
||||
audit_lines = (Path(tmp) / "logs" / "audit.jsonl").read_text().splitlines()
|
||||
upstream_lines = (Path(tmp) / "logs" / "upstream-requests.jsonl").read_text().splitlines()
|
||||
|
||||
self.assertEqual(len(audit_lines), 1)
|
||||
self.assertEqual(len(upstream_lines), 1)
|
||||
self.assertEqual(json.loads(audit_lines[0])["id"], "audit-id")
|
||||
self.assertEqual(json.loads(upstream_lines[0])["body"], body)
|
||||
self.assertNotIn("normal app log", audit_lines[0])
|
||||
self.assertNotIn("normal app log", upstream_lines[0])
|
||||
|
||||
def test_upstream_logging_is_disabled_by_default(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
env = {
|
||||
"CPTR_DATA_DIR": tmp,
|
||||
"CPTR_AUDIT_LOG_LEVEL": "NONE",
|
||||
"CPTR_LOG_UPSTREAM_REQUESTS": "false",
|
||||
}
|
||||
logger_mod, _ = _reload_logging_modules(env)
|
||||
logger_mod.setup_logging()
|
||||
|
||||
logger_mod.log_upstream_request(
|
||||
provider="anthropic",
|
||||
endpoint="https://api.anthropic.com/v1/messages",
|
||||
model="claude-sonnet",
|
||||
api_type="messages",
|
||||
body={"model": "claude-sonnet"},
|
||||
)
|
||||
|
||||
self.assertFalse((Path(tmp) / "logs" / "upstream-requests.jsonl").exists())
|
||||
|
||||
def test_audit_body_redacts_sensitive_json_fields(self):
|
||||
_, audit_mod = _reload_logging_modules({"CPTR_AUDIT_LOG_LEVEL": "REQUEST"})
|
||||
body = bytearray(
|
||||
json.dumps(
|
||||
{
|
||||
"username": "alice",
|
||||
"password": "secret",
|
||||
"nested": {"api_key": "sk-test", "token": "tok"},
|
||||
}
|
||||
).encode()
|
||||
)
|
||||
|
||||
redacted = json.loads(audit_mod._decode_body(body))
|
||||
|
||||
self.assertEqual(redacted["username"], "alice")
|
||||
self.assertEqual(redacted["password"], "********")
|
||||
self.assertEqual(redacted["nested"]["api_key"], "********")
|
||||
self.assertEqual(redacted["nested"]["token"], "********")
|
||||
|
||||
def test_audit_context_caps_request_body(self):
|
||||
_, audit_mod = _reload_logging_modules({"CPTR_AUDIT_LOG_LEVEL": "REQUEST"})
|
||||
context = audit_mod.AuditContext(max_body_size=5)
|
||||
|
||||
context.add_request(b"hello")
|
||||
context.add_request(b" world")
|
||||
|
||||
self.assertEqual(bytes(context.request_body), b"hello")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user