Files
openchamber/packages/ui/src/stores/useDirectoryStore.ts
T
Bohdan Triapitsyn 83ffb1af34 refactor(desktop): make Tauri thin shell running web sidecar (#273)
## What / Why
This PR finishes the desktop refactor: the Tauri app is now a thin shell that launches the web server as a sidecar and loads the UI from `http://127.0.0.1:<port>`. All real backend logic lives in `packages/web/server/index.js`; desktop Rust keeps only native integrations (menu/dialog/notifications/updater/deep-link + window chrome).
This unblocks:
- consistent behavior across web/desktop/vscode (single backend)
- simpler desktop maintenance (no duplicated Rust backend)
- host switching between Local + remote instances in desktop
- reliable cold-start behavior on slow machines (VSCode + desktop)
## Key changes
- Desktop sidecar runtime
  - build pipeline to bundle web dist + `openchamber-server` sidecar (`packages/desktop/scripts/build-sidecar.mjs`)
  - robust local port selection (prefer saved/default, fallback to random; persisted in `~/.config/openchamber/settings.json`)
  - improved PATH handling so the sidecar can locate `opencode` CLI (incl `~/.opencode/bin`, overrides, common bins)
  - disable native right-click context menu in production builds (dev keeps it)
- Desktop instance switcher (Tauri-only)
  - header button + modal to add/edit/delete remote hosts, set default, probe status/ping, switch back to Local escape hatch
  - auth gate includes host switcher so you can recover when a remote host is broken/auth-required
  - host list stored desktop-locally (not tied to the currently selected remote server)
- Notifications
  - decision logic moved server-side; desktop notifications emitted via sidecar stdout and shown natively by Tauri
  - prevent double-notifications on desktop Local origin (UI ignores SSE notification when native path is active)
  - restore macOS notification sound
- Updates
  - Tauri updater used only when viewing Local instance in desktop shell (avoid “remote web update” triggering desktop restart)
- Settings persistence & UX polish
  - persist model favorites/recents via `/api/config/settings` (works for web + desktop; not origin-dependent)
  - persist per-project sidebar collapse state in `projects[].sidebarCollapsed` via `/api/config/settings` (with debounce on toggles)
  - macOS header sizing/traffic-lights offsets fixed (marketing macOS major injected from desktop; MultiRun header aligned)
  - VSCode cold-start: keep retrying provider/agent loads after connection to avoid empty UI on slow machines
  - misc lint/type fixes + bun.lock sync
- Desktop bootstrap / resiliency
  - show onboarding screen when OpenCode CLI is missing (desktop Local origin), with retry hook to restart OpenCode after install
## Testing notes
- Desktop (macOS): switch Local <-> remote, set default host, verify auth gate recovery, native notifications (with sound), updater gated to Local
- Web: favorites/recents + per-project collapsed state persist across reload/restart
- VSCode: slow startup no longer results in missing providers/agents/models
2026-02-05 01:59:49 +02:00

397 lines
13 KiB
TypeScript

import { create } from 'zustand';
import { devtools } from 'zustand/middleware';
import { opencodeClient } from '@/lib/opencode/client';
import { getDesktopHomeDirectory, isVSCodeRuntime } from '@/lib/desktop';
import { updateDesktopSettings } from '@/lib/persistence';
import { useFileSearchStore } from '@/stores/useFileSearchStore';
import { streamDebugEnabled } from '@/stores/utils/streamDebug';
import { getSafeStorage } from './utils/safeStorage';
interface DirectoryStore {
currentDirectory: string;
directoryHistory: string[];
historyIndex: number;
homeDirectory: string;
hasPersistedDirectory: boolean;
isHomeReady: boolean;
isSwitchingDirectory: boolean;
setDirectory: (path: string, options?: { showOverlay?: boolean }) => void;
goBack: () => void;
goForward: () => void;
goToParent: () => void;
goHome: () => Promise<void>;
synchronizeHomeDirectory: (path: string) => void;
}
let cachedHomeDirectory: string | null = null;
const safeStorage = getSafeStorage();
const persistedLastDirectory = safeStorage.getItem('lastDirectory');
const initialHasPersistedDirectory =
typeof persistedLastDirectory === 'string' && persistedLastDirectory.length > 0;
const invalidateFileSearchCache = (scope?: string | null) => {
try {
useFileSearchStore.getState().invalidateDirectory(scope);
} catch (error) {
console.warn('Failed to invalidate file search cache:', error);
}
};
const normalizeDirectoryPath = (value: string): string => {
const trimmed = value.trim();
if (!trimmed) {
return trimmed;
}
const normalized = trimmed.replace(/\\/g, '/');
if (normalized.length > 1) {
return normalized.replace(/\/+$/, '');
}
return normalized;
};
const resolveTildePath = (path: string, homeDir?: string | null): string => {
const trimmed = path.trim();
if (!trimmed.startsWith('~')) {
return trimmed;
}
if (trimmed === '~') {
return homeDir || trimmed;
}
if (trimmed.startsWith('~/') || trimmed.startsWith('~\\')) {
return homeDir ? `${homeDir}${trimmed.slice(1)}` : trimmed;
}
return trimmed;
};
const resolveDirectoryPath = (path: string, homeDir?: string | null): string => {
const expanded = resolveTildePath(path, homeDir);
return normalizeDirectoryPath(expanded);
};
const getHomeDirectory = () => {
if (typeof window !== 'undefined') {
const storedHome = safeStorage.getItem('homeDirectory') || cachedHomeDirectory || null;
const saved = safeStorage.getItem('lastDirectory');
if (saved && !isVSCodeRuntime()) {
return resolveDirectoryPath(saved, storedHome);
}
if (cachedHomeDirectory) return cachedHomeDirectory;
const desktopHome =
(typeof window.__OPENCHAMBER_HOME__ === 'string' && window.__OPENCHAMBER_HOME__.length > 0
? window.__OPENCHAMBER_HOME__
: null);
if (desktopHome && desktopHome.length > 0) {
cachedHomeDirectory = desktopHome;
safeStorage.setItem('homeDirectory', desktopHome);
return desktopHome;
}
if (storedHome && !isVSCodeRuntime()) {
cachedHomeDirectory = storedHome;
return storedHome;
}
}
const nodeHome = typeof process !== 'undefined' && process?.env?.HOME;
if (nodeHome) {
return nodeHome;
}
return process?.cwd?.() || '/';
};
const normalizeHomeCandidate = (value?: string | null) => {
if (typeof value !== 'string') {
return null;
}
const trimmed = value.trim();
if (!trimmed) {
return null;
}
const normalized = trimmed.replace(/\\/g, '/');
if (normalized.length > 1) {
const withoutTrailingSlash = normalized.replace(/\/+$/, '');
if (withoutTrailingSlash && withoutTrailingSlash.length > 0) {
if (withoutTrailingSlash === '/') {
return null;
}
return withoutTrailingSlash;
}
}
if (normalized === '/' || normalized.length === 0) {
return null;
}
return normalized;
};
const persistResolvedHome = (resolved: string) => {
cachedHomeDirectory = resolved;
if (typeof window !== 'undefined') {
safeStorage.setItem('homeDirectory', resolved);
}
void updateDesktopSettings({ homeDirectory: resolved });
return resolved;
};
const initializeHomeDirectory = async () => {
const acceptCandidate = (candidate?: string | null) => {
const normalized = normalizeHomeCandidate(candidate);
return normalized ? persistResolvedHome(normalized) : null;
};
try {
const fsHome = await opencodeClient.getFilesystemHome();
const resolved = acceptCandidate(fsHome);
if (resolved) {
return resolved;
}
} catch (filesystemError) {
console.warn('Failed to obtain filesystem home directory:', filesystemError);
}
try {
const info = await opencodeClient.getSystemInfo();
const resolved = acceptCandidate(info?.homeDirectory);
if (resolved) {
return resolved;
}
} catch (error) {
console.warn('Failed to get home directory from system info:', error);
}
try {
const desktopHome = await getDesktopHomeDirectory();
const resolved = acceptCandidate(desktopHome);
if (resolved) {
return resolved;
}
} catch (desktopError) {
console.warn('Failed to obtain desktop-integrated home directory:', desktopError);
}
const fallback = getHomeDirectory();
const resolvedFallback = acceptCandidate(fallback);
if (resolvedFallback) {
return resolvedFallback;
}
return fallback;
};
const getVsCodeWorkspaceFolder = (): string | null => {
if (!isVSCodeRuntime()) {
return null;
}
const workspaceFolder = (window as unknown as { __VSCODE_CONFIG__?: { workspaceFolder?: unknown } }).__VSCODE_CONFIG__?.workspaceFolder;
if (typeof workspaceFolder !== 'string' || workspaceFolder.trim().length === 0) {
return null;
}
const normalized = normalizeDirectoryPath(workspaceFolder);
return normalized.length > 0 ? normalized : null;
};
const initialHomeDirectory = getVsCodeWorkspaceFolder() || getHomeDirectory();
if (initialHomeDirectory) {
opencodeClient.setDirectory(initialHomeDirectory);
}
const initialIsHomeReady = Boolean(initialHomeDirectory && initialHomeDirectory !== '/');
export const useDirectoryStore = create<DirectoryStore>()(
devtools(
(set, get) => ({
currentDirectory: initialHomeDirectory,
directoryHistory: [initialHomeDirectory],
historyIndex: 0,
homeDirectory: initialHomeDirectory,
hasPersistedDirectory: initialHasPersistedDirectory,
isHomeReady: initialIsHomeReady,
isSwitchingDirectory: false,
setDirectory: (path: string, options?: { showOverlay?: boolean }) => {
void options;
const homeDir = cachedHomeDirectory || get().homeDirectory || safeStorage.getItem('homeDirectory');
const resolvedPath = resolveDirectoryPath(path, homeDir);
if (streamDebugEnabled()) {
console.log('[DirectoryStore] setDirectory called with path:', resolvedPath);
}
opencodeClient.setDirectory(resolvedPath);
invalidateFileSearchCache();
set((state) => {
const newHistory = [...state.directoryHistory.slice(0, state.historyIndex + 1), resolvedPath];
safeStorage.setItem('lastDirectory', resolvedPath);
void updateDesktopSettings({ lastDirectory: resolvedPath });
return {
currentDirectory: resolvedPath,
directoryHistory: newHistory,
historyIndex: newHistory.length - 1,
hasPersistedDirectory: true,
isHomeReady: true,
isSwitchingDirectory: false,
};
});
},
goBack: () => {
const state = get();
if (state.historyIndex > 0) {
const newIndex = state.historyIndex - 1;
const newDirectory = state.directoryHistory[newIndex];
opencodeClient.setDirectory(newDirectory);
invalidateFileSearchCache();
safeStorage.setItem('lastDirectory', newDirectory);
void updateDesktopSettings({ lastDirectory: newDirectory });
set({
currentDirectory: newDirectory,
historyIndex: newIndex,
hasPersistedDirectory: true,
isHomeReady: true,
isSwitchingDirectory: false,
});
}
},
goForward: () => {
const state = get();
if (state.historyIndex < state.directoryHistory.length - 1) {
const newIndex = state.historyIndex + 1;
const newDirectory = state.directoryHistory[newIndex];
opencodeClient.setDirectory(newDirectory);
invalidateFileSearchCache();
safeStorage.setItem('lastDirectory', newDirectory);
void updateDesktopSettings({ lastDirectory: newDirectory });
set({
currentDirectory: newDirectory,
historyIndex: newIndex,
hasPersistedDirectory: true,
isHomeReady: true,
isSwitchingDirectory: false,
});
}
},
goToParent: () => {
const { currentDirectory, setDirectory } = get();
const homeDir = cachedHomeDirectory || get().homeDirectory || getHomeDirectory();
if (currentDirectory === homeDir || currentDirectory === '/') {
return;
}
const cleanPath = currentDirectory.endsWith('/')
? currentDirectory.slice(0, -1)
: currentDirectory;
const lastSlash = cleanPath.lastIndexOf('/');
if (lastSlash === -1) {
const home = cachedHomeDirectory || getHomeDirectory();
setDirectory(home);
} else if (lastSlash === 0) {
setDirectory('/');
} else {
setDirectory(cleanPath.substring(0, lastSlash));
}
},
goHome: async () => {
const homeDir =
cachedHomeDirectory ||
get().homeDirectory ||
(await initializeHomeDirectory());
get().setDirectory(homeDir);
},
synchronizeHomeDirectory: (homePath: string) => {
const state = get();
const resolvedHome = homePath;
cachedHomeDirectory = resolvedHome;
const needsUpdate = state.homeDirectory !== resolvedHome;
const savedLastDirectory = safeStorage.getItem('lastDirectory');
const hasSavedLastDirectory = typeof savedLastDirectory === 'string' && savedLastDirectory.length > 0;
const shouldReplaceCurrent =
!hasSavedLastDirectory &&
(
state.currentDirectory === '/' ||
state.currentDirectory === state.homeDirectory ||
!state.currentDirectory
);
if (!needsUpdate && !shouldReplaceCurrent) {
if (!state.isHomeReady) {
set({ isHomeReady: true });
}
return;
}
const resolvedReady = typeof resolvedHome === 'string' && resolvedHome !== '' && resolvedHome !== '/';
const resolvedCurrent = state.currentDirectory
? resolveDirectoryPath(state.currentDirectory, resolvedHome)
: state.currentDirectory;
const resolvedHistory = state.directoryHistory.map((entry) => resolveDirectoryPath(entry, resolvedHome));
const historyChanged = resolvedHistory.some((entry, index) => entry !== state.directoryHistory[index]);
const currentChanged = Boolean(resolvedCurrent && resolvedCurrent !== state.currentDirectory);
const updates: Partial<DirectoryStore> = {
homeDirectory: resolvedHome,
hasPersistedDirectory: hasSavedLastDirectory,
isHomeReady: resolvedReady
};
if (shouldReplaceCurrent) {
updates.currentDirectory = resolvedHome;
updates.directoryHistory = [resolvedHome];
updates.historyIndex = 0;
updates.isSwitchingDirectory = false;
} else if (currentChanged || historyChanged) {
updates.currentDirectory = resolvedCurrent as string;
updates.directoryHistory = resolvedHistory;
updates.historyIndex = Math.min(state.historyIndex, resolvedHistory.length - 1);
updates.isSwitchingDirectory = false;
}
set(() => updates as Partial<DirectoryStore>);
if ((shouldReplaceCurrent || currentChanged) && resolvedReady) {
const nextDirectory = shouldReplaceCurrent ? resolvedHome : (resolvedCurrent as string);
opencodeClient.setDirectory(nextDirectory);
invalidateFileSearchCache();
safeStorage.setItem('lastDirectory', nextDirectory);
void updateDesktopSettings({ lastDirectory: nextDirectory });
}
void updateDesktopSettings({ homeDirectory: resolvedHome });
}
}),
{
name: 'directory-store'
}
)
);
if (typeof window !== 'undefined') {
initializeHomeDirectory().then((home) => {
useDirectoryStore.getState().synchronizeHomeDirectory(home);
});
}