This commit is contained in:
Timothy Jaeryang Baek committed 2026-07-11 17:45:16 -05:00
1 parent 650fb254a2
commit 2d30dfe7ff
21 files changed
+1127 -595

No files matched your search

+22
View File
@@ -40,3 +40,25 @@ export const searchFiles = (query: string, path: string) =>
fetchJSON(
`/api/workspace/files/search?query=${encodeURIComponent(query)}&path=${encodeURIComponent(path)}`
);
export type ContentMatch = { line: number; column: number; text: string };
export type FileMatch = {
path: string;
relative_path: string;
name: string;
type: 'file' | 'directory';
name_match: boolean;
content_matches: ContentMatch[];
};
export type FileMatches = { results: FileMatch[]; truncated: boolean };
export const getFileMatches = (
query: string,
path: string,
showHidden: boolean,
signal?: AbortSignal
) =>
fetchJSON<FileMatches>(
`/api/workspace/files/matches?query=${encodeURIComponent(query)}&path=${encodeURIComponent(path)}&show_hidden=${showHidden}`,
{ signal }
);
File diff suppressed because it is too large. Load diff
@@ -59,7 +59,7 @@
let viewportTimer: ReturnType<typeof setTimeout> | undefined;
let reconnectAttempt = 0;
let disposed = false;
let viewport = { width: 1280, height: 720 };
let viewport = { width: 0, height: 0 };
let pendingPointer: Record<string, unknown> | undefined;
let pointerFrame = 0;
let hasFrame = false;
@@ -77,6 +77,7 @@
let suppressText = '';
let keepKeyboardFocus = false;
let audioClockOrigin: number | undefined;
let reapplyViewportAfterConfig = true;
const pressedKeys = new Map<string, Record<string, unknown>>();
const touchPoints = new Map<number, Record<string, unknown>>();
const macClient = /Mac|iPhone|iPad/.test(navigator.userAgent);
@@ -140,6 +141,7 @@
if (disposed) return;
ready = false;
lastViewport = '';
reapplyViewportAfterConfig = true;
awaitingFrame = true;
onstatus(hasFrame ? 'playing' : 'reconnecting');
const scheme = location.protocol === 'https:' ? 'wss' : 'ws';
@@ -250,6 +252,10 @@
}
});
decoder.configure({ codec: config.codec, optimizeForLatency: true });
if (managed && reapplyViewportAfterConfig) {
reapplyViewportAfterConfig = false;
void sendViewport(true);
}
}
function configureAudio(config: { codec: string; sampleRate: number; numberOfChannels: number }) {
@@ -325,10 +331,10 @@
}
}
async function sendViewport() {
async function sendViewport(force = false) {
const device = deviceProfile || (await deviceProfilePromise);
const key = JSON.stringify([viewport, quality, device, deviceMode, mobileViewport]);
if (key === lastViewport) return;
if (!force && key === lastViewport) return;
lastViewport = key;
send({
type: 'viewport',
@@ -336,7 +342,8 @@
quality,
device,
device_mode: deviceMode,
mobile_viewport: mobileViewport
mobile_viewport: mobileViewport,
force
});
}
@@ -15,7 +15,10 @@
deleteFiles,
moveFile,
uploadFiles as apiUpload,
createEntry
createEntry,
getFileMatches,
type FileMatch,
type ContentMatch
} from '$lib/apis/files';
import { fileIconName } from '$lib/utils/fileIcon';
import Icon from './Icon.svelte';
@@ -44,6 +47,14 @@
let dragExpandTimer: ReturnType<typeof setTimeout> | null = null;
let error = $state<string | null>(null);
let searchQuery = $state('');
let matchResults = $state<FileMatch[] | null>(null);
let matchLoading = $state(false);
let matchError = $state<string | null>(null);
let matchesTruncated = $state(false);
let matchTimer: ReturnType<typeof setTimeout> | null = null;
let matchController: AbortController | null = null;
let matchRequestId = 0;
let searchTargetRequestId = 0;
let dragOverDir = $state<string | null>(null);
let draggedItem = $state<string | null>(null);
let showNewInput = $state<'file' | 'folder' | null>(null);
@@ -80,6 +91,8 @@
let cwd = $derived($activeWorkspace?.fileBrowserCwd ?? $activeWorkspace?.path ?? '/');
let workspacePath = $derived($activeWorkspace?.path ?? '/');
let searchText = $derived(searchQuery.trim());
let isSearching = $derived(Boolean(searchText));
let gitStatus = $derived(gitStatusStore.status);
let gitRoot = $derived(workspacePath.replace(/\/$/, ''));
@@ -283,6 +296,7 @@
const isNavigation = _prevCwd !== '';
_prevCwd = cwd;
if (isNavigation) {
searchQuery = '';
// Navigated to a new directory: reset tree state
expandedDirs = new Set();
dirContents = new Map();
@@ -300,6 +314,50 @@
}
});
$effect(() => {
const query = searchText;
const hidden = showHidden;
if (matchTimer) clearTimeout(matchTimer);
matchTimer = null;
matchController?.abort();
matchController = null;
matchError = null;
const requestId = ++matchRequestId;
if (!query) {
matchResults = null;
matchLoading = false;
matchesTruncated = false;
return;
}
showNewInput = null;
clearSelection();
contextMenu = null;
directoryMenu = null;
addMenuOpen = false;
sortMenuOpen = false;
matchLoading = true;
matchTimer = setTimeout(async () => {
const controller = new AbortController();
matchController = controller;
try {
const data = await getFileMatches(query, cwd, hidden, controller.signal);
if (requestId === matchRequestId) {
matchResults = data.results;
matchesTruncated = data.truncated;
}
} catch (e: any) {
if (e.name !== 'AbortError' && requestId === matchRequestId) {
matchError = e.message || $t('files.failedToSearch');
matchResults = [];
}
} finally {
if (requestId === matchRequestId) matchLoading = false;
}
}, 200);
});
// Keep the websocket watch path in sync (separate effect so it doesn't
// re-trigger directory fetches via fsTick feedback loops)
$effect(() => {
@@ -464,9 +522,46 @@
}
function navigateTo(path: string) {
searchQuery = '';
setFileBrowserCwd(path);
}
function highlightParts(text: string): { text: string; match: boolean }[] {
const query = searchText.toLowerCase();
if (!query) return [{ text, match: false }];
const parts: { text: string; match: boolean }[] = [];
const lower = text.toLowerCase();
let start = 0;
let index = lower.indexOf(query, start);
while (index !== -1) {
if (index > start) parts.push({ text: text.slice(start, index), match: false });
parts.push({ text: text.slice(index, index + query.length), match: true });
start = index + query.length;
index = lower.indexOf(query, start);
}
if (start < text.length) parts.push({ text: text.slice(start), match: false });
return parts;
}
function openFileMatch(match: FileMatch) {
if (match.type === 'directory') {
navigateTo(match.path);
return;
}
openFileTab(match.path);
}
function openContentMatch(match: FileMatch, contentMatch: ContentMatch) {
openFileTab(match.path, undefined, {
searchTarget: {
line: contentMatch.line,
column: contentMatch.column,
length: searchText.length,
requestId: ++searchTargetRequestId
}
});
}
// fileIconName imported from $lib/utils/fileIcon
function formatSize(bytes: number | null): string {
@@ -955,9 +1050,9 @@
<!-- svelte-ignore a11y_no_static_element_interactions -->
<div
class="flex flex-col h-full overflow-hidden relative"
ondragover={onDropzoneOver}
ondragleave={onDropzoneLeave}
ondrop={onDropzoneDrop}
ondragover={(e) => !isSearching && onDropzoneOver(e)}
ondragleave={(e) => !isSearching && onDropzoneLeave(e)}
ondrop={(e) => !isSearching && onDropzoneDrop(e)}
>
<!-- Header: breadcrumb + actions -->
<div
@@ -1002,29 +1097,31 @@
<Icon name="refresh" size={11} />
</button>
<!-- Sort dropdown -->
<button
bind:this={sortBtnEl}
class="flex items-center justify-center w-5 h-5 rounded text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors duration-100 shrink-0"
onclick={() => {
sortMenuOpen = !sortMenuOpen;
}}
use:tooltip={$t('files.sort')}
>
<Icon name="sort" size={11} />
</button>
{#if !isSearching}
<!-- Sort dropdown -->
<button
bind:this={sortBtnEl}
class="flex items-center justify-center w-5 h-5 rounded text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors duration-100 shrink-0"
onclick={() => {
sortMenuOpen = !sortMenuOpen;
}}
use:tooltip={$t('files.sort')}
>
<Icon name="sort" size={11} />
</button>
<!-- Three-dot menu -->
<button
bind:this={addBtnEl}
class="flex items-center justify-center w-5 h-5 rounded text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors duration-100 shrink-0"
onclick={() => {
toggleAddMenu();
}}
use:tooltip={$t('files.actions')}
>
<Icon name="three-dots" size={11} />
</button>
<!-- Three-dot menu -->
<button
bind:this={addBtnEl}
class="flex items-center justify-center w-5 h-5 rounded text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors duration-100 shrink-0"
onclick={() => {
toggleAddMenu();
}}
use:tooltip={$t('files.actions')}
>
<Icon name="three-dots" size={11} />
</button>
{/if}
</div>
<!-- Ports -->
@@ -1051,7 +1148,7 @@
<input
type="text"
class="flex-1 border-none outline-none bg-transparent text-xs text-gray-900 dark:text-white placeholder:text-gray-400"
placeholder={$t('files.filter')}
placeholder={$t('files.searchFilesAndContents')}
bind:value={searchQuery}
/>
{#if searchQuery}
@@ -1064,9 +1161,12 @@
<!-- Sort bar replaced with dropdown in toolbar -->
<!-- File list -->
<div class="flex-1 overflow-y-auto p-1" oncontextmenu={onDirectoryContextMenu}>
<div
class="flex-1 overflow-y-auto p-1"
oncontextmenu={(e) => !isSearching && onDirectoryContextMenu(e)}
>
<!-- New item input -->
{#if showNewInput}
{#if showNewInput && !isSearching}
<div class="flex items-center gap-2 h-7 px-2">
<Icon
name={showNewInput === 'folder' ? 'folder' : 'empty-page'}
@@ -1113,6 +1213,80 @@
onclick={() => fetchDirectory(cwd)}>{$t('files.retry')}</button
>
</div>
{:else if isSearching}
{#if matchLoading}
<div class="flex items-center justify-center py-12">
<Spinner size={16} />
</div>
{:else if matchError}
<div class="flex items-center justify-center py-12">
<p class="text-xs text-red-400">{matchError}</p>
</div>
{:else if !matchResults?.length}
<div class="flex items-center justify-center py-12">
<p class="text-xs text-gray-400 dark:text-gray-600">{$t('files.noMatches')}</p>
</div>
{:else}
{#each matchResults as match (match.path)}
<div class="mb-1 rounded-lg bg-gray-50 dark:bg-white/[0.03] overflow-hidden">
<button
class="flex items-center gap-2 w-full min-h-8 px-2 text-left hover:bg-gray-100 dark:hover:bg-white/[0.06] transition-colors duration-75"
onclick={() => openFileMatch(match)}
>
<span
class="flex items-center justify-center w-4 shrink-0 {match.type === 'directory'
? 'text-gray-500 dark:text-gray-400'
: 'text-gray-400 dark:text-gray-500'}"
>
<Icon name={fileIconName(match.name, match.type)} size={14} strokeWidth={1.4} />
</span>
<span class="min-w-0 flex-1">
<span class="block truncate text-xs text-gray-800 dark:text-gray-200">
{#each highlightParts(match.name) as part}
<span
class={part.match ? 'font-semibold bg-amber-200/70 dark:bg-amber-400/20' : ''}
>{part.text}</span
>
{/each}
</span>
<span class="block truncate text-[0.625rem] text-gray-400 dark:text-gray-600"
>{match.relative_path}</span
>
</span>
{#if match.name_match}
<span class="shrink-0 text-[0.625rem] text-gray-400 dark:text-gray-500"
>{$t('files.filenameMatch')}</span
>
{/if}
</button>
{#each match.content_matches as contentMatch (contentMatch.line)}
<button
class="flex w-full items-baseline gap-2 px-2 py-1 pl-8 text-left hover:bg-gray-100 dark:hover:bg-white/[0.06] transition-colors duration-75"
onclick={() => openContentMatch(match, contentMatch)}
>
<span class="shrink-0 text-[0.625rem] font-mono text-gray-400 dark:text-gray-600"
>{$t('files.line', { line: contentMatch.line })}</span
>
<span
class="min-w-0 truncate text-[0.6875rem] font-mono text-gray-600 dark:text-gray-400"
>
{#each highlightParts(contentMatch.text) as part}
<span
class={part.match ? 'font-semibold bg-amber-200/70 dark:bg-amber-400/20' : ''}
>{part.text}</span
>
{/each}
</span>
</button>
{/each}
</div>
{/each}
{#if matchesTruncated}
<p class="px-2 py-2 text-center text-[0.6875rem] text-gray-400 dark:text-gray-600">
{$t('files.searchTruncated')}
</p>
{/if}
{/if}
{:else if visibleEntries.length === 0 && !showNewInput}
<div class="flex items-center justify-center py-12">
<p class="text-xs text-gray-400 dark:text-gray-600">
@@ -1268,7 +1442,7 @@
</div>
<!-- Upload dropzone overlay -->
{#if dropzoneActive}
{#if dropzoneActive && !isSearching}
<div
class="absolute inset-0 bg-blue-500/10 border-2 border-dashed border-blue-400 dark:border-blue-500 rounded-lg flex items-center justify-center z-10 pointer-events-none"
>
@@ -1277,7 +1451,7 @@
{/if}
<!-- Multi-select action bar -->
{#if selectedPaths.size > 0}
{#if selectedPaths.size > 0 && !isSearching}
<div
class="flex items-center justify-between h-8 px-2 border-t border-gray-200 dark:border-white/6 shrink-0 bg-blue-50 dark:bg-blue-500/5"
>
@@ -1,6 +1,13 @@
<script lang="ts">
import { onMount, onDestroy, tick } from 'svelte';
import { clearTabEdit, markTabUnsaved, updateTabFilePath, activeWorkspace } from '$lib/stores';
import {
clearFileSearchTarget,
clearTabEdit,
markTabUnsaved,
updateTabFilePath,
activeWorkspace,
type FileSearchTarget
} from '$lib/stores';
import { get } from 'svelte/store';
import { t } from '$lib/i18n';
import { tooltip } from '$lib/tooltip';
@@ -80,9 +87,10 @@
filePath: string;
tabId: string;
edit?: boolean;
searchTarget?: FileSearchTarget;
}
let { filePath, tabId, edit = false }: Props = $props();
let { filePath, tabId, edit = false, searchTarget }: Props = $props();
interface FileData {
path: string;
@@ -867,6 +875,33 @@
}
let themeObserver: MutationObserver | null = null;
let appliedSearchTarget = 0;
function applySearchTarget() {
if (!view || !searchTarget || appliedSearchTarget === searchTarget.requestId) return;
const target = searchTarget;
const line = view.state.doc.line(Math.min(Math.max(target.line, 1), view.state.doc.lines));
const from = Math.min(line.from + Math.max(target.column - 1, 0), line.to);
const to = Math.min(from + Math.max(target.length, 0), line.to);
view.dispatch({
selection: { anchor: from, head: to },
effects: EditorView.scrollIntoView(from, { y: 'center' })
});
appliedSearchTarget = target.requestId;
clearFileSearchTarget(tabId, target.requestId);
}
$effect(() => {
if (searchTarget && fileData && !fileData.binary) {
if (isMarkdown && markdownMode !== 'raw') switchMarkdownMode('raw');
else if (isJson && jsonViewMode !== 'source') toggleJsonView();
else if ((isHtml || isSvg) && previewMode) togglePreview();
else if (isCsv && !view) {
requestAnimationFrame(() => initEditor(fileData!.content!, fileData!.language));
}
}
applySearchTarget();
});
function initEditor(content: string, language: string | null) {
if (!editorEl) return;
@@ -944,6 +979,7 @@
const state = EditorState.create({ doc: content, extensions });
view = new EditorView({ state, parent: editorEl });
applyGitLineChanges();
applySearchTarget();
// Watch for theme changes and rebuild editor
themeObserver = new MutationObserver(() => {
@@ -281,10 +281,7 @@
<ToggleSwitch value={$widescreenMode} onchange={(value) => widescreenMode.set(value)} />
</label>
<h3 class="text-xs text-gray-400 dark:text-gray-600 mb-2 mt-5">
{$t('general.uiScale')}
</h3>
<div class="w-full">
<div class="w-full mt-5">
<div class="flex items-center gap-2">
<span id="ui-scale-label" class="text-xs text-gray-600 dark:text-gray-400">
{$t('general.uiScale')}
@@ -1,5 +1,6 @@
{
"app.tagline": "Dein Computer, von überall.",
"home.welcomeBack": "Willkommen zurück, {{name}}.",
"auth.createAccountHint": "Erstelle ein Konto, um loszulegen.",
"auth.signInSystemHint": "Melde dich mit deinem Systemkonto an.",
"auth.setup": "Einrichtung",
@@ -1,5 +1,6 @@
{
"app.tagline": "Your computer, from anywhere.",
"home.welcomeBack": "Welcome back, {{name}}.",
"auth.createAccountHint": "Create your account to get started.",
"auth.signInSystemHint": "Sign in with your system account.",
"auth.setup": "Setup",
@@ -46,6 +47,7 @@
"bar.sidebar": "Sidebar",
"bar.toggleSidebar": "Toggle sidebar",
"files.filter": "Filter...",
"files.searchFilesAndContents": "Search filenames and contents...",
"files.refresh": "Refresh",
"files.sort": "Sort",
"files.actions": "Actions",
@@ -56,6 +58,10 @@
"files.fileNamePlaceholder": "File name...",
"files.retry": "Retry",
"files.noMatches": "No matches",
"files.filenameMatch": "Filename match",
"files.line": "Line {{line}}",
"files.searchTruncated": "Some matches are not shown",
"files.failedToSearch": "Failed to search files",
"files.emptyDirectory": "Empty directory",
"files.dropToUpload": "Drop files to upload",
"files.selected": "{{count}} selected",
@@ -1,5 +1,6 @@
{
"app.tagline": "Tu computadora, desde cualquier lugar.",
"home.welcomeBack": "Te damos la bienvenida de nuevo, {{name}}.",
"auth.createAccountHint": "Crea tu cuenta para comenzar.",
"auth.signInSystemHint": "Inicia sesión con tu cuenta del sistema.",
"auth.setup": "Configuración",
@@ -1,5 +1,6 @@
{
"app.tagline": "Votre ordinateur, où que vous soyez.",
"home.welcomeBack": "Bon retour, {{name}}.",
"auth.createAccountHint": "Créez votre compte pour commencer.",
"auth.signInSystemHint": "Connectez-vous avec votre compte système.",
"auth.setup": "Configuration",
@@ -1,5 +1,6 @@
{
"app.tagline": "どこからでも、あなたのコンピュータへ。",
"home.welcomeBack": "おかえりなさい、{{name}}さん。",
"auth.createAccountHint": "アカウントを作成して始めましょう。",
"auth.signInSystemHint": "システムアカウントでサインインしてください。",
"auth.setup": "セットアップ",
@@ -1,5 +1,6 @@
{
"app.tagline": "어디서든, 당신의 컴퓨터로.",
"home.welcomeBack": "다시 오신 것을 환영합니다, {{name}}님.",
"auth.createAccountHint": "계정을 만들어 시작하세요.",
"auth.signInSystemHint": "시스템 계정으로 로그인하세요.",
"auth.setup": "설정",
@@ -1,5 +1,6 @@
{
"app.tagline": "Seu computador, de qualquer lugar.",
"home.welcomeBack": "Bem-vindo de volta, {{name}}.",
"auth.createAccountHint": "Crie sua conta para começar.",
"auth.signInSystemHint": "Faça login com sua conta do sistema.",
"auth.setup": "Configuração",
@@ -1,5 +1,6 @@
{
"app.tagline": "Ваш компьютер, откуда угодно.",
"home.welcomeBack": "С возвращением, {{name}}.",
"auth.createAccountHint": "Создайте аккаунт, чтобы начать.",
"auth.signInSystemHint": "Войдите с помощью системной учётной записи.",
"auth.setup": "Настройка",
@@ -1,5 +1,6 @@
{
"app.tagline": "随时随地,掌控你的电脑。",
"home.welcomeBack": "欢迎回来,{{name}}。",
"auth.createAccountHint": "创建账户以开始使用。",
"auth.signInSystemHint": "使用系统账户登录。",
"auth.setup": "初始设置",
@@ -1,5 +1,6 @@
{
"app.tagline": "隨時隨地,掌控你的電腦。",
"home.welcomeBack": "歡迎回來,{{name}}。",
"auth.createAccountHint": "建立帳號以開始使用。",
"auth.signInSystemHint": "使用系統帳號登入。",
"auth.setup": "初始設定",
+37 -6
View File
@@ -43,6 +43,13 @@ export type { AppearancePreferences, Theme, ThemeConfig };
// ── Types ───────────────────────────────────────────────────────
export interface FileSearchTarget {
line: number;
column: number;
length: number;
requestId: number;
}
export interface Tab {
id: string;
type: 'home' | 'files' | 'terminal' | 'file' | 'git' | 'chat' | 'preview' | 'browser'; // preview is migrated on load
@@ -56,6 +63,7 @@ export interface Tab {
unsaved?: boolean;
permanent?: boolean;
badge?: number;
searchTarget?: FileSearchTarget;
}
export type SplitDirection = 'horizontal' | 'vertical';
@@ -399,7 +407,7 @@ function persistPreferences(): void {
appearance: {
theme: get(theme),
themeConfig: sanitizeThemeConfig(get(themeConfig)),
textScale: get(textScale) ?? undefined
textScale: get(textScale)
},
sidebarOpen: get(sidebarOpen),
sidebarWidth: get(sidebarWidth),
@@ -413,7 +421,7 @@ function persistPreferences(): void {
requestParams: Object.keys(get(requestParams)).length ? get(requestParams) : undefined,
showUpdateToast: get(showUpdateToastPref),
pwa: get(pwaPreferences),
textScale: get(textScale) ?? undefined,
textScale: get(textScale),
widescreenMode: get(widescreenMode),
homeGroup: get(homeGroup)
};
@@ -884,10 +892,28 @@ export function updateTabLabel(tabId: string, label: string): void {
);
}
export function clearFileSearchTarget(tabId: string, requestId: number): void {
currentWorkspace.update((workspace) =>
workspace
? {
...workspace,
groups: workspace.groups.map((group) => ({
...group,
tabs: group.tabs.map((tab) =>
tab.id === tabId && tab.searchTarget?.requestId === requestId
? { ...tab, searchTarget: undefined }
: tab
)
}))
}
: workspace
);
}
export function openFileTab(
filePath: string,
targetGroupId?: string,
options: { edit?: boolean } = {}
options: { edit?: boolean; searchTarget?: FileSearchTarget } = {}
): void {
const ws = get(currentWorkspace);
if (!ws) return;
@@ -899,9 +925,13 @@ export function openFileTab(
// Reuse existing tab within this group
const existing = group.tabs.find((t) => t.type === 'file' && t.filePath === filePath);
if (existing) {
if (options.edit) {
if (options.edit || options.searchTarget) {
updateGroupTabs(gid, (tabs) => ({
tabs: tabs.map((t) => (t.id === existing.id ? { ...t, edit: true } : t)),
tabs: tabs.map((t) =>
t.id === existing.id
? { ...t, ...(options.edit ? { edit: true } : {}), searchTarget: options.searchTarget }
: t
),
activeTabId: existing.id
}));
return;
@@ -916,7 +946,8 @@ export function openFileTab(
type: 'file',
label: name,
filePath,
edit: options.edit
edit: options.edit,
searchTarget: options.searchTarget
};
updateGroupTabs(gid, (tabs) => ({
+14 -1
View File
@@ -23,6 +23,7 @@
import type { Tab, EditorGroup, EditorLayout, SplitDirection, WorkspaceState } from '$lib/stores';
import { chatEnabled } from '$lib/stores/chat';
import { t } from '$lib/i18n';
import { session } from '$lib/session';
import { get } from 'svelte/store';
import { getWelcome, getWorkspaceState } from '$lib/apis/state';
import { createSession, deleteSession } from '$lib/apis/terminal';
@@ -49,6 +50,7 @@
let pendingIntent = $state<LaunchIntent | null>(null);
let folderPickerIntent = $state<LaunchIntent | null>(null);
let folderPickerWorkspace = $state<string | null>(null);
const welcomeName = $derived($session?.display_name || $session?.username);
const activeHomeTab = $derived(
$homeGroup.tabs.find((tab) => tab.id === $homeGroup.activeTabId) ?? $homeGroup.tabs[0]
);
@@ -928,6 +930,12 @@
{/if}
</div>
{#if welcomeName}
<p class="mb-7 text-xl font-medium tracking-tight text-gray-800 dark:text-gray-200">
{$t('home.welcomeBack', { name: welcomeName })}
</p>
{/if}
<div class="mb-6">
<h2 class="mb-2 text-xs text-gray-400 dark:text-gray-600">{$t('home.start')}</h2>
<button
@@ -1152,7 +1160,12 @@
{:else}
{#each group.tabs.filter((tab) => tab.type === 'file' && tab.filePath) as tab (tab.id)}
<div class="persisted-tab" class:persisted-tab-hidden={tab.id !== group.activeTabId}>
<FileEditor filePath={tab.filePath!} tabId={tab.id} edit={tab.edit === true} />
<FileEditor
filePath={tab.filePath!}
tabId={tab.id}
edit={tab.edit === true}
searchTarget={tab.searchTarget}
/>
</div>
{/each}
{#each group.tabs.filter((tab) => tab.type === 'chat') as tab (tab.id)}
-1
View File
@@ -174,7 +174,6 @@
if (first.done || !first.value) throw new Error('Chrome tab capture returned no video');
let rect = crop(first.value);
await configure(rect.width, rect.height);
paused = false;
if (audioEnabled) void startAudio(stream);
let frame = first.value;
+220 -1
View File
@@ -8,7 +8,9 @@ single-user model. Not safe for shared or public instances. See README.md.
from __future__ import annotations
import asyncio
import os
import json
import shutil
import subprocess
from datetime import datetime, timezone
from pathlib import Path
from typing import Optional
@@ -323,6 +325,223 @@ SEARCH_IGNORE_DIRS = {
".DS_Store",
}
MAX_MATCH_RESULTS = 100
MAX_CONTENT_MATCHES_PER_FILE = 3
MAX_CONTENT_SEARCH_FILE_SIZE = 1 * 1024 * 1024
class ContentMatch(BaseModel):
line: int
column: int
text: str
class FileMatch(BaseModel):
path: str
relative_path: str
name: str
type: str # "file" | "directory"
name_match: bool
content_matches: list[ContentMatch]
class FileMatches(BaseModel):
results: list[FileMatch]
truncated: bool
def _is_search_ignored(name: str) -> bool:
return name in SEARCH_IGNORE_DIRS or name.endswith(".egg-info")
def _walk_match_entries(root: Path, show_hidden: bool):
"""Yield visible files and directories without following symlinks."""
try:
entries = sorted(root.iterdir(), key=lambda item: item.name.lower())
except (OSError, PermissionError):
return
for item in entries:
if _is_search_ignored(item.name) or (not show_hidden and item.name.startswith(".")):
continue
try:
if item.is_symlink():
yield item, "file"
elif item.is_dir():
yield item, "directory"
yield from _walk_match_entries(item, show_hidden)
elif item.is_file():
yield item, "file"
except (OSError, PermissionError):
continue
def _match_column(text: str, query_lower: str) -> int | None:
index = text.lower().find(query_lower)
if index < 0:
return None
# CodeMirror measures columns in UTF-16 code units.
return len(text[:index].encode("utf-16-le")) // 2 + 1
def _content_match(text: str, line: int, query_lower: str) -> ContentMatch | None:
text = text.rstrip("\r\n")
column = _match_column(text, query_lower)
return ContentMatch(line=line, column=column, text=text) if column is not None else None
def _content_matches_with_rg(
root: Path, query: str, query_lower: str, show_hidden: bool, files: set[Path]
) -> tuple[dict[Path, list[ContentMatch]], bool] | None:
rg = shutil.which("rg")
if not rg:
return None
args = [
rg,
"--json",
"--no-messages",
"--fixed-strings",
"--ignore-case",
"--line-number",
"--column",
"--max-count",
str(MAX_CONTENT_MATCHES_PER_FILE + 1),
"--no-ignore",
]
if show_hidden:
args.append("--hidden")
for ignored in SEARCH_IGNORE_DIRS:
pattern = f"!{ignored}" if ignored == ".DS_Store" else f"!{ignored}/**"
args.extend(("--glob", pattern))
args.extend(("--", query, str(root)))
try:
completed = subprocess.run(args, capture_output=True, text=True, check=False)
except OSError:
return None
if completed.returncode not in (0, 1):
return None
matches: dict[Path, list[ContentMatch]] = {}
truncated = False
for raw in completed.stdout.splitlines():
try:
message = json.loads(raw)
except json.JSONDecodeError:
continue
if message.get("type") != "match":
continue
data = message["data"]
path = Path(data["path"]["text"]).resolve()
if path not in files:
continue
line_matches = matches.setdefault(path, [])
if len(line_matches) >= MAX_CONTENT_MATCHES_PER_FILE:
truncated = True
continue
match = _content_match(data["lines"]["text"], data["line_number"], query_lower)
if match:
line_matches.append(match)
return matches, truncated
def _content_matches_with_python(
files: set[Path], query_lower: str
) -> tuple[dict[Path, list[ContentMatch]], bool]:
matches: dict[Path, list[ContentMatch]] = {}
truncated = False
for path in files:
try:
if path.stat().st_size > MAX_CONTENT_SEARCH_FILE_SIZE:
continue
with path.open("rb") as source:
if b"\0" in source.read(8192):
continue
lines = path.read_text(encoding="utf-8", errors="replace").splitlines()
except (OSError, PermissionError):
continue
for number, text in enumerate(lines, start=1):
match = _content_match(text, number, query_lower)
if not match:
continue
file_matches = matches.setdefault(path, [])
if len(file_matches) >= MAX_CONTENT_MATCHES_PER_FILE:
truncated = True
break
file_matches.append(match)
return matches, truncated
def find_file_matches(root: Path, query: str, show_hidden: bool = False) -> FileMatches:
"""Find filename/path and literal text matches below a browser directory."""
query = query.strip()
query_lower = query.lower()
entries = list(_walk_match_entries(root, show_hidden))
files = {path.resolve() for path, kind in entries if kind == "file" and not path.is_symlink()}
content_result = _content_matches_with_rg(root, query, query_lower, show_hidden, files)
content_matches, truncated = (
content_result if content_result is not None else _content_matches_with_python(files, query_lower)
)
matches: list[tuple[int, int, FileMatch]] = []
for path, kind in entries:
relative_path = path.relative_to(root).as_posix()
name_lower = path.name.lower()
relative_lower = relative_path.lower()
if name_lower == query_lower:
score = 0
elif name_lower.startswith(query_lower):
score = 1
elif query_lower in name_lower:
score = 2
elif query_lower in relative_lower:
score = 3
else:
score = 4
path_content_matches = content_matches.get(path.resolve(), []) if kind == "file" else []
name_match = score < 4
if not name_match and not path_content_matches:
continue
matches.append(
(
score,
len(relative_path),
FileMatch(
path=str(path),
relative_path=relative_path,
name=path.name,
type=kind,
name_match=name_match,
content_matches=path_content_matches,
),
)
)
matches.sort(key=lambda item: (item[0], item[1], item[2].relative_path.lower()))
if len(matches) > MAX_MATCH_RESULTS:
truncated = True
return FileMatches(results=[item[2] for item in matches[:MAX_MATCH_RESULTS]], truncated=truncated)
@router.get("/matches", response_model=FileMatches)
async def file_matches(
query: str = Query(..., description="Literal text to match"),
path: str = Query(..., description="Root path to search"),
show_hidden: bool = Query(False, description="Include dotfiles and dot-directories"),
):
"""Return filename/path and content matches below a directory."""
if not query.strip():
raise HTTPException(status_code=400, detail="Query must not be blank")
root = Path(path).resolve()
if not root.exists() or not root.is_dir():
raise HTTPException(status_code=404, detail=f"Path not found: {path}")
return await asyncio.to_thread(find_file_matches, root, query, show_hidden)
class SearchResult(BaseModel):
path: str
+20 -6
View File
@@ -426,6 +426,7 @@ class ChromeViewer:
controller_origin: str
encoder: WebSocket | None = None
encoder_connected: asyncio.Event = field(default_factory=asyncio.Event)
encoder_configured: asyncio.Event = field(default_factory=asyncio.Event)
first_keyframe: asyncio.Event = field(default_factory=asyncio.Event)
encoder_error: str = ""
config: dict[str, Any] | None = None
@@ -642,7 +643,7 @@ class ChromeViewerManager:
},
)
await asyncio.wait_for(
viewer.first_keyframe.wait(), 90 if host.source == "external" else 5
viewer.encoder_configured.wait(), 90 if host.source == "external" else 5
)
if viewer.encoder_error:
raise RuntimeError(viewer.encoder_error)
@@ -917,6 +918,7 @@ class ChromeViewerManager:
data = json.loads(message["text"])
if data.get("type") == "config":
viewer.config = data
viewer.encoder_configured.set()
viewer.keyframe = None
if viewer.viewport_initialized:
for peer in tuple(viewer.peers):
@@ -1044,6 +1046,7 @@ class ChromeViewerManager:
)
await viewer.controller_cdp.send("Runtime.enable")
viewer.first_keyframe.clear()
viewer.encoder_configured.clear()
viewer.encoder_error = ""
for _ in range(30):
ready = await viewer.controller_cdp.send(
@@ -1057,7 +1060,7 @@ class ChromeViewerManager:
"Runtime.evaluate",
{"expression": "window.startCapture()", "userGesture": True},
)
await asyncio.wait_for(viewer.first_keyframe.wait(), 5)
await asyncio.wait_for(viewer.encoder_configured.wait(), 5)
if viewer.encoder_error:
raise RuntimeError(viewer.encoder_error)
viewer.session.status = "playing"
@@ -1291,7 +1294,7 @@ class ChromeViewerManager:
device_changed = (
mode != viewer.session.device_mode or mobile_viewport != viewer.session.mobile_viewport
)
viewport_changed = viewer.viewport != layout_viewport
viewport_changed = viewer.viewport != layout_viewport or data.get("force") is True
viewer.viewport = layout_viewport
viewer.session.device_profile = profile
viewer.session.device_mode = mode
@@ -1354,7 +1357,13 @@ class ChromeViewerManager:
await viewer.target_cdp.send(
"Page.navigate", {"url": viewer.session.url or "about:blank"}
)
await self._request_keyframe(viewer)
await self._send_encoder(viewer, {"type": "resize"})
await self._send_encoder(
viewer,
{"type": "resume" if any(item.visible for item in viewer.peers) else "pause"},
)
if any(item.visible for item in viewer.peers):
await self._request_keyframe(viewer)
elif device_changed and viewer.session.url:
await viewer.target_cdp.send("Page.reload")
@@ -1551,9 +1560,14 @@ class ChromeViewerManager:
await self._send_personal({"type": "keyframe"})
return
await self._send_encoder(
viewer, {"type": "resume" if any(item.visible for item in viewer.peers) else "pause"}
viewer,
{
"type": "resume"
if viewer.viewport_initialized and any(item.visible for item in viewer.peers)
else "pause"
},
)
if visible:
if visible and viewer.viewport_initialized:
await self._request_keyframe(viewer)
async def _request_keyframe(self, viewer: ChromeViewer | PersonalTab) -> None: