Spaces:
Paused
Paused
File size: 18,737 Bytes
7142bcd 0ed8124 6c62075 0ed8124 6c62075 0ed8124 21ad36a 7142bcd 0ed8124 7142bcd 6c62075 7142bcd 0ed8124 6c62075 7142bcd 6c62075 0ed8124 7142bcd 21ad36a 0ed8124 7142bcd 0ed8124 6c62075 7142bcd 6c62075 7142bcd 0ed8124 6c62075 0ed8124 6c62075 0ed8124 c3633b1 0ed8124 21ad36a 0ed8124 f3ad26c 0ed8124 6c62075 0ed8124 6c62075 0ed8124 7142bcd 0ed8124 6c62075 0ed8124 643dfc6 0ed8124 7142bcd | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 | import {
useEffect,
useMemo,
useRef,
useState,
type CSSProperties,
type KeyboardEvent,
type PointerEvent,
} from 'react';
import type { BonsaiShellProps } from '../../lib/contracts';
import { normalizeThemeMode, resolveThemeMode, THEME_STORAGE_KEY, type ThemeMode } from '../theme';
import { ChatSurface } from './ChatSurface';
import { ConversationList } from './ConversationList';
import { Header, type ChatWidth } from './Header';
import { InspectorPanel } from './InspectorPanel';
import { ModelRail } from './ModelRail';
import { SettingsSheet } from './SettingsSheet';
const BROWSER_THEME_COLORS = {
light: '#f3f6f2',
dark: '#111511',
} as const;
const SIDEBAR_LAYOUT_STORAGE_KEY = 'bonsai-sidebar-layout-v1';
export const SIDEBAR_COLLAPSE_THRESHOLD = 132;
export const SIDEBAR_EXPAND_THRESHOLD = 176;
const MIN_CHAT_WIDTH = 360;
const RESIZE_STEP = 16;
type SidebarSide = 'left' | 'right';
interface SidebarLayout {
leftWidth: number;
rightWidth: number;
leftOpen: boolean;
rightOpen: boolean;
}
interface SidebarDrag {
side: SidebarSide;
pointerId: number;
startX: number;
startWidth: number;
moved: boolean;
}
export function resolveSidebarDrag(rawWidth: number, open: boolean, maxWidth: number) {
if ((open && rawWidth <= SIDEBAR_COLLAPSE_THRESHOLD)
|| (!open && rawWidth < SIDEBAR_EXPAND_THRESHOLD)) {
return { open: false, width: 0 } as const;
}
return {
open: true,
width: Math.round(Math.min(maxWidth, Math.max(SIDEBAR_COLLAPSE_THRESHOLD + 1, rawWidth))),
} as const;
}
function defaultSidebarLayout(): SidebarLayout {
const large = (globalThis.innerWidth ?? 0) >= 2400;
return {
leftWidth: large ? 340 : 260,
rightWidth: large ? 420 : 340,
leftOpen: true,
rightOpen: true,
};
}
function readSidebarLayout(): SidebarLayout {
const fallback = defaultSidebarLayout();
try {
const raw = globalThis.localStorage?.getItem(SIDEBAR_LAYOUT_STORAGE_KEY);
if (!raw) return fallback;
const stored = JSON.parse(raw) as Partial<SidebarLayout>;
const normalizeWidth = (value: unknown, defaultWidth: number) => (
typeof value === 'number' && Number.isFinite(value)
? Math.min(800, Math.max(SIDEBAR_EXPAND_THRESHOLD, Math.round(value)))
: defaultWidth
);
return {
leftWidth: normalizeWidth(stored.leftWidth, fallback.leftWidth),
rightWidth: normalizeWidth(stored.rightWidth, fallback.rightWidth),
leftOpen: typeof stored.leftOpen === 'boolean' ? stored.leftOpen : fallback.leftOpen,
rightOpen: typeof stored.rightOpen === 'boolean' ? stored.rightOpen : fallback.rightOpen,
};
} catch {
return fallback;
}
}
export function BonsaiShell(props: BonsaiShellProps) {
const [initialSidebarLayout] = useState(readSidebarLayout);
const [leftSidebarOpen, setLeftSidebarOpen] = useState(initialSidebarLayout.leftOpen);
const [rightSidebarOpen, setRightSidebarOpen] = useState(initialSidebarLayout.rightOpen);
const [leftSidebarWidth, setLeftSidebarWidth] = useState(initialSidebarLayout.leftWidth);
const [rightSidebarWidth, setRightSidebarWidth] = useState(initialSidebarLayout.rightWidth);
const [resizingSide, setResizingSide] = useState<SidebarSide | null>(null);
const [chatWidth, setChatWidth] = useState<ChatWidth>('centered');
const [themeMode, setThemeMode] = useState<ThemeMode>(() => {
try {
return normalizeThemeMode(globalThis.localStorage?.getItem(THEME_STORAGE_KEY));
} catch {
return 'system';
}
});
const [systemDark, setSystemDark] = useState(() => globalThis.matchMedia?.('(prefers-color-scheme: dark)').matches ?? false);
const workspaceRef = useRef<HTMLDivElement>(null);
const dragRef = useRef<SidebarDrag | null>(null);
const suppressClickRef = useRef<SidebarSide | null>(null);
const leftOpenRef = useRef(leftSidebarOpen);
const rightOpenRef = useRef(rightSidebarOpen);
const leftWidthRef = useRef(leftSidebarWidth);
const rightWidthRef = useRef(rightSidebarWidth);
const activeModel = props.models.find((model) => model.id === props.activeModelId);
const busy = props.streamState === 'loading' || props.streamState === 'streaming';
const resolvedTheme = resolveThemeMode(themeMode, systemDark);
const artifacts = useMemo(() => props.messages.flatMap((message) => message.artifacts ?? []), [props.messages]);
leftOpenRef.current = leftSidebarOpen;
rightOpenRef.current = rightSidebarOpen;
leftWidthRef.current = leftSidebarWidth;
rightWidthRef.current = rightSidebarWidth;
useEffect(() => {
const media = globalThis.matchMedia?.('(prefers-color-scheme: dark)');
if (!media) return;
const handleChange = (event: MediaQueryListEvent) => setSystemDark(event.matches);
setSystemDark(media.matches);
media.addEventListener('change', handleChange);
return () => media.removeEventListener('change', handleChange);
}, []);
useEffect(() => {
try {
globalThis.localStorage?.setItem(THEME_STORAGE_KEY, themeMode);
} catch {
// Theme still works for the current tab when storage is unavailable.
}
}, [themeMode]);
useEffect(() => {
const timer = window.setTimeout(() => {
try {
globalThis.localStorage?.setItem(SIDEBAR_LAYOUT_STORAGE_KEY, JSON.stringify({
leftWidth: leftSidebarWidth,
rightWidth: rightSidebarWidth,
leftOpen: leftSidebarOpen,
rightOpen: rightSidebarOpen,
} satisfies SidebarLayout));
} catch {
// Sidebar layout still works for the current tab when storage is unavailable.
}
}, 140);
return () => window.clearTimeout(timer);
}, [leftSidebarOpen, leftSidebarWidth, rightSidebarOpen, rightSidebarWidth]);
useEffect(() => {
const clampToViewport = () => {
const workspaceWidth = workspaceRef.current?.clientWidth ?? globalThis.innerWidth ?? 0;
if (workspaceWidth <= 820) return;
const available = Math.max(SIDEBAR_EXPAND_THRESHOLD * 2, workspaceWidth - MIN_CHAT_WIDTH);
const left = leftOpenRef.current ? leftWidthRef.current : 0;
const right = rightOpenRef.current ? rightWidthRef.current : 0;
if (left + right <= available) return;
const scale = available / (left + right);
if (leftOpenRef.current) setLeftSidebarWidth(Math.max(SIDEBAR_EXPAND_THRESHOLD, Math.floor(left * scale)));
if (rightOpenRef.current) setRightSidebarWidth(Math.max(SIDEBAR_EXPAND_THRESHOLD, Math.floor(right * scale)));
};
clampToViewport();
window.addEventListener('resize', clampToViewport);
return () => window.removeEventListener('resize', clampToViewport);
}, []);
useEffect(() => {
const themeColor = BROWSER_THEME_COLORS[resolvedTheme];
const meta = document.querySelector<HTMLMetaElement>('meta[name="theme-color"]');
const previousMetaColor = meta?.content;
const previousRootBackground = document.documentElement.style.backgroundColor;
const previousBodyBackground = document.body.style.backgroundColor;
const previousColorScheme = document.documentElement.style.colorScheme;
if (meta) meta.content = themeColor;
document.documentElement.style.backgroundColor = themeColor;
document.documentElement.style.colorScheme = resolvedTheme;
document.body.style.backgroundColor = themeColor;
return () => {
if (meta && previousMetaColor !== undefined) meta.content = previousMetaColor;
document.documentElement.style.backgroundColor = previousRootBackground;
document.documentElement.style.colorScheme = previousColorScheme;
document.body.style.backgroundColor = previousBodyBackground;
};
}, [resolvedTheme]);
if (!activeModel) {
throw new Error(`Active model ${props.activeModelId} is missing from the model catalog`);
}
const setSidebarOpen = (side: SidebarSide, open: boolean) => {
if (side === 'left') {
leftOpenRef.current = open;
setLeftSidebarOpen(open);
} else {
rightOpenRef.current = open;
setRightSidebarOpen(open);
}
};
const toggleSidebar = (side: SidebarSide) => {
setSidebarOpen(side, !(side === 'left' ? leftOpenRef.current : rightOpenRef.current));
};
const resizeMaximum = (side: SidebarSide, workspaceWidth: number): number => {
const large = workspaceWidth >= 2400;
const hardMaximum = side === 'left' ? (large ? 640 : 520) : (large ? 720 : 600);
const otherWidth = side === 'left'
? (rightOpenRef.current ? rightWidthRef.current : 0)
: (leftOpenRef.current ? leftWidthRef.current : 0);
return Math.max(
SIDEBAR_EXPAND_THRESHOLD,
Math.min(hardMaximum, workspaceWidth - otherWidth - MIN_CHAT_WIDTH),
);
};
const beginSidebarResize = (side: SidebarSide, event: PointerEvent<HTMLDivElement>) => {
if (event.pointerType === 'mouse' && event.button !== 0) return;
event.preventDefault();
event.currentTarget.setPointerCapture(event.pointerId);
dragRef.current = {
side,
pointerId: event.pointerId,
startX: event.clientX,
startWidth: side === 'left' ? leftWidthRef.current : rightWidthRef.current,
moved: false,
};
setResizingSide(side);
document.body.style.cursor = 'col-resize';
document.body.style.userSelect = 'none';
};
const moveSidebarResize = (event: PointerEvent<HTMLDivElement>) => {
const drag = dragRef.current;
const workspace = workspaceRef.current;
if (!drag || drag.pointerId !== event.pointerId || !workspace) return;
event.preventDefault();
if (Math.abs(event.clientX - drag.startX) > 2) drag.moved = true;
const rect = workspace.getBoundingClientRect();
const rawWidth = drag.side === 'left'
? event.clientX - rect.left
: rect.right - event.clientX;
const currentlyOpen = drag.side === 'left' ? leftOpenRef.current : rightOpenRef.current;
const next = resolveSidebarDrag(rawWidth, currentlyOpen, resizeMaximum(drag.side, rect.width));
setSidebarOpen(drag.side, next.open);
if (next.open) {
if (drag.side === 'left') {
leftWidthRef.current = next.width;
setLeftSidebarWidth(next.width);
} else {
rightWidthRef.current = next.width;
setRightSidebarWidth(next.width);
}
}
};
const endSidebarResize = (event: PointerEvent<HTMLDivElement>) => {
const drag = dragRef.current;
if (!drag || drag.pointerId !== event.pointerId) return;
if (event.currentTarget.hasPointerCapture(event.pointerId)) {
event.currentTarget.releasePointerCapture(event.pointerId);
}
const remainsOpen = drag.side === 'left' ? leftOpenRef.current : rightOpenRef.current;
if (!remainsOpen) {
if (drag.side === 'left') setLeftSidebarWidth(drag.startWidth);
else setRightSidebarWidth(drag.startWidth);
}
if (drag.moved) {
suppressClickRef.current = drag.side;
window.setTimeout(() => {
if (suppressClickRef.current === drag.side) suppressClickRef.current = null;
}, 0);
}
dragRef.current = null;
setResizingSide(null);
document.body.style.cursor = '';
document.body.style.userSelect = '';
};
const handleResizerClick = (side: SidebarSide) => {
if (suppressClickRef.current === side) {
suppressClickRef.current = null;
return;
}
toggleSidebar(side);
};
const handleResizerKeyDown = (side: SidebarSide, event: KeyboardEvent<HTMLDivElement>) => {
if (event.key === 'Enter' || event.key === ' ') {
event.preventDefault();
toggleSidebar(side);
return;
}
if (event.key === 'Home') {
event.preventDefault();
setSidebarOpen(side, false);
return;
}
if (event.key !== 'ArrowLeft' && event.key !== 'ArrowRight') return;
event.preventDefault();
const expanding = side === 'left' ? event.key === 'ArrowRight' : event.key === 'ArrowLeft';
const open = side === 'left' ? leftOpenRef.current : rightOpenRef.current;
if (!open) {
if (expanding) setSidebarOpen(side, true);
return;
}
const currentWidth = side === 'left' ? leftWidthRef.current : rightWidthRef.current;
const workspaceWidth = workspaceRef.current?.clientWidth ?? globalThis.innerWidth ?? 0;
const nextWidth = Math.min(
resizeMaximum(side, workspaceWidth),
currentWidth + (expanding ? RESIZE_STEP : -RESIZE_STEP),
);
if (nextWidth <= SIDEBAR_COLLAPSE_THRESHOLD) {
setSidebarOpen(side, false);
} else if (side === 'left') {
setLeftSidebarWidth(nextWidth);
} else {
setRightSidebarWidth(nextWidth);
}
};
const scrollToArtifact = (artifactId: string) => {
const artifact = document.getElementById(`artifact-${artifactId}`);
if (!artifact) return;
const reducedMotion = globalThis.matchMedia?.('(prefers-reduced-motion: reduce)').matches ?? false;
artifact.scrollIntoView({ behavior: reducedMotion ? 'auto' : 'smooth', block: 'center' });
artifact.focus({ preventScroll: true });
};
const workspaceStyle = {
'--model-rail-width': leftSidebarOpen ? `${leftSidebarWidth}px` : '0px',
'--inspector-width': rightSidebarOpen ? `${rightSidebarWidth}px` : '0px',
} as CSSProperties;
return (
<div className="station-frame" data-theme={resolvedTheme} data-theme-mode={themeMode}>
<Header
onOpenSettings={props.onOpenSettings}
disabled={busy}
leftSidebarOpen={leftSidebarOpen}
rightSidebarOpen={rightSidebarOpen}
chatWidth={chatWidth}
onToggleLeftSidebar={() => toggleSidebar('left')}
onToggleRightSidebar={() => toggleSidebar('right')}
onToggleChatWidth={() => setChatWidth((width) => width === 'centered' ? 'wide' : 'centered')}
/>
<div
ref={workspaceRef}
className={`workspace-grid layout-${chatWidth}${leftSidebarOpen ? '' : ' is-models-collapsed'}${rightSidebarOpen ? '' : ' is-inspector-collapsed'}${resizingSide ? ' is-resizing' : ''}`}
style={workspaceStyle}
>
<ModelRail
hidden={!leftSidebarOpen}
models={props.models}
activeModelId={props.activeModelId}
busy={busy}
onModelSelect={props.onModelSelect}
/>
{props.conversationListOpen ? <ConversationList
conversations={props.conversations}
activeConversationId={props.activeConversationId}
onNewConversation={props.onNewConversation}
onOpenConversation={props.onOpenConversation}
onOpenConversationSettings={props.onOpenConversationSettings}
onDeleteConversation={props.onDeleteConversation}
/> : <ChatSurface
activeModel={activeModel}
loadedModelId={props.loadedModelId}
messages={props.messages}
streamState={props.streamState}
modelLoadProgress={props.modelLoadProgress}
toolsEnabled={props.toolsEnabled}
runtimeStatus={props.runtimeStatus}
error={props.error}
shardRetry={props.shardRetry}
theme={resolvedTheme}
onLoadModel={props.onLoadModel}
onDismissError={props.onDismissError}
onRetryShard={props.onRetryShard}
onSend={props.onSend}
onRegenerate={props.onRegenerate}
onEditUserMessage={props.onEditUserMessage}
onCancel={props.onCancel}
onToolsEnabledChange={props.onToolsEnabledChange}
onOpenConversationList={props.onOpenConversationList}
onOpenSettings={props.onOpenSettings}
/>}
<InspectorPanel
hidden={!rightSidebarOpen}
telemetry={props.telemetry}
toolEvents={props.toolEvents}
artifacts={artifacts}
onSelectArtifact={scrollToArtifact}
/>
<SidebarResizer
side="left"
open={leftSidebarOpen}
width={leftSidebarWidth}
onPointerDown={(event) => beginSidebarResize('left', event)}
onPointerMove={moveSidebarResize}
onPointerUp={endSidebarResize}
onPointerCancel={endSidebarResize}
onClick={() => handleResizerClick('left')}
onKeyDown={(event) => handleResizerKeyDown('left', event)}
/>
<SidebarResizer
side="right"
open={rightSidebarOpen}
width={rightSidebarWidth}
onPointerDown={(event) => beginSidebarResize('right', event)}
onPointerMove={moveSidebarResize}
onPointerUp={endSidebarResize}
onPointerCancel={endSidebarResize}
onClick={() => handleResizerClick('right')}
onKeyDown={(event) => handleResizerKeyDown('right', event)}
/>
</div>
<SettingsSheet
open={props.settingsOpen}
themeMode={themeMode}
onThemeModeChange={setThemeMode}
activeModel={activeModel}
telemetry={props.telemetry}
settings={props.settings}
onSettingsChange={props.onSettingsChange}
onPersistStorage={props.onPersistStorage}
modelLoaded={props.loadedModelId !== null}
onUnloadModel={props.onUnloadModel}
onClearStorage={props.onClearStorage}
onClearConversation={props.onClearConversation}
onClose={props.onCloseSettings}
/>
</div>
);
}
interface SidebarResizerProps {
side: SidebarSide;
open: boolean;
width: number;
onPointerDown: (event: PointerEvent<HTMLDivElement>) => void;
onPointerMove: (event: PointerEvent<HTMLDivElement>) => void;
onPointerUp: (event: PointerEvent<HTMLDivElement>) => void;
onPointerCancel: (event: PointerEvent<HTMLDivElement>) => void;
onClick: () => void;
onKeyDown: (event: KeyboardEvent<HTMLDivElement>) => void;
}
function SidebarResizer({
side,
open,
width,
onPointerDown,
onPointerMove,
onPointerUp,
onPointerCancel,
onClick,
onKeyDown,
}: SidebarResizerProps) {
const label = `${open ? 'Resize or collapse' : 'Expand'} ${side === 'left' ? 'model' : 'telemetry'} sidebar`;
const arrow = side === 'left' ? (open ? '‹' : '›') : (open ? '›' : '‹');
return (
<div
className={`sidebar-resizer sidebar-resizer-${side}${open ? '' : ' is-collapsed'}`}
role="separator"
aria-label={label}
aria-orientation="vertical"
aria-valuemin={0}
aria-valuemax={800}
aria-valuenow={open ? width : 0}
tabIndex={0}
title={label}
onPointerDown={onPointerDown}
onPointerMove={onPointerMove}
onPointerUp={onPointerUp}
onPointerCancel={onPointerCancel}
onClick={onClick}
onKeyDown={onKeyDown}
>
<span className="sidebar-resizer-line" aria-hidden="true" />
<span className="sidebar-resizer-tab" aria-hidden="true">{arrow}</span>
</div>
);
}
|