diff --git a/CHANGELOG.md b/CHANGELOG.md index 0e845e8..0ac124d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/Dockerfile b/Dockerfile index 667340d..eed06bd 100644 --- a/Dockerfile +++ b/Dockerfile @@ -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 diff --git a/MANIFESTO.md b/MANIFESTO.md index c9db751..dc3d07a 100644 --- a/MANIFESTO.md +++ b/MANIFESTO.md @@ -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. diff --git a/README.md b/README.md index 640e480..51bc970 100644 --- a/README.md +++ b/README.md @@ -12,17 +12,11 @@ ![Cptr Demo](./demo.png) -The computer used to be a room. Then a desk. Then a bag. Now it's a URL. +See more at [cptr.sh](https://cptr.sh/) -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 diff --git a/cptr/app.py b/cptr/app.py index 4ba9d82..d894cfa 100644 --- a/cptr/app.py +++ b/cptr/app.py @@ -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), diff --git a/cptr/env.py b/cptr/env.py index cc3cf26..b71f82b 100644 --- a/cptr/env.py +++ b/cptr/env.py @@ -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) diff --git a/cptr/frontend/src/app.css b/cptr/frontend/src/app.css index 10a7843..5927914 100644 --- a/cptr/frontend/src/app.css +++ b/cptr/frontend/src/app.css @@ -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; } diff --git a/cptr/frontend/src/app.html b/cptr/frontend/src/app.html index 06594b2..c16e779 100644 --- a/cptr/frontend/src/app.html +++ b/cptr/frontend/src/app.html @@ -15,7 +15,7 @@ - + %sveltekit.head% diff --git a/cptr/frontend/src/lib/apis/admin.ts b/cptr/frontend/src/lib/apis/admin.ts index 4a6869c..40fec56 100644 --- a/cptr/frontend/src/lib/apis/admin.ts +++ b/cptr/frontend/src/lib/apis/admin.ts @@ -120,6 +120,9 @@ export interface ModelConfigResponse { export const getModelConfig = async (): Promise => fetchJSON('/api/admin/models/config'); +export const refreshModelList = async (): Promise => + fetchJSON('/api/admin/models/refresh', { method: 'POST' }); + export const updateModelConfig = ( modelId: string, update: { is_active?: boolean; params?: Record } diff --git a/cptr/frontend/src/lib/apis/chat.ts b/cptr/frontend/src/lib/apis/chat.ts index 2ebf53a..ecd0afb 100644 --- a/cptr/frontend/src/lib/apis/chat.ts +++ b/cptr/frontend/src/lib/apis/chat.ts @@ -41,6 +41,13 @@ export interface SendMessageResult { assistant_message?: ChatMessageRow; } +export interface ChatSendParams { + tool_approval_mode?: string; + plan_mode?: boolean; + request_params?: Record; + 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 } = {}, + params: ChatSendParams = {}, regenerationPrompt?: string, files?: { id: string; name: string; url: string; type: string }[] ) => diff --git a/cptr/frontend/src/lib/apis/git.ts b/cptr/frontend/src/lib/apis/git.ts index 382bf18..17e90c7 100644 --- a/cptr/frontend/src/lib/apis/git.ts +++ b/cptr/frontend/src/lib/apis/git.ts @@ -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 })); diff --git a/cptr/frontend/src/lib/components/Admin/AudioSettings.svelte b/cptr/frontend/src/lib/components/Admin/AudioSettings.svelte index 32b6c71..23e7e79 100644 --- a/cptr/frontend/src/lib/components/Admin/AudioSettings.svelte +++ b/cptr/frontend/src/lib/components/Admin/AudioSettings.svelte @@ -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 @@

+ +

{$t('admin.audio.tts')}

+ +
+ +

+ {$t('admin.audio.ttsEnabledHint')} +

+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ {$t('admin.audio.ttsFormat')} + +
+

+ {$t('admin.audio.ttsHint')} +

+
+ + +

{$t('admin.audio.voiceMode')}

