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
This commit is contained in:
Bohdan Triapitsyn
2026-02-05 01:59:49 +02:00
committed by GitHub
parent b733f26aed
commit 83ffb1af34
130 changed files with 4230 additions and 23488 deletions
+1
View File
@@ -378,6 +378,7 @@ export interface ProjectEntry {
addedAt?: number;
lastOpenedAt?: number;
worktreeDefaults?: WorktreeDefaults;
sidebarCollapsed?: boolean;
}
export interface SettingsPayload {
+3 -26
View File
@@ -1,4 +1,3 @@
import { isDesktopRuntime } from '@/lib/desktop';
import { useUIStore } from '@/stores/useUIStore';
export interface AppearancePreferences {
@@ -37,20 +36,14 @@ const extractRawAppearance = (data: unknown): RawAppearancePayload | null => {
};
export const saveAppearancePreferences = (preferences: AppearancePreferences): boolean => {
if (typeof window === 'undefined' || !isDesktopRuntime()) {
return false;
}
const api = window.opencodeAppearance;
if (!api || typeof api.save !== 'function') {
if (typeof window === 'undefined') {
return false;
}
try {
void api.save(preferences);
localStorage.setItem('appearance-preferences', JSON.stringify(preferences));
return true;
} catch (error) {
console.warn('Failed to save appearance preferences to desktop storage:', error);
} catch {
return false;
}
};
@@ -68,22 +61,6 @@ export const loadAppearancePreferences = async (): Promise<AppearancePreferences
return null;
}
if (isDesktopRuntime()) {
const api = window.opencodeAppearance;
if (!api || typeof api.load !== 'function') {
return null;
}
try {
const raw = await api.load();
const payload = typeof raw === 'object' && raw !== null ? (raw as RawAppearancePayload) : null;
return sanitizePreferences(payload);
} catch (error) {
console.warn('Failed to load appearance preferences from desktop storage:', error);
return null;
}
}
const stored = localStorage.getItem('appearance-preferences');
if (!stored) {
return null;
+3 -9
View File
@@ -216,13 +216,7 @@ export const debugUtils = {
const runtimeApis = typeof window !== 'undefined'
? (window as any).__OPENCHAMBER_RUNTIME_APIS__
: null;
const desktopServer = typeof window !== 'undefined'
? (window as any).__OPENCHAMBER_DESKTOP_SERVER__
: null;
const isDesktopRuntime = Boolean(
runtimeApis?.runtime?.isDesktop ||
(typeof window !== 'undefined' && (window as any).opencodeDesktop)
);
const isTauriShell = typeof window !== 'undefined' && Boolean((window as any).__TAURI__);
const safeJson = async (resp: Response) => {
try {
@@ -302,10 +296,10 @@ export const debugUtils = {
const report = {
runtime: {
platform: runtimeApis?.runtime?.platform ?? null,
isDesktop: isDesktopRuntime,
isDesktop: isTauriShell,
isVSCode: Boolean(runtimeApis?.runtime?.isVSCode),
hasRuntimeApis: Boolean(runtimeApis),
desktopServerOrigin: desktopServer?.origin ?? null,
desktopServerOrigin: null,
},
location: typeof window !== 'undefined'
? {
+160 -178
View File
@@ -21,14 +21,6 @@ export type UpdateProgress = {
total?: number;
};
export type DesktopServerInfo = {
webPort: number | null;
openCodePort: number | null;
host: string | null;
ready: boolean;
cliAvailable: boolean;
};
export type SkillCatalogConfig = {
id: string;
label: string;
@@ -74,6 +66,9 @@ export type DesktopSettings = {
padding?: number;
cornerRadius?: number;
inputBarOffset?: number;
favoriteModels?: Array<{ providerID: string; modelID: string }>;
recentModels?: Array<{ providerID: string; modelID: string }>;
diffLayoutPreference?: 'dynamic' | 'inline' | 'side-by-side';
diffViewMode?: 'single' | 'stacked';
directoryShowHidden?: boolean;
@@ -88,34 +83,58 @@ export type DesktopSettings = {
skillCatalogs?: SkillCatalogConfig[];
};
export type DesktopSettingsApi = {
getSettings: () => Promise<DesktopSettings>;
updateSettings: (changes: Partial<DesktopSettings>) => Promise<DesktopSettings>;
type TauriGlobal = {
core?: {
invoke?: (cmd: string, args?: Record<string, unknown>) => Promise<unknown>;
};
dialog?: {
open?: (options: Record<string, unknown>) => Promise<unknown>;
};
event?: {
listen?: (
event: string,
handler: (evt: { payload?: unknown }) => void,
) => Promise<() => void>;
};
};
export type DesktopApi = {
homeDirectory?: string;
macosMajorVersion?: number | null;
getServerInfo: () => Promise<DesktopServerInfo>;
restartOpenCode: () => Promise<{ success: boolean }>;
shutdown: () => Promise<{ success: boolean }>;
markRendererReady?: () => Promise<void> | void;
windowControl?: (action: 'close' | 'minimize' | 'maximize') => Promise<{ success: boolean }>;
getHomeDirectory?: () => Promise<{ success: boolean; path: string | null }>;
getSettings?: () => Promise<DesktopSettings>;
updateSettings?: (changes: Partial<DesktopSettings>) => Promise<DesktopSettings>;
requestDirectoryAccess?: (path: string) => Promise<{ success: boolean; path?: string; projectId?: string; error?: string }>;
startAccessingDirectory?: (path: string) => Promise<{ success: boolean; error?: string }>;
stopAccessingDirectory?: (path: string) => Promise<{ success: boolean; error?: string }>;
notifyAssistantCompletion?: (payload?: AssistantNotificationPayload) => Promise<{ success: boolean }>;
checkForUpdates?: () => Promise<UpdateInfo>;
downloadUpdate?: (onProgress?: (progress: UpdateProgress) => void) => Promise<void>;
restartToUpdate?: () => Promise<void>;
openExternal?: (url: string) => Promise<{ success: boolean; error?: string }>;
export const isTauriShell = (): boolean => {
if (typeof window === 'undefined') return false;
const tauri = (window as unknown as { __TAURI__?: TauriGlobal }).__TAURI__;
return typeof tauri?.core?.invoke === 'function';
};
export const isDesktopRuntime = (): boolean =>
typeof window !== "undefined" && typeof window.opencodeDesktop !== "undefined";
const normalizeOrigin = (raw: string): string | null => {
const trimmed = raw.trim();
if (!trimmed) return null;
try {
return new URL(trimmed).origin;
} catch {
try {
return new URL(trimmed.endsWith('/') ? trimmed : `${trimmed}/`).origin;
} catch {
return null;
}
}
};
export const isDesktopLocalOriginActive = (): boolean => {
if (typeof window === 'undefined') return false;
const local = typeof window.__OPENCHAMBER_LOCAL_ORIGIN__ === 'string' ? window.__OPENCHAMBER_LOCAL_ORIGIN__ : '';
const localOrigin = normalizeOrigin(local);
const currentOrigin = normalizeOrigin(window.location.origin) || window.location.origin;
return Boolean(localOrigin && currentOrigin && localOrigin === currentOrigin);
};
// Desktop shell detection that doesn't require Tauri IPC availability.
// (Remote pages can temporarily lose window.__TAURI__ if URL doesn't match remote allowlist.)
export const isDesktopShell = (): boolean => {
if (typeof window === 'undefined') return false;
if (typeof window.__OPENCHAMBER_LOCAL_ORIGIN__ === 'string' && window.__OPENCHAMBER_LOCAL_ORIGIN__.length > 0) {
return true;
}
return isTauriShell();
};
export const isVSCodeRuntime = (): boolean => {
if (typeof window === "undefined") return false;
@@ -125,37 +144,19 @@ export const isVSCodeRuntime = (): boolean => {
export const isWebRuntime = (): boolean => {
if (typeof window === "undefined") return false;
// Web runtime: not desktop, not VSCode
return !isDesktopRuntime() && !isVSCodeRuntime();
};
export const getDesktopApi = (): DesktopApi | null => {
if (!isDesktopRuntime()) {
return null;
const apis = (window as { __OPENCHAMBER_RUNTIME_APIS__?: { runtime?: { platform?: string } } }).__OPENCHAMBER_RUNTIME_APIS__;
const platform = apis?.runtime?.platform;
if (platform === 'web') {
return true;
}
return window.opencodeDesktop ?? null;
};
export const getDesktopSettingsApi = (): DesktopSettingsApi | null => {
if (typeof window === 'undefined') {
return null;
if (platform === 'desktop' || platform === 'vscode') {
return false;
}
if (window.opencodeDesktopSettings) {
return window.opencodeDesktopSettings;
}
const base = window.opencodeDesktop;
if (base?.getSettings && base?.updateSettings) {
return {
getSettings: base.getSettings.bind(base),
updateSettings: base.updateSettings.bind(base)
};
}
return null;
// Default: anything that's not VSCode behaves like web (HTTP UI).
return !isVSCodeRuntime();
};
export const getDesktopHomeDirectory = async (): Promise<string | null> => {
const api = getDesktopApi();
if (typeof window !== 'undefined') {
const embedded = window.__OPENCHAMBER_HOME__;
if (embedded && embedded.length > 0) {
@@ -163,148 +164,82 @@ export const getDesktopHomeDirectory = async (): Promise<string | null> => {
}
}
if (!api) {
return null;
}
if (typeof api.homeDirectory === 'string' && api.homeDirectory.length > 0) {
return api.homeDirectory;
}
try {
if (!api.getHomeDirectory) {
return null;
}
const result = await api.getHomeDirectory();
if (result?.success && typeof result.path === 'string' && result.path.length > 0) {
return result.path;
}
} catch (error) {
console.warn('Failed to obtain desktop home directory:', error);
}
return null;
};
export const fetchDesktopServerInfo = async (): Promise<DesktopServerInfo | null> => {
const api = getDesktopApi();
if (!api) {
return null;
}
try {
return await api.getServerInfo();
} catch (error) {
console.warn("Failed to read desktop server info", error);
return null;
}
};
export const isCliAvailable = (): boolean => {
if (typeof window === 'undefined') {
return false;
}
return window.__OPENCHAMBER_DESKTOP_SERVER__?.cliAvailable ?? false;
};
export const getDesktopSettings = async (): Promise<DesktopSettings | null> => {
const api = getDesktopSettingsApi();
if (!api) {
return null;
}
try {
return await api.getSettings();
} catch (error) {
console.warn('Failed to read desktop settings', error);
return null;
}
};
export const updateDesktopSettings = async (
changes: Partial<DesktopSettings>
): Promise<DesktopSettings | null> => {
const api = getDesktopSettingsApi();
if (!api) {
return null;
}
try {
return await api.updateSettings(changes);
} catch (error) {
console.warn('[desktop] Failed to update desktop settings', error);
return null;
}
};
export const requestDirectoryAccess = async (
directoryPath: string
): Promise<{ success: boolean; path?: string; projectId?: string; error?: string }> => {
const api = getDesktopApi();
if (!api || !api.requestDirectoryAccess) {
return { success: true, path: directoryPath };
}
try {
return await api.requestDirectoryAccess(directoryPath);
} catch (error) {
console.warn('Failed to request directory access', error);
return { success: false, error: error instanceof Error ? error.message : String(error) };
// Desktop shell: use native folder picker.
if (isTauriShell()) {
try {
const tauri = (window as unknown as { __TAURI__?: TauriGlobal }).__TAURI__;
const selected = await tauri?.dialog?.open?.({
directory: true,
multiple: false,
title: 'Select Working Directory',
});
if (!selected || typeof selected !== 'string') {
return { success: false, error: 'Directory selection cancelled' };
}
return { success: true, path: selected };
} catch (error) {
console.warn('Failed to request directory access (tauri)', error);
return { success: false, error: error instanceof Error ? error.message : String(error) };
}
}
return { success: true, path: directoryPath };
};
export const startAccessingDirectory = async (
directoryPath: string
): Promise<{ success: boolean; error?: string }> => {
const api = getDesktopApi();
if (!api || !api.startAccessingDirectory) {
return { success: true };
}
try {
return await api.startAccessingDirectory(directoryPath);
} catch (error) {
console.warn('Failed to start accessing directory', error);
return { success: false, error: error instanceof Error ? error.message : String(error) };
}
void directoryPath;
return { success: true };
};
export const stopAccessingDirectory = async (
directoryPath: string
): Promise<{ success: boolean; error?: string }> => {
const api = getDesktopApi();
if (!api || !api.stopAccessingDirectory) {
return { success: true };
}
try {
return await api.stopAccessingDirectory(directoryPath);
} catch (error) {
console.warn('Failed to stop accessing directory', error);
return { success: false, error: error instanceof Error ? error.message : String(error) };
}
void directoryPath;
return { success: true };
};
export const sendAssistantCompletionNotification = async (
payload?: AssistantNotificationPayload
): Promise<boolean> => {
const api = getDesktopApi();
if (!api || !api.notifyAssistantCompletion) {
return false;
}
try {
const result = await api.notifyAssistantCompletion(payload ?? {});
return Boolean(result?.success);
} catch (error) {
console.warn('Failed to send assistant completion notification', error);
return false;
if (isTauriShell()) {
try {
const tauri = (window as unknown as { __TAURI__?: TauriGlobal }).__TAURI__;
await tauri?.core?.invoke?.('desktop_notify', {
payload: {
title: payload?.title,
body: payload?.body,
tag: 'openchamber-agent-complete',
},
});
return true;
} catch (error) {
console.warn('Failed to send assistant completion notification (tauri)', error);
return false;
}
}
return false;
};
export const checkForDesktopUpdates = async (): Promise<UpdateInfo | null> => {
const api = getDesktopApi();
if (!api || !api.checkForUpdates) {
if (!isTauriShell() || !isDesktopLocalOriginActive()) {
return null;
}
try {
return await api.checkForUpdates();
const tauri = (window as unknown as { __TAURI__?: TauriGlobal }).__TAURI__;
const info = await tauri?.core?.invoke?.('desktop_check_for_updates');
return info as UpdateInfo;
} catch (error) {
console.warn('Failed to check for updates', error);
console.warn('Failed to check for updates (tauri)', error);
return null;
}
};
@@ -312,29 +247,76 @@ export const checkForDesktopUpdates = async (): Promise<UpdateInfo | null> => {
export const downloadDesktopUpdate = async (
onProgress?: (progress: UpdateProgress) => void
): Promise<boolean> => {
const api = getDesktopApi();
if (!api || !api.downloadUpdate) {
if (!isTauriShell() || !isDesktopLocalOriginActive()) {
return false;
}
const tauri = (window as unknown as { __TAURI__?: TauriGlobal }).__TAURI__;
let unlisten: null | (() => void | Promise<void>) = null;
let downloaded = 0;
let total: number | undefined;
try {
await api.downloadUpdate(onProgress);
if (typeof onProgress === 'function' && tauri?.event?.listen) {
unlisten = await tauri.event.listen('openchamber:update-progress', (evt) => {
const payload = evt?.payload;
if (!payload || typeof payload !== 'object') return;
const data = payload as { event?: unknown; data?: unknown };
const eventName = typeof data.event === 'string' ? data.event : null;
const eventData = data.data && typeof data.data === 'object' ? (data.data as Record<string, unknown>) : null;
if (eventName === 'Started') {
downloaded = 0;
total = typeof eventData?.contentLength === 'number' ? (eventData.contentLength as number) : undefined;
onProgress({ downloaded, total });
return;
}
if (eventName === 'Progress') {
const d = eventData?.downloaded;
const t = eventData?.total;
if (typeof d === 'number') downloaded = d;
if (typeof t === 'number') total = t;
onProgress({ downloaded, total });
return;
}
if (eventName === 'Finished') {
onProgress({ downloaded, total });
}
});
}
await tauri?.core?.invoke?.('desktop_download_and_install_update');
return true;
} catch (error) {
console.warn('Failed to download update', error);
console.warn('Failed to download update (tauri)', error);
return false;
} finally {
if (unlisten) {
try {
const result = unlisten();
if (result instanceof Promise) {
await result;
}
} catch {
// ignored
}
}
}
};
export const restartToApplyUpdate = async (): Promise<boolean> => {
const api = getDesktopApi();
if (!api || !api.restartToUpdate) {
if (!isTauriShell() || !isDesktopLocalOriginActive()) {
return false;
}
try {
await api.restartToUpdate();
const tauri = (window as unknown as { __TAURI__?: TauriGlobal }).__TAURI__;
await tauri?.core?.invoke?.('desktop_restart');
return true;
} catch (error) {
console.warn('Failed to restart for update', error);
console.warn('Failed to restart for update (tauri)', error);
return false;
}
};
+110
View File
@@ -0,0 +1,110 @@
import { isTauriShell } from '@/lib/desktop';
type TauriInvoke = (cmd: string, args?: Record<string, unknown>) => Promise<unknown>;
type TauriGlobal = {
core?: {
invoke?: TauriInvoke;
};
};
export type DesktopHost = {
id: string;
label: string;
url: string;
};
export type DesktopHostsConfig = {
hosts: DesktopHost[];
defaultHostId: string | null;
};
export type HostProbeResult = {
status: 'ok' | 'auth' | 'unreachable';
latencyMs: number;
};
const isRecord = (value: unknown): value is Record<string, unknown> => {
return typeof value === 'object' && value !== null;
};
const readString = (obj: Record<string, unknown>, key: string): string | null => {
const val = obj[key];
return typeof val === 'string' ? val : null;
};
const readNumber = (obj: Record<string, unknown>, key: string): number | null => {
const val = obj[key];
return typeof val === 'number' && Number.isFinite(val) ? val : null;
};
const parseHost = (value: unknown): DesktopHost | null => {
if (!isRecord(value)) return null;
const id = readString(value, 'id');
const label = readString(value, 'label');
const url = readString(value, 'url');
if (!id || !label || !url) return null;
return { id, label, url };
};
const getInvoke = (): TauriInvoke | null => {
if (!isTauriShell()) return null;
const tauri = (window as unknown as { __TAURI__?: TauriGlobal }).__TAURI__;
return typeof tauri?.core?.invoke === 'function' ? tauri.core.invoke : null;
};
export const desktopHostsGet = async (): Promise<DesktopHostsConfig> => {
const invoke = getInvoke();
if (!invoke) {
return { hosts: [], defaultHostId: 'local' };
}
const raw = await invoke('desktop_hosts_get');
if (!isRecord(raw)) {
return { hosts: [], defaultHostId: null };
}
const hostsRaw = raw.hosts;
const hosts = Array.isArray(hostsRaw)
? hostsRaw.map(parseHost).filter((h): h is DesktopHost => Boolean(h))
: [];
const defaultHostId =
readString(raw, 'defaultHostId') ||
readString(raw, 'default_host_id') ||
readString(raw, 'defaultHostID');
return { hosts, defaultHostId };
};
export const desktopHostsSet = async (config: DesktopHostsConfig): Promise<void> => {
const invoke = getInvoke();
if (!invoke) return;
await invoke('desktop_hosts_set', {
config: {
hosts: config.hosts,
defaultHostId: config.defaultHostId,
},
});
};
export const desktopHostProbe = async (url: string): Promise<HostProbeResult> => {
const invoke = getInvoke();
if (!invoke) {
return { status: 'unreachable', latencyMs: 0 };
}
const raw = await invoke('desktop_host_probe', { url });
if (!isRecord(raw)) {
return { status: 'unreachable', latencyMs: 0 };
}
const rawStatus = raw.status;
const status: HostProbeResult['status'] =
rawStatus === 'ok' || rawStatus === 'auth' || rawStatus === 'unreachable'
? rawStatus
: 'unreachable';
const latencyMs = readNumber(raw, 'latencyMs') ?? readNumber(raw, 'latency_ms') ?? 0;
return { status, latencyMs };
};
+9 -8
View File
@@ -1,4 +1,5 @@
import React from 'react';
import { isTauriShell } from '@/lib/desktop';
export type DeviceType = 'desktop' | 'mobile' | 'tablet';
@@ -28,7 +29,7 @@ export const BREAKPOINTS = {
} as const;
const setRootDeviceAttributes = (
isDesktopRuntime: boolean,
isTauriShellRuntime: boolean,
deviceType: DeviceType,
hasTouchInput: boolean,
) => {
@@ -49,7 +50,7 @@ const setRootDeviceAttributes = (
: 'device-desktop'
);
if (isDesktopRuntime) {
if (isTauriShellRuntime) {
root.classList.add('desktop-runtime');
root.style.setProperty('--is-mobile', '0');
root.style.setProperty('--device-type', 'desktop');
@@ -81,7 +82,7 @@ export function getDeviceInfo(): DeviceInfo {
const noHover = hoverQuery?.matches ?? false;
const maxTouchPoints = typeof navigator !== 'undefined' ? navigator.maxTouchPoints ?? 0 : 0;
const isDesktopRuntime = typeof window !== 'undefined' && typeof window.opencodeDesktop !== 'undefined';
const isTauriShellRuntime = isTauriShell();
const hasTouchInput = prefersCoarsePointer || noHover || maxTouchPoints > 0;
@@ -93,7 +94,7 @@ export function getDeviceInfo(): DeviceInfo {
let isDesktop = !hasTouchInput || width > BREAKPOINTS.lg;
let deviceType: DeviceType = 'desktop';
if (isDesktopRuntime) {
if (isTauriShellRuntime) {
isMobile = false;
isTablet = false;
isDesktop = true;
@@ -107,7 +108,7 @@ export function getDeviceInfo(): DeviceInfo {
deviceType = 'desktop';
}
setRootDeviceAttributes(isDesktopRuntime, deviceType, hasTouchInput);
setRootDeviceAttributes(isTauriShellRuntime, deviceType, hasTouchInput);
let breakpoint: keyof typeof BREAKPOINTS = 'xs';
for (const [key, value] of Object.entries(BREAKPOINTS)) {
@@ -130,7 +131,7 @@ export function getDeviceInfo(): DeviceInfo {
export function isMobileDeviceViaCSS(): boolean {
if (typeof window === 'undefined') return false;
if (typeof window.opencodeDesktop !== 'undefined') {
if (typeof window !== 'undefined' && isTauriShell()) {
return false;
}
@@ -205,7 +206,7 @@ export function useDeviceInfo(): DeviceInfo {
React.useEffect(() => {
if (typeof window === 'undefined') return;
const isDesktopRuntime = typeof window.opencodeDesktop !== 'undefined';
const isTauriShellRuntime = isTauriShell();
const supportsMatchMedia = typeof window.matchMedia === 'function';
const pointerQuery = supportsMatchMedia ? window.matchMedia('(pointer: coarse)') : null;
const hoverQuery = supportsMatchMedia ? window.matchMedia('(hover: none)') : null;
@@ -213,7 +214,7 @@ export function useDeviceInfo(): DeviceInfo {
const noHover = hoverQuery?.matches ?? false;
const maxTouchPoints = typeof navigator !== 'undefined' ? navigator.maxTouchPoints ?? 0 : 0;
const hasTouchInput = prefersCoarsePointer || noHover || maxTouchPoints > 0;
setRootDeviceAttributes(isDesktopRuntime, deviceInfo.deviceType, hasTouchInput);
setRootDeviceAttributes(isTauriShellRuntime, deviceInfo.deviceType, hasTouchInput);
}, [deviceInfo.deviceType, deviceInfo.hasTouchInput]);
return deviceInfo;
+76
View File
@@ -0,0 +1,76 @@
import { useUIStore } from '@/stores/useUIStore';
import { updateDesktopSettings } from '@/lib/persistence';
import { isVSCodeRuntime } from '@/lib/desktop';
type ModelRef = { providerID: string; modelID: string };
const refsEqual = (a: ModelRef[], b: ModelRef[]): boolean => {
if (a === b) return true;
if (a.length !== b.length) return false;
for (let i = 0; i < a.length; i += 1) {
if (a[i]?.providerID !== b[i]?.providerID) return false;
if (a[i]?.modelID !== b[i]?.modelID) return false;
}
return true;
};
export const startModelPrefsAutoSave = () => {
if (typeof window === 'undefined') {
return () => {};
}
if (isVSCodeRuntime()) {
return () => {};
}
let timer: number | null = null;
let lastSent: { favoriteModels: ModelRef[]; recentModels: ModelRef[] } | null = null;
let didSkipInitial = false;
const flush = () => {
timer = null;
const state = useUIStore.getState();
const payload = { favoriteModels: state.favoriteModels, recentModels: state.recentModels };
if (
lastSent &&
refsEqual(lastSent.favoriteModels, payload.favoriteModels) &&
refsEqual(lastSent.recentModels, payload.recentModels)
) {
return;
}
lastSent = {
favoriteModels: payload.favoriteModels.slice(),
recentModels: payload.recentModels.slice(),
};
void updateDesktopSettings(payload).catch(() => {});
};
const schedule = () => {
if (!didSkipInitial) {
didSkipInitial = true;
return;
}
if (timer !== null) {
window.clearTimeout(timer);
}
timer = window.setTimeout(flush, 1200);
};
const unsubscribe = useUIStore.subscribe((state, prevState) => {
const next = { favoriteModels: state.favoriteModels, recentModels: state.recentModels };
const prev = { favoriteModels: prevState.favoriteModels, recentModels: prevState.recentModels };
if (refsEqual(next.favoriteModels, prev.favoriteModels) && refsEqual(next.recentModels, prev.recentModels)) {
return;
}
schedule();
});
return () => {
unsubscribe();
if (timer !== null) {
window.clearTimeout(timer);
}
};
};
+161
View File
@@ -0,0 +1,161 @@
import { useSessionStore } from '@/stores/useSessionStore';
import { useUIStore } from '@/stores/useUIStore';
declare const __APP_VERSION__: string | undefined;
type ProbeResult = {
ok: boolean;
status: number;
elapsedMs: number;
summary: string;
};
const getCurrentDirectory = (): string => {
const state = useSessionStore.getState();
const currentSessionId = state.currentSessionId;
if (!currentSessionId) return '';
const session = state.sessions.find((s) => s.id === currentSessionId);
return typeof session?.directory === 'string' ? session.directory : '';
};
const safeFetch = async (input: string, timeoutMs = 6000): Promise<ProbeResult> => {
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), timeoutMs);
const startedAt = Date.now();
try {
const resp = await fetch(input, {
method: 'GET',
headers: { Accept: 'application/json' },
signal: controller.signal,
});
const elapsedMs = Date.now() - startedAt;
const contentType = resp.headers.get('content-type') || '';
const lower = contentType.toLowerCase();
const isJson = lower.includes('json') && !lower.includes('text/html');
let summary = '';
if (isJson) {
const json = await resp.json().catch(() => null);
if (Array.isArray(json)) {
summary = `json[array] len=${json.length}`;
} else if (json && typeof json === 'object') {
const keys = Object.keys(json).slice(0, 8);
summary = `json[object] keys=${keys.join(',')}${Object.keys(json).length > keys.length ? ',…' : ''}`;
} else {
summary = `json[${typeof json}]`;
}
} else {
summary = contentType ? `content-type=${contentType}` : 'no content-type';
}
return { ok: resp.ok && isJson, status: resp.status, elapsedMs, summary };
} catch (error) {
const elapsedMs = Date.now() - startedAt;
const isAbort =
controller.signal.aborted ||
(error instanceof Error && (error.name === 'AbortError' || error.message.toLowerCase().includes('aborted')));
const message = isAbort
? `timeout after ${timeoutMs}ms`
: error instanceof Error
? error.message
: String(error);
return { ok: false, status: 0, elapsedMs, summary: `error=${message}` };
} finally {
clearTimeout(timeout);
}
};
const formatIso = (timestamp: number | null | undefined): string => {
if (!timestamp || !Number.isFinite(timestamp)) return '(n/a)';
try {
return new Date(timestamp).toISOString();
} catch {
return '(invalid)';
}
};
export const buildOpenCodeStatusReport = async (): Promise<string> => {
const now = new Date();
const appVersion = typeof __APP_VERSION__ !== 'undefined' ? __APP_VERSION__ : '(unknown)';
const platform = typeof navigator !== 'undefined' ? navigator.userAgent : '(no navigator)';
const directory = getCurrentDirectory();
const eventStreamStatus = useUIStore.getState().eventStreamStatus;
const origin = typeof window !== 'undefined' ? window.location.origin : '';
const apiBase = origin ? `${origin.replace(/\/+$/, '')}/api/` : '';
const buildProbeUrl = (pathname: string, includeDirectory = true): string | null => {
if (!apiBase) return null;
const url = new URL(pathname.replace(/^\/+/, ''), apiBase);
if (includeDirectory && directory) {
url.searchParams.set('directory', directory);
}
return url.toString();
};
const probeTargets: Array<{ label: string; path: string; includeDirectory?: boolean; timeoutMs?: number }> = [
{ label: 'health', path: '/global/health', includeDirectory: false },
{ label: 'config', path: '/config', includeDirectory: true },
{ label: 'providers', path: '/config/providers', includeDirectory: true },
{ label: 'agents', path: '/agent', includeDirectory: true, timeoutMs: 12000 },
{ label: 'commands', path: '/command', includeDirectory: true, timeoutMs: 10000 },
{ label: 'project', path: '/project/current', includeDirectory: true },
{ label: 'path', path: '/path', includeDirectory: true },
{ label: 'sessions', path: '/session', includeDirectory: true, timeoutMs: 12000 },
{ label: 'sessionStatus', path: '/session/status', includeDirectory: true },
];
const probes = apiBase
? await Promise.all(
probeTargets.map(async (entry) => {
const url = buildProbeUrl(entry.path, entry.includeDirectory !== false);
if (!url) return { label: entry.label, url: '(none)', result: null as ProbeResult | null };
const result = await safeFetch(url, typeof entry.timeoutMs === 'number' ? entry.timeoutMs : undefined);
return { label: entry.label, url, result };
})
)
: [];
const lines: string[] = [];
lines.push(`Time: ${now.toISOString()}`);
lines.push(`OpenChamber version: ${appVersion}`);
lines.push(`Runtime: ${origin || '(unknown)'} (api=${origin ? origin + '/api' : '(unknown)'})`);
lines.push(`Event stream: ${eventStreamStatus}`);
lines.push(`Directory: ${directory || '(none)'}`);
lines.push(`Platform: ${platform}`);
if (typeof window !== 'undefined') {
const injected = (window as unknown as { __OPENCHAMBER_MACOS_MAJOR__?: unknown }).__OPENCHAMBER_MACOS_MAJOR__;
if (typeof injected === 'number' && Number.isFinite(injected) && injected > 0) {
lines.push(`macOS major: ${injected}`);
}
}
lines.push('');
if (probes.length) {
lines.push('OpenCode API probes:');
for (const probe of probes) {
if (!probe.result) {
lines.push(`- ${probe.label}: (no url)`);
continue;
}
const { ok, status, elapsedMs, summary } = probe.result;
const suffix = ok ? '' : ` url=${probe.url}`;
lines.push(`- ${probe.label}: ${ok ? 'ok' : 'fail'} status=${status} time=${elapsedMs}ms ${summary}${suffix}`);
}
} else {
lines.push('OpenCode API probes: (skipped)');
}
lines.push('');
lines.push(`Generated: ${formatIso(Date.now())}`);
return lines.join('\n');
};
export const showOpenCodeStatus = async (): Promise<void> => {
const text = await buildOpenCodeStatusReport();
const ui = useUIStore.getState();
ui.setOpenCodeStatusText(text);
ui.setOpenCodeStatusDialogOpen(true);
};
+75 -16
View File
@@ -1,4 +1,3 @@
import { getDesktopSettings, updateDesktopSettings as updateDesktopSettingsApi, isDesktopRuntime } from '@/lib/desktop';
import type { DesktopSettings } from '@/lib/desktop';
import { useUIStore } from '@/stores/useUIStore';
import { useMessageQueueStore } from '@/stores/messageQueueStore';
@@ -49,6 +48,18 @@ const persistToLocalStorage = (settings: DesktopSettings) => {
} else {
localStorage.removeItem('pinnedDirectories');
}
if (Array.isArray(settings.projects) && settings.projects.length > 0) {
const collapsed = settings.projects
.filter((project) => (project as unknown as { sidebarCollapsed?: boolean }).sidebarCollapsed === true)
.map((project) => project.id)
.filter((id): id is string => typeof id === 'string' && id.length > 0);
if (collapsed.length > 0) {
localStorage.setItem('oc.sessions.projectCollapse', JSON.stringify(collapsed));
} else {
localStorage.removeItem('oc.sessions.projectCollapse');
}
}
if (typeof settings.gitmojiEnabled === 'boolean') {
localStorage.setItem('gitmojiEnabled', String(settings.gitmojiEnabled));
} else {
@@ -143,6 +154,9 @@ const sanitizeProjects = (value: unknown): DesktopSettings['projects'] | undefin
) {
project.lastOpenedAt = candidate.lastOpenedAt;
}
if (typeof candidate.sidebarCollapsed === 'boolean') {
(project as unknown as Record<string, unknown>).sidebarCollapsed = candidate.sidebarCollapsed;
}
// Preserve worktreeDefaults
if (candidate.worktreeDefaults && typeof candidate.worktreeDefaults === 'object') {
const wt = candidate.worktreeDefaults as Record<string, unknown>;
@@ -164,6 +178,30 @@ const sanitizeProjects = (value: unknown): DesktopSettings['projects'] | undefin
return result.length > 0 ? result : undefined;
};
const sanitizeModelRefs = (value: unknown, limit: number): Array<{ providerID: string; modelID: string }> | undefined => {
if (!Array.isArray(value)) {
return undefined;
}
const result: Array<{ providerID: string; modelID: string }> = [];
const seen = new Set<string>();
for (const entry of value) {
if (!entry || typeof entry !== 'object') continue;
const candidate = entry as Record<string, unknown>;
const providerID = typeof candidate.providerID === 'string' ? candidate.providerID.trim() : '';
const modelID = typeof candidate.modelID === 'string' ? candidate.modelID.trim() : '';
if (!providerID || !modelID) continue;
const key = `${providerID}/${modelID}`;
if (seen.has(key)) continue;
seen.add(key);
result.push({ providerID, modelID });
if (result.length >= limit) break;
}
return result;
};
const getPersistApi = (): PersistApi | undefined => {
const candidate = (useUIStore as unknown as { persist?: PersistApi }).persist;
if (candidate && typeof candidate === 'object') {
@@ -240,6 +278,28 @@ const applyDesktopUiPreferences = (settings: DesktopSettings) => {
if (typeof settings.inputBarOffset === 'number' && Number.isFinite(settings.inputBarOffset) && settings.inputBarOffset !== store.inputBarOffset) {
store.setInputBarOffset(settings.inputBarOffset);
}
if (Array.isArray(settings.favoriteModels)) {
const current = store.favoriteModels;
const next = settings.favoriteModels;
const same =
current.length === next.length &&
current.every((item, idx) => item.providerID === next[idx]?.providerID && item.modelID === next[idx]?.modelID);
if (!same) {
useUIStore.setState({ favoriteModels: next });
}
}
if (Array.isArray(settings.recentModels)) {
const current = store.recentModels;
const next = settings.recentModels;
const same =
current.length === next.length &&
current.every((item, idx) => item.providerID === next[idx]?.providerID && item.modelID === next[idx]?.modelID);
if (!same) {
useUIStore.setState({ recentModels: next });
}
}
if (typeof settings.diffLayoutPreference === 'string'
&& (settings.diffLayoutPreference === 'dynamic' || settings.diffLayoutPreference === 'inline' || settings.diffLayoutPreference === 'side-by-side')) {
if (settings.diffLayoutPreference !== store.diffLayoutPreference) {
@@ -391,6 +451,16 @@ const sanitizeWebSettings = (payload: unknown): DesktopSettings | null => {
if (typeof candidate.inputBarOffset === 'number' && Number.isFinite(candidate.inputBarOffset)) {
result.inputBarOffset = candidate.inputBarOffset;
}
const favoriteModels = sanitizeModelRefs(candidate.favoriteModels, 64);
if (favoriteModels) {
result.favoriteModels = favoriteModels;
}
const recentModels = sanitizeModelRefs(candidate.recentModels, 16);
if (recentModels) {
result.recentModels = recentModels;
}
if (
typeof candidate.diffLayoutPreference === 'string'
&& (candidate.diffLayoutPreference === 'dynamic'
@@ -487,9 +557,9 @@ export const syncDesktopSettings = async (): Promise<void> => {
};
try {
const settings = isDesktopRuntime() ? await getDesktopSettings() : await fetchWebSettings();
if (settings) {
applySettings(settings);
const webSettings = await fetchWebSettings();
if (webSettings) {
applySettings(webSettings);
}
} catch (error) {
console.warn('Failed to synchronise settings:', error);
@@ -501,18 +571,7 @@ export const updateDesktopSettings = async (changes: Partial<DesktopSettings>):
return;
}
if (isDesktopRuntime()) {
try {
const updated = await updateDesktopSettingsApi(changes);
if (updated) {
persistToLocalStorage(updated);
applyDesktopUiPreferences(updated);
}
} catch (error) {
console.warn('Failed to update desktop settings:', error);
}
return;
}
// Desktop shell uses the same HTTP settings API as web.
const runtimeSettings = getRuntimeSettingsAPI();
if (runtimeSettings) {
+3 -3
View File
@@ -1,6 +1,6 @@
import { clsx, type ClassValue } from "clsx";
import { twMerge } from "tailwind-merge";
import { isDesktopRuntime } from "@/lib/desktop";
import { isTauriShell } from "@/lib/desktop";
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs));
@@ -21,7 +21,7 @@ export const isMacOS = (): boolean => {
* Browser intercepts Cmd shortcuts, so we only use Cmd in Tauri desktop app.
*/
export const hasModifier = (e: KeyboardEvent | React.KeyboardEvent): boolean => {
return isMacOS() && isDesktopRuntime() ? e.metaKey : e.ctrlKey;
return isMacOS() && isTauriShell() ? e.metaKey : e.ctrlKey;
};
/**
@@ -30,7 +30,7 @@ export const hasModifier = (e: KeyboardEvent | React.KeyboardEvent): boolean =>
* Browser intercepts Cmd shortcuts, so we only show Cmd in Tauri desktop app.
*/
export const getModifierLabel = (): string => {
return isMacOS() && isDesktopRuntime() ? '⌘' : 'Ctrl';
return isMacOS() && isTauriShell() ? '⌘' : 'Ctrl';
};
export const truncatePathMiddle = (