Compare commits

..
69 changed files with 4060 additions and 444 deletions
+10 -1
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
@@ -180,7 +181,7 @@ 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 source chat is unchanged. Copied messages receive new ids while retaining their role, content, name, creation time, order, and metadata except for the source request's transport-only `clientRequestId`. Attachments, tool-call metadata, and per-response `metadata.generation` are retained. For older replies with an exact call-log match, generation metadata is recovered before copying. LLM call logs, star/project memberships, and other child threads are not copied.
- The fork inherits the source chat's user, initiated/last-used provider and model, additional system prompt, and enabled tool settings.
- 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>'`.
@@ -233,6 +234,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`.
@@ -338,6 +342,7 @@ Behavior notes:
- 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.
- `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.
@@ -801,6 +806,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:
+4
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
@@ -146,6 +148,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
+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.
@@ -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
@@ -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
)
}
}
@@ -467,7 +479,8 @@ final class SybilViewModel {
return StreamingAssistantPresentation(
messageID: messageID,
ephemeralTrace: quickQuestionStreamingAssistantState.ephemeralTrace,
traceRevision: quickQuestionStreamingAssistantState.traceRevision
traceRevision: quickQuestionStreamingAssistantState.traceRevision,
isAwaitingVisibleText: quickQuestionStreamingAssistantState.isAwaitingVisibleText
)
}
@@ -2151,6 +2164,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,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
}
}
+1
View File
@@ -85,6 +85,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({
+4 -1
View File
@@ -123,7 +123,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({
+31
View File
@@ -0,0 +1,31 @@
import { fromPrismaProvider } 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 = fromPrismaProvider(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;
});
}
+4 -2
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";
@@ -1173,11 +1174,12 @@ export async function registerRoutes(app: FastifyInstance, options: { agentInlin
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);
@@ -1680,7 +1682,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) => {
+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]);
});
+50 -1
View File
@@ -29,7 +29,7 @@ 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
@@ -43,6 +43,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 +60,52 @@ 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 choose **Lightweight view** in the full workspace sidebar. **Full interface** switches back. Explicit switches (`?ui=lite` and `?ui=full`) remember the choice in `sybil:ui-mode`; workspace IDs, query parameters, and hashes survive switching. A direct `/lite` visit always works even if Full was previously selected.
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.
Agent notification settings include separate browser/server failure guidance and an expandable Android / GrapheneOS setup guide. See [mobile QA results and limitations](../docs/mobile-web-qa.md), including how to run the browser fixtures.
+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"
+78 -257
View File
@@ -1,5 +1,15 @@
import {
readSidebarSelectionFromUrl, buildWorkspaceUrl,
PROVIDER_FALLBACK_MODELS, EMPTY_MODEL_CATALOG, EMPTY_MODEL_PREFERENCES,
createClientRequestId, isRecoverableStreamDisconnect, hasNewPersistedUserMessage,
getModelOptions, getVisibleProviders, loadStoredModelPreferences, saveModelPreferences,
normalizeStoredProvider, normalizeStoredModelPreferences, pickProviderModel, buildCompletionMessages,
type ProviderModelPreferences,
} from "@/lib/workspace-domain";
import { buildUiModeUrl } from "@/lib/ui-mode";
import { useEffect, useLayoutEffect, useMemo, useRef, useState } from "preact/hooks";
import type { TargetedTouchEvent } from "preact";
import { getProviderLabel } from "@/lib/message-generation";
import {
Check,
Bot,
@@ -28,6 +38,7 @@ import { ChatComposer } from "@/components/chat/chat-composer";
import { ChatMessagesPanel } from "@/components/chat/chat-messages-panel";
import { AgentConversation } from "@/components/agent/agent-conversation";
import { AgentNotifications } from "@/components/agent/agent-notifications";
import { hasTextSelection, ownsMobileGesture } from "@/lib/mobile-workspace-gestures";
import { SearchResultsPanel } from "@/components/search/search-results-panel";
import { SearchMatchLabel } from "@/components/search/search-match-label";
import { SybilCharacter } from "@/components/sybil-character";
@@ -62,7 +73,6 @@ import {
type ChatDetail,
type ChatSummary,
type ChatToolInfo,
type CompletionRequestMessage,
type Message,
type SearchDetail,
type SearchSummary,
@@ -120,12 +130,6 @@ type ContextMenuState = {
item: SidebarSelection;
x: number;
y: number;
} | {
kind: "message";
chatId: string;
messageId: string;
x: number;
y: number;
};
type RenameChatDialogState = {
chatId: string;
@@ -143,53 +147,6 @@ type RefreshCollectionsOptions = {
selectFallback?: boolean;
};
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;
}
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}` : ""}`;
}
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"],
"hermes-agent": ["hermes-agent"],
};
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 },
};
const BASE_PROVIDERS: Provider[] = ["openai", "anthropic", "xai", "gemini"];
const ALL_PROVIDERS: Provider[] = [...BASE_PROVIDERS, "hermes-agent"];
const MODEL_PREFERENCES_STORAGE_KEY = "sybil:modelPreferencesByProvider";
const QUICK_QUESTION_MODEL_SELECTION_STORAGE_KEY = "sybil:quickQuestionModelSelection";
const STREAM_RESUME_RETRY_DELAYS_MS = [0, 250, 750, 1500];
const MOBILE_LAYOUT_MEDIA_QUERY = "(max-width: 767px)";
@@ -202,26 +159,18 @@ type MobileWorkspaceSwipe = {
touchIdentifier: number;
startX: number;
startY: number;
startTimestamp: number;
lastX: number;
lastTimestamp: number;
velocityX: number;
direction: -1 | 1 | null;
};
type ProviderModelPreferences = Record<Provider, string | null>;
type QuickQuestionModelSelection = {
provider: Provider;
modelPreferences: ProviderModelPreferences;
};
const EMPTY_MODEL_PREFERENCES: ProviderModelPreferences = {
openai: null,
anthropic: null,
xai: null,
gemini: null,
"hermes-agent": null,
};
const EMPTY_ACTIVE_RUNS: ActiveRunsState = {
chats: {},
searches: {},
@@ -288,34 +237,6 @@ function getActiveRunsAfterResume() {
return retryAfterAppResume(getActiveRuns);
}
function createClientRequestId() {
if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
return crypto.randomUUID();
}
return `web-${Date.now()}-${Math.random().toString(36).slice(2)}`;
}
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")
);
}
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));
});
}
const TRANSCRIPT_BOTTOM_GAP = 20;
const REPLY_SCROLL_BUFFER_MIN = 288;
const REPLY_SCROLL_BUFFER_MAX = 576;
@@ -380,16 +301,6 @@ const TEXT_ATTACHMENT_MIME_TYPES = new Set([
"image/svg+xml",
]);
function getModelOptions(catalog: ModelCatalogResponse["providers"], provider: Provider) {
const providerModels = catalog[provider]?.models ?? [];
if (providerModels.length) return providerModels;
return PROVIDER_FALLBACK_MODELS[provider];
}
function getVisibleProviders(catalog: ModelCatalogResponse["providers"]) {
return ALL_PROVIDERS.filter((provider) => provider !== "hermes-agent" || catalog[provider] !== undefined);
}
function getReplyScrollBufferHeight() {
if (typeof window === "undefined") return REPLY_SCROLL_BUFFER_MIN;
return Math.min(
@@ -495,44 +406,6 @@ function hasFileTransfer(dataTransfer: DataTransfer | null) {
return Array.from(dataTransfer.types ?? []).includes("Files") || getFilesFromDataTransfer(dataTransfer).length > 0;
}
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;
const parsed = JSON.parse(raw) as Partial<Record<Provider, string>>;
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,
"hermes-agent":
typeof parsed["hermes-agent"] === "string" && parsed["hermes-agent"].trim() ? parsed["hermes-agent"].trim() : null,
};
} catch {
return EMPTY_MODEL_PREFERENCES;
}
}
function normalizeStoredProvider(value: unknown): Provider {
return value === "anthropic" || value === "xai" || value === "gemini" || value === "openai" || value === "hermes-agent"
? value
: "openai";
}
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,
"hermes-agent":
typeof parsed["hermes-agent"] === "string" && parsed["hermes-agent"].trim() ? parsed["hermes-agent"].trim() : null,
};
}
function loadStoredQuickQuestionModelSelection(): QuickQuestionModelSelection {
if (typeof window === "undefined") {
return { provider: "openai", modelPreferences: EMPTY_MODEL_PREFERENCES };
@@ -550,20 +423,6 @@ function loadStoredQuickQuestionModelSelection(): QuickQuestionModelSelection {
}
}
function pickProviderModel(options: string[], preferred: string | null) {
if (preferred?.trim()) return preferred.trim();
return options[0] ?? "";
}
function getProviderLabel(provider: Provider | null | undefined) {
if (provider === "openai") return "OpenAI";
if (provider === "anthropic") return "Anthropic";
if (provider === "xai") return "xAI";
if (provider === "gemini") return "Gemini";
if (provider === "hermes-agent") return "Hermes Agent";
return "";
}
function getToolLabel(name: string) {
if (name === "web_search") return "Web search";
if (name === "fetch_url") return "Fetch URL";
@@ -609,10 +468,6 @@ function asToolLogMetadata(value: unknown): ToolLogMetadata | null {
return record as ToolLogMetadata;
}
function isToolCallLogMessage(message: Message) {
return asToolLogMetadata(message.metadata) !== null;
}
function isDisplayableMessage(message: Message) {
return message.role !== "system";
}
@@ -1434,7 +1289,7 @@ export default function App() {
hasSyncedSelectionHistoryRef.current = false;
return;
}
const current = `${window.location.pathname}${window.location.search}`;
const current = `${window.location.pathname}${window.location.search}${window.location.hash}`;
const next = buildWorkspaceUrl(selectedItem);
if (!hasSyncedSelectionHistoryRef.current) {
@@ -1467,7 +1322,7 @@ export default function App() {
useEffect(() => {
if (typeof window === "undefined") return;
window.localStorage.setItem(MODEL_PREFERENCES_STORAGE_KEY, JSON.stringify(providerModelPreferences));
saveModelPreferences(providerModelPreferences);
}, [providerModelPreferences]);
useEffect(() => {
@@ -1631,6 +1486,7 @@ export default function App() {
useEffect(() => {
if (isActiveSelectionSending) return;
if (isSearchMode) return;
const hasWorkspaceSelection = Boolean(selectedItem) || draftKind !== null;
if (!hasWorkspaceSelection) return;
const mobileLayout = isMobileLayout();
@@ -1640,7 +1496,7 @@ export default function App() {
}
suppressNextMobileComposerFocusRef.current = false;
focusComposer();
}, [draftKind, isActiveSelectionSending, selectedKey]);
}, [draftKind, isActiveSelectionSending, isSearchMode, selectedKey]);
useEffect(() => {
return () => {
@@ -1809,8 +1665,11 @@ export default function App() {
};
const handleMobileWorkspaceTouchStart = (event: TargetedTouchEvent<HTMLElement>) => {
resetMobileWorkspaceSwipe();
if (
event.defaultPrevented ||
event.touches.length !== 1 ||
hasTextSelection() ||
!isMobileLayout() ||
isMobileSidebarOpen ||
isQuickQuestionOpen ||
@@ -1820,13 +1679,7 @@ export default function App() {
return;
}
const target = event.target;
if (
target instanceof Element &&
target.closest("input, textarea, select, button, a, [role='dialog'], [data-mobile-swipe-ignore]")
) {
return;
}
if (ownsMobileGesture(event.target, event.currentTarget)) return;
const touch = event.touches.item(0);
if (!touch) return;
@@ -1834,6 +1687,7 @@ export default function App() {
touchIdentifier: touch.identifier,
startX: touch.clientX,
startY: touch.clientY,
startTimestamp: event.timeStamp,
lastX: touch.clientX,
lastTimestamp: event.timeStamp,
velocityX: 0,
@@ -1844,6 +1698,10 @@ export default function App() {
const handleMobileWorkspaceTouchMove = (event: TargetedTouchEvent<HTMLElement>) => {
const swipe = mobileWorkspaceSwipeRef.current;
if (!swipe) return;
if (event.touches.length !== 1 || hasTextSelection() || (swipe.direction === null && event.timeStamp - swipe.startTimestamp > 350)) {
resetMobileWorkspaceSwipe();
return;
}
const touch = findTouch(event.touches, swipe.touchIdentifier);
if (!touch) return;
@@ -1891,7 +1749,7 @@ export default function App() {
swipe.velocityX = ((touch.clientX - swipe.lastX) / elapsedMs) * 1000;
}
resetMobileWorkspaceSwipe();
if (direction === null) return;
if (direction === null || hasTextSelection()) return;
const directionalDistance = deltaX * direction;
const directionalVelocity = swipe.velocityX * direction;
@@ -1937,6 +1795,7 @@ export default function App() {
setIsChatSettingsOpen(false);
setChatSettingsError(null);
setIsMobileSidebarOpen(false);
focusComposer();
};
const selectAdjacentSidebarItem = (direction: -1 | 1) => {
@@ -2195,23 +2054,6 @@ export default function App() {
setContextMenu({ kind: "sidebar", item, x: Math.max(padding, x), y: Math.max(padding, y) });
};
const openMessageContextMenu = (event: MouseEvent, messageId: string) => {
if (selectedItem?.kind !== "chat" || messageId.startsWith("temp-")) return;
event.preventDefault();
const menuWidth = 176;
const menuHeight = 48;
const padding = 8;
const x = Math.min(event.clientX, window.innerWidth - menuWidth - padding);
const y = Math.min(event.clientY, window.innerHeight - menuHeight - padding);
setContextMenu({
kind: "message",
chatId: selectedItem.id,
messageId,
x: Math.max(padding, x),
y: Math.max(padding, y),
});
};
const handleRenameChatSubmit = async (event?: Event) => {
event?.preventDefault();
if (!renameChatDialog || isRenamingChat) return;
@@ -2625,22 +2467,7 @@ export default function App() {
}));
addActiveRun("chat", chatId);
const requestMessages: CompletionRequestMessage[] = [
...baseChat.messages
.filter((message) => !isToolCallLogMessage(message))
.map((message) => ({
id: message.id,
role: message.role,
content: message.content,
...(message.name ? { name: message.name } : {}),
...(getMessageAttachments(message.metadata).length ? { attachments: getMessageAttachments(message.metadata) } : {}),
})),
{
role: "user",
content,
...(attachments.length ? { attachments } : {}),
},
];
const requestMessages = buildCompletionMessages(baseChat.messages, content, attachments);
if (shouldRequestChatTitle(baseChat, pendingTitleGenerationRef.current.has(chatId)) && !content.toLowerCase().includes("@sybil")) {
pendingTitleGenerationRef.current.add(chatId);
@@ -3475,7 +3302,7 @@ export default function App() {
}
} finally {
const shouldSuppressMobileChatFocus = sentTarget?.kind === "chat" && isMobileLayout();
if ((!sentTarget || isCurrentSelection(sentTarget)) && !shouldSuppressMobileChatFocus) {
if ((!sentTarget || isCurrentSelection(sentTarget)) && !sentAsSearch && !shouldSuppressMobileChatFocus) {
focusComposer();
}
}
@@ -3518,7 +3345,7 @@ export default function App() {
<aside
className={cn(
"workspace-sidebar glass-panel fixed inset-y-0 left-0 z-40 flex w-[86vw] max-w-80 shrink-0 flex-col border-r border-violet-300/18 transition-transform md:static md:z-auto md:w-80 md:max-w-none",
"workspace-sidebar glass-panel fixed inset-y-0 left-0 z-40 flex w-[86vw] max-w-80 shrink-0 flex-col overflow-y-auto overscroll-contain border-r border-violet-300/18 transition-transform md:static md:z-auto md:w-80 md:max-w-none",
isMobileSidebarOpen ? "translate-x-0" : "-translate-x-full md:translate-x-0"
)}
>
@@ -3737,15 +3564,19 @@ export default function App() {
<p className="px-3 py-2 text-xs text-muted-foreground">Showing the 100 most recent matches. Refine your search to find more.</p>
) : null}
</div>
<a href={buildUiModeUrl("lite", new URL(buildWorkspaceUrl(selectedItem), window.location.href))} className="mx-4 mb-3 text-xs text-violet-100/70 underline underline-offset-4">
Lightweight view
</a>
{authMode === "token" ? <AgentNotifications onLogout={logout} /> : null}
</aside>
<main
className="workspace-content glass-panel relative flex min-w-0 flex-1 touch-pan-y flex-col overflow-hidden md:touch-auto"
className="workspace-content glass-panel relative flex min-w-0 flex-1 flex-col overflow-hidden"
onTouchStart={handleMobileWorkspaceTouchStart}
onTouchMove={handleMobileWorkspaceTouchMove}
onTouchEnd={handleMobileWorkspaceTouchEnd}
onTouchCancel={handleMobileWorkspaceTouchCancel}
onContextMenu={resetMobileWorkspaceSwipe}
>
{isAgentMode ? (
<AgentConversation room={agentRoom} onOpenSidebar={() => setIsMobileSidebarOpen(true)} isVisible={!isMobileSidebarOpen && !isQuickQuestionOpen} />
@@ -3763,8 +3594,11 @@ export default function App() {
<Menu className="h-4 w-4" />
</Button>
<div className="flex min-w-0 items-center gap-1.5">
<div className="min-w-0">
<h1 className="truncate text-sm font-semibold text-violet-50 md:text-base">{selectedTitle}</h1>
{!isSearchMode ? <p className="truncate text-xs text-violet-100/58 md:hidden" title={`${getProviderLabel(provider)} · ${model || "No model"}`}>
{getProviderLabel(provider)} · {model || "No model"}
</p> : null}
</div>
</div>
<div className="flex shrink-0 items-center justify-end gap-2">
@@ -3778,8 +3612,8 @@ export default function App() {
aria-label="Open chat settings"
>
<Settings2 className="h-4 w-4 shrink-0" />
<span className="hidden shrink-0 sm:inline">Settings</span>
<span className="hidden min-w-0 max-w-[18rem] truncate text-xs font-medium text-violet-100/58 sm:inline">
<span className="hidden shrink-0 md:inline">Settings</span>
<span className="hidden min-w-0 max-w-[18rem] truncate text-xs font-medium text-violet-100/58 md:inline">
{getProviderLabel(provider)} · {model || "No model"}
</span>
</Button>
@@ -3810,7 +3644,8 @@ export default function App() {
messages={displayMessages}
isLoading={isLoadingSelection}
isSending={isSendingActiveChat}
onMessageContextMenu={openMessageContextMenu}
onForkMessage={selectedItem?.kind === "chat" ? messageId => void handleForkChat(selectedItem.id, messageId) : undefined}
isForking={isForkingChat}
/>
) : (
<SearchResultsPanel
@@ -3897,65 +3732,51 @@ export default function App() {
style={{ left: contextMenu.x, top: contextMenu.y }}
onContextMenu={(event) => event.preventDefault()}
>
{contextMenu.kind === "message" ? (
<button
type="button"
className="flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-sm text-violet-100 transition hover:bg-violet-400/12 disabled:text-muted-foreground"
onClick={() => void handleForkChat(contextMenu.chatId, contextMenu.messageId)}
disabled={isForkingChat}
>
<GitFork className="h-3.5 w-3.5" />
Fork
</button>
) : (
<button
type="button"
className="flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-sm text-violet-100 transition hover:bg-violet-400/12"
onClick={() => void handleToggleStar(contextMenu.item)}
>
<Star
className={cn(
"h-3.5 w-3.5",
isSidebarTargetStarred(contextMenu.item)
? "fill-amber-300 text-amber-300"
: ""
)}
/>
{isSidebarTargetStarred(contextMenu.item) ? "Unstar" : "Star"}
</button>
{contextMenu.item.kind === "chat" ? (
<>
<button
type="button"
className="flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-sm text-violet-100 transition hover:bg-violet-400/12"
onClick={() => void handleToggleStar(contextMenu.item)}
className="flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-sm text-violet-100 transition hover:bg-violet-400/12 disabled:text-muted-foreground"
onClick={() => void handleForkChat(contextMenu.item.id)}
disabled={isForkingChat || isItemRunning(contextMenu.item)}
>
<Star
className={cn(
"h-3.5 w-3.5",
isSidebarTargetStarred(contextMenu.item)
? "fill-amber-300 text-amber-300"
: ""
)}
/>
{isSidebarTargetStarred(contextMenu.item) ? "Unstar" : "Star"}
<GitFork className="h-3.5 w-3.5" />
Fork
</button>
{contextMenu.item.kind === "chat" ? (
<>
<button
type="button"
className="flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-sm text-violet-100 transition hover:bg-violet-400/12 disabled:text-muted-foreground"
onClick={() => void handleForkChat(contextMenu.item.id)}
disabled={isForkingChat || isItemRunning(contextMenu.item)}
>
<GitFork className="h-3.5 w-3.5" />
Fork
</button>
<button
type="button"
className="flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-sm text-violet-100 transition hover:bg-violet-400/12"
onClick={() => openRenameChatDialog(contextMenu.item.id)}
>
<Pencil className="h-3.5 w-3.5" />
Rename
</button>
</>
) : null}
<button
type="button"
className="flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-sm text-rose-300 transition hover:bg-rose-500/12 disabled:text-muted-foreground"
onClick={() => void handleDeleteFromContextMenu()}
disabled={isDeleteBlocked(contextMenu.item)}
className="flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-sm text-violet-100 transition hover:bg-violet-400/12"
onClick={() => openRenameChatDialog(contextMenu.item.id)}
>
<Trash2 className="h-3.5 w-3.5" />
{isRootChat(contextMenu.item) ? "Delete group" : "Delete"}
<Pencil className="h-3.5 w-3.5" />
Rename
</button>
</>
)}
) : null}
<button
type="button"
className="flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-sm text-rose-300 transition hover:bg-rose-500/12 disabled:text-muted-foreground"
onClick={() => void handleDeleteFromContextMenu()}
disabled={isDeleteBlocked(contextMenu.item)}
>
<Trash2 className="h-3.5 w-3.5" />
{isRootChat(contextMenu.item) ? "Delete group" : "Delete"}
</button>
</div>
) : null}
{isChatSettingsOpen ? (
@@ -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) => {
@@ -6,7 +6,7 @@ import { disableAgentBrowserPush, enableAgentBrowserPush, getAgentPushState, obs
export function AgentNotifications({ onLogout }: { onLogout: () => Promise<void> }) {
const [state, setState] = useState(getAgentPushState), [signingOut, setSigningOut] = 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">
return <details className="max-h-[50dvh] shrink-0 overflow-y-auto overscroll-contain border-t border-violet-300/15 px-3 py-2 text-xs text-violet-100/75">
<summary className="flex cursor-pointer items-center gap-2 rounded py-2 focus-visible:outline focus-visible:outline-2 focus-visible:outline-ring"><Bell className="h-4 w-4" />Agent notifications</summary>
<div className="space-y-2 pb-1 pt-2">
<p>Notifications include Agent message text and may appear on your lock screen.</p>
@@ -18,6 +18,15 @@ export function AgentNotifications({ onLogout }: { onLogout: () => Promise<void>
<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>
</div>
<details>
<summary className="cursor-pointer py-2 underline">Android / GrapheneOS help</summary>
<div className="space-y-2 pb-2">
<p>Vanadium uses Google Play services for Web Push. On GrapheneOS, sandboxed Google Play must be installed in the same profile as Vanadium, with network access and a battery optimization exception for Play services.</p>
<p>Allow notifications for Sybil in browser site settings and for Vanadium in Android settings. Then reload Sybil and enable notifications again. Permission alone does not mean the browser can register for push.</p>
<p>If you choose not to use Google Play, you need a browser with an independent Web Push service. Sybil cannot replace the browser's push service or detect whether Play services is installed.</p>
<p><a className="underline" href="https://grapheneos.org/usage#sandboxed-google-play" target="_blank" rel="noopener noreferrer">GrapheneOS setup guide</a>{" · "}<a className="underline" href="https://chromium.googlesource.com/chromium/src/+/main/components/gcm_driver/android/java/src/org/chromium/components/gcm_driver/GoogleCloudMessagingV2.java" target="_blank" rel="noopener noreferrer">Chromium push implementation</a></p>
</div>
</details>
</div>
</details>;
}
@@ -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;
}
}
+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>;
}
+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, getVisibleProviders, 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: getVisibleProviders(catalog), 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.
+13 -48
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),
@@ -194,37 +179,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 +416,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 {
+1 -42
View File
@@ -411,48 +411,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;
+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;
}
+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];
},
});
}
}
+19
View File
@@ -0,0 +1,19 @@
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";
if (provider === "hermes-agent") return "Hermes Agent";
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;
}
+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 };
}
+160
View File
@@ -0,0 +1,160 @@
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"],
"hermes-agent": ["hermes-agent"],
};
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 BASE_PROVIDERS: Provider[] = ["openai", "anthropic", "xai", "gemini"];
export const ALL_PROVIDERS: Provider[] = [...BASE_PROVIDERS, "hermes-agent"];
export const MODEL_PREFERENCES_STORAGE_KEY = "sybil:modelPreferencesByProvider";
export type ProviderModelPreferences = Record<Provider, string | null>;
export const EMPTY_MODEL_PREFERENCES: ProviderModelPreferences = {
openai: null,
anthropic: null,
xai: null,
gemini: null,
"hermes-agent": 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 getVisibleProviders(catalog: ModelCatalogResponse["providers"]) {
return ALL_PROVIDERS.filter((provider) => provider !== "hermes-agent" || catalog[provider] !== undefined);
}
export function loadStoredModelPreferences() {
if (typeof window === "undefined") return EMPTY_MODEL_PREFERENCES;
try {
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 === "hermes-agent"
? 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,
"hermes-agent":
typeof parsed["hermes-agent"] === "string" && parsed["hermes-agent"].trim() ? parsed["hermes-agent"].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)); }
catch { /* Browsers with unavailable storage can still use this session. */ }
}
+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 });
}
+140
View File
@@ -0,0 +1,140 @@
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(".workspace-sidebar [role=alert]");
const waitEnable = () => page.waitForFunction(() => Array.from(document.querySelectorAll("button")).some(el => el.textContent === "Enable notifications" && !el.disabled));
async function attempt(pattern) {
await refresh.click(); await waitEnable(); await enable.click();
await page.waitForFunction(pattern => {
const el = document.querySelector(".workspace-sidebar [role=alert]");
return el && new RegExp(pattern).test(el.textContent);
}, pattern.source);
assert.match(await alert.textContent(), pattern);
assert.equal(await page.evaluate(() => window.__permissionGesture), true);
assert.equal(await page.getByRole("button", { name: "Turn off notifications", exact: true }).count(), 0);
assert.doesNotMatch(await page.locator(".workspace-sidebar").textContent(), /private-worker-detail|private-provider-key|private-server-token|private-endpoint/);
}
try {
await page.goto(target.href, { waitUntil: "networkidle" });
await page.getByRole("button", { name: "Open sidebar", exact: true }).click();
await page.getByText("Agent notifications", { exact: true }).click();
await 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 signOut = page.getByRole("button", { name: "Sign out", exact: true });
await signOut.scrollIntoViewIfNeeded();
assert.ok(await signOut.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(); }
+1 -1
View File
@@ -75,7 +75,7 @@ const expectEventually = async predicate => { for (let i = 0; i < 100; i++) { if
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 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;
+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 () => {
+10
View File
@@ -64,6 +64,16 @@ function Fixture() {
[95, shorterReply], [130, "A concise streamed final answer with one extra line.\n\nThe last snapshot settles the message height."],
[165, finalReply],
] as const;
window.setTimeout(() => {
const textarea = document.querySelector<HTMLTextAreaElement>('textarea[aria-label="Message Sybil Agent"]')!;
textarea.value = Array.from({ length: 8 }, (_, index) => `Concurrent composer draft ${index + 1}`).join("\n");
textarea.dispatchEvent(new Event("input", { bubbles: true }));
}, 25);
window.setTimeout(() => {
const textarea = document.querySelector<HTMLTextAreaElement>('textarea[aria-label="Message Sybil Agent"]')!;
textarea.value = "";
textarea.dispatchEvent(new Event("input", { bubbles: true }));
}, 115);
for (const [delay, content] of streamSnapshots) window.setTimeout(() => setRoomState(current => ({
...current,
messages: current.messages.map(item => item.id === "fixture-agent-reply" ? { ...item, content } : item),
+25
View File
@@ -0,0 +1,25 @@
import assert from "node:assert/strict";
import test from "node:test";
import { browserUuid } from "../src/lib/browser-uuid.ts";
test("native UUID generation keeps the crypto receiver", () => {
const source = {
randomUUID() { assert.equal(this, source); return "native-id"; },
getRandomValues() { assert.fail("native generation should be used"); },
};
assert.equal(browserUuid(source), "native-id");
});
test("older browsers generate RFC 4122 version 4 UUIDs using secure random bytes", () => {
const source = { getRandomValues(bytes) {
assert.equal(this, source);
assert.equal(bytes.length, 16);
for (let i = 0; i < bytes.length; i++) bytes[i] = i;
return bytes;
} };
assert.equal(browserUuid(source), "00010203-0405-4607-8809-0a0b0c0d0e0f");
});
test("missing secure randomness never falls back to a guessable identifier", () => {
assert.throws(() => browserUuid({}), /Secure browser identifiers are unavailable/);
});
@@ -7,6 +7,7 @@ import {
createStreamingAssistantMetadata,
createStreamingAttemptState,
finalizeStreamingAssistant,
isInlineAgentReplyPending,
markStreamingAssistantAsAgentAside,
promoteStreamingAssistantTrace,
setStreamingAssistantSegment,
@@ -126,6 +127,15 @@ test("Agent aside stream keeps identity through loading, markdown deltas, and co
assert.equal(messages.at(-1).content, "**Inline** reply");
});
test("inline Agent pending dots stop on first text, completion, failure, and cancellation", () => {
let message = markStreamingAssistantAsAgentAside([assistantMessage()], "temp-assistant-").at(-1);
assert.equal(isInlineAgentReplyPending(message, true), true);
message = setStreamingAssistantSegment([message], "temp-assistant-", "First visible text").at(-1);
assert.equal(isInlineAgentReplyPending(message, true), false);
assert.equal(isInlineAgentReplyPending(assistantMessage(), false), false, "failed or cancelled pending state is hidden");
assert.equal(isInlineAgentReplyPending({ ...message, id: "saved-agent-reply", content: "" }, true), false);
});
test("message helpers preserve identity when no matching temporary assistant exists", () => {
const messages = [
{
+139
View File
@@ -0,0 +1,139 @@
import assert from "node:assert/strict";
import { createHash } from "node:crypto";
// Local production preview only; every API call and socket is mocked.
// PLAYWRIGHT_MODULE=/path/playwright-core/index.mjs CHROME_EXECUTABLE=/path/chrome
// WEB_TEST_URL=http://127.0.0.1:5197 node tests/lite-agent.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:" && ["localhost", "127.0.0.1", "[::1]"].includes(target.hostname));
const browser = await chromium.launch({ headless: true, executablePath: process.env.CHROME_EXECUTABLE || undefined,
...(process.env.BROWSER_NO_SANDBOX === "1" ? { args: ["--no-sandbox"] } : {}) });
const context = await browser.newContext({ viewport: { width: 1000, height: 850 }, serviceWorkers: "block" });
await context.addInitScript(() => {
localStorage.setItem("sybil_admin_token", "lite-agent-fixture-token");
// Exercise missing APIs on Chromium readers without emulating their rendering engine.
Object.defineProperty(Crypto.prototype, "randomUUID", { configurable: true, value: undefined });
delete Array.prototype.at;
delete AbortSignal.prototype.throwIfAborted;
});
const errors = [], requests = [], submissions = [], downloads = [], persistedBeforeSend = [];
const sourceId = "00000000-0000-4000-8000-000000000001";
const date = "2026-11-10T12:00:00.000Z";
const idle = { state: "idle", isThinking: false, queued: 0, backgroundWorkers: 0, tools: [], queuedMessages: [] };
const image = Buffer.from("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+a2ioAAAAASUVORK5CYII=", "base64");
const attachment = { id: "att_12345678-1234-4234-8234-123456789abc", kind: "image", filename: "fixture.png", mimeType: "image/png",
sizeBytes: image.length, sha256: createHash("sha256").update(image).digest("hex") };
const history = [{ id: "outbound:1", role: "assistant", content: "A static **Agent reply**.\n\n![remote image](https://never-fetch.invalid/image.png)",
createdAt: date, name: null, metadata: { kind: "message", status: "complete", entryId: 1, agentAttachments: [attachment] } }];
let cursor = 1, readCursor = "0", failedSend = false, live;
const page = await context.newPage();
page.on("pageerror", error => errors.push(error.message));
await context.route("**/*", async route => {
const request = route.request(), url = new URL(request.url()), path = url.pathname;
requests.push(url.href);
if (url.origin !== target.origin) return route.abort();
if (!path.startsWith("/api/")) return route.continue();
assert.equal(request.headers().authorization, "Bearer lite-agent-fixture-token");
const method = request.method();
let body;
if (path.endsWith("/auth/session")) body = { authenticated: true, mode: "token" };
else if (path.endsWith("/workspace-items")) body = { items: [] };
else if (path.endsWith("/active-runs")) body = { chats: [], searches: [] };
else if (path.endsWith("/models")) body = { providers: { openai: { models: ["fixture-model"], loadedAt: date, error: null } } };
else if (path.endsWith("/chat-tools")) body = { tools: [] };
else if (path.endsWith("/agent/messages") && method === "POST") {
const submission = request.postDataJSON();
submissions.push(submission);
persistedBeforeSend.push(await page.evaluate(() => JSON.parse(sessionStorage.getItem("sybil.agent.optimistic-outbox.v1") || "[]")));
if (!failedSend) { failedSend = true; return route.abort("internetdisconnected"); }
const row = { id: `inbound:sybil:${submission.requestId}`, role: "user", content: submission.content,
createdAt: date, name: null, metadata: { kind: "message", status: "complete", entryId: ++cursor } };
history.push(row);
live.send(JSON.stringify({ type: "messages", conversationId: "fixture-room", messages: [row], cursor: String(cursor), beforeCursor: String(cursor), hasMore: false }));
body = { id: cursor, status: "placed", messageId: row.id };
} else if (path.endsWith("/agent/messages")) {
const after = url.searchParams.get("after");
const messages = after === null ? history : history.filter(message => message.metadata.entryId > Number(after));
body = { conversationId: "fixture-room", messages, cursor: String(cursor), beforeCursor: messages.length ? String(messages[0].metadata.entryId) : null, hasMore: false };
} else if (path.endsWith("/read-state")) {
if (method === "PUT") readCursor = request.postDataJSON().cursor;
body = { sourceId, cursor: readCursor, updatedAt: null };
} else if (path.endsWith("/agent")) body = { id: "fixture-room", title: "Sybil Agent", activity: idle, protocol: "pi-room.v1", websocket: "/v1/agent/ws" };
else if (path.endsWith("/content")) {
downloads.push(url.href);
return route.fulfill({ contentType: "image/png", body: image });
} else {
assert.fail(`Unexpected API request ${method} ${path}`);
}
await route.fulfill({ json: body });
});
await context.routeWebSocket("**/api/v1/agent/ws", socket => {
live = socket;
socket.onMessage(raw => {
const event = JSON.parse(String(raw));
if (event.type === "auth") {
assert.equal(event.token, "lite-agent-fixture-token");
socket.send(JSON.stringify({ type: "ready", conversationId: "fixture-room" }));
}
});
});
const open = () => page.goto(new URL("/lite?agent=root", target).href, { waitUntil: "networkidle" });
try {
await open();
const composer = page.getByRole("textbox", { name: "Message Sybil Agent", exact: true });
const send = page.getByRole("button", { name: "Send message", exact: true });
await page.getByRole("status").filter({ hasText: /^Connected$/ }).waitFor();
assert.equal(await page.getByRole("heading", { level: 1 }).count(), 1);
assert.equal(await page.locator(".lite-agent img").count(), 0);
assert.deepEqual(downloads, [], "attachments do not download automatically");
assert.equal(requests.some(url => /character-|\/assets\/App-/.test(url)), false);
assert.equal(requests.some(url => url.includes("never-fetch.invalid")), false);
assert.equal(requests.some(url => url.includes("/presence/") || url.includes("/push/")), false, "lite does not start background push sessions");
await composer.fill("A draft preserved on reload");
await page.reload({ waitUntil: "networkidle" });
await composer.waitFor();
assert.equal(await composer.inputValue(), "A draft preserved on reload");
await composer.fill("Durable message for offline retry");
await send.click();
await page.getByRole("button", { name: "Retry message", exact: true }).waitFor();
assert.equal(await composer.inputValue(), "", "durable outbox owns a failed delivery after local save");
assert.equal(submissions.length, 1);
assert.match(submissions[0].requestId, /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/);
assert.equal(persistedBeforeSend[0][0].requestId, submissions[0].requestId, "retry identity saved before POST");
await page.reload({ waitUntil: "networkidle" });
await page.getByRole("button", { name: "Retry message", exact: true }).click();
await page.waitForFunction(() => document.querySelectorAll(".lite-agent .lite-error").length === 0);
assert.equal(submissions.length, 2);
assert.equal(submissions[1].requestId, submissions[0].requestId, "reload and retry keep one idempotent delivery identity");
assert.equal(await page.locator(`[data-agent-message-id="inbound:sybil:${submissions[0].requestId}"]`).count(), 1);
const download = page.waitForEvent("download");
await page.getByRole("button", { name: "Download fixture.png", exact: true }).click();
assert.equal((await download).suggestedFilename(), "fixture.png");
assert.equal(downloads.length, 1);
assert.ok(downloads.every(url => !url.includes("token")));
assert.equal(await page.locator(".lite-agent img").count(), 0, "explicit download does not add an animated image preview");
await page.setViewportSize({ width: 390, height: 844 });
await composer.scrollIntoViewIfNeeded();
assert.equal(await page.evaluate(() => document.documentElement.scrollWidth > window.innerWidth), false);
assert.equal(await page.getByText("Start a conversation with Sybil.", { exact: true }).count(), 0);
const ownBubble = page.locator(`[data-agent-message-id="inbound:sybil:${submissions[0].requestId}"] .message-bubble--user`);
assert.equal(await ownBubble.count(), 1, "Agent reuses the original user bubble");
assert.equal(await ownBubble.evaluate(element => getComputedStyle(element).borderBottomRightRadius), "5px");
const viewport = page.viewportSize();
const composerBox = await composer.boundingBox();
assert.ok(composerBox.y >= 0 && composerBox.y + composerBox.height <= viewport.height, "Agent composer stays in the viewport");
const motion = await page.locator(".lite-agent").evaluate(element => [...element.querySelectorAll("*")].some(node => {
const style = getComputedStyle(node);
return style.animationName !== "none" || (style.transitionDuration !== "0s" && style.transitionDuration !== "0s, 0s");
}));
assert.equal(motion, false, "Agent presentation has no animations or transitions");
if (process.env.LITE_AGENT_SCREENSHOT) await page.screenshot({ path: process.env.LITE_AGENT_SCREENSHOT, fullPage: true });
assert.deepEqual(errors, []);
console.log("PASS Lite Agent: draft reload, durable failed send/retry, UUID fallback, explicit verified download, no media/push/animations, mobile layout");
} finally {
await context.close();
await browser.close();
}
+29
View File
@@ -0,0 +1,29 @@
import assert from "node:assert/strict";
import test from "node:test";
import { marked } from "marked";
import { installLiteCompatibility } from "../src/lib/lite-compat.ts";
test("Markdown still renders on readers without native Array.at", () => {
const original = Object.getOwnPropertyDescriptor(Array.prototype, "at");
try {
delete Array.prototype.at;
installLiteCompatibility();
assert.equal([1, 2, 3].at(-1), 3);
assert.equal([1, 2, 3].at(-4), undefined);
assert.equal([1, 2, 3].at(Infinity), undefined);
assert.equal(Object.getOwnPropertyDescriptor(Array.prototype, "at").enumerable, false);
const html = marked("## A reply\n\nFirst paragraph.\n\nSecond paragraph.\n\n| Name | Value |\n| --- | --- |\n| One | Two |");
assert.match(html, /<h2>A reply<\/h2>/);
assert.match(html, /<table>/);
assert.match(html, /<td>Two<\/td>/);
} finally {
if (original) Object.defineProperty(Array.prototype, "at", original);
else delete Array.prototype.at;
}
});
test("Lite keeps the browser's existing Array.at implementation", () => {
const original = Array.prototype.at;
installLiteCompatibility();
assert.equal(Array.prototype.at, original);
});
@@ -0,0 +1,206 @@
import assert from "node:assert/strict";
// All requests are fixtures. Run against a local production preview.
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 date = "2026-11-11T12:00:00Z";
const message = (id, content) => ({ id, role: "assistant", content, createdAt: date, name: null, metadata: null });
const makeChat = (id, title) => ({ id, title, parentChatId: null, titleGenerationPending: false, createdAt: date, updatedAt: date,
starred: false, starredAt: null, initiatedProvider: "openai", initiatedModel: "reader", lastUsedProvider: "openai", lastUsedModel: "reader",
additionalSystemPrompt: null, enabledTools: [], messages: [message(`${id}-initial`, `${title} initial answer`)] });
const waitGate = () => { let release; const promise = new Promise(resolve => { release = resolve; }); return { promise, release }; };
async function waitUntil(check) {
const deadline = Date.now() + 10000;
while (!check()) {
assert.ok(Date.now() < deadline, "fixture request arrived before timeout");
await new Promise(resolve => setTimeout(resolve, 20));
}
}
async function fixture(mode) {
const context = await browser.newContext({ viewport: { width: 1100, height: 850 } });
const a = makeChat("a", "Conversation A"), b = makeChat("b", "Conversation B");
const state = { active: mode.startsWith("attach"), attachCalls: 0, delayedReads: 0, submissions: 0, searchSubmissions: 0,
collectionReads: 0, holdB: false, gate: waitGate(), errors: [] };
const search = { id: "draft-search", title: "Draft search", query: "draft query", createdAt: date, updatedAt: date,
starred: false, starredAt: null, requestId: null, latencyMs: null, error: null, answerText: "Draft search completed",
answerRequestId: null, answerCitations: null, answerError: null, results: [] };
await context.addInitScript(() => localStorage.setItem("sybil_admin_token", "reader-token"));
await context.route("**/*", async route => {
const url = new URL(route.request().url());
if (url.origin !== target.origin) return route.abort();
if (!url.pathname.startsWith("/api/")) return route.continue();
const path = url.pathname.slice(4);
let body;
if (path === "/v1/auth/session") body = { authenticated: true, mode: "token" };
else if (path === "/v1/workspace-items") {
state.collectionReads += 1;
if (mode === "draft-navigation" && state.collectionReads === 1) await state.gate.promise;
body = { items: [a, b].map(chat => ({ ...chat, type: "chat" })) };
}
else if (path === "/v1/models") body = { providers: { openai: { models: ["reader"], loadedAt: date, error: null } } };
else if (path === "/v1/active-runs") body = { chats: state.active ? ["a"] : [], searches: [] };
else if (path === "/v1/chats/a") body = { chat: a };
else if (path === "/v1/chats/b") {
if (state.holdB) { state.delayedReads += 1; await state.gate.promise; }
body = { chat: b };
}
else if (path === "/v1/chat-completions/stream") {
state.submissions += 1;
await state.gate.promise;
b.messages.push(message("late-send", "Late reply for conversation B"));
return route.fulfill({ contentType: "text/event-stream", body: 'event: done\ndata: {"text":"Late reply for conversation B"}\n\n' }).catch(() => undefined);
}
else if (path === "/v1/searches" || path === "/v1/searches/draft-search") body = { search };
else if (path === "/v1/searches/draft-search/run/stream") {
state.searchSubmissions += 1;
return route.fulfill({ contentType: "text/event-stream", body: `event: done\ndata: ${JSON.stringify({ search })}\n\n` });
}
else if (path === "/v1/chats/a/stream/attach") {
state.attachCalls += 1;
if (mode === "attach-race") {
state.active = false; a.messages.push(message("finished", "Completed before attachment"));
return route.fulfill({ status: 404, json: { message: "active chat stream not found" } });
}
if (mode === "attach-retry" && state.attachCalls === 1) {
return route.fulfill({ status: 503, json: { message: "Connection is temporarily unavailable" } });
}
await state.gate.promise;
state.active = false; a.messages.push(message("finished", "Recovered completed answer"));
return route.fulfill({ contentType: "text/event-stream", body: 'event: done\ndata: {"text":"Recovered completed answer"}\n\n' });
}
else if (/\/agent\//.test(path)) body = {};
else return route.fulfill({ status: 404, json: { message: `Unexpected fixture route ${path}` } });
return route.fulfill({ json: body }).catch(() => undefined);
});
const page = await context.newPage();
page.setDefaultTimeout(10000);
page.on("pageerror", error => state.errors.push(error.message));
await page.goto(new URL(mode === "draft-navigation" ? "/lite" : "/lite?chat=a", target).href);
await page.getByRole("heading", { name: mode === "draft-navigation" ? "New chat" : "Conversation A", exact: true }).waitFor();
return { context, page, state, a, b };
}
try {
{
const { context, page, state } = await fixture("attach-success");
await page.waitForFunction(() => document.querySelector("#lite-draft")?.disabled === true);
await waitUntil(() => state.attachCalls === 1);
assert.equal(state.attachCalls, 1);
assert.equal(await page.getByRole("button", { name: "Send message", exact: true }).isDisabled(), true);
assert.equal(await page.getByText("Recovered completed answer", { exact: true }).count(), 0);
state.gate.release();
await page.getByText("Recovered completed answer", { exact: true }).waitFor();
await page.waitForFunction(() => !document.querySelector("#lite-draft").disabled);
assert.deepEqual(state.errors, []);
await context.close();
}
{
const { context, page, state } = await fixture("attach-race");
await page.getByText("Completed before attachment", { exact: true }).waitFor();
await page.waitForFunction(() => !document.querySelector("#lite-draft").disabled);
assert.equal(await page.getByRole("alert").count(), 0, "finished attachment race recovers quietly");
assert.deepEqual(state.errors, []);
await context.close();
}
{
const { context, page, state } = await fixture("attach-retry");
await page.getByRole("alert").filter({ hasText: "Connection is temporarily unavailable" }).waitFor();
assert.equal(await page.getByRole("button", { name: "Refresh", exact: true }).isEnabled(), true, "remote work cannot disable recovery");
assert.equal(await page.getByRole("button", { name: "New chat", exact: true }).isEnabled(), true, "failed attachment cannot trap navigation");
state.gate.release();
await page.getByRole("button", { name: "Refresh", exact: true }).click();
await page.getByText("Recovered completed answer", { exact: true }).waitFor();
assert.equal(state.attachCalls, 2);
assert.deepEqual(state.errors, []);
await context.close();
}
{
const { context, page, state } = await fixture("navigation");
await page.getByText("Conversation A initial answer", { exact: true }).waitFor();
state.holdB = true;
await page.locator(".lite-history-list button").filter({ hasText: "Conversation B" }).click();
await page.waitForURL(/chat=b/);
await page.waitForFunction(() => document.querySelector(".lite-status")?.textContent === "Loading…");
await page.locator(".lite-history-list button").filter({ hasText: "Conversation A" }).click();
await page.getByText("Conversation A initial answer", { exact: true }).waitFor();
state.gate.release();
await page.waitForTimeout(150);
assert.equal(await page.getByText("Conversation B initial answer", { exact: true }).count(), 0, "late selection cannot overwrite the current transcript");
assert.equal(new URL(page.url()).searchParams.get("chat"), "a");
await page.goBack();
await page.getByText("Conversation B initial answer", { exact: true }).waitFor();
assert.equal(new URL(page.url()).searchParams.get("chat"), "b");
assert.deepEqual(state.errors, []);
await context.close();
}
{
const { context, page, state } = await fixture("logout");
state.holdB = true;
await page.locator(".lite-history-list button").filter({ hasText: "Conversation B" }).click();
await page.waitForURL(/chat=b/);
await page.getByRole("button", { name: "Sign out", exact: true }).click();
await page.getByRole("heading", { name: "Sign in to Sybil", exact: true }).waitFor();
state.gate.release();
await page.waitForTimeout(150);
assert.equal(await page.getByText("Conversation B initial answer", { exact: true }).count(), 0, "late authenticated reads cannot repaint after sign out");
assert.deepEqual(state.errors, []);
await context.close();
}
{
const { context, page, state } = await fixture("back-during-send");
await page.locator(".lite-history-list button").filter({ hasText: "Conversation B" }).click();
await page.getByText("Conversation B initial answer", { exact: true }).waitFor();
await page.getByLabel("Message", { exact: true }).fill("A question only for conversation B");
await page.getByRole("button", { name: "Send message", exact: true }).click();
await page.waitForFunction(() => document.querySelector("#lite-draft")?.disabled === true);
await waitUntil(() => state.submissions === 1);
await page.goBack();
await page.getByText("Conversation A initial answer", { exact: true }).waitFor();
state.gate.release();
await page.waitForTimeout(150);
assert.equal(await page.getByLabel("Message", { exact: true }).inputValue(), "", "aborted send must not transplant a draft into another conversation");
assert.equal(await page.getByText("Late reply for conversation B", { exact: true }).count(), 0);
assert.equal(await page.getByText("A question only for conversation B", { exact: true }).count(), 0);
assert.deepEqual(state.errors, []);
await context.close();
}
{
const { context, page, state, a } = await fixture("model-refresh");
await page.getByText("Conversation A initial answer", { exact: true }).waitFor();
await page.locator("summary").filter({ hasText: "Settings" }).click();
await page.getByLabel("Model", { exact: true }).fill("my-next-model");
await page.getByRole("button", { name: "Refresh", exact: true }).click();
await page.waitForFunction(() => !document.querySelector("#lite-draft").disabled);
assert.equal(await page.getByLabel("Model", { exact: true }).inputValue(), "my-next-model", "refresh preserves an unsent model choice");
a.lastUsedModel = "updated-on-another-device";
await page.getByRole("button", { name: "Refresh", exact: true }).click();
await page.waitForFunction(() => document.querySelector('input[list="lite-model-options"]').value === "updated-on-another-device");
await page.locator(".lite-history-list button").filter({ hasText: "Conversation B" }).click();
await page.getByText("Conversation B initial answer", { exact: true }).waitFor();
assert.equal(await page.getByLabel("Model", { exact: true }).inputValue(), "reader", "switching conversations restores its saved model");
assert.deepEqual(state.errors, []);
await context.close();
}
{
const { context, page, state } = await fixture("draft-navigation");
await waitUntil(() => state.collectionReads === 1);
assert.equal(await page.getByLabel("Message", { exact: true }).isDisabled(), true);
await page.getByRole("button", { name: "New search", exact: true }).click();
await page.getByRole("heading", { name: "New search", exact: true }).waitFor();
await waitUntil(() => state.collectionReads >= 2);
await page.getByRole("button", { name: "New search", exact: true }).click();
state.gate.release();
await page.waitForFunction(() => !document.querySelector("#lite-draft").disabled);
await page.getByLabel("Search the web", { exact: true }).fill("draft query");
await page.getByRole("button", { name: "Search", exact: true }).click();
await page.getByText("Draft search completed", { exact: true }).waitFor();
assert.equal(state.searchSubmissions, 1);
assert.deepEqual(state.errors, []);
await context.close();
}
console.log("Lite recovery browser checks passed: active-stream attachment, completion race, retry, stale navigation, back, sign-out isolation, model selection and repeated draft navigation.");
} finally { await browser.close(); }
+194
View File
@@ -0,0 +1,194 @@
import assert from "node:assert/strict";
import { mkdir } from "node:fs/promises";
// Run against npm run build && npm run preview; all API responses are local fixtures.
const { chromium } = await import(process.env.PLAYWRIGHT_MODULE || "playwright-core");
const target = new URL(process.env.WEB_TEST_URL || "http://127.0.0.1:5197/");
assert.ok(target.protocol === "http:" && ["127.0.0.1", "localhost", "[::1]"].includes(target.hostname));
const 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: 1100, height: 900 } });
const date = "2026-11-11T12:00:00.000Z";
const markdown = "A response with **formatted text**.\n\n- First item\n- Second item\n\n| Name | Value |\n| --- | --- |\n| Example | Table content |\n\n```js\nconst longLine = '" + "wide-content-".repeat(35) + "';\n```\n\n![No automatic image](https://example.test/animation.gif)";
const message = (id, role, content, metadata = null) => ({ id, role, content, createdAt: date, name: null, metadata });
const chat = { id: "chat-one", title: "Reader test conversation", parentChatId: null, titleGenerationPending: false,
createdAt: date, updatedAt: date, starred: true, starredAt: date, initiatedProvider: "openai", initiatedModel: "reader-model",
lastUsedProvider: "openai", lastUsedModel: "reader-model", additionalSystemPrompt: "Keep replies concise", enabledTools: [],
messages: [message("user-one", "user", "Show a list, a table, and a code sample."), message("assistant-one", "assistant", markdown, { generation: { provider: "openai", model: "reader-model" } })] };
const chats = new Map([[chat.id, chat]]);
const searches = new Map();
const calls = [], errors = [], requests = [], streamRequests = [];
let failFirstStream = true, failNextStream = false;
await context.addInitScript(() => {
localStorage.setItem("sybil_admin_token", "lite-fixture-token");
// Chromium readers can predate this built-in even though they support modules.
delete Array.prototype.at;
});
await context.route("**/*", async route => {
const url = new URL(route.request().url());
requests.push(url.href);
if (url.origin !== target.origin) return route.abort();
if (!url.pathname.startsWith("/api/")) return route.continue();
const path = url.pathname.slice(4), method = route.request().method();
calls.push({ path, method });
let body;
if (path === "/v1/auth/session") body = { mode: "token", authenticated: true };
else if (path === "/v1/workspace-items") {
const items = [...chats.values()].map(chat => ({ ...chat, type: "chat" })).concat([...searches.values()].map(search => ({ ...search, type: "search" })));
body = { items: url.searchParams.has("q") ? items.filter(item => item.title.includes(url.searchParams.get("q"))) : items, hasMore: false };
}
else if (path === "/v1/models") body = { providers: { openai: { models: ["reader-model", "another-model"], loadedAt: date, error: null } } };
else if (path === "/v1/active-runs") body = { chats: [], searches: [] };
else if (path === "/v1/chats" && method === "POST") {
const created = { ...chat, id: `chat-${chats.size + 1}`, title: "New conversation", messages: [], starred: false, additionalSystemPrompt: null };
chats.set(created.id, created); body = { chat: created };
}
else if (/^\/v1\/chats\/[^/]+$/.test(path)) body = { chat: chats.get(path.split("/").pop()) };
else if (path.includes("/title")) body = { chat };
else if (path === "/v1/chat-completions/stream") {
const request = route.request().postDataJSON(); streamRequests.push(request);
if (failFirstStream) { failFirstStream = false; return route.abort("failed"); }
if (failNextStream) { failNextStream = false; return route.fulfill({ status: 503, json: { message: "Model is temporarily unavailable" } }); }
assert.ok(request.clientRequestId);
const selected = chats.get(request.chatId);
const content = request.messages[request.messages.length - 1].content;
await new Promise(resolve => setTimeout(resolve, 500));
selected.messages.push(message(`user-${streamRequests.length}`, "user", content), message(`assistant-${streamRequests.length}`, "assistant", "The completed answer.", { generation: { provider: request.provider, model: request.model } }));
return route.fulfill({ contentType: "text/event-stream", body: 'event: delta\ndata: {"text":"Do not paint partial tokens"}\n\nevent: done\ndata: {"text":"The completed answer."}\n\n' });
}
else if (path === "/v1/searches" && method === "POST") {
const request = route.request().postDataJSON();
const search = { id: "search-one", title: request.title, query: request.query, createdAt: date, updatedAt: date, starred: false, starredAt: null,
requestId: null, latencyMs: null, error: null, answerText: null, answerRequestId: null, answerCitations: null, answerError: null, results: [] };
searches.set(search.id, search); body = { search };
}
else if (path === "/v1/searches/search-one/run/stream") {
const search = searches.get("search-one"); search.answerText = "A useful search answer.";
search.results = [{ id: "result", title: "An original source", url: "https://example.test/source", text: "Source description", highlights: [], rank: 1 }];
return route.fulfill({ contentType: "text/event-stream", body: `event: done\ndata: ${JSON.stringify({ search })}\n\n` });
}
else if (path === "/v1/searches/search-one") body = { search: searches.get("search-one") };
else return route.fulfill({ status: 404, json: { message: `Unexpected fixture request ${method} ${path}` } });
return route.fulfill({ json: body });
});
const page = await context.newPage();
page.on("pageerror", error => errors.push(error.message));
page.setDefaultTimeout(10000);
async function openSidebar() {
const trigger = page.getByRole("button", { name: "Open sidebar", exact: true });
if (await trigger.isVisible()) await trigger.click();
}
async function selectNavigation(name) {
await openSidebar();
await page.getByRole("button", { name, exact: true }).click();
}
async function checkComposerLayout(width) {
const scroll = page.locator(".lite-scroll");
const before = await page.locator(".lite-composer-shell").boundingBox();
assert.ok(before.y >= 0 && before.y + before.height <= page.viewportSize().height + 1, `composer visible at ${width}px`);
await scroll.evaluate(element => { element.scrollTop = element.scrollHeight; });
const after = await page.locator(".lite-composer-shell").boundingBox();
assert.equal(after.y, before.y, "scrolling the transcript does not move the composer");
await scroll.evaluate(element => { element.scrollTop = 0; });
const pageHeight = await page.evaluate(() => ({ height: document.documentElement.scrollHeight, viewport: window.innerHeight }));
assert.ok(pageHeight.height <= pageHeight.viewport + 1, `transcript content stays inside its scroller at ${width}px: ${JSON.stringify(pageHeight)}`);
}
try {
await page.goto(new URL("/lite?chat=chat-one", target).href);
await page.getByRole("heading", { name: chat.title, exact: true }).waitFor();
await page.getByText("First item", { exact: true }).waitFor();
assert.equal(await page.getByLabel("Model", { exact: true }).inputValue(), "reader-model");
assert.equal(await page.locator(".lite-main img").count(), 0);
assert.equal(await page.locator(".md-content table").count(), 1);
const visuals = await page.evaluate(() => ({
animated: [...document.querySelectorAll("*")].filter(el => getComputedStyle(el).animationName !== "none").length,
overflow: document.documentElement.scrollWidth > window.innerWidth,
background: getComputedStyle(document.documentElement).backgroundImage,
}));
assert.equal(visuals.animated, 0); assert.equal(visuals.overflow, false); assert.equal(visuals.background, "none");
for (const text of ["What’s on your mind?", "Made for slower screens.", "A little space to think", "Your persistent assistant", "Find something useful", "What would you like to find?", "Clear text.", "Fewer distractions.", "Simple pages.", "Replies appear when complete."]) {
assert.equal(await page.getByText(text, { exact: false }).count(), 0, `no added flavor text: ${text}`);
}
const bubble = await page.locator(".lite-message-user .message-bubble--user").first().evaluate(element => {
const style = getComputedStyle(element), box = element.getBoundingClientRect(), row = element.closest(".lite-message").getBoundingClientRect();
return { right: box.right, rowRight: row.right, width: box.width, rowWidth: row.width, bottomRightRadius: style.borderBottomRightRadius, background: style.backgroundImage };
});
assert.ok(Math.abs(bubble.right - bubble.rowRight) <= 1 && bubble.width < bubble.rowWidth, "user bubbles retain original right alignment and width limit");
assert.equal(bubble.bottomRightRadius, "5px");
assert.equal(bubble.background, "none");
assert.equal(await page.locator('[data-assistant-footer="assistant-one"]').getByRole("button", { name: "Copy message", exact: true }).count(), 1);
await checkComposerLayout(1100);
if (process.env.LITE_ARTIFACT_DIR) {
await mkdir(process.env.LITE_ARTIFACT_DIR, { recursive: true });
await page.screenshot({ path: `${process.env.LITE_ARTIFACT_DIR}/lite-desktop.png`, fullPage: true });
}
// Selecting the current row must retain its loaded transcript.
await page.locator(".lite-history-list button").filter({ hasText: chat.title }).click();
await page.getByText("First item", { exact: true }).waitFor();
await page.getByLabel("Message", { exact: true }).fill("A follow-up question");
await page.getByRole("button", { name: "Send message", exact: true }).click();
await page.getByText("The completed answer.", { exact: true }).waitFor();
assert.equal(await page.getByLabel("Message", { exact: true }).inputValue(), "");
assert.equal(await page.getByText("Do not paint partial tokens", { exact: true }).count(), 0);
assert.equal(streamRequests.length, 2);
assert.equal(streamRequests[0].clientRequestId, streamRequests[1].clientRequestId, "transport retry reuses submission ID");
assert.deepEqual(streamRequests[0].messages, streamRequests[1].messages);
failNextStream = true;
await page.getByLabel("Message", { exact: true }).fill("Preserve this draft");
await page.getByRole("button", { name: "Send message", exact: true }).click();
await page.getByRole("alert").filter({ hasText: "Model is temporarily unavailable" }).waitFor();
assert.equal(await page.getByLabel("Message", { exact: true }).inputValue(), "Preserve this draft");
const failedRequest = streamRequests[streamRequests.length - 1];
await page.getByRole("button", { name: "Send message", exact: true }).click();
await page.waitForFunction(() => document.querySelector("#lite-draft").value === "");
assert.equal(streamRequests[streamRequests.length - 1].clientRequestId, failedRequest.clientRequestId);
for (const width of [320, 390, 600]) {
await page.setViewportSize({ width, height: 844 });
assert.equal(await page.evaluate(() => document.documentElement.scrollWidth > window.innerWidth), false, `no overflow at ${width}px`);
await checkComposerLayout(width);
await openSidebar();
await page.getByLabel("Search history", { exact: true }).fill("Reader");
const row = page.locator(".lite-history-list button").filter({ hasText: chat.title });
await row.waitFor();
await row.click();
assert.equal(await page.getByRole("button", { name: "Open sidebar", exact: true }).getAttribute("aria-expanded"), "false");
assert.equal(await page.locator(".lite-sidebar").evaluate(element => getComputedStyle(element).transitionDuration), "0s");
if (process.env.LITE_ARTIFACT_DIR) await page.screenshot({ path: `${process.env.LITE_ARTIFACT_DIR}/lite-${width}.png`, fullPage: true });
}
await selectNavigation("New chat");
await page.getByRole("heading", { name: "New chat", exact: true }).waitFor();
await page.waitForFunction(() => !document.querySelector("#lite-draft").disabled);
assert.equal(await page.locator(".lite-scroll").textContent(), "", "new chats have an empty transcript without welcome copy");
await page.getByLabel("Message", { exact: true }).fill("An unsent draft");
await selectNavigation("New chat");
assert.equal(await page.getByLabel("Message", { exact: true }).inputValue(), "");
await page.getByLabel("Message", { exact: true }).fill("Start a new conversation");
await page.getByRole("button", { name: "Send message", exact: true }).click();
await page.getByText("The completed answer.", { exact: true }).waitFor();
assert.ok(new URL(page.url()).searchParams.get("chat"));
await selectNavigation("New search");
await page.getByLabel("Search the web", { exact: true }).fill("e-ink reading");
await page.getByRole("button", { name: "Search", exact: true }).click();
await page.getByText("A useful search answer.", { exact: true }).waitFor();
assert.equal(await page.getByRole("link", { name: "An original source" }).getAttribute("href"), "https://example.test/source");
assert.equal(new URL(page.url()).searchParams.get("search"), "search-one");
assert.deepEqual(errors, []);
assert.equal(requests.some(url => /character-|\/assets\/App-/.test(url)), false);
assert.equal(await page.evaluate(() => Array.from(document.styleSheets).filter(sheet => !sheet.href || new URL(sheet.href).origin === location.origin)
.some(sheet => Array.from(sheet.cssRules).some(rule => rule.cssText.includes(".tool-call-stack-shell")))), false, "full animation styles are not loaded");
assert.equal(calls.some(call => /\/agent\//.test(call.path)), false, "chat/search does not open Agent or presence polling");
console.log("Lite workspace browser checks passed: original bubbles/footer, no flavor text, fixed composer, chat/retry, history/search, mobile sidebar and isolated assets.");
} catch (error) {
console.error("Workspace fixture state", { ...(await page.evaluate(() => ({
url: location.href, draft: document.querySelector("#lite-draft")?.value,
disabled: document.querySelector("#lite-draft")?.disabled,
title: document.querySelector("main h1")?.textContent,
statuses: [...document.querySelectorAll('[role="status"]')].map(element => element.textContent),
alerts: [...document.querySelectorAll('[role="alert"]')].map(element => element.textContent),
}))), pageErrors: errors, streams: streamRequests.length, recentCalls: calls.slice(-12) });
throw error;
} finally { await browser.close(); }
+15
View File
@@ -0,0 +1,15 @@
import assert from "node:assert/strict";
import test from "node:test";
import { getMessageGenerationLabel } from "../src/lib/message-generation.ts";
test("reply labels use the recorded provider and model", () => {
for (const [provider, label] of [["openai", "OpenAI"], ["anthropic", "Anthropic"], ["xai", "xAI"], ["gemini", "Gemini"], ["hermes-agent", "Hermes Agent"]]) {
assert.equal(getMessageGenerationLabel({ role: "assistant", metadata: { generation: { provider, model: "original-model" } } }), `${label} · original-model`);
}
});
test("missing or malformed attribution stays unknown and Agent asides keep their identity", () => {
for (const metadata of [null, [], {}, { provider: "openai", model: "unrelated" }, { generation: { provider: "unknown", model: "model" } }, { generation: { provider: "openai", model: "" } }, { generation: { provider: "openai", model: [] } }, { generation: { provider: "openai", model: "model" }, agentAside: true }]) {
assert.equal(getMessageGenerationLabel({ role: "assistant", metadata }), null);
}
});
+289
View File
@@ -0,0 +1,289 @@
import assert from "node:assert/strict";
import { mkdir } from "node:fs/promises";
// Run against a local production preview after npm run build. No live API calls.
// PLAYWRIGHT_MODULE=/path/playwright-core/index.mjs CHROME_EXECUTABLE=/path/chrome
// WEB_TEST_URL=http://127.0.0.1:5197 node tests/mobile-workspace.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 baseline = process.env.MOBILE_BASELINE === "1";
const artifactDir = process.env.MOBILE_ARTIFACT_DIR;
if (artifactDir) await mkdir(artifactDir, { recursive: true });
const browser = await chromium.launch({ executablePath: process.env.CHROME_EXECUTABLE || undefined, headless: true,
...(process.env.BROWSER_NO_SANDBOX === "1" ? { args: ["--no-sandbox"] } : {}) });
const context = await browser.newContext({ viewport: { width: 390, height: 844 }, isMobile: true, hasTouch: true,
permissions: ["clipboard-read", "clipboard-write"] });
const sourceId = "4599d348-e053-4937-987d-1392746fb2ce";
const date = "2026-11-02T12:00:00.000Z";
const markdown = [
"Mobile answer with selectable text. " + "This regular chat response should use the available width. ".repeat(7),
"| Name | Description with a very wide column | Another long heading | Final column |\n| --- | --- | --- | --- |\n| Alpha | Wide table content | More content | End |",
"> A quotation with selectable text and a nested horizontal code block:\n>\n> ```text\n> " + "quoted-unbroken-code-".repeat(22) + "\n> ```",
"```js\nconst longLine = '" + "horizontal-code-".repeat(28) + "';\n```",
"A final paragraph with a [native link menu](https://example.test/document).",
].join("\n\n");
const chat = { id: "mobile-chat", title: "Mobile QA conversation with a long title", parentChatId: null, titleGenerationPending: false,
createdAt: date, updatedAt: date, starred: false, starredAt: null, initiatedProvider: "openai", initiatedModel: "mobile-model-one",
lastUsedProvider: "openai", lastUsedModel: "mobile-model-one", additionalSystemPrompt: null, enabledTools: [],
messages: [{ id: "mobile-assistant", role: "assistant", content: markdown, createdAt: date, name: null, metadata: { generation: { provider: "openai", model: "mobile-model-one" } } }] };
const idle = { state: "idle", isThinking: false, queued: 0, backgroundWorkers: 0, tools: [], queuedMessages: [] };
const errors = [], calls = [], forkRequests = [];
let forkedChat;
let readCursor = "0";
await context.addInitScript(() => localStorage.setItem("sybil_admin_token", "mobile-fixture-token"));
await context.route("**/*", async route => {
const url = new URL(route.request().url());
if (url.origin !== target.origin) { await route.abort(); return; }
if (!url.pathname.startsWith("/api/")) { await route.continue(); return; }
const path = url.pathname, method = route.request().method();
calls.push({ path, method });
let value;
if (path.endsWith("/auth/session")) value = { mode: "token", authenticated: true };
else if (path.endsWith("/workspace-items")) value = { items: [chat, ...(forkedChat ? [forkedChat] : [])].map(chat => ({ ...chat, type: "chat" })) };
else if (path.endsWith("/models")) value = { providers: { openai: { models: ["mobile-model-one", "mobile-model-two"], loadedAt: date, error: null } } };
else if (path.endsWith("/chat-tools") || path.endsWith("/agent/tools")) value = { tools: [] };
else if (path.endsWith("/active-runs")) value = { chats: [], searches: [] };
else if (path.endsWith("/chats/mobile-chat")) {
if (method === "PATCH") Object.assign(chat, route.request().postDataJSON());
value = { chat };
} else if (path.endsWith("/chats/mobile-chat/fork")) {
forkRequests.push(route.request().postDataJSON());
await new Promise(resolve => setTimeout(resolve, 300));
forkedChat = { ...chat, id: "mobile-fork", title: "Forked conversation", parentChatId: chat.id };
value = { chat: forkedChat };
} else if (path.endsWith("/chats/mobile-fork")) value = { chat: forkedChat };
else if (path.endsWith("/agent/messages")) value = { conversationId: "1", messages: [{ ...chat.messages[0], id: "outbound:1", metadata: { entryId: 1 } }], cursor: "1", beforeCursor: null, hasMore: false };
else if (path.endsWith("/agent")) value = { id: "1", title: "Sybil Agent", activity: idle, protocol: "pi-room.v1", websocket: "/v1/agent/ws" };
else if (path.endsWith("/read-state")) {
if (method === "PUT") readCursor = route.request().postDataJSON().cursor;
value = { sourceId, cursor: readCursor, updatedAt: null };
}
else if (path.endsWith("/push/config")) value = { version: 1, enabled: false, webPushAvailable: false, apnsAvailable: false, sourceId, quarantined: false, policy: { presenceHeartbeatMs: 15000, presenceLeaseMs: 60000 } };
else if (path.includes("/presence/")) value = { expiresAt: date };
else value = {};
await route.fulfill({ json: value });
});
await context.routeWebSocket("**/api/v1/agent/ws", socket => socket.onMessage(raw => {
if (JSON.parse(String(raw)).type === "auth") socket.send(JSON.stringify({ type: "ready", conversationId: "1" }));
}));
const page = await context.newPage();
page.on("pageerror", error => errors.push(error.message));
const cdp = await context.newCDPSession(page);
async function openSidebar() {
const sidebar = page.locator(".workspace-sidebar");
if (await sidebar.evaluate(el => el.getBoundingClientRect().right <= 0)) {
await page.getByRole("button", { name: "Open sidebar", exact: true }).click();
}
}
async function selectChat() {
await openSidebar();
await page.getByRole("button", { name: new RegExp(chat.title) }).click();
await page.locator("main h1").filter({ hasText: chat.title }).waitFor();
await page.locator("main .md-content").waitFor();
await page.waitForFunction(() => document.querySelector(".workspace-sidebar").getBoundingClientRect().right <= 1);
}
async function drag(x, y, dx, dy = 0) {
await cdp.send("Input.dispatchTouchEvent", { type: "touchStart", touchPoints: [{ x, y }] });
for (let step = 1; step <= 8; step++) {
await cdp.send("Input.dispatchTouchEvent", { type: "touchMove", touchPoints: [{ x: x + dx * step / 8, y: y + dy * step / 8 }] });
await page.waitForTimeout(25);
}
await cdp.send("Input.dispatchTouchEvent", { type: "touchEnd", touchPoints: [] });
await page.waitForTimeout(200);
}
async function scrollHorizontally(locator) {
await locator.scrollIntoViewIfNeeded();
await locator.evaluate(el => { el.scrollLeft = 0; });
const box = await locator.boundingBox();
const x = Math.min(box.x + box.width - 30, 350), y = box.y + Math.min(box.height / 2, 30);
await drag(x, y, -130);
}
async function contextMenuCanceled(locator) {
return locator.evaluate(el => !el.dispatchEvent(new MouseEvent("contextmenu", { bubbles: true, cancelable: true, clientX: 100, clientY: 200 })));
}
async function checkFooterAlignment() {
const footer = page.locator('[data-assistant-footer="mobile-assistant"]');
await footer.scrollIntoViewIfNeeded();
// Leave space for the fixed composer when inspecting the final reply actions.
await footer.evaluate(el => el.scrollIntoView({ block: "center" }));
const layout = await footer.evaluate(el => ({
paragraphLeft: el.parentElement.querySelector(".md-content > p").getBoundingClientRect().left,
dateLeft: el.querySelector("time").getBoundingClientRect().left,
actionLeft: el.querySelector("button svg").getBoundingClientRect().left,
dateColor: getComputedStyle(el.querySelector("time")).color,
paragraphColor: getComputedStyle(el.parentElement.querySelector(".md-content")).color,
}));
assert.ok(Math.abs(layout.dateLeft - layout.paragraphLeft) < 1, "timestamp aligns with reply text");
assert.ok(Math.abs(layout.actionLeft - layout.paragraphLeft) < 1, "first action icon aligns with reply text");
assert.notEqual(layout.dateColor, layout.paragraphColor, "timestamp uses secondary color");
assert.equal(await footer.locator("time").getAttribute("datetime"), date);
assert.match(await footer.locator("time").textContent(), /2026/);
assert.equal(await footer.locator("[data-message-generation]").textContent(), "OpenAI · mobile-model-one");
}
try {
await page.goto(target.href, { waitUntil: "networkidle" });
await selectChat();
const metrics = await page.locator("main .md-content").evaluate(el => ({
width: el.getBoundingClientRect().width, parentWidth: el.parentElement.parentElement.getBoundingClientRect().width,
touchAction: getComputedStyle(document.querySelector("main")).touchAction,
modelVisible: Array.from(document.querySelectorAll("main header p")).some(el => el.textContent.includes("mobile-model-one") && el.getBoundingClientRect().height > 0),
}));
if (artifactDir) await page.screenshot({ path: `${artifactDir}/regular-390.png` });
const canceled = await contextMenuCanceled(page.locator("main .md-content p").first());
if (baseline) { await page.getByRole("button", { name: "Fork", exact: true }).waitFor(); await page.keyboard.press("Escape"); }
const table = page.locator("main .md-table-scroll");
await scrollHorizontally(table);
const stayed = await page.locator("main h1").textContent() === chat.title;
const scrolled = stayed ? await table.evaluate(el => el.scrollLeft) : 0;
console.log(JSON.stringify({ baseline, metrics, contextMenuCanceled: canceled, tableScrollLeft: scrolled, stayedInChat: stayed }));
if (baseline) {
await openSidebar(); await page.locator('[data-testid="agent-sidebar-item"]').click();
await page.locator(".agent-room .md-content").waitFor();
await page.waitForFunction(() => document.querySelector(".workspace-sidebar").getBoundingClientRect().right <= 1);
console.log("Agent width", await page.locator(".agent-room .md-content").evaluate(el => el.getBoundingClientRect().width));
if (artifactDir) await page.screenshot({ path: `${artifactDir}/agent-390.png` });
} else {
assert.equal(metrics.touchAction, "auto");
assert.equal(metrics.modelVisible, true);
assert.ok(Math.abs(metrics.width - metrics.parentWidth) < 2, "compact answer uses full transcript width");
assert.equal(canceled, false, "native menu is not canceled");
assert.ok(stayed && scrolled > 50, "trusted horizontal pan scrolls the table without navigation");
// Even at either end of nested scrollers, pans belong to the content.
for (const locator of [table, page.locator("main blockquote pre"), page.locator("main .md-content > pre")]) {
await scrollHorizontally(locator);
assert.equal(await page.locator("main h1").textContent(), chat.title);
assert.ok(await locator.evaluate(el => el.scrollLeft > 50));
await locator.evaluate(el => { el.scrollLeft = el.scrollWidth; });
await locator.scrollIntoViewIfNeeded();
let box = await locator.boundingBox();
await drag(box.x + box.width - 30, box.y + 20, -130);
assert.equal(await page.locator("main h1").textContent(), chat.title);
await locator.evaluate(el => { el.scrollLeft = 0; });
box = await locator.boundingBox();
await drag(box.x + 30, box.y + 20, 130);
assert.ok(await page.locator(".workspace-sidebar").evaluate(el => el.getBoundingClientRect().right <= 0));
}
const paragraph = page.locator("main .md-content p").first();
await paragraph.scrollIntoViewIfNeeded();
await paragraph.evaluate(el => {
const range = document.createRange(); range.selectNodeContents(el);
window.getSelection().removeAllRanges(); window.getSelection().addRange(range);
});
await page.keyboard.press("Control+c");
assert.match(await page.evaluate(() => navigator.clipboard.readText()), /Mobile answer/);
assert.equal(await contextMenuCanceled(paragraph), false);
assert.equal(await contextMenuCanceled(page.locator("main .md-content a")), false);
await page.keyboard.press("Escape");
// Selection, multi-touch, long-press and touchcancel must not become navigation.
for (const scenario of ["selection", "multi", "hold", "cancel"]) {
await page.locator("main header").evaluate((el, scenario) => {
if (scenario !== "selection") window.getSelection().removeAllRanges();
const touch = (x, id = 1) => new Touch({ identifier: id, target: el, clientX: x, clientY: 20 });
const send = (type, touches, changed = touches, time = 0) => {
const event = new TouchEvent(type, { bubbles: true, cancelable: true, touches, changedTouches: changed });
Object.defineProperty(event, "timeStamp", { value: 1000 + time }); el.dispatchEvent(event);
};
send("touchstart", [touch(120)]);
if (scenario === "multi") send("touchstart", [touch(120), touch(160, 2)]);
if (scenario === "cancel") send("touchcancel", [], [touch(120)]);
send("touchmove", [touch(280)], undefined, scenario === "hold" ? 500 : 100);
send("touchend", [], [touch(280)], 600);
}, scenario);
assert.ok(await page.locator(".workspace-sidebar").evaluate(el => el.getBoundingClientRect().right <= 0), scenario);
}
await page.evaluate(() => window.getSelection().removeAllRanges());
const composer = page.locator("main textarea");
assert.equal(await contextMenuCanceled(composer), false);
await page.evaluate(() => navigator.clipboard.writeText("native pasted draft"));
await composer.focus(); await page.keyboard.press("Control+v");
assert.equal(await composer.inputValue(), "native pasted draft");
assert.equal(calls.filter(call => call.method === "POST").length, 0);
// The footer uses the saved date and exposes Copy/Fork without a custom menu.
await checkFooterAlignment();
const copy = page.getByRole("button", { name: "Copy message", exact: true });
await copy.click();
await page.getByText("Message copied.", { exact: true }).waitFor({ state: "attached" });
assert.equal(await page.evaluate(() => navigator.clipboard.readText()), markdown);
await page.evaluate(() => Object.defineProperty(navigator.clipboard, "writeText", { configurable: true, value: async () => { throw new DOMException("Denied", "NotAllowedError"); } }));
await copy.click();
await page.getByText(/Could not copy\. Select the message text/).waitFor();
await page.evaluate(() => delete navigator.clipboard.writeText);
await copy.focus(); await page.keyboard.press("Enter");
await page.getByText("Message copied.", { exact: true }).waitFor({ state: "attached" });
const fork = page.getByRole("button", { name: "Fork chat from this message", exact: true });
await fork.click();
assert.equal(await fork.isDisabled(), true);
await page.getByRole("heading", { name: "Forked conversation", exact: true }).waitFor();
assert.deepEqual(forkRequests, [{ messageId: "mobile-assistant" }]);
await selectChat();
await page.getByRole("button", { name: "Open chat settings" }).click();
await page.getByRole("dialog").waitFor();
await page.getByPlaceholder("Select or type model", { exact: true }).fill("mobile-model-two");
await page.getByPlaceholder("Select or type model", { exact: true }).press("Enter");
await page.getByRole("button", { name: "Save", exact: true }).first().click();
await page.getByRole("dialog").waitFor({ state: "detached" });
assert.match(await page.locator("main header p").textContent(), /mobile-model-two/);
for (const width of [320, 390, 430, 767]) {
await page.setViewportSize({ width, height: 844 });
assert.equal(await page.evaluate(() => document.documentElement.scrollWidth > innerWidth), false, `${width}px page overflow`);
assert.ok(await page.locator("main header p").isVisible());
await checkFooterAlignment();
if (artifactDir) await page.screenshot({ path: `${artifactDir}/regular-${width}.png` });
}
await page.setViewportSize({ width: 390, height: 844 });
// Swipes still work in workspace chrome, away from text and scrollable content.
await drag(90, 8, 150);
await page.waitForFunction(() => document.querySelector(".workspace-sidebar").getBoundingClientRect().left >= 0);
await page.locator('[data-testid="agent-sidebar-item"]').click();
await page.locator(".agent-room .md-content").waitFor();
await page.waitForFunction(() => document.querySelector(".workspace-sidebar").getBoundingClientRect().right <= 1);
console.log("Agent width", await page.locator(".agent-room .md-content").evaluate(el => el.getBoundingClientRect().width));
if (artifactDir) await page.screenshot({ path: `${artifactDir}/agent-390.png` });
await scrollHorizontally(page.locator(".agent-room .md-table-scroll"));
assert.ok(await page.locator(".agent-room .md-table-scroll").evaluate(el => el.scrollLeft > 50));
assert.equal(await contextMenuCanceled(page.locator(".agent-room .md-content p").first()), false);
assert.equal(await page.evaluate(() => document.documentElement.scrollWidth > innerWidth), false);
// Keyboard-height approximation: both composers remain inside a shorter viewport.
await page.setViewportSize({ width: 390, height: 450 });
assert.ok(await page.locator(".agent-room textarea").evaluate(el => el.getBoundingClientRect().bottom <= innerHeight));
await selectChat();
assert.ok(await composer.evaluate(el => el.getBoundingClientRect().bottom <= innerHeight));
await page.setViewportSize({ width: 1280, height: 900 });
assert.equal(await page.evaluate(() => document.documentElement.scrollWidth > innerWidth), false);
assert.ok(await page.locator("main header button").filter({ hasText: "mobile-model-one" }).isVisible());
assert.equal(await contextMenuCanceled(paragraph), false);
await checkFooterAlignment();
await copy.click();
assert.equal(await page.evaluate(() => navigator.clipboard.readText()), markdown);
if (artifactDir) await page.screenshot({ path: `${artifactDir}/regular-1280.png` });
const manifest = await page.evaluate(async () => (await fetch("/manifest.webmanifest")).json());
assert.equal(manifest.display, "standalone"); assert.ok(!manifest.display_override?.includes("fullscreen"));
const viewport = await page.locator('meta[name="viewport"]').getAttribute("content");
assert.match(viewport, /user-scalable=no/);
assert.match(viewport, /maximum-scale=1\.0(?:,|$)/);
// A mixed-model history keeps each attribution after reload, including unknown old replies.
const longModel = "claude-" + "long-model-identifier-".repeat(8);
chat.messages.push(
{ ...chat.messages[0], id: "second-assistant", content: "A reply from a different provider.", metadata: { generation: { provider: "anthropic", model: longModel } } },
{ ...chat.messages[0], id: "legacy-assistant", content: "A reply with no generation record.", metadata: null },
);
await page.reload({ waitUntil: "networkidle" });
await page.getByRole("heading", { name: chat.title, exact: true }).waitFor();
assert.deepEqual(await page.locator("main [data-message-generation]").allTextContents(), ["OpenAI · mobile-model-one", `Anthropic · ${longModel}`, "Model not recorded"]);
for (const width of [320, 390, 1280]) {
await page.setViewportSize({ width, height: 844 });
if (width < 768) await page.waitForFunction(() => document.querySelector(".workspace-sidebar").getBoundingClientRect().right <= 1);
await page.locator('[data-assistant-footer="second-assistant"]').evaluate(el => el.scrollIntoView({ block: "center" }));
assert.ok(await page.locator('[data-assistant-footer="second-assistant"]').evaluate(el => el.scrollWidth <= el.clientWidth), "long model identifier wraps within the footer");
assert.equal(await page.evaluate(() => document.documentElement.scrollWidth > innerWidth), false, `${width}px model-label overflow`);
if (artifactDir) await page.screenshot({ path: `${artifactDir}/mixed-models-${width}.png` });
}
await page.setViewportSize({ width: 390, height: 844 });
await page.waitForFunction(() => document.querySelector(".workspace-sidebar").getBoundingClientRect().right <= 1);
await drag(300, 8, -160);
await page.getByRole("heading", { name: "New chat", exact: true }).waitFor();
assert.deepEqual(errors, []);
console.log("PASS mobile horizontal scrolling/edges, native menu/copy/paste, selection/multitouch/cancellation, compact widths/models, aligned timestamp and Copy/Fork footer, Agent layout, shorter viewport, desktop and PWA settings");
}
} finally { await context.close(); await browser.close(); }
+18
View File
@@ -0,0 +1,18 @@
import assert from 'node:assert/strict';
import { readFile } from 'node:fs/promises';
import test from 'node:test';
test('PWA icons include a compact adaptive icon', async () => {
const manifest = JSON.parse(await readFile(new URL('../public/manifest.webmanifest', import.meta.url), 'utf8'));
for (const size of ['192x192', '512x512']) {
assert.ok(manifest.icons.some(icon => icon.sizes === size && (icon.purpose ?? 'any').split(/\s+/).includes('any')));
}
const maskable = manifest.icons.filter(icon => (icon.purpose ?? 'any').split(/\s+/).includes('maskable'));
assert.equal(maskable.length, 1);
assert.equal(maskable[0].sizes, '512x512');
assert.equal(maskable[0].type, 'image/png');
const image = await readFile(new URL(`../public${maskable[0].src}`, import.meta.url));
assert.ok(image.length <= 32 * 1024);
assert.equal(image.readUInt32BE(16), 512);
assert.equal(image.readUInt32BE(20), 512);
});
+169
View File
@@ -0,0 +1,169 @@
import assert from "node:assert/strict";
import { spawn } from "node:child_process";
import { existsSync } from "node:fs";
import { homedir, tmpdir } from "node:os";
import { mkdtemp, rm } from "node:fs/promises";
// Browser regression test against the real app with a deterministic local API fixture.
// npm run build && npm run preview -- --host 127.0.0.1 --port 5198
// WEB_TEST_URL=http://127.0.0.1:5198/ node tests/search-focus.browser.mjs
const targetUrl = process.env.WEB_TEST_URL || "http://127.0.0.1:5198/";
assert.ok(new URL(targetUrl).hostname === "127.0.0.1" || new URL(targetUrl).hostname === "localhost");
const browserBinary = process.env.CHROME_EXECUTABLE || ["/usr/bin/chromium", "/usr/bin/google-chrome", "/usr/bin/chromium-browser",
`${homedir()}/.cache/ms-playwright/chromium-1243/chrome-linux64/chrome`].find(existsSync) || "chromium";
const profile = await mkdtemp(`${tmpdir()}/sybil-search-focus-browser-`);
const browser = spawn(browserBinary, ["--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 = "";
browser.stderr.setEncoding("utf8").on("data", chunk => { diagnostics += chunk; });
let socket;
let commandId = 0;
const pending = new Map();
const calls = [];
const date = "2026-11-04T12:00:00.000Z";
let searchNumber = 0;
let streamWasRequested = false;
let latestSearch = null;
const delay = ms => new Promise(resolve => setTimeout(resolve, ms));
async function waitForDebugPort() {
const deadline = Date.now() + 12000;
while (Date.now() < deadline) {
const match = diagnostics.match(/DevTools listening on ws:\/\/127\.0\.0\.1:(\d+)\//);
if (match) return Number(match[1]);
await delay(50);
}
throw new Error(`Chrome did not start: ${diagnostics.slice(-1000)}`);
}
async function connect() {
const port = await waitForDebugPort();
const response = await fetch(`http://127.0.0.1:${port}/json/new?about:blank`, { method: "PUT" });
const tab = await response.json();
socket = new WebSocket(tab.webSocketDebuggerUrl);
await new Promise((resolve, reject) => {
socket.addEventListener("open", resolve, { once: true });
socket.addEventListener("error", reject, { once: true });
});
socket.addEventListener("message", event => {
const message = JSON.parse(event.data);
if (message.method === "Fetch.requestPaused") void handlePausedRequest(message.params);
if (message.id) {
const request = pending.get(message.id);
if (request) {
pending.delete(message.id);
message.error ? request.reject(new Error(message.error.message)) : request.resolve(message.result);
}
}
});
await call("Page.enable");
await call("Runtime.enable");
await call("Fetch.enable", { patterns: [{ urlPattern: "*" }] });
await call("Page.addScriptToEvaluateOnNewDocument", { source: 'localStorage.setItem("sybil_admin_token", "search-focus-fixture-token");' });
await call("Page.navigate", { url: targetUrl });
}
function call(method, params = {}) {
return new Promise((resolve, reject) => {
const id = ++commandId;
pending.set(id, { resolve, reject });
socket.send(JSON.stringify({ id, method, params }));
});
}
async function evaluate(expression) {
const response = await call("Runtime.evaluate", { expression, awaitPromise: true, returnByValue: true });
assert.equal(response.exceptionDetails, undefined, response.exceptionDetails?.text);
return response.result?.value;
}
async function waitFor(expression, message) {
const deadline = Date.now() + 12000;
while (Date.now() < deadline) {
if (await evaluate(expression)) return;
await delay(40);
}
const body = await evaluate('document.body?.innerText.slice(0, 1200) || "no body"').catch(() => "evaluation failed");
throw new Error(`Timed out waiting for ${message}; body=${JSON.stringify(body)}; calls=${JSON.stringify(calls)}; chrome=${diagnostics.slice(-500)}`);
}
async function fulfill(id, value, contentType = "application/json") {
const body = Buffer.from(typeof value === "string" ? value : JSON.stringify(value)).toString("base64");
await call("Fetch.fulfillRequest", { requestId: id, responseCode: 200,
responseHeaders: [{ name: "Content-Type", value: contentType }], body });
}
async function handlePausedRequest(request) {
try {
const url = new URL(request.request.url);
if (url.origin !== new URL(targetUrl).origin || !url.pathname.startsWith("/api/")) {
await call("Fetch.continueRequest", { requestId: request.requestId });
return;
}
const path = url.pathname;
const method = request.request.method;
calls.push({ path, method });
if (path.endsWith("/auth/session")) return fulfill(request.requestId, { mode: "token", authenticated: true });
if (path.endsWith("/workspace-items")) return fulfill(request.requestId, { items: latestSearch ? [{ type: "search", ...latestSearch }] : [] });
if (path.endsWith("/models")) return fulfill(request.requestId, { providers: {} });
if (path.endsWith("/chat-tools") || path.endsWith("/agent/tools")) return fulfill(request.requestId, { tools: [] });
if (path.endsWith("/active-runs")) return fulfill(request.requestId, { chats: [], searches: [] });
if (path.endsWith("/agent")) return fulfill(request.requestId, { id: "fixture", title: "Sybil Agent", activity: { state: "idle", isThinking: false, queued: 0, backgroundWorkers: 0, tools: [], queuedMessages: [] }, protocol: "pi-room.v1", websocket: "/v1/agent/ws" });
if (path.endsWith("/agent/messages")) return fulfill(request.requestId, { conversationId: "fixture", messages: [], cursor: "0", beforeCursor: null, hasMore: false });
if (path.endsWith("/push/config")) return fulfill(request.requestId, { version: 1, enabled: false, webPushAvailable: false, apnsAvailable: false, sourceId: "fixture", quarantined: false, policy: { presenceHeartbeatMs: 15000, presenceLeaseMs: 60000 } });
if (path.includes("/presence/")) return fulfill(request.requestId, { expiresAt: date });
if (path.endsWith("/searches") && method === "POST") {
const number = ++searchNumber;
const body = JSON.parse(request.request.postData || "{}");
const search = { id: `search-${number}`, title: body.query, query: body.query, createdAt: date, updatedAt: date, starred: false, starredAt: null, requestId: null, latencyMs: null, error: null, answerText: null, answerRequestId: null, answerCitations: null, answerError: null, results: [] };
latestSearch = search;
return fulfill(request.requestId, { search, reused: false, cacheHit: false });
}
if (path.includes("/searches/") && method === "GET") return fulfill(request.requestId, { search: latestSearch });
if (path.includes("/searches/") && path.endsWith("/run/stream")) {
streamWasRequested = true;
const body = JSON.parse(request.request.postData || "{}");
const result = { id: `result-${searchNumber}`, createdAt: date, rank: 1, title: `Fixture result for ${body.query}`, url: "https://fixture.test/result", publishedDate: null, author: null, text: "Synthetic result; no provider called.", highlights: null, highlightScores: null, score: 1, favicon: null, image: null };
const search = { id: `search-${searchNumber}`, title: body.query, query: body.query, createdAt: date, updatedAt: date, starred: false, starredAt: null, requestId: "fixture-request", latencyMs: 1, error: null, answerText: null, answerRequestId: null, answerCitations: null, answerError: null, results: [result] };
latestSearch = search;
await delay(900);
const events = `event: search_results\ndata: ${JSON.stringify({ requestId: "fixture-request", results: [result] })}\n\nevent: done\ndata: ${JSON.stringify({ search })}\n\n`;
return fulfill(request.requestId, events, "text/event-stream");
}
return fulfill(request.requestId, {});
} catch (error) {
console.error("API fixture failed", error);
await call("Fetch.failRequest", { requestId: request.requestId, errorReason: "Failed" }).catch(() => undefined);
}
}
try {
await connect();
await waitFor('document.querySelector("#composer-input") && document.querySelector("#composer-input").isConnected', "app composer");
await evaluate('document.querySelector("button").blur()');
await evaluate('Array.from(document.querySelectorAll("button")).find(button => button.textContent.includes("New search")).click()');
await waitFor('document.activeElement?.id === "composer-input"', "New Search focus");
assert.equal(await evaluate('document.activeElement?.id'), "composer-input", "New Search focuses the search input");
await evaluate('Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, "value").set.call(document.querySelector("#composer-input"), "first fixture query"); document.querySelector("#composer-input").dispatchEvent(new Event("input", { bubbles: true }))');
await evaluate('Array.from(document.querySelectorAll("button")).find(button => button.getAttribute("aria-label") === "Search").click()');
await waitFor('document.querySelector("#composer-input")?.disabled', "running fixture search");
const streamDeadline = Date.now() + 8000;
while (!streamWasRequested && Date.now() < streamDeadline) await delay(25);
assert.equal(streamWasRequested, true, "the synthetic stream is pending before focus is moved");
assert.notEqual(await evaluate('document.activeElement?.id'), "composer-input", "starting search does not return focus to the input");
await evaluate('Array.from(document.querySelectorAll("button")).find(button => button.textContent.includes("New chat")).focus()');
assert.equal(await evaluate('document.activeElement?.textContent.includes("New chat")'), true, "search execution does not steal focus from another control");
await waitFor('document.body.innerText.includes("Fixture result for first fixture query")', "fixture result");
assert.equal(await evaluate('document.activeElement?.textContent.includes("New chat")'), true, "search completion preserves the user's focused control");
assert.ok(streamWasRequested, "fixture search stream was requested");
assert.equal(searchNumber, 1);
await evaluate('Array.from(document.querySelectorAll("button")).find(button => button.textContent.includes("New search")).click()');
await waitFor('document.activeElement?.id === "composer-input"', "repeated New Search focus");
assert.equal(await evaluate('document.activeElement?.id'), "composer-input", "repeated New Search focuses the input");
assert.equal(calls.filter(call => call.path.endsWith("/run/stream")).length, 1, "exactly one synthetic search ran");
console.log(JSON.stringify({ focusOnNewSearch: true, executionPreservedFocus: true, pendingFocusPreservedAtCompletion: true,
repeatedNewSearchFocus: true, normalSearchResultRendered: "Fixture result for first fixture query", fixtureOnly: true, apiRequests: calls.length }));
} finally {
if (socket) socket.close();
if (browser.exitCode === null) {
browser.kill("SIGTERM");
await Promise.race([new Promise(resolve => browser.once("close", resolve)), delay(2000)]);
}
await rm(profile, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
}
+100
View File
@@ -0,0 +1,100 @@
import assert from "node:assert/strict";
// Run against a production preview; requests to the backend are mocked.
// WEB_TEST_URL=http://127.0.0.1:5197 PLAYWRIGHT_MODULE=/path/to/playwright-core/index.mjs
// CHROME_EXECUTABLE=/path/to/chrome node tests/ui-mode.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 kindle = "Mozilla/5.0 (X11; Linux armv7l) AppleWebKit/537.36 Chrome/87.0 Safari/537.36 Kindle/3.0";
async function fixture(options = {}) {
const context = await browser.newContext({ viewport: { width: 600, height: 800 }, serviceWorkers: "block", ...options });
const requests = [], errors = [];
await context.route("**/*", async route => {
const url = new URL(route.request().url());
requests.push(url);
if (url.origin !== target.origin) return route.abort();
if (url.pathname.endsWith("/v1/auth/session")) {
return route.fulfill({ status: 401, json: { message: "missing bearer token" } });
}
if (url.pathname.includes("/api/")) return route.fulfill({ json: {} });
return route.continue();
});
const page = await context.newPage();
page.on("pageerror", error => errors.push(error.message));
const visit = async path => {
requests.length = 0;
await Promise.all([
page.waitForResponse(response => response.url().endsWith("/v1/auth/session")),
page.goto(new URL(path, target).href, { waitUntil: "networkidle" }),
]);
await page.locator('input[type="password"]').waitFor();
};
return { context, page, requests, errors, visit };
}
try {
const reader = await fixture({ userAgent: kindle });
await reader.visit("/?chat=keep-this#reply");
assert.equal(new URL(reader.page.url()).pathname, "/lite");
assert.equal(new URL(reader.page.url()).search, "?chat=keep-this");
assert.equal(new URL(reader.page.url()).hash, "#reply");
const styles = await reader.page.evaluate(() => Array.from(document.styleSheets).map(sheet => sheet.href));
assert.ok(styles.some(href => href && /lite.*\.css/.test(href)), "Lite has its own stylesheet");
assert.ok(reader.requests.every(url => !/character-.*\.(gif|png)|\/App-[^/]+\.js|agent-conversation/.test(url.href)), "Lite does not download full presentation assets");
assert.equal(await reader.page.locator(".lite-auth").evaluate(element => getComputedStyle(element).backgroundImage), "none");
const liteTypography = await reader.page.evaluate(() => ({
body: getComputedStyle(document.body).fontFamily,
wordmark: getComputedStyle(document.querySelector(".sybil-wordmark")).fontFamily,
}));
assert.ok(reader.requests.some(url => url.hostname === "fonts.googleapis.com"), "both presentations request the existing font stylesheet");
for (const text of ["A quieter workspace", "Simple pages.", "Clear text.", "No animations."]) {
assert.equal(await reader.page.getByText(text, { exact: false }).count(), 0, `no added sign-in flavor text: ${text}`);
}
assert.equal(await reader.page.locator('meta[name="viewport"]').getAttribute("content"), "width=device-width, initial-scale=1, viewport-fit=cover");
await reader.visit("/?ui=full&chat=keep-this");
assert.equal(new URL(reader.page.url()).pathname, "/");
assert.deepEqual(await reader.page.evaluate(() => ({
body: getComputedStyle(document.body).fontFamily,
wordmark: getComputedStyle(document.querySelector(".sybil-wordmark")).fontFamily,
})), liteTypography, "Lite preserves the original body and wordmark typefaces");
assert.equal(await reader.page.evaluate(() => localStorage.getItem("sybil:ui-mode")), "full");
await reader.visit("/");
assert.equal(new URL(reader.page.url()).pathname, "/", "stored full choice wins over Kindle hint");
await reader.visit("/lite?ui=lite");
await reader.visit("/");
assert.equal(new URL(reader.page.url()).pathname, "/lite", "explicit Lite choice persists");
assert.deepEqual(reader.errors, []);
await reader.context.close();
const dataSaver = await fixture();
await dataSaver.context.addInitScript(() => Object.defineProperty(navigator, "connection", { value: { saveData: true } }));
await dataSaver.visit("/");
assert.equal(new URL(dataSaver.page.url()).pathname, "/lite");
assert.deepEqual(dataSaver.errors, []);
await dataSaver.context.close();
const blocked = await fixture();
await blocked.context.addInitScript(() => Object.defineProperty(window, "localStorage", { get() { throw new Error("Storage denied"); } }));
await blocked.visit("/?ui=lite");
assert.equal(new URL(blocked.page.url()).pathname, "/lite");
assert.deepEqual(blocked.errors, [], "denied storage does not prevent sign in");
await blocked.context.close();
const failed = await fixture();
await failed.context.route("**/assets/lite-route-page-*.js", route => route.abort());
await failed.page.goto(new URL("/lite", target).href);
await failed.page.getByRole("heading", { name: "Sybil could not load" }).waitFor();
assert.equal(await failed.page.getByRole("button", { name: "Reload" }).count(), 1);
await failed.context.close();
console.log("UI routing, preference persistence, denied storage, isolated Lite assets and route failure recovery passed.");
} finally {
await browser.close();
}
+70
View File
@@ -0,0 +1,70 @@
import assert from "node:assert/strict";
import test from "node:test";
import {
UI_MODE_STORAGE_KEY,
buildUiModeUrl,
persistUiModePreference,
prefersLiteUi,
readUiModePreference,
resolveUiRoute,
} from "../src/lib/ui-mode.ts";
const location = (path = "/") => new URL(path, "https://sybil.test");
const reader = { userAgent: "Mozilla/5.0 (X11; Linux armv7l) AppleWebKit/531.2 Kindle/3.0" };
test("clear reader tokens and explicit data saving select Lite without treating all mobile devices as readers", () => {
assert.equal(prefersLiteUi(reader), true);
assert.equal(prefersLiteUi({ userAgent: "Kobo Touch" }), true);
assert.equal(prefersLiteUi({ userAgent: "PocketBook/1.0" }), true);
assert.equal(prefersLiteUi({ userAgent: "Mozilla/5.0 Silk/44.1 like Chrome/44.0" }), false);
assert.equal(prefersLiteUi({ userAgent: "Mozilla/5.0 Kindle Fire Build/ABC" }), false);
assert.equal(prefersLiteUi({ userAgent: "Mozilla/5.0 iPhone Mobile Safari" }), false);
assert.equal(prefersLiteUi({ userAgent: "Mozilla/5.0 Android Mobile Chrome/140" }), false);
assert.equal(prefersLiteUi({ saveData: true }), true);
assert.equal(prefersLiteUi({}), false);
});
test("automatic routing preserves deep links and hashes and only applies at the workspace entry", () => {
assert.deepEqual(resolveUiRoute(location("/?chat=abc&extra=value#reply"), reader, null), {
mode: "lite", url: "/lite?chat=abc&extra=value#reply", preference: null,
});
assert.equal(resolveUiRoute(location("/?agent=root"), reader, null).url, "/lite?agent=root");
assert.equal(resolveUiRoute(location("/search?q=eink"), reader, "lite").url, "/search?q=eink");
assert.equal(resolveUiRoute(location("/other"), reader, "lite").url, "/other");
});
test("explicit preference wins over detection and storage; a direct Lite visit wins over stored full", () => {
assert.deepEqual(resolveUiRoute(location("/?ui=full&chat=a"), reader, "lite"), {
mode: "full", url: "/?ui=full&chat=a", preference: "full",
});
assert.equal(resolveUiRoute(location("/?ui=lite"), {}, "full").url, "/lite?ui=lite");
assert.equal(resolveUiRoute(location("/lite?ui=full&chat=a"), reader, "lite").url, "/?ui=full&chat=a");
assert.equal(resolveUiRoute(location("/lite/"), {}, "full").url, "/lite");
assert.equal(resolveUiRoute(location("/"), {}, "lite").url, "/lite");
assert.equal(resolveUiRoute(location("/"), reader, "full").url, "/");
assert.equal(resolveUiRoute(location("/?ui=invalid"), {}, null).url, "/?ui=invalid");
});
test("manual mode links preserve workspace selection, standalone query and hash", () => {
assert.equal(buildUiModeUrl("lite", location("/?chat=abc&ui=full#reply")), "/lite?chat=abc&ui=lite#reply");
assert.equal(buildUiModeUrl("full", location("/lite?search=abc&ui=lite")), "/?search=abc&ui=full");
assert.equal(buildUiModeUrl("lite", location("/search?q=black+tea")), "/lite?q=black+tea&ui=lite");
assert.equal(buildUiModeUrl("full", location("/lite?q=black+tea")), "/search?q=black+tea&ui=full");
assert.equal(buildUiModeUrl("full", location("/lite?q=old&chat=current")), "/?q=old&chat=current&ui=full");
assert.equal(resolveUiRoute(location("/lite?q=black+tea&ui=full"), {}, null).url, "/search?q=black+tea&ui=full");
});
test("mode preference survives visits but denied or malformed storage cannot block startup", () => {
const values = new Map();
const storage = { getItem: key => values.get(key) ?? null, setItem: (key, value) => values.set(key, value) };
assert.equal(readUiModePreference(storage), null);
persistUiModePreference(storage, "lite");
assert.equal(readUiModePreference(storage), "lite");
values.set(UI_MODE_STORAGE_KEY, "unknown");
assert.equal(readUiModePreference(storage), null);
const blocked = { getItem() { throw new Error("denied"); }, setItem() { throw new Error("denied"); } };
assert.equal(readUiModePreference(blocked), null);
assert.doesNotThrow(() => persistUiModePreference(blocked, "full"));
assert.equal(readUiModePreference(null), null);
assert.doesNotThrow(() => persistUiModePreference(null, "lite"));
});
+65
View File
@@ -0,0 +1,65 @@
import assert from "node:assert/strict";
import test from "node:test";
import {
buildCompletionMessages, buildWorkspaceUrl, getModelOptions, getVisibleProviders,
hasNewPersistedUserMessage, loadStoredModelPreferences, normalizeStoredModelPreferences,
pickProviderModel, readSidebarSelectionFromUrl, saveModelPreferences,
} from "../src/lib/workspace-domain.ts";
const attachment = { kind: "text", id: "notes", filename: "notes.txt", mimeType: "text/plain", sizeBytes: 4, text: "plan", truncated: false };
const message = (id, role, content, metadata = null) => ({ id, role, content, metadata, createdAt: "2026-01-01T00:00:00Z", name: null });
test("both presentations submit provider history without UI tool logs and preserve attachments", () => {
const history = [
message("s", "system", "Be concise"),
message("u", "user", "Read my notes", { attachments: [attachment] }),
message("log", "tool", "Searching the web", { kind: "tool_call", toolCallId: "call-1" }),
{ ...message("tool", "tool", "Provider tool result"), name: "web_search" },
message("a", "assistant", "Here is the plan"),
];
const payload = buildCompletionMessages(history, "Continue", [attachment]);
assert.deepEqual(payload.map(entry => entry.role), ["system", "user", "tool", "assistant", "user"]);
assert.ok(!payload.some(entry => entry.id === "log"));
assert.deepEqual(payload[1].attachments, [attachment]);
assert.equal(payload[2].name, "web_search");
assert.deepEqual(payload.at(-1), { role: "user", content: "Continue", attachments: [attachment] });
assert.equal(history.length, 5);
});
test("reconciliation recognizes only a new matching persisted user turn", () => {
const old = message("old", "user", "Continue");
const next = message("next", "user", "Continue", { attachments: [attachment] });
const chat = { messages: [old, next] };
assert.equal(hasNewPersistedUserMessage(chat, new Set(["old"]), "Continue", [attachment]), true);
assert.equal(hasNewPersistedUserMessage(chat, new Set(["old", "next"]), "Continue", [attachment]), false);
assert.equal(hasNewPersistedUserMessage(chat, new Set(["old"]), "Continue", []), false);
assert.equal(hasNewPersistedUserMessage(chat, new Set(["old"]), "Different", [attachment]), false);
});
test("model policy preserves custom selections and uses advertised provider models", () => {
const catalog = { openai: { models: ["server-model"] }, "hermes-agent": { models: ["hermes"] } };
assert.deepEqual(getModelOptions(catalog, "openai"), ["server-model"]);
assert.equal(pickProviderModel(["server-model"], " custom-model "), "custom-model");
assert.equal(pickProviderModel(["server-model"], null), "server-model");
assert.ok(getVisibleProviders(catalog).includes("hermes-agent"));
assert.ok(!getVisibleProviders({}).includes("hermes-agent"));
assert.equal(normalizeStoredModelPreferences({ openai: " x ", xai: 123 }).openai, "x");
assert.equal(normalizeStoredModelPreferences({ xai: 123 }).xai, null);
});
test("selection URLs preserve interface choice and hash without stale selections", () => {
globalThis.window = { location: { pathname: "/lite", search: "?ui=lite&chat=old&search=stale", hash: "#reply" } };
try {
assert.deepEqual(readSidebarSelectionFromUrl(), { kind: "chat", id: "old" });
assert.equal(buildWorkspaceUrl({ kind: "agent", id: "root" }), "/lite?ui=lite&agent=root#reply");
assert.equal(buildWorkspaceUrl(null), "/lite?ui=lite#reply");
} finally { delete globalThis.window; }
});
test("blocked storage does not prevent reading defaults or using model controls", () => {
globalThis.window = { get localStorage() { throw new Error("Storage unavailable"); } };
try {
assert.equal(loadStoredModelPreferences().openai, null);
assert.doesNotThrow(() => saveModelPreferences(normalizeStoredModelPreferences({ openai: "x" })));
} finally { delete globalThis.window; }
});
+3
View File
@@ -4,6 +4,9 @@ import path from "node:path";
export default defineConfig({
plugins: [preact()],
// Keep syntax usable on older module-capable phones and e-readers. Web APIs
// still require feature support; this does not add a legacy polyfill bundle.
build: { target: ["chrome87", "firefox78", "safari14"] },
server: {
proxy: {
"/api": {