Merge pull request #33 from open-webui/main

0.2.1
This commit is contained in:
Tim Baek
2026-06-11 04:38:03 -05:00
committed by GitHub
Unverified
33 changed files with 1249 additions and 898 deletions
+1 -1
View File
@@ -1 +1 @@
3.9
3.13
+26
View File
@@ -5,6 +5,32 @@ 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.2.1] - 2026-06-11
### Added
- 🔍 **Global search modal.** New unified search (⌘K / ⌘⇧F) that finds chats by title *and* message content, plus files by name — across all workspaces or scoped to the active one. Shows recent chats when the query is empty. Replaces the old QuickOpen modal.
- 🌐 **Perplexity web search provider.** Added Perplexity as a first-class search provider (auto-detected between Exa and Tavily when `PERPLEXITY_API_KEY` is set).
- 🌐 **Chat Completions search provider.** Any OpenAI-compatible `/chat/completions` endpoint (e.g. Perplexity Sonar, LiteLLM proxy) can now be used for web search. Configure via Settings or environment variables.
- ➕ **New Chat button per workspace.** Each workspace row in the sidebar now shows a pencil icon on hover to quickly create a new chat.
### Fixed
- 🔍 **Search no longer pinned to last workspace.** When on a non-workspace page (e.g. Automations), search results are now global instead of silently scoped to the last-selected workspace.
- 🔄 **Sidebar chat cache invalidated globally.** Chat events from automations or other tabs now clear the cache for *all* workspaces, so re-expanding any workspace shows fresh data.
- 🔄 **New chats from automations appear in landing page.** The chat landing now debounce-reloads when it receives a socket event for an unknown chat, so automation-created chats appear without a manual refresh.
- 🏷️ **Chat tab labels update from DB title.** Opening a chat from search or sidebar now shows the real title instead of a generic "Chat" label.
- 🔁 **Duplicate new-chat tabs prevented.** Opening a new chat reuses an existing empty/pending chat tab instead of creating duplicates.
### Changed
- 🔗 **URL-driven navigation for chat and file intents.** Clicking a chat or file in the sidebar/search now uses URL query params (`chatId`, `file`, `dir`) which are consumed and cleaned up after navigation, enabling deep-linking and back-button support.
- 🍞 **Improved toast notifications.** Toaster now uses rich colors and close buttons for better visibility.
- 🔒 **Automations sidebar link hidden when chat is disabled.** The Automations nav item is now conditionally shown only when the chat/LLM backend is available.
- ⬆️ **Python 3.10 minimum.** Bumped `requires-python` from `>=3.9` to `>=3.10`.
- 📦 **Added `truststore` dependency.** Uses platform-native TLS certificate stores for better certificate handling.
- 🌍 **i18n for search UI.** Search-related strings added across all 10 supported locales.
## [0.2.0] - 2026-06-09
### Added
+2
View File
@@ -32,6 +32,8 @@ Read our [Manifesto](MANIFESTO.md).
pip install cptr
```
Or with [uv](https://docs.astral.sh/uv/): `uvx cptr@latest run`
## Run
```bash
+10
View File
@@ -14,6 +14,7 @@ from cptr.routers import (
files_router,
git_router,
proxy_router,
search_router,
state_router,
terminal_router,
workspace_router,
@@ -27,6 +28,14 @@ app = FastAPI()
@app.on_event("startup")
async def startup():
# Use OS certificate store (Windows CertStore, macOS Keychain, etc.)
# instead of the bundled certifi CA bundle — fixes #31.
import logging as _logging
import truststore
truststore.inject_into_ssl()
_logging.getLogger(__name__).info("truststore: using system certificate store")
await init_db()
from cptr.env import STARTUP_TOKEN
@@ -182,6 +191,7 @@ app.include_router(events_router)
app.include_router(files_router)
app.include_router(git_router)
app.include_router(proxy_router)
app.include_router(search_router)
app.include_router(state_router)
app.include_router(terminal_router)
app.include_router(workspace_router)
+47
View File
@@ -0,0 +1,47 @@
/**
* Unified search API: chats + files in one request.
*/
import { fetchJSON } from '$lib/apis';
export interface ChatSearchResult {
id: string;
title: string;
summary: string | null;
workspace: string;
updated_at: number;
created_at: number;
match_type: 'title' | 'message';
snippet: string | null;
}
export interface FileSearchResult {
path: string;
name: string;
type: 'file' | 'directory';
workspace: string;
}
export interface UnifiedSearchResponse {
chats: ChatSearchResult[];
files: FileSearchResult[];
}
export const unifiedSearch = (
query: string,
workspaces: string[],
workspace?: string,
chatLimit = 10,
fileLimit = 10
) => {
const params = new URLSearchParams({
q: query,
chat_limit: String(chatLimit),
file_limit: String(fileLimit)
});
if (workspace) params.set('workspace', workspace);
workspaces.forEach((w) => params.append('workspaces', w));
return fetchJSON<UnifiedSearchResponse>(`/api/search?${params}`);
};
export const getRecentChats = (limit = 9) =>
fetchJSON<{ chats: ChatSearchResult[] }>(`/api/search/recent?limit=${limit}`);
@@ -14,6 +14,10 @@
let exaKey = $state('');
let tavilyKey = $state('');
let braveKey = $state('');
let perplexityKey = $state('');
let ccKey = $state('');
let ccBaseUrl = $state('');
let ccModel = $state('');
async function loadConfig() {
try {
@@ -21,6 +25,10 @@
exaKey = config['web.exa_api_key'] || '';
tavilyKey = config['web.tavily_api_key'] || '';
braveKey = config['web.brave_api_key'] || '';
perplexityKey = config['web.perplexity_api_key'] || '';
ccKey = config['web.chat_completions_api_key'] || '';
ccBaseUrl = config['web.chat_completions_base_url'] || '';
ccModel = config['web.chat_completions_model'] || '';
} catch {
toast.error($t('admin.failedToLoadConfig'));
} finally {
@@ -106,7 +114,9 @@
<option value="exa">Exa</option>
<option value="tavily">Tavily</option>
<option value="brave">Brave</option>
<option value="perplexity">Perplexity</option>
<option value="duckduckgo">DuckDuckGo</option>
<option value="chat_completions">{$t('admin.webChatCompletions')}</option>
</select>
</div>
@@ -170,6 +180,68 @@
<p class="text-[11px] text-gray-400 dark:text-gray-600 mt-2">
{$t('admin.webDuckDuckGoNote')}
</p>
{:else if provider === 'perplexity'}
<div class="mt-3">
<label class="block text-[13px] text-gray-700 dark:text-gray-300 mb-1"
>{$t('admin.webPerplexityKey')}</label
>
<input
type="password"
class="w-full text-[13px] bg-gray-50 dark:bg-white/4 border border-gray-200 dark:border-white/8 rounded-lg px-2.5 py-1.5 outline-none text-gray-700 dark:text-gray-300 placeholder:text-gray-400 dark:placeholder:text-gray-600"
placeholder="pplx-..."
bind:value={perplexityKey}
onblur={() => saveKey('web.perplexity_api_key', perplexityKey)}
disabled={saving}
/>
<p class="text-[11px] text-gray-400 dark:text-gray-600 mt-0.5">
{$t('admin.webPerplexityHint')}
</p>
</div>
{:else if provider === 'chat_completions'}
<div class="mt-3 space-y-3">
<div>
<label class="block text-[13px] text-gray-700 dark:text-gray-300 mb-1"
>{$t('admin.webCcBaseUrl')}</label
>
<input
type="text"
class="w-full text-[13px] bg-gray-50 dark:bg-white/4 border border-gray-200 dark:border-white/8 rounded-lg px-2.5 py-1.5 outline-none text-gray-700 dark:text-gray-300 placeholder:text-gray-400 dark:placeholder:text-gray-600"
placeholder="https://api.perplexity.ai/v1"
bind:value={ccBaseUrl}
onblur={() => saveKey('web.chat_completions_base_url', ccBaseUrl)}
disabled={saving}
/>
</div>
<div>
<label class="block text-[13px] text-gray-700 dark:text-gray-300 mb-1"
>{$t('admin.webCcKey')}</label
>
<input
type="password"
class="w-full text-[13px] bg-gray-50 dark:bg-white/4 border border-gray-200 dark:border-white/8 rounded-lg px-2.5 py-1.5 outline-none text-gray-700 dark:text-gray-300 placeholder:text-gray-400 dark:placeholder:text-gray-600"
placeholder="sk-..."
bind:value={ccKey}
onblur={() => saveKey('web.chat_completions_api_key', ccKey)}
disabled={saving}
/>
</div>
<div>
<label class="block text-[13px] text-gray-700 dark:text-gray-300 mb-1"
>{$t('admin.webCcModel')}</label
>
<input
type="text"
class="w-full text-[13px] bg-gray-50 dark:bg-white/4 border border-gray-200 dark:border-white/8 rounded-lg px-2.5 py-1.5 outline-none text-gray-700 dark:text-gray-300 placeholder:text-gray-400 dark:placeholder:text-gray-600"
placeholder="sonar-pro"
bind:value={ccModel}
onblur={() => saveKey('web.chat_completions_model', ccModel)}
disabled={saving}
/>
</div>
<p class="text-[11px] text-gray-400 dark:text-gray-600">
{$t('admin.webCcHint')}
</p>
</div>
{/if}
{/if}
@@ -0,0 +1,313 @@
<script lang="ts">
import { workspaceList, currentWorkspace, showSearch } from '$lib/stores';
import {
unifiedSearch,
getRecentChats,
type ChatSearchResult,
type FileSearchResult
} from '$lib/apis/search';
import { goto } from '$app/navigation';
import { page } from '$app/stores';
import Modal from './Modal.svelte';
import Icon from './Icon.svelte';
import KeyPill from './KeyPill.svelte';
import Spinner from './common/Spinner.svelte';
import { t } from '$lib/i18n';
interface Props {
onclose: () => void;
}
let { onclose }: Props = $props();
let query = $state('');
let chatResults = $state<ChatSearchResult[]>([]);
let fileResults = $state<FileSearchResult[]>([]);
let recentChats = $state<ChatSearchResult[]>([]);
let loading = $state(false);
let selectedIndex = $state(0);
let inputEl: HTMLInputElement | undefined = $state();
let debounceTimer: ReturnType<typeof setTimeout> | null = null;
let resultsEl: HTMLDivElement | undefined = $state();
// Determine active workspace from the URL, not the store.
// When on /automations or other non-workspace pages, $currentWorkspace
// retains the last workspace but we should search across all.
const urlWorkspacePath = $derived($page.url.searchParams.get('workspace'));
const effectiveWorkspace = $derived(
urlWorkspacePath ? $currentWorkspace : null
);
// Show recents when no query, search results when query exists
const showingRecents = $derived(!query.trim());
const filteredRecents = $derived(
effectiveWorkspace
? recentChats.filter((c) => c.workspace === effectiveWorkspace!.path)
: recentChats
);
const displayedChats = $derived(showingRecents ? filteredRecents : chatResults);
const totalResults = $derived(displayedChats.length + fileResults.length);
$effect(() => {
requestAnimationFrame(() => inputEl?.focus());
});
// Load recent chats on mount
$effect(() => {
loadRecents();
});
async function loadRecents() {
try {
const data = await getRecentChats(9);
recentChats = data.chats;
} catch {
// ignore
}
}
$effect(() => {
if (debounceTimer) clearTimeout(debounceTimer);
if (!query.trim()) {
chatResults = [];
fileResults = [];
loading = false;
selectedIndex = 0;
return;
}
loading = true;
debounceTimer = setTimeout(() => doSearch(query), 250);
});
// When a workspace is explicitly active via URL, scope to files from that workspace only
const isWorkspaceScoped = $derived(!!effectiveWorkspace);
async function doSearch(q: string) {
const activeWs = effectiveWorkspace;
if (activeWs) {
// Workspace active: search chats + files scoped to this workspace
try {
const data = await unifiedSearch(q, [activeWs.path], activeWs.path);
chatResults = data.chats;
fileResults = data.files;
selectedIndex = 0;
} catch {
// ignore
} finally {
loading = false;
}
} else {
// No workspace: full search across all workspaces
const wsPaths = $workspaceList.map((w) => w.path);
if (wsPaths.length === 0) {
chatResults = [];
fileResults = [];
loading = false;
return;
}
try {
const data = await unifiedSearch(q, wsPaths);
chatResults = data.chats;
fileResults = data.files;
selectedIndex = 0;
} catch {
// ignore
} finally {
loading = false;
}
}
}
function workspaceName(wsPath: string): string {
const ws = $workspaceList.find((w) => w.path === wsPath);
if (ws) return ws.name;
const parts = wsPath.split('/');
return parts[parts.length - 1] || wsPath;
}
function selectChat(chat: ChatSearchResult) {
onclose();
goto(`/?workspace=${encodeURIComponent(chat.workspace)}&chatId=${encodeURIComponent(chat.id)}`);
}
function selectFile(file: FileSearchResult) {
onclose();
if (file.type === 'file') {
goto(`/?workspace=${encodeURIComponent(file.workspace)}&file=${encodeURIComponent(file.path)}`);
} else if (file.type === 'directory') {
goto(`/?workspace=${encodeURIComponent(file.workspace)}&dir=${encodeURIComponent(file.path)}`);
}
}
function handleKeydown(e: KeyboardEvent) {
// Cmd+1-9: jump to recent chat
if ((e.metaKey || e.ctrlKey) && e.key >= '1' && e.key <= '9' && showingRecents) {
const idx = parseInt(e.key) - 1;
if (idx < recentChats.length) {
e.preventDefault();
selectChat(recentChats[idx]);
return;
}
}
if (e.key === 'ArrowDown') {
e.preventDefault();
selectedIndex = Math.min(selectedIndex + 1, totalResults - 1);
scrollSelectedIntoView();
} else if (e.key === 'ArrowUp') {
e.preventDefault();
selectedIndex = Math.max(selectedIndex - 1, 0);
scrollSelectedIntoView();
} else if (e.key === 'Enter' && totalResults > 0) {
e.preventDefault();
activateSelected();
}
}
function scrollSelectedIntoView() {
requestAnimationFrame(() => {
const el = resultsEl?.querySelector(`[data-idx="${selectedIndex}"]`);
el?.scrollIntoView({ block: 'nearest', behavior: 'instant' });
});
}
function activateSelected() {
if (selectedIndex < displayedChats.length) {
selectChat(displayedChats[selectedIndex]);
} else {
const fileIdx = selectedIndex - displayedChats.length;
if (fileIdx < fileResults.length) {
selectFile(fileResults[fileIdx]);
}
}
}
function relPath(fullPath: string, wsPath: string): string {
return fullPath.startsWith(wsPath) ? fullPath.slice(wsPath.length + 1) : fullPath;
}
function relativeTime(ts: number): string {
const now = Date.now();
const diffMs = now - ts;
const diffSec = Math.floor(diffMs / 1000);
if (diffSec < 60) return 'now';
const diffMin = Math.floor(diffSec / 60);
if (diffMin < 60) return `${diffMin}m`;
const diffHr = Math.floor(diffMin / 60);
if (diffHr < 24) return `${diffHr}h`;
const diffDay = Math.floor(diffHr / 24);
if (diffDay < 30) return `${diffDay}d`;
const diffMonth = Math.floor(diffDay / 30);
return `${diffMonth}mo`;
}
</script>
<svelte:window onkeydown={handleKeydown} />
<Modal
{onclose}
class="w-full max-w-[560px] mx-4 max-md:mx-0 max-md:rounded-none max-h-[480px] max-md:max-h-dvh flex flex-col mb-[6vh] max-md:mb-0"
>
<!-- Search input -->
<div class="flex items-center px-3.5 py-3 gap-2">
<Icon name="search" size={14} class="text-gray-400 shrink-0" />
<input
bind:this={inputEl}
type="text"
class="flex-1 border-none outline-none bg-transparent text-xs text-gray-900 dark:text-white font-sans placeholder:text-gray-400"
placeholder={$t('search.placeholder')}
bind:value={query}
/>
</div>
<!-- Results -->
<div bind:this={resultsEl} class="overflow-y-auto px-1.5 pb-1.5 flex-1 min-h-0">
{#if showingRecents && filteredRecents.length > 0}
<!-- Recent chats (empty query) -->
<div class="text-[10px] font-medium uppercase tracking-wide text-gray-400 dark:text-gray-600 px-2 pt-1 pb-0.5">{$t('search.recentChats')}</div>
{#each filteredRecents as chat, i (chat.id)}
<button
data-idx={i}
class="group flex items-center gap-2 w-full h-7 px-2 rounded-xl text-left transition-colors duration-75
{i === selectedIndex
? 'bg-gray-200/50 text-gray-900 dark:bg-white/6 dark:text-white'
: 'text-gray-600 dark:text-gray-400 hover:bg-gray-50 dark:hover:bg-white/4'}"
onclick={() => selectChat(chat)}
onmouseenter={() => (selectedIndex = i)}
>
<span class="text-xs font-medium truncate flex-1">{chat.title}</span>
{#if i < 9 && !isWorkspaceScoped}
<KeyPill text={`⌘${i + 1}`} class="shrink-0 opacity-0 group-hover:opacity-100 transition-opacity duration-100" />
{/if}
<span class="text-[10px] text-gray-400 dark:text-gray-600 shrink-0">{workspaceName(chat.workspace)}</span>
</button>
{/each}
{:else if showingRecents}
<div class="py-6 text-center text-xs text-gray-400 dark:text-gray-600">{$t('search.noRecentChats')}</div>
{:else if !showingRecents}
{#if displayedChats.length > 0}
<!-- Chat search results -->
<div class="text-[10px] font-medium uppercase tracking-wide text-gray-400 dark:text-gray-600 px-2 pt-1 pb-0.5">{$t('search.chats')}</div>
{#each displayedChats as chat, i (chat.id)}
{@const idx = i}
<button
data-idx={idx}
class="flex items-start gap-2 w-full px-2 py-1.5 rounded-xl text-left transition-colors duration-75
{idx === selectedIndex
? 'bg-gray-200/50 text-gray-900 dark:bg-white/6 dark:text-white'
: 'text-gray-600 dark:text-gray-400 hover:bg-gray-50 dark:hover:bg-white/4'}"
onclick={() => selectChat(chat)}
onmouseenter={() => (selectedIndex = idx)}
>
<div class="flex-1 min-w-0">
<div class="flex items-center gap-2">
<span class="text-xs font-medium truncate">{chat.title}</span>
<span class="text-[10px] text-gray-400 dark:text-gray-600 shrink-0">{relativeTime(chat.updated_at)}</span>
</div>
{#if chat.match_type === 'message' && chat.snippet}
<div class="text-[11px] text-gray-400 dark:text-gray-600 truncate mt-0.5">{chat.snippet}</div>
{/if}
</div>
<span class="text-[10px] text-gray-400 dark:text-gray-600 shrink-0">{workspaceName(chat.workspace)}</span>
</button>
{/each}
{/if}
{#if fileResults.length > 0}
<!-- File search results -->
<div class="text-[10px] font-medium uppercase tracking-wide text-gray-400 dark:text-gray-600 px-2 pt-1 pb-0.5 {displayedChats.length > 0 ? 'mt-1' : ''}">{$t('search.files')}</div>
{#each fileResults as file, i (file.path)}
{@const idx = displayedChats.length + i}
<button
data-idx={idx}
class="flex items-center gap-2 w-full h-7 px-2 rounded-xl text-left transition-colors duration-75
{idx === selectedIndex
? 'bg-gray-200/50 text-gray-900 dark:bg-white/6 dark:text-white'
: 'text-gray-600 dark:text-gray-400 hover:bg-gray-50 dark:hover:bg-white/4'}"
onclick={() => selectFile(file)}
onmouseenter={() => (selectedIndex = idx)}
>
<Icon
name={file.type === 'directory' ? 'folder' : 'empty-page'}
size={14}
class="shrink-0 text-gray-400"
/>
<span class="text-xs font-medium shrink-0">{file.name}</span>
<span class="text-[11px] text-gray-400 overflow-hidden text-ellipsis whitespace-nowrap"
>{relPath(file.path, file.workspace)}</span
>
<span class="text-[10px] text-gray-400 dark:text-gray-600 shrink-0 ml-auto">{workspaceName(file.workspace)}</span>
</button>
{/each}
{/if}
{#if loading}
<div class="flex items-center justify-center py-8">
<Spinner size={16} />
</div>
{:else if query && totalResults === 0}
<div class="p-6 text-center text-xs text-gray-400">{$t('search.noResults')}</div>
{/if}
{/if}
</div>
</Modal>
+82 -43
View File
@@ -10,12 +10,14 @@
sidebarWidth,
appVersion,
showChangelog,
showSearch,
openChatTab,
setActiveTab
} from '$lib/stores';
import { get } from 'svelte/store';
import Sortable from 'sortablejs';
import Icon from './Icon.svelte';
import KeyPill from './KeyPill.svelte';
import DirectoryPicker from './DirectoryPicker.svelte';
import DropdownMenu from './DropdownMenu.svelte';
import SettingsModal from './SettingsModal.svelte';
@@ -28,6 +30,7 @@
import { chatEnabled } from '$lib/stores/chat';
import { socketStore } from '$lib/stores/socket.svelte';
import { t } from '$lib/i18n';
import { keybindings, formatChord } from '$lib/stores/keybindings';
import { onMount, onDestroy } from 'svelte';
@@ -48,6 +51,9 @@
let wsChatsCache = $state<Map<string, ChatInfo[]>>(new Map());
let wsChatsLoading = $state<Set<string>>(new Set());
// Keybinding shortcut display for search
let searchShortcut = $derived(formatChord($keybindings.quickOpen));
function toggleWorkspaceExpand(path: string) {
const next = new Set(expandedWorkspaces);
if (next.has(path)) {
@@ -94,23 +100,15 @@
}
function handleSidebarChatClick(chatId: string, wsPath: string, title: string) {
// If not already on this workspace, navigate first
const currentWsPath = $page.url.searchParams.get('workspace');
if ($page.url.pathname !== '/' || currentWsPath !== wsPath) {
goto(`/?workspace=${encodeURIComponent(wsPath)}`);
}
openChatTab(chatId, undefined, title);
goto(`/?workspace=${encodeURIComponent(wsPath)}&chatId=${encodeURIComponent(chatId)}`);
if (typeof window !== 'undefined' && window.innerWidth < 768) {
sidebarOpen.set(false);
}
}
function handleShowMoreChats(wsPath: string) {
// Navigate to the workspace and focus an existing chat tab (landing/history)
// instead of always creating a new one
goto(`/?workspace=${encodeURIComponent(wsPath)}`);
// Check if there's already a chat tab showing the landing page (no specific chatId)
const ws = get(currentWorkspace);
if (ws) {
for (const group of ws.groups) {
@@ -131,6 +129,13 @@
}
}
function handleNewChat(wsPath: string) {
goto(`/?workspace=${encodeURIComponent(wsPath)}&chatId`);
if (typeof window !== 'undefined' && window.innerWidth < 768) {
sidebarOpen.set(false);
}
}
// Socket listener for chat events — invalidate cache when chats update
const seenChatIds = new Set<string>();
@@ -141,6 +146,10 @@
if (!data.done && !data.title && !isNew) return;
// Invalidate cache for ALL workspaces so re-expanding shows fresh data
wsChatsCache = new Map();
// Re-fetch immediately for any currently expanded workspaces
for (const path of expandedWorkspaces) {
fetchWorkspaceChats(path);
}
@@ -308,8 +317,23 @@
</button>
</div>
<!-- Automations -->
<!-- Search -->
<div class="px-1.5 mt-1 shrink-0">
<button
class="group flex items-center gap-1.5 w-full h-7 px-2 rounded-lg text-xs text-gray-500 hover:text-gray-700 dark:hover:text-gray-300 transition-colors duration-100"
onclick={() => showSearch.set(true)}
>
<Icon name="search" size={14} />
<span class="flex-1 text-left overflow-hidden text-ellipsis whitespace-nowrap"
>{$t('search.search')}</span
>
<KeyPill text={searchShortcut} class="ml-auto shrink-0 opacity-0 group-hover:opacity-100 transition-opacity duration-100" />
</button>
</div>
<!-- Automations (only when chat/LLM backend is available) -->
{#if $chatEnabled}
<div class="px-1.5 shrink-0">
<a
href="/automations"
class="flex items-center gap-1.5 w-full h-7 px-2 rounded-lg text-xs text-gray-500 hover:text-gray-700 dark:hover:text-gray-300 transition-colors duration-100 no-underline"
@@ -323,6 +347,7 @@
<span class="flex-1 text-left overflow-hidden text-ellipsis whitespace-nowrap">Automations</span>
</a>
</div>
{/if}
<!-- Workspace section header -->
<div class="flex items-center justify-between h-8 pl-3.5 pr-1.5 shrink-0">
@@ -344,40 +369,42 @@
{@const chats = wsChatsCache.get(ws.path)}
{@const isLoading = wsChatsLoading.has(ws.path)}
<div class="ws-item">
<a
href="/?workspace={encodeURIComponent(ws.path)}"
class="group flex items-center gap-1.5 w-full h-7 px-2 rounded-lg text-xs font-medium transition-colors duration-100 no-underline
{ws.path === currentPath
? 'bg-gray-200/50 text-gray-900 dark:bg-white/8 dark:text-white'
: 'text-gray-500 hover:text-gray-700 dark:hover:text-gray-300'}"
onclick={(e) => handleWorkspaceClick(e, ws.path)}
>
<!-- Icon: folder by default, chevron on hover (when chat enabled) -->
{#if $chatEnabled}
<span
class="ws-icon-toggle shrink-0"
role="button"
tabindex="-1"
onclick={(e) => {
e.stopPropagation();
e.preventDefault();
toggleWorkspaceExpand(ws.path);
}}
aria-label={isExpanded ? 'Collapse' : 'Expand'}
>
<span class="ws-icon-folder"><Icon name="folder" size={14} /></span>
<span class="ws-icon-chevron" style="transform: rotate({isExpanded ? '90deg' : '0deg'})">
<Icon name="chevron-right" size={11} />
</span>
</span>
{:else}
<Icon name="folder" size={14} />
{/if}
<span class="flex-1 text-left overflow-hidden text-ellipsis whitespace-nowrap"
>{ws.name}</span
<div class="group flex items-center gap-1 w-full h-7 px-2 rounded-lg text-xs font-medium transition-colors duration-100
{ws.path === currentPath
? 'bg-gray-200/50 text-gray-900 dark:bg-white/8 dark:text-white'
: 'text-gray-500 hover:text-gray-700 dark:hover:text-gray-300'}">
<a
href="/?workspace={encodeURIComponent(ws.path)}"
class="flex items-center gap-1 flex-1 min-w-0 no-underline text-inherit"
onclick={(e) => handleWorkspaceClick(e, ws.path)}
>
<!-- Icon: folder by default, chevron on hover (when chat enabled) -->
{#if $chatEnabled}
<span
class="ws-icon-toggle shrink-0"
role="button"
tabindex="-1"
onclick={(e) => {
e.stopPropagation();
e.preventDefault();
toggleWorkspaceExpand(ws.path);
}}
aria-label={isExpanded ? 'Collapse' : 'Expand'}
>
<span class="ws-icon-folder"><Icon name="folder" size={14} /></span>
<span class="ws-icon-chevron" style="transform: rotate({isExpanded ? '90deg' : '0deg'})">
<Icon name="chevron-right" size={11} />
</span>
</span>
{:else}
<Icon name="folder" size={14} />
{/if}
<span class="flex-1 text-left overflow-hidden text-ellipsis whitespace-nowrap"
>{ws.name}</span
>
</a>
<span
class="flex items-center justify-center w-5 h-5 rounded shrink-0 text-gray-400 opacity-0 group-hover:opacity-100 hover:bg-gray-200 dark:hover:bg-white/10 transition-all duration-75"
class="flex items-center justify-center w-4 h-4 shrink-0 text-gray-400 opacity-0 group-hover:opacity-100 hover:text-gray-600 dark:hover:text-gray-300 transition-all duration-75"
role="button"
tabindex="-1"
onclick={(e) => openWsMenu(e, ws.path)}
@@ -385,7 +412,19 @@
>
<Icon name="three-dots" size={11} />
</span>
</a>
{#if $chatEnabled}
<span
class="flex items-center justify-center w-4 h-4 shrink-0 text-gray-400 opacity-0 group-hover:opacity-100 hover:text-gray-600 dark:hover:text-gray-300 transition-all duration-75"
role="button"
tabindex="-1"
onclick={() => handleNewChat(ws.path)}
aria-label="New Chat"
use:tooltip={'New Chat'}
>
<Icon name="pencil" size={11} />
</span>
{/if}
</div>
<!-- Collapsible chat list -->
{#if $chatEnabled && isExpanded}
@@ -229,6 +229,10 @@
if (gen !== loadGeneration) return;
allMessages = data.messages;
currentMessageId = data.chat.current_message_id;
// Update tab label with the real title from the DB
if (tabId && data.chat.title) {
updateTab(tabId, id, data.chat.title);
}
} finally {
if (isInitialLoad && gen === loadGeneration) loading = false;
}
@@ -294,6 +298,8 @@
// ── Socket listener ─────────────────────────────────────────
let landingRefreshTimer: ReturnType<typeof setTimeout> | null = null;
function handleSocketEvent(data: {
chat_id: string;
message_id: string;
@@ -305,15 +311,25 @@
}) {
// On the landing page, update the chat list in place from socket events
if (isLanding) {
if (data.done) {
previousChats = previousChats.map((c) =>
c.id === data.chat_id ? { ...c, is_active: false } : c
);
}
if (data.title) {
previousChats = previousChats.map((c) =>
c.id === data.chat_id ? { ...c, title: data.title! } : c
);
const knownChat = previousChats.some((c) => c.id === data.chat_id);
if (!knownChat) {
// New chat created elsewhere — debounce-reload the list
if (landingRefreshTimer) clearTimeout(landingRefreshTimer);
landingRefreshTimer = setTimeout(() => {
landingRefreshTimer = null;
loadPreviousChats(chatPage);
}, 300);
} else {
if (data.done) {
previousChats = previousChats.map((c) =>
c.id === data.chat_id ? { ...c, is_active: false } : c
);
}
if (data.title) {
previousChats = previousChats.map((c) =>
c.id === data.chat_id ? { ...c, title: data.title! } : c
);
}
}
}
@@ -419,6 +435,7 @@
socket.off('events:chat', handleSocketEvent);
socket.off('connect', handleReconnect);
}
if (landingRefreshTimer) clearTimeout(landingRefreshTimer);
// Don't clear streamingChatTabs here -- the global listener in
// chat.ts handles cleanup when the "done" event arrives, so the
// spinner persists even when the chat tab is not active.
+8 -1
View File
@@ -258,5 +258,12 @@
"admin.webTavilyHint": "API-Schlüssel unter tavily.com erhalten",
"admin.webBraveKey": "Brave-API-Schlüssel",
"admin.webBraveHint": "API-Schlüssel unter brave.com/search/api erhalten",
"admin.webDuckDuckGoNote": "DuckDuckGo benötigt keinen API-Schlüssel (Fallback)."
"admin.webDuckDuckGoNote": "DuckDuckGo benötigt keinen API-Schlüssel (Fallback).",
"admin.webPerplexityKey": "Perplexity API-Schlüssel",
"admin.webPerplexityHint": "API-Schlüssel unter perplexity.ai erhalten",
"admin.webChatCompletions": "Chat Completions",
"admin.webCcBaseUrl": "Basis-URL",
"admin.webCcKey": "API-Schlüssel",
"admin.webCcModel": "Modell",
"admin.webCcHint": "Beliebiger OpenAI-kompatibler Endpunkt (z. B. Perplexity Sonar, LiteLLM-Proxy)"
}
+16 -1
View File
@@ -78,6 +78,14 @@
"quickOpen.searchFiles": "Search files...",
"quickOpen.noFiles": "No files found",
"search.placeholder": "Search...",
"search.search": "Search",
"search.chats": "Chats",
"search.files": "Files",
"search.noResults": "No results found",
"search.recentChats": "Recent chats",
"search.noRecentChats": "No recent chats",
"settings.back": "Back",
"settings.general": "General",
"settings.account": "Account",
@@ -259,5 +267,12 @@
"admin.webTavilyHint": "Get your API key at tavily.com",
"admin.webBraveKey": "Brave API Key",
"admin.webBraveHint": "Get your API key at brave.com/search/api",
"admin.webDuckDuckGoNote": "DuckDuckGo requires no API key (fallback)."
"admin.webDuckDuckGoNote": "DuckDuckGo requires no API key (fallback).",
"admin.webPerplexityKey": "Perplexity API Key",
"admin.webPerplexityHint": "Get your API key at perplexity.ai",
"admin.webChatCompletions": "Chat Completions",
"admin.webCcBaseUrl": "Base URL",
"admin.webCcKey": "API Key",
"admin.webCcModel": "Model",
"admin.webCcHint": "Use any OpenAI-compatible endpoint (e.g. Perplexity Sonar, LiteLLM proxy)"
}
+8 -1
View File
@@ -258,5 +258,12 @@
"admin.webTavilyHint": "Obtén tu clave de API en tavily.com",
"admin.webBraveKey": "Clave de API de Brave",
"admin.webBraveHint": "Obtén tu clave de API en brave.com/search/api",
"admin.webDuckDuckGoNote": "DuckDuckGo no requiere clave de API (respaldo)."
"admin.webDuckDuckGoNote": "DuckDuckGo no requiere clave de API (respaldo).",
"admin.webPerplexityKey": "Clave de API de Perplexity",
"admin.webPerplexityHint": "Obtén tu clave de API en perplexity.ai",
"admin.webChatCompletions": "Chat Completions",
"admin.webCcBaseUrl": "URL base",
"admin.webCcKey": "Clave de API",
"admin.webCcModel": "Modelo",
"admin.webCcHint": "Cualquier endpoint compatible con OpenAI (ej. Perplexity Sonar, proxy LiteLLM)"
}
+8 -1
View File
@@ -258,5 +258,12 @@
"admin.webTavilyHint": "Obtenez votre clé API sur tavily.com",
"admin.webBraveKey": "Clé API Brave",
"admin.webBraveHint": "Obtenez votre clé API sur brave.com/search/api",
"admin.webDuckDuckGoNote": "DuckDuckGo ne nécessite aucune clé API (solution de repli)."
"admin.webDuckDuckGoNote": "DuckDuckGo ne nécessite aucune clé API (solution de repli).",
"admin.webPerplexityKey": "Clé API Perplexity",
"admin.webPerplexityHint": "Obtenez votre clé API sur perplexity.ai",
"admin.webChatCompletions": "Chat Completions",
"admin.webCcBaseUrl": "URL de base",
"admin.webCcKey": "Clé API",
"admin.webCcModel": "Modèle",
"admin.webCcHint": "Tout endpoint compatible OpenAI (ex. Perplexity Sonar, proxy LiteLLM)"
}
+8 -1
View File
@@ -258,5 +258,12 @@
"admin.webTavilyHint": "tavily.comでAPIキーを取得してください",
"admin.webBraveKey": "Brave APIキー",
"admin.webBraveHint": "brave.com/search/apiでAPIキーを取得してください",
"admin.webDuckDuckGoNote": "DuckDuckGoはAPIキー不要です(フォールバック)。"
"admin.webDuckDuckGoNote": "DuckDuckGoはAPIキー不要です(フォールバック)。",
"admin.webPerplexityKey": "Perplexity APIキー",
"admin.webPerplexityHint": "perplexity.ai でAPIキーを取得",
"admin.webChatCompletions": "Chat Completions",
"admin.webCcBaseUrl": "ベースURL",
"admin.webCcKey": "APIキー",
"admin.webCcModel": "モデル",
"admin.webCcHint": "OpenAI互換エンドポイント(例: Perplexity Sonar、LiteLLMプロキシ)"
}
+8 -1
View File
@@ -258,5 +258,12 @@
"admin.webTavilyHint": "tavily.com에서 API 키를 받으세요",
"admin.webBraveKey": "Brave API 키",
"admin.webBraveHint": "brave.com/search/api에서 API 키를 받으세요",
"admin.webDuckDuckGoNote": "DuckDuckGo는 API 키가 필요 없습니다(대체)."
"admin.webDuckDuckGoNote": "DuckDuckGo는 API 키가 필요 없습니다(대체).",
"admin.webPerplexityKey": "Perplexity API 키",
"admin.webPerplexityHint": "perplexity.ai에서 API 키를 받으세요",
"admin.webChatCompletions": "Chat Completions",
"admin.webCcBaseUrl": "기본 URL",
"admin.webCcKey": "API 키",
"admin.webCcModel": "모델",
"admin.webCcHint": "OpenAI 호환 엔드포인트 사용 (예: Perplexity Sonar, LiteLLM 프록시)"
}
@@ -258,5 +258,12 @@
"admin.webTavilyHint": "Obtenha sua chave de API em tavily.com",
"admin.webBraveKey": "Chave de API da Brave",
"admin.webBraveHint": "Obtenha sua chave de API em brave.com/search/api",
"admin.webDuckDuckGoNote": "DuckDuckGo não exige chave de API (fallback)."
"admin.webDuckDuckGoNote": "DuckDuckGo não exige chave de API (fallback).",
"admin.webPerplexityKey": "Chave de API do Perplexity",
"admin.webPerplexityHint": "Obtenha sua chave de API em perplexity.ai",
"admin.webChatCompletions": "Chat Completions",
"admin.webCcBaseUrl": "URL base",
"admin.webCcKey": "Chave de API",
"admin.webCcModel": "Modelo",
"admin.webCcHint": "Qualquer endpoint compatível com OpenAI (ex. Perplexity Sonar, proxy LiteLLM)"
}
+8 -1
View File
@@ -258,5 +258,12 @@
"admin.webTavilyHint": "Получите API-ключ на tavily.com",
"admin.webBraveKey": "API-ключ Brave",
"admin.webBraveHint": "Получите API-ключ на brave.com/search/api",
"admin.webDuckDuckGoNote": "DuckDuckGo не требует API-ключа (резервный вариант)."
"admin.webDuckDuckGoNote": "DuckDuckGo не требует API-ключа (резервный вариант).",
"admin.webPerplexityKey": "API-ключ Perplexity",
"admin.webPerplexityHint": "Получите API-ключ на perplexity.ai",
"admin.webChatCompletions": "Chat Completions",
"admin.webCcBaseUrl": "Базовый URL",
"admin.webCcKey": "API-ключ",
"admin.webCcModel": "Модель",
"admin.webCcHint": "Любой OpenAI-совместимый эндпоинт (напр. Perplexity Sonar, прокси LiteLLM)"
}
@@ -258,5 +258,12 @@
"admin.webTavilyHint": "在 tavily.com 获取你的 API 密钥",
"admin.webBraveKey": "Brave API 密钥",
"admin.webBraveHint": "在 brave.com/search/api 获取你的 API 密钥",
"admin.webDuckDuckGoNote": "DuckDuckGo 不需要 API 密钥(备用)。"
"admin.webDuckDuckGoNote": "DuckDuckGo 不需要 API 密钥(备用)。",
"admin.webPerplexityKey": "Perplexity API 密钥",
"admin.webPerplexityHint": "在 perplexity.ai 获取你的 API 密钥",
"admin.webChatCompletions": "Chat Completions",
"admin.webCcBaseUrl": "基础 URL",
"admin.webCcKey": "API 密钥",
"admin.webCcModel": "模型",
"admin.webCcHint": "使用任何 OpenAI 兼容端点(如 Perplexity Sonar、LiteLLM 代理)"
}
@@ -258,5 +258,12 @@
"admin.webTavilyHint": "在 tavily.com 取得你的 API 金鑰",
"admin.webBraveKey": "Brave API 金鑰",
"admin.webBraveHint": "在 brave.com/search/api 取得你的 API 金鑰",
"admin.webDuckDuckGoNote": "DuckDuckGo 不需要 API 金鑰(備用)。"
"admin.webDuckDuckGoNote": "DuckDuckGo 不需要 API 金鑰(備用)。",
"admin.webPerplexityKey": "Perplexity API 金鑰",
"admin.webPerplexityHint": "在 perplexity.ai 取得你的 API 金鑰",
"admin.webChatCompletions": "Chat Completions",
"admin.webCcBaseUrl": "基礎 URL",
"admin.webCcKey": "API 金鑰",
"admin.webCcModel": "模型",
"admin.webCcHint": "使用任何 OpenAI 相容端點(如 Perplexity Sonar、LiteLLM 代理)"
}
+12 -2
View File
@@ -138,6 +138,7 @@ export const planMode = writable(false);
export const appVersion = writable('');
export const lastSeenVersion = writable('');
export const showChangelog = writable(false);
export const showSearch = writable(false);
/** @deprecated Use toolApprovalMode */
export const autoApproveTools = {
subscribe: toolApprovalMode.subscribe,
@@ -666,7 +667,7 @@ export function openPreviewTab(port: number, targetGroupId?: string): void {
}));
}
export function openChatTab(chatId?: string, targetGroupId?: string, label?: string): void {
export function openChatTab(chatId?: string, targetGroupId?: string): void {
const ws = get(currentWorkspace);
if (!ws) return;
@@ -681,12 +682,21 @@ export function openChatTab(chatId?: string, targetGroupId?: string, label?: str
setActiveTab(existing.id, gid);
return;
}
} else {
// No chatId — reuse an existing new/pending chat tab if one is open
const existing = group.tabs.find(
(t) => t.type === 'chat' && (t.path?.startsWith('new-') || t.path?.startsWith('pending-'))
);
if (existing) {
setActiveTab(existing.id, gid);
return;
}
}
const newTab: Tab = {
id: nextId(),
type: 'chat',
label: label || 'New Chat',
label: chatId ? 'Chat' : 'New Chat',
path: chatId || `new-${Date.now()}`
};
@@ -35,6 +35,7 @@ export const ACTION_IDS = [
'nextTab',
'prevTab',
'quickOpen',
'searchAll',
'openSettings',
'toggleSplit',
'toggleSidebar'
@@ -52,6 +53,7 @@ export const ACTION_LABELS: Record<ActionId, string> = {
nextTab: 'Next Tab',
prevTab: 'Previous Tab',
quickOpen: 'Quick Open',
searchAll: 'Search',
openSettings: 'Open Settings',
toggleSplit: 'Toggle Split',
toggleSidebar: 'Toggle Sidebar'
@@ -67,6 +69,7 @@ export const DEFAULT_KEYBINDINGS: Record<ActionId, string> = {
nextTab: 'Cmd+Shift+]',
prevTab: 'Cmd+Shift+[',
quickOpen: 'Cmd+K',
searchAll: 'Cmd+Shift+F',
openSettings: 'Cmd+.',
toggleSplit: 'Cmd+\\',
toggleSidebar: 'Cmd+Shift+S'
@@ -231,6 +234,7 @@ export function executeAction(
callbacks?: {
toggleQuickOpen?: () => void;
toggleSettings?: () => void;
toggleSearch?: () => void;
}
): boolean {
switch (action) {
@@ -277,6 +281,10 @@ export function executeAction(
callbacks?.toggleSettings?.();
return true;
case 'searchAll':
callbacks?.toggleSearch?.();
return true;
case 'toggleSplit': {
const ws = get(currentWorkspace);
if (!ws) return false;
+12 -7
View File
@@ -9,7 +9,7 @@
import Sidebar from '$lib/components/Sidebar.svelte';
import ShortcutBar from '$lib/components/ShortcutBar.svelte';
import GitBar from '$lib/components/GitBar.svelte';
import QuickOpen from '$lib/components/QuickOpen.svelte';
import SearchModal from '$lib/components/SearchModal.svelte';
import SettingsModal from '$lib/components/SettingsModal.svelte';
import AuthScreen from '$lib/components/AuthScreen.svelte';
import ChangelogModal from '$lib/components/ChangelogModal.svelte';
@@ -26,7 +26,8 @@
closeGroup,
appVersion,
lastSeenVersion,
showChangelog
showChangelog,
showSearch
} from '$lib/stores';
import { matchKeybinding, executeAction } from '$lib/stores/keybindings';
import { systemEvents } from '$lib/stores/systemEvents.svelte';
@@ -38,7 +39,6 @@
import { refreshChatState, bindGlobalChatListener } from '$lib/stores/chat';
let { children } = $props();
let showQuickOpen = $state(false);
let showSettings = $state(false);
// Auth state
@@ -180,10 +180,13 @@
e.preventDefault();
executeAction(action, {
toggleQuickOpen: () => {
showQuickOpen = !showQuickOpen;
showSearch.update((v) => !v);
},
toggleSettings: () => {
showSettings = !showSettings;
},
toggleSearch: () => {
showSearch.update((v) => !v);
}
});
}
@@ -270,8 +273,8 @@
</div>
</div>
{#if showQuickOpen}
<QuickOpen onclose={() => (showQuickOpen = false)} />
{#if $showSearch}
<SearchModal onclose={() => showSearch.set(false)} />
{/if}
{#if showSettings}
<SettingsModal onclose={() => (showSettings = false)} />
@@ -286,8 +289,10 @@
<Toaster
position="top-right"
theme="system"
closeButton
richColors
toastOptions={{
style:
'font-size: 12px; font-family: var(--font-sans); background: transparent; border: none; box-shadow: none; border-radius: 8px; padding: 0;'
'font-size: 12px; font-family: var(--font-sans); border-radius: 8px;'
}}
/>
+40 -1
View File
@@ -14,6 +14,9 @@
openInSplit,
openTabInSplit,
setSplitDirection,
openChatTab,
openFileTab,
setFileBrowserCwd,
appVersion,
showChangelog
} from '$lib/stores';
@@ -40,14 +43,50 @@
// ── URL-driven workspace loading ───────────────────────────────
// The workspace path comes from the URL query param: ?workspace=/path/to/dir
// Each browser tab has its own URL → its own workspace.
// Intent params (chatId, file, dir) are processed AFTER loading.
let lastLoadedPath = $state<string | null>(null);
function processIntentParams() {
const url = new URL($page.url);
const chatId = url.searchParams.get('chatId');
const filePath = url.searchParams.get('file');
const dirPath = url.searchParams.get('dir');
let dirty = false;
if (url.searchParams.has('chatId')) {
if (chatId) {
openChatTab(chatId);
} else {
openChatTab();
}
url.searchParams.delete('chatId');
dirty = true;
}
if (filePath) {
openFileTab(filePath);
url.searchParams.delete('file');
dirty = true;
}
if (dirPath) {
setFileBrowserCwd(dirPath);
url.searchParams.delete('dir');
dirty = true;
}
if (dirty) {
history.replaceState(history.state, '', url.pathname + url.search);
}
}
$effect(() => {
const wsPath = $page.url.searchParams.get('workspace');
if (wsPath && wsPath !== lastLoadedPath) {
// New workspace — load then process intents
lastLoadedPath = wsPath;
loadWorkspace(wsPath);
loadWorkspace(wsPath).then(() => processIntentParams());
} else if (wsPath && wsPath === lastLoadedPath) {
// Same workspace — process intents immediately
processIntentParams();
} else if (!wsPath) {
lastLoadedPath = null;
currentWorkspace.set(null);
+95
View File
@@ -117,6 +117,101 @@ class Chat(Base):
await db.commit()
return result.rowcount > 0
@staticmethod
async def search_by_text(
user_id: str,
query: str,
limit: int = 10,
offset: int = 0,
) -> list[dict]:
"""Search chats by title AND message content (case-insensitive).
Returns dicts with chat fields + 'match_type' ('title' | 'message')
and 'snippet' (matching message excerpt or null).
Title matches rank first.
"""
from sqlalchemy import literal, union_all
async with await get_db() as db:
pattern = f"%{query}%"
# 1) Chats matching by title
title_q = (
select(
Chat.id,
Chat.title,
Chat.summary,
Chat.meta,
Chat.updated_at,
Chat.created_at,
literal("title").label("match_type"),
literal("").label("snippet"),
)
.where(Chat.user_id == user_id)
.where(Chat.title.ilike(pattern))
)
# 2) Chats matching by message content (exclude title-matched)
message_q = (
select(
Chat.id,
Chat.title,
Chat.summary,
Chat.meta,
Chat.updated_at,
Chat.created_at,
literal("message").label("match_type"),
ChatMessage.content.label("snippet"),
)
.join(ChatMessage, ChatMessage.chat_id == Chat.id)
.where(Chat.user_id == user_id)
.where(ChatMessage.content.ilike(pattern))
.where(~Chat.title.ilike(pattern)) # avoid duplicates
.group_by(Chat.id) # one result per chat
)
# Union, order by match_type (title first), then recency
combined = union_all(title_q, message_q).subquery()
result = await db.execute(
select(combined)
.order_by(combined.c.match_type, combined.c.updated_at.desc())
.limit(limit)
.offset(offset)
)
rows = result.all()
return [
{
"id": r.id,
"title": r.title,
"summary": r.summary,
"meta": r.meta,
"updated_at": r.updated_at,
"created_at": r.created_at,
"match_type": r.match_type,
"snippet": _extract_snippet(r.snippet, query) if r.snippet else None,
}
for r in rows
]
def _extract_snippet(content: str, query: str, context_chars: int = 80) -> str | None:
"""Extract a short snippet around the first match in message content."""
if not content:
return None
lower = content.lower()
idx = lower.find(query.lower())
if idx == -1:
return content[: context_chars * 2] + ("..." if len(content) > context_chars * 2 else "")
start = max(0, idx - context_chars)
end = min(len(content), idx + len(query) + context_chars)
snippet = content[start:end]
if start > 0:
snippet = "..." + snippet
if end < len(content):
snippet = snippet + "..."
return snippet
class ChatMessage(Base):
"""A single message in a chat conversation."""
+2
View File
@@ -8,6 +8,7 @@ from cptr.routers.events import router as events_router
from cptr.routers.files import router as files_router
from cptr.routers.git import router as git_router
from cptr.routers.proxy import router as proxy_router
from cptr.routers.search import router as search_router
from cptr.routers.state import router as state_router
from cptr.routers.terminal import router as terminal_router
from cptr.routers.workspace import router as workspace_router
@@ -21,6 +22,7 @@ __all__ = [
"files_router",
"git_router",
"proxy_router",
"search_router",
"state_router",
"terminal_router",
"workspace_router",
+144
View File
@@ -0,0 +1,144 @@
"""Unified search: chats + files in one request."""
from __future__ import annotations
import asyncio
from pathlib import Path
from typing import List, Optional
from fastapi import APIRouter, HTTPException, Query, Request
from cptr.models import Chat
from cptr.routers.workspace import walk_and_rank_files, SearchResult
router = APIRouter(prefix="/api/search", tags=["search"])
COOKIE_NAME = "cptr_session"
def _get_user(request: Request) -> str:
"""Extract user_id from cookie, raise 401 if not authenticated."""
from cptr.utils.config import check_access
token = request.cookies.get(COOKIE_NAME)
client_host = request.client.host if request.client else "127.0.0.1"
auth = check_access(client_host=client_host, jwt_token=token)
if not auth or not auth.user_id:
raise HTTPException(401, "authentication required")
return auth.user_id
@router.get("")
async def unified_search(
request: Request,
q: str = Query(..., min_length=1, description="Search query"),
workspaces: List[str] = Query(default=[], description="Workspace paths to search files in"),
workspace: Optional[str] = Query(None, description="Scope to one workspace path"),
chat_limit: int = Query(10, ge=0, le=50),
file_limit: int = Query(10, ge=0, le=50),
):
"""Search chats by title/content + files by name across workspaces.
Returns: { chats: [...], files: [...] }
"""
user_id = _get_user(request)
# Determine which workspaces to search for files
ws_paths = [workspace] if workspace else workspaces
# Run chat search and file search concurrently
chat_task = Chat.search_by_text(user_id, q, chat_limit)
async def _search_files() -> list[dict]:
if not ws_paths:
return []
all_results: list[dict] = []
per_ws_limit = max(3, file_limit // max(len(ws_paths), 1))
for ws in ws_paths:
root = Path(ws).resolve()
if not root.exists() or not root.is_dir():
continue
results = await asyncio.to_thread(walk_and_rank_files, root, q, per_ws_limit)
for r in results:
all_results.append(
{
"path": r.path,
"name": r.name,
"type": r.type,
"workspace": ws,
}
)
# Deduplicate by path and cap at file_limit
seen = set()
deduped = []
for f in all_results:
if f["path"] not in seen:
seen.add(f["path"])
deduped.append(f)
return deduped[:file_limit]
chat_results, file_results = await asyncio.gather(chat_task, _search_files())
# Filter chats by workspace if scoped
if workspace:
chat_results = [
c for c in chat_results if (c.get("meta") or {}).get("workspace") == workspace
]
# Build chat response (strip meta, add workspace)
chats_out = []
for c in chat_results:
chats_out.append(
{
"id": c["id"],
"title": c["title"],
"summary": c.get("summary"),
"workspace": (c.get("meta") or {}).get("workspace", ""),
"updated_at": c["updated_at"],
"created_at": c["created_at"],
"match_type": c.get("match_type", "title"),
"snippet": c.get("snippet"),
}
)
return {"chats": chats_out, "files": file_results}
@router.get("/recent")
async def recent_chats(
request: Request,
limit: int = Query(9, ge=1, le=20),
):
"""Return most recent chats across all workspaces (for empty-query state)."""
user_id = _get_user(request)
from sqlalchemy import select
from cptr.utils.db import get_db
async with await get_db() as db:
result = await db.execute(
select(Chat)
.where(Chat.user_id == user_id)
.order_by(Chat.updated_at.desc())
.limit(limit)
)
rows = list(result.scalars().all())
return {
"chats": [
{
"id": c.id,
"title": c.title,
"summary": c.summary,
"workspace": (c.meta or {}).get("workspace", ""),
"updated_at": c.updated_at,
"created_at": c.created_at,
"match_type": "recent",
"snippet": None,
}
for c in rows
]
}
+63 -57
View File
@@ -351,66 +351,72 @@ async def search_files(
if not root.exists() or not root.is_dir():
raise HTTPException(status_code=404, detail=f"Path not found: {path}")
def _walk_and_rank() -> list[SearchResult]:
query_lower = query.strip().lower().replace("\\", "/")
matches: list[tuple[int, int, SearchResult]] = []
max_collect = limit * 10
def walk(directory: Path, depth: int = 0):
if depth > 8 or len(matches) >= max_collect:
return
try:
for item in sorted(directory.iterdir(), key=lambda p: p.name.lower()):
if item.name in SEARCH_IGNORE_DIRS or item.name.startswith("."):
continue
if len(matches) >= max_collect:
return
name_lower = item.name.lower()
if query_lower and query_lower in name_lower:
if name_lower == query_lower:
score = 0
elif name_lower.startswith(query_lower):
score = 1
else:
score = 2
matches.append(
(
score,
len(item.name),
SearchResult(
path=str(item),
name=item.name,
type="directory" if item.is_dir() else "file",
),
)
)
elif not query_lower:
matches.append(
(
2,
len(item.name),
SearchResult(
path=str(item),
name=item.name,
type="directory" if item.is_dir() else "file",
),
)
)
if item.is_dir():
walk(item, depth + 1)
except (PermissionError, OSError):
pass
walk(root)
matches.sort(key=lambda m: (m[0], m[1]))
return [m[2] for m in matches[:limit]]
results = await asyncio.to_thread(_walk_and_rank)
results = await asyncio.to_thread(walk_and_rank_files, root, query, limit)
return SearchResponse(results=results)
def walk_and_rank_files(root: Path, query: str, limit: int = 20) -> list[SearchResult]:
"""Fuzzy file search — walks tree, ranks by name match quality.
Reusable by both the /search endpoint and the unified /api/search endpoint.
"""
query_lower = query.strip().lower().replace("\\", "/")
matches: list[tuple[int, int, SearchResult]] = []
max_collect = limit * 10
def walk(directory: Path, depth: int = 0):
if depth > 8 or len(matches) >= max_collect:
return
try:
for item in sorted(directory.iterdir(), key=lambda p: p.name.lower()):
if item.name in SEARCH_IGNORE_DIRS or item.name.startswith("."):
continue
if len(matches) >= max_collect:
return
name_lower = item.name.lower()
if query_lower and query_lower in name_lower:
if name_lower == query_lower:
score = 0
elif name_lower.startswith(query_lower):
score = 1
else:
score = 2
matches.append(
(
score,
len(item.name),
SearchResult(
path=str(item),
name=item.name,
type="directory" if item.is_dir() else "file",
),
)
)
elif not query_lower:
matches.append(
(
2,
len(item.name),
SearchResult(
path=str(item),
name=item.name,
type="directory" if item.is_dir() else "file",
),
)
)
if item.is_dir():
walk(item, depth + 1)
except (PermissionError, OSError):
pass
walk(root)
matches.sort(key=lambda m: (m[0], m[1]))
return [m[2] for m in matches[:limit]]
# ── File management ──────────────────────────────────────────────
+2 -5
View File
@@ -190,15 +190,12 @@ async def execute_automation(automation, webhook_payload: str | None = None) ->
model=bare_model,
)
# Notify frontend
# Notify frontend (standard chat event so sidebar updates)
await emit_to_user(
automation.user_id,
{
"type": "automation:result",
"automation_id": automation.id,
"name": automation.name,
"chat_id": chat.id,
"status": "success",
"title": automation.name,
},
)
+46
View File
@@ -0,0 +1,46 @@
"""Chat Completions search provider: any OpenAI-compatible endpoint.
Send the search query as a user message to a /chat/completions endpoint
and return the model's response. Works with Perplexity Sonar (web-grounded),
LiteLLM proxy, or any model that returns search-grounded results.
"""
from __future__ import annotations
import httpx
_SYSTEM_PROMPT = (
"You are a web search assistant. Given the user's query, provide a concise, "
"factual answer with relevant sources. Format each result as:\n"
"**Title**\nURL\nSnippet\n\n"
"Include up to 5 results. Cite your sources with URLs when possible."
)
async def search(
query: str,
api_key: str,
base_url: str,
model: str,
) -> str:
"""Search using an OpenAI-compatible chat completions endpoint."""
async with httpx.AsyncClient(timeout=30) as client:
resp = await client.post(
f"{base_url.rstrip('/')}/chat/completions",
json={
"model": model,
"messages": [
{"role": "system", "content": _SYSTEM_PROMPT},
{"role": "user", "content": query},
],
},
headers={
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json",
},
)
resp.raise_for_status()
data = resp.json()
content = data.get("choices", [{}])[0].get("message", {}).get("content", "")
return content or "No results found."
+33
View File
@@ -0,0 +1,33 @@
"""Perplexity Search provider: raw web search results.
https://docs.perplexity.ai – dedicated search endpoint returning
structured results (title, URL, snippet) without LLM synthesis.
"""
from __future__ import annotations
import httpx
async def search(query: str, api_key: str, count: int = 5) -> str:
"""Search using Perplexity's dedicated search API."""
async with httpx.AsyncClient(timeout=10) as client:
resp = await client.post(
"https://api.perplexity.ai/search",
json={"query": query},
headers={
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json",
},
)
resp.raise_for_status()
data = resp.json()
results = []
for item in data.get("results", [])[:count]:
title = item.get("title", "")
url = item.get("url", "")
snippet = item.get("snippet", "")
results.append(f"**{title}**\n{url}\n{snippet}")
return "\n\n".join(results) if results else "No results found."
+24 -5
View File
@@ -1,10 +1,11 @@
"""Search dispatcher: picks provider based on config.
Priority in auto mode:
1. Exa (EXA_API_KEY or web.exa_api_key)
2. Tavily (TAVILY_API_KEY or web.tavily_api_key)
3. Brave (BRAVE_API_KEY or web.brave_api_key)
4. DuckDuckGo (zero-config fallback)
1. Exa (EXA_API_KEY or web.exa_api_key)
2. Perplexity (PERPLEXITY_API_KEY or web.perplexity_api_key)
3. Tavily (TAVILY_API_KEY or web.tavily_api_key)
4. Brave (BRAVE_API_KEY or web.brave_api_key)
5. DuckDuckGo (zero-config fallback)
"""
from __future__ import annotations
@@ -40,7 +41,7 @@ async def _get_config(key: str) -> str:
async def web_search_handler(query: str) -> str:
"""Search the web using the configured or best available provider."""
from cptr.utils.web import exa, tavily, brave, duckduckgo
from cptr.utils.web import exa, perplexity, tavily, brave, duckduckgo, chat_completions
# Check if web access is disabled by admin
enabled = await _get_config("web.enabled")
@@ -50,8 +51,16 @@ async def web_search_handler(query: str) -> str:
provider = await _get_config("web.search_provider") or "auto"
exa_key = await _get_key("EXA_API_KEY", "web.exa_api_key")
perplexity_key = await _get_key("PERPLEXITY_API_KEY", "web.perplexity_api_key")
tavily_key = await _get_key("TAVILY_API_KEY", "web.tavily_api_key")
brave_key = await _get_key("BRAVE_API_KEY", "web.brave_api_key")
cc_key = await _get_key("CHAT_COMPLETIONS_SEARCH_API_KEY", "web.chat_completions_api_key")
cc_url = (
await _get_config("web.chat_completions_base_url")
) or os.environ.get("CHAT_COMPLETIONS_SEARCH_BASE_URL", "")
cc_model = (
await _get_config("web.chat_completions_model")
) or os.environ.get("CHAT_COMPLETIONS_SEARCH_MODEL", "")
# Explicit provider mode
if provider != "auto":
@@ -60,6 +69,10 @@ async def web_search_handler(query: str) -> str:
if not exa_key:
return "Error: Exa API key not configured."
return await exa.search(query, exa_key)
elif provider == "perplexity":
if not perplexity_key:
return "Error: Perplexity API key not configured."
return await perplexity.search(query, perplexity_key)
elif provider == "tavily":
if not tavily_key:
return "Error: Tavily API key not configured."
@@ -70,6 +83,10 @@ async def web_search_handler(query: str) -> str:
return await brave.search(query, brave_key)
elif provider == "duckduckgo":
return await duckduckgo.search(query)
elif provider == "chat_completions":
if not cc_key or not cc_url or not cc_model:
return "Error: Chat Completions search requires API key, base URL, and model."
return await chat_completions.search(query, cc_key, cc_url, cc_model)
else:
return f"Error: unknown search provider '{provider}'."
except Exception as e:
@@ -80,6 +97,8 @@ async def web_search_handler(query: str) -> str:
providers = []
if exa_key:
providers.append(("exa", lambda: exa.search(query, exa_key)))
if perplexity_key:
providers.append(("perplexity", lambda: perplexity.search(query, perplexity_key)))
if tavily_key:
providers.append(("tavily", lambda: tavily.search(query, tavily_key)))
if brave_key:
+4 -3
View File
@@ -1,10 +1,10 @@
[project]
name = "cptr"
version = "0.2.0"
version = "0.2.1"
description = "Your computer, from anywhere. Code, manage, and control your machine from the web."
license = {file = "LICENSE"}
readme = "README.md"
requires-python = ">=3.9"
requires-python = ">=3.10"
dependencies = [
"click>=8.1",
"fastapi[standard]>=0.128.8",
@@ -18,6 +18,7 @@ dependencies = [
"cryptography>=42.0",
"python-socketio[asgi]>=5.11",
"python-dateutil>=2.8",
"truststore>=0.10",
"pywinpty>=2.0; sys_platform == 'win32'",
]
@@ -46,7 +47,7 @@ exclude = ["cptr/frontend"]
[tool.ruff]
line-length = 100
target-version = "py39"
target-version = "py310"
extend-exclude = [
"cptr/frontend",
"dist",
Generated
+97 -755
View File
File diff suppressed because it is too large Load Diff