+ +
+
+ {$t('admin.audio.voiceModeSttMode')} + +
+

+ {voiceModeSttMode === 'browser' ? $t('admin.audio.voiceModeBrowserSttHint') : $t('admin.audio.voiceModeProviderSttHint')} +

+
+ + +
+

+ {$t('admin.audio.voiceModeSystemPromptHint')} +

+
+
+

diff --git a/cptr/frontend/src/lib/components/FileEditor.svelte b/cptr/frontend/src/lib/components/FileEditor.svelte index 70172cb..6d85c3c 100644 --- a/cptr/frontend/src/lib/components/FileEditor.svelte +++ b/cptr/frontend/src/lib/components/FileEditor.svelte @@ -646,7 +646,7 @@
- {fileData.name} + {fileData.name} {formatSize(fileData.size)}
@@ -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; diff --git a/cptr/frontend/src/lib/components/GitBar.svelte b/cptr/frontend/src/lib/components/GitBar.svelte index 9b1dd2b..9282e74 100644 --- a/cptr/frontend/src/lib/components/GitBar.svelte +++ b/cptr/frontend/src/lib/components/GitBar.svelte @@ -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 @@ }); - - {#if gitStatus?.is_repo}
{#each commits as c, i} {#if i === unpushedCount && unpushedCount > 0} -
- +
+ {unpushedCount} unpushed {unpushedCount === 1 ? 'commit' : 'commits'} @@ -800,7 +825,10 @@ onclick={() => selectCommit(c)} > {#if i < unpushedCount} - + {/if}
+ {:else if name === 'speaker'} + + + {:else if name === 'stop'} {/if} diff --git a/cptr/frontend/src/lib/components/Sidebar.svelte b/cptr/frontend/src/lib/components/Sidebar.svelte index fa1557e..0722634 100644 --- a/cptr/frontend/src/lib/components/Sidebar.svelte +++ b/cptr/frontend/src/lib/components/Sidebar.svelte @@ -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 { diff --git a/cptr/frontend/src/lib/components/VoiceMemoModal.svelte b/cptr/frontend/src/lib/components/VoiceMemoModal.svelte index ceb31be..4574d0f 100644 --- a/cptr/frontend/src/lib/components/VoiceMemoModal.svelte +++ b/cptr/frontend/src/lib/components/VoiceMemoModal.svelte @@ -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 diff --git a/cptr/frontend/src/lib/components/chat/AssistantMessage.svelte b/cptr/frontend/src/lib/components/chat/AssistantMessage.svelte index 08ce235..509a654 100644 --- a/cptr/frontend/src/lib/components/chat/AssistantMessage.svelte +++ b/cptr/frontend/src/lib/components/chat/AssistantMessage.svelte @@ -1,11 +1,14 @@
+ {#if $voiceModeEnabled} +
+ + + + + {voiceStatusLabel} +
+ {/if}
- +
diff --git a/cptr/frontend/src/lib/components/chat/ChatPanel.svelte b/cptr/frontend/src/lib/components/chat/ChatPanel.svelte index 6c0c7fb..61250ca 100644 --- a/cptr/frontend/src/lib/components/chat/ChatPanel.svelte +++ b/cptr/frontend/src/lib/components/chat/ChatPanel.svelte @@ -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; + 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(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(); + const ttsPreparedAudio = new Map(); + 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 { + 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 { + 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; + 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((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; + } + }
{#if isLanding}
-
+

@@ -911,9 +1252,9 @@ {:else} {#if loading} -
- -
+
+ +
{:else}
@@ -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} diff --git a/cptr/frontend/src/lib/components/chat/ConsecutiveActivityGroup.svelte b/cptr/frontend/src/lib/components/chat/ConsecutiveActivityGroup.svelte new file mode 100644 index 0000000..6ae5439 --- /dev/null +++ b/cptr/frontend/src/lib/components/chat/ConsecutiveActivityGroup.svelte @@ -0,0 +1,260 @@ + + +
+ + + {#if expanded} +
+
+ {#each entries as item, entryIdx} + {#if item.type === 'reasoning'} + + {:else} + + {/if} + {/each} +
+
+ {/if} + + {#if !expanded && hasPendingApproval && chatId} +
+ {#each pendingCalls as item} +
+ + {toolLabel(item.name, item.arguments || {})} + + + + + +
+ {/each} +
+ {/if} +
diff --git a/cptr/frontend/src/lib/components/chat/OutputEditView.svelte b/cptr/frontend/src/lib/components/chat/OutputEditView.svelte index 0d1793e..b8d2dfb 100644 --- a/cptr/frontend/src/lib/components/chat/OutputEditView.svelte +++ b/cptr/frontend/src/lib/components/chat/OutputEditView.svelte @@ -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) { diff --git a/cptr/frontend/src/lib/components/chat/ReasoningCollapsible.svelte b/cptr/frontend/src/lib/components/chat/ReasoningCollapsible.svelte new file mode 100644 index 0000000..4459aef --- /dev/null +++ b/cptr/frontend/src/lib/components/chat/ReasoningCollapsible.svelte @@ -0,0 +1,87 @@ + + +
+ + + {#if expanded && thoughtText} +
+
+
+ {thoughtText} +
+
+
+ {/if} +
diff --git a/cptr/frontend/src/lib/components/chat/SendButton.svelte b/cptr/frontend/src/lib/components/chat/SendButton.svelte index 7b5ead4..24e127e 100644 --- a/cptr/frontend/src/lib/components/chat/SendButton.svelte +++ b/cptr/frontend/src/lib/components/chat/SendButton.svelte @@ -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); {#if showStop} @@ -25,6 +28,33 @@ /> +{:else if showVoice} + {:else} + + + {:else} +
+ + + +
+ {/if} +
+
+ + {#if expanded} +
+
+ {#if Object.keys(args).length > 0} +
+
+ {$t('chat.toolInput')} +
+ {#if toolName === 'edit_file' && args.target} +
+
+ -{args.target + .length > 500 + ? args.target.slice(0, 500) + '...' + : args.target} +
+
+ +{( + args.replacement || '' + ).length > 500 + ? args.replacement.slice(0, 500) + '...' + : args.replacement || ''} +
+
+ {#if args.start_line} +
+ {$t('chat.toolLines', { + start: args.start_line, + end: args.end_line || 'end' + })} +
+ {/if} + {:else if toolName === 'run_command'} + {args.command} + {:else} +
+ {#each Object.entries(args) as [key, value]} +
+ {key} + + {typeof value === 'object' ? JSON.stringify(value) : value} + +
+ {/each} +
+ {/if} +
+ {/if} + + {#if pairedOutput?.output} +
+
+ {$t('chat.toolOutput')} +
+
+
{pairedOutput
+									.output.length > 10000
+									? pairedOutput.output.slice(0, 10000)
+									: pairedOutput.output}
+ {#if pairedOutput.output.length > 10000} +
+ {$t('chat.totalChars', { + count: pairedOutput.output.length.toLocaleString() + })} +
+ {/if} +
+
+ {/if} +
+
+ {/if} +

diff --git a/cptr/frontend/src/lib/i18n/locales/de.json b/cptr/frontend/src/lib/i18n/locales/de.json index d6d55b0..cc99577 100644 --- a/cptr/frontend/src/lib/i18n/locales/de.json +++ b/cptr/frontend/src/lib/i18n/locales/de.json @@ -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", diff --git a/cptr/frontend/src/lib/i18n/locales/en.json b/cptr/frontend/src/lib/i18n/locales/en.json index 934112d..11969a1 100644 --- a/cptr/frontend/src/lib/i18n/locales/en.json +++ b/cptr/frontend/src/lib/i18n/locales/en.json @@ -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" } - diff --git a/cptr/frontend/src/lib/i18n/locales/es.json b/cptr/frontend/src/lib/i18n/locales/es.json index 6c5b0b1..99e55b1 100644 --- a/cptr/frontend/src/lib/i18n/locales/es.json +++ b/cptr/frontend/src/lib/i18n/locales/es.json @@ -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", diff --git a/cptr/frontend/src/lib/i18n/locales/fr.json b/cptr/frontend/src/lib/i18n/locales/fr.json index 6bf7a9e..6a527fb 100644 --- a/cptr/frontend/src/lib/i18n/locales/fr.json +++ b/cptr/frontend/src/lib/i18n/locales/fr.json @@ -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é", diff --git a/cptr/frontend/src/lib/i18n/locales/ja.json b/cptr/frontend/src/lib/i18n/locales/ja.json index e704ec1..b7aef2f 100644 --- a/cptr/frontend/src/lib/i18n/locales/ja.json +++ b/cptr/frontend/src/lib/i18n/locales/ja.json @@ -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": "キーの作成に失敗しました", diff --git a/cptr/frontend/src/lib/i18n/locales/ko.json b/cptr/frontend/src/lib/i18n/locales/ko.json index 929f0cd..4823eba 100644 --- a/cptr/frontend/src/lib/i18n/locales/ko.json +++ b/cptr/frontend/src/lib/i18n/locales/ko.json @@ -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": "키 생성에 실패했습니다", diff --git a/cptr/frontend/src/lib/i18n/locales/pt-BR.json b/cptr/frontend/src/lib/i18n/locales/pt-BR.json index 41a4a2d..efc1dd6 100644 --- a/cptr/frontend/src/lib/i18n/locales/pt-BR.json +++ b/cptr/frontend/src/lib/i18n/locales/pt-BR.json @@ -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", diff --git a/cptr/frontend/src/lib/i18n/locales/ru.json b/cptr/frontend/src/lib/i18n/locales/ru.json index b9df36d..0be1266 100644 --- a/cptr/frontend/src/lib/i18n/locales/ru.json +++ b/cptr/frontend/src/lib/i18n/locales/ru.json @@ -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": "Не удалось создать ключ", diff --git a/cptr/frontend/src/lib/i18n/locales/zh-CN.json b/cptr/frontend/src/lib/i18n/locales/zh-CN.json index cd2d6ab..4dfeeb9 100644 --- a/cptr/frontend/src/lib/i18n/locales/zh-CN.json +++ b/cptr/frontend/src/lib/i18n/locales/zh-CN.json @@ -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": "创建密钥失败", diff --git a/cptr/frontend/src/lib/i18n/locales/zh-TW.json b/cptr/frontend/src/lib/i18n/locales/zh-TW.json index 31ed45b..8830152 100644 --- a/cptr/frontend/src/lib/i18n/locales/zh-TW.json +++ b/cptr/frontend/src/lib/i18n/locales/zh-TW.json @@ -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": "建立金鑰失敗", diff --git a/cptr/frontend/src/lib/stores/audio.ts b/cptr/frontend/src/lib/stores/audio.ts index 80dc57a..5e53376 100644 --- a/cptr/frontend/src/lib/stores/audio.ts +++ b/cptr/frontend/src/lib/stores/audio.ts @@ -14,20 +14,52 @@ export const QUALITY_BITRATES: Record = { export const voiceMemosEnabled = writable(false); export const transcribeEnabled = writable(true); +export const sttConfigured = writable(false); export const recordingQuality = writable('high'); export const showVoiceMemo = writable(false); +export const ttsEnabled = writable(false); +export const ttsConfigured = writable(false); +export const ttsVoice = writable('alloy'); +export const ttsFormat = writable('mp3'); +export const voiceModeEnabled = writable(false); +export const voiceModeSttMode = writable<'browser' | 'provider'>('browser'); +export const ttsPlaybackEnabled = writable( + 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 }>( - '/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'); } } diff --git a/cptr/frontend/src/lib/stores/gitStatus.svelte.ts b/cptr/frontend/src/lib/stores/gitStatus.svelte.ts index a1a0371..4fa158e 100644 --- a/cptr/frontend/src/lib/stores/gitStatus.svelte.ts +++ b/cptr/frontend/src/lib/stores/gitStatus.svelte.ts @@ -30,28 +30,29 @@ let _status = $state(null); let _loading = $state(false); let _currentRoot = ''; let _fetchPromise: Promise | 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; } diff --git a/cptr/frontend/src/routes/+layout.svelte b/cptr/frontend/src/routes/+layout.svelte index b7d92b3..72dd8d7 100644 --- a/cptr/frontend/src/routes/+layout.svelte +++ b/cptr/frontend/src/routes/+layout.svelte @@ -331,7 +331,7 @@
{#if !$currentWorkspace && $page.url.pathname === '/'} diff --git a/cptr/frontend/static/apple-touch-icon.png b/cptr/frontend/static/apple-touch-icon.png new file mode 100644 index 0000000..fd32ab6 Binary files /dev/null and b/cptr/frontend/static/apple-touch-icon.png differ diff --git a/cptr/frontend/static/icon-192.png b/cptr/frontend/static/icon-192.png index fbd2eab..f8b206f 100644 Binary files a/cptr/frontend/static/icon-192.png and b/cptr/frontend/static/icon-192.png differ diff --git a/cptr/frontend/static/icon-512.png b/cptr/frontend/static/icon-512.png index afebe2c..10c84f4 100644 Binary files a/cptr/frontend/static/icon-512.png and b/cptr/frontend/static/icon-512.png differ diff --git a/cptr/routers/admin.py b/cptr/routers/admin.py index a6d7d1d..acc4d4c 100644 --- a/cptr/routers/admin.py +++ b/cptr/routers/admin.py @@ -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 diff --git a/cptr/routers/audio.py b/cptr/routers/audio.py index 7f4e914..70f02aa 100644 --- a/cptr/routers/audio.py +++ b/cptr/routers/audio.py @@ -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))) diff --git a/cptr/routers/chat.py b/cptr/routers/chat.py index d157547..6cb90d8 100644 --- a/cptr/routers/chat.py +++ b/cptr/routers/chat.py @@ -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. diff --git a/cptr/routers/git.py b/cptr/routers/git.py index 8320686..1cadd09 100644 --- a/cptr/routers/git.py +++ b/cptr/routers/git.py @@ -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.""" diff --git a/cptr/utils/ai.py b/cptr/utils/ai.py index 08b8156..166fbf6 100644 --- a/cptr/utils/ai.py +++ b/cptr/utils/ai.py @@ -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, } diff --git a/cptr/utils/audit.py b/cptr/utils/audit.py new file mode 100644 index 0000000..a2d74f8 --- /dev/null +++ b/cptr/utils/audit.py @@ -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 diff --git a/cptr/utils/chat_task.py b/cptr/utils/chat_task.py index f511f34..a5e112a 100644 --- a/cptr/utils/chat_task.py +++ b/cptr/utils/chat_task.py @@ -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", ""), + 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, diff --git a/cptr/utils/git.py b/cptr/utils/git.py index 25499ad..d41b4ab 100644 --- a/cptr/utils/git.py +++ b/cptr/utils/git.py @@ -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, diff --git a/cptr/utils/logger.py b/cptr/utils/logger.py new file mode 100644 index 0000000..e1f5485 --- /dev/null +++ b/cptr/utils/logger.py @@ -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 ( + "{time:YYYY-MM-DD HH:mm:ss.SSS} | " + "{level: <8} | " + "{name}:{function}:{line} - " + "{message}" + 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("") diff --git a/cptr/utils/workspace.py b/cptr/utils/workspace.py new file mode 100644 index 0000000..c71ae34 --- /dev/null +++ b/cptr/utils/workspace.py @@ -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") diff --git a/pyproject.toml b/pyproject.toml index 2bf891a..7a1b032 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -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", diff --git a/uv.lock b/uv.lock index 4bd3d59..a6fba69 100644 --- a/uv.lock +++ b/uv.lock @@ -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"