Compare commits
6
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ea6ee8cc64 | ||
|
|
557775af45 | ||
|
|
7333fe03e7 | ||
|
|
92a16a39c0 | ||
|
|
91c7c0310e | ||
|
|
d88018fd64 |
@@ -13,9 +13,6 @@ services:
|
||||
ANTHROPIC_API_KEY: ${ANTHROPIC_API_KEY:-}
|
||||
XAI_API_KEY: ${XAI_API_KEY:-}
|
||||
GEMINI_API_KEY: ${GEMINI_API_KEY:-}
|
||||
HERMES_AGENT_API_BASE_URL: ${HERMES_AGENT_API_BASE_URL:-http://127.0.0.1:8642/v1}
|
||||
HERMES_AGENT_API_KEY: ${HERMES_AGENT_API_KEY:-}
|
||||
HERMES_AGENT_MODEL: ${HERMES_AGENT_MODEL:-}
|
||||
EXA_API_KEY: ${EXA_API_KEY:-}
|
||||
BRAVE_SEARCH_API_KEY: ${BRAVE_SEARCH_API_KEY:-}
|
||||
CHAT_WEB_SEARCH_ENGINE: ${CHAT_WEB_SEARCH_ENGINE:-exa}
|
||||
|
||||
+29
-15
@@ -37,16 +37,19 @@ Chat upload limits:
|
||||
"openai": { "models": ["chat-latest", "gpt-4.1-mini"], "loadedAt": "2026-02-14T00:00:00.000Z", "error": null },
|
||||
"anthropic": { "models": ["claude-3-5-sonnet-latest"], "loadedAt": null, "error": null },
|
||||
"xai": { "models": ["grok-3-mini"], "loadedAt": null, "error": null },
|
||||
"gemini": { "models": ["gemini-3.5-flash"], "loadedAt": null, "error": null },
|
||||
"hermes-agent": { "models": ["hermes-agent"], "loadedAt": null, "error": null }
|
||||
"gemini": { "models": ["gemini-3.5-flash"], "loadedAt": null, "error": null }
|
||||
}
|
||||
}
|
||||
```
|
||||
- Selectable providers are `openai`, `anthropic`, `xai`, and `gemini`. Unsupported provider IDs are rejected with HTTP 400 by chat creation, chat completion, and Quick Question endpoints. Sybil Agent runs through its dedicated room or an inline `@sybil` mention; it is not a model-catalog provider.
|
||||
- OpenAI model lists are filtered to models that are expected to work with the backend's Responses API implementation, including the exact `chat-latest` alias when returned by OpenAI. Audio, image-generation, embedding, moderation, and other specialized model ids remain excluded. See [OpenAI's Chat Latest documentation](https://developers.openai.com/api/docs/models/chat-latest) for supported capabilities.
|
||||
- Gemini model lists are loaded from Google's native Models API and filtered to Gemini `generateContent` model ids.
|
||||
- `hermes-agent` is included only when `HERMES_AGENT_API_KEY` is configured. Set it to Hermes `API_SERVER_KEY`, or any non-empty value if that local server does not require auth. `HERMES_AGENT_API_BASE_URL` defaults to `http://127.0.0.1:8642/v1`; set `HERMES_AGENT_MODEL` only when you need an additional fallback/override model id.
|
||||
- The backend loads provider model lists at startup and refreshes them about once every 24 hours. If a later provider refresh fails, the response keeps the last loaded model list for that provider and sets `error` to the latest failure message.
|
||||
|
||||
Each provider also includes `reasoningCapabilities`, a map keyed by exact model ID. For example, OpenAI includes `"gpt-5.2": { "efforts": ["none", "low", "medium", "high", "xhigh"], "defaultEffort": "none" }`. This metadata comes from a conservative backend allowlist verified against [OpenAI model documentation](https://developers.openai.com/api/docs/models/gpt-5.2) and the [reasoning guidance](https://developers.openai.com/api/docs/guides/deployment-checklist#set-up-reasoningeffort), independently of model-list refreshes. It describes capabilities, not account access. `defaultEffort: null` means the provider default has not been established; it does not mean `none`. Defaults vary by model (for example GPT-5.2 uses `none`, [GPT-5.5 uses `medium`](https://developers.openai.com/api/docs/models/gpt-5.5)).
|
||||
|
||||
Clients must use the returned effort levels for the selected provider/model. Missing entries, missing metadata from an older server, unknown aliases/snapshots, and other providers fall back to **Model default**, with no effort sent to the provider. Do not infer support from a `gpt-` prefix or from an OpenAI-compatible endpoint. The full web Chat Settings slider includes Model default plus the supported levels; choices are saved per chat and remembered per provider/model in browser storage for new chats.
|
||||
|
||||
## Chat Tools
|
||||
|
||||
### `GET /v1/chat-tools`
|
||||
@@ -104,6 +107,7 @@ Behavior notes:
|
||||
"initiatedModel": "gpt-4.1-mini",
|
||||
"lastUsedProvider": "openai",
|
||||
"lastUsedModel": "gpt-4.1-mini",
|
||||
"reasoningEffort": null,
|
||||
"additionalSystemPrompt": null,
|
||||
"enabledTools": ["web_search", "fetch_url"]
|
||||
},
|
||||
@@ -148,8 +152,9 @@ History search (`q`) notes:
|
||||
```json
|
||||
{
|
||||
"title": "optional title",
|
||||
"provider": "optional openai|anthropic|xai|gemini|hermes-agent",
|
||||
"provider": "optional openai|anthropic|xai|gemini",
|
||||
"model": "optional model id",
|
||||
"reasoningEffort": null,
|
||||
"additionalSystemPrompt": "optional stored system prompt",
|
||||
"enabledTools": ["web_search", "fetch_url"],
|
||||
"messages": [
|
||||
@@ -166,6 +171,7 @@ History search (`q`) notes:
|
||||
|
||||
Behavior notes:
|
||||
- `provider` and `model` must be supplied together when present.
|
||||
- `reasoningEffort` is optional: `null` (the default) or `none|minimal|low|medium|high|xhigh|max`. The server stores only an effort supported by that exact provider/model; unsupported combinations become `null`. A string outside this enum is rejected. `null` means omit the provider parameter, whereas `"none"` explicitly disables reasoning on models that support it.
|
||||
- Newly created non-fork chats have `parentChatId: null` and `titleGenerationPending: false`.
|
||||
- When `provider`/`model` are supplied, the new chat initializes `initiatedProvider`/`initiatedModel` and `lastUsedProvider`/`lastUsedModel`.
|
||||
- `additionalSystemPrompt` is trimmed and stored on the chat; blank values are stored as `null`.
|
||||
@@ -182,18 +188,19 @@ Behavior notes:
|
||||
Behavior notes:
|
||||
- With no `messageId`, the server copies the complete source transcript. With an assistant response `messageId`, it copies the transcript through that response, inclusive.
|
||||
- The source chat is unchanged. Copied messages receive new ids while retaining their role, content, name, creation time, order, and metadata except for the source request's transport-only `clientRequestId`. Attachments, tool-call metadata, and per-response `metadata.generation` are retained. For older replies with an exact call-log match, generation metadata is recovered before copying. LLM call logs, star/project memberships, and other child threads are not copied.
|
||||
- The fork inherits the source chat's user, initiated/last-used provider and model, additional system prompt, and enabled tool settings.
|
||||
- The fork inherits the source chat's user, initiated/last-used provider and model, supported reasoning effort, additional system prompt, and enabled tool settings.
|
||||
- A fork of a root or another fork always sets `parentChatId` to the single root chat id. Root chats keep `parentChatId: null`.
|
||||
- A whole-chat fork starts with `Fork of <source title>` (or `Fork of Untitled chat`). A message fork starts with `Fork of '<message snippet>'`.
|
||||
- The placeholder title is returned with `titleGenerationPending: true`. After the first new prompt, call `POST /v1/chats/title/suggest`; the placeholder is eligible for replacement exactly once.
|
||||
|
||||
### `PATCH /v1/chats/:chatId`
|
||||
- Body: any subset of `{ "title": string, "additionalSystemPrompt": string|null, "enabledTools": string[] }`
|
||||
- Body: any subset of `{ "title": string, "provider": Provider, "model": string, "reasoningEffort": ReasoningEffort|null, "additionalSystemPrompt": string|null, "enabledTools": string[] }`
|
||||
- Response: `{ "chat": ChatSummary }`
|
||||
- Blank titles are rejected. The server trims surrounding whitespace before storing the title.
|
||||
- Setting a title clears `titleGenerationPending`, preventing an in-flight or later automatic suggestion from replacing the manual title.
|
||||
- `additionalSystemPrompt: null` clears the stored prompt. Blank string values are also stored as `null`.
|
||||
- `enabledTools: []` disables Sybil-managed tools for this chat. Omitted settings are left unchanged.
|
||||
- `provider` and `model` must be supplied together. They update `lastUsedProvider`/`lastUsedModel` immediately, atomically with `reasoningEffort`, without changing the original `initiatedProvider`/`initiatedModel`. Changing the model/provider without an effort clears the old effort. Keeping the same model without an effort preserves it. An effort-only patch uses the saved model. `reasoningEffort: null` resets to Model default; unsupported combinations normalize to `null` as on creation.
|
||||
- Updating chat fields changes the returned chat's `updatedAt`.
|
||||
- Not found: `404 { "message": "chat not found" }`
|
||||
|
||||
@@ -286,7 +293,7 @@ Notes:
|
||||
{
|
||||
"chatId": "optional-chat-id",
|
||||
"clientRequestId": "optional-client-generated-id",
|
||||
"provider": "openai|anthropic|xai|gemini|hermes-agent",
|
||||
"provider": "openai|anthropic|xai|gemini",
|
||||
"model": "string",
|
||||
"messages": [
|
||||
{
|
||||
@@ -318,7 +325,8 @@ Notes:
|
||||
"additionalSystemPrompt": "optional one-off system prompt",
|
||||
"enabledTools": ["web_search", "fetch_url"],
|
||||
"temperature": 0.2,
|
||||
"maxTokens": 256
|
||||
"maxTokens": 256,
|
||||
"reasoningEffort": null
|
||||
}
|
||||
```
|
||||
- Response:
|
||||
@@ -337,7 +345,8 @@ Behavior notes:
|
||||
- If `chatId` is present, server validates chat existence.
|
||||
- `clientRequestId` is an optional stable identifier for retries of a persisted inline Agent completion.
|
||||
- For a persisted ordinary chat, a literal case-insensitive `@sybil` token in the latest user message invokes the existing persistent Sybil Agent instead of the selected provider for that turn. Email addresses, code spans/fences, indented code, and Markdown quote lines do not trigger it. The message and Agent reply remain visible in the chat; both are marked as Agent asides and are excluded by the backend from later selected-provider conversation history. The Agent root request is not projected into the visible Agent transcript.
|
||||
- The completion response identifies an inline Agent reply with `provider: "hermes-agent"`, `model: "sybil-agent"`, and `message.name: "Sybil Agent"`, `message.agentAside: true`.
|
||||
- The completion response identifies an inline Agent reply with `provider: "sybil-agent"`, `model: "sybil-agent"`, and `message.name: "Sybil Agent"`, `message.agentAside: true`.
|
||||
- The response provider identity can therefore differ from the request's selectable provider. Clients must accept `sybil-agent` in completion responses without adding it to provider selectors.
|
||||
- Agent asides are identified by backend-stored `metadata.agentAside`, not client-supplied metadata. The ordinary-chat list/history APIs above support Agent tools reading the complete visible thread, including prior asides and attachment data, with cursor pagination.
|
||||
- Before the Agent is invoked, the backend paginates and supplies the complete safe visible-thread projection as required initial context; the Agent does not have to choose `read_chat_history` for the current thread. User/assistant asides and full supported attachment representations are included, while system/tool rows and unrelated metadata are excluded. Historical content remains untrusted context, not new authority.
|
||||
- The initial context transfer is limited to 30 MiB. A stored text attachment marked truncated, incomplete history, or a transfer/provider context-limit failure returns an explicit error and no answer from partial history; providers may reject a complete thread that exceeds their model context window.
|
||||
@@ -345,6 +354,8 @@ Behavior notes:
|
||||
- Saved ordinary assistant responses also store the completion's provider/model in `metadata.generation`, exposed by `GET /v1/chats/:chatId`; changing the chat selection does not relabel previous responses.
|
||||
- `additionalSystemPrompt`, when present directly or loaded from stored chat settings, is prepended to the provider request as a `system` message and is not inserted into the persisted chat transcript by this endpoint.
|
||||
- `enabledTools` limits Sybil-managed tools for this request. When omitted for a saved chat, the stored chat setting is used; otherwise all available tools are enabled by default. An empty array disables Sybil-managed tools.
|
||||
- Optional `reasoningEffort` uses the enum/null contract above. Omission inherits the saved effort only when the request provider/model exactly matches the saved pair; otherwise it uses Model default. Explicit `null` resets it. The effective validated value is persisted alongside the last-used model on ordinary persisted calls, including failed calls. Inline `@sybil` calls use the separate Agent configuration.
|
||||
- The backend checks support again before sending OpenAI requests: Responses uses `reasoning: { effort }`; Chat Completions uses `reasoning_effort`. Defaults and unsupported combinations omit both fields. With an explicit effort other than `none`, OpenAI `temperature` is omitted to avoid incompatible sampling parameters. For allowlisted reasoning models, Chat Completions maps `maxTokens` to `max_completion_tokens`; Responses uses `max_output_tokens`.
|
||||
- `maxTokens` is optional. For `anthropic`, when omitted the backend requests the selected model's maximum output token limit from Anthropic's Models API and uses that as `max_tokens`; if the model limit cannot be loaded, the fallback is 128000. For other providers, omitted `maxTokens` is not sent as an explicit cap.
|
||||
- Server persists final assistant output and call metadata (`LlmCall`) in DB.
|
||||
- Server updates chat-level model metadata on each call: `lastUsedProvider`/`lastUsedModel`; first successful/failed call also initializes `initiatedProvider`/`initiatedModel` if unset.
|
||||
@@ -355,10 +366,9 @@ Behavior notes:
|
||||
- For `anthropic`, backend calls Anthropic's Messages API and enables internal tool use with Anthropic `tool_use`/`tool_result` content blocks.
|
||||
- For `xai`, backend calls xAI's OpenAI-compatible Chat Completions API and enables internal tool use with the same internal system instruction.
|
||||
- For `gemini`, backend calls Google's native Gemini `generateContent` API and enables internal tool use with Gemini function calling.
|
||||
- For `hermes-agent`, backend calls the configured Hermes Agent OpenAI-compatible Chat Completions API without adding Sybil-managed tool definitions; Hermes Agent handles its own tools server-side.
|
||||
- For `openai`, image attachments are sent as Responses `input_image` items and text attachments are sent as `input_text` items.
|
||||
- For `gemini`, image attachments are sent as native Gemini `inlineData` parts and text attachments are sent as text parts.
|
||||
- For `xai` and `hermes-agent`, image attachments are sent as Chat Completions content parts alongside text.
|
||||
- For `xai`, image attachments are sent as Chat Completions content parts alongside text.
|
||||
- For `openai`, Responses calls that can enter the server-managed tool loop use `store: true` so reasoning and function-call items can be passed between tool rounds.
|
||||
- For `anthropic`, image attachments are sent as Messages API `image` blocks using base64 source data; text attachments are added as `text` blocks.
|
||||
- Available Sybil-managed tool calls for `openai`, `anthropic`, `xai`, and `gemini`: `web_search` and `fetch_url`. When `CHAT_CODEX_TOOL_ENABLED=true`, `codex_exec` is also available. When `CHAT_SHELL_TOOL_ENABLED=true`, `shell_exec` is also available.
|
||||
@@ -481,6 +491,8 @@ Behavior notes:
|
||||
|
||||
## Type Shapes
|
||||
|
||||
Saved selections for unsupported provider IDs are returned as `null` for both the provider and its paired model. Chat messages and historical call records are preserved; an unsupported `calls[].provider` is returned as `null`, while the original call request/response snapshots remain unchanged. Clients should choose a supported provider before continuing those chats.
|
||||
|
||||
`ChatSummary`
|
||||
```json
|
||||
{
|
||||
@@ -492,10 +504,11 @@ Behavior notes:
|
||||
"updatedAt": "...",
|
||||
"starred": false,
|
||||
"starredAt": null,
|
||||
"initiatedProvider": "openai|anthropic|xai|gemini|hermes-agent|null",
|
||||
"initiatedProvider": "openai|anthropic|xai|gemini|null",
|
||||
"initiatedModel": "string|null",
|
||||
"lastUsedProvider": "openai|anthropic|xai|gemini|hermes-agent|null",
|
||||
"lastUsedProvider": "openai|anthropic|xai|gemini|null",
|
||||
"lastUsedModel": "string|null",
|
||||
"reasoningEffort": "none|minimal|low|medium|high|xhigh|max|null",
|
||||
"additionalSystemPrompt": null,
|
||||
"enabledTools": ["web_search", "fetch_url"]
|
||||
}
|
||||
@@ -546,10 +559,11 @@ Behavior notes:
|
||||
"updatedAt": "...",
|
||||
"starred": false,
|
||||
"starredAt": null,
|
||||
"initiatedProvider": "openai|anthropic|xai|gemini|hermes-agent|null",
|
||||
"initiatedProvider": "openai|anthropic|xai|gemini|null",
|
||||
"initiatedModel": "string|null",
|
||||
"lastUsedProvider": "openai|anthropic|xai|gemini|hermes-agent|null",
|
||||
"lastUsedProvider": "openai|anthropic|xai|gemini|null",
|
||||
"lastUsedModel": "string|null",
|
||||
"reasoningEffort": "none|minimal|low|medium|high|xhigh|max|null",
|
||||
"additionalSystemPrompt": null,
|
||||
"enabledTools": ["web_search", "fetch_url"],
|
||||
"messages": [Message]
|
||||
|
||||
@@ -26,7 +26,7 @@ Web presentation note: `/lite` uses these same chat streams and existing search
|
||||
"chatId": "optional-chat-id",
|
||||
"persist": true,
|
||||
"clientRequestId": "optional-client-generated-id",
|
||||
"provider": "openai|anthropic|xai|gemini|hermes-agent",
|
||||
"provider": "openai|anthropic|xai|gemini",
|
||||
"model": "string",
|
||||
"messages": [
|
||||
{
|
||||
@@ -58,7 +58,8 @@ Web presentation note: `/lite` uses these same chat streams and existing search
|
||||
"additionalSystemPrompt": "optional one-off system prompt",
|
||||
"enabledTools": ["web_search", "fetch_url"],
|
||||
"temperature": 0.2,
|
||||
"maxTokens": 256
|
||||
"maxTokens": 256,
|
||||
"reasoningEffort": null
|
||||
}
|
||||
```
|
||||
|
||||
@@ -73,10 +74,13 @@ Notes:
|
||||
- For persisted streams, backend stores only new non-assistant input history rows to avoid duplicates.
|
||||
- `additionalSystemPrompt`, when present directly or loaded from stored chat settings, is prepended to the provider request as a `system` message and is not inserted into the persisted chat transcript by this endpoint.
|
||||
- `enabledTools` limits Sybil-managed tools for this request. When omitted for a saved chat, the stored chat setting is used; otherwise all available tools are enabled by default. An empty array disables Sybil-managed tools.
|
||||
- Optional `reasoningEffort` accepts `null` or `none|minimal|low|medium|high|xhigh|max`. Load the selected provider/model's supported levels from `GET /v1/models` → `reasoningCapabilities` ([REST contract](./rest.md#models)). Omission inherits the chat's saved effort only for the exact same provider/model; `null` explicitly selects Model default. Unknown models and unsupported combinations normalize to `null`; invalid enum strings are rejected. The backend omits the effort parameter for Model default and unsupported combinations, letting the provider choose its model-specific default. `"none"` is an explicit setting and differs from `null`.
|
||||
- Ordinary persisted streams save the effective effort with the last-used provider/model. Non-persistent streams and Quick Questions do not save it. Inline `@sybil` turns use the separate Agent settings. OpenAI Responses requests use `reasoning: { effort }`, and Chat Completions requests use `reasoning_effort`, including subsequent tool rounds. Explicit reasoning efforts other than `none` omit `temperature`; allowlisted reasoning models use Chat Completions `max_completion_tokens` for `maxTokens`. SSE event shapes are unchanged.
|
||||
- `maxTokens` is optional. For `anthropic`, when omitted the backend requests the selected model's maximum output token limit from Anthropic's Models API and uses that as `max_tokens`; if the model limit cannot be loaded, the fallback is 128000. For other providers, omitted `maxTokens` is not sent as an explicit cap.
|
||||
- Attachments are optional and are persisted under `message.metadata.attachments` on stored user messages when `persist` is `true`.
|
||||
- For a persisted ordinary chat, a literal case-insensitive `@sybil` token in the latest user message invokes the existing persistent Sybil Agent instead of the selected provider. Email addresses, code spans/fences, indented code, and Markdown quote lines do not trigger it. The visible user message and inline Agent reply remain in the ordinary chat and are marked with backend-owned `metadata.agentAside`; the backend excludes both from later selected-provider context without deleting the visible rows. This routing does not apply to the special Agent tab or Quick Questions.
|
||||
- The `meta` event for an inline Agent reply contains `provider: "hermes-agent"`, `model: "sybil-agent"`, and `agentAside: true`. The selected ordinary provider is not run for that turn. Clients should render the response with the existing Sybil Agent identity and retain aside metadata on the optimistic streaming message until the canonical REST refresh.
|
||||
- The `meta` event for an inline Agent reply contains `provider: "sybil-agent"`, `model: "sybil-agent"`, and `agentAside: true`. The selected ordinary provider is not run for that turn. Clients should render the response with the existing Sybil Agent identity and retain aside metadata on the optimistic streaming message until the canonical REST refresh.
|
||||
- `sybil-agent` is a response identity, not an accepted request provider or a model-picker option. Decode completion metadata independently from the selectable provider list. Active-stream attachment and completed-request retries use the same identity.
|
||||
- Before the Agent request starts, the backend loads every page of the safe visible thread and sends it as required initial context, including previous asides and supported attachment contents. This is not an optional `read_chat_history` tool call. Hidden system/tool rows and unrelated metadata are excluded; transcript data is untrusted context. If history/attachment projection is incomplete or exceeds the 30 MiB transfer limit, or the Agent model rejects the complete context, the stream reports an error and emits no partial-context answer.
|
||||
|
||||
Persisted chat streams with a `chatId` are backend-owned active runs:
|
||||
@@ -105,13 +109,14 @@ This endpoint is intended for clients that restored an active `chatId` from `GET
|
||||
Request body:
|
||||
```json
|
||||
{
|
||||
"provider": "openai|anthropic|xai|gemini|hermes-agent",
|
||||
"provider": "openai|anthropic|xai|gemini",
|
||||
"model": "string",
|
||||
"question": "What is the capital of France?",
|
||||
"enabledTools": ["web_search", "fetch_url"],
|
||||
"userLocation": "optional city, region, country",
|
||||
"temperature": 0.2,
|
||||
"maxTokens": 256
|
||||
"maxTokens": 256,
|
||||
"reasoningEffort": null
|
||||
}
|
||||
```
|
||||
|
||||
@@ -121,7 +126,7 @@ Behavior notes:
|
||||
- The server prepends a Quick Question system prompt that asks for a succinct, direct, self-contained answer without follow-up questions. Clients do not send or maintain this prompt.
|
||||
- Quick Questions are always non-persistent. The endpoint does not create a chat or store messages, tool-call logs, assistant output, or `LlmCall` metadata.
|
||||
- The response uses the same `meta`, `tool_call`, `delta`, `done`, and `error` SSE events as chat completion streams. The `meta` event has `chatId: null` and `callId: null`.
|
||||
- `enabledTools`, `temperature`, and `maxTokens` are optional and behave as they do for chat completion streams. When `enabledTools` is omitted, all available Sybil-managed tools are enabled by default.
|
||||
- `enabledTools`, `temperature`, `maxTokens`, and `reasoningEffort` are optional and behave as they do for chat completion streams. When `enabledTools` is omitted, all available Sybil-managed tools are enabled by default. Omitted/null `reasoningEffort` uses the model default; Quick Questions never inherit ordinary chat settings. Existing Quick Question clients omit it.
|
||||
- User location is inferred from the same request headers as chat completion streams when `userLocation` is omitted.
|
||||
|
||||
## Event Stream Contract
|
||||
@@ -218,10 +223,9 @@ Terminal tool-call event:
|
||||
- `xai`: backend uses xAI's OpenAI-compatible Chat Completions API and may execute the same internal tool calls before producing final text.
|
||||
- `gemini`: backend uses Google's native Gemini `streamGenerateContent` API and may execute the same internal tool calls before producing final text.
|
||||
- `fetch_url` sends browser-like navigation headers for outbound URL requests to reduce false 403s from sites that reject generic server clients. It converts HTML to text and extracts selectable PDF text page by page (without OCR), including when the response media type is inaccurate but the PDF signature is present. URL downloads are limited to 10 MiB, PDF extraction to 30 pages per call and an isolated worker terminated after 8 seconds, and accumulated PDF text to `maxCharacters` (default 12,000; maximum 50,000), plus a brief truncation hint. PDF tool results include `pdfStatus`, `pageCount`, and selected `pages`; call with `pages:[...]` to retrieve specific pages. Encrypted, page-free, and text-free PDFs return explicit status and text with `ok:false`. Oversized responses fail with a size-limit error.
|
||||
- `hermes-agent`: backend uses the configured Hermes Agent OpenAI-compatible Chat Completions API. Sybil does not add its own tool definitions for this provider; Hermes Agent handles its own tools server-side. Custom Hermes stream events are normalized away unless they produce text deltas in this SSE contract.
|
||||
- `openai`: image attachments are sent as Responses `input_image` items; text attachments are sent as `input_text` items.
|
||||
- `gemini`: image attachments are sent as native Gemini `inlineData` parts; text attachments are inlined as text parts.
|
||||
- `xai` and `hermes-agent`: image attachments are sent as Chat Completions content parts; text attachments are inlined as text parts.
|
||||
- `xai`: image attachments are sent as Chat Completions content parts; text attachments are inlined as text parts.
|
||||
- `openai`: Responses calls that can enter the server-managed tool loop use `store: true` so reasoning and function-call items can be passed between tool rounds.
|
||||
- `anthropic`: streamed via event stream; emits `delta` from `content_block_delta` with `text_delta`, and emits normalized `tool_call` SSE events when Anthropic `tool_use` blocks are executed. Image attachments are sent as base64 `image` blocks and text attachments are appended as `text` blocks.
|
||||
- `web_search` uses `CHAT_WEB_SEARCH_ENGINE`: `exa` (default), `brave` (requires `BRAVE_SEARCH_API_KEY`), or `searxng` (requires `SEARXNG_BASE_URL`; the instance must allow `format=json`). This only affects chat-mode tool calls, not search-mode endpoints.
|
||||
|
||||
@@ -58,4 +58,3 @@ Instructions for work under `/Users/buzzert/src/sybil-2/ios`.
|
||||
- Anthropic: `claude-3-5-sonnet-latest`
|
||||
- xAI: `grok-3-mini`
|
||||
- Gemini: `gemini-3.5-flash`
|
||||
- Hermes Agent: `hermes-agent`
|
||||
|
||||
@@ -5,7 +5,6 @@ public enum Provider: String, Codable, CaseIterable, Hashable, Sendable {
|
||||
case anthropic
|
||||
case xai
|
||||
case gemini
|
||||
case hermesAgent = "hermes-agent"
|
||||
|
||||
public var displayName: String {
|
||||
switch self {
|
||||
@@ -13,7 +12,6 @@ public enum Provider: String, Codable, CaseIterable, Hashable, Sendable {
|
||||
case .anthropic: return "Anthropic"
|
||||
case .xai: return "xAI"
|
||||
case .gemini: return "Gemini"
|
||||
case .hermesAgent: return "Hermes Agent"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -192,9 +190,9 @@ extension ChatSummary {
|
||||
updatedAt = try container.decode(Date.self, forKey: .updatedAt)
|
||||
starred = try container.decodeIfPresent(Bool.self, forKey: .starred) ?? false
|
||||
starredAt = try container.decodeIfPresent(Date.self, forKey: .starredAt)
|
||||
initiatedProvider = try container.decodeIfPresent(Provider.self, forKey: .initiatedProvider)
|
||||
initiatedProvider = try container.decodeIfPresent(String.self, forKey: .initiatedProvider).flatMap(Provider.init(rawValue:))
|
||||
initiatedModel = try container.decodeIfPresent(String.self, forKey: .initiatedModel)
|
||||
lastUsedProvider = try container.decodeIfPresent(Provider.self, forKey: .lastUsedProvider)
|
||||
lastUsedProvider = try container.decodeIfPresent(String.self, forKey: .lastUsedProvider).flatMap(Provider.init(rawValue:))
|
||||
lastUsedModel = try container.decodeIfPresent(String.self, forKey: .lastUsedModel)
|
||||
}
|
||||
}
|
||||
@@ -329,9 +327,9 @@ extension WorkspaceItem {
|
||||
updatedAt = try container.decode(Date.self, forKey: .updatedAt)
|
||||
starred = try container.decodeIfPresent(Bool.self, forKey: .starred) ?? false
|
||||
starredAt = try container.decodeIfPresent(Date.self, forKey: .starredAt)
|
||||
initiatedProvider = try container.decodeIfPresent(Provider.self, forKey: .initiatedProvider)
|
||||
initiatedProvider = try container.decodeIfPresent(String.self, forKey: .initiatedProvider).flatMap(Provider.init(rawValue:))
|
||||
initiatedModel = try container.decodeIfPresent(String.self, forKey: .initiatedModel)
|
||||
lastUsedProvider = try container.decodeIfPresent(Provider.self, forKey: .lastUsedProvider)
|
||||
lastUsedProvider = try container.decodeIfPresent(String.self, forKey: .lastUsedProvider).flatMap(Provider.init(rawValue:))
|
||||
lastUsedModel = try container.decodeIfPresent(String.self, forKey: .lastUsedModel)
|
||||
}
|
||||
}
|
||||
@@ -522,9 +520,9 @@ extension ChatDetail {
|
||||
updatedAt = try container.decode(Date.self, forKey: .updatedAt)
|
||||
starred = try container.decodeIfPresent(Bool.self, forKey: .starred) ?? false
|
||||
starredAt = try container.decodeIfPresent(Date.self, forKey: .starredAt)
|
||||
initiatedProvider = try container.decodeIfPresent(Provider.self, forKey: .initiatedProvider)
|
||||
initiatedProvider = try container.decodeIfPresent(String.self, forKey: .initiatedProvider).flatMap(Provider.init(rawValue:))
|
||||
initiatedModel = try container.decodeIfPresent(String.self, forKey: .initiatedModel)
|
||||
lastUsedProvider = try container.decodeIfPresent(Provider.self, forKey: .lastUsedProvider)
|
||||
lastUsedProvider = try container.decodeIfPresent(String.self, forKey: .lastUsedProvider).flatMap(Provider.init(rawValue:))
|
||||
lastUsedModel = try container.decodeIfPresent(String.self, forKey: .lastUsedModel)
|
||||
messages = try container.decode([Message].self, forKey: .messages)
|
||||
}
|
||||
@@ -625,7 +623,8 @@ public struct CompletionRequestMessage: Codable, Sendable {
|
||||
public struct CompletionStreamMeta: Codable, Sendable {
|
||||
public var chatId: String?
|
||||
public var callId: String?
|
||||
public var provider: Provider
|
||||
// Responses may identify Sybil Agent, which is not a selectable LLM provider.
|
||||
public var provider: String
|
||||
public var model: String
|
||||
public var agentAside: Bool? = nil
|
||||
}
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
import SwiftUI
|
||||
#if os(iOS)
|
||||
import UIKit
|
||||
#endif
|
||||
|
||||
struct SybilPromptField: View {
|
||||
var placeholder: String = "Enter Prompt"
|
||||
@@ -6,9 +9,50 @@ struct SybilPromptField: View {
|
||||
@FocusState.Binding var focused: Bool
|
||||
var selection: Binding<TextSelection?>? = nil
|
||||
var axis: Axis = .vertical
|
||||
var returnSubmits = false
|
||||
var submit: () -> Void
|
||||
|
||||
var body: some View {
|
||||
Group {
|
||||
#if os(iOS) && !targetEnvironment(macCatalyst)
|
||||
if returnSubmits {
|
||||
SybilReturnSubmittingTextView(
|
||||
placeholder: placeholder,
|
||||
text: $text,
|
||||
focused: $focused,
|
||||
selection: selection,
|
||||
submit: submit
|
||||
)
|
||||
.overlay(alignment: .topLeading) {
|
||||
if text.isEmpty {
|
||||
Text(placeholder)
|
||||
.font(.sybil(.body))
|
||||
.foregroundStyle(SybilTheme.textMuted)
|
||||
.padding(.horizontal, 12)
|
||||
.padding(.vertical, 10)
|
||||
.allowsHitTesting(false)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
swiftUITextField
|
||||
}
|
||||
#else
|
||||
swiftUITextField
|
||||
.submitOnMacReturn(submit)
|
||||
#endif
|
||||
}
|
||||
.padding(.horizontal, 12)
|
||||
.padding(.vertical, 10)
|
||||
.background(
|
||||
RoundedRectangle(cornerRadius: 12)
|
||||
.fill(SybilTheme.composerGradient)
|
||||
.opacity(0.98)
|
||||
)
|
||||
.foregroundStyle(SybilTheme.text)
|
||||
}
|
||||
|
||||
@ViewBuilder
|
||||
private var swiftUITextField: some View {
|
||||
Group {
|
||||
if let selection {
|
||||
TextField(placeholder, text: $text, selection: selection, axis: axis)
|
||||
@@ -23,18 +67,127 @@ struct SybilPromptField: View {
|
||||
.lineLimit(1 ... 6)
|
||||
.submitLabel(.send)
|
||||
.onSubmit(submit)
|
||||
.submitOnMacReturn(submit)
|
||||
.padding(.horizontal, 12)
|
||||
.padding(.vertical, 10)
|
||||
.background(
|
||||
RoundedRectangle(cornerRadius: 12)
|
||||
.fill(SybilTheme.composerGradient)
|
||||
.opacity(0.98)
|
||||
)
|
||||
.foregroundStyle(SybilTheme.text)
|
||||
}
|
||||
}
|
||||
|
||||
#if os(iOS) && !targetEnvironment(macCatalyst)
|
||||
private final class ReturnSubmittingUITextView: UITextView {
|
||||
var shouldFocus = false
|
||||
|
||||
override func didMoveToWindow() {
|
||||
super.didMoveToWindow()
|
||||
if shouldFocus, window != nil, !isFirstResponder {
|
||||
becomeFirstResponder()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private struct SybilReturnSubmittingTextView: UIViewRepresentable {
|
||||
var placeholder: String
|
||||
@Binding var text: String
|
||||
@FocusState.Binding var focused: Bool
|
||||
var selection: Binding<TextSelection?>?
|
||||
var submit: () -> Void
|
||||
|
||||
func makeCoordinator() -> Coordinator {
|
||||
Coordinator(parent: self)
|
||||
}
|
||||
|
||||
func makeUIView(context: Context) -> ReturnSubmittingUITextView {
|
||||
let textView = ReturnSubmittingUITextView()
|
||||
SybilFontRegistry.registerIfNeeded()
|
||||
textView.delegate = context.coordinator
|
||||
textView.backgroundColor = .clear
|
||||
textView.textColor = UIColor(SybilTheme.text)
|
||||
let baseFont = UIFont(name: "Inter", size: 17) ?? .preferredFont(forTextStyle: .body)
|
||||
textView.font = UIFontMetrics(forTextStyle: .body).scaledFont(for: baseFont)
|
||||
textView.textContainerInset = .zero
|
||||
textView.textContainer.lineFragmentPadding = 0
|
||||
textView.isScrollEnabled = true
|
||||
textView.returnKeyType = .send
|
||||
textView.enablesReturnKeyAutomatically = false
|
||||
textView.autocapitalizationType = .sentences
|
||||
textView.autocorrectionType = .yes
|
||||
textView.accessibilityLabel = placeholder
|
||||
textView.accessibilityIdentifier = "quick-question-prompt"
|
||||
return textView
|
||||
}
|
||||
|
||||
func updateUIView(_ textView: ReturnSubmittingUITextView, context: Context) {
|
||||
context.coordinator.parent = self
|
||||
textView.shouldFocus = focused
|
||||
if textView.text != text {
|
||||
textView.text = text
|
||||
}
|
||||
if textView.isFirstResponder != focused {
|
||||
if focused {
|
||||
textView.becomeFirstResponder()
|
||||
} else {
|
||||
textView.resignFirstResponder()
|
||||
}
|
||||
}
|
||||
if let selection,
|
||||
let value = selection.wrappedValue,
|
||||
let selectedRange = nsRange(for: value, in: text) {
|
||||
if textView.selectedRange != selectedRange {
|
||||
textView.selectedRange = selectedRange
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func nsRange(for selection: TextSelection, in text: String) -> NSRange? {
|
||||
switch selection.indices {
|
||||
case .selection(let range):
|
||||
return NSRange(range, in: text)
|
||||
case .multiSelection:
|
||||
return nil
|
||||
@unknown default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func sizeThatFits(_ proposal: ProposedViewSize, uiView: UITextView, context: Context) -> CGSize? {
|
||||
guard let width = proposal.width, width.isFinite, width > 0 else { return nil }
|
||||
let measured = uiView.sizeThatFits(CGSize(width: width, height: .greatestFiniteMagnitude)).height
|
||||
let lineHeight = uiView.font?.lineHeight ?? 21
|
||||
return CGSize(width: width, height: min(max(lineHeight, measured), lineHeight * 6))
|
||||
}
|
||||
|
||||
final class Coordinator: NSObject, UITextViewDelegate {
|
||||
var parent: SybilReturnSubmittingTextView
|
||||
|
||||
init(parent: SybilReturnSubmittingTextView) {
|
||||
self.parent = parent
|
||||
}
|
||||
|
||||
func textViewDidChange(_ textView: UITextView) {
|
||||
parent.text = textView.text
|
||||
}
|
||||
|
||||
func textViewDidBeginEditing(_ textView: UITextView) {
|
||||
parent.focused = true
|
||||
}
|
||||
|
||||
func textViewDidEndEditing(_ textView: UITextView) {
|
||||
parent.focused = false
|
||||
}
|
||||
|
||||
func textViewDidChangeSelection(_ textView: UITextView) {
|
||||
guard let binding = parent.selection,
|
||||
let range = Range(textView.selectedRange, in: textView.text) else { return }
|
||||
binding.wrappedValue = TextSelection(range: range)
|
||||
}
|
||||
|
||||
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText replacement: String) -> Bool {
|
||||
guard replacement == "\n" else { return true }
|
||||
guard textView.markedTextRange == nil else { return true }
|
||||
parent.submit()
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
struct SybilPromptSendButton: View {
|
||||
var systemImage: String = "arrow.up"
|
||||
var canSend: Bool
|
||||
|
||||
@@ -9,6 +9,7 @@ struct SybilQuickQuestionView: View {
|
||||
@Environment(\.dismiss) private var dismiss
|
||||
@FocusState private var promptFocused: Bool
|
||||
@State private var promptSelection: TextSelection?
|
||||
@State private var autoSelectedFocusRequest: Int?
|
||||
|
||||
private var hasAnswerContent: Bool {
|
||||
!viewModel.quickQuestionMessages.isEmpty || viewModel.quickQuestionError != nil
|
||||
@@ -31,14 +32,45 @@ struct SybilQuickQuestionView: View {
|
||||
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .top)
|
||||
.background(SybilTheme.backgroundGradient)
|
||||
.preferredColorScheme(.dark)
|
||||
.onChange(of: promptFocused) { _, isFocused in
|
||||
guard isFocused else {
|
||||
return
|
||||
}
|
||||
selectInitialPromptIfNeeded(for: focusRequest)
|
||||
}
|
||||
.task(id: focusRequest) {
|
||||
promptFocused = false
|
||||
promptSelection = nil
|
||||
autoSelectedFocusRequest = nil
|
||||
try? await Task.sleep(for: .milliseconds(260))
|
||||
guard !Task.isCancelled else {
|
||||
return
|
||||
}
|
||||
promptFocused = true
|
||||
let prompt = viewModel.quickQuestionPrompt
|
||||
promptSelection = TextSelection(range: prompt.startIndex..<prompt.endIndex)
|
||||
}
|
||||
}
|
||||
|
||||
private func selectInitialPromptIfNeeded(for request: Int) {
|
||||
guard autoSelectedFocusRequest != request else {
|
||||
return
|
||||
}
|
||||
autoSelectedFocusRequest = request
|
||||
|
||||
let initialPrompt = viewModel.quickQuestionPrompt
|
||||
guard !initialPrompt.isEmpty else {
|
||||
return
|
||||
}
|
||||
|
||||
// Let SwiftUI apply focus before publishing the selection update.
|
||||
Task { @MainActor in
|
||||
await Task.yield()
|
||||
guard promptFocused,
|
||||
focusRequest == request,
|
||||
viewModel.quickQuestionPrompt == initialPrompt
|
||||
else {
|
||||
return
|
||||
}
|
||||
promptSelection = TextSelection(range: initialPrompt.startIndex..<initialPrompt.endIndex)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -103,9 +135,11 @@ struct SybilQuickQuestionView: View {
|
||||
),
|
||||
focused: $promptFocused,
|
||||
selection: $promptSelection,
|
||||
axis: .horizontal,
|
||||
axis: .vertical,
|
||||
returnSubmits: true,
|
||||
submit: submitQuestion
|
||||
)
|
||||
.accessibilityIdentifier("quick-question-prompt")
|
||||
|
||||
SybilPromptSendButton(canSend: viewModel.canSendQuickQuestion, submit: submitQuestion)
|
||||
.accessibilityLabel("Ask quick question")
|
||||
@@ -208,6 +242,7 @@ struct SybilQuickQuestionView: View {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private struct QuickQuestionPickerPill: View {
|
||||
var title: String
|
||||
|
||||
|
||||
@@ -12,13 +12,11 @@ final class SybilSettingsStore {
|
||||
static let preferredAnthropicModel = "sybil.ios.preferredAnthropicModel"
|
||||
static let preferredXAIModel = "sybil.ios.preferredXAIModel"
|
||||
static let preferredGeminiModel = "sybil.ios.preferredGeminiModel"
|
||||
static let preferredHermesAgentModel = "sybil.ios.preferredHermesAgentModel"
|
||||
static let quickQuestionPreferredProvider = "sybil.ios.quickQuestionPreferredProvider"
|
||||
static let quickQuestionPreferredOpenAIModel = "sybil.ios.quickQuestionPreferredOpenAIModel"
|
||||
static let quickQuestionPreferredAnthropicModel = "sybil.ios.quickQuestionPreferredAnthropicModel"
|
||||
static let quickQuestionPreferredXAIModel = "sybil.ios.quickQuestionPreferredXAIModel"
|
||||
static let quickQuestionPreferredGeminiModel = "sybil.ios.quickQuestionPreferredGeminiModel"
|
||||
static let quickQuestionPreferredHermesAgentModel = "sybil.ios.quickQuestionPreferredHermesAgentModel"
|
||||
}
|
||||
|
||||
private let defaults: UserDefaults
|
||||
@@ -46,8 +44,7 @@ final class SybilSettingsStore {
|
||||
.openai: defaults.string(forKey: Keys.preferredOpenAIModel) ?? "gpt-4.1-mini",
|
||||
.anthropic: defaults.string(forKey: Keys.preferredAnthropicModel) ?? "claude-3-5-sonnet-latest",
|
||||
.xai: defaults.string(forKey: Keys.preferredXAIModel) ?? "grok-3-mini",
|
||||
.gemini: defaults.string(forKey: Keys.preferredGeminiModel) ?? "gemini-3.5-flash",
|
||||
.hermesAgent: defaults.string(forKey: Keys.preferredHermesAgentModel) ?? "hermes-agent"
|
||||
.gemini: defaults.string(forKey: Keys.preferredGeminiModel) ?? "gemini-3.5-flash"
|
||||
]
|
||||
self.preferredModelByProvider = preferredModels
|
||||
|
||||
@@ -57,8 +54,7 @@ final class SybilSettingsStore {
|
||||
.openai: defaults.string(forKey: Keys.quickQuestionPreferredOpenAIModel) ?? "chat-latest",
|
||||
.anthropic: defaults.string(forKey: Keys.quickQuestionPreferredAnthropicModel) ?? preferredModels[.anthropic] ?? "claude-3-5-sonnet-latest",
|
||||
.xai: defaults.string(forKey: Keys.quickQuestionPreferredXAIModel) ?? preferredModels[.xai] ?? "grok-3-mini",
|
||||
.gemini: defaults.string(forKey: Keys.quickQuestionPreferredGeminiModel) ?? preferredModels[.gemini] ?? "gemini-3.5-flash",
|
||||
.hermesAgent: defaults.string(forKey: Keys.quickQuestionPreferredHermesAgentModel) ?? preferredModels[.hermesAgent] ?? "hermes-agent"
|
||||
.gemini: defaults.string(forKey: Keys.quickQuestionPreferredGeminiModel) ?? preferredModels[.gemini] ?? "gemini-3.5-flash"
|
||||
]
|
||||
}
|
||||
|
||||
@@ -77,14 +73,12 @@ final class SybilSettingsStore {
|
||||
defaults.set(preferredModelByProvider[.anthropic], forKey: Keys.preferredAnthropicModel)
|
||||
defaults.set(preferredModelByProvider[.xai], forKey: Keys.preferredXAIModel)
|
||||
defaults.set(preferredModelByProvider[.gemini], forKey: Keys.preferredGeminiModel)
|
||||
defaults.set(preferredModelByProvider[.hermesAgent], forKey: Keys.preferredHermesAgentModel)
|
||||
|
||||
defaults.set(quickQuestionPreferredProvider.rawValue, forKey: Keys.quickQuestionPreferredProvider)
|
||||
defaults.set(quickQuestionPreferredModelByProvider[.openai], forKey: Keys.quickQuestionPreferredOpenAIModel)
|
||||
defaults.set(quickQuestionPreferredModelByProvider[.anthropic], forKey: Keys.quickQuestionPreferredAnthropicModel)
|
||||
defaults.set(quickQuestionPreferredModelByProvider[.xai], forKey: Keys.quickQuestionPreferredXAIModel)
|
||||
defaults.set(quickQuestionPreferredModelByProvider[.gemini], forKey: Keys.quickQuestionPreferredGeminiModel)
|
||||
defaults.set(quickQuestionPreferredModelByProvider[.hermesAgent], forKey: Keys.quickQuestionPreferredHermesAgentModel)
|
||||
}
|
||||
|
||||
var trimmedTokenOrNil: String? {
|
||||
|
||||
@@ -254,8 +254,7 @@ final class SybilViewModel {
|
||||
.openai: ["gpt-4.1-mini", "chat-latest"],
|
||||
.anthropic: ["claude-3-5-sonnet-latest"],
|
||||
.xai: ["grok-3-mini"],
|
||||
.gemini: ["gemini-3.5-flash", "gemini-flash-latest"],
|
||||
.hermesAgent: ["hermes-agent"]
|
||||
.gemini: ["gemini-3.5-flash", "gemini-flash-latest"]
|
||||
]
|
||||
|
||||
init(
|
||||
@@ -283,9 +282,7 @@ final class SybilViewModel {
|
||||
}
|
||||
|
||||
var providerOptions: [Provider] {
|
||||
Provider.allCases.filter { candidate in
|
||||
candidate != .hermesAgent || modelCatalog[candidate] != nil
|
||||
}
|
||||
Provider.allCases
|
||||
}
|
||||
|
||||
var quickQuestionProviderModelOptions: [String] {
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
import Foundation
|
||||
import Testing
|
||||
@testable import Sybil
|
||||
|
||||
@Suite
|
||||
struct ProviderTests {
|
||||
@Test func selectableProvidersAndCatalogIgnoreRetiredIntegrations() throws {
|
||||
#expect(Provider.allCases.map(\.rawValue) == ["openai", "anthropic", "xai", "gemini"])
|
||||
let data = Data(#"{"providers":{"openai":{"models":["test-model"],"loadedAt":null,"error":null},"retired-provider":{"models":["old-model"],"loadedAt":null,"error":null}}}"#.utf8)
|
||||
let catalog = try JSONDecoder().decode(ModelCatalogResponse.self, from: data)
|
||||
#expect(catalog.providers.count == 1)
|
||||
#expect(catalog.providers[.openai]?.models == ["test-model"])
|
||||
}
|
||||
|
||||
@Test func historicalChatWithUnsupportedProviderStillDecodes() throws {
|
||||
let data = Data(#"{"id":"old-chat","createdAt":0,"updatedAt":0,"initiatedProvider":"retired-provider","initiatedModel":"old-model","lastUsedProvider":"retired-provider","lastUsedModel":"old-model"}"#.utf8)
|
||||
let chat = try JSONDecoder().decode(ChatSummary.self, from: data)
|
||||
#expect(chat.initiatedProvider == nil)
|
||||
#expect(chat.lastUsedProvider == nil)
|
||||
#expect(chat.id == "old-chat")
|
||||
}
|
||||
|
||||
@MainActor @Test func retiredSavedPreferencesUseSupportedDefaults() throws {
|
||||
let suite = "ProviderTests.\(UUID().uuidString)"
|
||||
let defaults = try #require(UserDefaults(suiteName: suite))
|
||||
defer { defaults.removePersistentDomain(forName: suite) }
|
||||
defaults.set("retired-provider", forKey: "sybil.ios.preferredProvider")
|
||||
defaults.set("retired-provider", forKey: "sybil.ios.quickQuestionPreferredProvider")
|
||||
defaults.set("kept-custom-model", forKey: "sybil.ios.preferredOpenAIModel")
|
||||
let settings = SybilSettingsStore(defaults: defaults)
|
||||
#expect(settings.preferredProvider == .openai)
|
||||
#expect(settings.quickQuestionPreferredProvider == .openai)
|
||||
#expect(settings.preferredModelByProvider[.openai] == "kept-custom-model")
|
||||
#expect(settings.preferredModelByProvider.count == 4)
|
||||
settings.persist()
|
||||
#expect(defaults.string(forKey: "sybil.ios.preferredProvider") == "openai")
|
||||
#expect(defaults.string(forKey: "sybil.ios.quickQuestionPreferredProvider") == "openai")
|
||||
}
|
||||
}
|
||||
@@ -32,11 +32,14 @@ struct SybilInlineMentionTests {
|
||||
@Test func streamMetaAcceptsOptionalAgentAsideFlag() throws {
|
||||
let legacyData = Data(#"{"chatId":"chat-1","provider":"openai","model":"test-model"}"#.utf8)
|
||||
let legacy = try JSONDecoder().decode(CompletionStreamMeta.self, from: legacyData)
|
||||
#expect(legacy.provider == "openai")
|
||||
#expect(legacy.agentAside == nil)
|
||||
|
||||
let asideData = Data(#"{"chatId":"chat-1","provider":"openai","model":"test-model","agentAside":true}"#.utf8)
|
||||
let asideData = Data(#"{"chatId":"chat-1","provider":"sybil-agent","model":"sybil-agent","agentAside":true}"#.utf8)
|
||||
let aside = try JSONDecoder().decode(CompletionStreamMeta.self, from: asideData)
|
||||
#expect(aside.agentAside == true)
|
||||
#expect(aside.provider == "sybil-agent")
|
||||
#expect(Provider(rawValue: aside.provider) == nil)
|
||||
}
|
||||
|
||||
@Test func asidePresentationUsesAssistantMetadata() {
|
||||
|
||||
@@ -15,6 +15,7 @@ from aiohttp import web
|
||||
sockets = set()
|
||||
messages = []
|
||||
requests = {}
|
||||
quick_questions = []
|
||||
read_cursor = 0
|
||||
cursor = 0
|
||||
busy = False
|
||||
@@ -108,7 +109,7 @@ async def route(request):
|
||||
for task in reply_tasks:
|
||||
task.cancel()
|
||||
reply_tasks.clear()
|
||||
messages.clear(); requests.clear(); attempts.clear(); cursor = 0; read_cursor = 0; busy = False
|
||||
messages.clear(); requests.clear(); quick_questions.clear(); attempts.clear(); cursor = 0; read_cursor = 0; busy = False
|
||||
attachment_capability = True; next_upload_error = None; blocked_proxy = False; transcript_comparison = False
|
||||
assistant_image_capability = False; fail_image_download = False
|
||||
push_installations.clear(); push_retired.clear(); push_requests.clear(); log.clear()
|
||||
@@ -177,7 +178,7 @@ async def route(request):
|
||||
await socket.close(code=1012)
|
||||
elif action == 'malformed':
|
||||
await broadcast(dict(type='messages', conversationId='fixture-root', messages=[{'id': 'broken'}], cursor='999999', beforeCursor=None, hasMore=False))
|
||||
return web.json_response(dict(cursor=cursor, readCursor=read_cursor, messages=messages, requests=requests, log=log,
|
||||
return web.json_response(dict(cursor=cursor, readCursor=read_cursor, messages=messages, requests=requests, quickQuestions=quick_questions, log=log,
|
||||
pushRequests=push_requests, pushActive=len(push_installations), pushRetired=len(push_retired)))
|
||||
if path == '/api/v1/auth/session':
|
||||
if auth_required and request.headers.get('Authorization') != 'Bearer fixture-token':
|
||||
@@ -295,6 +296,12 @@ async def route(request):
|
||||
if request.method == 'PUT':
|
||||
read_cursor = max(read_cursor, int((await request.json())['cursor']))
|
||||
return web.json_response(dict(cursor=str(read_cursor), updatedAt=stamp(), sourceId=PUSH_SOURCE))
|
||||
if path == '/api/v1/quick-questions/stream' and request.method == 'POST':
|
||||
quick_questions.append(await request.json())
|
||||
return web.Response(
|
||||
text='event: done\ndata: {"text":"Fixture answer"}\n\n',
|
||||
content_type='text/event-stream',
|
||||
)
|
||||
if path == '/api/v1/agent/messages':
|
||||
if request.method == 'POST':
|
||||
body = await request.json()
|
||||
|
||||
@@ -0,0 +1,256 @@
|
||||
import XCTest
|
||||
import UIKit
|
||||
|
||||
/// Uses the repository's 127.0.0.1 contract fixture and the real iOS home-screen shortcut.
|
||||
@MainActor
|
||||
final class QuickQuestionSelectionUITests: XCTestCase {
|
||||
private let app = XCUIApplication()
|
||||
private let springboard = XCUIApplication(bundleIdentifier: "com.apple.springboard")
|
||||
|
||||
override func setUp() async throws {
|
||||
continueAfterFailure = false
|
||||
try await control(["action": "reset", "count": 0])
|
||||
app.launchArguments = [
|
||||
"-sybil.ios.apiBaseURL", "http://127.0.0.1:8799/api",
|
||||
"-sybil.ios.adminToken", "fixture-token"
|
||||
]
|
||||
}
|
||||
|
||||
override func tearDown() async throws {
|
||||
app.terminate()
|
||||
UIPasteboard.general.string = nil
|
||||
}
|
||||
|
||||
func testQuickActionReselectsRetainedDraft() async throws {
|
||||
app.launch()
|
||||
openQuickQuestionFromHomeScreen()
|
||||
|
||||
let prompt = quickQuestionPromptElement()
|
||||
XCTAssertTrue(prompt.waitForExistence(timeout: 10))
|
||||
XCTAssertTrue(app.keyboards.firstMatch.waitForExistence(timeout: 10))
|
||||
XCTAssertLessThan(prompt.frame.height, 80, "An empty Quick Question composer should stay one line tall.")
|
||||
prompt.typeText("retained draft")
|
||||
XCTAssertEqual(prompt.value as? String, "retained draft")
|
||||
|
||||
// The real home-screen action requests a new focusRequest even while
|
||||
// this sheet remains presented. That task refocuses and reselects text.
|
||||
openQuickQuestionFromHomeScreen()
|
||||
|
||||
XCTAssertTrue(prompt.waitForExistence(timeout: 10))
|
||||
XCTAssertTrue(app.keyboards.firstMatch.waitForExistence(timeout: 10))
|
||||
XCTAssertEqual(prompt.value as? String, "retained draft")
|
||||
XCTAssertLessThan(prompt.frame.height, 80, "A one-line draft should keep the normal chat composer height.")
|
||||
|
||||
// The field is already focused with its initial draft selected. Do not tap
|
||||
// it here: typing immediately is the behavior under test.
|
||||
prompt.typeText("replacement")
|
||||
XCTAssertEqual(prompt.value as? String, "replacement")
|
||||
}
|
||||
|
||||
func testQuickQuestionComposerStartsCompactAndGrowsForMultilineText() {
|
||||
app.launch()
|
||||
let agentButton = app.buttons["agent-sidebar"]
|
||||
if !agentButton.waitForExistence(timeout: 2) || !agentButton.isHittable {
|
||||
let showSidebar = app.buttons["Show sidebar"]
|
||||
XCTAssertTrue(showSidebar.waitForExistence(timeout: 15))
|
||||
showSidebar.tap()
|
||||
}
|
||||
XCTAssertTrue(agentButton.waitForExistence(timeout: 5))
|
||||
agentButton.tap()
|
||||
|
||||
let normalField = app.textFields["agent-composer"]
|
||||
let normalView = app.textViews["agent-composer"]
|
||||
XCTAssertTrue(normalField.waitForExistence(timeout: 5) || normalView.waitForExistence(timeout: 5))
|
||||
let normalComposer = normalField.exists ? normalField : normalView
|
||||
let normalHeight = normalComposer.frame.height
|
||||
XCTAssertLessThan(normalHeight, 80, "The normal composer should start at one line.")
|
||||
|
||||
XCUIDevice.shared.press(.home)
|
||||
openQuickQuestionFromHomeScreen()
|
||||
|
||||
let prompt = quickQuestionPromptElement()
|
||||
XCTAssertTrue(prompt.waitForExistence(timeout: 10))
|
||||
XCTAssertTrue(app.keyboards.firstMatch.waitForExistence(timeout: 10))
|
||||
let oneLineHeight = prompt.frame.height
|
||||
XCTAssertLessThan(oneLineHeight, 80, "The Quick Question field must not fill the sheet when empty.")
|
||||
XCTAssertEqual(oneLineHeight, normalHeight, accuracy: 4, "The six-line Return field must keep the normal composer’s compact first line.")
|
||||
captureFrame("quick-question-empty-keyboard-visible", element: prompt)
|
||||
capture("quick-question-empty-keyboard-visible")
|
||||
|
||||
let growingDraft = (1...4).map { "Question line \($0)" }.joined(separator: "\n")
|
||||
UIPasteboard.general.string = growingDraft
|
||||
prompt.press(forDuration: 1.2)
|
||||
let paste = app.descendants(matching: .any)
|
||||
.matching(NSPredicate(format: "label == %@", "Paste"))
|
||||
.firstMatch
|
||||
XCTAssertTrue(paste.waitForExistence(timeout: 5), "The multiline fixture should be available to paste into the real text field.")
|
||||
paste.tap()
|
||||
|
||||
XCTAssertEqual(prompt.value as? String, growingDraft)
|
||||
let multilineHeight = prompt.frame.height
|
||||
captureFrame("quick-question-multiline-growing-keyboard-visible", element: prompt)
|
||||
capture("quick-question-multiline-growing-keyboard-visible")
|
||||
XCTAssertGreaterThan(multilineHeight, oneLineHeight * 2, "The shared vertical field should grow as lines are added.")
|
||||
XCTAssertLessThan(multilineHeight, oneLineHeight * 6 + 16, "The growing field should remain below its six-line cap.")
|
||||
|
||||
let appendedLines = (5...9).map { "\nQuestion line \($0)" }.joined()
|
||||
prompt.typeText(appendedLines)
|
||||
let cappedDraft = growingDraft + appendedLines
|
||||
XCTAssertEqual(prompt.value as? String, cappedDraft)
|
||||
let cappedHeight = prompt.frame.height
|
||||
captureFrame("quick-question-six-line-cap-keyboard-visible", element: prompt)
|
||||
capture("quick-question-six-line-cap-keyboard-visible")
|
||||
XCTAssertGreaterThan(cappedHeight, oneLineHeight * 5, "Nine lines should reach the existing six-line height cap.")
|
||||
XCTAssertLessThan(cappedHeight, oneLineHeight * 6 + 16, "Nine lines should remain inside the existing six-line visual cap.")
|
||||
XCTAssertEqual(
|
||||
prompt.value as? String,
|
||||
cappedDraft,
|
||||
"The capped field must retain all nine lines while its visible editor stays at the six-line cap."
|
||||
)
|
||||
}
|
||||
|
||||
func testQuickQuestionOneLineHeightMatchesNormalChatComposer() {
|
||||
app.launch()
|
||||
let agentButton = app.buttons["agent-sidebar"]
|
||||
if !agentButton.waitForExistence(timeout: 2) || !agentButton.isHittable {
|
||||
let showSidebar = app.buttons["Show sidebar"]
|
||||
XCTAssertTrue(showSidebar.waitForExistence(timeout: 15))
|
||||
showSidebar.tap()
|
||||
}
|
||||
XCTAssertTrue(agentButton.waitForExistence(timeout: 5))
|
||||
agentButton.tap()
|
||||
|
||||
let textField = app.textFields["agent-composer"]
|
||||
let textView = app.textViews["agent-composer"]
|
||||
XCTAssertTrue(textField.waitForExistence(timeout: 5) || textView.waitForExistence(timeout: 5))
|
||||
let normalComposer = textField.exists ? textField : textView
|
||||
let normalHeight = normalComposer.frame.height
|
||||
XCTAssertLessThan(normalHeight, 80, "The normal-chat composer should start at one line.")
|
||||
captureFrame("normal-chat-composer", element: normalComposer)
|
||||
capture("normal-chat-one-line-keyboard-hidden")
|
||||
|
||||
XCUIDevice.shared.press(.home)
|
||||
openQuickQuestionFromHomeScreen()
|
||||
let prompt = quickQuestionPromptElement()
|
||||
XCTAssertTrue(prompt.waitForExistence(timeout: 10))
|
||||
XCTAssertTrue(app.keyboards.firstMatch.waitForExistence(timeout: 10))
|
||||
let quickQuestionHeight = prompt.frame.height
|
||||
captureFrame("quick-question-composer-keyboard-visible", element: prompt)
|
||||
capture("quick-question-one-line-keyboard-visible")
|
||||
XCTAssertLessThan(quickQuestionHeight, 80, "Quick Question should start at one line.")
|
||||
XCTAssertEqual(
|
||||
quickQuestionHeight,
|
||||
normalHeight,
|
||||
accuracy: 4,
|
||||
"Quick Question should use the same one-line field sizing as normal chat."
|
||||
)
|
||||
}
|
||||
|
||||
func testQuickQuestionReturnSubmitsPromptExactlyOnceWithoutNewline() async throws {
|
||||
app.launch()
|
||||
openQuickQuestionFromHomeScreen()
|
||||
|
||||
let prompt = quickQuestionPromptElement()
|
||||
XCTAssertTrue(prompt.waitForExistence(timeout: 10))
|
||||
XCTAssertTrue(app.keyboards.firstMatch.waitForExistence(timeout: 10))
|
||||
prompt.typeText("Return submits once\n")
|
||||
|
||||
XCTAssertTrue(app.staticTexts["Fixture answer"].waitForExistence(timeout: 10))
|
||||
XCTAssertEqual(prompt.value as? String, "Return submits once", "Return must submit without adding a newline.")
|
||||
let state = try await control(["action": "state"])
|
||||
let submitted = try XCTUnwrap(state["quickQuestions"] as? [[String: Any]])
|
||||
XCTAssertEqual(submitted.count, 1, "One Return press must submit exactly one quick question.")
|
||||
XCTAssertEqual(submitted.first?["question"] as? String, "Return submits once")
|
||||
}
|
||||
|
||||
func testQuickQuestionMultilinePasteDoesNotSubmit() async throws {
|
||||
app.launch()
|
||||
openQuickQuestionFromHomeScreen()
|
||||
|
||||
let prompt = quickQuestionPromptElement()
|
||||
XCTAssertTrue(prompt.waitForExistence(timeout: 10))
|
||||
XCTAssertTrue(app.keyboards.firstMatch.waitForExistence(timeout: 10))
|
||||
let pasted = "First line\nSecond line"
|
||||
UIPasteboard.general.string = pasted
|
||||
prompt.press(forDuration: 1.2)
|
||||
let paste = app.descendants(matching: .any)
|
||||
.matching(NSPredicate(format: "label == %@", "Paste"))
|
||||
.firstMatch
|
||||
XCTAssertTrue(paste.waitForExistence(timeout: 5))
|
||||
paste.tap()
|
||||
|
||||
XCTAssertEqual(prompt.value as? String, pasted)
|
||||
let state = try await control(["action": "state"])
|
||||
let submitted = try XCTUnwrap(state["quickQuestions"] as? [[String: Any]])
|
||||
XCTAssertTrue(submitted.isEmpty, "Pasting multiline text must not submit the question.")
|
||||
}
|
||||
|
||||
func testSharedNormalComposerReturnInsertsNewline() async throws {
|
||||
app.launch()
|
||||
let textField = app.textFields["Enter Prompt"]
|
||||
let textView = app.textViews["Enter Prompt"]
|
||||
XCTAssertTrue(textField.waitForExistence(timeout: 5) || textView.waitForExistence(timeout: 5))
|
||||
let composer = textField.exists ? textField : textView
|
||||
composer.tap()
|
||||
composer.typeText("Normal chat keeps newline\n")
|
||||
|
||||
XCTAssertTrue((composer.value as? String)?.contains("\n") == true)
|
||||
let state = try await control(["action": "state"])
|
||||
let log = try XCTUnwrap(state["log"] as? [[String: Any]])
|
||||
XCTAssertFalse(
|
||||
log.contains { $0["method"] as? String == "POST" && ($0["path"] as? String)?.hasSuffix("/chat-completions/stream") == true },
|
||||
"Plain Return in normal chat must insert a newline without submitting."
|
||||
)
|
||||
}
|
||||
|
||||
private func quickQuestionPromptElement() -> XCUIElement {
|
||||
let textField = app.textFields["quick-question-prompt"]
|
||||
return textField.exists ? textField : app.textViews["quick-question-prompt"]
|
||||
}
|
||||
|
||||
private func openQuickQuestionFromHomeScreen() {
|
||||
XCUIDevice.shared.press(.home)
|
||||
let sybilIcon = springboard.icons.matching(identifier: "Sybil").firstMatch
|
||||
XCTAssertTrue(sybilIcon.waitForExistence(timeout: 10))
|
||||
let homeScreen = springboard.otherElements["Home screen icons"]
|
||||
XCTAssertTrue(homeScreen.waitForExistence(timeout: 5))
|
||||
for _ in 0..<2 {
|
||||
guard !sybilIcon.isHittable else {
|
||||
break
|
||||
}
|
||||
homeScreen.swipeLeft()
|
||||
}
|
||||
XCTAssertTrue(sybilIcon.isHittable, "Navigate to the home-screen page containing Sybil before opening its quick action.")
|
||||
sybilIcon.press(forDuration: 1.2)
|
||||
|
||||
let quickQuestion = springboard.buttons["Quick question"]
|
||||
XCTAssertTrue(quickQuestion.waitForExistence(timeout: 5))
|
||||
quickQuestion.tap()
|
||||
}
|
||||
|
||||
private func capture(_ name: String) {
|
||||
let attachment = XCTAttachment(screenshot: app.screenshot())
|
||||
attachment.name = name
|
||||
attachment.lifetime = .keepAlways
|
||||
add(attachment)
|
||||
}
|
||||
|
||||
private func captureFrame(_ name: String, element: XCUIElement) {
|
||||
let frame = element.frame
|
||||
let attachment = XCTAttachment(string: "x=\(frame.origin.x), y=\(frame.origin.y), width=\(frame.width), height=\(frame.height)")
|
||||
attachment.name = "frame-\(name)"
|
||||
attachment.lifetime = .keepAlways
|
||||
add(attachment)
|
||||
}
|
||||
|
||||
@discardableResult
|
||||
private func control(_ body: [String: Any]) async throws -> [String: Any] {
|
||||
var request = URLRequest(url: URL(string: "http://127.0.0.1:8799/control")!)
|
||||
request.httpMethod = "POST"
|
||||
request.httpBody = try JSONSerialization.data(withJSONObject: body)
|
||||
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
|
||||
let (data, response) = try await URLSession.shared.data(for: request)
|
||||
XCTAssertEqual((response as? HTTPURLResponse)?.statusCode, 200)
|
||||
return try XCTUnwrap(JSONSerialization.jsonObject(with: data) as? [String: Any])
|
||||
}
|
||||
}
|
||||
+5
-4
@@ -1,7 +1,7 @@
|
||||
# Sybil Server
|
||||
|
||||
Backend API for:
|
||||
- LLM multiplexer (OpenAI Responses / Anthropic / xAI Chat Completions-compatible Grok / Gemini / Hermes Agent)
|
||||
- LLM multiplexer (OpenAI Responses / Anthropic / xAI Chat Completions-compatible Grok / Gemini)
|
||||
- Personal chat database (chats/messages + LLM call log)
|
||||
|
||||
## Stack
|
||||
@@ -18,6 +18,10 @@ npm run dev
|
||||
|
||||
Migrations are applied automatically on server startup (`prisma migrate deploy`).
|
||||
|
||||
Historical provider IDs are stored as strings so retiring an integration does not make saved chats or call logs unreadable. The API validates new requests against the supported provider list and returns `null` for unsupported saved provider selections. These columns remain SQLite `TEXT`; no data rewrite is required.
|
||||
|
||||
Inline Sybil Agent completions identify their response provider as `sybil-agent`. Release native clients that accept this response identity before deploying the server change; older clients that decode completion metadata with the selectable-provider enum cannot decode it. See the [streaming contract](../docs/api/streaming-chat.md).
|
||||
|
||||
Open docs: `http://localhost:8787/docs`
|
||||
|
||||
API contract docs for clients:
|
||||
@@ -44,9 +48,6 @@ If `ADMIN_TOKEN` is not set, the server runs in open mode (dev).
|
||||
- `ANTHROPIC_API_KEY`
|
||||
- `XAI_API_KEY`
|
||||
- `GEMINI_API_KEY`
|
||||
- `HERMES_AGENT_API_BASE_URL` (`http://127.0.0.1:8642/v1` by default; include the `/v1` suffix)
|
||||
- `HERMES_AGENT_API_KEY` (enables the Hermes Agent provider; set to Hermes `API_SERVER_KEY`, or any non-empty value if that local server does not require auth)
|
||||
- `HERMES_AGENT_MODEL` (optional fallback/override model id; defaults client-side to `hermes-agent`)
|
||||
- `EXA_API_KEY`
|
||||
- `BRAVE_SEARCH_API_KEY` (required when `CHAT_WEB_SEARCH_ENGINE=brave`)
|
||||
- `CHAT_WEB_SEARCH_ENGINE` (`exa` by default; `brave` and `searxng` are also supported for chat tool calls only)
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
ALTER TABLE "Chat" ADD COLUMN "reasoningEffort" TEXT;
|
||||
@@ -9,14 +9,6 @@ datasource db {
|
||||
url = env("DATABASE_URL")
|
||||
}
|
||||
|
||||
enum Provider {
|
||||
openai
|
||||
anthropic
|
||||
xai
|
||||
gemini
|
||||
hermes_agent @map("hermes-agent")
|
||||
}
|
||||
|
||||
enum MessageRole {
|
||||
system
|
||||
user
|
||||
@@ -54,10 +46,13 @@ model Chat {
|
||||
title String?
|
||||
titleGenerationPending Boolean @default(false)
|
||||
|
||||
initiatedProvider Provider?
|
||||
// Historical provider IDs remain readable after an integration is retired.
|
||||
// Accepted request IDs are validated by the API, not a storage enum.
|
||||
initiatedProvider String?
|
||||
initiatedModel String?
|
||||
lastUsedProvider Provider?
|
||||
lastUsedProvider String?
|
||||
lastUsedModel String?
|
||||
reasoningEffort String?
|
||||
|
||||
additionalSystemPrompt String?
|
||||
enabledTools Json?
|
||||
@@ -103,7 +98,7 @@ model LlmCall {
|
||||
chat Chat @relation(fields: [chatId], references: [id], onDelete: Cascade)
|
||||
chatId String
|
||||
|
||||
provider Provider
|
||||
provider String
|
||||
model String
|
||||
|
||||
// request/response snapshots for debugging + replay
|
||||
|
||||
@@ -9,6 +9,8 @@ const clientDir = join(rootDir, "node_modules", ".prisma", "client");
|
||||
const clientIndex = join(clientDir, "index.js");
|
||||
const prismaJs = join(rootDir, "node_modules", "prisma", "build", "index.js");
|
||||
const genericEngine = join(clientDir, "libquery_engine.node");
|
||||
const schemaFile = join(rootDir, "prisma", "schema.prisma");
|
||||
const generatedSchemaFile = join(clientDir, "schema.prisma");
|
||||
|
||||
function parseExpectedEngineFiles() {
|
||||
if (!existsSync(clientIndex)) return [];
|
||||
@@ -39,7 +41,8 @@ function runPrismaGenerate() {
|
||||
let expectedFiles = parseExpectedEngineFiles();
|
||||
let missingFiles = missingEngineFiles(expectedFiles);
|
||||
|
||||
if (!expectedFiles.length || missingFiles.length) {
|
||||
const schemaChanged = !existsSync(generatedSchemaFile) || readFileSync(schemaFile, "utf8") !== readFileSync(generatedSchemaFile, "utf8");
|
||||
if (schemaChanged || !expectedFiles.length || missingFiles.length) {
|
||||
runPrismaGenerate();
|
||||
expectedFiles = parseExpectedEngineFiles();
|
||||
missingFiles = missingEngineFiles(expectedFiles);
|
||||
|
||||
@@ -11,13 +11,6 @@ const OptionalUrlSchema = z.preprocess(
|
||||
z.string().trim().url().optional()
|
||||
);
|
||||
|
||||
const DEFAULT_HERMES_AGENT_API_BASE_URL = "http://127.0.0.1:8642/v1";
|
||||
|
||||
const HermesAgentApiBaseUrlSchema = z.preprocess(
|
||||
(value) => (typeof value === "string" && value.trim() === "" ? undefined : value),
|
||||
z.string().trim().url().default(DEFAULT_HERMES_AGENT_API_BASE_URL)
|
||||
);
|
||||
|
||||
const ChatWebSearchEngineSchema = z.preprocess(
|
||||
(value) => {
|
||||
if (typeof value !== "string") return value;
|
||||
@@ -67,9 +60,6 @@ const EnvSchema = z.object({
|
||||
ANTHROPIC_API_KEY: z.string().optional(),
|
||||
XAI_API_KEY: z.string().optional(),
|
||||
GEMINI_API_KEY: z.string().optional(),
|
||||
HERMES_AGENT_API_BASE_URL: HermesAgentApiBaseUrlSchema,
|
||||
HERMES_AGENT_API_KEY: OptionalTrimmedStringSchema,
|
||||
HERMES_AGENT_MODEL: OptionalTrimmedStringSchema,
|
||||
SYBIL_AGENT_BASE_URL: z.string().url().default("http://sybil-agent:8788"),
|
||||
SYBIL_AGENT_API_KEY: OptionalTrimmedStringSchema,
|
||||
// Off until a deliberate server opt-in plus per-installation user consent.
|
||||
|
||||
@@ -12,7 +12,8 @@ import { searchBrave } from "../search/brave.js";
|
||||
import { exaClient } from "../search/exa.js";
|
||||
import { searchSearxng } from "../search/searxng.js";
|
||||
import { extractPdfText, hasPdfMagic, MAX_PDF_PAGES_PER_FETCH } from "./pdf-text.js";
|
||||
import type { ChatMessage } from "./types.js";
|
||||
import type { ChatMessage, Provider } from "./types.js";
|
||||
import type { ReasoningEffort } from "./reasoning-effort.js";
|
||||
|
||||
export const MAX_TOOL_ROUNDS = env.CHAT_MAX_TOOL_ROUNDS;
|
||||
const DEFAULT_WEB_RESULTS = 5;
|
||||
@@ -270,12 +271,14 @@ export type ToolAwareStreamingEvent =
|
||||
|
||||
export type ToolAwareCompletionParams = {
|
||||
client: any;
|
||||
provider?: Provider;
|
||||
model: string;
|
||||
messages: ChatMessage[];
|
||||
enabledTools?: string[];
|
||||
userLocation?: string;
|
||||
temperature?: number;
|
||||
maxTokens?: number;
|
||||
reasoningEffort?: ReasoningEffort | null;
|
||||
onToolEvent?: (event: ToolExecutionEvent) => void | Promise<void>;
|
||||
logContext?: {
|
||||
provider: string;
|
||||
|
||||
@@ -1,15 +1,16 @@
|
||||
import type { FastifyBaseLogger } from "fastify";
|
||||
import {
|
||||
fetchProviderCatalogModels,
|
||||
getProviderCatalogFallbackModels,
|
||||
listModelCatalogProviders,
|
||||
} from "./provider-adapters.js";
|
||||
import type { Provider } from "./types.js";
|
||||
import { getReasoningCatalog, type ReasoningCapabilities } from "./reasoning-effort.js";
|
||||
|
||||
export type ProviderModelSnapshot = {
|
||||
models: string[];
|
||||
loadedAt: string | null;
|
||||
error: string | null;
|
||||
reasoningCapabilities?: Record<string, ReasoningCapabilities>;
|
||||
};
|
||||
|
||||
export type ModelCatalogSnapshot = Partial<Record<Provider, ProviderModelSnapshot>>;
|
||||
@@ -49,9 +50,8 @@ async function refreshProviderModels(provider: Provider, logger?: FastifyBaseLog
|
||||
} catch (err: any) {
|
||||
const message = err?.message ?? String(err);
|
||||
const previous = modelCatalog[provider];
|
||||
const fallbackModels = getProviderCatalogFallbackModels(provider);
|
||||
modelCatalog[provider] = {
|
||||
models: previous?.models.length ? previous.models : fallbackModels,
|
||||
models: previous?.models ?? [],
|
||||
loadedAt: previous?.loadedAt ?? null,
|
||||
error: message,
|
||||
};
|
||||
@@ -94,6 +94,7 @@ export function getModelCatalogSnapshot(): ModelCatalogSnapshot {
|
||||
models: [...entry.models],
|
||||
loadedAt: entry.loadedAt,
|
||||
error: entry.error,
|
||||
reasoningCapabilities: getReasoningCatalog(provider),
|
||||
};
|
||||
}
|
||||
return snapshot;
|
||||
|
||||
@@ -2,14 +2,11 @@ import { performance } from "node:perf_hooks";
|
||||
import { prisma } from "../db.js";
|
||||
import { buildToolLogMessageData } from "./chat-tools.js";
|
||||
import { getProviderChatAdapter } from "./provider-adapters.js";
|
||||
import { toPrismaProvider } from "./provider-ids.js";
|
||||
import type { MultiplexRequest, MultiplexResponse, Provider } from "./types.js";
|
||||
|
||||
function asProviderEnum(p: Provider) {
|
||||
return toPrismaProvider(p);
|
||||
}
|
||||
import type { MultiplexRequest, MultiplexResponse } from "./types.js";
|
||||
import { normalizeReasoningEffort } from "./reasoning-effort.js";
|
||||
|
||||
export async function runMultiplex(req: MultiplexRequest): Promise<MultiplexResponse> {
|
||||
req = { ...req, reasoningEffort: normalizeReasoningEffort(req.provider, req.model, req.reasoningEffort) };
|
||||
const t0 = performance.now();
|
||||
const chatId = req.chatId ?? (await prisma.chat.create({ data: {}, select: { id: true } })).id;
|
||||
|
||||
@@ -17,7 +14,7 @@ export async function runMultiplex(req: MultiplexRequest): Promise<MultiplexResp
|
||||
const call = await prisma.llmCall.create({
|
||||
data: {
|
||||
chatId,
|
||||
provider: asProviderEnum(req.provider) as any,
|
||||
provider: req.provider,
|
||||
model: req.model,
|
||||
request: req as any,
|
||||
},
|
||||
@@ -28,14 +25,15 @@ export async function runMultiplex(req: MultiplexRequest): Promise<MultiplexResp
|
||||
prisma.chat.update({
|
||||
where: { id: chatId },
|
||||
data: {
|
||||
lastUsedProvider: asProviderEnum(req.provider) as any,
|
||||
lastUsedProvider: req.provider,
|
||||
lastUsedModel: req.model,
|
||||
reasoningEffort: req.reasoningEffort,
|
||||
},
|
||||
}),
|
||||
prisma.chat.updateMany({
|
||||
where: { id: chatId, initiatedProvider: null },
|
||||
data: {
|
||||
initiatedProvider: asProviderEnum(req.provider) as any,
|
||||
initiatedProvider: req.provider,
|
||||
initiatedModel: req.model,
|
||||
},
|
||||
}),
|
||||
@@ -54,6 +52,7 @@ export async function runMultiplex(req: MultiplexRequest): Promise<MultiplexResp
|
||||
userLocation: req.userLocation,
|
||||
temperature: req.temperature,
|
||||
maxTokens: req.maxTokens,
|
||||
reasoningEffort: req.reasoningEffort,
|
||||
logContext: {
|
||||
provider: req.provider,
|
||||
model: req.model,
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { getReasoningCapabilities, reasoningRequestOptions } from "../reasoning-effort.js";
|
||||
import {
|
||||
appendDanglingToolIntentCorrection,
|
||||
buildChatToolSystemPrompt,
|
||||
@@ -114,7 +115,8 @@ export async function completeWithChatCompletionsApi(params: ToolAwareCompletion
|
||||
model: params.model,
|
||||
messages: normalizePlainMessages(params.messages, params.userLocation),
|
||||
temperature: params.temperature,
|
||||
max_tokens: params.maxTokens,
|
||||
...(getReasoningCapabilities(params.provider, params.model) ? { max_completion_tokens: params.maxTokens } : { max_tokens: params.maxTokens }),
|
||||
...reasoningRequestOptions(params, "chat-completions"),
|
||||
} as any);
|
||||
|
||||
const usageAcc: Required<NonNullable<ToolAwareCompletionResult["usage"]>> = { inputTokens: 0, outputTokens: 0, totalTokens: 0 };
|
||||
@@ -142,7 +144,8 @@ export async function completeWithChatCompletionsApi(params: ToolAwareCompletion
|
||||
model: params.model,
|
||||
messages: conversation,
|
||||
temperature: params.temperature,
|
||||
max_tokens: params.maxTokens,
|
||||
...(getReasoningCapabilities(params.provider, params.model) ? { max_completion_tokens: params.maxTokens } : { max_tokens: params.maxTokens }),
|
||||
...reasoningRequestOptions(params, "chat-completions"),
|
||||
tools: enabledTools,
|
||||
tool_choice: "auto",
|
||||
} as any);
|
||||
@@ -227,7 +230,8 @@ export async function* streamWithChatCompletionsApi(params: ToolAwareCompletionP
|
||||
model: params.model,
|
||||
messages: normalizePlainMessages(params.messages, params.userLocation),
|
||||
temperature: params.temperature,
|
||||
max_tokens: params.maxTokens,
|
||||
...(getReasoningCapabilities(params.provider, params.model) ? { max_completion_tokens: params.maxTokens } : { max_tokens: params.maxTokens }),
|
||||
...reasoningRequestOptions(params, "chat-completions"),
|
||||
stream: true,
|
||||
} as any);
|
||||
|
||||
@@ -267,7 +271,8 @@ export async function* streamWithChatCompletionsApi(params: ToolAwareCompletionP
|
||||
model: params.model,
|
||||
messages: conversation,
|
||||
temperature: params.temperature,
|
||||
max_tokens: params.maxTokens,
|
||||
...(getReasoningCapabilities(params.provider, params.model) ? { max_completion_tokens: params.maxTokens } : { max_tokens: params.maxTokens }),
|
||||
...reasoningRequestOptions(params, "chat-completions"),
|
||||
tools: enabledTools,
|
||||
tool_choice: "auto",
|
||||
stream: true,
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { reasoningRequestOptions } from "../reasoning-effort.js";
|
||||
import {
|
||||
appendDanglingToolIntentCorrection,
|
||||
buildChatToolSystemPrompt,
|
||||
@@ -155,6 +156,7 @@ export async function completeWithResponsesApi(params: ToolAwareCompletionParams
|
||||
input,
|
||||
temperature: params.temperature,
|
||||
max_output_tokens: params.maxTokens,
|
||||
...reasoningRequestOptions(params, "responses"),
|
||||
tools: toResponsesTools(enabledTools),
|
||||
tool_choice: "auto",
|
||||
parallel_tool_calls: true,
|
||||
@@ -225,6 +227,7 @@ export async function* streamWithResponsesApi(params: ToolAwareCompletionParams)
|
||||
input,
|
||||
temperature: params.temperature,
|
||||
max_output_tokens: params.maxTokens,
|
||||
...reasoningRequestOptions(params, "responses"),
|
||||
tools: toResponsesTools(enabledTools),
|
||||
tool_choice: "auto",
|
||||
parallel_tool_calls: true,
|
||||
|
||||
@@ -8,9 +8,9 @@ import { completeWithChatCompletionsApi, streamWithChatCompletionsApi } from "./
|
||||
import { completeWithGeminiApi, streamWithGeminiApi } from "./protocols/gemini-api.js";
|
||||
import { completeWithMessagesApi, streamWithMessagesApi } from "./protocols/messages-api.js";
|
||||
import { completeWithResponsesApi, streamWithResponsesApi } from "./protocols/responses-api.js";
|
||||
import { env } from "../env.js";
|
||||
import { anthropicClient, geminiClient, hermesAgentClient, isHermesAgentConfigured, openaiClient, xaiClient } from "./providers.js";
|
||||
import { anthropicClient, geminiClient, openaiClient, xaiClient } from "./providers.js";
|
||||
import type { ChatMessage, Provider } from "./types.js";
|
||||
import { normalizeReasoningEffort, type ReasoningEffort } from "./reasoning-effort.js";
|
||||
|
||||
type ProviderAdapterParams = {
|
||||
model: string;
|
||||
@@ -19,6 +19,7 @@ type ProviderAdapterParams = {
|
||||
userLocation?: string;
|
||||
temperature?: number;
|
||||
maxTokens?: number;
|
||||
reasoningEffort?: ReasoningEffort | null;
|
||||
logContext?: ToolAwareCompletionParams["logContext"];
|
||||
};
|
||||
|
||||
@@ -37,9 +38,7 @@ type ChatProtocol = {
|
||||
};
|
||||
|
||||
type ModelCatalogSpec = {
|
||||
enabled?: () => boolean;
|
||||
fetchModels(client: any): Promise<string[]>;
|
||||
fallbackModels?: () => string[];
|
||||
sortModels?: (models: string[]) => string[];
|
||||
};
|
||||
|
||||
@@ -48,7 +47,7 @@ type ProviderBackendSpec = {
|
||||
plainProtocol: ChatProtocol;
|
||||
toolProtocol?: ChatProtocol;
|
||||
managedTools?: boolean;
|
||||
modelCatalog?: ModelCatalogSpec;
|
||||
modelCatalog: ModelCatalogSpec;
|
||||
};
|
||||
|
||||
const chatCompletionsProtocol: ChatProtocol = {
|
||||
@@ -129,15 +128,19 @@ async function fetchJson(url: URL): Promise<any> {
|
||||
return body;
|
||||
}
|
||||
|
||||
function withClient(params: ProviderAdapterParams, client: any, enabledTools?: string[]): ToolAwareCompletionParams {
|
||||
function withClient(params: ProviderAdapterParams, provider: Provider, client: any, enabledTools?: string[]): ToolAwareCompletionParams {
|
||||
const reasoningEffort = normalizeReasoningEffort(provider, params.model, params.reasoningEffort);
|
||||
return {
|
||||
client,
|
||||
provider,
|
||||
model: params.model,
|
||||
messages: params.messages,
|
||||
enabledTools,
|
||||
userLocation: params.userLocation,
|
||||
temperature: params.temperature,
|
||||
// OpenAI reasoning efforts other than none do not accept temperature.
|
||||
temperature: reasoningEffort && reasoningEffort !== "none" ? undefined : params.temperature,
|
||||
maxTokens: params.maxTokens,
|
||||
reasoningEffort,
|
||||
logContext: params.logContext,
|
||||
};
|
||||
}
|
||||
@@ -157,11 +160,11 @@ function createProviderChatAdapter(provider: Provider, spec: ProviderBackendSpec
|
||||
provider,
|
||||
complete(params) {
|
||||
const selected = selectChatProtocol(spec, params);
|
||||
return selected.protocol.complete(withClient(params, spec.createClient(), selected.enabledTools));
|
||||
return selected.protocol.complete(withClient(params, provider, spec.createClient(), selected.enabledTools));
|
||||
},
|
||||
stream(params) {
|
||||
const selected = selectChatProtocol(spec, params);
|
||||
return selected.protocol.stream(withClient(params, spec.createClient(), selected.enabledTools));
|
||||
return selected.protocol.stream(withClient(params, provider, spec.createClient(), selected.enabledTools));
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -226,23 +229,6 @@ const backendSpecs: Record<Provider, ProviderBackendSpec> = {
|
||||
sortModels: preferGeminiModels,
|
||||
},
|
||||
},
|
||||
"hermes-agent": {
|
||||
createClient: hermesAgentClient,
|
||||
plainProtocol: chatCompletionsProtocol,
|
||||
managedTools: false,
|
||||
modelCatalog: {
|
||||
enabled: isHermesAgentConfigured,
|
||||
async fetchModels(client) {
|
||||
const page = await client.models.list();
|
||||
const models = modelIdsFromListResponse(page);
|
||||
if (env.HERMES_AGENT_MODEL) models.push(env.HERMES_AGENT_MODEL);
|
||||
return models;
|
||||
},
|
||||
fallbackModels() {
|
||||
return env.HERMES_AGENT_MODEL ? [env.HERMES_AGENT_MODEL] : [];
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
const providerChatAdapters: Record<Provider, ProviderChatAdapter> = Object.fromEntries(
|
||||
@@ -264,21 +250,11 @@ export function describeProviderChatBackend(provider: Provider, enabledTools?: s
|
||||
}
|
||||
|
||||
export function listModelCatalogProviders(): Provider[] {
|
||||
return (Object.entries(backendSpecs) as [Provider, ProviderBackendSpec][])
|
||||
.filter(([, spec]) => {
|
||||
const catalog = spec.modelCatalog;
|
||||
return catalog !== undefined && catalog.enabled?.() !== false;
|
||||
})
|
||||
.map(([provider]) => provider);
|
||||
return Object.keys(backendSpecs) as Provider[];
|
||||
}
|
||||
|
||||
export async function fetchProviderCatalogModels(provider: Provider) {
|
||||
const spec = backendSpecs[provider].modelCatalog;
|
||||
if (!spec) return [];
|
||||
const models = uniqSorted(await spec.fetchModels(backendSpecs[provider].createClient()));
|
||||
return spec.sortModels ? spec.sortModels(models) : models;
|
||||
}
|
||||
|
||||
export function getProviderCatalogFallbackModels(provider: Provider) {
|
||||
return uniqSorted(backendSpecs[provider].modelCatalog?.fallbackModels?.() ?? []);
|
||||
}
|
||||
|
||||
@@ -1,43 +1,21 @@
|
||||
import type { Provider } from "./types.js";
|
||||
import { PROVIDERS, type Provider } from "./types.js";
|
||||
|
||||
type PrismaProvider = Exclude<Provider, "hermes-agent"> | "hermes_agent";
|
||||
|
||||
const apiToPrismaProvider = {
|
||||
openai: "openai",
|
||||
anthropic: "anthropic",
|
||||
xai: "xai",
|
||||
gemini: "gemini",
|
||||
"hermes-agent": "hermes_agent",
|
||||
} as const satisfies Record<Provider, PrismaProvider>;
|
||||
|
||||
const prismaToApiProvider = {
|
||||
openai: "openai",
|
||||
anthropic: "anthropic",
|
||||
xai: "xai",
|
||||
gemini: "gemini",
|
||||
hermes_agent: "hermes-agent",
|
||||
"hermes-agent": "hermes-agent",
|
||||
} as const satisfies Record<PrismaProvider | "hermes-agent", Provider>;
|
||||
|
||||
export function toPrismaProvider(provider: Provider): PrismaProvider {
|
||||
return apiToPrismaProvider[provider];
|
||||
}
|
||||
|
||||
export function fromPrismaProvider(provider: unknown): Provider | null {
|
||||
if (provider === null || provider === undefined) return null;
|
||||
return prismaToApiProvider[provider as keyof typeof prismaToApiProvider] ?? null;
|
||||
export function parseProvider(provider: unknown): Provider | null {
|
||||
return typeof provider === "string" && PROVIDERS.includes(provider as Provider) ? provider as Provider : null;
|
||||
}
|
||||
|
||||
export function serializeProviderFields<T extends Record<string, any>>(value: T): T {
|
||||
const next: Record<string, any> = { ...value };
|
||||
if ("initiatedProvider" in next) {
|
||||
next.initiatedProvider = fromPrismaProvider(next.initiatedProvider);
|
||||
next.initiatedProvider = parseProvider(next.initiatedProvider);
|
||||
if (!next.initiatedProvider && "initiatedModel" in next) next.initiatedModel = null;
|
||||
}
|
||||
if ("lastUsedProvider" in next) {
|
||||
next.lastUsedProvider = fromPrismaProvider(next.lastUsedProvider);
|
||||
next.lastUsedProvider = parseProvider(next.lastUsedProvider);
|
||||
if (!next.lastUsedProvider && "lastUsedModel" in next) next.lastUsedModel = null;
|
||||
}
|
||||
if ("provider" in next) {
|
||||
next.provider = fromPrismaProvider(next.provider);
|
||||
next.provider = parseProvider(next.provider);
|
||||
}
|
||||
if (Array.isArray(next.calls)) {
|
||||
next.calls = next.calls.map((call: Record<string, any>) => serializeProviderFields(call));
|
||||
|
||||
@@ -21,18 +21,6 @@ export function geminiClient() {
|
||||
};
|
||||
}
|
||||
|
||||
export function isHermesAgentConfigured() {
|
||||
return Boolean(env.HERMES_AGENT_API_KEY);
|
||||
}
|
||||
|
||||
export function hermesAgentClient() {
|
||||
if (!env.HERMES_AGENT_API_KEY) throw new Error("HERMES_AGENT_API_KEY not set");
|
||||
return new OpenAI({
|
||||
apiKey: env.HERMES_AGENT_API_KEY,
|
||||
baseURL: env.HERMES_AGENT_API_BASE_URL,
|
||||
});
|
||||
}
|
||||
|
||||
export function anthropicClient() {
|
||||
if (!env.ANTHROPIC_API_KEY) throw new Error("ANTHROPIC_API_KEY not set");
|
||||
return new Anthropic({ apiKey: env.ANTHROPIC_API_KEY });
|
||||
|
||||
@@ -13,6 +13,7 @@ export type QuickQuestionRequest = {
|
||||
userLocation?: string;
|
||||
temperature?: number;
|
||||
maxTokens?: number;
|
||||
reasoningEffort?: MultiplexRequest["reasoningEffort"];
|
||||
};
|
||||
|
||||
export function buildQuickQuestionMultiplexRequest({
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
export const REASONING_EFFORTS = ["none", "minimal", "low", "medium", "high", "xhigh", "max"] as const;
|
||||
export type ReasoningEffort = (typeof REASONING_EFFORTS)[number];
|
||||
export type ReasoningCapabilities = {
|
||||
efforts: ReasoningEffort[];
|
||||
defaultEffort: ReasoningEffort | null;
|
||||
};
|
||||
|
||||
// Verified against official model pages on 2026-11-15:
|
||||
// https://developers.openai.com/api/docs/models/{model}
|
||||
// https://developers.openai.com/api/docs/guides/deployment-checklist#set-up-reasoningeffort
|
||||
// Use exact documented aliases/snapshots. Do not infer support from a prefix:
|
||||
// chat-latest, pro/codex variants, fine-tunes, and future snapshots can differ.
|
||||
const modelGroups: { models: string[]; capabilities: ReasoningCapabilities }[] = [
|
||||
{
|
||||
models: ["gpt-5", "gpt-5-2025-08-07"],
|
||||
capabilities: { efforts: ["minimal", "low", "medium", "high"], defaultEffort: "medium" },
|
||||
},
|
||||
{
|
||||
models: ["gpt-5.1", "gpt-5.1-2025-11-13"],
|
||||
capabilities: { efforts: ["none", "low", "medium", "high"], defaultEffort: "none" },
|
||||
},
|
||||
{
|
||||
models: ["gpt-5.2", "gpt-5.2-2025-12-11", "gpt-5.4", "gpt-5.4-2026-03-05",
|
||||
"gpt-5.4-mini", "gpt-5.4-mini-2026-03-17", "gpt-5.4-nano", "gpt-5.4-nano-2026-03-17"],
|
||||
capabilities: { efforts: ["none", "low", "medium", "high", "xhigh"], defaultEffort: "none" },
|
||||
},
|
||||
{
|
||||
models: ["gpt-5.5", "gpt-5.5-2026-04-23"],
|
||||
capabilities: { efforts: ["none", "low", "medium", "high", "xhigh"], defaultEffort: "medium" },
|
||||
},
|
||||
{
|
||||
models: ["gpt-5.6", "gpt-5.6-sol", "gpt-6-sol", "gpt-6-luna"],
|
||||
capabilities: { efforts: ["none", "low", "medium", "high", "xhigh", "max"], defaultEffort: "medium" },
|
||||
},
|
||||
{
|
||||
models: ["gpt-6.1-sol"],
|
||||
capabilities: { efforts: ["low", "medium", "high", "xhigh", "max"], defaultEffort: "medium" },
|
||||
},
|
||||
{
|
||||
models: ["gpt-6-astra"],
|
||||
capabilities: { efforts: ["low", "medium", "high", "xhigh", "max"], defaultEffort: null },
|
||||
},
|
||||
];
|
||||
|
||||
const openAIModels = new Map(modelGroups.flatMap(({ models, capabilities }) => models.map((model) => [model, capabilities] as const)));
|
||||
|
||||
export function getReasoningCapabilities(provider: string | null | undefined, model: string | null | undefined) {
|
||||
return provider === "openai" && model ? openAIModels.get(model) ?? null : null;
|
||||
}
|
||||
|
||||
export function getReasoningCatalog(provider: string): Record<string, ReasoningCapabilities> {
|
||||
if (provider !== "openai") return {};
|
||||
return Object.fromEntries([...openAIModels].map(([model, value]) => [model, { ...value, efforts: [...value.efforts] }]));
|
||||
}
|
||||
|
||||
export function normalizeReasoningEffort(provider: string | null | undefined, model: string | null | undefined, effort: unknown): ReasoningEffort | null {
|
||||
const capabilities = getReasoningCapabilities(provider, model);
|
||||
return capabilities?.efforts.includes(effort as ReasoningEffort) ? effort as ReasoningEffort : null;
|
||||
}
|
||||
|
||||
export function reasoningRequestOptions(params: { provider?: string; model: string; reasoningEffort?: ReasoningEffort | null }, protocol: "responses" | "chat-completions") {
|
||||
const effort = normalizeReasoningEffort(params.provider, params.model, params.reasoningEffort);
|
||||
if (!effort) return {};
|
||||
return protocol === "responses" ? { reasoning: { effort } } : { reasoning_effort: effort };
|
||||
}
|
||||
@@ -5,8 +5,8 @@ import {
|
||||
type ToolExecutionEvent,
|
||||
} from "./chat-tools.js";
|
||||
import { getProviderChatAdapter } from "./provider-adapters.js";
|
||||
import { toPrismaProvider } from "./provider-ids.js";
|
||||
import type { MultiplexRequest, Provider } from "./types.js";
|
||||
import { normalizeReasoningEffort } from "./reasoning-effort.js";
|
||||
|
||||
type StreamUsage = {
|
||||
inputTokens?: number;
|
||||
@@ -27,6 +27,7 @@ function getChatIdOrCreate(chatId?: string) {
|
||||
}
|
||||
|
||||
export async function* runMultiplexStream(req: MultiplexRequest): AsyncGenerator<StreamEvent> {
|
||||
req = { ...req, reasoningEffort: normalizeReasoningEffort(req.provider, req.model, req.reasoningEffort) };
|
||||
const t0 = performance.now();
|
||||
const shouldPersist = req.persist !== false;
|
||||
const chatId = shouldPersist ? await getChatIdOrCreate(req.chatId) : null;
|
||||
@@ -36,7 +37,7 @@ export async function* runMultiplexStream(req: MultiplexRequest): AsyncGenerator
|
||||
? await prisma.llmCall.create({
|
||||
data: {
|
||||
chatId,
|
||||
provider: toPrismaProvider(req.provider) as any,
|
||||
provider: req.provider,
|
||||
model: req.model,
|
||||
request: req as any,
|
||||
},
|
||||
@@ -49,14 +50,15 @@ export async function* runMultiplexStream(req: MultiplexRequest): AsyncGenerator
|
||||
prisma.chat.update({
|
||||
where: { id: chatId },
|
||||
data: {
|
||||
lastUsedProvider: toPrismaProvider(req.provider) as any,
|
||||
lastUsedProvider: req.provider,
|
||||
lastUsedModel: req.model,
|
||||
reasoningEffort: req.reasoningEffort,
|
||||
},
|
||||
}),
|
||||
prisma.chat.updateMany({
|
||||
where: { id: chatId, initiatedProvider: null },
|
||||
data: {
|
||||
initiatedProvider: toPrismaProvider(req.provider) as any,
|
||||
initiatedProvider: req.provider,
|
||||
initiatedModel: req.model,
|
||||
},
|
||||
}),
|
||||
@@ -78,6 +80,7 @@ export async function* runMultiplexStream(req: MultiplexRequest): AsyncGenerator
|
||||
userLocation: req.userLocation,
|
||||
temperature: req.temperature,
|
||||
maxTokens: req.maxTokens,
|
||||
reasoningEffort: req.reasoningEffort,
|
||||
logContext: {
|
||||
provider: req.provider,
|
||||
model: req.model,
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
export const PROVIDERS = ["openai", "anthropic", "xai", "gemini", "hermes-agent"] as const;
|
||||
import type { ReasoningEffort } from "./reasoning-effort.js";
|
||||
|
||||
export const PROVIDERS = ["openai", "anthropic", "xai", "gemini"] as const;
|
||||
|
||||
export type Provider = (typeof PROVIDERS)[number];
|
||||
|
||||
@@ -42,6 +44,7 @@ export type MultiplexRequest = {
|
||||
userLocation?: string;
|
||||
temperature?: number;
|
||||
maxTokens?: number;
|
||||
reasoningEffort?: ReasoningEffort | null;
|
||||
};
|
||||
|
||||
export type MultiplexResponse = {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { fromPrismaProvider } from "./llm/provider-ids.js";
|
||||
import { parseProvider } from "./llm/provider-ids.js";
|
||||
|
||||
function record(value: unknown): Record<string, unknown> {
|
||||
return value && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : {};
|
||||
@@ -18,7 +18,7 @@ export function withMessageGenerations<T extends { role: string; metadata: unkno
|
||||
for (const call of calls) {
|
||||
const requestId = record(call.request).clientRequestId;
|
||||
if (typeof requestId !== "string" || !requestId || call.error !== null || call.latencyMs === null) continue;
|
||||
const provider = fromPrismaProvider(call.provider);
|
||||
const provider = parseProvider(call.provider);
|
||||
if (!provider || !call.model.trim()) continue;
|
||||
byRequest.set(requestId, byRequest.has(requestId) ? null : { provider, model: call.model });
|
||||
}
|
||||
|
||||
+50
-20
@@ -16,14 +16,16 @@ import { runMultiplexStream, type StreamEvent } from "./llm/streaming.js";
|
||||
import { getAvailableChatTools, normalizeEnabledChatTools } from "./llm/chat-tools.js";
|
||||
import { getModelCatalogSnapshot } from "./llm/model-catalog.js";
|
||||
import { buildQuickQuestionMultiplexRequest } from "./llm/quick-question.js";
|
||||
import { normalizeReasoningEffort, REASONING_EFFORTS, type ReasoningEffort } from "./llm/reasoning-effort.js";
|
||||
import { openaiClient } from "./llm/providers.js";
|
||||
import { serializeProviderFields, toPrismaProvider } from "./llm/provider-ids.js";
|
||||
import { serializeProviderFields } from "./llm/provider-ids.js";
|
||||
import { exaClient } from "./search/exa.js";
|
||||
import { isFreshSearchCacheHit, normalizeSearchQuery } from "./search-cache.js";
|
||||
import { searchWorkspace } from "./workspace-search.js";
|
||||
import type { ChatAttachment } from "./llm/types.js";
|
||||
import { PROVIDERS, type ChatAttachment } from "./llm/types.js";
|
||||
|
||||
const ProviderSchema = z.enum(["openai", "anthropic", "xai", "gemini", "hermes-agent"]);
|
||||
const ProviderSchema = z.enum(PROVIDERS);
|
||||
const ReasoningEffortSchema = z.enum(REASONING_EFFORTS).nullable();
|
||||
const MAX_ADDITIONAL_SYSTEM_PROMPT_CHARS = 12_000;
|
||||
const MAX_FORK_MESSAGE_SNIPPET_CHARS = 48;
|
||||
const EnabledToolsSchema = z.array(z.string().trim().min(1).max(80)).max(20).transform((value) => normalizeEnabledChatTools(value));
|
||||
@@ -209,6 +211,7 @@ const CompletionStreamBody = z
|
||||
userLocation: z.string().trim().min(1).max(200).optional(),
|
||||
temperature: z.number().min(0).max(2).optional(),
|
||||
maxTokens: z.number().int().positive().optional(),
|
||||
reasoningEffort: ReasoningEffortSchema.optional(),
|
||||
})
|
||||
.superRefine((value, ctx) => {
|
||||
if (value.persist === false && value.chatId) {
|
||||
@@ -235,6 +238,7 @@ const QuickQuestionStreamBody = z.object({
|
||||
userLocation: z.string().trim().min(1).max(200).optional(),
|
||||
temperature: z.number().min(0).max(2).optional(),
|
||||
maxTokens: z.number().int().positive().optional(),
|
||||
reasoningEffort: ReasoningEffortSchema.optional(),
|
||||
});
|
||||
|
||||
function mergeAttachmentsIntoMetadata(metadata: unknown, attachments?: ChatAttachment[]) {
|
||||
@@ -269,16 +273,16 @@ function prependAdditionalSystemPrompt<T extends { messages: IncomingChatMessage
|
||||
};
|
||||
}
|
||||
|
||||
async function applyStoredChatSettings<T extends { chatId?: string; messages: IncomingChatMessage[]; additionalSystemPrompt?: string; enabledTools?: string[] }>(
|
||||
async function applyStoredChatSettings<T extends { chatId?: string; provider: string; model: string; messages: IncomingChatMessage[]; additionalSystemPrompt?: string; enabledTools?: string[]; reasoningEffort?: ReasoningEffort | null }>(
|
||||
body: T
|
||||
) {
|
||||
if (!body.chatId || (body.additionalSystemPrompt !== undefined && body.enabledTools !== undefined)) {
|
||||
if (!body.chatId || (body.additionalSystemPrompt !== undefined && body.enabledTools !== undefined && body.reasoningEffort !== undefined)) {
|
||||
return prependAdditionalSystemPrompt(body);
|
||||
}
|
||||
|
||||
const chat = await prisma.chat.findUnique({
|
||||
where: { id: body.chatId },
|
||||
select: { additionalSystemPrompt: true, enabledTools: true },
|
||||
select: { additionalSystemPrompt: true, enabledTools: true, reasoningEffort: true, lastUsedProvider: true, lastUsedModel: true },
|
||||
});
|
||||
if (!chat) return prependAdditionalSystemPrompt(body);
|
||||
|
||||
@@ -286,6 +290,10 @@ async function applyStoredChatSettings<T extends { chatId?: string; messages: In
|
||||
...body,
|
||||
additionalSystemPrompt: body.additionalSystemPrompt ?? chat.additionalSystemPrompt ?? undefined,
|
||||
enabledTools: body.enabledTools ?? normalizeEnabledChatTools(chat.enabledTools),
|
||||
// Omission inherits only for the saved model; null explicitly resets it.
|
||||
reasoningEffort: normalizeReasoningEffort(body.provider, body.model, body.reasoningEffort !== undefined
|
||||
? body.reasoningEffort
|
||||
: chat.lastUsedProvider === body.provider && chat.lastUsedModel === body.model ? chat.reasoningEffort : null),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -335,7 +343,7 @@ function executeActiveAgentAsideStream(chatId: string, body: z.infer<typeof Comp
|
||||
type: "meta",
|
||||
chatId,
|
||||
callId: null,
|
||||
provider: "hermes-agent",
|
||||
provider: "sybil-agent",
|
||||
model: "sybil-agent",
|
||||
agentAside: true,
|
||||
});
|
||||
@@ -556,6 +564,7 @@ const chatSummarySelect = {
|
||||
initiatedModel: true,
|
||||
lastUsedProvider: true,
|
||||
lastUsedModel: true,
|
||||
reasoningEffort: true,
|
||||
additionalSystemPrompt: true,
|
||||
enabledTools: true,
|
||||
projectItems: starredProjectItemsSelect,
|
||||
@@ -815,7 +824,7 @@ function completeChatSubmissionStream(
|
||||
type: "meta",
|
||||
chatId,
|
||||
callId: null,
|
||||
provider: agentAside ? "hermes-agent" : body.provider,
|
||||
provider: agentAside ? "sybil-agent" : body.provider,
|
||||
model: agentAside ? "sybil-agent" : body.model,
|
||||
...(agentAside ? { agentAside: true } : {}),
|
||||
});
|
||||
@@ -1082,7 +1091,7 @@ export async function registerRoutes(app: FastifyInstance, options: { agentInlin
|
||||
} : undefined,
|
||||
orderBy: [{ updatedAt: "desc" }, { id: "asc" }],
|
||||
take: limit + 1,
|
||||
select: { id: true, title: true, parentChatId: true, createdAt: true, updatedAt: true, initiatedProvider: true, initiatedModel: true, lastUsedProvider: true, lastUsedModel: true },
|
||||
select: { id: true, title: true, parentChatId: true, createdAt: true, updatedAt: true, initiatedProvider: true, initiatedModel: true, lastUsedProvider: true, lastUsedModel: true, reasoningEffort: true },
|
||||
});
|
||||
const hasMore = chats.length > limit;
|
||||
const page = hasMore ? chats.slice(0, limit) : chats;
|
||||
@@ -1103,6 +1112,7 @@ export async function registerRoutes(app: FastifyInstance, options: { agentInlin
|
||||
title: z.string().optional(),
|
||||
provider: ProviderSchema.optional(),
|
||||
model: z.string().trim().min(1).optional(),
|
||||
reasoningEffort: ReasoningEffortSchema.optional(),
|
||||
additionalSystemPrompt: z.string().max(MAX_ADDITIONAL_SYSTEM_PROMPT_CHARS).optional(),
|
||||
enabledTools: EnabledToolsSchema.optional(),
|
||||
messages: z.array(CompletionMessageSchema).optional(),
|
||||
@@ -1129,10 +1139,11 @@ export async function registerRoutes(app: FastifyInstance, options: { agentInlin
|
||||
const chat = await prisma.chat.create({
|
||||
data: {
|
||||
title: body.title,
|
||||
initiatedProvider: body.provider ? (toPrismaProvider(body.provider) as any) : undefined,
|
||||
initiatedProvider: body.provider,
|
||||
initiatedModel: body.model,
|
||||
lastUsedProvider: body.provider ? (toPrismaProvider(body.provider) as any) : undefined,
|
||||
lastUsedProvider: body.provider,
|
||||
lastUsedModel: body.model,
|
||||
reasoningEffort: normalizeReasoningEffort(body.provider, body.model, body.reasoningEffort),
|
||||
additionalSystemPrompt: normalizeAdditionalSystemPrompt(body.additionalSystemPrompt),
|
||||
enabledTools: body.enabledTools as any,
|
||||
messages: body.messages?.length
|
||||
@@ -1170,6 +1181,7 @@ export async function registerRoutes(app: FastifyInstance, options: { agentInlin
|
||||
initiatedModel: true,
|
||||
lastUsedProvider: true,
|
||||
lastUsedModel: true,
|
||||
reasoningEffort: true,
|
||||
additionalSystemPrompt: true,
|
||||
enabledTools: true,
|
||||
userId: true,
|
||||
@@ -1199,6 +1211,7 @@ export async function registerRoutes(app: FastifyInstance, options: { agentInlin
|
||||
initiatedModel: source.initiatedModel,
|
||||
lastUsedProvider: source.lastUsedProvider,
|
||||
lastUsedModel: source.lastUsedModel,
|
||||
reasoningEffort: normalizeReasoningEffort(source.lastUsedProvider, source.lastUsedModel, source.reasoningEffort),
|
||||
additionalSystemPrompt: source.additionalSystemPrompt,
|
||||
enabledTools: (source.enabledTools ?? undefined) as any,
|
||||
userId: source.userId,
|
||||
@@ -1231,11 +1244,16 @@ export async function registerRoutes(app: FastifyInstance, options: { agentInlin
|
||||
const Params = z.object({ chatId: z.string() });
|
||||
const Body = z.object({
|
||||
title: z.string().trim().min(1).optional(),
|
||||
provider: ProviderSchema.optional(),
|
||||
model: z.string().trim().min(1).optional(),
|
||||
reasoningEffort: ReasoningEffortSchema.optional(),
|
||||
additionalSystemPrompt: z.string().max(MAX_ADDITIONAL_SYSTEM_PROMPT_CHARS).nullable().optional(),
|
||||
enabledTools: EnabledToolsSchema.optional(),
|
||||
});
|
||||
}).refine((value) => Boolean(value.provider) === Boolean(value.model), "provider and model must be supplied together");
|
||||
const { chatId } = Params.parse(req.params);
|
||||
const body = Body.parse(req.body ?? {});
|
||||
const parsed = Body.safeParse(req.body ?? {});
|
||||
if (!parsed.success) return app.httpErrors.badRequest(parsed.error.message);
|
||||
const body = parsed.data;
|
||||
|
||||
const data: Record<string, unknown> = {};
|
||||
if (body.title !== undefined) {
|
||||
@@ -1244,13 +1262,24 @@ export async function registerRoutes(app: FastifyInstance, options: { agentInlin
|
||||
}
|
||||
if (body.additionalSystemPrompt !== undefined) data.additionalSystemPrompt = normalizeAdditionalSystemPrompt(body.additionalSystemPrompt);
|
||||
if (body.enabledTools !== undefined) data.enabledTools = body.enabledTools;
|
||||
|
||||
const updated = await prisma.chat.updateMany({
|
||||
where: { id: chatId },
|
||||
data: data as any,
|
||||
const updated = await prisma.$transaction(async (tx) => {
|
||||
const current = await tx.chat.findUnique({ where: { id: chatId } });
|
||||
if (!current) return null;
|
||||
const provider = body.provider ?? current.lastUsedProvider;
|
||||
const model = body.model ?? current.lastUsedModel;
|
||||
if (body.provider !== undefined) {
|
||||
data.lastUsedProvider = provider;
|
||||
data.lastUsedModel = model;
|
||||
}
|
||||
if (body.provider !== undefined || body.reasoningEffort !== undefined) {
|
||||
const sameModel = provider === current.lastUsedProvider && model === current.lastUsedModel;
|
||||
data.reasoningEffort = normalizeReasoningEffort(provider, model, body.reasoningEffort !== undefined
|
||||
? body.reasoningEffort : sameModel ? current.reasoningEffort : null);
|
||||
}
|
||||
return tx.chat.update({ where: { id: chatId }, data: data as any });
|
||||
});
|
||||
|
||||
if (updated.count === 0) return app.httpErrors.notFound("chat not found");
|
||||
if (!updated) return app.httpErrors.notFound("chat not found");
|
||||
|
||||
const chat = await getChatSummary(chatId);
|
||||
if (!chat) return app.httpErrors.notFound("chat not found");
|
||||
@@ -1738,6 +1767,7 @@ export async function registerRoutes(app: FastifyInstance, options: { agentInlin
|
||||
userLocation: z.string().trim().min(1).max(200).optional(),
|
||||
temperature: z.number().min(0).max(2).optional(),
|
||||
maxTokens: z.number().int().positive().optional(),
|
||||
reasoningEffort: ReasoningEffortSchema.optional(),
|
||||
});
|
||||
|
||||
const parsed = Body.safeParse(req.body);
|
||||
@@ -1761,7 +1791,7 @@ export async function registerRoutes(app: FastifyInstance, options: { agentInlin
|
||||
const completedAgentAside = Boolean((completed.metadata as Record<string, unknown> | null)?.agentAside === true);
|
||||
return {
|
||||
chatId: body.chatId,
|
||||
provider: completedAgentAside ? "hermes-agent" : body.provider,
|
||||
provider: completedAgentAside ? "sybil-agent" : body.provider,
|
||||
model: completedAgentAside ? "sybil-agent" : body.model,
|
||||
message: {
|
||||
role: "assistant",
|
||||
@@ -1778,7 +1808,7 @@ export async function registerRoutes(app: FastifyInstance, options: { agentInlin
|
||||
await storeAgentAsideReply(body.chatId, content, body.clientRequestId);
|
||||
return {
|
||||
chatId: body.chatId,
|
||||
provider: "hermes-agent",
|
||||
provider: "sybil-agent",
|
||||
model: "sybil-agent",
|
||||
message: { role: "assistant", content, name: "Sybil Agent", agentAside: true },
|
||||
};
|
||||
|
||||
@@ -58,7 +58,7 @@ test("mention invokes only the inline Agent, stores both sides, and replays by r
|
||||
};
|
||||
const first = await app.inject({ method: "POST", url: "/v1/chat-completions", headers: auth, payload: body });
|
||||
assert.equal(first.statusCode, 200, first.body);
|
||||
assert.equal(first.json().provider, "hermes-agent");
|
||||
assert.equal(first.json().provider, "sybil-agent");
|
||||
assert.equal(first.json().message.name, "Sybil Agent");
|
||||
assert.equal(first.json().message.agentAside, true);
|
||||
assert.equal(first.json().message.content, "Synthetic Sybil reply");
|
||||
@@ -66,7 +66,7 @@ test("mention invokes only the inline Agent, stores both sides, and replays by r
|
||||
|
||||
const retry = await app.inject({ method: "POST", url: "/v1/chat-completions", headers: auth, payload: body });
|
||||
assert.equal(retry.statusCode, 200, retry.body);
|
||||
assert.equal(retry.json().provider, "hermes-agent");
|
||||
assert.equal(retry.json().provider, "sybil-agent");
|
||||
assert.equal(retry.json().message.name, "Sybil Agent");
|
||||
assert.equal(retry.json().message.agentAside, true);
|
||||
assert.equal(retry.json().message.content, "Synthetic Sybil reply");
|
||||
@@ -224,9 +224,12 @@ test("streamed mention is idempotent and identifies the inline Agent", async ()
|
||||
const retry = streamingApp.inject({ method: "POST", url: "/v1/chat-completions/stream", headers: auth, payload });
|
||||
finish("Synthetic streamed reply");
|
||||
const [firstResponse, retryResponse] = await Promise.all([first, retry]);
|
||||
for (const response of [firstResponse, retryResponse]) {
|
||||
const completedReplay = await streamingApp.inject({ method: "POST", url: "/v1/chat-completions/stream", headers: auth, payload });
|
||||
for (const response of [firstResponse, retryResponse, completedReplay]) {
|
||||
assert.equal(response.statusCode, 200, response.body);
|
||||
assert.match(response.body, /"agentAside":true/);
|
||||
assert.match(response.body, /"provider":"sybil-agent"/);
|
||||
assert.match(response.body, /"model":"sybil-agent"/);
|
||||
assert.match(response.body, /Synthetic streamed reply/);
|
||||
}
|
||||
assert.equal(calls, 1);
|
||||
|
||||
@@ -125,13 +125,13 @@ test("plain Chat Completions stream does not send Sybil-managed tools", async ()
|
||||
const events = await collectEvents(
|
||||
streamWithChatCompletionsApi({
|
||||
client: client as any,
|
||||
model: "hermes-agent",
|
||||
model: "grok-test",
|
||||
messages: [{ role: "user", content: "Say hi" }],
|
||||
enabledTools: [],
|
||||
})
|
||||
);
|
||||
|
||||
assert.equal(requestBody.model, "hermes-agent");
|
||||
assert.equal(requestBody.model, "grok-test");
|
||||
assert.equal(requestBody.stream, true);
|
||||
assert.equal("tools" in requestBody, false);
|
||||
assert.deepEqual(
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { env } from "../src/env.js";
|
||||
import { describeProviderChatBackend, fetchProviderCatalogModels } from "../src/llm/provider-adapters.js";
|
||||
import { describeProviderChatBackend, fetchProviderCatalogModels, listModelCatalogProviders } from "../src/llm/provider-adapters.js";
|
||||
|
||||
for (const { name, listedModels, expectedModels } of [
|
||||
{
|
||||
@@ -47,6 +47,7 @@ for (const { name, listedModels, expectedModels } of [
|
||||
}
|
||||
|
||||
test("provider backend registry selects chat protocol and managed-tool mode", () => {
|
||||
assert.deepEqual(listModelCatalogProviders(), ["openai", "anthropic", "xai", "gemini"]);
|
||||
assert.deepEqual(describeProviderChatBackend("openai", []), {
|
||||
provider: "openai",
|
||||
protocol: "chat-completions",
|
||||
@@ -77,10 +78,4 @@ test("provider backend registry selects chat protocol and managed-tool mode", ()
|
||||
managedTools: true,
|
||||
enabledTools: ["web_search"],
|
||||
});
|
||||
assert.deepEqual(describeProviderChatBackend("hermes-agent", ["web_search"]), {
|
||||
provider: "hermes-agent",
|
||||
protocol: "chat-completions",
|
||||
managedTools: false,
|
||||
enabledTools: [],
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,14 +1,26 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { fromPrismaProvider, serializeProviderFields, toPrismaProvider } from "../src/llm/provider-ids.js";
|
||||
import { parseProvider, serializeProviderFields } from "../src/llm/provider-ids.js";
|
||||
import { PROVIDERS } from "../src/llm/types.js";
|
||||
|
||||
test("Hermes Agent provider id maps between API and Prisma enum forms", () => {
|
||||
assert.equal(toPrismaProvider("hermes-agent"), "hermes_agent");
|
||||
assert.equal(fromPrismaProvider("hermes_agent"), "hermes-agent");
|
||||
assert.equal(toPrismaProvider("gemini"), "gemini");
|
||||
assert.equal(fromPrismaProvider("gemini"), "gemini");
|
||||
assert.deepEqual(serializeProviderFields({ initiatedProvider: "hermes_agent", lastUsedProvider: "gemini" }), {
|
||||
initiatedProvider: "hermes-agent",
|
||||
lastUsedProvider: "gemini",
|
||||
test("only supported provider IDs can become active selections", () => {
|
||||
for (const provider of PROVIDERS) assert.equal(parseProvider(provider), provider);
|
||||
for (const provider of [null, undefined, "retired-provider", "sybil-agent", "toString", {}]) {
|
||||
assert.equal(parseProvider(provider), null);
|
||||
}
|
||||
});
|
||||
|
||||
test("retired saved selections are cleared without changing historical call records", () => {
|
||||
const record = {
|
||||
initiatedProvider: "retired-provider", initiatedModel: "old-model",
|
||||
lastUsedProvider: "gemini", lastUsedModel: "current-model",
|
||||
calls: [{ provider: "retired-provider", model: "old-model", request: { provider: "retired-provider" } }],
|
||||
};
|
||||
assert.deepEqual(serializeProviderFields(record), {
|
||||
initiatedProvider: null, initiatedModel: null,
|
||||
lastUsedProvider: "gemini", lastUsedModel: "current-model",
|
||||
calls: [{ provider: null, model: "old-model", request: { provider: "retired-provider" } }],
|
||||
});
|
||||
assert.equal(record.initiatedProvider, "retired-provider");
|
||||
assert.equal(record.calls[0]!.provider, "retired-provider");
|
||||
});
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { mkdtempSync, rmSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { dirname, join, resolve } from "node:path";
|
||||
import test from "node:test";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import Fastify from "fastify";
|
||||
import sensible from "@fastify/sensible";
|
||||
import { PROVIDERS } from "../src/llm/types.js";
|
||||
|
||||
const serverRoot = resolve(dirname(fileURLToPath(import.meta.url)), "..");
|
||||
const databaseDir = mkdtempSync(join(tmpdir(), "sybil-provider-retirement-"));
|
||||
process.env.DATABASE_URL = `file:${join(databaseDir, "test.db")}`;
|
||||
process.env.ADMIN_TOKEN = "provider-retirement-test-token";
|
||||
execFileSync(process.execPath, [join(serverRoot, "node_modules/prisma/build/index.js"), "migrate", "deploy"], {
|
||||
cwd: serverRoot, env: { ...process.env, PRISMA_HIDE_UPDATE_MESSAGE: "1" }, stdio: "pipe",
|
||||
});
|
||||
const [{ registerRoutes }, { prisma }] = await Promise.all([import("../src/routes.js"), import("../src/db.js")]);
|
||||
const app = Fastify({ logger: false });
|
||||
await app.register(sensible);
|
||||
await registerRoutes(app, { agentInlineInvoker: async () => { throw new Error("Unsupported requests must not invoke the Agent"); } });
|
||||
await app.ready();
|
||||
const auth = { authorization: "Bearer provider-retirement-test-token" };
|
||||
test.after(async () => { await app.close(); await prisma.$disconnect(); rmSync(databaseDir, { recursive: true, force: true }); });
|
||||
|
||||
test("catalog and request validation expose only the remaining LLM providers", async () => {
|
||||
const catalog = await app.inject({ method: "GET", url: "/v1/models", headers: auth });
|
||||
assert.equal(catalog.statusCode, 200);
|
||||
assert.deepEqual(Object.keys(catalog.json().providers), [...PROVIDERS]);
|
||||
const before = await prisma.chat.count();
|
||||
for (const provider of ["retired-provider", "sybil-agent"]) {
|
||||
for (const url of ["/v1/chats", "/v1/chat-completions", "/v1/chat-completions/stream", "/v1/quick-questions/stream"]) {
|
||||
const response = await app.inject({ method: "POST", url, headers: auth, payload: {
|
||||
provider, model: "test-model", messages: [{ role: "user", content: "@sybil test" }], question: "test",
|
||||
} });
|
||||
assert.equal(response.statusCode, 400, `${url}: ${response.body}`);
|
||||
}
|
||||
}
|
||||
assert.equal(await prisma.chat.count(), before);
|
||||
assert.equal(await prisma.llmCall.count(), 0);
|
||||
for (const provider of PROVIDERS) {
|
||||
const response = await app.inject({ method: "POST", url: "/v1/chats", headers: auth, payload: { provider, model: "test-model" } });
|
||||
assert.equal(response.statusCode, 200, response.body);
|
||||
assert.equal(response.json().chat.lastUsedProvider, provider);
|
||||
}
|
||||
});
|
||||
|
||||
test("existing text provider IDs remain readable and forkable without relabeling history", async () => {
|
||||
const chat = await prisma.chat.create({ data: {
|
||||
title: "Archived provider conversation",
|
||||
initiatedProvider: "retired-provider", initiatedModel: "archived-model",
|
||||
lastUsedProvider: "retired-provider", lastUsedModel: "archived-model",
|
||||
messages: { create: { role: "assistant", content: "Original saved answer", metadata: { clientRequestId: "old-request" } } },
|
||||
calls: { create: { provider: "retired-provider", model: "archived-model", request: { provider: "retired-provider", clientRequestId: "old-request" }, latencyMs: 1 } },
|
||||
}, include: { messages: true, calls: true } });
|
||||
const detail = await app.inject({ method: "GET", url: `/v1/chats/${chat.id}`, headers: auth });
|
||||
assert.equal(detail.statusCode, 200, detail.body);
|
||||
const saved = detail.json().chat;
|
||||
for (const key of ["initiatedProvider", "initiatedModel", "lastUsedProvider", "lastUsedModel"]) assert.equal(saved[key], null);
|
||||
assert.equal(saved.messages[0].content, "Original saved answer");
|
||||
assert.equal(saved.messages[0].metadata.generation, undefined);
|
||||
assert.equal(saved.calls[0].provider, null);
|
||||
assert.equal(saved.calls[0].request.provider, "retired-provider");
|
||||
for (const url of ["/v1/chats", "/v1/workspace-items", "/v1/chats?limit=50"]) {
|
||||
const response = await app.inject({ method: "GET", url, headers: auth });
|
||||
assert.equal(response.statusCode, 200, `${url}: ${response.body}`);
|
||||
const rows = response.json().chats ?? response.json().items;
|
||||
assert.equal(rows.find((row: any) => row.id === chat.id).lastUsedProvider, null);
|
||||
}
|
||||
const fork = await app.inject({ method: "POST", url: `/v1/chats/${chat.id}/fork`, headers: auth, payload: {} });
|
||||
assert.equal(fork.statusCode, 200, fork.body);
|
||||
const forkDetail = await app.inject({ method: "GET", url: `/v1/chats/${fork.json().chat.id}`, headers: auth });
|
||||
assert.equal(forkDetail.statusCode, 200, forkDetail.body);
|
||||
assert.equal(forkDetail.json().chat.lastUsedProvider, null);
|
||||
assert.equal(forkDetail.json().chat.messages[0].content, "Original saved answer");
|
||||
const stored = await prisma.chat.findUniqueOrThrow({ where: { id: chat.id }, include: { calls: true } });
|
||||
assert.equal(stored.lastUsedProvider, "retired-provider");
|
||||
assert.equal(stored.calls[0]!.provider, "retired-provider");
|
||||
});
|
||||
@@ -0,0 +1,174 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { dirname, join, resolve } from "node:path";
|
||||
import test from "node:test";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import Fastify from "fastify";
|
||||
import sensible from "@fastify/sensible";
|
||||
import { getReasoningCatalog, normalizeReasoningEffort } from "../src/llm/reasoning-effort.js";
|
||||
|
||||
const serverRoot = resolve(dirname(fileURLToPath(import.meta.url)), "..");
|
||||
const databaseDir = mkdtempSync(join(tmpdir(), "sybil-reasoning-"));
|
||||
process.env.DATABASE_URL = `file:${join(databaseDir, "test.db")}`;
|
||||
writeFileSync(join(databaseDir, "test.db"), "");
|
||||
process.env.OPENAI_API_KEY = "test-key";
|
||||
process.env.XAI_API_KEY = "test-key";
|
||||
delete process.env.ADMIN_TOKEN;
|
||||
execFileSync(process.execPath, [join(serverRoot, "node_modules/prisma/build/index.js"), "migrate", "deploy"], {
|
||||
cwd: serverRoot, env: { ...process.env, PRISMA_HIDE_UPDATE_MESSAGE: "1" }, stdio: "pipe",
|
||||
});
|
||||
const [{ registerRoutes }, { prisma }, { getProviderChatAdapter }] = await Promise.all([
|
||||
import("../src/routes.js"), import("../src/db.js"), import("../src/llm/provider-adapters.js"),
|
||||
]);
|
||||
const app = Fastify({ logger: false });
|
||||
await app.register(sensible);
|
||||
await registerRoutes(app);
|
||||
await app.ready();
|
||||
|
||||
const requests: { path: string; body: any }[] = [];
|
||||
const originalFetch = globalThis.fetch;
|
||||
globalThis.fetch = async (input, init) => {
|
||||
const url = new URL(input instanceof Request ? input.url : String(input));
|
||||
assert.ok(["api.openai.com", "api.x.ai"].includes(url.hostname), `Unexpected network request: ${url.origin}`);
|
||||
const body = JSON.parse(String(init?.body));
|
||||
requests.push({ path: url.pathname, body });
|
||||
const message = { id: "message", type: "message", role: "assistant", content: [{ type: "output_text", text: "Mock answer." }] };
|
||||
const response = { id: "response", status: "completed", output: [message], output_text: "Mock answer." };
|
||||
if (!body.stream) return Response.json(url.pathname.endsWith("/responses") ? response : {
|
||||
id: "completion", choices: [{ message: { role: "assistant", content: "Mock answer." }, finish_reason: "stop" }],
|
||||
});
|
||||
const events = url.pathname.endsWith("/responses") ? [
|
||||
{ type: "response.output_item.added", item: message, output_index: 0 },
|
||||
{ type: "response.output_text.delta", delta: "Mock answer.", output_index: 0 },
|
||||
{ type: "response.completed", response },
|
||||
] : [{ choices: [{ index: 0, delta: { content: "Mock answer." }, finish_reason: "stop" }] }];
|
||||
return new Response(events.map((event) => `data: ${JSON.stringify(event)}\n\n`).join("") + "data: [DONE]\n\n", {
|
||||
headers: { "Content-Type": "text/event-stream" },
|
||||
});
|
||||
};
|
||||
test.after(async () => {
|
||||
globalThis.fetch = originalFetch;
|
||||
await app.close();
|
||||
await prisma.$disconnect();
|
||||
rmSync(databaseDir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
test("capabilities require an exact verified provider/model/effort combination", () => {
|
||||
assert.equal(normalizeReasoningEffort("openai", "gpt-5.2", "xhigh"), "xhigh");
|
||||
assert.equal(normalizeReasoningEffort("openai", "gpt-5.2-2025-12-11", "none"), "none");
|
||||
assert.equal(normalizeReasoningEffort("openai", "gpt-5", "minimal"), "minimal");
|
||||
for (const [provider, model, effort] of [
|
||||
["openai", "gpt-5.1", "xhigh"], ["openai", "gpt-6.1-sol", "none"],
|
||||
["openai", "gpt-5.2-future", "high"], ["openai", "gpt-5.2-pro", "high"],
|
||||
["openai", "ft:gpt-5.2", "high"], ["openai", "gpt-4.1-mini", "high"],
|
||||
["openai", "chat-latest", "high"], ["xai", "gpt-5.2", "high"],
|
||||
]) assert.equal(normalizeReasoningEffort(provider, model, effort), null);
|
||||
const catalog = getReasoningCatalog("openai");
|
||||
assert.equal(catalog["gpt-5.2"].defaultEffort, "none");
|
||||
assert.equal(catalog["gpt-5.5"].defaultEffort, "medium");
|
||||
assert.deepEqual(getReasoningCatalog("anthropic"), {});
|
||||
catalog["gpt-5.2"].efforts.push("max");
|
||||
assert.equal(normalizeReasoningEffort("openai", "gpt-5.2", "max"), null);
|
||||
});
|
||||
|
||||
test("real SDK serialization uses the right effort field for every OpenAI protocol and stream mode", async () => {
|
||||
for (const enabledTools of [[], ["web_search"]]) {
|
||||
for (const streaming of [false, true]) {
|
||||
for (const reasoningEffort of ["high", "none", null] as const) {
|
||||
const adapter = getProviderChatAdapter("openai");
|
||||
const params = { model: "gpt-5.2", messages: [{ role: "user" as const, content: "Hello" }], enabledTools, reasoningEffort, temperature: 0.2, maxTokens: 1000 };
|
||||
if (streaming) {
|
||||
const events = [];
|
||||
for await (const event of adapter.stream(params)) events.push(event);
|
||||
assert.equal(events.at(-1)?.type, "done");
|
||||
} else assert.equal((await adapter.complete(params)).text, "Mock answer.");
|
||||
const { path, body } = requests.at(-1)!;
|
||||
assert.equal(path, enabledTools.length ? "/v1/responses" : "/v1/chat/completions");
|
||||
if (enabledTools.length) {
|
||||
assert.deepEqual(body.reasoning, reasoningEffort ? { effort: reasoningEffort } : undefined);
|
||||
assert.equal(body.reasoning_effort, undefined);
|
||||
assert.equal(body.max_output_tokens, 1000);
|
||||
} else {
|
||||
assert.equal(body.reasoning_effort, reasoningEffort ?? undefined);
|
||||
assert.equal(body.reasoning, undefined);
|
||||
assert.equal(body.max_completion_tokens, 1000);
|
||||
assert.equal(body.max_tokens, undefined);
|
||||
}
|
||||
assert.equal(body.temperature, reasoningEffort === "high" ? undefined : 0.2);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test("unsupported models, unsupported efforts and other providers never receive an effort field", async () => {
|
||||
for (const provider of ["openai", "xai"] as const) {
|
||||
for (const model of ["gpt-4.1-mini", "chat-latest", "gpt-5.1", "gpt-5.2-unknown"]) {
|
||||
for (const enabledTools of [[], ["web_search"]]) {
|
||||
const adapter = getProviderChatAdapter(provider);
|
||||
await adapter.complete({ model, messages: [{ role: "user", content: "Hi" }], enabledTools, reasoningEffort: "xhigh" });
|
||||
const { body } = requests.at(-1)!;
|
||||
assert.equal("reasoning" in body, false);
|
||||
assert.equal("reasoning_effort" in body, false);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test("chat settings persist, survive all summary/detail reads and forks, and reset on a model change", async () => {
|
||||
const created = await app.inject({ method: "POST", url: "/v1/chats", payload: { provider: "openai", model: "gpt-5.2", reasoningEffort: "high" } });
|
||||
assert.equal(created.statusCode, 200, created.body);
|
||||
const chat = created.json().chat;
|
||||
assert.equal(chat.reasoningEffort, "high");
|
||||
for (const url of [`/v1/chats/${chat.id}`, "/v1/chats", "/v1/chats?limit=10", "/v1/workspace-items"]) {
|
||||
const body = (await app.inject({ method: "GET", url })).json();
|
||||
const stored = body.chat ?? (body.chats ?? body.items).find((item: any) => item.id === chat.id);
|
||||
assert.equal(stored.reasoningEffort, "high", url);
|
||||
}
|
||||
const fork = await app.inject({ method: "POST", url: `/v1/chats/${chat.id}/fork`, payload: {} });
|
||||
assert.equal(fork.json().chat.reasoningEffort, "high");
|
||||
const patch = async (payload: object) => app.inject({ method: "PATCH", url: `/v1/chats/${chat.id}`, payload });
|
||||
assert.equal((await patch({ title: "Renamed" })).json().chat.reasoningEffort, "high");
|
||||
const switched = (await patch({ provider: "openai", model: "gpt-5.1" })).json().chat;
|
||||
assert.equal(switched.lastUsedModel, "gpt-5.1");
|
||||
assert.equal(switched.reasoningEffort, null);
|
||||
assert.equal((await patch({ reasoningEffort: "xhigh" })).json().chat.reasoningEffort, null);
|
||||
assert.equal((await patch({ reasoningEffort: "low" })).json().chat.reasoningEffort, "low");
|
||||
assert.equal((await patch({ reasoningEffort: null })).json().chat.reasoningEffort, null);
|
||||
assert.equal((await patch({ model: "gpt-5.2" })).statusCode, 400);
|
||||
assert.equal((await patch({ reasoningEffort: "bogus" })).statusCode, 400);
|
||||
const catalog = (await app.inject({ method: "GET", url: "/v1/models" })).json();
|
||||
assert.deepEqual(catalog.providers.openai.reasoningCapabilities["gpt-5.2"].efforts, ["none", "low", "medium", "high", "xhigh"]);
|
||||
});
|
||||
|
||||
test("saved effort is inherited by older clients, overridden/reset explicitly, and never carried to another model", async () => {
|
||||
for (const streaming of [false, true]) {
|
||||
const chat = await prisma.chat.create({ data: { lastUsedProvider: "openai", lastUsedModel: "gpt-5.2", reasoningEffort: "high", enabledTools: [] } });
|
||||
const send = async (extra: object) => {
|
||||
const response = await app.inject({ method: "POST", url: `/v1/chat-completions${streaming ? "/stream" : ""}`,
|
||||
payload: { chatId: chat.id, provider: "openai", model: "gpt-5.2", messages: [{ role: "user", content: "Hello" }], ...extra } });
|
||||
assert.equal(response.statusCode, 200, response.body);
|
||||
assert.doesNotMatch(response.body, /event: error/);
|
||||
return requests.at(-1)!.body;
|
||||
};
|
||||
assert.equal((await send({})).reasoning_effort, "high");
|
||||
assert.equal((await send({ reasoningEffort: "low" })).reasoning_effort, "low");
|
||||
assert.equal((await prisma.chat.findUniqueOrThrow({ where: { id: chat.id } })).reasoningEffort, "low");
|
||||
assert.equal((await send({ reasoningEffort: null })).reasoning_effort, undefined);
|
||||
await send({ reasoningEffort: "high" });
|
||||
assert.equal((await send({ model: "gpt-5.1" })).reasoning_effort, undefined);
|
||||
assert.equal((await prisma.chat.findUniqueOrThrow({ where: { id: chat.id } })).reasoningEffort, null);
|
||||
}
|
||||
});
|
||||
|
||||
test("Quick Questions accept validated effort without inheriting or persisting chat settings", async () => {
|
||||
const count = await prisma.chat.count();
|
||||
for (const [model, effort, expected] of [["gpt-5.2", "high", "high"], ["gpt-5.1", "xhigh", undefined], ["chat-latest", "high", undefined], ["gpt-5.2", undefined, undefined]] as const) {
|
||||
const response = await app.inject({ method: "POST", url: "/v1/quick-questions/stream", payload: { provider: "openai", model, question: "Hello", enabledTools: [], reasoningEffort: effort } });
|
||||
assert.equal(response.statusCode, 200, response.body);
|
||||
assert.doesNotMatch(response.body, /event: error/);
|
||||
assert.equal(requests.at(-1)!.body.reasoning_effort, expected);
|
||||
}
|
||||
assert.equal(await prisma.chat.count(), count);
|
||||
});
|
||||
+1
-1
@@ -23,7 +23,7 @@ Configuration is environment-only (no in-app settings).
|
||||
|
||||
- `SYBIL_TUI_API_BASE_URL`: API base URL. Default: `http://127.0.0.1:8787`
|
||||
- `SYBIL_TUI_ADMIN_TOKEN`: optional bearer token for token-mode servers
|
||||
- `SYBIL_TUI_DEFAULT_PROVIDER`: `openai` | `anthropic` | `xai` | `hermes-agent` (default: `openai`)
|
||||
- `SYBIL_TUI_DEFAULT_PROVIDER`: `openai` | `anthropic` | `xai` | `gemini` (default: `openai`)
|
||||
- `SYBIL_TUI_DEFAULT_MODEL`: optional default model name
|
||||
- `SYBIL_TUI_SEARCH_NUM_RESULTS`: results per search run (default: `10`)
|
||||
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
import type { Provider } from "./types.js";
|
||||
|
||||
const PROVIDERS: Provider[] = ["openai", "anthropic", "xai", "gemini", "hermes-agent"];
|
||||
const PROVIDERS: Provider[] = ["openai", "anthropic", "xai", "gemini"];
|
||||
|
||||
function normalizeBaseUrl(value: string) {
|
||||
const trimmed = value.trim();
|
||||
|
||||
+5
-15
@@ -42,14 +42,12 @@ type ToolLogMetadata = {
|
||||
resultPreview?: string | null;
|
||||
};
|
||||
|
||||
const BASE_PROVIDERS: Provider[] = ["openai", "anthropic", "xai", "gemini"];
|
||||
const PROVIDERS: Provider[] = [...BASE_PROVIDERS, "hermes-agent"];
|
||||
const PROVIDERS: Provider[] = ["openai", "anthropic", "xai", "gemini"];
|
||||
const PROVIDER_FALLBACK_MODELS: Record<Provider, string[]> = {
|
||||
openai: ["gpt-4.1-mini"],
|
||||
anthropic: ["claude-3-5-sonnet-latest"],
|
||||
xai: ["grok-3-mini"],
|
||||
gemini: ["gemini-3.5-flash", "gemini-flash-latest"],
|
||||
"hermes-agent": ["hermes-agent"],
|
||||
};
|
||||
|
||||
const EMPTY_MODEL_CATALOG: ModelCatalogResponse["providers"] = {
|
||||
@@ -82,7 +80,6 @@ function getProviderLabel(provider: Provider | null | undefined) {
|
||||
if (provider === "anthropic") return "Anthropic";
|
||||
if (provider === "xai") return "xAI";
|
||||
if (provider === "gemini") return "Gemini";
|
||||
if (provider === "hermes-agent") return "Hermes Agent";
|
||||
return "";
|
||||
}
|
||||
|
||||
@@ -227,10 +224,6 @@ function getModelOptions(catalog: ModelCatalogResponse["providers"], provider: P
|
||||
return PROVIDER_FALLBACK_MODELS[provider];
|
||||
}
|
||||
|
||||
function getVisibleProviders(catalog: ModelCatalogResponse["providers"]) {
|
||||
return PROVIDERS.filter((provider) => provider !== "hermes-agent" || catalog[provider] !== undefined);
|
||||
}
|
||||
|
||||
function pickProviderModel(options: string[], preferred: string | null, fallback: string | null = null) {
|
||||
if (fallback && options.includes(fallback)) return fallback;
|
||||
if (preferred && options.includes(preferred)) return preferred;
|
||||
@@ -276,7 +269,6 @@ async function main() {
|
||||
anthropic: null,
|
||||
xai: null,
|
||||
gemini: null,
|
||||
"hermes-agent": null,
|
||||
};
|
||||
let model: string = config.defaultModel ?? pickProviderModel(getModelOptions(modelCatalog, provider), null);
|
||||
let errorMessage: string | null = null;
|
||||
@@ -509,7 +501,7 @@ async function main() {
|
||||
if (draftKind || selectedItem?.kind !== "chat") return;
|
||||
|
||||
const detailSelection =
|
||||
selectedChat?.id === selectedItem.id && selectedChat.lastUsedProvider && selectedChat.lastUsedModel?.trim()
|
||||
selectedChat?.id === selectedItem.id && selectedChat.lastUsedProvider && PROVIDERS.includes(selectedChat.lastUsedProvider) && selectedChat.lastUsedModel?.trim()
|
||||
? {
|
||||
provider: selectedChat.lastUsedProvider,
|
||||
model: selectedChat.lastUsedModel.trim(),
|
||||
@@ -518,7 +510,7 @@ async function main() {
|
||||
|
||||
const summary = getSelectedChatSummary();
|
||||
const summarySelection =
|
||||
summary?.lastUsedProvider && summary.lastUsedModel?.trim()
|
||||
summary?.lastUsedProvider && PROVIDERS.includes(summary.lastUsedProvider) && summary.lastUsedModel?.trim()
|
||||
? {
|
||||
provider: summary.lastUsedProvider,
|
||||
model: summary.lastUsedModel.trim(),
|
||||
@@ -1473,10 +1465,8 @@ async function main() {
|
||||
}
|
||||
|
||||
function cycleProvider() {
|
||||
const visibleProviders = getVisibleProviders(modelCatalog);
|
||||
const cycleProviders = visibleProviders.length ? visibleProviders : BASE_PROVIDERS;
|
||||
const currentIndex = Math.max(0, cycleProviders.indexOf(provider));
|
||||
const nextProvider: Provider = cycleProviders[(currentIndex + 1) % cycleProviders.length] ?? "openai";
|
||||
const currentIndex = Math.max(0, PROVIDERS.indexOf(provider));
|
||||
const nextProvider: Provider = PROVIDERS[(currentIndex + 1) % PROVIDERS.length] ?? "openai";
|
||||
provider = nextProvider;
|
||||
syncModelForProvider();
|
||||
updateUI();
|
||||
|
||||
+2
-2
@@ -1,4 +1,4 @@
|
||||
export type Provider = "openai" | "anthropic" | "xai" | "gemini" | "hermes-agent";
|
||||
export type Provider = "openai" | "anthropic" | "xai" | "gemini";
|
||||
|
||||
export type ProviderModelInfo = {
|
||||
models: string[];
|
||||
@@ -140,7 +140,7 @@ export type CompletionRequestMessage = {
|
||||
};
|
||||
|
||||
export type CompletionStreamHandlers = {
|
||||
onMeta?: (payload: { chatId: string; callId: string; provider: Provider; model: string }) => void;
|
||||
onMeta?: (payload: { chatId: string | null; callId: string | null; provider: Provider | "sybil-agent"; model: string; agentAside?: boolean }) => void;
|
||||
onToolCall?: (payload: ToolCallEvent) => void;
|
||||
onDelta?: (payload: { text: string }) => void;
|
||||
onDone?: (payload: { text: string; usage?: { inputTokens?: number; outputTokens?: number; totalTokens?: number } }) => void;
|
||||
|
||||
+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.
|
||||
|
||||
+115
-209
@@ -1,19 +1,19 @@
|
||||
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,
|
||||
getModelOptions, PROVIDERS, loadStoredModelPreferences, saveModelPreferences,
|
||||
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 { ReasoningEffortControl } from "@/components/ReasoningEffortControl";
|
||||
import { getReasoningCapabilities, loadReasoningPreferences, normalizeReasoningEffort, reasoningPreferenceKey, saveReasoningPreferences, type ReasoningEffort } from "@/lib/reasoning-effort";
|
||||
import type { TargetedTouchEvent } from "preact";
|
||||
import { getProviderLabel } from "@/lib/message-generation";
|
||||
import {
|
||||
Check,
|
||||
Bot,
|
||||
ChevronDown,
|
||||
GitFork,
|
||||
Globe2,
|
||||
LoaderCircle,
|
||||
@@ -35,9 +35,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 +148,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 +166,6 @@ type MobileWorkspaceSwipe = {
|
||||
direction: -1 | 1 | null;
|
||||
};
|
||||
|
||||
type QuickQuestionModelSelection = {
|
||||
provider: Provider;
|
||||
modelPreferences: ProviderModelPreferences;
|
||||
};
|
||||
|
||||
const EMPTY_ACTIVE_RUNS: ActiveRunsState = {
|
||||
chats: {},
|
||||
searches: {},
|
||||
@@ -406,22 +401,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 +494,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,11 +685,16 @@ 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];
|
||||
});
|
||||
const [quickProvider, setQuickProvider] = useState<Provider>(() => loadStoredQuickQuestionModelSelection().provider);
|
||||
const [reasoningPreferences, setReasoningPreferences] = useState(loadReasoningPreferences);
|
||||
const [reasoningPreferencesSaved, setReasoningPreferencesSaved] = useState(true);
|
||||
const [reasoningEffort, setReasoningEffort] = useState<ReasoningEffort | null>(() => loadReasoningPreferences()[reasoningPreferenceKey(provider, model)] ?? null);
|
||||
const [quickProviderModelPreferences, setQuickProviderModelPreferences] = useState<ProviderModelPreferences>(
|
||||
() => loadStoredQuickQuestionModelSelection().modelPreferences
|
||||
);
|
||||
@@ -877,6 +716,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);
|
||||
@@ -884,6 +724,7 @@ export default function App() {
|
||||
const [chatSettingsTitleDraft, setChatSettingsTitleDraft] = useState("");
|
||||
const [chatSettingsProviderDraft, setChatSettingsProviderDraft] = useState<Provider>("openai");
|
||||
const [chatSettingsModelDraft, setChatSettingsModelDraft] = useState("");
|
||||
const [chatSettingsReasoningDraft, setChatSettingsReasoningDraft] = useState<ReasoningEffort | null>(null);
|
||||
const [chatSettingsPromptDraft, setChatSettingsPromptDraft] = useState("");
|
||||
const [chatSettingsEnabledToolsDraft, setChatSettingsEnabledToolsDraft] = useState<string[]>([]);
|
||||
const [additionalSystemPrompt, setAdditionalSystemPrompt] = useState("");
|
||||
@@ -1048,6 +889,8 @@ export default function App() {
|
||||
setChatSettingsTitleDraft("");
|
||||
setChatSettingsProviderDraft("openai");
|
||||
setChatSettingsModelDraft("");
|
||||
setChatSettingsReasoningDraft(null);
|
||||
setReasoningEffort(null);
|
||||
setChatSettingsPromptDraft("");
|
||||
setChatSettingsEnabledToolsDraft([]);
|
||||
setAdditionalSystemPrompt("");
|
||||
@@ -1286,6 +1129,7 @@ export default function App() {
|
||||
|
||||
useEffect(() => {
|
||||
if (!isAuthenticated) {
|
||||
setIsAppSettingsOpen(false);
|
||||
hasSyncedSelectionHistoryRef.current = false;
|
||||
return;
|
||||
}
|
||||
@@ -1311,7 +1155,12 @@ export default function App() {
|
||||
() => getModelOptions(modelCatalog, chatSettingsProviderDraft),
|
||||
[chatSettingsProviderDraft, modelCatalog]
|
||||
);
|
||||
const providerOptions = useMemo(() => getVisibleProviders(modelCatalog), [modelCatalog]);
|
||||
const providerOptions = PROVIDERS;
|
||||
const chatSettingsReasoningCapabilities = getReasoningCapabilities(modelCatalog, chatSettingsProviderDraft, chatSettingsModelDraft);
|
||||
|
||||
useEffect(() => {
|
||||
setReasoningPreferencesSaved(saveReasoningPreferences(reasoningPreferences));
|
||||
}, [reasoningPreferences]);
|
||||
|
||||
useEffect(() => {
|
||||
if (model.trim()) return;
|
||||
@@ -1322,7 +1171,7 @@ export default function App() {
|
||||
|
||||
useEffect(() => {
|
||||
if (typeof window === "undefined") return;
|
||||
saveModelPreferences(providerModelPreferences);
|
||||
setModelPreferencesSaved(saveModelPreferences(providerModelPreferences));
|
||||
}, [providerModelPreferences]);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -1334,15 +1183,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(() => {
|
||||
@@ -1602,6 +1456,7 @@ export default function App() {
|
||||
if (!chat) return;
|
||||
setAdditionalSystemPrompt(chat.additionalSystemPrompt ?? "");
|
||||
setEnabledTools(normalizeEnabledTools(chat.enabledTools, availableChatTools));
|
||||
setReasoningEffort(chat.reasoningEffort ?? null);
|
||||
}, [availableChatTools, draftKind, selectedChat, selectedChatSummary, selectedItem]);
|
||||
|
||||
const selectedTitle = useMemo(() => {
|
||||
@@ -1653,6 +1508,9 @@ export default function App() {
|
||||
setSelectedSearch(null);
|
||||
setPendingAttachments([]);
|
||||
setDraftChatTitle("");
|
||||
const nextModel = pickProviderModel(getModelOptions(modelCatalog, provider), providerModelPreferences[provider]);
|
||||
setModel(nextModel);
|
||||
setReasoningEffort(reasoningPreferences[reasoningPreferenceKey(provider, nextModel)] ?? null);
|
||||
setAdditionalSystemPrompt("");
|
||||
setEnabledTools(getDefaultEnabledTools(availableChatTools));
|
||||
setIsChatSettingsOpen(false);
|
||||
@@ -1674,6 +1532,7 @@ export default function App() {
|
||||
isMobileSidebarOpen ||
|
||||
isQuickQuestionOpen ||
|
||||
isChatSettingsOpen ||
|
||||
isAppSettingsOpen ||
|
||||
renameChatDialog !== null
|
||||
) {
|
||||
return;
|
||||
@@ -1835,7 +1694,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 +1727,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);
|
||||
@@ -1908,6 +1767,7 @@ export default function App() {
|
||||
initiatedModel: updatedChat.initiatedModel,
|
||||
lastUsedProvider: updatedChat.lastUsedProvider,
|
||||
lastUsedModel: updatedChat.lastUsedModel,
|
||||
reasoningEffort: updatedChat.reasoningEffort,
|
||||
additionalSystemPrompt: updatedChat.additionalSystemPrompt,
|
||||
enabledTools: updatedChat.enabledTools,
|
||||
};
|
||||
@@ -1967,6 +1827,7 @@ export default function App() {
|
||||
setChatSettingsTitleDraft(getChatSettingsSeedTitle());
|
||||
setChatSettingsProviderDraft(provider);
|
||||
setChatSettingsModelDraft(model);
|
||||
setChatSettingsReasoningDraft(reasoningEffort);
|
||||
setChatSettingsPromptDraft(additionalSystemPrompt);
|
||||
setChatSettingsEnabledToolsDraft(normalizeEnabledTools(enabledTools, availableChatTools));
|
||||
setIsChatSettingsOpen(true);
|
||||
@@ -1979,9 +1840,19 @@ export default function App() {
|
||||
});
|
||||
};
|
||||
|
||||
const commitLocalChatSettings = (nextProvider: Provider, nextModel: string, nextPrompt: string, nextTools: string[], nextTitle: string) => {
|
||||
const changeChatSettingsModel = (nextProvider: Provider, nextModel: string) => {
|
||||
setChatSettingsProviderDraft(nextProvider);
|
||||
setChatSettingsModelDraft(nextModel.trim());
|
||||
setChatSettingsReasoningDraft(nextProvider === provider && nextModel.trim() === model.trim()
|
||||
? reasoningEffort : reasoningPreferences[reasoningPreferenceKey(nextProvider, nextModel)] ?? null);
|
||||
setChatSettingsError(null);
|
||||
};
|
||||
|
||||
const commitLocalChatSettings = (nextProvider: Provider, nextModel: string, nextPrompt: string, nextTools: string[], nextTitle: string, nextEffort: ReasoningEffort | null) => {
|
||||
setProvider(nextProvider);
|
||||
setModel(nextModel);
|
||||
setReasoningEffort(nextEffort);
|
||||
setReasoningPreferences((current) => ({ ...current, [reasoningPreferenceKey(nextProvider, nextModel)]: nextEffort }));
|
||||
setProviderModelPreferences((current) => ({
|
||||
...current,
|
||||
[nextProvider]: nextModel || null,
|
||||
@@ -2010,6 +1881,7 @@ export default function App() {
|
||||
}
|
||||
|
||||
const nextPrompt = chatSettingsPromptDraft.trim();
|
||||
const nextEffort = normalizeReasoningEffort(chatSettingsReasoningCapabilities, chatSettingsReasoningDraft);
|
||||
const nextTools = availableChatTools.length
|
||||
? normalizeEnabledTools(chatSettingsEnabledToolsDraft, availableChatTools)
|
||||
: chatSettingsEnabledToolsDraft;
|
||||
@@ -2021,6 +1893,9 @@ export default function App() {
|
||||
if (isExistingChat) {
|
||||
const updatedChat = await updateChatSettings(existingChatId, {
|
||||
title: nextTitle,
|
||||
provider: chatSettingsProviderDraft,
|
||||
model: nextModel,
|
||||
reasoningEffort: nextEffort,
|
||||
additionalSystemPrompt: nextPrompt || null,
|
||||
...(availableChatTools.length ? { enabledTools: nextTools } : {}),
|
||||
});
|
||||
@@ -2030,7 +1905,7 @@ export default function App() {
|
||||
setDraftKind("chat");
|
||||
}
|
||||
|
||||
commitLocalChatSettings(chatSettingsProviderDraft, nextModel, nextPrompt, nextTools, nextTitle);
|
||||
commitLocalChatSettings(chatSettingsProviderDraft, nextModel, nextPrompt, nextTools, nextTitle, nextEffort);
|
||||
setIsChatSettingsOpen(false);
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : String(err);
|
||||
@@ -2376,6 +2251,7 @@ export default function App() {
|
||||
|
||||
const handleSendChat = async (content: string, attachments: ChatAttachment[]): Promise<SidebarSelection> => {
|
||||
const selectedModel = model.trim();
|
||||
const selectedEffort = normalizeReasoningEffort(getReasoningCapabilities(modelCatalog, provider, selectedModel), reasoningEffort);
|
||||
if (!selectedModel) {
|
||||
throw new Error("No model available for selected provider");
|
||||
}
|
||||
@@ -2409,6 +2285,7 @@ export default function App() {
|
||||
...(draftChatTitle.trim() ? { title: draftChatTitle.trim() } : {}),
|
||||
provider,
|
||||
model: selectedModel,
|
||||
reasoningEffort: selectedEffort,
|
||||
...(additionalSystemPrompt.trim() ? { additionalSystemPrompt: additionalSystemPrompt.trim() } : {}),
|
||||
...(initialEnabledTools !== undefined ? { enabledTools: initialEnabledTools } : {}),
|
||||
});
|
||||
@@ -2438,6 +2315,7 @@ export default function App() {
|
||||
initiatedModel: chat.initiatedModel,
|
||||
lastUsedProvider: chat.lastUsedProvider,
|
||||
lastUsedModel: chat.lastUsedModel,
|
||||
reasoningEffort: chat.reasoningEffort,
|
||||
additionalSystemPrompt: chat.additionalSystemPrompt,
|
||||
enabledTools: chat.enabledTools,
|
||||
messages: [],
|
||||
@@ -2500,6 +2378,7 @@ export default function App() {
|
||||
clientRequestId,
|
||||
provider,
|
||||
model: selectedModel,
|
||||
reasoningEffort: selectedEffort,
|
||||
messages: requestMessages,
|
||||
},
|
||||
{
|
||||
@@ -3075,6 +2954,7 @@ export default function App() {
|
||||
initiatedModel: chat.initiatedModel,
|
||||
lastUsedProvider: chat.lastUsedProvider,
|
||||
lastUsedModel: chat.lastUsedModel,
|
||||
reasoningEffort: chat.reasoningEffort,
|
||||
additionalSystemPrompt: chat.additionalSystemPrompt,
|
||||
enabledTools: chat.enabledTools,
|
||||
messages: [],
|
||||
@@ -3237,6 +3117,7 @@ export default function App() {
|
||||
initiatedModel: chat.initiatedModel,
|
||||
lastUsedProvider: chat.lastUsedProvider,
|
||||
lastUsedModel: chat.lastUsedModel,
|
||||
reasoningEffort: chat.reasoningEffort,
|
||||
additionalSystemPrompt: chat.additionalSystemPrompt,
|
||||
enabledTools: chat.enabledTools,
|
||||
messages: [],
|
||||
@@ -3564,10 +3445,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 +3472,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 +3505,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 +3672,25 @@ 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 && reasoningPreferencesSaved}
|
||||
onRetrySave={() => {
|
||||
setModelPreferencesSaved(saveModelPreferences(providerModelPreferences));
|
||||
setReasoningPreferencesSaved(saveReasoningPreferences(reasoningPreferences));
|
||||
setQuickPreferencesSaved(saveQuickQuestionModelSelection({ provider: quickProvider, modelPreferences: quickProviderModelPreferences }));
|
||||
}}
|
||||
/> : null}
|
||||
{isChatSettingsOpen ? (
|
||||
<dialog
|
||||
ref={chatSettingsDialogRef}
|
||||
@@ -3879,10 +3791,8 @@ export default function App() {
|
||||
value={chatSettingsProviderDraft}
|
||||
onChange={(event) => {
|
||||
const nextProvider = event.currentTarget.value as Provider;
|
||||
setChatSettingsProviderDraft(nextProvider);
|
||||
const options = getModelOptions(modelCatalog, nextProvider);
|
||||
setChatSettingsModelDraft(pickProviderModel(options, providerModelPreferences[nextProvider]));
|
||||
setChatSettingsError(null);
|
||||
changeChatSettingsModel(nextProvider, pickProviderModel(options, providerModelPreferences[nextProvider]));
|
||||
}}
|
||||
disabled={isSavingChatSettings}
|
||||
>
|
||||
@@ -3902,13 +3812,19 @@ export default function App() {
|
||||
value={chatSettingsModelDraft}
|
||||
disabled={isSavingChatSettings}
|
||||
onChange={(nextModel) => {
|
||||
setChatSettingsModelDraft(nextModel.trim());
|
||||
setChatSettingsError(null);
|
||||
changeChatSettingsModel(chatSettingsProviderDraft, nextModel);
|
||||
}}
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<ReasoningEffortControl
|
||||
capabilities={chatSettingsReasoningCapabilities}
|
||||
value={chatSettingsReasoningDraft}
|
||||
onChange={setChatSettingsReasoningDraft}
|
||||
disabled={isSavingChatSettings}
|
||||
/>
|
||||
|
||||
<label className="block">
|
||||
<span className="mb-1.5 block text-xs font-semibold text-violet-100/72">Additional system prompt</span>
|
||||
<Textarea
|
||||
@@ -4130,10 +4046,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 +4061,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>
|
||||
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
import { normalizeReasoningEffort, reasoningEffortLabel, type ReasoningCapabilities, type ReasoningEffort } from "@/lib/reasoning-effort";
|
||||
|
||||
export function ReasoningEffortControl({ capabilities, value, onChange, disabled }: {
|
||||
capabilities: ReasoningCapabilities | null;
|
||||
value: ReasoningEffort | null;
|
||||
onChange: (effort: ReasoningEffort | null) => void;
|
||||
disabled?: boolean;
|
||||
}) {
|
||||
const effort = normalizeReasoningEffort(capabilities, value);
|
||||
const label = effort ? reasoningEffortLabel(effort)
|
||||
: `Model default${capabilities?.defaultEffort ? ` (${reasoningEffortLabel(capabilities.defaultEffort)})` : ""}`;
|
||||
return (
|
||||
<section className="rounded-lg border border-violet-300/18 bg-background/44 px-3 py-3">
|
||||
<div className="flex flex-wrap items-center justify-between gap-2">
|
||||
<label htmlFor="chat-reasoning-effort" className="text-xs font-semibold text-violet-100/72">Reasoning effort</label>
|
||||
<output htmlFor="chat-reasoning-effort" className="text-sm text-violet-50">{label}</output>
|
||||
</div>
|
||||
{capabilities ? (
|
||||
<>
|
||||
<input
|
||||
id="chat-reasoning-effort"
|
||||
type="range"
|
||||
min={0}
|
||||
max={capabilities.efforts.length}
|
||||
step={1}
|
||||
value={effort ? capabilities.efforts.indexOf(effort) + 1 : 0}
|
||||
onInput={(event) => onChange(capabilities.efforts[Number(event.currentTarget.value) - 1] ?? null)}
|
||||
aria-valuetext={label}
|
||||
aria-describedby="chat-reasoning-help"
|
||||
disabled={disabled}
|
||||
className="mt-2 h-8 w-full cursor-pointer accent-violet-400 disabled:cursor-default disabled:opacity-50"
|
||||
/>
|
||||
<div className="flex justify-between text-xs text-muted-foreground" aria-hidden="true">
|
||||
<span>Model default</span>
|
||||
<span>{reasoningEffortLabel(capabilities.efforts[capabilities.efforts.length - 1])}</span>
|
||||
</div>
|
||||
<p id="chat-reasoning-help" className="mt-2 text-xs text-muted-foreground">Higher effort gives the model more time to reason and can increase response time and cost.</p>
|
||||
</>
|
||||
) : (
|
||||
<p className="mt-2 text-xs text-muted-foreground">Reasoning settings aren’t available for this model. It will use its own defaults.</p>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -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,60 @@
|
||||
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, PROVIDERS, 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 = PROVIDERS;
|
||||
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">
|
||||
{providers.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>;
|
||||
}
|
||||
@@ -9,7 +9,7 @@ import { shouldRequestChatTitle } from "@/lib/chat-forking";
|
||||
import type { SidebarSelection } from "@/lib/sidebar-selection";
|
||||
import {
|
||||
buildCompletionMessages, buildWorkspaceUrl, createClientRequestId, EMPTY_MODEL_CATALOG,
|
||||
getModelOptions, getVisibleProviders, hasNewPersistedUserMessage, isRecoverableStreamDisconnect,
|
||||
getModelOptions, PROVIDERS, hasNewPersistedUserMessage, isRecoverableStreamDisconnect,
|
||||
loadStoredModelPreferences, pickProviderModel, readSidebarSelectionFromUrl, saveModelPreferences,
|
||||
} from "@/lib/workspace-domain";
|
||||
|
||||
@@ -293,7 +293,7 @@ export function useLiteWorkspace(isAuthenticated: boolean, onAuthFailure: (messa
|
||||
: selection?.kind === "search" ? activeRuns.searches.includes(selection.id) : false;
|
||||
return {
|
||||
selection, draftKind, items, chat, search, provider, model,
|
||||
providerOptions: getVisibleProviders(catalog), modelOptions: getModelOptions(catalog, provider),
|
||||
providerOptions: PROVIDERS, modelOptions: getModelOptions(catalog, provider),
|
||||
isLoading, isBusy: isSending || selectedRun, isSending, error, activeRuns,
|
||||
selectItem, newChat: () => startDraft("chat"), newSearch: () => startDraft("search"),
|
||||
setProvider, setModel, send, refresh,
|
||||
|
||||
+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;
|
||||
}
|
||||
|
||||
|
||||
+13
-3
@@ -1,3 +1,5 @@
|
||||
import type { ReasoningCapabilities, ReasoningEffort } from "./reasoning-effort";
|
||||
|
||||
export type ChatSummary = {
|
||||
id: string;
|
||||
title: string | null;
|
||||
@@ -11,6 +13,7 @@ export type ChatSummary = {
|
||||
initiatedModel: string | null;
|
||||
lastUsedProvider: Provider | null;
|
||||
lastUsedModel: string | null;
|
||||
reasoningEffort?: ReasoningEffort | null;
|
||||
additionalSystemPrompt: string | null;
|
||||
enabledTools: string[] | null;
|
||||
};
|
||||
@@ -72,6 +75,7 @@ export type ChatDetail = {
|
||||
initiatedModel: string | null;
|
||||
lastUsedProvider: Provider | null;
|
||||
lastUsedModel: string | null;
|
||||
reasoningEffort?: ReasoningEffort | null;
|
||||
additionalSystemPrompt: string | null;
|
||||
enabledTools: string[] | null;
|
||||
messages: Message[];
|
||||
@@ -156,12 +160,14 @@ export type CompletionRequestMessage = {
|
||||
attachments?: ChatAttachment[];
|
||||
};
|
||||
|
||||
export type Provider = "openai" | "anthropic" | "xai" | "gemini" | "hermes-agent";
|
||||
export type Provider = "openai" | "anthropic" | "xai" | "gemini";
|
||||
export type CompletionProvider = Provider | "sybil-agent";
|
||||
|
||||
export type ProviderModelInfo = {
|
||||
models: string[];
|
||||
loadedAt: string | null;
|
||||
error: string | null;
|
||||
reasoningCapabilities?: Record<string, ReasoningCapabilities>;
|
||||
};
|
||||
|
||||
export type ModelCatalogResponse = {
|
||||
@@ -187,7 +193,7 @@ type CompletionResponse = {
|
||||
};
|
||||
|
||||
type CompletionStreamHandlers = {
|
||||
onMeta?: (payload: { chatId: string | null; callId: string | null; provider: Provider; model: string; agentAside?: boolean }) => void;
|
||||
onMeta?: (payload: { chatId: string | null; callId: string | null; provider: CompletionProvider; model: string; agentAside?: boolean }) => void;
|
||||
onToolCall?: (payload: ToolCallEvent) => void;
|
||||
onDelta?: (payload: { text: string }) => void;
|
||||
onDone?: (payload: { text: string; usage?: { inputTokens?: number; outputTokens?: number; totalTokens?: number } }) => void;
|
||||
@@ -206,6 +212,7 @@ type CreateChatRequest = {
|
||||
title?: string;
|
||||
provider?: Provider;
|
||||
model?: string;
|
||||
reasoningEffort?: ReasoningEffort | null;
|
||||
additionalSystemPrompt?: string;
|
||||
enabledTools?: string[];
|
||||
messages?: CompletionRequestMessage[];
|
||||
@@ -344,7 +351,7 @@ export async function updateChatStar(chatId: string, starred: boolean) {
|
||||
|
||||
export async function updateChatSettings(
|
||||
chatId: string,
|
||||
body: { title?: string; additionalSystemPrompt?: string | null; enabledTools?: string[] }
|
||||
body: { title?: string; provider?: Provider; model?: string; reasoningEffort?: ReasoningEffort | null; additionalSystemPrompt?: string | null; enabledTools?: string[] }
|
||||
) {
|
||||
const data = await api<{ chat: ChatSummary }>(`/v1/chats/${chatId}`, {
|
||||
method: "PATCH",
|
||||
@@ -568,6 +575,7 @@ export async function runCompletion(body: {
|
||||
chatId: string;
|
||||
provider: Provider;
|
||||
model: string;
|
||||
reasoningEffort?: ReasoningEffort | null;
|
||||
messages: CompletionRequestMessage[];
|
||||
additionalSystemPrompt?: string;
|
||||
enabledTools?: string[];
|
||||
@@ -586,6 +594,7 @@ export async function runCompletionStream(
|
||||
clientRequestId?: string;
|
||||
provider: Provider;
|
||||
model: string;
|
||||
reasoningEffort?: ReasoningEffort | null;
|
||||
messages: CompletionRequestMessage[];
|
||||
additionalSystemPrompt?: string;
|
||||
enabledTools?: string[];
|
||||
@@ -616,6 +625,7 @@ export async function runQuickQuestionStream(
|
||||
body: {
|
||||
provider: Provider;
|
||||
model: string;
|
||||
reasoningEffort?: ReasoningEffort | null;
|
||||
question: string;
|
||||
},
|
||||
handlers: CompletionStreamHandlers,
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { Provider } from "./api";
|
||||
import { PROVIDERS } from "./workspace-domain.ts";
|
||||
|
||||
type PersistedChatModel = {
|
||||
lastUsedProvider: Provider | null;
|
||||
@@ -11,7 +12,7 @@ export type ChatModelSelection = {
|
||||
};
|
||||
|
||||
export function getChatModelSelection(chat: PersistedChatModel | null): ChatModelSelection | null {
|
||||
if (!chat?.lastUsedProvider || !chat.lastUsedModel?.trim()) return null;
|
||||
if (!chat?.lastUsedProvider || !PROVIDERS.includes(chat.lastUsedProvider) || !chat.lastUsedModel?.trim()) return null;
|
||||
return {
|
||||
provider: chat.lastUsedProvider,
|
||||
model: chat.lastUsedModel.trim(),
|
||||
|
||||
@@ -5,7 +5,6 @@ export function getProviderLabel(provider: unknown) {
|
||||
if (provider === "anthropic") return "Anthropic";
|
||||
if (provider === "xai") return "xAI";
|
||||
if (provider === "gemini") return "Gemini";
|
||||
if (provider === "hermes-agent") return "Hermes Agent";
|
||||
return "";
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
import type { ModelCatalogResponse, Provider } from "./api";
|
||||
|
||||
export const REASONING_EFFORTS = ["none", "minimal", "low", "medium", "high", "xhigh", "max"] as const;
|
||||
export type ReasoningEffort = (typeof REASONING_EFFORTS)[number];
|
||||
export type ReasoningCapabilities = { efforts: ReasoningEffort[]; defaultEffort: ReasoningEffort | null };
|
||||
export type ReasoningPreferences = Record<string, ReasoningEffort | null>;
|
||||
export const REASONING_PREFERENCES_STORAGE_KEY = "sybil:reasoningEffortByModel";
|
||||
|
||||
export function reasoningPreferenceKey(provider: Provider, model: string) {
|
||||
return JSON.stringify([provider, model.trim()]);
|
||||
}
|
||||
|
||||
export function getReasoningCapabilities(catalog: ModelCatalogResponse["providers"], provider: Provider, model: string): ReasoningCapabilities | null {
|
||||
// Missing/old catalogs and unrecognized values must fail closed.
|
||||
const entry = catalog[provider]?.reasoningCapabilities?.[model.trim()];
|
||||
if (!entry || !Array.isArray(entry.efforts) || !entry.efforts.length
|
||||
|| !entry.efforts.every((effort) => REASONING_EFFORTS.includes(effort))
|
||||
|| new Set(entry.efforts).size !== entry.efforts.length
|
||||
|| (entry.defaultEffort !== null && !entry.efforts.includes(entry.defaultEffort))) return null;
|
||||
return entry;
|
||||
}
|
||||
|
||||
export function normalizeReasoningEffort(capabilities: ReasoningCapabilities | null, effort: unknown): ReasoningEffort | null {
|
||||
return capabilities?.efforts.includes(effort as ReasoningEffort) ? effort as ReasoningEffort : null;
|
||||
}
|
||||
|
||||
export function reasoningEffortLabel(effort: ReasoningEffort) {
|
||||
if (effort === "xhigh") return "Extra high";
|
||||
return effort.charAt(0).toUpperCase() + effort.slice(1);
|
||||
}
|
||||
|
||||
export function loadReasoningPreferences(): ReasoningPreferences {
|
||||
try {
|
||||
const parsed: unknown = JSON.parse(window.localStorage.getItem(REASONING_PREFERENCES_STORAGE_KEY) ?? "{}");
|
||||
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return {};
|
||||
return Object.fromEntries(Object.entries(parsed).filter(([, value]) => value === null || REASONING_EFFORTS.includes(value)));
|
||||
} catch { return {}; }
|
||||
}
|
||||
|
||||
export function saveReasoningPreferences(preferences: ReasoningPreferences) {
|
||||
try { window.localStorage.setItem(REASONING_PREFERENCES_STORAGE_KEY, JSON.stringify(preferences)); return true; }
|
||||
catch { return false; }
|
||||
}
|
||||
@@ -36,7 +36,6 @@ export const PROVIDER_FALLBACK_MODELS: Record<Provider, string[]> = {
|
||||
anthropic: ["claude-3-5-sonnet-latest"],
|
||||
xai: ["grok-3-mini"],
|
||||
gemini: ["gemini-3.5-flash", "gemini-flash-latest"],
|
||||
"hermes-agent": ["hermes-agent"],
|
||||
};
|
||||
|
||||
export const EMPTY_MODEL_CATALOG: ModelCatalogResponse["providers"] = {
|
||||
@@ -46,19 +45,19 @@ export const EMPTY_MODEL_CATALOG: ModelCatalogResponse["providers"] = {
|
||||
gemini: { models: [], loadedAt: null, error: null },
|
||||
};
|
||||
|
||||
export const BASE_PROVIDERS: Provider[] = ["openai", "anthropic", "xai", "gemini"];
|
||||
export const ALL_PROVIDERS: Provider[] = [...BASE_PROVIDERS, "hermes-agent"];
|
||||
export const PROVIDERS: Provider[] = ["openai", "anthropic", "xai", "gemini"];
|
||||
|
||||
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,
|
||||
anthropic: null,
|
||||
xai: null,
|
||||
gemini: null,
|
||||
"hermes-agent": null,
|
||||
};
|
||||
|
||||
export function createClientRequestId() {
|
||||
@@ -95,10 +94,6 @@ export function getModelOptions(catalog: ModelCatalogResponse["providers"], prov
|
||||
return PROVIDER_FALLBACK_MODELS[provider];
|
||||
}
|
||||
|
||||
export function getVisibleProviders(catalog: ModelCatalogResponse["providers"]) {
|
||||
return ALL_PROVIDERS.filter((provider) => provider !== "hermes-agent" || catalog[provider] !== undefined);
|
||||
}
|
||||
|
||||
export function loadStoredModelPreferences() {
|
||||
if (typeof window === "undefined") return EMPTY_MODEL_PREFERENCES;
|
||||
try {
|
||||
@@ -111,7 +106,7 @@ export function loadStoredModelPreferences() {
|
||||
}
|
||||
|
||||
export function normalizeStoredProvider(value: unknown): Provider {
|
||||
return value === "anthropic" || value === "xai" || value === "gemini" || value === "openai" || value === "hermes-agent"
|
||||
return value === "anthropic" || value === "xai" || value === "gemini" || value === "openai"
|
||||
? value
|
||||
: "openai";
|
||||
}
|
||||
@@ -124,8 +119,6 @@ export function normalizeStoredModelPreferences(value: unknown): ProviderModelPr
|
||||
anthropic: typeof parsed.anthropic === "string" && parsed.anthropic.trim() ? parsed.anthropic.trim() : null,
|
||||
xai: typeof parsed.xai === "string" && parsed.xai.trim() ? parsed.xai.trim() : null,
|
||||
gemini: typeof parsed.gemini === "string" && parsed.gemini.trim() ? parsed.gemini.trim() : null,
|
||||
"hermes-agent":
|
||||
typeof parsed["hermes-agent"] === "string" && parsed["hermes-agent"].trim() ? parsed["hermes-agent"].trim() : null,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -155,6 +148,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,328 @@
|
||||
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", "retired-provider": "old-model" }));
|
||||
localStorage.setItem("sybil:quickQuestionModelSelection", JSON.stringify({ provider: "xai", modelPreferences: { xai: "legacy-quick", openai: "quick-original", "retired-provider": "old-model" } }));
|
||||
}
|
||||
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 }, "retired-provider": { models: ["old-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.deepEqual(await quickProvider.locator("option").evaluateAll(options => options.map(option => option.value)), ["openai", "anthropic", "xai", "gemini"]);
|
||||
assert.equal(await settings.getByRole("combobox").count(), 6, "only four chat models and the two Quick Questions controls");
|
||||
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.deepEqual(Object.keys(stored.chats), ["openai", "anthropic", "xai", "gemini"]);
|
||||
assert.equal(stored.quick.provider, "openai");
|
||||
assert.equal(stored.quick.modelPreferences.xai, "legacy-quick");
|
||||
assert.deepEqual(Object.keys(stored.quick.modelPreferences), ["openai", "anthropic", "xai", "gemini"]);
|
||||
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();
|
||||
}
|
||||
@@ -18,6 +18,12 @@ test("chat model selections are normalized from persisted metadata", () => {
|
||||
);
|
||||
});
|
||||
|
||||
test("unsupported historical providers never restore an active model selection", () => {
|
||||
for (const provider of ["retired-provider", "sybil-agent", null]) {
|
||||
assert.equal(getChatModelSelection({ lastUsedProvider: provider, lastUsedModel: "archived-model" }), null);
|
||||
}
|
||||
});
|
||||
|
||||
test("unrelated chat updates do not change the model synchronization key", () => {
|
||||
const beforeSettingsSave = getChatModelSelection({
|
||||
lastUsedProvider: "openai",
|
||||
|
||||
@@ -0,0 +1,144 @@
|
||||
import assert from "node:assert/strict";
|
||||
|
||||
// Run against a local production preview; all API/socket traffic is mocked.
|
||||
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"].includes(target.hostname));
|
||||
const browser = await chromium.launch({ headless: true, executablePath: process.env.CHROME_EXECUTABLE || undefined,
|
||||
...(process.env.BROWSER_NO_SANDBOX === "1" ? { args: ["--no-sandbox"] } : {}) });
|
||||
const date = "2026-11-15T12:00:00Z";
|
||||
const capabilities = {
|
||||
"gpt-5.2": { efforts: ["none", "low", "medium", "high", "xhigh"], defaultEffort: "none" },
|
||||
"gpt-6.1-sol": { efforts: ["low", "medium", "high", "xhigh", "max"], defaultEffort: "medium" },
|
||||
};
|
||||
|
||||
async function fixture(viewport, withCapabilities = true) {
|
||||
const context = await browser.newContext({ viewport, isMobile: viewport.width < 768, hasTouch: viewport.width < 768 });
|
||||
await context.addInitScript(() => {
|
||||
localStorage.setItem("sybil_admin_token", "fixture-token");
|
||||
localStorage.setItem("sybil:ui-mode", "full");
|
||||
});
|
||||
const chat = { id: "reasoning-chat", title: "Reasoning fixture", createdAt: date, updatedAt: date,
|
||||
parentChatId: null, titleGenerationPending: false, starred: false, starredAt: null,
|
||||
initiatedProvider: "openai", initiatedModel: "gpt-5.2", lastUsedProvider: "openai", lastUsedModel: "gpt-5.2",
|
||||
additionalSystemPrompt: null, enabledTools: [], reasoningEffort: null, messages: [] };
|
||||
const chats = new Map([[chat.id, chat]]);
|
||||
const writes = [], errors = [];
|
||||
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();
|
||||
const body = request.method() === "GET" ? null : request.postDataJSON();
|
||||
if (body) writes.push({ path, body });
|
||||
let value = {};
|
||||
const id = path.match(/\/chats\/([^/]+)$/)?.[1];
|
||||
if (path.endsWith("/auth/session")) value = { mode: "token", authenticated: true };
|
||||
else if (path.endsWith("/workspace-items")) value = { items: [...chats.values()].map(chat => ({ ...chat, type: "chat" })) };
|
||||
else if (path.endsWith("/models")) value = { providers: { openai: { models: Object.keys(capabilities), loadedAt: date, error: null,
|
||||
...(withCapabilities ? { reasoningCapabilities: capabilities } : {}) }, anthropic: { models: ["claude-fixture"], reasoningCapabilities: {} } } };
|
||||
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: { state: "idle", isThinking: false, tools: [], queuedMessages: [] }, protocol: "pi-room.v1", websocket: "/v1/agent/ws" };
|
||||
else if (path.endsWith("/read-state")) value = { sourceId: "fixture", cursor: "0", updatedAt: null };
|
||||
else if (path.endsWith("/push/config")) value = { enabled: false };
|
||||
else if (path.endsWith("/chats") && body) {
|
||||
const created = { ...chat, id: `new-${chats.size}`, title: body.title || "New chat", initiatedProvider: body.provider,
|
||||
initiatedModel: body.model, lastUsedProvider: body.provider, lastUsedModel: body.model, reasoningEffort: body.reasoningEffort ?? null };
|
||||
chats.set(created.id, created);
|
||||
value = { chat: created };
|
||||
} else if (id && chats.has(id)) {
|
||||
const current = chats.get(id);
|
||||
if (request.method() === "PATCH") Object.assign(current, body, { lastUsedProvider: body.provider ?? current.lastUsedProvider, lastUsedModel: body.model ?? current.lastUsedModel });
|
||||
value = { chat: current };
|
||||
} else if (path.endsWith("/chat-completions/stream")) {
|
||||
const current = chats.get(body.chatId);
|
||||
current.messages = [{ id: "answer", role: "assistant", content: "Fixture answer.", createdAt: date, metadata: null }];
|
||||
return route.fulfill({ contentType: "text/event-stream", body: [
|
||||
["meta", { chatId: current.id, callId: "call", provider: body.provider, model: body.model }],
|
||||
["delta", { text: "Fixture answer." }], ["done", { text: "Fixture answer." }],
|
||||
].map(([event, data]) => `event: ${event}\ndata: ${JSON.stringify(data)}\n\n`).join("") });
|
||||
}
|
||||
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 dialog = page.getByRole("dialog", { name: "Chat settings", exact: true });
|
||||
const slider = dialog.getByRole("slider", { name: "Reasoning effort" });
|
||||
const open = async () => { await page.getByRole("button", { name: "Open chat settings", exact: true }).click(); await dialog.waitFor(); };
|
||||
const changeModel = async model => { const input = dialog.getByRole("combobox", { name: "Model", exact: true }); await input.fill(model); await input.press("Enter"); };
|
||||
const save = async () => { await dialog.getByRole("button", { name: "Save", exact: true }).click(); await dialog.waitFor({ state: "hidden" }); };
|
||||
return { context, page, dialog, slider, open, changeModel, save, chat, writes, errors };
|
||||
}
|
||||
|
||||
try {
|
||||
for (const viewport of [{ width: 1280, height: 900 }, { width: 390, height: 844 }]) {
|
||||
const f = await fixture(viewport);
|
||||
const { page, dialog, slider, chat, writes } = f;
|
||||
await f.open();
|
||||
assert.equal(await slider.getAttribute("aria-valuetext"), "Model default (None)");
|
||||
await slider.press("End");
|
||||
await slider.press("ArrowLeft");
|
||||
assert.equal(await slider.getAttribute("aria-valuetext"), "High");
|
||||
await dialog.getByRole("button", { name: "Cancel", exact: true }).click();
|
||||
assert.equal(writes.filter(write => write.path.endsWith(`/chats/${chat.id}`)).length, 0);
|
||||
await f.open();
|
||||
assert.equal(await slider.getAttribute("aria-valuetext"), "Model default (None)");
|
||||
await slider.press("End");
|
||||
await slider.press("ArrowLeft");
|
||||
await f.save();
|
||||
assert.equal(chat.reasoningEffort, "high");
|
||||
assert.equal(writes.at(-1).body.model, "gpt-5.2");
|
||||
await page.reload({ waitUntil: "networkidle" });
|
||||
await f.open();
|
||||
assert.equal(await slider.getAttribute("aria-valuetext"), "High");
|
||||
await f.changeModel("gpt-6.1-sol");
|
||||
assert.equal(await slider.getAttribute("aria-valuetext"), "Model default (Medium)");
|
||||
await slider.press("Home");
|
||||
await slider.press("ArrowRight");
|
||||
assert.equal(await slider.getAttribute("aria-valuetext"), "Low"); // no unsupported None/Minimal
|
||||
await f.changeModel("gpt-5.2-pro");
|
||||
assert.equal(await slider.count(), 0);
|
||||
await dialog.getByText(/Reasoning settings aren’t available/).waitFor();
|
||||
await f.changeModel("gpt-5.2");
|
||||
assert.equal(await slider.getAttribute("aria-valuetext"), "High");
|
||||
await dialog.getByRole("combobox", { name: "Provider", exact: true }).selectOption("anthropic");
|
||||
assert.equal(await slider.count(), 0);
|
||||
await dialog.getByRole("button", { name: "Cancel", exact: true }).click();
|
||||
await page.keyboard.press("Control+j");
|
||||
await f.open();
|
||||
assert.equal(await slider.getAttribute("aria-valuetext"), "High");
|
||||
const bounds = await dialog.boundingBox();
|
||||
assert.ok(bounds.x >= 0 && bounds.x + bounds.width <= viewport.width + 1);
|
||||
if (process.env.REASONING_SCREENSHOT_DIR) await page.screenshot({ path: `${process.env.REASONING_SCREENSHOT_DIR}/reasoning-${viewport.width}.png` });
|
||||
await f.save();
|
||||
const composer = page.locator("#composer-input");
|
||||
await composer.fill("Test remembered effort");
|
||||
const submitted = page.waitForResponse(response => response.url().endsWith("/chat-completions/stream"));
|
||||
await composer.press("Enter");
|
||||
await submitted;
|
||||
assert.equal(writes.findLast(write => write.path.endsWith("/chats")).body.reasoningEffort, "high");
|
||||
assert.equal(writes.findLast(write => write.path.endsWith("/chat-completions/stream")).body.reasoningEffort, "high");
|
||||
await page.getByText("Fixture answer.", { exact: true }).waitFor();
|
||||
await f.open();
|
||||
await slider.press("Home");
|
||||
await f.save();
|
||||
assert.equal(writes.findLast(write => /\/chats\/[^/]+$/.test(write.path)).body.reasoningEffort, null);
|
||||
assert.deepEqual(f.errors, []);
|
||||
await f.context.close();
|
||||
}
|
||||
const oldServer = await fixture({ width: 1280, height: 900 }, false);
|
||||
await oldServer.open();
|
||||
assert.equal(await oldServer.slider.count(), 0);
|
||||
await oldServer.dialog.getByText(/Reasoning settings aren’t available/).waitFor();
|
||||
await oldServer.save();
|
||||
assert.equal(oldServer.chat.reasoningEffort, null);
|
||||
assert.deepEqual(oldServer.errors, []);
|
||||
await oldServer.context.close();
|
||||
console.log("Reasoning settings browser checks passed (desktop, mobile, missing capabilities).");
|
||||
} 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");
|
||||
|
||||
@@ -3,7 +3,7 @@ import test from "node:test";
|
||||
import { getMessageGenerationLabel } from "../src/lib/message-generation.ts";
|
||||
|
||||
test("reply labels use the recorded provider and model", () => {
|
||||
for (const [provider, label] of [["openai", "OpenAI"], ["anthropic", "Anthropic"], ["xai", "xAI"], ["gemini", "Gemini"], ["hermes-agent", "Hermes Agent"]]) {
|
||||
for (const [provider, label] of [["openai", "OpenAI"], ["anthropic", "Anthropic"], ["xai", "xAI"], ["gemini", "Gemini"]]) {
|
||||
assert.equal(getMessageGenerationLabel({ role: "assistant", metadata: { generation: { provider, model: "original-model" } } }), `${label} · original-model`);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { getReasoningCapabilities, loadReasoningPreferences, normalizeReasoningEffort, reasoningPreferenceKey, saveReasoningPreferences } from "../src/lib/reasoning-effort.ts";
|
||||
|
||||
const capabilities = { efforts: ["none", "low", "medium", "high", "xhigh"], defaultEffort: "none" };
|
||||
const catalog = { openai: { reasoningCapabilities: { "gpt-5.2": capabilities } } };
|
||||
|
||||
test("capabilities come only from the selected provider/model and a valid catalog entry", () => {
|
||||
assert.deepEqual(getReasoningCapabilities(catalog, "openai", " gpt-5.2 "), capabilities);
|
||||
for (const [data, provider, model] of [[{}, "openai", "gpt-5.2"], [catalog, "xai", "gpt-5.2"], [catalog, "openai", "gpt-5.2-new"]]) {
|
||||
assert.equal(getReasoningCapabilities(data, provider, model), null);
|
||||
}
|
||||
for (const entry of [{}, { efforts: [] }, { efforts: ["future"], defaultEffort: "future" }, { efforts: ["high"], defaultEffort: "none" }]) {
|
||||
assert.equal(getReasoningCapabilities({ openai: { reasoningCapabilities: { model: entry } } }, "openai", "model"), null);
|
||||
}
|
||||
assert.equal(normalizeReasoningEffort(capabilities, "xhigh"), "xhigh");
|
||||
assert.equal(normalizeReasoningEffort(capabilities, "max"), null);
|
||||
assert.equal(normalizeReasoningEffort(null, "high"), null);
|
||||
assert.equal(normalizeReasoningEffort(capabilities, null), null);
|
||||
});
|
||||
|
||||
test("browser memory is per provider/model and survives corrupt or unavailable storage", (t) => {
|
||||
const original = globalThis.window;
|
||||
t.after(() => { globalThis.window = original; });
|
||||
let stored = "{}";
|
||||
globalThis.window = { localStorage: { getItem: () => stored, setItem: (_, value) => { stored = value; } } };
|
||||
const key = reasoningPreferenceKey("openai", "gpt-5.2");
|
||||
assert.notEqual(key, reasoningPreferenceKey("xai", "gpt-5.2"));
|
||||
assert.notEqual(key, reasoningPreferenceKey("openai", "gpt-5.1"));
|
||||
assert.equal(saveReasoningPreferences({ [key]: "high" }), true);
|
||||
assert.deepEqual(loadReasoningPreferences(), { [key]: "high" });
|
||||
stored = JSON.stringify({ [key]: "future", other: null });
|
||||
assert.deepEqual(loadReasoningPreferences(), { other: null });
|
||||
stored = "broken JSON";
|
||||
assert.deepEqual(loadReasoningPreferences(), {});
|
||||
globalThis.window = { get localStorage() { throw new Error("blocked"); } };
|
||||
assert.deepEqual(loadReasoningPreferences(), {});
|
||||
assert.equal(saveReasoningPreferences({ [key]: "high" }), false);
|
||||
});
|
||||
@@ -1,9 +1,10 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import {
|
||||
buildCompletionMessages, buildWorkspaceUrl, getModelOptions, getVisibleProviders,
|
||||
buildCompletionMessages, buildWorkspaceUrl, getModelOptions, PROVIDERS, normalizeStoredProvider,
|
||||
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 };
|
||||
@@ -37,12 +38,13 @@ test("reconciliation recognizes only a new matching persisted user turn", () =>
|
||||
});
|
||||
|
||||
test("model policy preserves custom selections and uses advertised provider models", () => {
|
||||
const catalog = { openai: { models: ["server-model"] }, "hermes-agent": { models: ["hermes"] } };
|
||||
const catalog = { openai: { models: ["server-model"] } };
|
||||
assert.deepEqual(getModelOptions(catalog, "openai"), ["server-model"]);
|
||||
assert.equal(pickProviderModel(["server-model"], " custom-model "), "custom-model");
|
||||
assert.equal(pickProviderModel(["server-model"], null), "server-model");
|
||||
assert.ok(getVisibleProviders(catalog).includes("hermes-agent"));
|
||||
assert.ok(!getVisibleProviders({}).includes("hermes-agent"));
|
||||
assert.deepEqual(PROVIDERS, ["openai", "anthropic", "xai", "gemini"]);
|
||||
assert.equal(normalizeStoredProvider("retired-provider"), "openai");
|
||||
assert.deepEqual(Object.keys(normalizeStoredModelPreferences({ "retired-provider": "old-model" })), PROVIDERS);
|
||||
assert.equal(normalizeStoredModelPreferences({ openai: " x ", xai: 123 }).openai, "x");
|
||||
assert.equal(normalizeStoredModelPreferences({ xai: 123 }).xai, null);
|
||||
});
|
||||
@@ -61,5 +63,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