2026-06-06 19:49:33 +08:00
import {
2026-07-22 22:35:39 +08:00
lazy ,
Suspense ,
2026-06-06 19:49:33 +08:00
useCallback ,
useEffect ,
useMemo ,
useRef ,
useState ,
type ReactNode ,
} from "react" ;
2026-09-14 11:13:40 +08:00
import { ArrowRight , ChevronDown , Eye , EyeOff , Moon , ShieldCheck , Sun , X } from "lucide-react" ;
import { Trans , useTranslation } from "react-i18next" ;
2026-07-19 23:30:49 +08:00
import { channelUiPresentation } from "@/channel-plugins/registry" ;
2026-09-24 15:37:18 +08:00
import { StarPrompt } from "@/components/StarPrompt" ;
2026-04-18 18:51:53 +00:00
import { Sidebar } from "@/components/Sidebar" ;
2026-10-13 13:56:28 +08:00
import { RemoteInstances } from "@/components/remote/RemoteInstances" ;
import { useRemoteConnections } from "@/components/remote/remote-context" ;
2026-09-27 20:51:49 +08:00
import { RemoteConnectionsPage } from "@/components/remote/RemoteConnectionsPage" ;
2026-09-14 11:13:40 +08:00
import { LanguageSwitcher } from "@/components/LanguageSwitcher" ;
2026-09-10 11:10:51 +08:00
import { SidebarResizeHandle , SIDEBAR_MIN_WIDTH , SIDEBAR_MAX_WIDTH } from "@/components/SidebarResizeHandle" ;
import { matchSidebarShortcut } from "@/lib/sidebar-shortcuts" ;
2026-08-12 14:45:12 +08:00
import type { SidebarDeleteItem } from "@/components/ChatList" ;
2026-07-22 22:35:39 +08:00
import type { SettingsSectionKey } from "@/components/settings/SettingsView" ;
2026-09-24 23:10:57 +08:00
import { StartupShell } from "@/components/StartupShell" ;
2026-09-25 23:42:01 +08:00
import { ComposerDraftStore , clearStoredComposerDrafts } from "@/lib/composer-draft" ;
2026-09-24 23:10:57 +08:00
import { activateReloadCache , clearReloadCache } from "@/lib/reload-cache" ;
import { webuiThreadCache } from "@/lib/webui-thread-cache" ;
2026-09-09 14:02:26 +08:00
import { ThreadVisibilityContext } from "@/hooks/useThreadVisibility" ;
2026-09-10 11:10:51 +08:00
import type { SettingsExitGuard } from "@/components/settings/contracts" ;
2026-08-12 14:45:12 +08:00
import { PaneWorkbench } from "@/components/workbench/PaneWorkbench" ;
import {
MAX_WORKBENCH_PANES ,
addWorkbenchPane ,
attachWorkbenchPane ,
createWorkbenchTab ,
detachWorkbenchPane ,
dissolveWorkbenchTab ,
orderWorkbenchTabs ,
reconcileWorkbench ,
renameWorkbenchTab ,
setWorkbenchLayout ,
setWorkbenchPaneLayoutOrder ,
setWorkbenchSplitRatios ,
workbenchTab ,
workbenchTabForPane ,
type WorkbenchState ,
} from "@/components/workbench/workbench-model" ;
2026-08-05 13:24:45 +08:00
import { floatingSurfaceElevationClassName } from "@/components/ui/floating-surface" ;
2026-05-19 22:42:38 +08:00
import { Sheet , SheetContent , SheetTitle } from "@/components/ui/sheet" ;
2026-05-14 16:02:31 +08:00
2026-04-18 18:51:53 +00:00
import { useSessions } from "@/hooks/useSessions" ;
2026-10-16 11:38:05 +08:00
import { useReconnectRuns } from "@/hooks/useReconnectRuns" ;
2026-05-17 17:04:57 +08:00
import { useDeferredTitleRefresh } from "@/hooks/useDeferredTitleRefresh" ;
2026-05-19 22:42:38 +08:00
import { useSidebarState } from "@/hooks/useSidebarState" ;
2026-06-06 19:49:33 +08:00
import { useSkills } from "@/hooks/useSkills" ;
2026-07-13 13:11:46 +08:00
import { useLogoFallback } from "@/hooks/useLogoFallback" ;
2026-07-22 22:35:39 +08:00
import { usePageVisibility } from "@/hooks/usePageVisibility" ;
2026-08-12 14:45:12 +08:00
import { useMediaQuery } from "@/hooks/useMediaQuery" ;
2026-10-04 00:09:49 +08:00
import { useAppViewport } from "@/hooks/useAppViewport" ;
2026-09-12 16:32:46 +08:00
import type { SendAttachment , SendOptions } from "@/hooks/useNanobotStream" ;
2026-05-17 17:04:57 +08:00
import { ThemeProvider , useTheme } from "@/hooks/useTheme" ;
2026-07-13 13:11:46 +08:00
import { logoFallbackUrls } from "@/lib/provider-brand" ;
2026-04-18 18:51:53 +00:00
import { cn } from "@/lib/utils" ;
2026-05-06 23:15:18 +08:00
import {
2026-07-08 15:46:52 +08:00
BootstrapAuthRequiredError ,
2026-05-06 23:15:18 +08:00
clearSavedSecret ,
2026-07-08 14:27:52 +08:00
consumeUrlBootstrapSecret ,
2026-05-06 23:15:18 +08:00
deriveWsUrl ,
fetchBootstrap ,
loadSavedSecret ,
saveSecret ,
} from "@/lib/bootstrap" ;
2026-08-12 14:45:12 +08:00
import { displayTitle , sortSessions } from "@/lib/chat-groups" ;
2026-05-17 23:52:50 +08:00
import { deriveTitle } from "@/lib/format" ;
2026-04-18 18:51:53 +00:00
import { NanobotClient } from "@/lib/nanobot-client" ;
2026-09-21 00:41:00 +08:00
import { ThreadMessageCache } from "@/lib/thread-message-cache" ;
2026-09-21 17:48:49 +08:00
import { FilePreviewStore } from "@/hooks/useFilePreviewState" ;
2026-05-08 09:40:15 +00:00
import { ClientProvider , useClient } from "@/providers/ClientProvider" ;
2026-05-29 03:42:53 +08:00
import type {
2026-07-14 14:47:42 +08:00
BootstrapResponse ,
2026-05-29 03:42:53 +08:00
ChatSummary ,
RuntimeSurface ,
2026-07-13 13:11:46 +08:00
PairingRequestInfo ,
2026-06-11 19:11:37 +08:00
SessionAutomationJob ,
2026-05-29 03:42:53 +08:00
SettingsPayload ,
WorkspaceScopePayload ,
WorkspacesPayload ,
} from "@/lib/types" ;
2026-05-06 23:15:18 +08:00
import { Button } from "@/components/ui/button" ;
import { Input } from "@/components/ui/input" ;
2026-09-14 11:13:40 +08:00
import { Disclosure } from "@/components/ui/disclosure" ;
2026-07-13 13:11:46 +08:00
import {
fetchPairingRequests ,
fetchSettings ,
fetchWorkspaces ,
runPairingAction ,
} from "@/lib/api" ;
2026-05-29 03:42:53 +08:00
import {
createRuntimeHost ,
2026-09-03 08:59:49 +08:00
isNativeRuntime ,
2026-05-29 03:42:53 +08:00
toRuntimeSurface ,
} from "@/lib/runtime" ;
2026-08-05 19:24:41 +08:00
import { projectNameFromPath , scopeWithAccessMode } from "@/lib/workspace" ;
import {
createTemporaryChatSession ,
2026-08-07 13:27:53 +08:00
deriveTemporaryChatTitle ,
2026-08-05 19:24:41 +08:00
} from "@/lib/temporary-chat" ;
2026-04-18 18:51:53 +00:00
type BootState =
| { status : "loading" }
| { status : "error" ; message : string }
2026-05-06 23:15:18 +08:00
| { status : "auth" ; failed? : boolean }
2026-04-18 18:51:53 +00:00
| {
status : "ready" ;
client : NanobotClient ;
token : string ;
2026-08-02 00:38:17 +09:00
tokenExpiresAt : number | null ;
2026-04-18 18:51:53 +00:00
modelName : string | null ;
2026-07-14 14:47:42 +08:00
ingressLimits : BootstrapResponse [ "limits" ] | null ;
2026-05-29 03:42:53 +08:00
runtimeSurface : RuntimeSurface ;
2026-10-05 05:16:33 +08:00
webuiCapabilities : string [];
2026-04-18 18:51:53 +00:00
};
2026-10-05 05:16:33 +08:00
function bootstrapCapabilities ( boot : BootstrapResponse ) : string [] {
const capabilities = boot . terminal ? . webui ? . capabilities ;
return Array . isArray ( capabilities ) ? capabilities . filter (( entry ) => typeof entry === "string" ) : [];
}
2026-04-18 18:51:53 +00:00
const SIDEBAR_STORAGE_KEY = "nanobot-webui.sidebar" ;
2026-06-15 17:30:06 +08:00
const SESSION_UPDATES_STORAGE_KEY = "nanobot-webui.sidebar.session-updates.v1" ;
const LEGACY_COMPLETED_RUNS_STORAGE_KEY = "nanobot-webui.sidebar.completed-runs.v1" ;
2026-05-08 09:40:15 +00:00
const RESTART_STARTED_KEY = "nanobot-webui.restartStartedAt" ;
2026-07-13 13:11:46 +08:00
const RESTART_ROUTE_KEY = "nanobot-webui.restartRoute" ;
const RESTART_ROUTE_TTL_MS = 5 * 60 * 1000 ;
2026-05-06 14:15:36 +00:00
const SIDEBAR_WIDTH = 272 ;
2026-09-10 11:10:51 +08:00
const SIDEBAR_WIDTH_STORAGE_KEY = "nanobot-webui.sidebar.width" ;
2026-05-22 00:31:55 +08:00
const SIDEBAR_RAIL_WIDTH = 56 ;
2026-06-14 16:46:34 +08:00
const MOBILE_SIDEBAR_WIDTH = `min( ${ SIDEBAR_WIDTH } px, calc(100vw - 0.75rem))` ;
2026-05-18 00:53:36 +08:00
const TOKEN_REFRESH_MARGIN_MS = 30 _000 ;
const TOKEN_REFRESH_MIN_DELAY_MS = 5 _000 ;
2026-07-13 13:11:46 +08:00
const PAIRING_POLL_INTERVAL_MS = 5 _000 ;
2026-07-22 22:35:39 +08:00
const PAIRING_IDLE_POLL_INTERVAL_MS = 15 _000 ;
2026-07-13 13:11:46 +08:00
const PAIRING_DISMISS_SNOOZE_MS = 30 _000 ;
2026-09-27 20:51:49 +08:00
type ShellView = "chat" | "settings" | "apps" | "automations" | "skills" | "channels" | "remote" ;
2026-06-02 11:29:18 +08:00
type ShellRoute = {
view : ShellView ;
activeKey : string | null ;
settingsSection : SettingsSectionKey ;
2026-08-07 11:20:08 +08:00
temporary? : boolean ;
2026-06-02 11:29:18 +08:00
};
2026-09-24 23:10:57 +08:00
const loadThreadShell = () => import ( "@/components/thread/ThreadShell" );
const ThreadShell = lazy (() => loadThreadShell (). then (
2026-09-09 14:02:26 +08:00
( module ) => ({ default : module . ThreadShell }),
));
2026-07-22 22:35:39 +08:00
const loadSettingsView = () => import ( "@/components/settings/SettingsView" );
const SettingsView = lazy ( async () => {
const module = await loadSettingsView ();
return { default : module . SettingsView };
});
const SessionSearchDialog = lazy ( async () => {
const module = await import ( "@/components/SessionSearchDialog" );
return { default : module . SessionSearchDialog };
});
const DeleteConfirm = lazy ( async () => {
const module = await import ( "@/components/DeleteConfirm" );
return { default : module . DeleteConfirm };
});
const RenameChatDialog = lazy ( async () => {
const module = await import ( "@/components/RenameChatDialog" );
return { default : module . RenameChatDialog };
});
2026-09-09 14:02:26 +08:00
function SurfaceLoadingFallback ({ label } : { label? : string }) {
2026-08-03 16:03:31 +08:00
const { t } = useTranslation ();
2026-07-22 22:35:39 +08:00
return (
< div
aria-busy = "true"
className = "flex h-full w-full flex-col gap-5 px-5 py-8 sm:px-8 lg:px-12"
>
2026-09-09 14:02:26 +08:00
< span className = "sr-only" >{ label ?? t ( "settings.status.loading" )}</ span >
2026-07-22 22:35:39 +08:00
< div className = "h-4 w-20 animate-pulse rounded bg-muted/70 motion-reduce:animate-none" />
< div className = "h-9 w-48 animate-pulse rounded bg-muted/70 motion-reduce:animate-none" />
< div className = "mt-4 h-12 w-full max-w-3xl animate-pulse rounded-md bg-muted/55 motion-reduce:animate-none" />
< div className = "h-28 w-full max-w-3xl animate-pulse rounded-md bg-muted/40 motion-reduce:animate-none" />
</ div >
);
}
2026-06-02 11:29:18 +08:00
const SETTINGS_SECTION_KEYS : SettingsSectionKey [] = [
2026-09-10 11:10:51 +08:00
"capabilities" ,
2026-06-02 11:29:18 +08:00
"overview" ,
2026-09-10 11:10:51 +08:00
"about" ,
2026-06-02 11:29:18 +08:00
"appearance" ,
"models" ,
"image" ,
2026-06-09 01:08:49 +08:00
"voice" ,
2026-06-02 11:29:18 +08:00
"browser" ,
2026-07-13 13:11:46 +08:00
"channels" ,
2026-06-02 11:29:18 +08:00
"apps" ,
2026-06-13 20:08:18 +08:00
"automations" ,
2026-09-10 11:10:51 +08:00
"memory" ,
2026-06-06 19:49:33 +08:00
"skills" ,
2026-06-02 11:29:18 +08:00
"runtime" ,
"advanced" ,
];
function isSettingsSectionKey ( value : string | null ) : value is SettingsSectionKey {
return SETTINGS_SECTION_KEYS . includes ( value as SettingsSectionKey );
}
function defaultShellRoute () : ShellRoute {
return { view : "chat" , activeKey : null , settingsSection : "overview" };
}
2026-06-06 19:49:33 +08:00
function shellViewForSettingsSection ( section : SettingsSectionKey ) : ShellView {
2026-09-10 11:10:51 +08:00
if ( section === "apps" || section === "automations" || section === "skills" || section === "channels" ) return section ;
2026-06-06 19:49:33 +08:00
return "settings" ;
}
2026-07-13 13:11:46 +08:00
function fallbackRestartHash ( hash : string ) : boolean {
return ! hash || hash === "/" || hash === "/new" ;
}
function rememberRestartRoute () : void {
if ( typeof window === "undefined" ) return ;
try {
window . localStorage . setItem ( RESTART_ROUTE_KEY , window . location . hash || "#/new" );
} catch {
// ignore storage errors
}
}
function maybeRestoreRestartHash ( hash : string ) : string {
if ( typeof window === "undefined" || ! fallbackRestartHash ( hash )) return hash ;
try {
const startedAt = Number ( window . localStorage . getItem ( RESTART_STARTED_KEY ) ?? "0" );
const storedHash = window . localStorage . getItem ( RESTART_ROUTE_KEY );
if ( ! startedAt || ! storedHash || Date . now () - startedAt > RESTART_ROUTE_TTL_MS ) {
window . localStorage . removeItem ( RESTART_ROUTE_KEY );
return hash ;
}
window . localStorage . removeItem ( RESTART_ROUTE_KEY );
const nextHash = storedHash . startsWith ( "#" ) ? storedHash : `# ${ storedHash } ` ;
window . history . replaceState (
null ,
"" ,
` ${ window . location . pathname }${ window . location . search }${ nextHash } ` ,
);
return nextHash . slice ( 1 );
} catch {
return hash ;
}
}
2026-06-02 11:29:18 +08:00
function readShellRoute () : ShellRoute {
if ( typeof window === "undefined" ) return defaultShellRoute ();
2026-07-13 13:11:46 +08:00
const currentHash = window . location . hash . startsWith ( "#" )
2026-06-02 11:29:18 +08:00
? window . location . hash . slice ( 1 )
: window . location . hash ;
2026-07-13 13:11:46 +08:00
const hash = maybeRestoreRestartHash ( currentHash );
2026-06-02 11:29:18 +08:00
if ( ! hash || hash === "/" || hash === "/new" ) return defaultShellRoute ();
const [ path , query = "" ] = hash . split ( "?" , 2 );
const params = new URLSearchParams ( query );
const rawSettingsSection = params . get ( "section" );
const settingsSection = isSettingsSectionKey ( rawSettingsSection )
? rawSettingsSection
: "overview" ;
2026-09-25 00:01:12 +08:00
const saved : unknown = window . history . state ? . nanobotReturnChat ;
const returnChat = saved && typeof saved === "object" && "hash" in saved
&& saved . hash === window . location . hash ? saved : null ;
const activeKey = params . get ( "chat" ) ? . trim ()
|| ( returnChat && "key" in returnChat && typeof returnChat . key === "string"
? returnChat.key : null );
const temporary = Boolean ( returnChat && "temporary" in returnChat && returnChat . temporary === true );
2026-06-02 11:29:18 +08:00
if ( path === "/settings" ) {
2026-06-06 19:49:33 +08:00
return {
view : shellViewForSettingsSection ( settingsSection ),
activeKey ,
2026-09-25 00:01:12 +08:00
temporary ,
2026-06-06 19:49:33 +08:00
settingsSection ,
};
2026-06-02 11:29:18 +08:00
}
if ( path === "/apps" ) {
2026-09-25 00:01:12 +08:00
return { view : "apps" , activeKey , temporary , settingsSection : "apps" };
2026-06-02 11:29:18 +08:00
}
2026-06-13 20:08:18 +08:00
if ( path === "/automations" ) {
2026-09-25 00:01:12 +08:00
return { view : "automations" , activeKey , temporary , settingsSection : "automations" };
2026-06-13 20:08:18 +08:00
}
2026-09-10 11:10:51 +08:00
if ( path === "/channels" ) {
2026-09-25 00:01:12 +08:00
return { view : "channels" , activeKey , temporary , settingsSection : "channels" };
2026-09-10 11:10:51 +08:00
}
2026-09-27 20:51:49 +08:00
if ( path === "/remote" ) {
return { view : "remote" , activeKey , temporary , settingsSection : "overview" };
}
2026-06-06 19:49:33 +08:00
if ( path === "/skills" ) {
2026-09-25 00:01:12 +08:00
return { view : "skills" , activeKey , temporary , settingsSection : "skills" };
2026-06-06 19:49:33 +08:00
}
2026-08-06 18:29:04 +08:00
if ( path . startsWith ( "/temporary/" )) {
const encoded = path . slice ( "/temporary/" . length );
try {
const chatId = decodeURIComponent ( encoded ). trim ();
2026-08-07 11:20:08 +08:00
return chatId
2026-08-06 18:29:04 +08:00
? {
view : "chat" ,
activeKey : `websocket: ${ chatId } ` ,
settingsSection : "overview" ,
2026-08-07 11:20:08 +08:00
temporary : true ,
2026-08-06 18:29:04 +08:00
}
: defaultShellRoute ();
} catch {
return defaultShellRoute ();
}
2026-08-05 19:24:41 +08:00
}
2026-06-02 11:29:18 +08:00
if ( path . startsWith ( "/chat/" )) {
const encoded = path . slice ( "/chat/" . length );
try {
const key = decodeURIComponent ( encoded ). trim ();
return key
? { view : "chat" , activeKey : key , settingsSection : "overview" }
: defaultShellRoute ();
} catch {
return defaultShellRoute ();
}
}
return defaultShellRoute ();
}
function shellRouteHash ( route : ShellRoute ) : string {
if ( route . view === "chat" ) {
2026-08-07 11:20:08 +08:00
if ( route . temporary && route . activeKey ? . startsWith ( "websocket:" )) {
const chatId = route . activeKey . slice ( "websocket:" . length );
return `#/temporary/ ${ encodeURIComponent ( chatId ) } ` ;
}
2026-06-02 11:29:18 +08:00
return route . activeKey
? `#/chat/ ${ encodeURIComponent ( route . activeKey ) } `
: "#/new" ;
}
const params = new URLSearchParams ();
if ( route . view === "settings" && route . settingsSection !== "overview" ) {
params . set ( "section" , route . settingsSection );
}
const query = params . toString ();
return `#/ ${ route . view }${ query ? `? ${ query } ` : "" } ` ;
}
function writeShellRoute ( route : ShellRoute , replace = false ) : void {
if ( typeof window === "undefined" ) return ;
const nextHash = shellRouteHash ( route );
2026-09-25 00:01:12 +08:00
const state = {
... window . history . state ,
nanobotReturnChat : route.view === "chat" ? null : {
hash : nextHash ,
key : route.activeKey ,
temporary : route.temporary === true ,
},
};
const url = ` ${ window . location . pathname }${ window . location . search }${ nextHash } ` ;
if ( replace || window . location . hash === nextHash ) {
window . history . replaceState ( state , "" , url );
} else {
window . history . pushState ( state , "" , url );
2026-06-02 11:29:18 +08:00
}
}
2026-04-18 18:51:53 +00:00
2026-05-18 00:53:36 +08:00
function bootstrapTokenExpiresAt ( expiresInSeconds : number ) : number {
return Date . now () + Math . max ( 0 , expiresInSeconds ) * 1000 ;
}
function tokenRefreshDelayMs ( expiresAt : number ) : number {
const remaining = Math . max ( 0 , expiresAt - Date . now ());
const margin = Math . min (
TOKEN_REFRESH_MARGIN_MS ,
Math . max ( 1 _000 , remaining / 2 ),
);
return Math . max ( TOKEN_REFRESH_MIN_DELAY_MS , remaining - margin );
}
2026-05-06 23:15:18 +08:00
function AuthForm ({
failed ,
onSecret ,
} : {
failed : boolean ;
onSecret : ( secret : string ) => void ;
}) {
const { t } = useTranslation ();
2026-08-10 15:22:25 +08:00
const inputRef = useRef < HTMLInputElement >( null );
2026-05-06 23:15:18 +08:00
const [ value , setValue ] = useState ( "" );
2026-08-10 15:22:25 +08:00
const [ passwordVisible , setPasswordVisible ] = useState ( false );
2026-05-06 23:15:18 +08:00
const [ submitting , setSubmitting ] = useState ( false );
2026-08-10 15:22:25 +08:00
const [ validationError , setValidationError ] = useState < "required" | "invalid" | null > (
failed ? "invalid" : null ,
);
const errorMessage = validationError ? t ( `app.auth. ${ validationError } ` ) : null ;
2026-05-06 23:15:18 +08:00
2026-09-14 11:13:40 +08:00
useEffect (() => {
if ( ! validationError ) return ;
const timeout = window . setTimeout (() => setValidationError ( null ), 3 _000 );
return () => window . clearTimeout ( timeout );
}, [ validationError ]);
2026-05-06 23:15:18 +08:00
const handleSubmit = ( e : React.FormEvent ) => {
e . preventDefault ();
const secret = value . trim ();
2026-08-10 15:22:25 +08:00
if ( ! secret ) {
2026-09-14 11:13:40 +08:00
setValue ( "" );
2026-08-10 15:22:25 +08:00
setValidationError ( "required" );
inputRef . current ? . focus ();
return ;
}
2026-05-06 23:15:18 +08:00
setSubmitting ( true );
onSecret ( secret );
};
return (
2026-09-14 11:13:40 +08:00
< main className = "flex h-full w-full flex-col overflow-y-auto bg-background" >
< div className = "mx-5 mt-5 shrink-0 self-end sm:mx-8" >
< LanguageSwitcher className = "h-8 min-w-0 gap-2 px-3 text-xs" />
</ div >
< div className = "flex flex-1 shrink-0 items-center justify-center px-6 pb-20 pt-8" >
< section
aria-labelledby = "webui-auth-title"
className = "w-full max-w-xs"
2026-05-06 23:15:18 +08:00
>
2026-09-14 11:13:40 +08:00
< div className = "text-center" >
< img
src = "/brand/nanobot_mark.svg"
alt = ""
width = { 56 }
height = { 56 }
draggable = { false }
className = "mx-auto mb-5 h-14 w-14 select-none"
/>
< h1 id = "webui-auth-title" className = "text-balance text-2xl font-semibold tracking-tight text-foreground sm:text-[1.75rem]" >
{ t ( "app.auth.title" )}
</ h1 >
</ div >
< form onSubmit = { handleSubmit } className = "mt-8" >
< div className = "relative" >
< Input
ref = { inputRef }
id = "webui-access-password"
name = "webui-access-password"
aria-label = { t ( "app.auth.label" )}
type = { passwordVisible ? "text" : "password" }
autoComplete = "current-password"
value = { value }
onChange = {( e ) => {
setValue ( e . target . value );
setValidationError ( null );
}}
disabled = { submitting }
aria-invalid = { validationError ? true : undefined }
aria-describedby = { validationError ? "webui-auth-error" : undefined }
placeholder = { errorMessage ?? undefined }
className = { cn (
"h-12 rounded-full border-foreground/15 bg-muted/30 px-4 pr-24 text-base" ,
validationError && "placeholder:text-[13px] placeholder:text-red-600 dark:placeholder:text-red-400" ,
)}
autoFocus
/>
< Button
type = "button"
variant = "ghost"
size = "icon"
disabled = { submitting }
aria-label = { t (
passwordVisible ? "app.auth.hidePassword" : "app.auth.showPassword" ,
)}
aria-controls = "webui-access-password"
onClick = {() => setPasswordVisible (( visible ) => ! visible )}
className = "absolute right-12 top-1/2 h-10 w-10 -translate-y-1/2 rounded-full text-muted-foreground hover:text-foreground"
>
{ passwordVisible ? (
< EyeOff className = "h-4 w-4" strokeWidth = { 1.75 } aria - hidden />
) : (
< Eye className = "h-4 w-4" strokeWidth = { 1.75 } aria - hidden />
)}
</ Button >
< Button
type = "submit"
variant = "ghost"
size = "icon"
disabled = { submitting }
aria-label = { t ( "app.auth.submit" )}
title = { t ( "app.auth.submit" )}
className = "absolute right-1 top-1/2 h-10 w-10 -translate-y-1/2 rounded-full"
>
< ArrowRight className = "h-4 w-4" strokeWidth = { 1.75 } aria - hidden />
</ Button >
</ div >
{ errorMessage ? (
< p id = "webui-auth-error" role = "alert" className = "sr-only" >
{ errorMessage }
</ p >
) : null }
</ form >
< Disclosure
className = "mt-4"
summaryClassName = "flex min-h-11 items-center justify-center gap-1.5 rounded-compact text-[13px] text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/50"
contentClassName = "rounded-control bg-muted/50 p-4 text-sm leading-6 text-muted-foreground"
summary = {(
<>
< span >{ t ( "app.auth.helpTitle" )}</ span >
< ChevronDown className = "h-3.5 w-3.5 shrink-0 transition-transform group-data-[state=open]/disclosure:rotate-180 motion-reduce:transition-none" strokeWidth = { 1.5 } aria - hidden />
</>
)}
>
< p >{ t ( "app.auth.helpConfig" )}</ p >
< code className = "mt-2 block rounded-compact bg-background px-3 py-2 font-mono text-xs text-foreground [overflow-wrap:anywhere]" >
~ /.nanobot/config.json
</ code >
< p className = "mt-4" >{ t ( "app.auth.helpSecret" )}</ p >
< code className = "mt-2 block rounded-compact bg-background px-3 py-2 font-mono text-xs text-foreground [overflow-wrap:anywhere]" >
channels . websocket . tokenIssueSecret
</ code >
< p className = "mt-3" >
< Trans
i18nKey = "app.auth.helpFallback"
components = {{ code : < code className = "font-mono text-xs text-foreground [overflow-wrap:anywhere]" /> }}
/>
</ p >
</ Disclosure >
</ section >
</ div >
</ main >
2026-05-06 23:15:18 +08:00
);
}
2026-09-10 11:10:51 +08:00
function readSidebarWidth () : number {
try {
const width = Number ( window . localStorage . getItem ( SIDEBAR_WIDTH_STORAGE_KEY ));
return Number . isFinite ( width ) && width >= SIDEBAR_MIN_WIDTH
? Math . min ( SIDEBAR_MAX_WIDTH , width ) : SIDEBAR_WIDTH ;
} catch {
return SIDEBAR_WIDTH ;
}
}
2026-04-18 18:51:53 +00:00
function readSidebarOpen () : boolean {
if ( typeof window === "undefined" ) return true ;
try {
const raw = window . localStorage . getItem ( SIDEBAR_STORAGE_KEY );
if ( raw === null ) return true ;
return raw === "1" ;
} catch {
return true ;
}
}
2026-06-15 17:30:06 +08:00
function readSessionUpdateChatIds () : Set < string > {
2026-05-19 22:42:38 +08:00
if ( typeof window === "undefined" ) return new Set ();
try {
2026-06-15 17:30:06 +08:00
const raw =
window . localStorage . getItem ( SESSION_UPDATES_STORAGE_KEY )
?? window . localStorage . getItem ( LEGACY_COMPLETED_RUNS_STORAGE_KEY );
2026-05-19 22:42:38 +08:00
const parsed = raw ? JSON . parse ( raw ) : [];
if ( ! Array . isArray ( parsed )) return new Set ();
return new Set ( parsed . filter (( item ) : item is string => typeof item === "string" ));
} catch {
return new Set ();
}
}
2026-06-15 17:30:06 +08:00
function writeSessionUpdateChatIds ( chatIds : Set < string >) : void {
2026-05-19 22:42:38 +08:00
try {
window . localStorage . setItem (
2026-06-15 17:30:06 +08:00
SESSION_UPDATES_STORAGE_KEY ,
2026-05-19 22:42:38 +08:00
JSON . stringify ( Array . from ( chatIds )),
);
} catch {
// ignore storage errors (private mode, etc.)
}
}
2026-05-29 03:42:53 +08:00
function normalizeWorkspaceScope ( scope : WorkspaceScopePayload ) : WorkspaceScopePayload {
const accessMode = scope . access_mode === "restricted" ? "restricted" : "full" ;
return {
... scope ,
project_name : scope.project_name ?? projectNameFromPath ( scope . project_path ),
access_mode : accessMode ,
restrict_to_workspace : accessMode === "restricted" ,
};
}
2026-07-08 15:46:52 +08:00
function isBootstrapAuthRequired ( error : unknown ) : boolean {
if ( error instanceof BootstrapAuthRequiredError ) return true ;
const msg = error instanceof Error ? error.message : String ( error );
return msg . includes ( "HTTP 401" ) || msg . includes ( "HTTP 403" );
}
2026-05-29 03:42:53 +08:00
function HostChrome ({
2026-06-06 19:49:33 +08:00
rightAction ,
2026-05-29 03:42:53 +08:00
} : {
2026-06-06 19:49:33 +08:00
rightAction? : ReactNode ;
2026-05-29 03:42:53 +08:00
}) {
return (
2026-06-06 19:49:33 +08:00
< header className = "host-drag-region pointer-events-none absolute inset-x-0 top-0 z-40 h-11 bg-transparent text-foreground/90" >
{ rightAction ? (
< div className = "host-no-drag pointer-events-auto absolute right-3 top-2" >
{ rightAction }
</ div >
) : null }
2026-05-29 03:42:53 +08:00
</ header >
);
}
2026-07-13 13:11:46 +08:00
function PairingCodePopup ({
requests ,
total ,
busyCode ,
error ,
onApprove ,
onDismiss ,
} : {
requests : PairingRequestInfo [];
total : number ;
busyCode : string | null ;
error : string | null ;
onApprove : ( code : string ) => void ;
2026-10-11 18:31:50 +08:00
onDismiss : ( request : PairingRequestInfo ) => void ;
2026-07-13 13:11:46 +08:00
}) {
const { t } = useTranslation ();
const [ value , setValue ] = useState ( "" );
2026-10-11 18:31:50 +08:00
const attemptedCode = useRef < string | null >( null );
2026-07-13 13:11:46 +08:00
const normalizedCode = normalizePairingCode ( value );
const matchedRequest = useMemo (
() => requests . find (( request ) => request . code === normalizedCode ) ?? null ,
[ normalizedCode , requests ],
);
2026-10-11 18:15:39 +08:00
// Keep delivered and legacy requests usable even when another bot cannot reply.
const firstRequest = requests . find (( request ) => (
! request . delivery_status || request . delivery_status === "sent"
)) ?? requests [ 0 ] ?? null ;
2026-07-13 13:11:46 +08:00
const displayRequest = matchedRequest ?? firstRequest ;
2026-10-11 18:15:39 +08:00
const deliveryBlocked = displayRequest ? . delivery_status === "failed"
|| displayRequest ? . delivery_status === "sending" ;
const expires = formatPairingExpiry ( displayRequest ? . expires_in_seconds );
2026-07-13 13:11:46 +08:00
const isCompleteCode = normalizedCode . length === 9 ;
const showNoMatch = isCompleteCode && ! matchedRequest && ! busyCode ;
useEffect (() => {
2026-10-11 18:31:50 +08:00
if ( ! matchedRequest || busyCode || attemptedCode . current === matchedRequest . code ) return ;
attemptedCode . current = matchedRequest . code ;
2026-07-13 13:11:46 +08:00
onApprove ( matchedRequest . code );
}, [ busyCode , matchedRequest , onApprove ]);
useEffect (() => {
2026-10-11 18:31:50 +08:00
if ( ! requests . length ) {
setValue ( "" );
attemptedCode . current = null ;
}
2026-07-13 13:11:46 +08:00
}, [ requests . length ]);
if ( ! firstRequest ) return null ;
2026-10-11 18:15:39 +08:00
const codeInput = (
< PairingCodeSlots
value = { value }
disabled = { Boolean ( busyCode )}
matched = { Boolean ( matchedRequest )}
invalid = { showNoMatch }
ariaLabel = { t ( "app.pairing.code" , { defaultValue : "Pairing code" })}
2026-10-11 18:31:50 +08:00
onChange = {( next ) => {
attemptedCode . current = null ;
setValue ( formatPairingCodeInput ( next ));
}}
2026-10-11 18:15:39 +08:00
/>
);
2026-07-13 13:11:46 +08:00
return (
< div
role = "dialog"
aria-live = "polite"
aria-label = { t ( "app.pairing.title" , { defaultValue : "Pair a chat user" })}
className = { cn (
"fixed right-4 top-[calc(0.75rem+env(safe-area-inset-top))] z-[70]" ,
2026-08-14 07:07:09 +09:00
"w-[min(calc(100vw-2rem),24rem)] rounded-modal" ,
2026-08-05 13:24:45 +08:00
floatingSurfaceElevationClassName ,
"p-4" ,
2026-07-13 13:11:46 +08:00
"animate-in fade-in-0 slide-in-from-top-2 duration-200" ,
)}
>
< div className = "flex items-start gap-3" >
< PairingChannelBadge channel = { displayRequest . channel } />
< div className = "min-w-0 flex-1" >
< div className = "flex items-start justify-between gap-3" >
< div className = "min-w-0" >
< p className = "text-[15px] font-semibold tracking-[-0.01em]" >
{ t ( "app.pairing.title" , { defaultValue : "Pair a chat user" })}
</ p >
2026-10-11 18:15:39 +08:00
< p
className = "mt-1 text-pretty text-[13px] leading-5 text-muted-foreground"
role = { displayRequest . delivery_status === "failed" ? "alert" : undefined }
>
{ displayRequest . delivery_status === "failed" ? t ( "app.pairing.deliveryFailed" , {
defaultValue : "Couldn't send the pairing code. Check this bot's send-message permissions and gateway logs, then send it another private message to retry." ,
}) : displayRequest . delivery_status === "sending" ? t ( "app.pairing.deliverySending" , {
defaultValue : "Sending a pairing code to your chat. If it doesn't arrive, send the bot another private message to retry." ,
}) : t ( "app.pairing.description" , {
2026-07-13 13:11:46 +08:00
defaultValue : "Enter the pairing code shown in the chat." ,
})}
</ p >
</ div >
< button
type = "button"
aria-label = { t ( "common.close" , { defaultValue : "Close" })}
2026-10-11 18:31:50 +08:00
onClick = {() => onDismiss ( displayRequest )}
2026-07-13 13:11:46 +08:00
className = "rounded-full p-1 text-muted-foreground transition hover:bg-muted hover:text-foreground"
>
< X className = "h-4 w-4" aria - hidden />
</ button >
</ div >
2026-10-11 18:15:39 +08:00
{ deliveryBlocked ? (
< details className = "mt-3 text-[12.5px] text-muted-foreground" >
< summary className = "cursor-pointer" >
{ t ( "app.pairing.haveCode" , { defaultValue : "Already received a code?" })}
</ summary >
{ codeInput }
</ details >
) : (
<>
< label className = "mt-4 block text-[12.5px] font-medium text-foreground" >
{ t ( "app.pairing.code" , { defaultValue : "Pairing code" })}
</ label >
{ codeInput }
</>
)}
2026-07-13 13:11:46 +08:00
2026-10-11 18:15:39 +08:00
{ ! deliveryBlocked || total > 1 ? (
< div className = "mt-3 flex items-center justify-between gap-3 text-[12.5px] text-muted-foreground" >
< span >
2026-10-11 18:31:50 +08:00
{ matchedRequest && busyCode === matchedRequest . code
2026-10-11 18:15:39 +08:00
? t ( "app.pairing.matched" , {
defaultValue : "Matched {{channel}}. Connecting..." ,
channel : channelLabel ( matchedRequest . channel ),
})
: deliveryBlocked ? null : t ( "app.pairing.expiresInline" , {
defaultValue : "Code expires {{expires}}." ,
expires ,
})}
2026-07-13 13:11:46 +08:00
</ span >
2026-10-11 18:15:39 +08:00
{ total > 1 ? (
< span className = "shrink-0" >
{ t ( "app.pairing.queueCount" , {
defaultValue : "{{count}} pending" ,
count : total ,
})}
</ span >
) : null }
</ div >
) : null }
2026-07-13 13:11:46 +08:00
{ showNoMatch ? (
< p className = "mt-2 text-[12px] leading-5 text-destructive" >
{ t ( "app.pairing.noMatch" , {
defaultValue : "No pending request matches this code." ,
})}
</ p >
) : null }
{ error ? (
2026-10-11 18:31:50 +08:00
< div className = "mt-2 space-y-2" >
< p role = "alert" className = "text-[12px] leading-5 text-destructive" >{ error }</ p >
{ matchedRequest ? (
< Button
variant = "outline"
size = "sm"
disabled = { Boolean ( busyCode )}
onClick = {() => onApprove ( matchedRequest . code )}
>
{ t ( "common.retry" , { defaultValue : "Retry" })}
</ Button >
) : null }
</ div >
2026-07-13 13:11:46 +08:00
) : null }
</ div >
</ div >
</ div >
);
}
function PairingChannelBadge ({ channel } : { channel : string }) {
2026-07-19 23:30:49 +08:00
const presentation = pairingChannelPresentation ( channel );
const initials = presentation . initials ;
const color = presentation . color ;
2026-07-13 13:11:46 +08:00
const logoUrls = useMemo (
() => logoFallbackUrls ( presentation ? . logoUrl ),
[ presentation ? . logoUrl ],
);
const { logoUrl , onLogoError , onLogoLoad } = useLogoFallback ( logoUrls );
return (
< div
className = "mt-0.5 grid h-10 w-10 shrink-0 place-items-center overflow-hidden rounded-2xl border bg-background shadow-sm"
style = {{
borderColor : ` ${ color } 30` ,
boxShadow : `inset 0 0 0 1px ${ color } 14, 0 1px 2px rgba(15,23,42,0.06)` ,
}}
aria - hidden
>
{ logoUrl ? (
< img
src = { logoUrl }
alt = ""
decoding = "async"
loading = "lazy"
className = "h-6 w-6 object-contain"
onLoad = { onLogoLoad }
onError = { onLogoError }
/>
) : presentation ? (
< span className = "text-[11px] font-bold tracking-[-0.02em]" style = {{ color }}>
{ initials }
</ span >
) : (
< ShieldCheck className = "h-5 w-5" style = {{ color }} />
)}
</ div >
);
}
function PairingCodeSlots ({
value ,
disabled ,
matched ,
invalid ,
ariaLabel ,
onChange ,
} : {
value : string ;
disabled : boolean ;
matched : boolean ;
invalid : boolean ;
ariaLabel : string ;
onChange : ( value : string ) => void ;
}) {
const inputRef = useRef < HTMLInputElement >( null );
const [ focused , setFocused ] = useState ( false );
const compact = compactPairingCode ( value );
const activeIndex = Math . min ( compact . length , 7 );
const slots = Array . from ({ length : 8 }, ( _ , index ) => compact [ index ] ?? "" );
const renderSlot = ( char : string , index : number ) => {
const highlighted = focused && index === activeIndex && ! matched && ! invalid ;
return (
< div
key = { index }
className = { cn (
"grid h-10 w-7 place-items-center rounded-xl border" ,
"bg-background/80 font-mono text-[16px] font-semibold uppercase" ,
"text-foreground shadow-[0_1px_1px_rgba(15,23,42,0.04)] transition" ,
matched
? "border-emerald-500/45 bg-emerald-500/10 text-emerald-700 dark:text-emerald-300"
: invalid
? "border-destructive/55 bg-destructive/5 text-destructive"
: highlighted
? "border-foreground/30 bg-background text-foreground"
: char
? "border-border/80 bg-background text-foreground"
: "border-border/55 bg-muted/35 text-muted-foreground" ,
)}
>
{ char || " " }
</ div >
);
};
return (
< div
className = { cn (
"relative mt-2 rounded-2xl border border-transparent p-1" ,
"transition duration-150" ,
focused && ! disabled ? "border-ring/20 bg-muted/35" : "bg-transparent" ,
)}
onClick = {() => inputRef . current ? . focus ()}
>
< input
ref = { inputRef }
value = { value }
aria-label = { ariaLabel }
inputMode = "text"
autoCapitalize = "characters"
autoComplete = "off"
autoCorrect = "off"
spellCheck = { false }
maxLength = { 9 }
disabled = { disabled }
onFocus = {() => setFocused ( true )}
onBlur = {() => setFocused ( false )}
onChange = {( event ) => onChange ( event . target . value )}
className = "absolute inset-0 z-10 h-full w-full cursor-text opacity-0 disabled:cursor-default"
/>
< div className = "pointer-events-none flex items-center gap-1.5" >
{ slots . slice ( 0 , 4 ). map (( char , index ) => renderSlot ( char , index ))}
< div className = "mx-0.5 h-px w-2.5 rounded-full bg-muted-foreground/35" />
{ slots . slice ( 4 ). map (( char , index ) => renderSlot ( char , index + 4 ))}
</ div >
</ div >
);
}
function compactPairingCode ( raw : string ) : string {
return raw . replace ( /[^a-zA-Z0-9]/g , "" ). slice ( 0 , 8 ). toUpperCase ();
}
function formatPairingCodeInput ( raw : string ) : string {
const compact = compactPairingCode ( raw );
if ( compact . length <= 4 ) return compact ;
return ` ${ compact . slice ( 0 , 4 ) } - ${ compact . slice ( 4 ) } ` ;
}
function normalizePairingCode ( raw : string ) : string {
return formatPairingCodeInput ( raw );
}
function pairingChannelKey ( channel : string ) : string {
const raw = channel . trim (). toLowerCase ();
if ( ! raw ) return "" ;
return raw . split ( /[.:]/ )[ 0 ] ?? raw ;
}
function channelLabel ( channel : string ) : string {
2026-07-19 23:30:49 +08:00
return pairingChannelPresentation ( channel ). label ;
}
function pairingChannelPresentation ( channel : string ) {
2026-07-13 13:11:46 +08:00
const key = pairingChannelKey ( channel );
2026-07-19 23:30:49 +08:00
const plugin = channelUiPresentation ( key );
return {
label : plugin?.displayName ?? channel ,
initials : plugin?.initials ?? channel . slice ( 0 , 2 ). toUpperCase (),
color : plugin?.color ?? "#10B981" ,
logoUrl : plugin?.logoUrl ,
};
2026-07-13 13:11:46 +08:00
}
function formatPairingExpiry ( seconds : number | null | undefined ) : string {
if ( seconds == null ) return "soon" ;
if ( seconds <= 0 ) return "expired" ;
if ( seconds < 60 ) return ` ${ seconds } s` ;
return ` ${ Math . ceil ( seconds / 60 ) } min` ;
}
2026-09-03 08:59:49 +08:00
function resolveRuntimeSurface (
surface : RuntimeSurface | null | undefined ,
fallback : RuntimeSurface ,
) : RuntimeSurface {
if ( isNativeRuntime ( surface )) return "native" ;
return surface ? toRuntimeSurface ( surface ) : fallback ;
}
2026-04-18 18:51:53 +00:00
export default function App() {
2026-10-04 00:09:49 +08:00
useAppViewport ();
2026-04-19 06:39:06 +00:00
const { t } = useTranslation ();
2026-04-18 18:51:53 +00:00
const [ state , setState ] = useState < BootState >({ status : "loading" });
2026-05-18 00:53:36 +08:00
const bootstrapSecretRef = useRef ( "" );
2026-04-18 18:51:53 +00:00
2026-06-06 19:49:33 +08:00
const refreshReadyClient = useCallback (
async ( client : NanobotClient , fallbackSurface : RuntimeSurface ) => {
const boot = await fetchBootstrap ( "" , bootstrapSecretRef . current );
const url = deriveWsUrl ( boot . ws_path , boot . token , boot . ws_url );
2026-09-03 08:59:49 +08:00
const runtimeSurface = resolveRuntimeSurface ( boot . runtime_surface , fallbackSurface );
2026-06-06 19:49:33 +08:00
const runtimeHost = createRuntimeHost ( runtimeSurface , boot . runtime_capabilities );
2026-08-02 00:38:17 +09:00
const tokenExpiresAt = boot . expires_in
? bootstrapTokenExpiresAt ( boot . expires_in )
: null ;
2026-06-06 19:49:33 +08:00
if ( runtimeHost . socketFactory ) {
client . updateUrl ( url , runtimeHost . socketFactory );
} else {
client . updateUrl ( url );
}
2026-07-28 11:40:01 +08:00
client . updateMaxFrameBytes ( boot . limits ? . transport . max_frame_bytes );
2026-06-06 19:49:33 +08:00
setState (( current ) =>
current . status === "ready" && current . client === client
? {
... current ,
2026-08-02 00:38:17 +09:00
token : boot.api_token ?? "" ,
2026-06-06 19:49:33 +08:00
tokenExpiresAt ,
modelName : boot.model_name ?? current . modelName ,
2026-07-14 14:47:42 +08:00
ingressLimits : boot.limits ?? current . ingressLimits ,
2026-06-06 19:49:33 +08:00
runtimeSurface ,
2026-10-05 05:16:33 +08:00
webuiCapabilities : bootstrapCapabilities ( boot ),
2026-06-06 19:49:33 +08:00
}
: current ,
);
2026-08-02 00:38:17 +09:00
return { token : boot.api_token ?? "" , url };
2026-06-06 19:49:33 +08:00
},
[],
);
2026-05-06 23:15:18 +08:00
const bootstrapWithSecret = useCallback (
( secret : string ) => {
let cancelled = false ;
2026-09-24 23:10:57 +08:00
if ( readShellRoute (). view === "chat" ) void loadThreadShell (). catch (() => {});
2026-05-06 23:15:18 +08:00
( async () => {
setState ({ status : "loading" });
try {
const boot = await fetchBootstrap ( "" , secret );
if ( cancelled ) return ;
if ( secret ) saveSecret ( secret );
2026-05-29 03:42:53 +08:00
const url = deriveWsUrl ( boot . ws_path , boot . token , boot . ws_url );
2026-09-24 23:10:57 +08:00
activateReloadCache ( url );
2026-09-03 08:59:49 +08:00
const runtimeSurface = resolveRuntimeSurface ( boot . runtime_surface , "browser" );
2026-05-29 03:42:53 +08:00
const runtimeHost = createRuntimeHost ( runtimeSurface , boot . runtime_capabilities );
2026-05-24 14:44:42 +08:00
const client = new NanobotClient ({
2026-05-06 23:15:18 +08:00
url ,
2026-07-28 11:40:01 +08:00
maxFrameBytes : boot.limits?.transport.max_frame_bytes ,
2026-05-29 03:42:53 +08:00
socketFactory : runtimeHost.socketFactory ,
2026-05-06 23:15:18 +08:00
onReauth : async () => {
try {
2026-06-06 19:49:33 +08:00
const refreshed = await refreshReadyClient ( client , runtimeSurface );
return refreshed . url ;
2026-05-06 23:15:18 +08:00
} catch {
return null ;
}
},
});
2026-05-18 00:53:36 +08:00
bootstrapSecretRef . current = secret ;
2026-05-06 23:15:18 +08:00
client . connect ();
setState ({
status : "ready" ,
client ,
2026-08-02 00:38:17 +09:00
token : boot.api_token ?? "" ,
tokenExpiresAt : boot.expires_in
? bootstrapTokenExpiresAt ( boot . expires_in )
: null ,
2026-05-06 23:15:18 +08:00
modelName : boot.model_name ?? null ,
2026-07-14 14:47:42 +08:00
ingressLimits : boot.limits ?? null ,
2026-05-29 03:42:53 +08:00
runtimeSurface ,
2026-10-05 05:16:33 +08:00
webuiCapabilities : bootstrapCapabilities ( boot ),
2026-05-06 23:15:18 +08:00
});
} catch ( e ) {
if ( cancelled ) return ;
2026-07-08 15:46:52 +08:00
if ( isBootstrapAuthRequired ( e )) {
2026-09-24 23:10:57 +08:00
clearReloadCache ();
2026-09-25 23:42:01 +08:00
clearStoredComposerDrafts ();
2026-09-24 23:10:57 +08:00
webuiThreadCache . clear ();
2026-06-22 10:57:55 +08:00
setState ({ status : "auth" , failed : !! secret });
2026-05-06 23:15:18 +08:00
} else {
2026-07-08 15:46:52 +08:00
setState ({
status : "error" ,
message : e instanceof Error ? e.message : String ( e ),
});
2026-05-06 23:15:18 +08:00
}
}
})();
return () => {
cancelled = true ;
};
},
2026-06-06 19:49:33 +08:00
[ refreshReadyClient ],
2026-05-06 23:15:18 +08:00
);
2026-05-18 00:53:36 +08:00
useEffect (() => {
2026-08-02 00:38:17 +09:00
if ( state . status !== "ready" || state . tokenExpiresAt === null ) return ;
2026-05-18 00:53:36 +08:00
const client = state . client ;
const timer = window . setTimeout ( async () => {
try {
2026-06-06 19:49:33 +08:00
await refreshReadyClient ( client , state . runtimeSurface );
2026-05-18 00:53:36 +08:00
} catch ( e ) {
2026-07-08 15:46:52 +08:00
if ( isBootstrapAuthRequired ( e )) {
2026-09-24 23:10:57 +08:00
clearReloadCache ();
2026-09-25 23:42:01 +08:00
clearStoredComposerDrafts ();
2026-09-24 23:10:57 +08:00
webuiThreadCache . clear ();
2026-06-22 10:57:55 +08:00
setState ({ status : "auth" , failed : !! bootstrapSecretRef . current });
2026-05-18 00:53:36 +08:00
}
}
}, tokenRefreshDelayMs ( state . tokenExpiresAt ));
return () => window . clearTimeout ( timer );
2026-06-06 19:49:33 +08:00
}, [ refreshReadyClient , state ]);
2026-05-18 00:53:36 +08:00
2026-04-18 18:51:53 +00:00
useEffect (() => {
2026-07-08 14:27:52 +08:00
const saved = consumeUrlBootstrapSecret () || loadSavedSecret ();
2026-05-06 23:15:18 +08:00
return bootstrapWithSecret ( saved );
}, [ bootstrapWithSecret ]);
2026-04-18 18:51:53 +00:00
if ( state . status === "loading" ) {
2026-09-24 23:10:57 +08:00
return < StartupShell />;
2026-04-18 18:51:53 +00:00
}
2026-05-06 23:15:18 +08:00
if ( state . status === "auth" ) {
return (
< AuthForm
failed = { !! state . failed }
onSecret = {( s ) => bootstrapWithSecret ( s )}
/>
);
}
2026-04-18 18:51:53 +00:00
if ( state . status === "error" ) {
return (
< div className = "flex h-full w-full items-center justify-center px-4 text-center" >
< div className = "flex max-w-md flex-col items-center gap-3" >
2026-04-19 06:39:06 +00:00
< p className = "text-lg font-semibold" >{ t ( "app.error.title" )}</ p >
2026-04-18 18:51:53 +00:00
< p className = "text-sm text-muted-foreground" >{ state . message }</ p >
< p className = "text-xs text-muted-foreground" >
2026-04-19 06:39:06 +00:00
{ t ( "app.error.gatewayHint" )}
2026-04-18 18:51:53 +00:00
</ p >
</ div >
</ div >
);
}
2026-04-25 18:05:06 +00:00
const handleModelNameChange = ( modelName : string | null ) => {
setState (( current ) =>
current . status === "ready" ? { ... current , modelName } : current ,
);
};
2026-05-06 23:15:18 +08:00
const handleLogout = () => {
if ( state . status === "ready" ) {
state . client . close ();
}
clearSavedSecret ();
2026-09-24 23:10:57 +08:00
clearReloadCache ();
2026-09-25 23:42:01 +08:00
clearStoredComposerDrafts ();
2026-09-24 23:10:57 +08:00
webuiThreadCache . clear ();
2026-05-06 23:15:18 +08:00
setState ({ status : "auth" });
};
2026-06-06 19:49:33 +08:00
const handleNativeEngineRestart = async () : Promise < string > => {
2026-07-14 15:00:30 +08:00
const runtimeHost = createRuntimeHost ( state . runtimeSurface );
if ( ! runtimeHost . restartEngine ) {
2026-06-06 19:49:33 +08:00
throw new Error ( "native engine restart is unavailable" );
}
2026-07-13 13:11:46 +08:00
rememberRestartRoute ();
try {
window . localStorage . setItem ( RESTART_STARTED_KEY , String ( Date . now ()));
} catch {
// ignore storage errors
}
try {
2026-07-14 15:00:30 +08:00
await runtimeHost . restartEngine ();
2026-07-13 13:11:46 +08:00
const refreshed = await refreshReadyClient ( state . client , state . runtimeSurface );
return refreshed . token ;
} finally {
try {
window . localStorage . removeItem ( RESTART_STARTED_KEY );
window . localStorage . removeItem ( RESTART_ROUTE_KEY );
} catch {
// ignore storage errors
}
}
2026-06-06 19:49:33 +08:00
};
2026-04-18 18:51:53 +00:00
return (
< ClientProvider
client = { state . client }
token = { state . token }
modelName = { state . modelName }
2026-07-14 14:47:42 +08:00
ingressLimits = { state . ingressLimits }
2026-10-05 05:16:33 +08:00
webuiCapabilities = { state . webuiCapabilities }
2026-04-18 18:51:53 +00:00
>
2026-09-27 20:51:49 +08:00
< RemoteInstances >< Shell
2026-05-29 03:42:53 +08:00
runtimeSurface = { state . runtimeSurface }
onModelNameChange = { handleModelNameChange }
onLogout = { handleLogout }
2026-06-06 19:49:33 +08:00
onNativeEngineRestart = { handleNativeEngineRestart }
2026-09-27 20:51:49 +08:00
/></ RemoteInstances >
2026-04-18 18:51:53 +00:00
</ ClientProvider >
);
}
2026-05-17 17:04:57 +08:00
function Shell ({
2026-05-29 03:42:53 +08:00
runtimeSurface ,
2026-05-17 17:04:57 +08:00
onModelNameChange ,
onLogout ,
2026-06-06 19:49:33 +08:00
onNativeEngineRestart ,
2026-05-17 17:04:57 +08:00
} : {
2026-05-29 03:42:53 +08:00
runtimeSurface : RuntimeSurface ;
2026-05-17 17:04:57 +08:00
onModelNameChange : ( modelName : string | null ) => void ;
onLogout : () => void ;
2026-06-06 19:49:33 +08:00
onNativeEngineRestart : () => Promise < string >;
2026-05-17 17:04:57 +08:00
}) {
2026-04-19 06:39:06 +00:00
const { t , i18n } = useTranslation ();
2026-09-30 23:09:23 +08:00
const remoteConnections = useRemoteConnections ();
const localActive = remoteConnections ? . localActive !== false ;
2026-10-01 23:42:47 +08:00
const managingConnections = remoteConnections ? . managing === true && ! remoteConnections ? . activeHostId ;
const { theme , toggle } = useTheme ();
const managementMain = useRef < HTMLElement >( null );
const reportManagementSurface = remoteConnections ? . reportManagementSurface ;
useEffect (() => {
const main = managementMain . current ;
if ( ! main || ! reportManagementSurface ) return ;
const report = () => {
const rect = main . getBoundingClientRect ();
reportManagementSurface ({ left : rect.left , top : rect.top , width : rect.width , height : rect.height }, theme );
};
const observer = new ResizeObserver ( report );
observer . observe ( main );
window . addEventListener ( "resize" , report );
report ();
return () => { observer . disconnect (); window . removeEventListener ( "resize" , report ); };
}, [ reportManagementSurface , theme ]);
2026-09-30 23:30:25 +08:00
const remoteConnectionsRef = useRef ( remoteConnections );
remoteConnectionsRef . current = remoteConnections ;
2026-07-30 10:25:22 +08:00
const { client , getToken } = useClient ();
2026-10-16 11:38:05 +08:00
useReconnectRuns ( client , getToken );
2026-06-12 18:13:25 +08:00
const {
sessions ,
loading ,
2026-10-16 15:47:15 +08:00
error : sessionsError ,
2026-06-12 18:13:25 +08:00
refresh ,
createChat ,
forkChat ,
deleteChat ,
getSessionAutomations ,
} = useSessions ();
2026-10-16 15:47:15 +08:00
// Failed reads retain an empty list or partial reload cache, not proof of deletion.
const sessionsLoaded = ! loading && sessionsError === null ;
2026-08-12 14:45:12 +08:00
const {
state : sidebarState ,
loading : sidebarStateLoading ,
update : updateSidebarState ,
} =
2026-10-16 15:47:15 +08:00
useSidebarState ( sessions , sessionsLoaded );
2026-06-02 11:29:18 +08:00
const initialRouteRef = useRef < ShellRoute | null >( null );
if ( ! initialRouteRef . current ) initialRouteRef . current = readShellRoute ();
const [ activeKey , setActiveKey ] = useState < string | null >(
initialRouteRef . current . activeKey ,
);
const [ view , setView ] = useState < ShellView >( initialRouteRef . current . view );
2026-09-25 00:01:12 +08:00
const [ chatVisited , setChatVisited ] = useState ( initialRouteRef . current . view === "chat" );
useEffect (() => {
if ( view === "chat" ) setChatVisited ( true );
}, [ view ]);
useEffect (() => {
// Normalize legacy links while retaining their return destination in history.
if ( new URLSearchParams ( window . location . hash . split ( "?" )[ 1 ]). has ( "chat" )) {
writeShellRoute ( initialRouteRef . current ! , true );
}
}, []);
2026-08-06 18:29:04 +08:00
const [ temporarySessions , setTemporarySessions ] = useState < Record < string , ChatSummary >>({});
const [ temporaryChatEnabled , setTemporaryChatEnabled ] = useState ( false );
2026-06-02 11:29:18 +08:00
const [ settingsInitialSection , setSettingsInitialSection ] =
useState < SettingsSectionKey >( initialRouteRef . current . settingsSection );
2026-05-29 03:42:53 +08:00
const [ hostSidebarOpen , setHostSidebarOpen ] =
2026-04-18 18:51:53 +00:00
useState < boolean >( readSidebarOpen );
2026-09-10 11:10:51 +08:00
const [ sidebarWidth , setSidebarWidth ] = useState ( readSidebarWidth );
const [ sidebarDragging , setSidebarDragging ] = useState ( false );
2026-04-18 18:51:53 +00:00
const [ mobileSidebarOpen , setMobileSidebarOpen ] = useState ( false );
2026-09-30 15:09:14 +08:00
useEffect (() => {
// The drawer portals outside the local host panel; don't leave it over a remote view.
2026-09-30 23:09:23 +08:00
if ( ! localActive || managingConnections ) setMobileSidebarOpen ( false );
}, [ localActive , managingConnections ]);
2026-09-21 13:44:42 +08:00
const mobileSidebarRef = useRef < HTMLDivElement >( null );
2026-05-19 22:42:38 +08:00
const [ sessionSearchOpen , setSessionSearchOpen ] = useState ( false );
2026-08-12 14:45:12 +08:00
const mobileWorkbench = useMediaQuery ( "(max-width: 767px)" );
const workbenchState = sidebarState . workbench ;
const updateWorkbenchState = useCallback ((
updater : ( current : WorkbenchState ) => WorkbenchState ,
) => {
void updateSidebarState (( current ) => {
const next = updater ( current . workbench );
return next === current . workbench ? current : { ... current , workbench : next };
});
}, [ updateSidebarState ]);
const lastActivePaneByTabRef = useRef ( new Map < string , string >());
const [ creatingPane , setCreatingPane ] = useState ( false );
const topicSessions = sessions ;
2026-04-18 18:51:53 +00:00
const [ pendingDelete , setPendingDelete ] = useState < {
2026-08-12 14:45:12 +08:00
items : SidebarDeleteItem [];
2026-06-11 19:11:37 +08:00
automations? : SessionAutomationJob [];
2026-04-18 18:51:53 +00:00
} | null > ( null );
2026-05-19 22:42:38 +08:00
const [ pendingRename , setPendingRename ] = useState < {
key : string ;
label : string ;
} | null > ( null );
2026-08-12 14:45:12 +08:00
const [ pendingTabRename , setPendingTabRename ] = useState < {
key : string ;
label : string ;
} | null > ( null );
2026-05-29 03:42:53 +08:00
const [ pendingProjectRename , setPendingProjectRename ] = useState < {
key : string ;
label : string ;
} | null > ( null );
2026-05-08 09:40:15 +00:00
const restartSawDisconnectRef = useRef ( false );
2026-10-12 11:36:42 +08:00
const restartStartedAtRef = useRef ( 0 );
2026-05-08 09:40:15 +00:00
const [ restartToast , setRestartToast ] = useState < string | null >( null );
2026-05-08 15:31:52 +00:00
const [ isRestarting , setIsRestarting ] = useState ( false );
2026-07-13 13:11:46 +08:00
const [ pairingRequests , setPairingRequests ] = useState < PairingRequestInfo [] >([]);
const [ pairingBusyCode , setPairingBusyCode ] = useState < string | null >( null );
const [ pairingError , setPairingError ] = useState < string | null >( null );
2026-07-30 10:25:22 +08:00
const pairingRefreshRef = useRef < Promise < number > | null >( null );
2026-10-11 18:31:50 +08:00
const [ snoozedPairingCodes , setSnoozedPairingCodes ] = useState < Map < string , {
until : number ;
deliveryStatus : PairingRequestInfo [ "delivery_status" ];
}>>(
2026-07-13 13:11:46 +08:00
() => new Map (),
);
2026-05-19 22:42:38 +08:00
const [ runningChatIds , setRunningChatIds ] = useState < Set < string >>(() => new Set ());
2026-06-15 17:30:06 +08:00
const [ updatedChatIds , setUpdatedChatIds ] = useState < Set < string >>( readSessionUpdateChatIds );
2026-05-29 03:42:53 +08:00
const [ workspaces , setWorkspaces ] = useState < WorkspacesPayload | null >( null );
2026-10-07 21:28:53 +08:00
const { skills , loading : skillsLoading , error : skillsError } = useSkills ( getToken );
2026-07-22 22:35:39 +08:00
const pageVisible = usePageVisibility ();
2026-05-29 03:42:53 +08:00
const [ settingsSnapshot , setSettingsSnapshot ] = useState < SettingsPayload | null >( null );
2026-09-24 22:05:31 +08:00
const [ settingsLoading , setSettingsLoading ] = useState ( true );
2026-09-23 17:27:34 +08:00
const settingsRefreshGenerationRef = useRef ( 0 );
2026-09-12 16:32:46 +08:00
const [ pendingAutomationMessage , setPendingAutomationMessage ] = useState < {
id : string ;
chatId : string ;
content : string ;
images? : SendAttachment [];
options? : SendOptions ;
} | null > ( null );
2026-09-10 11:10:51 +08:00
const settingsExitGuardRef = useRef < SettingsExitGuard | null >( null );
const currentShellRouteRef = useRef < ShellRoute >({ view , activeKey , settingsSection : settingsInitialSection });
2026-09-25 00:01:12 +08:00
currentShellRouteRef . current = {
view , activeKey , settingsSection : settingsInitialSection ,
temporary : Boolean ( activeKey && temporarySessions [ activeKey ]),
};
2026-09-10 11:10:51 +08:00
const registerSettingsExitGuard = useCallback (( guard : SettingsExitGuard | null ) => {
settingsExitGuardRef . current = guard ;
}, []);
2026-05-29 03:42:53 +08:00
const [ workspaceError , setWorkspaceError ] = useState < string | null >( null );
const [ draftWorkspaceScope , setDraftWorkspaceScope ] =
useState < WorkspaceScopePayload | null >( null );
const [ workspaceOverrides , setWorkspaceOverrides ] =
useState < Record < string , WorkspaceScopePayload >>({});
2026-05-19 22:42:38 +08:00
const runningChatIdsRef = useRef < Set < string >>( new Set ());
2026-05-30 23:45:26 +08:00
const activeChatIdRef = useRef < string | null >( null );
2026-08-07 14:56:23 +08:00
const pendingCreatedSessionKeyRef = useRef < string | null >( null );
2026-08-06 18:29:04 +08:00
const temporarySessionsRef = useRef < Record < string , ChatSummary >>({});
2026-06-06 19:49:33 +08:00
const effectiveRuntimeSurface =
settingsSnapshot ? . surface ?? settingsSnapshot ? . runtime_surface ?? runtimeSurface ;
2026-09-03 08:59:49 +08:00
const showHostChrome = isNativeRuntime ( effectiveRuntimeSurface );
2026-06-06 19:49:33 +08:00
const showMainSidebar = view !== "settings" ;
2026-08-07 11:20:08 +08:00
const activeTemporarySession = activeKey ? temporarySessions [ activeKey ] ?? null : null ;
const temporaryChatId = activeTemporarySession ? . chatId ?? null ;
2026-09-25 00:01:12 +08:00
const temporaryChatActive = temporaryChatId !== null ;
2026-08-06 18:29:04 +08:00
const temporaryChatRequested = temporaryChatActive || temporaryChatEnabled ;
const temporarySessionList = useMemo (
() => Object . values ( temporarySessions ). sort (( a , b ) => (
Date . parse ( b . createdAt ?? "" ) - Date . parse ( a . createdAt ?? "" )
)),
[ temporarySessions ],
);
const temporaryChatIds = useMemo (
() => temporarySessionList . map (( session ) => session . chatId ),
[ temporarySessionList ],
);
2026-09-21 00:41:00 +08:00
// Pane shells can unmount during navigation. Keep replay state for this app
// session, pinning temporary chats because they cannot reload disk history.
const retainedTemporaryChatIdsRef = useRef ( new Set < string >());
2026-09-25 23:42:01 +08:00
const [ draftStore ] = useState (() => new ComposerDraftStore ());
2026-09-21 17:48:49 +08:00
const [ filePreviewStore ] = useState (() => new FilePreviewStore ());
2026-09-21 00:41:00 +08:00
const [ threadMessageCache ] = useState (() => new ThreadMessageCache (
( key ) => retainedTemporaryChatIdsRef . current . has ( key ),
));
useEffect (() => {
const retained = new Set ( temporaryChatIds );
for ( const chatId of retainedTemporaryChatIdsRef . current ) {
2026-09-21 17:48:49 +08:00
if ( ! retained . has ( chatId )) {
threadMessageCache . delete ( chatId );
filePreviewStore . delete ( `websocket: ${ chatId } ` );
2026-09-25 23:42:01 +08:00
draftStore . delete ( `websocket: ${ chatId } ` );
2026-09-21 17:48:49 +08:00
}
2026-09-21 00:41:00 +08:00
}
retainedTemporaryChatIdsRef . current = retained ;
2026-09-25 23:42:01 +08:00
}, [ temporaryChatIds , threadMessageCache , filePreviewStore , draftStore ]);
2026-04-18 18:51:53 +00:00
2026-06-02 11:29:18 +08:00
const navigate = useCallback (
( route : ShellRoute , options ?: { replace? : boolean }) => {
2026-09-10 11:10:51 +08:00
const leave = () => {
2026-10-01 23:42:47 +08:00
// The visible sidebar always belongs to its existing host. Navigation
// dismisses global management without switching to a different host.
if ( remoteConnectionsRef . current ? . managing ) remoteConnectionsRef . current . closeManagement ();
2026-09-10 11:10:51 +08:00
setActiveKey ( route . activeKey );
setView ( route . view );
setSettingsInitialSection ( route . settingsSection );
2026-09-25 00:01:12 +08:00
writeShellRoute ({
... route ,
temporary : route.temporary || Boolean ( route . activeKey && temporarySessionsRef . current [ route . activeKey ]),
}, options ? . replace );
2026-09-10 11:10:51 +08:00
};
if ( currentShellRouteRef . current . view === "settings" && route . view !== "settings" && settingsExitGuardRef . current ) {
settingsExitGuardRef . current ( leave );
} else leave ();
2026-06-02 11:29:18 +08:00
},
[],
);
useEffect (() => {
const applyRoute = () => {
const route = readShellRoute ();
2026-09-30 15:09:14 +08:00
if ( route . view === "remote" ) setMobileSidebarOpen ( false );
2026-09-10 11:10:51 +08:00
if ( currentShellRouteRef . current . view === "settings" && route . view !== "settings" && settingsExitGuardRef . current ) {
writeShellRoute ( currentShellRouteRef . current , true );
settingsExitGuardRef . current (() => {
setActiveKey ( route . activeKey );
setView ( route . view );
setSettingsInitialSection ( route . settingsSection );
writeShellRoute ( route , true );
setWorkspaceError ( null );
if ( route . view === "chat" && ! route . activeKey ) setDraftWorkspaceScope ( null );
});
return ;
}
2026-06-02 11:29:18 +08:00
setActiveKey ( route . activeKey );
setView ( route . view );
setSettingsInitialSection ( route . settingsSection );
setWorkspaceError ( null );
if ( route . view === "chat" && ! route . activeKey ) {
setDraftWorkspaceScope ( null );
}
};
window . addEventListener ( "hashchange" , applyRoute );
2026-09-09 14:40:35 +08:00
window . addEventListener ( "popstate" , applyRoute );
return () => {
window . removeEventListener ( "hashchange" , applyRoute );
window . removeEventListener ( "popstate" , applyRoute );
};
2026-06-02 11:29:18 +08:00
}, []);
2026-08-05 19:24:41 +08:00
useEffect (() => {
2026-08-06 18:29:04 +08:00
temporarySessionsRef . current = temporarySessions ;
}, [ temporarySessions ]);
2026-08-05 19:24:41 +08:00
useEffect (() => {
2026-08-06 18:29:04 +08:00
if ( view === "chat" && ! activeKey ) return ;
setTemporaryChatEnabled ( false );
}, [ activeKey , view ]);
useEffect (() => () => {
for ( const session of Object . values ( temporarySessionsRef . current )) {
client . discardTemporaryChat ( session . chatId );
}
}, [ client ]);
2026-08-05 19:24:41 +08:00
2026-05-29 03:42:53 +08:00
useEffect (() => {
let cancelled = false ;
2026-09-23 17:27:34 +08:00
const requestGeneration = settingsRefreshGenerationRef . current ;
2026-09-24 22:05:31 +08:00
setSettingsLoading ( true );
2026-07-30 10:25:22 +08:00
fetchSettings ( getToken ())
2026-05-29 03:42:53 +08:00
. then (( payload ) => {
2026-09-23 17:27:34 +08:00
if ( ! cancelled && requestGeneration === settingsRefreshGenerationRef . current ) {
setSettingsSnapshot ( payload );
}
2026-05-29 03:42:53 +08:00
})
. catch (() => {
2026-09-23 17:27:34 +08:00
if ( ! cancelled && requestGeneration === settingsRefreshGenerationRef . current ) {
setSettingsSnapshot ( null );
}
2026-09-24 22:05:31 +08:00
})
. finally (() => {
if ( ! cancelled ) setSettingsLoading ( false );
2026-05-29 03:42:53 +08:00
});
return () => {
cancelled = true ;
};
2026-07-30 10:25:22 +08:00
}, [ getToken ]);
2026-05-29 03:42:53 +08:00
2026-04-18 18:51:53 +00:00
useEffect (() => {
try {
window . localStorage . setItem (
SIDEBAR_STORAGE_KEY ,
2026-05-29 03:42:53 +08:00
hostSidebarOpen ? "1" : "0" ,
2026-04-18 18:51:53 +00:00
);
} catch {
// ignore storage errors (private mode, etc.)
}
2026-09-10 11:10:51 +08:00
try {
window . localStorage . setItem ( SIDEBAR_WIDTH_STORAGE_KEY , String ( sidebarWidth ));
} catch {
// Storage can be unavailable in private browsing.
}
}, [ hostSidebarOpen , sidebarWidth ]);
2026-04-18 18:51:53 +00:00
2026-05-19 22:42:38 +08:00
useEffect (() => {
2026-06-15 17:30:06 +08:00
writeSessionUpdateChatIds ( updatedChatIds );
}, [ updatedChatIds ]);
2026-04-18 18:51:53 +00:00
2026-07-30 10:25:22 +08:00
const refreshPairingRequests = useCallback (() : Promise < number > => {
if ( pairingRefreshRef . current ) return pairingRefreshRef . current ;
const request = ( async () => {
try {
const payload = await fetchPairingRequests ( getToken ());
const requests = Array . isArray ( payload . requests ) ? payload . requests : [];
setPairingRequests ( requests );
setSnoozedPairingCodes (( current ) => {
if ( current . size === 0 ) return current ;
2026-10-11 18:31:50 +08:00
const activeRequests = new Map ( requests . map (( request ) => [ request . code , request ]));
2026-07-30 10:25:22 +08:00
const now = Date . now ();
const next = new Map (
Array . from ( current ). filter (
2026-10-11 18:31:50 +08:00
([ code , snooze ]) => activeRequests . has ( code )
&& snooze . until > now
&& activeRequests . get ( code ) ? . delivery_status === snooze . deliveryStatus ,
2026-07-30 10:25:22 +08:00
),
);
return next . size === current . size ? current : next ;
});
return requests . length ;
} catch {
// Pairing is an opportunistic WebUI affordance. The slash command path
// remains available if this polling request fails.
return 0 ;
}
})();
const clearRequest = () => {
if ( pairingRefreshRef . current === request ) pairingRefreshRef . current = null ;
};
pairingRefreshRef . current = request ;
void request . then ( clearRequest , clearRequest );
return request ;
}, [ getToken ]);
2026-07-13 13:11:46 +08:00
useEffect (() => {
2026-07-22 22:35:39 +08:00
if ( ! pageVisible ) return undefined ;
let disposed = false ;
let timer : number | null = null ;
const poll = async () => {
const requestCount = await refreshPairingRequests ();
if ( disposed ) return ;
timer = window . setTimeout (
() => void poll (),
requestCount > 0 ? PAIRING_POLL_INTERVAL_MS : PAIRING_IDLE_POLL_INTERVAL_MS ,
);
};
void poll ();
return () => {
disposed = true ;
if ( timer !== null ) window . clearTimeout ( timer );
};
}, [ pageVisible , refreshPairingRequests ]);
2026-07-13 13:11:46 +08:00
2026-04-18 18:51:53 +00:00
const activeSession = useMemo < ChatSummary | null >(() => {
if ( ! activeKey ) return null ;
2026-08-07 11:20:08 +08:00
if ( temporarySessions [ activeKey ]) return temporarySessions [ activeKey ];
2026-04-18 18:51:53 +00:00
return sessions . find (( s ) => s . key === activeKey ) ?? null ;
2026-08-06 18:29:04 +08:00
}, [ sessions , activeKey , temporarySessions ]);
2026-08-12 14:45:12 +08:00
const activeTabMatch = useMemo (() => (
activeKey && ! temporarySessions [ activeKey ]
? workbenchTabForPane ( workbenchState , activeKey )
: null
), [ activeKey , temporarySessions , workbenchState ]);
const activeTabKey = activeTabMatch ? . tabKey ?? null ;
const activeTabState = activeTabMatch ? . tab ?? null ;
const activePaneSession = activeSession ;
useEffect (() => {
if ( ! activeTabKey || ! activeKey || ! activeTabState ? . paneKeys . includes ( activeKey )) return ;
lastActivePaneByTabRef . current . set ( activeTabKey , activeKey );
}, [ activeKey , activeTabKey , activeTabState ]);
2026-05-19 22:42:38 +08:00
const runningChatIdList = useMemo (() => Array . from ( runningChatIds ), [ runningChatIds ]);
2026-06-15 17:30:06 +08:00
const updatedChatIdList = useMemo (() => Array . from ( updatedChatIds ), [ updatedChatIds ]);
2026-08-22 19:33:22 +08:00
const recoveryChatIdList = useMemo (
() => sessions
. filter (( session ) => (
session . recoveryState ? . status === "awaiting_user"
|| session . recoveryState ? . status === "failed"
))
. map (( session ) => session . chatId ),
[ sessions ],
);
2026-08-12 14:45:12 +08:00
const activeChatId = activePaneSession ? . chatId ?? null ;
2026-05-30 23:45:26 +08:00
useEffect (() => {
activeChatIdRef . current = activeChatId ;
if ( ! activeChatId ) return ;
2026-06-15 17:30:06 +08:00
setUpdatedChatIds (( current ) => {
2026-05-30 23:45:26 +08:00
if ( ! current . has ( activeChatId )) return current ;
const next = new Set ( current );
next . delete ( activeChatId );
return next ;
});
}, [ activeChatId ]);
2026-05-29 03:42:53 +08:00
const activeWorkspaceScope = useMemo < WorkspaceScopePayload | null >(() => {
2026-08-06 18:29:04 +08:00
if ( temporaryChatRequested ) {
2026-08-05 19:24:41 +08:00
return workspaces ? . default_scope
? normalizeWorkspaceScope ( scopeWithAccessMode ( workspaces . default_scope , "restricted" ))
: null ;
}
2026-05-29 03:42:53 +08:00
if ( activeChatId && workspaceOverrides [ activeChatId ]) {
return workspaceOverrides [ activeChatId ];
}
2026-08-12 14:45:12 +08:00
if ( activePaneSession ? . workspaceScope ) {
return activePaneSession . workspaceScope ;
2026-05-29 03:42:53 +08:00
}
return draftWorkspaceScope ?? workspaces ? . default_scope ?? null ;
}, [
activeChatId ,
2026-08-12 14:45:12 +08:00
activePaneSession ? . workspaceScope ,
2026-05-29 03:42:53 +08:00
draftWorkspaceScope ,
2026-08-06 18:29:04 +08:00
temporaryChatRequested ,
2026-05-29 03:42:53 +08:00
workspaceOverrides ,
workspaces ? . default_scope ,
]);
const activeChatRunning = activeChatId ? runningChatIds . has ( activeChatId ) : false ;
const refreshWorkspaces = useCallback ( async () => {
try {
2026-07-30 10:25:22 +08:00
const payload = await fetchWorkspaces ( getToken ());
2026-05-29 03:42:53 +08:00
setWorkspaces ( payload );
} catch {
setWorkspaces ( null );
}
2026-07-30 10:25:22 +08:00
}, [ getToken ]);
2026-05-29 03:42:53 +08:00
useEffect (() => {
void refreshWorkspaces ();
}, [ refreshWorkspaces ]);
2026-05-19 22:42:38 +08:00
useEffect (() => {
2026-10-16 15:47:15 +08:00
if ( ! sessionsLoaded ) return ;
2026-05-19 22:42:38 +08:00
const knownChatIds = new Set ( sessions . map (( session ) => session . chatId ));
2026-06-15 17:30:06 +08:00
setUpdatedChatIds (( current ) => {
2026-05-19 22:42:38 +08:00
const next = new Set (
Array . from ( current ). filter (( chatId ) => knownChatIds . has ( chatId )),
);
return next . size === current . size ? current : next ;
});
2026-05-29 03:42:53 +08:00
setWorkspaceOverrides (( current ) => {
const entries = Object . entries ( current ). filter (([ chatId ]) => knownChatIds . has ( chatId ));
return entries . length === Object . keys ( current ). length ? current : Object.fromEntries ( entries );
});
2026-10-16 15:47:15 +08:00
}, [ sessionsLoaded , sessions ]);
2026-05-19 22:42:38 +08:00
2026-08-12 14:45:12 +08:00
useEffect (() => {
2026-10-16 15:47:15 +08:00
if ( ! sessionsLoaded || sidebarStateLoading ) return ;
2026-08-12 14:45:12 +08:00
const validKeys = new Set ( sessions . map (( session ) => session . key ));
updateWorkbenchState (( current ) => {
return reconcileWorkbench ( current , validKeys );
});
}, [
2026-10-16 15:47:15 +08:00
sessionsLoaded ,
2026-08-12 14:45:12 +08:00
sidebarStateLoading ,
sessions ,
updateWorkbenchState ,
]);
2026-06-02 11:29:18 +08:00
useEffect (() => {
2026-08-07 14:56:23 +08:00
if ( loading ) return ;
const pendingCreatedKey = pendingCreatedSessionKeyRef . current ;
if ( pendingCreatedKey && sessions . some (( session ) => session . key === pendingCreatedKey )) {
pendingCreatedSessionKeyRef . current = null ;
}
2026-08-06 18:29:04 +08:00
if ( ! activeKey ) return ;
2026-08-07 11:20:08 +08:00
const currentRoute = readShellRoute ();
2026-09-25 00:01:12 +08:00
if ( temporarySessions [ activeKey ]) return ;
2026-08-07 11:20:08 +08:00
if ( currentRoute . temporary ) {
2026-09-25 00:01:12 +08:00
navigate ( currentRoute . view === "chat" ? defaultShellRoute () : {
... currentRoute , activeKey : null , temporary : false ,
}, { replace : true });
2026-08-06 18:29:04 +08:00
return ;
}
if ( sessions . some (( session ) => session . key === activeKey )) return ;
2026-08-07 14:56:23 +08:00
// WebKit can commit the route before useSessions' optimistic insert.
// Keep that just-created destination valid until the session list catches up.
if ( pendingCreatedKey === activeKey ) return ;
2026-06-02 11:29:18 +08:00
navigate (
currentRoute . view === "chat"
? defaultShellRoute ()
: {
... currentRoute ,
activeKey : null ,
},
{ replace : true },
);
2026-08-06 18:29:04 +08:00
}, [ activeKey , loading , navigate , sessions , temporarySessions ]);
2026-06-02 11:29:18 +08:00
2026-05-29 03:42:53 +08:00
useEffect (() => {
2026-06-15 17:30:06 +08:00
return client . onSessionUpdate (( chatId , scope , workspaceScope ) => {
if ( scope === "thread" ) {
setUpdatedChatIds (( current ) => {
const next = new Set ( current );
if ( activeChatIdRef . current === chatId ) {
next . delete ( chatId );
} else {
next . add ( chatId );
}
return next . size === current . size && next . has ( chatId ) === current . has ( chatId )
? current
: next ;
});
}
2026-05-29 03:42:53 +08:00
if ( ! workspaceScope ) return ;
const next = normalizeWorkspaceScope ( workspaceScope );
setWorkspaceOverrides (( current ) => ({
... current ,
2026-06-15 17:30:06 +08:00
[ chatId ] : next ,
2026-05-29 03:42:53 +08:00
}));
setDraftWorkspaceScope ( next );
setWorkspaceError ( null );
void refreshWorkspaces ();
});
}, [ client , refreshWorkspaces ]);
useEffect (() => {
return client . onError (( error ) => {
if ( error . kind !== "workspace_scope_rejected" ) return ;
2026-07-28 11:40:01 +08:00
if ( error . chatId && error . chatId !== activeChatIdRef . current ) return ;
2026-05-29 03:42:53 +08:00
setWorkspaceError ( t ( "errors.workspaceScopeRejected.body" ));
void refreshWorkspaces ();
});
}, [ client , refreshWorkspaces , t ]);
2026-05-19 22:42:38 +08:00
useEffect (() => {
if ( loading ) return ;
const activeRunIds = sessions
. filter (( session ) => typeof session . runStartedAt === "number" )
. map (( session ) => session . chatId );
if ( activeRunIds . length === 0 ) return ;
for ( const chatId of activeRunIds ) {
client . attach ( chatId );
}
}, [ client , loading , sessions ]);
2026-04-18 18:51:53 +00:00
2026-05-29 03:42:53 +08:00
const openHostSidebar = useCallback (() => {
setHostSidebarOpen ( true );
2026-09-03 00:01:39 +08:00
}, []);
2026-05-22 00:31:55 +08:00
2026-04-18 18:51:53 +00:00
const closeMobileSidebar = useCallback (() => {
setMobileSidebarOpen ( false );
}, []);
const toggleSidebar = useCallback (() => {
2026-05-29 03:42:53 +08:00
const isNativeHost =
2026-04-18 18:51:53 +00:00
typeof window !== "undefined" &&
window . matchMedia ( "(min-width: 1024px)" ). matches ;
2026-05-29 03:42:53 +08:00
if ( isNativeHost ) {
setHostSidebarOpen (( v ) => ! v );
2026-04-18 18:51:53 +00:00
} else {
setMobileSidebarOpen (( v ) => ! v );
}
2026-09-03 00:01:39 +08:00
}, []);
2026-04-18 18:51:53 +00:00
2026-05-29 03:42:53 +08:00
const applyWorkspaceScope = useCallback (
( scope : WorkspaceScopePayload ) => {
const next = normalizeWorkspaceScope ( scope );
setWorkspaceError ( null );
if ( activeChatId ) {
2026-08-05 19:24:41 +08:00
if ( temporaryChatActive ) {
2026-08-06 18:29:04 +08:00
setTemporarySessions (( current ) => {
if ( ! activeKey || ! current [ activeKey ]) return current ;
return {
... current ,
[ activeKey ] : { ... current [ activeKey ], workspaceScope : next },
};
});
2026-08-05 19:24:41 +08:00
} else if ( ! activeChatRunning ) {
2026-05-29 03:42:53 +08:00
client . setWorkspaceScope ( activeChatId , next );
}
return ;
}
setDraftWorkspaceScope ( next );
},
2026-08-06 18:29:04 +08:00
[ activeChatId , activeChatRunning , activeKey , client , temporaryChatActive ],
2026-05-29 03:42:53 +08:00
);
2026-09-04 10:36:24 +08:00
const onCreateChat = useCallback ( async (
workspaceScope? : WorkspaceScopePayload | null ,
_initialMessage? : string ,
modelPreset? : string | null ,
) => {
2026-04-18 18:51:53 +00:00
try {
2026-05-29 03:42:53 +08:00
const scope = workspaceScope ?? activeWorkspaceScope ;
2026-09-04 10:36:24 +08:00
const chatId = await createChat ( scope , modelPreset );
2026-08-07 14:56:23 +08:00
const key = `websocket: ${ chatId } ` ;
pendingCreatedSessionKeyRef . current = key ;
2026-06-02 11:29:18 +08:00
navigate ({
view : "chat" ,
2026-08-07 14:56:23 +08:00
activeKey : key ,
2026-06-02 11:29:18 +08:00
settingsSection : "overview" ,
});
2026-04-18 18:51:53 +00:00
setMobileSidebarOpen ( false );
2026-05-29 03:42:53 +08:00
if ( scope ) {
setWorkspaceOverrides (( current ) => ({
... current ,
[ chatId ] : normalizeWorkspaceScope ( scope ),
}));
}
2026-04-18 18:51:53 +00:00
return chatId ;
} catch ( e ) {
console . error ( "Failed to create chat" , e );
2026-05-29 03:42:53 +08:00
if ( e instanceof Error && e . message . startsWith ( "workspace_scope_rejected:" )) {
setWorkspaceError ( t ( "errors.workspaceScopeRejected.body" ));
}
2026-04-18 18:51:53 +00:00
return null ;
}
2026-06-02 11:29:18 +08:00
}, [ activeWorkspaceScope , createChat , navigate , t ]);
2026-04-18 18:51:53 +00:00
2026-09-12 16:32:46 +08:00
const onStartAutomationChat = useCallback ( async (
content : string ,
images? : SendAttachment [],
options? : SendOptions ,
modelPreset? : string | null ,
) => {
const chatId = await onCreateChat (
options ? . workspaceScope ?? activeWorkspaceScope ,
content ,
modelPreset ,
);
if ( ! chatId ) return false ;
setPendingAutomationMessage ({
id : crypto.randomUUID (),
chatId ,
content ,
images ,
options ,
});
return true ;
}, [ activeWorkspaceScope , onCreateChat ]);
const onPendingAutomationMessageConsumed = useCallback (( id : string ) => {
setPendingAutomationMessage (( current ) => current ? . id === id ? null : current );
}, []);
2026-08-06 18:29:04 +08:00
const onCreateTemporaryChat = useCallback (
async (
workspaceScope? : WorkspaceScopePayload | null ,
initialMessage? : string ,
2026-09-04 10:36:24 +08:00
modelPreset? : string | null ,
2026-08-06 18:29:04 +08:00
) => {
2026-08-07 11:20:08 +08:00
try {
const chatId = await client . newTemporaryChat ();
const session = createTemporaryChatSession ( chatId );
const restrictedScope = workspaceScope
? normalizeWorkspaceScope ( scopeWithAccessMode ( workspaceScope , "restricted" ))
: null ;
const nextSession : ChatSummary = {
... session ,
preview : initialMessage ?? "" ,
2026-09-04 10:36:24 +08:00
modelPreset : modelPreset ?? null ,
2026-08-07 11:20:08 +08:00
...( restrictedScope ? { workspaceScope : restrictedScope } : {}),
};
setTemporarySessions (( current ) => ({
... current ,
[ nextSession . key ] : nextSession ,
}));
setTemporaryChatEnabled ( false );
setWorkspaceError ( null );
setSessionSearchOpen ( false );
navigate ({
view : "chat" ,
activeKey : nextSession.key ,
settingsSection : "overview" ,
temporary : true ,
});
setMobileSidebarOpen ( false );
return nextSession . chatId ;
} catch ( error ) {
console . error ( "Failed to create temporary chat" , error );
return null ;
}
2026-08-06 18:29:04 +08:00
},
2026-08-07 11:20:08 +08:00
[ client , navigate ],
2026-08-06 18:29:04 +08:00
);
2026-06-05 19:49:34 +08:00
const onForkChat = useCallback ( async (
sourceChatId : string ,
beforeUserIndex : number ,
) => {
try {
2026-06-10 02:07:47 +08:00
const sourceSession = sessions . find (( session ) => session . chatId === sourceChatId );
const sourceTitle = sourceSession
? displayTitle ( sourceSession , sidebarState . title_overrides , t ( "chat.newChat" ))
: t ( "chat.newChat" );
const chatId = await forkChat (
sourceChatId ,
beforeUserIndex ,
t ( "chat.forkTitle" , { title : sourceTitle }),
);
2026-06-05 19:49:34 +08:00
navigate ({
view : "chat" ,
activeKey : `websocket: ${ chatId } ` ,
settingsSection : "overview" ,
});
setMobileSidebarOpen ( false );
return chatId ;
} catch ( e ) {
console . error ( "Failed to fork chat" , e );
return null ;
}
2026-06-10 02:07:47 +08:00
}, [ forkChat , navigate , sessions , sidebarState . title_overrides , t ]);
2026-06-05 19:49:34 +08:00
2026-05-06 14:15:36 +00:00
const onNewChat = useCallback (() => {
2026-06-02 11:29:18 +08:00
navigate ( defaultShellRoute ());
2026-08-06 18:29:04 +08:00
setTemporaryChatEnabled ( false );
2026-05-29 03:42:53 +08:00
setDraftWorkspaceScope ( null );
setWorkspaceError ( null );
2026-06-04 11:03:06 +08:00
setSessionSearchOpen ( false );
2026-05-06 14:15:36 +00:00
setMobileSidebarOpen ( false );
2026-06-02 11:29:18 +08:00
}, [ navigate ]);
2026-05-06 14:15:36 +00:00
2026-08-06 18:29:04 +08:00
const onTemporaryChatEnabledChange = useCallback (( enabled : boolean ) => {
if ( view !== "chat" || activeKey ) return ;
setTemporaryChatEnabled ( enabled );
setDraftWorkspaceScope ( null );
2026-08-05 19:24:41 +08:00
setWorkspaceError ( null );
2026-08-06 18:29:04 +08:00
}, [ activeKey , view ]);
2026-08-05 19:24:41 +08:00
2026-05-29 03:42:53 +08:00
const onNewChatInProject = useCallback (
( projectPath : string , projectName : string ) => {
const base = workspaces ? . default_scope ?? activeWorkspaceScope ;
const trimmed = projectPath . trim ();
if ( ! base || ! trimmed ) {
onNewChat ();
return ;
}
2026-08-06 18:29:04 +08:00
setTemporaryChatEnabled ( false );
2026-06-02 11:29:18 +08:00
navigate ( defaultShellRoute ());
2026-05-29 03:42:53 +08:00
setDraftWorkspaceScope ( normalizeWorkspaceScope ({
project_path : trimmed ,
project_name : projectName || projectNameFromPath ( trimmed ),
access_mode : base.access_mode ,
restrict_to_workspace : base.access_mode === "restricted" ,
}));
setWorkspaceError ( null );
setMobileSidebarOpen ( false );
},
2026-06-02 11:29:18 +08:00
[ activeWorkspaceScope , navigate , onNewChat , workspaces ? . default_scope ],
2026-05-29 03:42:53 +08:00
);
2026-04-18 18:51:53 +00:00
const onSelectChat = useCallback (
( key : string ) => {
2026-08-07 11:20:08 +08:00
const selectedTemporary = temporarySessionsRef . current [ key ];
const selected = selectedTemporary
2026-08-06 18:29:04 +08:00
?? sessions . find (( session ) => session . key === key );
2026-05-29 03:42:53 +08:00
const selectedChatId = selected ? . chatId ;
2026-05-19 22:42:38 +08:00
if ( selectedChatId ) {
2026-06-15 17:30:06 +08:00
setUpdatedChatIds (( current ) => {
2026-05-19 22:42:38 +08:00
if ( ! current . has ( selectedChatId )) return current ;
const next = new Set ( current );
next . delete ( selectedChatId );
return next ;
});
}
2026-05-29 03:42:53 +08:00
if ( selected ? . workspaceScope ) {
setDraftWorkspaceScope ( normalizeWorkspaceScope ( selected . workspaceScope ));
} else {
setDraftWorkspaceScope ( null );
}
setWorkspaceError ( null );
2026-08-07 11:20:08 +08:00
navigate ({
view : "chat" ,
activeKey : key ,
settingsSection : "overview" ,
...( selectedTemporary ? { temporary : true } : {}),
});
2026-04-18 18:51:53 +00:00
setMobileSidebarOpen ( false );
},
2026-06-02 11:29:18 +08:00
[ navigate , sessions ],
2026-05-19 22:42:38 +08:00
);
2026-08-06 18:29:04 +08:00
const onCloseTemporaryChat = useCallback (( key : string ) => {
const session = temporarySessionsRef . current [ key ];
if ( ! session ) return ;
const remaining = temporarySessionList . filter (( item ) => item . key !== key );
const nextSessions = Object . fromEntries ( remaining . map (( item ) => [ item . key , item ]));
temporarySessionsRef . current = nextSessions ;
setTemporarySessions ( nextSessions );
client . discardTemporaryChat ( session . chatId );
if ( activeKey === key ) {
if ( remaining . length === 0 ) setDraftWorkspaceScope ( null );
setWorkspaceError ( null );
navigate ({
view : "chat" ,
activeKey : remaining [ 0 ] ? . key ?? null ,
settingsSection : "overview" ,
2026-08-07 11:20:08 +08:00
...( remaining [ 0 ] ? { temporary : true } : {}),
2026-08-06 18:29:04 +08:00
}, { replace : true });
}
setMobileSidebarOpen ( false );
}, [ activeKey , client , navigate , temporarySessionList ]);
2026-05-19 22:42:38 +08:00
const onTogglePin = useCallback (
( key : string ) => {
void updateSidebarState (( current ) => {
const pinned = new Set ( current . pinned_keys );
if ( pinned . has ( key )) {
pinned . delete ( key );
} else {
pinned . add ( key );
}
return {
... current ,
pinned_keys : Array.from ( pinned ),
};
});
},
[ updateSidebarState ],
);
const onRequestRename = useCallback (( key : string , label : string ) => {
setPendingRename ({ key , label });
}, []);
const onConfirmRename = useCallback (
( title : string ) => {
if ( ! pendingRename ) return ;
const key = pendingRename . key ;
setPendingRename ( null );
void updateSidebarState (( current ) => {
const titleOverrides = { ... current . title_overrides };
const cleaned = title . trim ();
if ( cleaned ) {
titleOverrides [ key ] = cleaned ;
} else {
delete titleOverrides [ key ];
}
return {
... current ,
title_overrides : titleOverrides ,
};
});
},
[ pendingRename , updateSidebarState ],
);
2026-08-12 14:45:12 +08:00
const onRequestRenameTab = useCallback (( key : string , label : string ) => {
setPendingTabRename ({ key , label });
}, []);
const onConfirmTabRename = useCallback (( title : string ) => {
if ( ! pendingTabRename ) return ;
updateWorkbenchState (( current ) => (
renameWorkbenchTab ( current , pendingTabRename . key , title )
));
setPendingTabRename ( null );
}, [ pendingTabRename , updateWorkbenchState ]);
2026-05-29 03:42:53 +08:00
const onToggleGroup = useCallback (
( groupId : string ) => {
void updateSidebarState (( current ) => {
const collapsedGroups = { ... current . collapsed_groups };
if ( groupId === "workspace:chats" || groupId === "date:all" ) {
if ( collapsedGroups [ groupId ] === false ) {
delete collapsedGroups [ groupId ];
} else {
collapsedGroups [ groupId ] = false ;
}
return {
... current ,
collapsed_groups : collapsedGroups ,
};
}
if ( collapsedGroups [ groupId ]) {
delete collapsedGroups [ groupId ];
} else {
collapsedGroups [ groupId ] = true ;
}
return {
... current ,
collapsed_groups : collapsedGroups ,
};
});
},
[ updateSidebarState ],
);
const onRequestRenameProject = useCallback (( key : string , label : string ) => {
setPendingProjectRename ({ key , label });
}, []);
const onConfirmProjectRename = useCallback (
( title : string ) => {
if ( ! pendingProjectRename ) return ;
const key = pendingProjectRename . key ;
setPendingProjectRename ( null );
void updateSidebarState (( current ) => {
const projectNameOverrides = { ... current . project_name_overrides };
const cleaned = title . trim ();
if ( cleaned ) {
projectNameOverrides [ key ] = cleaned ;
} else {
delete projectNameOverrides [ key ];
}
return {
... current ,
project_name_overrides : projectNameOverrides ,
};
});
},
[ pendingProjectRename , updateSidebarState ],
);
2026-05-19 22:42:38 +08:00
const onToggleArchive = useCallback (
( key : string ) => {
void updateSidebarState (( current ) => {
const archived = new Set ( current . archived_keys );
const pinned = current . pinned_keys . filter (( item ) => item !== key );
if ( archived . has ( key )) {
archived . delete ( key );
} else {
archived . add ( key );
}
return {
... current ,
pinned_keys : pinned ,
archived_keys : Array.from ( archived ),
};
});
if ( activeKey === key && ! sidebarState . archived_keys . includes ( key )) {
const archived = new Set ([... sidebarState . archived_keys , key ]);
2026-08-12 14:45:12 +08:00
const next = topicSessions . find (( session ) => ! archived . has ( session . key ));
2026-06-02 11:29:18 +08:00
navigate ({
view : "chat" ,
activeKey : next?.key ?? null ,
settingsSection : "overview" ,
});
2026-05-19 22:42:38 +08:00
}
},
2026-08-12 14:45:12 +08:00
[ activeKey , navigate , sidebarState . archived_keys , topicSessions , updateSidebarState ],
2026-08-06 11:19:46 +08:00
);
2026-05-19 22:42:38 +08:00
const onToggleArchived = useCallback (() => {
void updateSidebarState (( current ) => ({
... current ,
view : {
... current . view ,
show_archived : ! current . view . show_archived ,
},
}));
}, [ updateSidebarState ]);
const onOpenSessionSearch = useCallback (() => {
setMobileSidebarOpen ( false );
setSessionSearchOpen ( true );
}, []);
2026-08-12 14:45:12 +08:00
const onAddPane = useCallback ( async () => {
const tabKey = activeTabKey ;
if (
! tabKey
|| ! activeKey
|| ! activeSession
|| creatingPane
|| ( activeTabState ? . paneKeys . length ?? 0 ) >= MAX_WORKBENCH_PANES
|| temporarySessionsRef . current [ activeKey ]
) return ;
setMobileSidebarOpen ( false );
setSessionSearchOpen ( false );
setCreatingPane ( true );
try {
const scope = activeWorkspaceScope ;
const chatId = await createChat ( scope );
const paneKey = `websocket: ${ chatId } ` ;
pendingCreatedSessionKeyRef . current = paneKey ;
updateWorkbenchState (( current ) => addWorkbenchPane ( current , activeKey , paneKey ));
navigate ({
view : "chat" ,
activeKey : paneKey ,
settingsSection : "overview" ,
});
if ( scope ) {
setWorkspaceOverrides (( current ) => ({
... current ,
[ chatId ] : normalizeWorkspaceScope ( scope ),
}));
}
} catch ( error ) {
console . error ( "Failed to create pane" , error );
if ( error instanceof Error && error . message . startsWith ( "workspace_scope_rejected:" )) {
setWorkspaceError ( t ( "errors.workspaceScopeRejected.body" ));
}
} finally {
setCreatingPane ( false );
}
}, [
activeKey ,
activeSession ,
activeTabKey ,
activeTabState ,
activeWorkspaceScope ,
createChat ,
creatingPane ,
navigate ,
t ,
updateWorkbenchState ,
]);
2026-05-19 22:42:38 +08:00
const onSelectSearchResult = useCallback (
( key : string ) => {
setSessionSearchOpen ( false );
onSelectChat ( key );
},
[ onSelectChat ],
2026-04-18 18:51:53 +00:00
);
2026-09-02 04:19:12 +08:00
const onOpenSettings = useCallback (( section : SettingsSectionKey = "overview" ) => {
2026-05-19 22:42:38 +08:00
setSessionSearchOpen ( false );
2026-09-10 11:10:51 +08:00
navigate ({ view : shellViewForSettingsSection ( section ), activeKey , settingsSection : section });
2026-05-06 14:15:36 +00:00
setMobileSidebarOpen ( false );
2026-06-02 11:29:18 +08:00
}, [ activeKey , navigate ]);
2026-05-06 14:15:36 +00:00
2026-07-22 22:35:39 +08:00
const onSettingsIntent = useCallback (() => {
void loadSettingsView ();
}, []);
2026-09-02 04:19:12 +08:00
const onOpenModelSettings = useCallback (() => {
onOpenSettings ( "models" );
2026-06-06 19:49:33 +08:00
}, [ onOpenSettings ]);
2026-05-25 20:07:02 +08:00
const onOpenApps = useCallback (() => {
setSessionSearchOpen ( false );
2026-06-02 11:29:18 +08:00
navigate ({ view : "apps" , activeKey , settingsSection : "apps" });
2026-05-25 20:07:02 +08:00
setMobileSidebarOpen ( false );
2026-06-02 11:29:18 +08:00
}, [ activeKey , navigate ]);
2026-06-13 20:08:18 +08:00
const onOpenAutomations = useCallback (() => {
setSessionSearchOpen ( false );
navigate ({ view : "automations" , activeKey , settingsSection : "automations" });
setMobileSidebarOpen ( false );
}, [ activeKey , navigate ]);
2026-09-10 11:10:51 +08:00
const onOpenChannels = useCallback (() => {
setSessionSearchOpen ( false );
navigate ({ view : "channels" , activeKey , settingsSection : "channels" });
setMobileSidebarOpen ( false );
}, [ activeKey , navigate ]);
2026-06-06 19:49:33 +08:00
const onOpenSkills = useCallback (() => {
setSessionSearchOpen ( false );
navigate ({ view : "skills" , activeKey , settingsSection : "skills" });
setMobileSidebarOpen ( false );
}, [ activeKey , navigate ]);
2026-09-10 11:10:51 +08:00
useEffect (() => {
const actions = { newChat : onNewChat , search : onOpenSessionSearch , apps : onOpenApps ,
skills : onOpenSkills , automations : onOpenAutomations , channels : onOpenChannels , settings : () => onOpenSettings () };
const handleKeyDown = ( event : globalThis.KeyboardEvent ) => {
2026-09-27 20:51:49 +08:00
if ( ! localActive ) return ;
2026-09-10 11:10:51 +08:00
const action = matchSidebarShortcut ( event );
if ( ! action ) return ;
event . preventDefault ();
actions [ action ]();
};
window . addEventListener ( "keydown" , handleKeyDown );
return () => window . removeEventListener ( "keydown" , handleKeyDown );
2026-09-27 20:51:49 +08:00
}, [ localActive , onNewChat , onOpenSessionSearch , onOpenApps , onOpenSkills , onOpenAutomations , onOpenChannels , onOpenSettings ]);
2026-09-10 11:10:51 +08:00
2026-06-02 11:29:18 +08:00
const onSettingsSectionChange = useCallback (
( section : SettingsSectionKey ) => {
navigate ({
2026-06-06 19:49:33 +08:00
view : shellViewForSettingsSection ( section ),
2026-06-02 11:29:18 +08:00
activeKey ,
settingsSection : section ,
});
},
[ activeKey , navigate ],
);
2026-05-25 20:07:02 +08:00
2026-05-08 15:35:18 +00:00
const onBackToChat = useCallback (() => {
setMobileSidebarOpen ( false );
2026-06-02 11:29:18 +08:00
const nextKey = (() => {
if ( ! activeKey ) return null ;
2026-09-25 00:01:12 +08:00
if ( temporarySessionsRef . current [ activeKey ]) return activeKey ;
2026-08-12 14:45:12 +08:00
if ( topicSessions . some (( session ) => session . key === activeKey )) return activeKey ;
2026-09-25 00:01:12 +08:00
return null ;
2026-06-02 11:29:18 +08:00
})();
navigate ({
view : "chat" ,
activeKey : nextKey ,
2026-09-25 00:01:12 +08:00
temporary : Boolean ( nextKey && temporarySessionsRef . current [ nextKey ]),
2026-06-02 11:29:18 +08:00
settingsSection : "overview" ,
2026-05-08 15:35:18 +00:00
});
2026-09-02 04:19:12 +08:00
}, [ activeKey , navigate , topicSessions ]);
2026-05-08 15:35:18 +00:00
2026-05-08 09:40:15 +00:00
const onRestart = useCallback (() => {
const chatId = activeSession ? . chatId ?? client . defaultChatId ;
if ( ! chatId ) return ;
restartSawDisconnectRef . current = false ;
2026-10-12 11:36:42 +08:00
restartStartedAtRef . current = Date . now ();
2026-05-08 15:31:52 +00:00
setIsRestarting ( true );
2026-07-13 13:11:46 +08:00
rememberRestartRoute ();
2026-05-08 09:40:15 +00:00
try {
2026-10-12 11:36:42 +08:00
window . localStorage . setItem ( RESTART_STARTED_KEY , String ( restartStartedAtRef . current ));
2026-05-08 09:40:15 +00:00
} catch {
// ignore storage errors
}
2026-07-24 17:34:26 +08:00
void client . sendSystemCommand ( chatId , "/restart" ). catch (() => {});
2026-05-08 09:40:15 +00:00
}, [ activeSession ? . chatId , client ]);
2026-05-12 09:05:24 +00:00
useEffect (() => {
return client . onRuntimeModelUpdate (( modelName ) => {
onModelNameChange ( modelName );
});
}, [ client , onModelNameChange ]);
2026-05-19 22:42:38 +08:00
useEffect (() => {
return client . onRunStatus (( chatId , startedAt ) => {
if ( startedAt != null ) {
const nextRunning = new Set ( runningChatIdsRef . current );
nextRunning . add ( chatId );
runningChatIdsRef . current = nextRunning ;
setRunningChatIds ( nextRunning );
2026-06-15 17:30:06 +08:00
setUpdatedChatIds (( current ) => {
2026-05-19 22:42:38 +08:00
if ( ! current . has ( chatId )) return current ;
const next = new Set ( current );
next . delete ( chatId );
return next ;
});
return ;
}
if ( ! runningChatIdsRef . current . has ( chatId )) return ;
const nextRunning = new Set ( runningChatIdsRef . current );
nextRunning . delete ( chatId );
runningChatIdsRef . current = nextRunning ;
setRunningChatIds ( nextRunning );
2026-08-07 11:20:08 +08:00
if (
Object . values ( temporarySessionsRef . current ). some (
( session ) => session . chatId === chatId ,
)
) return ;
2026-06-15 17:30:06 +08:00
setUpdatedChatIds (( current ) => {
2026-05-19 22:42:38 +08:00
const next = new Set ( current );
2026-05-30 23:45:26 +08:00
if ( activeChatIdRef . current === chatId ) {
next . delete ( chatId );
} else {
next . add ( chatId );
}
2026-05-19 22:42:38 +08:00
return next ;
});
});
}, [ client ]);
2026-08-05 19:24:41 +08:00
useEffect (() => {
let wasOpen = client . status === "open" ;
return client . onStatus (( status ) => {
if ( status === "open" ) {
wasOpen = true ;
return ;
}
if ( ! wasOpen ) return ;
2026-08-06 18:29:04 +08:00
wasOpen = false ;
2026-09-21 17:48:49 +08:00
filePreviewStore . clear ();
2026-08-06 18:29:04 +08:00
if ( Object . keys ( temporarySessionsRef . current ). length === 0 ) return ;
temporarySessionsRef . current = {};
setTemporarySessions ({});
2026-08-07 11:20:08 +08:00
if ( readShellRoute (). temporary ) {
2026-08-06 18:29:04 +08:00
navigate ( defaultShellRoute (), { replace : true });
}
2026-08-05 19:24:41 +08:00
});
2026-09-21 17:48:49 +08:00
}, [ client , navigate , filePreviewStore ]);
2026-08-05 19:24:41 +08:00
2026-05-08 09:40:15 +00:00
useEffect (() => {
2026-09-23 17:27:34 +08:00
let cancelled = false ;
let retryTimer : number | undefined ;
const refreshSettings = ( generation : number , attempt = 0 ) : void => {
void fetchSettings ( getToken ())
. then (( payload ) => {
if ( ! cancelled && generation === settingsRefreshGenerationRef . current ) {
setSettingsSnapshot ( payload );
}
})
. catch (() => {
if ( cancelled || generation !== settingsRefreshGenerationRef . current || attempt >= 3 ) return ;
retryTimer = window . setTimeout (() => refreshSettings ( generation , attempt + 1 ), 250 );
});
};
const unsubscribe = client . onStatus (( status ) => {
2026-10-12 11:36:42 +08:00
// Another tab can consume the reload marker before this tab reconnects.
const startedAt = restartStartedAtRef . current || (() => {
2026-05-24 14:44:42 +08:00
try {
return Number ( window . localStorage . getItem ( RESTART_STARTED_KEY ) ?? "0" );
} catch {
return 0 ;
}
})();
2026-05-08 09:40:15 +00:00
if ( ! startedAt ) return ;
if ( status !== "open" ) {
2026-10-12 11:36:42 +08:00
restartStartedAtRef . current = startedAt ;
2026-05-08 09:40:15 +00:00
restartSawDisconnectRef . current = true ;
return ;
}
const elapsedMs = Date . now () - startedAt ;
if ( ! restartSawDisconnectRef . current && elapsedMs < 1500 ) return ;
try {
window . localStorage . removeItem ( RESTART_STARTED_KEY );
2026-07-13 13:11:46 +08:00
window . localStorage . removeItem ( RESTART_ROUTE_KEY );
2026-05-08 09:40:15 +00:00
} catch {
// ignore storage errors
}
2026-09-23 17:27:34 +08:00
const refreshGeneration = ++ settingsRefreshGenerationRef . current ;
2026-10-12 11:36:42 +08:00
restartStartedAtRef . current = 0 ;
2026-05-08 15:31:52 +00:00
setIsRestarting ( false );
2026-05-08 09:40:15 +00:00
setRestartToast ( t ( "app.restart.completed" , { seconds : ( elapsedMs / 1000 ). toFixed ( 1 ) }));
window . setTimeout (() => setRestartToast ( null ), 3 _500 );
2026-09-23 17:27:34 +08:00
refreshSettings ( refreshGeneration );
2026-05-08 09:40:15 +00:00
});
2026-09-23 17:27:34 +08:00
return () => {
cancelled = true ;
unsubscribe ();
if ( retryTimer !== undefined ) window . clearTimeout ( retryTimer );
};
}, [ client , getToken , t ]);
2026-05-08 09:40:15 +00:00
2026-08-05 19:24:41 +08:00
const onTurnEnd = useDeferredTitleRefresh (
2026-08-12 14:45:12 +08:00
temporaryChatActive ? null : activePaneSession ,
2026-08-05 19:24:41 +08:00
refresh ,
);
2026-05-06 14:15:36 +00:00
2026-04-18 18:51:53 +00:00
const onConfirmDelete = useCallback ( async () => {
if ( ! pendingDelete ) return ;
2026-08-12 14:45:12 +08:00
const items = pendingDelete . items ;
const deletingKeys = new Set ( items . map (( item ) => item . key ));
2026-06-12 17:02:29 +08:00
const hasAutomations = ( pendingDelete . automations ? . length ?? 0 ) > 0 ;
2026-08-12 14:45:12 +08:00
const deletingActive = activeKey !== null && deletingKeys . has ( activeKey );
const currentIndex = topicSessions . findIndex (( s ) => s . key === activeKey );
2026-08-29 11:44:03 +08:00
const availableKeys = new Set ( topicSessions . map (( session ) => session . key ));
const siblingFallbackKey = deletingActive
? activeTabState ? . paneKeys . find (( key ) => (
! deletingKeys . has ( key ) && availableKeys . has ( key )
)) ?? null
: null ;
2026-04-18 18:51:53 +00:00
const fallbackKey = deletingActive
2026-08-12 14:45:12 +08:00
? (
2026-08-29 11:44:03 +08:00
siblingFallbackKey
?? topicSessions . slice ( currentIndex + 1 ). find (( session ) => (
2026-08-12 14:45:12 +08:00
! deletingKeys . has ( session . key )
)) ? . key
?? topicSessions . slice ( 0 , Math . max ( 0 , currentIndex )). reverse (). find (( session ) => (
! deletingKeys . has ( session . key )
)) ? . key
?? null
)
2026-04-18 18:51:53 +00:00
: activeKey ;
try {
2026-08-12 14:45:12 +08:00
for ( let index = 0 ; index < items . length ; index += 1 ) {
const item = items [ index ];
const result = await deleteChat (
item . key ,
hasAutomations ? { deleteAutomations : true } : undefined ,
);
if ( result . blocked_by_automations ) {
setPendingDelete ({
items : items.slice ( index ),
automations : result.automations ?? [],
});
return ;
}
2026-09-21 17:48:49 +08:00
filePreviewStore . delete ( item . key );
2026-09-25 23:42:01 +08:00
draftStore . delete ( item . key );
2026-06-11 19:11:37 +08:00
}
setPendingDelete ( null );
2026-06-02 11:29:18 +08:00
if ( deletingActive ) {
navigate ({
view : "chat" ,
2026-06-11 19:11:37 +08:00
activeKey : fallbackKey ,
2026-06-02 11:29:18 +08:00
settingsSection : "overview" ,
}, { replace : true });
}
2026-06-11 19:11:37 +08:00
} catch ( e ) {
2026-04-18 18:51:53 +00:00
console . error ( "Failed to delete session" , e );
}
2026-09-25 23:42:01 +08:00
}, [ pendingDelete , deleteChat , activeKey , activeTabState , navigate , topicSessions , filePreviewStore , draftStore ]);
2026-04-18 18:51:53 +00:00
2026-08-12 14:45:12 +08:00
const onRequestDeleteMany = useCallback ( async ( items : SidebarDeleteItem []) => {
const uniqueItems = Array . from ( new Map ( items . map (( item ) => [ item . key , item ])). values ());
if ( uniqueItems . length === 0 ) return ;
const automationResults = await Promise . allSettled (
uniqueItems . map (( item ) => getSessionAutomations ( item . key )),
);
const automations = automationResults . flatMap (( result ) => (
result . status === "fulfilled" ? result . value : []
));
setPendingDelete ({ items : uniqueItems , automations });
2026-06-12 18:13:25 +08:00
}, [ getSessionAutomations ]);
2026-06-12 17:02:29 +08:00
2026-08-12 14:45:12 +08:00
const onRequestDelete = useCallback (( key : string , label : string ) => {
void onRequestDeleteMany ([{ key , label }]);
}, [ onRequestDeleteMany ]);
2026-07-13 13:11:46 +08:00
const visiblePairingRequests = useMemo (
() => {
const now = Date . now ();
return pairingRequests . filter (( request ) => {
2026-10-11 18:31:50 +08:00
const snooze = snoozedPairingCodes . get ( request . code );
return ! snooze || snooze . until <= now ;
2026-07-13 13:11:46 +08:00
});
},
[ pairingRequests , snoozedPairingCodes ],
);
const onPairingAction = useCallback (
async ( action : "approve" | "deny" , code : string ) => {
setPairingBusyCode ( code );
setPairingError ( null );
try {
2026-08-10 15:43:54 +08:00
const payload = await runPairingAction ( client , action , code );
2026-07-13 13:11:46 +08:00
setPairingRequests ( Array . isArray ( payload . requests ) ? payload . requests : []);
setSnoozedPairingCodes (( current ) => {
if ( ! current . has ( code )) return current ;
const next = new Map ( current );
next . delete ( code );
return next ;
});
} catch ( e ) {
setPairingError (( e as Error ). message );
void refreshPairingRequests ();
} finally {
setPairingBusyCode ( null );
}
},
2026-08-10 15:43:54 +08:00
[ client , refreshPairingRequests ],
2026-07-13 13:11:46 +08:00
);
2026-10-11 18:31:50 +08:00
const onDismissPairingRequest = useCallback (( request : PairingRequestInfo ) => {
2026-07-13 13:11:46 +08:00
setSnoozedPairingCodes (( current ) => {
const next = new Map ( current );
2026-10-11 18:31:50 +08:00
next . set ( request . code , {
until : Date.now () + PAIRING_DISMISS_SNOOZE_MS ,
deliveryStatus : request.delivery_status ,
});
2026-07-13 13:11:46 +08:00
return next ;
});
}, []);
2026-08-12 14:45:12 +08:00
const titleForSession = useCallback (( session : ChatSummary ) => (
sidebarState . title_overrides [ session . key ]
|| session . title
|| deriveTitle ( session . preview , t ( "chat.newChat" ))
), [ sidebarState . title_overrides , t ]);
const automaticSidebarSort = sidebarState . view . sort === "manual"
? "updated_desc"
: sidebarState . view . sort ;
const orderedWorkbenchTabs = useMemo (() => {
const orderedSessions = sortSessions (
sessions ,
automaticSidebarSort ,
sidebarState . title_overrides ,
sidebarState . session_order ,
);
const updatedAtByKey = new Map ( sessions . map (( session ) => [
session . key ,
session . updatedAt ?? session . createdAt ,
]));
return orderWorkbenchTabs (
workbenchState ,
orderedSessions . map (( session ) => session . key ),
updatedAtByKey ,
);
}, [
automaticSidebarSort ,
sessions ,
sidebarState . session_order ,
sidebarState . title_overrides ,
workbenchState ,
]);
const orderedWorkbenchTabsByKey = useMemo (
() => new Map ( orderedWorkbenchTabs . map (( tab ) => [ tab . tabKey , tab ])),
[ orderedWorkbenchTabs ],
);
const sidebarTabPresentations = useMemo (() => {
const sessionsByKey = new Map ( sessions . map (( session ) => [ session . key , session ]));
return orderedWorkbenchTabs . flatMap (( tab ) => {
const anchorKey = tab . tab . paneKeys . find (( key ) => sessionsByKey . has ( key ))
?? tab . paneKeys [ 0 ];
const anchor = sessionsByKey . get ( anchorKey );
if ( ! anchor ) return [];
const title = tab . tab . title ?? titleForSession ( anchor );
const visible = tab . tab . explicit || tab . paneKeys . length > 1 ;
const rowKey = visible ? tab.tabKey : tab.paneKeys [ 0 ];
return [{
orderedTab : tab ,
rowKey ,
title ,
session : visible
? {
... anchor ,
key : tab.tabKey ,
chatId : `workbench-tab: ${ tab . tabKey } ` ,
title ,
preview : "" ,
updatedAt : tab.updatedAt ,
}
: anchor ,
}];
});
}, [ orderedWorkbenchTabs , sessions , titleForSession ]);
const sidebarTopicSessions = useMemo (
() => sidebarTabPresentations . map (( presentation ) => presentation . session ),
[ sidebarTabPresentations ],
);
2026-08-05 19:24:41 +08:00
const headerTitle = temporaryChatActive
2026-08-07 13:27:53 +08:00
? deriveTemporaryChatTitle ( activeSession ? . preview , t ( "temporaryChat.title" ))
2026-08-05 19:24:41 +08:00
: activeSession
2026-08-12 14:45:12 +08:00
? titleForSession ( activeSession )
2026-04-19 06:39:06 +00:00
: t ( "app.brand" );
2026-08-12 14:45:12 +08:00
const workbenchPaneSessions = useMemo (() => {
if ( ! activeTabState ) return [];
const byKey = new Map ( sessions . map (( session ) => [ session . key , session ]));
const sortedPaneKeys = activeTabKey
? orderedWorkbenchTabsByKey . get ( activeTabKey ) ? . paneKeys ?? activeTabState.paneKeys
: activeTabState.paneKeys ;
const paneKeys = [
... activeTabState . layoutPaneKeys . filter (( key ) => byKey . has ( key )),
... sortedPaneKeys . filter (( key ) => ! activeTabState . layoutPaneKeys . includes ( key )),
];
return paneKeys
. map (( key ) => byKey . get ( key ))
. filter (( session ) : session is ChatSummary => session !== undefined );
}, [ activeTabKey , activeTabState , orderedWorkbenchTabsByKey , sessions ]);
const paneChromeEnabled = Boolean (
activeKey && activeSession && ! temporaryChatActive && activeTabState ,
);
const activeTabVisible = Boolean (
activeTabState
&& ( activeTabState . explicit || activeTabState . paneKeys . length > 1 ),
);
const renderedWorkbenchPanes = useMemo (() => {
if ( paneChromeEnabled ) {
return workbenchPaneSessions . map (( session ) => ({
key : session.key ,
reactKey : session.key === activeTabState ? . paneKeys [ 0 ]
? "tab-root"
: `pane: ${ session . key } ` ,
title : titleForSession ( session ),
}));
}
return [{
key : activeKey ?? "new-topic" ,
reactKey : "tab-root" ,
title : headerTitle ,
}];
}, [
activeKey ,
activeTabState ? . paneKeys ,
headerTitle ,
paneChromeEnabled ,
titleForSession ,
workbenchPaneSessions ,
]);
const renderedActivePaneKey = activeKey ?? renderedWorkbenchPanes [ 0 ]. key ;
const renderedWorkbenchLayout = paneChromeEnabled && activeTabState
? activeTabState . layout
: "columns" ;
const renderedWorkbenchSplitRatios = paneChromeEnabled && activeTabState
? activeTabState . splitRatios
: [];
const sidebarPaneGroups = useMemo (() => {
const sessionsByKey = new Map ( sessions . map (( session ) => [ session . key , session ]));
return Object . fromEntries ( sidebarTabPresentations . map (( presentation ) => {
const orderedTab = presentation . orderedTab ;
const panes = orderedTab . paneKeys
. map (( key ) => sessionsByKey . get ( key ))
. filter (( session ) : session is ChatSummary => session !== undefined )
. map (( session ) => ({
key : session.key ,
chatId : session.chatId ,
title : titleForSession ( session ),
2026-08-18 09:53:55 +08:00
handle : session.handle ,
2026-08-12 14:45:12 +08:00
}));
return [ presentation . rowKey , {
tabKey : orderedTab.tabKey ,
title : presentation.title ,
activePaneKey : activeKey && orderedTab . paneKeys . includes ( activeKey )
? activeKey
: orderedTab.paneKeys [ 0 ],
visible : orderedTab.tab.explicit || orderedTab . paneKeys . length > 1 ,
panes ,
}];
}));
}, [
activeKey ,
sessions ,
sidebarTabPresentations ,
titleForSession ,
]);
const activePaneLimitReached = Boolean (
activeTabState && activeTabState . paneKeys . length >= MAX_WORKBENCH_PANES ,
);
const onActivateWorkbenchPane = useCallback (( paneKey : string ) => {
onSelectChat ( paneKey );
}, [ onSelectChat ]);
const onSelectSidebarTab = useCallback (( tabKey : string ) => {
const tab = workbenchTab ( workbenchState , tabKey );
if ( ! tab ) return ;
const rememberedPaneKey = lastActivePaneByTabRef . current . get ( tabKey );
onSelectChat (
rememberedPaneKey && tab . paneKeys . includes ( rememberedPaneKey )
? rememberedPaneKey
: tab.paneKeys [ 0 ],
);
}, [ onSelectChat , workbenchState ]);
const onSelectSidebarItem = useCallback (( key : string ) => {
if (
temporarySessionsRef . current [ key ]
|| sessions . some (( session ) => session . key === key )
) {
onSelectChat ( key );
return ;
}
onSelectSidebarTab ( key );
}, [ onSelectChat , onSelectSidebarTab , sessions ]);
const onSelectSidebarPane = useCallback (( _tabKey : string , paneKey : string ) => {
onSelectChat ( paneKey );
}, [ onSelectChat ]);
const onDetachWorkbenchPane = useCallback (( tabKey : string , paneKey : string ) => {
updateWorkbenchState (( current ) => detachWorkbenchPane ( current , tabKey , paneKey ));
}, [ updateWorkbenchState ]);
const onCreateWorkbenchTab = useCallback (( paneKey : string ) => {
updateWorkbenchState (( current ) => createWorkbenchTab ( current , paneKey ));
}, [ updateWorkbenchState ]);
const onDissolveWorkbenchTab = useCallback (( tabKey : string ) => {
updateWorkbenchState (( current ) => dissolveWorkbenchTab ( current , tabKey ));
}, [ updateWorkbenchState ]);
const onAttachWorkbenchPane = useCallback ((
paneKey : string ,
tabKey : string ,
) => {
updateWorkbenchState (( current ) => {
const target = workbenchTab ( current , tabKey );
if (
! target
|| ( ! target . explicit && target . paneKeys . length < 2 )
|| ( ! target . paneKeys . includes ( paneKey ) && target . paneKeys . length >= MAX_WORKBENCH_PANES )
) return current ;
return attachWorkbenchPane ( current , tabKey , paneKey );
});
}, [ updateWorkbenchState ]);
2026-04-19 06:39:06 +00:00
useEffect (() => {
2026-09-27 20:51:49 +08:00
if ( ! localActive ) return ;
2026-05-08 15:31:52 +00:00
if ( view === "settings" ) {
document . title = t ( "app.documentTitle.chat" , {
title : t ( "settings.sidebar.title" ),
});
return ;
}
2026-05-25 20:07:02 +08:00
if ( view === "apps" ) {
document . title = t ( "app.documentTitle.chat" , {
title : t ( "settings.nav.apps" , { defaultValue : "Apps" }),
});
return ;
}
2026-06-13 20:08:18 +08:00
if ( view === "automations" ) {
document . title = t ( "app.documentTitle.chat" , {
title : t ( "settings.nav.automations" , { defaultValue : "Automations" }),
});
return ;
}
2026-09-10 11:10:51 +08:00
if ( view === "channels" ) {
document . title = t ( "app.documentTitle.chat" , { title : t ( "settings.nav.channels" ) });
return ;
}
2026-09-27 20:51:49 +08:00
if ( view === "remote" ) {
document . title = t ( "app.documentTitle.chat" , { title : t ( "remote.title" ) });
return ;
}
2026-06-06 19:49:33 +08:00
if ( view === "skills" ) {
document . title = t ( "app.documentTitle.chat" , {
title : t ( "settings.nav.skills" , { defaultValue : "Skills" }),
});
return ;
}
2026-04-19 06:39:06 +00:00
document . title = activeSession
? t ( "app.documentTitle.chat" , { title : headerTitle })
: t ( "app.documentTitle.base" );
2026-09-27 20:51:49 +08:00
}, [ localActive , activeSession , headerTitle , i18n . resolvedLanguage , t , view ]);
2026-04-18 18:51:53 +00:00
2026-08-12 14:45:12 +08:00
const pinnedPaneKeys = useMemo (
() => new Set ( sidebarState . pinned_keys ),
[ sidebarState . pinned_keys ],
);
const archivedPaneKeys = useMemo (
() => new Set ( sidebarState . archived_keys ),
[ sidebarState . archived_keys ],
);
const sidebarPinnedTabKeys = useMemo (() => sidebarTabPresentations
. filter (({ orderedTab }) => orderedTab . paneKeys . some (( key ) => pinnedPaneKeys . has ( key )))
. map (({ rowKey }) => rowKey ), [ pinnedPaneKeys , sidebarTabPresentations ]);
const sidebarArchivedTabKeys = useMemo (() => sidebarTabPresentations
. filter (({ orderedTab }) => orderedTab . paneKeys . every (( key ) => archivedPaneKeys . has ( key )))
. map (({ rowKey }) => rowKey ), [ archivedPaneKeys , sidebarTabPresentations ]);
const activeSidebarKey = activeTabKey
? sidebarTabPresentations . find (({ orderedTab }) => (
orderedTab . tabKey === activeTabKey
)) ? . rowKey ?? activeKey
: activeKey ;
2026-04-18 18:51:53 +00:00
const sidebarProps = {
2026-10-16 15:47:15 +08:00
sessions : sidebarStateLoading ? [] : sidebarTopicSessions ,
temporarySessions : sidebarStateLoading ? [] : temporarySessionList ,
2026-09-30 23:30:25 +08:00
activeKey : ! managingConnections && view === "chat"
2026-08-12 14:45:12 +08:00
? ( temporaryChatActive ? activeKey : activeSidebarKey )
: null ,
2026-10-16 15:47:15 +08:00
loading : loading || sidebarStateLoading ,
2026-09-30 23:30:25 +08:00
newChatActive : ! managingConnections && view === "chat" && activeKey === null ,
2026-05-06 14:15:36 +00:00
onNewChat ,
2026-08-12 14:45:12 +08:00
onSelect : onSelectSidebarItem ,
2026-08-06 18:29:04 +08:00
onCloseTemporaryChat ,
2026-06-12 17:02:29 +08:00
onRequestDelete ,
2026-08-12 14:45:12 +08:00
onRequestDeleteMany ,
2026-05-19 22:42:38 +08:00
onTogglePin ,
onRequestRename ,
onToggleArchive ,
2026-08-12 14:45:12 +08:00
onRequestRenameTab ,
paneGroups : sidebarPaneGroups ,
onSelectPane : onSelectSidebarPane ,
onCreateTab : mobileWorkbench ? undefined : onCreateWorkbenchTab ,
onDetachPane : mobileWorkbench ? undefined : onDetachWorkbenchPane ,
onDissolveTab : mobileWorkbench ? undefined : onDissolveWorkbenchTab ,
onAttachPane : mobileWorkbench ? undefined : onAttachWorkbenchPane ,
2026-05-29 03:42:53 +08:00
onToggleGroup ,
onRequestRenameProject ,
onNewChatInProject ,
2026-05-08 15:31:52 +00:00
onOpenSettings ,
2026-05-25 20:07:02 +08:00
onOpenApps ,
2026-06-13 20:08:18 +08:00
onOpenAutomations ,
2026-09-10 11:10:51 +08:00
onOpenChannels ,
2026-06-06 19:49:33 +08:00
onOpenSkills ,
2026-07-22 22:35:39 +08:00
onSettingsIntent ,
2026-05-19 22:42:38 +08:00
onOpenSearch : onOpenSessionSearch ,
2026-09-30 23:30:25 +08:00
activeUtility : ! managingConnections && ( view === "apps" || view === "automations" || view === "skills" || view === "channels" ) ? view : null ,
2026-05-19 22:42:38 +08:00
onToggleArchived ,
2026-08-12 14:45:12 +08:00
pinnedKeys : sidebarPinnedTabKeys ,
archivedKeys : sidebarArchivedTabKeys ,
pinnedPaneKeys : sidebarState.pinned_keys ,
archivedPaneKeys : sidebarState.archived_keys ,
2026-08-06 11:19:46 +08:00
sessionOrder : sidebarState.session_order ,
2026-05-19 22:42:38 +08:00
titleOverrides : sidebarState.title_overrides ,
2026-05-29 03:42:53 +08:00
projectNameOverrides : sidebarState.project_name_overrides ,
collapsedGroups : sidebarState.collapsed_groups ,
2026-05-19 22:42:38 +08:00
runningChatIds : runningChatIdList ,
2026-06-15 17:30:06 +08:00
updatedChatIds : updatedChatIdList ,
2026-08-22 19:33:22 +08:00
recoveryChatIds : recoveryChatIdList ,
2026-08-12 14:45:12 +08:00
viewState : { ... sidebarState . view , sort : automaticSidebarSort },
2026-05-19 22:42:38 +08:00
showArchived : sidebarState.view.show_archived ,
2026-08-12 14:45:12 +08:00
archivedCount : sidebarArchivedTabKeys.length ,
2026-05-29 03:42:53 +08:00
defaultWorkspacePath : workspaces?.default_scope.project_path ?? null ,
2026-04-18 18:51:53 +00:00
};
2026-09-10 11:10:51 +08:00
const hostSidebarFlowWidth = hostSidebarOpen ? sidebarWidth : SIDEBAR_RAIL_WIDTH ;
2026-04-18 18:51:53 +00:00
2026-05-31 17:00:42 +08:00
useEffect (() => {
document . documentElement . classList . toggle ( "native-host" , showHostChrome );
return () => {
document . documentElement . classList . remove ( "native-host" );
};
}, [ showHostChrome ]);
2026-04-18 18:51:53 +00:00
return (
2026-05-17 17:04:57 +08:00
< ThemeProvider theme = { theme }>
2026-09-30 23:30:25 +08:00
< StarPrompt ready = { localActive && ! managingConnections && ! loading && ! sidebarStateLoading } />
2026-05-29 03:42:53 +08:00
< div
className = { cn (
"relative h-full w-full overflow-hidden" ,
2026-05-31 17:00:42 +08:00
showHostChrome && "host-window-shell" ,
2026-05-29 03:42:53 +08:00
)}
>
{ showHostChrome ? (
< HostChrome
2026-06-06 19:49:33 +08:00
rightAction = {
view === "chat" ? undefined : (
< Button
type = "button"
variant = "ghost"
size = "icon"
aria-label = { t ( "thread.header.toggleTheme" )}
onClick = { toggle }
className = "h-8 w-8 rounded-full text-muted-foreground/85 hover:bg-accent/40 hover:text-foreground"
>
{ theme === "dark" ? (
< Sun className = "h-4 w-4" />
) : (
< Moon className = "h-4 w-4" />
)}
</ Button >
)
}
2026-05-29 03:42:53 +08:00
/>
) : null }
< div
className = { cn (
"relative flex h-full w-full overflow-hidden" ,
)}
>
{ /* Host sidebar: in normal flow, so the thread area width stays honest. */ }
{ showMainSidebar ? (
< aside
2026-06-06 19:49:33 +08:00
data-testid = "host-sidebar-flow"
2026-09-11 19:36:57 +08:00
data-resizing = { sidebarDragging || undefined }
2026-09-10 11:10:51 +08:00
id = "main-sidebar"
2026-05-29 03:42:53 +08:00
className = { cn (
2026-09-11 19:36:57 +08:00
"group/sidebar relative z-20 hidden shrink-0 overflow-hidden lg:block" ,
2026-09-10 11:10:51 +08:00
sidebarDragging ? "select-none" : "transition-[width] duration-300 ease-out motion-reduce:transition-none" ,
2026-05-29 03:42:53 +08:00
)}
style = {{
2026-06-06 19:49:33 +08:00
width : hostSidebarFlowWidth ,
2026-05-29 03:42:53 +08:00
}}
>
2026-09-03 00:01:39 +08:00
< div
className = { cn (
"absolute inset-y-0 left-0 h-full w-full overflow-hidden" ,
showHostChrome
? "host-sidebar-glass"
: "bg-sidebar" ,
)}
>
2026-05-29 03:42:53 +08:00
< Sidebar
{ ...sidebarProps }
2026-09-03 00:01:39 +08:00
collapsed = { ! hostSidebarOpen }
2026-05-29 03:42:53 +08:00
hostChromeInset = { showHostChrome }
onExpand = { openHostSidebar }
/>
</ div >
2026-09-10 11:10:51 +08:00
< SidebarResizeHandle
width = { sidebarWidth }
open = { hostSidebarOpen }
onDraggingChange = { setSidebarDragging }
onResize = {( width , open ) => {
if ( open ) setSidebarWidth ( width );
setHostSidebarOpen ( open );
}}
/>
2026-05-29 03:42:53 +08:00
</ aside >
) : null }
{ showMainSidebar ? (
< Sheet
open = { mobileSidebarOpen }
onOpenChange = {( open ) => setMobileSidebarOpen ( open )}
>
< SheetContent
2026-09-21 13:44:42 +08:00
ref = { mobileSidebarRef }
onOpenAutoFocus = {( event ) => {
// Keep opening navigation from focusing the search tooltip trigger.
event . preventDefault ();
mobileSidebarRef . current ? . focus ({ preventScroll : true });
}}
2026-05-29 03:42:53 +08:00
side = "left"
showCloseButton = { false }
aria-describedby = { undefined }
className = "p-0 lg:hidden"
2026-06-14 16:46:34 +08:00
style = {{ width : MOBILE_SIDEBAR_WIDTH , maxWidth : MOBILE_SIDEBAR_WIDTH }}
2026-05-29 03:42:53 +08:00
>
< SheetTitle className = "sr-only" >{ t ( "sidebar.navigation" )}</ SheetTitle >
< Sidebar
{ ...sidebarProps }
onCollapse = { closeMobileSidebar }
containActionMenus
/>
</ SheetContent >
</ Sheet >
) : null }
2026-07-22 22:35:39 +08:00
{ sessionSearchOpen ? (
< Suspense fallback = { null }>
< SessionSearchDialog
open
onOpenChange = { setSessionSearchOpen }
2026-08-12 14:45:12 +08:00
sessions = { topicSessions }
2026-07-22 22:35:39 +08:00
activeKey = { activeKey }
loading = { loading }
titleOverrides = { sidebarState . title_overrides }
onSelect = { onSelectSearchResult }
/>
</ Suspense >
) : null }
2026-10-01 23:42:47 +08:00
< main ref = { managementMain }
aria-hidden = { managingConnections && remoteConnections ? . embeddedManagement || undefined }
{ ... ( managingConnections && remoteConnections ? .embeddedManagement ? { inert : "" } : {} ) }
2026-05-31 17:00:42 +08:00
className = { cn (
"relative flex h-full min-w-0 flex-1 flex-col overflow-hidden bg-background" ,
)}
>
2026-09-30 23:30:25 +08:00
< div className = { cn ( "absolute inset-0 flex flex-col" , managingConnections && "hidden" )}
aria-hidden = { managingConnections || undefined } { ... ( managingConnections ? { inert : "" } : {} ) }>
2026-09-25 00:01:12 +08:00
{( view === "chat" || chatVisited ) && < div
2026-05-29 03:42:53 +08:00
className = { cn (
"absolute inset-0 flex flex-col" ,
2026-07-22 22:35:39 +08:00
view !== "chat" && "hidden" ,
2026-05-29 03:42:53 +08:00
)}
2026-05-17 17:04:57 +08:00
>
2026-09-30 23:30:25 +08:00
< ThreadVisibilityContext.Provider value = { localActive && ! managingConnections && view === "chat" }>
2026-09-24 23:10:57 +08:00
< Suspense fallback = {< StartupShell embedded />}>
2026-09-09 14:02:26 +08:00
< PaneWorkbench
panes = { renderedWorkbenchPanes }
activePaneKey = { renderedActivePaneKey }
layout = { renderedWorkbenchLayout }
splitRatios = { renderedWorkbenchSplitRatios }
chrome = { paneChromeEnabled }
showLayoutControl = { activeTabVisible }
addPaneDisabled = { creatingPane || activePaneLimitReached }
addPaneDisabledLabel = { activePaneLimitReached
? t ( "workbench.paneLimit" , {
count : MAX_WORKBENCH_PANES ,
})
: undefined }
onActivatePane = { onActivateWorkbenchPane }
onAddPane = { onAddPane }
onLayoutChange = {( layout ) => {
if ( ! activeTabKey ) return ;
updateWorkbenchState (( current ) => (
setWorkbenchLayout ( current , activeTabKey , layout )
));
}}
onPaneOrderChange = {( paneKeys ) => {
if ( ! activeTabKey ) return ;
updateWorkbenchState (( current ) => (
setWorkbenchPaneLayoutOrder ( current , activeTabKey , paneKeys )
));
}}
onSplitRatiosChange = {( splitRatios ) => {
if ( ! activeTabKey ) return ;
updateWorkbenchState (( current ) => (
setWorkbenchSplitRatios ( current , activeTabKey , splitRatios )
));
}}
renderPane = {( pane , context ) => {
if ( ! paneChromeEnabled ) {
return (
< ThreadShell
session = { activeSession }
sessions = { sessions }
title = { headerTitle }
temporary = { temporaryChatRequested }
temporaryChatIds = { temporaryChatIds }
2026-09-21 00:41:00 +08:00
messageCache = { threadMessageCache }
2026-09-21 17:48:49 +08:00
filePreviewStore = { filePreviewStore }
2026-09-25 23:42:01 +08:00
draftStore = { draftStore }
2026-09-09 14:02:26 +08:00
temporaryChatEnabled = { temporaryChatEnabled }
onTemporaryChatEnabledChange = {
! activeKey ? onTemporaryChatEnabledChange : undefined
}
onToggleSidebar = { toggleSidebar }
onNewChat = { onNewChat }
onCreateChat = {
temporaryChatEnabled ? onCreateTemporaryChat : onCreateChat
}
2026-09-12 16:32:46 +08:00
pendingFirstMessage = { pendingAutomationMessage }
onPendingFirstMessageConsumed = { onPendingAutomationMessageConsumed }
2026-09-09 14:02:26 +08:00
onForkChat = { temporaryChatActive ? undefined : onForkChat }
onTurnEnd = { onTurnEnd }
theme = { theme }
onToggleTheme = { toggle }
hideSidebarToggleForHostChrome
hideHeader = { false }
workspaceScope = { activeWorkspaceScope }
workspaceDefaultScope = { workspaces ? . default_scope ?? null }
workspaceControls = { workspaces ? . controls ?? null }
workspaceScopeDisabled = { activeChatRunning }
workspaceError = { workspaceError }
onWorkspaceScopeChange = { applyWorkspaceScope }
settingsSnapshot = { settingsSnapshot }
2026-09-24 22:05:31 +08:00
settingsLoading = { settingsLoading }
2026-09-09 14:02:26 +08:00
onOpenModelSettings = { onOpenModelSettings }
skills = { skills }
/>
);
}
2026-08-12 14:45:12 +08:00
2026-09-09 14:02:26 +08:00
const paneSession = workbenchPaneSessions . find (
( session ) => session . key === pane . key ,
);
if ( ! paneSession ) return null ;
const paneScope = workspaceOverrides [ paneSession . chatId ]
?? paneSession . workspaceScope
?? workspaces ? . default_scope
?? null ;
const paneRunning = runningChatIds . has ( paneSession . chatId );
return (
< ThreadShell
session = { paneSession }
sessions = { sessions }
title = { pane . title }
2026-09-21 00:41:00 +08:00
temporaryChatIds = { temporaryChatIds }
messageCache = { threadMessageCache }
2026-09-21 17:48:49 +08:00
filePreviewStore = { filePreviewStore }
2026-09-25 23:42:01 +08:00
draftStore = { draftStore }
2026-09-09 14:02:26 +08:00
onToggleSidebar = { toggleSidebar }
onNewChat = { onNewChat }
onCreateChat = { onCreateChat }
2026-09-12 16:32:46 +08:00
pendingFirstMessage = { pendingAutomationMessage }
onPendingFirstMessageConsumed = { onPendingAutomationMessageConsumed }
2026-09-09 14:02:26 +08:00
onForkChat = { onForkChat }
onTurnEnd = { context . active ? onTurnEnd : () => void refresh ()}
theme = { theme }
onToggleTheme = { toggle }
hideSidebarToggle = { ! context . active }
hideSidebarToggleForHostChrome = { context . active }
hideThemeButton = { ! context . active }
hideHeaderTitle
2026-09-10 13:27:01 +08:00
inlineHandle = { ! mobileWorkbench && workbenchPaneSessions . length > 1 }
2026-09-09 14:02:26 +08:00
headerActions = { context . headerActions }
headerPortalTarget = { context . headerPortalTarget }
headerActive = { context . active }
composerPortalTarget = { context . composerPortalTarget }
composerActive = { context . active }
composerInputAriaLabel = { t ( "workbench.composerAria" , {
title : pane.title ,
})}
emptyComposerVariant = "thread"
workspaceScope = { paneScope }
workspaceDefaultScope = { workspaces ? . default_scope ?? null }
workspaceControls = { workspaces ? . controls ?? null }
workspaceScopeDisabled = { paneRunning }
workspaceError = { context . active ? workspaceError : null }
onWorkspaceScopeChange = {( scope ) => {
if ( paneRunning ) return ;
const next = normalizeWorkspaceScope ( scope );
setWorkspaceError ( null );
setWorkspaceOverrides (( current ) => ({
... current ,
[ paneSession . chatId ] : next ,
}));
client . setWorkspaceScope ( paneSession . chatId , next );
}}
settingsSnapshot = { settingsSnapshot }
2026-09-24 22:05:31 +08:00
settingsLoading = { settingsLoading }
2026-09-09 14:02:26 +08:00
onOpenModelSettings = { onOpenModelSettings }
skills = { skills }
/>
);
}}
/>
</ Suspense >
</ ThreadVisibilityContext.Provider >
2026-09-25 00:01:12 +08:00
</ div >}
2026-05-29 03:42:53 +08:00
{ view !== "chat" && (
< div className = "absolute inset-0 flex flex-col" >
2026-09-27 20:51:49 +08:00
{ view === "remote" ? < RemoteConnectionsPage
mainNavigationExpanded = { showMainSidebar && hostSidebarOpen }
hostChromeInset = { showHostChrome }
onBackToChat = { onBackToChat }
/> : < Suspense fallback = {< SurfaceLoadingFallback />}>
2026-07-22 22:35:39 +08:00
< SettingsView
2026-09-10 11:10:51 +08:00
registerExitGuard = { registerSettingsExitGuard }
2026-07-22 22:35:39 +08:00
theme = { theme }
initialSection = { settingsInitialSection }
initialSettings = { settingsSnapshot }
showSidebar = { view === "settings" }
2026-09-13 03:38:39 +08:00
mainNavigationExpanded = { showMainSidebar && hostSidebarOpen }
2026-07-22 22:35:39 +08:00
onToggleTheme = { toggle }
onBackToChat = { onBackToChat }
onModelNameChange = { onModelNameChange }
onSettingsChange = { setSettingsSnapshot }
skills = { skills }
2026-10-07 21:28:53 +08:00
skillsLoading = { skillsLoading }
skillsError = { skillsError }
2026-09-12 16:32:46 +08:00
onStartAutomationChat = { onStartAutomationChat }
2026-09-11 19:10:15 +08:00
titleOverrides = { sidebarState . title_overrides }
2026-10-06 14:35:20 +08:00
sessions = { topicSessions }
2026-07-22 22:35:39 +08:00
onSectionChange = { onSettingsSectionChange }
onLogout = { onLogout }
onRestart = { onRestart }
onNativeEngineRestart = { onNativeEngineRestart }
isRestarting = { isRestarting }
hostChromeInset = { showHostChrome }
/>
2026-09-27 20:51:49 +08:00
</ Suspense >}
2026-05-29 03:42:53 +08:00
</ div >
)}
2026-09-30 23:30:25 +08:00
</ div >
2026-10-01 23:42:47 +08:00
{ managingConnections && ! remoteConnections ? . embeddedManagement && < div className = "absolute inset-0 flex flex-col" >
2026-09-30 23:30:25 +08:00
< RemoteConnectionsPage
mainNavigationExpanded = { showMainSidebar && hostSidebarOpen }
hostChromeInset = { showHostChrome }
onBackToChat = {() => remoteConnections ? . closeManagement ()}
/>
</ div >}
2026-05-29 03:42:53 +08:00
</ main >
</ div >
2026-04-18 18:51:53 +00:00
2026-07-22 22:35:39 +08:00
{ pendingDelete ? (
< Suspense fallback = { null }>
< DeleteConfirm
open
2026-08-12 14:45:12 +08:00
title = { pendingDelete . items [ 0 ] ? . label ?? "" }
count = { pendingDelete . items . length }
2026-07-22 22:35:39 +08:00
automations = { pendingDelete . automations }
onCancel = {() => setPendingDelete ( null )}
onConfirm = { onConfirmDelete }
/>
</ Suspense >
) : null }
{ pendingRename ? (
< Suspense fallback = { null }>
< RenameChatDialog
open
title = { pendingRename . label }
onCancel = {() => setPendingRename ( null )}
onConfirm = { onConfirmRename }
/>
</ Suspense >
) : null }
2026-08-12 14:45:12 +08:00
{ pendingTabRename ? (
< Suspense fallback = { null }>
< RenameChatDialog
open
title = { pendingTabRename . label }
2026-08-14 06:51:38 +09:00
dialogTitle = { t ( "workbench.renameGroupTitle" )}
description = { t ( "workbench.renameGroupDescription" )}
placeholder = { t ( "workbench.renameGroupPlaceholder" )}
2026-08-12 14:45:12 +08:00
onCancel = {() => setPendingTabRename ( null )}
onConfirm = { onConfirmTabRename }
/>
</ Suspense >
) : null }
2026-07-22 22:35:39 +08:00
{ pendingProjectRename ? (
< Suspense fallback = { null }>
< RenameChatDialog
open
title = { pendingProjectRename . label }
dialogTitle = { t ( "chat.renameProjectTitle" )}
description = { t ( "chat.renameProjectDescription" )}
placeholder = { t ( "chat.renameProjectPlaceholder" )}
onCancel = {() => setPendingProjectRename ( null )}
onConfirm = { onConfirmProjectRename }
/>
</ Suspense >
) : null }
2026-05-17 17:04:57 +08:00
{ restartToast ? (
2026-08-06 18:29:04 +08:00
< div className = "fixed left-1/2 top-[calc(0.75rem+env(safe-area-inset-top))] z-50 flex w-[min(32rem,calc(100vw-1rem))] -translate-x-1/2 flex-col items-center gap-2" >
< div
role = "status"
className = { cn (
floatingSurfaceElevationClassName ,
"max-w-full rounded-full px-4 py-2 text-sm font-medium" ,
)}
>
{ restartToast }
</ div >
2026-05-17 17:04:57 +08:00
</ div >
) : null }
2026-07-13 13:11:46 +08:00
< PairingCodePopup
requests = { visiblePairingRequests }
total = { visiblePairingRequests . length }
busyCode = { pairingBusyCode }
error = { pairingError }
onApprove = {( code ) => void onPairingAction ( "approve" , code )}
onDismiss = { onDismissPairingRequest }
/>
2026-05-17 17:04:57 +08:00
</ div >
</ ThemeProvider >
2026-04-18 18:51:53 +00:00
);
}