From f6023daec88cfcded329f532086395e8afe0c822 Mon Sep 17 00:00:00 2001 From: Timothy Jaeryang Baek Date: Tue, 9 Jun 2026 22:12:11 +0100 Subject: [PATCH] refac --- cptr/app.py | 2 + cptr/frontend/src/lib/apis/search.ts | 47 +++ .../src/lib/components/SearchModal.svelte | 305 ++++++++++++++++++ .../src/lib/components/Sidebar.svelte | 54 ++-- .../src/lib/components/chat/ChatPanel.svelte | 4 + cptr/frontend/src/lib/i18n/locales/en.json | 8 + cptr/frontend/src/lib/stores.ts | 14 +- cptr/frontend/src/lib/stores/keybindings.ts | 8 + cptr/frontend/src/routes/+layout.svelte | 15 +- cptr/frontend/src/routes/+page.svelte | 41 ++- cptr/models/chats.py | 95 ++++++ cptr/routers/__init__.py | 2 + cptr/routers/search.py | 144 +++++++++ cptr/routers/workspace.py | 120 +++---- 14 files changed, 763 insertions(+), 96 deletions(-) create mode 100644 cptr/frontend/src/lib/apis/search.ts create mode 100644 cptr/frontend/src/lib/components/SearchModal.svelte create mode 100644 cptr/routers/search.py diff --git a/cptr/app.py b/cptr/app.py index 946af38..2cee5f0 100644 --- a/cptr/app.py +++ b/cptr/app.py @@ -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) diff --git a/cptr/frontend/src/lib/apis/search.ts b/cptr/frontend/src/lib/apis/search.ts new file mode 100644 index 0000000..9efc0f4 --- /dev/null +++ b/cptr/frontend/src/lib/apis/search.ts @@ -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(`/api/search?${params}`); +}; + +export const getRecentChats = (limit = 9) => + fetchJSON<{ chats: ChatSearchResult[] }>(`/api/search/recent?limit=${limit}`); diff --git a/cptr/frontend/src/lib/components/SearchModal.svelte b/cptr/frontend/src/lib/components/SearchModal.svelte new file mode 100644 index 0000000..75b41dc --- /dev/null +++ b/cptr/frontend/src/lib/components/SearchModal.svelte @@ -0,0 +1,305 @@ + + + + + + +
+ + +
+ + +
+ {#if showingRecents && filteredRecents.length > 0} + +
{$t('search.recentChats')}
+ {#each filteredRecents as chat, i (chat.id)} + + {/each} + {:else if showingRecents} +
{$t('search.noRecentChats')}
+ {:else if !showingRecents} + {#if displayedChats.length > 0} + +
{$t('search.chats')}
+ {#each displayedChats as chat, i (chat.id)} + {@const idx = i} + + {/each} + {/if} + + {#if fileResults.length > 0} + +
{$t('search.files')}
+ {#each fileResults as file, i (file.path)} + {@const idx = displayedChats.length + i} + + {/each} + {/if} + + {#if loading} +
+ +
+ {:else if query && totalResults === 0} +
{$t('search.noResults')}
+ {/if} + {/if} +
+
diff --git a/cptr/frontend/src/lib/components/Sidebar.svelte b/cptr/frontend/src/lib/components/Sidebar.svelte index e302b50..315263b 100644 --- a/cptr/frontend/src/lib/components/Sidebar.svelte +++ b/cptr/frontend/src/lib/components/Sidebar.svelte @@ -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>(new Map()); let wsChatsLoading = $state>(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((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 @@ + +
+ +
+ {#if $chatEnabled} -
+
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()}` }; diff --git a/cptr/frontend/src/lib/stores/keybindings.ts b/cptr/frontend/src/lib/stores/keybindings.ts index bc02f71..7fa7dac 100644 --- a/cptr/frontend/src/lib/stores/keybindings.ts +++ b/cptr/frontend/src/lib/stores/keybindings.ts @@ -35,6 +35,7 @@ export const ACTION_IDS = [ 'nextTab', 'prevTab', 'quickOpen', + 'searchAll', 'openSettings', 'toggleSplit', 'toggleSidebar' @@ -52,6 +53,7 @@ export const ACTION_LABELS: Record = { 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 = { 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; diff --git a/cptr/frontend/src/routes/+layout.svelte b/cptr/frontend/src/routes/+layout.svelte index 8b4b190..22acf13 100644 --- a/cptr/frontend/src/routes/+layout.svelte +++ b/cptr/frontend/src/routes/+layout.svelte @@ -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 @@
- {#if showQuickOpen} - (showQuickOpen = false)} /> + {#if $showSearch} + showSearch.set(false)} /> {/if} {#if showSettings} (showSettings = false)} /> diff --git a/cptr/frontend/src/routes/+page.svelte b/cptr/frontend/src/routes/+page.svelte index 3e910ec..308ae3b 100644 --- a/cptr/frontend/src/routes/+page.svelte +++ b/cptr/frontend/src/routes/+page.svelte @@ -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(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); diff --git a/cptr/models/chats.py b/cptr/models/chats.py index 8fed6dd..88015c3 100644 --- a/cptr/models/chats.py +++ b/cptr/models/chats.py @@ -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.""" diff --git a/cptr/routers/__init__.py b/cptr/routers/__init__.py index b9ad358..a127096 100644 --- a/cptr/routers/__init__.py +++ b/cptr/routers/__init__.py @@ -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", diff --git a/cptr/routers/search.py b/cptr/routers/search.py new file mode 100644 index 0000000..5d39b8b --- /dev/null +++ b/cptr/routers/search.py @@ -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 + ] + } diff --git a/cptr/routers/workspace.py b/cptr/routers/workspace.py index 932894f..7bfbec5 100644 --- a/cptr/routers/workspace.py +++ b/cptr/routers/workspace.py @@ -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 ──────────────────────────────────────────────