diff --git a/web/README.md b/web/README.md index 7b1d4b3..01d4ead 100644 --- a/web/README.md +++ b/web/README.md @@ -34,6 +34,7 @@ Default dev URL: `http://localhost:5173` ## UI - Left panel: mixed list of chat conversations and Exa searches. +- The sidebar footer has one **Settings** button. It opens app settings; the conversation header's **Chat settings** button still edits only the current chat. - Sidebar search uses `GET /v1/workspace-items?q=…` to search all saved titles, conversation messages, and web-search queries/answers. It waits 300 ms while typing and cancels superseded requests. Results include a single-line matching excerpt @@ -65,7 +66,7 @@ Client API contract docs: ## Lightweight interface -Open `/lite` directly, or choose **Lightweight view** in the full workspace sidebar. **Full interface** switches back. Explicit switches (`?ui=lite` and `?ui=full`) remember the choice in `sybil:ui-mode`; workspace IDs, query parameters, and hashes survive switching. A direct `/lite` visit always works even if Full was previously selected. +Open `/lite` directly or from a bookmark; it is intentionally absent from the full workspace sidebar and settings. **Full interface** switches back. Explicit switches (`?ui=lite` and `?ui=full`) remember the choice in `sybil:ui-mode`; workspace IDs, query parameters, and hashes survive switching. A direct `/lite` visit always works even if Full was previously selected. At `/`, an explicit or saved choice wins over automatic detection. Otherwise recognizable Kindle/Kobo/PocketBook user agents or `navigator.connection.saveData === true` select Lite. Silk/Kindle Fire alone do not identify an e-ink device. Screen size, CPU count, and reduced-motion preferences do not trigger a redirect. `/search` stays a standalone search unless explicitly switched; switching its `q` parameter into Lite prefills a search without starting a request. @@ -108,4 +109,34 @@ Installed Sybil uses `standalone` display, retaining the system status bar where Horizontal navigation swipes start on workspace chrome or empty space. Text, tables, quotations, code, controls, existing selections and nested horizontal scrollers keep native gestures, including at scroll edges. Long-press/right-click on transcript text and links uses the native browser menu; the reply footer provides Copy and Fork. -Agent notification settings include separate browser/server failure guidance and an expandable Android / GrapheneOS setup guide. See [mobile QA results and limitations](../docs/mobile-web-qa.md), including how to run the browser fixtures. +**Settings → Notifications** includes browser/server failure guidance. **Troubleshooting** contains browser permission and connection status, Refresh, and the expandable Android / GrapheneOS setup guide. See [mobile QA results and limitations](../docs/mobile-web-qa.md), including how to run the browser fixtures. + +## App settings + +The sidebar has one **Settings** entry. Desktop opens a 760 px pane with a section list and scrollable content. Mobile opens a section list; each section has Back and Close in a fixed header. Safe-area padding and 44 px controls keep the pane usable on narrow and short screens. Close, Escape, and desktop backdrop dismissal return focus to the Settings button. Workspace shortcuts and Agent read tracking are suspended while settings covers the workspace; the selected conversation, composer draft, and background notification session remain intact. + +| Section | Controls | +| --- | --- | +| Notifications | Agent status, enable/disable, and a brief lock-screen preview notice. Actionable errors remain visible; Troubleshooting contains permission/connection diagnostics, Refresh, and Android / GrapheneOS help. | +| Models | A remembered chat model for each provider, plus Quick Questions' separate provider and per-provider model selections. Both use the existing catalog and shared picker, including custom model names and keyboard selection. | +| Connection & session | Read-only configured server location, signed-in/open mode, Sign out with notification revocation, and a Keyboard shortcuts disclosure. Credentials are never displayed. | + +Model selections save automatically to this browser using the existing `sybil:modelPreferencesByProvider` and `sybil:quickQuestionModelSelection` keys. Existing stored choices require no migration. New chats use the remembered model for the current provider; there is no new persistent default-provider setting for regular chats. Selecting or editing an existing conversation retains its own model and settings. Editing a model through Chat settings or Quick Questions updates the same remembered choices shown in app settings. Clearing a model entry returns to that provider's existing fallback. + +Preferences apply locally, with no server request or account synchronization. If storage is blocked or full, the page keeps working with the changed values and Models shows a concise persistence error with **Retry saving**. Closing and reopening settings preserves session values; reloading requires successful storage. Quick Questions' controls are disabled during an active quick request or conversion, matching the inline controls. + +Chat title, star, provider/model overrides, additional system prompt, and enabled tools stay in **Chat settings**. The web server address remains build-configured; native iOS retains its existing editable connection settings. Open-mode servers explain that notifications require token sign-in and omit Sign out. `/lite` stays a direct/bookmarked route, absent from sidebar and settings; its saved UI-mode preference and automatic detection remain intact. Push consent, presence, registration, retry, revocation, API contracts, and the full app's disabled zoom are unchanged. + +### Settings verification + +After `npm run build`, start the local preview as described above. With `PLAYWRIGHT_MODULE` and `CHROME_EXECUTABLE` set, run: + +```bash +node tests/app-settings.browser.mjs +node tests/agent-push.browser.mjs +node tests/agent-push-errors.browser.mjs +node tests/mobile-workspace.browser.mjs +node tests/ui-mode.browser.mjs +``` + +The settings fixture covers desktop/mobile sections, Back/Close/focus and shortcut isolation, catalog/custom/keyboard model selection, migration-free preference persistence and reload, shared Quick Questions settings, existing-chat and draft preservation, blocked/full storage and retry, connection details, collapsed help, short-screen scrolling, open-mode behavior, direct `/lite` navigation, and disabled zoom in the full app. Set `SETTINGS_ARTIFACT_DIR` to save screenshots. Push fixtures retain their existing consent, failure, retry, source-change, worker, and offline sign-out checks through the new pane. APIs and push providers are mocked; actual phone delivery and native keyboard behavior still require device verification. diff --git a/web/src/App.tsx b/web/src/App.tsx index f491832..9129545 100644 --- a/web/src/App.tsx +++ b/web/src/App.tsx @@ -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(null); - const inputRef = useRef(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 ( -
-
- { - 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} - /> - -
- {open ? ( -
-
- {normalizedDraftValue && !hasExactOption ? ( - - ) : null} - {filteredOptions.length ? ( - filteredOptions.map((option) => ( - - )) - ) : !normalizedDraftValue ? ( -

No models found

- ) : null} -
-
- ) : null} -
- ); -} function getChatTitle(chat: Pick, messages?: ChatDetail["messages"]) { if (chat.title?.trim()) return chat.title.trim(); @@ -851,6 +683,8 @@ export default function App() { const [modelCatalog, setModelCatalog] = useState(EMPTY_MODEL_CATALOG); const [availableChatTools, setAvailableChatTools] = useState([]); const [providerModelPreferences, setProviderModelPreferences] = useState(() => 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(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(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() {

Showing the 100 most recent matches. Refine your search to find more.

) : null} - - Lightweight view - - {authMode === "token" ? : null} +
+ +
{isAgentMode ? ( - setIsMobileSidebarOpen(true)} isVisible={!isMobileSidebarOpen && !isQuickQuestionOpen} /> + setIsMobileSidebarOpen(true)} isVisible={!isMobileSidebarOpen && !isQuickQuestionOpen && !isAppSettingsOpen} /> ) : <>
@@ -3612,7 +3467,7 @@ export default function App() { aria-label="Open chat settings" > - Settings + Chat settings {getProviderLabel(provider)} · {model || "No model"} @@ -3779,6 +3634,24 @@ export default function App() {
) : null} + {isAppSettingsOpen ? 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 ? ( { - 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} /> diff --git a/web/src/components/agent/agent-notifications.tsx b/web/src/components/agent/agent-notifications.tsx index fb51828..689e7a6 100644 --- a/web/src/components/agent/agent-notifications.tsx +++ b/web/src/components/agent/agent-notifications.tsx @@ -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 }) { - 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
- Agent notifications -
-

Notifications include Agent message text and may appear on your lock screen.

-

{state.message}

- {state.error ?

{state.error}

: null} -
- {state.enabled ? - : } - - + const permission = !("Notification" in window) ? "Unavailable" + : Notification.permission === "granted" ? "Allowed" + : Notification.permission === "denied" ? "Blocked" : "Not requested"; + + return
+

+

+
+
+

Agent replies

+

{state.message}

+

Message previews may appear on your lock screen.

-
- Android / GrapheneOS help -
-

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.

-

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.

-

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.

-

GrapheneOS setup guide{" · "}Chromium push implementation

-
-
+ {state.error ?

{state.error}

: null} + {state.enabled ? ( + + ) : ( + + )}
-
; +
+ + Troubleshooting +
+
+
Browser permission
{permission}
+
Connection
{window.isSecureContext ? "Secure" : "Requires HTTPS"}
+
+

Alerts arrive when all Sybil web sessions are inactive. After changing browser or system permissions, refresh the status.

+ +
+ Android / GrapheneOS help +
+

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.

+

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.

+

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.

+

GrapheneOS setup guide{" · "}Chromium push implementation

+
+
+
+
+ ; } diff --git a/web/src/components/chat/model-combobox.tsx b/web/src/components/chat/model-combobox.tsx new file mode 100644 index 0000000..80e1ad8 --- /dev/null +++ b/web/src/components/chat/model-combobox.tsx @@ -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(null); + const inputRef = useRef(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
{ + 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(); + } + }}> +
+ = 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} + /> + +
+ {open ?
+
+ {choices.map((option, index) => )} + {!choices.length ?

No models found

: null} +
+
: null} +
; +} diff --git a/web/src/components/settings/app-settings.tsx b/web/src/components/settings/app-settings.tsx new file mode 100644 index 0000000..f957b2c --- /dev/null +++ b/web/src/components/settings/app-settings.tsx @@ -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; +}) { + const dialogRef = useRef(null); + const contentRef = useRef(null); + const navRef = useRef(null); + const lastSectionRef = useRef
(null); + const [section, setSection] = useState
(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(`[data-section="${lastSectionRef.current}"]`)?.focus({ preventScroll: true }); + } + }, [section]); + + return { event.preventDefault(); onClose(); }} + onClick={(event) => { if (event.target === event.currentTarget) onClose(); }} + > +
+
+
+ {section ? : null} +

