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:
Bohdan Triapitsyn
2026-06-02 00:43:05 +03:00
committed by GitHub
parent a4314c189b
commit 2031e3b4a8
282 changed files with 16524 additions and 4259 deletions
@@ -142,10 +142,8 @@ type ChatViewportProps = {
stickyUserHeader: boolean;
scrollRef: React.RefObject<HTMLDivElement | null>;
messageListRef: React.RefObject<MessageListHandle | null>;
turnStart: number;
pendingRevealWork: boolean;
renderedMessages: SessionMessageRecord[];
hasMoreAboveTurns: boolean;
isLoadingOlder: boolean;
sessionIsWorking: boolean;
streamingMessageId: string | null;
@@ -158,7 +156,6 @@ type ChatViewportProps = {
} | null;
handleMessageContentChange: (reason?: ContentChangeReason) => void;
getAnimationHandlers: (messageId: string) => AnimationHandlers;
handleLoadOlder: () => void;
handleHistoryScroll: () => void;
scrollToBottom: () => void;
sessionQuestions: QuestionRequest[];
@@ -173,10 +170,8 @@ const ChatViewport = React.memo(({
stickyUserHeader,
scrollRef,
messageListRef,
turnStart,
pendingRevealWork,
renderedMessages,
hasMoreAboveTurns,
isLoadingOlder,
sessionIsWorking,
streamingMessageId,
@@ -184,7 +179,6 @@ const ChatViewport = React.memo(({
retryOverlay,
handleMessageContentChange,
getAnimationHandlers,
handleLoadOlder,
handleHistoryScroll,
scrollToBottom,
sessionQuestions,
@@ -230,7 +224,6 @@ const ChatViewport = React.memo(({
<MessageList
ref={messageListRef}
sessionKey={currentSessionId}
turnStart={turnStart}
disableStaging={pendingRevealWork}
messages={renderedMessages}
sessionIsWorking={sessionIsWorking}
@@ -239,9 +232,7 @@ const ChatViewport = React.memo(({
retryOverlay={retryOverlay}
onMessageContentChange={handleMessageContentChange}
getAnimationHandlers={getAnimationHandlers}
hasMoreAbove={hasMoreAboveTurns}
isLoadingOlder={isLoadingOlder}
onLoadOlder={handleLoadOlder}
scrollToBottom={scrollToBottom}
scrollRef={scrollRef}
/>
@@ -274,10 +265,8 @@ const ChatViewport = React.memo(({
&& prev.stickyUserHeader === next.stickyUserHeader
&& prev.scrollRef === next.scrollRef
&& prev.messageListRef === next.messageListRef
&& prev.turnStart === next.turnStart
&& prev.pendingRevealWork === next.pendingRevealWork
&& prev.renderedMessages === next.renderedMessages
&& prev.hasMoreAboveTurns === next.hasMoreAboveTurns
&& prev.isLoadingOlder === next.isLoadingOlder
&& prev.sessionIsWorking === next.sessionIsWorking
&& prev.streamingMessageId === next.streamingMessageId
@@ -285,7 +274,6 @@ const ChatViewport = React.memo(({
&& prev.retryOverlay === next.retryOverlay
&& prev.handleMessageContentChange === next.handleMessageContentChange
&& prev.getAnimationHandlers === next.getAnimationHandlers
&& prev.handleLoadOlder === next.handleLoadOlder
&& prev.handleHistoryScroll === next.handleHistoryScroll
&& prev.scrollToBottom === next.scrollToBottom
&& prev.sessionQuestions === next.sessionQuestions
@@ -645,8 +633,6 @@ export const ChatContainer: React.FC<ChatContainerProps> = ({ autoOpenDraft = tr
isPinned,
showScrollButton,
});
const { loadEarlier } = timelineController;
const resumeToLatestInstant = React.useCallback(() => {
goToBottom('instant');
}, [goToBottom]);
@@ -662,10 +648,6 @@ export const ChatContainer: React.FC<ChatContainerProps> = ({ autoOpenDraft = tr
handleMessageContentChange('permission');
}, [handleMessageContentChange, sessionPermissions, sessionQuestions]);
const handleLoadOlder = React.useCallback(() => {
void loadEarlier({ userInitiated: true });
}, [loadEarlier]);
const navigation = useChatTurnNavigation({
sessionId: currentSessionId,
turnIds: timelineController.turnIds,
@@ -957,10 +939,8 @@ export const ChatContainer: React.FC<ChatContainerProps> = ({ autoOpenDraft = tr
stickyUserHeader={stickyUserHeader}
scrollRef={scrollRef}
messageListRef={messageListRef}
turnStart={timelineController.turnStart}
pendingRevealWork={timelineController.pendingRevealWork}
renderedMessages={timelineController.renderedMessages}
hasMoreAboveTurns={timelineController.historySignals.hasMoreAboveTurns}
isLoadingOlder={timelineController.isLoadingOlder}
sessionIsWorking={sessionIsWorking}
streamingMessageId={streamingMessageId}
@@ -968,7 +948,6 @@ export const ChatContainer: React.FC<ChatContainerProps> = ({ autoOpenDraft = tr
retryOverlay={retryOverlay}
handleMessageContentChange={handleMessageContentChange}
getAnimationHandlers={getAnimationHandlers}
handleLoadOlder={handleLoadOlder}
handleHistoryScroll={timelineController.handleHistoryScroll}
scrollToBottom={resumeToLatestInstant}
sessionQuestions={sessionQuestions}
+44 -31
View File
@@ -31,12 +31,13 @@ import { PendingChangesBar } from './PendingChangesBar';
import { useChatSurfaceMode } from './useChatSurfaceMode';
import { MobileAgentButton } from './MobileAgentButton';
import { MobileModelButton } from './MobileModelButton';
import { MobileSessionStatusBar } from './MobileSessionStatusBar';
import { MobileSessionStatusBar, MobileSessionPanelTrigger } from './MobileSessionStatusBar';
import { useCurrentSessionActivity } from '@/hooks/useSessionActivity';
import { toast } from '@/components/ui';
import { Button } from '@/components/ui/button';
// useMessageStore removed — messages now come from sync system
import { isTauriShell, isVSCodeRuntime } from '@/lib/desktop';
import { runtimeFetch } from '@/lib/runtime-fetch';
import { isIMECompositionEvent } from '@/lib/ime';
import { StopIcon } from '@/components/icons/StopIcon';
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';
@@ -56,7 +57,7 @@ import { DraftPresetChips } from './DraftPresetChips';
import { useChatSearchDirectory } from '@/hooks/useChatSearchDirectory';
import { opencodeClient } from '@/lib/opencode/client';
import { useProjectsStore } from '@/stores/useProjectsStore';
import { PROJECT_COLOR_MAP, PROJECT_ICON_MAP, getProjectIconImageUrl } from '@/lib/projectMeta';
import { PROJECT_COLOR_MAP, PROJECT_ICON_MAP, ProjectIconImage } from '@/lib/projectMeta';
import { useGitBranches, useGitStore, useIsGitRepo } from '@/stores/useGitStore';
import { useDirectoryStore } from '@/stores/useDirectoryStore';
import { useSkillsStore } from '@/stores/useSkillsStore';
@@ -1030,11 +1031,11 @@ const ChatInputComponent: React.FC<ChatInputProps> = ({ onOpenSettings, scrollTo
const isExpandedInput = useUIStore((state) => state.isExpandedInput);
const setExpandedInput = useUIStore((state) => state.setExpandedInput);
const setTimelineDialogOpen = useUIStore((state) => state.setTimelineDialogOpen);
const { git: runtimeGit, vscode: vscodeApi } = useRuntimeAPIs();
const cycleAgentShortcutOverride = useUIStore((state) => state.shortcutOverrides.cycle_agent);
const cycleAgentShortcut = React.useMemo(() => (
getEffectiveShortcutCombo('cycle_agent', cycleAgentShortcutOverride ? { cycle_agent: cycleAgentShortcutOverride } : undefined)
), [cycleAgentShortcutOverride]);
const { git: runtimeGit } = useRuntimeAPIs();
const { currentTheme } = useThemeSystem();
const chatSearchDirectory = useChatSearchDirectory();
const isGitRepo = useIsGitRepo(currentDirectory);
@@ -1869,14 +1870,8 @@ const ChatInputComponent: React.FC<ChatInputProps> = ({ onOpenSettings, scrollTo
else if (commandName === 'compact' && currentSessionId) {
try {
await sessionActions.waitForConnectionOrThrow();
const { opencodeClient } = await import('@/lib/opencode/client');
const sdk = opencodeClient.getSdkClient();
const configState = useConfigStore.getState();
await sdk.session.summarize({
sessionID: currentSessionId,
modelID: configState.currentModelId || '',
providerID: configState.currentProviderId || '',
});
const compactDirectory = useSessionUIStore.getState().getDirectoryForSession(currentSessionId) || currentDirectory || undefined;
await opencodeClient.summarizeSession(currentSessionId, currentProviderId, currentModelId, compactDirectory);
} catch (error) {
toast.error(error instanceof Error ? error.message : t('chat.chatInput.toast.compactFailed'));
}
@@ -2722,7 +2717,17 @@ const ChatInputComponent: React.FC<ChatInputProps> = ({ onOpenSettings, scrollTo
} else {
setShowFileMention(false);
}
}, [inputMode, setCommandQuery, setMentionQuery, setShowCommandAutocomplete, setShowFileMention, setShowSkillAutocomplete, setSkillQuery]);
}, [
inputMode,
setCommandQuery,
setMentionQuery,
setShowCommandAutocomplete,
setShowFileMention,
setShowSkillAutocomplete,
setShowSnippetAutocomplete,
setSkillQuery,
setSnippetQuery,
]);
const insertTextAtSelection = React.useCallback((text: string) => {
if (!text) {
@@ -3469,7 +3474,7 @@ const ChatInputComponent: React.FC<ChatInputProps> = ({ onOpenSettings, scrollTo
const blob = new Blob([byteArray], { type: result.mime || 'application/octet-stream' });
file = new File([blob], fileName, { type: result.mime || 'application/octet-stream' });
} else {
const response = await fetch(`/api/fs/raw?path=${encodeURIComponent(normalizedPath)}`);
const response = await runtimeFetch('/api/fs/raw', { query: { path: normalizedPath } });
if (!response.ok) {
throw new Error(`Failed to read dropped file (${response.status})`);
}
@@ -3523,8 +3528,10 @@ const ChatInputComponent: React.FC<ChatInputProps> = ({ onOpenSettings, scrollTo
const handleVSCodePickFiles = React.useCallback(async () => {
try {
const response = await fetch('/api/vscode/pick-files');
const data = await response.json();
const data = (await vscodeApi?.pickFiles?.()) as {
files?: Array<{ name: string; mimeType?: string; dataUrl?: string }>;
skipped?: Array<{ name?: string; reason?: string }>;
} | undefined;
const picked = Array.isArray(data?.files) ? data.files : [];
const skipped = Array.isArray(data?.skipped) ? data.skipped : [];
@@ -3563,7 +3570,7 @@ const ChatInputComponent: React.FC<ChatInputProps> = ({ onOpenSettings, scrollTo
console.error('VS Code file pick failed', error);
toast.error(error instanceof Error ? error.message : t('chat.chatInput.toast.vscodePickFailed'));
}
}, [attachFiles, t]);
}, [attachFiles, t, vscodeApi]);
const handlePickLocalFiles = React.useCallback(() => {
if (isVSCodeRuntime()) {
@@ -3823,30 +3830,32 @@ const ChatInputComponent: React.FC<ChatInputProps> = ({ onOpenSettings, scrollTo
iconImage?: { mime: string; updatedAt: number; source: 'custom' | 'auto' } | null;
iconBackground?: string | null;
}) => {
const imageUrl = getProjectIconImageUrl(
{ id: project.id, iconImage: project.iconImage ?? null },
{
themeVariant: currentTheme.metadata.variant,
iconColor: currentTheme.colors.surface.foreground,
},
);
const projectIconName = project.icon ? PROJECT_ICON_MAP[project.icon] : null;
const iconColor = getProjectIconColor(project.color);
const fallbackIcon = projectIconName ? (
<Icon name={projectIconName} className="h-3.5 w-3.5 shrink-0" style={iconColor ? { color: iconColor } : undefined} />
) : (
<Icon name="folder" className="h-3.5 w-3.5 shrink-0 text-muted-foreground/80" style={iconColor ? { color: iconColor } : undefined}/>
);
return (
<span className="inline-flex min-w-0 items-center gap-1.5">
{imageUrl ? (
{project.iconImage ? (
<span
className="inline-flex h-3.5 w-3.5 shrink-0 items-center justify-center overflow-hidden rounded-[3px]"
style={project.iconBackground ? { backgroundColor: project.iconBackground } : undefined}
>
<img src={imageUrl} alt="" className="h-full w-full object-contain" draggable={false} />
<ProjectIconImage
project={{ id: project.id, iconImage: project.iconImage ?? null }}
options={{
themeVariant: currentTheme.metadata.variant,
iconColor: currentTheme.colors.surface.foreground,
}}
className="h-full w-full object-contain"
fallback={fallbackIcon}
/>
</span>
) : projectIconName ? (
<Icon name={projectIconName} className="h-3.5 w-3.5 shrink-0" style={iconColor ? { color: iconColor } : undefined} />
) : (
<Icon name="folder" className="h-3.5 w-3.5 shrink-0 text-muted-foreground/80" style={iconColor ? { color: iconColor } : undefined}/>
)}
) : fallbackIcon}
<span className="truncate">{getProjectDisplayLabel(project)}</span>
</span>
);
@@ -4426,6 +4435,10 @@ const ChatInputComponent: React.FC<ChatInputProps> = ({ onOpenSettings, scrollTo
<>
<div className="flex w-full items-center justify-between gap-x-1.5">
<div className="flex items-center gap-x-1.5">
<MobileSessionPanelTrigger
footerIconButtonClass={footerIconButtonClass}
iconSizeClass={iconSizeClass}
/>
<ComposerAttachmentControls
isVSCode={isVSCode}
footerIconButtonClass={footerIconButtonClass}
@@ -4530,7 +4543,7 @@ const ChatInputComponent: React.FC<ChatInputProps> = ({ onOpenSettings, scrollTo
)}
</div>
{/* Mobile Session Status Bar - above input */}
{/* Mobile session panel: slide-up overlay toggled by MobileSessionPanelTrigger. */}
{isMobile && <MobileSessionStatusBar />}
</div>
</div>
@@ -6,7 +6,7 @@ import { toast } from '@/components/ui';
import { cn } from '@/lib/utils';
import { openExternalUrl } from '@/lib/url';
import { Tooltip, TooltipTrigger, TooltipContent } from '@/components/ui/tooltip';
import { useIsVSCodeRuntime } from '@/hooks/useRuntimeAPIs';
import { useRuntimeAPIs } from '@/hooks/useRuntimeAPIs';
import { FileTypeIcon } from '@/components/icons/FileTypeIcon';
import { Icon } from "@/components/icon/Icon";
import { useI18n } from '@/lib/i18n';
@@ -19,7 +19,8 @@ export const FileAttachmentButton = memo(() => {
const fileInputRef = useRef<HTMLInputElement>(null);
const addAttachedFile = useInputStore((state) => state.addAttachedFile);
const isMobile = useUIStore((state) => state.isMobile);
const isVSCodeRuntime = useIsVSCodeRuntime();
const runtimeApis = useRuntimeAPIs();
const isVSCodeRuntime = runtimeApis.runtime.isVSCode;
const buttonSizeClass = isMobile ? 'h-9 w-9' : 'h-7 w-7';
const iconSizeClass = isMobile ? 'h-5 w-5' : 'h-[18px] w-[18px]';
@@ -47,8 +48,10 @@ export const FileAttachmentButton = memo(() => {
const handleVSCodePick = async () => {
try {
const response = await fetch('/api/vscode/pick-files');
const data = await response.json();
const data = (await runtimeApis.vscode?.pickFiles?.()) as {
files?: Array<{ name: string; mimeType?: string; dataUrl?: string }>;
skipped?: Array<{ name?: string; reason?: string }>;
} | undefined;
const picked = Array.isArray(data?.files) ? data.files : [];
const skipped = Array.isArray(data?.skipped) ? data.skipped : [];
@@ -449,7 +452,7 @@ export const ActiveEditorFileSuggestion = memo(() => {
const attachedFiles = useInputStore((s) => s.attachedFiles)
const addVSCodeFileAttachment = useInputStore((s) => s.addVSCodeFileAttachment)
const addVSCodeSelectionAttachment = useInputStore((s) => s.addVSCodeSelectionAttachment)
const isVSCodeRuntime = useIsVSCodeRuntime();
const isVSCodeRuntime = useRuntimeAPIs().runtime.isVSCode;
if (!isVSCodeRuntime || !activeEditorFile) return null;
@@ -16,6 +16,7 @@ import { toast } from '@/components/ui';
import { Icon } from "@/components/icon/Icon";
import { copyTextToClipboard } from '@/lib/clipboard';
import { useI18n } from '@/lib/i18n';
import { runtimeFetch } from '@/lib/runtime-fetch';
import { getExternalFaviconUrl, isExternalHttpUrl, isLoopbackHttpUrl, openExternalUrl } from '@/lib/url';
import { useOptionalThemeSystem } from '@/contexts/useThemeSystem';
@@ -1341,7 +1342,7 @@ const fileReferenceExists = (resolvedPath: string): Promise<boolean> => {
const request = new Promise<boolean>((resolve) => {
const run = () => {
activeFileReferenceStatCount += 1;
void fetch(`/api/fs/stat?path=${encodeURIComponent(normalizedPath)}`, {
void runtimeFetch(`/api/fs/stat?path=${encodeURIComponent(normalizedPath)}`, {
method: 'GET',
cache: 'no-store',
})
@@ -391,7 +391,6 @@ const getNormalizedMessageForDisplay = (message: ChatMessageEntry): ChatMessageE
interface MessageListProps {
sessionKey: string;
turnStart: number;
disableStaging?: boolean;
messages: ChatMessageEntry[];
sessionIsWorking?: boolean;
@@ -405,9 +404,7 @@ interface MessageListProps {
} | null;
onMessageContentChange: (reason?: ContentChangeReason) => void;
getAnimationHandlers: (messageId: string) => AnimationHandlers;
hasMoreAbove: boolean;
isLoadingOlder: boolean;
onLoadOlder: () => void;
scrollToBottom?: () => void;
scrollRef?: React.RefObject<HTMLDivElement | null>;
}
@@ -1101,7 +1098,6 @@ StreamingTailContent.displayName = 'StreamingTailContent';
const MessageList = React.forwardRef<MessageListHandle, MessageListProps>(({
sessionKey,
turnStart,
disableStaging = false,
messages,
sessionIsWorking = false,
@@ -1110,9 +1106,7 @@ const MessageList = React.forwardRef<MessageListHandle, MessageListProps>(({
retryOverlay = null,
onMessageContentChange,
getAnimationHandlers,
hasMoreAbove,
isLoadingOlder,
onLoadOlder,
scrollToBottom,
scrollRef,
}, ref) => {
@@ -1128,7 +1122,6 @@ const MessageList = React.forwardRef<MessageListHandle, MessageListProps>(({
animatedIds: Set<string>;
}>({ sessionKey: undefined, previousOrder: [], animatedIds: new Set() });
const stableGetAnimationHandlers = useStableEvent(getAnimationHandlers);
const stableOnLoadOlder = useStableEvent(onLoadOlder);
const stableScrollToBottom = useStableEvent(() => {
scrollToBottom?.();
});
@@ -1675,24 +1668,6 @@ const MessageList = React.forwardRef<MessageListHandle, MessageListProps>(({
return (
<div>
{(turnStart > 0 || hasMoreAbove) && (
<div className="flex justify-center py-3">
{isLoadingOlder ? (
<span className="text-xs uppercase tracking-wide text-muted-foreground/80">
Loading
</span>
) : (
<button
type="button"
onClick={stableOnLoadOlder}
className="text-xs uppercase tracking-wide text-muted-foreground/80 hover:text-foreground"
>
Load older messages
</button>
)}
</div>
)}
<FadeInDisabledProvider disabled={disableFadeIn}>
<div className="relative w-full">
<StaticHistoryList
File diff suppressed because it is too large Load Diff
@@ -3,6 +3,7 @@ import { useDirectoryStore } from '@/stores/useDirectoryStore';
import { useGitStore, useIsGitRepo } from '@/stores/useGitStore';
import { useUIStore } from '@/stores/useUIStore';
import { RuntimeAPIContext } from '@/contexts/runtimeAPIContext';
import { useMobileAppActions } from '@/apps/mobileAppContext';
import { sessionEvents } from '@/lib/sessionEvents';
import { normalizePath } from '@/components/session/sidebar/utils';
import { Icon } from "@/components/icon/Icon";
@@ -29,6 +30,7 @@ export const PendingChangesBar: React.FC = React.memo(() => {
);
const ensureStatus = useGitStore((s) => s.ensureStatus);
const fetchStatus = useGitStore((s) => s.fetchStatus);
const mobileActions = useMobileAppActions();
// Close popover when clicking outside
React.useEffect(() => {
@@ -90,6 +92,16 @@ export const PendingChangesBar: React.FC = React.memo(() => {
? file.path
: (currentDirectory.endsWith('/') ? currentDirectory : currentDirectory + '/') + file.path;
// Dedicated mobile root: open the per-file diff inside the mobile Changes surface.
if (mobileActions) {
mobileActions.openChanges({
diffPath: file.relativePath,
staged: file.hasStagedChanges && !file.hasWorkingChanges,
});
setIsExpanded(false);
return;
}
const editor = runtime?.editor;
if (editor) {
void editor.openFile(absolutePath);
@@ -0,0 +1,41 @@
import { describe, expect, test } from 'bun:test';
import { shouldAutoLoadEarlierForUnderfilledPinnedViewport } from './useChatTimelineController';
const baseInput = {
sessionId: 'ses_1',
isPinned: true,
canLoadEarlier: true,
isLoadingOlder: false,
pendingRevealWork: false,
scrollHeight: 799,
clientHeight: 800,
};
describe('shouldAutoLoadEarlierForUnderfilledPinnedViewport', () => {
test('loads when pinned content does not fill the viewport', () => {
expect(shouldAutoLoadEarlierForUnderfilledPinnedViewport(baseInput)).toBe(true);
});
test('does not load when content already overflows', () => {
expect(shouldAutoLoadEarlierForUnderfilledPinnedViewport({
...baseInput,
scrollHeight: 802,
})).toBe(false);
});
test('does not load while user is away from bottom or history work is active', () => {
expect(shouldAutoLoadEarlierForUnderfilledPinnedViewport({
...baseInput,
isPinned: false,
})).toBe(false);
expect(shouldAutoLoadEarlierForUnderfilledPinnedViewport({
...baseInput,
isLoadingOlder: true,
})).toBe(false);
expect(shouldAutoLoadEarlierForUnderfilledPinnedViewport({
...baseInput,
pendingRevealWork: true,
})).toBe(false);
});
});
@@ -97,6 +97,21 @@ const rememberTurnModel = (key: string, value: { messages: ChatMessageEntry[]; m
turnModelCache.set(key, value)
}
export const shouldAutoLoadEarlierForUnderfilledPinnedViewport = (input: {
sessionId: string | null;
isPinned: boolean;
canLoadEarlier: boolean;
isLoadingOlder: boolean;
pendingRevealWork: boolean;
scrollHeight: number;
clientHeight: number;
}): boolean => {
if (!input.sessionId) return false;
if (!input.isPinned || !input.canLoadEarlier) return false;
if (input.isLoadingOlder || input.pendingRevealWork) return false;
return input.scrollHeight <= input.clientHeight + 1;
};
export const useChatTimelineController = ({
sessionId,
messages,
@@ -524,26 +539,32 @@ export const useChatTimelineController = ({
void loadEarlier({ userInitiated: true });
}, [loadEarlier, scrollRef]);
const loadEarlierIfPinnedViewportUnderfilled = React.useCallback(() => {
if (historyInteractionRef.current) return;
const container = scrollRef.current;
if (!container) return;
if (!shouldAutoLoadEarlierForUnderfilledPinnedViewport({
sessionId: sessionIdRef.current,
isPinned: isPinnedRef.current,
canLoadEarlier: historySignalsRef.current.canLoadEarlier,
isLoadingOlder: isLoadingOlderRef.current,
pendingRevealWork: pendingRevealWorkRef.current,
scrollHeight: container.scrollHeight,
clientHeight: container.clientHeight,
})) {
return;
}
void loadEarlier();
}, [loadEarlier, scrollRef]);
React.useEffect(() => {
if (!sessionId || isLoadingOlder || pendingRevealWork) {
return;
}
if (!isPinned || !historySignals.canLoadEarlier) {
return;
}
if (typeof window === 'undefined') {
return;
}
const frame = window.requestAnimationFrame(() => {
const container = scrollRef.current;
if (!container) return;
if (!isPinnedRef.current) return;
if (!historySignalsRef.current.canLoadEarlier) return;
if (isLoadingOlderRef.current || pendingRevealWorkRef.current) return;
if (container.scrollHeight > container.clientHeight + 1) return;
void loadEarlier();
loadEarlierIfPinnedViewportUnderfilled();
});
return () => window.cancelAnimationFrame(frame);
@@ -551,13 +572,49 @@ export const useChatTimelineController = ({
historySignals.canLoadEarlier,
isLoadingOlder,
isPinned,
loadEarlier,
loadEarlierIfPinnedViewportUnderfilled,
pendingRevealWork,
renderedMessages.length,
scrollRef,
sessionId,
]);
React.useEffect(() => {
if (typeof window === 'undefined' || typeof ResizeObserver === 'undefined') {
return;
}
const container = scrollRef.current;
if (!container) {
return;
}
let frame: number | null = null;
const scheduleCheck = () => {
if (frame !== null) {
return;
}
frame = window.requestAnimationFrame(() => {
frame = null;
loadEarlierIfPinnedViewportUnderfilled();
});
};
const observer = new ResizeObserver(scheduleCheck);
observer.observe(container);
const content = container.firstElementChild;
if (content instanceof Element) {
observer.observe(content);
}
scheduleCheck();
return () => {
if (frame !== null) {
window.cancelAnimationFrame(frame);
}
observer.disconnect();
};
}, [loadEarlierIfPinnedViewportUnderfilled, scrollRef, sessionId]);
const scrollToTurn = React.useCallback(async (
turnId: string,
options?: { behavior?: ScrollBehavior },
@@ -31,6 +31,7 @@ import { TextSelectionMenu } from './TextSelectionMenu';
import { copyTextToClipboard } from '@/lib/clipboard';
import { useChatSurfaceMode } from '@/components/chat/useChatSurfaceMode';
import { isVSCodeRuntime } from '@/lib/desktop';
import { useRuntimeAPIs } from '@/hooks/useRuntimeAPIs';
import { toPng } from 'html-to-image';
import { toast } from '@/components/ui';
import { Icon } from "@/components/icon/Icon";
@@ -1034,6 +1035,7 @@ const AssistantMessageBody = React.memo(({
const collapsibleThinkingBlocks = useUIStore((state) => state.collapsibleThinkingBlocks);
const groupReasoningBlocks = useUIStore((state) => state.groupReasoningBlocks);
const showSplitAssistantMessageActions = useUIStore((state) => state.showSplitAssistantMessageActions);
const vscodeApi = useRuntimeAPIs().vscode;
const isSortedRenderMode = chatRenderMode === 'sorted';
const collapsedPreviewCount = 7;
const isLastAssistantInTurn = turnGroupingContext?.isLastAssistantInTurn ?? false;
@@ -1319,17 +1321,10 @@ const AssistantMessageBody = React.memo(({
const fileName = `message-${messageId}.png`;
if (isVSCodeRuntime()) {
const response = await fetch('/api/vscode/save-image', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ fileName, dataUrl }),
});
if (!response.ok) {
const payload = await vscodeApi?.saveImage?.({ fileName, dataUrl }) as { saved?: boolean; canceled?: boolean; error?: string } | undefined;
if (!payload) {
throw new Error('Failed to save image in VS Code');
}
const payload = await response.json() as { saved?: boolean; canceled?: boolean; error?: string };
if (payload.saved !== true) {
if (payload.canceled) {
return;
@@ -1355,7 +1350,7 @@ const AssistantMessageBody = React.memo(({
}
}
},
[messageId, t]
[messageId, t, vscodeApi]
);
const activityPartsForTurn = React.useMemo(() => {
@@ -27,6 +27,7 @@ import { VirtualizedCodeBlock, type CodeLine } from './parts/VirtualizedCodeBloc
import { JsonTreeView } from '@/components/ui/JsonTreeView';
import { Icon } from "@/components/icon/Icon";
import { useI18n } from '@/lib/i18n';
import { runtimeFetch } from '@/lib/runtime-fetch';
interface ToolOutputDialogProps {
popup: ToolPopupContent;
@@ -739,7 +740,7 @@ const MermaidPreviewDialog: React.FC<{
if (!normalizedPath) {
sourcePromise = Promise.reject(new Error('Invalid local file path for Mermaid preview.'));
} else {
sourcePromise = fetch(`/api/fs/raw?path=${encodeURIComponent(normalizedPath)}`)
sourcePromise = runtimeFetch('/api/fs/raw', { query: { path: normalizedPath } })
.then((response) => {
if (!response.ok) {
return Promise.reject(new Error(`Failed to read diagram file (${response.status})`));