Decouple bundled UI from runtime API and add remote instance tooling (#1228)
Add a packaged-client runtime boundary so the shared UI can talk to local, desktop, remote, and VS Code runtimes through the right transport instead of assuming one same-origin web server. Centralize OpenChamber-owned API access behind RuntimeAPIs, runtimeFetch, and runtime URL helpers, while keeping official OpenCode traffic on the SDK path. Support runtime switching, remote host selection, desktop client credentials, and headless connection links for pairing packaged clients with remote OpenChamber servers. Harden the new auth model by moving long-lived client tokens out of browser URLs, introducing short-lived scoped URL tokens for browser-owned transports, restricting URL-token access to explicit readable/realtime routes, and making client-token management session-scoped or self-scoped as appropriate. Update browser-owned assets and preview proxy flows to work with the split runtime model, including authenticated project icons, preview token propagation, CSP-safe preview bridge injection, and preview proxy auth that survives short-lived URL-token expiry. Tighten Electron security boundaries for packaged clients by gating privileged preload state to trusted origins and requiring explicit confirmation before connect deep-links import or switch remote runtimes. Also refresh agent guidance and project skills so future runtime/API, auth, preview, UI, CLI, settings, locale, and drag-to-reorder work follows the new architecture.
This commit is contained in:
committed by
GitHub
parent
a4314c189b
commit
2031e3b4a8
@@ -19,6 +19,10 @@ import { useSessionUIStore } from '@/sync/session-ui-store';
|
||||
import { useInputStore } from '@/sync/input-store';
|
||||
import { ContextPanelContent } from './ContextSidebarTab';
|
||||
import { toast } from '@/components/ui';
|
||||
import { runtimeFetch } from '@/lib/runtime-fetch';
|
||||
import { refreshRuntimeUrlAuthToken } from '@/lib/runtime-auth';
|
||||
import { getRuntimeUrlResolver } from '@/lib/runtime-url';
|
||||
import { getRuntimeApiBaseUrl } from '@/lib/runtime-switch';
|
||||
import { Icon } from "@/components/icon/Icon";
|
||||
import { OpenChamberLogo } from "@/components/ui/OpenChamberLogo";
|
||||
import { invokeDesktopCommand } from '@/lib/desktopNative';
|
||||
@@ -436,15 +440,42 @@ type PreviewPaneProps = {
|
||||
type PreviewProxyState =
|
||||
| { status: 'idle' }
|
||||
| { status: 'loading' }
|
||||
| { status: 'ready'; proxyBasePath: string; expiresAt: number }
|
||||
| { status: 'ready'; proxyBasePath: string; previewToken?: string; expiresAt: number }
|
||||
| { status: 'error'; message: string };
|
||||
|
||||
const getPreviewProxyOrigin = (proxySrc: string): string => {
|
||||
if (typeof window === 'undefined') return '';
|
||||
try {
|
||||
return new URL(proxySrc || window.location.href, window.location.href).origin;
|
||||
} catch {
|
||||
return window.location.origin;
|
||||
}
|
||||
};
|
||||
|
||||
const postPreviewBridgeMessage = (frameWindow: Window, proxySrc: string, payload: Record<string, unknown>): void => {
|
||||
const targetOrigin = getPreviewProxyOrigin(proxySrc);
|
||||
frameWindow.postMessage(payload, targetOrigin);
|
||||
};
|
||||
|
||||
const stripPreviewTokenFromUrl = (value: string): string => {
|
||||
if (!value) return value;
|
||||
try {
|
||||
const parsed = new URL(value);
|
||||
parsed.searchParams.delete('oc_preview_token');
|
||||
parsed.searchParams.delete('oc_client_token');
|
||||
parsed.searchParams.delete('oc_url_token');
|
||||
return parsed.toString();
|
||||
} catch {
|
||||
return value;
|
||||
}
|
||||
};
|
||||
const PreviewPane: React.FC<PreviewPaneProps> = ({ rawUrl, onNavigate }) => {
|
||||
const { t } = useI18n();
|
||||
const { currentTheme } = useThemeSystem();
|
||||
const [reloadNonce, bumpReload] = React.useReducer((x: number) => x + 1, 0);
|
||||
const [proxyRegistrationNonce, bumpProxyRegistration] = React.useReducer((x: number) => x + 1, 0);
|
||||
const [proxyState, setProxyState] = React.useState<PreviewProxyState>({ status: 'idle' });
|
||||
const [urlAuthReadyKey, setUrlAuthReadyKey] = React.useState('');
|
||||
const iframeRef = React.useRef<HTMLIFrameElement | null>(null);
|
||||
const nextConsoleEventIdRef = React.useRef(1);
|
||||
const [bridgeReady, setBridgeReady] = React.useState(false);
|
||||
@@ -480,6 +511,7 @@ const PreviewPane: React.FC<PreviewPaneProps> = ({ rawUrl, onNavigate }) => {
|
||||
: null;
|
||||
|
||||
const targetKey = normalizedUrl ? normalizedUrl.toString() : '';
|
||||
const proxyCacheKey = targetKey ? `${getRuntimeApiBaseUrl() || 'same-origin'}|${targetKey}` : '';
|
||||
const previewColorScheme = currentTheme.metadata.variant;
|
||||
|
||||
React.useEffect(() => {
|
||||
@@ -488,18 +520,21 @@ const PreviewPane: React.FC<PreviewPaneProps> = ({ rawUrl, onNavigate }) => {
|
||||
return;
|
||||
}
|
||||
|
||||
const cached = getCachedProxyTarget(targetKey);
|
||||
if (cached) {
|
||||
setProxyState({ status: 'ready', proxyBasePath: cached.proxyBasePath, expiresAt: cached.expiresAt });
|
||||
const cached = getCachedProxyTarget(proxyCacheKey);
|
||||
if (cached?.previewToken) {
|
||||
setProxyState({ status: 'ready', proxyBasePath: cached.proxyBasePath, previewToken: cached.previewToken, expiresAt: cached.expiresAt });
|
||||
return;
|
||||
}
|
||||
if (cached) {
|
||||
previewProxyTargetCache.delete(proxyCacheKey);
|
||||
}
|
||||
|
||||
let cancelled = false;
|
||||
setProxyState({ status: 'loading' });
|
||||
|
||||
void (async () => {
|
||||
try {
|
||||
const response = await fetch('/api/preview/targets', {
|
||||
const response = await runtimeFetch('/api/preview/targets', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
credentials: 'include',
|
||||
@@ -507,7 +542,7 @@ const PreviewPane: React.FC<PreviewPaneProps> = ({ rawUrl, onNavigate }) => {
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
previewProxyTargetCache.delete(targetKey);
|
||||
previewProxyTargetCache.delete(proxyCacheKey);
|
||||
const errorBody = await response.json().catch(() => ({}));
|
||||
const message = typeof errorBody?.error === 'string'
|
||||
? errorBody.error
|
||||
@@ -518,23 +553,24 @@ const PreviewPane: React.FC<PreviewPaneProps> = ({ rawUrl, onNavigate }) => {
|
||||
return;
|
||||
}
|
||||
|
||||
const body = await response.json() as { proxyBasePath?: unknown; expiresAt?: unknown };
|
||||
const body = await response.json() as { proxyBasePath?: unknown; previewToken?: unknown; expiresAt?: unknown };
|
||||
const proxyBasePath = typeof body.proxyBasePath === 'string' ? body.proxyBasePath : '';
|
||||
const previewToken = typeof body.previewToken === 'string' ? body.previewToken : '';
|
||||
const expiresAt = typeof body.expiresAt === 'number' ? body.expiresAt : 0;
|
||||
if (!proxyBasePath) {
|
||||
previewProxyTargetCache.delete(targetKey);
|
||||
if (!proxyBasePath || !previewToken) {
|
||||
previewProxyTargetCache.delete(proxyCacheKey);
|
||||
if (!cancelled) {
|
||||
setProxyState({ status: 'error', message: t('contextPanel.preview.proxyError') });
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
previewProxyTargetCache.set(targetKey, { proxyBasePath, expiresAt });
|
||||
previewProxyTargetCache.set(proxyCacheKey, { proxyBasePath, previewToken, expiresAt });
|
||||
if (!cancelled) {
|
||||
setProxyState({ status: 'ready', proxyBasePath, expiresAt });
|
||||
setProxyState({ status: 'ready', proxyBasePath, previewToken, expiresAt });
|
||||
}
|
||||
} catch (error) {
|
||||
previewProxyTargetCache.delete(targetKey);
|
||||
previewProxyTargetCache.delete(proxyCacheKey);
|
||||
if (!cancelled) {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
setProxyState({ status: 'error', message });
|
||||
@@ -545,27 +581,51 @@ const PreviewPane: React.FC<PreviewPaneProps> = ({ rawUrl, onNavigate }) => {
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [isLoopback, proxyRegistrationNonce, t, targetKey]);
|
||||
}, [isLoopback, proxyCacheKey, proxyRegistrationNonce, t, targetKey]);
|
||||
|
||||
const directSrc = normalizedUrl
|
||||
&& (normalizedUrl.protocol === 'http:' || normalizedUrl.protocol === 'https:')
|
||||
? normalizedUrl.toString()
|
||||
: '';
|
||||
|
||||
const proxySrc = isLoopback && proxyState.status === 'ready' && normalizedUrl
|
||||
const proxyUrlAuthKey = isLoopback && proxyState.status === 'ready'
|
||||
? `${proxyState.proxyBasePath}|${proxyState.previewToken || ''}|${reloadNonce}`
|
||||
: '';
|
||||
|
||||
React.useEffect(() => {
|
||||
if (!proxyUrlAuthKey) {
|
||||
setUrlAuthReadyKey('');
|
||||
return;
|
||||
}
|
||||
|
||||
let cancelled = false;
|
||||
setUrlAuthReadyKey('');
|
||||
void refreshRuntimeUrlAuthToken(getRuntimeApiBaseUrl())
|
||||
.then((token) => {
|
||||
if (!cancelled && token) setUrlAuthReadyKey(proxyUrlAuthKey);
|
||||
})
|
||||
.catch(() => {});
|
||||
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [proxyUrlAuthKey]);
|
||||
|
||||
const proxySrc = isLoopback && proxyState.status === 'ready' && normalizedUrl && urlAuthReadyKey === proxyUrlAuthKey
|
||||
? (() => {
|
||||
const path = normalizedUrl.pathname || '/';
|
||||
const searchParams = new URLSearchParams(normalizedUrl.search);
|
||||
searchParams.set('ocPreview', String(reloadNonce));
|
||||
searchParams.set('oc_preview_token', proxyState.previewToken || '');
|
||||
const search = searchParams.toString();
|
||||
const hash = normalizedUrl.hash || '';
|
||||
return `${proxyState.proxyBasePath}${path}${search ? `?${search}` : ''}${hash}`;
|
||||
return getRuntimeUrlResolver().authenticatedAsset(`${proxyState.proxyBasePath}${path}${search ? `?${search}` : ''}${hash}`);
|
||||
})()
|
||||
: '';
|
||||
|
||||
const effectiveSrc = isLoopback ? proxySrc : directSrc;
|
||||
const headerSrc = effectiveSrc || directSrc;
|
||||
const showLoading = isLoopback && (proxyState.status === 'loading' || proxyState.status === 'idle');
|
||||
const headerSrc = isLoopback ? stripPreviewTokenFromUrl(proxySrc) : directSrc;
|
||||
const showLoading = isLoopback && (proxyState.status === 'loading' || proxyState.status === 'idle' || urlAuthReadyKey !== proxyUrlAuthKey);
|
||||
const showError = isLoopback && proxyState.status === 'error';
|
||||
|
||||
const attachPreviewAnnotation = React.useCallback((target: PreviewElementMetadata) => {
|
||||
@@ -630,26 +690,26 @@ const PreviewPane: React.FC<PreviewPaneProps> = ({ rawUrl, onNavigate }) => {
|
||||
if (!bridgeReady || !frameWindow) {
|
||||
return;
|
||||
}
|
||||
frameWindow.postMessage({
|
||||
postPreviewBridgeMessage(frameWindow, proxySrc, {
|
||||
source: 'openchamber-preview-parent',
|
||||
version: 1,
|
||||
type: 'set-inspect-mode',
|
||||
enabled: inspectMode,
|
||||
}, window.location.origin);
|
||||
}, [bridgeReady, inspectMode]);
|
||||
});
|
||||
}, [bridgeReady, inspectMode, proxySrc]);
|
||||
|
||||
React.useEffect(() => {
|
||||
const frameWindow = iframeRef.current?.contentWindow;
|
||||
if (!bridgeReady || !frameWindow) {
|
||||
return;
|
||||
}
|
||||
frameWindow.postMessage({
|
||||
postPreviewBridgeMessage(frameWindow, proxySrc, {
|
||||
source: 'openchamber-preview-parent',
|
||||
version: 1,
|
||||
type: 'set-color-scheme',
|
||||
scheme: previewColorScheme,
|
||||
}, window.location.origin);
|
||||
}, [bridgeReady, previewColorScheme]);
|
||||
});
|
||||
}, [bridgeReady, previewColorScheme, proxySrc]);
|
||||
|
||||
React.useEffect(() => {
|
||||
if (!inspectMode || typeof window === 'undefined') return;
|
||||
@@ -860,7 +920,7 @@ const PreviewPane: React.FC<PreviewPaneProps> = ({ rawUrl, onNavigate }) => {
|
||||
void (async () => {
|
||||
const probe = async (): Promise<Response | null> => {
|
||||
try {
|
||||
return await fetch(proxySrc, {
|
||||
return await runtimeFetch(proxySrc, {
|
||||
method: 'GET',
|
||||
credentials: 'include',
|
||||
cache: 'no-store',
|
||||
@@ -882,7 +942,7 @@ const PreviewPane: React.FC<PreviewPaneProps> = ({ rawUrl, onNavigate }) => {
|
||||
}
|
||||
|
||||
if (response.status === 403 || response.status === 404) {
|
||||
previewProxyTargetCache.delete(targetKey);
|
||||
previewProxyTargetCache.delete(proxyCacheKey);
|
||||
setProxyState({ status: 'loading' });
|
||||
bumpProxyRegistration();
|
||||
return;
|
||||
@@ -918,7 +978,7 @@ const PreviewPane: React.FC<PreviewPaneProps> = ({ rawUrl, onNavigate }) => {
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [proxySrc, reloadNonce, targetKey]);
|
||||
}, [proxyCacheKey, proxySrc, reloadNonce]);
|
||||
|
||||
const showUpstreamStarting = isLoopback
|
||||
&& proxyState.status === 'ready'
|
||||
@@ -943,7 +1003,8 @@ const PreviewPane: React.FC<PreviewPaneProps> = ({ rawUrl, onNavigate }) => {
|
||||
|
||||
try {
|
||||
const location = frameWindow.location;
|
||||
if (location.origin !== window.location.origin) {
|
||||
const proxyOrigin = getPreviewProxyOrigin(proxySrc);
|
||||
if (location.origin !== proxyOrigin) {
|
||||
return;
|
||||
}
|
||||
if (location.pathname.startsWith(proxyState.proxyBasePath)) {
|
||||
@@ -955,7 +1016,7 @@ const PreviewPane: React.FC<PreviewPaneProps> = ({ rawUrl, onNavigate }) => {
|
||||
} catch {
|
||||
// Cross-origin frames are expected for non-loopback/direct previews.
|
||||
}
|
||||
}, [isLoopback, proxyState]);
|
||||
}, [isLoopback, proxySrc, proxyState]);
|
||||
|
||||
return (
|
||||
<div className="absolute inset-0 flex flex-col">
|
||||
@@ -1195,6 +1256,7 @@ const IframeBrowserPane: React.FC<DesktopBrowserPaneProps> = ({ initialUrl, dire
|
||||
const [isInspecting, setIsInspecting] = React.useState(false);
|
||||
const [hoverTarget, setHoverTarget] = React.useState<PreviewElementMetadata | null>(null);
|
||||
const [proxyState, setProxyState] = React.useState<PreviewProxyState>({ status: 'idle' });
|
||||
const [urlAuthReadyKey, setUrlAuthReadyKey] = React.useState('');
|
||||
const currentSessionId = useSessionUIStore((state) => state.currentSessionId);
|
||||
const newSessionDraftOpen = useSessionUIStore((state) => state.newSessionDraft?.open);
|
||||
const addInlineCommentDraft = useInlineCommentDraftStore((state) => state.addDraft);
|
||||
@@ -1264,10 +1326,13 @@ const IframeBrowserPane: React.FC<DesktopBrowserPaneProps> = ({ initialUrl, dire
|
||||
|
||||
const proxyTargetKey = getBrowserProxyTargetKey(currentUrl);
|
||||
const cached = getCachedProxyTarget(proxyTargetKey);
|
||||
if (cached) {
|
||||
setProxyState({ status: 'ready', proxyBasePath: cached.proxyBasePath, expiresAt: cached.expiresAt });
|
||||
if (cached?.previewToken) {
|
||||
setProxyState({ status: 'ready', proxyBasePath: cached.proxyBasePath, previewToken: cached.previewToken, expiresAt: cached.expiresAt });
|
||||
return;
|
||||
}
|
||||
if (cached) {
|
||||
previewProxyTargetCache.delete(proxyTargetKey);
|
||||
}
|
||||
|
||||
let cancelled = false;
|
||||
setProxyState({ status: 'loading' });
|
||||
@@ -1275,7 +1340,7 @@ const IframeBrowserPane: React.FC<DesktopBrowserPaneProps> = ({ initialUrl, dire
|
||||
|
||||
void (async () => {
|
||||
try {
|
||||
const response = await fetch('/api/preview/targets', {
|
||||
const response = await runtimeFetch('/api/preview/targets', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
credentials: 'include',
|
||||
@@ -1293,19 +1358,20 @@ const IframeBrowserPane: React.FC<DesktopBrowserPaneProps> = ({ initialUrl, dire
|
||||
return;
|
||||
}
|
||||
|
||||
const body = await response.json() as { proxyBasePath?: unknown; expiresAt?: unknown };
|
||||
const body = await response.json() as { proxyBasePath?: unknown; previewToken?: unknown; expiresAt?: unknown };
|
||||
const proxyBasePath = typeof body.proxyBasePath === 'string' ? body.proxyBasePath : '';
|
||||
const previewToken = typeof body.previewToken === 'string' ? body.previewToken : '';
|
||||
const expiresAt = typeof body.expiresAt === 'number' ? body.expiresAt : 0;
|
||||
if (!proxyBasePath) {
|
||||
if (!proxyBasePath || !previewToken) {
|
||||
if (!cancelled) {
|
||||
setProxyState({ status: 'error', message: t('contextPanel.preview.proxyError') });
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
previewProxyTargetCache.set(proxyTargetKey, { proxyBasePath, expiresAt });
|
||||
previewProxyTargetCache.set(proxyTargetKey, { proxyBasePath, previewToken, expiresAt });
|
||||
if (!cancelled) {
|
||||
setProxyState({ status: 'ready', proxyBasePath, expiresAt });
|
||||
setProxyState({ status: 'ready', proxyBasePath, previewToken, expiresAt });
|
||||
}
|
||||
} catch (error) {
|
||||
if (!cancelled) {
|
||||
@@ -1320,16 +1386,44 @@ const IframeBrowserPane: React.FC<DesktopBrowserPaneProps> = ({ initialUrl, dire
|
||||
};
|
||||
}, [currentUrl, t]);
|
||||
|
||||
const proxyUrlAuthKey = currentUrl && proxyState.status === 'ready'
|
||||
? `${proxyState.proxyBasePath}|${proxyState.previewToken || ''}|${reloadNonce}`
|
||||
: '';
|
||||
|
||||
React.useEffect(() => {
|
||||
if (!proxyUrlAuthKey) {
|
||||
setUrlAuthReadyKey('');
|
||||
return;
|
||||
}
|
||||
|
||||
let cancelled = false;
|
||||
setUrlAuthReadyKey('');
|
||||
void refreshRuntimeUrlAuthToken(getRuntimeApiBaseUrl())
|
||||
.then((token) => {
|
||||
if (!cancelled && token) setUrlAuthReadyKey(proxyUrlAuthKey);
|
||||
})
|
||||
.catch(() => {});
|
||||
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [proxyUrlAuthKey]);
|
||||
|
||||
const proxySrc = React.useMemo(() => {
|
||||
if (urlAuthReadyKey !== proxyUrlAuthKey) return '';
|
||||
if (!currentUrl || proxyState.status !== 'ready') return '';
|
||||
try {
|
||||
const parsed = new URL(currentUrl);
|
||||
const path = parsed.pathname || '/';
|
||||
return `${proxyState.proxyBasePath}${path}${parsed.search}${parsed.hash}`;
|
||||
const searchParams = new URLSearchParams(parsed.search);
|
||||
searchParams.set('ocPreview', String(reloadNonce));
|
||||
searchParams.set('oc_preview_token', proxyState.previewToken || '');
|
||||
const search = searchParams.toString();
|
||||
return getRuntimeUrlResolver().authenticatedAsset(`${proxyState.proxyBasePath}${path}${search ? `?${search}` : ''}${parsed.hash}`);
|
||||
} catch {
|
||||
return '';
|
||||
}
|
||||
}, [currentUrl, proxyState]);
|
||||
}, [currentUrl, proxyState, proxyUrlAuthKey, reloadNonce, urlAuthReadyKey]);
|
||||
|
||||
const iframeSrc = proxySrc || (proxyState.status === 'error' ? currentUrl : '');
|
||||
|
||||
|
||||
@@ -32,6 +32,7 @@ import { useFeatureFlagsStore } from '@/stores/useFeatureFlagsStore';
|
||||
import { useGitHubAuthStore } from '@/stores/useGitHubAuthStore';
|
||||
import { useRuntimeAPIs } from '@/hooks/useRuntimeAPIs';
|
||||
import { ContextUsageDisplay } from '@/components/ui/ContextUsageDisplay';
|
||||
import { UpdateDialog } from '@/components/ui/UpdateDialog';
|
||||
import { useDeviceInfo, useTabletStandalonePwaRuntime } from '@/lib/device';
|
||||
import { cn, hasModifier } from '@/lib/utils';
|
||||
import { McpDropdownContent } from '@/components/mcp/McpDropdown';
|
||||
@@ -62,11 +63,14 @@ import { forceKillTerminal } from '@/lib/terminalApi';
|
||||
import { useTerminalStore } from '@/stores/useTerminalStore';
|
||||
import { ProjectActionsButton } from '@/components/layout/ProjectActionsButton';
|
||||
import { SessionSwitcherDropdown } from '@/components/session/SessionSwitcherDropdown';
|
||||
import { canUseElectronDesktopIPC, invokeDesktop, isDesktopShell, isVSCodeRuntime, startDesktopWindowDrag } from '@/lib/desktop';
|
||||
import { desktopHostsGet, locationMatchesHost, redactSensitiveUrl } from '@/lib/desktopHosts';
|
||||
import { canUseElectronDesktopIPC, invokeDesktop, isDesktopLocalOriginActive, isDesktopShell, isVSCodeRuntime, startDesktopWindowDrag, type UpdateInfo } from '@/lib/desktop';
|
||||
import { desktopHostsGet, getDesktopHostApiUrl, locationMatchesHost, redactSensitiveUrl } from '@/lib/desktopHosts';
|
||||
import { resolveSessionDiffStats } from '@/components/session/sidebar/utils';
|
||||
import { Icon } from "@/components/icon/Icon";
|
||||
import { useI18n } from '@/lib/i18n';
|
||||
import { runtimeFetch } from '@/lib/runtime-fetch';
|
||||
import { getRuntimeBearerTokenSync } from '@/lib/runtime-auth';
|
||||
import { getRuntimeApiBaseUrl } from '@/lib/runtime-switch';
|
||||
import type { Session } from '@opencode-ai/sdk/v2/client';
|
||||
import type { IconName } from "@/components/icon/icons";
|
||||
|
||||
@@ -323,6 +327,7 @@ type DesktopServicesMenuProps = {
|
||||
isDesktopApp: boolean;
|
||||
currentInstanceLabel: string;
|
||||
compactCurrentInstanceLabel: string;
|
||||
currentInstanceIsLocal: boolean;
|
||||
isDesktopServicesOpen: boolean;
|
||||
setIsDesktopServicesOpen: React.Dispatch<React.SetStateAction<boolean>>;
|
||||
refreshCurrentInstanceLabel: () => Promise<void>;
|
||||
@@ -346,6 +351,10 @@ type DesktopServicesMenuProps = {
|
||||
showDevShutdown: boolean;
|
||||
isDevShutdownInFlight: boolean;
|
||||
onDevShutdown: () => Promise<void>;
|
||||
remoteUpdateInfo: UpdateInfo | null;
|
||||
remoteUpdateChecking: boolean;
|
||||
remoteUpdateError: string | null;
|
||||
onOpenRemoteUpdate: () => void;
|
||||
showPredValues: boolean;
|
||||
};
|
||||
|
||||
@@ -353,6 +362,7 @@ const DesktopServicesMenu = React.memo(function DesktopServicesMenu({
|
||||
isDesktopApp,
|
||||
currentInstanceLabel,
|
||||
compactCurrentInstanceLabel,
|
||||
currentInstanceIsLocal,
|
||||
isDesktopServicesOpen,
|
||||
setIsDesktopServicesOpen,
|
||||
refreshCurrentInstanceLabel,
|
||||
@@ -376,6 +386,10 @@ const DesktopServicesMenu = React.memo(function DesktopServicesMenu({
|
||||
showDevShutdown,
|
||||
isDevShutdownInFlight,
|
||||
onDevShutdown,
|
||||
remoteUpdateInfo,
|
||||
remoteUpdateChecking,
|
||||
remoteUpdateError,
|
||||
onOpenRemoteUpdate,
|
||||
showPredValues,
|
||||
}: DesktopServicesMenuProps) {
|
||||
const { t } = useI18n();
|
||||
@@ -453,12 +467,39 @@ const DesktopServicesMenu = React.memo(function DesktopServicesMenu({
|
||||
</div>
|
||||
|
||||
{isDesktopApp && desktopServicesTab === 'instance' ? (
|
||||
<DesktopHostSwitcherDialog
|
||||
embedded
|
||||
open={isDesktopServicesOpen && desktopServicesTab === 'instance'}
|
||||
onOpenChange={() => {}}
|
||||
onHostSwitched={() => setIsDesktopServicesOpen(false)}
|
||||
/>
|
||||
<div>
|
||||
{!currentInstanceIsLocal ? (
|
||||
<div className="border-b border-[var(--interactive-border)] px-4 py-2.5">
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<div className="min-w-0">
|
||||
<div className="typography-ui-label font-medium text-foreground">{t('header.services.remoteUpdate.title')}</div>
|
||||
<div className="typography-micro text-muted-foreground">
|
||||
{remoteUpdateInfo?.available
|
||||
? t('header.services.remoteUpdate.available', { version: remoteUpdateInfo.version || '' })
|
||||
: remoteUpdateChecking
|
||||
? t('header.services.remoteUpdate.checking')
|
||||
: remoteUpdateError || t('header.services.remoteUpdate.upToDate')}
|
||||
</div>
|
||||
</div>
|
||||
{remoteUpdateInfo?.available ? (
|
||||
<button
|
||||
type="button"
|
||||
className="shrink-0 rounded-md bg-[var(--primary-base)] px-3 py-1.5 typography-ui-label font-medium text-[var(--primary-foreground)] hover:opacity-90"
|
||||
onClick={onOpenRemoteUpdate}
|
||||
>
|
||||
{t('header.services.remoteUpdate.actions.open')}
|
||||
</button>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
<DesktopHostSwitcherDialog
|
||||
embedded
|
||||
open={isDesktopServicesOpen && desktopServicesTab === 'instance'}
|
||||
onOpenChange={() => {}}
|
||||
onHostSwitched={() => setIsDesktopServicesOpen(false)}
|
||||
/>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{desktopServicesTab === 'mcp' ? (
|
||||
@@ -889,6 +930,11 @@ export const Header: React.FC<HeaderProps> = ({
|
||||
const [isDesktopServicesOpen, setIsDesktopServicesOpen] = React.useState(false);
|
||||
const [isUsageRefreshSpinning, setIsUsageRefreshSpinning] = React.useState(false);
|
||||
const [currentInstanceLabel, setCurrentInstanceLabel] = React.useState('Local');
|
||||
const [currentInstanceIsLocal, setCurrentInstanceIsLocal] = React.useState(true);
|
||||
const [remoteUpdateDialogOpen, setRemoteUpdateDialogOpen] = React.useState(false);
|
||||
const [remoteUpdateInfo, setRemoteUpdateInfo] = React.useState<UpdateInfo | null>(null);
|
||||
const [remoteUpdateChecking, setRemoteUpdateChecking] = React.useState(false);
|
||||
const [remoteUpdateError, setRemoteUpdateError] = React.useState<string | null>(null);
|
||||
const compactCurrentInstanceLabel = React.useMemo(() => formatCompactHeaderLabel(currentInstanceLabel), [currentInstanceLabel]);
|
||||
const [desktopServicesTab, setDesktopServicesTab] = React.useState<'instance' | 'usage' | 'mcp'>(
|
||||
isDesktopApp ? 'instance' : 'usage'
|
||||
@@ -912,17 +958,25 @@ export const Header: React.FC<HeaderProps> = ({
|
||||
}
|
||||
|
||||
try {
|
||||
const cfg = await desktopHostsGet();
|
||||
const currentHref = window.location.href;
|
||||
const localOrigin = window.__OPENCHAMBER_LOCAL_ORIGIN__ || window.location.origin;
|
||||
|
||||
if (locationMatchesHost(currentHref, localOrigin)) {
|
||||
if (isDesktopLocalOriginActive()) {
|
||||
setCurrentInstanceLabel('Local');
|
||||
setCurrentInstanceIsLocal(true);
|
||||
return;
|
||||
}
|
||||
setCurrentInstanceIsLocal(false);
|
||||
|
||||
const cfg = await desktopHostsGet();
|
||||
const localOrigin = window.__OPENCHAMBER_LOCAL_ORIGIN__ || window.location.origin;
|
||||
const runtimeApiBaseUrl = getRuntimeApiBaseUrl();
|
||||
|
||||
if (runtimeApiBaseUrl && locationMatchesHost(runtimeApiBaseUrl, localOrigin)) {
|
||||
setCurrentInstanceLabel('Local');
|
||||
setCurrentInstanceIsLocal(true);
|
||||
return;
|
||||
}
|
||||
|
||||
const match = cfg.hosts.find((host) => {
|
||||
return locationMatchesHost(currentHref, host.url);
|
||||
return runtimeApiBaseUrl ? locationMatchesHost(runtimeApiBaseUrl, getDesktopHostApiUrl(host)) : false;
|
||||
});
|
||||
|
||||
if (match?.label?.trim()) {
|
||||
@@ -933,12 +987,98 @@ export const Header: React.FC<HeaderProps> = ({
|
||||
setCurrentInstanceLabel('Instance');
|
||||
} catch {
|
||||
setCurrentInstanceLabel('Local');
|
||||
setCurrentInstanceIsLocal(true);
|
||||
}
|
||||
}, [isDesktopApp]);
|
||||
|
||||
useEffect(() => {
|
||||
void refreshCurrentInstanceLabel();
|
||||
}, [refreshCurrentInstanceLabel]);
|
||||
|
||||
const checkRemoteInstanceUpdate = React.useCallback(async () => {
|
||||
if (currentInstanceIsLocal) {
|
||||
setRemoteUpdateInfo(null);
|
||||
setRemoteUpdateError(null);
|
||||
return;
|
||||
}
|
||||
|
||||
setRemoteUpdateChecking(true);
|
||||
setRemoteUpdateError(null);
|
||||
try {
|
||||
const params = new URLSearchParams({ appType: 'web', instanceMode: 'remote' });
|
||||
const response = await runtimeFetch(`/api/openchamber/update-check?${params.toString()}`, {
|
||||
method: 'GET',
|
||||
headers: { Accept: 'application/json' },
|
||||
});
|
||||
if (!response.ok) {
|
||||
throw new Error(`Server responded with ${response.status}`);
|
||||
}
|
||||
const data = await response.json();
|
||||
setRemoteUpdateInfo({
|
||||
available: data.available ?? false,
|
||||
version: data.version,
|
||||
currentVersion: data.currentVersion ?? 'unknown',
|
||||
body: data.body,
|
||||
nextSuggestedCheckInSec: typeof data.nextSuggestedCheckInSec === 'number' ? data.nextSuggestedCheckInSec : undefined,
|
||||
packageManager: data.packageManager,
|
||||
updateCommand: data.updateCommand,
|
||||
});
|
||||
} catch (error) {
|
||||
setRemoteUpdateInfo(null);
|
||||
setRemoteUpdateError(error instanceof Error ? error.message : t('header.services.remoteUpdate.error'));
|
||||
} finally {
|
||||
setRemoteUpdateChecking(false);
|
||||
}
|
||||
}, [currentInstanceIsLocal, t]);
|
||||
|
||||
React.useEffect(() => {
|
||||
setRemoteUpdateInfo(null);
|
||||
setRemoteUpdateError(null);
|
||||
setRemoteUpdateDialogOpen(false);
|
||||
}, [currentInstanceIsLocal, currentInstanceLabel]);
|
||||
|
||||
React.useEffect(() => {
|
||||
if (!isDesktopApp || currentInstanceIsLocal) {
|
||||
return;
|
||||
}
|
||||
|
||||
const initialDelayMs = 3000;
|
||||
const intervalMs = 60 * 60 * 1000;
|
||||
let disposed = false;
|
||||
let timer: number | null = null;
|
||||
|
||||
const schedule = (delayMs: number) => {
|
||||
timer = window.setTimeout(() => {
|
||||
if (disposed || (typeof document !== 'undefined' && document.visibilityState !== 'visible')) {
|
||||
schedule(intervalMs);
|
||||
return;
|
||||
}
|
||||
void checkRemoteInstanceUpdate().finally(() => {
|
||||
if (!disposed) {
|
||||
schedule(intervalMs);
|
||||
}
|
||||
});
|
||||
}, delayMs);
|
||||
};
|
||||
|
||||
schedule(initialDelayMs);
|
||||
|
||||
return () => {
|
||||
disposed = true;
|
||||
if (timer !== null) {
|
||||
window.clearTimeout(timer);
|
||||
}
|
||||
};
|
||||
}, [checkRemoteInstanceUpdate, currentInstanceIsLocal, currentInstanceLabel, isDesktopApp]);
|
||||
|
||||
const openRemoteInstanceUpdate = React.useCallback(() => {
|
||||
if (remoteUpdateInfo?.available) {
|
||||
setRemoteUpdateDialogOpen(true);
|
||||
return;
|
||||
}
|
||||
void checkRemoteInstanceUpdate();
|
||||
}, [checkRemoteInstanceUpdate, remoteUpdateInfo?.available]);
|
||||
|
||||
useQuotaAutoRefresh();
|
||||
const selectedModels = useQuotaStore((state) => state.selectedModels);
|
||||
const expandedFamilies = useQuotaStore((state) => state.expandedFamilies);
|
||||
@@ -1300,7 +1440,7 @@ export const Header: React.FC<HeaderProps> = ({
|
||||
const payload = runtimeApis.github
|
||||
? await runtimeApis.github.authActivate(accountId)
|
||||
: await (async () => {
|
||||
const response = await fetch('/api/github/auth/activate', {
|
||||
const response = await runtimeFetch('/api/github/auth/activate', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
@@ -1366,6 +1506,8 @@ export const Header: React.FC<HeaderProps> = ({
|
||||
void invokeDesktop('desktop_open_draft_mini_chat_window', {
|
||||
directory: normalize(openDirectory || activeProject?.path || ''),
|
||||
projectId: activeProject?.id ?? null,
|
||||
apiBaseUrl: getRuntimeApiBaseUrl(),
|
||||
clientToken: getRuntimeBearerTokenSync(),
|
||||
}).catch((error) => {
|
||||
console.warn('[header] failed to open draft mini chat window', error);
|
||||
});
|
||||
@@ -1383,6 +1525,8 @@ export const Header: React.FC<HeaderProps> = ({
|
||||
void invokeDesktop('desktop_open_session_mini_chat_window', {
|
||||
sessionId: currentSessionId,
|
||||
directory: normalize(openDirectory || activeProject?.path || ''),
|
||||
apiBaseUrl: getRuntimeApiBaseUrl(),
|
||||
clientToken: getRuntimeBearerTokenSync(),
|
||||
}).catch((error) => {
|
||||
console.warn('[header] failed to open session mini chat window', error);
|
||||
});
|
||||
@@ -1740,7 +1884,7 @@ export const Header: React.FC<HeaderProps> = ({
|
||||
}
|
||||
|
||||
try {
|
||||
const devRes = await fetch('/api/system/dev-shutdown', {
|
||||
const devRes = await runtimeFetch('/api/system/dev-shutdown', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ previewUrls }),
|
||||
@@ -1748,7 +1892,7 @@ export const Header: React.FC<HeaderProps> = ({
|
||||
if (devRes.ok) {
|
||||
shutdownRequested = true;
|
||||
} else {
|
||||
const shutdownRes = await fetch('/api/system/shutdown', { method: 'POST' });
|
||||
const shutdownRes = await runtimeFetch('/api/system/shutdown', { method: 'POST' });
|
||||
shutdownRequested = shutdownRes.ok;
|
||||
}
|
||||
} catch {
|
||||
@@ -1929,6 +2073,7 @@ export const Header: React.FC<HeaderProps> = ({
|
||||
isDesktopApp={isDesktopApp}
|
||||
currentInstanceLabel={currentInstanceLabel}
|
||||
compactCurrentInstanceLabel={compactCurrentInstanceLabel}
|
||||
currentInstanceIsLocal={currentInstanceIsLocal}
|
||||
isDesktopServicesOpen={isDesktopServicesOpen}
|
||||
setIsDesktopServicesOpen={setIsDesktopServicesOpen}
|
||||
refreshCurrentInstanceLabel={refreshCurrentInstanceLabel}
|
||||
@@ -1953,6 +2098,10 @@ export const Header: React.FC<HeaderProps> = ({
|
||||
showDevShutdown={showDevShutdown}
|
||||
isDevShutdownInFlight={isDevShutdownInFlight}
|
||||
onDevShutdown={handleDevShutdown}
|
||||
remoteUpdateInfo={remoteUpdateInfo}
|
||||
remoteUpdateChecking={remoteUpdateChecking}
|
||||
remoteUpdateError={remoteUpdateError}
|
||||
onOpenRemoteUpdate={openRemoteInstanceUpdate}
|
||||
/>
|
||||
<HeaderIconActionButton
|
||||
title={t('header.actions.terminalPanelWithShortcut', { shortcut: shortcutLabel('toggle_terminal') })}
|
||||
@@ -2533,12 +2682,26 @@ export const Header: React.FC<HeaderProps> = ({
|
||||
);
|
||||
|
||||
return (
|
||||
<header
|
||||
ref={headerRef}
|
||||
className={headerClassName}
|
||||
style={{ ['--padding-scale' as string]: '1' } as React.CSSProperties}
|
||||
>
|
||||
{isMobile ? renderMobile() : renderDesktop()}
|
||||
</header>
|
||||
<>
|
||||
<header
|
||||
ref={headerRef}
|
||||
className={headerClassName}
|
||||
style={{ ['--padding-scale' as string]: '1' } as React.CSSProperties}
|
||||
>
|
||||
{isMobile ? renderMobile() : renderDesktop()}
|
||||
</header>
|
||||
<UpdateDialog
|
||||
open={remoteUpdateDialogOpen}
|
||||
onOpenChange={setRemoteUpdateDialogOpen}
|
||||
info={remoteUpdateInfo}
|
||||
downloading={false}
|
||||
downloaded={false}
|
||||
progress={null}
|
||||
error={remoteUpdateError}
|
||||
onDownload={() => {}}
|
||||
onRestart={() => {}}
|
||||
runtimeType="web"
|
||||
/>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -24,13 +24,13 @@ import { cn } from '@/lib/utils';
|
||||
import { lazyWithChunkRecovery } from '@/lib/chunkLoadRecovery';
|
||||
|
||||
import { ChatView } from '@/components/views/ChatView';
|
||||
import { DiffView } from '@/components/views/DiffView';
|
||||
import { FilesView } from '@/components/views/FilesView';
|
||||
import { GitView } from '@/components/views/GitView';
|
||||
import { PlanView } from '@/components/views/PlanView';
|
||||
|
||||
// Heavy views loaded on-demand to reduce initial bundle parse time.
|
||||
const PlanView = lazyWithChunkRecovery(() => import('@/components/views/PlanView').then(m => ({ default: m.PlanView })));
|
||||
const GitView = lazyWithChunkRecovery(() => import('@/components/views/GitView').then(m => ({ default: m.GitView })));
|
||||
const DiffView = lazyWithChunkRecovery(() => import('@/components/views/DiffView').then(m => ({ default: m.DiffView })));
|
||||
const TerminalView = lazyWithChunkRecovery(() => import('@/components/views/TerminalView').then(m => ({ default: m.TerminalView })));
|
||||
const FilesView = lazyWithChunkRecovery(() => import('@/components/views/FilesView').then(m => ({ default: m.FilesView })));
|
||||
const SettingsView = lazyWithChunkRecovery(() => import('@/components/views/SettingsView').then(m => ({ default: m.SettingsView })));
|
||||
const SettingsWindow = lazyWithChunkRecovery(() => import('@/components/views/SettingsWindow').then(m => ({ default: m.SettingsWindow })));
|
||||
const MultiRunWindow = lazyWithChunkRecovery(() => import('@/components/views/MultiRunWindow').then(m => ({ default: m.MultiRunWindow })));
|
||||
|
||||
@@ -10,7 +10,7 @@ import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { toast } from '@/components/ui';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { PROJECT_ICONS, PROJECT_COLORS, PROJECT_COLOR_MAP, getProjectIconImageUrl } from '@/lib/projectMeta';
|
||||
import { PROJECT_ICONS, PROJECT_COLORS, PROJECT_COLOR_MAP, ProjectIconImage } from '@/lib/projectMeta';
|
||||
import { useProjectsStore } from '@/stores/useProjectsStore';
|
||||
import { useThemeSystem } from '@/contexts/useThemeSystem';
|
||||
import { useI18n } from '@/lib/i18n';
|
||||
@@ -146,19 +146,8 @@ export const ProjectEditDialog: React.FC<ProjectEditDialogProps> = ({
|
||||
const hasCustomIcon = currentIconImage?.source === 'custom';
|
||||
const effectiveHasImageIcon = (hasStoredImageIcon && !pendingRemoveImageIcon) || hasPendingUploadImageIcon;
|
||||
const hasRemovableImageIcon = effectiveHasImageIcon;
|
||||
const iconPreviewUrl = !previewImageFailed
|
||||
? (hasPendingUploadImageIcon
|
||||
? pendingUploadIconPreviewUrl
|
||||
: (hasStoredImageIcon && !pendingRemoveImageIcon
|
||||
? getProjectIconImageUrl(
|
||||
{ id: projectId, iconImage: currentIconImage ?? null },
|
||||
{
|
||||
themeVariant: currentTheme.metadata.variant,
|
||||
iconColor: currentTheme.colors.surface.foreground,
|
||||
},
|
||||
)
|
||||
: null))
|
||||
: null;
|
||||
const showStoredImagePreview = hasStoredImageIcon && !pendingRemoveImageIcon;
|
||||
const showImagePreview = !previewImageFailed && (hasPendingUploadImageIcon || showStoredImagePreview);
|
||||
|
||||
React.useEffect(() => {
|
||||
setPreviewImageFailed(false);
|
||||
@@ -352,7 +341,7 @@ export const ProjectEditDialog: React.FC<ProjectEditDialogProps> = ({
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
{effectiveHasImageIcon && iconPreviewUrl && (
|
||||
{effectiveHasImageIcon && showImagePreview && (
|
||||
<div className="flex items-center gap-2 pt-1">
|
||||
<span className="typography-meta text-muted-foreground">{t('projectEditDialog.field.preview')}</span>
|
||||
<span className="inline-flex h-8 w-8 items-center justify-center rounded-lg border border-border/60 bg-[var(--surface-elevated)] p-1">
|
||||
@@ -360,13 +349,25 @@ export const ProjectEditDialog: React.FC<ProjectEditDialogProps> = ({
|
||||
className="inline-flex h-4 w-4 items-center justify-center overflow-hidden rounded-[2px]"
|
||||
style={iconBackground ? { backgroundColor: iconBackground } : undefined}
|
||||
>
|
||||
<img
|
||||
src={iconPreviewUrl}
|
||||
alt=""
|
||||
className="h-full w-full object-contain"
|
||||
draggable={false}
|
||||
onError={() => setPreviewImageFailed(true)}
|
||||
/>
|
||||
{hasPendingUploadImageIcon && pendingUploadIconPreviewUrl ? (
|
||||
<img
|
||||
src={pendingUploadIconPreviewUrl}
|
||||
alt=""
|
||||
className="h-full w-full object-contain"
|
||||
draggable={false}
|
||||
onError={() => setPreviewImageFailed(true)}
|
||||
/>
|
||||
) : (
|
||||
<ProjectIconImage
|
||||
project={{ id: projectId, iconImage: currentIconImage }}
|
||||
options={{
|
||||
themeVariant: currentTheme.metadata.variant,
|
||||
iconColor: currentTheme.colors.surface.foreground,
|
||||
}}
|
||||
className="h-full w-full object-contain"
|
||||
onError={() => setPreviewImageFailed(true)}
|
||||
/>
|
||||
)}
|
||||
</span>
|
||||
</span>
|
||||
</div>
|
||||
|
||||
Reference in New Issue
Block a user