Compare commits

..
119 changed files with 6569 additions and 949 deletions
+1
View File
@@ -31,6 +31,7 @@ RUN apt-get update \
RUN npm ci --omit=dev --no-audit --no-fund
COPY --from=server-build /app/server/dist ./dist
COPY server/src/llm/pdf-text-worker.mjs ./dist/llm/pdf-text-worker.mjs
ENV NODE_ENV=production
ENV HOST=0.0.0.0
-3
View File
@@ -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}
+40 -17
View File
@@ -25,6 +25,7 @@ Chat upload limits:
- Response: `{ "authenticated": true, "mode": "open" | "token" }`
- In token mode, a missing bearer token returns `401` (`missing bearer token`); an incorrect token returns `403` (`invalid bearer token`).
- Web clients show a neutral sign-in form when the initial check has no token, and an error when a supplied token is rejected. Open development servers authenticate automatically; the sign-in form has no tokenless bypass.
- The full and `/lite` web interfaces share this authentication flow and the same stored token. If browser storage is unavailable, the token remains usable in memory for the current page but cannot be restored after reload. This does not change bearer-token requirements for API requests.
## Models
@@ -36,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`
@@ -103,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"]
},
@@ -147,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": [
@@ -165,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`.
@@ -180,19 +187,20 @@ 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 and tool-call metadata are retained. 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 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, 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" }`
@@ -233,6 +241,9 @@ Behavior notes:
### `GET /v1/chats/:chatId`
- Response: `{ "chat": ChatDetail }`
- Saved ordinary assistant responses can include `metadata.generation: { "provider": "openai", "model": "gpt-4.1-mini" }`. These are the provider/model identifiers used for that completion request, captured separately from the chat's mutable last-used selection. Model aliases remain the requested alias; this does not claim an underlying provider snapshot ID.
- Newly generated responses store this metadata for both streaming and non-streaming completions. It survives reloads and forks. Inline Sybil Agent replies retain their separate `metadata.agentAside` identity.
- For older assistant messages without generation metadata, this response recovers it only when `metadata.clientRequestId` matches exactly one completed, successful call in the same chat. This read does not rewrite stored history. Missing or ambiguous records, including some older forks/imports, remain unattributed; clients must not substitute the chat's current or last-used model. The web footer displays “Model not recorded” in that case.
### `GET /v1/chats/:chatId/messages`
- Requires the same authenticated owner/admin credential as other chat routes. Responses use `Cache-Control: no-store`.
@@ -282,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": [
{
@@ -314,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:
@@ -333,13 +345,17 @@ 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.
- For `chatId` calls, server stores only *new* non-assistant messages from provided history to avoid duplicates.
- 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.
@@ -350,16 +366,15 @@ 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.
- `web_search` returns ranked results with per-result summaries/snippets. Its backend engine is selected by `CHAT_WEB_SEARCH_ENGINE`: `exa` (default), `brave` (requires `BRAVE_SEARCH_API_KEY`), or `searxng` (requires `SEARXNG_BASE_URL`; the instance must allow `format=json`).
- Brave searches are queued and evenly paced according to the shortest window in Brave's `X-RateLimit-Policy` response header. The backend also honors `X-RateLimit-Remaining`/`X-RateLimit-Reset` and retries `429` responses up to three times with reset-aware exponential backoff; quota resets beyond the bounded retry window fail immediately.
- `fetch_url` fetches a URL with browser-like navigation headers and returns plaintext page content (HTML converted to text server-side).
- `fetch_url` fetches an HTTP(S) URL with browser-like navigation headers and returns plaintext page content. HTML is converted to text. PDF files are detected by media type or PDF signature and have selectable text extracted with page markers (no OCR); at most 10 MiB and 30 pages are read per call. The optional `pages` array selects up to 30 page numbers for follow-up reads, and `maxCharacters` bounds PDF text collection; a brief truncation hint may follow the extracted text. PDF parsing runs in a worker terminated after 8 seconds. Responses identify page count, selected pages, truncation, encrypted PDFs, empty PDFs, and PDFs without extractable text; unavailable extraction returns `ok:false` with `pdfStatus`. Other URL responses also have a 10 MiB download limit.
- `codex_exec` delegates coding, shell, repository inspection, and other complex software tasks to a persistent remote Codex CLI workspace over SSH. The server runs `codex exec --dangerously-bypass-approvals-and-sandbox --skip-git-repo-check <non-interactive wrapped prompt>` on the configured devbox inside `CHAT_CODEX_REMOTE_WORKDIR`, with SSH stdin closed.
- `shell_exec` runs arbitrary non-interactive shell commands on the same configured devbox, starting in `CHAT_CODEX_REMOTE_WORKDIR`. It uses `bash -lc` when bash exists, otherwise `sh -lc`, closes SSH stdin, and does not run inside the Sybil server container.
- Devbox tool configuration:
@@ -476,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
{
@@ -487,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"]
}
@@ -541,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]
@@ -801,6 +820,10 @@ All push/config/presence routes require a configured `ADMIN_TOKEN` and bearer au
`vapidPublicKey` is present only when Web Push is enabled and its credentials are valid. No private keys, tokens, paths or configured account identifiers are returned. Source discovery and browser presence run independently of transport enablement/installation consent. Clients bind local consent to a known source UUID as well as the authenticated backend; null/unknown source cannot opt in. A source change retires prior local consent/installation and requires a new UUID plus explicit user opt-in, rechecking the source after asynchronous permission/subscription/registration work. `sourceId` is the persisted bound runtime UUID or null before discovery. A changed runtime source or regressed durable cursor quarantines delivery and cancels pending alerts without resetting the canonical read cursor. There is deliberately no HTTP read-reset/rebaseline endpoint; an operator must reconcile replacement runtime data with source-aware clients before enabling a new baseline.
`webPushAvailable` describes the **server transport**, not the browser or device's push service. Browser permission `granted` and exposed Push APIs also do not prove that a subscription can be created. The web client distinguishes insecure/unsupported contexts, iOS Home Screen requirements, permission dismissal/denial, worker startup, push subscription errors/timeouts, local storage failures, and authenticated server failures. HTTP 401/403 require sign-in recovery; 400/413 mean a rejected subscription; 409 requires a new installation identity; 429 means retry later; 503 indicates server availability/configuration. These are client diagnostics for existing statuses, with no endpoint or response-shape change. Raw provider messages, response bodies, subscription endpoints and credentials must never be echoed to the UI. Background presence/config refreshes preserve a failed opt-in's diagnosis until an explicit retry or refresh.
For Android/GrapheneOS setup and device verification limits, see [mobile web QA and notification guidance](../mobile-web-qa.md). Vanadium's Chromium Android push transport depends on Google Play services; a website cannot supply an alternative browser push transport or reliably detect installed Android packages. Keep this distinct from server configuration errors.
### `PUT /v1/agent/push/installations/:installationId`
Use a stable random UUID per local installation, authenticated with the current shared token. Registration is explicit user opt-in and requires enabled/configured transport. Native body:
+17 -9
View File
@@ -17,6 +17,8 @@ Authentication:
- Same as REST endpoints (`Authorization: Bearer <token>` when token mode is enabled)
- The web client checks [`GET /v1/auth/session`](rest.md#get-v1authsession) before opening streams. An initial missing-token response prompts sign-in without an error; an incorrect supplied token is an authentication failure. The web sign-in form has no tokenless bypass; open development servers still authenticate automatically. Stream authorization requirements are unchanged.
Web presentation note: `/lite` uses these same chat streams and existing search streams, including idempotent `clientRequestId` retries and active-run attachment. It displays completed responses instead of repainting individual deltas. Its Agent view shares the room protocol and durable delivery/read-state handling. These are presentation choices; request shapes, event payloads, persistence, and endpoint semantics are unchanged.
## Chat Completion Request Body
```json
@@ -24,7 +26,7 @@ Authentication:
"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": [
{
@@ -56,7 +58,8 @@ Authentication:
"additionalSystemPrompt": "optional one-off system prompt",
"enabledTools": ["web_search", "fetch_url"],
"temperature": 0.2,
"maxTokens": 256
"maxTokens": 256,
"reasoningEffort": null
}
```
@@ -71,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:
@@ -103,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
}
```
@@ -119,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
@@ -146,6 +153,8 @@ Each tool invocation can emit multiple `tool_call` events with the same `toolCal
For `persist: false` streams, `chatId` and `callId` are `null`.
When an ordinary persisted completion finishes, its assistant message stores the same request-time provider/model in `metadata.generation`, available in the canonical `GET /v1/chats/:chatId` refresh. Clients must use per-message generation metadata for historical response labels, not the current chat selection. Older messages can lack attribution; see [chat detail](rest.md#get-v1chatschatid). This adds no SSE events or fields, and does not change non-persistent Quick Questions or inline Agent identity.
### `delta`
```json
@@ -213,11 +222,10 @@ Terminal tool-call event:
- `anthropic`: backend uses Anthropic's Messages API and may execute the same internal tools with `tool_use`/`tool_result` content blocks before producing final text.
- `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.
- `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.
- `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.
- `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.
+69
View File
@@ -0,0 +1,69 @@
# Mobile web QA — 2026-11-02
This change is limited to the web client and its tests/documentation, with no backend contract or native app release changes. This report records the focused mobile QA and remaining device verification limits.
## Reproduction and fixes
The production bundle was exercised with local API/socket fixtures in touch-enabled Chromium at 390×844. Before/after measurements use identical messages and viewport dimensions.
| Area | Before | After |
| --- | --- | --- |
| Installed display | Manifest preferred `fullscreen`, including `display_override` | `standalone`, no fullscreen override; normal Apple status-bar style |
| Horizontal table pan | `touch-action: pan-y` on the workspace; table stayed at `scrollLeft=0`, swipe created a new chat | Native table scrolled to `scrollLeft=160`, current chat retained |
| Regular assistant width | 304.30px of a 358px transcript at 390px viewport | 358px; desktop width rule retained |
| Agent message width | 287.52px | 287.52px; bubble/avatar styling retained |
| Compact model | Hidden | Provider and active model beneath title; updates after changing model in settings |
| Context menu | Assistant context-menu event canceled for a Fork-only menu | Native event allowed for text, links and composer; Copy and Fork are available in the reply footer |
| Zoom | Viewport disabled user scaling | Fixed-scale viewport retained (`maximum-scale=1.0`, `user-scalable=no`) |
| Notification failures | Browser exception names and server statuses replaced by a generic error; background refresh erased errors | Stage-specific, redacted recovery guidance, retained until explicit retry/refresh |
Text owns gestures across regular chat, search markdown and Agent. Dynamic horizontal scrollers and code/table/quote elements are protected even at both ends. Selections, multi-touch, long-press starts and touch cancellation abandon navigation tracking. Blank workspace chrome still supports sidebar/new-chat swipes. Notification help is bounded and scrollable; sidebar content remains reachable on shorter screens.
The assistant-footer follow-up replaces the standalone ellipsis with a subtle local date/time from the saved message's `createdAt`, followed by Copy and Fork. The timestamp and first action icon align with the paragraph on mobile and desktop. Copy preserves Markdown and reports clipboard failures without interfering with native selection. Fork uses the existing message-specific endpoint and is disabled while the request is pending. Agent bubbles and streaming placeholders retain their existing presentation; API contracts are unchanged.
## Notification diagnosis and official sources
A read-only authenticated request to the running server's `GET /v1/agent/push/config` returned HTTP 200 with `enabled=true`, `webPushAvailable=true`, a known source, `quarantined=false`, and a public key present. Credentials/key values were not printed. This rules out disabled transport configuration at the time of inspection; it does not prove delivery or identify the actual phone's failed step.
Chromium's Android [GCM driver](https://chromium.googlesource.com/chromium/src/+/main/components/gcm_driver/android/java/src/org/chromium/components/gcm_driver/GCMDriver.java) uses [GoogleCloudMessagingV2](https://chromium.googlesource.com/chromium/src/+/main/components/gcm_driver/android/java/src/org/chromium/components/gcm_driver/GoogleCloudMessagingV2.java), which checks for `com.google.android.gms` and rejects registration when Google Play services is absent. Vanadium is GrapheneOS's Chromium browser, as documented in the [official browsing guide](https://grapheneos.org/usage#web-browsing). Missing/unreachable Play services is therefore a plausible cause on GrapheneOS; the old generic message cannot establish that cause.
The [official sandboxed Google Play guide](https://grapheneos.org/usage#sandboxed-google-play) requires dependent apps and Play in the same profile and recommends a battery optimization exception for background push. Check network access, Sybil's site notification permission and Vanadium's Android notification permission, then reload and explicitly enable again. Users choosing not to install Play need a browser with an independent push service. Sybil cannot replace that browser service or inspect installed Android packages, so it does not disable Vanadium based on user-agent detection.
Permission and subscription are separate: [`PushManager.subscribe()`](https://developer.mozilla.org/en-US/docs/Web/API/PushManager/subscribe) can fail after permission was granted. Diagnostics identify the failed layer and known exception name without echoing arbitrary browser/provider messages. No permissions are requested in the background; opt-in still requests permission synchronously from the user's click. Registration failures retain rollback and revocation behavior, including storage failure after browser subscription.
`standalone` can retain the device status bar, unlike fullscreen ([manifest display reference](https://developer.mozilla.org/en-US/docs/Web/Progressive_web_apps/Manifest/Reference/display)). Existing installations may retain older manifest metadata until their browser updates it. Chrome documents [manifest update scheduling](https://web.dev/articles/manifest-updates); Vanadium installation/update behavior still needs device verification. The manifest URL, app ID, start URL and service-worker scope remain stable.
## Automated verification
- `npm run build` and `npm test` in `web`.
- `mobile-workspace.browser.mjs`: trusted CDP touch pans on tables, nested quotation code and code blocks; both scroll edges; selection/clipboard copy and text paste; uncanceled context-menu events; aligned saved timestamp, Copy success/failure/retry and direct Fork with the correct message ID; synthetic multi-touch/long-press/cancel scenarios; both navigation directions; model change; widths 320, 390, 430 and 767; 1280px desktop check; 450px-height composer checks; unchanged Agent width; manifest and zoom settings. Screenshots were inspected.
- `agent-push-errors.browser.mjs`: mobile permission dismissal/denial, worker failure, `AbortError`, `NotAllowedError`, `NotSupportedError`, `InvalidStateError`, subscription timeout, HTTP 400/401/403/409/429/503, rollback, preserved error after background refresh, successful retry, missing APIs/insecure context, iOS Home Screen guidance, and reachable notification controls at 320×568 and 390×450. API/push-provider outcomes are mocked; worker registration is real except the deliberate failure case.
- Existing `agent-push.browser.mjs`: real worker activation/notification display/IndexedDB and read-close, explicit consent, source changes, multiple sessions, credential rotation, revocation and offline logout with mocked push provider/backend.
- Existing `pwa.browser.mjs`: production service-worker activation/reload and authentication flows.
Run browser checks after building, using an existing Playwright/Chromium installation. These fixtures intentionally reject non-loopback targets and mock backend/provider traffic.
```sh
cd web
npm run build
npm test
npm run preview -- --host 127.0.0.1 --port 5197 --strictPort
```
In another shell, with `PLAYWRIGHT_MODULE=/absolute/path/to/playwright-core/index.mjs` and `CHROME_EXECUTABLE=/absolute/path/to/chrome` exported:
```sh
cd web
node tests/mobile-workspace.browser.mjs
node tests/agent-push-errors.browser.mjs
node tests/agent-push.browser.mjs
node tests/pwa.browser.mjs
```
`MOBILE_ARTIFACT_DIR` saves layout screenshots. `PUSH_ERROR_SCREENSHOT` saves notification settings. `MOBILE_BASELINE=1` records the original layout/gesture failures against a separately served original build.
## Device verification limits
No physical GrapheneOS/Vanadium, Android Chrome, or iPhone/Safari device was available. Desktop Chromium touch emulation cannot verify Android system status-bar visibility, native long-press menu rendering/selection handles, actual pinch/keyboard behavior, installed-PWA metadata updates or background FCM delivery. Clipboard tests use the browser engine's keyboard copy/paste and synthetic context-menu dispatch; cancellation/selection assertions are not a claim that Android's system menu was displayed. A shorter viewport approximates keyboard space, without emulating the keyboard itself.
On the user's device after an authorized deployment: check the installed status bar and fixed-scale viewport, pan both ways through wide tables/quotes/code without navigation, long-press/copy/paste, change model, then explicitly enable notifications and inspect the new error if registration fails. Verify actual background delivery with all Sybil web sessions inactive. The underlying phone-specific notification failure remains unconfirmed until that check.
-1
View File
@@ -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`
@@ -235,6 +235,53 @@ struct AgentAvatar: View {
}
}
struct AgentTypingDots: View {
@Environment(\.accessibilityReduceMotion) private var reduceMotion
var body: some View {
TimelineView(.animation(minimumInterval: 1 / 30, paused: reduceMotion)) { timeline in
HStack(spacing: 3) {
ForEach(0..<3, id: \.self) { index in
let pulse = pulse(at: timeline.date, index: index)
Circle()
.fill(Color(red: 0.80, green: 0.70, blue: 0.91))
.frame(width: 3, height: 3)
.opacity(reduceMotion ? 0.7 : pulse.opacity)
.offset(y: reduceMotion ? 0 : pulse.rise)
}
}
.padding(.horizontal, 8)
.padding(.vertical, 6)
.background(
Color(red: 0.12, green: 0.075, blue: 0.21).opacity(0.42),
in: RoundedRectangle(cornerRadius: 9)
)
}
.accessibilityElement(children: .ignore)
.accessibilityLabel("Sybil is thinking")
}
private func pulse(at date: Date, index: Int) -> (opacity: Double, rise: CGFloat) {
let cycle = 1.4
let delay = Double(index) * 0.16 / cycle
let elapsed = date.timeIntervalSinceReferenceDate.truncatingRemainder(dividingBy: cycle) / cycle
let phase = (elapsed - delay + 1).truncatingRemainder(dividingBy: 1)
let intensity: Double
if phase <= 0.35 {
let progress = phase / 0.35
let eased = progress * progress * (3 - 2 * progress)
intensity = 0.35 + 0.65 * eased
} else if phase <= 0.70 {
let progress = (phase - 0.35) / 0.35
let eased = progress * progress * (3 - 2 * progress)
intensity = 1 - 0.65 * eased
} else {
intensity = 0.35
}
return (intensity, -2 * CGFloat((intensity - 0.35) / 0.65))
}
}
// Activity/read publications still update the transcript. Completed rows depend
// only on message values and heading; scrolling needs no per-row geometry.
private struct AgentTranscriptRow: View, Equatable {
@@ -234,7 +234,13 @@ struct MessageBubble: View {
)
}
if isStreamingAssistant && !agentStyle {
if agentStyle && shouldShowInlineAgentPendingDots(
message: message,
isSending: isSending,
presentation: matchingStreamingAssistantPresentation
) {
AgentTypingDots()
} else if isStreamingAssistant && !agentStyle {
StreamingAssistantContentView(
content: message.content,
isSending: isSending,
@@ -289,6 +295,24 @@ struct MessageBubble: View {
}
}
func shouldShowInlineAgentPendingDots(
message: Message,
isSending: Bool,
presentation: StreamingAssistantPresentation?
) -> Bool {
guard message.isAgentAside,
message.role == .assistant,
message.id.hasPrefix("temp-assistant-"),
isSending,
let presentation,
presentation.messageID == message.id,
presentation.isAwaitingVisibleText
else {
return false
}
return message.content.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
}
private struct StreamingTraceHeightPreferenceKey: PreferenceKey {
static let defaultValue: CGFloat = 0
@@ -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
}
@@ -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? {
@@ -54,10 +54,14 @@ struct StreamingAssistantState: Equatable, Sendable {
private(set) var initiatedToolCallIDs: Set<String> = []
private(set) var ephemeralTrace: String?
private(set) var traceRevision = 0
private(set) var isAwaitingVisibleText = true
mutating func receiveDelta(_ text: String) -> StreamingAssistantContentUpdate {
guard !text.isEmpty else { return .unchanged }
segmentText += text
if !segmentText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
isAwaitingVisibleText = false
}
ephemeralTrace = nil
return .replace(segmentText)
}
@@ -79,20 +83,27 @@ struct StreamingAssistantState: Equatable, Sendable {
mutating func receiveDone(_ text: String) -> StreamingAssistantContentUpdate {
segmentText = ""
ephemeralTrace = nil
isAwaitingVisibleText = false
return .replace(text)
}
mutating func receiveError() -> StreamingAssistantContentUpdate {
segmentText = ""
ephemeralTrace = nil
isAwaitingVisibleText = false
return .unchanged
}
mutating func receiveCancel() {
isAwaitingVisibleText = false
}
}
struct StreamingAssistantPresentation: Equatable, Sendable {
var messageID: String
var ephemeralTrace: String?
var traceRevision: Int
var isAwaitingVisibleText: Bool
}
private struct PendingChatState {
@@ -107,7 +118,8 @@ private struct PendingChatState {
return StreamingAssistantPresentation(
messageID: messageID,
ephemeralTrace: streamingAssistantState.ephemeralTrace,
traceRevision: streamingAssistantState.traceRevision
traceRevision: streamingAssistantState.traceRevision,
isAwaitingVisibleText: streamingAssistantState.isAwaitingVisibleText
)
}
}
@@ -242,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(
@@ -271,9 +282,7 @@ final class SybilViewModel {
}
var providerOptions: [Provider] {
Provider.allCases.filter { candidate in
candidate != .hermesAgent || modelCatalog[candidate] != nil
}
Provider.allCases
}
var quickQuestionProviderModelOptions: [String] {
@@ -467,7 +476,8 @@ final class SybilViewModel {
return StreamingAssistantPresentation(
messageID: messageID,
ephemeralTrace: quickQuestionStreamingAssistantState.ephemeralTrace,
traceRevision: quickQuestionStreamingAssistantState.traceRevision
traceRevision: quickQuestionStreamingAssistantState.traceRevision,
isAwaitingVisibleText: quickQuestionStreamingAssistantState.isAwaitingVisibleText
)
}
@@ -2151,6 +2161,13 @@ final class SybilViewModel {
pendingDraftChatState = PendingChatState(chatID: nil, messages: optimisticMessages)
}
defer {
if Task.isCancelled {
if let resolvedChatID = chatID {
pendingChatStates[resolvedChatID]?.streamingAssistantState.receiveCancel()
} else {
pendingDraftChatState?.streamingAssistantState.receiveCancel()
}
}
if let resolvedChatID = chatID {
pendingChatStates[resolvedChatID] = nil
} else {
@@ -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() {
@@ -0,0 +1,141 @@
import SwiftUI
import UIKit
import XCTest
@testable import Sybil
@MainActor
final class AgentInlineThinkingDotsTests: XCTestCase {
func testPendingDotsReplaceWithTextAndHideOnDoneFailureOrCancel() async throws {
let messageID = "temp-assistant-inline-dots-fixture"
let date = Date(timeIntervalSince1970: 1_750_000_000)
let user = Message(id: "temp-user-inline-dots-fixture", createdAt: date, role: .user, content: "@Sybil, summarize this.", name: nil)
var reply = Message(
id: messageID,
createdAt: date,
role: .assistant,
content: "",
name: nil,
metadata: .object(["agentAside": .bool(true)])
)
var state = StreamingAssistantState()
var presentation = Self.presentation(messageID: messageID, state: state)
XCTAssertTrue(shouldShowInlineAgentPendingDots(message: reply, isSending: true, presentation: presentation))
await capture(messages: [user, reply], presentation: presentation, sending: true, name: "inline-agent-pending-dancing-dots")
XCTAssertEqual(state.receiveDelta(" \n"), .replace(" \n"))
reply.content = state.segmentText
presentation = Self.presentation(messageID: messageID, state: state)
XCTAssertTrue(shouldShowInlineAgentPendingDots(message: reply, isSending: true, presentation: presentation))
XCTAssertEqual(state.receiveDelta("Here is the Agent reply."), .replace(" \nHere is the Agent reply."))
reply.content = state.segmentText
presentation = Self.presentation(messageID: messageID, state: state)
XCTAssertFalse(shouldShowInlineAgentPendingDots(message: reply, isSending: true, presentation: presentation))
await capture(messages: [user, reply], presentation: presentation, sending: true, name: "inline-agent-first-visible-text-same-bubble")
XCTAssertEqual(state.receiveDone("Completed Agent reply."), .replace("Completed Agent reply."))
reply.content = "Completed Agent reply."
presentation = Self.presentation(messageID: messageID, state: state)
XCTAssertFalse(shouldShowInlineAgentPendingDots(message: reply, isSending: true, presentation: presentation))
XCTAssertEqual(reply.id, messageID)
var failed = StreamingAssistantState()
let failurePresentation = Self.presentation(messageID: messageID, state: failed)
XCTAssertTrue(shouldShowInlineAgentPendingDots(message: reply.withContent(""), isSending: true, presentation: failurePresentation))
XCTAssertEqual(failed.receiveError(), .unchanged)
XCTAssertFalse(shouldShowInlineAgentPendingDots(
message: reply.withContent(""), isSending: true, presentation: Self.presentation(messageID: messageID, state: failed)
))
var cancelled = StreamingAssistantState()
let cancelPresentation = Self.presentation(messageID: messageID, state: cancelled)
XCTAssertTrue(shouldShowInlineAgentPendingDots(message: reply.withContent(""), isSending: true, presentation: cancelPresentation))
cancelled.receiveCancel()
XCTAssertFalse(shouldShowInlineAgentPendingDots(
message: reply.withContent(""), isSending: true, presentation: Self.presentation(messageID: messageID, state: cancelled)
))
}
private static func presentation(messageID: String, state: StreamingAssistantState) -> StreamingAssistantPresentation {
StreamingAssistantPresentation(
messageID: messageID,
ephemeralTrace: state.ephemeralTrace,
traceRevision: state.traceRevision,
isAwaitingVisibleText: state.isAwaitingVisibleText
)
}
private func capture(
messages: [Message],
presentation: StreamingAssistantPresentation,
sending: Bool,
name: String
) async {
let host = UIHostingController(rootView: InlineAgentReplySnapshot(
messages: messages,
presentation: presentation,
sending: sending
))
let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 390, height: 170))
window.rootViewController = host
window.makeKeyAndVisible()
host.view.frame = window.bounds
host.view.setNeedsLayout()
host.view.layoutIfNeeded()
try? await Task.sleep(for: .milliseconds(80))
let image = UIGraphicsImageRenderer(bounds: host.view.bounds).image { _ in
XCTAssertTrue(host.view.drawHierarchy(in: host.view.bounds, afterScreenUpdates: true))
}
if let data = image.pngData() {
let attachment = XCTAttachment(data: data, uniformTypeIdentifier: "public.png")
attachment.name = name
attachment.lifetime = .keepAlways
add(attachment)
} else {
XCTFail("Could not encode (name) screenshot")
}
window.isHidden = true
window.rootViewController = nil
}
}
private struct InlineAgentReplySnapshot: View {
var messages: [Message]
var presentation: StreamingAssistantPresentation
var sending: Bool
var body: some View {
ZStack(alignment: .topLeading) {
SybilTheme.background.ignoresSafeArea()
VStack(alignment: .leading, spacing: 8) {
Text("Inline @Sybil reply")
.font(.sybil(.caption))
.foregroundStyle(SybilTheme.textMuted)
ForEach(messages) { message in
if message.isAgentAside {
AgentMessageRow(
message: message,
isSending: sending,
streamingAssistantPresentation: presentation
)
} else {
Text(message.content).foregroundStyle(SybilTheme.text)
}
}
Spacer(minLength: 0)
}
.padding(16)
}
.frame(width: 390, height: 170)
.environment(\.colorScheme, .dark)
}
}
private extension Message {
func withContent(_ content: String) -> Message {
var copy = self
copy.content = content
return copy
}
}
+5 -4
View File
@@ -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)
+263
View File
@@ -21,6 +21,7 @@
"html-to-text": "^9.0.5",
"marked": "17.0.2",
"openai": "^6.16.0",
"pdfjs-dist": "5.4.394",
"pino-pretty": "^13.1.3",
"prisma": "^6.6.0",
"web-push": "^3.6.7",
@@ -775,6 +776,256 @@
"node": ">=8"
}
},
"node_modules/@napi-rs/canvas": {
"version": "0.1.100",
"resolved": "https://registry.npmjs.org/@napi-rs/canvas/-/canvas-0.1.100.tgz",
"integrity": "sha512-xglYA6q3XO5P3BNJYxVZ1IV7DLVjp1Py6nwag88YntrS+3vKHyYcMqXVS4ZztJmwz2uGvz1FWhI/4LgbR5uQDA==",
"license": "MIT",
"optional": true,
"workspaces": [
"e2e/*"
],
"engines": {
"node": ">= 10"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/Brooooooklyn"
},
"optionalDependencies": {
"@napi-rs/canvas-android-arm64": "0.1.100",
"@napi-rs/canvas-darwin-arm64": "0.1.100",
"@napi-rs/canvas-darwin-x64": "0.1.100",
"@napi-rs/canvas-linux-arm-gnueabihf": "0.1.100",
"@napi-rs/canvas-linux-arm64-gnu": "0.1.100",
"@napi-rs/canvas-linux-arm64-musl": "0.1.100",
"@napi-rs/canvas-linux-riscv64-gnu": "0.1.100",
"@napi-rs/canvas-linux-x64-gnu": "0.1.100",
"@napi-rs/canvas-linux-x64-musl": "0.1.100",
"@napi-rs/canvas-win32-arm64-msvc": "0.1.100",
"@napi-rs/canvas-win32-x64-msvc": "0.1.100"
}
},
"node_modules/@napi-rs/canvas-android-arm64": {
"version": "0.1.100",
"resolved": "https://registry.npmjs.org/@napi-rs/canvas-android-arm64/-/canvas-android-arm64-0.1.100.tgz",
"integrity": "sha512-hjhCKhntPv9+t4ckHymdx0phYNcVW+GKQR6Lzw2zE+pOVjOplSmtx9nNNknTjbEDLcuLZqA1y8ufKg1XfgftzQ==",
"cpu": [
"arm64"
],
"license": "MIT",
"optional": true,
"os": [
"android"
],
"engines": {
"node": ">= 10"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/Brooooooklyn"
}
},
"node_modules/@napi-rs/canvas-darwin-arm64": {
"version": "0.1.100",
"resolved": "https://registry.npmjs.org/@napi-rs/canvas-darwin-arm64/-/canvas-darwin-arm64-0.1.100.tgz",
"integrity": "sha512-2PcswRaC7Ly645DGt88///zuFDhJxJYdKAs1uU3mfk1atYkXufgcgLfBpk6Tm12nCQBaNt1wpybuPZ4qOhTo8A==",
"cpu": [
"arm64"
],
"license": "MIT",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": ">= 10"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/Brooooooklyn"
}
},
"node_modules/@napi-rs/canvas-darwin-x64": {
"version": "0.1.100",
"resolved": "https://registry.npmjs.org/@napi-rs/canvas-darwin-x64/-/canvas-darwin-x64-0.1.100.tgz",
"integrity": "sha512-ePNZtj7pNIva/siZMg+HmbeozkIjqUIYdoymH8HaA3qK7LfzFN4WMBM8G6HQ9ZC+H3+Dnn5pqtiXpgLykaPOhw==",
"cpu": [
"x64"
],
"license": "MIT",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": ">= 10"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/Brooooooklyn"
}
},
"node_modules/@napi-rs/canvas-linux-arm-gnueabihf": {
"version": "0.1.100",
"resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-arm-gnueabihf/-/canvas-linux-arm-gnueabihf-0.1.100.tgz",
"integrity": "sha512-d5cDB48oWFGU8/XPhUOFAlySgb/VAu7D+s8fi55K1Pcfg8aPplHWqMgibhVLU8ky7Pyg/fuiVLz4Nf3JrSTuUA==",
"cpu": [
"arm"
],
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">= 10"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/Brooooooklyn"
}
},
"node_modules/@napi-rs/canvas-linux-arm64-gnu": {
"version": "0.1.100",
"resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-arm64-gnu/-/canvas-linux-arm64-gnu-0.1.100.tgz",
"integrity": "sha512-rDxgxRu69RvDlX/bh9o22DxLsGr8EqsNgotL9+RwQE1S0b0cqeatqsw6aW45mukm0B42DIAaAacKaYQ8cqS1nw==",
"cpu": [
"arm64"
],
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">= 10"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/Brooooooklyn"
}
},
"node_modules/@napi-rs/canvas-linux-arm64-musl": {
"version": "0.1.100",
"resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-arm64-musl/-/canvas-linux-arm64-musl-0.1.100.tgz",
"integrity": "sha512-K3mDW66N+xT2/V439u1alFANiBUjdEx2gLiNYnCmUsva5jZMxWTjafBYwTzYK+EMFMHrUoabuU+T1BIP5CgbYQ==",
"cpu": [
"arm64"
],
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">= 10"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/Brooooooklyn"
}
},
"node_modules/@napi-rs/canvas-linux-riscv64-gnu": {
"version": "0.1.100",
"resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-riscv64-gnu/-/canvas-linux-riscv64-gnu-0.1.100.tgz",
"integrity": "sha512-mooqUBTIsccZpnoQC4NgrC1v6C1vof39etLNMnBwCY+p0gajWJvAHLGQ6g/gGyS5YrpDW+GefSN4+Cvcr08UWw==",
"cpu": [
"riscv64"
],
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">= 10"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/Brooooooklyn"
}
},
"node_modules/@napi-rs/canvas-linux-x64-gnu": {
"version": "0.1.100",
"resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-x64-gnu/-/canvas-linux-x64-gnu-0.1.100.tgz",
"integrity": "sha512-1eCvkDCazm7FFhsT7DfGOdSaHgZVK3bt/dSBl5EWHOWmnz+I7j8tPseJqqD81NF+MH21jKUK4wQSDjN0mdhnTg==",
"cpu": [
"x64"
],
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">= 10"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/Brooooooklyn"
}
},
"node_modules/@napi-rs/canvas-linux-x64-musl": {
"version": "0.1.100",
"resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-x64-musl/-/canvas-linux-x64-musl-0.1.100.tgz",
"integrity": "sha512-20arT6lnI19S68qNlii73TSEDbECNgzMz2EpldC1V3mZFuRkeujXkcebRk0LRJe9SEUAooYiLokfMViY8IX7yA==",
"cpu": [
"x64"
],
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">= 10"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/Brooooooklyn"
}
},
"node_modules/@napi-rs/canvas-win32-arm64-msvc": {
"version": "0.1.100",
"resolved": "https://registry.npmjs.org/@napi-rs/canvas-win32-arm64-msvc/-/canvas-win32-arm64-msvc-0.1.100.tgz",
"integrity": "sha512-DZFFT1wIAg37LJw37yhMRFfjATd3vTQzjZ1Yki8u2vhO6Hi5VE6BVaGQ1aaDu7xb4iMErz+9EOwjpS7xcxFeBw==",
"cpu": [
"arm64"
],
"license": "MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">= 10"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/Brooooooklyn"
}
},
"node_modules/@napi-rs/canvas-win32-x64-msvc": {
"version": "0.1.100",
"resolved": "https://registry.npmjs.org/@napi-rs/canvas-win32-x64-msvc/-/canvas-win32-x64-msvc-0.1.100.tgz",
"integrity": "sha512-MyT1j3mHC2+Lu4pBi9mKyMJhtP6U7k7EldY7sj/uS5gJA65gTXt8MefJQXLJo5d/vZbuWmfxzkEUNc/urV3pHA==",
"cpu": [
"x64"
],
"license": "MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">= 10"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/Brooooooklyn"
}
},
"node_modules/@pinojs/redact": {
"version": "0.4.0",
"resolved": "https://registry.npmjs.org/@pinojs/redact/-/redact-0.4.0.tgz",
@@ -1939,6 +2190,18 @@
"url": "https://github.com/sponsors/isaacs"
}
},
"node_modules/pdfjs-dist": {
"version": "5.4.394",
"resolved": "https://registry.npmjs.org/pdfjs-dist/-/pdfjs-dist-5.4.394.tgz",
"integrity": "sha512-9ariAYGqUJzx+V/1W4jHyiyCep6IZALmDzoaTLZ6VNu8q9LWi1/ukhzHgE2Xsx96AZi0mbZuK4/ttIbqSbLypg==",
"license": "Apache-2.0",
"engines": {
"node": ">=20.16.0 || >=22.3.0"
},
"optionalDependencies": {
"@napi-rs/canvas": "^0.1.81"
}
},
"node_modules/peberminta": {
"version": "0.9.0",
"resolved": "https://registry.npmjs.org/peberminta/-/peberminta-0.9.0.tgz",
+1
View File
@@ -30,6 +30,7 @@
"html-to-text": "^9.0.5",
"marked": "17.0.2",
"openai": "^6.16.0",
"pdfjs-dist": "5.4.394",
"pino-pretty": "^13.1.3",
"prisma": "^6.6.0",
"web-push": "^3.6.7",
@@ -0,0 +1 @@
ALTER TABLE "Chat" ADD COLUMN "reasoningEffort" TEXT;
+6 -11
View File
@@ -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
+4 -1
View File
@@ -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);
-10
View File
@@ -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.
+36
View File
@@ -0,0 +1,36 @@
export const MAX_FETCH_RESPONSE_BYTES = 10 * 1024 * 1024;
export async function readBoundedResponseBytes(response: Response, maxBytes: number) {
const contentLength = Number(response.headers.get("content-length"));
if (Number.isFinite(contentLength) && contentLength > maxBytes) {
await response.body?.cancel();
throw new Error(`URL response exceeds the ${Math.floor(maxBytes / (1024 * 1024))} MiB download limit.`);
}
const reader = response.body?.getReader();
if (!reader) return new Uint8Array();
const chunks: Uint8Array[] = [];
let totalBytes = 0;
try {
while (true) {
const { done, value } = await reader.read();
if (done) break;
totalBytes += value.byteLength;
if (totalBytes > maxBytes) {
await reader.cancel();
throw new Error(`URL response exceeds the ${Math.floor(maxBytes / (1024 * 1024))} MiB download limit.`);
}
chunks.push(value);
}
} finally {
reader.releaseLock();
}
const bytes = new Uint8Array(totalBytes);
let offset = 0;
for (const chunk of chunks) {
bytes.set(chunk, offset);
offset += chunk.byteLength;
}
return bytes;
}
+74 -41
View File
@@ -6,11 +6,14 @@ import { promisify } from "node:util";
import { convert as htmlToText } from "html-to-text";
import { z } from "zod";
import { buildBrowserLikeNavigationHeaders } from "../browser-fetch-headers.js";
import { MAX_FETCH_RESPONSE_BYTES, readBoundedResponseBytes } from "./bounded-response.js";
import { env } from "../env.js";
import { searchBrave } from "../search/brave.js";
import { exaClient } from "../search/exa.js";
import { searchSearxng } from "../search/searxng.js";
import type { ChatMessage } from "./types.js";
import { extractPdfText, hasPdfMagic, MAX_PDF_PAGES_PER_FETCH } from "./pdf-text.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;
@@ -45,6 +48,7 @@ const FetchUrlArgsSchema = z
.object({
url: z.string().trim().url(),
maxCharacters: z.coerce.number().int().min(500).max(MAX_FETCH_MAX_CHARACTERS).optional(),
pages: z.array(z.coerce.number().int().min(1).max(1_000_000)).min(1).max(MAX_PDF_PAGES_PER_FETCH).optional(),
})
.strict();
@@ -163,7 +167,7 @@ const BASE_CHAT_TOOLS: any[] = [
function: {
name: "fetch_url",
description:
"Fetch a webpage by URL and return readable plaintext content extracted from the page for deeper inspection.",
"Fetch a webpage by URL and return readable plaintext content. Text PDFs are extracted page by page; use pages:[3,4] to retrieve selected pages after a truncated result. Scanned PDFs have no extractable text.",
parameters: {
type: "object",
properties: {
@@ -174,6 +178,12 @@ const BASE_CHAT_TOOLS: any[] = [
maximum: MAX_FETCH_MAX_CHARACTERS,
description: "Maximum response text characters returned (default 12000).",
},
pages: {
type: "array",
items: { type: "integer", minimum: 1, maximum: 1000000 },
maxItems: MAX_PDF_PAGES_PER_FETCH,
description: "For PDFs, extract these page numbers only (up to 30 per fetch).",
},
},
required: ["url"],
additionalProperties: false,
@@ -261,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;
@@ -561,48 +573,69 @@ async function runFetchUrlTool(input: unknown): Promise<ToolRunOutcome> {
signal: controller.signal,
headers: buildBrowserLikeNavigationHeaders(),
});
if (!response.ok) {
await response.body?.cancel();
throw new Error(`Fetch failed with status ${response.status}.`);
}
const contentType = (response.headers.get("content-type") ?? "").toLowerCase();
const bytes = await readBoundedResponseBytes(response, MAX_FETCH_RESPONSE_BYTES);
const url = response.url || parsed.toString();
if (contentType.includes("application/pdf") || hasPdfMagic(bytes)) {
if (!hasPdfMagic(bytes)) {
return { ok: false, url, status: response.status, contentType: contentType || null, pdfStatus: "invalid", text: "The server declared a PDF, but the downloaded file does not have a valid PDF header." };
}
const result = await extractPdfText(bytes, args.pages, maxCharacters);
const text = result.truncated
? `${result.text}\n\n[truncated; re-fetch selected pages with pages:[N,...]]`
: result.text;
return {
ok: result.status === "ok",
url,
status: response.status,
contentType: contentType || "application/pdf",
pdfStatus: result.status,
pageCount: result.pageCount,
pages: result.pages,
pagesTruncated: result.pageCount !== null && result.pageCount > result.pages.length,
truncated: result.truncated,
text,
};
}
const body = new TextDecoder().decode(bytes);
const isHtml = contentType.includes("text/html") || /<!doctype html|<html[\s>]/i.test(body);
const extracted = isHtml
? htmlToText(body, {
wordwrap: false,
preserveNewlines: true,
selectors: [
{ selector: "img", format: "skip" },
{ selector: "script", format: "skip" },
{ selector: "style", format: "skip" },
{ selector: "noscript", format: "skip" },
{ selector: "a", options: { ignoreHref: true } },
],
})
: body;
const normalized = compactWhitespace(extracted);
const truncated = normalized.length > maxCharacters;
const text = truncated
? `${normalized.slice(0, maxCharacters)}\n\n[truncated ${normalized.length - maxCharacters} characters]`
: normalized;
return {
ok: true,
url,
status: response.status,
contentType: contentType || null,
title: isHtml ? extractHtmlTitle(body) : null,
truncated,
text,
};
} finally {
clearTimeout(timeout);
}
if (!response.ok) {
throw new Error(`Fetch failed with status ${response.status}.`);
}
const contentType = (response.headers.get("content-type") ?? "").toLowerCase();
const body = await response.text();
const isHtml = contentType.includes("text/html") || /<!doctype html|<html[\s>]/i.test(body);
let extracted = body;
if (isHtml) {
extracted = htmlToText(body, {
wordwrap: false,
preserveNewlines: true,
selectors: [
{ selector: "img", format: "skip" },
{ selector: "script", format: "skip" },
{ selector: "style", format: "skip" },
{ selector: "noscript", format: "skip" },
{ selector: "a", options: { ignoreHref: true } },
],
});
}
const normalized = compactWhitespace(extracted);
const truncated = normalized.length > maxCharacters;
const text = truncated
? `${normalized.slice(0, maxCharacters)}\n\n[truncated ${normalized.length - maxCharacters} characters]`
: normalized;
return {
ok: true,
url: response.url || parsed.toString(),
status: response.status,
contentType: contentType || null,
title: isHtml ? extractHtmlTitle(body) : null,
truncated,
text,
};
}
function shellQuote(value: string) {
+4 -3
View File
@@ -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;
+9 -9
View File
@@ -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,
@@ -85,6 +84,7 @@ export async function runMultiplex(req: MultiplexRequest): Promise<MultiplexResp
chatId: call.chatId,
role: "assistant" as any,
content: outText,
metadata: { generation: { provider: req.provider, model: req.model } },
},
});
await tx.llmCall.update({
+100
View File
@@ -0,0 +1,100 @@
import { getDocument } from "pdfjs-dist/legacy/build/pdf.mjs";
import { parentPort, workerData } from "node:worker_threads";
const { bytes, requestedPages, maxCharacters, maxPages } = workerData;
function isPasswordError(error) {
return Boolean(error && typeof error === "object" && error.name === "PasswordException");
}
async function extract() {
let loadingTask;
try {
loadingTask = getDocument({
data: bytes,
standardFontDataUrl: new URL("../../node_modules/pdfjs-dist/standard_fonts/", import.meta.url).href,
isEvalSupported: false,
disableFontFace: true,
stopAtErrors: true,
});
const document = await loadingTask.promise;
if (document.numPages === 0) {
return { status: "no_pages", pageCount: 0, pages: [], text: "This PDF has no pages.", truncated: false };
}
const pages = requestedPages?.length
? [...new Set(requestedPages)].slice(0, maxPages)
: Array.from({ length: Math.min(document.numPages, maxPages) }, (_, index) => index + 1);
const invalidPage = pages.find((page) => page > document.numPages);
if (invalidPage) {
return {
status: "error",
pageCount: document.numPages,
pages: [],
text: `Requested page ${invalidPage}, but this PDF has ${document.numPages} pages.`,
truncated: false,
};
}
const chunks = [];
let characterCount = 0;
let foundText = false;
let truncated = false;
const append = (text) => {
const remaining = maxCharacters - characterCount;
if (remaining <= 0) {
truncated = true;
return;
}
const part = text.slice(0, remaining);
chunks.push(part);
characterCount += part.length;
if (part.length < text.length) truncated = true;
};
for (const pageNumber of pages) {
append(`${chunks.length ? "\n\n" : ""}--- Page ${pageNumber} ---\n`);
if (truncated) break;
const page = await document.getPage(pageNumber);
const reader = page.streamTextContent().getReader();
try {
while (!truncated) {
const { done, value } = await reader.read();
if (done) break;
for (const item of value.items) {
if (!("str" in item) || !item.str) continue;
foundText = true;
append(item.str + (item.hasEOL ? "\n" : " "));
if (truncated) break;
}
}
} finally {
if (truncated) await reader.cancel().catch(() => undefined);
reader.releaseLock();
}
if (truncated) break;
}
const text = chunks.join("").trimEnd();
if (!foundText) {
return {
status: "no_text",
pageCount: document.numPages,
pages,
text: "No extractable text was found in the selected pages.",
truncated: false,
};
}
return { status: "ok", pageCount: document.numPages, pages, text, truncated };
} catch (error) {
if (isPasswordError(error)) {
return { status: "encrypted", pageCount: null, pages: [], text: "This PDF is encrypted and requires a password.", truncated: false };
}
const message = error instanceof Error ? error.message : String(error);
return { status: "error", pageCount: null, pages: [], text: `PDF reading failed: ${message}`, truncated: false };
} finally {
await loadingTask?.destroy().catch(() => undefined);
}
}
parentPort?.postMessage(await extract());
+69
View File
@@ -0,0 +1,69 @@
import { Worker } from "node:worker_threads";
import { fileURLToPath } from "node:url";
export const MAX_PDF_PAGES_PER_FETCH = 30;
export const PDF_PARSE_TIMEOUT_MS = 8_000;
const DEFAULT_PDF_TEXT_CHARACTERS = 12_000;
export type PdfTextResult =
| { status: "ok"; pageCount: number; pages: number[]; text: string; truncated: boolean }
| { status: "no_pages"; pageCount: 0; pages: []; text: "This PDF has no pages."; truncated: false }
| { status: "no_text"; pageCount: number; pages: number[]; text: "No extractable text was found in the selected pages."; truncated: false }
| { status: "encrypted"; pageCount: null; pages: []; text: "This PDF is encrypted and requires a password."; truncated: false }
| { status: "error"; pageCount: number | null; pages: number[]; text: string; truncated: false };
export function hasPdfMagic(bytes: Uint8Array) {
const headerEnd = Math.min(bytes.length, 1024);
return Buffer.from(bytes.subarray(0, headerEnd)).includes(Buffer.from("%PDF-"));
}
export function extractPdfText(
bytes: Uint8Array,
requestedPages?: number[],
maxCharacters = DEFAULT_PDF_TEXT_CHARACTERS,
timeoutMs = PDF_PARSE_TIMEOUT_MS,
): Promise<PdfTextResult> {
return new Promise((resolve) => {
let settled = false;
let timeout: ReturnType<typeof setTimeout>;
let worker: Worker;
const finish = (result: PdfTextResult) => {
if (settled) return;
settled = true;
clearTimeout(timeout);
void worker.terminate().catch(() => undefined);
resolve(result);
};
try {
worker = new Worker(fileURLToPath(new URL("./pdf-text-worker.mjs", import.meta.url)), {
workerData: { bytes: new Uint8Array(bytes), requestedPages, maxCharacters, maxPages: MAX_PDF_PAGES_PER_FETCH },
execArgv: [],
});
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
resolve({ status: "error", pageCount: null, pages: [], text: `PDF reader could not start: ${message}`, truncated: false });
return;
}
timeout = setTimeout(() => {
finish({
status: "error",
pageCount: null,
pages: [],
text: `PDF reading exceeded its time limit (${timeoutMs} ms).`,
truncated: false,
});
}, timeoutMs);
worker.once("message", (result: PdfTextResult) => finish(result));
worker.once("error", (error) => {
const message = error instanceof Error ? error.message : String(error);
finish({ status: "error", pageCount: null, pages: [], text: `PDF reading failed: ${message}`, truncated: false });
});
worker.once("exit", (code) => {
if (!settled) {
finish({ status: "error", pageCount: null, pages: [], text: `PDF reader exited unexpectedly (${code}).`, truncated: false });
}
});
});
}
@@ -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,
+13 -37
View File
@@ -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?.() ?? []);
}
+8 -30
View File
@@ -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));
-12
View File
@@ -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 });
+1
View File
@@ -13,6 +13,7 @@ export type QuickQuestionRequest = {
userLocation?: string;
temperature?: number;
maxTokens?: number;
reasoningEffort?: MultiplexRequest["reasoningEffort"];
};
export function buildQuickQuestionMultiplexRequest({
+65
View File
@@ -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 };
}
+11 -5
View File
@@ -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,
@@ -123,7 +126,10 @@ export async function* runMultiplexStream(req: MultiplexRequest): AsyncGenerator
chatId,
role: "assistant" as any,
content: text,
metadata: req.clientRequestId ? ({ clientRequestId: req.clientRequestId } as any) : undefined,
metadata: {
...(req.clientRequestId ? { clientRequestId: req.clientRequestId } : {}),
generation: { provider: req.provider, model: req.model },
},
},
});
await tx.llmCall.update({
+4 -1
View File
@@ -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 = {
+31
View File
@@ -0,0 +1,31 @@
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> : {};
}
type RecordedCall = {
provider: unknown;
model: string;
request: unknown;
error: string | null;
latencyMs: number | null;
};
/** Recover older streaming replies only through an unambiguous, completed request ID. */
export function withMessageGenerations<T extends { role: string; metadata: unknown }>(messages: T[], calls: RecordedCall[]): T[] {
const byRequest = new Map<string, { provider: string; model: string } | null>();
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 = parseProvider(call.provider);
if (!provider || !call.model.trim()) continue;
byRequest.set(requestId, byRequest.has(requestId) ? null : { provider, model: call.model });
}
return messages.map(message => {
const metadata = record(message.metadata);
if (message.role !== "assistant" || metadata.agentAside === true || metadata.generation !== undefined) return message;
const generation = typeof metadata.clientRequestId === "string" ? byRequest.get(metadata.clientRequestId) : null;
return generation ? { ...message, metadata: { ...metadata, generation } } : message;
});
}
+54 -22
View File
@@ -7,6 +7,7 @@ import { invokeAgentInline, type AgentInlineInvoker } from "./agent-inline.js";
import { buildInlineAgentThreadContext, decodeChatHistoryCursor, decodeChatListCursor, encodeChatListCursor, loadCompleteChatHistory, readChatHistoryPage } from "./chat-history.js";
import { containsSybilMention, filterAgentAsideMessages } from "./agent-mention.js";
import { prisma } from "./db.js";
import { withMessageGenerations } from "./message-generation.js";
import { requireAdmin } from "./auth.js";
import { env } from "./env.js";
import { buildComparableAttachments } from "./llm/message-content.js";
@@ -15,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));
@@ -208,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) {
@@ -234,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[]) {
@@ -268,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);
@@ -285,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),
});
}
@@ -334,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,
});
@@ -555,6 +564,7 @@ const chatSummarySelect = {
initiatedModel: true,
lastUsedProvider: true,
lastUsedModel: true,
reasoningEffort: true,
additionalSystemPrompt: true,
enabledTools: true,
projectItems: starredProjectItemsSelect,
@@ -814,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 } : {}),
});
@@ -1081,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;
@@ -1102,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(),
@@ -1128,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
@@ -1169,15 +1181,17 @@ export async function registerRoutes(app: FastifyInstance, options: { agentInlin
initiatedModel: true,
lastUsedProvider: true,
lastUsedModel: true,
reasoningEffort: true,
additionalSystemPrompt: true,
enabledTools: true,
userId: true,
messages: { orderBy: [{ createdAt: "asc" }, { id: "asc" }] },
calls: { select: { provider: true, model: true, request: true, error: true, latencyMs: true } },
},
});
if (!source) return { status: "chat-not-found" as const };
let messages = source.messages;
let messages = withMessageGenerations(source.messages, source.calls);
let selectedMessage: (typeof source.messages)[number] | undefined;
if (parsed.data.messageId) {
const selectedIndex = messages.findIndex((message) => message.id === parsed.data.messageId);
@@ -1197,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,
@@ -1229,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) {
@@ -1242,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");
@@ -1680,7 +1711,7 @@ export async function registerRoutes(app: FastifyInstance, options: { agentInlin
},
});
if (!chat) return app.httpErrors.notFound("chat not found");
return { chat: serializeChatLike(chat) };
return { chat: serializeChatLike({ ...chat, messages: withMessageGenerations(chat.messages, chat.calls) }) };
});
app.post("/v1/chats/:chatId/messages", async (req) => {
@@ -1736,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);
@@ -1759,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",
@@ -1776,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 },
};
+6 -3
View File
@@ -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);
+26
View File
@@ -0,0 +1,26 @@
import assert from "node:assert/strict";
import test from "node:test";
import { readBoundedResponseBytes } from "../src/llm/bounded-response.js";
const oneMiB = 1024 * 1024;
test("reads response bytes within the declared size limit", async () => {
const bytes = await readBoundedResponseBytes(new Response("small"), oneMiB);
assert.equal(new TextDecoder().decode(bytes), "small");
});
test("rejects oversized responses from Content-Length before buffering", async () => {
const response = new Response("x", { headers: { "content-length": String(oneMiB + 1) } });
await assert.rejects(readBoundedResponseBytes(response, oneMiB), /exceeds the 1 MiB download limit/);
});
test("rejects streamed responses when Content-Length is absent", async () => {
const response = new Response(new ReadableStream({
start(controller) {
controller.enqueue(new Uint8Array(oneMiB));
controller.enqueue(new Uint8Array(1));
controller.close();
},
}));
await assert.rejects(readBoundedResponseBytes(response, oneMiB), /exceeds the 1 MiB download limit/);
});
+102 -3
View File
@@ -4,6 +4,7 @@ import { type ToolAwareStreamingEvent } from "../src/llm/chat-tools.js";
import { completeWithChatCompletionsApi, streamWithChatCompletionsApi } from "../src/llm/protocols/chat-completions-api.js";
import { completeWithMessagesApi, streamWithMessagesApi } from "../src/llm/protocols/messages-api.js";
import { streamWithResponsesApi } from "../src/llm/protocols/responses-api.js";
import { createPdf } from "./pdf-fixture.js";
async function* streamFrom(events: any[]) {
for (const event of events) {
@@ -124,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(
@@ -241,10 +242,12 @@ test("fetch_url sends browser-like navigation headers", async () => {
try {
let requestCount = 0;
const requestBodies: any[] = [];
const client = {
chat: {
completions: {
create: async () => {
create: async (body: any) => {
requestBodies.push(body);
requestCount += 1;
if (requestCount === 1) {
return {
@@ -295,12 +298,108 @@ test("fetch_url sends browser-like navigation headers", async () => {
"Sec-Fetch-Site": "none",
"Sec-Fetch-User": "?1",
});
const toolResult = requestBodies[1]?.messages?.find((message: any) => message.role === "tool");
const fetched = JSON.parse(toolResult?.content ?? "{}");
assert.match(fetched.text, /Consumer price index/);
assert.equal(fetched.title, "CPI");
assert.equal(result.toolEvents[0]?.status, "completed");
} finally {
globalThis.fetch = originalFetch;
}
});
test("fetch_url extracts a mislabeled PDF and returns page handles", async () => {
const originalFetch = globalThis.fetch;
const fetchCalls: Array<{ input: RequestInfo | URL; init?: RequestInit }> = [];
const pdf = createPdf(["Revenue is 42.", "Costs are 18."]);
globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
fetchCalls.push({ input, init });
return new Response(pdf, { status: 200, headers: { "content-type": "text/plain" } });
}) as typeof fetch;
try {
const requestBodies: any[] = [];
const client = {
messages: {
create: async (body: any) => {
requestBodies.push(body);
if (requestBodies.length === 1) {
return {
content: [{
type: "tool_use",
id: "pdf_call",
name: "fetch_url",
input: { url: "https://example.com/report.pdf", pages: [2] },
}],
usage: { input_tokens: 1, output_tokens: 1 },
};
}
return { content: [{ type: "text", text: "Read page two" }], usage: { input_tokens: 1, output_tokens: 1 } };
},
},
};
const result = await completeWithMessagesApi({
client: client as any,
model: "claude-test",
messages: [{ role: "user", content: "Read the report" }],
});
const toolResult = requestBodies[1]?.messages?.at(-1)?.content?.[0];
const fetched = JSON.parse(toolResult?.content ?? "{}");
assert.equal(result.text, "Read page two");
assert.equal(fetchCalls.length, 1);
assert.equal(fetched.ok, true);
assert.equal(fetched.pdfStatus, "ok");
assert.equal(fetched.pageCount, 2);
assert.deepEqual(fetched.pages, [2]);
assert.equal(fetched.pagesTruncated, true);
assert.match(fetched.text, /--- Page 2 ---/);
assert.match(fetched.text, /Costs are 18/);
assert.doesNotMatch(fetched.text, /Revenue is 42/);
} finally {
globalThis.fetch = originalFetch;
}
});
test("fetch_url marks encrypted and text-free PDFs as unavailable", async () => {
const originalFetch = globalThis.fetch;
let responseBytes = createPdf([""]);
globalThis.fetch = (async () => new Response(responseBytes, {
status: 200,
headers: { "content-type": "application/pdf" },
})) as typeof fetch;
try {
for (const [pdf, expectedStatus] of [[createPdf([""]), "no_text"], [createPdf(["Secret"], true), "encrypted"]] as const) {
responseBytes = pdf;
const requestBodies: any[] = [];
const client = {
messages: {
create: async (body: any) => {
requestBodies.push(body);
if (requestBodies.length === 1) {
return {
content: [{ type: "tool_use", id: "pdf_status_call", name: "fetch_url", input: { url: "https://example.com/report.pdf" } }],
usage: { input_tokens: 1, output_tokens: 1 },
};
}
return { content: [{ type: "text", text: "Unavailable" }], usage: { input_tokens: 1, output_tokens: 1 } };
},
},
};
await completeWithMessagesApi({ client: client as any, model: "claude-test", messages: [{ role: "user", content: "Read PDF" }] });
const toolResult = requestBodies[1]?.messages?.at(-1)?.content?.[0];
const fetched = JSON.parse(toolResult?.content ?? "{}");
assert.equal(fetched.ok, false);
assert.equal(fetched.pdfStatus, expectedStatus);
assert.equal(toolResult?.is_error, true);
assert.ok(fetched.text.length > 0);
}
} finally {
globalThis.fetch = originalFetch;
}
});
test("Messages API executes tool_use blocks and sends tool_result follow-up", async () => {
const originalFetch = globalThis.fetch;
const fetchCalls: Array<{ input: RequestInfo | URL; init?: RequestInit }> = [];
+85
View File
@@ -0,0 +1,85 @@
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 { withMessageGenerations } from "../src/message-generation.js";
const serverRoot = resolve(dirname(fileURLToPath(import.meta.url)), "..");
const databaseDir = mkdtempSync(join(tmpdir(), "sybil-message-generation-"));
process.env.DATABASE_URL = `file:${join(databaseDir, "test.db")}`;
process.env.ADMIN_TOKEN = "message-generation-test-token";
process.env.OPENAI_API_KEY = "synthetic-openai-key";
process.env.XAI_API_KEY = "synthetic-xai-key";
writeFileSync(join(databaseDir, "test.db"), "");
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 }, { runMultiplex }, { runMultiplexStream }] = await Promise.all([
import("../src/routes.js"), import("../src/db.js"), import("../src/llm/multiplexer.js"), import("../src/llm/streaming.js"),
]);
const app = Fastify({ logger: false });
await app.register(sensible);
await registerRoutes(app);
await app.ready();
const auth = { authorization: "Bearer message-generation-test-token" };
test.after(async () => { await app.close(); await prisma.$disconnect(); rmSync(databaseDir, { recursive: true, force: true }); });
test("streaming and non-streaming replies retain their own model across selection changes and forks", async t => {
t.mock.method(globalThis, "fetch", async (input: RequestInfo | URL, init?: RequestInit) => {
const url = input instanceof Request ? input.url : String(input);
assert.ok(["https://api.openai.com/v1/chat/completions", "https://api.x.ai/v1/chat/completions"].includes(url), url);
const body = JSON.parse(input instanceof Request ? await input.text() : String(init?.body));
const content = `Reply from ${body.model}`;
return body.stream
? new Response(`data: ${JSON.stringify({ choices: [{ index: 0, delta: { content }, finish_reason: null }] })}\n\ndata: [DONE]\n\n`, { headers: { "content-type": "text/event-stream" } })
: Response.json({ choices: [{ message: { role: "assistant", content } }] });
});
const chat = await prisma.chat.create({ data: { title: "Mixed models" } });
const messages = [{ role: "user" as const, content: "Answer" }];
const events = [];
for await (const event of runMultiplexStream({ chatId: chat.id, provider: "openai", model: "model-one", clientRequestId: "first-turn", messages, enabledTools: [] })) events.push(event);
assert.equal(events.at(-1)?.type, "done");
await runMultiplex({ chatId: chat.id, provider: "xai", model: "model-two", messages, enabledTools: [] });
await prisma.chat.update({ where: { id: chat.id }, data: { lastUsedProvider: "gemini", lastUsedModel: "model-next" } });
const detail = await app.inject({ method: "GET", url: `/v1/chats/${chat.id}`, headers: auth });
assert.equal(detail.statusCode, 200);
const saved = detail.json().chat.messages;
assert.deepEqual(saved.map((m: any) => m.metadata.generation), [{ provider: "openai", model: "model-one" }, { provider: "xai", model: "model-two" }]);
assert.equal(saved[0].metadata.clientRequestId, "first-turn");
const fork = await app.inject({ method: "POST", url: `/v1/chats/${chat.id}/fork`, headers: auth, payload: { messageId: saved[1].id } });
assert.equal(fork.statusCode, 200);
const forkDetail = await app.inject({ method: "GET", url: `/v1/chats/${fork.json().chat.id}`, headers: auth });
assert.deepEqual(forkDetail.json().chat.messages.map((m: any) => m.metadata.generation), saved.map((m: any) => m.metadata.generation));
assert.equal(forkDetail.json().chat.messages[0].metadata.clientRequestId, undefined);
});
test("legacy call matches are projected without rewriting history and survive a new fork", async () => {
const chat = await prisma.chat.create({ data: {
title: "Older reply", lastUsedProvider: "gemini", lastUsedModel: "different-current-model",
messages: { create: { role: "assistant", content: "Older reply", metadata: { clientRequestId: "legacy-request", citations: ["https://example.test"] } } },
calls: { create: { provider: "anthropic", model: "original-model", request: { clientRequestId: "legacy-request" }, latencyMs: 10 } },
}, include: { messages: true } });
const detail = await app.inject({ method: "GET", url: `/v1/chats/${chat.id}`, headers: auth });
assert.deepEqual(detail.json().chat.messages[0].metadata.generation, { provider: "anthropic", model: "original-model" });
assert.deepEqual((await prisma.message.findUniqueOrThrow({ where: { id: chat.messages[0]!.id } })).metadata, chat.messages[0]!.metadata);
const fork = await app.inject({ method: "POST", url: `/v1/chats/${chat.id}/fork`, headers: auth, payload: {} });
const forkDetail = await app.inject({ method: "GET", url: `/v1/chats/${fork.json().chat.id}`, headers: auth });
assert.deepEqual(forkDetail.json().chat.messages[0].metadata, { citations: ["https://example.test"], generation: { provider: "anthropic", model: "original-model" } });
});
test("missing, ambiguous, failed and unfinished calls never guess a reply's model", () => {
const call = { provider: "openai", model: "model-one", request: { clientRequestId: "request" }, error: null, latencyMs: 10 };
const message = { role: "assistant", metadata: { clientRequestId: "request" } };
for (const calls of [[], [call, { ...call, provider: "xai" }], [{ ...call, error: "failed" }], [{ ...call, latencyMs: null }]]) {
assert.deepEqual(withMessageGenerations([message], calls), [message]);
}
const existing = { ...message, metadata: { ...message.metadata, generation: { provider: "gemini", model: "original" } } };
const aside = { ...message, metadata: { ...message.metadata, agentAside: true } };
const user = { ...message, role: "user" };
assert.deepEqual(withMessageGenerations([existing, aside, user], [call]), [existing, aside, user]);
});
+37
View File
@@ -0,0 +1,37 @@
export function createPdf(pages: string[], encrypted = false): Uint8Array {
const fontId = 3 + pages.length * 2;
const objects = [
"<< /Type /Catalog /Pages 2 0 R >>",
`<< /Type /Pages /Kids [${pages.map((_, index) => `${3 + index * 2} 0 R`).join(" ")}] /Count ${pages.length} >>`,
];
for (let index = 0; index < pages.length; index += 1) {
const pageId = 3 + index * 2;
const contentId = pageId + 1;
const text = pages[index]!;
const operators = Array.from({ length: Math.ceil(text.length / 100) }, (_, partIndex) => {
const part = text.slice(partIndex * 100, (partIndex + 1) * 100);
const escaped = part.replaceAll("\\", "\\\\").replaceAll("(", "\\(").replaceAll(")", "\\)");
return `(${escaped}) Tj`;
});
const content = text ? `BT /F1 12 Tf 72 720 Td ${operators.join(" ")} ET` : "";
objects.push(
`<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Resources << /Font << /F1 ${fontId} 0 R >> >> /Contents ${contentId} 0 R >>`,
`<< /Length ${Buffer.byteLength(content)} >>\nstream\n${content}\nendstream`,
);
}
objects.push("<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>");
const encryptionId = objects.length + 1;
if (encrypted) objects.push(`<< /Filter /Standard /V 1 /R 2 /O <${"00".repeat(32)}> /U <${"00".repeat(32)}> /P -4 >>`);
let output = "%PDF-1.4\n";
const offsets = [0];
objects.forEach((object, index) => {
offsets.push(Buffer.byteLength(output));
output += `${index + 1} 0 obj\n${object}\nendobj\n`;
});
const xrefOffset = Buffer.byteLength(output);
output += `xref\n0 ${objects.length + 1}\n0000000000 65535 f \n`;
for (const offset of offsets.slice(1)) output += `${String(offset).padStart(10, "0")} 00000 n \n`;
output += `trailer\n<< /Size ${objects.length + 1} /Root 1 0 R${encrypted ? ` /Encrypt ${encryptionId} 0 R` : ""} >>\nstartxref\n${xrefOffset}\n%%EOF`;
return new TextEncoder().encode(output);
}
+63
View File
@@ -0,0 +1,63 @@
import assert from "node:assert/strict";
import test from "node:test";
import { extractPdfText, hasPdfMagic } from "../src/llm/pdf-text.js";
import { createPdf } from "./pdf-fixture.js";
test("extracts selectable text with page markers and selected-page support", async () => {
const bytes = createPdf(["Quarterly revenue was 42.", "Costs were 18."]);
const result = await extractPdfText(bytes, [2]);
assert.equal(result.status, "ok");
assert.equal(result.pageCount, 2);
assert.deepEqual(result.pages, [2]);
assert.match(result.text, /--- Page 2 ---/);
assert.match(result.text, /Costs were 18\./);
assert.doesNotMatch(result.text, /Quarterly revenue/);
});
test("reports PDFs with no selectable text clearly", async () => {
const result = await extractPdfText(createPdf([""]));
assert.equal(result.status, "no_text");
assert.match(result.text, /No extractable text/);
});
test("reports encrypted PDFs clearly", async () => {
const result = await extractPdfText(createPdf(["Secret"], true));
assert.equal(result.status, "encrypted");
assert.match(result.text, /encrypted and requires a password/);
});
test("reports page-free PDFs and rejects invalid requested pages", async () => {
const empty = await extractPdfText(createPdf([]));
assert.equal(empty.status, "no_pages");
assert.match(empty.text, /no pages/);
const outOfRange = await extractPdfText(createPdf(["Only page"]), [2]);
assert.equal(outOfRange.status, "error");
assert.match(outOfRange.text, /has 1 pages/);
});
test("limits each extraction to 30 pages and preserves the full page count", async () => {
const result = await extractPdfText(createPdf(Array.from({ length: 31 }, (_, index) => `Text on page ${index + 1}.`)));
assert.equal(result.status, "ok");
assert.equal(result.pageCount, 31);
assert.equal(result.pages.length, 30);
assert.equal(result.pages.at(-1), 30);
});
test("caps accumulated extracted text at the caller limit", async () => {
const result = await extractPdfText(createPdf(["Long sentence. ".repeat(200)]), undefined, 50);
assert.equal(result.status, "ok");
assert.equal(result.truncated, true);
assert.ok(result.text.length <= 50);
});
test("terminates an over-time worker and returns an explicit timeout result", async () => {
const result = await extractPdfText(createPdf(["Small document"]), undefined, 12_000, 1);
assert.equal(result.status, "error");
assert.match(result.text, /time limit/);
});
test("recognizes PDF magic in a mislabeled or prefixed response", () => {
assert.equal(hasPdfMagic(new TextEncoder().encode("%PDF-1.4")), true);
assert.equal(hasPdfMagic(new TextEncoder().encode(`${" ".repeat(500)}%PDF-1.7`)), true);
assert.equal(hasPdfMagic(new TextEncoder().encode("<html>not a PDF</html>")), false);
});
+2 -7
View File
@@ -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: [],
});
});
+21 -9
View File
@@ -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");
});
+80
View File
@@ -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");
});
+174
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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;
+81 -1
View File
@@ -29,11 +29,12 @@ Default dev URL: `http://localhost:5173`
- On startup, the app checks `GET /v1/auth/session`.
- If backend runs with `ADMIN_TOKEN`, sign in using that token.
- If backend runs in open mode (`ADMIN_TOKEN` unset), you can continue without a token.
- The entered token is stored in browser `localStorage` and can be cleared via Logout.
- The entered token is stored in browser `localStorage` and can be cleared via Logout. When browser storage is blocked, authentication still works for the current page; sign in again after reloading.
## 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
@@ -43,6 +44,7 @@ Default dev URL: `http://localhost:5173`
prefixes, so `plan` also finds `planning`.
- Right panel:
- Chat mode: transcript + provider/model controls.
- Saved assistant replies show their received date/time in your local timezone and the provider/model used for that response, with Copy and Fork actions aligned beneath the reply on mobile and desktop. The model label stays with the response when you change models; older replies without a reliable record show “Model not recorded.” Copy preserves the message's Markdown; Fork starts a conversation through that reply.
- Search mode: top AI answer block + Google-style Exa results view.
- Composer adapts to the active item:
- Chat sends `POST /v1/chat-completions/stream` (SSE).
@@ -59,4 +61,82 @@ Client API contract docs:
## Routes
- `/`: full Sybil app (sidebar + chat/search workspace)
- `/lite`: lightweight chat, web search, and Agent workspace for e-readers and older smartphones
- `/search?q=bitcoin+price`: standalone search page that renders only the search query box and results panel
## Lightweight interface
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.
Detection is intentionally limited: [user agent identification is unreliable](https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/Browser_detection_using_the_user_agent), and [Save-Data](https://developer.mozilla.org/en-US/docs/Web/API/NetworkInformation/saveData) is an explicit user preference available only in some browsers. Readers without recognizable browser data can bookmark `/lite`.
Lite follows the existing workspace layout: sidebar, compact conversation header, scrolling transcript, and bottom composer. It uses the same Inter font stack and SYBIL wordmark, the original chat bubble shapes, and the shared assistant metadata/Copy footer. Solid, high-contrast light surfaces replace gradients and translucent backgrounds; there are no character images, animations, or added welcome/tagline copy. Mobile uses an instant sidebar toggle, and pinch zoom remains available.
The route does not load the full workspace stylesheet or animated Agent presentation. Typography, bubble geometry, and assistant reply actions are shared with the full interface. Markdown tables and code scroll within the transcript; history and ordinary transcripts render in batches of 30. Images are not rendered automatically. Regular chats and searches consume the existing SSE APIs but publish completed responses, avoiding repeated token-by-token screen redraws. Refresh restores saved content and reconnects to selected active runs. Chat retries retain the same submission ID.
The Agent view loads only when opened and reuses the shared room hook, durable outbox, older history, and read tracking. It receives completed message updates, supports failed-delivery retries, and downloads attachments only when requested. Lite does not start notification presence polling or register a service worker. Existing browser workers/subscriptions are unaffected by switching views; sign-out keeps the shared revocation behavior.
The focused controls support reading and sending text, model selection (including custom model names), saved-history search, web searches, and Agent conversations. Uploads, chat settings, fork management, Quick Questions, and notification settings remain accessible through **Full interface**. Existing chat settings and attachments remain part of the shared conversation context.
### Code boundaries
- `main.tsx`, `root-router.tsx`, and `lib/ui-mode.ts` choose and lazily load one presentation before its UI assets download. Mode links perform document navigation to keep global styles isolated.
- `pages/lite-route-page.tsx` and `pages/lite.css` own Lite's markup and appearance. Full UI components do not need Lite conditionals.
- `typography.css`, `components/chat/message-bubble.css`, and `AssistantMessageFooter` keep fonts, bubble geometry, and reply actions consistent across the two presentations. Lite supplies flat color values through CSS variables.
- `hooks/use-lite-workspace.ts` adapts workspace state to completion-only rendering. Both presentations use `lib/api.ts`, `lib/workspace-domain.ts` (model preferences, history payloads, attachment context, URLs, and retry rules), `useSessionAuth`, `useWorkspaceSearch`, and sanitized `MarkdownContent`.
- `components/lite/lite-agent.tsx` supplies a simple presentation over `useAgentRoom`; transport, delivery identities, attachments, and read-state semantics stay shared.
Production syntax targets Chrome 87, Firefox 78, and Safari 14. Browsers still need JavaScript modules, dynamic imports, Fetch/ReadableStream, AbortController, and BigInt; Agent additionally uses WebSocket and browser storage. A small feature-detected shim supplies `Array.at`, used by the Markdown dependency, and secure UUID creation falls back to `crypto.getRandomValues`. This is not an ES5 frontend or a guarantee for every Kindle firmware. Browsers without module support show an explanatory fallback. Physical Kindle testing remains necessary.
### Verification
Run `npm test` and `npm run build`, then `npm run preview -- --host 127.0.0.1 --port 5197`. Browser fixtures mock all API calls and require Playwright Chromium (set `PLAYWRIGHT_MODULE` / `CHROME_EXECUTABLE` if installed elsewhere):
```bash
node tests/ui-mode.browser.mjs
node tests/lite-workspace.browser.mjs
node tests/lite-workspace-recovery.browser.mjs
node tests/lite-agent.browser.mjs
```
Set `LITE_ARTIFACT_DIR=/tmp/sybil-lite-qa` on the workspace fixture to save desktop and 320/390/600 px screenshots. Checks cover routing overrides, blocked storage, asset isolation, shared typography and bubble shapes, absence of added flavor text, composer placement, Markdown without native `Array.at`, chat submission/retry, search, saved-history navigation, active-run recovery, Agent delivery, and narrow-screen overflow. Chromium emulation does not reproduce e-ink refresh behavior or older engine implementations.
## Mobile web
Installed Sybil uses `standalone` display, retaining the system status bar where the browser supports it. The viewport keeps pinch zoom disabled. Compact regular-chat replies use the transcript width and the active provider/model appears beneath the title; Agent keeps its existing layout.
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.
**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.
+5 -1
View File
@@ -8,7 +8,7 @@
<meta name="theme-color" content="#0f172a" />
<meta name="mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />
<meta name="apple-mobile-web-app-status-bar-style" content="default" />
<meta name="apple-mobile-web-app-title" content="Sybil" />
<meta name="format-detection" content="telephone=no" />
<link rel="manifest" href="/manifest.webmanifest" />
@@ -20,6 +20,10 @@
</head>
<body>
<div id="app"></div>
<noscript>Sybil needs JavaScript. Enable it in your browser to use the lightweight UI at /lite.</noscript>
<script nomodule>
document.getElementById("app").textContent = "This browser cannot run Sybil. A browser with JavaScript module support is required, including for the lightweight UI.";
</script>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

+2 -3
View File
@@ -5,8 +5,7 @@
"description": "Sybil chat and search workspace",
"start_url": "/",
"scope": "/",
"display": "fullscreen",
"display_override": ["fullscreen", "standalone"],
"display": "standalone",
"background_color": "#0b0718",
"theme_color": "#0f172a",
"icons": [
@@ -23,7 +22,7 @@
"purpose": "any"
},
{
"src": "/icons/icon-maskable-512.png",
"src": "/icons/icon-maskable-compact-512.png",
"sizes": "512x512",
"type": "image/png",
"purpose": "maskable"
+184 -457
View File
File diff suppressed because it is too large Load Diff
@@ -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>
);
}
@@ -46,23 +46,44 @@ function dayLabel(date: Date | null) {
today.setDate(today.getDate() - 1);
return dayKey(date) === dayKey(today) ? "Yesterday" : dayFormat.format(date);
}
function measureComposerHeight(textarea: HTMLTextAreaElement) {
const measurement = textarea.cloneNode(false) as HTMLTextAreaElement;
measurement.removeAttribute("id");
measurement.removeAttribute("name");
measurement.setAttribute("aria-hidden", "true");
measurement.tabIndex = -1;
measurement.value = textarea.value;
Object.assign(measurement.style, {
position: "fixed", left: "-10000px", top: "0", visibility: "hidden", pointerEvents: "none",
width: `${textarea.getBoundingClientRect().width}px`, height: "0px", minHeight: "0px",
maxHeight: "none", overflow: "hidden", resize: "none",
});
textarea.parentElement?.appendChild(measurement);
const height = measurement.scrollHeight;
measurement.remove();
return height;
}
function toolName(value: unknown) {
return typeof value === "string" ? value.replace(/_/g, " ") : "Tool";
}
export const AgentBubble = memo(function AgentBubble({ message, animate, onRetry, download, showThinkingIndicator = false }: { message: Message; animate: boolean; onRetry: (id: string) => void; download: AgentRoomHookResult["downloadAttachment"]; showThinkingIndicator?: boolean }) {
export function AgentThinkingDots({ label = "Sybil is thinking" }: { label?: string }) {
return <span className="agent-room__typing-dots" aria-label={label} role="status"><i /><i /><i /></span>;
}
export const AgentBubble = memo(function AgentBubble({ message, animate, onRetry, download, showThinkingIndicator = false, isPending = false }: { message: Message; animate: boolean; onRetry: (id: string) => void; download: AgentRoomHookResult["downloadAttachment"]; showThinkingIndicator?: boolean; isPending?: boolean }) {
const own = message.role === "user";
const info = metadata(message);
const status = typeof info.status === "string" ? info.status : "complete";
const failed = status === "failed" || status === "unconfirmed";
const thinking = showThinkingIndicator && !own && status === "sending" && !message.content.trim();
const thinking = showThinkingIndicator && !own && (isPending ?? status === "sending") && !message.content.trim();
const date = dateOf(message.createdAt);
return (
<article className={`agent-room__message ${own ? "is-own" : "is-agent"}`} data-agent-message-id={message.id} data-message-status={status} data-animation={animate ? "enter" : undefined} aria-label={own ? "Your message" : "Sybil's message"}>
{!own ? <span className="agent-room__message-avatar" aria-hidden="true"><img src="/character-still.png" alt="" draggable={false} /></span> : null}
<div className="agent-room__message-content">
<div className={`message-bubble${own ? " message-bubble--user" : ""}`}>
{own ? <p className="agent-room__plain-message">{message.content}</p> : thinking ? <span className="inline-flex items-center gap-1" aria-label="Sybil is thinking" role="status"><span className="inline-block h-1.5 w-1.5 animate-bounce rounded-full bg-muted-foreground [animation-delay:0ms]" /><span className="inline-block h-1.5 w-1.5 animate-bounce rounded-full bg-muted-foreground [animation-delay:140ms]" /><span className="inline-block h-1.5 w-1.5 animate-bounce rounded-full bg-muted-foreground [animation-delay:280ms]" /></span> : <MarkdownContent markdown={message.content} openLinksInNewTab allowImages={false} />}
{own ? <p className="agent-room__plain-message">{message.content}</p> : thinking ? <AgentThinkingDots /> : <MarkdownContent markdown={message.content} openLinksInNewTab allowImages={false} />}
{agentAttachments(message.metadata, message.role).map(file => <AgentAttachmentCard key={file.id} file={file} download={download} inline={message.role === "assistant"} />)}
</div>
{own && failed && typeof info.error === "string" ? <div className="agent-attachment__error" role="alert">{info.error}</div> : null}
@@ -284,8 +305,10 @@ export function AgentConversation({ room, onOpenSidebar, isVisible = true }: Pro
useLayoutEffect(() => {
const textarea = textareaRef.current;
if (!textarea) return;
textarea.style.height = "0px";
textarea.style.height = `${Math.min(156, Math.max(46, textarea.scrollHeight))}px`;
// Measure offscreen: collapsing a focused textarea can make its scroll
// parent reveal the caret, while its own scrollHeight cannot measure a
// smaller draft until its current height has been removed.
textarea.style.height = `${Math.min(156, Math.max(46, measureComposerHeight(textarea)))}px`;
}, [draft]);
const updateDraft = (value: string) => {
@@ -1,23 +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="shrink-0 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>
{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,76 @@
.assistant-message-footer {
position: relative;
color: var(--message-footer-color, hsl(var(--muted-foreground)));
}
.assistant-message-footer__metadata,
.assistant-message-footer__status {
font-size: .75rem;
line-height: 1.25rem;
overflow-wrap: anywhere;
}
.assistant-message-footer__metadata time {
white-space: nowrap;
}
.assistant-message-footer__actions {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: .25rem;
margin-left: -.5rem;
}
.assistant-message-footer__action {
display: inline-flex;
height: 2.5rem;
min-height: 2.5rem;
align-items: center;
gap: .375rem;
border: 0;
border-radius: var(--radius, 0);
padding: 0 .5rem;
font: inherit;
font-size: .75rem;
line-height: 1rem;
color: inherit;
background: none;
cursor: pointer;
transition: var(--message-footer-transition, color 150ms cubic-bezier(.4, 0, .2, 1), background-color 150ms cubic-bezier(.4, 0, .2, 1));
}
.assistant-message-footer__action svg {
width: .875rem;
height: .875rem;
}
.assistant-message-footer__action:hover {
background: var(--message-footer-hover-background, rgb(167 139 250 / .12));
color: var(--message-footer-hover-color, #ede9fe);
}
.assistant-message-footer__action:focus-visible {
outline: 2px solid var(--message-footer-focus-color, hsl(var(--ring)));
}
.assistant-message-footer__action:disabled {
cursor: wait;
opacity: .5;
}
.assistant-message-footer__status {
display: block;
}
.assistant-message-footer__status--hidden {
position: absolute;
width: 1px;
height: 1px;
padding: 0;
margin: -1px;
overflow: hidden;
clip: rect(0, 0, 0, 0);
white-space: nowrap;
border-width: 0;
}
@@ -0,0 +1,58 @@
import { useEffect, useRef, useState } from "preact/hooks";
import { Check, Copy, GitFork } from "lucide-preact";
import type { Message } from "@/lib/api";
import { getMessageGenerationLabel } from "@/lib/message-generation";
import "./assistant-message-footer.css";
const receivedFormat = new Intl.DateTimeFormat(undefined, {
year: "numeric", month: "short", day: "numeric", hour: "numeric", minute: "2-digit",
});
const actionClass = "assistant-message-footer__action";
export function AssistantMessageFooter({ message, onFork, isForking = false }: {
message: Message;
onFork?: (messageId: string) => void;
isForking?: boolean;
}) {
const [copyState, setCopyState] = useState<"idle" | "copied" | "failed">("idle");
const resetTimer = useRef<ReturnType<typeof setTimeout>>();
useEffect(() => () => clearTimeout(resetTimer.current), []);
const copy = async () => {
clearTimeout(resetTimer.current);
try {
await navigator.clipboard.writeText(message.content);
setCopyState("copied");
resetTimer.current = setTimeout(() => setCopyState("idle"), 2000);
} catch {
setCopyState("failed");
}
};
const received = new Date(message.createdAt);
const hasDate = Number.isFinite(received.getTime());
const generation = getMessageGenerationLabel(message);
return (
<div className="assistant-message-footer" data-assistant-footer={message.id} data-mobile-swipe-ignore>
<div className="assistant-message-footer__metadata">
{hasDate ? <><time dateTime={message.createdAt} title={`Received ${received.toLocaleString()}`}>
{receivedFormat.format(received)}
</time><span aria-hidden="true"> · </span></> : null}
<span data-message-generation>{generation ?? "Model not recorded"}</span>
</div>
<div className="assistant-message-footer__actions" role="group" aria-label="Message actions">
{message.content.trim() ? <button type="button" className={actionClass} onClick={() => void copy()} title="Copy message" aria-label="Copy message">
{copyState === "copied" ? <Check aria-hidden="true" /> : <Copy aria-hidden="true" />}
<span>{copyState === "copied" ? "Copied" : "Copy"}</span>
</button> : null}
{onFork ? <button type="button" className={actionClass} onClick={() => onFork(message.id)} disabled={isForking} title="Fork chat from this message" aria-label="Fork chat from this message">
<GitFork aria-hidden="true" />
<span>Fork</span>
</button> : null}
</div>
<span className={`assistant-message-footer__status${copyState === "failed" ? "" : " assistant-message-footer__status--hidden"}`} role="status" aria-live="polite">
{copyState === "copied" ? "Message copied." : copyState === "failed" ? "Could not copy. Select the message text and use your browser’s Copy command." : ""}
</span>
</div>
);
}
+10 -10
View File
@@ -2,8 +2,9 @@ import { useEffect, useLayoutEffect, useMemo, useRef, useState } from "preact/ho
import type { ComponentChildren, JSX } from "preact";
import { cn } from "@/lib/utils";
import { ChatAttachmentList } from "@/components/chat/chat-attachment-list";
import { AssistantMessageFooter } from "@/components/chat/assistant-message-footer";
import { getMessageAttachments, type Message } from "@/lib/api";
import { asStreamingAssistantMetadata } from "@/lib/chat-stream-presentation";
import { asStreamingAssistantMetadata, isInlineAgentReplyPending } from "@/lib/chat-stream-presentation";
import { AgentBubble } from "@/components/agent/agent-conversation";
import { MarkdownContent } from "@/components/markdown/markdown-content";
import { ChevronDown, ChevronUp, Globe2, Link2, Wrench } from "lucide-preact";
@@ -12,7 +13,8 @@ type Props = {
messages: Message[];
isLoading: boolean;
isSending: boolean;
onMessageContextMenu?: (event: MouseEvent, messageId: string) => void;
onForkMessage?: (messageId: string) => void;
isForking?: boolean;
};
type ToolLogMetadata = {
@@ -538,7 +540,7 @@ export function StreamingAssistantPresentation({ message, isSending }: { message
);
}
export function ChatMessagesPanel({ messages, isLoading, isSending, onMessageContextMenu }: Props) {
export function ChatMessagesPanel({ messages, isLoading, isSending, onForkMessage, isForking }: Props) {
const hasPendingAssistant = messages.some((message) => message.id.startsWith("temp-assistant-"));
const renderItems = useMemo(() => buildMessageRenderItems(messages), [messages]);
const toolCallMessageIDs = useMemo(() => getToolCallMessageIDs(messages), [messages]);
@@ -604,7 +606,7 @@ export function ChatMessagesPanel({ messages, isLoading, isSending, onMessageCon
if (message.role === "assistant" && metadata.agentAside === true) {
return (
<div key={message.id} className="flex justify-start" data-agent-aside="true">
<AgentBubble message={message} animate={message.id.startsWith("temp-assistant-")} onRetry={() => {}} download={noAgentAttachmentDownload} showThinkingIndicator />
<AgentBubble message={message} animate={message.id.startsWith("temp-assistant-")} onRetry={() => {}} download={noAgentAttachmentDownload} showThinkingIndicator isPending={isInlineAgentReplyPending(message, isSending)} />
</div>
);
}
@@ -618,13 +620,8 @@ export function ChatMessagesPanel({ messages, isLoading, isSending, onMessageCon
"min-w-0 space-y-3",
isUser
? "message-bubble message-bubble--user max-w-[87%] md:max-w-[78%]"
: "max-w-[85%] text-base leading-7 text-violet-50"
: "w-full max-w-full md:w-auto md:max-w-[85%] text-base leading-7 text-violet-50"
)}
onContextMenu={
message.role === "assistant" && !message.id.startsWith("temp-") && onMessageContextMenu
? (event) => onMessageContextMenu(event, message.id)
: undefined
}
>
{attachments.length ? <ChatAttachmentList attachments={attachments} tone={isUser ? "user" : "assistant"} /> : null}
{streamingAssistantMetadata ? (
@@ -642,6 +639,9 @@ export function ChatMessagesPanel({ messages, isLoading, isSending, onMessageCon
className={cn("[&_a]:text-inherit [&_a]:underline", !isUser && "leading-[1.82] text-violet-50")}
/>
) : null}
{message.role === "assistant" && !message.id.startsWith("temp-") ? (
<AssistantMessageFooter message={message} onFork={onForkMessage} isForking={isForking} />
) : null}
</div>
</div>
);
@@ -0,0 +1,30 @@
/* Geometry is shared across regular chat, Agent, and the lightweight view. */
.message-bubble {
min-width: 0;
padding: 13px 17px;
border: 1px solid var(--message-bubble-border, hsl(256 37% 57% / .18));
border-radius: 18px 18px 18px 5px;
background: var(--message-bubble-background, linear-gradient(150deg, hsl(251 36% 15% / .93), hsl(244 35% 11% / .93)));
box-shadow: var(--message-bubble-shadow, 0 3px 12px hsl(239 55% 2% / .13));
font-size: 14px;
line-height: 1.68;
overflow-wrap: anywhere;
}
.message-bubble--user {
border-color: var(--message-bubble-user-border, hsl(266 80% 72% / .3));
border-radius: 18px 18px 5px 18px;
background: var(--message-bubble-user-background, linear-gradient(135deg, hsl(264 59% 33% / .86), hsl(259 58% 26% / .9)));
color: var(--message-bubble-user-color, hsl(265 55% 97%));
}
.message-bubble .md-content {
font-size: inherit;
line-height: inherit;
}
@media (max-width: 767px) {
.message-bubble {
padding: 11px 14px;
}
}
+118
View File
@@ -0,0 +1,118 @@
import { useEffect, useId, useLayoutEffect, useMemo, useRef, useState } from "preact/hooks";
import { Check, ChevronDown } from "lucide-preact";
import { cn } from "@/lib/utils";
type ModelComboboxProps = {
options: string[];
value: string;
onChange: (value: string) => void;
disabled?: boolean;
className?: string;
id?: string;
label?: string;
inlineOptions?: boolean;
};
export function ModelCombobox({ options, value, onChange, disabled = false, className, id, label = "Model", inlineOptions = false }: ModelComboboxProps) {
const generatedId = useId();
const fieldId = id || generatedId;
const [open, setOpen] = useState(false);
const [draftValue, setDraftValue] = useState(value);
const [activeIndex, setActiveIndex] = useState(-1);
const rootRef = useRef<HTMLDivElement>(null);
const inputRef = useRef<HTMLInputElement>(null);
const normalizedDraftValue = draftValue.trim();
const choices = useMemo(() => {
const needle = normalizedDraftValue.toLowerCase();
const listed = options.filter(option => !needle || option.toLowerCase().includes(needle)).map(option => ({ value: option, label: option }));
return normalizedDraftValue && !options.includes(normalizedDraftValue)
? [{ value: normalizedDraftValue, label: `Use "${normalizedDraftValue}"` }, ...listed] : listed;
}, [normalizedDraftValue, options]);
useLayoutEffect(() => { if (!open) setDraftValue(value); }, [open, value]);
useLayoutEffect(() => {
if (open) inputRef.current?.focus();
}, [open]);
useEffect(() => {
if (activeIndex >= 0) document.getElementById(`${fieldId}-option-${activeIndex}`)?.scrollIntoView({ block: "nearest" });
}, [activeIndex, fieldId]);
const commit = (next = normalizedDraftValue) => {
if (next !== value) onChange(next);
setDraftValue(next);
setActiveIndex(-1);
setOpen(false);
};
useEffect(() => {
if (!open) return;
const handlePointerDown = (event: PointerEvent) => {
if (!rootRef.current?.contains(event.target as Node)) commit();
};
window.addEventListener("pointerdown", handlePointerDown);
return () => window.removeEventListener("pointerdown", handlePointerDown);
}, [open, normalizedDraftValue, value, onChange]);
return <div className="relative min-w-0" ref={rootRef} onFocusOut={(event) => {
if (open && !rootRef.current?.contains(event.relatedTarget as Node | null)) commit();
}} onKeyDown={(event) => {
if (event.key === "Escape" && open) {
event.preventDefault();
event.stopPropagation();
setOpen(false);
setDraftValue(value);
inputRef.current?.focus();
}
}}>
<div className={cn("flex h-10 min-w-56 items-center rounded-lg border border-violet-300/22 bg-background/72 pl-3 text-sm shadow-[inset_0_1px_0_hsl(255_100%_92%_/_0.06)] focus-within:border-violet-300/45 focus-within:ring-1 focus-within:ring-ring/70", className)}>
<input
ref={inputRef}
id={fieldId}
role="combobox"
aria-label={label}
aria-autocomplete="list"
aria-expanded={open}
aria-controls={`${fieldId}-options`}
aria-activedescendant={open && activeIndex >= 0 && choices[activeIndex] ? `${fieldId}-option-${activeIndex}` : undefined}
value={draftValue}
onFocus={() => { if (!disabled) { setDraftValue(value); setActiveIndex(-1); setOpen(true); } }}
onInput={(event) => { setDraftValue(event.currentTarget.value); setActiveIndex(-1); setOpen(true); }}
onKeyDown={(event) => {
if (event.key === "ArrowDown" || event.key === "ArrowUp") {
event.preventDefault();
setOpen(true);
setActiveIndex(current => {
if (!choices.length) return -1;
if (current < 0) return event.key === "ArrowDown" ? 0 : choices.length - 1;
return (current + (event.key === "ArrowDown" ? 1 : -1) + choices.length) % choices.length;
});
} else if (event.key === "Enter") {
event.preventDefault();
commit(open && choices[activeIndex] ? choices[activeIndex].value : normalizedDraftValue);
}
}}
className="h-full min-w-0 flex-1 bg-transparent outline-none placeholder:text-muted-foreground"
placeholder="Select or type model"
disabled={disabled}
/>
<button type="button" className="flex h-full w-11 shrink-0 items-center justify-center text-muted-foreground focus-visible:outline focus-visible:outline-2 focus-visible:outline-ring disabled:opacity-50"
onClick={() => { if (open) commit(); else { setDraftValue(value); setActiveIndex(-1); setOpen(true); } }} disabled={disabled}
aria-label={`Toggle ${label.toLowerCase()} options`} aria-expanded={open} aria-controls={`${fieldId}-options`} tabIndex={-1}>
<ChevronDown aria-hidden="true" className="h-4 w-4" />
</button>
</div>
{open ? <div className={cn("z-50 mt-2 w-full rounded-lg border border-violet-300/20 bg-[hsl(238_48%_7%)] p-1 shadow-2xl shadow-black/45", !inlineOptions && "absolute right-0")}>
<div id={`${fieldId}-options`} role="listbox" aria-label={`${label} options`} className="max-h-56 overflow-y-auto overscroll-contain">
{choices.map((option, index) => <button key={option.value} id={`${fieldId}-option-${index}`} type="button" role="option" tabIndex={-1}
aria-selected={option.value === value}
className={cn("flex min-h-11 w-full items-center gap-2 rounded-md px-2 py-2 text-left text-sm hover:bg-violet-400/12", activeIndex === index && "bg-violet-400/12")}
onPointerDown={event => event.preventDefault()}
onClick={() => commit(option.value)}>
<Check aria-hidden="true" className={cn("h-4 w-4 shrink-0", option.value === value ? "opacity-100" : "opacity-0")} />
<span className="truncate">{option.label}</span>
</button>)}
{!choices.length ? <p className="px-2 py-2 text-sm text-muted-foreground">No models found</p> : null}
</div>
</div> : null}
</div>;
}
+225
View File
@@ -0,0 +1,225 @@
import { useEffect, useLayoutEffect, useMemo, useRef, useState } from "preact/hooks";
import { SendHorizontal } from "lucide-preact";
import { useAgentRoom, type AgentRoomHookResult } from "@/hooks/use-agent-room";
import { MarkdownContent } from "@/components/markdown/markdown-content";
import { agentTranscriptMessages } from "@/lib/agent-room-presentation";
import { agentAttachments, attachmentSize, type AgentAttachment } from "@/lib/agent-attachments";
const DRAFT_KEY = "sybil.pi-root.draft";
const timeFormat = new Intl.DateTimeFormat(undefined, { hour: "numeric", minute: "2-digit" });
function readDraft() {
try { return sessionStorage.getItem(DRAFT_KEY) || ""; } catch { return ""; }
}
function saveDraft(value: string) {
try {
if (value) sessionStorage.setItem(DRAFT_KEY, value);
else sessionStorage.removeItem(DRAFT_KEY);
} catch { /* Draft storage is optional; the shared outbox handles durable delivery. */ }
}
function LiteAgentAttachment({ file, download }: {
file: AgentAttachment;
download: AgentRoomHookResult["downloadAttachment"];
}) {
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const request = useRef<AbortController | null>(null);
useEffect(() => () => request.current?.abort(), []);
const retrieve = async () => {
if (request.current) return;
const controller = new AbortController();
request.current = controller;
setBusy(true);
setError(null);
try {
const blob = await download(file, controller.signal);
if (controller.signal.aborted) return;
const url = URL.createObjectURL(blob);
const link = document.createElement("a");
link.href = url;
link.download = file.filename;
document.body.appendChild(link);
link.click();
link.remove();
setTimeout(() => URL.revokeObjectURL(url), 1000);
} catch (failure) {
if (!controller.signal.aborted) setError(failure instanceof Error ? failure.message : "Download failed.");
} finally {
request.current = null;
if (!controller.signal.aborted) setBusy(false);
}
};
return <li>
<span>{file.filename} ({attachmentSize(file.sizeBytes)})</span>{" "}
<button type="button" disabled={busy} onClick={() => void retrieve()} aria-label={`Download ${file.filename}`}>
{busy ? "Downloading…" : "Download"}
</button>
{error ? <p className="lite-error" role="alert">{error}</p> : null}
</li>;
}
/** Mounted only while Agent is selected; protocol, outbox and read state stay shared. */
export function LiteAgent() {
const room = useAgentRoom(true);
const [draft, setDraft] = useState(readDraft);
const [sending, setSending] = useState(false);
const [sendError, setSendError] = useState<string | null>(null);
const sendingRef = useRef(false);
const mounted = useRef(true);
const draftRef = useRef(draft);
const end = useRef<HTMLDivElement>(null);
const scroller = useRef<HTMLDivElement>(null);
const viewport = useRef({ pinned: true, top: 0, height: 0, firstId: null as string | null });
const messages = useMemo(() => agentTranscriptMessages(room.messages), [room.messages]);
const uploads = room.uploadQueue.snapshot();
const pendingUploads = uploads.some(file => file.status !== "ready");
useEffect(() => () => { mounted.current = false; }, []);
useLayoutEffect(() => {
const element = scroller.current;
if (!element || room.isLoading) return;
const previous = viewport.current;
const firstId = messages[0]?.id ?? null;
if (previous.pinned) element.scrollTop = element.scrollHeight;
else if (previous.firstId && firstId !== previous.firstId && messages.some(message => message.id === previous.firstId)) {
// Keep the existing messages in place when an older page is prepended.
element.scrollTop = previous.top + element.scrollHeight - previous.height;
}
previous.top = element.scrollTop;
previous.height = element.scrollHeight;
previous.firstId = firstId;
}, [messages, room.isLoading, room.isTyping]);
useEffect(() => {
const markVisibleRead = () => {
if (room.isLoading || document.visibilityState !== "visible" || !document.hasFocus()) return;
const position = end.current?.getBoundingClientRect();
const viewport = scroller.current?.getBoundingClientRect();
if (position && viewport && viewport.width > 0 && viewport.height > 0 && position.top >= Math.max(0, viewport.top) && position.top <= Math.min(window.innerHeight, viewport.bottom)) room.markRead();
};
const scrollElement = scroller.current;
markVisibleRead();
scrollElement?.addEventListener("scroll", markVisibleRead, { passive: true });
window.addEventListener("focus", markVisibleRead);
window.addEventListener("resize", markVisibleRead);
document.addEventListener("visibilitychange", markVisibleRead);
return () => {
scrollElement?.removeEventListener("scroll", markVisibleRead);
window.removeEventListener("focus", markVisibleRead);
window.removeEventListener("resize", markVisibleRead);
document.removeEventListener("visibilitychange", markVisibleRead);
};
}, [room.markRead, room.isLoading, messages]);
const updateDraft = (value: string) => {
draftRef.current = value;
setDraft(value);
saveDraft(value);
};
const submit = async () => {
const content = draftRef.current.trim();
if (sendingRef.current || (!content && !uploads.length) || pendingUploads || room.isLoading) return;
sendingRef.current = true;
setSending(true);
setSendError(null);
try {
const attachments = room.uploadQueue.ready();
await room.sendMessage(content, attachments, () => {
// A saved outbox row owns retries from here, even if the HTTP response is lost.
saveDraft("");
draftRef.current = "";
if (mounted.current) setDraft("");
});
} catch (failure) {
if (mounted.current) setSendError(failure instanceof Error ? failure.message : "Message could not be sent.");
} finally {
sendingRef.current = false;
if (mounted.current) setSending(false);
}
};
return <section className="lite-agent" aria-label="Sybil Agent">
<div className="lite-agent-connection" aria-label="Agent connection">
<span className="lite-muted" role="status">
{room.isLoading ? "Loading conversation…" : room.connection === "connected" ? "Connected" : room.connection === "connecting" ? "Connecting…" : room.connection === "reconnecting" ? "Reconnecting…" : "Offline"}
</span>
<a href="#lite-agent-end">Latest messages</a>
<button type="button" onClick={room.retry} disabled={room.isLoading}>Reconnect</button>
</div>
<div className="lite-agent-scroll" ref={scroller} onScroll={event => {
const element = event.currentTarget;
viewport.current.pinned = element.scrollHeight - element.scrollTop - element.clientHeight <= 24;
viewport.current.top = element.scrollTop;
viewport.current.height = element.scrollHeight;
}}>
<div className="lite-transcript" aria-label="Agent messages" aria-busy={room.isLoading}>
{room.error ? <p className="lite-error" role="alert">{room.error}</p> : null}
{room.hasOlder ? <button type="button" onClick={room.loadOlder} disabled={room.isLoadingOlder}>
{room.isLoadingOlder ? "Loading older messages…" : "Load older messages"}
</button> : null}
{room.olderError ? <p className="lite-error" role="alert">{room.olderError}</p> : null}
{messages.map(message => {
const info = message.metadata && typeof message.metadata === "object" && !Array.isArray(message.metadata)
? message.metadata as Record<string, unknown> : {};
const status = typeof info.status === "string" ? info.status : "complete";
const own = message.role === "user";
const failed = own && (status === "failed" || status === "unconfirmed");
const files = agentAttachments(message.metadata, message.role);
const date = new Date(message.createdAt);
return <article key={message.id} className={`lite-message${own ? " lite-message-user" : ""}`} data-agent-message-id={message.id} aria-label={own ? "Your message" : "Sybil's message"}>
<div className="lite-message-content">
<div className={`message-bubble${own ? " message-bubble--user" : ""}`}>
{own ? <p className="lite-plain-text">{message.content}</p>
: <MarkdownContent markdown={message.content} allowImages={false} />}
{files.length ? <ul className="lite-attachments">{files.map(file => <LiteAgentAttachment key={file.id} file={file} download={room.downloadAttachment} />)}</ul> : null}
</div>
<div className="lite-message-meta">
<span>{own ? "You" : "Sybil"}</span>
{Number.isFinite(date.getTime()) && date.getFullYear() >= 2000 ? <time dateTime={message.createdAt} title={date.toLocaleString()}>{timeFormat.format(date)}</time> : null}
{own && status === "sending" ? <span role="status">Sending…</span> : null}
{own && status === "queued" ? <span role="status">Queued</span> : null}
{failed ? <span className="lite-delivery-error" role="status">
{status === "unconfirmed" ? "Unconfirmed" : "Not sent"}{" "}
<button type="button" aria-label="Retry message" onClick={() => void room.retryMessage(message.id).catch(() => undefined)}>Retry</button>
</span> : null}
</div>
{failed && typeof info.error === "string" ? <p className="lite-error" role="alert">{info.error}</p> : null}
</div>
</article>;
})}
{room.isTyping ? <p className="lite-status" role="status">Sybil is thinking…</p> : null}
<div id="lite-agent-end" ref={end} />
</div>
</div>
<div className="lite-composer-shell">
<form className="lite-composer" onSubmit={event => { event.preventDefault(); void submit(); }}>
<label className="lite-visually-hidden" htmlFor="lite-agent-message">Message Sybil Agent</label>
<textarea id="lite-agent-message" rows={1} maxLength={40000} value={draft} disabled={sending} placeholder="Message Sybil Agent…"
onInput={event => updateDraft(event.currentTarget.value)}
onKeyDown={event => { if (event.key === "Enter" && !event.shiftKey && !event.isComposing) { event.preventDefault(); void submit(); } }} />
{uploads.length ? <div className="lite-attachments">
<p>Attachments saved with your draft</p>
<ul>{uploads.map(file => <li key={file.uploadId}>
{file.filename} — {file.status === "ready" ? "Ready to send" : "Open the full interface to resume this upload"}{" "}
<button type="button" disabled={sending} onClick={() => {
try { room.uploadQueue.remove(file.uploadId); setSendError(null); }
catch (error) { setSendError(error instanceof Error ? error.message : String(error)); }
}}>Remove</button>
</li>)}</ul>
</div> : null}
<div className="lite-composer-footer">
<button className="lite-primary lite-send" type="submit" aria-label="Send message" disabled={sending || room.isLoading || pendingUploads || (!draft.trim() && !uploads.length)}>
<SendHorizontal size={19} aria-hidden="true" />
</button>
</div>
{sendError ? <p className="lite-error" role="alert">{sendError}</p> : null}
</form>
</div>
</section>;
}
@@ -0,0 +1,119 @@
import { useLayoutEffect, useRef, useState } from "preact/hooks";
import { ArrowLeft, Bell, ChevronRight, Cpu, Keyboard, LoaderCircle, LogOut, Server, X } from "lucide-preact";
import { AgentNotifications } from "@/components/agent/agent-notifications";
import { ModelSettings, type ModelSettingsProps } from "@/components/settings/model-settings";
import { Button } from "@/components/ui/button";
import type { AuthMode } from "@/hooks/use-session-auth";
import { getApiBaseUrl } from "@/lib/api";
import { cn } from "@/lib/utils";
type Section = "notifications" | "models" | "connection";
const sections = [
{ id: "notifications", title: "Notifications", description: "Agent alerts and permissions", icon: Bell },
{ id: "models", title: "Models", description: "Chats and Quick Questions", icon: Cpu },
{ id: "connection", title: "Connection & session", description: "Server, sign-in, and shortcuts", icon: Server },
] as const;
function displayServerUrl() {
try {
const url = new URL(getApiBaseUrl(), window.location.href);
return `${url.origin}${url.pathname}`.replace(/\/$/, "");
} catch { return "Unavailable"; }
}
export function AppSettings({ authMode, onClose, onLogout, ...modelSettings }: ModelSettingsProps & {
authMode: AuthMode | null;
onClose: () => void;
onLogout: () => Promise<void>;
}) {
const dialogRef = useRef<HTMLDialogElement>(null);
const contentRef = useRef<HTMLDivElement>(null);
const navRef = useRef<HTMLElement>(null);
const lastSectionRef = useRef<Section | null>(null);
const [section, setSection] = useState<Section | null>(null);
const [signingOut, setSigningOut] = useState(false);
const activeSection = section ?? "notifications";
const modifier = /Mac|iPhone|iPad|iPod/i.test(navigator.platform) ? "⌘" : "Ctrl";
useLayoutEffect(() => {
const dialog = dialogRef.current;
const previouslyFocused = document.activeElement;
dialog?.showModal();
return () => {
dialog?.close();
if (previouslyFocused instanceof HTMLElement && previouslyFocused.isConnected) previouslyFocused.focus({ preventScroll: true });
};
}, []);
useLayoutEffect(() => {
if (section) {
lastSectionRef.current = section;
if (contentRef.current) contentRef.current.scrollTop = 0;
contentRef.current?.focus({ preventScroll: true });
} else if (lastSectionRef.current) {
navRef.current?.querySelector<HTMLButtonElement>(`[data-section="${lastSectionRef.current}"]`)?.focus({ preventScroll: true });
}
}, [section]);
return <dialog
ref={dialogRef}
aria-labelledby="app-settings-title"
className="fixed inset-0 m-0 flex h-dvh max-h-none w-full max-w-none items-center justify-center overflow-hidden bg-transparent p-0 text-foreground backdrop:bg-black/70 backdrop:backdrop-blur-md md:p-6"
onCancel={(event) => { event.preventDefault(); onClose(); }}
onClick={(event) => { if (event.target === event.currentTarget) onClose(); }}
>
<div className="glass-panel flex h-full min-h-0 w-full flex-col overflow-hidden md:h-[min(44rem,calc(100dvh-3rem))] md:max-w-[760px] md:rounded-2xl md:border md:border-violet-300/24">
<header className="app-settings-header flex shrink-0 items-center justify-between gap-4 border-b border-violet-300/15">
<div className="flex min-w-0 items-center gap-2">
{section ? <Button type="button" variant="ghost" size="icon" className="h-11 w-11 shrink-0 md:hidden" aria-label="Back to settings" onClick={() => setSection(null)}>
<ArrowLeft aria-hidden="true" className="h-5 w-5" />
</Button> : null}
<h2 id="app-settings-title" className="text-lg font-semibold text-violet-50">Settings</h2>
</div>
<Button type="button" size="icon" variant="ghost" className="h-11 w-11 shrink-0" aria-label="Close settings" onClick={onClose}>
<X aria-hidden="true" className="h-5 w-5" />
</Button>
</header>
<div className="flex min-h-0 flex-1 flex-col md:flex-row">
<nav ref={navRef} aria-label="Settings sections" className={cn("app-settings-nav shrink-0 space-y-2 overflow-y-auto overscroll-contain md:block md:w-44 md:border-r md:border-violet-300/15", section && "hidden")}>
{sections.map(({ id, title, description, icon: Icon }) => <button key={id} type="button" data-section={id} aria-label={title}
aria-current={activeSection === id ? "page" : undefined} aria-controls="app-settings-content" onClick={() => setSection(id)}
className={cn("flex min-h-11 w-full items-center gap-3 rounded-lg px-3 py-4 text-left text-violet-100/75 hover:bg-violet-400/10 hover:text-violet-50 focus-visible:outline focus-visible:outline-2 focus-visible:outline-ring md:items-start md:gap-2 md:py-3", activeSection === id && "md:bg-violet-400/15 md:text-violet-50")}>
<Icon aria-hidden="true" className="mt-0.5 h-4 w-4 shrink-0 text-violet-300" />
<span className="min-w-0 flex-1"><span className="block text-sm font-medium leading-5">{title}</span><span className="mt-1 block text-xs text-muted-foreground md:hidden">{description}</span></span>
<ChevronRight aria-hidden="true" className="h-4 w-4 shrink-0 md:hidden" />
</button>)}
</nav>
<div ref={contentRef} id="app-settings-content" role="group" aria-label={sections.find(item => item.id === activeSection)?.title} tabIndex={-1}
className={cn("app-settings-content min-h-0 min-w-0 flex-1 overflow-y-auto overscroll-contain outline-none md:block", !section && "hidden")}>
{activeSection === "notifications" ? authMode === "token" ? <AgentNotifications /> : (
<section aria-labelledby="notification-settings-title" className="space-y-3">
<h3 id="notification-settings-title" className="flex items-center gap-2 text-base font-semibold text-violet-50"><Bell aria-hidden="true" className="h-4 w-4 text-violet-300" />Notifications</h3>
<p className="text-sm leading-relaxed text-muted-foreground">Agent notifications require a server with token sign-in.</p>
</section>
) : activeSection === "models" ? <ModelSettings {...modelSettings} /> : (
<section aria-labelledby="connection-settings-title" className="space-y-6">
<h3 id="connection-settings-title" className="flex items-center gap-2 text-base font-semibold text-violet-50"><Server aria-hidden="true" className="h-4 w-4 text-violet-300" />Connection &amp; session</h3>
<dl className="space-y-5 text-sm">
<div className="space-y-1.5"><dt className="font-medium text-violet-100/80">Server</dt><dd className="break-all text-muted-foreground">{displayServerUrl()}</dd></div>
<div className="space-y-1.5"><dt className="font-medium text-violet-100/80">Sign-in</dt><dd className="text-muted-foreground">{authMode === "token" ? "Signed in on this browser." : "Open mode. No sign-in required."}</dd></div>
</dl>
{authMode === "token" ? <Button type="button" className="h-11" variant="secondary" disabled={signingOut} onClick={() => {
setSigningOut(true);
void onLogout().finally(() => setSigningOut(false));
}}>
{signingOut ? <LoaderCircle aria-hidden="true" className="mr-2 h-4 w-4 animate-spin" /> : <LogOut aria-hidden="true" className="mr-2 h-4 w-4" />}Sign out
</Button> : null}
<details className="border-t border-violet-300/15 pt-2">
<summary className="flex min-h-11 cursor-pointer items-center gap-2 py-3 text-sm text-violet-100/75 focus-visible:outline focus-visible:outline-2 focus-visible:outline-ring"><Keyboard aria-hidden="true" className="h-4 w-4" />Keyboard shortcuts</summary>
<dl className="space-y-3 pb-2 pt-2 text-xs text-muted-foreground">
{[ ["New chat", `${modifier} + J`], ["New search", `${modifier} + Shift + J`], ["Quick Question", `${modifier} + I`], ["Previous / next item", `${modifier} + ↑ / ↓`] ].map(([label, keys]) => <div key={label} className="flex flex-wrap justify-between gap-2"><dt>{label}</dt><dd><kbd>{keys}</kbd></dd></div>)}
</dl>
</details>
</section>
)}
</div>
</div>
</div>
</dialog>;
}
@@ -0,0 +1,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>;
}
+301
View File
@@ -0,0 +1,301 @@
import { useEffect, useRef, useState } from "preact/hooks";
import {
attachCompletionStream, attachSearchStream, createChat, createSearch, getActiveRuns, getChat, getSearch,
listModels, listWorkspaceItems, runCompletionStream, runSearchStream, suggestChatTitle,
type ActiveRunsResponse, type ChatDetail, type ModelCatalogResponse, type Provider, type SearchDetail, type WorkspaceItem,
} from "@/lib/api";
import { getChatModelSelection, getChatModelSelectionSyncKey } from "@/lib/chat-model-selection";
import { shouldRequestChatTitle } from "@/lib/chat-forking";
import type { SidebarSelection } from "@/lib/sidebar-selection";
import {
buildCompletionMessages, buildWorkspaceUrl, createClientRequestId, EMPTY_MODEL_CATALOG,
getModelOptions, PROVIDERS, hasNewPersistedUserMessage, isRecoverableStreamDisconnect,
loadStoredModelPreferences, pickProviderModel, readSidebarSelectionFromUrl, saveModelPreferences,
} from "@/lib/workspace-domain";
const NO_RUNS: ActiveRunsResponse = { chats: [], searches: [] };
const errorText = (error: unknown) => error instanceof Error ? error.message : String(error);
const sameSelection = (left: SidebarSelection | null, right: SidebarSelection | null) => left?.kind === right?.kind && left?.id === right?.id;
/** Lightweight presentation adapter: reuse the API and domain rules, publish completed responses only. */
export function useLiteWorkspace(isAuthenticated: boolean, onAuthFailure: (message: string) => void) {
const [selection, setSelection] = useState<SidebarSelection | null>(readSidebarSelectionFromUrl);
const [draftKind, setDraftKind] = useState<"chat" | "search">(() => new URLSearchParams(window.location.search).has("q") ? "search" : "chat");
const [items, setItems] = useState<WorkspaceItem[]>([]);
const [chat, setChat] = useState<ChatDetail | null>(null);
const [search, setSearch] = useState<SearchDetail | null>(null);
const [catalog, setCatalog] = useState<ModelCatalogResponse["providers"]>(EMPTY_MODEL_CATALOG);
const [preferences, setPreferences] = useState(loadStoredModelPreferences);
const [provider, updateProvider] = useState<Provider>("openai");
const [model, updateModel] = useState(() => loadStoredModelPreferences().openai ?? "");
const [activeRuns, setActiveRuns] = useState(NO_RUNS);
const [isLoading, setIsLoading] = useState(false);
const [isSending, setIsSending] = useState(false);
const [error, setError] = useState<string | null>(null);
const [navigationRevision, setNavigationRevision] = useState(0);
const selected = useRef(selection);
const authenticated = useRef(isAuthenticated); authenticated.current = isAuthenticated;
const reportAuthFailure = useRef(onAuthFailure); reportAuthFailure.current = onAuthFailure;
const mounted = useRef(true);
const epoch = useRef(0);
const loadRevision = useRef(0);
const operation = useRef<AbortController | null>(null);
const pendingRequest = useRef<Parameters<typeof runCompletionStream>[0] | null>(null);
const modelSelectionSyncKey = useRef<string | null>(null);
const isCurrent = (requestEpoch: number) => mounted.current && authenticated.current && epoch.current === requestEpoch;
const report = (failure: unknown, requestEpoch: number) => {
if (!isCurrent(requestEpoch)) return;
const message = errorText(failure);
if (message.includes("bearer token")) reportAuthFailure.current(message);
else setError(message);
};
const rememberModel = (nextProvider: Provider, nextModel: string) => {
updateProvider(nextProvider); updateModel(nextModel);
setPreferences(current => {
const next = { ...current, [nextProvider]: nextModel.trim() || null };
saveModelPreferences(next);
return next;
});
};
const applyChat = (detail: ChatDetail, syncModel = false) => {
setChat(detail); setSearch(null);
const saved = getChatModelSelection(detail);
const syncKey = getChatModelSelectionSyncKey(detail.id, saved);
if (syncModel && saved && syncKey !== modelSelectionSyncKey.current) rememberModel(saved.provider, saved.model);
modelSelectionSyncKey.current = syncKey;
};
const select = (target: SidebarSelection | null, history: "push" | "replace" | null = "push") => {
if (!sameSelection(selected.current, target)) modelSelectionSyncKey.current = null;
selected.current = target; setSelection(target); setChat(null); setSearch(null); setError(null);
loadRevision.current += 1;
if (history) window.history[history === "push" ? "pushState" : "replaceState"]({}, "", buildWorkspaceUrl(target));
};
const updateItems = (item: WorkspaceItem) => setItems(current => [item, ...current.filter(existing => existing.type !== item.type || existing.id !== item.id)]);
// Attach to backend-owned runs after navigation or reload. No timer or repeated polling is needed.
const attach = async (target: SidebarSelection, requestEpoch: number) => {
if (target.kind === "agent" || operation.current || !isCurrent(requestEpoch)) return;
const controller = new AbortController(); operation.current = controller; setIsSending(true);
try {
let streamError: string | null = null;
const handlers = { onError: (payload: { message: string }) => { streamError = payload.message; } };
if (target.kind === "chat") await attachCompletionStream(target.id, handlers, { signal: controller.signal });
else await attachSearchStream(target.id, handlers, { signal: controller.signal });
if (!isCurrent(requestEpoch)) return;
if (streamError) throw new Error(streamError);
const detail = target.kind === "chat" ? await getChat(target.id) : await getSearch(target.id);
if (!isCurrent(requestEpoch)) return;
if (sameSelection(selected.current, target)) {
if (target.kind === "chat") applyChat(detail as ChatDetail, true);
else setSearch(detail as SearchDetail);
}
updateItems({ ...detail, type: target.kind } as WorkspaceItem);
setActiveRuns(current => ({
chats: target.kind === "chat" ? current.chats.filter(id => id !== target.id) : current.chats,
searches: target.kind === "search" ? current.searches.filter(id => id !== target.id) : current.searches,
}));
} catch (failure) {
if (!controller.signal.aborted && isCurrent(requestEpoch)) {
try {
// A run can finish between listing active runs and attaching. Recover its saved result.
const [runs, detail] = await Promise.all([
getActiveRuns(), target.kind === "chat" ? getChat(target.id) : getSearch(target.id),
]);
if (!isCurrent(requestEpoch)) return;
setActiveRuns(runs);
if (sameSelection(selected.current, target)) {
if (target.kind === "chat") applyChat(detail as ChatDetail, true);
else setSearch(detail as SearchDetail);
}
const remainsActive = (target.kind === "chat" ? runs.chats : runs.searches).includes(target.id);
if (remainsActive || !/^active (chat|search) stream not found$/i.test(errorText(failure))) report(failure, requestEpoch);
} catch { report(failure, requestEpoch); }
}
} finally {
if (operation.current === controller) {
operation.current = null;
if (isCurrent(requestEpoch)) setIsSending(false);
}
}
};
const refresh = async () => {
if (!authenticated.current || operation.current) return;
const requestEpoch = epoch.current;
const revision = ++loadRevision.current;
const target = selected.current;
setIsLoading(true); setError(null);
try {
const [nextItems, runs, detail] = await Promise.all([
listWorkspaceItems(), getActiveRuns(),
target?.kind === "chat" ? getChat(target.id) : target?.kind === "search" ? getSearch(target.id) : Promise.resolve(null),
]);
if (!isCurrent(requestEpoch) || revision !== loadRevision.current) return;
setItems(nextItems); setActiveRuns(runs);
if (detail && target?.kind === "chat") applyChat(detail as ChatDetail, true);
else if (detail && target?.kind === "search") setSearch(detail as SearchDetail);
if (target && (target.kind === "chat" ? runs.chats.includes(target.id) : target.kind === "search" && runs.searches.includes(target.id))) {
void attach(target, requestEpoch);
}
} catch (failure) { if (revision === loadRevision.current) report(failure, requestEpoch); }
finally { if (isCurrent(requestEpoch) && revision === loadRevision.current) setIsLoading(false); }
};
useEffect(() => {
mounted.current = true;
return () => { mounted.current = false; epoch.current += 1; operation.current?.abort(); };
}, []);
useEffect(() => {
epoch.current += 1;
operation.current?.abort(); operation.current = null;
pendingRequest.current = null;
modelSelectionSyncKey.current = null;
setIsSending(false); setIsLoading(false);
if (!isAuthenticated) {
setItems([]); setChat(null); setSearch(null); setActiveRuns(NO_RUNS); setError(null);
return;
}
const requestEpoch = epoch.current;
void listModels().then(result => {
if (!isCurrent(requestEpoch)) return;
setCatalog(result.providers);
updateModel(current => current || pickProviderModel(getModelOptions(result.providers, provider), preferences[provider]));
}).catch(failure => report(failure, requestEpoch));
}, [isAuthenticated]);
useEffect(() => { if (isAuthenticated) void refresh(); }, [isAuthenticated, selection?.kind, selection?.id, navigationRevision]);
useEffect(() => {
const navigate = () => {
operation.current?.abort(); operation.current = null; setIsSending(false);
pendingRequest.current = null;
// Retire callbacks from a previous view, even if its fetch resolves after abort.
epoch.current += 1;
select(readSidebarSelectionFromUrl(), null);
setNavigationRevision(value => value + 1);
setDraftKind(new URLSearchParams(window.location.search).has("q") ? "search" : "chat");
};
window.addEventListener("popstate", navigate);
return () => window.removeEventListener("popstate", navigate);
}, []);
const selectItem = (target: SidebarSelection) => {
if (!operation.current && !sameSelection(selected.current, target)) select(target);
};
const startDraft = (kind: "chat" | "search") => {
if (operation.current) return;
pendingRequest.current = null;
setDraftKind(kind); select(null);
// A fresh draft can keep the same null selection while retiring an in-flight load.
setNavigationRevision(value => value + 1);
// The standalone search query is a prefill, not a persistent mode flag.
const url = new URL(window.location.href); url.searchParams.delete("q");
window.history.replaceState({}, "", url.pathname + url.search + url.hash);
};
const setProvider = (next: Provider) => {
if (!operation.current) rememberModel(next, pickProviderModel(getModelOptions(catalog, next), preferences[next]));
};
const setModel = (next: string) => { if (!operation.current) rememberModel(provider, next); };
const send = async (text: string): Promise<boolean> => {
const content = text.trim();
if (!content || !authenticated.current || operation.current || isLoading || selected.current?.kind === "agent") return false;
const running = selected.current?.kind === "chat" ? activeRuns.chats : activeRuns.searches;
if (selected.current && running.includes(selected.current.id)) return false;
const requestEpoch = epoch.current;
const controller = new AbortController(); operation.current = controller;
setIsSending(true); setError(null);
let target = selected.current;
let baseChat: ChatDetail | null = null;
let accepted = false;
try {
const kind = target?.kind ?? draftKind;
if (kind === "search") {
if (!target) {
const created = await createSearch({ query: content, title: content.slice(0, 80) });
if (!isCurrent(requestEpoch)) return false;
target = { kind: "search", id: created.id }; select(target, "replace"); updateItems({ ...created, type: "search" });
}
let completed: SearchDetail | null = null;
let streamError: string | null = null;
await runSearchStream(target.id, { query: content, title: content.slice(0, 80), type: "auto", numResults: 10 }, {
onDone: payload => { completed = payload.search; },
onError: payload => { streamError = payload.message; },
}, { signal: controller.signal });
if (streamError) throw new Error(streamError);
const detail: SearchDetail = completed ?? await getSearch(target.id);
if (!isCurrent(requestEpoch)) return false;
setSearch(detail); updateItems({ ...detail, type: "search" });
accepted = true;
} else {
const selectedModel = model.trim();
if (!selectedModel) throw new Error("Enter a model before sending.");
if (!target) {
const created = await createChat({ provider, model: selectedModel });
if (!isCurrent(requestEpoch)) return false;
target = { kind: "chat", id: created.id }; select(target, "replace"); updateItems({ ...created, type: "chat" });
baseChat = { ...created, messages: [] };
} else baseChat = chat?.id === target.id ? chat : await getChat(target.id);
if (!isCurrent(requestEpoch)) return false;
applyChat(baseChat);
const previousMessageIds = new Set(baseChat.messages.map(message => message.id));
const previous = pendingRequest.current;
const lastMessage = previous?.messages[previous.messages.length - 1];
const request = previous?.chatId === target.id && lastMessage?.content === content && previous.provider === provider && previous.model === selectedModel
? previous
: { chatId: target.id, clientRequestId: createClientRequestId(), provider, model: selectedModel, messages: buildCompletionMessages(baseChat.messages, content) };
pendingRequest.current = request;
if (shouldRequestChatTitle(baseChat, false) && !content.toLowerCase().includes("@sybil")) {
void suggestChatTitle({ chatId: target.id, content }).catch(() => undefined);
}
for (let attempt = 0; ; attempt += 1) {
let streamError: string | null = null;
try {
await runCompletionStream(request, { onError: payload => { streamError = payload.message; } }, { signal: controller.signal });
if (streamError) throw new Error(streamError);
accepted = true;
pendingRequest.current = null;
break;
} catch (failure) {
if (controller.signal.aborted || !isCurrent(requestEpoch)) return false;
// Replay the identical idempotent request once after transport loss.
if (attempt === 0 && !streamError && isRecoverableStreamDisconnect(failure)) continue;
try {
const persisted = await getChat(target.id);
accepted = hasNewPersistedUserMessage(persisted, previousMessageIds, content, []);
if (isCurrent(requestEpoch)) applyChat(persisted);
if (accepted) pendingRequest.current = null;
} catch { /* Retain the exact request for a safe manual retry. */ }
throw failure;
}
}
const detail = await getChat(target.id);
if (!isCurrent(requestEpoch)) return false;
applyChat(detail); updateItems({ ...detail, type: "chat" });
}
} catch (failure) {
if (!controller.signal.aborted) report(failure, requestEpoch);
} finally {
if (operation.current === controller) {
operation.current = null;
if (isCurrent(requestEpoch)) {
setIsSending(false);
// Refresh active state after failures too, so a surviving backend run cannot be submitted twice.
void getActiveRuns().then(runs => { if (isCurrent(requestEpoch)) setActiveRuns(runs); }).catch(() => undefined);
}
}
}
return accepted;
};
const selectedRun = selection?.kind === "chat" ? activeRuns.chats.includes(selection.id)
: selection?.kind === "search" ? activeRuns.searches.includes(selection.id) : false;
return {
selection, draftKind, items, chat, search, provider, model,
providerOptions: PROVIDERS, modelOptions: getModelOptions(catalog, provider),
isLoading, isBusy: isSending || selectedRun, isSending, error, activeRuns,
selectItem, newChat: () => startDraft("chat"), newSearch: () => startDraft("search"),
setProvider, setModel, send, refresh,
};
}
+10 -8
View File
@@ -7,15 +7,17 @@ const TOKEN_STORAGE_KEY = "sybil_admin_token";
export type AuthMode = "open" | "token";
function readStoredToken() {
return localStorage.getItem(TOKEN_STORAGE_KEY)?.trim() || null;
try { return localStorage.getItem(TOKEN_STORAGE_KEY)?.trim() || null; }
catch { return null; }
}
function persistToken(token: string | null) {
if (token) {
localStorage.setItem(TOKEN_STORAGE_KEY, token);
return;
try {
if (token) localStorage.setItem(TOKEN_STORAGE_KEY, token);
else localStorage.removeItem(TOKEN_STORAGE_KEY);
} catch {
// Browsers that disable storage can still keep a session in this document.
}
localStorage.removeItem(TOKEN_STORAGE_KEY);
}
function normalizeAuthError(message: string) {
@@ -28,7 +30,7 @@ function normalizeAuthError(message: string) {
return message;
}
export function useSessionAuth() {
export function useSessionAuth({ backgroundSession = true }: { backgroundSession?: boolean } = {}) {
const initialToken = readStoredToken() ?? getConfiguredToken() ?? "";
const [authTokenInput, setAuthTokenInput] = useState(initialToken);
@@ -81,9 +83,9 @@ export function useSessionAuth() {
};
useEffect(() => {
if (!isAuthenticated || authMode !== "token") return;
if (!backgroundSession || !isAuthenticated || authMode !== "token") return;
return startAgentBrowserSession();
}, [isAuthenticated, authMode]);
}, [isAuthenticated, authMode, backgroundSession]);
useEffect(() => {
// Signing out in one tab retires the others instead of using a stale token.
+27 -51
View File
@@ -1,17 +1,9 @@
@import url("https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&family=Orbitron:wght@700;800;900&display=swap");
@import "./components/chat/message-bubble.css";
@tailwind base;
@tailwind components;
@tailwind utilities;
@font-face {
font-family: "StalinistOne";
src: url("/StalinistOne-Regular.ttf") format("truetype");
font-weight: 400;
font-style: normal;
font-display: swap;
}
:root {
color-scheme: dark;
--safe-area-top: env(safe-area-inset-top, 0px);
@@ -61,7 +53,7 @@ body {
background-image:
linear-gradient(90deg, hsl(187 92% 49% / 0.08), transparent 24%, hsl(264 92% 59% / 0.12) 74%, transparent),
linear-gradient(180deg, hsl(250 60% 16% / 0.68), hsl(235 45% 4%) 48%, hsl(235 54% 3%));
font-family: "Inter", "Avenir Next", "Segoe UI", sans-serif;
font-family: var(--font-body, "Inter", "Avenir Next", "Segoe UI", sans-serif);
overflow: hidden;
overscroll-behavior: none;
}
@@ -80,13 +72,6 @@ textarea {
color: hsl(258 36% 98%);
}
.sybil-wordmark {
font-family: "StalinistOne", "Orbitron", "Inter", sans-serif;
font-weight: 400;
letter-spacing: 0;
line-height: 1;
}
.app-grid-surface {
background-image:
linear-gradient(hsl(244 48% 20% / 0.18) 1px, transparent 1px),
@@ -114,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))
@@ -122,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))
@@ -139,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;
}
@@ -194,37 +190,6 @@ textarea {
0 14px 36px hsl(240 80% 2% / 0.28);
}
/* Shared by regular chats and the persistent agent transcript. */
.message-bubble {
min-width: 0;
padding: 13px 17px;
border: 1px solid hsl(256 37% 57% / .18);
border-radius: 18px 18px 18px 5px;
background: linear-gradient(150deg, hsl(251 36% 15% / .93), hsl(244 35% 11% / .93));
box-shadow: 0 3px 12px hsl(239 55% 2% / .13);
font-size: 14px;
line-height: 1.68;
overflow-wrap: anywhere;
}
.message-bubble--user {
border-color: hsl(266 80% 72% / .3);
border-radius: 18px 18px 5px 18px;
background: linear-gradient(135deg, hsl(264 59% 33% / .86), hsl(259 58% 26% / .9));
color: hsl(265 55% 97%);
}
.message-bubble .md-content {
font-size: inherit;
line-height: inherit;
}
@media (max-width: 767px) {
.message-bubble {
padding: 11px 14px;
}
}
.tool-call-stack-shell {
perspective: 900px;
transform-style: preserve-3d;
@@ -462,6 +427,17 @@ textarea {
word-break: break-word;
}
.md-table-scroll,
.md-content pre,
.md-content blockquote {
overscroll-behavior-x: contain;
}
.md-content blockquote {
max-width: 100%;
overflow-x: auto;
}
.md-content > :first-child {
margin-top: 0;
}
+3 -1
View File
@@ -1,3 +1,5 @@
import { browserUuid } from "./browser-uuid.ts";
/** Agent descriptors are independent of ordinary chat's inline attachment schema. */
export type AgentAttachment = {
id: string; kind: "image" | "text" | "file"; filename: string; mimeType: string;
@@ -104,7 +106,7 @@ export function createAgentUploadQueue(options: {
const limit = image ? Math.min(6 * 1024 * 1024, cap.maxImageBytes) : Math.min(8 * 1024 * 1024, cap.maxFileBytes);
if (file.size > limit) throw new Error(`${file.name} exceeds the ${image ? "6" : "8"} MiB file limit.`);
}
const added = selected.map(file => ({ uploadId: (options.newId || (() => crypto.randomUUID()))(), file, filename: file.name, sizeBytes: file.size, mimeType: file.type, status: "waiting" as const }));
const added = selected.map(file => ({ uploadId: (options.newId || browserUuid)(), file, filename: file.name, sizeBytes: file.size, mimeType: file.type, status: "waiting" as const }));
for (const row of added) rows.set(row.uploadId, row);
try { persist(); } catch (error) { for (const row of added) rows.delete(row.uploadId); throw error; }
publish(); pump();
+2 -1
View File
@@ -1,6 +1,7 @@
import type { Message } from "./api";
import { agentAttachments, attachmentCaption, parseAgentAttachment, type AgentAttachment } from "./agent-attachments.ts";
import { compareAgentMessages, normalizeAgentMessage } from "./agent-messages.ts";
import { browserUuid } from "./browser-uuid.ts";
export const AGENT_OUTBOX_STORAGE_KEY = "sybil.agent.optimistic-outbox.v1";
export type AgentDeliveryStatus = "sending" | "queued" | "complete" | "failed" | "unconfirmed";
@@ -28,7 +29,7 @@ export function createAgentOptimisticOutbox(options: {
newId?: () => string;
now?: () => number;
}) {
const newId = options.newId || (() => crypto.randomUUID());
const newId = options.newId || browserUuid;
const now = options.now || Date.now;
const rows = new Map<string, AgentOutboxRow>();
const inFlight = new Map<string, Promise<void>>();
+11 -19
View File
@@ -1,19 +1,13 @@
import { getApiBaseUrl, getAuthToken } from "./api";
import { ensureServiceWorker } from "../pwa";
import { browserPushOperation } from "./agent-push-errors.ts";
import { browserUuid } from "./browser-uuid.ts";
import {
AGENT_PUSH_STORAGE_KEY, AgentPushClient, agentPushAuthorityScope, agentPushCursor, agentPushSourceId,
createAgentPresenceReporter, createAgentPushController, parseAgentPushConsent, type AgentPushView, type PushSubscriptionHandle,
} from "./agent-push.ts";
let sessionId: string | undefined;
function browserUuid() {
if (typeof globalThis.crypto?.randomUUID === "function") return crypto.randomUUID();
if (typeof globalThis.crypto?.getRandomValues !== "function") throw new Error("Secure browser identifiers are unavailable.");
const bytes = crypto.getRandomValues(new Uint8Array(16));
bytes[6] = bytes[6] & 15 | 64; bytes[8] = bytes[8] & 63 | 128;
const hex = Array.from(bytes, byte => byte.toString(16).padStart(2, "0")).join("");
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
}
/** A document UUID avoids duplicated sessionStorage IDs when the user duplicates a tab. */
export function getAgentPresenceSessionId() { try { return sessionId ||= browserUuid(); } catch { return undefined; } }
const api = new AgentPushClient({ baseUrl: getApiBaseUrl(), token: getAuthToken });
@@ -24,17 +18,12 @@ async function consentScope() {
return digest;
}
const listeners = new Set<(state: AgentPushView) => void>();
function bounded<T>(promise: Promise<T>, timeoutMs = 10000): Promise<T> {
return new Promise((resolve, reject) => {
const timeout = setTimeout(() => reject(new Error("Browser notification operation timed out.")), timeoutMs);
promise.then(value => { clearTimeout(timeout); resolve(value); }, () => { clearTimeout(timeout); reject(new Error("Browser notification operation failed.")); });
});
}
const subscriptionHandle = (subscription: PushSubscription): PushSubscriptionHandle => ({
toJSON: () => subscription.toJSON(), unsubscribe: () => bounded(subscription.unsubscribe()),
toJSON: () => subscription.toJSON(), unsubscribe: () => browserPushOperation(() => subscription.unsubscribe(), "subscription"),
});
const readConsent = () => { try { return parseAgentPushConsent(localStorage.getItem(AGENT_PUSH_STORAGE_KEY)); } catch { return null; } };
const support = () => {
if (!window.isSecureContext) return "insecure" as const;
const ios = /iPad|iPhone|iPod/.test(navigator.userAgent) || (navigator.platform === "MacIntel" && navigator.maxTouchPoints > 1);
const standalone = window.matchMedia("(display-mode: standalone)").matches || window.matchMedia("(display-mode: fullscreen)").matches
|| (navigator as Navigator & { standalone?: boolean }).standalone === true;
@@ -79,11 +68,14 @@ const controller = createAgentPushController({
requestPermission: () => Notification.requestPermission(),
subscription: async () => {
if (!("serviceWorker" in navigator)) return null;
const registration = await bounded(navigator.serviceWorker.getRegistration("/"));
const subscription = registration ? await bounded(registration.pushManager.getSubscription()) : null;
const registration = await browserPushOperation(() => navigator.serviceWorker.getRegistration("/"), "worker");
const subscription = registration ? await browserPushOperation(() => registration.pushManager.getSubscription(), "subscription") : null;
return subscription ? subscriptionHandle(subscription) : null;
},
subscribe: async key => subscriptionHandle(await bounded((await ensureServiceWorker()).pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: decodePublicKey(key) }))),
subscribe: async key => {
const registration = await browserPushOperation(ensureServiceWorker, "worker", 20000);
return subscriptionHandle(await browserPushOperation(() => registration.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: decodePublicKey(key) }), "subscription"));
},
clearNotifications: () => postWorker({ type: "sybil-agent-logout", version: 1 }),
},
});
@@ -91,7 +83,7 @@ export const getAgentPushState = () => controller.state();
export function observeAgentPush(listener: (state: AgentPushView) => void) { listeners.add(listener); listener(controller.state()); return () => { listeners.delete(listener); }; }
export const enableAgentBrowserPush = () => controller.enable();
export const disableAgentBrowserPush = () => controller.disable();
export const refreshAgentBrowserPush = () => controller.refresh();
export const refreshAgentBrowserPush = () => controller.refresh(true);
const presence = createAgentPresenceReporter({
snapshot: () => ({ visibility: !document.hidden && document.visibilityState === "visible" ? "visible" : "hidden", focused: document.hasFocus() }),
+43
View File
@@ -0,0 +1,43 @@
/** Only messages constructed here may reach the UI; provider bodies can contain secrets. */
export class AgentPushError extends Error {}
export type AgentPushStage = "permission" | "worker" | "subscription" | "storage" | "lock" | "service";
export function agentPushFailure(cause: unknown, stage: AgentPushStage): AgentPushError {
if (cause instanceof AgentPushError) return cause;
const name = cause instanceof Error || (typeof DOMException !== "undefined" && cause instanceof DOMException) ? cause.name : "";
if (stage === "storage" || name === "QuotaExceededError") return new AgentPushError("Browser storage is unavailable. Allow site storage and free some space, then try again.");
if (stage === "worker") return new AgentPushError("The notification worker could not start. Reload Sybil and try again. If this continues, check that this browser allows service workers and site storage.");
if (stage === "lock") return new AgentPushError("Another Sybil tab is still updating notifications. Close other Sybil tabs, then try again.");
if ((stage === "permission" || stage === "subscription") && ["NotAllowedError", "SecurityError"].includes(name)) {
return new AgentPushError("The browser did not allow notifications. Allow notifications for Sybil in site settings and for the browser in system settings, then try again.");
}
if (stage === "permission") return new AgentPushError("The browser could not request notification permission. Check browser site settings and system settings, then reload Sybil and try again.");
if (stage === "subscription") {
if (name === "InvalidStateError") return new AgentPushError("The browser has an incompatible notification subscription. Turn off notifications for Sybil in site settings, reload, then enable them again.");
if (["InvalidAccessError", "DataError", "TypeError"].includes(name)) return new AgentPushError("The browser rejected the server's notification key. Ask the server administrator to check Web Push configuration.");
if (name === "NotSupportedError") return new AgentPushError("This browser exposes notification APIs but cannot create a push subscription. Update it or use a browser with a working Web Push service. See Android / GrapheneOS help below.");
const detail = ["AbortError", "NetworkError", "TimeoutError"].includes(name) ? ` (${name})` : "";
return new AgentPushError(`The browser could not connect to its push service${detail}. Check your connection and browser push support, then try again. On Vanadium, see Android / GrapheneOS help below.`);
}
return new AgentPushError("The Sybil notification service could not be reached. Check your connection and try again.");
}
export function agentPushHttpFailure(status: number): AgentPushError {
if (status === 401 || status === 403) return new AgentPushError("Your sign-in is no longer authorized. Sign out and sign in again to manage notifications.");
if (status === 400 || status === 413) return new AgentPushError("The server rejected the notification subscription. Refresh Sybil and retry; if it continues, ask the server administrator to check Web Push configuration.");
if (status === 409) return new AgentPushError("This notification registration has expired. Refresh and enable notifications again to create a new registration.");
if (status === 429) return new AgentPushError("The notification service is busy. Wait a moment, then try again.");
if (status === 503) return new AgentPushError("Web Push is unavailable on the Sybil server. Ask the server administrator to check notification configuration and service health.");
return new AgentPushError("The Sybil server could not save notification settings. Try again; if it continues, ask the server administrator to check service health.");
}
/** Keep DOMException names for diagnosis, but never expose their arbitrary messages. */
export function browserPushOperation<T>(operation: () => Promise<T>, stage: AgentPushStage, timeoutMs = 10000): Promise<T> {
return new Promise((resolve, reject) => {
const timeout = setTimeout(() => reject(agentPushFailure(new DOMException("", "TimeoutError"), stage)), timeoutMs);
const fail = (cause: unknown) => { clearTimeout(timeout); reject(agentPushFailure(cause, stage)); };
try { operation().then(value => { clearTimeout(timeout); resolve(value); }, fail); }
catch (cause) { fail(cause); }
});
}
+43 -24
View File
@@ -1,3 +1,5 @@
import { AgentPushError, agentPushFailure, agentPushHttpFailure, type AgentPushStage } from "./agent-push-errors.ts";
/** Browser-only push contracts. Secrets stay in page request headers, never worker messages. */
export const AGENT_PUSH_STORAGE_KEY = "sybil.agent.push.v1";
export const AGENT_PUSH_CHANGED_EVENT = "sybil-agent-push-changed";
@@ -18,8 +20,9 @@ export function parseAgentPushConfig(value: unknown): AgentPushConfig {
|| (config.quarantined !== undefined && typeof config.quarantined !== "boolean") || !policy
|| typeof policy.presenceHeartbeatMs !== "number" || policy.presenceHeartbeatMs < 5000 || policy.presenceHeartbeatMs > 30000
|| typeof policy.presenceLeaseMs !== "number" || policy.presenceLeaseMs < 30000 || policy.presenceLeaseMs > 120000
|| (config.webPushAvailable && config.vapidPublicKey === undefined)
|| (config.vapidPublicKey !== undefined && (typeof config.vapidPublicKey !== "string" || !/^[A-Za-z0-9_-]{87}$/.test(config.vapidPublicKey)))) {
throw new Error("Notification configuration is unavailable.");
throw new AgentPushError("The server returned invalid notification configuration. Refresh Sybil; if it continues, ask the server administrator to check Web Push configuration.");
}
return { ...config, quarantined: config.quarantined === true } as AgentPushConfig;
}
@@ -36,28 +39,28 @@ export class AgentPushClient {
constructor(options: { baseUrl: string; token: () => string | null; fetch?: typeof globalThis.fetch }) { this.options = options; }
private async request(path: string, method = "GET", body?: unknown, keepalive = false, expectedScope?: string): Promise<unknown> {
const token = this.options.token();
if (!token) throw new Error("Sign in to manage notifications.");
if (!token) throw new AgentPushError("Sign in to manage notifications.");
const controller = new AbortController(), timeout = setTimeout(() => controller.abort(), 8000);
try {
// Capture the bearer before hashing, then use that exact bearer for the
// request. A concurrent sign-in must not turn old-authority cleanup into
// a new-authority DELETE whose204 falsely clears a durable tombstone.
if (expectedScope !== undefined && expectedScope !== await agentPushAuthorityScope(this.options.baseUrl, token)) throw new Error("Notification authority changed.");
if (expectedScope !== undefined && expectedScope !== await agentPushAuthorityScope(this.options.baseUrl, token)) throw new AgentPushError("The signed-in server changed. Refresh and enable notifications again.");
const response = await (this.options.fetch || globalThis.fetch)(`${this.options.baseUrl.replace(/\/+$/, "")}/v1/agent${path}`, {
method, headers: { Authorization: `Bearer ${token}`, ...(body === undefined ? {} : { "Content-Type": "application/json" }) },
...(body === undefined ? {} : { body: JSON.stringify(body) }), cache: "no-store", redirect: "error", credentials: "omit", signal: controller.signal, keepalive,
});
// Never echo server/provider bodies: they may contain endpoint or key material.
if (!response.ok) throw new Error(response.status === 401 ? "Sign in to manage notifications." : "Notification settings could not be saved. Try again.");
if (!response.ok) throw agentPushHttpFailure(response.status);
return response.status === 204 ? undefined : await response.json();
} catch { throw new Error("Notification service is unavailable. Try again when connected."); }
} catch (cause) { throw agentPushFailure(cause, "service"); }
finally { clearTimeout(timeout); }
}
async config() { return parseAgentPushConfig(await this.request("/push/config")); }
async register(id: string, subscription: PushSubscriptionJSON, expectedScope?: string) {
if (!agentPushUuid(id)) throw new Error("Invalid notification installation.");
const value = object(await this.request(`/push/installations/${id}`, "PUT", { transport: "web", enabled: true, subscription }, false, expectedScope));
if (!value || value.installationId !== id || value.transport !== "web" || value.enabled !== true || !Number.isSafeInteger(value.version) || Number(value.version) < 1) throw new Error("Notification registration was not acknowledged.");
if (!value || value.installationId !== id || value.transport !== "web" || value.enabled !== true || !Number.isSafeInteger(value.version) || Number(value.version) < 1) throw new AgentPushError("The Sybil server did not acknowledge the notification registration. Refresh and try again.");
}
async revoke(id: string, expectedScope?: string) {
if (!agentPushUuid(id)) throw new Error("Invalid notification installation.");
@@ -94,7 +97,7 @@ export function parseAgentPushConsent(raw: string | null): AgentPushConsent | nu
export type AgentPushView = { busy: boolean; enabled: boolean; canEnable: boolean; message: string; error: string | null };
export type PushSubscriptionHandle = Pick<PushSubscription, "toJSON" | "unsubscribe">;
type PushPlatform = {
support: () => "supported" | "unsupported" | "install";
support: () => "supported" | "unsupported" | "install" | "insecure";
permission: () => NotificationPermission;
requestPermission: () => Promise<NotificationPermission>;
subscription: () => Promise<PushSubscriptionHandle | null>;
@@ -109,15 +112,16 @@ export function createAgentPushController(options: {
uuid: () => string; lock: <T>(operation: () => Promise<T>) => Promise<T>; changed: (view: AgentPushView) => void;
}) {
let config: AgentPushConfig | null = null, busy = false, error: string | null = null, localRevocation: AgentPushConsent | null = null;
let refreshError: string | null = null;
let scope: string | null = null;
let registeredSubscription: string | null = null;
const currentConsent = () => localRevocation || options.read();
const matchesContext = (record: AgentPushConsent) => !!scope && record.scope === scope
&& agentPushSourceId(record.sourceId) && record.sourceId === config?.sourceId;
const transportAvailable = () => !!config?.enabled && config.webPushAvailable && !config.quarantined && agentPushSourceId(config.sourceId);
const transportAvailable = () => !!config?.enabled && config.webPushAvailable && !!config.vapidPublicKey && !config.quarantined && agentPushSourceId(config.sourceId);
const refreshContext = async () => {
const nextScope = await options.scope(), nextConfig = await options.api.config();
if (nextScope !== await options.scope()) { scope = null; config = null; throw new Error("Notification authority changed."); }
if (nextScope !== await options.scope()) { scope = null; config = null; throw new AgentPushError("The signed-in server changed. Refresh and enable notifications again."); }
scope = nextScope; config = nextConfig;
};
const recheckContext = async (record: AgentPushConsent) => {
@@ -130,14 +134,17 @@ export function createAgentPushController(options: {
const cleanupFull = (consent?.pendingRevocations?.length || 0) >= MAX_AGENT_PUSH_REVOCATIONS;
const enabled = consent?.enabled === true && !consent.revocationPending && permission === "granted";
const message = support === "install" ? "On iPhone or iPad, add Sybil to your Home Screen, then enable notifications there."
: support === "insecure" ? "Notifications require a secure connection. Open Sybil over HTTPS, then try again."
: support === "unsupported" ? "This browser does not support notifications here. Use a supported browser over HTTPS."
: permission === "denied" ? "Notifications are blocked. Allow them in browser settings, then try again."
: permission === "denied" ? "Notifications are blocked. Allow Sybil in browser site settings and allow the browser's notifications in system settings, then refresh."
: cleanupFull ? "Notification cleanup is full. Sign in to a previous server to finish removing old registrations before enabling more."
: consent?.revocationPending ? "Notifications are off here. Server removal will retry when connected."
: config?.quarantined ? "Notification delivery is paused after an Agent source change. Ask the server administrator to reconcile the source before enabling notifications."
: config?.enabled && config.webPushAvailable && !agentPushSourceId(config.sourceId) ? "The Agent notification source is not ready yet. Refresh in a moment; if it continues, ask the server administrator to check the Agent connection."
: !available ? "Notifications are not configured on this server yet."
: enabled ? "Notifications are on for this browser."
: "Get an alert for unread Agent replies when all your web sessions are inactive.";
return { busy, enabled, canEnable: !busy && available && support === "supported" && permission !== "denied" && !consent?.revocationPending && !cleanupFull, message, error };
return { busy, enabled, canEnable: !busy && available && support === "supported" && permission !== "denied" && !consent?.revocationPending && !cleanupFull, message, error: error || refreshError };
};
const publish = () => options.changed(state());
const write = (consent: AgentPushConsent) => { options.write(consent); publish(); };
@@ -195,7 +202,7 @@ export function createAgentPushController(options: {
await revoke(pending);
};
const disable = async () => {
error = null;
error = null; refreshError = null;
const record = { ...consent(), enabled: false, revocationPending: true, revision: options.uuid() };
// Synchronous durable intent is necessary before logout clears page credentials.
registeredSubscription = null;
@@ -216,8 +223,9 @@ export function createAgentPushController(options: {
}
finally { busy = false; publish(); }
};
const refresh = async () => {
const refresh = async (clearError = false) => {
if (busy) return;
if (clearError) error = null;
try {
await refreshContext();
await options.lock(async () => {
@@ -246,18 +254,18 @@ export function createAgentPushController(options: {
const stillMatching = await recheckContext(record);
if (currentConsent()?.revision !== record.revision) { await retireAtOriginalAuthority(record); return; }
if (!stillMatching) { await invalidate(record); return; }
} catch { await invalidate(record); throw new Error("Notification service is unavailable."); }
} catch (cause) { await invalidate(record); throw cause; }
registeredSubscription = serialized;
}
}
});
error = null;
} catch { error = "Notification service is unavailable. Try again when connected."; }
refreshError = null;
} catch (cause) { refreshError = agentPushFailure(cause, "service").message; }
publish();
};
const enable = async () => {
if (!state().canEnable || state().enabled || busy || !config?.vapidPublicKey || !scope || !agentPushSourceId(config.sourceId)) return;
error = null;
error = null; refreshError = null;
// Explicit revocation permanently retires the old UUID on the server. Each
// new opt-in has a new identity, so a delayed old PUT cannot resurrect it.
const record: AgentPushConsent = { version: 1, installationId: options.uuid(), revision: options.uuid(), scope, sourceId: config.sourceId,
@@ -267,35 +275,46 @@ export function createAgentPushController(options: {
// Must execute in the original click stack, before locks, worker startup or fetches.
let permission: Promise<NotificationPermission>;
try { permission = options.platform.requestPermission(); }
catch { error = "Notifications could not be requested. Check browser settings and try again."; publish(); return; }
catch (cause) { error = agentPushFailure(cause, "permission").message; publish(); return; }
busy = true; publish();
let stage: AgentPushStage = "permission";
try {
if (await permission !== "granted") { error = "Notifications were not allowed. You can change this in browser settings."; return; }
const decision = await permission;
if (decision !== "granted") { error = decision === "denied"
? "Notifications were not allowed. Allow Sybil in browser site settings and allow the browser's notifications in system settings, then refresh."
: "The notification prompt was dismissed. Tap Enable notifications again and choose Allow."; return; }
stage = "lock";
await options.lock(async () => {
stage = "service";
const unchanged = () => options.read()?.revision === record.revision;
if (!unchanged()) return;
const matching = await recheckContext(record);
if (!unchanged()) return;
if (!matching || config?.vapidPublicKey !== publicKey) { await invalidate(record); return; }
stage = "subscription";
const subscription = await options.platform.subscription() || await options.platform.subscribe(publicKey);
if (!unchanged()) { await subscription.unsubscribe(); return; }
// A tombstone also covers a lost registration response or failed local storage write.
const pending = { ...record, enabled: false, revocationPending: true }; write(pending);
const pending = { ...record, enabled: false, revocationPending: true };
try {
stage = "storage"; write(pending);
stage = "service";
const matchingBeforeRegister = await recheckContext(record);
if (!unchanged() || !matchingBeforeRegister || config?.vapidPublicKey !== publicKey) { await revoke(pending); return; }
await options.api.register(record.installationId, subscription.toJSON(), record.scope);
if (!unchanged()) { await retireAtOriginalAuthority(record); await subscription.unsubscribe(); return; }
const matchingAfterRegister = await recheckContext(record);
if (!unchanged() || !matchingAfterRegister || config?.vapidPublicKey !== publicKey) { await revoke(pending); return; }
write({ ...record, enabled: true, revocationPending: false });
stage = "storage"; write({ ...record, enabled: true, revocationPending: false });
registeredSubscription = JSON.stringify(subscription.toJSON());
} catch {
} catch (cause) {
// Retain cleanup intent even when storage fails after subscribing.
if (options.read()?.revision === record.revision) localRevocation = pending;
await revoke(pending);
throw new Error("Notifications could not be enabled. Try again when connected.");
throw agentPushFailure(cause, stage);
}
});
} catch { error = "Notifications could not be enabled. Try again when connected."; }
} catch (cause) { error = agentPushFailure(cause, stage).message; }
finally { busy = false; publish(); }
};
return { state, refresh, enable, disable };
+8 -4
View File
@@ -40,6 +40,10 @@ export type AgentRoomEvent =
const object = (value: unknown): Record<string, unknown> | undefined => value !== null && typeof value === "object" && !Array.isArray(value)
? value as Record<string, unknown> : undefined;
const defined = (value: Record<string, unknown>) => Object.fromEntries(Object.entries(value).filter(([, item]) => item !== undefined));
function checkAborted(signal?: AbortSignal) {
// AbortSignal.throwIfAborted() is newer than the browsers supported by Lite.
if (signal?.aborted) throw signal.reason ?? new DOMException("Download canceled.", "AbortError");
}
export function normalizeAgentCursor(value: unknown): string {
if (typeof value !== "string" || !/^\d+$/.test(value)) throw new Error("Invalid agent message cursor.");
return BigInt(value).toString();
@@ -239,7 +243,7 @@ export class AgentRoomClient {
}
async download(attachment: AgentAttachment, signal?: AbortSignal): Promise<Blob> {
const file = parseAgentAttachment(attachment), headers = new Headers(), token = this.token();
signal?.throwIfAborted();
checkAborted(signal);
while (this.activeDownloads >= 2) {
await new Promise<void>((resolve, reject) => {
const cleanup = () => { this.downloadWaiters.delete(wake); signal?.removeEventListener("abort", abort); };
@@ -248,7 +252,7 @@ export class AgentRoomClient {
this.downloadWaiters.add(wake); signal?.addEventListener("abort", abort, { once: true });
if (signal?.aborted) abort();
});
signal?.throwIfAborted();
checkAborted(signal);
}
this.activeDownloads++;
try {
@@ -262,7 +266,7 @@ export class AgentRoomClient {
try {
for (;;) {
const { done, value } = await reader.read(); if (done) break;
signal?.throwIfAborted();
checkAborted(signal);
if (size + value.length > bytes.length) throw new Error("Attachment download exceeds its size limit.");
bytes.set(value, size); size += value.length;
}
@@ -272,7 +276,7 @@ export class AgentRoomClient {
if (sha256 !== file.sha256) throw new Error("Attachment checksum did not match.");
if (file.kind === "image" && response.headers.get("content-type")?.split(";")[0].trim() !== file.mimeType)
throw new Error("Attachment image type did not match.");
signal?.throwIfAborted();
checkAborted(signal);
if (token !== this.token()) throw new Error("Authentication changed. Retry the download.");
return new Blob([bytes], { type: response.headers.get("content-type") || "application/octet-stream" });
} finally {
+14 -45
View File
@@ -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",
@@ -411,48 +418,7 @@ export async function deleteSearch(searchId: string) {
await api<{ deleted: true }>(`/v1/searches/${searchId}`, { method: "DELETE" });
}
export function getMessageAttachments(metadata: unknown): ChatAttachment[] {
if (!metadata || typeof metadata !== "object" || Array.isArray(metadata)) return [];
const attachments = (metadata as Record<string, unknown>).attachments;
if (!Array.isArray(attachments)) return [];
const parsed: ChatAttachment[] = [];
for (const entry of attachments) {
if (!entry || typeof entry !== "object" || Array.isArray(entry)) continue;
const record = entry as Record<string, unknown>;
const kind = record.kind;
const id = typeof record.id === "string" ? record.id : "";
const filename = typeof record.filename === "string" ? record.filename : "";
const mimeType = typeof record.mimeType === "string" ? record.mimeType : "";
const sizeBytes = typeof record.sizeBytes === "number" ? record.sizeBytes : 0;
if (kind === "image" && typeof record.dataUrl === "string" && (mimeType === "image/png" || mimeType === "image/jpeg")) {
parsed.push({
kind,
id,
filename,
mimeType,
sizeBytes,
dataUrl: record.dataUrl,
} satisfies ChatImageAttachment);
continue;
}
if (kind === "text" && typeof record.text === "string") {
parsed.push({
kind,
id,
filename,
mimeType,
sizeBytes,
text: record.text,
truncated: record.truncated === true,
} satisfies ChatTextAttachment);
}
}
return parsed;
}
export { getMessageAttachments } from "./chat-attachments";
type RunSearchStreamHandlers = {
onSearchResults?: (payload: { requestId: string | null; results: SearchResultItem[] }) => void;
@@ -609,6 +575,7 @@ export async function runCompletion(body: {
chatId: string;
provider: Provider;
model: string;
reasoningEffort?: ReasoningEffort | null;
messages: CompletionRequestMessage[];
additionalSystemPrompt?: string;
enabledTools?: string[];
@@ -627,6 +594,7 @@ export async function runCompletionStream(
clientRequestId?: string;
provider: Provider;
model: string;
reasoningEffort?: ReasoningEffort | null;
messages: CompletionRequestMessage[];
additionalSystemPrompt?: string;
enabledTools?: string[];
@@ -657,6 +625,7 @@ export async function runQuickQuestionStream(
body: {
provider: Provider;
model: string;
reasoningEffort?: ReasoningEffort | null;
question: string;
},
handlers: CompletionStreamHandlers,
+12
View File
@@ -0,0 +1,12 @@
type BrowserCrypto = Pick<Crypto, "getRandomValues"> & Partial<Pick<Crypto, "randomUUID">>;
/** Secure UUIDs also work on browsers that predate Crypto.randomUUID(). */
export function browserUuid(source: BrowserCrypto | undefined = typeof crypto === "undefined" ? undefined : crypto): string {
if (typeof source?.randomUUID === "function") return source.randomUUID();
if (typeof source?.getRandomValues !== "function") throw new Error("Secure browser identifiers are unavailable.");
const bytes = source.getRandomValues(new Uint8Array(16));
bytes[6] = bytes[6] & 15 | 64;
bytes[8] = bytes[8] & 63 | 128;
const hex = Array.from(bytes, byte => byte.toString(16).padStart(2, "0")).join("");
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
}
+44
View File
@@ -0,0 +1,44 @@
import type { ChatAttachment, ChatImageAttachment, ChatTextAttachment } from "./api";
export function getMessageAttachments(metadata: unknown): ChatAttachment[] {
if (!metadata || typeof metadata !== "object" || Array.isArray(metadata)) return [];
const attachments = (metadata as Record<string, unknown>).attachments;
if (!Array.isArray(attachments)) return [];
const parsed: ChatAttachment[] = [];
for (const entry of attachments) {
if (!entry || typeof entry !== "object" || Array.isArray(entry)) continue;
const record = entry as Record<string, unknown>;
const kind = record.kind;
const id = typeof record.id === "string" ? record.id : "";
const filename = typeof record.filename === "string" ? record.filename : "";
const mimeType = typeof record.mimeType === "string" ? record.mimeType : "";
const sizeBytes = typeof record.sizeBytes === "number" ? record.sizeBytes : 0;
if (kind === "image" && typeof record.dataUrl === "string" && (mimeType === "image/png" || mimeType === "image/jpeg")) {
parsed.push({
kind,
id,
filename,
mimeType,
sizeBytes,
dataUrl: record.dataUrl,
} satisfies ChatImageAttachment);
continue;
}
if (kind === "text" && typeof record.text === "string") {
parsed.push({
kind,
id,
filename,
mimeType,
sizeBytes,
text: record.text,
truncated: record.truncated === true,
} satisfies ChatTextAttachment);
}
}
return parsed;
}
+2 -1
View File
@@ -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(),
+7
View File
@@ -2,6 +2,13 @@ import type { Message, ToolCallEvent } from "@/lib/api";
export const STREAMING_ASSISTANT_METADATA_KIND = "streaming_assistant";
export function isInlineAgentReplyPending(message: Message, isSending: boolean): boolean {
const metadata = message.metadata && typeof message.metadata === "object" && !Array.isArray(message.metadata)
? message.metadata as Record<string, unknown> : {};
return isSending && message.role === "assistant" && message.id.startsWith("temp-assistant-")
&& metadata.agentAside === true && !message.content.trim();
}
export type StreamingAssistantMetadata = {
kind: typeof STREAMING_ASSISTANT_METADATA_KIND;
ephemeralTrace: string | null;
+14
View File
@@ -0,0 +1,14 @@
/** Marked uses at() internally, including on Chromium-based readers predating it. */
export function installLiteCompatibility() {
if (!("at" in Array.prototype)) {
Object.defineProperty(Array.prototype, "at", {
configurable: true,
writable: true,
value: function at(this: unknown[], index: number) {
const offset = Math.trunc(Number(index)) || 0;
const position = offset < 0 ? this.length + offset : offset;
return position < 0 || position >= this.length ? undefined : this[position];
},
});
}
}
+18
View File
@@ -0,0 +1,18 @@
import type { Message } from "./api";
export function getProviderLabel(provider: unknown) {
if (provider === "openai") return "OpenAI";
if (provider === "anthropic") return "Anthropic";
if (provider === "xai") return "xAI";
if (provider === "gemini") return "Gemini";
return "";
}
export function getMessageGenerationLabel(message: Pick<Message, "role" | "metadata">): string | null {
if (message.role !== "assistant" || !message.metadata || typeof message.metadata !== "object" || Array.isArray(message.metadata)) return null;
const metadata = message.metadata as Record<string, unknown>;
if (metadata.agentAside === true || !metadata.generation || typeof metadata.generation !== "object" || Array.isArray(metadata.generation)) return null;
const generation = metadata.generation as Record<string, unknown>;
const provider = getProviderLabel(generation.provider);
return provider && typeof generation.model === "string" && generation.model.trim() ? `${provider} · ${generation.model.trim()}` : null;
}
+14
View File
@@ -0,0 +1,14 @@
/** Text, controls and nested scrollers own their gestures, even at a scroll edge. */
export function ownsMobileGesture(target: EventTarget | null, workspace: HTMLElement): boolean {
if (!(target instanceof Element)) return true;
if (target.closest("input, textarea, select, button, a, summary, [contenteditable]:not([contenteditable='false']), [role='button'], [role='dialog'], [data-mobile-swipe-ignore], .md-content, .message-bubble, .agent-room__plain-message, pre, code, table, blockquote")) return true;
for (let element: Element | null = target; element && element !== workspace; element = element.parentElement) {
if (element.scrollWidth > element.clientWidth + 1 && /auto|scroll/.test(getComputedStyle(element).overflowX)) return true;
}
return false;
}
export function hasTextSelection(): boolean {
const selection = window.getSelection();
return !!selection && !selection.isCollapsed;
}
+43
View File
@@ -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; }
}
+62
View File
@@ -0,0 +1,62 @@
export type UiMode = "full" | "lite";
export type UiLocation = Pick<Location, "pathname" | "search" | "hash">;
type PreferenceStorage = Pick<Storage, "getItem" | "setItem">;
export const UI_MODE_STORAGE_KEY = "sybil:ui-mode";
export function parseUiMode(value: string | null): UiMode | null {
return value === "full" || value === "lite" ? value : null;
}
export function readUiModePreference(storage: PreferenceStorage | null): UiMode | null {
try {
return parseUiMode(storage?.getItem(UI_MODE_STORAGE_KEY) ?? null);
} catch {
return null;
}
}
export function persistUiModePreference(storage: PreferenceStorage | null, mode: UiMode) {
try {
storage?.setItem(UI_MODE_STORAGE_KEY, mode);
} catch {
// The explicit URL still works when private browsing blocks storage.
}
}
export function prefersLiteUi({ userAgent = "", saveData = false }: { userAgent?: string; saveData?: boolean }) {
// Silk is also a tablet/phone browser; it is not an e-ink signal by itself.
const isReader = /\b(?:Kindle|Kobo|PocketBook)\b/i.test(userAgent)
&& !/\b(?:Silk|Kindle Fire)\b/i.test(userAgent);
return saveData || isReader;
}
export function isLitePath(path: string) {
return path === "/lite" || path === "/lite/";
}
function fullPath(location: UiLocation) {
const params = new URLSearchParams(location.search);
const isStandaloneSearch = params.has("q") && !["chat", "search", "agent"].some(key => params.has(key));
return location.pathname === "/search" || (isLitePath(location.pathname) && isStandaloneSearch) ? "/search" : "/";
}
/** Ordinary links deliberately navigate documents, keeping the two stylesheets isolated. */
export function buildUiModeUrl(mode: UiMode, location: UiLocation = window.location) {
const params = new URLSearchParams(location.search);
params.set("ui", mode);
return `${mode === "lite" ? "/lite" : fullPath(location)}?${params.toString()}${location.hash}`;
}
/** Decide once at entry, before downloading either presentation. */
export function resolveUiRoute(
location: UiLocation,
hints: { userAgent?: string; saveData?: boolean },
storedPreference: UiMode | null,
) {
const explicit = parseUiMode(new URLSearchParams(location.search).get("ui"));
const mode = explicit ?? (isLitePath(location.pathname) ? "lite"
: location.pathname === "/" ? storedPreference ?? (prefersLiteUi(hints) ? "lite" : "full") : "full");
const path = mode === "lite" ? "/lite" : isLitePath(location.pathname) ? fullPath(location) : location.pathname;
return { mode, url: `${path}${location.search}${location.hash}`, preference: explicit };
}
+170
View File
@@ -0,0 +1,170 @@
import type { ChatAttachment, ChatDetail, CompletionRequestMessage, Message, ModelCatalogResponse, Provider } from "./api";
import type { SidebarSelection } from "./sidebar-selection";
import { getMessageAttachments } from "./chat-attachments.ts";
import { QUICK_QUESTION_DEFAULT_MODEL } from "./quick-question.ts";
export function readSidebarSelectionFromUrl(): SidebarSelection | null {
if (typeof window === "undefined") return null;
const params = new URLSearchParams(window.location.search);
if (params.get("agent") === "root") return { kind: "agent", id: "root" };
const chatId = params.get("chat")?.trim();
if (chatId) {
return { kind: "chat", id: chatId };
}
const searchId = params.get("search")?.trim();
if (searchId) {
return { kind: "search", id: searchId };
}
return null;
}
export function buildWorkspaceUrl(selection: SidebarSelection | null) {
if (typeof window === "undefined") return "/";
const params = new URLSearchParams(window.location.search);
params.delete("chat");
params.delete("search");
params.delete("agent");
if (selection) {
params.set(selection.kind, selection.id);
}
const query = params.toString();
return `${window.location.pathname}${query ? `?${query}` : ""}${window.location.hash}`;
}
export const PROVIDER_FALLBACK_MODELS: Record<Provider, string[]> = {
openai: ["gpt-4.1-mini", QUICK_QUESTION_DEFAULT_MODEL],
anthropic: ["claude-3-5-sonnet-latest"],
xai: ["grok-3-mini"],
gemini: ["gemini-3.5-flash", "gemini-flash-latest"],
};
export const EMPTY_MODEL_CATALOG: ModelCatalogResponse["providers"] = {
openai: { models: [], loadedAt: null, error: null },
anthropic: { models: [], loadedAt: null, error: null },
xai: { models: [], loadedAt: null, error: null },
gemini: { models: [], loadedAt: null, error: null },
};
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,
};
export function createClientRequestId() {
if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
return crypto.randomUUID();
}
return `web-${Date.now()}-${Math.random().toString(36).slice(2)}`;
}
export function isRecoverableStreamDisconnect(error: unknown) {
if (error instanceof TypeError) return true;
const message = (error instanceof Error ? error.message : String(error)).toLowerCase();
return (
message.includes("failed to fetch") ||
message.includes("load failed") ||
message.includes("network error") ||
message.includes("networkerror") ||
message.includes("no response stream") ||
message.includes("stream disconnected before completion")
);
}
export function hasNewPersistedUserMessage(chat: ChatDetail, previousMessageIds: Set<string>, content: string, attachments: ChatAttachment[]) {
return chat.messages.some((message) => {
if (previousMessageIds.has(message.id) || message.role !== "user" || message.content !== content) return false;
const persistedAttachmentIds = new Set(getMessageAttachments(message.metadata).map((attachment) => attachment.id));
return attachments.length === persistedAttachmentIds.size && attachments.every((attachment) => persistedAttachmentIds.has(attachment.id));
});
}
export function getModelOptions(catalog: ModelCatalogResponse["providers"], provider: Provider) {
const providerModels = catalog[provider]?.models ?? [];
if (providerModels.length) return providerModels;
return PROVIDER_FALLBACK_MODELS[provider];
}
export function loadStoredModelPreferences() {
if (typeof window === "undefined") return EMPTY_MODEL_PREFERENCES;
try {
const raw = window.localStorage.getItem(MODEL_PREFERENCES_STORAGE_KEY);
if (!raw) return EMPTY_MODEL_PREFERENCES;
return normalizeStoredModelPreferences(JSON.parse(raw));
} catch {
return EMPTY_MODEL_PREFERENCES;
}
}
export function normalizeStoredProvider(value: unknown): Provider {
return value === "anthropic" || value === "xai" || value === "gemini" || value === "openai"
? value
: "openai";
}
export function normalizeStoredModelPreferences(value: unknown): ProviderModelPreferences {
if (!value || typeof value !== "object" || Array.isArray(value)) return EMPTY_MODEL_PREFERENCES;
const parsed = value as Partial<Record<Provider, unknown>>;
return {
openai: typeof parsed.openai === "string" && parsed.openai.trim() ? parsed.openai.trim() : null,
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,
};
}
export function pickProviderModel(options: string[], preferred: string | null) {
if (preferred?.trim()) return preferred.trim();
return options[0] ?? "";
}
/** Persisted tool activity is a UI log, not a provider conversation message. */
export function buildCompletionMessages(messages: Message[], content: string, attachments: ChatAttachment[] = []): CompletionRequestMessage[] {
return [
...messages.filter(message => {
const metadata = message.metadata;
return !metadata || typeof metadata !== "object" || Array.isArray(metadata) || (metadata as Record<string, unknown>).kind !== "tool_call";
}).map(message => {
const savedAttachments = getMessageAttachments(message.metadata);
return {
id: message.id,
role: message.role,
content: message.content,
...(message.name ? { name: message.name } : {}),
...(savedAttachments.length ? { attachments: savedAttachments } : {}),
};
}),
{ role: "user", content, ...(attachments.length ? { attachments } : {}) },
];
}
export function saveModelPreferences(preferences: ProviderModelPreferences) {
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; }
}
+26 -2
View File
@@ -1,8 +1,32 @@
import { render } from "preact";
import { RootRouter } from "@/root-router";
import { registerServiceWorker } from "@/pwa";
import "./index.css";
import { persistUiModePreference, readUiModePreference, resolveUiRoute } from "@/lib/ui-mode";
import "./typography.css";
registerServiceWorker();
// Both presentations use the same fonts. A blocked CDN does not block the UI.
const fonts = document.createElement("link");
fonts.rel = "stylesheet";
fonts.href = "https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&family=Orbitron:wght@700;800;900&display=swap";
document.head.appendChild(fonts);
let storage: Storage | null = null;
try { storage = window.localStorage; } catch { /* Storage may be unavailable in private browsing. */ }
const connection = (navigator as Navigator & { connection?: { saveData?: boolean } }).connection;
const route = resolveUiRoute(window.location, {
userAgent: navigator.userAgent,
saveData: connection?.saveData,
}, readUiModePreference(storage));
if (route.preference) persistUiModePreference(storage, route.preference);
if (route.url !== `${window.location.pathname}${window.location.search}${window.location.hash}`) {
window.history.replaceState(window.history.state, "", route.url);
}
if (route.mode === "lite") {
document.querySelector('meta[name="viewport"]')?.setAttribute("content", "width=device-width, initial-scale=1, viewport-fit=cover");
document.querySelector('meta[name="theme-color"]')?.setAttribute("content", "#ffffff");
} else {
registerServiceWorker();
}
render(<RootRouter />, document.getElementById("app")!);
+267
View File
@@ -0,0 +1,267 @@
import type { ComponentType } from "preact";
import { useEffect, useLayoutEffect, useRef, useState } from "preact/hooks";
import { Bot, LogOut, Menu, MessageSquare, Plus, RefreshCw, Search, SendHorizontal, Settings2, Star, X } from "lucide-preact";
import { AssistantMessageFooter } from "@/components/chat/assistant-message-footer";
import { MarkdownContent } from "@/components/markdown/markdown-content";
import { useSessionAuth } from "@/hooks/use-session-auth";
import { useLiteWorkspace } from "@/hooks/use-lite-workspace";
import { useWorkspaceSearch } from "@/hooks/use-workspace-search";
import { getMessageAttachments, type Message, type SearchDetail, type WorkspaceItem } from "@/lib/api";
import { getProviderLabel } from "@/lib/message-generation";
import { buildUiModeUrl } from "@/lib/ui-mode";
import "./lite.css";
const PAGE_SIZE = 30;
function LiteAgentPanel() {
const [Agent, setAgent] = useState<ComponentType | null>(null);
const [failed, setFailed] = useState(false);
useEffect(() => {
let active = true;
setFailed(false);
void import("@/components/lite/lite-agent").then(module => {
if (active) setAgent(() => module.LiteAgent);
}, () => { if (active) setFailed(true); });
return () => { active = false; };
}, []);
if (failed) return <div className="lite-error" role="alert"><p>Agent could not load. Check your connection and reload this page.</p><button onClick={() => window.location.reload()}>Reload</button></div>;
return Agent ? <Agent /> : <p role="status">Opening Agent…</p>;
}
function itemTitle(item: WorkspaceItem) {
return item.title?.trim() || (item.type === "search" ? item.query : null) || (item.type === "chat" ? "New chat" : "New search");
}
function formatDate(value: string) {
const date = new Date(value);
return Number.isNaN(date.getTime()) ? "" : date.toLocaleDateString(undefined, { month: "short", day: "numeric" });
}
function webLink(value: string | undefined) {
return value && /^https?:\/\//i.test(value) ? value : undefined;
}
function LiteMessage({ message }: { message: Message }) {
const attachments = getMessageAttachments(message.metadata);
if (message.role === "system") return null;
if (message.role === "tool") return (
<details className="lite-tool">
<summary>{message.name || "Tool activity"}</summary>
<pre>{message.content}</pre>
</details>
);
return (
<article className={`lite-message${message.role === "user" ? " lite-message-user" : ""}`} aria-label={message.role === "user" ? "Your message" : "Assistant message"}>
<div className={`lite-message-content${message.role === "user" ? " message-bubble message-bubble--user" : ""}`}>
{attachments.length > 0 && <ul className="lite-attachments" aria-label="Attachments">
{attachments.map(file => <li key={file.id}>{file.filename}</li>)}
</ul>}
<MarkdownContent markdown={message.content} allowImages={false} openLinksInNewTab />
{message.role === "assistant" && <AssistantMessageFooter message={message} />}
</div>
</article>
);
}
function LiteTranscript({ messages }: { messages: Message[] }) {
const [count, setCount] = useState(PAGE_SIZE);
const visible = messages.filter(message => message.role !== "system");
return (
<section className="lite-transcript" aria-label="Conversation">
{visible.length > count && <button type="button" onClick={() => setCount(value => value + PAGE_SIZE)}>Show earlier messages ({visible.length - count})</button>}
{visible.slice(-count).map(message => <LiteMessage key={message.id} message={message} />)}
</section>
);
}
function LiteSearch({ search }: { search: SearchDetail }) {
return (
<section className="lite-search-results" aria-label="Web search results">
{search.error && <p className="lite-error" role="alert">{search.error}</p>}
{search.answerError && <p className="lite-error" role="alert">{search.answerError}</p>}
{search.answerText && <article className="lite-search-answer"><h2>Answer</h2><MarkdownContent markdown={search.answerText} allowImages={false} /></article>}
{!!search.answerCitations?.length && <details className="lite-tool"><summary>Answer sources</summary><ul>
{search.answerCitations.map((citation, index) => <li key={index}><a href={webLink(citation.url)}>{citation.title || citation.url || `Source ${index + 1}`}</a></li>)}
</ul></details>}
<ol className="lite-result-list">
{search.results.map(result => <li key={result.id}>
<h2><a href={webLink(result.url)}>{result.title || result.url}</a></h2>
<p className="lite-result-url">{result.url}</p>
{(result.highlights?.length || result.text) && <p>{(result.highlights?.join(" ") || result.text || "").slice(0, 600)}</p>}
</li>)}
</ol>
{!search.results.length && !search.answerText && !search.error && <p>No results saved for this search.</p>}
</section>
);
}
export default function LiteRoutePage() {
const auth = useSessionAuth({ backgroundSession: false });
const workspace = useLiteWorkspace(auth.isAuthenticated, auth.handleAuthFailure);
const [sidebarOpen, setSidebarOpen] = useState(false);
const [historyQuery, setHistoryQuery] = useState("");
const [historyCount, setHistoryCount] = useState(PAGE_SIZE);
const [draft, setDraft] = useState(() => new URLSearchParams(window.location.search).get("q") || "");
const [submitted, setSubmitted] = useState("");
const submitLock = useRef(false);
const transcriptRef = useRef<HTMLDivElement>(null);
const followTranscript = useRef(true);
const historySearch = useWorkspaceSearch(historyQuery, auth.isAuthenticated, workspace.items.length);
const historyItems = historyQuery.trim() ? historySearch.items : workspace.items;
const isAgent = workspace.selection?.kind === "agent";
const isSearch = workspace.selection?.kind === "search" || (!workspace.selection && workspace.draftKind === "search");
const title = isAgent ? "Sybil Agent" : isSearch ? workspace.search?.title || "New search" : workspace.chat?.title || "New chat";
const selectedKey = workspace.selection ? `${workspace.selection.kind}:${workspace.selection.id}` : workspace.draftKind;
const priorSelection = useRef(selectedKey);
const lastMessageId = workspace.chat?.messages[workspace.chat.messages.length - 1]?.id;
useEffect(() => {
document.title = `${title} · Sybil Lite`;
}, [title]);
useLayoutEffect(() => {
if (priorSelection.current !== selectedKey && (!submitLock.current || !workspace.isSending)) {
setDraft("");
setSubmitted("");
}
priorSelection.current = selectedKey;
}, [selectedKey, workspace.isSending]);
useEffect(() => { setHistoryCount(PAGE_SIZE); }, [historyQuery]);
useLayoutEffect(() => { followTranscript.current = true; }, [selectedKey]);
useLayoutEffect(() => {
const transcript = transcriptRef.current;
if (transcript && followTranscript.current) transcript.scrollTop = isSearch ? 0 : transcript.scrollHeight;
}, [selectedKey, lastMessageId, submitted, workspace.isBusy]);
useEffect(() => {
if (!sidebarOpen) return;
const close = (event: KeyboardEvent) => { if (event.key === "Escape") setSidebarOpen(false); };
window.addEventListener("keydown", close);
return () => window.removeEventListener("keydown", close);
}, [sidebarOpen]);
const send = async (event: Event) => {
event.preventDefault();
const text = draft.trim();
if (!text || workspace.isBusy || submitLock.current) return;
submitLock.current = true;
followTranscript.current = true;
setSubmitted(text);
try {
if (await workspace.send(text)) setDraft("");
} finally {
setSubmitted("");
submitLock.current = false;
}
};
const fullLink = <a href={buildUiModeUrl("full", window.location)}>Full interface</a>;
const brand = <a className="lite-brand sybil-wordmark" href="/lite?ui=lite" aria-label="Sybil home">SYBIL</a>;
if (auth.isCheckingSession) return <div className="lite-auth">{brand}<p role="status">Checking session…</p></div>;
if (!auth.isAuthenticated) return (
<main className="lite-auth">
{brand}
<h1>Sign in to Sybil</h1>
<p>Enter your admin token.</p>
<form onSubmit={event => { event.preventDefault(); if (auth.authTokenInput.trim()) void auth.handleSignIn(auth.authTokenInput.trim()); }}>
<label htmlFor="lite-token">Admin token</label>
<input id="lite-token" type="password" autoComplete="off" required value={auth.authTokenInput}
onInput={event => auth.setAuthTokenInput(event.currentTarget.value)} disabled={auth.isSigningIn} />
<button className="lite-primary" disabled={auth.isSigningIn || !auth.authTokenInput.trim()}>{auth.isSigningIn ? "Signing in…" : "Sign in"}</button>
</form>
{auth.authError && <p className="lite-error" role="alert">{auth.authError}</p>}
{fullLink}
</main>
);
return (
<div className="lite-shell">
<a className="lite-skip" href="#lite-main">Skip to conversation</a>
{sidebarOpen && <button type="button" className="lite-sidebar-backdrop" aria-label="Close sidebar" onClick={() => setSidebarOpen(false)} />}
<aside id="lite-sidebar" className={`lite-sidebar${sidebarOpen ? " is-open" : ""}`} aria-label="Workspace">
<header className="lite-sidebar-header">
{brand}
<button type="button" className="lite-icon-button lite-sidebar-close" aria-label="Close sidebar" onClick={() => setSidebarOpen(false)}><X aria-hidden="true" /></button>
</header>
<nav className="lite-workspace-actions" aria-label="Workspace actions">
<button className="lite-primary" type="button" onClick={() => { workspace.newChat(); setDraft(""); setSidebarOpen(false); }} disabled={workspace.isSending}><Plus aria-hidden="true" />New chat</button>
<button type="button" onClick={() => { workspace.newSearch(); setDraft(""); setSidebarOpen(false); }} disabled={workspace.isSending}><Search aria-hidden="true" />New search</button>
<button className="lite-agent-button" type="button" aria-current={isAgent ? "page" : undefined} onClick={() => { workspace.selectItem({ kind: "agent", id: "root" }); setSidebarOpen(false); }} disabled={workspace.isSending}><Bot aria-hidden="true" />Sybil Agent</button>
</nav>
<div className="lite-history-search">
<Search aria-hidden="true" />
<label className="lite-visually-hidden" htmlFor="lite-history-query">Search history</label>
<input id="lite-history-query" type="search" placeholder="Search chats and web searches" value={historyQuery} onInput={event => setHistoryQuery(event.currentTarget.value)} />
</div>
<section className="lite-history" aria-label="History">
<h2>History</h2>
{historySearch.error && historyQuery && <p className="lite-error" role="alert">{historySearch.error}</p>}
{historySearch.isLoading && <p role="status">Searching history…</p>}
<ul className="lite-history-list">
{historyItems.slice(0, historyCount).map(item => <li key={`${item.type}:${item.id}`}>
<button type="button" aria-current={workspace.selection?.kind === item.type && workspace.selection.id === item.id ? "page" : undefined}
disabled={workspace.isSending} onClick={() => { workspace.selectItem({ kind: item.type, id: item.id }); setSidebarOpen(false); }}>
{item.type === "chat" ? <MessageSquare aria-hidden="true" /> : <Search aria-hidden="true" />}
<span className="lite-history-item-content"><span className="lite-history-title">{itemTitle(item)}{item.starred && <Star aria-label="Starred" />}</span>
<time dateTime={item.updatedAt}>{formatDate(item.updatedAt)}</time>
{historyQuery && item.searchSnippet && <small>{item.searchSnippet}</small>}
</span>
</button>
</li>)}
</ul>
{historyItems.length > historyCount && <button type="button" onClick={() => setHistoryCount(value => value + PAGE_SIZE)}>More history</button>}
{!historyItems.length && !workspace.isLoading && !historySearch.isLoading && <p className="lite-muted">{historyQuery ? "No matches." : "No chats or searches."}</p>}
{historySearch.hasMore && <p className="lite-muted">Refine your search to see more matches.</p>}
</section>
<footer className="lite-sidebar-footer">
{fullLink}
<button type="button" className="lite-text-button" onClick={() => void auth.logout()}><LogOut aria-hidden="true" />Sign out</button>
</footer>
</aside>
<main id="lite-main" className="lite-main" tabIndex={-1}>
<header className="lite-workspace-header">
<button type="button" className="lite-icon-button lite-sidebar-trigger" aria-label="Open sidebar" aria-expanded={sidebarOpen} aria-controls="lite-sidebar" onClick={() => setSidebarOpen(true)}><Menu aria-hidden="true" /></button>
<div className="lite-workspace-title"><h1>{title}</h1>{!isSearch && !isAgent && <p>{getProviderLabel(workspace.provider)} · {workspace.model || "No model"}</p>}</div>
{!isAgent && <div className="lite-header-actions">
<button className="lite-icon-button" type="button" aria-label="Refresh" title="Refresh" onClick={() => void workspace.refresh()} disabled={workspace.isSending || workspace.isLoading}><RefreshCw aria-hidden="true" /></button>
{!isSearch && <details className="lite-settings"><summary aria-label="Settings"><Settings2 aria-hidden="true" /><span>Settings</span></summary>
<div className="lite-model-controls">
<label>Provider<select value={workspace.provider} onChange={event => workspace.setProvider(event.currentTarget.value as typeof workspace.provider)} disabled={workspace.isBusy}>
{workspace.providerOptions.map(provider => <option key={provider} value={provider}>{getProviderLabel(provider)}</option>)}
</select></label>
<label>Model<input list="lite-model-options" value={workspace.model} onInput={event => workspace.setModel(event.currentTarget.value)} disabled={workspace.isBusy} autoComplete="off" /></label>
<datalist id="lite-model-options">{workspace.modelOptions.map(model => <option key={model} value={model} />)}</datalist>
</div>
</details>}
</div>}
</header>
{isAgent ? <LiteAgentPanel /> : <>
<div className="lite-scroll" ref={transcriptRef} tabIndex={0} aria-label={isSearch ? "Search results" : "Conversation"}
onScroll={event => { const element = event.currentTarget; followTranscript.current = element.scrollHeight - element.scrollTop - element.clientHeight < 96; }}>
{workspace.isLoading && <p className="lite-status" role="status">Loading…</p>}
{workspace.chat && <LiteTranscript key={workspace.chat.id} messages={workspace.chat.messages} />}
{workspace.search && <LiteSearch search={workspace.search} />}
{submitted && <div className="lite-transcript"><article className="lite-message lite-message-user"><div className="lite-message-content message-bubble message-bubble--user"><p className="lite-plain-text">{submitted}</p></div></article></div>}
{workspace.isBusy && <p className="lite-status" role="status">{isSearch ? "Searching…" : "Generating…"}{!workspace.isSending && " Refresh to reconnect."}</p>}
</div>
<div className="lite-composer-shell">
{workspace.error && <p className="lite-error" role="alert">{workspace.error}</p>}
<form className="lite-composer" onSubmit={send}>
<label className="lite-visually-hidden" htmlFor="lite-draft">{isSearch ? "Search the web" : "Message"}</label>
<textarea id="lite-draft" rows={2} value={draft} onInput={event => setDraft(event.currentTarget.value)}
onKeyDown={event => { if (event.key === "Enter" && !event.shiftKey && !event.isComposing) void send(event); }}
disabled={workspace.isBusy || workspace.isLoading} placeholder={isSearch ? "Search the web" : "Enter prompt..."} />
<div className="lite-composer-footer">
<button className="lite-primary lite-send" type="submit" aria-label={isSearch ? "Search" : "Send message"} disabled={!draft.trim() || workspace.isBusy || workspace.isLoading || (!isSearch && !workspace.model.trim())}>{isSearch ? <Search aria-hidden="true" /> : <SendHorizontal aria-hidden="true" />}</button>
</div>
</form>
</div>
</>}
</main>
</div>
);
}
+188
View File
@@ -0,0 +1,188 @@
@import "../components/chat/message-bubble.css";
:root {
color-scheme: light;
color: #211c2b;
background: #fff;
font-size: 16px;
line-height: 1.5;
--radius: 0px;
--lite-border: #ada7b8;
--lite-muted: #595064;
--lite-accent: #50327c;
--message-bubble-background: #f3f1f7;
--message-bubble-border: #aaa2b6;
--message-bubble-shadow: none;
--message-bubble-user-background: #e9e0f5;
--message-bubble-user-border: #9683b1;
--message-bubble-user-color: #211c2b;
--message-footer-color: var(--lite-muted);
--message-footer-hover-background: #ede8f4;
--message-footer-hover-color: #211c2b;
--message-footer-focus-color: var(--lite-accent);
--message-footer-transition: none;
}
* { box-sizing: border-box; }
html, body, #app { height: 100%; width: 100%; margin: 0; }
body { overflow: hidden; }
button, input, select, textarea { font: inherit; color: inherit; }
button, input, select, textarea, summary { border: 1px solid var(--lite-border); border-radius: var(--radius); background: #fff; }
button { display: inline-flex; justify-content: center; align-items: center; gap: .5rem; cursor: pointer; padding: .5rem .75rem; min-height: 40px; font-size: .875rem; font-weight: 500; line-height: 1.4; }
button:hover { background: #ede8f4; }
button:disabled { cursor: default; color: #625b6d; background: #eae7ee; border-color: var(--lite-border); }
button svg, summary svg { width: 1rem; height: 1rem; flex: none; }
input, select, textarea { display: block; width: 100%; padding: .5rem .75rem; min-height: 40px; }
textarea { resize: vertical; line-height: 1.5; }
label { display: block; font-size: .875rem; font-weight: 500; }
a { color: var(--lite-accent); text-decoration: underline; overflow-wrap: anywhere; }
:focus-visible { outline: 2px solid var(--lite-accent); outline-offset: 2px; }
h1, h2, h3, p { margin: 0; }
h1 { font-size: 1rem; font-weight: 600; line-height: 1.5; }
h2 { font-size: 1.1rem; line-height: 1.4; }
small { font-size: .75rem; }
summary { display: flex; align-items: center; gap: .5rem; cursor: pointer; padding: .5rem .75rem; min-height: 40px; font-size: .875rem; list-style: none; }
summary::-webkit-details-marker { display: none; }
pre { max-width: 100%; overflow: auto; padding: .75rem; border: 1px solid var(--lite-border); border-radius: var(--radius); background: #f5f3f8; font-size: .875rem; }
::selection { color: #fff; background: var(--lite-accent); }
.lite-shell { display: flex; height: 100%; min-height: 0; padding: env(safe-area-inset-top, 0) env(safe-area-inset-right, 0) env(safe-area-inset-bottom, 0) env(safe-area-inset-left, 0); }
.lite-sidebar { display: flex; flex-direction: column; width: 320px; flex: none; min-height: 0; border-right: 1px solid var(--lite-border); background: #f4f1f8; }
.lite-sidebar-header { display: flex; align-items: center; justify-content: space-between; min-height: 96px; padding: 20px 16px 16px; }
.lite-brand { display: inline-block; color: var(--lite-accent); font-size: 30px; text-decoration: none; }
.lite-workspace-actions { display: flex; flex-direction: column; gap: .75rem; padding: 0 12px 12px; }
.lite-workspace-actions button { width: 100%; justify-content: flex-start; gap: .75rem; padding-left: .75rem; }
.lite-workspace-actions button:first-child { min-height: 44px; font-size: 15px; }
.lite-workspace-actions .lite-agent-button { min-height: 50px; border-color: #bcb5c7; background: #f4f1f8; font-weight: 600; }
.lite-agent-button svg { width: 18px; height: 18px; }
.lite-agent-button[aria-current="page"] { background: #e4d9f3; border-color: var(--lite-accent); }
.lite-primary { color: #fff; background: var(--lite-accent); border-color: var(--lite-accent); }
.lite-primary:hover { background: #402563; }
.lite-history-search { position: relative; margin: 0 12px 12px; }
.lite-history-search > svg { position: absolute; top: 12px; left: 12px; height: 16px; width: 16px; color: var(--lite-muted); }
.lite-history-search input { padding-left: 36px; font-size: 14px; }
.lite-history { flex: 1; min-height: 0; overflow-y: auto; padding: 0 12px 12px; }
.lite-history h2 { margin: 12px 8px 8px; font-size: 10px; font-weight: 600; letter-spacing: .08em; text-transform: uppercase; color: var(--lite-muted); }
.lite-history-list { list-style: none; padding: 0; margin: 0; }
.lite-history-list li { margin-bottom: 4px; }
.lite-history-list button { width: 100%; justify-content: flex-start; align-items: flex-start; gap: .5rem; text-align: left; padding: 10px 12px; background: #f4f1f8; border-color: #f4f1f8; }
.lite-history-list button:hover { background: #ede8f4; }
.lite-history-list button[aria-current="page"] { border-color: var(--lite-accent); background: #e4d9f3; }
.lite-history-list button > svg { margin-top: 2px; }
.lite-history-item-content { min-width: 0; flex: 1; }
.lite-history-title { display: block; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; font-size: 14px; font-weight: 600; }
.lite-history-title svg { display: inline; width: 12px; height: 12px; margin-left: 5px; fill: currentColor; }
.lite-history-item-content time, .lite-history-item-content small { display: block; margin-top: 4px; color: var(--lite-muted); font-size: 12px; font-weight: 400; overflow-wrap: anywhere; }
.lite-sidebar-footer { display: flex; align-items: center; justify-content: space-between; border-top: 1px solid var(--lite-border); padding: 8px 16px; font-size: 12px; }
.lite-text-button { padding: .5rem 0; border: 0; background: none; font-size: inherit; }
.lite-main { display: flex; flex-direction: column; min-width: 0; min-height: 0; flex: 1; }
.lite-workspace-header { display: flex; flex: none; align-items: center; gap: .5rem; min-height: 65px; padding: 12px 28px; border-bottom: 1px solid var(--lite-border); background: #f9f7fc; }
.lite-workspace-title { flex: 1; min-width: 0; }
.lite-workspace-title h1, .lite-workspace-title p { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.lite-workspace-title p { color: var(--lite-muted); font-size: 12px; }
.lite-header-actions { display: flex; align-items: center; gap: 8px; }
.lite-icon-button { width: 40px; padding: 0; flex: none; }
.lite-settings { position: relative; }
.lite-settings[open] summary { border-color: var(--lite-accent); }
.lite-model-controls { position: absolute; top: calc(100% + 8px); right: 0; z-index: 10; width: 280px; padding: 16px; border: 1px solid var(--lite-border); border-radius: var(--radius); background: #fff; }
.lite-model-controls label + label { margin-top: 12px; }
.lite-model-controls input, .lite-model-controls select { margin-top: 4px; font-weight: 400; }
.lite-scroll, .lite-agent-scroll { flex: 1; min-height: 0; overflow-y: auto; overflow-x: hidden; padding: 32px 40px 24px; }
.lite-transcript, .lite-search-results { max-width: 896px; margin: 0 auto; min-width: 0; }
.lite-message { display: flex; justify-content: flex-start; min-width: 0; margin-bottom: 24px; }
.lite-message-user { justify-content: flex-end; }
.lite-message-content { min-width: 0; max-width: 85%; overflow-wrap: anywhere; }
.lite-message:not(.lite-message-user) > .lite-message-content { font-size: 16px; line-height: 1.82; }
.lite-message-user > .lite-message-content { max-width: 78%; }
.lite-message-content > .assistant-message-footer { margin-top: 12px; }
.lite-message-meta { display: flex; flex-wrap: wrap; align-items: baseline; gap: 7px; margin: 5px 3px 0; color: var(--lite-muted); font-size: 11px; line-height: 1.4; }
.lite-message-meta time::before { content: "·"; margin-right: 7px; }
.lite-message-user .lite-message-meta { justify-content: flex-end; }
.lite-plain-text { white-space: pre-wrap; overflow-wrap: anywhere; }
.lite-tool { max-width: 896px; margin: 0 auto 24px; font-size: .875rem; overflow-wrap: anywhere; }
.lite-tool summary { display: list-item; list-style: disclosure-closed inside; width: fit-content; max-width: 100%; }
.lite-tool[open] summary { list-style-type: disclosure-open; }
.lite-attachments { font-size: .875rem; padding-left: 1.25rem; margin: 8px 0; }
.lite-composer-shell { flex: none; padding: 12px 24px 24px; background: #fff; }
.lite-composer { max-width: 896px; margin: 0 auto; padding: 8px; border: 1px solid #9683b1; border-radius: var(--radius); background: #faf8fd; }
.lite-composer textarea { max-height: 160px; min-height: 48px; padding: 12px; border: 0; border-radius: var(--radius); background: #faf8fd; font-size: 16px; resize: vertical; }
.lite-composer textarea:focus { outline: 0; }
.lite-composer:focus-within { outline: 2px solid var(--lite-accent); outline-offset: 2px; }
.lite-composer-footer { display: flex; align-items: center; justify-content: flex-end; padding: 0 8px 4px; }
.lite-send { width: 40px; height: 40px; padding: 0; }
.lite-send svg { width: 18px; height: 18px; }
.lite-muted { color: var(--lite-muted); font-size: 12px; }
.lite-status { max-width: 896px; margin: 0 auto 16px; color: var(--lite-muted); font-size: 14px; }
.lite-error { max-width: 896px; margin: 0 auto 12px; padding: 8px 12px; border: 1px solid #873535; border-radius: var(--radius); color: #732222; background: #fff; font-size: 13px; overflow-wrap: anywhere; }
.lite-error button { margin-top: 8px; }
.lite-agent { display: flex; flex-direction: column; flex: 1; min-height: 0; }
.lite-agent-connection { display: flex; flex-wrap: wrap; align-items: center; gap: 12px; padding: 4px 28px; border-bottom: 1px solid var(--lite-border); font-size: 12px; }
.lite-agent-connection button { margin-left: auto; border: 0; min-height: 32px; padding: 4px 0; background: none; font-size: 12px; }
.lite-agent-scroll .lite-transcript { display: flex; flex-direction: column; justify-content: flex-end; min-height: 100%; max-width: 848px; }
.lite-agent-scroll .lite-transcript > * { flex: none; }
.lite-agent-scroll { overflow-anchor: none; }
.lite-agent .lite-message { margin-bottom: 15px; }
.lite-agent .lite-message-content { max-width: 89%; }
.lite-agent .lite-message-user .lite-message-content { max-width: 78%; }
.lite-agent .lite-composer { display: flex; flex-wrap: wrap; align-items: flex-end; gap: 10px; max-width: 788px; padding: 7px 8px 7px 5px; border-radius: 17px; }
.lite-agent .lite-composer textarea { flex: 1; min-width: 0; width: auto; min-height: 46px; max-height: 156px; resize: none; padding: 13px 11px; font-size: 14px; line-height: 20px; border-radius: 12px; }
.lite-agent .lite-composer-footer { flex: none; padding: 0; }
.lite-agent .lite-send { width: 38px; height: 38px; min-height: 38px; margin-bottom: 4px; border-radius: 11px; }
.lite-agent .lite-composer > .lite-attachments, .lite-agent .lite-composer > .lite-error { flex-basis: 100%; }
.lite-delivery-error { color: #732222; }
.lite-delivery-error button { min-height: 0; padding: 0; border: 0; border-radius: 0; background: none; color: inherit; font-size: inherit; text-decoration: underline; }
.lite-result-list { list-style: none; padding: 0; margin: 24px 0 0; }
.lite-result-list li { margin-bottom: 24px; }
.lite-result-list h2 { font-size: 18px; font-weight: 500; }
.lite-result-url { margin: 4px 0 8px; font-size: 12px; color: var(--lite-muted); overflow-wrap: anywhere; }
.lite-search-answer { padding-bottom: 16px; border-bottom: 1px solid var(--lite-border); margin-bottom: 16px; }
.lite-search-answer h2 { margin-bottom: 12px; }
.md-content { overflow-wrap: anywhere; }
.md-content > :first-child { margin-top: 0; }
.md-content > :last-child { margin-bottom: 0; }
.md-content p + p { margin-top: .85rem; }
.md-content h1, .md-content h2, .md-content h3 { margin: 1.2rem 0 .45rem; line-height: 1.25; font-weight: 700; }
.md-content h1 { font-size: 1.45rem; }
.md-content h2 { font-size: 1.25rem; }
.md-content h3 { font-size: 1.1rem; }
.md-content ul, .md-content ol { padding-left: 1.35rem; margin: .85rem 0; }
.md-content li + li { margin-top: .3rem; }
.md-content blockquote { border-left: 3px solid #aaa2b6; margin: 1rem 0; padding-left: 1rem; }
.md-content code { font-size: .86em; border-radius: var(--radius); background: #ebe7f1; padding: .05rem .3rem; }
.md-content pre { margin: 1rem 0; }
.md-content pre code { display: block; background: none; padding: 0; font-size: .88em; line-height: 1.55; white-space: pre; }
.md-table-scroll { max-width: 100%; overflow-x: auto; margin: .35rem 0 1rem; }
.md-content table { border-collapse: collapse; min-width: 100%; font-size: .94em; line-height: 1.48; }
.md-content td, .md-content th { border: 1px solid var(--lite-border); text-align: left; padding: .48rem .7rem; }
.md-content th { background: #ede8f4; white-space: nowrap; }
.lite-auth { max-width: 448px; margin: 15vh auto 0; padding: 24px; border: 1px solid var(--lite-border); border-radius: var(--radius); background: #f9f7fc; }
.lite-auth .lite-brand { margin-bottom: 24px; }
.lite-auth h1 { font-size: 18px; }
.lite-auth p { margin-top: 4px; font-size: 14px; }
.lite-auth form { margin: 20px 0 12px; }
.lite-auth input { margin: 8px 0 12px; }
.lite-auth .lite-primary { width: 100%; }
.lite-auth > a:last-child { font-size: 12px; }
.lite-sidebar-trigger, .lite-sidebar-close, .lite-sidebar-backdrop { display: none; }
.lite-skip, .lite-visually-hidden { position: absolute; width: 1px; height: 1px; padding: 0; overflow: hidden; clip: rect(0, 0, 0, 0); white-space: nowrap; }
.lite-skip:focus { z-index: 100; top: 0; left: 0; width: auto; height: auto; clip: auto; padding: .5rem; background: #fff; }
@supports (height: 100dvh) { html, body, #app { height: 100dvh; } }
@media (min-width: 1024px) { .lite-scroll, .lite-agent-scroll { padding-left: 56px; padding-right: 56px; } }
@media (max-width: 767px) {
.lite-sidebar { display: none; position: fixed; inset: 0 auto 0 0; z-index: 30; width: 86vw; max-width: 320px; }
.lite-sidebar.is-open { display: flex; }
.lite-sidebar-trigger, .lite-sidebar-close { display: inline-flex; background: none; border: 0; }
.lite-sidebar-backdrop { display: block; position: fixed; inset: 0; z-index: 20; width: 100%; height: 100%; border: 0; border-radius: 0; background: #c9c3d3; }
.lite-sidebar-backdrop:hover { background: #c9c3d3; }
.lite-workspace-header { min-height: 65px; padding: 10px 12px; }
.lite-workspace-title h1 { font-size: 14px; }
.lite-header-actions { gap: 4px; }
.lite-settings summary { justify-content: center; width: 40px; padding: 0; }
.lite-settings summary > span { display: none; }
.lite-model-controls { width: min(280px, calc(100vw - 24px)); }
.lite-scroll, .lite-agent-scroll { padding: 24px 16px; }
.lite-message-content { width: 100%; max-width: 100%; }
.lite-message-user > .lite-message-content { width: auto; max-width: 87%; }
.lite-composer-shell { padding: 8px 12px 12px; }
.lite-agent-connection { padding: 4px 16px; }
.lite-agent .lite-message-content { width: auto; }
.lite-auth { margin: 8vh 16px 0; padding: 24px; max-width: none; }
}
+45 -8
View File
@@ -1,18 +1,55 @@
import { useEffect, useState } from "preact/hooks";
import App from "@/App";
import SearchRoutePage from "@/pages/search-route-page";
import type { ComponentType } from "preact";
import { buildUiModeUrl, isLitePath } from "@/lib/ui-mode";
import { installLiteCompatibility } from "@/lib/lite-compat";
function routeName(path: string) {
return isLitePath(path) ? "lite" : path === "/search" ? "search" : "full";
}
async function loadPage(path: string) {
if (isLitePath(path)) {
installLiteCompatibility();
return import("@/pages/lite-route-page");
}
const [page] = await Promise.all([
path === "/search" ? import("@/pages/search-route-page") : import("@/App"),
import("./index.css"),
]);
return page;
}
export function RootRouter() {
const [path, setPath] = useState(window.location.pathname);
const [Page, setPage] = useState<ComponentType | null>(null);
const [failed, setFailed] = useState(false);
useEffect(() => {
const onPopState = () => setPath(window.location.pathname);
let disposed = false;
const path = window.location.pathname;
void loadPage(path).then(page => {
if (!disposed) setPage(() => page.default);
}, () => {
if (!disposed) setFailed(true);
});
// Same-route history belongs to its page. Crossing presentations requires a
// clean document so the full UI's global CSS cannot leak into Lite.
const onPopState = () => {
if (routeName(window.location.pathname) !== routeName(path)) window.location.reload();
};
window.addEventListener("popstate", onPopState);
return () => window.removeEventListener("popstate", onPopState);
return () => {
disposed = true;
window.removeEventListener("popstate", onPopState);
};
}, []);
if (path === "/search") {
return <SearchRoutePage />;
if (failed) {
return <main style={{ maxWidth: "36rem", margin: "2rem auto", padding: "1rem", fontFamily: "sans-serif" }}>
<h1>Sybil could not load</h1>
<p>Check your connection, then reload this page.</p>
<p><button onClick={() => window.location.reload()}>Reload</button></p>
<p><a href={buildUiModeUrl("lite")}>Lightweight UI</a> · <a href={buildUiModeUrl("full")}>Full UI</a></p>
</main>;
}
return <App />;
return Page ? <Page /> : <p role="status" style={{ margin: "2rem", fontFamily: "sans-serif" }}>Loading Sybil…</p>;
}
+23
View File
@@ -0,0 +1,23 @@
@font-face {
font-family: "StalinistOne";
src: url("/StalinistOne-Regular.ttf") format("truetype");
font-weight: 400;
font-style: normal;
font-display: swap;
}
:root {
--font-body: "Inter", "Avenir Next", "Segoe UI", sans-serif;
--font-wordmark: "StalinistOne", "Orbitron", "Inter", sans-serif;
}
body {
font-family: var(--font-body);
}
.sybil-wordmark {
font-family: var(--font-wordmark);
font-weight: 400;
letter-spacing: 0;
line-height: 1;
}
+12
View File
@@ -47,6 +47,18 @@ test('downloads bound concurrent bytes, validate hashes/types, cancel queued wor
await assert.rejects(wrongType.download({...file,kind:'image',mimeType:'image/png'}),/type did not match/);
});
test('downloads support older AbortSignals without throwIfAborted or reason', async () => {
let calls = 0;
const client = new AgentRoomClient({ fetch: async () => { calls++; return new Response('data'); } });
const controller = new AbortController();
Object.defineProperty(controller.signal, 'throwIfAborted', { value: undefined });
Object.defineProperty(controller.signal, 'reason', { value: undefined });
assert.equal(await (await client.download(file, controller.signal)).text(), 'data');
controller.abort();
await assert.rejects(client.download(file, controller.signal), error => error.name === 'AbortError');
assert.equal(calls, 1, 'an already canceled download never starts another request');
});
test('composer gates unsupported servers, count/type/size and batches before upload; preserves retry ID and remove races',async()=>{
let capability, attempts=[], next=0, changed=0, finish;
const queue=createAgentUploadQueue({capability:()=>capability,newId:()=>`upload-${++next}`,changed:()=>changed++,upload:async(_file,id,signal)=>{attempts.push({id,signal});if(attempts.length===1)throw new Error('Quota full');return new Promise(resolve=>finish=resolve);}});
@@ -0,0 +1,8 @@
<!doctype html>
<html lang="en">
<head><meta charset="UTF-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Agent composer layout fixture</title>
<style>html,body,#root{height:100%;margin:0}body{overflow:hidden}#root{display:flex;min-height:0}textarea{font-size:14.25px!important;line-height:20.5px!important}</style>
</head>
<body><div id="root"></div><script type="module" src="/tests/agent-composer-layout-fixture.tsx"></script></body>
</html>
@@ -0,0 +1,29 @@
import { render } from "preact";
import { useMemo } from "preact/hooks";
import type { Message } from "../src/lib/api";
import type { AgentRoomHookResult } from "../src/hooks/use-agent-room";
import { AgentConversation } from "../src/components/agent/agent-conversation";
import "../src/index.css";
const createdAt = "2026-11-08T12:00:00.000Z";
const paragraph = "Synthetic transcript content for composer resize and scroll anchoring. ".repeat(5);
function message(index: number, content: string): Message {
return { id: `layout-${index}`, createdAt: new Date(Date.parse(createdAt) + index * 1000).toISOString(),
role: index % 2 ? "assistant" : "user", content, name: null, metadata: { kind: "message", status: "complete" } };
}
function Fixture() {
const history = useMemo(() => Array.from({ length: 24 }, (_, i) => message(i, `${paragraph}${paragraph}`)), []);
const messages = [...history, message(24, `${paragraph}${paragraph}`)];
const uploadQueue = { snapshot: () => [], add: () => undefined, remove: () => undefined, ready: () => [],
reselect: async () => undefined, retry: () => undefined, clear: () => undefined };
const room = { messages, activity: null, unreadCount: 0, connection: "connected", error: null, isLoading: false,
isLoadingOlder: false, olderError: null, hasOlder: false, historyBeforeCursor: null, attachmentCapability: undefined,
uploadQueue, uploadAttachment: async () => { throw new Error("not used"); }, downloadAttachment: async () => new Blob(),
isTyping: false, sendMessage: async () => ({ status: "queued" }), retryMessage: async () => undefined,
markRead: () => undefined, retry: () => undefined, loadOlder: () => undefined, unreadCountIsPartial: false,
} as unknown as AgentRoomHookResult;
return <AgentConversation room={room} onOpenSidebar={() => undefined} />;
}
render(<Fixture />, document.getElementById("root")!);
+129
View File
@@ -0,0 +1,129 @@
import assert from 'node:assert/strict';
import { spawn } from 'node:child_process';
import { createServer } from 'vite';
import { mkdtemp, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
const root = resolve(fileURLToPath(new URL('..', import.meta.url)));
const browser = process.env.CHROME_EXECUTABLE || '/home/buzzert/.cache/ms-playwright/chromium-1243/chrome-linux64/chrome';
const profile = await mkdtemp(`${tmpdir()}/sybil-agent-composer-layout-`);
const server = await createServer({ configFile: resolve(root, 'vite.config.ts'), root, logLevel: 'error',
server: { host: '127.0.0.1', port: 0, strictPort: false } });
let child, socket;
try {
await server.listen();
const address = server.httpServer.address();
const port = await new Promise((resolvePort, reject) => {
child = spawn(browser, ['--headless', '--no-sandbox', '--disable-dev-shm-usage', '--disable-gpu',
'--remote-debugging-port=0', '--remote-allow-origins=*', `--user-data-dir=${profile}`, '--no-first-run']);
let diagnostics = '';
const timeout = setTimeout(() => reject(new Error(`Chrome startup failed: ${diagnostics.slice(-500)}`)), 10000);
child.stderr.setEncoding('utf8').on('data', chunk => {
diagnostics += chunk;
const match = diagnostics.match(/DevTools listening on ws:\/\/127\.0\.0\.1:(\d+)\//);
if (match) { clearTimeout(timeout); resolvePort(Number(match[1])); }
});
child.once('error', error => { clearTimeout(timeout); reject(error); });
child.once('close', code => { clearTimeout(timeout); reject(new Error(`Chrome exited (${code})`)); });
});
const response = await fetch(`http://127.0.0.1:${port}/json/new?http://127.0.0.1:${address.port}/tests/agent-composer-layout-fixture.html`, { method: 'PUT' });
assert.equal(response.status, 200);
const target = await response.json();
socket = new WebSocket(target.webSocketDebuggerUrl);
await new Promise((resolveOpen, reject) => { socket.addEventListener('open', resolveOpen, { once: true }); socket.addEventListener('error', reject, { once: true }); });
let id = 0;
const pending = new Map();
socket.addEventListener('message', event => {
const message = JSON.parse(event.data), request = pending.get(message.id);
if (!request) return;
pending.delete(message.id);
message.error ? request.reject(new Error(message.error.message)) : request.resolve(message.result);
});
const call = (method, params = {}) => new Promise((resolveCall, reject) => {
const requestId = ++id; pending.set(requestId, { resolve: resolveCall, reject });
socket.send(JSON.stringify({ id: requestId, method, params }));
});
await call('Page.enable'); await call('Runtime.enable');
await call('Page.addScriptToEvaluateOnNewDocument', { source: `(() => {
window.__layoutTrace = [];
const Native = window.ResizeObserver;
window.ResizeObserver = class extends Native {
constructor(callback) { super((entries, observer) => {
const time = performance.now();
for (const entry of entries) window.__layoutTrace.push({ kind: 'resize', time,
target: entry.target.className || entry.target.tagName,
height: entry.contentRect.height, clientHeight: entry.target.clientHeight,
scrollHeight: entry.target.scrollHeight, scrollTop: entry.target.scrollTop });
callback(entries, observer);
}); }
};
document.addEventListener('scroll', event => {
const el = event.target;
if (el instanceof HTMLElement && el.classList.contains('agent-room__scroll')) window.__layoutTrace.push({ kind: 'scroll', time: performance.now(),
clientHeight: el.clientHeight, scrollHeight: el.scrollHeight, scrollTop: el.scrollTop,
gap: el.scrollHeight - el.scrollTop - el.clientHeight });
}, true);
})()` });
const configurations = [{ width: 1200, height: 900, dpr: 1 }, { width: 803, height: 777, dpr: 1.25 }, { width: 389, height: 844, dpr: 2 }];
const all = [];
for (const config of configurations) {
await call('Emulation.setDeviceMetricsOverride', { width: config.width, height: config.height, deviceScaleFactor: config.dpr, mobile: config.width < 768 });
await call('Page.navigate', { url: `http://127.0.0.1:${address.port}/tests/agent-composer-layout-fixture.html?case=${config.width}` });
const result = await call('Runtime.evaluate', { awaitPromise: true, returnByValue: true, expression: `new Promise(resolve => {
const wait = () => {
const scroller = document.querySelector('.agent-room__scroll'), textarea = document.querySelector('textarea[aria-label="Message Sybil Agent"]');
if (!scroller || !textarea) return setTimeout(wait, 20);
setTimeout(async () => {
const settle = () => new Promise(done => requestAnimationFrame(() => requestAnimationFrame(() => setTimeout(done, 90))));
const gap = () => scroller.scrollHeight - scroller.scrollTop - scroller.clientHeight;
const visibleAnchor = () => [...scroller.querySelectorAll('[data-agent-entry-id]')].find(row => row.getBoundingClientRect().bottom > scroller.getBoundingClientRect().top + 8);
const sample = label => { const row = visibleAnchor(); return { label, top: scroller.scrollTop, scrollHeight: scroller.scrollHeight, clientHeight: scroller.clientHeight,
gap: gap(), textareaHeight: textarea.getBoundingClientRect().height, textareaScrollHeight: textarea.scrollHeight,
anchorId: row?.dataset.agentEntryId, anchorTop: row?.getBoundingClientRect().top, dpr: devicePixelRatio } };
const setValue = async (value, label) => { textarea.value = value; textarea.dispatchEvent(new Event('input', { bubbles: true })); await settle(); return sample(label); };
const result = { config: ${JSON.stringify(config)}, bottom: [], nonbottom: [] };
scroller.scrollTop = scroller.scrollHeight; scroller.dispatchEvent(new Event('scroll')); await settle();
result.bottom.push(sample('empty'));
result.bottom.push(await setValue('Short draft', 'short'));
result.bottom.push(await setValue(Array.from({length: 8}, (_,i) => 'Line '+(i+1)).join('\\n'), 'eight-lines'));
result.bottom.push(await setValue(Array.from({length: 26}, (_,i) => 'Wrapped composer line '+(i+1)+' with enough words to wrap at this viewport width.').join('\\n'), 'wrapped-and-capped'));
result.bottom.push(await setValue('one line again', 'shrink'));
result.bottom.push(await setValue('', 'cleared'));
scroller.scrollTop = Math.max(0, (scroller.scrollHeight - scroller.clientHeight) * 0.55); scroller.dispatchEvent(new Event('scroll')); await settle();
const before = sample('before-nonbottom');
result.nonbottom.push(await setValue(Array.from({length: 7}, (_,i) => 'Reader draft '+i).join('\\n'), 'nonbottom-grow'));
result.nonbottom.push(await setValue('shrunk reader draft', 'nonbottom-shrink'));
result.nonbottom.push({ before });
result.trace = (window).__layoutTrace;
resolve(result);
}, 500);
}; wait();
})` });
assert.equal(result.exceptionDetails, undefined, result.exceptionDetails?.text);
all.push(result.result.value);
}
if (process.env.RECORD_ONLY !== '1') for (const result of all) {
for (const sample of result.bottom) assert.ok(Math.abs(sample.gap) <= 1,
`bottom pin drift at ${result.config.width}px/${result.config.dpr}x: ${JSON.stringify(sample)}`);
const byLabel = Object.fromEntries(result.bottom.map(sample => [sample.label, sample]));
assert.equal(byLabel['wrapped-and-capped'].textareaHeight, 156, `textarea cap changed: ${JSON.stringify(result.bottom)}`);
assert.ok(byLabel.shrink.textareaHeight <= 48 && byLabel.cleared.textareaHeight <= 48,
`textarea did not shrink with the draft: ${JSON.stringify(result.bottom)}`);
assert.equal(byLabel.cleared.clientHeight, byLabel.empty.clientHeight,
`composer did not return to its empty height: ${JSON.stringify(result.bottom)}`);
const before = result.nonbottom.find(sample => sample.before)?.before;
for (const sample of result.nonbottom.filter(sample => sample.label?.startsWith('nonbottom-'))) {
assert.equal(sample.anchorId, before.anchorId, `nonbottom anchor changed: ${JSON.stringify({ before, sample })}`);
assert.ok(Math.abs(sample.anchorTop - before.anchorTop) <= 1, `nonbottom transcript jumped: ${JSON.stringify({ before, sample })}`);
}
const nonbottomShrink = result.nonbottom.find(sample => sample.label === 'nonbottom-shrink');
assert.ok(nonbottomShrink.textareaHeight <= 48, `nonbottom textarea did not shrink: ${JSON.stringify(nonbottomShrink)}`);
}
process.stdout.write(JSON.stringify({ browser, all }, null, 2) + '\n');
} finally {
socket?.close();
if (child && child.exitCode === null) { const closed = new Promise(done => child.once('close', done)); child.kill('SIGTERM'); await closed; }
await server.close(); await rm(profile, { recursive: true, force: true });
}
+142
View File
@@ -0,0 +1,142 @@
import assert from "node:assert/strict";
// Production bundle/worker, mobile Chromium; all API and push-provider operations are fixtures.
// Use the same PLAYWRIGHT_MODULE, CHROME_EXECUTABLE and WEB_TEST_URL as agent-push.browser.mjs.
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 browser = await chromium.launch({ executablePath: process.env.CHROME_EXECUTABLE || undefined, headless: true,
...(process.env.BROWSER_NO_SANDBOX === "1" ? { args: ["--no-sandbox"] } : {}) });
const context = await browser.newContext({ viewport: { width: 390, height: 844 }, isMobile: true, hasTouch: true });
const sourceId = "4599d348-e053-4937-987d-1392746fb2ce";
const config = { version: 1, enabled: true, webPushAvailable: true, apnsAvailable: false, sourceId, quarantined: false,
vapidPublicKey: "B".repeat(87), policy: { presenceHeartbeatMs: 15000, presenceLeaseMs: 60000 } };
let registerStatus = 200, configStatus = 200, puts = 0;
const errors = [];
await context.addInitScript(() => {
localStorage.setItem("sybil_admin_token", "mobile-notification-fixture");
window.__permission = "default"; window.__decision = "default"; window.__subscribed = false; window.__subscribes = 0;
window.__subscribeError = null; window.__workerError = false; window.__subscribeHang = false; window.__permissionGesture = false;
Object.defineProperty(Notification, "permission", { configurable: true, get: () => window.__permission });
Notification.requestPermission = () => {
window.__permissionGesture = navigator.userActivation.isActive;
window.__permission = window.__decision; return Promise.resolve(window.__permission);
};
const register = navigator.serviceWorker.register.bind(navigator.serviceWorker);
navigator.serviceWorker.register = (...args) => window.__workerError ? Promise.reject(new Error("private-worker-detail")) : register(...args);
const subscription = { toJSON: () => ({ endpoint: "https://fcm.googleapis.com/fcm/send/private-endpoint", keys: { p256dh: "B".repeat(87), auth: "A".repeat(22) } }),
unsubscribe: async () => { window.__subscribed = false; return true; } };
PushManager.prototype.getSubscription = async () => window.__subscribed ? subscription : null;
PushManager.prototype.subscribe = async () => {
window.__subscribes++;
if (window.__subscribeError) throw new DOMException("private-provider-key", window.__subscribeError);
if (window.__subscribeHang) return await new Promise(() => {});
window.__subscribed = true; return subscription;
};
});
await context.route("**/*", async route => {
const request = route.request(), url = new URL(request.url()), path = url.pathname;
if (url.origin !== target.origin) { await route.abort(); return; }
if (!path.startsWith("/api/")) { await route.continue(); return; }
let value = {}, status = 200;
if (path.endsWith("/push/config")) { value = config; status = configStatus; }
else if (path.includes("/push/installations/")) {
if (request.method() === "DELETE") { await route.fulfill({ status: 204 }); return; }
puts++; status = registerStatus;
value = status === 200 ? { installationId: path.split("/").at(-1), transport: "web", enabled: true, version: 1 } : { error: "private-server-token" };
} else if (path.endsWith("/auth/session")) value = { mode: "token", authenticated: true };
else if (path.endsWith("/workspace-items")) value = { items: [] };
else if (path.endsWith("/models")) value = { providers: {} };
else if (path.endsWith("/chat-tools")) value = { tools: [] };
else if (path.endsWith("/active-runs")) value = { chats: [], searches: [] };
else if (path.endsWith("/read-state")) value = { sourceId, cursor: "0", updatedAt: null };
await route.fulfill({ status, json: value });
});
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("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("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.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.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());
await page.evaluate(() => { window.__permission = "default"; window.__decision = "granted"; window.__workerError = true; });
await attempt(/worker could not start/); assert.equal(puts, 0);
await page.evaluate(() => { window.__workerError = false; });
for (const [name, pattern] of [["AbortError", /push service \(AbortError\)/], ["NotAllowedError", /site settings.*system settings/],
["NotSupportedError", /cannot create a push subscription/], ["InvalidStateError", /incompatible notification subscription/]]) {
await page.evaluate(name => { window.__subscribeError = name; }, name);
await attempt(pattern); assert.equal(puts, 0);
// Successful foreground config refresh must not dismiss an opt-in diagnosis.
await page.evaluate(() => window.dispatchEvent(new Event("online")));
await page.waitForTimeout(150);
assert.match(await alert.textContent(), pattern);
}
await page.evaluate(() => { window.__subscribeError = null; window.__subscribeHang = true; });
await page.clock.install();
await refresh.click(); await waitEnable();
const before = await page.evaluate(() => window.__subscribes);
await enable.click(); await page.waitForFunction(before => window.__subscribes > before, before);
await page.clock.fastForward(10001);
await alert.filter({ hasText: "TimeoutError" }).waitFor(); assert.equal(puts, 0);
await page.clock.resume();
await page.evaluate(() => { window.__subscribeHang = false; });
for (const [status, pattern] of [[401, /sign-in.*authorized/], [403, /sign-in.*authorized/], [400, /rejected.*subscription/],
[409, /expired/], [429, /busy/], [503, /unavailable on the Sybil server/]]) {
registerStatus = status; await attempt(pattern);
assert.equal(await page.evaluate(() => window.__subscribed), false, "failed registration rolls back the subscription");
}
registerStatus = 200; configStatus = 503;
await refresh.click(); await alert.filter({ hasText: "unavailable on the Sybil server" }).waitFor();
configStatus = 200;
await refresh.click(); await waitEnable(); await enable.click();
await page.getByRole("button", { name: "Turn off notifications", exact: true }).waitFor();
assert.equal(await alert.count(), 0);
await page.getByText("Android / GrapheneOS help", { exact: true }).click();
await page.getByRole("link", { name: "GrapheneOS setup guide" }).waitFor();
assert.equal(await page.evaluate(() => document.documentElement.scrollWidth > innerWidth), false);
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 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);
}
await page.setViewportSize({ width: 390, height: 844 });
await page.getByRole("button", { name: "Turn off notifications", exact: true }).click(); await waitEnable();
await page.evaluate(() => { delete window.PushManager; });
await refresh.click(); await page.getByText(/This browser does not support notifications here/).waitFor();
assert.ok(await enable.isDisabled());
await page.evaluate(() => {
Object.defineProperty(window, "isSecureContext", { configurable: true, value: true });
Object.defineProperty(navigator, "userAgent", { configurable: true, value: "Mozilla/5.0 (iPhone; CPU iPhone OS 18_0 like Mac OS X)" });
});
await refresh.click(); await page.getByText(/On iPhone or iPad, add Sybil to your Home Screen/).waitFor();
assert.ok(await enable.isDisabled());
await page.evaluate(() => { Object.defineProperty(window, "isSecureContext", { configurable: true, value: false }); });
await refresh.click(); await page.getByText(/Notifications require a secure connection/).waitFor();
assert.ok(await enable.isDisabled());
assert.deepEqual(errors, []);
console.log("PASS mobile permission dismissal/denial, worker/subscription failures, timeout, HTTP statuses, rollback, retained diagnostics, recovery, unsupported/insecure browsers and GrapheneOS guidance");
} finally { await context.close(); await browser.close(); }
+13 -5
View File
@@ -71,11 +71,15 @@ 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 page.getByText("Notifications are not configured on this server yet.", { exact: true }).waitFor();
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), []);
config.sourceId = sourceId;
@@ -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")) }));
+68 -1
View File
@@ -6,6 +6,7 @@ import {
MAX_AGENT_PUSH_REVOCATIONS, parseAgentPushConfig, parseAgentPushConsent,
} from "../src/lib/agent-push.ts";
import { agentAuthFrame, applyAgentEvent, createAgentRoomState, parseAgentRoomEvent } from "../src/lib/agent-room.ts";
import { AgentPushError, browserPushOperation } from "../src/lib/agent-push-errors.ts";
const sourceId = "4599d348-e053-4937-987d-1392746fb2ce";
const replacementSourceId = "22222222-2222-4222-8222-222222222222";
@@ -120,7 +121,72 @@ test("a stuck cross-tab lock cannot prevent server retirement or local logout cl
test("synchronous permission API failures remain a recoverable opt-in error", async () => {
const f = fixture({ platform: { requestPermission: () => { throw new Error("user gesture rejected"); } } });
await f.controller.refresh(); await f.controller.enable();
assert.equal(f.record().enabled, false); assert.match(f.controller.state().error, /could not be requested/);
assert.equal(f.record().enabled, false); assert.match(f.controller.state().error, /browser.*system settings/);
});
test("browser subscription failures retain safe diagnoses across background refreshes", async () => {
for (const [name, message] of [["AbortError", /push service \(AbortError\)/], ["NotAllowedError", /site settings.*system settings/],
["NotSupportedError", /cannot create a push subscription/], ["InvalidStateError", /incompatible notification subscription/], ["InvalidAccessError", /notification key/]]) {
const f = fixture({ platform: { subscribe: () => browserPushOperation(() => Promise.reject(new DOMException("private-endpoint-and-key", name)), "subscription") } });
await f.controller.refresh(); await f.controller.enable();
assert.match(f.controller.state().error, message);
assert.equal(f.controller.state().enabled, false);
assert.ok(!f.calls.some(([name]) => name === "register"));
await f.controller.refresh();
assert.match(f.controller.state().error, message, "heartbeat cannot erase a failed opt-in");
assert.doesNotMatch(JSON.stringify(f.states), /private-endpoint-and-key/);
await f.controller.refresh(true);
assert.equal(f.controller.state().error, null, "explicit refresh clears the previous attempt");
}
});
test("worker startup and subscription timeouts have distinct actionable errors", async () => {
for (const [stage, message] of [["worker", /worker could not start/], ["subscription", /push service \(TimeoutError\)/]]) {
const f = fixture({ platform: { subscribe: () => browserPushOperation(() => new Promise(() => {}), stage, 5) } });
await f.controller.refresh(); await f.controller.enable();
assert.match(f.controller.state().error, message); assert.equal(f.controller.state().busy, false);
assert.equal(f.controller.state().enabled, false);
}
});
test("dismissed prompts and insecure contexts do not attempt a subscription", async () => {
const f = fixture({ platform: { requestPermission: async () => "default" } });
await f.controller.refresh(); await f.controller.enable();
assert.match(f.controller.state().error, /dismissed/); assert.equal(f.calls.length, 0);
f.setSupport("insecure");
assert.equal(f.controller.state().canEnable, false); assert.match(f.controller.state().message, /HTTPS/);
});
test("notification API errors retain status-specific guidance through rollback without echoing bodies", async () => {
for (const [status, message] of [[401, /sign-in.*authorized/], [403, /sign-in.*authorized/], [400, /rejected.*subscription/],
[409, /expired/], [429, /busy/], [503, /unavailable on the Sybil server/], [500, /server.*save notification settings/]]) {
const api = new AgentPushClient({ baseUrl: "https://sybil.example", token: () => "private-auth-token",
fetch: async () => new Response(JSON.stringify({ error: "private-endpoint-and-key" }), { status }) });
const f = fixture({ api: { register: (id, subscription) => api.register(id, subscription) } });
await f.controller.refresh(); await f.controller.enable();
assert.match(f.controller.state().error, message); assert.equal(f.controller.state().enabled, false);
assert.ok(f.calls.some(([name]) => name === "unsubscribe"));
assert.doesNotMatch(JSON.stringify(f.states), /private-auth-token|private-endpoint-and-key/);
}
});
test("failed storage after subscribing still unsubscribes and retains cleanup intent", async () => {
const f = fixture(); let writes = 0;
const write = f.options.write;
f.options.write = value => { if (++writes > 1) throw new DOMException("private-storage-detail", "QuotaExceededError"); write(value); };
await f.controller.refresh(); await f.controller.enable();
assert.match(f.controller.state().error, /storage.*free some space/);
assert.equal(f.controller.state().enabled, false);
assert.ok(f.calls.some(([name]) => name === "unsubscribe"));
assert.ok(f.calls.some(([name]) => name === "revoke"));
assert.ok(!f.calls.some(([name]) => name === "register"));
assert.doesNotMatch(JSON.stringify(f.states), /private-storage-detail/);
});
test("server errors during refresh are distinct from unavailable browser push", async () => {
const f = fixture({ api: { config: async () => { throw new AgentPushError("Web Push is unavailable on the Sybil server."); } } });
await f.controller.refresh();
assert.match(f.controller.state().error, /Sybil server/); assert.equal(f.controller.state().canEnable, false);
});
test("subscription rotation upserts the same installation; permission revocation removes it", async () => {
@@ -418,6 +484,7 @@ test("read frames validate source/cursor and preserve existing read semantics",
assert.throws(() => parseAgentRoomEvent(JSON.stringify({ type: "read_state", cursor: "1", updatedAt: null, sourceId: "https://evil.test" })));
assert.equal(parseAgentPushConsent('{"enabled":true}'), null);
assert.throws(() => parseAgentPushConfig({ ...configuration(), policy: { presenceHeartbeatMs: 1, presenceLeaseMs: 60000 } }));
assert.throws(() => parseAgentPushConfig({ ...configuration(), vapidPublicKey: undefined }), /invalid notification configuration/);
});
test("API keeps credentials in headers, validates receipts, handles 204 and redacts provider bodies", async () => {

Some files were not shown because too many files have changed in this diff Show More