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
@@ -30,7 +30,7 @@ export const ChatContainer: React.FC = () => {
isSyncing,
messageStreamStates,
trimToViewportWindow,
sessionActivityPhase,
sessionStatus,
newSessionDraft,
} = useSessionStore();
@@ -161,8 +161,8 @@ export const ChatContainer: React.FC = () => {
try {
await loadMessages(currentSessionId);
} finally {
const currentPhase = sessionActivityPhase?.get(currentSessionId) ?? 'idle';
const isActivePhase = currentPhase === 'busy' || currentPhase === 'cooldown';
const statusType = sessionStatus?.get(currentSessionId)?.type ?? 'idle';
const isActivePhase = statusType === 'busy' || statusType === 'retry';
// When pinned and active, scroll is already maintained automatically
const shouldSkipScroll = isActivePhase && isPinned;
@@ -179,7 +179,7 @@ export const ChatContainer: React.FC = () => {
};
void load();
}, [currentSessionId, isPinned, loadMessages, messages, scrollToBottom, sessionActivityPhase]);
}, [currentSessionId, isPinned, loadMessages, messages, scrollToBottom, sessionStatus]);
if (!currentSessionId && !draftOpen) {
return (
@@ -266,14 +266,7 @@ export const ChatContainer: React.FC = () => {
<ScrollShadow
className="absolute inset-0 overflow-y-auto overflow-x-hidden z-0 chat-scroll overlay-scrollbar-target"
ref={scrollRef}
style={{
contain: 'strict',
['--scroll-shadow-size' as string]: '48px',
// GPU acceleration hints for smoother scrolling
transform: 'translateZ(0)',
willChange: 'scroll-position',
backfaceVisibility: 'hidden',
}}
observeMutations={false}
data-scroll-shadow="true"
data-scrollbar="chat"
>
@@ -232,6 +232,9 @@ export const ChatInput: React.FC<ChatInputProps> = ({ onOpenSettings, scrollToBo
const canAbort = working.isWorking;
// Keep a ref to handleSubmit so callbacks don't depend on it.
const handleSubmitRef = React.useRef<(e?: React.FormEvent) => Promise<void>>(async () => {});
// Add message to queue instead of sending
const handleQueueMessage = React.useCallback(() => {
if (!hasContent || !currentSessionId) return;
@@ -448,23 +451,21 @@ export const ChatInput: React.FC<ChatInputProps> = ({ onOpenSettings, scrollToBo
}
};
handleSubmitRef.current = handleSubmit;
// Primary action for send button - respects queue mode setting
const handlePrimaryAction = React.useCallback(() => {
const canQueue = hasContent && currentSessionId && sessionPhase !== 'idle';
if (queueModeEnabled && canQueue) {
handleQueueMessage();
} else {
void handleSubmit();
void handleSubmitRef.current();
}
}, [hasContent, currentSessionId, sessionPhase, queueModeEnabled, handleQueueMessage, handleSubmit]);
// Keep a ref to handleSubmit for auto-send effect
const handleSubmitRef = React.useRef(handleSubmit);
handleSubmitRef.current = handleSubmit;
}, [hasContent, currentSessionId, sessionPhase, queueModeEnabled, handleQueueMessage]);
// Auto-send queued messages when session becomes idle (but not after abort)
React.useEffect(() => {
const wasWorking = prevSessionPhaseRef.current === 'busy' || prevSessionPhaseRef.current === 'cooldown';
const wasWorking = prevSessionPhaseRef.current === 'busy' || prevSessionPhaseRef.current === 'retry';
const isNowIdle = sessionPhase === 'idle';
// Check if session was recently aborted (within last 2 seconds)
@@ -1483,8 +1484,6 @@ export const ChatInput: React.FC<ChatInputProps> = ({ onOpenSettings, scrollToBo
isWaitingForPermission={working.isWaitingForPermission}
wasAborted={working.wasAborted}
abortActive={working.abortActive}
completionId={working.lastCompletionId}
isComplete={working.isComplete}
showAbortStatus={showAbortStatus}
/>
</div>
@@ -38,7 +38,8 @@ import { ProviderLogo } from '@/components/ui/ProviderLogo';
import { ScrollableOverlay } from '@/components/ui/ScrollableOverlay';
import { Switch } from '@/components/ui/switch';
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';
import { useIsDesktopRuntime, useIsVSCodeRuntime } from '@/hooks/useRuntimeAPIs';
import { useIsVSCodeRuntime } from '@/hooks/useRuntimeAPIs';
import { isDesktopShell } from '@/lib/desktop';
import { getAgentColor } from '@/lib/agentColors';
import { useDeviceInfo } from '@/lib/device';
import { getEditModeColors } from '@/lib/permissions/editModeColors';
@@ -346,7 +347,7 @@ export const ModelControls: React.FC<ModelControlsProps> = ({
const { favoriteModelsList, recentModelsList } = useModelLists();
const { isMobile } = useDeviceInfo();
const isDesktopRuntime = useIsDesktopRuntime();
const isDesktop = React.useMemo(() => isDesktopShell(), []);
const isVSCodeRuntime = useIsVSCodeRuntime();
// Only use mobile panels on actual mobile devices, VSCode uses desktop dropdowns
const isCompact = isMobile;
@@ -2405,7 +2406,7 @@ export const ModelControls: React.FC<ModelControlsProps> = ({
'model-controls__variant-label',
controlTextSize,
'font-medium min-w-0 truncate',
isDesktopRuntime ? 'max-w-[180px]' : undefined,
isDesktop ? 'max-w-[180px]' : undefined,
colorClass,
)}
>
@@ -2473,7 +2474,7 @@ export const ModelControls: React.FC<ModelControlsProps> = ({
'model-controls__agent-label',
controlTextSize,
'font-medium min-w-0 truncate',
isDesktopRuntime ? 'max-w-[220px]' : undefined
isDesktop ? 'max-w-[220px]' : undefined
)}
style={uiAgentName ? { color: `var(${getAgentColor(uiAgentName).var})` } : undefined}
>
+9 -17
View File
@@ -53,8 +53,6 @@ interface StatusRowProps {
isWaitingForPermission?: boolean;
wasAborted?: boolean;
abortActive?: boolean;
completionId?: string | null;
isComplete?: boolean;
// Abort state (for mobile/vscode)
showAbort?: boolean;
onAbort?: () => void;
@@ -69,8 +67,6 @@ export const StatusRow: React.FC<StatusRowProps> = ({
isWaitingForPermission,
wasAborted,
abortActive,
completionId,
isComplete,
showAbort,
onAbort,
showAbortStatus,
@@ -124,17 +120,16 @@ export const StatusRow: React.FC<StatusRowProps> = ({
const hasActiveTodos = visibleTodos.some((t) => t.status === "in_progress" || t.status === "pending");
// Original logic from ChatInput
const shouldRenderPlaceholder = !showAbortStatus && (wasAborted || !abortActive);
// Track if placeholder is showing result (done/aborted) to keep StatusRow mounted
const [placeholderShowingResult, setPlaceholderShowingResult] = React.useState(false);
// Keep StatusRow rendered while:
// - isWorking (active session)
// - isComplete (showing "Done" result)
// - wasAborted (showing "Aborted" result)
// - placeholderShowingResult (placeholder still displaying result)
// - hasActiveTodos or showAbortStatus
const hasContent = isWorking || isComplete || wasAborted || placeholderShowingResult || hasActiveTodos || showAbortStatus;
// - wasAborted / showAbortStatus
// - hasActiveTodos
const hasContent =
isWorking ||
Boolean(wasAborted) ||
Boolean(showAbortStatus) ||
hasActiveTodos;
// Close popover when clicking outside
const popoverRef = React.useRef<HTMLDivElement>(null);
@@ -212,13 +207,10 @@ export const StatusRow: React.FC<StatusRowProps> = ({
) : shouldRenderPlaceholder ? (
<WorkingPlaceholder
key={currentSessionId ?? "no-session"}
isWorking={isWorking}
statusText={statusText}
isGenericStatus={isGenericStatus}
isWaitingForPermission={isWaitingForPermission}
wasAborted={wasAborted}
completionId={completionId ?? null}
isComplete={isComplete}
onResultVisibilityChange={setPlaceholderShowingResult}
/>
) : null}
</div>
@@ -1,254 +1,132 @@
import { useState, useEffect, useRef, useCallback } from 'react';
import React from 'react';
import { Text } from '@/components/ui/text';
interface WorkingPlaceholderProps {
statusText: string | null;
isGenericStatus?: boolean;
isWaitingForPermission?: boolean;
wasAborted?: boolean;
completionId?: string | null;
isComplete?: boolean;
onResultVisibilityChange?: (isShowingResult: boolean) => void;
isWorking: boolean;
statusText: string | null;
isGenericStatus?: boolean;
isWaitingForPermission?: boolean;
}
const STATUS_DISPLAY_TIME = 1500; // Minimum time to show each status
const DONE_DISPLAY_TIME = 2000; // Time to show Done/Aborted status
type PlaceholderState = 'idle' | 'showing' | 'done' | 'aborted';
const STATUS_DISPLAY_TIME_MS = 1200;
export function WorkingPlaceholder({
isWorking,
statusText,
isGenericStatus,
isWaitingForPermission,
}: WorkingPlaceholderProps) {
const [displayedText, setDisplayedText] = React.useState<string | null>(null);
const [displayedPermission, setDisplayedPermission] = React.useState<boolean>(false);
const statusShownAtRef = React.useRef<number>(0);
const queuedStatusRef = React.useRef<{ text: string; permission: boolean } | null>(null);
const processQueueTimerRef = React.useRef<ReturnType<typeof setTimeout> | null>(null);
const clearTimers = React.useCallback(() => {
if (processQueueTimerRef.current) {
clearTimeout(processQueueTimerRef.current);
processQueueTimerRef.current = null;
}
}, []);
const showStatus = React.useCallback((text: string, permission: boolean) => {
clearTimers();
queuedStatusRef.current = null;
setDisplayedText(text);
setDisplayedPermission(permission);
statusShownAtRef.current = Date.now();
}, [clearTimers]);
const scheduleQueueProcess = React.useCallback(() => {
if (processQueueTimerRef.current) return;
const elapsed = Date.now() - statusShownAtRef.current;
const remaining = Math.max(0, STATUS_DISPLAY_TIME_MS - elapsed);
processQueueTimerRef.current = setTimeout(() => {
processQueueTimerRef.current = null;
const queued = queuedStatusRef.current;
if (queued) {
showStatus(queued.text, queued.permission);
}
}, remaining);
}, [showStatus]);
React.useEffect(() => {
if (!isWorking) {
clearTimers();
queuedStatusRef.current = null;
setDisplayedText(null);
setDisplayedPermission(false);
return;
}
const incomingText = isWaitingForPermission ? 'waiting for permission' : statusText;
const incomingPermission = Boolean(isWaitingForPermission);
const incomingGeneric = Boolean(isGenericStatus) && !incomingPermission;
if (!incomingText) {
return;
}
if (!displayedText) {
showStatus(incomingText, incomingPermission);
return;
}
if (incomingText === displayedText && incomingPermission === displayedPermission) {
return;
}
// Ignore generic churn.
if (incomingGeneric) {
return;
}
const elapsed = Date.now() - statusShownAtRef.current;
if (elapsed >= STATUS_DISPLAY_TIME_MS) {
showStatus(incomingText, incomingPermission);
return;
}
queuedStatusRef.current = { text: incomingText, permission: incomingPermission };
scheduleQueueProcess();
}, [
isWorking,
statusText,
isGenericStatus,
isWaitingForPermission,
wasAborted,
completionId,
isComplete,
onResultVisibilityChange,
}: WorkingPlaceholderProps) {
// Internal state machine
const [state, setState] = useState<PlaceholderState>('idle');
const [displayedText, setDisplayedText] = useState<string | null>(null);
const [displayedPermission, setDisplayedPermission] = useState<boolean>(false);
displayedText,
displayedPermission,
clearTimers,
showStatus,
scheduleQueueProcess,
]);
// Refs for timing
const statusShownAtRef = useRef<number>(0);
const queuedStatusRef = useRef<{ text: string; permission: boolean } | null>(null);
const processQueueTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const doneTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const lastCompletionIdRef = useRef<string | null>(null);
// Track if we've ever shown activity in this turn
const hasShownActivityRef = useRef<boolean>(false);
// Track the previous isComplete value to detect edges
const prevIsCompleteRef = useRef<boolean>(false);
const prevWasAbortedRef = useRef<boolean>(false);
React.useEffect(() => () => clearTimers(), [clearTimers]);
// Clear all timers
const clearTimers = useCallback(() => {
if (processQueueTimerRef.current) {
clearTimeout(processQueueTimerRef.current);
processQueueTimerRef.current = null;
}
if (doneTimerRef.current) {
clearTimeout(doneTimerRef.current);
doneTimerRef.current = null;
}
}, []);
if (!isWorking || !displayedText) {
return null;
}
// Show a status immediately
const showStatus = useCallback((text: string, permission: boolean) => {
clearTimers();
queuedStatusRef.current = null;
setDisplayedText(text);
setDisplayedPermission(permission);
setState('showing');
statusShownAtRef.current = Date.now();
hasShownActivityRef.current = true;
}, [clearTimers]);
const label = displayedText.charAt(0).toUpperCase() + displayedText.slice(1);
const displayText = `${label}...`;
// Schedule processing of queued status
const scheduleQueueProcess = useCallback(() => {
if (processQueueTimerRef.current) return; // Already scheduled
const elapsed = Date.now() - statusShownAtRef.current;
const remaining = Math.max(0, STATUS_DISPLAY_TIME - elapsed);
processQueueTimerRef.current = setTimeout(() => {
processQueueTimerRef.current = null;
const queued = queuedStatusRef.current;
if (queued) {
showStatus(queued.text, queued.permission);
}
// If nothing queued, keep showing current status
}, remaining);
}, [showStatus]);
// Show done/aborted result
const showResult = useCallback((result: 'done' | 'aborted') => {
clearTimers();
queuedStatusRef.current = null;
// Only show result if we had activity
if (!hasShownActivityRef.current) {
setState('idle');
setDisplayedText(null);
onResultVisibilityChange?.(false);
return;
}
// Skip duplicate completion for same completionId
if (result === 'done' && completionId && lastCompletionIdRef.current === completionId) {
setState('idle');
setDisplayedText(null);
hasShownActivityRef.current = false;
onResultVisibilityChange?.(false);
return;
}
if (result === 'done' && completionId) {
lastCompletionIdRef.current = completionId;
}
setState(result);
setDisplayedText(null);
onResultVisibilityChange?.(true);
// Auto-hide after DONE_DISPLAY_TIME
doneTimerRef.current = setTimeout(() => {
doneTimerRef.current = null;
setState('idle');
hasShownActivityRef.current = false;
onResultVisibilityChange?.(false);
}, DONE_DISPLAY_TIME);
}, [clearTimers, completionId, onResultVisibilityChange]);
// Main effect: handle prop changes
useEffect(() => {
// Detect abort edge (false -> true)
if (wasAborted && !prevWasAbortedRef.current) {
prevWasAbortedRef.current = true;
showResult('aborted');
return;
}
prevWasAbortedRef.current = !!wasAborted;
// Detect completion edge (false -> true)
if (isComplete && !prevIsCompleteRef.current) {
prevIsCompleteRef.current = true;
showResult('done');
return;
}
// Reset edge detection when isComplete goes back to false
if (!isComplete && prevIsCompleteRef.current) {
prevIsCompleteRef.current = false;
}
// If we're showing done/aborted, don't process new status
if (state === 'done' || state === 'aborted') {
return;
}
// Handle new status text
if (statusText) {
const now = Date.now();
const elapsed = now - statusShownAtRef.current;
if (state === 'idle' || !displayedText) {
// Not showing anything - show immediately (generic OK at turn start)
showStatus(statusText, !!isWaitingForPermission);
} else if (statusText !== displayedText || !!isWaitingForPermission !== displayedPermission) {
// Already showing something - ignore generic statuses
if (isGenericStatus) {
return;
}
// Different specific status
if (elapsed >= STATUS_DISPLAY_TIME) {
// Minimum time passed - show immediately
showStatus(statusText, !!isWaitingForPermission);
} else {
// Queue the latest (overwrites previous queued)
queuedStatusRef.current = { text: statusText, permission: !!isWaitingForPermission };
scheduleQueueProcess();
}
}
// Same status - keep showing
}
// IMPORTANT: When statusText becomes null, we do NOT clear the display
// Only done/abort signals clear the display
}, [statusText, isWaitingForPermission, wasAborted, isComplete, state, displayedText, displayedPermission, showStatus, showResult, scheduleQueueProcess, isGenericStatus]);
// Cleanup on unmount
useEffect(() => {
return () => clearTimers();
}, [clearTimers]);
// Handle tab visibility changes
useEffect(() => {
const handleVisibilityChange = () => {
if (typeof document === 'undefined') return;
if (document.visibilityState !== 'visible') return;
// If showing done/aborted when user returns, hide it
if (state === 'done' || state === 'aborted') {
clearTimers();
setState('idle');
setDisplayedText(null);
hasShownActivityRef.current = false;
}
};
document.addEventListener('visibilitychange', handleVisibilityChange);
return () => document.removeEventListener('visibilitychange', handleVisibilityChange);
}, [state, clearTimers]);
// Render nothing if idle with no text
if (state === 'idle' && !displayedText) {
return null;
}
// Determine what to show
let label: string;
let showEllipsis = true;
if (state === 'done') {
label = 'Done';
showEllipsis = false;
} else if (state === 'aborted') {
label = 'Aborted';
showEllipsis = false;
} else if (displayedText) {
label = displayedText.charAt(0).toUpperCase() + displayedText.slice(1);
} else {
label = 'Working';
}
const displayText = showEllipsis ? `${label}...` : label;
const isVisible = state !== 'idle';
return (
<div
className={`flex h-full items-center text-muted-foreground pl-[2ch] transition-opacity duration-200 ${isVisible ? 'opacity-100' : 'opacity-0'}`}
role="status"
aria-live={displayedPermission ? 'assertive' : 'polite'}
aria-label={label}
data-waiting={displayedPermission ? 'true' : undefined}
>
<span className="flex items-center gap-1.5">
{state === 'done' ? (
<Text variant="hover-enter" className="typography-ui-header">
Done
</Text>
) : state === 'aborted' ? (
<Text variant="hover-enter" className="typography-ui-header text-status-error">
Aborted
</Text>
) : (
<Text variant="shine" className="typography-ui-header">
{displayText}
</Text>
)}
</span>
</div>
);
return (
<div
className={
'flex h-full items-center text-muted-foreground pl-[2ch]'
}
role="status"
aria-live={displayedPermission ? 'assertive' : 'polite'}
aria-label={label}
data-waiting={displayedPermission ? 'true' : undefined}
>
<span className="flex items-center gap-1.5">
<Text variant="shine" className="typography-ui-header">
{displayText}
</Text>
</span>
</div>
);
}