mirror of
https://github.com/open-webui/computer.git
synced 2026-11-22 21:50:43 -05:00
55 files changed
+3348
-787
No files matched your search
@@ -5,6 +5,25 @@ All notable changes to this project will be documented in this file.
|
||||
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
|
||||
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
||||
|
||||
## [0.5.0] - 2026-06-16
|
||||
|
||||
### Added
|
||||
|
||||
- 🎙️ **Voice mode.** Talk to the AI hands-free. When text-to-speech is configured, a new voice button appears in the chat input. Tap it to start listening. Speak your message, and cptr will transcribe it, send it to the AI, and read the response back to you out loud. The mic re-arms automatically so you can have a back-and-forth conversation without touching the screen.
|
||||
- 🔊 **Text-to-speech.** AI responses can now be read aloud. Connect any OpenAI-compatible TTS API from Settings > Audio, pick a voice and format, and responses will stream as audio sentence by sentence. Works with voice mode or on its own: click the speaker icon on any message to hear it.
|
||||
- 💭 **Reasoning display.** Models that think before responding (like o3 or Claude with extended thinking) now show their reasoning in the chat. Thought steps appear as collapsible sections you can expand to see what the AI was considering.
|
||||
- 📋 **Audit logging.** Every mutating API request (POST, PUT, PATCH, DELETE) can now be logged to a structured JSON file. Sensitive fields like passwords and API keys are automatically redacted. Configure the level of detail with the `CPTR_AUDIT_LOG_LEVEL` environment variable: metadata only, request bodies, or full request and response.
|
||||
- 📊 **Upstream request logging.** Optionally log every outgoing AI API call (provider, model, endpoint, request body) to a separate file for debugging and cost tracking. Enable with `CPTR_LOG_UPSTREAM_REQUESTS=true`.
|
||||
- 🪵 **Structured logging.** All application logs now go through Loguru with configurable format (text or JSON), level, and rotation. Standard library loggers (uvicorn, etc.) are intercepted and routed through the same system.
|
||||
|
||||
### Changed
|
||||
|
||||
- 💬 **Redesigned tool call and reasoning UI.** Tool calls and reasoning steps are now displayed as clean, collapsible rows with status indicators (spinning while running, green check when done, red X if rejected). Consecutive tool calls are grouped together so the chat stays compact. Each group shows a summary like "3 read_file, 1 edit_file" and can be expanded to see individual calls with their inputs and outputs.
|
||||
- 🔊 **Audio settings expanded.** The Audio admin panel now has separate sections for speech-to-text and text-to-speech, plus a voice mode system prompt that tells the AI to keep responses short and conversational when you are talking to it.
|
||||
- 🎙️ **Transcription caching.** Audio transcriptions are cached in the workspace so the same recording is not sent to the API twice. Transcription results are also saved alongside the audio file.
|
||||
- 📱 **PWA icon and touch icon.** Updated app icons and added an Apple touch icon for better home screen appearance on iOS.
|
||||
- 🌍 **New translation keys.** Added voice mode, TTS, reasoning, and tool call labels across all 10 supported languages.
|
||||
|
||||
## [0.4.10] - 2026-06-15
|
||||
|
||||
### Changed
|
||||
|
||||
+5
-4
@@ -26,16 +26,17 @@ RUN uv build --wheel --out-dir /dist
|
||||
FROM ghcr.io/astral-sh/uv:python3.12-bookworm-slim AS runtime
|
||||
|
||||
LABEL org.opencontainers.image.source="https://github.com/open-webui/computer"
|
||||
LABEL org.opencontainers.image.description="cptr - your computer, from anywhere"
|
||||
LABEL org.opencontainers.image.licenses="BSL-1.1"
|
||||
LABEL org.opencontainers.image.description="cptr: your computer, from anywhere"
|
||||
|
||||
# Runtime deps: git for git operations, tini for PID 1
|
||||
RUN apt-get update && \
|
||||
apt-get install -y --no-install-recommends git tini && \
|
||||
rm -rf /var/lib/apt/lists/*
|
||||
|
||||
# Create non-root user
|
||||
RUN useradd --create-home --shell /bin/bash cptr
|
||||
# Create non-root user and writable data directory
|
||||
RUN useradd --create-home --shell /bin/bash cptr && \
|
||||
mkdir -p /data && \
|
||||
chown -R cptr:cptr /data
|
||||
USER cptr
|
||||
WORKDIR /home/cptr
|
||||
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
# Manifesto
|
||||
|
||||
> **TL;DR** We pushed code and went to dinner. Prod broke. Phone in pocket, laptop at home. So we built `cptr` for ourselves. Your machine, in any browser. Files, terminal, editor, git, all of it. Phone, tablet, laptop, whatever. It literally is your computer. Now go outside.
|
||||
|
||||
A developer moves to Portugal for the light. She works remotely for a company in New York. The commute is gone. The office is gone. Her apartment has a terrace with bougainvillea and a view of the Tagus. She sits at a desk in a dark room for eight hours and sees the river between pull requests.
|
||||
|
||||
A father works from home. His daughter is three. He is present in the house for every hour she is awake. He is available for almost none of them. "Working from home" means a closed door, a lit screen, and a posture that says: not now. She learns early that he is home but not here. Remote work promised presence. It delivered proximity.
|
||||
|
||||
@@ -12,17 +12,11 @@
|
||||
|
||||

|
||||
|
||||
The computer used to be a room. Then a desk. Then a bag. Now it's a URL.
|
||||
<sub>See more at [cptr.sh](https://cptr.sh/)</sub>
|
||||
|
||||
Your phone goes everywhere with you. You run your life from it. Your computer used to stay home. Now it can come along.
|
||||
`cptr` (short for "computer") runs on your machine and serves your whole computer (files, terminal, editor, git) to any browser. It literally is your computer.
|
||||
|
||||
`cptr` (short for "computer") runs on your machine and puts the whole thing in a browser tab. Pull out your phone and you're in. Files, editor, terminal, git, running on the computer you already own.
|
||||
|
||||
Push a hotfix from the train. Check on a deploy from bed. Ship a side project from the park. Stage and commit without touching the command line, or open the terminal and do it the old way. Search across files. Preview markdown. Drag things around. Switch between projects without losing your place.
|
||||
|
||||
Close the tab. Come back tomorrow on any device. Everything is where you left it. Sessions survive disconnects. Your work doesn't care which screen you're on.
|
||||
|
||||
Life is short. Touch grass.
|
||||
Phone, tablet, laptop, another computer, even the one it's running on. Designed to feel native on every screen. Plug in an AI that can actually read, write, and run things on your machine, or bring your favourite terminal agent. Terminal multiplexer, parallel AI agents, full workstation, one tool, any device.
|
||||
|
||||
## Install
|
||||
|
||||
@@ -76,6 +70,9 @@ Bring your own API key. Works with OpenAI, Anthropic, Ollama, or any OpenAI-comp
|
||||
| | |
|
||||
|---|---|
|
||||
| 💬 **Chat** | Built-in AI with streaming responses and tool calling. Not just conversation: it can act. |
|
||||
| 🎙️ **Voice mode** | Talk to the AI hands-free. It listens, responds, and reads the answer back to you. The mic re-arms so you can have a real conversation. |
|
||||
| 🔊 **Text-to-speech** | AI responses read aloud, sentence by sentence. Works with any OpenAI-compatible TTS API. |
|
||||
| 💭 **Reasoning** | See what the AI is thinking. Models like o3 and Claude show their chain of thought as expandable sections. |
|
||||
| 🔧 **File tools** | AI reads, writes, edits, and searches your codebase directly. |
|
||||
| ▶️ **Run commands** | AI executes shell commands and reads the output. Foreground or background. |
|
||||
| 🌐 **Web browsing** | Navigate pages, click elements, fill forms, take screenshots. |
|
||||
@@ -113,6 +110,8 @@ cptr exposes an OpenAI-compatible API (`/v1/chat/completions`). Any client that
|
||||
| 🔔 **Notifications** | Browser notifications and webhooks (Slack, Discord, Teams) when tasks finish. |
|
||||
| 📊 **Usage** | Token counts and timing on every response. |
|
||||
| 📄 **System prompts** | Per-model, per-workspace, or global. Template variables included. |
|
||||
| 📋 **Audit logging** | Structured audit trail of all API mutations with automatic redaction of sensitive data. |
|
||||
| 🪵 **Diagnostic logging** | Configurable structured logs (text or JSON) with optional upstream request capture. |
|
||||
| ⌨️ **Keyboard shortcuts** | Customisable keybindings with a settings panel. |
|
||||
| 🌍 **10 languages** | EN, DE, ES, FR, JA, KO, PT-BR, RU, ZH-CN, ZH-TW. |
|
||||
| 🔐 **Auth** | Username/password with JWT sessions. Signup toggle for admins. |
|
||||
@@ -125,9 +124,13 @@ cptr exposes an OpenAI-compatible API (`/v1/chat/completions`). Any client that
|
||||
|
||||
**Computer, not chat.** The core is the filesystem, the terminal, and git. Files over apps. Plain files on your machine, not content trapped inside another product. AI conversations are files too: searchable, editable, movable, commit-able. cptr is a window into the real system, not a container on top of it.
|
||||
|
||||
Read our [Manifesto](MANIFESTO.md).
|
||||
`cptr` runs on your machine and puts the whole thing in a browser tab. Pull out your phone and you're in. Files, editor, terminal, git, running on the computer you already own.
|
||||
|
||||
Push a hotfix from the train. Check on a deploy from bed. Ship a side project from the park. Stage and commit without touching the command line, or open the terminal and do it the old way. Search across files. Preview markdown. Drag things around. Switch between projects without losing your place.
|
||||
|
||||
Close the tab. Come back tomorrow on any device. Everything is where you left it. Sessions survive disconnects. Your work doesn't care which screen you're on.
|
||||
|
||||
Life is short. Touch grass. Read our [Manifesto](MANIFESTO.md).
|
||||
|
||||
## Docker
|
||||
|
||||
@@ -146,6 +149,8 @@ Then open the URL printed in the logs, usually `http://localhost:8000/?token=...
|
||||
|
||||
`cptr` stores its state in `/data`. Mount your project into the container, like `-v "$PWD:/workspace"`, so cptr can access it.
|
||||
|
||||
If you bind-mount a host directory to `/data`, make sure that directory is writable by the container user. SQLite needs to create and update `/data/app.db`, and host directory permissions take precedence over the image's built-in `/data` ownership.
|
||||
|
||||
The `:dev` image is also available and tracks the `main` branch.
|
||||
|
||||
## Security model
|
||||
|
||||
+17
@@ -33,6 +33,10 @@ app = FastAPI()
|
||||
|
||||
@app.on_event("startup")
|
||||
async def startup():
|
||||
from cptr.utils.logger import setup_logging
|
||||
|
||||
setup_logging()
|
||||
|
||||
# Use OS certificate store (Windows CertStore, macOS Keychain, etc.)
|
||||
# instead of the bundled certifi CA bundle — fixes #31.
|
||||
import logging as _logging
|
||||
@@ -127,6 +131,19 @@ async def auth_middleware(request: Request, call_next):
|
||||
return await call_next(request)
|
||||
|
||||
|
||||
from cptr.env import AUDIT_EXCLUDED_PATHS, AUDIT_MAX_BODY_SIZE
|
||||
from cptr.utils.audit import AuditLevel, AuditLoggingMiddleware, get_audit_level
|
||||
|
||||
audit_level = get_audit_level()
|
||||
if audit_level != AuditLevel.NONE:
|
||||
app.add_middleware(
|
||||
AuditLoggingMiddleware,
|
||||
audit_level=audit_level,
|
||||
excluded_paths=AUDIT_EXCLUDED_PATHS,
|
||||
max_body_size=AUDIT_MAX_BODY_SIZE,
|
||||
)
|
||||
|
||||
|
||||
# Proxy fallback middleware: intercepts sub-resource requests for proxied
|
||||
# dev servers (JS modules, CSS, etc.) based on the Referer header chain.
|
||||
# Added after auth middleware so it wraps outermost (runs before auth),
|
||||
|
||||
+36
@@ -9,6 +9,17 @@ from __future__ import annotations
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def _env_bool(name: str, default: str = "false") -> bool:
|
||||
return os.environ.get(name, default).lower() in ("true", "1", "yes", "on")
|
||||
|
||||
|
||||
def _env_int(name: str, default: int) -> int:
|
||||
try:
|
||||
return int(os.environ.get(name, str(default)))
|
||||
except ValueError:
|
||||
return default
|
||||
|
||||
# ── Data directory ──────────────────────────────────────────
|
||||
# Where cptr stores its database, config, and user data.
|
||||
# Default: ~/.cptr
|
||||
@@ -16,6 +27,31 @@ DATA_DIR = Path(os.environ.get("CPTR_DATA_DIR", str(Path.home() / ".cptr")))
|
||||
CONFIG_FILE = DATA_DIR / "config.toml"
|
||||
DB_FILE = DATA_DIR / "app.db"
|
||||
|
||||
# ── Logging ─────────────────────────────────────────────────
|
||||
LOG_LEVEL = os.environ.get("CPTR_LOG_LEVEL", "INFO").upper()
|
||||
LOG_FORMAT = os.environ.get("CPTR_LOG_FORMAT", "text").lower()
|
||||
|
||||
AUDIT_LOG_LEVEL = os.environ.get("CPTR_AUDIT_LOG_LEVEL", "NONE").upper()
|
||||
AUDIT_LOG_PATH = Path(
|
||||
os.environ.get("CPTR_AUDIT_LOG_PATH", str(DATA_DIR / "logs" / "audit.jsonl"))
|
||||
)
|
||||
AUDIT_LOG_ROTATION = os.environ.get("CPTR_AUDIT_LOG_ROTATION", "10 MB")
|
||||
AUDIT_MAX_BODY_SIZE = _env_int("CPTR_AUDIT_MAX_BODY_SIZE", 2048)
|
||||
AUDIT_EXCLUDED_PATHS = [
|
||||
path.strip()
|
||||
for path in os.environ.get("CPTR_AUDIT_EXCLUDED_PATHS", "/api/chats,/v1/chat").split(",")
|
||||
if path.strip()
|
||||
]
|
||||
|
||||
LOG_UPSTREAM_REQUESTS = _env_bool("CPTR_LOG_UPSTREAM_REQUESTS", "false")
|
||||
UPSTREAM_REQUEST_LOG_PATH = Path(
|
||||
os.environ.get(
|
||||
"CPTR_UPSTREAM_REQUEST_LOG_PATH",
|
||||
str(DATA_DIR / "logs" / "upstream-requests.jsonl"),
|
||||
)
|
||||
)
|
||||
UPSTREAM_REQUEST_LOG_ROTATION = os.environ.get("CPTR_UPSTREAM_REQUEST_LOG_ROTATION", "50 MB")
|
||||
|
||||
# ── Startup token ───────────────────────────────────────────
|
||||
# One-time token for first-time setup. Set by CLI, consumed by app.
|
||||
STARTUP_TOKEN: str | None = os.environ.pop("CPTR_STARTUP_TOKEN", None)
|
||||
|
||||
@@ -82,11 +82,13 @@
|
||||
border-radius: 9999px;
|
||||
}
|
||||
|
||||
.scrollbar-hidden {
|
||||
.scrollbar-hidden,
|
||||
.scrollbar-none {
|
||||
scrollbar-width: none;
|
||||
-ms-overflow-style: none;
|
||||
}
|
||||
.scrollbar-hidden::-webkit-scrollbar {
|
||||
.scrollbar-hidden::-webkit-scrollbar,
|
||||
.scrollbar-none::-webkit-scrollbar {
|
||||
display: none;
|
||||
}
|
||||
|
||||
|
||||
@@ -15,7 +15,7 @@
|
||||
<meta name="apple-mobile-web-app-capable" content="yes" />
|
||||
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />
|
||||
<meta name="apple-mobile-web-app-title" content="cptr" />
|
||||
<link rel="apple-touch-icon" href="/icon-192.png" />
|
||||
<link rel="apple-touch-icon" href="/apple-touch-icon.png" />
|
||||
%sveltekit.head%
|
||||
</head>
|
||||
<body data-sveltekit-preload-data="hover">
|
||||
|
||||
@@ -120,6 +120,9 @@ export interface ModelConfigResponse {
|
||||
export const getModelConfig = async (): Promise<ModelConfigResponse> =>
|
||||
fetchJSON<ModelConfigResponse>('/api/admin/models/config');
|
||||
|
||||
export const refreshModelList = async (): Promise<ModelConfigResponse> =>
|
||||
fetchJSON<ModelConfigResponse>('/api/admin/models/refresh', { method: 'POST' });
|
||||
|
||||
export const updateModelConfig = (
|
||||
modelId: string,
|
||||
update: { is_active?: boolean; params?: Record<string, unknown> }
|
||||
|
||||
@@ -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 }[]
|
||||
) =>
|
||||
|
||||
@@ -59,13 +59,18 @@ export const gitCommit = (root: string, message: string) =>
|
||||
|
||||
export const gitPull = (root: string) => fetchJSON('/api/git/pull', jsonBody({ root }));
|
||||
|
||||
export const gitFetch = (root: string) => fetchJSON('/api/git/fetch', jsonBody({ root }));
|
||||
|
||||
export const gitPush = (
|
||||
root: string,
|
||||
{ force = false, set_upstream = false, branch }: { force?: boolean; set_upstream?: boolean; branch?: string } = {}
|
||||
{
|
||||
force = false,
|
||||
set_upstream = false,
|
||||
branch
|
||||
}: { force?: boolean; set_upstream?: boolean; branch?: string } = {}
|
||||
) => fetchJSON('/api/git/push', jsonBody({ root, force, set_upstream, branch }));
|
||||
|
||||
export const gitUncommit = (root: string) =>
|
||||
fetchJSON('/api/git/uncommit', jsonBody({ root }));
|
||||
export const gitUncommit = (root: string) => fetchJSON('/api/git/uncommit', jsonBody({ root }));
|
||||
|
||||
export const createGitBranch = (root: string, name: string) =>
|
||||
fetchJSON('/api/git/branch', jsonBody({ root, name }));
|
||||
|
||||
@@ -18,6 +18,17 @@
|
||||
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('');
|
||||
let voiceModeSttMode = $state<'browser' | 'provider'>('browser');
|
||||
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 +41,15 @@
|
||||
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) || '';
|
||||
voiceModeSttMode =
|
||||
config['audio.voice_mode_stt_mode'] === 'provider' ? 'provider' : 'browser';
|
||||
} catch {}
|
||||
loading = false;
|
||||
});
|
||||
@@ -42,13 +62,24 @@
|
||||
'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,
|
||||
'audio.voice_mode_stt_mode': voiceModeSttMode
|
||||
};
|
||||
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 +171,110 @@
|
||||
</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 class="flex items-center justify-between">
|
||||
<span class="text-xs text-gray-600 dark:text-gray-400">{$t('admin.audio.voiceModeSttMode')}</span>
|
||||
<select
|
||||
bind:value={voiceModeSttMode}
|
||||
class="bg-transparent text-xs text-gray-600 dark:text-gray-400 outline-none cursor-pointer"
|
||||
>
|
||||
<option value="browser">{$t('admin.audio.voiceModeSttBrowser')}</option>
|
||||
<option value="provider">{$t('admin.audio.voiceModeSttProvider')}</option>
|
||||
</select>
|
||||
</div>
|
||||
<p class="text-[11px] text-gray-400 dark:text-gray-600 -mt-1">
|
||||
{voiceModeSttMode === 'browser' ? $t('admin.audio.voiceModeBrowserSttHint') : $t('admin.audio.voiceModeProviderSttHint')}
|
||||
</p>
|
||||
<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
|
||||
|
||||
@@ -3,12 +3,15 @@
|
||||
import { toast } from 'svelte-sonner';
|
||||
import {
|
||||
getModelConfig,
|
||||
refreshModelList,
|
||||
updateModelConfig,
|
||||
getAdminConfig,
|
||||
updateConfig,
|
||||
type ModelConfigEntry
|
||||
} from '$lib/apis/admin';
|
||||
import { t } from '$lib/i18n';
|
||||
import { tooltip } from '$lib/tooltip';
|
||||
import { refreshChatState } from '$lib/stores/chat';
|
||||
import Icon from '../Icon.svelte';
|
||||
import Spinner from '$lib/components/common/Spinner.svelte';
|
||||
import ModelSelector from '$lib/components/common/ModelSelector.svelte';
|
||||
@@ -26,6 +29,7 @@
|
||||
|
||||
let loading = $state(true);
|
||||
let saving = $state(false);
|
||||
let refreshing = $state(false);
|
||||
let models = $state<ModelEntry[]>([]);
|
||||
let selectedId = $state<string | null>(null);
|
||||
|
||||
@@ -54,7 +58,7 @@
|
||||
|
||||
const DEFAULT_PROMPT_PLACEHOLDER = `You are a helpful coding assistant. You have access to tools to read, search, and modify files in the workspace. Use them to help the user with their coding tasks.
|
||||
|
||||
For complex tasks, create an implementation plan first using create_artifact, then wait for approval before coding.
|
||||
For complex tasks, create an implementation plan first using create_artifact. Then wait for an explicit approval message before using tools or implementing.
|
||||
|
||||
{{INSTRUCTIONS}}
|
||||
|
||||
@@ -86,37 +90,75 @@ Files:
|
||||
return result;
|
||||
}
|
||||
|
||||
onMount(async () => {
|
||||
try {
|
||||
const data = await getModelConfig();
|
||||
const config = data.config || {};
|
||||
function applyModelConfig(
|
||||
data: Awaited<ReturnType<typeof getModelConfig>>,
|
||||
preserveDirty = false
|
||||
) {
|
||||
const config = data.config || {};
|
||||
const previousById = new Map(models.map((model) => [model.id, model]));
|
||||
|
||||
if (!preserveDirty || !globalDirty) {
|
||||
globalRows = parseRows(config['*']);
|
||||
globalSystemPrompt = config['*']?.params?.system_prompt || '';
|
||||
globalExpanded = globalRows.length > 0 || !!globalSystemPrompt;
|
||||
models = data.models.map((m) => {
|
||||
const mc = config[m.id];
|
||||
return {
|
||||
...m,
|
||||
is_active: mc?.is_active !== false,
|
||||
rows: parseRows(mc),
|
||||
systemPrompt: (mc?.params as any)?.system_prompt || '',
|
||||
dirty: false
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
models = data.models.map((m) => {
|
||||
const previous = previousById.get(m.id);
|
||||
if (preserveDirty && previous?.dirty) {
|
||||
return { ...previous, ...m };
|
||||
}
|
||||
|
||||
const mc = config[m.id];
|
||||
return {
|
||||
...m,
|
||||
is_active: mc?.is_active !== false,
|
||||
rows: parseRows(mc),
|
||||
systemPrompt: (mc?.params as any)?.system_prompt || '',
|
||||
dirty: false
|
||||
};
|
||||
});
|
||||
|
||||
if (selectedId && !models.some((model) => model.id === selectedId)) {
|
||||
selectedId = null;
|
||||
}
|
||||
}
|
||||
|
||||
async function loadModelConfig() {
|
||||
try {
|
||||
applyModelConfig(await getModelConfig());
|
||||
} catch {
|
||||
toast.error($t('models.failedToLoad'));
|
||||
} finally {
|
||||
loading = false;
|
||||
}
|
||||
}
|
||||
|
||||
onMount(async () => {
|
||||
await loadModelConfig();
|
||||
|
||||
// Load admin config (default model, context compaction)
|
||||
try {
|
||||
const adminCfg = await getAdminConfig();
|
||||
compactTokenThreshold = Number(adminCfg['chat.compact_token_threshold']) || 80000;
|
||||
defaultModelId = typeof adminCfg['chat.default_model'] === 'string' ? adminCfg['chat.default_model'] : '';
|
||||
defaultModelId =
|
||||
typeof adminCfg['chat.default_model'] === 'string' ? adminCfg['chat.default_model'] : '';
|
||||
} catch {}
|
||||
});
|
||||
|
||||
async function refreshModels() {
|
||||
refreshing = true;
|
||||
try {
|
||||
applyModelConfig(await refreshModelList(), true);
|
||||
await refreshChatState();
|
||||
toast.success($t('models.refreshed'));
|
||||
} catch {
|
||||
toast.error($t('models.refreshFailed'));
|
||||
} finally {
|
||||
refreshing = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function toggleModel(e: Event, model: ModelEntry) {
|
||||
e.stopPropagation();
|
||||
const newVal = !model.is_active;
|
||||
@@ -278,9 +320,20 @@ Files:
|
||||
<div class="flex justify-center py-8"><Spinner size={16} /></div>
|
||||
{:else}
|
||||
<div class="flex-1 min-h-0 overflow-y-auto">
|
||||
<h2 class="text-sm font-medium text-gray-900 dark:text-white mb-4">
|
||||
{$t('admin.models')}
|
||||
</h2>
|
||||
<div class="flex items-center justify-between mb-4">
|
||||
<h2 class="text-sm font-medium text-gray-900 dark:text-white">
|
||||
{$t('admin.models')}
|
||||
</h2>
|
||||
<button
|
||||
class="flex items-center justify-center w-6 h-6 rounded-lg text-gray-400 hover:text-gray-700 disabled:opacity-50 disabled:hover:text-gray-400 dark:text-gray-600 dark:hover:text-gray-300 dark:disabled:hover:text-gray-600 transition-colors duration-75"
|
||||
onclick={refreshModels}
|
||||
disabled={refreshing || saving}
|
||||
aria-label={$t('models.refresh')}
|
||||
use:tooltip={$t('models.refresh')}
|
||||
>
|
||||
<Icon name="refresh" size={13} class={refreshing ? 'animate-spin' : ''} />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<!-- Default model -->
|
||||
<h3 class="text-xs text-gray-400 dark:text-gray-600 mb-2">
|
||||
|
||||
@@ -646,7 +646,7 @@
|
||||
<!-- Universal toolbar (hidden for untitled files with no content yet) -->
|
||||
<div class="toolbar">
|
||||
<div class="toolbar-left">
|
||||
<span class="file-name">{fileData.name}</span>
|
||||
<span class="file-name scrollbar-none">{fileData.name}</span>
|
||||
<span class="file-size">{formatSize(fileData.size)}</span>
|
||||
</div>
|
||||
<div class="toolbar-right">
|
||||
@@ -880,6 +880,7 @@
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 8px;
|
||||
height: 30px;
|
||||
padding: 0 10px;
|
||||
border-bottom: 1px solid var(--color-gray-200);
|
||||
@@ -893,26 +894,42 @@
|
||||
.toolbar-left {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
flex: 1 1 auto;
|
||||
gap: 8px;
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.toolbar-right {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
flex: 0 0 auto;
|
||||
gap: 2px;
|
||||
}
|
||||
|
||||
.file-name {
|
||||
display: block;
|
||||
flex: 1 1 auto;
|
||||
min-width: 0;
|
||||
overflow-x: auto;
|
||||
overflow-y: hidden;
|
||||
white-space: nowrap;
|
||||
font-size: 12px;
|
||||
font-weight: 500;
|
||||
color: var(--color-gray-700);
|
||||
}
|
||||
|
||||
.file-name::-webkit-scrollbar {
|
||||
display: none;
|
||||
}
|
||||
|
||||
:global(.dark) .file-name {
|
||||
color: var(--color-gray-300);
|
||||
}
|
||||
|
||||
.file-size {
|
||||
flex: 0 0 auto;
|
||||
white-space: nowrap;
|
||||
font-size: 11px;
|
||||
color: var(--color-gray-400);
|
||||
}
|
||||
@@ -921,6 +938,7 @@
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
flex: 0 0 auto;
|
||||
width: 20px;
|
||||
height: 20px;
|
||||
border-radius: 4px;
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
unstageFiles,
|
||||
discardChanges,
|
||||
gitCommit,
|
||||
gitFetch,
|
||||
gitPull,
|
||||
gitPush,
|
||||
gitUncommit,
|
||||
@@ -55,15 +56,17 @@
|
||||
const allStaged = $derived(totalChanges > 0 && unstagedFiles.length === 0);
|
||||
const someStaged = $derived(stagedFiles.length > 0 && unstagedFiles.length > 0);
|
||||
|
||||
let gitStatus = $derived(gitStatusStore.status as {
|
||||
is_repo: boolean;
|
||||
branch: string;
|
||||
upstream: string;
|
||||
remote_url: string;
|
||||
ahead: number;
|
||||
behind: number;
|
||||
files: GitFile[];
|
||||
} | null);
|
||||
let gitStatus = $derived(
|
||||
gitStatusStore.status as {
|
||||
is_repo: boolean;
|
||||
branch: string;
|
||||
upstream: string;
|
||||
remote_url: string;
|
||||
ahead: number;
|
||||
behind: number;
|
||||
files: GitFile[];
|
||||
} | null
|
||||
);
|
||||
|
||||
// Branch has never been pushed to remote
|
||||
const needsPublish = $derived(!gitStatus?.upstream);
|
||||
@@ -85,7 +88,11 @@
|
||||
if (remoteWebUrl.includes('github.com')) return 'GitHub';
|
||||
if (remoteWebUrl.includes('gitlab.com') || remoteWebUrl.includes('gitlab')) return 'GitLab';
|
||||
if (remoteWebUrl.includes('bitbucket')) return 'Bitbucket';
|
||||
try { return new URL(remoteWebUrl).hostname; } catch { return 'Remote'; }
|
||||
try {
|
||||
return new URL(remoteWebUrl).hostname;
|
||||
} catch {
|
||||
return 'Remote';
|
||||
}
|
||||
});
|
||||
|
||||
// Clear stale selection when file is no longer in the changed list
|
||||
@@ -114,8 +121,8 @@
|
||||
}
|
||||
});
|
||||
|
||||
async function refresh() {
|
||||
await gitStatusStore.refresh();
|
||||
async function refresh({ force = false }: { force?: boolean } = {}) {
|
||||
await gitStatusStore.refresh({ force });
|
||||
}
|
||||
|
||||
async function selectFile(path: string, staged: boolean, untracked: boolean = false) {
|
||||
@@ -236,7 +243,22 @@
|
||||
const d = await gitPull(workspacePath);
|
||||
flash(d.ok ? $t('git.pulled') : d.message);
|
||||
loading = false;
|
||||
await refresh();
|
||||
await refresh({ force: true });
|
||||
}
|
||||
|
||||
async function doFetch() {
|
||||
loading = true;
|
||||
try {
|
||||
const d = (await gitFetch(workspacePath)) as { ok?: boolean; message?: string };
|
||||
flash(d.ok ? d.message || $t('git.fetch') : d.message || 'Fetch failed');
|
||||
} catch (e) {
|
||||
flash(e instanceof Error ? e.message : 'Fetch failed');
|
||||
} finally {
|
||||
loading = false;
|
||||
await refresh({ force: true });
|
||||
if (showBranches) await loadBranches();
|
||||
if (view === 'history') await loadHistory();
|
||||
}
|
||||
}
|
||||
|
||||
async function doPush() {
|
||||
@@ -247,7 +269,7 @@
|
||||
});
|
||||
flash(d.ok ? $t('git.pushed') : d.message);
|
||||
loading = false;
|
||||
await refresh();
|
||||
await refresh({ force: true });
|
||||
}
|
||||
|
||||
async function switchBranch(branch: string) {
|
||||
@@ -353,7 +375,7 @@
|
||||
}
|
||||
|
||||
const syncAction = $derived.by(() => {
|
||||
if (!gitStatus) return { label: $t('git.fetch'), icon: 'refresh', action: doPull };
|
||||
if (!gitStatus) return { label: $t('git.fetch'), icon: 'refresh', action: doFetch };
|
||||
if (gitStatus.behind > 0)
|
||||
return {
|
||||
label: $t('git.pullCount', { count: gitStatus.behind }),
|
||||
@@ -366,9 +388,8 @@
|
||||
icon: 'upload',
|
||||
action: doPush
|
||||
};
|
||||
if (!gitStatus.upstream)
|
||||
return { label: $t('git.publish'), icon: 'upload', action: doPush };
|
||||
return { label: $t('git.fetch'), icon: 'refresh', action: doPull };
|
||||
if (!gitStatus.upstream) return { label: $t('git.publish'), icon: 'upload', action: doPush };
|
||||
return { label: $t('git.fetch'), icon: 'refresh', action: doFetch };
|
||||
});
|
||||
|
||||
function onResizeStart(e: PointerEvent) {
|
||||
@@ -444,8 +465,6 @@
|
||||
});
|
||||
</script>
|
||||
|
||||
|
||||
|
||||
{#if gitStatus?.is_repo}
|
||||
<div
|
||||
class="shrink-0 border-t border-gray-200 dark:border-white/6 relative"
|
||||
@@ -785,8 +804,14 @@
|
||||
<div class="flex-1 overflow-y-auto">
|
||||
{#each commits as c, i}
|
||||
{#if i === unpushedCount && unpushedCount > 0}
|
||||
<div class="flex items-center gap-2 px-2.5 py-1 border-b border-gray-100 dark:border-white/4 bg-gray-50/50 dark:bg-white/2">
|
||||
<Icon name="upload" size={10} class="text-gray-400 dark:text-gray-600 shrink-0" />
|
||||
<div
|
||||
class="flex items-center gap-2 px-2.5 py-1 border-b border-gray-100 dark:border-white/4 bg-gray-50/50 dark:bg-white/2"
|
||||
>
|
||||
<Icon
|
||||
name="upload"
|
||||
size={10}
|
||||
class="text-gray-400 dark:text-gray-600 shrink-0"
|
||||
/>
|
||||
<span class="text-[10px] text-gray-400 dark:text-gray-600">
|
||||
{unpushedCount} unpushed {unpushedCount === 1 ? 'commit' : 'commits'}
|
||||
</span>
|
||||
@@ -800,7 +825,10 @@
|
||||
onclick={() => selectCommit(c)}
|
||||
>
|
||||
{#if i < unpushedCount}
|
||||
<span class="w-1.5 h-1.5 rounded-full bg-blue-500 dark:bg-blue-400 shrink-0" title="Unpushed"></span>
|
||||
<span
|
||||
class="w-1.5 h-1.5 rounded-full bg-blue-500 dark:bg-blue-400 shrink-0"
|
||||
title="Unpushed"
|
||||
></span>
|
||||
{/if}
|
||||
<div class="flex flex-col min-w-0 flex-1">
|
||||
<span class="text-xs text-gray-800 dark:text-gray-200 truncate w-full"
|
||||
|
||||
@@ -8,7 +8,6 @@
|
||||
import Icon from './Icon.svelte';
|
||||
import Spinner from '$lib/components/common/Spinner.svelte';
|
||||
|
||||
|
||||
type DiffLine = { type: 'added' | 'removed' | 'context'; content: string };
|
||||
type DiffHunk = { header: string; lines: DiffLine[] };
|
||||
type DiffFile = { path: string; hunks: DiffHunk[] };
|
||||
@@ -114,7 +113,7 @@
|
||||
}
|
||||
|
||||
async function refreshReview(initial = false) {
|
||||
await gitStatusStore.refresh();
|
||||
await gitStatusStore.refresh({ force: true });
|
||||
}
|
||||
|
||||
function fileKey(file: GitFile): string {
|
||||
|
||||
@@ -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}
|
||||
|
||||
@@ -545,6 +545,7 @@
|
||||
flex-direction: column;
|
||||
background: white;
|
||||
border-right: 1px solid var(--color-gray-200);
|
||||
padding-top: env(safe-area-inset-top, 0px);
|
||||
}
|
||||
|
||||
:global(.dark) .sidebar {
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -1,11 +1,14 @@
|
||||
<script lang="ts">
|
||||
import { tick } from 'svelte';
|
||||
import { slide } from 'svelte/transition';
|
||||
import { quintOut } from 'svelte/easing';
|
||||
import { get } from 'svelte/store';
|
||||
import MarkdownRenderer from '$lib/components/markdown/MarkdownRenderer.svelte';
|
||||
import OutputEditView from './OutputEditView.svelte';
|
||||
import ConsecutiveActivityGroup from './ConsecutiveActivityGroup.svelte';
|
||||
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 {
|
||||
@@ -17,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,
|
||||
@@ -31,10 +36,12 @@
|
||||
messageId,
|
||||
siblingIndex = 0,
|
||||
siblingTotal = 1,
|
||||
speaking = false,
|
||||
onapprove,
|
||||
onnavigate,
|
||||
onregenerate,
|
||||
onedit
|
||||
onedit,
|
||||
onspeak
|
||||
}: Props = $props();
|
||||
|
||||
let edit = $state(false);
|
||||
@@ -44,25 +51,6 @@
|
||||
let showUsageTooltip = $state(false);
|
||||
let textareaEl: HTMLTextAreaElement;
|
||||
|
||||
// Track which tool call outputs are expanded
|
||||
let expandedCalls = $state<Set<string>>(new Set());
|
||||
// Track which groups are expanded
|
||||
let expandedGroups = $state<Set<number>>(new Set());
|
||||
|
||||
function toggleCallExpanded(callId: string) {
|
||||
const next = new Set(expandedCalls);
|
||||
if (next.has(callId)) next.delete(callId);
|
||||
else next.add(callId);
|
||||
expandedCalls = next;
|
||||
}
|
||||
|
||||
function toggleGroupExpanded(groupIdx: number) {
|
||||
const next = new Set(expandedGroups);
|
||||
if (next.has(groupIdx)) next.delete(groupIdx);
|
||||
else next.add(groupIdx);
|
||||
expandedGroups = next;
|
||||
}
|
||||
|
||||
async function startEdit() {
|
||||
edit = true;
|
||||
if (output?.length) {
|
||||
@@ -144,7 +132,11 @@
|
||||
switch (name) {
|
||||
case 'read_file': {
|
||||
const p = shortPath(args.path);
|
||||
if (args.start_line) return _t('chat.tool.readFileRange', { path: p, range: `${args.start_line}–${args.end_line || 'end'}` });
|
||||
if (args.start_line)
|
||||
return _t('chat.tool.readFileRange', {
|
||||
path: p,
|
||||
range: `${args.start_line}–${args.end_line || 'end'}`
|
||||
});
|
||||
return _t('chat.tool.readFile', { path: p });
|
||||
}
|
||||
case 'edit_file':
|
||||
@@ -160,11 +152,15 @@
|
||||
? _t('chat.tool.listDirectoryRecursive', { path: shortPath(args.path) })
|
||||
: _t('chat.tool.listDirectory', { path: shortPath(args.path) });
|
||||
case 'search_files': {
|
||||
const scope = args.include ? _t('chat.tool.searchFilesScope', { include: args.include }) : '';
|
||||
const scope = args.include
|
||||
? _t('chat.tool.searchFilesScope', { include: args.include })
|
||||
: '';
|
||||
return _t('chat.tool.searchFiles', { query: args.query || '?', scope });
|
||||
}
|
||||
case 'run_command':
|
||||
return args.background ? _t('chat.tool.backgroundCommand', { command: args.command || '?' }) : args.command || '?';
|
||||
return args.background
|
||||
? _t('chat.tool.backgroundCommand', { command: args.command || '?' })
|
||||
: args.command || '?';
|
||||
case 'check_task':
|
||||
return _t('chat.tool.checkTask', { id: args.task_id || '?' });
|
||||
case 'kill_task':
|
||||
@@ -196,11 +192,13 @@
|
||||
}
|
||||
|
||||
// ── Consecutive grouping logic ────────────────────────────────
|
||||
// Groups consecutive function_call items together, breaking on message items.
|
||||
// Groups consecutive assistant activity (reasoning + tool calls), breaking on message items.
|
||||
|
||||
interface ToolGroup {
|
||||
type: 'tool_group';
|
||||
interface ActivityGroup {
|
||||
type: 'activity_group';
|
||||
entries: any[]; // ordered reasoning/function_call items
|
||||
calls: any[]; // function_call items
|
||||
reasoning: any[];
|
||||
outputs: Map<string, any>; // call_id → function_call_output
|
||||
}
|
||||
|
||||
@@ -214,11 +212,12 @@
|
||||
item: any;
|
||||
}
|
||||
|
||||
type DisplayItem = ToolGroup | MessageItem | ArtifactItem;
|
||||
type DisplayItem = ActivityGroup | MessageItem | ArtifactItem;
|
||||
|
||||
const outputText = $derived.by((): string => {
|
||||
return (output || [])
|
||||
.filter((i: any) => i.type === 'message')
|
||||
.filter((i: any) => messageItemText(i).trim())
|
||||
.flatMap((i: any) => i.content || [])
|
||||
.map((c: any) => c.text || '')
|
||||
.join('');
|
||||
@@ -230,11 +229,15 @@
|
||||
return content.startsWith(outputText) ? content.slice(outputText.length) : '';
|
||||
});
|
||||
|
||||
function messageItemText(item: any): string {
|
||||
return (item.content || []).map((c: any) => c.text || '').join('');
|
||||
}
|
||||
|
||||
const displayItems = $derived.by((): DisplayItem[] => {
|
||||
if (!output?.length) return [];
|
||||
|
||||
const items: DisplayItem[] = [];
|
||||
let currentGroup: ToolGroup | null = null;
|
||||
let currentGroup: ActivityGroup | null = null;
|
||||
|
||||
// Collect all function_call_output items for lookup
|
||||
const outputMap = new Map<string, any>();
|
||||
@@ -244,8 +247,20 @@
|
||||
}
|
||||
}
|
||||
|
||||
const ensureGroup = () => {
|
||||
if (!currentGroup) {
|
||||
currentGroup = {
|
||||
type: 'activity_group',
|
||||
entries: [],
|
||||
calls: [],
|
||||
reasoning: [],
|
||||
outputs: outputMap
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
const flushGroup = () => {
|
||||
if (currentGroup && currentGroup.calls.length > 0) {
|
||||
if (currentGroup && (currentGroup.calls.length > 0 || currentGroup.reasoning.length > 0)) {
|
||||
items.push(currentGroup);
|
||||
currentGroup = null;
|
||||
}
|
||||
@@ -253,13 +268,20 @@
|
||||
|
||||
for (const item of output) {
|
||||
if (item.type === 'function_call') {
|
||||
if (!currentGroup) {
|
||||
currentGroup = { type: 'tool_group', calls: [], outputs: outputMap };
|
||||
}
|
||||
currentGroup.calls.push(item);
|
||||
ensureGroup();
|
||||
currentGroup!.entries.push(item);
|
||||
currentGroup!.calls.push(item);
|
||||
} else if (item.type === 'reasoning') {
|
||||
ensureGroup();
|
||||
currentGroup!.entries.push(item);
|
||||
currentGroup!.reasoning.push(item);
|
||||
} else if (item.type === 'message') {
|
||||
flushGroup();
|
||||
items.push({ type: 'message_item', item });
|
||||
// Some providers emit empty message shells between reasoning/tool items.
|
||||
// Only visible assistant text should break a consecutive activity run.
|
||||
if (messageItemText(item).trim()) {
|
||||
flushGroup();
|
||||
items.push({ type: 'message_item', item });
|
||||
}
|
||||
} else if (item.type === 'artifact') {
|
||||
flushGroup();
|
||||
items.push({ type: 'artifact_item', item });
|
||||
@@ -271,35 +293,6 @@
|
||||
return items;
|
||||
});
|
||||
|
||||
/** Summary text for a tool group header */
|
||||
function groupSummaryText(calls: any[]): string {
|
||||
if (calls.length <= 3) {
|
||||
// Show individual human-readable labels for small groups
|
||||
return calls.map((c: any) => toolLabel(c.name || 'tool', c.arguments || {})).join(', ');
|
||||
}
|
||||
// For larger groups, show counts by tool type
|
||||
const nameCounts: Record<string, number> = {};
|
||||
for (const c of calls) {
|
||||
const name = c.name || 'tool';
|
||||
nameCounts[name] = (nameCounts[name] || 0) + 1;
|
||||
}
|
||||
return Object.entries(nameCounts)
|
||||
.map(([name, count]) => (count > 1 ? `${count} ${name}` : name))
|
||||
.join(', ');
|
||||
}
|
||||
|
||||
function groupHasPending(calls: any[]): boolean {
|
||||
return !done && calls.some((c: any) => c.status !== 'completed' && c.status !== 'rejected');
|
||||
}
|
||||
|
||||
function groupAllDone(calls: any[]): boolean {
|
||||
return calls.every((c: any) => c.status === 'completed');
|
||||
}
|
||||
|
||||
function groupHasRejected(calls: any[]): boolean {
|
||||
return calls.some((c: any) => c.status === 'rejected');
|
||||
}
|
||||
|
||||
/** Format usage data for tooltip display */
|
||||
function formatUsageLabel(key: string): string {
|
||||
return key.replace(/_/g, ' ').replace(/\b\w/g, (l) => l.toUpperCase());
|
||||
@@ -378,12 +371,9 @@
|
||||
/>
|
||||
{:else if displayItem.type === 'artifact_item'}
|
||||
{@const artifact = displayItem.item}
|
||||
{@const preview = (artifact.content || '')
|
||||
.replace(/^#.*\n*/m, '')
|
||||
.trim()
|
||||
.slice(0, 200)}
|
||||
{@const preview = (artifact.content || '').replace(/^#.*\n*/m, '').trim()}
|
||||
<button
|
||||
class="w-full text-left my-2 rounded-xl cursor-pointer
|
||||
class="w-full min-w-0 overflow-hidden text-left my-2 rounded-xl cursor-pointer
|
||||
border border-gray-200 dark:border-white/8
|
||||
hover:border-gray-300 dark:hover:border-white/12
|
||||
hover:bg-gray-50/50 dark:hover:bg-white/[0.03]
|
||||
@@ -396,471 +386,51 @@
|
||||
}
|
||||
}}
|
||||
>
|
||||
<div class="flex items-center gap-2 px-3 pt-2.5 pb-0.5">
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
fill="none"
|
||||
viewBox="0 0 24 24"
|
||||
stroke-width="1.5"
|
||||
stroke="currentColor"
|
||||
class="size-3.5 shrink-0 text-gray-400 dark:text-gray-500"
|
||||
>
|
||||
<path
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
d="M19.5 14.25v-2.625a3.375 3.375 0 0 0-3.375-3.375h-1.5A1.125 1.125 0 0 1 13.5 7.125v-1.5a3.375 3.375 0 0 0-3.375-3.375H8.25m2.25 0H5.625c-.621 0-1.125.504-1.125 1.125v17.25c0 .621.504 1.125 1.125 1.125h12.75c.621 0 1.125-.504 1.125-1.125V11.25a9 9 0 0 0-9-9Z"
|
||||
/>
|
||||
</svg>
|
||||
<span class="text-xs font-medium text-gray-800 dark:text-gray-100"
|
||||
>{artifact.title || $t('chat.artifact')}</span
|
||||
>
|
||||
</div>
|
||||
{#if preview}
|
||||
<p
|
||||
class="px-3 pb-2.5 text-[10px] text-gray-400 dark:text-gray-500 line-clamp-2 leading-relaxed"
|
||||
>
|
||||
{preview}{preview.length >= 200 ? '...' : ''}
|
||||
</p>
|
||||
{/if}
|
||||
</button>
|
||||
{:else if displayItem.type === 'tool_group'}
|
||||
{@const calls = displayItem.calls}
|
||||
{@const outputs = displayItem.outputs}
|
||||
{@const hasPending = groupHasPending(calls)}
|
||||
{@const allDone = groupAllDone(calls)}
|
||||
{@const hasRejected = groupHasRejected(calls)}
|
||||
{@const isGroupOpen = expandedGroups.has(groupIdx)}
|
||||
{@const hasPendingApproval = calls.some((c: any) => c.status === 'pending')}
|
||||
|
||||
<div class="w-full min-w-0 flex flex-col my-0.5">
|
||||
<!-- Group header -->
|
||||
<button
|
||||
class="w-full min-w-0 text-left text-gray-500 hover:text-gray-700 dark:hover:text-gray-300 transition cursor-pointer"
|
||||
aria-label={$t('chat.toggleToolCalls')}
|
||||
aria-expanded={isGroupOpen}
|
||||
onclick={() => toggleGroupExpanded(groupIdx)}
|
||||
>
|
||||
<div class="min-w-0 px-3 py-2.5">
|
||||
<div
|
||||
class="flex items-center gap-1.5 text-sm min-w-0 {hasPending ? 'shimmer' : ''}"
|
||||
class="line-clamp-1 max-h-4 text-xs leading-4 font-medium text-gray-800 dark:text-gray-100 [overflow-wrap:anywhere]"
|
||||
>
|
||||
<!-- Status icon -->
|
||||
{#if hasPending}
|
||||
<div class="flex justify-center text-center">
|
||||
<svg
|
||||
aria-hidden="true"
|
||||
class="size-4"
|
||||
viewBox="0 0 24 24"
|
||||
fill="currentColor"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
>
|
||||
<style>
|
||||
.spinner_tc {
|
||||
transform-origin: center;
|
||||
animation: spinner_tc_a 0.75s infinite linear;
|
||||
}
|
||||
@keyframes spinner_tc_a {
|
||||
100% {
|
||||
transform: rotate(360deg);
|
||||
}
|
||||
}
|
||||
</style>
|
||||
<path
|
||||
d="M12,1A11,11,0,1,0,23,12,11,11,0,0,0,12,1Zm0,19a8,8,0,1,1,8-8A8,8,0,0,1,12,20Z"
|
||||
opacity=".25"
|
||||
/>
|
||||
<path
|
||||
d="M10.14,1.16a11,11,0,0,0-9,8.92A1.59,1.59,0,0,0,2.46,12,1.52,1.52,0,0,0,4.11,10.7a8,8,0,0,1,6.66-6.61A1.42,1.42,0,0,0,12,2.69h0A1.57,1.57,0,0,0,10.14,1.16Z"
|
||||
class="spinner_tc"
|
||||
/>
|
||||
</svg>
|
||||
</div>
|
||||
{:else if allDone}
|
||||
<div class="text-emerald-500 dark:text-emerald-400">
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
fill="none"
|
||||
viewBox="0 0 24 24"
|
||||
stroke-width="2"
|
||||
stroke="currentColor"
|
||||
class="size-4"
|
||||
>
|
||||
<path
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
d="M9 12.75 11.25 15 15 9.75M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0Z"
|
||||
/>
|
||||
</svg>
|
||||
</div>
|
||||
{:else if hasRejected}
|
||||
<div class="text-red-400 dark:text-red-500">
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
fill="none"
|
||||
viewBox="0 0 24 24"
|
||||
stroke-width="2.5"
|
||||
stroke="currentColor"
|
||||
class="size-4"
|
||||
>
|
||||
<path
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
d="M6 18L18 6M6 6l12 12"
|
||||
/>
|
||||
</svg>
|
||||
</div>
|
||||
{:else}
|
||||
<div class="text-gray-400 dark:text-gray-500">
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
fill="none"
|
||||
viewBox="0 0 24 24"
|
||||
stroke-width="1.75"
|
||||
stroke="currentColor"
|
||||
class="size-3.5"
|
||||
>
|
||||
<path
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
d="M21.75 6.75a4.5 4.5 0 0 1-4.884 4.484c-1.076-.091-2.264.071-2.95.904l-7.152 8.684a2.548 2.548 0 1 1-3.586-3.586l8.684-7.152c.833-.686.995-1.874.904-2.95a4.5 4.5 0 0 1 6.336-4.486l-3.276 3.276a3.004 3.004 0 0 0 2.25 2.25l3.276-3.276c.256.565.398 1.192.398 1.852Z"
|
||||
/>
|
||||
</svg>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<!-- Summary text -->
|
||||
<div class="flex-1 min-w-0 line-clamp-1">
|
||||
<span class="text-gray-600 dark:text-gray-300"
|
||||
>{hasPending ? $t('chat.exploring') : $t('chat.explored')}</span
|
||||
>
|
||||
{#if groupSummaryText(calls)}
|
||||
<span class="text-gray-400 dark:text-gray-500 ml-1"
|
||||
>{groupSummaryText(calls)}</span
|
||||
>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<!-- Chevron -->
|
||||
<div class="flex shrink-0 self-center text-gray-400 dark:text-gray-500">
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
fill="none"
|
||||
viewBox="0 0 24 24"
|
||||
stroke-width="3.5"
|
||||
stroke="currentColor"
|
||||
class="size-3 transition-transform duration-200 {isGroupOpen
|
||||
? 'rotate-180'
|
||||
: ''}"
|
||||
>
|
||||
<path
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
d="m19.5 8.25-7.5 7.5-7.5-7.5"
|
||||
/>
|
||||
</svg>
|
||||
</div>
|
||||
{artifact.title || $t('chat.artifact')}
|
||||
</div>
|
||||
</button>
|
||||
|
||||
<!-- Expanded group content -->
|
||||
{#if isGroupOpen}
|
||||
<div transition:slide={{ duration: 300, easing: quintOut, axis: 'y' }}>
|
||||
<div class="mb-0.5 space-y-0.5 mt-1">
|
||||
{#each calls as item}
|
||||
{@const args = item.arguments || {}}
|
||||
{@const toolName = item.name}
|
||||
{@const callId = item.call_id || toolName}
|
||||
{@const isExecuting = item.status === 'running' || item.status === 'in_progress' || (!item.status && !done)}
|
||||
{@const isDone = item.status === 'completed'}
|
||||
{@const isRejected = item.status === 'rejected'}
|
||||
{@const isPending = item.status === 'pending'}
|
||||
{@const isExpanded = expandedCalls.has(callId)}
|
||||
{@const pairedOutput = outputs.get(item.call_id)}
|
||||
|
||||
<div class="w-full min-w-0 flex flex-col">
|
||||
<!-- Individual tool call row -->
|
||||
<button
|
||||
class="w-full min-w-0 text-left text-gray-500 hover:text-gray-700 dark:hover:text-gray-300 transition cursor-pointer"
|
||||
onclick={() => toggleCallExpanded(callId)}
|
||||
>
|
||||
<div
|
||||
class="flex items-center gap-1.5 text-sm min-w-0 {isExecuting
|
||||
? 'shimmer'
|
||||
: ''}"
|
||||
>
|
||||
<!-- Status icon -->
|
||||
{#if isExecuting}
|
||||
<div class="flex justify-center text-center">
|
||||
<svg
|
||||
aria-hidden="true"
|
||||
class="size-4"
|
||||
viewBox="0 0 24 24"
|
||||
fill="currentColor"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
>
|
||||
<style>
|
||||
.spinner_inner {
|
||||
transform-origin: center;
|
||||
animation: spinner_inner_a 0.75s infinite linear;
|
||||
}
|
||||
@keyframes spinner_inner_a {
|
||||
100% {
|
||||
transform: rotate(360deg);
|
||||
}
|
||||
}
|
||||
</style>
|
||||
<path
|
||||
d="M12,1A11,11,0,1,0,23,12,11,11,0,0,0,12,1Zm0,19a8,8,0,1,1,8-8A8,8,0,0,1,12,20Z"
|
||||
opacity=".25"
|
||||
/>
|
||||
<path
|
||||
d="M10.14,1.16a11,11,0,0,0-9,8.92A1.59,1.59,0,0,0,2.46,12,1.52,1.52,0,0,0,4.11,10.7a8,8,0,0,1,6.66-6.61A1.42,1.42,0,0,0,12,2.69h0A1.57,1.57,0,0,0,10.14,1.16Z"
|
||||
class="spinner_inner"
|
||||
/>
|
||||
</svg>
|
||||
</div>
|
||||
{:else if isDone}
|
||||
<div class="text-emerald-500 dark:text-emerald-400">
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
fill="none"
|
||||
viewBox="0 0 24 24"
|
||||
stroke-width="2"
|
||||
stroke="currentColor"
|
||||
class="size-4"
|
||||
>
|
||||
<path
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
d="M9 12.75 11.25 15 15 9.75M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0Z"
|
||||
/>
|
||||
</svg>
|
||||
</div>
|
||||
{:else if isRejected}
|
||||
<div class="text-red-400 dark:text-red-500">
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
fill="none"
|
||||
viewBox="0 0 24 24"
|
||||
stroke-width="2.5"
|
||||
stroke="currentColor"
|
||||
class="size-4"
|
||||
>
|
||||
<path
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
d="M6 18L18 6M6 6l12 12"
|
||||
/>
|
||||
</svg>
|
||||
</div>
|
||||
{:else}
|
||||
<div class="text-gray-400 dark:text-gray-500">
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
fill="none"
|
||||
viewBox="0 0 24 24"
|
||||
stroke-width="1.75"
|
||||
stroke="currentColor"
|
||||
class="size-3.5"
|
||||
>
|
||||
<path
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
d="M21.75 6.75a4.5 4.5 0 0 1-4.884 4.484c-1.076-.091-2.264.071-2.95.904l-7.152 8.684a2.548 2.548 0 1 1-3.586-3.586l8.684-7.152c.833-.686.995-1.874.904-2.95a4.5 4.5 0 0 1 6.336-4.486l-3.276 3.276a3.004 3.004 0 0 0 2.25 2.25l3.276-3.276c.256.565.398 1.192.398 1.852Z"
|
||||
/>
|
||||
</svg>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<!-- Label -->
|
||||
<div class="flex-1 min-w-0 line-clamp-1">
|
||||
<span class="font-normal">{toolLabel(toolName, args)}</span>
|
||||
</div>
|
||||
|
||||
<!-- Right side: approval buttons or chevron -->
|
||||
{#if isPending && chatId}
|
||||
<!-- Approval buttons -->
|
||||
<span
|
||||
class="flex gap-1 shrink-0"
|
||||
onclick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<button
|
||||
class="text-[11px] px-2.5 py-0.5 rounded-md
|
||||
text-gray-600 dark:text-gray-300
|
||||
bg-gray-100 dark:bg-white/8
|
||||
hover:bg-gray-200 dark:hover:bg-white/12
|
||||
transition-colors duration-100"
|
||||
onclick={() => onapprove(messageId, item.call_id, true)}
|
||||
>{$t('chat.allow')}</button
|
||||
>
|
||||
<button
|
||||
class="text-[11px] px-2 py-0.5 rounded-md
|
||||
text-gray-400 dark:text-gray-500
|
||||
hover:text-gray-600 dark:hover:text-gray-300
|
||||
transition-colors duration-100"
|
||||
onclick={() => onapprove(messageId, item.call_id, false)}
|
||||
>{$t('chat.deny')}</button
|
||||
>
|
||||
</span>
|
||||
{:else}
|
||||
<!-- Chevron -->
|
||||
<div class="flex shrink-0 self-center translate-y-[1px]">
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
fill="none"
|
||||
viewBox="0 0 24 24"
|
||||
stroke-width="3.5"
|
||||
stroke="currentColor"
|
||||
class="size-3 transition-transform duration-200 text-gray-400 dark:text-gray-500 {isExpanded
|
||||
? 'rotate-180'
|
||||
: ''}"
|
||||
>
|
||||
<path
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
d="m19.5 8.25-7.5 7.5-7.5-7.5"
|
||||
/>
|
||||
</svg>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
</button>
|
||||
|
||||
<!-- Expanded detail panel -->
|
||||
{#if isExpanded}
|
||||
<div transition:slide={{ duration: 300, easing: quintOut, axis: 'y' }}>
|
||||
<div
|
||||
class="border border-gray-50 dark:border-gray-850/30 rounded-2xl my-1.5 p-3 space-y-3 overflow-hidden"
|
||||
>
|
||||
<!-- Input section -->
|
||||
{#if Object.keys(args).length > 0}
|
||||
<div>
|
||||
<div
|
||||
class="text-[10px] uppercase tracking-wider text-gray-400 dark:text-gray-500 mb-1.5 px-1"
|
||||
>
|
||||
{$t('chat.toolInput')}
|
||||
</div>
|
||||
{#if toolName === 'edit_file' && args.target}
|
||||
<!-- Diff view for edits -->
|
||||
<div
|
||||
class="text-[11px] font-mono rounded-lg overflow-hidden border border-gray-200/60 dark:border-white/6"
|
||||
>
|
||||
<div
|
||||
class="bg-red-50/80 dark:bg-red-950/20 text-red-700 dark:text-red-400 px-2.5 py-1 whitespace-pre-wrap break-all leading-relaxed"
|
||||
>
|
||||
<span
|
||||
class="select-none text-red-400 dark:text-red-600 mr-1"
|
||||
>−</span
|
||||
>{args.target.length > 500
|
||||
? args.target.slice(0, 500) + '…'
|
||||
: args.target}
|
||||
</div>
|
||||
<div
|
||||
class="bg-green-50/80 dark:bg-green-950/20 text-green-700 dark:text-green-400 px-2.5 py-1 whitespace-pre-wrap break-all leading-relaxed"
|
||||
>
|
||||
<span
|
||||
class="select-none text-green-400 dark:text-green-600 mr-1"
|
||||
>+</span
|
||||
>{(args.replacement || '').length > 500
|
||||
? args.replacement.slice(0, 500) + '…'
|
||||
: args.replacement || ''}
|
||||
</div>
|
||||
</div>
|
||||
{#if args.start_line}
|
||||
<div
|
||||
class="text-[10px] text-gray-400 dark:text-gray-600 mt-1 px-1"
|
||||
>
|
||||
{$t('chat.toolLines', { start: args.start_line, end: args.end_line || 'end' })}
|
||||
</div>
|
||||
{/if}
|
||||
{:else if toolName === 'run_command'}
|
||||
<code
|
||||
class="block text-xs font-mono text-gray-600 dark:text-gray-300 bg-gray-50 dark:bg-gray-900 rounded-lg px-2.5 py-1.5 overflow-x-auto break-all whitespace-pre-wrap"
|
||||
>{args.command}</code
|
||||
>
|
||||
{:else}
|
||||
<!-- Key-value pairs -->
|
||||
<div class="px-1 space-y-0.5">
|
||||
{#each Object.entries(args) as [key, value]}
|
||||
<div class="flex gap-2 text-xs py-0.5">
|
||||
<span class="text-gray-600 dark:text-gray-400 shrink-0"
|
||||
>{key}</span
|
||||
>
|
||||
<span class="text-gray-800 dark:text-gray-200 break-all">
|
||||
{typeof value === 'object'
|
||||
? JSON.stringify(value)
|
||||
: value}
|
||||
</span>
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<!-- Output section -->
|
||||
{#if pairedOutput?.output}
|
||||
<div>
|
||||
<div
|
||||
class="text-[10px] uppercase tracking-wider text-gray-400 dark:text-gray-500 mb-1.5 px-1"
|
||||
>
|
||||
{$t('chat.toolOutput')}
|
||||
</div>
|
||||
<div class="w-full min-w-0 overflow-hidden">
|
||||
<pre
|
||||
class="text-xs text-gray-600 dark:text-gray-300 whitespace-pre-wrap break-words font-mono max-h-64 overflow-auto leading-relaxed">{pairedOutput
|
||||
.output.length > 10000
|
||||
? pairedOutput.output.slice(0, 10000)
|
||||
: pairedOutput.output}</pre>
|
||||
{#if pairedOutput.output.length > 10000}
|
||||
<div
|
||||
class="text-[10px] text-gray-400 dark:text-gray-600 mt-1 px-1"
|
||||
>
|
||||
{$t('chat.totalChars', { count: pairedOutput.output.length.toLocaleString() })}
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
{/each}
|
||||
{#if preview}
|
||||
<div
|
||||
class="line-clamp-2 max-h-8 text-[10px] leading-4 font-normal text-gray-400 dark:text-gray-500 [overflow-wrap:anywhere]"
|
||||
>
|
||||
{preview}
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
</button>
|
||||
{:else if displayItem.type === 'activity_group'}
|
||||
{#if displayItem.entries.length === 1}
|
||||
{@const item = displayItem.entries[0]}
|
||||
{#if item.type === 'reasoning'}
|
||||
<ReasoningCollapsible {item} fallbackId={`reasoning-${groupIdx}-0`} />
|
||||
{:else}
|
||||
<ToolCallCollapsible
|
||||
{item}
|
||||
pairedOutput={displayItem.outputs.get(item.call_id)}
|
||||
{done}
|
||||
{chatId}
|
||||
{messageId}
|
||||
{toolLabel}
|
||||
{onapprove}
|
||||
/>
|
||||
{/if}
|
||||
|
||||
<!-- Show approval buttons outside group when collapsed & has pending -->
|
||||
{#if !isGroupOpen && hasPendingApproval && chatId}
|
||||
<div class="mt-1 space-y-0.5">
|
||||
{#each calls.filter((c: any) => c.status === 'pending') as item}
|
||||
<div class="flex items-center gap-2 py-1 px-1">
|
||||
<span
|
||||
class="text-xs text-gray-500 dark:text-gray-400 flex-1 min-w-0 line-clamp-1"
|
||||
>{toolLabel(item.name, item.arguments || {})}</span
|
||||
>
|
||||
<span class="flex gap-1 shrink-0">
|
||||
<button
|
||||
class="text-[11px] px-2.5 py-0.5 rounded-md
|
||||
text-gray-600 dark:text-gray-300
|
||||
bg-gray-100 dark:bg-white/8
|
||||
hover:bg-gray-200 dark:hover:bg-white/12
|
||||
transition-colors duration-100"
|
||||
onclick={() => onapprove(messageId, item.call_id, true)}>{$t('chat.allow')}</button
|
||||
>
|
||||
<button
|
||||
class="text-[11px] px-2 py-0.5 rounded-md
|
||||
text-gray-400 dark:text-gray-500
|
||||
hover:text-gray-600 dark:hover:text-gray-300
|
||||
transition-colors duration-100"
|
||||
onclick={() => onapprove(messageId, item.call_id, false)}>{$t('chat.deny')}</button
|
||||
>
|
||||
</span>
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
{:else}
|
||||
<ConsecutiveActivityGroup
|
||||
entries={displayItem.entries}
|
||||
calls={displayItem.calls}
|
||||
reasoning={displayItem.reasoning}
|
||||
outputs={displayItem.outputs}
|
||||
{done}
|
||||
{chatId}
|
||||
{messageId}
|
||||
{groupIdx}
|
||||
{toolLabel}
|
||||
{onapprove}
|
||||
/>
|
||||
{/if}
|
||||
{/if}
|
||||
{/each}
|
||||
{#if done && unrenderedContent && displayItems.length > 0}
|
||||
@@ -971,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';
|
||||
@@ -7,6 +7,7 @@
|
||||
import Placeholder from '@tiptap/extension-placeholder';
|
||||
import CodeBlockLowlight from '@tiptap/extension-code-block-lowlight';
|
||||
import { all, createLowlight } from 'lowlight';
|
||||
import { toast } from 'svelte-sonner';
|
||||
|
||||
import { createFileMention, extractMentionedFiles, type FileMentionAttrs } from './FileMention';
|
||||
import { createSkillMention, extractMentionedSkills, type SkillMentionAttrs } from './SkillMention';
|
||||
@@ -22,6 +23,13 @@
|
||||
import QueuedMessageItem from './QueuedMessageItem.svelte';
|
||||
import Icon from '../Icon.svelte';
|
||||
import { planMode } from '$lib/stores';
|
||||
import {
|
||||
sttConfigured,
|
||||
ttsConfigured,
|
||||
ttsEnabled,
|
||||
voiceModeEnabled,
|
||||
voiceModeSttMode
|
||||
} from '$lib/stores/audio';
|
||||
import Spinner from '$lib/components/common/Spinner.svelte';
|
||||
import { t } from '$lib/i18n';
|
||||
|
||||
@@ -56,6 +64,27 @@
|
||||
|
||||
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);
|
||||
let voiceCaptureRecorder: MediaRecorder | null = null;
|
||||
let voiceCaptureStream: MediaStream | null = null;
|
||||
let voiceCaptureChunks: Blob[] = [];
|
||||
let voiceCaptureMimeType = 'audio/webm';
|
||||
const voiceModeAvailable = $derived(
|
||||
$ttsEnabled && $ttsConfigured && ($voiceModeSttMode === 'browser' || $sttConfigured)
|
||||
);
|
||||
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 +514,8 @@
|
||||
});
|
||||
|
||||
onDestroy(() => {
|
||||
stopVoiceRecognition();
|
||||
if (voiceRestartTimer) clearTimeout(voiceRestartTimer);
|
||||
destroyPopup();
|
||||
destroySkillPopup();
|
||||
editor?.destroy();
|
||||
@@ -525,8 +556,290 @@
|
||||
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(stopCapture = true) {
|
||||
clearVoiceRestartTimer();
|
||||
const recognition = voiceRecognition;
|
||||
voiceRecognition = null;
|
||||
voiceStopRequested = true;
|
||||
if (stopCapture) stopVoiceCapture();
|
||||
try {
|
||||
recognition?.stop();
|
||||
} catch {}
|
||||
voiceListening = false;
|
||||
}
|
||||
|
||||
function chooseVoiceCaptureMimeType() {
|
||||
if (typeof MediaRecorder === 'undefined') return 'audio/webm';
|
||||
if (MediaRecorder.isTypeSupported?.('audio/webm;codecs=opus')) return 'audio/webm;codecs=opus';
|
||||
if (MediaRecorder.isTypeSupported?.('audio/webm')) return 'audio/webm';
|
||||
if (MediaRecorder.isTypeSupported?.('audio/mp4')) return 'audio/mp4';
|
||||
return '';
|
||||
}
|
||||
|
||||
async function startVoiceCapture() {
|
||||
if (!workspace || voiceCaptureRecorder || typeof MediaRecorder === 'undefined') return;
|
||||
try {
|
||||
const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
|
||||
if (!voiceRecognition || !voiceListening) {
|
||||
stream.getTracks().forEach((track) => track.stop());
|
||||
return;
|
||||
}
|
||||
const mimeType = chooseVoiceCaptureMimeType();
|
||||
const recorder = new MediaRecorder(stream, mimeType ? { mimeType } : undefined);
|
||||
voiceCaptureStream = stream;
|
||||
voiceCaptureRecorder = recorder;
|
||||
voiceCaptureChunks = [];
|
||||
voiceCaptureMimeType = recorder.mimeType || mimeType || 'audio/webm';
|
||||
recorder.ondataavailable = (event) => {
|
||||
if (event.data.size > 0) voiceCaptureChunks.push(event.data);
|
||||
};
|
||||
recorder.start();
|
||||
} catch {
|
||||
voiceCaptureRecorder = null;
|
||||
voiceCaptureStream = null;
|
||||
voiceCaptureChunks = [];
|
||||
}
|
||||
}
|
||||
|
||||
async function stopVoiceCapture(): Promise<{ blob: Blob; filename: string; contentType: string } | null> {
|
||||
const recorder = voiceCaptureRecorder;
|
||||
const stream = voiceCaptureStream;
|
||||
const chunks = voiceCaptureChunks;
|
||||
const contentType = voiceCaptureMimeType || 'audio/webm';
|
||||
voiceCaptureRecorder = null;
|
||||
voiceCaptureStream = null;
|
||||
|
||||
if (!recorder) {
|
||||
voiceCaptureChunks = [];
|
||||
stream?.getTracks().forEach((track) => track.stop());
|
||||
return null;
|
||||
}
|
||||
|
||||
await new Promise<void>((resolve) => {
|
||||
recorder.onstop = () => resolve();
|
||||
try {
|
||||
if (recorder.state !== 'inactive') recorder.stop();
|
||||
else resolve();
|
||||
} catch {
|
||||
resolve();
|
||||
}
|
||||
});
|
||||
stream?.getTracks().forEach((track) => track.stop());
|
||||
voiceCaptureChunks = [];
|
||||
if (!chunks.length) return null;
|
||||
const ext = contentType.includes('mp4') ? 'm4a' : 'webm';
|
||||
return {
|
||||
blob: new Blob(chunks, { type: contentType }),
|
||||
filename: `voice-mode.${ext}`,
|
||||
contentType
|
||||
};
|
||||
}
|
||||
|
||||
async function saveVoiceModeSttCapture(
|
||||
capture: { blob: Blob; filename: string; contentType: string },
|
||||
text: string
|
||||
) {
|
||||
// Browser STT does not need provider transcription, but the captured audio still
|
||||
// matters. Sending audio plus transcript through the normal transcribe route keeps
|
||||
// browser and provider voice samples in one STT cache for the data flywheel.
|
||||
if (!workspace || !text.trim()) return;
|
||||
const form = new FormData();
|
||||
form.append('file', capture.blob, capture.filename);
|
||||
form.append('text', text.trim());
|
||||
form.append('workspace', workspace);
|
||||
form.append('source', 'voice_mode');
|
||||
form.append('language', navigator.language || 'en-US');
|
||||
try {
|
||||
await fetch('/api/audio/transcribe', { method: 'POST', body: form });
|
||||
} catch {}
|
||||
}
|
||||
|
||||
async function transcribeVoiceModeCapture(
|
||||
capture: { blob: Blob; filename: string; contentType: string }
|
||||
): Promise<string> {
|
||||
const form = new FormData();
|
||||
form.append('file', capture.blob, capture.filename);
|
||||
form.append('workspace', workspace);
|
||||
const res = await fetch('/api/audio/transcribe', { method: 'POST', body: form });
|
||||
if (!res.ok) {
|
||||
let detail = `${res.status}`;
|
||||
try {
|
||||
const data = await res.json();
|
||||
detail = data?.detail || data?.error || detail;
|
||||
} catch {}
|
||||
throw new Error(detail);
|
||||
}
|
||||
const data = await res.json();
|
||||
return (data?.text || '').trim();
|
||||
}
|
||||
|
||||
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 browserText = '';
|
||||
for (let i = event.resultIndex; i < event.results.length; i++) {
|
||||
const result = event.results[i];
|
||||
if (result?.isFinal) browserText += ` ${result[0]?.transcript || ''}`;
|
||||
}
|
||||
browserText = browserText.trim();
|
||||
if (!browserText) return;
|
||||
voiceWaitingForResponse = true;
|
||||
voiceSawStreaming = false;
|
||||
const capturePromise = stopVoiceCapture();
|
||||
stopVoiceRecognition(false);
|
||||
const capture = await capturePromise;
|
||||
let text = browserText;
|
||||
if ($voiceModeSttMode === 'provider' && capture) {
|
||||
try {
|
||||
text = (await transcribeVoiceModeCapture(capture)) || browserText;
|
||||
} catch (err: any) {
|
||||
const detail = err?.message ? ` ${err.message}` : '';
|
||||
toast.error(`${$t('chat.voiceProviderSttFallback')}${detail}`);
|
||||
text = browserText;
|
||||
}
|
||||
} else if ($voiceModeSttMode === 'provider') {
|
||||
toast.error($t('chat.voiceProviderSttNoAudio'));
|
||||
} else if (capture) {
|
||||
void saveVoiceModeSttCapture(capture, browserText);
|
||||
}
|
||||
if (!text.trim()) {
|
||||
voiceWaitingForResponse = false;
|
||||
scheduleVoiceRestart(500);
|
||||
return;
|
||||
}
|
||||
inputText = text;
|
||||
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;
|
||||
stopVoiceCapture();
|
||||
if (!voiceStopRequested) scheduleVoiceRestart(1200);
|
||||
voiceStopRequested = false;
|
||||
};
|
||||
|
||||
try {
|
||||
recognition.start();
|
||||
voiceListening = true;
|
||||
voiceRearming = false;
|
||||
void startVoiceCapture();
|
||||
} 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 +913,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 +988,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';
|
||||
@@ -41,6 +50,12 @@
|
||||
import { toast } from 'svelte-sonner';
|
||||
import { t } from '$lib/i18n';
|
||||
|
||||
type PreparedTtsAudio = {
|
||||
promise: Promise<Blob>;
|
||||
controller: AbortController;
|
||||
generation: number;
|
||||
};
|
||||
|
||||
interface Props {
|
||||
workspace: string;
|
||||
chatId?: string;
|
||||
@@ -60,6 +75,23 @@
|
||||
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 ttsAudio: HTMLAudioElement | null = null;
|
||||
let ttsObjectUrl: string | null = null;
|
||||
let ttsErrorShown = false;
|
||||
let speakingMessageId = $state<string | null>(null);
|
||||
let ttsStopRequested = false;
|
||||
// This browser memory cache only helps while the current page is open, such as when
|
||||
// someone taps the same speak button twice. The backend cache is the durable source
|
||||
// for cross-session reuse and the workspace data flywheel.
|
||||
let ttsAudioCacheBytes = 0;
|
||||
const ttsAudioCache = new Map<string, Blob>();
|
||||
const ttsPreparedAudio = new Map<string, PreparedTtsAudio>();
|
||||
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 +248,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,13 +389,31 @@
|
||||
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;
|
||||
const itemType = data.output.type;
|
||||
if (callId && itemType) {
|
||||
|
||||
if (itemType === 'reasoning') {
|
||||
// Responses-style reasoning items stream as output item updates.
|
||||
const itemId = data.output.id;
|
||||
const existingIdx = itemId
|
||||
? existing.findIndex((o: any) => o.type === 'reasoning' && o.id === itemId)
|
||||
: existing.findIndex((o: any) => o.type === 'reasoning');
|
||||
if (existingIdx >= 0) {
|
||||
existing[existingIdx] = data.output;
|
||||
msg.output = [...existing];
|
||||
} else {
|
||||
msg.output = [...existing, data.output];
|
||||
}
|
||||
} else if (callId && itemType) {
|
||||
const existingIdx = existing.findIndex(
|
||||
(o: any) => o.type === itemType && o.call_id === callId
|
||||
);
|
||||
@@ -382,6 +433,7 @@
|
||||
toast.error(data.error, { duration: 8000 });
|
||||
}
|
||||
if (data.done) {
|
||||
flushTtsBuffer();
|
||||
// Clear streaming indicator for this tab
|
||||
if (tabId) {
|
||||
streamingChatTabs.update((s) => {
|
||||
@@ -437,6 +489,7 @@
|
||||
});
|
||||
|
||||
onDestroy(() => {
|
||||
stopTtsPlayback();
|
||||
const socket = socketStore.getSocket();
|
||||
if (socket) {
|
||||
socket.off('events:chat', handleSocketEvent);
|
||||
@@ -448,6 +501,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(() => {
|
||||
@@ -515,10 +578,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
|
||||
@@ -552,14 +626,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
|
||||
);
|
||||
@@ -617,14 +690,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
|
||||
);
|
||||
@@ -694,6 +766,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;
|
||||
@@ -782,12 +855,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;
|
||||
@@ -829,7 +904,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];
|
||||
@@ -867,13 +942,279 @@
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
function shouldUseTts() {
|
||||
return $ttsEnabled && $ttsConfigured && ($ttsPlaybackEnabled || $voiceModeEnabled);
|
||||
}
|
||||
|
||||
function resetTtsBuffer() {
|
||||
ttsBuffer = '';
|
||||
ttsInsideCodeFence = false;
|
||||
}
|
||||
|
||||
function stopTtsPlayback() {
|
||||
ttsStopRequested = true;
|
||||
ttsGeneration += 1;
|
||||
ttsQueue = [];
|
||||
resetTtsBuffer();
|
||||
for (const pending of ttsPreparedAudio.values()) pending.controller.abort();
|
||||
ttsPreparedAudio.clear();
|
||||
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];
|
||||
void prepareTtsAudio(text, ttsGeneration);
|
||||
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 readTtsError(response: Response): Promise<string> {
|
||||
try {
|
||||
const data = await response.json();
|
||||
return data?.detail || data?.error || `${response.status}`;
|
||||
} catch {
|
||||
return `${response.status}`;
|
||||
}
|
||||
}
|
||||
|
||||
function showTtsFailure(detail: string) {
|
||||
if (!ttsErrorShown) {
|
||||
ttsErrorShown = true;
|
||||
toast.error($t('admin.audio.tts') + ': ' + detail);
|
||||
}
|
||||
ttsPlaybackEnabled.set(false);
|
||||
voiceModeEnabled.set(false);
|
||||
}
|
||||
|
||||
function prepareTtsAudio(text: string, generation: number): Promise<Blob> {
|
||||
const cacheKey = ttsCacheKey(text);
|
||||
const cached = getCachedTtsAudio(cacheKey);
|
||||
if (cached) return Promise.resolve(cached);
|
||||
|
||||
const existing = ttsPreparedAudio.get(cacheKey);
|
||||
if (existing && existing.generation === generation) return existing.promise;
|
||||
if (existing) existing.controller.abort();
|
||||
|
||||
const controller = new AbortController();
|
||||
let promise!: Promise<Blob>;
|
||||
promise = fetch('/api/audio/speech', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ text, voice: $ttsVoice, workspace }),
|
||||
signal: controller.signal
|
||||
})
|
||||
.then(async (response) => {
|
||||
if (!response.ok) throw new Error(await readTtsError(response));
|
||||
const blob = await response.blob();
|
||||
cacheTtsAudio(cacheKey, blob);
|
||||
return blob;
|
||||
})
|
||||
.finally(() => {
|
||||
const current = ttsPreparedAudio.get(cacheKey);
|
||||
if (current?.promise === promise) ttsPreparedAudio.delete(cacheKey);
|
||||
});
|
||||
void promise.catch(() => {});
|
||||
ttsPreparedAudio.set(cacheKey, { promise, controller, generation });
|
||||
return promise;
|
||||
}
|
||||
|
||||
async function playTtsQueue(generation: number) {
|
||||
ttsStopRequested = false;
|
||||
ttsPlaying = true;
|
||||
try {
|
||||
while (generation === ttsGeneration && ttsQueue.length > 0) {
|
||||
if (!shouldUseTts()) break;
|
||||
const text = ttsQueue.shift();
|
||||
if (!text) continue;
|
||||
|
||||
const blob = await prepareTtsAudio(text, generation);
|
||||
|
||||
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;
|
||||
}
|
||||
} catch (err: any) {
|
||||
if (!ttsStopRequested && err?.name !== 'AbortError' && !ttsErrorShown) {
|
||||
showTtsFailure(err?.message || '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">
|
||||
{#if isLanding}
|
||||
<!-- Landing: input + recent chats -->
|
||||
<div class="flex-1 overflow-y-auto flex flex-col">
|
||||
<div class="max-w-xl w-full mx-auto px-4 flex flex-col my-auto pt-6 {previousChats.length === 0 ? 'pb-20' : 'pb-6'}">
|
||||
<div
|
||||
class="max-w-xl w-full mx-auto px-4 flex flex-col my-auto pt-6 {previousChats.length === 0
|
||||
? 'pb-20'
|
||||
: 'pb-6'}"
|
||||
>
|
||||
<!-- Greeting -->
|
||||
<div class="mb-8 text-center">
|
||||
<h1 class="text-lg font-normal text-gray-800 dark:text-gray-200 tracking-tight">
|
||||
@@ -911,9 +1252,9 @@
|
||||
{:else}
|
||||
<!-- Conversation view -->
|
||||
{#if loading}
|
||||
<div class="flex-1 flex items-center justify-center text-gray-400 dark:text-gray-500">
|
||||
<Spinner size={24} />
|
||||
</div>
|
||||
<div class="flex-1 flex items-center justify-center text-gray-400 dark:text-gray-500">
|
||||
<Spinner size={24} />
|
||||
</div>
|
||||
{:else}
|
||||
<div bind:this={messagesEl} class="flex-1 overflow-y-auto" onscroll={handleMessagesScroll}>
|
||||
<div class="max-w-2xl mx-auto px-4 pt-4 pb-16 flex flex-col gap-4">
|
||||
@@ -940,9 +1281,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}
|
||||
|
||||
@@ -0,0 +1,260 @@
|
||||
<script lang="ts">
|
||||
import { slide } from 'svelte/transition';
|
||||
import { quintOut } from 'svelte/easing';
|
||||
import { t } from '$lib/i18n';
|
||||
import ReasoningCollapsible from './ReasoningCollapsible.svelte';
|
||||
import ToolCallCollapsible from './ToolCallCollapsible.svelte';
|
||||
|
||||
interface Props {
|
||||
entries: any[];
|
||||
calls: any[];
|
||||
reasoning: any[];
|
||||
outputs: Map<string, any>;
|
||||
done: boolean;
|
||||
chatId: string | null;
|
||||
messageId: string;
|
||||
groupIdx: number;
|
||||
toolLabel: (name: string, args: any) => string;
|
||||
onapprove: (messageId: string, callId: string, approved: boolean) => void;
|
||||
}
|
||||
|
||||
let {
|
||||
entries,
|
||||
calls,
|
||||
reasoning,
|
||||
outputs,
|
||||
done,
|
||||
chatId,
|
||||
messageId,
|
||||
groupIdx,
|
||||
toolLabel,
|
||||
onapprove
|
||||
}: Props = $props();
|
||||
|
||||
let expanded = $state(false);
|
||||
|
||||
const hasReasoningPending = $derived(
|
||||
reasoning.some((ri: any) => ri.status === 'in_progress' || ri.status === 'running')
|
||||
);
|
||||
const hasPending = $derived(
|
||||
(!done && calls.some((c: any) => c.status !== 'completed' && c.status !== 'rejected')) ||
|
||||
hasReasoningPending
|
||||
);
|
||||
const allDone = $derived(
|
||||
(calls.length === 0 || calls.every((c: any) => c.status === 'completed')) &&
|
||||
!hasReasoningPending
|
||||
);
|
||||
const hasRejected = $derived(calls.some((c: any) => c.status === 'rejected'));
|
||||
const pendingCalls = $derived(calls.filter((c: any) => c.status === 'pending'));
|
||||
const hasPendingApproval = $derived(pendingCalls.length > 0);
|
||||
const isThoughtOnly = $derived(calls.length === 0);
|
||||
const summaryText = $derived.by(() => groupSummaryText(calls));
|
||||
|
||||
function toggleExpanded() {
|
||||
expanded = !expanded;
|
||||
}
|
||||
|
||||
function groupSummaryText(groupCalls: any[]): string {
|
||||
if (groupCalls.length <= 3) {
|
||||
return groupCalls
|
||||
.map((call: any) => toolLabel(call.name || 'tool', call.arguments || {}))
|
||||
.join(', ');
|
||||
}
|
||||
|
||||
const nameCounts: Record<string, number> = {};
|
||||
for (const call of groupCalls) {
|
||||
const name = call.name || 'tool';
|
||||
nameCounts[name] = (nameCounts[name] || 0) + 1;
|
||||
}
|
||||
|
||||
return Object.entries(nameCounts)
|
||||
.map(([name, count]) => (count > 1 ? `${count} ${name}` : name))
|
||||
.join(', ');
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="w-full min-w-0 flex flex-col my-0.5">
|
||||
<button
|
||||
class="w-full min-w-0 text-left text-gray-500 hover:text-gray-700 dark:hover:text-gray-300 transition cursor-pointer"
|
||||
aria-label={$t('chat.toggleToolCalls')}
|
||||
aria-expanded={expanded}
|
||||
onclick={toggleExpanded}
|
||||
>
|
||||
<div class="flex items-center gap-1.5 text-sm min-w-0 {hasPending ? 'shimmer' : ''}">
|
||||
{#if isThoughtOnly}
|
||||
<div class="text-gray-400 dark:text-gray-500">
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
fill="none"
|
||||
viewBox="0 0 24 24"
|
||||
stroke-width="1.75"
|
||||
stroke="currentColor"
|
||||
class="size-3.5"
|
||||
>
|
||||
<path
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
d="M9.813 15.904 9 18.75l-.813-2.846a4.5 4.5 0 0 0-3.09-3.09L2.25 12l2.846-.813a4.5 4.5 0 0 0 3.09-3.09L9 5.25l.813 2.846a4.5 4.5 0 0 0 3.09 3.09L15.75 12l-2.846.813a4.5 4.5 0 0 0 3.09 3.09ZM18.259 8.715 18 9.75l-.259-1.035a3.375 3.375 0 0 0-2.455-2.456L14.25 6l1.036-.259a3.375 3.375 0 0 0 2.455-2.456L18 2.25l.259 1.035a3.375 3.375 0 0 0 2.455 2.456L21.75 6l-1.036.259a3.375 3.375 0 0 0-2.455 2.456ZM16.894 20.567 16.5 21.75l-.394-1.183a2.25 2.25 0 0 0-1.423-1.423L13.5 18.75l1.183-.394a2.25 2.25 0 0 0 1.423-1.423l.394-1.183.394 1.183a2.25 2.25 0 0 0 1.423 1.423l1.183.394-1.183.394a2.25 2.25 0 0 0-1.423 1.423Z"
|
||||
/>
|
||||
</svg>
|
||||
</div>
|
||||
{:else if hasPending}
|
||||
<div class="flex justify-center text-center">
|
||||
<svg
|
||||
aria-hidden="true"
|
||||
class="size-4"
|
||||
viewBox="0 0 24 24"
|
||||
fill="currentColor"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
>
|
||||
<style>
|
||||
.spinner_tc {
|
||||
transform-origin: center;
|
||||
animation: spinner_tc_a 0.75s infinite linear;
|
||||
}
|
||||
@keyframes spinner_tc_a {
|
||||
100% {
|
||||
transform: rotate(360deg);
|
||||
}
|
||||
}
|
||||
</style>
|
||||
<path
|
||||
d="M12,1A11,11,0,1,0,23,12,11,11,0,0,0,12,1Zm0,19a8,8,0,1,1,8-8A8,8,0,0,1,12,20Z"
|
||||
opacity=".25"
|
||||
/>
|
||||
<path
|
||||
d="M10.14,1.16a11,11,0,0,0-9,8.92A1.59,1.59,0,0,0,2.46,12,1.52,1.52,0,0,0,4.11,10.7a8,8,0,0,1,6.66-6.61A1.42,1.42,0,0,0,12,2.69h0A1.57,1.57,0,0,0,10.14,1.16Z"
|
||||
class="spinner_tc"
|
||||
/>
|
||||
</svg>
|
||||
</div>
|
||||
{:else if allDone}
|
||||
<div class="text-emerald-500 dark:text-emerald-400">
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
fill="none"
|
||||
viewBox="0 0 24 24"
|
||||
stroke-width="2"
|
||||
stroke="currentColor"
|
||||
class="size-4"
|
||||
>
|
||||
<path
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
d="M9 12.75 11.25 15 15 9.75M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0Z"
|
||||
/>
|
||||
</svg>
|
||||
</div>
|
||||
{:else if hasRejected}
|
||||
<div class="text-red-400 dark:text-red-500">
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
fill="none"
|
||||
viewBox="0 0 24 24"
|
||||
stroke-width="2.5"
|
||||
stroke="currentColor"
|
||||
class="size-4"
|
||||
>
|
||||
<path stroke-linecap="round" stroke-linejoin="round" d="M6 18L18 6M6 6l12 12" />
|
||||
</svg>
|
||||
</div>
|
||||
{:else}
|
||||
<div class="text-gray-400 dark:text-gray-500">
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
fill="none"
|
||||
viewBox="0 0 24 24"
|
||||
stroke-width="1.75"
|
||||
stroke="currentColor"
|
||||
class="size-3.5"
|
||||
>
|
||||
<path
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
d="M21.75 6.75a4.5 4.5 0 0 1-4.884 4.484c-1.076-.091-2.264.071-2.95.904l-7.152 8.684a2.548 2.548 0 1 1-3.586-3.586l8.684-7.152c.833-.686.995-1.874.904-2.95a4.5 4.5 0 0 1 6.336-4.486l-3.276 3.276a3.004 3.004 0 0 0 2.25 2.25l3.276-3.276c.256.565.398 1.192.398 1.852Z"
|
||||
/>
|
||||
</svg>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<div class="flex-1 min-w-0 line-clamp-1">
|
||||
<span class="text-gray-600 dark:text-gray-300">
|
||||
{isThoughtOnly
|
||||
? hasPending
|
||||
? $t('chat.thinking')
|
||||
: $t('chat.edit.thought')
|
||||
: hasPending
|
||||
? $t('chat.exploring')
|
||||
: $t('chat.explored')}
|
||||
</span>
|
||||
{#if !isThoughtOnly && summaryText}
|
||||
<span class="text-gray-400 dark:text-gray-500 ml-1">{summaryText}</span>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<div class="flex shrink-0 self-center text-gray-400 dark:text-gray-500">
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
fill="none"
|
||||
viewBox="0 0 24 24"
|
||||
stroke-width="3.5"
|
||||
stroke="currentColor"
|
||||
class="size-3 transition-transform duration-200 {expanded ? 'rotate-180' : ''}"
|
||||
>
|
||||
<path stroke-linecap="round" stroke-linejoin="round" d="m19.5 8.25-7.5 7.5-7.5-7.5" />
|
||||
</svg>
|
||||
</div>
|
||||
</div>
|
||||
</button>
|
||||
|
||||
{#if expanded}
|
||||
<div transition:slide={{ duration: 300, easing: quintOut, axis: 'y' }}>
|
||||
<div class="mb-0.5 space-y-0.5 mt-1">
|
||||
{#each entries as item, entryIdx}
|
||||
{#if item.type === 'reasoning'}
|
||||
<ReasoningCollapsible {item} fallbackId={`reasoning-${groupIdx}-${entryIdx}`} />
|
||||
{:else}
|
||||
<ToolCallCollapsible
|
||||
{item}
|
||||
pairedOutput={outputs.get(item.call_id)}
|
||||
{done}
|
||||
{chatId}
|
||||
{messageId}
|
||||
{toolLabel}
|
||||
{onapprove}
|
||||
/>
|
||||
{/if}
|
||||
{/each}
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
{#if !expanded && hasPendingApproval && chatId}
|
||||
<div class="mt-1 space-y-0.5">
|
||||
{#each pendingCalls as item}
|
||||
<div class="flex items-center gap-2 py-1 px-1">
|
||||
<span class="text-xs text-gray-500 dark:text-gray-400 flex-1 min-w-0 line-clamp-1">
|
||||
{toolLabel(item.name, item.arguments || {})}
|
||||
</span>
|
||||
<span class="flex gap-1 shrink-0">
|
||||
<button
|
||||
class="text-[11px] px-2.5 py-0.5 rounded-md
|
||||
text-gray-600 dark:text-gray-300
|
||||
bg-gray-100 dark:bg-white/8
|
||||
hover:bg-gray-200 dark:hover:bg-white/12
|
||||
transition-colors duration-100"
|
||||
onclick={() => onapprove(messageId, item.call_id, true)}>{$t('chat.allow')}</button
|
||||
>
|
||||
<button
|
||||
class="text-[11px] px-2 py-0.5 rounded-md
|
||||
text-gray-400 dark:text-gray-500
|
||||
hover:text-gray-600 dark:hover:text-gray-300
|
||||
transition-colors duration-100"
|
||||
onclick={() => onapprove(messageId, item.call_id, false)}>{$t('chat.deny')}</button
|
||||
>
|
||||
</span>
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
@@ -150,7 +150,8 @@
|
||||
return (item.summary ?? item.content ?? [])
|
||||
.filter((p: any) => 'text' in p)
|
||||
.map((p: any) => p.text ?? '')
|
||||
.join('');
|
||||
.join('')
|
||||
.trim();
|
||||
}
|
||||
|
||||
function updateReasoningText(idx: number, text: string) {
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
<script lang="ts">
|
||||
import { slide } from 'svelte/transition';
|
||||
import { quintOut } from 'svelte/easing';
|
||||
import { t } from '$lib/i18n';
|
||||
|
||||
interface Props {
|
||||
item: any;
|
||||
fallbackId: string;
|
||||
}
|
||||
|
||||
let { item, fallbackId }: Props = $props();
|
||||
|
||||
let expanded = $state(false);
|
||||
|
||||
const reasoningId = $derived(item.id || fallbackId);
|
||||
const isThinking = $derived(item.status === 'in_progress' || item.status === 'running');
|
||||
const thoughtText = $derived.by(() => {
|
||||
return (item.summary ?? item.content ?? [])
|
||||
.filter((part: any) => 'text' in part)
|
||||
.map((part: any) => part.text ?? '')
|
||||
.join('')
|
||||
.trim();
|
||||
});
|
||||
|
||||
function toggleExpanded() {
|
||||
expanded = !expanded;
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="w-full min-w-0 flex flex-col">
|
||||
<button
|
||||
class="w-full min-w-0 text-left text-gray-500 hover:text-gray-700 dark:hover:text-gray-300 transition cursor-pointer"
|
||||
aria-expanded={expanded}
|
||||
aria-controls={reasoningId}
|
||||
onclick={toggleExpanded}
|
||||
>
|
||||
<div class="flex items-center gap-1.5 text-sm min-w-0 {isThinking ? 'shimmer' : ''}">
|
||||
<div class="text-gray-400 dark:text-gray-500">
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
fill="none"
|
||||
viewBox="0 0 24 24"
|
||||
stroke-width="1.75"
|
||||
stroke="currentColor"
|
||||
class="size-3.5"
|
||||
>
|
||||
<path
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
d="M9.813 15.904 9 18.75l-.813-2.846a4.5 4.5 0 0 0-3.09-3.09L2.25 12l2.846-.813a4.5 4.5 0 0 0 3.09-3.09L9 5.25l.813 2.846a4.5 4.5 0 0 0 3.09 3.09L15.75 12l-2.846.813a4.5 4.5 0 0 0 3.09 3.09ZM18.259 8.715 18 9.75l-.259-1.035a3.375 3.375 0 0 0-2.455-2.456L14.25 6l1.036-.259a3.375 3.375 0 0 0 2.455-2.456L18 2.25l.259 1.035a3.375 3.375 0 0 0 2.455 2.456L21.75 6l-1.036.259a3.375 3.375 0 0 0-2.455 2.456ZM16.894 20.567 16.5 21.75l-.394-1.183a2.25 2.25 0 0 0-1.423-1.423L13.5 18.75l1.183-.394a2.25 2.25 0 0 0 1.423-1.423l.394-1.183.394 1.183a2.25 2.25 0 0 0 1.423 1.423l1.183.394-1.183.394a2.25 2.25 0 0 0-1.423 1.423Z"
|
||||
/>
|
||||
</svg>
|
||||
</div>
|
||||
|
||||
<div class="flex-1 min-w-0 line-clamp-1">
|
||||
<span class="font-normal">
|
||||
{isThinking ? $t('chat.thinking') : $t('chat.edit.thought')}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div class="flex shrink-0 self-center translate-y-[1px]">
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
fill="none"
|
||||
viewBox="0 0 24 24"
|
||||
stroke-width="3.5"
|
||||
stroke="currentColor"
|
||||
class="size-3 transition-transform duration-200 text-gray-400 dark:text-gray-500 {expanded
|
||||
? 'rotate-180'
|
||||
: ''}"
|
||||
>
|
||||
<path stroke-linecap="round" stroke-linejoin="round" d="m19.5 8.25-7.5 7.5-7.5-7.5" />
|
||||
</svg>
|
||||
</div>
|
||||
</div>
|
||||
</button>
|
||||
|
||||
{#if expanded && thoughtText}
|
||||
<div id={reasoningId} transition:slide={{ duration: 300, easing: quintOut, axis: 'y' }}>
|
||||
<div class="mt-1 mb-0.5 px-1">
|
||||
<div class="text-sm text-gray-500 dark:text-gray-400 whitespace-pre-wrap">
|
||||
{thoughtText}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
@@ -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
|
||||
|
||||
@@ -0,0 +1,267 @@
|
||||
<script lang="ts">
|
||||
import { slide } from 'svelte/transition';
|
||||
import { quintOut } from 'svelte/easing';
|
||||
import { t } from '$lib/i18n';
|
||||
|
||||
interface Props {
|
||||
item: any;
|
||||
pairedOutput?: any;
|
||||
done: boolean;
|
||||
chatId: string | null;
|
||||
messageId: string;
|
||||
toolLabel: (name: string, args: any) => string;
|
||||
onapprove: (messageId: string, callId: string, approved: boolean) => void;
|
||||
}
|
||||
|
||||
let { item, pairedOutput, done, chatId, messageId, toolLabel, onapprove }: Props = $props();
|
||||
|
||||
let expanded = $state(false);
|
||||
|
||||
const args = $derived(item.arguments || {});
|
||||
const toolName = $derived(item.name);
|
||||
const callId = $derived(item.call_id || toolName);
|
||||
const isExecuting = $derived(
|
||||
item.status === 'running' || item.status === 'in_progress' || (!item.status && !done)
|
||||
);
|
||||
const isDone = $derived(item.status === 'completed');
|
||||
const isRejected = $derived(item.status === 'rejected');
|
||||
const isPending = $derived(item.status === 'pending');
|
||||
|
||||
function toggleExpanded() {
|
||||
expanded = !expanded;
|
||||
}
|
||||
|
||||
function handleRowKeydown(e: KeyboardEvent) {
|
||||
if (e.key === 'Enter' || e.key === ' ') {
|
||||
e.preventDefault();
|
||||
toggleExpanded();
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="w-full min-w-0 flex flex-col">
|
||||
<div
|
||||
role="button"
|
||||
tabindex="0"
|
||||
class="w-full min-w-0 text-left text-gray-500 hover:text-gray-700 dark:hover:text-gray-300 transition cursor-pointer"
|
||||
aria-expanded={expanded}
|
||||
aria-controls={callId}
|
||||
onclick={toggleExpanded}
|
||||
onkeydown={handleRowKeydown}
|
||||
>
|
||||
<div class="flex items-center gap-1.5 text-sm min-w-0 {isExecuting ? 'shimmer' : ''}">
|
||||
{#if isExecuting}
|
||||
<div class="flex justify-center text-center">
|
||||
<svg
|
||||
aria-hidden="true"
|
||||
class="size-4"
|
||||
viewBox="0 0 24 24"
|
||||
fill="currentColor"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
>
|
||||
<style>
|
||||
.spinner_inner {
|
||||
transform-origin: center;
|
||||
animation: spinner_inner_a 0.75s infinite linear;
|
||||
}
|
||||
@keyframes spinner_inner_a {
|
||||
100% {
|
||||
transform: rotate(360deg);
|
||||
}
|
||||
}
|
||||
</style>
|
||||
<path
|
||||
d="M12,1A11,11,0,1,0,23,12,11,11,0,0,0,12,1Zm0,19a8,8,0,1,1,8-8A8,8,0,0,1,12,20Z"
|
||||
opacity=".25"
|
||||
/>
|
||||
<path
|
||||
d="M10.14,1.16a11,11,0,0,0-9,8.92A1.59,1.59,0,0,0,2.46,12,1.52,1.52,0,0,0,4.11,10.7a8,8,0,0,1,6.66-6.61A1.42,1.42,0,0,0,12,2.69h0A1.57,1.57,0,0,0,10.14,1.16Z"
|
||||
class="spinner_inner"
|
||||
/>
|
||||
</svg>
|
||||
</div>
|
||||
{:else if isDone}
|
||||
<div class="text-emerald-500 dark:text-emerald-400">
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
fill="none"
|
||||
viewBox="0 0 24 24"
|
||||
stroke-width="2"
|
||||
stroke="currentColor"
|
||||
class="size-4"
|
||||
>
|
||||
<path
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
d="M9 12.75 11.25 15 15 9.75M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0Z"
|
||||
/>
|
||||
</svg>
|
||||
</div>
|
||||
{:else if isRejected}
|
||||
<div class="text-red-400 dark:text-red-500">
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
fill="none"
|
||||
viewBox="0 0 24 24"
|
||||
stroke-width="2.5"
|
||||
stroke="currentColor"
|
||||
class="size-4"
|
||||
>
|
||||
<path stroke-linecap="round" stroke-linejoin="round" d="M6 18L18 6M6 6l12 12" />
|
||||
</svg>
|
||||
</div>
|
||||
{:else}
|
||||
<div class="text-gray-400 dark:text-gray-500">
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
fill="none"
|
||||
viewBox="0 0 24 24"
|
||||
stroke-width="1.75"
|
||||
stroke="currentColor"
|
||||
class="size-3.5"
|
||||
>
|
||||
<path
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
d="M21.75 6.75a4.5 4.5 0 0 1-4.884 4.484c-1.076-.091-2.264.071-2.95.904l-7.152 8.684a2.548 2.548 0 1 1-3.586-3.586l8.684-7.152c.833-.686.995-1.874.904-2.95a4.5 4.5 0 0 1 6.336-4.486l-3.276 3.276a3.004 3.004 0 0 0 2.25 2.25l3.276-3.276c.256.565.398 1.192.398 1.852Z"
|
||||
/>
|
||||
</svg>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<div class="flex-1 min-w-0 line-clamp-1">
|
||||
<span class="font-normal">{toolLabel(toolName, args)}</span>
|
||||
</div>
|
||||
|
||||
{#if isPending && chatId}
|
||||
<span class="flex gap-1 shrink-0">
|
||||
<button
|
||||
class="text-[11px] px-2.5 py-0.5 rounded-md
|
||||
text-gray-600 dark:text-gray-300
|
||||
bg-gray-100 dark:bg-white/8
|
||||
hover:bg-gray-200 dark:hover:bg-white/12
|
||||
transition-colors duration-100"
|
||||
onclick={(e) => {
|
||||
e.stopPropagation();
|
||||
onapprove(messageId, item.call_id, true);
|
||||
}}>{$t('chat.allow')}</button
|
||||
>
|
||||
<button
|
||||
class="text-[11px] px-2 py-0.5 rounded-md
|
||||
text-gray-400 dark:text-gray-500
|
||||
hover:text-gray-600 dark:hover:text-gray-300
|
||||
transition-colors duration-100"
|
||||
onclick={(e) => {
|
||||
e.stopPropagation();
|
||||
onapprove(messageId, item.call_id, false);
|
||||
}}>{$t('chat.deny')}</button
|
||||
>
|
||||
</span>
|
||||
{:else}
|
||||
<div class="flex shrink-0 self-center translate-y-[1px]">
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
fill="none"
|
||||
viewBox="0 0 24 24"
|
||||
stroke-width="3.5"
|
||||
stroke="currentColor"
|
||||
class="size-3 transition-transform duration-200 text-gray-400 dark:text-gray-500 {expanded
|
||||
? 'rotate-180'
|
||||
: ''}"
|
||||
>
|
||||
<path stroke-linecap="round" stroke-linejoin="round" d="m19.5 8.25-7.5 7.5-7.5-7.5" />
|
||||
</svg>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{#if expanded}
|
||||
<div id={callId} transition:slide={{ duration: 300, easing: quintOut, axis: 'y' }}>
|
||||
<div
|
||||
class="border border-gray-50 dark:border-gray-850/30 rounded-2xl my-1.5 p-3 space-y-3 overflow-hidden"
|
||||
>
|
||||
{#if Object.keys(args).length > 0}
|
||||
<div>
|
||||
<div
|
||||
class="text-[10px] uppercase tracking-wider text-gray-400 dark:text-gray-500 mb-1.5 px-1"
|
||||
>
|
||||
{$t('chat.toolInput')}
|
||||
</div>
|
||||
{#if toolName === 'edit_file' && args.target}
|
||||
<div
|
||||
class="text-[11px] font-mono rounded-lg overflow-hidden border border-gray-200/60 dark:border-white/6"
|
||||
>
|
||||
<div
|
||||
class="bg-red-50/80 dark:bg-red-950/20 text-red-700 dark:text-red-400 px-2.5 py-1 whitespace-pre-wrap break-all leading-relaxed"
|
||||
>
|
||||
<span class="select-none text-red-400 dark:text-red-600 mr-1">-</span>{args.target
|
||||
.length > 500
|
||||
? args.target.slice(0, 500) + '...'
|
||||
: args.target}
|
||||
</div>
|
||||
<div
|
||||
class="bg-green-50/80 dark:bg-green-950/20 text-green-700 dark:text-green-400 px-2.5 py-1 whitespace-pre-wrap break-all leading-relaxed"
|
||||
>
|
||||
<span class="select-none text-green-400 dark:text-green-600 mr-1">+</span>{(
|
||||
args.replacement || ''
|
||||
).length > 500
|
||||
? args.replacement.slice(0, 500) + '...'
|
||||
: args.replacement || ''}
|
||||
</div>
|
||||
</div>
|
||||
{#if args.start_line}
|
||||
<div class="text-[10px] text-gray-400 dark:text-gray-600 mt-1 px-1">
|
||||
{$t('chat.toolLines', {
|
||||
start: args.start_line,
|
||||
end: args.end_line || 'end'
|
||||
})}
|
||||
</div>
|
||||
{/if}
|
||||
{:else if toolName === 'run_command'}
|
||||
<code
|
||||
class="block text-xs font-mono text-gray-600 dark:text-gray-300 bg-gray-50 dark:bg-gray-900 rounded-lg px-2.5 py-1.5 overflow-x-auto break-all whitespace-pre-wrap"
|
||||
>{args.command}</code
|
||||
>
|
||||
{:else}
|
||||
<div class="px-1 space-y-0.5">
|
||||
{#each Object.entries(args) as [key, value]}
|
||||
<div class="flex gap-2 text-xs py-0.5">
|
||||
<span class="text-gray-600 dark:text-gray-400 shrink-0">{key}</span>
|
||||
<span class="text-gray-800 dark:text-gray-200 break-all">
|
||||
{typeof value === 'object' ? JSON.stringify(value) : value}
|
||||
</span>
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
{#if pairedOutput?.output}
|
||||
<div>
|
||||
<div
|
||||
class="text-[10px] uppercase tracking-wider text-gray-400 dark:text-gray-500 mb-1.5 px-1"
|
||||
>
|
||||
{$t('chat.toolOutput')}
|
||||
</div>
|
||||
<div class="w-full min-w-0 overflow-hidden">
|
||||
<pre
|
||||
class="text-xs text-gray-600 dark:text-gray-300 whitespace-pre-wrap break-words font-mono max-h-64 overflow-auto leading-relaxed">{pairedOutput
|
||||
.output.length > 10000
|
||||
? pairedOutput.output.slice(0, 10000)
|
||||
: pairedOutput.output}</pre>
|
||||
{#if pairedOutput.output.length > 10000}
|
||||
<div class="text-[10px] text-gray-400 dark:text-gray-600 mt-1 px-1">
|
||||
{$t('chat.totalChars', {
|
||||
count: pairedOutput.output.length.toLocaleString()
|
||||
})}
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
@@ -265,6 +265,9 @@
|
||||
"models.failedToLoad": "Modellkonfiguration konnte nicht geladen werden",
|
||||
"models.failedToToggle": "Modell konnte nicht umgeschaltet werden",
|
||||
"models.failedToSave": "Speichern fehlgeschlagen",
|
||||
"models.refresh": "Modellliste aktualisieren",
|
||||
"models.refreshed": "Modellliste aktualisiert",
|
||||
"models.refreshFailed": "Modellliste konnte nicht aktualisiert werden",
|
||||
"models.savedDefaults": "Globale Standardwerte gespeichert",
|
||||
"models.savedParams": "Parameter für {{name}} gespeichert",
|
||||
"models.add": "+ Hinzufügen",
|
||||
@@ -472,6 +475,21 @@
|
||||
"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.voiceModeSttMode": "Speech recognition",
|
||||
"admin.audio.voiceModeSttBrowser": "Browser",
|
||||
"admin.audio.voiceModeSttProvider": "Configured STT",
|
||||
"admin.audio.voiceModeBrowserSttHint": "Uses browser speech recognition, then stores the audio and transcript locally for the voice data flywheel.",
|
||||
"admin.audio.voiceModeProviderSttHint": "Sends voice-mode audio through the configured STT provider and stores the result locally.",
|
||||
"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",
|
||||
@@ -553,6 +571,14 @@
|
||||
"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.voiceProviderSttFallback": "Configured STT failed. Used browser transcript.",
|
||||
"chat.voiceProviderSttNoAudio": "Configured STT needs microphone audio, but no voice-mode recording was captured.",
|
||||
"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",
|
||||
|
||||
@@ -321,6 +321,9 @@
|
||||
"models.failedToLoad": "Failed to load model config",
|
||||
"models.failedToToggle": "Failed to toggle model",
|
||||
"models.failedToSave": "Failed to save",
|
||||
"models.refresh": "Refresh model list",
|
||||
"models.refreshed": "Model list refreshed",
|
||||
"models.refreshFailed": "Failed to refresh model list",
|
||||
"models.savedDefaults": "Saved global defaults",
|
||||
"models.savedParams": "Saved params for {{name}}",
|
||||
"models.add": "+ Add",
|
||||
@@ -587,6 +590,21 @@
|
||||
"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.voiceModeSttMode": "Speech recognition",
|
||||
"admin.audio.voiceModeSttBrowser": "Browser",
|
||||
"admin.audio.voiceModeSttProvider": "Configured STT",
|
||||
"admin.audio.voiceModeBrowserSttHint": "Uses browser speech recognition, then stores the audio and transcript locally for the voice data flywheel.",
|
||||
"admin.audio.voiceModeProviderSttHint": "Sends voice-mode audio through the configured STT provider and stores the result locally.",
|
||||
"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.",
|
||||
@@ -676,10 +694,19 @@
|
||||
|
||||
"chat.edit.text": "Text",
|
||||
"chat.edit.thought": "Thought",
|
||||
"chat.thinking": "Thinking",
|
||||
"chat.edit.tool": "Tool",
|
||||
"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.voiceProviderSttFallback": "Configured STT failed. Used browser transcript.",
|
||||
"chat.voiceProviderSttNoAudio": "Configured STT needs microphone audio, but no voice-mode recording was captured.",
|
||||
"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?",
|
||||
|
||||
@@ -771,4 +798,3 @@
|
||||
"onboarding.connectAiNudge": "Connect an AI provider to start chatting.",
|
||||
"onboarding.goToConnections": "Settings → Connections"
|
||||
}
|
||||
|
||||
@@ -265,6 +265,9 @@
|
||||
"models.failedToLoad": "Error al cargar configuración de modelos",
|
||||
"models.failedToToggle": "Error al alternar modelo",
|
||||
"models.failedToSave": "Error al guardar",
|
||||
"models.refresh": "Actualizar lista de modelos",
|
||||
"models.refreshed": "Lista de modelos actualizada",
|
||||
"models.refreshFailed": "Error al actualizar la lista de modelos",
|
||||
"models.savedDefaults": "Valores predeterminados globales guardados",
|
||||
"models.savedParams": "Parámetros guardados para {{name}}",
|
||||
"models.add": "+ Agregar",
|
||||
@@ -472,6 +475,21 @@
|
||||
"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.voiceModeSttMode": "Speech recognition",
|
||||
"admin.audio.voiceModeSttBrowser": "Browser",
|
||||
"admin.audio.voiceModeSttProvider": "Configured STT",
|
||||
"admin.audio.voiceModeBrowserSttHint": "Uses browser speech recognition, then stores the audio and transcript locally for the voice data flywheel.",
|
||||
"admin.audio.voiceModeProviderSttHint": "Sends voice-mode audio through the configured STT provider and stores the result locally.",
|
||||
"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",
|
||||
@@ -553,6 +571,14 @@
|
||||
"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.voiceProviderSttFallback": "Configured STT failed. Used browser transcript.",
|
||||
"chat.voiceProviderSttNoAudio": "Configured STT needs microphone audio, but no voice-mode recording was captured.",
|
||||
"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",
|
||||
|
||||
@@ -265,6 +265,9 @@
|
||||
"models.failedToLoad": "Échec du chargement de la configuration des modèles",
|
||||
"models.failedToToggle": "Échec du basculement du modèle",
|
||||
"models.failedToSave": "Échec de la sauvegarde",
|
||||
"models.refresh": "Actualiser la liste des modèles",
|
||||
"models.refreshed": "Liste des modèles actualisée",
|
||||
"models.refreshFailed": "Échec de l’actualisation de la liste des modèles",
|
||||
"models.savedDefaults": "Valeurs par défaut globales enregistrées",
|
||||
"models.savedParams": "Paramètres enregistrés pour {{name}}",
|
||||
"models.add": "+ Ajouter",
|
||||
@@ -471,6 +474,21 @@
|
||||
"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.voiceModeSttMode": "Speech recognition",
|
||||
"admin.audio.voiceModeSttBrowser": "Browser",
|
||||
"admin.audio.voiceModeSttProvider": "Configured STT",
|
||||
"admin.audio.voiceModeBrowserSttHint": "Uses browser speech recognition, then stores the audio and transcript locally for the voice data flywheel.",
|
||||
"admin.audio.voiceModeProviderSttHint": "Sends voice-mode audio through the configured STT provider and stores the result locally.",
|
||||
"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",
|
||||
@@ -552,6 +570,14 @@
|
||||
"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.voiceProviderSttFallback": "Configured STT failed. Used browser transcript.",
|
||||
"chat.voiceProviderSttNoAudio": "Configured STT needs microphone audio, but no voice-mode recording was captured.",
|
||||
"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é",
|
||||
|
||||
@@ -265,6 +265,9 @@
|
||||
"models.failedToLoad": "モデル設定の読み込みに失敗しました",
|
||||
"models.failedToToggle": "モデルの切り替えに失敗しました",
|
||||
"models.failedToSave": "保存に失敗しました",
|
||||
"models.refresh": "モデル一覧を更新",
|
||||
"models.refreshed": "モデル一覧を更新しました",
|
||||
"models.refreshFailed": "モデル一覧の更新に失敗しました",
|
||||
"models.savedDefaults": "グローバルデフォルトを保存しました",
|
||||
"models.savedParams": "{{name}} のパラメータを保存しました",
|
||||
"models.add": "+ 追加",
|
||||
@@ -472,6 +475,21 @@
|
||||
"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.voiceModeSttMode": "Speech recognition",
|
||||
"admin.audio.voiceModeSttBrowser": "Browser",
|
||||
"admin.audio.voiceModeSttProvider": "Configured STT",
|
||||
"admin.audio.voiceModeBrowserSttHint": "Uses browser speech recognition, then stores the audio and transcript locally for the voice data flywheel.",
|
||||
"admin.audio.voiceModeProviderSttHint": "Sends voice-mode audio through the configured STT provider and stores the result locally.",
|
||||
"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",
|
||||
@@ -553,6 +571,14 @@
|
||||
"chat.edit.tool": "ツール",
|
||||
"chat.edit.item": "項目",
|
||||
"chat.dictate.unsupported": "このブラウザでは音声認識がサポートされていません。",
|
||||
"chat.voiceModeOn": "Voice mode on",
|
||||
"chat.voiceListening": "Listening...",
|
||||
"chat.voiceWaiting": "Waiting for response...",
|
||||
"chat.voiceProviderSttFallback": "Configured STT failed. Used browser transcript.",
|
||||
"chat.voiceProviderSttNoAudio": "Configured STT needs microphone audio, but no voice-mode recording was captured.",
|
||||
"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": "キーの作成に失敗しました",
|
||||
|
||||
@@ -265,6 +265,9 @@
|
||||
"models.failedToLoad": "모델 설정 로드 실패",
|
||||
"models.failedToToggle": "모델 전환 실패",
|
||||
"models.failedToSave": "저장 실패",
|
||||
"models.refresh": "모델 목록 새로고침",
|
||||
"models.refreshed": "모델 목록 새로고침됨",
|
||||
"models.refreshFailed": "모델 목록 새로고침 실패",
|
||||
"models.savedDefaults": "글로벌 기본값 저장됨",
|
||||
"models.savedParams": "{{name}} 파라미터 저장됨",
|
||||
"models.add": "+ 추가",
|
||||
@@ -472,6 +475,21 @@
|
||||
"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.voiceModeSttMode": "Speech recognition",
|
||||
"admin.audio.voiceModeSttBrowser": "Browser",
|
||||
"admin.audio.voiceModeSttProvider": "Configured STT",
|
||||
"admin.audio.voiceModeBrowserSttHint": "Uses browser speech recognition, then stores the audio and transcript locally for the voice data flywheel.",
|
||||
"admin.audio.voiceModeProviderSttHint": "Sends voice-mode audio through the configured STT provider and stores the result locally.",
|
||||
"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",
|
||||
@@ -553,6 +571,14 @@
|
||||
"chat.edit.tool": "도구",
|
||||
"chat.edit.item": "항목",
|
||||
"chat.dictate.unsupported": "이 브라우저에서는 음성 인식이 지원되지 않습니다.",
|
||||
"chat.voiceModeOn": "Voice mode on",
|
||||
"chat.voiceListening": "Listening...",
|
||||
"chat.voiceWaiting": "Waiting for response...",
|
||||
"chat.voiceProviderSttFallback": "Configured STT failed. Used browser transcript.",
|
||||
"chat.voiceProviderSttNoAudio": "Configured STT needs microphone audio, but no voice-mode recording was captured.",
|
||||
"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": "키 생성에 실패했습니다",
|
||||
|
||||
@@ -265,6 +265,9 @@
|
||||
"models.failedToLoad": "Falha ao carregar configuração de modelos",
|
||||
"models.failedToToggle": "Falha ao alternar modelo",
|
||||
"models.failedToSave": "Falha ao salvar",
|
||||
"models.refresh": "Atualizar lista de modelos",
|
||||
"models.refreshed": "Lista de modelos atualizada",
|
||||
"models.refreshFailed": "Falha ao atualizar lista de modelos",
|
||||
"models.savedDefaults": "Padrões globais salvos",
|
||||
"models.savedParams": "Parâmetros salvos para {{name}}",
|
||||
"models.add": "+ Adicionar",
|
||||
@@ -472,6 +475,21 @@
|
||||
"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.voiceModeSttMode": "Speech recognition",
|
||||
"admin.audio.voiceModeSttBrowser": "Browser",
|
||||
"admin.audio.voiceModeSttProvider": "Configured STT",
|
||||
"admin.audio.voiceModeBrowserSttHint": "Uses browser speech recognition, then stores the audio and transcript locally for the voice data flywheel.",
|
||||
"admin.audio.voiceModeProviderSttHint": "Sends voice-mode audio through the configured STT provider and stores the result locally.",
|
||||
"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",
|
||||
@@ -553,6 +571,14 @@
|
||||
"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.voiceProviderSttFallback": "Configured STT failed. Used browser transcript.",
|
||||
"chat.voiceProviderSttNoAudio": "Configured STT needs microphone audio, but no voice-mode recording was captured.",
|
||||
"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",
|
||||
|
||||
@@ -265,6 +265,9 @@
|
||||
"models.failedToLoad": "Не удалось загрузить конфигурацию моделей",
|
||||
"models.failedToToggle": "Не удалось переключить модель",
|
||||
"models.failedToSave": "Не удалось сохранить",
|
||||
"models.refresh": "Обновить список моделей",
|
||||
"models.refreshed": "Список моделей обновлен",
|
||||
"models.refreshFailed": "Не удалось обновить список моделей",
|
||||
"models.savedDefaults": "Глобальные значения по умолчанию сохранены",
|
||||
"models.savedParams": "Параметры для {{name}} сохранены",
|
||||
"models.add": "+ Добавить",
|
||||
@@ -472,6 +475,21 @@
|
||||
"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.voiceModeSttMode": "Speech recognition",
|
||||
"admin.audio.voiceModeSttBrowser": "Browser",
|
||||
"admin.audio.voiceModeSttProvider": "Configured STT",
|
||||
"admin.audio.voiceModeBrowserSttHint": "Uses browser speech recognition, then stores the audio and transcript locally for the voice data flywheel.",
|
||||
"admin.audio.voiceModeProviderSttHint": "Sends voice-mode audio through the configured STT provider and stores the result locally.",
|
||||
"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",
|
||||
@@ -553,6 +571,14 @@
|
||||
"chat.edit.tool": "Инструмент",
|
||||
"chat.edit.item": "Элемент",
|
||||
"chat.dictate.unsupported": "Распознавание речи не поддерживается в этом браузере.",
|
||||
"chat.voiceModeOn": "Voice mode on",
|
||||
"chat.voiceListening": "Listening...",
|
||||
"chat.voiceWaiting": "Waiting for response...",
|
||||
"chat.voiceProviderSttFallback": "Configured STT failed. Used browser transcript.",
|
||||
"chat.voiceProviderSttNoAudio": "Configured STT needs microphone audio, but no voice-mode recording was captured.",
|
||||
"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": "Не удалось создать ключ",
|
||||
|
||||
@@ -265,6 +265,9 @@
|
||||
"models.failedToLoad": "加载模型配置失败",
|
||||
"models.failedToToggle": "切换模型失败",
|
||||
"models.failedToSave": "保存失败",
|
||||
"models.refresh": "刷新模型列表",
|
||||
"models.refreshed": "模型列表已刷新",
|
||||
"models.refreshFailed": "刷新模型列表失败",
|
||||
"models.savedDefaults": "全局默认值已保存",
|
||||
"models.savedParams": "{{name}} 的参数已保存",
|
||||
"models.add": "+ 添加",
|
||||
@@ -472,6 +475,21 @@
|
||||
"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.voiceModeSttMode": "Speech recognition",
|
||||
"admin.audio.voiceModeSttBrowser": "Browser",
|
||||
"admin.audio.voiceModeSttProvider": "Configured STT",
|
||||
"admin.audio.voiceModeBrowserSttHint": "Uses browser speech recognition, then stores the audio and transcript locally for the voice data flywheel.",
|
||||
"admin.audio.voiceModeProviderSttHint": "Sends voice-mode audio through the configured STT provider and stores the result locally.",
|
||||
"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",
|
||||
@@ -553,6 +571,14 @@
|
||||
"chat.edit.tool": "工具",
|
||||
"chat.edit.item": "项目",
|
||||
"chat.dictate.unsupported": "此浏览器不支持语音识别。",
|
||||
"chat.voiceModeOn": "Voice mode on",
|
||||
"chat.voiceListening": "Listening...",
|
||||
"chat.voiceWaiting": "Waiting for response...",
|
||||
"chat.voiceProviderSttFallback": "Configured STT failed. Used browser transcript.",
|
||||
"chat.voiceProviderSttNoAudio": "Configured STT needs microphone audio, but no voice-mode recording was captured.",
|
||||
"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": "创建密钥失败",
|
||||
|
||||
@@ -265,6 +265,9 @@
|
||||
"models.failedToLoad": "載入模型設定失敗",
|
||||
"models.failedToToggle": "切換模型失敗",
|
||||
"models.failedToSave": "儲存失敗",
|
||||
"models.refresh": "重新整理模型清單",
|
||||
"models.refreshed": "模型清單已重新整理",
|
||||
"models.refreshFailed": "重新整理模型清單失敗",
|
||||
"models.savedDefaults": "全域預設值已儲存",
|
||||
"models.savedParams": "{{name}} 的參數已儲存",
|
||||
"models.add": "+ 新增",
|
||||
@@ -472,6 +475,21 @@
|
||||
"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.voiceModeSttMode": "Speech recognition",
|
||||
"admin.audio.voiceModeSttBrowser": "Browser",
|
||||
"admin.audio.voiceModeSttProvider": "Configured STT",
|
||||
"admin.audio.voiceModeBrowserSttHint": "Uses browser speech recognition, then stores the audio and transcript locally for the voice data flywheel.",
|
||||
"admin.audio.voiceModeProviderSttHint": "Sends voice-mode audio through the configured STT provider and stores the result locally.",
|
||||
"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",
|
||||
@@ -553,6 +571,14 @@
|
||||
"chat.edit.tool": "工具",
|
||||
"chat.edit.item": "項目",
|
||||
"chat.dictate.unsupported": "此瀏覽器不支援語音辨識。",
|
||||
"chat.voiceModeOn": "Voice mode on",
|
||||
"chat.voiceListening": "Listening...",
|
||||
"chat.voiceWaiting": "Waiting for response...",
|
||||
"chat.voiceProviderSttFallback": "Configured STT failed. Used browser transcript.",
|
||||
"chat.voiceProviderSttNoAudio": "Configured STT needs microphone audio, but no voice-mode recording was captured.",
|
||||
"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": "建立金鑰失敗",
|
||||
|
||||
@@ -14,20 +14,52 @@ export const QUALITY_BITRATES: Record<RecordingQuality, number> = {
|
||||
|
||||
export const voiceMemosEnabled = writable<boolean>(false);
|
||||
export const transcribeEnabled = writable<boolean>(true);
|
||||
export const sttConfigured = writable<boolean>(false);
|
||||
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 voiceModeSttMode = writable<'browser' | 'provider'>('browser');
|
||||
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;
|
||||
stt_configured: boolean;
|
||||
recording_quality: string;
|
||||
tts_enabled: boolean;
|
||||
tts_configured: boolean;
|
||||
tts_voice: string;
|
||||
tts_format: string;
|
||||
voice_mode_stt_mode?: string;
|
||||
}>('/api/audio/state');
|
||||
voiceMemosEnabled.set(data.voice_memos_enabled === true);
|
||||
transcribeEnabled.set(data.transcribe_enabled !== false);
|
||||
sttConfigured.set(data.stt_configured === true);
|
||||
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');
|
||||
voiceModeSttMode.set(data.voice_mode_stt_mode === 'provider' ? 'provider' : 'browser');
|
||||
} catch {
|
||||
voiceMemosEnabled.set(false);
|
||||
sttConfigured.set(false);
|
||||
ttsEnabled.set(false);
|
||||
ttsConfigured.set(false);
|
||||
voiceModeSttMode.set('browser');
|
||||
}
|
||||
}
|
||||
@@ -30,28 +30,29 @@ let _status = $state<GitStatus | null>(null);
|
||||
let _loading = $state(false);
|
||||
let _currentRoot = '';
|
||||
let _fetchPromise: Promise<void> | null = null;
|
||||
let _fetchSeq = 0;
|
||||
|
||||
async function _doFetch(root: string) {
|
||||
async function _doFetch(root: string, seq: number) {
|
||||
if (!root) {
|
||||
_status = null;
|
||||
return;
|
||||
}
|
||||
_loading = true;
|
||||
try {
|
||||
const data = (await fetchJSON(
|
||||
`/api/git/status?root=${encodeURIComponent(root)}`
|
||||
)) as GitStatus;
|
||||
const data = (await fetchJSON(`/api/git/status?root=${encodeURIComponent(root)}`)) as GitStatus;
|
||||
// Only apply if root hasn't changed while we were fetching
|
||||
if (root === _currentRoot) {
|
||||
if (root === _currentRoot && seq === _fetchSeq) {
|
||||
_status = data;
|
||||
}
|
||||
} catch {
|
||||
if (root === _currentRoot) {
|
||||
if (root === _currentRoot && seq === _fetchSeq) {
|
||||
_status = null;
|
||||
}
|
||||
} finally {
|
||||
_loading = false;
|
||||
_fetchPromise = null;
|
||||
if (seq === _fetchSeq) {
|
||||
_loading = false;
|
||||
_fetchPromise = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -71,7 +72,8 @@ export const gitStatusStore = {
|
||||
if (root === _currentRoot) return;
|
||||
_currentRoot = root;
|
||||
_status = null;
|
||||
this.refresh();
|
||||
_fetchPromise = null;
|
||||
this.refresh({ force: true });
|
||||
},
|
||||
|
||||
/** Clear all state (no workspace). */
|
||||
@@ -80,16 +82,18 @@ export const gitStatusStore = {
|
||||
_status = null;
|
||||
_loading = false;
|
||||
_fetchPromise = null;
|
||||
_fetchSeq++;
|
||||
},
|
||||
|
||||
/**
|
||||
* Refresh git status from the server.
|
||||
* Concurrent calls are coalesced into a single fetch.
|
||||
*/
|
||||
refresh() {
|
||||
refresh({ force = false }: { force?: boolean } = {}) {
|
||||
if (!_currentRoot) return;
|
||||
if (!_fetchPromise) {
|
||||
_fetchPromise = _doFetch(_currentRoot);
|
||||
if (!_fetchPromise || force) {
|
||||
const seq = ++_fetchSeq;
|
||||
_fetchPromise = _doFetch(_currentRoot, seq);
|
||||
}
|
||||
return _fetchPromise;
|
||||
}
|
||||
|
||||
@@ -331,7 +331,7 @@
|
||||
<div
|
||||
id="main-col"
|
||||
class="flex flex-col flex-1 min-w-0 min-h-0 overflow-hidden"
|
||||
style="padding-bottom: var(--keyboard-inset-bottom, 0px);"
|
||||
style="padding-top: env(safe-area-inset-top, 0px); padding-bottom: var(--keyboard-inset-bottom, 0px);"
|
||||
>
|
||||
{#if !$currentWorkspace && $page.url.pathname === '/'}
|
||||
<Bar />
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 6.3 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 8.2 KiB After Width: | Height: | Size: 6.9 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 29 KiB After Width: | Height: | Size: 21 KiB |
+28
-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."""
|
||||
@@ -367,6 +376,11 @@ CONFIG_KEY_CHAT_MODELS = "chat.models"
|
||||
async def get_model_config(request: Request):
|
||||
"""Get per-model config and full model list (including inactive) for the admin Models tab."""
|
||||
require_admin(request)
|
||||
return await _build_model_config(request)
|
||||
|
||||
|
||||
async def _build_model_config(request: Request):
|
||||
"""Build model configuration response for the admin Models tab."""
|
||||
config = await Config.get(CONFIG_KEY_CHAT_MODELS) or {}
|
||||
|
||||
# Build full model list from all enabled connections (same as chat.py
|
||||
@@ -392,6 +406,14 @@ async def get_model_config(request: Request):
|
||||
return {"config": config, "models": models}
|
||||
|
||||
|
||||
@router.post("/models/refresh")
|
||||
async def refresh_model_list(request: Request):
|
||||
"""Clear cached provider-discovered models and return the refreshed model list."""
|
||||
require_admin(request)
|
||||
invalidate_model_cache(request.app.state)
|
||||
return await _build_model_config(request)
|
||||
|
||||
|
||||
class UpdateModelConfigRequest(BaseModel):
|
||||
is_active: Optional[bool] = None
|
||||
params: Optional[dict] = None
|
||||
|
||||
+326
-6
@@ -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,24 @@ 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
|
||||
stt_configured: bool
|
||||
recording_quality: str
|
||||
tts_enabled: bool
|
||||
tts_configured: bool
|
||||
tts_voice: str
|
||||
tts_format: str
|
||||
voice_mode_stt_mode: 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 +67,65 @@ def _get_user(request: Request) -> str:
|
||||
return auth.user_id
|
||||
|
||||
|
||||
def _workspace_audio_cache_dir(workspace: str | None, kind: str) -> Path | None:
|
||||
# Voice samples are project context, so they live under the workspace .cptr
|
||||
# folder and move with the project. That keeps STT and TTS artifacts available
|
||||
# for reuse, debugging, and the local data flywheel while ensure_cptr_gitignored
|
||||
# keeps them out of git.
|
||||
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:
|
||||
# The key includes the provider settings plus the exact audio bytes or text.
|
||||
# Without those inputs, a model, voice, or format change could accidentally reuse
|
||||
# the wrong artifact. The JSON file beside the audio explains what the hash means.
|
||||
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 +190,30 @@ 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,
|
||||
stt_configured=bool(stt_key),
|
||||
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"),
|
||||
voice_mode_stt_mode=str((await Config.get("audio.voice_mode_stt_mode")) or "browser"),
|
||||
)
|
||||
|
||||
|
||||
async def _transcribe_chunk(
|
||||
data: bytes,
|
||||
filename: str,
|
||||
@@ -130,7 +235,14 @@ 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),
|
||||
text: str | None = Form(None),
|
||||
source: str | None = Form(None),
|
||||
language: 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
|
||||
@@ -138,6 +250,53 @@ async def transcribe(file: UploadFile, request: Request):
|
||||
"""
|
||||
_get_user(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
|
||||
provided_text = (text or "").strip()
|
||||
|
||||
if provided_text:
|
||||
# Browser speech recognition already produced text, so there is no provider
|
||||
# call to cache. We still store the captured audio and transcript in the
|
||||
# normal STT folder so browser mode and provider mode produce the same kind
|
||||
# of data flywheel sample without paying for a second transcription.
|
||||
if not raw_data:
|
||||
raise HTTPException(400, "Speech-to-text capture requires non-empty audio.")
|
||||
if cache_dir:
|
||||
audio_ext = _audio_extension(filename, content_type)
|
||||
key = _cache_key(
|
||||
{
|
||||
"type": "stt",
|
||||
"source": source or "browser_speech_recognition",
|
||||
"text": provided_text,
|
||||
"filename": filename,
|
||||
"content_type": content_type,
|
||||
"language": language or "",
|
||||
},
|
||||
raw_data,
|
||||
)
|
||||
cache_json_path = cache_dir / f"{key}.json"
|
||||
cache_audio_path = cache_dir / f"{key}{audio_ext}"
|
||||
if not cache_json_path.exists() or not cache_audio_path.exists():
|
||||
_write_bytes_atomic(cache_audio_path, raw_data)
|
||||
_write_json_atomic(
|
||||
cache_json_path,
|
||||
{
|
||||
"type": "stt",
|
||||
"source": source or "browser_speech_recognition",
|
||||
"transcription_source": "browser_speech_recognition",
|
||||
"text": provided_text,
|
||||
"audio_file": cache_audio_path.name,
|
||||
"filename": filename,
|
||||
"content_type": content_type,
|
||||
"language": language,
|
||||
},
|
||||
)
|
||||
return {"text": provided_text, "cached": True}
|
||||
|
||||
api_key_encrypted = await Config.get("audio.stt_api_key")
|
||||
if not api_key_encrypted:
|
||||
raise HTTPException(
|
||||
@@ -149,14 +308,49 @@ async def transcribe(file: UploadFile, request: Request):
|
||||
base_url = (await Config.get("audio.stt_base_url")) or "https://api.openai.com/v1"
|
||||
model = (await Config.get("audio.stt_model")) or "whisper-1"
|
||||
|
||||
raw_data = await file.read()
|
||||
filename = file.filename or "audio.webm"
|
||||
content_type = file.content_type or "audio/webm"
|
||||
if cache_dir:
|
||||
# Provider STT is cacheable because identical audio with the same provider
|
||||
# settings should produce the same transcript. Keeping the original audio
|
||||
# beside the JSON makes the sample reusable for audits, replay, and future
|
||||
# data flywheel work instead of being a one-off API response.
|
||||
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 +384,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 +427,114 @@ 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:
|
||||
# TTS is especially worth caching because short phrases repeat often across
|
||||
# messages and replays. The key uses provider, model, voice, format, and exact
|
||||
# text so a phrase like "Hi." can be reused safely without new spend, while
|
||||
# the neighboring JSON records why that audio file exists.
|
||||
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.
|
||||
|
||||
@@ -20,6 +20,7 @@ from cptr.utils.git import (
|
||||
delete_branch,
|
||||
diff,
|
||||
discard,
|
||||
fetch,
|
||||
is_repo,
|
||||
log,
|
||||
pull,
|
||||
@@ -243,6 +244,15 @@ async def git_pull(body: RootRequest):
|
||||
_handle_git_error(e)
|
||||
|
||||
|
||||
@router.post("/fetch")
|
||||
async def git_fetch(body: RootRequest):
|
||||
"""Fetch from remote without merging."""
|
||||
try:
|
||||
return await fetch(body.root)
|
||||
except GitError as e:
|
||||
_handle_git_error(e)
|
||||
|
||||
|
||||
@router.post("/push")
|
||||
async def git_push(body: PushRequest):
|
||||
"""Push to remote."""
|
||||
|
||||
+175
-43
@@ -1,7 +1,7 @@
|
||||
"""Provider streaming and completion functions: raw httpx.
|
||||
|
||||
Each streaming function takes a ChatCompletionForm + url + key.
|
||||
All yield normalized events: text_delta, tool_call, usage, done.
|
||||
All yield normalized events: text_delta, output, tool_call, usage, done.
|
||||
|
||||
chat_completion() provides a simple non-streaming call for lightweight tasks
|
||||
(title generation, summarization, etc.).
|
||||
@@ -10,6 +10,7 @@ chat_completion() provides a simple non-streaming call for lightweight tasks
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import copy
|
||||
import json
|
||||
import logging
|
||||
import uuid
|
||||
@@ -24,10 +25,21 @@ from cptr.env import (
|
||||
STREAM_READ_TIMEOUT_SECONDS,
|
||||
STREAM_WRITE_TIMEOUT_SECONDS,
|
||||
)
|
||||
from cptr.utils.logger import log_upstream_request
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _reasoning_output_item(text: str = "", *, status: str = "in_progress") -> dict:
|
||||
"""Create a Responses-style reasoning output item."""
|
||||
return {
|
||||
"type": "reasoning",
|
||||
"id": f"rs_{uuid.uuid4().hex}",
|
||||
"status": status,
|
||||
"content": [{"type": "text", "text": text}],
|
||||
}
|
||||
|
||||
|
||||
def _openrouter_headers(url: str) -> dict[str, str]:
|
||||
"""Return OpenRouter app-info headers when the URL is an OpenRouter endpoint."""
|
||||
if "openrouter.ai" in url:
|
||||
@@ -93,6 +105,13 @@ async def chat_completion(
|
||||
body["system"] = system
|
||||
if request_params:
|
||||
body.update(request_params)
|
||||
log_upstream_request(
|
||||
provider="anthropic",
|
||||
endpoint=f"{base_url}/messages",
|
||||
model=model,
|
||||
api_type="messages",
|
||||
body=body,
|
||||
)
|
||||
resp = await client.post(
|
||||
f"{base_url}/messages",
|
||||
json=body,
|
||||
@@ -113,6 +132,13 @@ async def chat_completion(
|
||||
body_r["instructions"] = system
|
||||
if request_params:
|
||||
body_r.update(request_params)
|
||||
log_upstream_request(
|
||||
provider=provider,
|
||||
endpoint=f"{base_url}/responses",
|
||||
model=model,
|
||||
api_type="responses",
|
||||
body=body_r,
|
||||
)
|
||||
resp = await client.post(
|
||||
f"{base_url}/responses",
|
||||
json=body_r,
|
||||
@@ -130,6 +156,13 @@ async def chat_completion(
|
||||
}
|
||||
if request_params:
|
||||
body_cc.update(request_params)
|
||||
log_upstream_request(
|
||||
provider=provider,
|
||||
endpoint=f"{base_url}/chat/completions",
|
||||
model=model,
|
||||
api_type="chat_completions",
|
||||
body=body_cc,
|
||||
)
|
||||
resp = await client.post(
|
||||
f"{base_url}/chat/completions",
|
||||
json=body_cc,
|
||||
@@ -169,7 +202,7 @@ def _to_anthropic_messages(messages: list[dict]) -> list[dict]:
|
||||
role = m["role"]
|
||||
if role == "system":
|
||||
continue # system goes in body.system
|
||||
|
||||
|
||||
content = m.get("content", "")
|
||||
if isinstance(content, list):
|
||||
formatted_content = []
|
||||
@@ -177,14 +210,16 @@ def _to_anthropic_messages(messages: list[dict]) -> list[dict]:
|
||||
if block.get("type") == "text":
|
||||
formatted_content.append({"type": "text", "text": block.get("text", "")})
|
||||
elif block.get("type") == "image":
|
||||
formatted_content.append({
|
||||
"type": "image",
|
||||
"source": {
|
||||
"type": "base64",
|
||||
"media_type": block.get("media_type", "image/jpeg"),
|
||||
"data": block.get("base64", "")
|
||||
formatted_content.append(
|
||||
{
|
||||
"type": "image",
|
||||
"source": {
|
||||
"type": "base64",
|
||||
"media_type": block.get("media_type", "image/jpeg"),
|
||||
"data": block.get("base64", ""),
|
||||
},
|
||||
}
|
||||
})
|
||||
)
|
||||
content = formatted_content
|
||||
if role == "tool":
|
||||
# tool result → Anthropic tool_result block
|
||||
@@ -196,14 +231,16 @@ def _to_anthropic_messages(messages: list[dict]) -> list[dict]:
|
||||
if block.get("type") == "text":
|
||||
tool_content.append({"type": "text", "text": block.get("text", "")})
|
||||
elif block.get("type") == "image":
|
||||
tool_content.append({
|
||||
"type": "image",
|
||||
"source": {
|
||||
"type": "base64",
|
||||
"media_type": block.get("media_type", "image/jpeg"),
|
||||
"data": block.get("base64", ""),
|
||||
tool_content.append(
|
||||
{
|
||||
"type": "image",
|
||||
"source": {
|
||||
"type": "base64",
|
||||
"media_type": block.get("media_type", "image/jpeg"),
|
||||
"data": block.get("base64", ""),
|
||||
},
|
||||
}
|
||||
})
|
||||
)
|
||||
else:
|
||||
tool_content = content
|
||||
result.append(
|
||||
@@ -262,6 +299,13 @@ async def stream_anthropic(
|
||||
body.update(request_params)
|
||||
# Remove None values
|
||||
body = {k: v for k, v in body.items() if v is not None}
|
||||
log_upstream_request(
|
||||
provider="anthropic",
|
||||
endpoint=f"{url}/messages",
|
||||
model=form_data.model,
|
||||
api_type="messages",
|
||||
body=body,
|
||||
)
|
||||
headers = {"x-api-key": key, "anthropic-version": "2023-06-01", **_openrouter_headers(url)}
|
||||
|
||||
emitted = False
|
||||
@@ -286,7 +330,10 @@ async def stream_anthropic(
|
||||
msg_usage = event.get("message", {}).get("usage", {})
|
||||
if msg_usage:
|
||||
usage_data["input_tokens"] = msg_usage.get("input_tokens", 0)
|
||||
for cache_key in ("cache_read_input_tokens", "cache_creation_input_tokens"):
|
||||
for cache_key in (
|
||||
"cache_read_input_tokens",
|
||||
"cache_creation_input_tokens",
|
||||
):
|
||||
if msg_usage.get(cache_key):
|
||||
usage_data[cache_key] = msg_usage[cache_key]
|
||||
|
||||
@@ -342,11 +389,27 @@ async def stream_anthropic(
|
||||
# ── OpenAI Chat Completions ──────────────────────────────────
|
||||
|
||||
|
||||
def _reasoning_items_to_content(items: list[dict]) -> str:
|
||||
"""Convert Responses API reasoning items to a reasoning_content string.
|
||||
|
||||
Reasoning items may expose text in content or summary blocks. We extract
|
||||
those text blocks and join them for Chat Completions-compatible providers.
|
||||
"""
|
||||
texts: list[str] = []
|
||||
for item in items:
|
||||
blocks = item.get("content") or item.get("summary") or []
|
||||
for block in blocks:
|
||||
if isinstance(block, dict) and block.get("type") == "text" and block.get("text"):
|
||||
texts.append(block["text"])
|
||||
return "\n".join(texts)
|
||||
|
||||
|
||||
def _to_openai_messages(messages: list[dict], instructions: str) -> list[dict]:
|
||||
"""Canonical messages → OpenAI Chat Completions format.
|
||||
|
||||
Strips non-standard fields (reasoning_items, fc_id in tool_calls)
|
||||
that are used internally but would cause 400 errors from OpenAI.
|
||||
Converts reasoning_items (Responses API format) to reasoning_content
|
||||
(Chat Completions format) for providers like Kimi that require it.
|
||||
Strips other non-standard fields (fc_id in tool_calls).
|
||||
"""
|
||||
result = []
|
||||
if instructions:
|
||||
@@ -366,24 +429,28 @@ def _to_openai_messages(messages: list[dict], instructions: str) -> list[dict]:
|
||||
formatted_content.append(block)
|
||||
elif block.get("type") == "image":
|
||||
data_uri = f"data:{block.get('media_type', 'image/jpeg')};base64,{block.get('base64', '')}"
|
||||
formatted_content.append({
|
||||
"type": "image_url",
|
||||
"image_url": {"url": data_uri}
|
||||
})
|
||||
formatted_content.append({"type": "image_url", "image_url": {"url": data_uri}})
|
||||
new_m = dict(m)
|
||||
new_m["content"] = formatted_content
|
||||
# Strip non-standard fields
|
||||
new_m.pop("reasoning_items", None)
|
||||
# Convert reasoning_items → reasoning_content for round-tripping
|
||||
ri = new_m.pop("reasoning_items", None)
|
||||
if ri and new_m.get("role") == "assistant":
|
||||
rc = _reasoning_items_to_content(ri)
|
||||
if rc:
|
||||
new_m["reasoning_content"] = rc
|
||||
result.append(new_m)
|
||||
else:
|
||||
out = dict(m)
|
||||
# Strip non-standard fields that are only for Responses API
|
||||
out.pop("reasoning_items", None)
|
||||
# Convert reasoning_items → reasoning_content for round-tripping
|
||||
ri = out.pop("reasoning_items", None)
|
||||
if ri and out.get("role") == "assistant":
|
||||
rc = _reasoning_items_to_content(ri)
|
||||
if rc:
|
||||
out["reasoning_content"] = rc
|
||||
# Clean tool_calls: remove fc_id which is Responses-API-only
|
||||
if "tool_calls" in out:
|
||||
out["tool_calls"] = [
|
||||
{k: v for k, v in tc.items() if k != "fc_id"}
|
||||
for tc in out["tool_calls"]
|
||||
{k: v for k, v in tc.items() if k != "fc_id"} for tc in out["tool_calls"]
|
||||
]
|
||||
result.append(out)
|
||||
return result
|
||||
@@ -414,6 +481,13 @@ async def stream_openai_completions(
|
||||
body["tools"] = tools
|
||||
if request_params:
|
||||
body.update(request_params)
|
||||
log_upstream_request(
|
||||
provider="openai",
|
||||
endpoint=f"{url}/chat/completions",
|
||||
model=form_data.model,
|
||||
api_type="chat_completions",
|
||||
body=body,
|
||||
)
|
||||
headers = {"Authorization": f"Bearer {key}", **_openrouter_headers(url)}
|
||||
|
||||
emitted = False
|
||||
@@ -431,9 +505,25 @@ async def stream_openai_completions(
|
||||
logger.info("[stream] openai completions status=%s", resp.status_code)
|
||||
if resp.status_code >= 400:
|
||||
error_body = await resp.aread()
|
||||
logger.error("[stream] openai completions error body: %s", error_body.decode(errors="replace"))
|
||||
logger.error(
|
||||
"[stream] openai completions error body: %s",
|
||||
error_body.decode(errors="replace"),
|
||||
)
|
||||
resp.raise_for_status()
|
||||
tool_calls: dict[int, dict] = {}
|
||||
reasoning_buffer = "" # Accumulate reasoning_content deltas (Kimi, DeepSeek)
|
||||
reasoning_item: dict | None = None
|
||||
|
||||
def complete_reasoning_item() -> dict | None:
|
||||
nonlocal reasoning_buffer, reasoning_item
|
||||
if reasoning_item is None:
|
||||
return None
|
||||
reasoning_item["status"] = "completed"
|
||||
item = copy.deepcopy(reasoning_item)
|
||||
reasoning_item = None
|
||||
reasoning_buffer = ""
|
||||
return item
|
||||
|
||||
async for line in resp.aiter_lines():
|
||||
if not line.startswith("data: ") or line == "data: [DONE]":
|
||||
continue
|
||||
@@ -441,10 +531,29 @@ async def stream_openai_completions(
|
||||
choices = chunk.get("choices", [])
|
||||
delta = choices[0].get("delta", {}) if choices else {}
|
||||
|
||||
# Capture reasoning_content from providers like Kimi / DeepSeek
|
||||
if delta.get("reasoning_content"):
|
||||
reasoning_buffer += delta["reasoning_content"]
|
||||
if reasoning_item is None:
|
||||
reasoning_item = _reasoning_output_item()
|
||||
reasoning_item["content"][0]["text"] = reasoning_buffer
|
||||
emitted = True
|
||||
yield {"type": "output", "item": copy.deepcopy(reasoning_item)}
|
||||
|
||||
if delta.get("content"):
|
||||
item = complete_reasoning_item()
|
||||
if item is not None:
|
||||
emitted = True
|
||||
yield {"type": "output", "item": item}
|
||||
emitted = True
|
||||
yield {"type": "text_delta", "content": delta["content"]}
|
||||
|
||||
if delta.get("tool_calls"):
|
||||
item = complete_reasoning_item()
|
||||
if item is not None:
|
||||
emitted = True
|
||||
yield {"type": "output", "item": item}
|
||||
|
||||
for tc in delta.get("tool_calls", []):
|
||||
idx = tc["index"]
|
||||
if idx not in tool_calls:
|
||||
@@ -456,6 +565,11 @@ async def stream_openai_completions(
|
||||
tool_calls[idx]["arguments_json"] += tc["function"].get("arguments", "")
|
||||
|
||||
if choices and choices[0].get("finish_reason") == "tool_calls":
|
||||
# Emit accumulated reasoning before tool calls
|
||||
item = complete_reasoning_item()
|
||||
if item is not None:
|
||||
emitted = True
|
||||
yield {"type": "output", "item": item}
|
||||
for tc in tool_calls.values():
|
||||
emitted = True
|
||||
yield {
|
||||
@@ -466,6 +580,12 @@ async def stream_openai_completions(
|
||||
}
|
||||
|
||||
if chunk.get("usage"):
|
||||
# Emit any remaining reasoning BEFORE usage
|
||||
# (usage triggers immediate save+return in chat_task)
|
||||
item = complete_reasoning_item()
|
||||
if item is not None:
|
||||
emitted = True
|
||||
yield {"type": "output", "item": item}
|
||||
raw = chunk["usage"]
|
||||
emitted = True
|
||||
yield {
|
||||
@@ -474,6 +594,11 @@ async def stream_openai_completions(
|
||||
"output_tokens": raw.get("completion_tokens", 0),
|
||||
}
|
||||
|
||||
# Emit any remaining reasoning if no usage event was received
|
||||
item = complete_reasoning_item()
|
||||
if item is not None:
|
||||
emitted = True
|
||||
yield {"type": "output", "item": item}
|
||||
emitted = True
|
||||
yield {"type": "done"}
|
||||
return
|
||||
@@ -497,11 +622,7 @@ def _to_responses_input(messages: list[dict], instructions: str) -> list[dict]:
|
||||
# Pre-collect all tool result call_ids so we can validate function_calls
|
||||
# have matching outputs. This prevents orphaned function_calls (from
|
||||
# crashes, data corruption, etc.) from permanently breaking the chat.
|
||||
tool_result_ids = {
|
||||
m.get("tool_call_id", "")
|
||||
for m in messages
|
||||
if m.get("role") == "tool"
|
||||
}
|
||||
tool_result_ids = {m.get("tool_call_id", "") for m in messages if m.get("role") == "tool"}
|
||||
|
||||
items = []
|
||||
for m in messages:
|
||||
@@ -561,13 +682,12 @@ def _to_responses_input(messages: list[dict], instructions: str) -> list[dict]:
|
||||
formatted_content = []
|
||||
for block in content:
|
||||
if block.get("type") == "text":
|
||||
formatted_content.append({"type": "input_text", "text": block.get("text", "")})
|
||||
formatted_content.append(
|
||||
{"type": "input_text", "text": block.get("text", "")}
|
||||
)
|
||||
elif block.get("type") == "image":
|
||||
data_uri = f"data:{block.get('media_type', 'image/jpeg')};base64,{block.get('base64', '')}"
|
||||
formatted_content.append({
|
||||
"type": "input_image",
|
||||
"image_url": data_uri
|
||||
})
|
||||
formatted_content.append({"type": "input_image", "image_url": data_uri})
|
||||
items.append({"type": "message", "role": role, "content": formatted_content})
|
||||
else:
|
||||
items.append({"type": "message", "role": role, "content": content})
|
||||
@@ -598,6 +718,13 @@ async def stream_openai_responses(
|
||||
body["tools"] = tools
|
||||
if request_params:
|
||||
body.update(request_params)
|
||||
log_upstream_request(
|
||||
provider="openai",
|
||||
endpoint=f"{url}/responses",
|
||||
model=form_data.model,
|
||||
api_type="responses",
|
||||
body=body,
|
||||
)
|
||||
headers = {"Authorization": f"Bearer {key}", **_openrouter_headers(url)}
|
||||
|
||||
emitted = False
|
||||
@@ -606,7 +733,8 @@ async def stream_openai_responses(
|
||||
async with httpx.AsyncClient(timeout=_STREAM_TIMEOUT) as client:
|
||||
logger.info(
|
||||
"[stream] openai responses POST %s/responses model=%s input_items=%d types=%s",
|
||||
url, form_data.model,
|
||||
url,
|
||||
form_data.model,
|
||||
len(body.get("input", [])),
|
||||
[i.get("type", i.get("role", "?")) for i in body.get("input", [])],
|
||||
)
|
||||
@@ -616,7 +744,10 @@ async def stream_openai_responses(
|
||||
logger.info("[stream] openai responses status=%s", resp.status_code)
|
||||
if resp.status_code >= 400:
|
||||
error_body = await resp.aread()
|
||||
logger.error("[stream] openai responses error body: %s", error_body.decode(errors="replace"))
|
||||
logger.error(
|
||||
"[stream] openai responses error body: %s",
|
||||
error_body.decode(errors="replace"),
|
||||
)
|
||||
resp.raise_for_status()
|
||||
async for line in resp.aiter_lines():
|
||||
if not line.startswith("data: "):
|
||||
@@ -644,8 +775,9 @@ async def stream_openai_responses(
|
||||
}
|
||||
elif item["type"] == "reasoning":
|
||||
# Reasoning items must be round-tripped for reasoning models
|
||||
emitted = True
|
||||
yield {
|
||||
"type": "reasoning",
|
||||
"type": "output",
|
||||
"item": item,
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,169 @@
|
||||
"""File-based HTTP audit logging middleware."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import re
|
||||
import uuid
|
||||
from enum import Enum
|
||||
from typing import Any, Awaitable, Callable
|
||||
|
||||
from starlette.requests import Request
|
||||
|
||||
from cptr.env import AUDIT_LOG_LEVEL, AUDIT_MAX_BODY_SIZE
|
||||
from cptr.utils.logger import audit_logger
|
||||
|
||||
|
||||
class AuditLevel(str, Enum):
|
||||
NONE = "NONE"
|
||||
METADATA = "METADATA"
|
||||
REQUEST = "REQUEST"
|
||||
REQUEST_RESPONSE = "REQUEST_RESPONSE"
|
||||
|
||||
|
||||
_SENSITIVE_KEYS = {"password", "api_key", "token", "authorization", "cookie", "secret"}
|
||||
|
||||
|
||||
def _redact(value: Any) -> Any:
|
||||
if isinstance(value, dict):
|
||||
return {
|
||||
k: "********" if k.lower() in _SENSITIVE_KEYS else _redact(v)
|
||||
for k, v in value.items()
|
||||
}
|
||||
if isinstance(value, list):
|
||||
return [_redact(v) for v in value]
|
||||
return value
|
||||
|
||||
|
||||
def _decode_body(body: bytearray) -> str | None:
|
||||
if not body:
|
||||
return None
|
||||
text = body.decode("utf-8", errors="replace")
|
||||
try:
|
||||
return json.dumps(_redact(json.loads(text)), ensure_ascii=False, default=str)
|
||||
except Exception:
|
||||
for key in _SENSITIVE_KEYS:
|
||||
text = re.sub(
|
||||
rf'("{re.escape(key)}"\s*:\s*")[^"]*(")',
|
||||
r"\1********\2",
|
||||
text,
|
||||
flags=re.IGNORECASE,
|
||||
)
|
||||
return text
|
||||
|
||||
|
||||
class AuditContext:
|
||||
def __init__(self, max_body_size: int) -> None:
|
||||
self.request_body = bytearray()
|
||||
self.response_body = bytearray()
|
||||
self.max_body_size = max_body_size
|
||||
self.status_code: int | None = None
|
||||
|
||||
def add_request(self, chunk: bytes) -> None:
|
||||
self._add(self.request_body, chunk)
|
||||
|
||||
def add_response(self, chunk: bytes) -> None:
|
||||
self._add(self.response_body, chunk)
|
||||
|
||||
def _add(self, target: bytearray, chunk: bytes) -> None:
|
||||
if not chunk or len(target) >= self.max_body_size:
|
||||
return
|
||||
target.extend(chunk[: self.max_body_size - len(target)])
|
||||
|
||||
|
||||
class AuditLoggingMiddleware:
|
||||
"""Capture safe HTTP audit entries to the audit Loguru sink."""
|
||||
|
||||
AUDITED_METHODS = {"POST", "PUT", "PATCH", "DELETE"}
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
app,
|
||||
*,
|
||||
audit_level: AuditLevel,
|
||||
excluded_paths: list[str] | None = None,
|
||||
max_body_size: int = AUDIT_MAX_BODY_SIZE,
|
||||
) -> None:
|
||||
self.app = app
|
||||
self.audit_level = audit_level
|
||||
self.excluded_paths = excluded_paths or []
|
||||
self.max_body_size = max_body_size
|
||||
|
||||
async def __call__(
|
||||
self,
|
||||
scope: dict[str, Any],
|
||||
receive: Callable[[], Awaitable[dict[str, Any]]],
|
||||
send: Callable[[dict[str, Any]], Awaitable[None]],
|
||||
) -> None:
|
||||
if scope.get("type") != "http":
|
||||
await self.app(scope, receive, send)
|
||||
return
|
||||
|
||||
request = Request(scope)
|
||||
if self._should_skip(request):
|
||||
await self.app(scope, receive, send)
|
||||
return
|
||||
|
||||
context = AuditContext(self.max_body_size)
|
||||
|
||||
async def receive_wrapper() -> dict[str, Any]:
|
||||
message = await receive()
|
||||
if self.audit_level in (AuditLevel.REQUEST, AuditLevel.REQUEST_RESPONSE):
|
||||
if message.get("type") == "http.request":
|
||||
context.add_request(message.get("body", b""))
|
||||
return message
|
||||
|
||||
async def send_wrapper(message: dict[str, Any]) -> None:
|
||||
if message.get("type") == "http.response.start":
|
||||
context.status_code = message.get("status")
|
||||
elif (
|
||||
self.audit_level == AuditLevel.REQUEST_RESPONSE
|
||||
and message.get("type") == "http.response.body"
|
||||
):
|
||||
context.add_response(message.get("body", b""))
|
||||
await send(message)
|
||||
|
||||
try:
|
||||
await self.app(scope, receive_wrapper, send_wrapper)
|
||||
finally:
|
||||
self._write_entry(request, context)
|
||||
|
||||
def _should_skip(self, request: Request) -> bool:
|
||||
if AUDIT_LOG_LEVEL == "NONE" or request.method not in self.AUDITED_METHODS:
|
||||
return True
|
||||
path = request.url.path
|
||||
return any(path.startswith(excluded) for excluded in self.excluded_paths)
|
||||
|
||||
def _write_entry(self, request: Request, context: AuditContext) -> None:
|
||||
auth = getattr(request.state, "auth", None)
|
||||
user = {}
|
||||
if auth is not None:
|
||||
user = {
|
||||
"id": getattr(auth, "user_id", None),
|
||||
"username": getattr(auth, "username", None),
|
||||
"role": getattr(auth, "role", None),
|
||||
}
|
||||
|
||||
audit_logger().bind(
|
||||
id=str(uuid.uuid4()),
|
||||
audit_level=self.audit_level.value,
|
||||
user=user,
|
||||
method=request.method,
|
||||
path=request.url.path,
|
||||
status_code=context.status_code,
|
||||
source_ip=request.client.host if request.client else None,
|
||||
user_agent=request.headers.get("user-agent"),
|
||||
request_body=_decode_body(context.request_body)
|
||||
if self.audit_level in (AuditLevel.REQUEST, AuditLevel.REQUEST_RESPONSE)
|
||||
else None,
|
||||
response_body=_decode_body(context.response_body)
|
||||
if self.audit_level == AuditLevel.REQUEST_RESPONSE
|
||||
else None,
|
||||
).info("")
|
||||
|
||||
|
||||
def get_audit_level() -> AuditLevel:
|
||||
try:
|
||||
return AuditLevel(AUDIT_LOG_LEVEL)
|
||||
except ValueError:
|
||||
return AuditLevel.NONE
|
||||
+190
-63
@@ -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
|
||||
@@ -34,7 +37,8 @@ logger = logging.getLogger(__name__)
|
||||
|
||||
PLAN_MODE_PROMPT = (
|
||||
"[Plan Mode] Research the codebase with read-only tools, then present your plan "
|
||||
"using create_artifact. Wait for approval before coding."
|
||||
"using create_artifact. Then wait for an explicit approval message before using "
|
||||
"tools or implementing."
|
||||
)
|
||||
|
||||
# ── Task registry ───────────────────────────────────────────
|
||||
@@ -316,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 = (
|
||||
@@ -327,7 +327,8 @@ DEFAULT_SYSTEM_PROMPT = (
|
||||
"You have access to tools to read, search, and modify files in the workspace. "
|
||||
"Use them to help the user with their coding tasks.\n\n"
|
||||
"For complex tasks, create an implementation plan first using "
|
||||
"create_artifact, then wait for approval before coding."
|
||||
"create_artifact. Then wait for an explicit approval message before using "
|
||||
"tools or implementing."
|
||||
"\n\n{{INSTRUCTIONS}}"
|
||||
"\n\n{{SKILLS}}"
|
||||
"\n\nWorkspace: {{WORKSPACE_NAME}}"
|
||||
@@ -436,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 ────────────────────────────────────────
|
||||
|
||||
|
||||
@@ -612,9 +631,7 @@ async def _load_message_history(chat_id: str, message_id: str) -> tuple[list[dic
|
||||
# This is needed to filter out orphaned function_calls
|
||||
# (e.g. from crashes, partial persistence, or data corruption).
|
||||
output_call_ids = {
|
||||
item["call_id"]
|
||||
for item in m.output
|
||||
if item.get("type") == "function_call_output"
|
||||
item["call_id"] for item in m.output if item.get("type") == "function_call_output"
|
||||
}
|
||||
|
||||
# ── Group output items into per-iteration turns ──
|
||||
@@ -671,10 +688,7 @@ async def _load_message_history(chat_id: str, message_id: str) -> tuple[list[dic
|
||||
for ti, turn in enumerate(turns):
|
||||
# Filter calls to only those with matching outputs
|
||||
turn_output_ids = {o["call_id"] for o in turn["outputs"]}
|
||||
matched_calls = [
|
||||
tc for tc in turn["calls"]
|
||||
if tc["id"] in turn_output_ids
|
||||
]
|
||||
matched_calls = [tc for tc in turn["calls"] if tc["id"] in turn_output_ids]
|
||||
if matched_calls:
|
||||
if ti == 0:
|
||||
# First turn: attach to the existing entry
|
||||
@@ -721,9 +735,7 @@ def _sanitize_tool_pairs(messages: list[dict]) -> list[dict]:
|
||||
"""
|
||||
# Collect all tool-result call_ids in the conversation
|
||||
tool_result_ids = {
|
||||
m["tool_call_id"]
|
||||
for m in messages
|
||||
if m.get("role") == "tool" and m.get("tool_call_id")
|
||||
m["tool_call_id"] for m in messages if m.get("role") == "tool" and m.get("tool_call_id")
|
||||
}
|
||||
|
||||
# Collect all tool_call ids declared by assistant messages
|
||||
@@ -788,7 +800,10 @@ def _parse_image_data_uri(result: str) -> tuple[str, str] | None:
|
||||
|
||||
|
||||
def _append_tool_to_messages(
|
||||
messages: list[dict], event: dict, result: str, provider: str,
|
||||
messages: list[dict],
|
||||
event: dict,
|
||||
result: str,
|
||||
provider: str,
|
||||
reasoning_items: list[dict] | None = None,
|
||||
):
|
||||
"""Append a tool call + result to the message history for the next API call."""
|
||||
@@ -942,6 +957,49 @@ def _scrub_incomplete_items(output_items: list[dict]) -> None:
|
||||
item["status"] = "failed"
|
||||
|
||||
|
||||
def _reasoning_text_len(item: dict) -> int:
|
||||
"""Return displayable reasoning text length for diagnostics."""
|
||||
blocks = item.get("summary") or item.get("content") or []
|
||||
if not isinstance(blocks, list):
|
||||
return 0
|
||||
return sum(len(block.get("text") or "") for block in blocks if isinstance(block, dict))
|
||||
|
||||
|
||||
def _output_debug_stats(output_items: list[dict] | None) -> tuple[dict[str, int], int, int]:
|
||||
"""Return output type counts plus reasoning count/text length."""
|
||||
counts: dict[str, int] = {}
|
||||
reasoning_count = 0
|
||||
reasoning_chars = 0
|
||||
for item in output_items or []:
|
||||
itype = item.get("type", "?")
|
||||
counts[itype] = counts.get(itype, 0) + 1
|
||||
if itype == "reasoning":
|
||||
reasoning_count += 1
|
||||
reasoning_chars += _reasoning_text_len(item)
|
||||
return counts, reasoning_count, reasoning_chars
|
||||
|
||||
|
||||
def _output_item_key(item: dict) -> tuple | None:
|
||||
"""Stable key for Responses-style output item updates."""
|
||||
if item.get("id"):
|
||||
return ("id", item["id"])
|
||||
if item.get("type") and item.get("call_id"):
|
||||
return ("call", item["type"], item["call_id"])
|
||||
return None
|
||||
|
||||
|
||||
def _upsert_output_item(items: list[dict], item: dict) -> bool:
|
||||
"""Insert or replace a Responses-style output item by id/call_id."""
|
||||
key = _output_item_key(item)
|
||||
if key is not None:
|
||||
for idx, existing in enumerate(items):
|
||||
if _output_item_key(existing) == key:
|
||||
items[idx] = item
|
||||
return False
|
||||
items.append(item)
|
||||
return True
|
||||
|
||||
|
||||
def _find_safe_split(messages: list[dict], target_keep: int) -> int:
|
||||
"""Find a safe split index that doesn't break tool call pairs.
|
||||
|
||||
@@ -1067,6 +1125,9 @@ async def run_chat_task(
|
||||
nonlocal text_buffer
|
||||
if not text_buffer:
|
||||
return None
|
||||
if not text_buffer.strip():
|
||||
text_buffer = ""
|
||||
return None
|
||||
logger.info(
|
||||
"[task %s] flush_text: %d chars into message item", message_id[:8], len(text_buffer)
|
||||
)
|
||||
@@ -1086,11 +1147,34 @@ async def run_chat_task(
|
||||
"""Update in-memory state so API can serve it on refresh."""
|
||||
_task_state[message_id] = {"content": content, "output": output_items}
|
||||
|
||||
async def _save_message(save_reason: str, **kwargs) -> bool:
|
||||
"""Persist a message update and log enough detail to debug skipped saves."""
|
||||
saved_output = kwargs.get("output", output_items)
|
||||
saved_content = kwargs.get("content", content)
|
||||
counts, reasoning_count, reasoning_chars = _output_debug_stats(saved_output)
|
||||
logger.info(
|
||||
"[task %s] db save (%s) begin: done=%s content=%d chars output=%d items reasoning=%d items/%d chars types=%s",
|
||||
message_id[:8],
|
||||
save_reason,
|
||||
kwargs.get("done", "<unchanged>"),
|
||||
len(saved_content or ""),
|
||||
len(saved_output or []),
|
||||
reasoning_count,
|
||||
reasoning_chars,
|
||||
counts,
|
||||
)
|
||||
saved = await ChatMessage.update(message_id, **kwargs)
|
||||
log = logger.info if saved else logger.warning
|
||||
log("[task %s] db save (%s) result: updated=%s", message_id[:8], save_reason, saved)
|
||||
return saved
|
||||
|
||||
try:
|
||||
provider = connection["provider"]
|
||||
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:
|
||||
@@ -1105,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
|
||||
@@ -1135,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:
|
||||
@@ -1206,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
|
||||
@@ -1272,7 +1357,8 @@ async def run_chat_task(
|
||||
|
||||
restart = False
|
||||
pending_calls: list[dict] = [] # Collect tool calls from this response
|
||||
pending_reasoning: list[dict] = [] # Reasoning items for round-tripping
|
||||
response_reasoning_items: list[dict] = [] # Pair with tool outputs on the next request
|
||||
streamed_reasoning_chars = 0
|
||||
|
||||
async for event in stream:
|
||||
if event["type"] == "text_delta":
|
||||
@@ -1285,9 +1371,30 @@ async def run_chat_task(
|
||||
# Collect tool call — don't execute yet
|
||||
pending_calls.append(event)
|
||||
|
||||
elif event["type"] == "reasoning":
|
||||
# Collect reasoning items for round-tripping with tool calls
|
||||
pending_reasoning.append(event["item"])
|
||||
elif event["type"] in ("output", "reasoning"):
|
||||
# Providers stream normalized Responses-style output items.
|
||||
# "reasoning" is kept temporarily for compatibility with older
|
||||
# provider adapters.
|
||||
item = event["item"]
|
||||
_upsert_output_item(output_items, item)
|
||||
if item.get("type") == "reasoning":
|
||||
streamed_reasoning_chars = max(
|
||||
streamed_reasoning_chars,
|
||||
_reasoning_text_len(item),
|
||||
)
|
||||
if item.get("status") in (None, "completed"):
|
||||
_upsert_output_item(response_reasoning_items, item)
|
||||
logger.info(
|
||||
"[task %s] output item: type=%s status=%s output=%d items reasoning_chars=%d response_reasoning_items=%d",
|
||||
message_id[:8],
|
||||
item.get("type"),
|
||||
item.get("status"),
|
||||
len(output_items),
|
||||
streamed_reasoning_chars,
|
||||
len(response_reasoning_items),
|
||||
)
|
||||
_sync_state()
|
||||
await emit(output=item)
|
||||
|
||||
elif event["type"] == "usage":
|
||||
usage = {k: v for k, v in event.items() if k != "type"}
|
||||
@@ -1301,15 +1408,14 @@ async def run_chat_task(
|
||||
if not pending_calls:
|
||||
# No tool calls — final response, we're done
|
||||
_flush_text()
|
||||
logger.info(
|
||||
"[task %s] save (usage): content=%d chars, output=%d items, types=%s",
|
||||
message_id[:8],
|
||||
len(content),
|
||||
len(output_items),
|
||||
[i.get("type") for i in output_items],
|
||||
)
|
||||
await ChatMessage.update(
|
||||
message_id,
|
||||
if streamed_reasoning_chars and not response_reasoning_items:
|
||||
logger.warning(
|
||||
"[task %s] reasoning output streamed (%d chars) but no completed reasoning item arrived before usage; DB output may contain only in-progress reasoning",
|
||||
message_id[:8],
|
||||
streamed_reasoning_chars,
|
||||
)
|
||||
await _save_message(
|
||||
"usage",
|
||||
content=content,
|
||||
output=output_items,
|
||||
usage=usage,
|
||||
@@ -1320,11 +1426,36 @@ async def run_chat_task(
|
||||
return
|
||||
|
||||
elif event["type"] == "done":
|
||||
# Stream ended without explicit usage
|
||||
pass
|
||||
# Stream ended — if usage already triggered a save+return, we won't
|
||||
# reach here. This is the fallback for providers that don't support
|
||||
# stream_options.include_usage.
|
||||
if not pending_calls:
|
||||
_flush_text()
|
||||
if streamed_reasoning_chars and not response_reasoning_items:
|
||||
logger.warning(
|
||||
"[task %s] reasoning output streamed (%d chars) but no completed reasoning item arrived before done; DB output may contain only in-progress reasoning",
|
||||
message_id[:8],
|
||||
streamed_reasoning_chars,
|
||||
)
|
||||
await _save_message(
|
||||
"done fallback",
|
||||
content=content,
|
||||
output=output_items,
|
||||
usage=last_usage,
|
||||
done=True,
|
||||
)
|
||||
_task_state.pop(message_id, None)
|
||||
await _emit_done()
|
||||
return
|
||||
|
||||
# ── Process collected tool calls ────────────────────
|
||||
if pending_calls:
|
||||
if streamed_reasoning_chars and not response_reasoning_items:
|
||||
logger.warning(
|
||||
"[task %s] reasoning output streamed (%d chars) before tool calls but no completed reasoning item arrived; model continuation will not include reasoning items",
|
||||
message_id[:8],
|
||||
streamed_reasoning_chars,
|
||||
)
|
||||
flushed_item = _flush_text()
|
||||
|
||||
tool_ctx = {
|
||||
@@ -1350,9 +1481,6 @@ async def run_chat_task(
|
||||
if needs_approval:
|
||||
# First non-auto tool stops the loop for approval
|
||||
tc = needs_approval
|
||||
# Store reasoning items before function_call for round-tripping
|
||||
for ri in pending_reasoning:
|
||||
output_items.append(ri)
|
||||
item = {
|
||||
"type": "function_call",
|
||||
"id": str(uuid.uuid4()),
|
||||
@@ -1363,8 +1491,8 @@ async def run_chat_task(
|
||||
"status": "pending",
|
||||
}
|
||||
output_items.append(item)
|
||||
await ChatMessage.update(
|
||||
message_id,
|
||||
await _save_message(
|
||||
"pending approval",
|
||||
content=content,
|
||||
output=output_items,
|
||||
done=False,
|
||||
@@ -1376,9 +1504,7 @@ async def run_chat_task(
|
||||
await emit(done=True)
|
||||
return
|
||||
|
||||
# All calls are auto-approved — store reasoning + build UI items
|
||||
for ri in pending_reasoning:
|
||||
output_items.append(ri)
|
||||
# All calls are auto-approved — build UI items
|
||||
call_items: list[tuple[dict, dict]] = [] # (event, ui_item)
|
||||
for tc in pending_calls:
|
||||
item = {
|
||||
@@ -1401,8 +1527,12 @@ async def run_chat_task(
|
||||
_sync_state()
|
||||
|
||||
# Separate delegate_task (concurrent) from others (sequential)
|
||||
delegate_indices = [i for i, (tc, _) in enumerate(call_items) if tc["name"] == "delegate_task"]
|
||||
other_indices = [i for i, (tc, _) in enumerate(call_items) if tc["name"] != "delegate_task"]
|
||||
delegate_indices = [
|
||||
i for i, (tc, _) in enumerate(call_items) if tc["name"] == "delegate_task"
|
||||
]
|
||||
other_indices = [
|
||||
i for i, (tc, _) in enumerate(call_items) if tc["name"] != "delegate_task"
|
||||
]
|
||||
|
||||
# Execute non-delegate tools sequentially first
|
||||
# Collect results for batch message construction
|
||||
@@ -1441,8 +1571,10 @@ async def run_chat_task(
|
||||
# with their shared reasoning items (required for reasoning model round-tripping)
|
||||
if sequential_results:
|
||||
_append_batch_to_messages(
|
||||
messages, sequential_results, provider,
|
||||
reasoning_items=pending_reasoning,
|
||||
messages,
|
||||
sequential_results,
|
||||
provider,
|
||||
reasoning_items=response_reasoning_items,
|
||||
)
|
||||
new_messages_since += 1 + len(sequential_results)
|
||||
|
||||
@@ -1487,30 +1619,25 @@ async def run_chat_task(
|
||||
# Build combined message for all delegate calls
|
||||
if delegate_results:
|
||||
# Only attach reasoning if sequential calls didn't consume it
|
||||
ri = pending_reasoning if not other_indices else None
|
||||
ri = response_reasoning_items if not other_indices else None
|
||||
_append_batch_to_messages(
|
||||
messages, delegate_results, provider,
|
||||
messages,
|
||||
delegate_results,
|
||||
provider,
|
||||
reasoning_items=ri,
|
||||
)
|
||||
new_messages_since += 1 + len(delegate_results)
|
||||
|
||||
# Persist after all tool calls
|
||||
await ChatMessage.update(message_id, content=content, output=output_items)
|
||||
await _save_message("tool calls complete", content=content, output=output_items)
|
||||
restart = True
|
||||
|
||||
if not restart:
|
||||
flushed_item = _flush_text()
|
||||
if flushed_item:
|
||||
await emit(output=flushed_item)
|
||||
logger.info(
|
||||
"[task %s] save (end): content=%d chars, output=%d items, types=%s",
|
||||
message_id[:8],
|
||||
len(content),
|
||||
len(output_items),
|
||||
[i.get("type") for i in output_items],
|
||||
)
|
||||
await ChatMessage.update(
|
||||
message_id,
|
||||
await _save_message(
|
||||
"end",
|
||||
content=content,
|
||||
output=output_items,
|
||||
done=True,
|
||||
@@ -1520,8 +1647,8 @@ async def run_chat_task(
|
||||
return
|
||||
|
||||
# Max iterations reached
|
||||
await ChatMessage.update(
|
||||
message_id,
|
||||
await _save_message(
|
||||
"max iterations",
|
||||
content=content,
|
||||
output=output_items,
|
||||
done=True,
|
||||
@@ -1533,7 +1660,7 @@ async def run_chat_task(
|
||||
except asyncio.CancelledError:
|
||||
_flush_text()
|
||||
_scrub_incomplete_items(output_items)
|
||||
await ChatMessage.update(message_id, content=content, output=output_items, done=True)
|
||||
await _save_message("cancelled", content=content, output=output_items, done=True)
|
||||
_task_state.pop(message_id, None)
|
||||
await _emit_done()
|
||||
except Exception as e:
|
||||
@@ -1561,8 +1688,8 @@ async def run_chat_task(
|
||||
if flushed_item:
|
||||
await emit(output=flushed_item)
|
||||
_scrub_incomplete_items(output_items)
|
||||
await ChatMessage.update(
|
||||
message_id,
|
||||
await _save_message(
|
||||
"error",
|
||||
content=content,
|
||||
output=output_items,
|
||||
done=True,
|
||||
|
||||
@@ -55,6 +55,10 @@ async def is_repo(root: str) -> bool:
|
||||
|
||||
async def status(root: str) -> dict[str, Any]:
|
||||
"""Get repo status using porcelain v2 format."""
|
||||
# Refresh Git's cached file metadata first so status catches edits whose
|
||||
# filesystem stat information was stale.
|
||||
await _run("update-index", "-q", "--refresh", cwd=root, check=False)
|
||||
|
||||
_, out, _ = await _run(
|
||||
"status", "--porcelain=v2", "--branch", "--untracked-files=all", cwd=root
|
||||
)
|
||||
@@ -474,6 +478,12 @@ async def pull(root: str) -> dict[str, Any]:
|
||||
return {"ok": code == 0, "message": (out + err).strip()}
|
||||
|
||||
|
||||
async def fetch(root: str) -> dict[str, Any]:
|
||||
"""Fetch remote refs without merging."""
|
||||
code, out, err = await _run("fetch", "--prune", cwd=root, check=False)
|
||||
return {"ok": code == 0, "message": (out + err).strip()}
|
||||
|
||||
|
||||
async def push(
|
||||
root: str,
|
||||
force: bool = False,
|
||||
|
||||
@@ -0,0 +1,212 @@
|
||||
"""Loguru-based app, audit, and upstream diagnostic logging."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import sys
|
||||
import traceback
|
||||
import uuid
|
||||
from typing import Any
|
||||
|
||||
from loguru import logger as loguru_logger
|
||||
|
||||
from cptr.env import (
|
||||
AUDIT_LOG_LEVEL,
|
||||
AUDIT_LOG_PATH,
|
||||
AUDIT_LOG_ROTATION,
|
||||
LOG_FORMAT,
|
||||
LOG_LEVEL,
|
||||
LOG_UPSTREAM_REQUESTS,
|
||||
UPSTREAM_REQUEST_LOG_PATH,
|
||||
UPSTREAM_REQUEST_LOG_ROTATION,
|
||||
)
|
||||
|
||||
|
||||
_LEVELS = {
|
||||
"CRITICAL": "critical",
|
||||
"ERROR": "error",
|
||||
"WARNING": "warning",
|
||||
"INFO": "info",
|
||||
"DEBUG": "debug",
|
||||
"TRACE": "trace",
|
||||
}
|
||||
_AUDIT_LEVELS = {"METADATA", "REQUEST", "REQUEST_RESPONSE"}
|
||||
_configured = False
|
||||
|
||||
|
||||
class InterceptHandler(logging.Handler):
|
||||
"""Route stdlib logging records through Loguru."""
|
||||
|
||||
def emit(self, record: logging.LogRecord) -> None:
|
||||
try:
|
||||
level: str | int = loguru_logger.level(record.levelname).name
|
||||
except ValueError:
|
||||
level = record.levelno
|
||||
|
||||
frame = logging.currentframe()
|
||||
depth = 2
|
||||
while frame and frame.f_code.co_filename == logging.__file__:
|
||||
frame = frame.f_back
|
||||
depth += 1
|
||||
|
||||
loguru_logger.opt(depth=depth, exception=record.exc_info).log(
|
||||
level, record.getMessage()
|
||||
)
|
||||
|
||||
|
||||
def _json_stdout_sink(message) -> None:
|
||||
record = message.record
|
||||
entry: dict[str, Any] = {
|
||||
"timestamp": record["time"].isoformat(),
|
||||
"level": _LEVELS.get(record["level"].name, record["level"].name.lower()),
|
||||
"message": record["message"],
|
||||
"module": record["name"],
|
||||
"function": record["function"],
|
||||
"line": record["line"],
|
||||
}
|
||||
if record["extra"]:
|
||||
entry["extra"] = record["extra"]
|
||||
if record["exception"]:
|
||||
exc = record["exception"]
|
||||
entry["error"] = {
|
||||
"type": exc.type.__name__ if exc.type else None,
|
||||
"message": str(exc.value) if exc.value else None,
|
||||
"stacktrace": "".join(
|
||||
traceback.format_exception(exc.type, exc.value, exc.traceback)
|
||||
).rstrip(),
|
||||
}
|
||||
sys.stdout.write(json.dumps(entry, ensure_ascii=False, default=str) + "\n")
|
||||
sys.stdout.flush()
|
||||
|
||||
|
||||
def _text_stdout_format(record) -> str:
|
||||
extra = ""
|
||||
visible_extra = {
|
||||
k: v
|
||||
for k, v in record["extra"].items()
|
||||
if k not in {"auditable", "upstream_diagnostic"}
|
||||
}
|
||||
if visible_extra:
|
||||
extra = " - {extra[extra_json]}"
|
||||
record["extra"]["extra_json"] = json.dumps(visible_extra, ensure_ascii=False, default=str)
|
||||
return (
|
||||
"<green>{time:YYYY-MM-DD HH:mm:ss.SSS}</green> | "
|
||||
"<level>{level: <8}</level> | "
|
||||
"<cyan>{name}</cyan>:<cyan>{function}</cyan>:<cyan>{line}</cyan> - "
|
||||
"<level>{message}</level>"
|
||||
f"{extra}\n{{exception}}"
|
||||
)
|
||||
|
||||
|
||||
def _audit_format(record) -> str:
|
||||
extra = record["extra"]
|
||||
entry = {
|
||||
"id": extra.get("id", ""),
|
||||
"timestamp": extra.get("timestamp") or record["time"].isoformat(),
|
||||
"audit_level": extra.get("audit_level", ""),
|
||||
"user": extra.get("user") or {},
|
||||
"method": extra.get("method", ""),
|
||||
"path": extra.get("path", ""),
|
||||
"status_code": extra.get("status_code"),
|
||||
"source_ip": extra.get("source_ip"),
|
||||
"user_agent": extra.get("user_agent"),
|
||||
"request_body": extra.get("request_body"),
|
||||
"response_body": extra.get("response_body"),
|
||||
}
|
||||
record["extra"]["file_json"] = json.dumps(entry, ensure_ascii=False, default=str)
|
||||
return "{extra[file_json]}\n"
|
||||
|
||||
|
||||
def _upstream_format(record) -> str:
|
||||
extra = record["extra"]
|
||||
entry = {
|
||||
"id": extra.get("id", ""),
|
||||
"timestamp": extra.get("timestamp") or record["time"].isoformat(),
|
||||
"provider": extra.get("provider", ""),
|
||||
"endpoint": extra.get("endpoint", ""),
|
||||
"model": extra.get("model", ""),
|
||||
"api_type": extra.get("api_type", ""),
|
||||
"body": extra.get("body"),
|
||||
}
|
||||
record["extra"]["file_json"] = json.dumps(entry, ensure_ascii=False, default=str)
|
||||
return "{extra[file_json]}\n"
|
||||
|
||||
|
||||
def setup_logging() -> None:
|
||||
"""Configure stdout logging and optional file sinks once."""
|
||||
global _configured
|
||||
if _configured:
|
||||
return
|
||||
_configured = True
|
||||
|
||||
loguru_logger.remove()
|
||||
|
||||
def normal_filter(record) -> bool:
|
||||
return not record["extra"].get("auditable") and not record["extra"].get(
|
||||
"upstream_diagnostic"
|
||||
)
|
||||
|
||||
if LOG_FORMAT == "json":
|
||||
loguru_logger.add(_json_stdout_sink, level=LOG_LEVEL, filter=normal_filter)
|
||||
else:
|
||||
loguru_logger.add(
|
||||
sys.stdout,
|
||||
level=LOG_LEVEL,
|
||||
format=_text_stdout_format,
|
||||
filter=normal_filter,
|
||||
)
|
||||
|
||||
if AUDIT_LOG_LEVEL in _AUDIT_LEVELS:
|
||||
AUDIT_LOG_PATH.parent.mkdir(parents=True, exist_ok=True)
|
||||
loguru_logger.add(
|
||||
str(AUDIT_LOG_PATH),
|
||||
level="INFO",
|
||||
rotation=AUDIT_LOG_ROTATION,
|
||||
format=_audit_format,
|
||||
filter=lambda record: record["extra"].get("auditable") is True,
|
||||
)
|
||||
|
||||
if LOG_UPSTREAM_REQUESTS:
|
||||
UPSTREAM_REQUEST_LOG_PATH.parent.mkdir(parents=True, exist_ok=True)
|
||||
loguru_logger.add(
|
||||
str(UPSTREAM_REQUEST_LOG_PATH),
|
||||
level="INFO",
|
||||
rotation=UPSTREAM_REQUEST_LOG_ROTATION,
|
||||
format=_upstream_format,
|
||||
filter=lambda record: record["extra"].get("upstream_diagnostic") is True,
|
||||
)
|
||||
|
||||
logging.basicConfig(handlers=[InterceptHandler()], level=LOG_LEVEL, force=True)
|
||||
for name in ("uvicorn", "uvicorn.error", "uvicorn.access"):
|
||||
uvicorn_logger = logging.getLogger(name)
|
||||
uvicorn_logger.handlers = [InterceptHandler()]
|
||||
uvicorn_logger.setLevel(LOG_LEVEL)
|
||||
|
||||
loguru_logger.info("logging configured")
|
||||
|
||||
|
||||
def audit_logger():
|
||||
return loguru_logger.bind(auditable=True)
|
||||
|
||||
|
||||
def log_upstream_request(
|
||||
*,
|
||||
provider: str,
|
||||
endpoint: str,
|
||||
model: str,
|
||||
api_type: str,
|
||||
body: dict,
|
||||
) -> None:
|
||||
"""Write an exact upstream request body to the diagnostic sink when enabled."""
|
||||
if not LOG_UPSTREAM_REQUESTS:
|
||||
return
|
||||
loguru_logger.bind(
|
||||
upstream_diagnostic=True,
|
||||
id=str(uuid.uuid4()),
|
||||
provider=provider,
|
||||
endpoint=endpoint,
|
||||
model=model,
|
||||
api_type=api_type,
|
||||
body=body,
|
||||
).info("")
|
||||
@@ -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")
|
||||
+2
-1
@@ -1,6 +1,6 @@
|
||||
[project]
|
||||
name = "cptr"
|
||||
version = "0.4.10"
|
||||
version = "0.5.0"
|
||||
description = "Your computer, from anywhere. Code, manage, and control your machine from the web."
|
||||
license = {file = "LICENSE"}
|
||||
readme = "README.md"
|
||||
@@ -16,6 +16,7 @@ dependencies = [
|
||||
"alembic>=1.13",
|
||||
"PyJWT>=2.8",
|
||||
"cryptography>=42.0",
|
||||
"loguru>=0.7.3",
|
||||
"python-socketio[asgi]>=5.11",
|
||||
"python-dateutil>=2.8",
|
||||
"truststore>=0.10",
|
||||
|
||||
@@ -265,7 +265,7 @@ wheels = [
|
||||
|
||||
[[package]]
|
||||
name = "cptr"
|
||||
version = "0.4.3"
|
||||
version = "0.4.10"
|
||||
source = { editable = "." }
|
||||
dependencies = [
|
||||
{ name = "aiosqlite" },
|
||||
@@ -275,6 +275,7 @@ dependencies = [
|
||||
{ name = "cryptography" },
|
||||
{ name = "fastapi", extra = ["standard"] },
|
||||
{ name = "httpx" },
|
||||
{ name = "loguru" },
|
||||
{ name = "pyjwt" },
|
||||
{ name = "python-dateutil" },
|
||||
{ name = "python-socketio" },
|
||||
@@ -311,6 +312,7 @@ requires-dist = [
|
||||
{ name = "cryptography", specifier = ">=42.0" },
|
||||
{ name = "fastapi", extras = ["standard"], specifier = ">=0.128.8" },
|
||||
{ name = "httpx", specifier = ">=0.28.1" },
|
||||
{ name = "loguru", specifier = ">=0.7.3" },
|
||||
{ name = "mcp", marker = "extra == 'mcp'", specifier = ">=1.8" },
|
||||
{ name = "openpyxl", marker = "extra == 'docs'", specifier = ">=3.1" },
|
||||
{ name = "pyjwt", specifier = ">=2.8" },
|
||||
@@ -806,6 +808,19 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/41/45/1a4ed80516f02155c51f51e8cedb3c1902296743db0bbc66608a0db2814f/jsonschema_specifications-2025.9.1-py3-none-any.whl", hash = "sha256:98802fee3a11ee76ecaca44429fda8a41bff98b00a0f2838151b113f210cc6fe", size = 18437 },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "loguru"
|
||||
version = "0.7.3"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "colorama", marker = "sys_platform == 'win32'" },
|
||||
{ name = "win32-setctime", marker = "sys_platform == 'win32'" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/3a/05/a1dae3dffd1116099471c643b8924f5aa6524411dc6c63fdae648c4f1aca/loguru-0.7.3.tar.gz", hash = "sha256:19480589e77d47b8d85b2c827ad95d49bf31b0dcde16593892eb51dd18706eb6", size = 63559 }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/0c/29/0348de65b8cc732daa3e33e67806420b2ae89bdce2b04af740289c5c6c8c/loguru-0.7.3-py3-none-any.whl", hash = "sha256:31a33c10c8e1e10422bfd431aeb5d351c7cf7fa671e3c4df004162264b28220c", size = 61595 },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "lxml"
|
||||
version = "6.1.1"
|
||||
@@ -2686,6 +2701,15 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/6f/28/258ebab549c2bf3e64d2b0217b973467394a9cea8c42f70418ca2c5d0d2e/websockets-16.0-py3-none-any.whl", hash = "sha256:1637db62fad1dc833276dded54215f2c7fa46912301a24bd94d45d46a011ceec", size = 171598 },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "win32-setctime"
|
||||
version = "1.2.0"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/b3/8f/705086c9d734d3b663af0e9bb3d4de6578d08f46b1b101c2442fd9aecaa2/win32_setctime-1.2.0.tar.gz", hash = "sha256:ae1fdf948f5640aae05c511ade119313fb6a30d7eabe25fef9764dca5873c4c0", size = 4867 }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/e1/07/c6fe3ad3e685340704d314d765b7912993bcb8dc198f0e7a89382d37974b/win32_setctime-1.2.0-py3-none-any.whl", hash = "sha256:95d644c4e708aba81dc3704a116d8cbc974d70b3bdb8be1d150e36be6e9d1390", size = 4083 },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wsproto"
|
||||
version = "1.2.0"
|
||||
|
||||
Reference in new issue
Block a user