Settings

+
+ +
+
+ +
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" ? : ( +
+

+

Agent notifications require a server with token sign-in.

+
+ ) : activeSection === "models" ? : ( +
+

+
+
Server
{displayServerUrl()}
+
Sign-in
{authMode === "token" ? "Signed in on this browser." : "Open mode. No sign-in required."}
+
+ {authMode === "token" ? : null} +
+ +
+ {[ ["New chat", `${modifier} + J`], ["New search", `${modifier} + Shift + J`], ["Quick Question", `${modifier} + I`], ["Previous / next item", `${modifier} + ↑ / ↓`] ].map(([label, keys]) =>
{label}
{keys}
)} +
+
+
+ )} +
+
+
+
; +} diff --git a/web/src/components/settings/model-settings.tsx b/web/src/components/settings/model-settings.tsx new file mode 100644 index 0000000..446ac6a --- /dev/null +++ b/web/src/components/settings/model-settings.tsx @@ -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
+
+

+

Remembered on this browser. Existing chats keep their settings.

+
+ {!props.preferencesSaved ?
+

Browser storage is unavailable. Changes work for this page, but may be lost on reload.

+ +
: null} +
+ Chats +

Choose a model for new chats with each provider. You can also type a model name.

+ {providers.map(provider =>
+ + props.onChatModelChange(provider, model)} inlineOptions className="h-11 min-w-0 text-base md:text-sm" /> +
)} +
+
+ Quick Questions +

A separate selection for quick answers.

