Merge pull request #129 from open-webui/main

0.9.2
This commit is contained in:
Tim Baek authored and GitHub committed 2026-07-11 21:07:27 -05:00
commit 1a3baea292
45 files changed
+1284 -771

No files matched your search

+12
View File
@@ -5,6 +5,18 @@ 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.9.2] - 2026-07-11
### Added
- 💬 **Helpful planning questions.** When a plan needs your input, Computer can now ask a few focused questions with clear choices and a recommended answer.
### Changed
- 🧠 **Each chat remembers its own choices.** Your selected model and chat options now stay with that conversation instead of carrying over from another one.
- 🏠 **A more capable Home.** Open files from conversations while using Home, and keep those file tabs available as you move between tabs.
- 🎨 **A more consistent look.** Your appearance choice now carries through to browsers, terminals, editors, previews, menus, and other everyday parts of the app.
## [0.9.1] - 2026-07-11
### Fixed
+32 -51
View File
@@ -8,19 +8,19 @@
--font-sans: 'Inter', -apple-system, BlinkMacSystemFont, ui-sans-serif, system-ui, sans-serif;
--font-mono: 'JetBrains Mono', 'Fira Code', ui-monospace, monospace;
/* Exact Open WebUI gray scale - pure neutral, zero chroma */
--color-gray-50: oklch(0.98 0 0);
--color-gray-100: oklch(0.94 0 0);
--color-gray-200: oklch(0.92 0 0);
--color-gray-300: oklch(0.85 0 0);
--color-gray-400: oklch(0.77 0 0);
--color-gray-500: oklch(0.69 0 0);
--color-gray-600: oklch(0.51 0 0);
--color-gray-700: oklch(0.42 0 0);
--color-gray-800: oklch(0.32 0 0);
--color-gray-850: oklch(0.27 0 0);
--color-gray-900: oklch(0.2 0 0);
--color-gray-950: oklch(0.16 0 0);
/* Keep Tailwind's neutral utilities on the selected appearance. */
--color-gray-50: color-mix(in oklab, var(--app-bg) 96%, var(--app-fg));
--color-gray-100: color-mix(in oklab, var(--app-bg) 92%, var(--app-fg));
--color-gray-200: color-mix(in oklab, var(--app-bg) 85%, var(--app-fg));
--color-gray-300: color-mix(in oklab, var(--app-bg) 75%, var(--app-fg));
--color-gray-400: color-mix(in oklab, var(--app-bg) 65%, var(--app-fg));
--color-gray-500: color-mix(in oklab, var(--app-bg) 55%, var(--app-fg));
--color-gray-600: color-mix(in oklab, var(--app-bg) 45%, var(--app-fg));
--color-gray-700: color-mix(in oklab, var(--app-bg) 35%, var(--app-fg));
--color-gray-800: color-mix(in oklab, var(--app-bg) 25%, var(--app-fg));
--color-gray-850: color-mix(in oklab, var(--app-bg) 20%, var(--app-fg));
--color-gray-900: color-mix(in oklab, var(--app-bg) 15%, var(--app-fg));
--color-gray-950: color-mix(in oklab, var(--app-bg) 10%, var(--app-fg));
}
:root {
@@ -76,19 +76,12 @@
/* Scrollbar - Open WebUI style */
::-webkit-scrollbar-thumb {
--tw-border-opacity: 1;
background-color: rgba(215, 215, 215, 0.6);
border-color: rgba(255, 255, 255, var(--tw-border-opacity));
background-color: color-mix(in oklab, var(--app-fg) 32%, transparent);
border-color: var(--app-bg);
border-radius: 624.9375rem;
border-width: 1px;
}
/* Dark theme scrollbar styles */
.dark ::-webkit-scrollbar-thumb {
background-color: rgba(67, 67, 67, 0.6);
border-color: rgba(0, 0, 0, var(--tw-border-opacity));
}
::-webkit-scrollbar {
height: 0.45rem;
width: 0.45rem;
@@ -293,20 +286,20 @@
}
.dark .cm-editor {
background-color: #000 !important;
background-color: var(--app-bg) !important;
}
.dark .cm-gutters {
background-color: #000 !important;
background-color: var(--app-bg) !important;
border: none !important;
}
.dark .cm-activeLine {
background-color: rgba(255, 255, 255, 0.04) !important;
background-color: var(--app-hover) !important;
}
.dark .cm-activeLineGutter {
background-color: rgba(255, 255, 255, 0.04) !important;
background-color: var(--app-hover) !important;
}
:not(.dark) .cm-gutters {
@@ -338,45 +331,33 @@
.shimmer {
background: linear-gradient(
110deg,
#b4b4b4 0%,
#b4b4b4 43%,
#e8e8e8 50%,
#b4b4b4 57%,
#b4b4b4 100%
var(--app-fg-subtle) 0%,
var(--app-fg-subtle) 43%,
var(--app-fg) 50%,
var(--app-fg-subtle) 57%,
var(--app-fg-subtle) 100%
);
background-size: 200% 100%;
background-clip: text;
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
animation: shimmer 1.5s cubic-bezier(0.7, 0, 1, 0.4) infinite;
color: #b4b4b4;
}
.dark .shimmer {
background: linear-gradient(
110deg,
#9a9a9a 0%,
#9a9a9a 43%,
#5e5e5e 50%,
#9a9a9a 57%,
#9a9a9a 100%
);
background-size: 200% 100%;
background-clip: text;
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
animation: shimmer 1.5s cubic-bezier(0.7, 0, 1, 0.4) infinite;
color: #9a9a9a;
color: var(--app-fg-subtle);
}
/* Inline code (codespan), Open WebUI style */
.codespan {
padding: 0.15rem 0.3rem;
font-size: 0.85em;
@apply font-mono rounded-md text-gray-800 bg-gray-100 dark:text-gray-200 dark:bg-gray-800 mx-0.5;
@apply font-mono rounded-md mx-0.5;
background: var(--app-hover);
color: var(--app-fg);
}
/* Tippy tooltip theme */
.tippy-box[data-theme~='cptr'] {
@apply rounded-lg bg-gray-950 text-xs border border-gray-900 shadow-xl;
@apply rounded-lg text-xs border shadow-xl;
background: var(--app-bg);
color: var(--app-fg);
border-color: var(--app-border);
}
+21 -1
View File
@@ -59,8 +59,10 @@ export interface SendMessageResult {
assistant_message?: ChatMessageRow;
}
export type ToolApprovalMode = 'ask' | 'auto' | 'full';
export interface ChatSendParams {
tool_approval_mode?: string;
tool_approval_mode?: ToolApprovalMode;
plan_mode?: boolean;
request_params?: Record<string, unknown>;
voice_mode?: boolean;
@@ -104,6 +106,12 @@ export const updateChatTitle = (chatId: string, title: string) =>
body: JSON.stringify({ title })
});
export const updateChatSettings = (chatId: string, modelId: string, params: ChatSendParams) =>
fetchJSON<{ ok: boolean }>(
`/api/chats/${chatId}/settings`,
jsonBody({ model_id: modelId, params })
);
export const forkChat = (chatId: string, messageId?: string | null) =>
fetchJSON<{ ok: boolean; chat_id: string }>(
`/api/chats/${chatId}/fork`,
@@ -147,6 +155,18 @@ export const approveToolCall = (
jsonBody({ call_id: callId, approved })
);
export const answerAskUser = (
chatId: string,
messageId: string,
callId: string,
answers: Record<string, string>,
timedOut = false
) =>
fetchJSON(
`/api/chats/${chatId}/messages/${messageId}/answer`,
jsonBody({ call_id: callId, answers, timed_out: timedOut })
);
export const cancelTask = (chatId: string, messageId: string) =>
fetchJSON(`/api/chats/${chatId}/messages/${messageId}/cancel`, { method: 'POST' });
@@ -7,7 +7,8 @@
import Icon from '../Icon.svelte';
import DropdownMenu from '../DropdownMenu.svelte';
import ModelSelector from '../common/ModelSelector.svelte';
import { selectedModelId, workspaceList } from '$lib/stores';
import { workspaceList } from '$lib/stores';
import { defaultModel } from '$lib/stores/chat';
import { getPathDisplayName } from '$lib/utils/paths';
import { createBot, updateBot, verifyBotToken, type BotData, type BotForm } from '$lib/apis/bots';
import { toast } from 'svelte-sonner';
@@ -25,7 +26,7 @@
let platform = $state(bot?.platform || 'telegram');
let name = $state(bot?.name || '');
let token = $state('');
let modelId = $state(bot?.model_id || $selectedModelId || '');
let modelId = $state(bot?.model_id || $defaultModel || '');
let workspace = $state(bot?.workspace || '');
let allowedSenders = $state(bot?.allowed_senders?.join(', ') || '');
let saving = $state(false);
@@ -416,7 +416,7 @@
height: 100%;
border: 0;
display: block;
background: white;
background: var(--app-bg);
}
.preview-error {
height: 100%;
@@ -699,7 +699,7 @@
width: 100%;
height: 100%;
display: block;
background: white;
background: var(--app-bg);
}
.chrome-container {
position: relative;
@@ -955,16 +955,17 @@
'&': {
height: '100%',
fontSize: '0.8125rem',
backgroundColor: dark ? '#000' : '#ffffff'
backgroundColor: 'var(--app-bg)',
color: 'var(--app-fg)'
},
'.cm-scroller': { fontFamily: '"JetBrains Mono", "Fira Code", ui-monospace, monospace' },
'.cm-gutters': {
backgroundColor: dark ? '#000' : '#ffffff',
color: dark ? '#555' : '#999',
backgroundColor: 'var(--app-bg)',
color: 'var(--app-fg-subtle)',
border: 'none'
},
'.cm-activeLineGutter': { backgroundColor: dark ? '#1a1a1a' : '#f3f4f6' },
'.cm-activeLine': { backgroundColor: dark ? '#1a1a1a' : '#f9fafb' },
'.cm-activeLineGutter': { backgroundColor: 'var(--app-hover)' },
'.cm-activeLine': { backgroundColor: 'var(--app-hover)' },
'.cm-lineNumbers .cm-gutterElement.cm-git-line-added': {
boxShadow: `inset 0.125rem 0 0 ${dark ? 'rgba(52, 211, 153, 0.75)' : 'rgba(5, 150, 105, 0.65)'}`
},
@@ -1306,8 +1307,8 @@
flex-shrink: 0;
}
:global(.dark) .toolbar {
border-bottom-color: rgba(255, 255, 255, 0.06);
.toolbar {
border-bottom-color: var(--app-border);
}
.toolbar-left {
@@ -1353,7 +1354,7 @@
}
:global(.dark) .file-name {
color: var(--color-gray-300);
color: var(--app-fg);
}
.file-git-stats {
@@ -1436,7 +1437,7 @@
}
:global(.dark) .toolbar-btn.active {
color: white;
color: var(--app-fg);
}
.editor-area {
@@ -1463,7 +1464,7 @@
max-width: 100%;
max-height: 100%;
border-radius: 0.5rem;
background: #000;
background: var(--app-bg);
}
.media-container audio {
@@ -1,6 +1,7 @@
<script lang="ts">
import { goto } from '$app/navigation';
import { activeWorkspace, addWorkspace, openFileTab, selectedModelId } from '$lib/stores';
import { activeWorkspace, addWorkspace, openFileTab } from '$lib/stores';
import { defaultModel } from '$lib/stores/chat';
import {
getGitLog,
getGitDiff,
@@ -382,7 +383,7 @@
if (!stagedFiles.length || generatingCommitMessage) return;
generatingCommitMessage = true;
try {
const message = await generateGitCommitMessage(workspacePath, $selectedModelId || undefined);
const message = await generateGitCommitMessage(workspacePath, $defaultModel || undefined);
commitSummary = message.summary;
commitDescription = message.description;
} catch (e) {
@@ -1498,7 +1499,8 @@
{#each fileDiff as df}
{#if fileDiff.length > 1}
<div
class="px-2 py-1 text-[0.625rem] text-gray-500 dark:text-gray-400 bg-white dark:bg-[#1a1a1a] border-b border-gray-100 dark:border-white/4 sticky top-0 z-10 font-medium"
class="px-2 py-1 text-[0.625rem] text-gray-500 dark:text-gray-400 border-b border-gray-100 dark:border-white/4 sticky top-0 z-10 font-medium"
style="background: var(--app-bg); border-color: var(--app-border);"
>
{df.path}
</div>
@@ -1714,6 +1716,6 @@
.git-resize-handle:hover,
.git-resize-handle.active {
background: rgba(150, 150, 150, 0.12);
background: var(--app-active);
}
</style>
@@ -138,7 +138,7 @@
}
function handleContextMenu(e: MouseEvent, tab: Tab) {
if (!isWideScreen) return;
if (!isWideScreen || tab.permanent) return;
e.preventDefault();
contextMenu = { tab, x: e.clientX, y: e.clientY };
}
@@ -9,6 +9,13 @@
</script>
<span
class="inline-flex items-center justify-center h-[1.125rem] px-[0.3125rem] rounded-full text-[0.625rem] font-medium leading-none bg-[#e8e8e8] text-[#555] dark:bg-[#1e1e1e] dark:text-[#999] {className}"
class="key-pill inline-flex items-center justify-center h-[1.125rem] px-[0.3125rem] rounded-full text-[0.625rem] font-medium leading-none {className}"
>{text}</span
>
<style>
.key-pill {
background: var(--app-hover);
color: var(--app-fg-muted);
}
</style>
@@ -348,7 +348,7 @@
.appearance-swatch {
width: 1.5rem;
height: 1.5rem;
border: 1px solid rgb(156 163 175 / 0.35);
border: 1px solid var(--app-border);
border-radius: 624.9375rem;
background: transparent;
padding: 0.125rem;
@@ -364,7 +364,7 @@
.ui-scale-range::-webkit-slider-runnable-track {
height: 0.125rem;
border-radius: 624.9375rem;
background: rgb(209 213 219 / 0.7);
background: var(--app-divider);
}
.ui-scale-range::-webkit-slider-thumb {
@@ -373,32 +373,22 @@
height: 0.75rem;
margin-top: -0.3125rem;
border-radius: 624.9375rem;
border: 1px solid rgb(156 163 175 / 0.45);
background: rgb(255 255 255);
border: 1px solid var(--app-border);
background: var(--app-bg);
}
.ui-scale-range::-moz-range-track {
height: 0.125rem;
border-radius: 624.9375rem;
background: rgb(209 213 219 / 0.7);
background: var(--app-divider);
}
.ui-scale-range::-moz-range-thumb {
width: 0.75rem;
height: 0.75rem;
border-radius: 624.9375rem;
border: 1px solid rgb(156 163 175 / 0.45);
background: rgb(255 255 255);
border: 1px solid var(--app-border);
background: var(--app-bg);
}
:global(.dark) .ui-scale-range::-webkit-slider-runnable-track,
:global(.dark) .ui-scale-range::-moz-range-track {
background: rgb(255 255 255 / 0.12);
}
:global(.dark) .ui-scale-range::-webkit-slider-thumb,
:global(.dark) .ui-scale-range::-moz-range-thumb {
border-color: rgb(255 255 255 / 0.18);
background: rgb(229 231 235);
}
</style>
@@ -168,7 +168,7 @@
.shortcut-row {
@apply flex items-center gap-2 px-1 py-1.5;
border-bottom: 1px solid rgba(128, 128, 128, 0.04);
border-bottom: 1px solid var(--app-divider);
}
.shortcut-row:last-child {
@@ -183,8 +183,8 @@
border-radius: 0.25rem;
font-size: 0.625rem;
font-weight: 500;
background: rgba(59, 130, 246, 0.1);
color: rgba(59, 130, 246, 0.7);
background: var(--app-active);
color: var(--app-fg);
animation: pulse-subtle 1.5s ease-in-out infinite;
}
@@ -463,7 +463,7 @@
.notification-target-row {
@apply flex items-center gap-3 px-1 py-1.5;
border-bottom: 1px solid rgba(128, 128, 128, 0.04);
border-bottom: 1px solid var(--app-divider);
}
.notification-target-row:last-child {
@@ -224,18 +224,13 @@
align-items: center;
gap: 0.25rem;
padding: 0.25rem 0.5rem;
background: var(--color-gray-100);
border-top: 1px solid var(--color-gray-200);
background: var(--app-bg);
border-top: 1px solid var(--app-border);
overflow-x: auto;
flex-shrink: 0;
scrollbar-width: none;
}
:global(.dark) .shortcut-bar {
background: #0a0a0a;
border-top-color: rgba(255, 255, 255, 0.06);
}
.shortcut-bar::-webkit-scrollbar {
display: none;
}
@@ -246,8 +241,8 @@
font-family: var(--font-mono);
font-weight: 500;
border-radius: 0.3125rem;
color: var(--color-gray-600);
background: var(--color-gray-200);
color: var(--app-fg-muted);
background: var(--app-hover);
white-space: nowrap;
flex-shrink: 0;
transition: all 0.1s ease;
@@ -256,22 +251,12 @@
-webkit-tap-highlight-color: transparent;
}
:global(.dark) .key {
background: rgba(255, 255, 255, 0.08);
color: var(--color-gray-400);
}
.key:active {
transform: scale(0.95);
}
.key.active {
background: var(--color-gray-900);
color: white;
}
:global(.dark) .key.active {
background: white;
color: black;
background: var(--app-fg);
color: var(--app-bg);
}
</style>
@@ -151,7 +151,7 @@
.resize-handle:hover,
.resize-handle.active {
background: rgba(150, 150, 150, 0.12);
background: var(--app-active);
}
}
</style>
@@ -411,7 +411,7 @@
transition:
opacity 0.1s,
transform 0.1s;
color: #9ca3af;
color: var(--app-fg-subtle);
}
:global(.dark) .ws-icon-chevron {
@@ -458,12 +458,12 @@
width: 0.25rem;
height: 0.25rem;
border-radius: 50%;
background: #9ca3af;
background: var(--app-fg-subtle);
animation: dotPulse 1s ease-in-out infinite;
}
:global(.dark) .ws-chat-loading-dot {
background: #6b7280;
background: var(--app-fg-muted);
}
.ws-chat-loading-dot:nth-child(2) {
@@ -155,25 +155,27 @@
resizeTimeout = setTimeout(() => doFit(), 350);
}
function isDarkMode(): boolean {
return document.documentElement.classList.contains('dark');
function themeColor(name: '--app-bg' | '--app-fg') {
return getComputedStyle(document.documentElement).getPropertyValue(name).trim();
}
const darkTheme = {
background: '#000000',
foreground: '#e0e0e0',
cursor: '#e0e0e0',
cursorAccent: '#000000',
selectionBackground: 'rgba(255, 255, 255, 0.2)'
};
function withAlpha(color: string, alpha: number) {
const hex = /^#([0-9a-f]{6})$/i.exec(color)?.[1];
if (!hex) return color;
return `rgba(${parseInt(hex.slice(0, 2), 16)}, ${parseInt(hex.slice(2, 4), 16)}, ${parseInt(hex.slice(4, 6), 16)}, ${alpha})`;
}
const lightTheme = {
background: '#ffffff',
foreground: '#1a1a1a',
cursor: '#1a1a1a',
cursorAccent: '#ffffff',
selectionBackground: 'rgba(0, 0, 0, 0.15)'
};
function terminalTheme() {
const background = themeColor('--app-bg');
const foreground = themeColor('--app-fg');
return {
background,
foreground,
cursor: foreground,
cursorAccent: background,
selectionBackground: withAlpha(foreground, 0.2)
};
}
// Send input to PTY via WebSocket (binary prefix protocol).
// Writes directly into the pre-allocated buffer. Zero allocation
@@ -256,16 +258,19 @@
scrollback: 10000,
macOptionClickForceSelection: true,
disableStdin: readOnly,
theme: isDarkMode() ? darkTheme : lightTheme
theme: terminalTheme()
});
// Watch for theme changes
const observer = new MutationObserver(() => {
if (term) {
term.options.theme = isDarkMode() ? darkTheme : lightTheme;
term.options.theme = terminalTheme();
}
});
observer.observe(document.documentElement, { attributes: true, attributeFilter: ['class'] });
observer.observe(document.documentElement, {
attributes: true,
attributeFilter: ['class', 'style']
});
// Handle macOS key combos that need special escape sequences
term.attachCustomKeyEventHandler((e: KeyboardEvent) => {
@@ -521,7 +526,7 @@
:global(.xterm-viewport) {
overflow-y: auto !important;
scrollbar-width: thin;
scrollbar-color: rgba(75, 85, 99, 0.4) transparent;
scrollbar-color: color-mix(in oklab, var(--app-fg) 40%, transparent) transparent;
overscroll-behavior: contain;
}
/* When moved to flex sibling on mobile, override xterm's offscreen
@@ -8,7 +8,8 @@
import DropdownMenu from '../DropdownMenu.svelte';
import ModelSelector from '../common/ModelSelector.svelte';
import ScheduleDropdown from './ScheduleDropdown.svelte';
import { selectedModelId, workspaceList } from '$lib/stores';
import { workspaceList } from '$lib/stores';
import { defaultModel } from '$lib/stores/chat';
import { getPathDisplayName } from '$lib/utils/paths';
import type { AutomationData, AutomationForm } from '$lib/apis/automations';
import { createAutomation, updateAutomation } from '$lib/apis/automations';
@@ -25,7 +26,7 @@
let name = $state(automation?.name || '');
let prompt = $state(automation?.prompt || '');
let modelId = $state(automation?.model_id || $selectedModelId || '');
let modelId = $state(automation?.model_id || $defaultModel || '');
let workspace = $state(automation?.workspace || '');
let rrule = $state(automation?.rrule || 'RRULE:FREQ=DAILY;BYHOUR=9;BYMINUTE=0');
let saving = $state(false);
@@ -282,20 +282,12 @@
padding: 0.25rem 0.625rem;
border-radius: 1rem;
font-size: 0.75rem;
color: var(--color-gray-600);
color: var(--app-fg-muted);
transition: background 0.1s;
}
:global(.dark) .schedule-trigger {
color: var(--color-gray-400);
}
.schedule-trigger:hover {
background: rgba(0, 0, 0, 0.05);
}
:global(.dark) .schedule-trigger:hover {
background: rgba(255, 255, 255, 0.05);
background: var(--app-hover);
}
.schedule-panel {
@@ -304,15 +296,10 @@
width: 12rem;
padding: 0.25rem;
border-radius: 1rem;
background: white;
border: 1px solid var(--color-gray-200);
background: var(--app-bg);
border: 1px solid var(--app-border);
box-shadow:
0 0.25rem 0.375rem -0.0625rem rgba(0, 0, 0, 0.1),
0 0.125rem 0.25rem -0.125rem rgba(0, 0, 0, 0.1);
}
:global(.dark) .schedule-panel {
background: #0a0a0a;
border-color: rgba(255, 255, 255, 0.08);
0 0.25rem 0.375rem -0.0625rem color-mix(in oklab, var(--app-fg) 10%, transparent),
0 0.125rem 0.25rem -0.125rem color-mix(in oklab, var(--app-fg) 10%, transparent);
}
</style>
@@ -0,0 +1,218 @@
<script lang="ts">
interface Props {
item: any;
pairedOutput: any;
chatId: string | null;
messageId: string;
onanswer: (
messageId: string,
callId: string,
answers: Record<string, string>,
timedOut: boolean
) => void;
}
let { item, pairedOutput, chatId, messageId, onanswer }: Props = $props();
let selections = $state<Record<string, string>>({});
let otherAnswers = $state<Record<string, string>>({});
let submitting = $state(false);
let questionIndex = $state(0);
const request = $derived(item.arguments || {});
const questions = $derived(Array.isArray(request.questions) ? request.questions : []);
const question = $derived(questions[questionIndex]);
const pending = $derived(item.status === 'pending');
function hasAnswers(answers: Record<string, string>) {
return (
questions.length > 0 &&
questions.every((question: any) => {
const choice = answers[question.id];
return choice && (choice !== '__other__' || otherAnswers[question.id]?.trim());
})
);
}
const canSubmit = $derived(hasAnswers(selections));
const resolved = $derived.by(() => {
try {
return JSON.parse(pairedOutput?.output || '{}');
} catch {
return {};
}
});
function submit(timedOut = false, selected = selections) {
if (!chatId || (!hasAnswers(selected) && !timedOut)) return;
const answers: Record<string, string> = {};
for (const question of questions) {
const choice = selected[question.id];
answers[question.id] = timedOut
? question.options[0].label
: choice === '__other__'
? otherAnswers[question.id].trim()
: choice;
}
submitting = true;
onanswer(messageId, item.call_id, answers, timedOut);
}
function selectAnswer(questionId: string, answer: string) {
const selected = { ...selections, [questionId]: answer };
selections = selected;
if (answer === '__other__') return;
advance(selected);
}
function advance(selected = selections) {
if (questionIndex < questions.length - 1) {
questionIndex += 1;
} else if (hasAnswers(selected)) {
submit(false, selected);
}
}
</script>
<section class="my-1 rounded-2xl bg-gray-100/70 px-3.5 py-3 dark:bg-white/[0.055]">
<div class="mb-3 flex items-center justify-between gap-3">
<div class="text-[0.6875rem] font-medium tracking-wide text-gray-500 dark:text-gray-400">
Planning question
</div>
{#if pending}
<div class="text-[0.6875rem] text-gray-500 dark:text-gray-400">
{questionIndex + 1} of {questions.length} · paused while visible
</div>
{:else if item.timed_out || resolved.timed_out}
<div class="text-[0.6875rem] text-gray-500 dark:text-gray-400">Recommendations used</div>
{/if}
</div>
<div class="space-y-2.5">
{#if question}
{#key question.id}
<div class="space-y-2.5">
<div>
<div class="text-sm font-medium tracking-[-0.01em] text-gray-900 dark:text-gray-100">
{question.header}
</div>
<div class="mt-1 text-xs leading-relaxed text-gray-600 dark:text-gray-300">
{question.question}
</div>
</div>
{#if pending}
<div class="space-y-0.5">
{#each question.options || [] as option, optionIndex}
<label
class="flex cursor-pointer items-start gap-2.5 rounded-xl px-2.5 py-1.5 transition-colors {selections[
question.id
] === option.label
? 'bg-white shadow-sm dark:bg-white/[0.1]'
: 'hover:bg-white/70 dark:hover:bg-white/[0.06]'}"
onclick={() => selections[question.id] === option.label && advance(selections)}
>
<input
class="sr-only"
type="radio"
name={question.id}
value={option.label}
checked={selections[question.id] === option.label}
onchange={() => selectAnswer(question.id, option.label)}
/>
<span
class="mt-1 flex size-3.5 shrink-0 items-center justify-center rounded-full border {selections[
question.id
] === option.label
? 'border-gray-900 dark:border-white'
: 'border-gray-300 dark:border-white/25'}"
>
{#if selections[question.id] === option.label}
<span class="size-1.5 rounded-full bg-gray-900 dark:bg-white"></span>
{/if}
</span>
<span class="min-w-0 text-xs">
<span class="text-gray-800 dark:text-gray-100">{option.label}</span>
{#if optionIndex === 0}
<span class="ml-1.5 text-[0.625rem] text-gray-400 dark:text-gray-500"
>Recommended</span
>
{/if}
<span class="mt-0.5 block leading-relaxed text-gray-500 dark:text-gray-400">
{option.description}
</span>
</span>
</label>
{/each}
<label
class="flex cursor-pointer items-center gap-2.5 rounded-xl px-2.5 py-1.5 text-xs transition-colors {selections[
question.id
] === '__other__'
? 'bg-white shadow-sm dark:bg-white/[0.1]'
: 'hover:bg-white/70 dark:hover:bg-white/[0.06]'}"
>
<input
class="sr-only"
type="radio"
name={question.id}
value="__other__"
checked={selections[question.id] === '__other__'}
onchange={() => selectAnswer(question.id, '__other__')}
/>
<span
class="flex size-3.5 shrink-0 items-center justify-center rounded-full border {selections[
question.id
] === '__other__'
? 'border-gray-900 dark:border-white'
: 'border-gray-300 dark:border-white/25'}"
>
{#if selections[question.id] === '__other__'}
<span class="size-1.5 rounded-full bg-gray-900 dark:bg-white"></span>
{/if}
</span>
<span class="text-gray-700 dark:text-gray-200">Other</span>
</label>
{#if selections[question.id] === '__other__'}
<input
class="w-full rounded-xl bg-transparent px-2.5 py-1.5 text-xs text-gray-800 outline-none placeholder:text-gray-400 dark:text-gray-100 dark:placeholder:text-gray-500"
placeholder="Type your answer"
value={otherAnswers[question.id] || ''}
oninput={(event) =>
(otherAnswers = { ...otherAnswers, [question.id]: event.currentTarget.value })}
/>
{/if}
</div>
{:else}
<div class="text-xs leading-relaxed text-gray-600 dark:text-gray-300">
{resolved.answers?.[question.id]?.answers?.join(', ') || 'No answer recorded'}
</div>
{/if}
</div>
{/key}
{/if}
<div class="flex items-center justify-between gap-2 pt-0.5">
<button
type="button"
class="rounded-lg px-2.5 py-1.5 text-xs text-gray-500 transition-colors hover:bg-white/70 hover:text-gray-800 disabled:opacity-30 dark:text-gray-400 dark:hover:bg-white/10 dark:hover:text-gray-100"
disabled={questionIndex === 0}
onclick={() => (questionIndex -= 1)}
>
Previous
</button>
{#if questionIndex < questions.length - 1}
<button
type="button"
class="rounded-lg bg-gray-900 px-3 py-1.5 text-xs font-medium text-white transition-transform active:scale-[0.98] dark:bg-white dark:text-black"
onclick={() => (questionIndex += 1)}
>
Next
</button>
{:else if pending}
<button
type="button"
class="rounded-lg bg-gray-900 px-3 py-1.5 text-xs font-medium text-white transition-transform active:scale-[0.98] disabled:cursor-not-allowed disabled:opacity-40 dark:bg-white dark:text-black"
disabled={!canSubmit || submitting}
onclick={() => submit()}
>
Submit answers
</button>
{/if}
</div>
</div>
</section>
@@ -158,6 +158,15 @@
collapsedFiles = { ...collapsedFiles, [key]: !collapsedFiles[key] };
}
function openArtifact(artifact: any) {
const workspace = get(currentWorkspace);
const path =
workspace && artifact.path
? `${workspace.path.replace(/\/$/, '')}/${artifact.path}`
: artifact.path;
if (path) openFileTab(path);
}
/** Human-readable label for a tool call */
function toolLabel(name: string, args: any): string {
const _t = $t;
@@ -201,6 +210,10 @@
return _t('chat.tool.killTask', { id: args.task_id || '?' });
case 'image_generate':
return args.image || args.images?.length ? 'Edit image' : 'Generate image';
case 'ask_user': {
const count = Array.isArray(args.questions) ? args.questions.length : 0;
return `Asked ${count} question${count === 1 ? '' : 's'}`;
}
case 'web_search':
return _t('chat.tool.webSearch', { query: args.query || '?' });
case 'read_url': {
@@ -343,9 +356,11 @@
for (const [index, item] of output.entries()) {
if (item.type === 'function_call') {
ensureGroup();
currentGroup!.entries.push(item);
currentGroup!.calls.push(item);
if (item.name !== 'ask_user' || item.status !== 'pending') {
ensureGroup();
currentGroup!.entries.push(item);
currentGroup!.calls.push(item);
}
} else if (item.type === 'reasoning') {
ensureGroup();
currentGroup!.entries.push(item);
@@ -458,13 +473,7 @@
hover:border-gray-300 dark:hover:border-white/12
hover:bg-gray-50/50 dark:hover:bg-white/[0.03]
transition-colors duration-150 {preview ? 'h-[4.375rem]' : 'h-[2.375rem]'}"
onclick={() => {
const ws = get(currentWorkspace);
if (ws && artifact.path) {
const fullPath = ws.path.replace(/\/$/, '') + '/' + artifact.path;
openFileTab(fullPath);
}
}}
onclick={() => openArtifact(artifact)}
>
<div class="h-full min-w-0 overflow-hidden px-3 py-2.5">
<div
@@ -130,11 +130,7 @@
min-height: 10rem;
overflow: hidden;
resize: vertical;
background: white;
}
:global(.dark) .preview-box {
background: black;
background: var(--app-bg);
}
.preview-box.tall {
@@ -152,11 +148,7 @@
overflow: auto;
resize: vertical;
padding: 0.875rem 1rem;
background: white;
}
:global(.dark) .text-preview {
background: rgba(0, 0, 0, 0.25);
background: var(--app-bg);
}
.mono-preview {
@@ -166,16 +158,12 @@
font-family: var(--font-mono);
font-size: 0.75rem;
line-height: 1.35;
color: var(--color-gray-800);
}
:global(.dark) .mono-preview {
color: var(--color-gray-200);
color: var(--app-fg);
}
.media-preview {
padding: 0.75rem 1rem;
background: white;
background: var(--app-bg);
}
.video-preview {
@@ -186,10 +174,6 @@
resize: vertical;
}
:global(.dark) .media-preview {
background: rgba(0, 0, 0, 0.25);
}
.media-preview audio,
.media-preview video {
width: 100%;
@@ -201,10 +185,6 @@
.preview-state {
padding: 0.75rem 1rem;
font-size: 0.75rem;
color: var(--color-gray-500);
}
:global(.dark) .preview-state {
color: var(--color-gray-400);
color: var(--app-fg-muted);
}
</style>
@@ -27,14 +27,14 @@
import DictateButton from './DictateButton.svelte';
import QueuedMessageItem from './QueuedMessageItem.svelte';
import Tasks from './Tasks.svelte';
import AskUserCard from './AskUserCard.svelte';
import Icon from '../Icon.svelte';
import { planMode } from '$lib/stores';
import type { ToolApprovalMode } from '$lib/apis/chat';
import {
sttConfigured,
ttsConfigured,
ttsEnabled,
unlockTtsAudioPlayback,
voiceModeEnabled,
voiceModeSttMode
} from '$lib/stores/audio';
import Spinner from '$lib/components/common/Spinner.svelte';
@@ -65,12 +65,17 @@
interface Props {
inputText: string;
selectedModel: string;
toolApprovalMode?: ToolApprovalMode;
planMode?: boolean;
requestParams?: Record<string, unknown>;
voiceModeEnabled?: boolean;
sending: boolean;
streaming?: boolean;
workspace?: string;
placeholder?: string;
contextUsage?: ContextUsage | null;
tasks?: ChatTask[];
askUser?: any;
queuedMessages?: { id: string; content: string }[];
hasChatContent?: boolean;
onsend: () => void;
@@ -80,19 +85,31 @@
onstatus?: () => void;
onskillslist?: () => void;
oncancel?: () => void;
onaskuseranswer?: (
messageId: string,
callId: string,
answers: Record<string, string>,
timedOut: boolean
) => void;
onqueuesendnow?: (id: string) => void;
onqueueedit?: (id: string) => void;
onqueuedelete?: (id: string) => void;
onsettingschange?: () => void;
}
let {
inputText = $bindable(),
selectedModel = $bindable(),
toolApprovalMode = $bindable('auto'),
planMode = $bindable(false),
requestParams = $bindable({}),
voiceModeEnabled = $bindable(false),
sending,
streaming = false,
workspace = '',
placeholder = 'Message...',
contextUsage = null,
tasks = [],
askUser = null,
queuedMessages = [],
hasChatContent = false,
onsend,
@@ -102,9 +119,11 @@
onstatus,
onskillslist,
oncancel,
onaskuseranswer,
onqueuesendnow,
onqueueedit,
onqueuedelete
onqueuedelete,
onsettingschange
}: Props = $props();
let editorEl: HTMLDivElement | undefined = $state();
@@ -127,7 +146,7 @@
const voiceStatusLabel = $derived(
voiceWaitingForResponse || streaming || sending
? $t('chat.voiceWaiting')
: voiceListening || voiceRearming || $voiceModeEnabled
: voiceListening || voiceRearming || voiceModeEnabled
? $t('chat.voiceListening')
: $t('chat.voiceModeOn')
);
@@ -160,7 +179,6 @@
}
async function processFiles(files: File[]) {
if (!workspace) return;
for (const file of files) {
const id = Math.random().toString(36).substring(7);
const isImage = file.type.startsWith('image/');
@@ -669,7 +687,7 @@
clearVoiceRestartTimer();
if (
!voiceModeAvailable ||
!$voiceModeEnabled ||
!voiceModeEnabled ||
voiceWaitingForResponse ||
voiceListening ||
voiceRecognition ||
@@ -813,7 +831,7 @@
clearVoiceRestartTimer(false);
if (
!voiceModeAvailable ||
!$voiceModeEnabled ||
!voiceModeEnabled ||
voiceWaitingForResponse ||
voiceListening ||
voiceRecognition ||
@@ -829,7 +847,7 @@
(window as any).SpeechRecognition || (window as any).webkitSpeechRecognition;
if (!SpeechRecognition) {
alert($t('chat.dictate.unsupported'));
voiceModeEnabled.set(false);
voiceModeEnabled = false;
voiceRearming = false;
return;
}
@@ -881,7 +899,7 @@
recognition.onerror = (event: any) => {
voiceListening = false;
if (event?.error === 'not-allowed' || event?.error === 'service-not-allowed') {
voiceModeEnabled.set(false);
voiceModeEnabled = false;
stopVoiceRecognition();
}
};
@@ -913,8 +931,9 @@
alert($t('chat.ttsNotConfigured'));
return;
}
const next = !$voiceModeEnabled;
voiceModeEnabled.set(next);
const next = !voiceModeEnabled;
voiceModeEnabled = next;
onsettingschange?.();
if (next) {
void unlockTtsAudioPlayback();
void acquireVoiceWakeLock();
@@ -930,11 +949,11 @@
}
$effect(() => {
if (!voiceModeAvailable && $voiceModeEnabled) {
voiceModeEnabled.set(false);
if (!voiceModeAvailable && voiceModeEnabled) {
voiceModeEnabled = false;
stopVoiceRecognition();
}
if (!$voiceModeEnabled) return;
if (!voiceModeEnabled) return;
if (streaming) voiceSawStreaming = true;
if (voiceSawStreaming && !streaming && !sending) {
voiceWaitingForResponse = false;
@@ -944,7 +963,7 @@
});
$effect(() => {
if ($voiceModeEnabled && inputText.trim()) {
if (voiceModeEnabled && inputText.trim()) {
stopVoiceRecognition();
}
});
@@ -1109,6 +1128,18 @@
}}
role="presentation"
>
{#if askUser && onaskuseranswer}
<div class="mx-1">
<AskUserCard
item={askUser.item}
pairedOutput={askUser.output}
chatId={askUser.chatId}
messageId={askUser.messageId}
onanswer={onaskuseranswer}
/>
</div>
{/if}
{#if tasks.length > 0}
<div class="mx-1">
<Tasks {tasks} />
@@ -1226,7 +1257,7 @@
<span class="flex-1 min-w-0 flex items-baseline gap-1.5 overflow-hidden">
<span class="truncate">{$t('chat.commandPlan')}</span>
<span class="app-muted text-[0.625rem] truncate shrink-0">
{$planMode ? $t('chat.commandPlanOn') : $t('chat.commandPlanOff')}
{planMode ? $t('chat.commandPlanOn') : $t('chat.commandPlanOff')}
</span>
</span>
</button>
@@ -1443,7 +1474,7 @@
{/if}
<!-- Editor area -->
<div class="px-2.5">
{#if $voiceModeEnabled}
{#if voiceModeEnabled}
<div class="app-muted pt-2 flex items-center gap-2 text-[0.6875rem] font-medium">
<span class="relative flex size-2">
<span
@@ -1471,23 +1502,25 @@
onmousedown={(e) => e.stopPropagation()}
>
<div class="ml-0.5 self-end flex items-center gap-1">
{#if workspace}
<PlusMenu
onfiles={(files) => {
if (files) processFiles(Array.from(files));
}}
oncapture={(file) => {
processFiles([file]);
}}
/>
{/if}
{#if $planMode}
<PlusMenu
bind:toolApprovalMode
bind:planMode
bind:requestParams
onchange={onsettingschange}
onfiles={(files) => {
if (files) processFiles(Array.from(files));
}}
oncapture={(file) => {
processFiles([file]);
}}
/>
{#if planMode}
<button
type="button"
aria-label={$t('chat.commandPlanOff')}
title={$t('chat.commandPlanOff')}
class="app-surface app-interactive group p-[0.3125rem] flex gap-1 items-center text-xs rounded-full transition-colors duration-150 border"
onclick={() => planMode.set(false)}
onclick={() => onplan?.()}
>
<svg
class="size-3 shrink-0 group-hover:hidden"
@@ -1519,7 +1552,7 @@
{/if}
</div>
<div class="self-end mr-1 flex items-center gap-2">
<ModelSelector bind:selectedModel />
<ModelSelector bind:selectedModel onchange={onsettingschange} />
<DictateButton
ontext={(text) => {
inputText += text;
@@ -1531,7 +1564,7 @@
onsend={handleSubmit}
{oncancel}
onvoice={voiceModeAvailable ? toggleVoiceMode : undefined}
voiceActive={$voiceModeEnabled || voiceListening}
voiceActive={voiceModeEnabled || voiceListening}
/>
</div>
</div>
@@ -7,6 +7,7 @@
forkChat as apiForkChat,
sendMessage as apiSendMessage,
approveToolCall,
answerAskUser,
cancelTask,
compactChat as apiCompactChat,
updateCurrentMessage,
@@ -14,9 +15,11 @@
createMessage,
queueSendNow as apiQueueSendNow,
queueDelete as apiQueueDelete,
updateChatSettings,
type ChatMessageRow,
type ChatSendParams,
type ChatInfo,
type ToolApprovalMode,
type ContextUsage,
type ChatTask
} from '$lib/apis/chat';
@@ -30,16 +33,7 @@
import { socketStore } from '$lib/stores/socket.svelte';
import { onMount, onDestroy, tick } from 'svelte';
import { get } from 'svelte/store';
import {
currentWorkspace,
openChatTab,
toolApprovalMode,
planMode,
streamingBehavior,
selectedModelId,
requestParams,
widescreenMode
} from '$lib/stores';
import { currentWorkspace, openChatTab, streamingBehavior, widescreenMode } from '$lib/stores';
import { getPathDisplayName } from '$lib/utils/paths';
import {
ttsEnabled,
@@ -49,8 +43,7 @@
ttsAutoStreamEnabled,
ttsPlaybackEnabled,
ttsVoice,
unlockTtsAudioPlayback,
voiceModeEnabled
unlockTtsAudioPlayback
} from '$lib/stores/audio';
import ChatInput from './ChatInput.svelte';
@@ -76,15 +69,49 @@
workspace?: string;
chatId?: string;
tabId?: string;
active?: boolean;
ontabupdate?: (tabId: string, chatId: string, label: string) => void;
onopenchat?: (chatId?: string) => void;
}
let { workspace = '', chatId: initialChatId, tabId, ontabupdate, onopenchat }: Props = $props();
let {
workspace = '',
chatId: initialChatId,
tabId,
active = true,
ontabupdate,
onopenchat
}: Props = $props();
let inputText = $state('');
let chatId = $state<string | null>(initialChatId ?? null);
let selectedModel = $state('');
let toolApprovalMode = $state<ToolApprovalMode>('auto');
let planMode = $state(false);
let requestParams = $state<Record<string, unknown>>({});
let voiceModeEnabled = $state(false);
let allMessages = $state<ChatMessageRow[]>([]);
const pendingAskUser = $derived.by(() => {
for (const message of [...allMessages].reverse()) {
const item = message.output?.find(
(output: any) =>
output.type === 'function_call' &&
output.name === 'ask_user' &&
output.status === 'pending'
);
if (item) {
return {
item,
output: message.output?.find(
(output: any) =>
output.type === 'function_call_output' && output.call_id === item.call_id
),
chatId,
messageId: message.id
};
}
}
return null;
});
let currentMessageId = $state<string | null>(null);
let contextUsage = $state<ContextUsage | null>(null);
let chatTasks = $state<ChatTask[]>([]);
@@ -370,10 +397,11 @@
const savedScroll = !isInitialLoad && messagesEl ? messagesEl.scrollTop : -1;
try {
const data = await getChat(id, selectedModel || undefined);
const data = await getChat(id);
// Discard stale response if a newer loadChat was called while we waited
if (gen !== loadGeneration) return;
allMessages = data.messages;
loadChatSettings(data.chat.meta);
currentMessageId = data.chat.current_message_id;
contextUsage = data.context_usage ?? null;
setChatTasks(
@@ -619,13 +647,49 @@
if (chatId) loadChat(chatId);
}
onMount(() => {
function resetChatSettings() {
const models = get(chatModels);
const saved = get(selectedModelId);
const dm = get(defaultModel);
if (saved && models.some((m) => m.id === saved)) selectedModel = saved;
else if (dm) selectedModel = dm;
if (dm) selectedModel = dm;
else if (models.length) selectedModel = models[0].id;
toolApprovalMode = 'auto';
planMode = false;
requestParams = {};
voiceModeEnabled = false;
}
function loadChatSettings(meta: Record<string, any> | null) {
resetChatSettings();
const params = meta?.params;
if (!params || typeof params !== 'object') return;
if (
params.tool_approval_mode === 'ask' ||
params.tool_approval_mode === 'auto' ||
params.tool_approval_mode === 'full'
) {
toolApprovalMode = params.tool_approval_mode;
}
planMode = params.plan_mode === true;
if (params.request_params && typeof params.request_params === 'object') {
requestParams = params.request_params;
}
voiceModeEnabled = params.voice_mode === true;
const models = get(chatModels);
if (
typeof meta?.last_model === 'string' &&
models.some((model) => model.id === meta.last_model)
) {
selectedModel = meta.last_model;
}
}
async function persistChatSettings() {
if (!chatId || !selectedModel) return;
await updateChatSettings(chatId, selectedModel, getChatSendParams()).catch(() => {});
}
onMount(() => {
resetChatSettings();
if (chatId) {
loadChat(chatId);
@@ -660,23 +724,17 @@
$effect(() => {
if (!$ttsEnabled || !$ttsConfigured) {
voiceModeEnabled.set(false);
voiceModeEnabled = false;
ttsPlaybackEnabled.set(false);
stopTtsPlayback();
} else if (
(!$ttsPlaybackEnabled && !$voiceModeEnabled && !$ttsAutoStreamEnabled) ||
(!$ttsPlaybackEnabled && !voiceModeEnabled && !$ttsAutoStreamEnabled) ||
!$ttsConfigured
) {
stopTtsPlayback();
}
});
// ── Persist model selection ─────────────────────────────────
$effect(() => {
if (selectedModel) selectedModelId.set(selectedModel);
});
// ── Sync streaming state to shared store for tab icon ────
$effect(() => {
@@ -698,6 +756,22 @@
return () => unregisterStreamingChat(chatId!);
});
$effect(() => {
if (!chatId || !tabId) return;
const send = () =>
socketStore
.getSocket()
?.emit('chat:view', { chat_id: chatId, view_id: tabId, visible: active });
send();
const off = socketStore.on('connect', send);
return () => {
off();
socketStore
.getSocket()
?.emit('chat:view', { chat_id: chatId, view_id: tabId, visible: false });
};
});
// ── Auto-scroll ─────────────────────────────────────────────
function scrollToBottom() {
@@ -740,11 +814,11 @@
function getChatSendParams(): ChatSendParams {
const params: ChatSendParams = {
tool_approval_mode: get(toolApprovalMode),
plan_mode: get(planMode),
request_params: get(requestParams)
tool_approval_mode: toolApprovalMode,
plan_mode: planMode,
request_params: requestParams
};
if (get(voiceModeEnabled)) params.voice_mode = true;
if (voiceModeEnabled) params.voice_mode = true;
return params;
}
@@ -957,7 +1031,8 @@
}
function handlePlanCommand() {
planMode.set(!get(planMode));
planMode = !planMode;
persistChatSettings();
}
function firstUserMessageTitle(): string {
@@ -1115,6 +1190,19 @@
});
}
function handleAskUserAnswer(
messageId: string,
callId: string,
answers: Record<string, string>,
timedOut: boolean
) {
if (!chatId) return;
answerAskUser(chatId, messageId, callId, answers, timedOut).catch((err) => {
console.error('[chat] ask_user answer error', err);
loadChat(chatId!);
});
}
function handleNavigate(messageId: string, direction: -1 | 1) {
const entry = activePath.find((p) => p.msg.id === messageId);
if (!entry) return;
@@ -1228,12 +1316,12 @@
return (
$ttsEnabled &&
$ttsConfigured &&
($ttsPlaybackEnabled || $voiceModeEnabled || $ttsAutoStreamEnabled)
($ttsPlaybackEnabled || voiceModeEnabled || $ttsAutoStreamEnabled)
);
}
function shouldStreamTts() {
return $ttsEnabled && $ttsConfigured && ($voiceModeEnabled || $ttsAutoStreamEnabled);
return $ttsEnabled && $ttsConfigured && (voiceModeEnabled || $ttsAutoStreamEnabled);
}
function resetTtsBuffer() {
@@ -1423,7 +1511,7 @@
toast.error($t('admin.audio.tts') + ': ' + detail);
}
ttsPlaybackEnabled.set(false);
voiceModeEnabled.set(false);
voiceModeEnabled = false;
}
function scheduleTtsPrepare(generation: number) {
@@ -1526,7 +1614,7 @@
if (generation === ttsGeneration) ttsPlaying = false;
if (generation === ttsGeneration) speakingMessageId = null;
if (generation === ttsGeneration) ttsStopRequested = false;
if (generation === ttsGeneration && !$voiceModeEnabled) ttsPlaybackEnabled.set(false);
if (generation === ttsGeneration && !voiceModeEnabled) ttsPlaybackEnabled.set(false);
}
}
</script>
@@ -1577,12 +1665,19 @@
bind:this={chatInputEl}
bind:inputText
bind:selectedModel
bind:toolApprovalMode
bind:planMode
bind:requestParams
bind:voiceModeEnabled
{sending}
{workspace}
placeholder={$t('chat.placeholder', { name: workspaceDisplayName })}
tasks={chatTasks}
askUser={pendingAskUser}
onaskuseranswer={handleAskUserAnswer}
onsend={send}
onplan={handlePlanCommand}
onsettingschange={persistChatSettings}
{queuedMessages}
onqueuesendnow={handleQueueSendNow}
onqueueedit={handleQueueEdit}
@@ -1695,16 +1790,23 @@
bind:this={chatInputEl}
bind:inputText
bind:selectedModel
bind:toolApprovalMode
bind:planMode
bind:requestParams
bind:voiceModeEnabled
{sending}
{streaming}
{workspace}
{contextUsage}
{hasChatContent}
tasks={chatTasks}
askUser={pendingAskUser}
onaskuseranswer={handleAskUserAnswer}
onsend={send}
oncompact={handleManualCompact}
onfork={handleForkChat}
onplan={handlePlanCommand}
onsettingschange={persistChatSettings}
onstatus={handleStatusCommand}
onskillslist={handleSkillsListCommand}
oncancel={handleCancel}
@@ -1,6 +1,6 @@
<script lang="ts">
import { onMount } from 'svelte';
import { toolApprovalMode, planMode, requestParams, type ToolApprovalMode } from '$lib/stores';
import type { ToolApprovalMode } from '$lib/apis/chat';
import { tooltip } from '$lib/tooltip';
import { t } from '$lib/i18n';
import Icon from '../Icon.svelte';
@@ -9,8 +9,19 @@
interface Props {
onfiles: (files: FileList) => void;
oncapture?: (file: File) => void;
toolApprovalMode?: ToolApprovalMode;
planMode?: boolean;
requestParams?: Record<string, unknown>;
onchange?: () => void;
}
let { onfiles, oncapture }: Props = $props();
let {
onfiles,
oncapture,
toolApprovalMode = $bindable('auto'),
planMode = $bindable(false),
requestParams = $bindable({}),
onchange
}: Props = $props();
let open = $state(false);
let tab = $state<'' | 'tools' | 'request_params'>('');
@@ -28,12 +39,12 @@
]);
const currentModeLabel = $derived(
modes.find((m) => m.value === $toolApprovalMode)?.label ?? $t('plusMenu.toolPermissions')
modes.find((m) => m.value === toolApprovalMode)?.label ?? $t('plusMenu.toolPermissions')
);
// ── Request params state ────────────────────────
let paramRows = $state<Array<{ key: string; value: string }>>(
Object.entries($requestParams).map(([key, value]) => ({
Object.entries(requestParams).map(([key, value]) => ({
key,
value: typeof value === 'object' ? JSON.stringify(value, null, 2) : String(value)
}))
@@ -64,9 +75,17 @@
result[key.trim()] = value;
}
}
requestParams.set(result);
requestParams = result;
onchange?.();
}
$effect(() => {
paramRows = Object.entries(requestParams).map(([key, value]) => ({
key,
value: typeof value === 'object' ? JSON.stringify(value, null, 2) : String(value)
}));
});
function toggle() {
open = !open;
if (open) {
@@ -88,7 +107,8 @@
}
function selectMode(mode: ToolApprovalMode) {
toolApprovalMode.set(mode);
toolApprovalMode = mode;
onchange?.();
}
function triggerUpload() {
@@ -282,7 +302,10 @@
<!-- Plan mode toggle -->
<button
class="flex items-center gap-2 w-full h-7 px-2 rounded-xl text-xs text-gray-500 dark:text-gray-400 hover:bg-gray-50 dark:hover:bg-white/5 hover:text-gray-900 dark:hover:text-white transition-colors duration-75"
onclick={() => planMode.update((v) => !v)}
onclick={() => {
planMode = !planMode;
onchange?.();
}}
>
<svg
class="size-3.5 shrink-0"
@@ -299,7 +322,13 @@
<line x1="9" y1="17" x2="15" y2="17" />
</svg>
<span class="flex-1 text-left truncate">{$t('plusMenu.planMode')}</span>
<ToggleSwitch value={$planMode} onchange={(v) => planMode.set(v)} />
<ToggleSwitch
value={planMode}
onchange={(v) => {
planMode = v;
onchange?.();
}}
/>
</button>
<div class="app-divider h-px mx-1 my-0.5"></div>
@@ -359,14 +388,14 @@
{#each modes as mode}
<button
class="flex items-center gap-2 w-full h-7 px-2 rounded-xl text-xs transition-colors duration-75
{$toolApprovalMode === mode.value
{toolApprovalMode === mode.value
? 'text-gray-900 dark:text-white bg-gray-50 dark:bg-white/5'
: 'text-gray-500 dark:text-gray-400 hover:bg-gray-50 dark:hover:bg-white/5 hover:text-gray-900 dark:hover:text-white'}"
onclick={() => selectMode(mode.value)}
use:tooltip={{ content: mode.desc, placement: 'right' }}
>
<span class="flex-1 text-left truncate">{mode.label}</span>
{#if $toolApprovalMode === mode.value}
{#if toolApprovalMode === mode.value}
<svg
class="w-3 h-3 shrink-0 text-gray-400 dark:text-gray-500"
viewBox="0 0 24 24"
@@ -16,9 +16,9 @@
let { item, pairedOutput, done, chatId, messageId, toolLabel, onapprove }: Props = $props();
let expanded = $state($expandToolDetails);
let expanded = $state($expandToolDetails || item.name === 'ask_user');
$effect(() => {
expanded = $expandToolDetails;
expanded = $expandToolDetails || item.name === 'ask_user';
});
const args = $derived(item.arguments || {});
@@ -30,6 +30,15 @@
const isDone = $derived(item.status === 'completed');
const isRejected = $derived(item.status === 'rejected');
const isPending = $derived(item.status === 'pending');
const isAskUser = $derived(toolName === 'ask_user');
const askUserQuestions = $derived(Array.isArray(args.questions) ? args.questions : []);
const askUserAnswers = $derived.by(() => {
try {
return JSON.parse(pairedOutput?.output || '{}').answers || {};
} catch {
return {};
}
});
const imageToolOutput = $derived.by(() => {
if (toolName !== 'image_generate' || !pairedOutput?.output) {
return null;
@@ -103,6 +112,20 @@
/>
</svg>
</div>
{:else if isAskUser}
<div class="text-gray-400 dark:text-gray-500">
<svg
aria-hidden="true"
class="size-3.5"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="1.75"
>
<path stroke-linecap="round" stroke-linejoin="round" d="m5 12 3 3 5-7" />
<path stroke-linecap="round" stroke-linejoin="round" d="M13 7h6M13 12h6M13 17h6" />
</svg>
</div>
{:else if isDone}
<div class="text-emerald-500 dark:text-emerald-400">
<svg
@@ -202,97 +225,115 @@
{#if expanded}
<div id={callId} transition:slide={{ duration: 300, easing: quintOut, axis: 'y' }}>
<div
class="border border-gray-50 dark:border-gray-850/30 rounded-2xl my-1.5 p-3 space-y-3 overflow-hidden"
class={isAskUser
? 'ml-5 mt-1.5 space-y-1.5 text-xs leading-relaxed'
: 'border border-gray-50 dark:border-gray-850/30 rounded-2xl my-1.5 p-3 space-y-3 overflow-hidden'}
>
{#if Object.keys(args).length > 0}
<div>
<div
class="text-[0.625rem] uppercase tracking-wider text-gray-400 dark:text-gray-500 mb-1.5 px-1"
>
{$t('chat.toolInput')}
{#if isAskUser}
{#each askUserQuestions as question}
{@const answer = askUserAnswers[question.id]?.answers?.join(', ')}
<div>
<div class="text-gray-600 dark:text-gray-300">{question.question}</div>
<div class="text-gray-400 dark:text-gray-500">
{answer || 'No answer recorded'}{answer === question.options?.[0]?.label
? ' (Recommended)'
: ''}
</div>
</div>
{#if toolName === 'edit_file' && args.target}
{/each}
{:else}
{#if Object.keys(args).length > 0}
<div>
<div
class="text-[0.6875rem] font-mono rounded-lg overflow-hidden border border-gray-200/60 dark:border-white/6"
class="text-[0.625rem] uppercase tracking-wider text-gray-400 dark:text-gray-500 mb-1.5 px-1"
>
<div
class="bg-red-50/80 dark:bg-red-950/20 text-red-700 dark:text-red-400 px-2.5 py-1 whitespace-pre-wrap break-all leading-relaxed"
>
<span class="select-none text-red-400 dark:text-red-600 mr-1">-</span>{args.target
.length > 500
? args.target.slice(0, 500) + '...'
: args.target}
</div>
<div
class="bg-green-50/80 dark:bg-green-950/20 text-green-700 dark:text-green-400 px-2.5 py-1 whitespace-pre-wrap break-all leading-relaxed"
>
<span class="select-none text-green-400 dark:text-green-600 mr-1">+</span>{(
args.replacement || ''
).length > 500
? args.replacement.slice(0, 500) + '...'
: args.replacement || ''}
</div>
{$t('chat.toolInput')}
</div>
{#if args.start_line}
<div class="text-[0.625rem] text-gray-400 dark:text-gray-600 mt-1 px-1">
{$t('chat.toolLines', {
start: args.start_line,
end: args.end_line || 'end'
})}
</div>
{/if}
{:else if toolName === 'run_command'}
<code
class="block text-xs font-mono text-gray-600 dark:text-gray-300 bg-gray-50 dark:bg-gray-900 rounded-lg px-2.5 py-1.5 overflow-x-auto break-all whitespace-pre-wrap"
>{args.command}</code
>
{:else}
<div class="px-1 space-y-0.5">
{#each Object.entries(args) as [key, value]}
<div class="flex gap-2 text-xs py-0.5">
<span class="text-gray-600 dark:text-gray-400 shrink-0">{key}</span>
<span class="text-gray-800 dark:text-gray-200 break-all whitespace-pre-wrap">
{typeof value === 'object' ? JSON.stringify(value, null, 2) : value}
</span>
{#if toolName === 'edit_file' && args.target}
<div
class="text-[0.6875rem] font-mono rounded-lg overflow-hidden border border-gray-200/60 dark:border-white/6"
>
<div
class="bg-red-50/80 dark:bg-red-950/20 text-red-700 dark:text-red-400 px-2.5 py-1 whitespace-pre-wrap break-all leading-relaxed"
>
<span class="select-none text-red-400 dark:text-red-600 mr-1">-</span>{args
.target.length > 500
? args.target.slice(0, 500) + '...'
: args.target}
</div>
{/each}
</div>
{/if}
</div>
{/if}
{#if pairedOutput?.output}
<div>
<div
class="text-[0.625rem] uppercase tracking-wider text-gray-400 dark:text-gray-500 mb-1.5 px-1"
>
{$t('chat.toolOutput')}
</div>
<div class="w-full min-w-0 overflow-hidden">
{#if imageToolOutput?.length}
<div class="px-1 space-y-1">
{#each imageToolOutput as image}
<div class="text-xs text-gray-600 dark:text-gray-300 break-all leading-relaxed">
{image.path || image.url || image.id}
<div
class="bg-green-50/80 dark:bg-green-950/20 text-green-700 dark:text-green-400 px-2.5 py-1 whitespace-pre-wrap break-all leading-relaxed"
>
<span class="select-none text-green-400 dark:text-green-600 mr-1">+</span>{(
args.replacement || ''
).length > 500
? args.replacement.slice(0, 500) + '...'
: args.replacement || ''}
</div>
</div>
{#if args.start_line}
<div class="text-[0.625rem] text-gray-400 dark:text-gray-600 mt-1 px-1">
{$t('chat.toolLines', {
start: args.start_line,
end: args.end_line || 'end'
})}
</div>
{/if}
{:else if toolName === 'run_command'}
<code
class="block text-xs font-mono text-gray-600 dark:text-gray-300 bg-gray-50 dark:bg-gray-900 rounded-lg px-2.5 py-1.5 overflow-x-auto break-all whitespace-pre-wrap"
>{args.command}</code
>
{:else}
<div class="px-1 space-y-0.5">
{#each Object.entries(args) as [key, value]}
<div class="flex gap-2 text-xs py-0.5">
<span class="text-gray-600 dark:text-gray-400 shrink-0">{key}</span>
<span class="text-gray-800 dark:text-gray-200 break-all whitespace-pre-wrap">
{typeof value === 'object' ? JSON.stringify(value, null, 2) : value}
</span>
</div>
{/each}
</div>
{:else}
<pre
class="text-xs text-gray-600 dark:text-gray-300 whitespace-pre-wrap break-words font-mono max-h-64 overflow-auto leading-relaxed">{formattedOutput.length >
10000
? formattedOutput.slice(0, 10000)
: formattedOutput}</pre>
{/if}
{#if !imageToolOutput?.length && formattedOutput.length > 10000}
<div class="text-[0.625rem] text-gray-400 dark:text-gray-600 mt-1 px-1">
{$t('chat.totalChars', {
count: formattedOutput.length.toLocaleString()
})}
</div>
{/if}
</div>
</div>
{/if}
{#if pairedOutput?.output}
<div>
<div
class="text-[0.625rem] uppercase tracking-wider text-gray-400 dark:text-gray-500 mb-1.5 px-1"
>
{$t('chat.toolOutput')}
</div>
<div class="w-full min-w-0 overflow-hidden">
{#if imageToolOutput?.length}
<div class="px-1 space-y-1">
{#each imageToolOutput as image}
<div
class="text-xs text-gray-600 dark:text-gray-300 break-all leading-relaxed"
>
{image.path || image.url || image.id}
</div>
{/each}
</div>
{:else}
<pre
class="text-xs text-gray-600 dark:text-gray-300 whitespace-pre-wrap break-words font-mono max-h-64 overflow-auto leading-relaxed">{formattedOutput.length >
10000
? formattedOutput.slice(0, 10000)
: formattedOutput}</pre>
{/if}
{#if !imageToolOutput?.length && formattedOutput.length > 10000}
<div class="text-[0.625rem] text-gray-400 dark:text-gray-600 mt-1 px-1">
{$t('chat.totalChars', {
count: formattedOutput.length.toLocaleString()
})}
</div>
{/if}
</div>
</div>
{/if}
{/if}
</div>
</div>
@@ -8,8 +8,14 @@
selectedModel: string;
preferAbove?: boolean;
align?: 'start' | 'end';
onchange?: (model: string) => void;
}
let { selectedModel = $bindable(), preferAbove = true, align = 'end' }: Props = $props();
let {
selectedModel = $bindable(),
preferAbove = true,
align = 'end',
onchange
}: Props = $props();
let btnEl: HTMLButtonElement | undefined = $state();
let searchInputEl: HTMLInputElement | undefined = $state();
@@ -33,6 +39,7 @@
check: true,
onclick: () => {
selectedModel = m.id;
onchange?.(m.id);
}
}))
);
@@ -102,7 +102,7 @@
border: none;
border-radius: 0.3125rem;
background: transparent;
color: #c4c4c4;
color: var(--app-fg-subtle);
font-size: 0.65625rem;
font-weight: 500;
cursor: pointer;
@@ -113,13 +113,13 @@
}
.pagination-btn:hover:not(:disabled):not(.active) {
background: rgba(0, 0, 0, 0.03);
color: #9ca3af;
background: var(--app-hover);
color: var(--app-fg-muted);
}
.pagination-btn.active {
background: rgba(0, 0, 0, 0.04);
color: #8b8b8b;
background: var(--app-active);
color: var(--app-fg);
}
.pagination-btn:disabled {
@@ -134,27 +134,9 @@
min-width: 1.375rem;
height: 1.375rem;
font-size: 0.65625rem;
color: #d1d5db;
color: var(--app-fg-subtle);
user-select: none;
letter-spacing: 0.0625rem;
}
/* Dark mode */
:global(.dark) .pagination-btn {
color: #4b5563;
}
:global(.dark) .pagination-btn:hover:not(:disabled):not(.active) {
background: rgba(255, 255, 255, 0.04);
color: #6b7280;
}
:global(.dark) .pagination-btn.active {
background: rgba(255, 255, 255, 0.06);
color: #9ca3af;
}
:global(.dark) .pagination-ellipsis {
color: #4b5563;
}
</style>
@@ -222,17 +222,12 @@
align-items: center;
height: 2.25rem;
padding: 0 0.5rem;
border-bottom: 1px solid var(--color-gray-200);
background: white;
border-bottom: 1px solid var(--app-border);
background: var(--app-bg);
flex-shrink: 0;
overflow: hidden;
}
:global(.dark) .editor-toolbar {
background: #000;
border-bottom-color: rgba(255, 255, 255, 0.06);
}
.toolbar-scroll {
display: flex;
align-items: center;
@@ -258,7 +253,7 @@
border: none;
border-radius: 0.3125rem;
background: transparent;
color: var(--color-gray-500);
color: var(--app-fg-muted);
font-size: 0.75rem;
font-weight: 500;
cursor: pointer;
@@ -268,13 +263,13 @@
}
.tb-btn:hover {
background: var(--color-gray-100);
color: var(--color-gray-700);
background: var(--app-hover);
color: var(--app-fg);
}
.tb-btn.active {
background: var(--color-gray-200);
color: var(--color-gray-900);
background: var(--app-active);
color: var(--app-fg);
}
.tb-btn:disabled {
@@ -282,20 +277,6 @@
cursor: default;
}
:global(.dark) .tb-btn {
color: var(--color-gray-500);
}
:global(.dark) .tb-btn:hover {
background: rgba(255, 255, 255, 0.06);
color: var(--color-gray-300);
}
:global(.dark) .tb-btn.active {
background: rgba(255, 255, 255, 0.1);
color: white;
}
.heading-btn {
font-size: 0.6875rem;
font-weight: 700;
@@ -305,15 +286,11 @@
.tb-divider {
width: 1px;
height: 1rem;
background: var(--color-gray-200);
background: var(--app-divider);
margin: 0 0.25rem;
flex-shrink: 0;
}
:global(.dark) .tb-divider {
background: rgba(255, 255, 255, 0.08);
}
.highlight-icon {
background: rgba(255, 213, 79, 0.4);
border-radius: 0.125rem;
@@ -337,8 +314,8 @@
padding-bottom: env(safe-area-inset-bottom, 0);
}
:global(.dark) .editor-toolbar {
border-top-color: rgba(255, 255, 255, 0.06);
.editor-toolbar {
border-top-color: var(--app-border);
border-bottom: none;
}
@@ -54,25 +54,17 @@
margin: 0 0 0.75rem;
border-radius: 0.5rem;
overflow: hidden;
border: 1px solid var(--color-gray-200);
}
:global(.dark) .mermaid-block {
border-color: rgba(255, 255, 255, 0.06);
border: 1px solid var(--app-border);
}
.mermaid-container {
display: flex;
justify-content: center;
padding: 1rem;
background: var(--color-gray-50);
background: var(--app-hover);
overflow-x: auto;
}
:global(.dark) .mermaid-container {
background: rgba(255, 255, 255, 0.02);
}
.mermaid-container :global(svg) {
max-width: 100%;
height: auto;
@@ -101,14 +93,10 @@
margin: 0;
padding: 0.5rem 0.75rem;
font-size: 0.75rem;
background: var(--color-gray-100);
background: var(--app-hover);
border-radius: 0.25rem;
color: var(--color-gray-600);
color: var(--app-fg-muted);
font-family: 'JetBrains Mono', 'Fira Code', ui-monospace, monospace;
}
:global(.dark) .mermaid-source {
background: rgba(255, 255, 255, 0.04);
color: var(--color-gray-400);
}
</style>
@@ -220,15 +220,14 @@
min-height: 100%;
font-size: 0.875rem;
line-height: 1.7;
color: var(--color-gray-800);
color: var(--app-fg);
outline: none;
word-wrap: break-word;
overflow-wrap: break-word;
}
.rte-container.dark-mode :global(.rte-prosemirror) {
color: var(--color-gray-200);
caret-color: white;
caret-color: var(--app-fg);
}
/* ── Placeholder ──────────────────────────────── */
@@ -236,15 +235,11 @@
.rte-container :global(.rte-prosemirror p.is-editor-empty:first-child::before) {
content: attr(data-placeholder);
float: left;
color: var(--color-gray-400);
color: var(--app-fg-subtle);
pointer-events: none;
height: 0;
}
.rte-container.dark-mode :global(.rte-prosemirror p.is-editor-empty:first-child::before) {
color: var(--color-gray-600);
}
/* ── Headings (match MarkdownRenderer sizes) ──── */
.rte-container :global(.rte-prosemirror h1) {
@@ -328,45 +323,32 @@
.rte-container :global(.rte-prosemirror blockquote) {
margin: 0 0 0.75rem;
padding: 0.25rem 1rem;
border-left: 0.1875rem solid var(--color-gray-300);
color: var(--color-gray-600);
}
.rte-container.dark-mode :global(.rte-prosemirror blockquote) {
border-left-color: rgba(255, 255, 255, 0.15);
color: var(--color-gray-400);
border-left: 0.1875rem solid var(--app-border);
color: var(--app-fg-muted);
}
/* ── Horizontal rule ──────────────────────────── */
.rte-container :global(.rte-prosemirror hr) {
border: none;
border-top: 1px solid var(--color-gray-200);
border-top: 1px solid var(--app-border);
margin: 1.25rem 0;
}
.rte-container.dark-mode :global(.rte-prosemirror hr) {
border-top-color: rgba(255, 255, 255, 0.08);
}
/* ── Code (inline) ─────────────────────────────── */
.rte-container :global(.rte-prosemirror code) {
background: var(--color-gray-100);
background: var(--app-hover);
border-radius: 0.1875rem;
padding: 0.0625rem 0.3125rem;
font-size: 0.78125rem;
font-family: 'JetBrains Mono', 'Fira Code', ui-monospace, monospace;
}
.rte-container.dark-mode :global(.rte-prosemirror code) {
background: rgba(255, 255, 255, 0.08);
}
/* ── Code blocks ───────────────────────────────── */
.rte-container :global(.rte-prosemirror pre) {
background: var(--color-gray-100);
background: var(--app-hover);
border-radius: 0.375rem;
padding: 0.75rem 1rem;
overflow-x: auto;
@@ -375,10 +357,6 @@
font-family: 'JetBrains Mono', 'Fira Code', ui-monospace, monospace;
}
.rte-container.dark-mode :global(.rte-prosemirror pre) {
background: rgba(255, 255, 255, 0.04);
}
.rte-container :global(.rte-prosemirror pre code) {
background: none;
padding: 0;
@@ -397,29 +375,20 @@
.rte-container :global(.rte-prosemirror th),
.rte-container :global(.rte-prosemirror td) {
border: 1px solid var(--color-gray-200);
border: 1px solid var(--app-border);
padding: 0.375rem 0.625rem;
text-align: left;
}
.rte-container :global(.rte-prosemirror th) {
font-weight: 600;
background: var(--color-gray-50);
}
.rte-container.dark-mode :global(.rte-prosemirror th) {
background: rgba(255, 255, 255, 0.04);
}
.rte-container.dark-mode :global(.rte-prosemirror th),
.rte-container.dark-mode :global(.rte-prosemirror td) {
border-color: rgba(255, 255, 255, 0.08);
background: var(--app-hover);
}
/* ── Links ──────────────────────────────────────── */
.rte-container :global(.rte-prosemirror a) {
color: #3b82f6;
color: var(--app-fg);
text-decoration: none;
cursor: pointer;
}
@@ -88,64 +88,40 @@
}
th {
background: var(--color-gray-50);
color: var(--color-gray-600);
background: var(--app-hover);
color: var(--app-fg-muted);
font-weight: 600;
font-size: 0.6875rem;
text-transform: uppercase;
letter-spacing: 0.03em;
padding: 0.375rem 0.75rem;
text-align: left;
border-bottom: 1px solid var(--color-gray-200);
}
:global(.dark) th {
background: rgba(255, 255, 255, 0.04);
color: var(--color-gray-400);
border-bottom-color: rgba(255, 255, 255, 0.06);
border-bottom: 1px solid var(--app-border);
}
td {
padding: 0.25rem 0.75rem;
color: var(--color-gray-800);
border-bottom: 1px solid var(--color-gray-100);
}
:global(.dark) td {
color: var(--color-gray-200);
border-bottom-color: rgba(255, 255, 255, 0.04);
color: var(--app-fg);
border-bottom: 1px solid var(--app-divider);
}
tbody tr:hover td {
background: rgba(0, 0, 0, 0.02);
}
:global(.dark) tbody tr:hover td {
background: rgba(255, 255, 255, 0.02);
background: var(--app-hover);
}
/* Row numbers */
.row-num {
color: var(--color-gray-400);
color: var(--app-fg-subtle);
font-size: 0.6875rem;
text-align: right;
padding-right: 0.5rem;
padding-left: 0.5rem;
user-select: none;
min-width: 2rem;
border-right: 1px solid var(--color-gray-100);
}
:global(.dark) .row-num {
border-right-color: rgba(255, 255, 255, 0.04);
color: var(--color-gray-600);
border-right: 1px solid var(--app-divider);
}
thead .row-num {
border-right-color: var(--color-gray-200);
}
:global(.dark) thead .row-num {
border-right-color: rgba(255, 255, 255, 0.06);
border-right-color: var(--app-border);
}
</style>
@@ -118,12 +118,7 @@
width: 100%;
height: 100%;
overflow: hidden;
background: repeating-conic-gradient(var(--color-gray-100) 0% 25%, transparent 0% 50%) 50% /
1rem 1rem;
}
:global(.dark) .image-preview {
background: repeating-conic-gradient(rgba(255, 255, 255, 0.04) 0% 25%, transparent 0% 50%) 50% /
background: repeating-conic-gradient(var(--app-hover) 0% 25%, transparent 0% 50%) 50% /
1rem 1rem;
}
@@ -153,16 +148,10 @@
gap: 0.125rem;
padding: 0.125rem;
border-radius: 0.5rem;
background: rgba(255, 255, 255, 0.9);
background: color-mix(in oklab, var(--app-bg) 90%, transparent);
backdrop-filter: blur(0.5rem);
border: 1px solid rgba(0, 0, 0, 0.08);
box-shadow: 0 0.125rem 0.5rem rgba(0, 0, 0, 0.1);
}
:global(.dark) .zoom-toolbar {
background: rgba(30, 30, 30, 0.9);
border-color: rgba(255, 255, 255, 0.1);
box-shadow: 0 0.125rem 0.5rem rgba(0, 0, 0, 0.3);
border: 1px solid var(--app-border);
box-shadow: 0 0.125rem 0.5rem color-mix(in oklab, var(--app-fg) 10%, transparent);
}
.zoom-btn {
@@ -172,18 +161,13 @@
width: 1.75rem;
height: 1.75rem;
border-radius: 0.375rem;
color: var(--color-gray-500);
color: var(--app-fg-muted);
transition: all 0.1s;
}
.zoom-btn:hover {
background: rgba(0, 0, 0, 0.06);
color: var(--color-gray-700);
}
:global(.dark) .zoom-btn:hover {
background: rgba(255, 255, 255, 0.1);
color: var(--color-gray-300);
background: var(--app-hover);
color: var(--app-fg);
}
.zoom-level {
@@ -192,19 +176,14 @@
font-size: 0.6875rem;
font-weight: 500;
text-align: center;
color: var(--color-gray-500);
color: var(--app-fg-muted);
border-radius: 0.375rem;
font-variant-numeric: tabular-nums;
transition: all 0.1s;
}
.zoom-level:hover {
background: rgba(0, 0, 0, 0.06);
color: var(--color-gray-700);
}
:global(.dark) .zoom-level:hover {
background: rgba(255, 255, 255, 0.1);
color: var(--color-gray-300);
background: var(--app-hover);
color: var(--app-fg);
}
</style>
@@ -360,11 +360,7 @@
padding: 1.5rem 2rem;
font-size: 0.875rem;
line-height: 1.7;
color: var(--color-gray-800);
}
:global(.dark) .docx-content {
color: var(--color-gray-200);
color: var(--app-fg);
}
.docx-content :global(h1) {
@@ -392,7 +388,7 @@
}
.docx-content :global(td),
.docx-content :global(th) {
border: 1px solid var(--color-gray-200);
border: 1px solid var(--app-border);
padding: 0.25rem 0.5rem;
}
.docx-content :global(img) {
@@ -405,34 +401,25 @@
.sheet-tabs {
display: flex;
gap: 0;
border-bottom: 1px solid var(--color-gray-200);
border-bottom: 1px solid var(--app-border);
padding: 0 0.25rem;
flex-shrink: 0;
overflow-x: auto;
}
:global(.dark) .sheet-tabs {
border-bottom-color: rgba(255, 255, 255, 0.06);
}
.sheet-tab {
padding: 0.375rem 0.75rem;
font-size: 0.6875rem;
font-weight: 500;
color: var(--color-gray-500);
color: var(--app-fg-muted);
border-bottom: 0.125rem solid transparent;
white-space: nowrap;
transition: all 0.1s;
}
.sheet-tab.active {
color: var(--color-gray-900);
border-bottom-color: var(--color-gray-900);
}
:global(.dark) .sheet-tab.active {
color: white;
border-bottom-color: white;
color: var(--app-fg);
border-bottom-color: var(--app-fg);
}
.xlsx-content {
@@ -455,48 +442,30 @@
}
.xlsx-content :global(th) {
background: var(--color-gray-50);
color: var(--color-gray-500);
background: var(--app-hover);
color: var(--app-fg-muted);
font-weight: 600;
font-size: 0.625rem;
padding: 0.25rem 0.5rem;
text-align: center;
border-bottom: 1px solid var(--color-gray-200);
}
:global(.dark) .xlsx-content :global(th) {
background: rgba(255, 255, 255, 0.04);
color: var(--color-gray-400);
border-bottom-color: rgba(255, 255, 255, 0.06);
border-bottom: 1px solid var(--app-border);
}
.xlsx-content :global(td) {
padding: 0.1875rem 0.5rem;
color: var(--color-gray-800);
border-bottom: 1px solid var(--color-gray-100);
border-right: 1px solid var(--color-gray-100);
}
:global(.dark) .xlsx-content :global(td) {
color: var(--color-gray-200);
border-bottom-color: rgba(255, 255, 255, 0.04);
border-right-color: rgba(255, 255, 255, 0.04);
color: var(--app-fg);
border-bottom: 1px solid var(--app-divider);
border-right: 1px solid var(--app-divider);
}
.xlsx-content :global(.rn) {
color: var(--color-gray-400);
color: var(--app-fg-subtle);
font-size: 0.625rem;
text-align: right;
user-select: none;
min-width: 1.75rem;
border-right: 1px solid var(--color-gray-200);
background: var(--color-gray-50);
}
:global(.dark) .xlsx-content :global(.rn) {
border-right-color: rgba(255, 255, 255, 0.06);
background: rgba(255, 255, 255, 0.02);
color: var(--color-gray-600);
border-right: 1px solid var(--app-border);
background: var(--app-hover);
}
.xlsx-content :global(.num) {
@@ -517,18 +486,14 @@
flex-direction: column;
gap: 0.5rem;
align-items: center;
background: var(--color-gray-100);
}
:global(.dark) .pptx-content {
background: rgba(255, 255, 255, 0.02);
background: var(--app-hover);
}
.slide {
position: relative;
width: 100%;
max-width: 50rem;
box-shadow: 0 0.0625rem 0.25rem rgba(0, 0, 0, 0.12);
box-shadow: 0 0.0625rem 0.25rem color-mix(in oklab, var(--app-fg) 12%, transparent);
border-radius: 0.25rem;
overflow: hidden;
}
@@ -319,19 +319,13 @@
gap: 0.125rem;
padding: 0.125rem;
border-radius: 0.5rem;
background: rgba(255, 255, 255, 0.9);
background: color-mix(in oklab, var(--app-bg) 90%, transparent);
backdrop-filter: blur(0.5rem);
border: 1px solid rgba(0, 0, 0, 0.08);
box-shadow: 0 0.125rem 0.5rem rgba(0, 0, 0, 0.1);
border: 1px solid var(--app-border);
box-shadow: 0 0.125rem 0.5rem color-mix(in oklab, var(--app-fg) 10%, transparent);
z-index: 10;
}
:global(.dark) .zoom-toolbar {
background: rgba(30, 30, 30, 0.9);
border-color: rgba(255, 255, 255, 0.1);
box-shadow: 0 0.125rem 0.5rem rgba(0, 0, 0, 0.3);
}
.zoom-btn {
display: flex;
align-items: center;
@@ -339,18 +333,13 @@
width: 1.75rem;
height: 1.75rem;
border-radius: 0.375rem;
color: var(--color-gray-500);
color: var(--app-fg-muted);
transition: all 0.1s;
}
.zoom-btn:hover {
background: rgba(0, 0, 0, 0.06);
color: var(--color-gray-700);
}
:global(.dark) .zoom-btn:hover {
background: rgba(255, 255, 255, 0.1);
color: var(--color-gray-300);
background: var(--app-hover);
color: var(--app-fg);
}
.zoom-level {
@@ -359,20 +348,15 @@
font-size: 0.6875rem;
font-weight: 500;
text-align: center;
color: var(--color-gray-500);
color: var(--app-fg-muted);
border-radius: 0.375rem;
font-variant-numeric: tabular-nums;
transition: all 0.1s;
}
.zoom-level:hover {
background: rgba(0, 0, 0, 0.06);
color: var(--color-gray-700);
}
:global(.dark) .zoom-level:hover {
background: rgba(255, 255, 255, 0.1);
color: var(--color-gray-300);
background: var(--app-hover);
color: var(--app-fg);
}
/* ── pdfjs TextLayer styles ─────────────────────────────────── */
@@ -421,7 +405,7 @@
}
:global(.textLayer ::selection) {
background: rgba(0, 100, 255, 0.25);
background: color-mix(in oklab, var(--app-fg) 25%, transparent);
}
:global(.textLayer br::selection) {
@@ -266,16 +266,12 @@
display: flex;
align-items: center;
gap: 0;
border-bottom: 1px solid var(--color-gray-200);
border-bottom: 1px solid var(--app-border);
padding: 0 0.25rem;
flex-shrink: 0;
overflow-x: auto;
}
:global(.dark) .tab-bar {
border-bottom-color: rgba(255, 255, 255, 0.06);
}
.tabs {
display: flex;
gap: 0;
@@ -288,28 +284,19 @@
padding: 0.375rem 0.75rem;
font-size: 0.6875rem;
font-weight: 500;
color: var(--color-gray-500);
color: var(--app-fg-muted);
border-bottom: 0.125rem solid transparent;
transition: all 0.1s;
white-space: nowrap;
}
.tab:hover {
color: var(--color-gray-700);
}
:global(.dark) .tab:hover {
color: var(--color-gray-300);
color: var(--app-fg);
}
.tab.active {
color: var(--color-gray-900);
border-bottom-color: var(--color-gray-900);
}
:global(.dark) .tab.active {
color: white;
border-bottom-color: white;
color: var(--app-fg);
border-bottom-color: var(--app-fg);
}
.query-tab {
@@ -324,49 +311,40 @@
display: flex;
gap: 0.5rem;
padding: 0.5rem 0.75rem;
border-bottom: 1px solid var(--color-gray-100);
border-bottom: 1px solid var(--app-divider);
flex-shrink: 0;
}
:global(.dark) .query-bar {
border-bottom-color: rgba(255, 255, 255, 0.04);
}
.query-input {
flex: 1;
font-family: var(--font-mono);
font-size: 0.75rem;
padding: 0.375rem 0.625rem;
border: 1px solid var(--color-gray-200);
border: 1px solid var(--app-border);
border-radius: 0.375rem;
background: transparent;
color: var(--color-gray-800);
color: var(--app-fg);
resize: vertical;
outline: none;
}
:global(.dark) .query-input {
border-color: rgba(255, 255, 255, 0.1);
color: var(--color-gray-200);
}
.query-input:focus {
border-color: #3b82f6;
border-color: var(--app-fg);
}
.run-btn {
padding: 0.375rem 0.75rem;
font-size: 0.6875rem;
font-weight: 500;
color: white;
background: #2563eb;
color: var(--app-bg);
background: var(--app-fg);
border-radius: 0.375rem;
align-self: flex-end;
transition: background 0.1s;
}
.run-btn:hover {
background: #1d4ed8;
background: var(--app-fg-muted);
}
.query-error {
@@ -400,62 +378,42 @@
}
th {
background: var(--color-gray-50);
color: var(--color-gray-600);
background: var(--app-hover);
color: var(--app-fg-muted);
font-weight: 600;
font-size: 0.6875rem;
padding: 0.3125rem 0.625rem;
text-align: left;
border-bottom: 1px solid var(--color-gray-200);
}
:global(.dark) th {
background: rgba(255, 255, 255, 0.04);
color: var(--color-gray-400);
border-bottom-color: rgba(255, 255, 255, 0.06);
border-bottom: 1px solid var(--app-border);
}
td {
padding: 0.1875rem 0.625rem;
color: var(--color-gray-800);
border-bottom: 1px solid var(--color-gray-100);
}
:global(.dark) td {
color: var(--color-gray-200);
border-bottom-color: rgba(255, 255, 255, 0.04);
color: var(--app-fg);
border-bottom: 1px solid var(--app-divider);
}
tbody tr:hover td {
background: rgba(0, 0, 0, 0.02);
}
:global(.dark) tbody tr:hover td {
background: rgba(255, 255, 255, 0.02);
background: var(--app-hover);
}
.row-num {
color: var(--color-gray-400);
color: var(--app-fg-subtle);
font-size: 0.625rem;
text-align: right;
padding-right: 0.375rem;
user-select: none;
min-width: 2rem;
border-right: 1px solid var(--color-gray-100);
}
:global(.dark) .row-num {
border-right-color: rgba(255, 255, 255, 0.04);
color: var(--color-gray-600);
border-right: 1px solid var(--app-divider);
}
.cell-null {
color: var(--color-gray-400);
color: var(--app-fg-subtle);
font-style: italic;
}
.cell-blob {
color: var(--color-gray-400);
color: var(--app-fg-subtle);
font-style: italic;
}
@@ -475,30 +433,21 @@
justify-content: center;
gap: 0.75rem;
padding: 0.375rem;
border-top: 1px solid var(--color-gray-100);
border-top: 1px solid var(--app-divider);
flex-shrink: 0;
}
:global(.dark) .pagination {
border-top-color: rgba(255, 255, 255, 0.04);
}
.page-btn {
font-size: 0.6875rem;
padding: 0.1875rem 0.625rem;
border-radius: 0.25rem;
color: var(--color-gray-500);
color: var(--app-fg-muted);
transition: all 0.1s;
}
.page-btn:hover:not(:disabled) {
background: var(--color-gray-100);
color: var(--color-gray-700);
}
:global(.dark) .page-btn:hover:not(:disabled) {
background: rgba(255, 255, 255, 0.06);
color: var(--color-gray-300);
background: var(--app-hover);
color: var(--app-fg);
}
.page-btn:disabled {
@@ -508,7 +457,7 @@
.page-info {
font-size: 0.6875rem;
color: var(--color-gray-400);
color: var(--app-fg-subtle);
font-variant-numeric: tabular-nums;
}
</style>
@@ -125,14 +125,10 @@
justify-content: space-between;
height: 2.25rem;
padding: 0 0.75rem;
border-bottom: 1px solid var(--color-gray-200);
border-bottom: 1px solid var(--app-border);
flex-shrink: 0;
}
:global(.dark) .toolbar {
border-bottom-color: rgba(255, 255, 255, 0.06);
}
.toolbar-left {
display: flex;
align-items: center;
@@ -147,7 +143,7 @@
.file-label {
font-size: 0.6875rem;
font-weight: 500;
color: var(--color-gray-500);
color: var(--app-fg-muted);
}
.toolbar-btn {
@@ -158,24 +154,16 @@
height: 1.5rem;
padding: 0 0.25rem;
border-radius: 0.375rem;
color: var(--color-gray-400);
color: var(--app-fg-subtle);
transition: all 0.1s;
}
.toolbar-btn:hover {
color: var(--color-gray-600);
}
:global(.dark) .toolbar-btn:hover {
color: var(--color-gray-300);
color: var(--app-fg-muted);
}
.toolbar-btn.active {
color: var(--color-gray-900);
}
:global(.dark) .toolbar-btn.active {
color: white;
color: var(--app-fg);
}
.zoom-text {
@@ -193,12 +181,7 @@
width: 100%;
height: 100%;
overflow: hidden;
background: repeating-conic-gradient(var(--color-gray-100) 0% 25%, transparent 0% 50%) 50% /
1rem 1rem;
}
:global(.dark) .visual-container {
background: repeating-conic-gradient(rgba(255, 255, 255, 0.04) 0% 25%, transparent 0% 50%) 50% /
background: repeating-conic-gradient(var(--app-hover) 0% 25%, transparent 0% 50%) 50% /
1rem 1rem;
}
@@ -225,12 +208,9 @@
font-family: var(--font-mono);
font-size: 0.78125rem;
line-height: 1.6;
color: var(--color-gray-800);
color: var(--app-fg);
white-space: pre-wrap;
word-break: break-all;
}
:global(.dark) .source-view {
color: var(--color-gray-200);
}
</style>
+35 -44
View File
@@ -110,21 +110,15 @@ export interface HomeState {
splitDirection: SplitDirection;
}
export type ToolApprovalMode = 'ask' | 'auto' | 'full';
export interface UserPreferences {
theme?: Theme;
appearance?: AppearancePreferences;
sidebarOpen: boolean;
sidebarWidth: number;
toolApprovalMode: ToolApprovalMode;
planMode: boolean;
locale: string;
workspaceOrder?: string[]; // ordered paths for sidebar drag-reorder
keybindings?: Record<string, string>; // user-customised keyboard shortcuts
version?: string; // last seen app version for changelog
selectedModelId?: string; // last selected chat model, synced across browsers
requestParams?: Record<string, unknown>; // arbitrary params merged into API request body
showUpdateToast?: boolean; // show version update notifications (default true)
pwa?: PwaPreferences;
textScale?: number | null;
@@ -304,9 +298,6 @@ if (typeof window !== 'undefined') {
}
export const sidebarWidth = writable(220);
export const theme = writable<Theme>('dark');
export const toolApprovalMode = writable<ToolApprovalMode>('auto');
export const planMode = writable(false);
export const requestParams = writable<Record<string, unknown>>({});
export const appVersion = writable('');
export const lastSeenVersion = writable('');
export const latestVersion = writable('');
@@ -323,19 +314,11 @@ export const updateAvailable = derived([appVersion, latestVersion], ([$app, $lat
export const showChangelog = writable(false);
export const showUpdateToastPref = writable(true);
export const showSearch = writable(false);
/** @deprecated Use toolApprovalMode */
export const autoApproveTools = {
subscribe: toolApprovalMode.subscribe,
set: (v: boolean) => toolApprovalMode.set(v ? 'full' : 'ask'),
update: (fn: (v: boolean) => boolean) =>
toolApprovalMode.update((m) => (fn(m === 'full') ? 'full' : 'ask'))
};
export const stateLoaded = writable(false);
export const gitReviewOpen = writable(false);
export const isGitRepo = writable(false);
export type StreamingBehavior = 'queue' | 'interrupt';
export const streamingBehavior = writable<StreamingBehavior>('queue');
export const selectedModelId = writable<string>('');
export const pwaPreferences = writable<PwaPreferences>(defaultPwaPreferences);
export const themeConfig = writable<ThemeConfig | null>(null);
export const textScale = writable<number | null>(null);
@@ -439,14 +422,10 @@ function persistPreferences(): void {
},
sidebarOpen: get(sidebarOpen),
sidebarWidth: get(sidebarWidth),
toolApprovalMode: get(toolApprovalMode),
planMode: get(planMode),
locale: i18next.language,
workspaceOrder: get(workspaceOrder),
keybindings: get(keybindings),
version: get(lastSeenVersion),
selectedModelId: get(selectedModelId) || undefined,
requestParams: Object.keys(get(requestParams)).length ? get(requestParams) : undefined,
showUpdateToast: get(showUpdateToastPref),
pwa: get(pwaPreferences),
textScale: get(textScale),
@@ -480,15 +459,6 @@ function subscribeForPersistence() {
sidebarWidth.subscribe(() => {
if (get(stateLoaded)) persistPreferences();
});
toolApprovalMode.subscribe(() => {
if (get(stateLoaded)) persistPreferences();
});
planMode.subscribe(() => {
if (get(stateLoaded)) persistPreferences();
});
requestParams.subscribe(() => {
if (get(stateLoaded)) persistPreferences();
});
workspaceOrder.subscribe(() => {
if (get(stateLoaded)) persistPreferences();
});
@@ -498,9 +468,6 @@ function subscribeForPersistence() {
lastSeenVersion.subscribe(() => {
if (get(stateLoaded)) persistPreferences();
});
selectedModelId.subscribe(() => {
if (get(stateLoaded)) persistPreferences();
});
showUpdateToastPref.subscribe(() => {
if (get(stateLoaded)) persistPreferences();
});
@@ -533,20 +500,10 @@ export async function loadPreferences(): Promise<void> {
themeConfig.set(sanitizeThemeConfig(appearance.themeConfig));
if (prefs.sidebarOpen !== undefined) sidebarOpen.set(prefs.sidebarOpen as boolean);
if (prefs.sidebarWidth !== undefined) sidebarWidth.set(prefs.sidebarWidth as number);
// Support new toolApprovalMode and legacy boolean autoApproveTools
if (prefs.toolApprovalMode) {
toolApprovalMode.set(prefs.toolApprovalMode as ToolApprovalMode);
} else if (prefs.autoApproveTools !== undefined) {
// Legacy boolean migration
toolApprovalMode.set((prefs.autoApproveTools as unknown as boolean) ? 'full' : 'ask');
}
if (prefs.planMode !== undefined) planMode.set(prefs.planMode as boolean);
if (prefs.locale) changeLocale(prefs.locale as string);
if (Array.isArray(prefs.workspaceOrder)) workspaceOrder.set(prefs.workspaceOrder as string[]);
if (prefs.keybindings) loadKeybindings(prefs.keybindings as Record<string, string>);
if (prefs.version) lastSeenVersion.set(prefs.version as string);
if (prefs.selectedModelId) selectedModelId.set(prefs.selectedModelId as string);
if (prefs.requestParams) requestParams.set(prefs.requestParams as Record<string, unknown>);
if (prefs.showUpdateToast !== undefined)
showUpdateToastPref.set(prefs.showUpdateToast as boolean);
textScale.set(
@@ -988,7 +945,10 @@ export function openFileTab(
options: { edit?: boolean; searchTarget?: FileSearchTarget } = {}
): void {
const ws = get(currentWorkspace);
if (!ws) return;
if (!ws) {
openHomeFileTab(filePath, targetGroupId, options);
return;
}
const gid = targetGroupId ?? ws.activeGroupId;
const group = ws.groups.find((g) => g.id === gid);
@@ -1028,6 +988,37 @@ export function openFileTab(
}));
}
function openHomeFileTab(
filePath: string,
targetGroupId?: string,
options: { edit?: boolean; searchTarget?: FileSearchTarget } = {}
): void {
const state = get(homeState);
const groupId = targetGroupId ?? state.activeGroupId;
const group = state.groups.find((item) => item.id === groupId);
if (!group) return;
const existing = group.tabs.find((tab) => tab.type === 'file' && tab.filePath === filePath);
const tab: Tab = existing ?? {
id: nextId(),
type: 'file',
label: getPathDisplayName(filePath, filePath),
filePath,
edit: options.edit,
searchTarget: options.searchTarget
};
const updateGroup = (group: EditorGroup) =>
group.id === groupId
? { ...group, tabs: existing ? group.tabs : [...group.tabs, tab], activeTabId: tab.id }
: group;
homeState.update((current) => ({
...current,
activeGroupId: groupId,
groups: current.groups.map(updateGroup)
}));
}
export function openUntitledFileTab(targetGroupId?: string): void {
// Find the lowest unused number across ALL groups
const ws = get(currentWorkspace);
-1
View File
@@ -23,7 +23,6 @@ export const ttsVoice = writable<string>('alloy');
export const ttsFormat = writable<string>('mp3');
export const ttsPlaybackSpeed = writable<number>(1);
export const ttsAutoStreamEnabled = writable<boolean>(false);
export const voiceModeEnabled = writable<boolean>(false);
export const voiceModeSttMode = writable<'browser' | 'provider'>('browser');
export const ttsPlaybackEnabled = writable<boolean>(
typeof localStorage !== 'undefined'
+17 -5
View File
@@ -1042,12 +1042,23 @@
? undefined
: tab.path}
tabId={tab.id}
active={tab.id === homePane.activeTabId}
ontabupdate={(tabId, chatId, label) =>
updateHomeChatTab(tabId, chatId, label, homePane.id)}
onopenchat={(chatId) => openHomeChat(chatId, homePane.id)}
/>
</div>
{/each}
{#each homePane.tabs.filter((tab) => tab.type === 'file' && tab.filePath) as tab (tab.id)}
<div class="persisted-tab" class:persisted-tab-hidden={tab.id !== homePane.activeTabId}>
<FileEditor
filePath={tab.filePath!}
tabId={tab.id}
edit={tab.edit === true}
searchTarget={tab.searchTarget}
/>
</div>
{/each}
{#each homePane.tabs.filter((tab) => tab.type === 'terminal' && tab.sessionId) as tab (tab.id)}
<div class="persisted-tab" class:persisted-tab-hidden={tab.id !== homePane.activeTabId}>
<Terminal sessionId={tab.sessionId!} />
@@ -1373,6 +1384,7 @@
? undefined
: tab.path}
tabId={tab.id}
active={tab.id === group.activeTabId}
/>
</div>
{/each}
@@ -1530,11 +1542,11 @@
height: 100%;
left: 50%;
transform: translateX(-50%);
background: oklch(0.92 0 0);
background: var(--app-divider);
}
:global(.dark) .split-divider-h::before {
background: rgba(255, 255, 255, 0.06);
background: var(--app-divider);
}
.split-divider-v::before {
@@ -1542,16 +1554,16 @@
width: 100%;
top: 50%;
transform: translateY(-50%);
background: oklch(0.92 0 0);
background: var(--app-divider);
}
:global(.dark) .split-divider-v::before {
background: rgba(255, 255, 255, 0.06);
background: var(--app-divider);
}
.split-divider:hover,
.is-dragging .split-divider {
background: rgba(150, 150, 150, 0.12);
background: var(--app-active);
}
/* Drag state */
+107
View File
@@ -502,6 +502,11 @@ class UpdateChatRequest(BaseModel):
title: str
class UpdateChatSettingsRequest(BaseModel):
model_id: str
params: dict = {}
@router.patch("/{chat_id}")
async def update_chat(chat_id: str, body: UpdateChatRequest, request: Request):
"""Rename a chat."""
@@ -521,6 +526,21 @@ async def update_chat(chat_id: str, body: UpdateChatRequest, request: Request):
return {"ok": True, "title": title}
@router.patch("/{chat_id}/settings")
async def update_chat_settings(chat_id: str, body: UpdateChatSettingsRequest, request: Request):
"""Save composer settings for one chat."""
user_id = _get_user(request)
chat = await Chat.get_by_id(chat_id)
if not chat or chat.user_id != user_id:
raise HTTPException(404, "chat not found")
meta = dict(chat.meta or {})
meta["last_model"] = body.model_id
meta["params"] = body.params
await Chat.update_meta(chat_id, meta, now_ms())
return {"ok": True}
@router.delete("/{chat_id}")
async def delete_chat(chat_id: str, request: Request):
"""Delete a chat and all its messages."""
@@ -849,6 +869,93 @@ class ApproveRequest(BaseModel):
approved: bool = True
class AskUserAnswerRequest(BaseModel):
call_id: str
answers: dict[str, str]
timed_out: bool = False
class AskUserNotPendingError(ValueError):
pass
async def resolve_ask_user(
app,
chat_id: str,
message_id: str,
call_id: str,
answers: dict[str, str] | None,
timed_out: bool,
):
chat = await Chat.get_by_id(chat_id)
msg = await ChatMessage.get_by_id(message_id)
if not chat or not msg or msg.chat_id != chat_id:
raise AskUserNotPendingError("ask_user request is no longer pending")
output = list(msg.output or [])
call = next(
(
item
for item in output
if item.get("type") == "function_call"
and item.get("name") == "ask_user"
and item.get("call_id") == call_id
and item.get("status") == "pending"
),
None,
)
if not call:
raise AskUserNotPendingError("ask_user request is no longer pending")
if timed_out and now_ms() < int(call.get("expires_at") or 0):
raise AskUserNotPendingError("ask_user request has not timed out")
from cptr.utils.chat_task import ask_user_answers, start_task
from cptr.utils.model_targets import resolve_model_target
from cptr.socket.main import emit_to_user
result = ask_user_answers(call.get("arguments") or {}, None if timed_out else answers)
if timed_out:
result["timed_out"] = True
call["status"] = "completed"
call["timed_out"] = timed_out
output.append(
{"type": "function_call_output", "call_id": call_id, "output": json.dumps(result)}
)
await ChatMessage.update(message_id, output=output, done=False)
await emit_to_user(chat.user_id, {"chat_id": chat_id, "message_id": message_id, "output": call})
await emit_to_user(
chat.user_id, {"chat_id": chat_id, "message_id": message_id, "output": output[-1]}
)
target = await resolve_model_target(msg.model or "", app.state)
start_task(
message_id=message_id,
chat_id=chat_id,
user_id=chat.user_id,
workspace=(chat.meta or {}).get("workspace", ""),
target=target,
)
@router.post("/{chat_id}/messages/{message_id}/answer")
async def answer_ask_user(
chat_id: str, message_id: str, body: AskUserAnswerRequest, request: Request
):
"""Resolve a pending Plan-mode ask_user request and resume the chat."""
user_id = _get_user(request)
chat = await Chat.get_by_id(chat_id)
if not chat or chat.user_id != user_id:
raise HTTPException(404, "chat not found")
try:
await resolve_ask_user(
request.app, chat_id, message_id, body.call_id, body.answers, body.timed_out
)
except AskUserNotPendingError as exc:
raise HTTPException(409, str(exc)) from exc
except ValueError as exc:
raise HTTPException(422, str(exc)) from exc
return {"ok": True}
@router.post("/{chat_id}/messages/{message_id}/approve")
async def approve_tool(chat_id: str, message_id: str, body: ApproveRequest, request: Request):
"""Execute or reject a pending tool call, then continue."""
+32
View File
@@ -16,6 +16,8 @@ sio = socketio.AsyncServer(async_mode="asgi", cors_allowed_origins=CORS_ALLOWED_
# user_id → set of connected sids
_user_sids: dict[str, set[str]] = {}
# (user_id, chat_id) → visible panel instances
_chat_view_sids: dict[tuple[str, str], set[tuple[str, str]]] = {}
@sio.on("connect")
@@ -47,6 +49,32 @@ async def on_disconnect(sid):
_user_sids[uid].discard(sid)
if not _user_sids[uid]:
del _user_sids[uid]
for key, views in list(_chat_view_sids.items()):
views_copy = {view for view in views if view[0] != sid}
if views_copy:
_chat_view_sids[key] = views_copy
else:
del _chat_view_sids[key]
@sio.on("chat:view")
async def on_chat_view(sid, data):
"""Track which chat panels are currently visible for timeout pausing."""
session = await sio.get_session(sid)
user_id = session.get("user_id")
chat_id = data.get("chat_id") if isinstance(data, dict) else None
view_id = data.get("view_id") if isinstance(data, dict) else None
if not user_id or not isinstance(chat_id, str) or not isinstance(view_id, str):
return
views = _chat_view_sids.setdefault((user_id, chat_id), set())
view = (sid, view_id)
if data.get("visible"):
views.add(view)
else:
views.discard(view)
if not views:
del _chat_view_sids[(user_id, chat_id)]
async def emit_to_user(user_id: str, data: dict):
@@ -55,6 +83,10 @@ async def emit_to_user(user_id: str, data: dict):
await sio.emit("events:chat", data, to=sid)
def is_chat_visible(user_id: str, chat_id: str) -> bool:
return bool(_chat_view_sids.get((user_id, chat_id)))
def is_user_active(user_id: str) -> bool:
"""Return True when the user has at least one connected app session."""
return bool(_user_sids.get(user_id))
+216 -4
View File
@@ -10,6 +10,7 @@ import json
import logging
import re
import uuid
from typing import Any
from cptr.events import EVENTS, publish_event
from cptr.env import CHAT_MAX_ITERATIONS, CHAT_TOOL_COMMAND_MAX_CHARS, CHAT_TOOL_MAX_CHARS
@@ -58,10 +59,118 @@ from cptr.utils.model_targets import AgentModelTarget, ApiModelTarget, ModelTarg
logger = logging.getLogger(__name__)
ASK_USER_NAME = "ask_user"
DEFAULT_AUTO_RESOLUTION_MS = 120_000
ASK_USER_SCHEMA = {
"name": ASK_USER_NAME,
"description": "Ask the user one to three material planning questions and wait for their answers.",
"parameters": {
"type": "object",
"properties": {
"questions": {
"type": "array",
"minItems": 1,
"maxItems": 3,
"items": {
"type": "object",
"properties": {
"id": {"type": "string"},
"header": {"type": "string"},
"question": {"type": "string"},
"options": {
"type": "array",
"minItems": 2,
"maxItems": 3,
"items": {
"type": "object",
"properties": {
"label": {"type": "string"},
"description": {"type": "string"},
},
"required": ["label", "description"],
},
},
},
"required": ["id", "header", "question", "options"],
},
},
"autoResolutionMs": {
"type": "integer",
"minimum": 60_000,
"maximum": 240_000,
"default": DEFAULT_AUTO_RESOLUTION_MS,
},
},
"required": ["questions"],
},
}
def validate_ask_user_request(arguments: dict[str, Any]) -> dict[str, Any]:
questions = arguments.get("questions")
if not isinstance(questions, list) or not questions:
raise ValueError("ask_user requires one to three questions")
questions = questions[:3]
normalized_questions = []
ids: set[str] = set()
for question in questions:
if not isinstance(question, dict):
raise ValueError("each question must be an object")
if not all(
isinstance(question.get(key), str) and question[key].strip()
for key in ("id", "header", "question")
):
raise ValueError("each question needs an id, header, and question")
if question["id"] in ids:
raise ValueError("question ids must be unique")
ids.add(question["id"])
options = question.get("options")
if not isinstance(options, list) or len(options) < 2:
raise ValueError("each question requires two or three options")
options = options[:3]
if any(
not isinstance(option, dict)
or not isinstance(option.get("label"), str)
or not option["label"].strip()
or not isinstance(option.get("description"), str)
or not option["description"].strip()
for option in options
):
raise ValueError("each option needs a label and description")
normalized_questions.append({**question, "options": options})
timeout = arguments.get("autoResolutionMs", DEFAULT_AUTO_RESOLUTION_MS)
if (
isinstance(timeout, bool)
or not isinstance(timeout, int)
or not 60_000 <= timeout <= 240_000
):
timeout = DEFAULT_AUTO_RESOLUTION_MS
return {"questions": normalized_questions, "autoResolutionMs": timeout}
def ask_user_answers(
arguments: dict[str, Any], answers: dict[str, str] | None = None
) -> dict[str, Any]:
request = validate_ask_user_request(arguments)
result: dict[str, Any] = {}
for question in request["questions"]:
answer = question["options"][0]["label"] if answers is None else answers.get(question["id"])
if not isinstance(answer, str) or not answer.strip():
raise ValueError(f"missing answer for {question['id']}")
result[question["id"]] = {"answers": [answer.strip()]}
if answers is not None and set(answers) != set(result):
raise ValueError("answers must match the requested question ids")
return {"answers": result}
PLAN_MODE_PROMPT = (
"[Plan Mode] Research the codebase with read-only tools, then present your plan "
"using create_artifact. Then wait for an explicit approval message before using "
"tools or implementing."
"[Plan Mode] Research with read-only tools before planning. When a material decision "
"cannot be discovered, use ask_user with one to three questions, two to three options "
"each, and the recommended option first. Ask only after research and never alongside "
"another tool call. Then present a concise plan in your response. Use create_artifact "
"only when a substantial plan or analysis benefits from being saved for review. Wait for "
"an explicit "
"approval message before using write tools or implementing."
)
SKILLS_CREATE_RE = re.compile(r"^/skills:create(?:\s+(.*))?$", re.IGNORECASE | re.DOTALL)
@@ -1848,8 +1957,8 @@ async def run_chat_task(
if plan_mode:
tools = [t for t in tools if ALL_TOOLS.get(t["name"], {}).get("auto")]
tools = [t for t in tools if t["name"] not in {"delegate_task", "update_memory"}]
# Inject create_artifact (only available in plan mode)
tools.append(_fn_to_schema("create_artifact", create_artifact))
tools.append(ASK_USER_SCHEMA)
messages.append({"role": "user", "content": PLAN_MODE_PROMPT})
logger.info(
"[task %s] plan mode active, %d tools available", message_id[:8], len(tools)
@@ -2011,6 +2120,7 @@ async def run_chat_task(
restart = False
pending_calls: list[dict] = [] # Collect tool calls from this response
pending_call_ids: set[str] = set()
response_reasoning_items: list[dict] = [] # Pair with tool outputs on the next request
streamed_reasoning_chars = 0
@@ -2023,6 +2133,16 @@ async def run_chat_task(
elif event["type"] == "tool_call":
# Collect tool call — don't execute yet
call_id = event["call_id"]
if call_id in pending_call_ids:
logger.warning(
"[task %s] ignoring duplicate tool call id=%s name=%s",
message_id[:8],
call_id,
event["name"],
)
continue
pending_call_ids.add(call_id)
pending_calls.append(event)
elif event["type"] in ("output", "reasoning"):
@@ -2113,6 +2233,98 @@ async def run_chat_task(
"builtin_tools": builtin_tools,
}
ask_user_calls = [tc for tc in pending_calls if tc["name"] == ASK_USER_NAME]
if ask_user_calls:
tc = ask_user_calls[0]
error = None
if len(pending_calls) != 1:
error = "Error: ask_user must be called by itself after research."
elif len(ask_user_calls) != 1:
error = "Error: only one ask_user call is allowed per turn."
else:
try:
arguments = validate_ask_user_request(tc["arguments"])
except ValueError as exc:
error = f"Error: {exc}"
if error:
item = {
"type": "function_call",
"id": str(uuid.uuid4()),
"call_id": tc["call_id"],
"fc_id": tc.get("id", ""),
"name": ASK_USER_NAME,
"arguments": tc["arguments"],
"status": "completed",
}
result_item = {
"type": "function_call_output",
"call_id": tc["call_id"],
"output": error,
}
output_items.extend((item, result_item))
if flushed_item:
await emit(output=flushed_item)
await emit(output=item)
await emit(output=result_item)
_sync_state()
_append_batch_to_messages(
messages,
[(tc, error)],
provider,
reasoning_items=response_reasoning_items,
)
new_messages_since += 2
await _save_message(
"invalid ask_user", content=content, output=output_items
)
continue
expires_at = now_ms() + arguments["autoResolutionMs"]
item = {
"type": "function_call",
"id": str(uuid.uuid4()),
"call_id": tc["call_id"],
"fc_id": tc.get("id", ""),
"name": ASK_USER_NAME,
"arguments": arguments,
"status": "pending",
"expires_at": expires_at,
}
output_items.append(item)
await _save_message(
"pending ask_user",
content=content,
output=output_items,
done=False,
)
if flushed_item:
await emit(output=flushed_item)
await emit(output=item)
_task_state.pop(message_id, None)
async def auto_answer():
from cptr.socket.main import is_chat_visible
remaining = arguments["autoResolutionMs"] / 1000
while remaining > 0:
await asyncio.sleep(1)
if not is_chat_visible(user_id, chat_id):
remaining -= 1
from cptr.app import app
from cptr.routers.chat import AskUserNotPendingError, resolve_ask_user
try:
await resolve_ask_user(
app, chat_id, message_id, tc["call_id"], None, True
)
except AskUserNotPendingError:
pass
asyncio.create_task(auto_answer())
await emit(done=True)
return
# Check if any call needs approval
needs_approval = None
for tc in pending_calls:
+1 -1
View File
@@ -1,6 +1,6 @@
[project]
name = "cptr"
version = "0.9.1"
version = "0.9.2"
description = "Your computer, from anywhere. Code, manage, and control your machine from the web."
license = {file = "LICENSE"}
readme = "README.md"
Generated
+1 -1
View File
@@ -284,7 +284,7 @@ wheels = [
[[package]]
name = "cptr"
version = "0.9.1"
version = "0.9.2"
source = { editable = "." }
dependencies = [
{ name = "aiosqlite" },