feat(web): add global settings and simplify sidebar

This commit is contained in:
2026-11-12 15:25:12 -08:00
parent b7fdf7a89c
commit d88018fd64
13 changed files with 853 additions and 242 deletions
+63 -200
View File
@@ -1,19 +1,17 @@
import {
readSidebarSelectionFromUrl, buildWorkspaceUrl,
PROVIDER_FALLBACK_MODELS, EMPTY_MODEL_CATALOG, EMPTY_MODEL_PREFERENCES,
PROVIDER_FALLBACK_MODELS, EMPTY_MODEL_CATALOG,
createClientRequestId, isRecoverableStreamDisconnect, hasNewPersistedUserMessage,
getModelOptions, getVisibleProviders, loadStoredModelPreferences, saveModelPreferences,
normalizeStoredProvider, normalizeStoredModelPreferences, pickProviderModel, buildCompletionMessages,
loadStoredQuickQuestionModelSelection, saveQuickQuestionModelSelection, pickProviderModel, buildCompletionMessages,
type ProviderModelPreferences,
} from "@/lib/workspace-domain";
import { buildUiModeUrl } from "@/lib/ui-mode";
import { useEffect, useLayoutEffect, useMemo, useRef, useState } from "preact/hooks";
import type { TargetedTouchEvent } from "preact";
import { getProviderLabel } from "@/lib/message-generation";
import {
Check,
Bot,
ChevronDown,
GitFork,
Globe2,
LoaderCircle,
@@ -35,9 +33,10 @@ import { Separator } from "@/components/ui/separator";
import { AuthScreen } from "@/components/auth/auth-screen";
import { ChatAttachmentList } from "@/components/chat/chat-attachment-list";
import { ChatComposer } from "@/components/chat/chat-composer";
import { ModelCombobox } from "@/components/chat/model-combobox";
import { ChatMessagesPanel } from "@/components/chat/chat-messages-panel";
import { AgentConversation } from "@/components/agent/agent-conversation";
import { AgentNotifications } from "@/components/agent/agent-notifications";
import { AppSettings } from "@/components/settings/app-settings";
import { hasTextSelection, ownsMobileGesture } from "@/lib/mobile-workspace-gestures";
import { SearchResultsPanel } from "@/components/search/search-results-panel";
import { SearchMatchLabel } from "@/components/search/search-match-label";
@@ -147,7 +146,6 @@ type RefreshCollectionsOptions = {
selectFallback?: boolean;
};
const QUICK_QUESTION_MODEL_SELECTION_STORAGE_KEY = "sybil:quickQuestionModelSelection";
const STREAM_RESUME_RETRY_DELAYS_MS = [0, 250, 750, 1500];
const MOBILE_LAYOUT_MEDIA_QUERY = "(max-width: 767px)";
const MOBILE_SWIPE_ACTIVATION_DISTANCE = 18;
@@ -166,11 +164,6 @@ type MobileWorkspaceSwipe = {
direction: -1 | 1 | null;
};
type QuickQuestionModelSelection = {
provider: Provider;
modelPreferences: ProviderModelPreferences;
};
const EMPTY_ACTIVE_RUNS: ActiveRunsState = {
chats: {},
searches: {},
@@ -406,22 +399,6 @@ function hasFileTransfer(dataTransfer: DataTransfer | null) {
return Array.from(dataTransfer.types ?? []).includes("Files") || getFilesFromDataTransfer(dataTransfer).length > 0;
}
function loadStoredQuickQuestionModelSelection(): QuickQuestionModelSelection {
if (typeof window === "undefined") {
return { provider: "openai", modelPreferences: EMPTY_MODEL_PREFERENCES };
}
try {
const raw = window.localStorage.getItem(QUICK_QUESTION_MODEL_SELECTION_STORAGE_KEY);
if (!raw) return { provider: "openai", modelPreferences: EMPTY_MODEL_PREFERENCES };
const parsed = JSON.parse(raw) as { provider?: unknown; modelPreferences?: unknown };
return {
provider: normalizeStoredProvider(parsed.provider),
modelPreferences: normalizeStoredModelPreferences(parsed.modelPreferences),
};
} catch {
return { provider: "openai", modelPreferences: EMPTY_MODEL_PREFERENCES };
}
}
function getToolLabel(name: string) {
if (name === "web_search") return "Web search";
@@ -515,151 +492,6 @@ function upsertOptimisticToolMessage(messages: Message[], event: ToolCallEvent,
return [...messages.slice(0, assistantIndex), toolMessage, ...messages.slice(assistantIndex)];
}
type ModelComboboxProps = {
options: string[];
value: string;
onChange: (value: string) => void;
disabled?: boolean;
className?: string;
};
function ModelCombobox({ options, value, onChange, disabled = false, className }: ModelComboboxProps) {
const [open, setOpen] = useState(false);
const [draftValue, setDraftValue] = useState(value);
const rootRef = useRef<HTMLDivElement>(null);
const inputRef = useRef<HTMLInputElement>(null);
const normalizedDraftValue = draftValue.trim();
const filteredOptions = useMemo(() => {
const needle = normalizedDraftValue.toLowerCase();
if (!needle) return options;
return options.filter((option) => option.toLowerCase().includes(needle));
}, [normalizedDraftValue, options]);
const hasExactOption = options.includes(normalizedDraftValue);
useEffect(() => {
if (open) return;
setDraftValue(value);
}, [open, value]);
useEffect(() => {
if (!open) return;
inputRef.current?.focus();
}, [open]);
const commitDraftValue = () => {
onChange(normalizedDraftValue);
setDraftValue(normalizedDraftValue);
setOpen(false);
};
useEffect(() => {
if (!open) return;
const handlePointerDown = (event: PointerEvent) => {
if (rootRef.current?.contains(event.target as Node)) return;
commitDraftValue();
};
const handleKeyDown = (event: KeyboardEvent) => {
if (event.key !== "Escape") return;
setOpen(false);
setDraftValue(value);
};
window.addEventListener("pointerdown", handlePointerDown);
window.addEventListener("keydown", handleKeyDown);
return () => {
window.removeEventListener("pointerdown", handlePointerDown);
window.removeEventListener("keydown", handleKeyDown);
};
}, [commitDraftValue, open, value]);
return (
<div className="relative" ref={rootRef}>
<div
className={cn(
"flex h-10 min-w-56 items-center rounded-lg border border-violet-300/22 bg-background/72 px-3 text-sm shadow-[inset_0_1px_0_hsl(255_100%_92%_/_0.06)]",
className
)}
>
<input
ref={inputRef}
value={draftValue}
onFocus={() => {
if (disabled) return;
setDraftValue(value);
setOpen(true);
}}
onInput={(event) => {
setDraftValue(event.currentTarget.value);
setOpen(true);
}}
onKeyDown={(event) => {
if (event.key !== "Enter") return;
event.preventDefault();
commitDraftValue();
}}
className="h-full min-w-0 flex-1 bg-transparent outline-none placeholder:text-muted-foreground"
placeholder="Select or type model"
disabled={disabled}
/>
<button
type="button"
className="ml-2 shrink-0 text-muted-foreground disabled:opacity-50"
onClick={() => {
if (disabled) return;
if (open) {
commitDraftValue();
return;
}
setDraftValue(value);
setOpen(true);
}}
disabled={disabled}
aria-label="Toggle model options"
>
<ChevronDown className="h-4 w-4" />
</button>
</div>
{open ? (
<div className="absolute right-0 z-50 mt-2 w-full rounded-lg border border-violet-300/20 bg-[hsl(238_48%_7%)] p-1 shadow-2xl shadow-black/45">
<div className="max-h-64 overflow-y-auto">
{normalizedDraftValue && !hasExactOption ? (
<button
type="button"
className="flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-sm hover:bg-violet-400/12"
onClick={commitDraftValue}
>
<Check className={cn("h-4 w-4", normalizedDraftValue === value ? "opacity-100" : "opacity-0")} />
<span className="truncate">Use "{normalizedDraftValue}"</span>
</button>
) : null}
{filteredOptions.length ? (
filteredOptions.map((option) => (
<button
key={option}
type="button"
className="flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-sm hover:bg-violet-400/12"
onClick={() => {
onChange(option);
setOpen(false);
setDraftValue(option);
}}
>
<Check className={cn("h-4 w-4", option === value ? "opacity-100" : "opacity-0")} />
<span className="truncate">{option}</span>
</button>
))
) : !normalizedDraftValue ? (
<p className="px-2 py-2 text-sm text-muted-foreground">No models found</p>
) : null}
</div>
</div>
) : null}
</div>
);
}
function getChatTitle(chat: Pick<ChatSummary, "title">, messages?: ChatDetail["messages"]) {
if (chat.title?.trim()) return chat.title.trim();
@@ -851,6 +683,8 @@ export default function App() {
const [modelCatalog, setModelCatalog] = useState<ModelCatalogResponse["providers"]>(EMPTY_MODEL_CATALOG);
const [availableChatTools, setAvailableChatTools] = useState<ChatToolInfo[]>([]);
const [providerModelPreferences, setProviderModelPreferences] = useState<ProviderModelPreferences>(() => loadStoredModelPreferences());
const [modelPreferencesSaved, setModelPreferencesSaved] = useState(true);
const [quickPreferencesSaved, setQuickPreferencesSaved] = useState(true);
const [model, setModel] = useState(() => {
const stored = loadStoredModelPreferences();
return stored.openai ?? PROVIDER_FALLBACK_MODELS.openai[0];
@@ -877,6 +711,7 @@ export default function App() {
const [renameChatError, setRenameChatError] = useState<string | null>(null);
const [isRenamingChat, setIsRenamingChat] = useState(false);
const [isChatSettingsOpen, setIsChatSettingsOpen] = useState(false);
const [isAppSettingsOpen, setIsAppSettingsOpen] = useState(false);
const [isSavingChatSettings, setIsSavingChatSettings] = useState(false);
const [isTogglingChatSettingsStar, setIsTogglingChatSettingsStar] = useState(false);
const [chatSettingsError, setChatSettingsError] = useState<string | null>(null);
@@ -1286,6 +1121,7 @@ export default function App() {
useEffect(() => {
if (!isAuthenticated) {
setIsAppSettingsOpen(false);
hasSyncedSelectionHistoryRef.current = false;
return;
}
@@ -1322,7 +1158,7 @@ export default function App() {
useEffect(() => {
if (typeof window === "undefined") return;
saveModelPreferences(providerModelPreferences);
setModelPreferencesSaved(saveModelPreferences(providerModelPreferences));
}, [providerModelPreferences]);
useEffect(() => {
@@ -1334,15 +1170,20 @@ export default function App() {
useEffect(() => {
if (typeof window === "undefined") return;
window.localStorage.setItem(
QUICK_QUESTION_MODEL_SELECTION_STORAGE_KEY,
JSON.stringify({
provider: quickProvider,
modelPreferences: quickProviderModelPreferences,
} satisfies QuickQuestionModelSelection)
);
setQuickPreferencesSaved(saveQuickQuestionModelSelection({ provider: quickProvider, modelPreferences: quickProviderModelPreferences }));
}, [quickProvider, quickProviderModelPreferences]);
const selectQuickProvider = (nextProvider: Provider) => {
setQuickProvider(nextProvider);
setQuickModel(pickQuickQuestionModel(nextProvider, getModelOptions(modelCatalog, nextProvider), quickProviderModelPreferences[nextProvider]));
};
const selectQuickModel = (nextModel: string) => {
const normalizedModel = nextModel.trim();
setQuickModel(normalizedModel);
setQuickProviderModelPreferences(current => ({ ...current, [quickProvider]: normalizedModel || null }));
};
useEffect(() => {
if (!isQuickQuestionOpen || typeof window === "undefined") return;
window.requestAnimationFrame(() => {
@@ -1653,6 +1494,7 @@ export default function App() {
setSelectedSearch(null);
setPendingAttachments([]);
setDraftChatTitle("");
setModel(pickProviderModel(getModelOptions(modelCatalog, provider), providerModelPreferences[provider]));
setAdditionalSystemPrompt("");
setEnabledTools(getDefaultEnabledTools(availableChatTools));
setIsChatSettingsOpen(false);
@@ -1674,6 +1516,7 @@ export default function App() {
isMobileSidebarOpen ||
isQuickQuestionOpen ||
isChatSettingsOpen ||
isAppSettingsOpen ||
renameChatDialog !== null
) {
return;
@@ -1835,7 +1678,7 @@ export default function App() {
if (!isAuthenticated) return;
const handleKeyDown = (event: KeyboardEvent) => {
if (chatSettingsDialogRef.current?.open) return;
if (isAppSettingsOpen || chatSettingsDialogRef.current?.open) return;
const hasPrimaryModifier = event.metaKey || event.ctrlKey;
if (!hasPrimaryModifier || event.altKey) return;
@@ -1868,7 +1711,7 @@ export default function App() {
window.addEventListener("keydown", handleKeyDown);
return () => window.removeEventListener("keydown", handleKeyDown);
}, [isAuthenticated, isQuickQuestionOpen, orderedSidebarItems]);
}, [isAuthenticated, isAppSettingsOpen, isQuickQuestionOpen, orderedSidebarItems, provider, modelCatalog, providerModelPreferences]);
const getRenameSeedTitle = (chatId: string) => {
if (selectedChat?.id === chatId) return getChatTitle(selectedChat, selectedChat.messages);
@@ -3564,10 +3407,22 @@ export default function App() {
<p className="px-3 py-2 text-xs text-muted-foreground">Showing the 100 most recent matches. Refine your search to find more.</p>
) : null}
</div>
<a href={buildUiModeUrl("lite", new URL(buildWorkspaceUrl(selectedItem), window.location.href))} className="mx-4 mb-3 text-xs text-violet-100/70 underline underline-offset-4">
Lightweight view
</a>
{authMode === "token" ? <AgentNotifications onLogout={logout} /> : null}
<div className="shrink-0 border-t border-violet-300/15 p-3">
<Button
type="button"
variant="ghost"
className="h-11 w-full justify-start gap-3 rounded-lg px-3 text-violet-100/75 hover:bg-violet-400/10 hover:text-violet-50"
aria-label="Open app settings"
aria-haspopup="dialog"
onClick={(event) => {
event.currentTarget.focus({ preventScroll: true });
setContextMenu(null);
setIsAppSettingsOpen(true);
}}
>
<Settings2 aria-hidden="true" className="h-4 w-4" />Settings
</Button>
</div>
</aside>
<main
@@ -3579,7 +3434,7 @@ export default function App() {
onContextMenu={resetMobileWorkspaceSwipe}
>
{isAgentMode ? (
<AgentConversation room={agentRoom} onOpenSidebar={() => setIsMobileSidebarOpen(true)} isVisible={!isMobileSidebarOpen && !isQuickQuestionOpen} />
<AgentConversation room={agentRoom} onOpenSidebar={() => setIsMobileSidebarOpen(true)} isVisible={!isMobileSidebarOpen && !isQuickQuestionOpen && !isAppSettingsOpen} />
) : <>
<header className="flex items-center justify-between gap-2 border-b border-violet-300/12 bg-[linear-gradient(180deg,hsl(243_48%_10%_/_0.86),hsl(236_48%_6%_/_0.66))] px-4 py-3 md:gap-3 md:px-7">
<div className="flex min-w-0 items-center gap-2">
@@ -3612,7 +3467,7 @@ export default function App() {
aria-label="Open chat settings"
>
<Settings2 className="h-4 w-4 shrink-0" />
<span className="hidden shrink-0 md:inline">Settings</span>
<span className="hidden shrink-0 md:inline">Chat settings</span>
<span className="hidden min-w-0 max-w-[18rem] truncate text-xs font-medium text-violet-100/58 md:inline">
{getProviderLabel(provider)} · {model || "No model"}
</span>
@@ -3779,6 +3634,24 @@ export default function App() {
</button>
</div>
) : null}
{isAppSettingsOpen ? <AppSettings
authMode={authMode}
onClose={() => setIsAppSettingsOpen(false)}
onLogout={logout}
modelCatalog={modelCatalog}
chatModels={providerModelPreferences}
onChatModelChange={(candidate, nextModel) => setProviderModelPreferences(current => ({ ...current, [candidate]: nextModel.trim() || null }))}
quickProvider={quickProvider}
quickModel={quickModel}
quickModelsDisabled={isQuickQuestionSending || isConvertingQuickQuestion}
onQuickProviderChange={selectQuickProvider}
onQuickModelChange={selectQuickModel}
preferencesSaved={modelPreferencesSaved && quickPreferencesSaved}
onRetrySave={() => {
setModelPreferencesSaved(saveModelPreferences(providerModelPreferences));
setQuickPreferencesSaved(saveQuickQuestionModelSelection({ provider: quickProvider, modelPreferences: quickProviderModelPreferences }));
}}
/> : null}
{isChatSettingsOpen ? (
<dialog
ref={chatSettingsDialogRef}
@@ -4130,10 +4003,7 @@ export default function App() {
className="h-10 min-w-32 rounded-lg border border-violet-300/22 bg-background/72 px-3 text-sm text-violet-50 outline-none shadow-[inset_0_1px_0_hsl(255_100%_92%_/_0.06)] focus:border-violet-300/45 focus:ring-1 focus:ring-ring/70"
value={quickProvider}
onChange={(event) => {
const nextProvider = event.currentTarget.value as Provider;
setQuickProvider(nextProvider);
const options = getModelOptions(modelCatalog, nextProvider);
setQuickModel(pickQuickQuestionModel(nextProvider, options, quickProviderModelPreferences[nextProvider]));
selectQuickProvider(event.currentTarget.value as Provider);
}}
disabled={isQuickQuestionSending || isConvertingQuickQuestion}
aria-label="Quick question provider"
@@ -4148,14 +4018,7 @@ export default function App() {
options={quickProviderModelOptions}
value={quickModel}
disabled={isQuickQuestionSending || isConvertingQuickQuestion}
onChange={(nextModel) => {
const normalizedModel = nextModel.trim();
setQuickModel(normalizedModel);
setQuickProviderModelPreferences((current) => ({
...current,
[quickProvider]: normalizedModel || null,
}));
}}
onChange={selectQuickModel}
/>
</div>
@@ -1,32 +1,63 @@
import { useEffect, useState } from "preact/hooks";
import { Bell } from "lucide-preact";
import { Bell, ChevronDown, LoaderCircle, RefreshCw } from "lucide-preact";
import { Button } from "@/components/ui/button";
import { disableAgentBrowserPush, enableAgentBrowserPush, getAgentPushState, observeAgentPush, refreshAgentBrowserPush } from "@/lib/agent-push-browser";
export function AgentNotifications({ onLogout }: { onLogout: () => Promise<void> }) {
const [state, setState] = useState(getAgentPushState), [signingOut, setSigningOut] = useState(false);
export function AgentNotifications() {
const [state, setState] = useState(getAgentPushState);
const [refreshing, setRefreshing] = useState(false);
useEffect(() => observeAgentPush(setState), []);
return <details className="max-h-[50dvh] shrink-0 overflow-y-auto overscroll-contain border-t border-violet-300/15 px-3 py-2 text-xs text-violet-100/75">
<summary className="flex cursor-pointer items-center gap-2 rounded py-2 focus-visible:outline focus-visible:outline-2 focus-visible:outline-ring"><Bell className="h-4 w-4" />Agent notifications</summary>
<div className="space-y-2 pb-1 pt-2">
<p>Notifications include Agent message text and may appear on your lock screen.</p>
<p role="status">{state.message}</p>
{state.error ? <p role="alert" className="text-rose-300">{state.error}</p> : null}
<div className="flex flex-wrap gap-2">
{state.enabled ? <Button className="h-8 text-xs" variant="secondary" disabled={state.busy} onClick={() => void disableAgentBrowserPush()}>Turn off notifications</Button>
: <Button className="h-8 text-xs" variant="secondary" disabled={!state.canEnable} onClick={() => void enableAgentBrowserPush()}>Enable notifications</Button>}
<Button className="h-8 text-xs" variant="ghost" disabled={state.busy} onClick={() => void refreshAgentBrowserPush()}>Refresh</Button>
<Button className="h-8 text-xs" variant="ghost" disabled={signingOut} onClick={() => { setSigningOut(true); void onLogout().finally(() => setSigningOut(false)); }}>Sign out</Button>
const permission = !("Notification" in window) ? "Unavailable"
: Notification.permission === "granted" ? "Allowed"
: Notification.permission === "denied" ? "Blocked" : "Not requested";
return <section aria-labelledby="notification-settings-title" className="space-y-5">
<h3 id="notification-settings-title" className="flex items-center gap-2 text-base font-semibold text-violet-50">
<Bell aria-hidden="true" className="h-4 w-4 text-violet-300" />Notifications
</h3>
<div className="space-y-4 rounded-xl border border-violet-300/15 bg-violet-300/[0.03] p-4">
<div className="space-y-1.5">
<h4 className="text-sm font-medium text-violet-50">Agent replies</h4>
<p role="status" className="text-sm leading-relaxed text-violet-100/75">{state.message}</p>
<p className="text-xs leading-relaxed text-muted-foreground">Message previews may appear on your lock screen.</p>
</div>
<details>
<summary className="cursor-pointer py-2 underline">Android / GrapheneOS help</summary>
<div className="space-y-2 pb-2">
<p>Vanadium uses Google Play services for Web Push. On GrapheneOS, sandboxed Google Play must be installed in the same profile as Vanadium, with network access and a battery optimization exception for Play services.</p>
<p>Allow notifications for Sybil in browser site settings and for Vanadium in Android settings. Then reload Sybil and enable notifications again. Permission alone does not mean the browser can register for push.</p>
<p>If you choose not to use Google Play, you need a browser with an independent Web Push service. Sybil cannot replace the browser's push service or detect whether Play services is installed.</p>
<p><a className="underline" href="https://grapheneos.org/usage#sandboxed-google-play" target="_blank" rel="noopener noreferrer">GrapheneOS setup guide</a>{" · "}<a className="underline" href="https://chromium.googlesource.com/chromium/src/+/main/components/gcm_driver/android/java/src/org/chromium/components/gcm_driver/GoogleCloudMessagingV2.java" target="_blank" rel="noopener noreferrer">Chromium push implementation</a></p>
</div>
</details>
{state.error ? <p role="alert" className="break-words text-sm leading-relaxed text-rose-300">{state.error}</p> : null}
{state.enabled ? (
<Button type="button" className="h-11" variant="secondary" disabled={state.busy || refreshing} onClick={() => void disableAgentBrowserPush()}>
{state.busy ? <LoaderCircle aria-hidden="true" className="mr-2 h-4 w-4 animate-spin" /> : null}Turn off notifications
</Button>
) : (
<Button type="button" className="h-11" disabled={!state.canEnable || refreshing} onClick={() => void enableAgentBrowserPush()}>
{state.busy ? <LoaderCircle aria-hidden="true" className="mr-2 h-4 w-4 animate-spin" /> : null}Enable notifications
</Button>
)}
</div>
</details>;
<details className="group rounded-xl border border-violet-300/15">
<summary className="flex min-h-11 cursor-pointer list-none items-center justify-between gap-3 rounded-xl px-4 py-3 text-sm text-violet-100/75 focus-visible:outline focus-visible:outline-2 focus-visible:outline-ring [&::-webkit-details-marker]:hidden">
Troubleshooting<ChevronDown aria-hidden="true" className="h-4 w-4 shrink-0 group-open:rotate-180" />
</summary>
<div className="space-y-4 border-t border-violet-300/10 px-4 py-4 text-sm leading-relaxed text-violet-100/75">
<dl className="space-y-2 text-xs">
<div className="flex flex-wrap justify-between gap-x-4 gap-y-1"><dt className="text-muted-foreground">Browser permission</dt><dd>{permission}</dd></div>
<div className="flex flex-wrap justify-between gap-x-4 gap-y-1"><dt className="text-muted-foreground">Connection</dt><dd>{window.isSecureContext ? "Secure" : "Requires HTTPS"}</dd></div>
</dl>
<p>Alerts arrive when all Sybil web sessions are inactive. After changing browser or system permissions, refresh the status.</p>
<Button type="button" className="h-11" variant="secondary" disabled={state.busy || refreshing} onClick={() => {
setRefreshing(true);
void refreshAgentBrowserPush().finally(() => setRefreshing(false));
}}>
<RefreshCw aria-hidden="true" className={`mr-2 h-4 w-4${refreshing ? " animate-spin" : ""}`} />Refresh
</Button>
<details>
<summary className="min-h-11 cursor-pointer py-3 underline underline-offset-4 focus-visible:outline focus-visible:outline-2 focus-visible:outline-ring">Android / GrapheneOS help</summary>
<div className="space-y-3 pb-2 text-xs leading-relaxed">
<p>Vanadium uses Google Play services for Web Push. On GrapheneOS, sandboxed Google Play must be installed in the same profile as Vanadium, with network access and a battery optimization exception for Play services.</p>
<p>Allow notifications for Sybil in browser site settings and for Vanadium in Android settings. Then reload Sybil and enable notifications again. Permission alone does not mean the browser can register for push.</p>
<p>If you choose not to use Google Play, you need a browser with an independent Web Push service. Sybil cannot replace the browser's push service or detect whether Play services is installed.</p>
<p><a className="underline" href="https://grapheneos.org/usage#sandboxed-google-play" target="_blank" rel="noopener noreferrer">GrapheneOS setup guide</a>{" · "}<a className="underline" href="https://chromium.googlesource.com/chromium/src/+/main/components/gcm_driver/android/java/src/org/chromium/components/gcm_driver/GoogleCloudMessagingV2.java" target="_blank" rel="noopener noreferrer">Chromium push implementation</a></p>
</div>
</details>
</div>
</details>
</section>;
}
+118
View File
@@ -0,0 +1,118 @@
import { useEffect, useId, useLayoutEffect, useMemo, useRef, useState } from "preact/hooks";
import { Check, ChevronDown } from "lucide-preact";
import { cn } from "@/lib/utils";
type ModelComboboxProps = {
options: string[];
value: string;
onChange: (value: string) => void;
disabled?: boolean;
className?: string;
id?: string;
label?: string;
inlineOptions?: boolean;
};
export function ModelCombobox({ options, value, onChange, disabled = false, className, id, label = "Model", inlineOptions = false }: ModelComboboxProps) {
const generatedId = useId();
const fieldId = id || generatedId;
const [open, setOpen] = useState(false);
const [draftValue, setDraftValue] = useState(value);
const [activeIndex, setActiveIndex] = useState(-1);
const rootRef = useRef<HTMLDivElement>(null);
const inputRef = useRef<HTMLInputElement>(null);
const normalizedDraftValue = draftValue.trim();
const choices = useMemo(() => {
const needle = normalizedDraftValue.toLowerCase();
const listed = options.filter(option => !needle || option.toLowerCase().includes(needle)).map(option => ({ value: option, label: option }));
return normalizedDraftValue && !options.includes(normalizedDraftValue)
? [{ value: normalizedDraftValue, label: `Use "${normalizedDraftValue}"` }, ...listed] : listed;
}, [normalizedDraftValue, options]);
useLayoutEffect(() => { if (!open) setDraftValue(value); }, [open, value]);
useLayoutEffect(() => {
if (open) inputRef.current?.focus();
}, [open]);
useEffect(() => {
if (activeIndex >= 0) document.getElementById(`${fieldId}-option-${activeIndex}`)?.scrollIntoView({ block: "nearest" });
}, [activeIndex, fieldId]);
const commit = (next = normalizedDraftValue) => {
if (next !== value) onChange(next);
setDraftValue(next);
setActiveIndex(-1);
setOpen(false);
};
useEffect(() => {
if (!open) return;
const handlePointerDown = (event: PointerEvent) => {
if (!rootRef.current?.contains(event.target as Node)) commit();
};
window.addEventListener("pointerdown", handlePointerDown);
return () => window.removeEventListener("pointerdown", handlePointerDown);
}, [open, normalizedDraftValue, value, onChange]);
return <div className="relative min-w-0" ref={rootRef} onFocusOut={(event) => {
if (open && !rootRef.current?.contains(event.relatedTarget as Node | null)) commit();
}} onKeyDown={(event) => {
if (event.key === "Escape" && open) {
event.preventDefault();
event.stopPropagation();
setOpen(false);
setDraftValue(value);
inputRef.current?.focus();
}
}}>
<div className={cn("flex h-10 min-w-56 items-center rounded-lg border border-violet-300/22 bg-background/72 pl-3 text-sm shadow-[inset_0_1px_0_hsl(255_100%_92%_/_0.06)] focus-within:border-violet-300/45 focus-within:ring-1 focus-within:ring-ring/70", className)}>
<input
ref={inputRef}
id={fieldId}
role="combobox"
aria-label={label}
aria-autocomplete="list"
aria-expanded={open}
aria-controls={`${fieldId}-options`}
aria-activedescendant={open && activeIndex >= 0 && choices[activeIndex] ? `${fieldId}-option-${activeIndex}` : undefined}
value={draftValue}
onFocus={() => { if (!disabled) { setDraftValue(value); setActiveIndex(-1); setOpen(true); } }}
onInput={(event) => { setDraftValue(event.currentTarget.value); setActiveIndex(-1); setOpen(true); }}
onKeyDown={(event) => {
if (event.key === "ArrowDown" || event.key === "ArrowUp") {
event.preventDefault();
setOpen(true);
setActiveIndex(current => {
if (!choices.length) return -1;
if (current < 0) return event.key === "ArrowDown" ? 0 : choices.length - 1;
return (current + (event.key === "ArrowDown" ? 1 : -1) + choices.length) % choices.length;
});
} else if (event.key === "Enter") {
event.preventDefault();
commit(open && choices[activeIndex] ? choices[activeIndex].value : normalizedDraftValue);
}
}}
className="h-full min-w-0 flex-1 bg-transparent outline-none placeholder:text-muted-foreground"
placeholder="Select or type model"
disabled={disabled}
/>
<button type="button" className="flex h-full w-11 shrink-0 items-center justify-center text-muted-foreground focus-visible:outline focus-visible:outline-2 focus-visible:outline-ring disabled:opacity-50"
onClick={() => { if (open) commit(); else { setDraftValue(value); setActiveIndex(-1); setOpen(true); } }} disabled={disabled}
aria-label={`Toggle ${label.toLowerCase()} options`} aria-expanded={open} aria-controls={`${fieldId}-options`} tabIndex={-1}>
<ChevronDown aria-hidden="true" className="h-4 w-4" />
</button>
</div>
{open ? <div className={cn("z-50 mt-2 w-full rounded-lg border border-violet-300/20 bg-[hsl(238_48%_7%)] p-1 shadow-2xl shadow-black/45", !inlineOptions && "absolute right-0")}>
<div id={`${fieldId}-options`} role="listbox" aria-label={`${label} options`} className="max-h-56 overflow-y-auto overscroll-contain">
{choices.map((option, index) => <button key={option.value} id={`${fieldId}-option-${index}`} type="button" role="option" tabIndex={-1}
aria-selected={option.value === value}
className={cn("flex min-h-11 w-full items-center gap-2 rounded-md px-2 py-2 text-left text-sm hover:bg-violet-400/12", activeIndex === index && "bg-violet-400/12")}
onPointerDown={event => event.preventDefault()}
onClick={() => commit(option.value)}>
<Check aria-hidden="true" className={cn("h-4 w-4 shrink-0", option.value === value ? "opacity-100" : "opacity-0")} />
<span className="truncate">{option.label}</span>
</button>)}
{!choices.length ? <p className="px-2 py-2 text-sm text-muted-foreground">No models found</p> : null}
</div>
</div> : null}
</div>;
}
@@ -0,0 +1,119 @@
import { useLayoutEffect, useRef, useState } from "preact/hooks";
import { ArrowLeft, Bell, ChevronRight, Cpu, Keyboard, LoaderCircle, LogOut, Server, X } from "lucide-preact";
import { AgentNotifications } from "@/components/agent/agent-notifications";
import { ModelSettings, type ModelSettingsProps } from "@/components/settings/model-settings";
import { Button } from "@/components/ui/button";
import type { AuthMode } from "@/hooks/use-session-auth";
import { getApiBaseUrl } from "@/lib/api";
import { cn } from "@/lib/utils";
type Section = "notifications" | "models" | "connection";
const sections = [
{ id: "notifications", title: "Notifications", description: "Agent alerts and permissions", icon: Bell },
{ id: "models", title: "Models", description: "Chats and Quick Questions", icon: Cpu },
{ id: "connection", title: "Connection & session", description: "Server, sign-in, and shortcuts", icon: Server },
] as const;
function displayServerUrl() {
try {
const url = new URL(getApiBaseUrl(), window.location.href);
return `${url.origin}${url.pathname}`.replace(/\/$/, "");
} catch { return "Unavailable"; }
}
export function AppSettings({ authMode, onClose, onLogout, ...modelSettings }: ModelSettingsProps & {
authMode: AuthMode | null;
onClose: () => void;
onLogout: () => Promise<void>;
}) {
const dialogRef = useRef<HTMLDialogElement>(null);
const contentRef = useRef<HTMLDivElement>(null);
const navRef = useRef<HTMLElement>(null);
const lastSectionRef = useRef<Section | null>(null);
const [section, setSection] = useState<Section | null>(null);
const [signingOut, setSigningOut] = useState(false);
const activeSection = section ?? "notifications";
const modifier = /Mac|iPhone|iPad|iPod/i.test(navigator.platform) ? "⌘" : "Ctrl";
useLayoutEffect(() => {
const dialog = dialogRef.current;
const previouslyFocused = document.activeElement;
dialog?.showModal();
return () => {
dialog?.close();
if (previouslyFocused instanceof HTMLElement && previouslyFocused.isConnected) previouslyFocused.focus({ preventScroll: true });
};
}, []);
useLayoutEffect(() => {
if (section) {
lastSectionRef.current = section;
if (contentRef.current) contentRef.current.scrollTop = 0;
contentRef.current?.focus({ preventScroll: true });
} else if (lastSectionRef.current) {
navRef.current?.querySelector<HTMLButtonElement>(`[data-section="${lastSectionRef.current}"]`)?.focus({ preventScroll: true });
}
}, [section]);
return <dialog
ref={dialogRef}
aria-labelledby="app-settings-title"
className="fixed inset-0 m-0 flex h-dvh max-h-none w-full max-w-none items-center justify-center overflow-hidden bg-transparent p-0 text-foreground backdrop:bg-black/70 backdrop:backdrop-blur-md md:p-6"
onCancel={(event) => { event.preventDefault(); onClose(); }}
onClick={(event) => { if (event.target === event.currentTarget) onClose(); }}
>
<div className="glass-panel flex h-full min-h-0 w-full flex-col overflow-hidden md:h-[min(44rem,calc(100dvh-3rem))] md:max-w-[760px] md:rounded-2xl md:border md:border-violet-300/24">
<header className="app-settings-header flex shrink-0 items-center justify-between gap-4 border-b border-violet-300/15">
<div className="flex min-w-0 items-center gap-2">
{section ? <Button type="button" variant="ghost" size="icon" className="h-11 w-11 shrink-0 md:hidden" aria-label="Back to settings" onClick={() => setSection(null)}>
<ArrowLeft aria-hidden="true" className="h-5 w-5" />
</Button> : null}
<h2 id="app-settings-title" className="text-lg font-semibold text-violet-50">Settings</h2>
</div>
<Button type="button" size="icon" variant="ghost" className="h-11 w-11 shrink-0" aria-label="Close settings" onClick={onClose}>
<X aria-hidden="true" className="h-5 w-5" />
</Button>
</header>
<div className="flex min-h-0 flex-1 flex-col md:flex-row">
<nav ref={navRef} aria-label="Settings sections" className={cn("app-settings-nav shrink-0 space-y-2 overflow-y-auto overscroll-contain md:block md:w-44 md:border-r md:border-violet-300/15", section && "hidden")}>
{sections.map(({ id, title, description, icon: Icon }) => <button key={id} type="button" data-section={id} aria-label={title}
aria-current={activeSection === id ? "page" : undefined} aria-controls="app-settings-content" onClick={() => setSection(id)}
className={cn("flex min-h-11 w-full items-center gap-3 rounded-lg px-3 py-4 text-left text-violet-100/75 hover:bg-violet-400/10 hover:text-violet-50 focus-visible:outline focus-visible:outline-2 focus-visible:outline-ring md:items-start md:gap-2 md:py-3", activeSection === id && "md:bg-violet-400/15 md:text-violet-50")}>
<Icon aria-hidden="true" className="mt-0.5 h-4 w-4 shrink-0 text-violet-300" />
<span className="min-w-0 flex-1"><span className="block text-sm font-medium leading-5">{title}</span><span className="mt-1 block text-xs text-muted-foreground md:hidden">{description}</span></span>
<ChevronRight aria-hidden="true" className="h-4 w-4 shrink-0 md:hidden" />
</button>)}
</nav>
<div ref={contentRef} id="app-settings-content" role="group" aria-label={sections.find(item => item.id === activeSection)?.title} tabIndex={-1}
className={cn("app-settings-content min-h-0 min-w-0 flex-1 overflow-y-auto overscroll-contain outline-none md:block", !section && "hidden")}>
{activeSection === "notifications" ? authMode === "token" ? <AgentNotifications /> : (
<section aria-labelledby="notification-settings-title" className="space-y-3">
<h3 id="notification-settings-title" className="flex items-center gap-2 text-base font-semibold text-violet-50"><Bell aria-hidden="true" className="h-4 w-4 text-violet-300" />Notifications</h3>
<p className="text-sm leading-relaxed text-muted-foreground">Agent notifications require a server with token sign-in.</p>
</section>
) : activeSection === "models" ? <ModelSettings {...modelSettings} /> : (
<section aria-labelledby="connection-settings-title" className="space-y-6">
<h3 id="connection-settings-title" className="flex items-center gap-2 text-base font-semibold text-violet-50"><Server aria-hidden="true" className="h-4 w-4 text-violet-300" />Connection &amp; session</h3>
<dl className="space-y-5 text-sm">
<div className="space-y-1.5"><dt className="font-medium text-violet-100/80">Server</dt><dd className="break-all text-muted-foreground">{displayServerUrl()}</dd></div>
<div className="space-y-1.5"><dt className="font-medium text-violet-100/80">Sign-in</dt><dd className="text-muted-foreground">{authMode === "token" ? "Signed in on this browser." : "Open mode. No sign-in required."}</dd></div>
</dl>
{authMode === "token" ? <Button type="button" className="h-11" variant="secondary" disabled={signingOut} onClick={() => {
setSigningOut(true);
void onLogout().finally(() => setSigningOut(false));
}}>
{signingOut ? <LoaderCircle aria-hidden="true" className="mr-2 h-4 w-4 animate-spin" /> : <LogOut aria-hidden="true" className="mr-2 h-4 w-4" />}Sign out
</Button> : null}
<details className="border-t border-violet-300/15 pt-2">
<summary className="flex min-h-11 cursor-pointer items-center gap-2 py-3 text-sm text-violet-100/75 focus-visible:outline focus-visible:outline-2 focus-visible:outline-ring"><Keyboard aria-hidden="true" className="h-4 w-4" />Keyboard shortcuts</summary>
<dl className="space-y-3 pb-2 pt-2 text-xs text-muted-foreground">
{[ ["New chat", `${modifier} + J`], ["New search", `${modifier} + Shift + J`], ["Quick Question", `${modifier} + I`], ["Previous / next item", `${modifier} + ↑ / ↓`] ].map(([label, keys]) => <div key={label} className="flex flex-wrap justify-between gap-2"><dt>{label}</dt><dd><kbd>{keys}</kbd></dd></div>)}
</dl>
</details>
</section>
)}
</div>
</div>
</div>
</dialog>;
}
@@ -0,0 +1,62 @@
import { Cpu } from "lucide-preact";
import { ModelCombobox } from "@/components/chat/model-combobox";
import { Button } from "@/components/ui/button";
import type { ModelCatalogResponse, Provider } from "@/lib/api";
import { getProviderLabel } from "@/lib/message-generation";
import { getModelOptions, getVisibleProviders, pickProviderModel, type ProviderModelPreferences } from "@/lib/workspace-domain";
export type ModelSettingsProps = {
modelCatalog: ModelCatalogResponse["providers"];
chatModels: ProviderModelPreferences;
onChatModelChange: (provider: Provider, model: string) => void;
quickProvider: Provider;
quickModel: string;
quickModelsDisabled: boolean;
onQuickProviderChange: (provider: Provider) => void;
onQuickModelChange: (model: string) => void;
preferencesSaved: boolean;
onRetrySave: () => void;
};
export function ModelSettings(props: ModelSettingsProps) {
const providers = getVisibleProviders(props.modelCatalog);
// Retain a previously selected optional provider even while its catalog is unavailable.
const quickProviders = providers.includes(props.quickProvider) ? providers : [...providers, props.quickProvider];
return <section aria-labelledby="model-settings-title" className="space-y-6">
<div className="space-y-2">
<h3 id="model-settings-title" className="flex items-center gap-2 text-base font-semibold text-violet-50"><Cpu aria-hidden="true" className="h-4 w-4 text-violet-300" />Models</h3>
<p className="text-sm leading-relaxed text-muted-foreground">Remembered on this browser. Existing chats keep their settings.</p>
</div>
{!props.preferencesSaved ? <div className="space-y-3 rounded-lg border border-amber-300/25 bg-amber-300/5 p-3">
<p role="alert" className="text-sm leading-relaxed text-amber-100">Browser storage is unavailable. Changes work for this page, but may be lost on reload.</p>
<Button type="button" variant="secondary" className="h-11" onClick={props.onRetrySave}>Retry saving</Button>
</div> : null}
<fieldset className="min-w-0 space-y-4">
<legend className="mb-2 text-sm font-semibold text-violet-50">Chats</legend>
<p className="text-xs leading-relaxed text-muted-foreground">Choose a model for new chats with each provider. You can also type a model name.</p>
{providers.map(provider => <div key={provider} className="min-w-0 space-y-1.5 md:grid md:grid-cols-[88px_minmax(0,1fr)] md:gap-3 md:space-y-0">
<label for={`chat-preference-${provider}`} className="block text-sm text-violet-100/80 md:pt-3">{getProviderLabel(provider)}</label>
<ModelCombobox id={`chat-preference-${provider}`} label={`${getProviderLabel(provider)} chat model`}
options={getModelOptions(props.modelCatalog, provider)} value={pickProviderModel(getModelOptions(props.modelCatalog, provider), props.chatModels[provider])}
onChange={model => props.onChatModelChange(provider, model)} inlineOptions className="h-11 min-w-0 text-base md:text-sm" />
</div>)}
</fieldset>
<fieldset className="min-w-0 space-y-4 border-t border-violet-300/15 pt-5" disabled={props.quickModelsDisabled}>
<legend className="pt-5 text-sm font-semibold text-violet-50">Quick Questions</legend>
<p className="text-xs leading-relaxed text-muted-foreground">A separate selection for quick answers.</p>
<div className="space-y-1.5 md:grid md:grid-cols-[88px_minmax(0,1fr)] md:gap-3 md:space-y-0">
<label for="settings-quick-provider" className="block text-sm text-violet-100/80 md:pt-3">Provider</label>
<select id="settings-quick-provider" aria-label="Quick Questions provider" value={props.quickProvider}
onChange={event => props.onQuickProviderChange(event.currentTarget.value as Provider)}
className="h-11 w-full rounded-lg border border-violet-300/22 bg-background/72 px-3 text-base outline-none focus:border-violet-300/45 focus:ring-1 focus:ring-ring/70 disabled:opacity-50 md:text-sm">
{quickProviders.map(provider => <option key={provider} value={provider}>{getProviderLabel(provider)}</option>)}
</select>
</div>
<div className="space-y-1.5 md:grid md:grid-cols-[88px_minmax(0,1fr)] md:gap-3 md:space-y-0">
<label for="settings-quick-model" className="block text-sm text-violet-100/80 md:pt-3">Model</label>
<ModelCombobox id="settings-quick-model" label="Quick Questions model" options={getModelOptions(props.modelCatalog, props.quickProvider)}
value={props.quickModel} onChange={props.onQuickModelChange} disabled={props.quickModelsDisabled} inlineOptions className="h-11 min-w-0 text-base md:text-sm" />
</div>
</fieldset>
</section>;
}
+14 -3
View File
@@ -99,7 +99,8 @@ textarea {
max(0.75rem, var(--safe-area-left));
}
.chat-settings-header {
.chat-settings-header,
.app-settings-header {
padding:
calc(0.5rem + var(--safe-area-top))
max(0.75rem, var(--safe-area-right))
@@ -107,7 +108,8 @@ textarea {
max(0.75rem, var(--safe-area-left));
}
.chat-settings-content {
.chat-settings-content,
.app-settings-content {
padding:
1rem
max(1rem, var(--safe-area-right))
@@ -124,9 +126,18 @@ textarea {
max(1rem, var(--safe-area-left));
}
.app-settings-nav {
padding: 1rem max(1rem, var(--safe-area-right)) max(1rem, var(--safe-area-bottom)) max(1rem, var(--safe-area-left));
}
@media (min-width: 768px) {
.app-settings-nav {
padding: 1rem 0.5rem;
}
.chat-settings-header,
.chat-settings-content {
.chat-settings-content,
.app-settings-header,
.app-settings-content {
padding: 1.25rem;
}
+21 -2
View File
@@ -50,8 +50,10 @@ export const BASE_PROVIDERS: Provider[] = ["openai", "anthropic", "xai", "gemini
export const ALL_PROVIDERS: Provider[] = [...BASE_PROVIDERS, "hermes-agent"];
export const MODEL_PREFERENCES_STORAGE_KEY = "sybil:modelPreferencesByProvider";
export const QUICK_QUESTION_MODEL_SELECTION_STORAGE_KEY = "sybil:quickQuestionModelSelection";
export type ProviderModelPreferences = Record<Provider, string | null>;
export type QuickQuestionModelSelection = { provider: Provider; modelPreferences: ProviderModelPreferences };
export const EMPTY_MODEL_PREFERENCES: ProviderModelPreferences = {
openai: null,
@@ -155,6 +157,23 @@ export function buildCompletionMessages(messages: Message[], content: string, at
}
export function saveModelPreferences(preferences: ProviderModelPreferences) {
try { window.localStorage.setItem(MODEL_PREFERENCES_STORAGE_KEY, JSON.stringify(preferences)); }
catch { /* Browsers with unavailable storage can still use this session. */ }
try { window.localStorage.setItem(MODEL_PREFERENCES_STORAGE_KEY, JSON.stringify(preferences)); return true; }
catch { return false; /* Browsers with unavailable storage can still use this session. */ }
}
export function loadStoredQuickQuestionModelSelection(): QuickQuestionModelSelection {
const fallback = { provider: "openai" as const, modelPreferences: EMPTY_MODEL_PREFERENCES };
if (typeof window === "undefined") return fallback;
try {
const raw = window.localStorage.getItem(QUICK_QUESTION_MODEL_SELECTION_STORAGE_KEY);
if (!raw) return fallback;
const parsed = JSON.parse(raw);
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return fallback;
return { provider: normalizeStoredProvider(parsed.provider), modelPreferences: normalizeStoredModelPreferences(parsed.modelPreferences) };
} catch { return fallback; }
}
export function saveQuickQuestionModelSelection(selection: QuickQuestionModelSelection) {
try { window.localStorage.setItem(QUICK_QUESTION_MODEL_SELECTION_STORAGE_KEY, JSON.stringify(selection)); return true; }
catch { return false; }
}