mirror of
https://github.com/open-webui/computer.git
synced 2026-11-23 06:00:43 -05:00
refac
This commit is contained in:
1 parent
0155b93408
commit
f6023daec8
14 files changed
+763
-96
No files matched your search
@@ -14,6 +14,7 @@ from cptr.routers import (
|
||||
files_router,
|
||||
git_router,
|
||||
proxy_router,
|
||||
search_router,
|
||||
state_router,
|
||||
terminal_router,
|
||||
workspace_router,
|
||||
@@ -190,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)
|
||||
|
||||
@@ -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}`);
|
||||
@@ -0,0 +1,305 @@
|
||||
<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();
|
||||
|
||||
// Show recents when no query, search results when query exists
|
||||
const showingRecents = $derived(!query.trim());
|
||||
const filteredRecents = $derived(
|
||||
$currentWorkspace
|
||||
? recentChats.filter((c) => c.workspace === $currentWorkspace!.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 active, scope to files from that workspace only
|
||||
const isWorkspaceScoped = $derived(!!$currentWorkspace);
|
||||
|
||||
async function doSearch(q: string) {
|
||||
const activeWs = $currentWorkspace;
|
||||
|
||||
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>
|
||||
@@ -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,26 +129,8 @@
|
||||
}
|
||||
}
|
||||
|
||||
async function handleNewChat(wsPath: string) {
|
||||
// Navigate to the workspace if not already there
|
||||
const currentWsPath = $page.url.searchParams.get('workspace');
|
||||
if ($page.url.pathname !== '/' || currentWsPath !== wsPath) {
|
||||
await goto(`/?workspace=${encodeURIComponent(wsPath)}`);
|
||||
}
|
||||
// Wait for loadWorkspace() to finish populating currentWorkspace
|
||||
// (it runs async in a $effect after goto resolves)
|
||||
const ws = get(currentWorkspace);
|
||||
if (!ws || ws.path !== wsPath) {
|
||||
await new Promise<void>((resolve) => {
|
||||
const unsub = currentWorkspace.subscribe((w) => {
|
||||
if (w && w.path === wsPath) {
|
||||
unsub();
|
||||
resolve();
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
openChatTab();
|
||||
function handleNewChat(wsPath: string) {
|
||||
goto(`/?workspace=${encodeURIComponent(wsPath)}&chatId`);
|
||||
if (typeof window !== 'undefined' && window.innerWidth < 768) {
|
||||
sidebarOpen.set(false);
|
||||
}
|
||||
@@ -333,9 +313,23 @@
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<!-- 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 mt-1 shrink-0">
|
||||
<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"
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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)} />
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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."""
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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
@@ -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 ──────────────────────────────────────────────
|
||||
|
||||
|
||||
|
||||
Reference in new issue
Block a user