mirror of
https://github.com/open-webui/computer.git
synced 2026-11-25 23:00:55 -05:00
refac
This commit is contained in:
1 parent
c1896a7ff0
commit
290faeede8
8 files changed
+209
-94
No files matched your search
@@ -3,8 +3,36 @@
|
||||
*/
|
||||
import { fetchJSON, jsonBody } from '$lib/apis';
|
||||
|
||||
export const getGitStatus = (root: string) =>
|
||||
fetchJSON(`/api/git/status?root=${encodeURIComponent(root)}`);
|
||||
// Deduplicate concurrent getGitStatus calls.
|
||||
// Multiple components (layout, GitBar, FileEditor × N) all fetch on mount;
|
||||
// this ensures they share a single in-flight request and a brief result cache.
|
||||
const _statusCache = new Map<string, { promise: Promise<unknown>; ts: number }>();
|
||||
const STATUS_CACHE_MS = 2000;
|
||||
|
||||
export const getGitStatus = (root: string): Promise<unknown> => {
|
||||
const cached = _statusCache.get(root);
|
||||
if (cached && Date.now() - cached.ts < STATUS_CACHE_MS) {
|
||||
return cached.promise;
|
||||
}
|
||||
const promise = fetchJSON(`/api/git/status?root=${encodeURIComponent(root)}`);
|
||||
_statusCache.set(root, { promise, ts: Date.now() });
|
||||
// Clean up after cache window
|
||||
promise.finally(() => {
|
||||
setTimeout(() => {
|
||||
const entry = _statusCache.get(root);
|
||||
if (entry && entry.promise === promise) {
|
||||
_statusCache.delete(root);
|
||||
}
|
||||
}, STATUS_CACHE_MS);
|
||||
});
|
||||
return promise;
|
||||
};
|
||||
|
||||
/** Force a fresh git status fetch, bypassing the cache. */
|
||||
export const getGitStatusFresh = (root: string): Promise<unknown> => {
|
||||
_statusCache.delete(root);
|
||||
return getGitStatus(root);
|
||||
};
|
||||
|
||||
export const getGitLog = (root: string, limit = 30) =>
|
||||
fetchJSON(`/api/git/log?root=${encodeURIComponent(root)}&limit=${limit}`);
|
||||
|
||||
@@ -35,6 +35,7 @@
|
||||
|
||||
let entries = $state<FileEntry[]>([]);
|
||||
let loading = $state(false);
|
||||
let initialLoad = $state(true);
|
||||
let fetchTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
let fetching = false;
|
||||
let error = $state<string | null>(null);
|
||||
@@ -109,6 +110,7 @@
|
||||
// Navigated to a new directory: reset tree state
|
||||
expandedDirs = new Set();
|
||||
dirContents = new Map();
|
||||
initialLoad = true;
|
||||
} else {
|
||||
// Component (re)mount: restore tree state from cache
|
||||
const cachedExpanded = _treeExpandedCache.get(cwd);
|
||||
@@ -130,11 +132,12 @@
|
||||
}
|
||||
});
|
||||
|
||||
// Auto-refresh on filesystem changes (debounced)
|
||||
// Auto-refresh on filesystem changes (debounced, silent)
|
||||
$effect(() => {
|
||||
const _tick = systemEvents.fsTick; // subscribe
|
||||
if (_tick > 0 && cwd && !fetching && systemEvents.isRelevantFsChange(cwd)) {
|
||||
debouncedFetch(cwd);
|
||||
// Use a longer debounce for auto-refresh to batch rapid fs events
|
||||
debouncedFetch(cwd, 800);
|
||||
// Also refresh expanded directories
|
||||
for (const dir of expandedDirs) {
|
||||
fetchSubdir(dir);
|
||||
@@ -153,12 +156,12 @@
|
||||
}
|
||||
}
|
||||
|
||||
function debouncedFetch(path: string) {
|
||||
function debouncedFetch(path: string, delay = 300) {
|
||||
if (fetchTimer) clearTimeout(fetchTimer);
|
||||
fetchTimer = setTimeout(() => {
|
||||
fetchTimer = null;
|
||||
fetchDirectoryImmediate(path);
|
||||
}, 300);
|
||||
}, delay);
|
||||
}
|
||||
|
||||
async function fetchDirectoryImmediate(path: string) {
|
||||
@@ -166,7 +169,10 @@
|
||||
fetchTimer = null;
|
||||
if (fetching) return; // skip overlapping fetches
|
||||
fetching = true;
|
||||
loading = true;
|
||||
// Only show the loading spinner on initial load (no entries yet).
|
||||
// Background refreshes silently update entries in-place.
|
||||
const isInitial = entries.length === 0;
|
||||
if (isInitial) loading = true;
|
||||
error = null;
|
||||
try {
|
||||
const data = await listDir(path);
|
||||
@@ -183,6 +189,7 @@
|
||||
}
|
||||
} finally {
|
||||
loading = false;
|
||||
initialLoad = false;
|
||||
fetching = false;
|
||||
}
|
||||
}
|
||||
@@ -752,7 +759,7 @@
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
{#if loading}
|
||||
{#if loading && initialLoad}
|
||||
<div class="flex items-center justify-center py-12">
|
||||
<div
|
||||
class="w-4 h-4 border-2 border-gray-300 border-t-gray-600 dark:border-gray-700 dark:border-t-gray-400 rounded-full animate-spin"
|
||||
|
||||
@@ -4,7 +4,8 @@
|
||||
import { get } from 'svelte/store';
|
||||
import { tooltip } from '$lib/tooltip';
|
||||
import { readFile, writeFile } from '$lib/apis/files';
|
||||
import { getGitDiff, getGitStatus } from '$lib/apis/git';
|
||||
import { getGitDiff } from '$lib/apis/git';
|
||||
import { gitStatusStore } from '$lib/stores/gitStatus.svelte';
|
||||
import Icon from './Icon.svelte';
|
||||
import SaveDialog from './SaveDialog.svelte';
|
||||
import type RichTextEditorType from './markdown/RichTextEditor.svelte';
|
||||
@@ -356,23 +357,16 @@
|
||||
loading = false;
|
||||
}
|
||||
|
||||
// Check git status for this file (non-blocking)
|
||||
// Check git status for this file from centralized store (non-blocking)
|
||||
if (!isUntitled && !isBinaryPreview) {
|
||||
try {
|
||||
const ws = get(activeWorkspace);
|
||||
if (ws) {
|
||||
const status = (await getGitStatus(ws.path)) as {
|
||||
is_repo?: boolean;
|
||||
files?: { path: string }[];
|
||||
};
|
||||
if (status?.is_repo && status.files) {
|
||||
const relPath = path.startsWith(ws.path)
|
||||
? path.slice(ws.path.replace(/\/$/, '').length + 1)
|
||||
: path;
|
||||
hasGitChanges = status.files.some((f) => f.path === relPath);
|
||||
}
|
||||
}
|
||||
} catch {}
|
||||
const status = gitStatusStore.status;
|
||||
const ws = get(activeWorkspace);
|
||||
if (ws && status?.is_repo && status.files) {
|
||||
const relPath = path.startsWith(ws.path)
|
||||
? path.slice(ws.path.replace(/\/$/, '').length + 1)
|
||||
: path;
|
||||
hasGitChanges = status.files.some((f) => f.path === relPath);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
<script lang="ts">
|
||||
import { activeWorkspace, openFileTab } from '$lib/stores';
|
||||
import {
|
||||
getGitStatus,
|
||||
getGitLog,
|
||||
getGitDiff,
|
||||
getGitShow,
|
||||
@@ -15,6 +14,7 @@
|
||||
checkoutBranch,
|
||||
createGitBranch
|
||||
} from '$lib/apis/git';
|
||||
import { gitStatusStore } from '$lib/stores/gitStatus.svelte';
|
||||
import Icon from './Icon.svelte';
|
||||
import DropdownMenu from './DropdownMenu.svelte';
|
||||
import { tooltip } from '$lib/tooltip';
|
||||
@@ -29,13 +29,6 @@
|
||||
let view = $state<'changes' | 'history'>('changes');
|
||||
let showDiff = $state(false);
|
||||
let showBranches = $state(false);
|
||||
let gitStatus = $state<{
|
||||
is_repo: boolean;
|
||||
branch: string;
|
||||
ahead: number;
|
||||
behind: number;
|
||||
files: GitFile[];
|
||||
} | null>(null);
|
||||
let commits = $state<Commit[]>([]);
|
||||
let branchData = $state<{ current: string; local: string[]; remote: string[] } | null>(null);
|
||||
let newBranchName = $state('');
|
||||
@@ -60,15 +53,14 @@
|
||||
const allStaged = $derived(totalChanges > 0 && unstagedFiles.length === 0);
|
||||
const someStaged = $derived(stagedFiles.length > 0 && unstagedFiles.length > 0);
|
||||
|
||||
$effect(() => {
|
||||
if (workspacePath) {
|
||||
refresh();
|
||||
const iv = setInterval(refresh, 5000);
|
||||
return () => clearInterval(iv);
|
||||
} else {
|
||||
gitStatus = null;
|
||||
}
|
||||
});
|
||||
// Read from centralized store instead of independent polling
|
||||
let gitStatus = $derived(gitStatusStore.status as {
|
||||
is_repo: boolean;
|
||||
branch: string;
|
||||
ahead: number;
|
||||
behind: number;
|
||||
files: GitFile[];
|
||||
} | null);
|
||||
|
||||
// Clear stale selection when file is no longer in the changed list
|
||||
$effect(() => {
|
||||
@@ -97,12 +89,7 @@
|
||||
});
|
||||
|
||||
async function refresh() {
|
||||
if (!workspacePath) return;
|
||||
try {
|
||||
gitStatus = await getGitStatus(workspacePath);
|
||||
} catch {
|
||||
/* silent */
|
||||
}
|
||||
await gitStatusStore.refresh();
|
||||
}
|
||||
|
||||
async function selectFile(path: string, staged: boolean, untracked: boolean = false) {
|
||||
|
||||
@@ -1,19 +1,12 @@
|
||||
<script lang="ts">
|
||||
import { activeWorkspace, openFileTab, gitReviewOpen } from '$lib/stores';
|
||||
import { getGitDiff, getGitStatus } from '$lib/apis/git';
|
||||
import { getGitDiff } from '$lib/apis/git';
|
||||
import { gitStatusStore, type GitStatus, type GitFile } from '$lib/stores/gitStatus.svelte';
|
||||
|
||||
import { tooltip } from '$lib/tooltip';
|
||||
import Icon from './Icon.svelte';
|
||||
|
||||
type GitFile = { path: string; status: string; staged: boolean };
|
||||
type GitStatus = {
|
||||
is_repo: boolean;
|
||||
branch: string;
|
||||
upstream?: string;
|
||||
ahead: number;
|
||||
behind: number;
|
||||
files: GitFile[];
|
||||
};
|
||||
|
||||
type DiffLine = { type: 'added' | 'removed' | 'context'; content: string };
|
||||
type DiffHunk = { header: string; lines: DiffLine[] };
|
||||
type DiffFile = { path: string; hunks: DiffHunk[] };
|
||||
@@ -29,7 +22,7 @@
|
||||
};
|
||||
type NumberedLine = DiffLine & { oldNumber: number | null; newNumber: number | null };
|
||||
|
||||
let gitStatus = $state<GitStatus | null>(null);
|
||||
let gitStatus = $derived(gitStatusStore.status);
|
||||
let reviewFiles = $state<ReviewFile[]>([]);
|
||||
let loading = $state(false);
|
||||
let refreshing = $state(false);
|
||||
@@ -40,22 +33,23 @@
|
||||
const totalChanges = $derived(reviewFiles.length);
|
||||
const anyExpanded = $derived(reviewFiles.some((file) => file.expanded));
|
||||
|
||||
// React to git status changes from centralized store
|
||||
let _prevStatusRef: GitStatus | null = null;
|
||||
$effect(() => {
|
||||
if (!workspacePath) {
|
||||
gitStatus = null;
|
||||
const status = gitStatus;
|
||||
if (!workspacePath || !status) {
|
||||
reviewFiles = [];
|
||||
return;
|
||||
}
|
||||
|
||||
refreshReview(true);
|
||||
const interval = setInterval(() => refreshReview(false), 5000);
|
||||
return () => {
|
||||
loadSeq += 1;
|
||||
clearInterval(interval);
|
||||
};
|
||||
// Only re-fetch diffs when status actually changes
|
||||
if (status !== _prevStatusRef) {
|
||||
const isInitial = _prevStatusRef === null;
|
||||
_prevStatusRef = status;
|
||||
fetchDiffs(status, isInitial);
|
||||
}
|
||||
});
|
||||
|
||||
async function refreshReview(initial = false) {
|
||||
async function fetchDiffs(status: GitStatus, initial = false) {
|
||||
const seq = ++loadSeq;
|
||||
const root = workspacePath;
|
||||
if (!root) return;
|
||||
@@ -65,10 +59,6 @@
|
||||
error = '';
|
||||
|
||||
try {
|
||||
const status = (await getGitStatus(root)) as GitStatus;
|
||||
if (seq !== loadSeq || root !== workspacePath) return;
|
||||
|
||||
gitStatus = status;
|
||||
if (!status.is_repo) {
|
||||
reviewFiles = [];
|
||||
return;
|
||||
@@ -112,7 +102,6 @@
|
||||
} catch (e) {
|
||||
if (seq !== loadSeq) return;
|
||||
error = e instanceof Error ? e.message : 'Failed to load git changes';
|
||||
gitStatus = null;
|
||||
reviewFiles = [];
|
||||
} finally {
|
||||
if (seq === loadSeq) {
|
||||
@@ -122,6 +111,10 @@
|
||||
}
|
||||
}
|
||||
|
||||
async function refreshReview(initial = false) {
|
||||
await gitStatusStore.refresh();
|
||||
}
|
||||
|
||||
function fileKey(file: GitFile): string {
|
||||
return `${file.staged ? 'staged' : 'unstaged'}:${file.status}:${file.path}`;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
/**
|
||||
* Centralized git status store.
|
||||
*
|
||||
* Single source of truth – replaces scattered getGitStatus() calls
|
||||
* across layout, GitBar, GitView, and FileEditor.
|
||||
*
|
||||
* Components read from this store; mutations (commit, stage, etc.)
|
||||
* call refresh() to update everyone at once.
|
||||
*/
|
||||
|
||||
import { fetchJSON } from '$lib/apis';
|
||||
|
||||
export interface GitFile {
|
||||
path: string;
|
||||
status: string;
|
||||
staged: boolean;
|
||||
}
|
||||
|
||||
export interface GitStatus {
|
||||
is_repo: boolean;
|
||||
branch: string;
|
||||
upstream?: string;
|
||||
ahead: number;
|
||||
behind: number;
|
||||
files: GitFile[];
|
||||
}
|
||||
|
||||
let _status = $state<GitStatus | null>(null);
|
||||
let _loading = $state(false);
|
||||
let _currentRoot = '';
|
||||
let _fetchPromise: Promise<void> | null = null;
|
||||
|
||||
async function _doFetch(root: string) {
|
||||
if (!root) {
|
||||
_status = null;
|
||||
return;
|
||||
}
|
||||
_loading = true;
|
||||
try {
|
||||
const data = (await fetchJSON(
|
||||
`/api/git/status?root=${encodeURIComponent(root)}`
|
||||
)) as GitStatus;
|
||||
// Only apply if root hasn't changed while we were fetching
|
||||
if (root === _currentRoot) {
|
||||
_status = data;
|
||||
}
|
||||
} catch {
|
||||
if (root === _currentRoot) {
|
||||
_status = null;
|
||||
}
|
||||
} finally {
|
||||
_loading = false;
|
||||
_fetchPromise = null;
|
||||
}
|
||||
}
|
||||
|
||||
export const gitStatusStore = {
|
||||
get status() {
|
||||
return _status;
|
||||
},
|
||||
get loading() {
|
||||
return _loading;
|
||||
},
|
||||
get isRepo() {
|
||||
return _status?.is_repo ?? false;
|
||||
},
|
||||
|
||||
/** Set the workspace root and fetch status. */
|
||||
setRoot(root: string) {
|
||||
if (root === _currentRoot) return;
|
||||
_currentRoot = root;
|
||||
_status = null;
|
||||
this.refresh();
|
||||
},
|
||||
|
||||
/** Clear all state (no workspace). */
|
||||
clear() {
|
||||
_currentRoot = '';
|
||||
_status = null;
|
||||
_loading = false;
|
||||
_fetchPromise = null;
|
||||
},
|
||||
|
||||
/**
|
||||
* Refresh git status from the server.
|
||||
* Concurrent calls are coalesced into a single fetch.
|
||||
*/
|
||||
refresh() {
|
||||
if (!_currentRoot) return;
|
||||
if (!_fetchPromise) {
|
||||
_fetchPromise = _doFetch(_currentRoot);
|
||||
}
|
||||
return _fetchPromise;
|
||||
}
|
||||
};
|
||||
@@ -31,7 +31,7 @@
|
||||
import { socketStore } from '$lib/stores/socket.svelte';
|
||||
import { setSession, clearSession } from '$lib/session';
|
||||
import { getSession, getConfig } from '$lib/apis/auth';
|
||||
import { getGitStatus } from '$lib/apis/git';
|
||||
import { gitStatusStore } from '$lib/stores/gitStatus.svelte';
|
||||
import { t } from '$lib/i18n';
|
||||
import { refreshChatState, bindGlobalChatListener } from '$lib/stores/chat';
|
||||
|
||||
@@ -200,32 +200,21 @@
|
||||
}
|
||||
});
|
||||
|
||||
// Detect if workspace is a git repo
|
||||
// Drive centralized git status from workspace
|
||||
$effect(() => {
|
||||
const ws = $currentWorkspace;
|
||||
if (!ws) {
|
||||
gitStatusStore.clear();
|
||||
isGitRepo.set(false);
|
||||
gitReviewOpen.set(false);
|
||||
return;
|
||||
}
|
||||
const wsPath = ws.path;
|
||||
let cancelled = false;
|
||||
gitStatusStore.setRoot(ws.path);
|
||||
});
|
||||
|
||||
async function check() {
|
||||
try {
|
||||
const status = (await getGitStatus(wsPath)) as { is_repo?: boolean };
|
||||
if (!cancelled) isGitRepo.set(Boolean(status?.is_repo));
|
||||
} catch {
|
||||
if (!cancelled) isGitRepo.set(false);
|
||||
}
|
||||
}
|
||||
|
||||
check();
|
||||
const interval = setInterval(check, 5000);
|
||||
return () => {
|
||||
cancelled = true;
|
||||
clearInterval(interval);
|
||||
};
|
||||
// Sync isGitRepo flag from centralized store
|
||||
$effect(() => {
|
||||
isGitRepo.set(gitStatusStore.isRepo);
|
||||
});
|
||||
</script>
|
||||
|
||||
|
||||
+23
-1
@@ -33,7 +33,17 @@ router = APIRouter(prefix="/api/events", tags=["events"])
|
||||
|
||||
def _create_observer():
|
||||
if platform.system() == "Darwin":
|
||||
return PollingObserver()
|
||||
# Prefer the native FSEvents observer on macOS – it fires only on
|
||||
# real filesystem changes instead of polling (which generates
|
||||
# constant false-positive "modified" events from stat calls).
|
||||
try:
|
||||
from watchdog.observers.fsevents import FSEventsObserver
|
||||
|
||||
return FSEventsObserver()
|
||||
except ImportError:
|
||||
# If the C-extension isn't available, fall back to polling
|
||||
# with a longer interval to reduce noise.
|
||||
return PollingObserver(timeout=3)
|
||||
return Observer()
|
||||
|
||||
|
||||
@@ -44,8 +54,15 @@ class _ChangeCollector(FileSystemEventHandler):
|
||||
self._changes: set[str] = set()
|
||||
self._lock = threading.Lock()
|
||||
|
||||
# Paths that should never trigger a user-visible refresh
|
||||
_IGNORED_SEGMENTS = {".git", "__pycache__", ".DS_Store", "node_modules"}
|
||||
|
||||
def _record(self, event: FileSystemEvent) -> None:
|
||||
path = event.src_path
|
||||
# Skip noisy internal paths that shouldn't trigger file browser refreshes
|
||||
parts = Path(path).parts
|
||||
if any(seg in self._IGNORED_SEGMENTS for seg in parts):
|
||||
return
|
||||
with self._lock:
|
||||
self._changes.add(str(Path(path).parent))
|
||||
self._changes.add(path)
|
||||
@@ -57,6 +74,11 @@ class _ChangeCollector(FileSystemEventHandler):
|
||||
self._record(event)
|
||||
|
||||
def on_modified(self, event: FileSystemEvent) -> None:
|
||||
# Ignore directory-modified events – these fire on any child
|
||||
# change (which we already capture via on_created/on_deleted)
|
||||
# and on metadata-only updates like atime from stat calls.
|
||||
if event.is_directory:
|
||||
return
|
||||
self._record(event)
|
||||
|
||||
def on_moved(self, event: FileSystemEvent) -> None:
|
||||
|
||||
Reference in new issue
Block a user