feat(web): add global settings and simplify sidebar
This commit is contained in:
+33
-2
@@ -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.
|
||||
|
||||
+63
-200
@@ -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>;
|
||||
}
|
||||
|
||||
@@ -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 & 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
@@ -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;
|
||||
}
|
||||
|
||||
|
||||
@@ -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; }
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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")) }));
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
@@ -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");
|
||||
|
||||
@@ -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; }
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user