+
+ + +
+
+ + +
+
+
; +} diff --git a/web/src/index.css b/web/src/index.css index 13104bf..05adef1 100644 --- a/web/src/index.css +++ b/web/src/index.css @@ -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; } diff --git a/web/src/lib/workspace-domain.ts b/web/src/lib/workspace-domain.ts index 2ce1725..5aa7a3e 100644 --- a/web/src/lib/workspace-domain.ts +++ b/web/src/lib/workspace-domain.ts @@ -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; +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; } } diff --git a/web/tests/agent-push-errors.browser.mjs b/web/tests/agent-push-errors.browser.mjs index 34a19cc..da3aa6c 100644 --- a/web/tests/agent-push-errors.browser.mjs +++ b/web/tests/agent-push-errors.browser.mjs @@ -56,23 +56,25 @@ await context.routeWebSocket("**/api/v1/agent/ws", socket => socket.close()); const page = await context.newPage(); page.on("pageerror", error => errors.push(error.message)); const enable = page.getByRole("button", { name: "Enable notifications", exact: true }); const refresh = page.getByRole("button", { name: "Refresh", exact: true }); -const alert = page.locator(".workspace-sidebar [role=alert]"); +const alert = page.locator("dialog [role=alert]"); const waitEnable = () => page.waitForFunction(() => Array.from(document.querySelectorAll("button")).some(el => el.textContent === "Enable notifications" && !el.disabled)); async function attempt(pattern) { await refresh.click(); await waitEnable(); await enable.click(); await page.waitForFunction(pattern => { - const el = document.querySelector(".workspace-sidebar [role=alert]"); + const el = document.querySelector("dialog [role=alert]"); return el && new RegExp(pattern).test(el.textContent); }, pattern.source); assert.match(await alert.textContent(), pattern); assert.equal(await page.evaluate(() => window.__permissionGesture), true); assert.equal(await page.getByRole("button", { name: "Turn off notifications", exact: true }).count(), 0); - assert.doesNotMatch(await page.locator(".workspace-sidebar").textContent(), /private-worker-detail|private-provider-key|private-server-token|private-endpoint/); + assert.doesNotMatch(await page.getByRole("dialog", { name: "Settings", exact: true }).textContent(), /private-worker-detail|private-provider-key|private-server-token|private-endpoint/); } try { await page.goto(target.href, { waitUntil: "networkidle" }); await page.getByRole("button", { name: "Open sidebar", exact: true }).click(); - await page.getByText("Agent notifications", { exact: true }).click(); + await page.getByRole("button", { name: "Open app settings", exact: true }).click(); + await page.getByRole("button", { name: "Notifications", exact: true }).click(); + await page.getByText("Troubleshooting", { exact: true }).click(); await attempt(/prompt was dismissed/); assert.equal(puts, 0); await page.evaluate(() => { window.__decision = "denied"; }); await attempt(/not allowed/); assert.equal(puts, 0); assert.ok(await enable.isDisabled()); @@ -114,9 +116,9 @@ try { if (process.env.PUSH_ERROR_SCREENSHOT) await page.screenshot({ path: process.env.PUSH_ERROR_SCREENSHOT }); for (const viewport of [{ width: 320, height: 568 }, { width: 390, height: 450 }]) { await page.setViewportSize(viewport); - const signOut = page.getByRole("button", { name: "Sign out", exact: true }); - await signOut.scrollIntoViewIfNeeded(); - assert.ok(await signOut.evaluate(el => { + const control = page.getByRole("button", { name: "Refresh", exact: true }); + await control.scrollIntoViewIfNeeded(); + assert.ok(await control.evaluate(el => { const box = el.getBoundingClientRect(); return box.top >= 0 && box.bottom <= innerHeight; }), "notification controls remain reachable with long help and a short viewport"); assert.equal(await page.evaluate(() => document.documentElement.scrollWidth > innerWidth), false); diff --git a/web/tests/agent-push.browser.mjs b/web/tests/agent-push.browser.mjs index 12257b3..2a1b61e 100644 --- a/web/tests/agent-push.browser.mjs +++ b/web/tests/agent-push.browser.mjs @@ -71,10 +71,14 @@ await context.routeWebSocket("**/api/v1/agent/ws", socket => { }); }); const page = await context.newPage(); page.on("pageerror", error => errors.push(error.message)); +const openSettings = async () => { + await page.getByRole("button", { name: "Open app settings", exact: true }).click(); + await page.getByText("Troubleshooting", { exact: true }).click(); +}; const expectEventually = async predicate => { for (let i = 0; i < 100; i++) { if (await predicate()) return; await new Promise(resolve => setTimeout(resolve, 50)); } assert.fail("Condition did not settle"); }; try { await page.goto(target.href, { waitUntil: "networkidle" }); - await page.getByText("Agent notifications", { exact: true }).click(); + await openSettings(); await page.getByText(/The Agent notification source is not ready yet/).waitFor(); assert.equal(await page.getByRole("button", { name: "Enable notifications", exact: true }).isDisabled(), true, "unknown source cannot opt in"); assert.deepEqual(await page.evaluate(() => window.__pushCalls), []); @@ -165,6 +169,7 @@ try { // The rendered room belongs to source A. A B read frame must stop the room, // preserving A's cursor instead of relabeling old queued reads with B. await second.close(); + await page.getByRole("button", { name: "Close settings", exact: true }).click(); await page.locator('[data-testid="agent-sidebar-item"]').click(); sockets[0].socket.send(JSON.stringify({ type: "read_state", sourceId: replacementSourceId, cursor: "0", updatedAt: null })); await page.getByText("Agent history changed. Reload the page before marking messages read.", { exact: true }).waitFor(); @@ -177,6 +182,7 @@ try { const oldConsent = await page.evaluate(() => JSON.parse(localStorage.getItem("sybil.agent.push.v1"))); const registrationCount = requests.filter(request => request.path.includes("/push/installations/") && request.method === "PUT").length; config.sourceId = replacementSourceId; readSourceId = replacementSourceId; readCursor = "0"; + await openSettings(); await page.getByRole("button", { name: "Refresh", exact: true }).click(); await expectEventually(() => page.getByRole("button", { name: "Enable notifications", exact: true }).isEnabled()); const retiredConsent = await page.evaluate(() => JSON.parse(localStorage.getItem("sybil.agent.push.v1"))); @@ -190,10 +196,11 @@ try { assert.equal(replacementConsent.scope, oldConsent.scope); assert.notEqual(replacementConsent.installationId, oldConsent.installationId); assert.ok((await page.evaluate(() => window.__pushCalls.filter(call => call.type === "permission"))).every(call => call.gesture === true)); const socketCount = sockets.length; + await page.getByRole("button", { name: "Close settings", exact: true }).click(); await page.getByRole("button", { name: "Retry", exact: true }).click(); await expectEventually(() => sockets.length > socketCount); assert.equal(await page.getByText("Agent history changed. Reload the page before marking messages read.", { exact: true }).count(), 0, "explicit reload binds a fresh room to B"); - await page.getByText("Agent notifications", { exact: true }).click(); + await openSettings(); await page.getByRole("button", { name: "Turn off notifications", exact: true }).waitFor(); // Credential rotation is a new authority scope. The old UUID remains queued @@ -201,7 +208,7 @@ try { const originalAuthority = await page.evaluate(() => JSON.parse(localStorage.getItem("sybil.agent.push.v1"))); await page.evaluate(() => localStorage.setItem("sybil_admin_token", "browser-fixture-rotated-token")); await page.reload({ waitUntil: "networkidle" }); - await page.getByText("Agent notifications", { exact: true }).click(); + await openSettings(); await expectEventually(() => page.getByRole("button", { name: "Enable notifications", exact: true }).isEnabled()); const rotatedOff = await page.evaluate(() => JSON.parse(localStorage.getItem("sybil.agent.push.v1"))); assert.deepEqual(rotatedOff.pendingRevocations, [{ installationId: originalAuthority.installationId, scope: originalAuthority.scope }]); @@ -215,7 +222,7 @@ try { assert.notEqual(rotatedOn.installationId, originalAuthority.installationId); assert.deepEqual(rotatedOn.pendingRevocations, rotatedOff.pendingRevocations); await page.evaluate(() => localStorage.setItem("sybil_admin_token", "browser-fixture-token")); await page.reload({ waitUntil: "networkidle" }); - await page.getByText("Agent notifications", { exact: true }).click(); + await openSettings(); await expectEventually(() => page.getByRole("button", { name: "Enable notifications", exact: true }).isEnabled()); const returned = await page.evaluate(() => JSON.parse(localStorage.getItem("sybil.agent.push.v1"))); assert.deepEqual(returned.pendingRevocations, [{ installationId: rotatedOn.installationId, scope: rotatedOn.scope }]); @@ -227,6 +234,7 @@ try { // Offline sign-out still removes the local subscription and leaves a tombstone. failDelete = true; + await page.getByRole("button", { name: "Connection & session", exact: true }).click(); await page.getByRole("button", { name: "Sign out", exact: true }).click(); await page.getByRole("button", { name: /Sign in/i }).waitFor(); const local = await page.evaluate(() => ({ token: localStorage.getItem("sybil_admin_token"), subscription: localStorage.getItem("fixture-subscription"), consent: JSON.parse(localStorage.getItem("sybil.agent.push.v1")) })); diff --git a/web/tests/app-settings.browser.mjs b/web/tests/app-settings.browser.mjs new file mode 100644 index 0000000..4b5d7ba --- /dev/null +++ b/web/tests/app-settings.browser.mjs @@ -0,0 +1,324 @@ +import assert from "node:assert/strict"; +import { mkdir } from "node:fs/promises"; + +// Production preview only; every API/socket request is a local fixture. +// Uses PLAYWRIGHT_MODULE, CHROME_EXECUTABLE and WEB_TEST_URL like the push fixtures. +const { chromium } = await import(process.env.PLAYWRIGHT_MODULE || "playwright-core"); +const target = new URL(process.env.WEB_TEST_URL || "http://127.0.0.1:5197/"); +assert.ok(target.protocol === "http:" && ["127.0.0.1", "localhost", "[::1]"].includes(target.hostname)); +const artifactDir = process.env.SETTINGS_ARTIFACT_DIR; +if (artifactDir) await mkdir(artifactDir, { recursive: true }); +const browser = await chromium.launch({ executablePath: process.env.CHROME_EXECUTABLE || undefined, headless: true, + ...(process.env.BROWSER_NO_SANDBOX === "1" ? { args: ["--no-sandbox"] } : {}) }); +const date = "2026-11-12T12:00:00.000Z"; +const sourceId = "4599d348-e053-4937-987d-1392746fb2ce"; +const chat = { id: "settings-chat", title: "Settings fixture conversation", parentChatId: null, titleGenerationPending: false, + createdAt: date, updatedAt: date, starred: false, starredAt: null, initiatedProvider: "openai", initiatedModel: "fixture-model", + lastUsedProvider: "openai", lastUsedModel: "fixture-model", additionalSystemPrompt: null, enabledTools: [], + messages: [{ id: "reply", role: "assistant", content: "Keep this conversation open.", createdAt: date, name: null, metadata: null }] }; +const search = { id: "settings-search", title: "Saved search fixture", query: "saved query", createdAt: date, updatedAt: date, + starred: false, starredAt: null, results: [], answer: "Saved search answer", status: "completed" }; +const idle = { state: "idle", isThinking: false, queued: 0, backgroundWorkers: 0, tools: [], queuedMessages: [] }; + +async function fixture(viewport, mode = "token", options = {}) { + const context = await browser.newContext({ viewport, isMobile: viewport.width < 768, hasTouch: viewport.width < 768 }); + const errors = [], writes = []; + await context.addInitScript(({ mode, options }) => { + if (mode === "token") localStorage.setItem("sybil_admin_token", "settings-fixture-token"); + localStorage.setItem("sybil:ui-mode", "full"); + if (options.seedModels && !localStorage.getItem("model-fixture-seeded")) { + localStorage.setItem("model-fixture-seeded", "true"); + localStorage.setItem("sybil:modelPreferencesByProvider", JSON.stringify({ openai: "remembered-initial", anthropic: "legacy-custom" })); + localStorage.setItem("sybil:quickQuestionModelSelection", JSON.stringify({ provider: "xai", modelPreferences: { xai: "legacy-quick", openai: "quick-original" } })); + } + window.__denyPreferenceWrites = !!options.denyWrites; + const setItem = Storage.prototype.setItem; + Storage.prototype.setItem = function (key, value) { + if (window.__denyPreferenceWrites && ["sybil:modelPreferencesByProvider", "sybil:quickQuestionModelSelection"].includes(key)) throw new DOMException("Full", "QuotaExceededError"); + return setItem.call(this, key, value); + }; + if (options.blockStorage) Object.defineProperty(window, "localStorage", { get() { throw new Error("Storage unavailable"); } }); + window.__permissionRequests = 0; + Notification.requestPermission = () => { window.__permissionRequests++; return Promise.resolve("default"); }; + }, { mode, options }); + await context.route("**/*", async route => { + const request = route.request(), url = new URL(request.url()), path = url.pathname; + if (url.origin !== target.origin) return route.abort(); + if (!path.startsWith("/api/")) return route.continue(); + if (request.method() !== "GET") writes.push(path); + let value = {}; + if (path.endsWith("/auth/session")) value = { mode, authenticated: true }; + else if (path.endsWith("/workspace-items")) value = { items: [{ ...chat, type: "chat" }, { ...search, type: "search" }] }; + else if (path.endsWith(`/chats/${chat.id}`)) value = { chat }; + else if (path.endsWith(`/searches/${search.id}`)) value = { search }; + else if (path.endsWith("/models")) value = { providers: { openai: { models: ["fixture-model", "listed-next-model"], loadedAt: date, error: null } } }; + else if (path.endsWith("/chat-tools") || path.endsWith("/agent/tools")) value = { tools: [] }; + else if (path.endsWith("/active-runs")) value = { chats: [], searches: [] }; + else if (path.endsWith("/agent/messages")) value = { conversationId: "1", messages: [], cursor: "0", beforeCursor: null, hasMore: false }; + else if (path.endsWith("/agent")) value = { id: "1", title: "Sybil Agent", activity: idle, protocol: "pi-room.v1", websocket: "/v1/agent/ws" }; + else if (path.endsWith("/read-state")) value = { sourceId, cursor: "0", updatedAt: null }; + else if (path.endsWith("/push/config")) value = { version: 1, enabled: true, webPushAvailable: true, apnsAvailable: false, + vapidPublicKey: "B".repeat(87), sourceId, quarantined: false, policy: { presenceHeartbeatMs: 15000, presenceLeaseMs: 60000 } }; + else if (path.includes("/presence/")) value = { expiresAt: date }; + await route.fulfill({ json: value }); + }); + await context.routeWebSocket("**/api/v1/agent/ws", socket => socket.onMessage(raw => { + if (JSON.parse(String(raw)).type === "auth") socket.send(JSON.stringify({ type: "ready", conversationId: "1" })); + })); + const page = await context.newPage(); + page.on("pageerror", error => errors.push(error.message)); + await page.goto(new URL(`/?chat=${chat.id}`, target).href, { waitUntil: "networkidle" }); + await page.locator("main h1").filter({ hasText: chat.title }).waitFor(); + const openSidebar = async () => { + if (await page.locator(".workspace-sidebar").evaluate(el => innerWidth < 768 && el.classList.contains("-translate-x-full"))) { + await page.getByRole("button", { name: "Open sidebar", exact: true }).click(); + } + await page.waitForFunction(() => document.querySelector(".workspace-sidebar").getBoundingClientRect().left >= 0); + }; + const settings = page.getByRole("dialog", { name: "Settings", exact: true }); + const trigger = page.getByRole("button", { name: "Open app settings", exact: true }); + const selectSection = async name => { + const back = settings.getByRole("button", { name: "Back to settings", exact: true }); + if (await back.isVisible()) await back.click(); + await settings.getByRole("button", { name, exact: true }).click(); + await settings.getByRole("group", { name, exact: true }).waitFor(); + }; + const openSettings = async (section = "Notifications") => { + await openSidebar(); + await trigger.click(); + await settings.waitFor(); + assert.equal(await page.getByRole("button", { name: "Close settings", exact: true }).evaluate(el => el === document.activeElement), true); + if (artifactDir && await page.evaluate(() => innerWidth < 768)) await page.screenshot({ path: `${artifactDir}/settings-sections-${viewport.width}.png` }); + await selectSection(section); + }; + return { context, page, settings, trigger, openSidebar, openSettings, selectSection, errors, writes }; +} + +async function assertFits(locator) { + await locator.scrollIntoViewIfNeeded(); + assert.ok(await locator.evaluate(el => { + const rect = el.getBoundingClientRect(); + return rect.left >= 0 && rect.right <= innerWidth && rect.top >= 0 && rect.bottom <= innerHeight; + }), "control fits in the visible viewport"); +} + +try { + for (const viewport of [{ width: 1280, height: 900 }, { width: 390, height: 844 }]) { + const { context, page, settings, trigger, openSidebar, openSettings, selectSection, errors, writes } = await fixture(viewport); + const originalUrl = page.url(); + await page.locator("#composer-input").fill("Keep my unfinished draft"); + await openSidebar(); + assert.equal(await page.getByRole("link", { name: /Lightweight view/i }).count(), 0); + assert.equal(await page.locator('.workspace-sidebar a[href*="lite"]').count(), 0); + assert.equal(await page.getByText("Agent notifications", { exact: true }).count(), 0); + await assertFits(trigger); + await openSettings(); + assert.equal(await settings.evaluate(el => el.matches(":modal")), true); + assert.equal(await page.getByRole("button", { name: "Refresh", exact: true }).isVisible(), false); + assert.equal(await page.getByText("Browser permission", { exact: true }).isVisible(), false); + assert.equal(await page.getByRole("link", { name: "GrapheneOS setup guide" }).isVisible(), false); + assert.equal(await page.evaluate(() => window.__permissionRequests), 0, "opening Settings does not request consent"); + // A modal must keep focus off background controls even when they request it. + await page.locator("#composer-input").evaluate(el => el.focus()); + assert.equal(await settings.evaluate(el => el.contains(document.activeElement)), true); + for (let index = 0; index < 8; index++) { + await page.keyboard.press("Tab"); + assert.equal(await page.evaluate(() => !!document.activeElement?.closest(".workspace-shell")), false); + } + for (const shortcut of ["Control+j", "Control+Shift+j", "Control+i", "Control+ArrowDown"]) { + await page.keyboard.press(shortcut); + } + assert.equal(page.url(), originalUrl, "workspace navigation shortcuts cannot change the selection under Settings"); + assert.equal(await page.locator("#quick-question-input").count(), 0); + await settings.getByText("Troubleshooting", { exact: true }).click(); + await settings.getByText("Browser permission", { exact: true }).waitFor(); + await settings.getByRole("button", { name: "Refresh", exact: true }).click(); + await page.waitForFunction(() => Array.from(document.querySelectorAll("button")).some(el => el.textContent === "Enable notifications" && !el.disabled)); + assert.equal(await page.evaluate(() => window.__permissionRequests), 0, "refresh does not request consent"); + await page.keyboard.press("Escape"); + await settings.waitFor({ state: "detached" }); + assert.equal(await trigger.evaluate(el => el === document.activeElement), true, "dismissal restores focus to Settings"); + assert.equal(await page.locator("#composer-input").inputValue(), "Keep my unfinished draft"); + assert.equal(page.url(), originalUrl); + await openSettings(); + assert.equal(await settings.getByText("Browser permission", { exact: true }).isVisible(), false, "diagnostics starts collapsed on each visit"); + if (artifactDir) await page.screenshot({ path: `${artifactDir}/settings-${viewport.width}.png` }); + if (viewport.width >= 768) { + await page.mouse.click(8, 8); + await settings.waitFor({ state: "detached" }); + assert.equal(await trigger.evaluate(el => el === document.activeElement), true); + } else { + await settings.getByRole("button", { name: "Close settings", exact: true }).click(); + await settings.waitFor({ state: "detached" }); + } + if (artifactDir) await page.screenshot({ path: `${artifactDir}/sidebar-${viewport.width}.png` }); + // The same entry remains available from chat, search, and Agent workspaces. + for (const item of [page.getByRole("button", { name: new RegExp(search.title) }), page.locator('[data-testid="agent-sidebar-item"]')]) { + await openSidebar(); + await item.click(); + await openSettings(); + await settings.getByRole("heading", { name: "Notifications", exact: true }).waitFor(); + await settings.getByRole("button", { name: "Close settings", exact: true }).click(); + } + await openSidebar(); + await page.getByRole("button", { name: new RegExp(chat.title) }).click(); + await page.getByRole("button", { name: "Open chat settings", exact: true }).click(); + await page.getByRole("dialog", { name: "Chat settings", exact: true }).waitFor(); + await page.keyboard.press("Escape"); + await openSettings(); + if (viewport.width < 768) { + await settings.getByText("Troubleshooting", { exact: true }).click(); + await settings.getByText("Android / GrapheneOS help", { exact: true }).click(); + for (const smallViewport of [{ width: 320, height: 568 }, { width: 390, height: 450 }, { width: 767, height: 600 }]) { + await page.setViewportSize(smallViewport); + await assertFits(settings.getByRole("button", { name: "Refresh", exact: true })); + await assertFits(settings.getByRole("button", { name: "Close settings", exact: true })); + assert.ok(await settings.locator(".app-settings-content").evaluate(el => el.scrollWidth <= el.clientWidth), "no settings body overflow"); + if (artifactDir) await page.screenshot({ path: `${artifactDir}/help-${smallViewport.width}x${smallViewport.height}.png` }); + } + } + await selectSection("Connection & session"); + await assertFits(settings.getByRole("button", { name: "Sign out", exact: true })); + await settings.getByText(`${target.origin}/api`, { exact: true }).waitFor(); + assert.doesNotMatch(await settings.textContent(), /settings-fixture-token/); + await settings.getByText("Keyboard shortcuts", { exact: true }).click(); + await settings.getByText("New chat", { exact: true }).waitFor(); + if (artifactDir) await page.screenshot({ path: `${artifactDir}/connection-${viewport.width}.png` }); + assert.equal(await page.evaluate(() => document.documentElement.scrollWidth > innerWidth), false); + const viewportMeta = await page.locator('meta[name="viewport"]').getAttribute("content"); + assert.match(viewportMeta, /user-scalable=no/); + assert.match(viewportMeta, /maximum-scale=1\.0(?:,|$)/); + assert.equal(writes.filter(path => !path.includes("/presence/") && !path.endsWith("/read-state")).length, 0, "opening settings never mutates chat or push preferences"); + // The hidden route is still available despite a saved Full preference. + await page.goto(new URL(`/lite?chat=${chat.id}`, target).href, { waitUntil: "networkidle" }); + await page.locator(".lite-shell").waitFor(); + assert.equal(new URL(page.url()).pathname, "/lite"); + assert.equal(new URL(page.url()).searchParams.get("chat"), chat.id); + const liteSidebarTrigger = page.getByRole("button", { name: "Open sidebar", exact: true }); + if (await liteSidebarTrigger.isVisible()) await liteSidebarTrigger.click(); + await page.getByRole("link", { name: "Full interface", exact: true }).click(); + await page.locator("main h1").filter({ hasText: chat.title }).waitFor(); + assert.match(await page.locator('meta[name="viewport"]').getAttribute("content"), /user-scalable=no/); + assert.deepEqual(errors, []); + await context.close(); + } + + for (const viewport of [{ width: 1280, height: 900 }, { width: 320, height: 568 }]) { + const { page, context, settings, openSidebar, openSettings, selectSection, errors, writes } = await fixture(viewport, "token", { seedModels: true }); + await page.locator("#composer-input").fill("Preserve my draft while choosing future models"); + await openSettings("Models"); + const chatModel = settings.getByRole("combobox", { name: "OpenAI chat model", exact: true }); + assert.equal(await chatModel.inputValue(), "remembered-initial"); + assert.equal(await settings.getByRole("combobox", { name: "Anthropic chat model", exact: true }).inputValue(), "legacy-custom"); + const quickProvider = settings.getByRole("combobox", { name: "Quick Questions provider", exact: true }); + const quickModel = settings.getByRole("combobox", { name: "Quick Questions model", exact: true }); + assert.equal(await quickProvider.inputValue(), "xai"); + assert.equal(await quickModel.inputValue(), "legacy-quick"); + // Reuse the catalog, accept custom values, commit with Tab, and cancel only the picker with Escape. + await chatModel.fill("listed-next"); + await settings.getByRole("option", { name: "listed-next-model", exact: true }).click(); + assert.equal(await chatModel.inputValue(), "listed-next-model"); + await chatModel.fill(""); + await chatModel.press("ArrowUp"); + await chatModel.press("Enter"); + assert.equal(await chatModel.inputValue(), "listed-next-model", "ArrowUp starts at the last catalog choice"); + await chatModel.fill(""); + await chatModel.press("ArrowDown"); + await chatModel.press("Enter"); + assert.equal(await chatModel.inputValue(), "fixture-model", "ArrowDown starts at the first catalog choice"); + await chatModel.fill("custom-chat-model"); + await chatModel.press("Tab"); + await page.waitForFunction(() => JSON.parse(localStorage.getItem("sybil:modelPreferencesByProvider")).openai === "custom-chat-model"); + await chatModel.fill("discard-this-model"); + await chatModel.press("Escape"); + assert.equal(await settings.isVisible(), true, "first Escape dismisses the model picker"); + assert.equal(await chatModel.inputValue(), "custom-chat-model"); + await quickProvider.selectOption("openai"); + assert.equal(await quickModel.inputValue(), "quick-original"); + await quickModel.fill("quick-new-model"); + await quickModel.press("Enter"); + await quickProvider.selectOption("xai"); + assert.equal(await quickModel.inputValue(), "legacy-quick", "Quick Questions retains a separate choice for every provider"); + await quickProvider.selectOption("openai"); + assert.equal(await quickModel.inputValue(), "quick-new-model"); + await page.waitForFunction(() => { + const selection = JSON.parse(localStorage.getItem("sybil:quickQuestionModelSelection")); + return selection.provider === "openai" && selection.modelPreferences.openai === "quick-new-model"; + }); + const stored = await page.evaluate(() => ({ chats: JSON.parse(localStorage.getItem("sybil:modelPreferencesByProvider")), quick: JSON.parse(localStorage.getItem("sybil:quickQuestionModelSelection")) })); + assert.equal(stored.chats.openai, "custom-chat-model"); + assert.equal(stored.chats.anthropic, "legacy-custom"); + assert.equal(stored.quick.provider, "openai"); + assert.equal(stored.quick.modelPreferences.xai, "legacy-quick"); + assert.equal(await settings.locator(".app-settings-content").evaluate(el => el.scrollWidth > el.clientWidth), false); + await settings.getByRole("heading", { name: "Models", exact: true }).scrollIntoViewIfNeeded(); + if (artifactDir) await page.screenshot({ path: `${artifactDir}/models-${viewport.width}.png` }); + await settings.getByRole("button", { name: "Close settings", exact: true }).click(); + assert.equal(await page.locator("#composer-input").inputValue(), "Preserve my draft while choosing future models"); + // Global model changes never patch the selected chat or change its current model. + if (viewport.width < 768) await page.getByRole("button", { name: "Close sidebar", exact: true }).click({ position: { x: viewport.width - 4, y: 80 } }); + await page.getByRole("button", { name: "Open chat settings", exact: true }).click(); + assert.equal(await page.getByRole("combobox", { name: "Model", exact: true }).inputValue(), "fixture-model"); + await page.keyboard.press("Escape"); + // Both menu and keyboard new-chat actions use the remembered model. + await page.keyboard.press("Control+j"); + await page.getByRole("button", { name: "Open chat settings", exact: true }).click(); + assert.equal(await page.getByRole("combobox", { name: "Model", exact: true }).inputValue(), "custom-chat-model"); + await page.keyboard.press("Escape"); + await page.keyboard.press("Control+i"); + assert.equal(await page.getByRole("combobox", { name: "Model", exact: true }).inputValue(), "quick-new-model", "Quick Questions uses the same preferences"); + await page.getByRole("combobox", { name: "Model", exact: true }).fill("quick-inline-model"); + await page.getByRole("combobox", { name: "Model", exact: true }).press("Enter"); + await page.getByRole("button", { name: "Close quick question", exact: true }).click(); + await openSettings("Models"); + assert.equal(await quickModel.inputValue(), "quick-inline-model", "inline Quick Questions changes appear in Settings"); + await page.reload({ waitUntil: "networkidle" }); + await openSettings("Models"); + assert.equal(await chatModel.inputValue(), "custom-chat-model"); + assert.equal(await quickModel.inputValue(), "quick-inline-model"); + // Section navigation is keyboard accessible and restores focus when returning to the mobile list. + if (viewport.width < 768) { + await settings.getByRole("button", { name: "Back to settings", exact: true }).click(); + assert.equal(await settings.getByRole("button", { name: "Models", exact: true }).evaluate(el => el === document.activeElement), true); + await page.keyboard.press("Enter"); + assert.equal(await settings.getByRole("group", { name: "Models", exact: true }).isVisible(), true); + } + await selectSection("Notifications"); + assert.equal(await settings.getByRole("button", { name: "Enable notifications", exact: true }).isVisible(), true); + assert.equal(writes.filter(path => !path.includes("/presence/") && !path.endsWith("/read-state")).length, 0, "model preferences never write to the server"); + assert.deepEqual(errors, []); + await context.close(); + } + + for (const options of [{ denyWrites: true }, { blockStorage: true }]) { + const { page, context, settings, openSettings, errors } = await fixture({ width: 390, height: 450 }, "open", options); + await openSettings("Models"); + await settings.getByRole("alert").filter({ hasText: "Browser storage is unavailable" }).waitFor(); + const model = settings.getByRole("combobox", { name: "OpenAI chat model", exact: true }); + await model.fill("session-only-model"); + await model.press("Enter"); + assert.equal(await model.inputValue(), "session-only-model", "storage failure retains usable in-memory preferences"); + if (options.denyWrites) { + await page.evaluate(() => { window.__denyPreferenceWrites = false; }); + await settings.getByRole("button", { name: "Retry saving", exact: true }).click(); + await settings.getByRole("alert").waitFor({ state: "detached" }); + assert.equal(await page.evaluate(() => JSON.parse(localStorage.getItem("sybil:modelPreferencesByProvider")).openai), "session-only-model"); + } + assert.deepEqual(errors, []); + await context.close(); + } + + const open = await fixture({ width: 390, height: 844 }, "open"); + await open.openSettings(); + await open.settings.getByText("Agent notifications require a server with token sign-in.", { exact: true }).waitFor(); + assert.equal(await open.settings.getByRole("button", { name: "Enable notifications", exact: true }).count(), 0); + await open.selectSection("Connection & session"); + await open.settings.getByText("Open mode. No sign-in required.", { exact: true }).waitFor(); + assert.equal(await open.settings.getByRole("button", { name: "Sign out", exact: true }).count(), 0); + await open.settings.getByRole("button", { name: "Close settings", exact: true }).click(); + assert.deepEqual(open.errors, []); + await open.context.close(); + console.log("PASS app Settings: desktop/mobile sections and focus, model migration/persistence/custom selection, Quick Questions sharing, existing-chat isolation, blocked storage/retry, diagnostics, connection, open mode, hidden /lite and full-app zoom"); +} finally { + await browser.close(); +} diff --git a/web/tests/lite-workspace.browser.mjs b/web/tests/lite-workspace.browser.mjs index 20cd27a..afb73f1 100644 --- a/web/tests/lite-workspace.browser.mjs +++ b/web/tests/lite-workspace.browser.mjs @@ -161,6 +161,7 @@ try { await selectNavigation("New chat"); await page.getByRole("heading", { name: "New chat", exact: true }).waitFor(); await page.waitForFunction(() => !document.querySelector("#lite-draft").disabled); + await page.locator(".lite-scroll [role=status]").waitFor({ state: "hidden" }); assert.equal(await page.locator(".lite-scroll").textContent(), "", "new chats have an empty transcript without welcome copy"); await page.getByLabel("Message", { exact: true }).fill("An unsent draft"); await selectNavigation("New chat"); diff --git a/web/tests/workspace-domain.test.mjs b/web/tests/workspace-domain.test.mjs index 5764d3a..f1163ed 100644 --- a/web/tests/workspace-domain.test.mjs +++ b/web/tests/workspace-domain.test.mjs @@ -4,6 +4,7 @@ import { buildCompletionMessages, buildWorkspaceUrl, getModelOptions, getVisibleProviders, hasNewPersistedUserMessage, loadStoredModelPreferences, normalizeStoredModelPreferences, pickProviderModel, readSidebarSelectionFromUrl, saveModelPreferences, + loadStoredQuickQuestionModelSelection, saveQuickQuestionModelSelection, } from "../src/lib/workspace-domain.ts"; const attachment = { kind: "text", id: "notes", filename: "notes.txt", mimeType: "text/plain", sizeBytes: 4, text: "plan", truncated: false }; @@ -61,5 +62,26 @@ test("blocked storage does not prevent reading defaults or using model controls" try { assert.equal(loadStoredModelPreferences().openai, null); assert.doesNotThrow(() => saveModelPreferences(normalizeStoredModelPreferences({ openai: "x" }))); + assert.equal(saveModelPreferences(normalizeStoredModelPreferences({ openai: "x" })), false); + assert.equal(loadStoredQuickQuestionModelSelection().provider, "openai"); + assert.equal(saveQuickQuestionModelSelection({ provider: "openai", modelPreferences: {} }), false); + } finally { delete globalThis.window; } +}); + +test("Quick Questions reuses its existing key and normalizes corrupt or older preferences", () => { + const stored = new Map(); + globalThis.window = { localStorage: { getItem: key => stored.get(key), setItem: (key, value) => stored.set(key, value) } }; + try { + const selection = { provider: "anthropic", modelPreferences: normalizeStoredModelPreferences({ anthropic: "custom-model" }) }; + assert.equal(saveQuickQuestionModelSelection(selection), true); + assert.deepEqual(JSON.parse(stored.get("sybil:quickQuestionModelSelection")), selection); + assert.deepEqual(loadStoredQuickQuestionModelSelection(), selection); + for (const value of ["null", "[]", "invalid json", '{"provider":"unknown","modelPreferences":{"openai":false}}']) { + stored.set("sybil:quickQuestionModelSelection", value); + assert.equal(loadStoredQuickQuestionModelSelection().provider, "openai"); + assert.equal(loadStoredQuickQuestionModelSelection().modelPreferences.openai, null); + } + assert.equal(saveModelPreferences(selection.modelPreferences), true); + assert.deepEqual(JSON.parse(stored.get("sybil:modelPreferencesByProvider")), selection.modelPreferences); } finally { delete globalThis.window; } });