okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge main (87dfca0e7) into f-own-int: the 0.2.14 app branch, fixtures and CI fixes, the Qwen4-readiness tools, the shape-engine build scriptsffb3d9b31

main
20.6 KiB203 linesraw
1import {sessionTitle} from '../lib/session-title';
2import { tr } from '../lib/i18n';
3import { useNative } from '../lib/native';
4import { modelFamilyIcon } from '../lib/model-icons';
5import { TaskTree } from './TaskTree';
6/** Quiet navigation, with the same destinations at every window size. */
7import { useEffect, useId, useLayoutEffect, useRef, useState, type RefObject } from 'react';
8import { createPortal } from 'react-dom';
9import { FloatingMenu } from '../components/FloatingMenu';
10import { measureFrame } from '../lib/overlay-place';
11import { QuitStrataDialog } from '../components/QuitStrata';
12import { useAppMode } from '../lib/app-mode';
13import { href, useLocation, type Route } from '../lib/router';
14import { cx, relTime, relTimeShort } from '../lib/format';
15import { useMedia } from '../lib/responsive';
16import { recentChats, recentChatDescription } from '../lib/recent-chats';
17import type { Session } from '../lib/types';
18import { MOD, runCommand } from '../lib/commands';
19import { bindingFor, bindingKeys, useBindings } from '../lib/shortcut-bindings';
20import { Btn, Dialog, Icon, IconBtn, type IconName } from '../components/ui';
21import { Brand } from '../components/Brand';
22import { addWorkspace, deleteSession, go, isUnread, liveChatIds, pickWorkspace, renameSession, removeWorkspace, renameWorkspace, selectSession, setActiveWorkspace, setNavOpen, togglePin, toggleRail, setTheme, useStore } from '../lib/store';
23export function Sidebar({ containerRef }: {
24    containerRef: RefObject<HTMLElement | null>;
25}) {
26    useBindings();
27    const location = useLocation();
28    const compact = useMedia('(max-width: 1279px)');
29    const rail = useStore(s => s.rail);
30    const theme = useStore(s => s.theme);
31    const systemDark = useMedia('(prefers-color-scheme: dark)');
32    const dark = theme === 'dark' || theme === 'system' && systemDark;
33    const navOpen = useStore(s => s.navOpen);
34    const collapsed = compact ? !navOpen : rail;
35    const sessions = useStore(s => s.sessions);
36    const library = useStore(s => s.library);
37    const monitor = useStore(s => s.monitor);
38    const workspaces = useStore(s => s.workspaces);
39    const activeWorkspace = useStore(s => s.activeWorkspace);
40    const activeSession = useStore(s => s.activeSession);
41    // The chats that have a turn running now (the board reads the same list). The count is what makes this redraw when one starts or ends.
42    const liveCount = useStore(s => s.liveChats);
43    const working = new Set(liveCount ? liveChatIds() : []);
44    const [query, setQuery] = useState('');
45    const [searchOpen, setSearchOpen] = useState(false);
46    const searchInput = useRef<HTMLInputElement>(null);
47    const searchTrigger = useRef<HTMLButtonElement>(null);
48    useEffect(() => {
49        if (searchOpen)
50            searchInput.current?.focus();
51    }, [searchOpen, collapsed]);
52    function closeSearch() { setQuery(''); setSearchOpen(false); requestAnimationFrame(() => searchTrigger.current?.focus()); }
53    const [recentOpen, setRecentOpen] = useState(false);
54    const [includeArchived, setIncludeArchived] = useState(false);
55    const [removeWorkspaceId, setRemoveWorkspaceId] = useState<string | null>(null);
56    const [menuId, setMenuId] = useState<string | null>(null);
57    const [renameId, setRenameId] = useState<string | null>(null);
58    const [renameWsId, setRenameWsId] = useState<string | null>(null), [wsName, setWsName] = useState('');
59    const [name, setName] = useState('');
60    const [deleteId, setDeleteId] = useState<string | null>(null);
61    const [folders, setFolders] = useState<Record<string, boolean>>({});
62    const menuTrigger = useRef<HTMLElement | null>(null);
63    const current = library?.variants.find(v => v.id === library.loaded);
64    const native = useNative(), nativeCurrent = native?.instances.find(i => i.id === native.defaultId);
65    const modelName = nativeCurrent?.label ?? (current?.local ? current.name : current?.family) ?? tr('No model loaded');
66    // The version from the catalog and the card it runs on ("Q2_0 · GPU 2"), not the file id.
67    const nativeSize = nativeCurrent ? native?.catalog?.families.flatMap(f => f.sizes).find(s => s.id === nativeCurrent.model) : undefined;
68    const nativeSecond = nativeCurrent ? [nativeSize?.model ?? nativeCurrent.model.toUpperCase(), nativeCurrent.gpus.length ? nativeCurrent.gpus.map(g => `GPU ${g + 1}`).join(' + ') : ''].filter(Boolean).join(' · ') : null;
69    const modelQuant = nativeSecond ?? current?.quant ?? tr('View model versions');
70    const phase = nativeCurrent ? (nativeCurrent.status === 'ready' ? nativeCurrent.phase : nativeCurrent.status) : monitor?.phase ?? 'idle';
71    const status = phase === 'unavailable' ? 'Status unavailable' : phase === 'error' ? 'Error' : phase === 'loading' ? 'Loading' : !current && !nativeCurrent ? 'No model loaded' : phase === 'reading' ? 'Reading prompt' : phase === 'thinking' ? 'Thinking' : phase === 'generating' ? 'Generating' : 'Ready';
72    // The model is busy with a chat that is not the one in front of the person: the chip says which one (a title, or how many).
73    const awayChats = [...working].filter(id => !(location.route === 'chat' && id === activeSession));
74    const awayTitle = awayChats.length === 1 ? sessions.find(s => s.id === awayChats[0]) : undefined;
75    const workingLine = awayChats.length === 1 && awayTitle ? tr("Working · {0}", [sessionTitle(awayTitle)]) : awayChats.length > 1 ? tr("{0} chats working", [awayChats.length]) : null;
76    const menuSession = sessions.find(s => s.id === menuId);
77    const q = query.trim().toLowerCase();
78    const matching = sessions.filter(s => (!s.archived || q || includeArchived) && (!q || `${sessionTitle(s)} ${s.messages.map(m => m.content).join(' ')}`.toLowerCase().includes(q))).sort((a, b) => Number(!!b.pinned) - Number(!!a.pinned) || b.updatedAt.localeCompare(a.updatedAt));
79    function openMenu(id: string, trigger: HTMLElement) { menuTrigger.current = trigger; setMenuId(id); }
80    function closeMenu() { setMenuId(null); menuTrigger.current?.focus(); }
81    return <>
82    <aside className="nav" ref={containerRef} aria-label={tr("Main navigation")} aria-modal={navOpen && compact ? true : undefined} role={navOpen && compact ? 'dialog' : undefined} tabIndex={-1}>
83      <div className="nav__top">{tr(!collapsed ? <a className="nav__brand" href={href('chat')} aria-label={tr("Strata — open chat")}><Brand variant="lockup" height={28} decorative className="nav__brand-lockup"/></a> : null)}<button type="button" className="nav__collapse" aria-label={tr(collapsed ? 'Show sidebar' : 'Hide sidebar')} title={tr(collapsed ? 'Show sidebar' : 'Hide sidebar')} onClick={() => compact ? setNavOpen(!navOpen) : toggleRail()}><Icon name="panel" size={20}/></button></div>
84      <div className="nav__scroll">
85        <button className="st-btn st-btn--primary nav-new" aria-label={tr("New chat")} title={tr("New chat")} onClick={() => runCommand('new')}><Icon name="new-chat" size={18}/><span className="nav__rail-hide">{tr("New chat")}</span></button>
86        <TaskTree collapsed={collapsed}/>
87        {tr(collapsed ? <div className="nav-recent" aria-label={tr("Recent chats")}>{tr(recentChats(sessions, activeSession).map((session, index) => <RecentChatLink key={session.id} session={session} slot={index + 1} active={activeSession === session.id && location.route === 'chat'}/>))}</div> : null)}
88        {!collapsed ? <div className="ws">
89          <div className="ws__head">{tr(searchOpen ? <div className="nav-search"><Icon name="search" size={16}/><input ref={searchInput} className="st-input st-input--bare" type="search" placeholder={tr("Search chats…")} aria-label={tr("Search chats")} value={query} onChange={e => setQuery(e.target.value)} onKeyDown={e => {
90                    if (e.key === 'Escape') {
91                        e.preventDefault();
92                        closeSearch();
93                    }
94                }}/><IconBtn name="x" title={tr("Close chat search")} onClick={closeSearch}/></div> : <><span className="navgroup__label">{tr("Workspaces")}</span><div className="ws__tools"><button ref={searchTrigger} type="button" className="st-btn st-btn--icon" aria-label={tr("Search chats")} title={tr("Search chats")} onClick={() => setSearchOpen(true)}><Icon name="search" size={18}/></button><IconBtn name="folder-plus" title={tr("Add a workspace folder")} onClick={() => { void pickWorkspace().then(path => path ? addWorkspace(path) : undefined); }}/></div></>)}</div>
95          {workspaces.map(w => {
96                const expanded = folders[w.id] !== false || !!q;
97                const rows = matching.filter(s => s.workspace === w.path || !!w.aliases?.includes(s.workspace));
98                const shown = q ? rows : rows.slice(0, 20);
99                return <div className="ws__group" key={w.id}>
100              <div className={cx('ws__row', activeWorkspace === w.id && 'is-active')}><button className="ws__name" aria-expanded={expanded} onClick={() => { setActiveWorkspace(w.id); setFolders(f => ({ ...f, [w.id]: !expanded })); }}><Icon name="chevron" size={14} className={cx('ws__chev', expanded && 'is-open')}/><Icon name="folder" size={17}/><span>{w.name}</span></button><IconBtn name="pencil" title={tr("Rename {0}", [w.name])} onClick={() => { setWsName(w.name); setNavOpen(false); setRenameWsId(w.id); }}/>{tr(w.id !== 'root' ? <IconBtn name="x" title={tr("Remove {0} from sidebar", [w.name])} onClick={() => { setNavOpen(false); setRemoveWorkspaceId(w.id); }}/> : null)}</div>
101              {tr(expanded ? <div className="navsessions">
102                {tr(shown.map(s => <div key={s.id}>
103                  <div className="ws__session row"><a className="navsession" href={href('chat', s.id)} data-working={working.has(s.id) || undefined} aria-current={activeSession === s.id && location.route === 'chat' ? 'page' : undefined} onClick={() => selectSession(s.id)} onContextMenu={e => { e.preventDefault(); openMenu(s.id, e.currentTarget); }} title={sessionTitle(s)}>{tr(working.has(s.id) ? <span className="navsession__working" role="img" aria-label={tr("Working")} title={tr("Working")}><svg viewBox="0 0 16 16" aria-hidden="true" focusable="false"><circle className="navsession__track" cx="8" cy="8" r="6"/><circle className="navsession__arc" cx="8" cy="8" r="6" pathLength="100"/></svg></span> : null)}<span className="navsession__title">{sessionTitle(s)}</span>{tr(s.pinned ? <span aria-label={tr("Pinned")}><Icon name="pin" size={12}/></span> : <span className="navsession__time">{relTimeShort(s.updatedAt)}</span>)}{tr(!working.has(s.id) && isUnread(s, activeSession) ? <span className="navsession__unread" aria-label={tr("Unread")}/> : null)}{tr(s.archived ? <span className="xs muted">{tr("Archived")}</span> : null)}</a><button className="st-btn st-btn--icon session-overflow" aria-label={tr("Actions for {0}", [sessionTitle(s)])} onClick={e => openMenu(s.id, e.currentTarget)}><Icon name="ellipsis" size={16}/></button></div>
104                </div>))}
105                {tr(!shown.length ? <p className="small muted ws__empty">{tr(q ? 'No matching chats' : 'No chats yet')}</p> : null)}
106                {tr(!q && rows.length > shown.length ? <button className="ws-view small" onClick={() => { setNavOpen(false); setRecentOpen(true); }}>{tr("View all chats")}</button> : null)}
107              </div> : null)}
108            </div>;
109            })}
110        </div> : null}
111      </div>
112      <div className="nav__foot">
113        <button className="enginechip" data-state={status === 'Ready' ? 'ready' : ['Reading prompt', 'Thinking', 'Generating', 'Loading'].includes(status) ? 'busy' : 'off'} onClick={() => go('models')} title={tr("{0} \u00B7 {1} \u00B7 {2}", [modelName, workingLine ?? modelQuant, tr(status)])} aria-label={tr("{0} \u00B7 {1}", [modelName, modelQuant])}><span className="enginechip__family"><Icon name={modelFamilyIcon(current?.family)} size={20}/><span className="enginechip__dot"/></span><span className="enginechip__text nav__rail-hide"><span className="enginechip__title">{modelName}</span><span className="enginechip__sub">{workingLine ?? modelQuant}</span></span></button>
114        <NavLink route="skills" label={tr("Skills")} icon="skills" current={location.route}/>
115        <NavLink route="monitor" label={tr("Monitor")} icon="activity" current={location.route}/>
116        <NavLink route="models" label={tr("Models")} icon="models" current={location.route === 'tuning' ? 'models' : location.route}/>
117        <div className="nav__bottom"><MoreMenu current={location.route}/><button className="st-btn st-btn--icon theme-switch" aria-label={tr(dark ? 'Switch to light mode' : 'Switch to dark mode')} title={tr(dark ? 'Switch to light mode' : 'Switch to dark mode')} onClick={() => setTheme(dark ? 'light' : 'dark')}><span key={String(dark)} className="theme-switch__icon"><Icon name={dark ? 'sun' : 'moon'} size={19}/></span></button></div>
118      </div>
119    </aside>
120    {tr(menuId && menuSession ? <FloatingMenu anchor={menuTrigger.current} title={tr("Actions for {0}", [sessionTitle(menuSession)])} onClose={closeMenu}>
121      <button role="menuitem" className="menu__item" onClick={() => { setName(sessionTitle(menuSession)); setNavOpen(false); setRenameId(menuId); setMenuId(null); }}><Icon name="pencil"/>{tr("Rename")}</button>
122      <button role="menuitem" className="menu__item" onClick={() => { togglePin(menuId); closeMenu(); }}><Icon name="pin"/>{tr(menuSession.pinned ? 'Unpin' : 'Pin')}</button>
123      <button role="menuitem" className="menu__item menu__item--danger" onClick={() => { setNavOpen(false); setDeleteId(menuId); setMenuId(null); }}><Icon name="trash"/>{tr("Delete chat")}</button>
124    </FloatingMenu> : null)}
125    <Dialog open={!!renameId} compact title={tr("Rename chat")} onClose={() => setRenameId(null)} actions={<><Btn onClick={() => setRenameId(null)}>{tr("Cancel")}</Btn><Btn variant="primary" disabled={!name.trim()} onClick={() => {
126                if (renameId)
127                    renameSession(renameId, name.trim());
128                setRenameId(null);
129            }}>{tr("Save name")}</Btn></>}><label className="input-field" htmlFor="chat-name"><span>{tr("Chat name")}</span><input className="st-input" id="chat-name" value={name} onFocus={e => e.currentTarget.select()} onChange={e => setName(e.target.value)}/></label></Dialog>
130    <Dialog open={!!renameWsId} compact title={tr("Rename workspace")} onClose={() => setRenameWsId(null)} actions={<><Btn onClick={() => setRenameWsId(null)}>{tr("Cancel")}</Btn><Btn variant="primary" disabled={!wsName.trim()} onClick={() => {
131                if (renameWsId)
132                    void renameWorkspace(renameWsId, wsName.trim());
133                setRenameWsId(null);
134            }}>{tr("Save name")}</Btn></>}><label className="input-field" htmlFor="workspace-name"><span>{tr("Workspace name")}</span><input className="st-input" id="workspace-name" value={wsName} onFocus={e => e.currentTarget.select()} onChange={e => setWsName(e.target.value)}/></label><p className="small muted">{tr("Only the name changes. The folder stays where it is.")}</p></Dialog>
135    <Dialog open={!!deleteId} compact title={tr("Delete this chat?")} onClose={() => setDeleteId(null)} actions={<><Btn onClick={() => setDeleteId(null)}>{tr("Keep chat")}</Btn><Btn variant="danger" onClick={() => {
136                if (deleteId)
137                    deleteSession(deleteId);
138                setDeleteId(null);
139            }}>{tr("Delete chat")}</Btn></>}><p>{tr("This chat will be permanently deleted.")}</p></Dialog>
140    <Dialog open={!!removeWorkspaceId} title={tr("Remove workspace from sidebar?")} onClose={() => setRemoveWorkspaceId(null)} actions={<><Btn onClick={() => setRemoveWorkspaceId(null)}>{tr("Keep workspace")}</Btn><Btn onClick={() => {
141                if (removeWorkspaceId)
142                    void removeWorkspace(removeWorkspaceId).then(() => setRemoveWorkspaceId(null));
143            }}>{tr("Remove from sidebar")}</Btn></>}><p>{tr("Files stay on your computer. Add this folder again to reopen its chats.")}</p></Dialog>
144    <Dialog open={recentOpen} title={tr("All chats")} onClose={() => setRecentOpen(false)}><div className="stack"><label className="row small"><input type="checkbox" checked={includeArchived} onChange={e => setIncludeArchived(e.target.checked)}/>{tr("Include archived chats")}</label><input type="search" className="st-input" placeholder={tr("Search chats…")} aria-label={tr("Search all chats")} value={query} onChange={e => setQuery(e.target.value)}/>{tr(matching.map(s => <button className="recent-chat" key={s.id} onClick={() => { selectSession(s.id); go('chat', s.id); setRecentOpen(false); }}><span>{sessionTitle(s)}</span><span className="xs muted">{tr(relTime(s.updatedAt))}</span></button>))}{tr(!matching.length ? <p className="small muted">{tr("No matching chats. Try another search.")}</p> : null)}</div></Dialog>
145  </>;
146}
147function RecentChatLink({ session, active, slot }: {
148    session: Session;
149    active: boolean;
150    slot: number;
151}) {
152    const binding = bindingFor('chat:slot:' + slot, { key: String(slot), mod: true, shift: false, alt: false });
153    const keys = bindingKeys(binding, MOD);
154    const anchor = useRef<HTMLAnchorElement>(null);
155    const tooltip = useRef<HTMLDivElement>(null);
156    const id = useId();
157    const [open, setOpen] = useState(false);
158    const [position, setPosition] = useState({ left: 0, top: 0 });
159    useLayoutEffect(() => {
160        if (!open)
161            return;
162        const place = () => {
163            const rect = anchor.current?.getBoundingClientRect();
164            if (!rect)
165                return;
166            const { scale, viewport } = measureFrame();
167            const height = tooltip.current?.getBoundingClientRect().height ?? 80 * scale;
168            setPosition({ left: (rect.right + 12) / scale, top: Math.max(12, Math.min(rect.top, viewport.height - height - 12)) / scale });
169        };
170        place();
171        window.addEventListener('resize', place);
172        window.addEventListener('scroll', place, true);
173        return () => { window.removeEventListener('resize', place); window.removeEventListener('scroll', place, true); };
174    }, [open]);
175    return <>
176    <a ref={anchor} className="navitem nav-recent__chat" href={href('chat', session.id)} aria-label={sessionTitle(session)} aria-current={active ? 'page' : undefined} aria-describedby={open ? id : undefined} onClick={() => { setOpen(false); selectSession(session.id); }} onMouseEnter={() => setOpen(true)} onMouseLeave={() => setOpen(false)} onFocus={() => setOpen(true)} onBlur={() => setOpen(false)} onKeyDown={event => {
177            if (event.key === 'Escape' && open) {
178                event.preventDefault();
179                event.stopPropagation();
180                setOpen(false);
181            }
182        }}><Icon name="chat"/><span className="nav-chat-number" aria-hidden="true">{tr(slot)}</span></a>
183    {open ? createPortal(<div ref={tooltip} id={id} role="tooltip" className="nav-chat-tooltip" style={position}><strong>{sessionTitle(session)}</strong><span>{session.messages.length ? recentChatDescription(session) : tr(recentChatDescription(session))}</span>{tr(binding ? <kbd className="nav-chat-shortcut">{tr(keys.join(" "))}</kbd> : null)}</div>, document.body) : null}
184  </>;
185}
186function NavLink({ route, label, icon, current, meta }: {
187    route: Route;
188    label: string;
189    icon: IconName;
190    current: string;
191    meta?: string;
192}) {
193    return <a className="navitem" href={href(route)} aria-current={current === route ? 'page' : undefined} title={tr(label)} aria-label={tr(label)}><Icon name={icon}/><span className="navitem__text">{tr(label)}</span>{tr(meta ? <span className="navitem__meta">{tr(meta)}</span> : null)}</a>;
194}
195function MoreMenu({ current }: {
196    current: string;
197}) {
198    const [open, setOpen] = useState(false);
199    const [quitOpen, setQuitOpen] = useState(false);
200    const appMode = useAppMode();
201    const ref = useRef<HTMLButtonElement>(null);
202    return <><button ref={ref} className="navitem nav__more" title={tr("More — Serving and Settings")} aria-label={tr("More — Serving and Settings")} aria-haspopup="menu" aria-expanded={open} data-active={['serving', 'settings'].includes(current) || undefined} aria-current={['serving', 'settings'].includes(current) ? 'page' : undefined} onClick={() => setOpen(v => !v)}><Icon name="ellipsis"/><span className="navitem__text">{tr("More")}</span></button>{tr(open ? <FloatingMenu anchor={ref.current} title={tr("More")} onClose={() => { setOpen(false); ref.current?.focus(); }}>{tr(([{ route: 'serving', label: 'Serving', icon: 'link' }, { route: 'settings', label: 'Settings', icon: 'settings' }] as const).map(d => <a key={d.route} role="menuitem" className="menu__item" href={href(d.route)} onClick={() => setOpen(false)}><Icon name={d.icon}/>{tr(d.label)}</a>))}{appMode.canQuit ? <button type="button" role="menuitem" className="menu__item" onClick={() => { setOpen(false); setNavOpen(false); setQuitOpen(true); }}><Icon name="x"/>{tr("Quit Strata")}</button> : null}</FloatingMenu> : null)}<QuitStrataDialog open={quitOpen} onClose={() => setQuitOpen(false)}/></>;
203}