Compare commits

..
41 changed files with 1919 additions and 196 deletions
+1
View File
@@ -31,6 +31,7 @@ RUN apt-get update \
RUN npm ci --omit=dev --no-audit --no-fund
COPY --from=server-build /app/server/dist ./dist
COPY server/src/llm/pdf-text-worker.mjs ./dist/llm/pdf-text-worker.mjs
ENV NODE_ENV=production
ENV HOST=0.0.0.0
+5 -1
View File
@@ -363,7 +363,7 @@ Behavior notes:
- Available Sybil-managed tool calls for `openai`, `anthropic`, `xai`, and `gemini`: `web_search` and `fetch_url`. When `CHAT_CODEX_TOOL_ENABLED=true`, `codex_exec` is also available. When `CHAT_SHELL_TOOL_ENABLED=true`, `shell_exec` is also available.
- `web_search` returns ranked results with per-result summaries/snippets. Its backend engine is selected by `CHAT_WEB_SEARCH_ENGINE`: `exa` (default), `brave` (requires `BRAVE_SEARCH_API_KEY`), or `searxng` (requires `SEARXNG_BASE_URL`; the instance must allow `format=json`).
- Brave searches are queued and evenly paced according to the shortest window in Brave's `X-RateLimit-Policy` response header. The backend also honors `X-RateLimit-Remaining`/`X-RateLimit-Reset` and retries `429` responses up to three times with reset-aware exponential backoff; quota resets beyond the bounded retry window fail immediately.
- `fetch_url` fetches a URL with browser-like navigation headers and returns plaintext page content (HTML converted to text server-side).
- `fetch_url` fetches an HTTP(S) URL with browser-like navigation headers and returns plaintext page content. HTML is converted to text. PDF files are detected by media type or PDF signature and have selectable text extracted with page markers (no OCR); at most 10 MiB and 30 pages are read per call. The optional `pages` array selects up to 30 page numbers for follow-up reads, and `maxCharacters` bounds PDF text collection; a brief truncation hint may follow the extracted text. PDF parsing runs in a worker terminated after 8 seconds. Responses identify page count, selected pages, truncation, encrypted PDFs, empty PDFs, and PDFs without extractable text; unavailable extraction returns `ok:false` with `pdfStatus`. Other URL responses also have a 10 MiB download limit.
- `codex_exec` delegates coding, shell, repository inspection, and other complex software tasks to a persistent remote Codex CLI workspace over SSH. The server runs `codex exec --dangerously-bypass-approvals-and-sandbox --skip-git-repo-check <non-interactive wrapped prompt>` on the configured devbox inside `CHAT_CODEX_REMOTE_WORKDIR`, with SSH stdin closed.
- `shell_exec` runs arbitrary non-interactive shell commands on the same configured devbox, starting in `CHAT_CODEX_REMOTE_WORKDIR`. It uses `bash -lc` when bash exists, otherwise `sh -lc`, closes SSH stdin, and does not run inside the Sybil server container.
- Devbox tool configuration:
@@ -805,6 +805,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:
+1 -1
View File
@@ -215,7 +215,7 @@ Terminal tool-call event:
- `anthropic`: backend uses Anthropic's Messages API and may execute the same internal tools with `tool_use`/`tool_result` content blocks before producing final text.
- `xai`: backend uses xAI's OpenAI-compatible Chat Completions API and may execute the same internal tool calls before producing final text.
- `gemini`: backend uses Google's native Gemini `streamGenerateContent` API and may execute the same internal tool calls before producing final text.
- `fetch_url` sends browser-like navigation headers for outbound URL requests to reduce false 403s from sites that reject generic server clients.
- `fetch_url` sends browser-like navigation headers for outbound URL requests to reduce false 403s from sites that reject generic server clients. It converts HTML to text and extracts selectable PDF text page by page (without OCR), including when the response media type is inaccurate but the PDF signature is present. URL downloads are limited to 10 MiB, PDF extraction to 30 pages per call and an isolated worker terminated after 8 seconds, and accumulated PDF text to `maxCharacters` (default 12,000; maximum 50,000), plus a brief truncation hint. PDF tool results include `pdfStatus`, `pageCount`, and selected `pages`; call with `pages:[...]` to retrieve specific pages. Encrypted, page-free, and text-free PDFs return explicit status and text with `ok:false`. Oversized responses fail with a size-limit error.
- `hermes-agent`: backend uses the configured Hermes Agent OpenAI-compatible Chat Completions API. Sybil does not add its own tool definitions for this provider; Hermes Agent handles its own tools server-side. Custom Hermes stream events are normalized away unless they produce text deltas in this SSE contract.
- `openai`: image attachments are sent as Responses `input_image` items; text attachments are sent as `input_text` items.
- `gemini`: image attachments are sent as native Gemini `inlineData` parts; text attachments are inlined as text parts.
+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
}
}
+263
View File
@@ -21,6 +21,7 @@
"html-to-text": "^9.0.5",
"marked": "17.0.2",
"openai": "^6.16.0",
"pdfjs-dist": "5.4.394",
"pino-pretty": "^13.1.3",
"prisma": "^6.6.0",
"web-push": "^3.6.7",
@@ -775,6 +776,256 @@
"node": ">=8"
}
},
"node_modules/@napi-rs/canvas": {
"version": "0.1.100",
"resolved": "https://registry.npmjs.org/@napi-rs/canvas/-/canvas-0.1.100.tgz",
"integrity": "sha512-xglYA6q3XO5P3BNJYxVZ1IV7DLVjp1Py6nwag88YntrS+3vKHyYcMqXVS4ZztJmwz2uGvz1FWhI/4LgbR5uQDA==",
"license": "MIT",
"optional": true,
"workspaces": [
"e2e/*"
],
"engines": {
"node": ">= 10"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/Brooooooklyn"
},
"optionalDependencies": {
"@napi-rs/canvas-android-arm64": "0.1.100",
"@napi-rs/canvas-darwin-arm64": "0.1.100",
"@napi-rs/canvas-darwin-x64": "0.1.100",
"@napi-rs/canvas-linux-arm-gnueabihf": "0.1.100",
"@napi-rs/canvas-linux-arm64-gnu": "0.1.100",
"@napi-rs/canvas-linux-arm64-musl": "0.1.100",
"@napi-rs/canvas-linux-riscv64-gnu": "0.1.100",
"@napi-rs/canvas-linux-x64-gnu": "0.1.100",
"@napi-rs/canvas-linux-x64-musl": "0.1.100",
"@napi-rs/canvas-win32-arm64-msvc": "0.1.100",
"@napi-rs/canvas-win32-x64-msvc": "0.1.100"
}
},
"node_modules/@napi-rs/canvas-android-arm64": {
"version": "0.1.100",
"resolved": "https://registry.npmjs.org/@napi-rs/canvas-android-arm64/-/canvas-android-arm64-0.1.100.tgz",
"integrity": "sha512-hjhCKhntPv9+t4ckHymdx0phYNcVW+GKQR6Lzw2zE+pOVjOplSmtx9nNNknTjbEDLcuLZqA1y8ufKg1XfgftzQ==",
"cpu": [
"arm64"
],
"license": "MIT",
"optional": true,
"os": [
"android"
],
"engines": {
"node": ">= 10"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/Brooooooklyn"
}
},
"node_modules/@napi-rs/canvas-darwin-arm64": {
"version": "0.1.100",
"resolved": "https://registry.npmjs.org/@napi-rs/canvas-darwin-arm64/-/canvas-darwin-arm64-0.1.100.tgz",
"integrity": "sha512-2PcswRaC7Ly645DGt88///zuFDhJxJYdKAs1uU3mfk1atYkXufgcgLfBpk6Tm12nCQBaNt1wpybuPZ4qOhTo8A==",
"cpu": [
"arm64"
],
"license": "MIT",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": ">= 10"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/Brooooooklyn"
}
},
"node_modules/@napi-rs/canvas-darwin-x64": {
"version": "0.1.100",
"resolved": "https://registry.npmjs.org/@napi-rs/canvas-darwin-x64/-/canvas-darwin-x64-0.1.100.tgz",
"integrity": "sha512-ePNZtj7pNIva/siZMg+HmbeozkIjqUIYdoymH8HaA3qK7LfzFN4WMBM8G6HQ9ZC+H3+Dnn5pqtiXpgLykaPOhw==",
"cpu": [
"x64"
],
"license": "MIT",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": ">= 10"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/Brooooooklyn"
}
},
"node_modules/@napi-rs/canvas-linux-arm-gnueabihf": {
"version": "0.1.100",
"resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-arm-gnueabihf/-/canvas-linux-arm-gnueabihf-0.1.100.tgz",
"integrity": "sha512-d5cDB48oWFGU8/XPhUOFAlySgb/VAu7D+s8fi55K1Pcfg8aPplHWqMgibhVLU8ky7Pyg/fuiVLz4Nf3JrSTuUA==",
"cpu": [
"arm"
],
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">= 10"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/Brooooooklyn"
}
},
"node_modules/@napi-rs/canvas-linux-arm64-gnu": {
"version": "0.1.100",
"resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-arm64-gnu/-/canvas-linux-arm64-gnu-0.1.100.tgz",
"integrity": "sha512-rDxgxRu69RvDlX/bh9o22DxLsGr8EqsNgotL9+RwQE1S0b0cqeatqsw6aW45mukm0B42DIAaAacKaYQ8cqS1nw==",
"cpu": [
"arm64"
],
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">= 10"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/Brooooooklyn"
}
},
"node_modules/@napi-rs/canvas-linux-arm64-musl": {
"version": "0.1.100",
"resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-arm64-musl/-/canvas-linux-arm64-musl-0.1.100.tgz",
"integrity": "sha512-K3mDW66N+xT2/V439u1alFANiBUjdEx2gLiNYnCmUsva5jZMxWTjafBYwTzYK+EMFMHrUoabuU+T1BIP5CgbYQ==",
"cpu": [
"arm64"
],
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">= 10"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/Brooooooklyn"
}
},
"node_modules/@napi-rs/canvas-linux-riscv64-gnu": {
"version": "0.1.100",
"resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-riscv64-gnu/-/canvas-linux-riscv64-gnu-0.1.100.tgz",
"integrity": "sha512-mooqUBTIsccZpnoQC4NgrC1v6C1vof39etLNMnBwCY+p0gajWJvAHLGQ6g/gGyS5YrpDW+GefSN4+Cvcr08UWw==",
"cpu": [
"riscv64"
],
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">= 10"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/Brooooooklyn"
}
},
"node_modules/@napi-rs/canvas-linux-x64-gnu": {
"version": "0.1.100",
"resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-x64-gnu/-/canvas-linux-x64-gnu-0.1.100.tgz",
"integrity": "sha512-1eCvkDCazm7FFhsT7DfGOdSaHgZVK3bt/dSBl5EWHOWmnz+I7j8tPseJqqD81NF+MH21jKUK4wQSDjN0mdhnTg==",
"cpu": [
"x64"
],
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">= 10"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/Brooooooklyn"
}
},
"node_modules/@napi-rs/canvas-linux-x64-musl": {
"version": "0.1.100",
"resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-x64-musl/-/canvas-linux-x64-musl-0.1.100.tgz",
"integrity": "sha512-20arT6lnI19S68qNlii73TSEDbECNgzMz2EpldC1V3mZFuRkeujXkcebRk0LRJe9SEUAooYiLokfMViY8IX7yA==",
"cpu": [
"x64"
],
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">= 10"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/Brooooooklyn"
}
},
"node_modules/@napi-rs/canvas-win32-arm64-msvc": {
"version": "0.1.100",
"resolved": "https://registry.npmjs.org/@napi-rs/canvas-win32-arm64-msvc/-/canvas-win32-arm64-msvc-0.1.100.tgz",
"integrity": "sha512-DZFFT1wIAg37LJw37yhMRFfjATd3vTQzjZ1Yki8u2vhO6Hi5VE6BVaGQ1aaDu7xb4iMErz+9EOwjpS7xcxFeBw==",
"cpu": [
"arm64"
],
"license": "MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">= 10"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/Brooooooklyn"
}
},
"node_modules/@napi-rs/canvas-win32-x64-msvc": {
"version": "0.1.100",
"resolved": "https://registry.npmjs.org/@napi-rs/canvas-win32-x64-msvc/-/canvas-win32-x64-msvc-0.1.100.tgz",
"integrity": "sha512-MyT1j3mHC2+Lu4pBi9mKyMJhtP6U7k7EldY7sj/uS5gJA65gTXt8MefJQXLJo5d/vZbuWmfxzkEUNc/urV3pHA==",
"cpu": [
"x64"
],
"license": "MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">= 10"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/Brooooooklyn"
}
},
"node_modules/@pinojs/redact": {
"version": "0.4.0",
"resolved": "https://registry.npmjs.org/@pinojs/redact/-/redact-0.4.0.tgz",
@@ -1939,6 +2190,18 @@
"url": "https://github.com/sponsors/isaacs"
}
},
"node_modules/pdfjs-dist": {
"version": "5.4.394",
"resolved": "https://registry.npmjs.org/pdfjs-dist/-/pdfjs-dist-5.4.394.tgz",
"integrity": "sha512-9ariAYGqUJzx+V/1W4jHyiyCep6IZALmDzoaTLZ6VNu8q9LWi1/ukhzHgE2Xsx96AZi0mbZuK4/ttIbqSbLypg==",
"license": "Apache-2.0",
"engines": {
"node": ">=20.16.0 || >=22.3.0"
},
"optionalDependencies": {
"@napi-rs/canvas": "^0.1.81"
}
},
"node_modules/peberminta": {
"version": "0.9.0",
"resolved": "https://registry.npmjs.org/peberminta/-/peberminta-0.9.0.tgz",
+1
View File
@@ -30,6 +30,7 @@
"html-to-text": "^9.0.5",
"marked": "17.0.2",
"openai": "^6.16.0",
"pdfjs-dist": "5.4.394",
"pino-pretty": "^13.1.3",
"prisma": "^6.6.0",
"web-push": "^3.6.7",
+36
View File
@@ -0,0 +1,36 @@
export const MAX_FETCH_RESPONSE_BYTES = 10 * 1024 * 1024;
export async function readBoundedResponseBytes(response: Response, maxBytes: number) {
const contentLength = Number(response.headers.get("content-length"));
if (Number.isFinite(contentLength) && contentLength > maxBytes) {
await response.body?.cancel();
throw new Error(`URL response exceeds the ${Math.floor(maxBytes / (1024 * 1024))} MiB download limit.`);
}
const reader = response.body?.getReader();
if (!reader) return new Uint8Array();
const chunks: Uint8Array[] = [];
let totalBytes = 0;
try {
while (true) {
const { done, value } = await reader.read();
if (done) break;
totalBytes += value.byteLength;
if (totalBytes > maxBytes) {
await reader.cancel();
throw new Error(`URL response exceeds the ${Math.floor(maxBytes / (1024 * 1024))} MiB download limit.`);
}
chunks.push(value);
}
} finally {
reader.releaseLock();
}
const bytes = new Uint8Array(totalBytes);
let offset = 0;
for (const chunk of chunks) {
bytes.set(chunk, offset);
offset += chunk.byteLength;
}
return bytes;
}
+70 -40
View File
@@ -6,10 +6,12 @@ import { promisify } from "node:util";
import { convert as htmlToText } from "html-to-text";
import { z } from "zod";
import { buildBrowserLikeNavigationHeaders } from "../browser-fetch-headers.js";
import { MAX_FETCH_RESPONSE_BYTES, readBoundedResponseBytes } from "./bounded-response.js";
import { env } from "../env.js";
import { searchBrave } from "../search/brave.js";
import { exaClient } from "../search/exa.js";
import { searchSearxng } from "../search/searxng.js";
import { extractPdfText, hasPdfMagic, MAX_PDF_PAGES_PER_FETCH } from "./pdf-text.js";
import type { ChatMessage } from "./types.js";
export const MAX_TOOL_ROUNDS = env.CHAT_MAX_TOOL_ROUNDS;
@@ -45,6 +47,7 @@ const FetchUrlArgsSchema = z
.object({
url: z.string().trim().url(),
maxCharacters: z.coerce.number().int().min(500).max(MAX_FETCH_MAX_CHARACTERS).optional(),
pages: z.array(z.coerce.number().int().min(1).max(1_000_000)).min(1).max(MAX_PDF_PAGES_PER_FETCH).optional(),
})
.strict();
@@ -163,7 +166,7 @@ const BASE_CHAT_TOOLS: any[] = [
function: {
name: "fetch_url",
description:
"Fetch a webpage by URL and return readable plaintext content extracted from the page for deeper inspection.",
"Fetch a webpage by URL and return readable plaintext content. Text PDFs are extracted page by page; use pages:[3,4] to retrieve selected pages after a truncated result. Scanned PDFs have no extractable text.",
parameters: {
type: "object",
properties: {
@@ -174,6 +177,12 @@ const BASE_CHAT_TOOLS: any[] = [
maximum: MAX_FETCH_MAX_CHARACTERS,
description: "Maximum response text characters returned (default 12000).",
},
pages: {
type: "array",
items: { type: "integer", minimum: 1, maximum: 1000000 },
maxItems: MAX_PDF_PAGES_PER_FETCH,
description: "For PDFs, extract these page numbers only (up to 30 per fetch).",
},
},
required: ["url"],
additionalProperties: false,
@@ -561,48 +570,69 @@ async function runFetchUrlTool(input: unknown): Promise<ToolRunOutcome> {
signal: controller.signal,
headers: buildBrowserLikeNavigationHeaders(),
});
if (!response.ok) {
await response.body?.cancel();
throw new Error(`Fetch failed with status ${response.status}.`);
}
const contentType = (response.headers.get("content-type") ?? "").toLowerCase();
const bytes = await readBoundedResponseBytes(response, MAX_FETCH_RESPONSE_BYTES);
const url = response.url || parsed.toString();
if (contentType.includes("application/pdf") || hasPdfMagic(bytes)) {
if (!hasPdfMagic(bytes)) {
return { ok: false, url, status: response.status, contentType: contentType || null, pdfStatus: "invalid", text: "The server declared a PDF, but the downloaded file does not have a valid PDF header." };
}
const result = await extractPdfText(bytes, args.pages, maxCharacters);
const text = result.truncated
? `${result.text}\n\n[truncated; re-fetch selected pages with pages:[N,...]]`
: result.text;
return {
ok: result.status === "ok",
url,
status: response.status,
contentType: contentType || "application/pdf",
pdfStatus: result.status,
pageCount: result.pageCount,
pages: result.pages,
pagesTruncated: result.pageCount !== null && result.pageCount > result.pages.length,
truncated: result.truncated,
text,
};
}
const body = new TextDecoder().decode(bytes);
const isHtml = contentType.includes("text/html") || /<!doctype html|<html[\s>]/i.test(body);
const extracted = isHtml
? htmlToText(body, {
wordwrap: false,
preserveNewlines: true,
selectors: [
{ selector: "img", format: "skip" },
{ selector: "script", format: "skip" },
{ selector: "style", format: "skip" },
{ selector: "noscript", format: "skip" },
{ selector: "a", options: { ignoreHref: true } },
],
})
: body;
const normalized = compactWhitespace(extracted);
const truncated = normalized.length > maxCharacters;
const text = truncated
? `${normalized.slice(0, maxCharacters)}\n\n[truncated ${normalized.length - maxCharacters} characters]`
: normalized;
return {
ok: true,
url,
status: response.status,
contentType: contentType || null,
title: isHtml ? extractHtmlTitle(body) : null,
truncated,
text,
};
} finally {
clearTimeout(timeout);
}
if (!response.ok) {
throw new Error(`Fetch failed with status ${response.status}.`);
}
const contentType = (response.headers.get("content-type") ?? "").toLowerCase();
const body = await response.text();
const isHtml = contentType.includes("text/html") || /<!doctype html|<html[\s>]/i.test(body);
let extracted = body;
if (isHtml) {
extracted = htmlToText(body, {
wordwrap: false,
preserveNewlines: true,
selectors: [
{ selector: "img", format: "skip" },
{ selector: "script", format: "skip" },
{ selector: "style", format: "skip" },
{ selector: "noscript", format: "skip" },
{ selector: "a", options: { ignoreHref: true } },
],
});
}
const normalized = compactWhitespace(extracted);
const truncated = normalized.length > maxCharacters;
const text = truncated
? `${normalized.slice(0, maxCharacters)}\n\n[truncated ${normalized.length - maxCharacters} characters]`
: normalized;
return {
ok: true,
url: response.url || parsed.toString(),
status: response.status,
contentType: contentType || null,
title: isHtml ? extractHtmlTitle(body) : null,
truncated,
text,
};
}
function shellQuote(value: string) {
+100
View File
@@ -0,0 +1,100 @@
import { getDocument } from "pdfjs-dist/legacy/build/pdf.mjs";
import { parentPort, workerData } from "node:worker_threads";
const { bytes, requestedPages, maxCharacters, maxPages } = workerData;
function isPasswordError(error) {
return Boolean(error && typeof error === "object" && error.name === "PasswordException");
}
async function extract() {
let loadingTask;
try {
loadingTask = getDocument({
data: bytes,
standardFontDataUrl: new URL("../../node_modules/pdfjs-dist/standard_fonts/", import.meta.url).href,
isEvalSupported: false,
disableFontFace: true,
stopAtErrors: true,
});
const document = await loadingTask.promise;
if (document.numPages === 0) {
return { status: "no_pages", pageCount: 0, pages: [], text: "This PDF has no pages.", truncated: false };
}
const pages = requestedPages?.length
? [...new Set(requestedPages)].slice(0, maxPages)
: Array.from({ length: Math.min(document.numPages, maxPages) }, (_, index) => index + 1);
const invalidPage = pages.find((page) => page > document.numPages);
if (invalidPage) {
return {
status: "error",
pageCount: document.numPages,
pages: [],
text: `Requested page ${invalidPage}, but this PDF has ${document.numPages} pages.`,
truncated: false,
};
}
const chunks = [];
let characterCount = 0;
let foundText = false;
let truncated = false;
const append = (text) => {
const remaining = maxCharacters - characterCount;
if (remaining <= 0) {
truncated = true;
return;
}
const part = text.slice(0, remaining);
chunks.push(part);
characterCount += part.length;
if (part.length < text.length) truncated = true;
};
for (const pageNumber of pages) {
append(`${chunks.length ? "\n\n" : ""}--- Page ${pageNumber} ---\n`);
if (truncated) break;
const page = await document.getPage(pageNumber);
const reader = page.streamTextContent().getReader();
try {
while (!truncated) {
const { done, value } = await reader.read();
if (done) break;
for (const item of value.items) {
if (!("str" in item) || !item.str) continue;
foundText = true;
append(item.str + (item.hasEOL ? "\n" : " "));
if (truncated) break;
}
}
} finally {
if (truncated) await reader.cancel().catch(() => undefined);
reader.releaseLock();
}
if (truncated) break;
}
const text = chunks.join("").trimEnd();
if (!foundText) {
return {
status: "no_text",
pageCount: document.numPages,
pages,
text: "No extractable text was found in the selected pages.",
truncated: false,
};
}
return { status: "ok", pageCount: document.numPages, pages, text, truncated };
} catch (error) {
if (isPasswordError(error)) {
return { status: "encrypted", pageCount: null, pages: [], text: "This PDF is encrypted and requires a password.", truncated: false };
}
const message = error instanceof Error ? error.message : String(error);
return { status: "error", pageCount: null, pages: [], text: `PDF reading failed: ${message}`, truncated: false };
} finally {
await loadingTask?.destroy().catch(() => undefined);
}
}
parentPort?.postMessage(await extract());
+69
View File
@@ -0,0 +1,69 @@
import { Worker } from "node:worker_threads";
import { fileURLToPath } from "node:url";
export const MAX_PDF_PAGES_PER_FETCH = 30;
export const PDF_PARSE_TIMEOUT_MS = 8_000;
const DEFAULT_PDF_TEXT_CHARACTERS = 12_000;
export type PdfTextResult =
| { status: "ok"; pageCount: number; pages: number[]; text: string; truncated: boolean }
| { status: "no_pages"; pageCount: 0; pages: []; text: "This PDF has no pages."; truncated: false }
| { status: "no_text"; pageCount: number; pages: number[]; text: "No extractable text was found in the selected pages."; truncated: false }
| { status: "encrypted"; pageCount: null; pages: []; text: "This PDF is encrypted and requires a password."; truncated: false }
| { status: "error"; pageCount: number | null; pages: number[]; text: string; truncated: false };
export function hasPdfMagic(bytes: Uint8Array) {
const headerEnd = Math.min(bytes.length, 1024);
return Buffer.from(bytes.subarray(0, headerEnd)).includes(Buffer.from("%PDF-"));
}
export function extractPdfText(
bytes: Uint8Array,
requestedPages?: number[],
maxCharacters = DEFAULT_PDF_TEXT_CHARACTERS,
timeoutMs = PDF_PARSE_TIMEOUT_MS,
): Promise<PdfTextResult> {
return new Promise((resolve) => {
let settled = false;
let timeout: ReturnType<typeof setTimeout>;
let worker: Worker;
const finish = (result: PdfTextResult) => {
if (settled) return;
settled = true;
clearTimeout(timeout);
void worker.terminate().catch(() => undefined);
resolve(result);
};
try {
worker = new Worker(fileURLToPath(new URL("./pdf-text-worker.mjs", import.meta.url)), {
workerData: { bytes: new Uint8Array(bytes), requestedPages, maxCharacters, maxPages: MAX_PDF_PAGES_PER_FETCH },
execArgv: [],
});
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
resolve({ status: "error", pageCount: null, pages: [], text: `PDF reader could not start: ${message}`, truncated: false });
return;
}
timeout = setTimeout(() => {
finish({
status: "error",
pageCount: null,
pages: [],
text: `PDF reading exceeded its time limit (${timeoutMs} ms).`,
truncated: false,
});
}, timeoutMs);
worker.once("message", (result: PdfTextResult) => finish(result));
worker.once("error", (error) => {
const message = error instanceof Error ? error.message : String(error);
finish({ status: "error", pageCount: null, pages: [], text: `PDF reading failed: ${message}`, truncated: false });
});
worker.once("exit", (code) => {
if (!settled) {
finish({ status: "error", pageCount: null, pages: [], text: `PDF reader exited unexpectedly (${code}).`, truncated: false });
}
});
});
}
+26
View File
@@ -0,0 +1,26 @@
import assert from "node:assert/strict";
import test from "node:test";
import { readBoundedResponseBytes } from "../src/llm/bounded-response.js";
const oneMiB = 1024 * 1024;
test("reads response bytes within the declared size limit", async () => {
const bytes = await readBoundedResponseBytes(new Response("small"), oneMiB);
assert.equal(new TextDecoder().decode(bytes), "small");
});
test("rejects oversized responses from Content-Length before buffering", async () => {
const response = new Response("x", { headers: { "content-length": String(oneMiB + 1) } });
await assert.rejects(readBoundedResponseBytes(response, oneMiB), /exceeds the 1 MiB download limit/);
});
test("rejects streamed responses when Content-Length is absent", async () => {
const response = new Response(new ReadableStream({
start(controller) {
controller.enqueue(new Uint8Array(oneMiB));
controller.enqueue(new Uint8Array(1));
controller.close();
},
}));
await assert.rejects(readBoundedResponseBytes(response, oneMiB), /exceeds the 1 MiB download limit/);
});
+100 -1
View File
@@ -4,6 +4,7 @@ import { type ToolAwareStreamingEvent } from "../src/llm/chat-tools.js";
import { completeWithChatCompletionsApi, streamWithChatCompletionsApi } from "../src/llm/protocols/chat-completions-api.js";
import { completeWithMessagesApi, streamWithMessagesApi } from "../src/llm/protocols/messages-api.js";
import { streamWithResponsesApi } from "../src/llm/protocols/responses-api.js";
import { createPdf } from "./pdf-fixture.js";
async function* streamFrom(events: any[]) {
for (const event of events) {
@@ -241,10 +242,12 @@ test("fetch_url sends browser-like navigation headers", async () => {
try {
let requestCount = 0;
const requestBodies: any[] = [];
const client = {
chat: {
completions: {
create: async () => {
create: async (body: any) => {
requestBodies.push(body);
requestCount += 1;
if (requestCount === 1) {
return {
@@ -295,12 +298,108 @@ test("fetch_url sends browser-like navigation headers", async () => {
"Sec-Fetch-Site": "none",
"Sec-Fetch-User": "?1",
});
const toolResult = requestBodies[1]?.messages?.find((message: any) => message.role === "tool");
const fetched = JSON.parse(toolResult?.content ?? "{}");
assert.match(fetched.text, /Consumer price index/);
assert.equal(fetched.title, "CPI");
assert.equal(result.toolEvents[0]?.status, "completed");
} finally {
globalThis.fetch = originalFetch;
}
});
test("fetch_url extracts a mislabeled PDF and returns page handles", async () => {
const originalFetch = globalThis.fetch;
const fetchCalls: Array<{ input: RequestInfo | URL; init?: RequestInit }> = [];
const pdf = createPdf(["Revenue is 42.", "Costs are 18."]);
globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
fetchCalls.push({ input, init });
return new Response(pdf, { status: 200, headers: { "content-type": "text/plain" } });
}) as typeof fetch;
try {
const requestBodies: any[] = [];
const client = {
messages: {
create: async (body: any) => {
requestBodies.push(body);
if (requestBodies.length === 1) {
return {
content: [{
type: "tool_use",
id: "pdf_call",
name: "fetch_url",
input: { url: "https://example.com/report.pdf", pages: [2] },
}],
usage: { input_tokens: 1, output_tokens: 1 },
};
}
return { content: [{ type: "text", text: "Read page two" }], usage: { input_tokens: 1, output_tokens: 1 } };
},
},
};
const result = await completeWithMessagesApi({
client: client as any,
model: "claude-test",
messages: [{ role: "user", content: "Read the report" }],
});
const toolResult = requestBodies[1]?.messages?.at(-1)?.content?.[0];
const fetched = JSON.parse(toolResult?.content ?? "{}");
assert.equal(result.text, "Read page two");
assert.equal(fetchCalls.length, 1);
assert.equal(fetched.ok, true);
assert.equal(fetched.pdfStatus, "ok");
assert.equal(fetched.pageCount, 2);
assert.deepEqual(fetched.pages, [2]);
assert.equal(fetched.pagesTruncated, true);
assert.match(fetched.text, /--- Page 2 ---/);
assert.match(fetched.text, /Costs are 18/);
assert.doesNotMatch(fetched.text, /Revenue is 42/);
} finally {
globalThis.fetch = originalFetch;
}
});
test("fetch_url marks encrypted and text-free PDFs as unavailable", async () => {
const originalFetch = globalThis.fetch;
let responseBytes = createPdf([""]);
globalThis.fetch = (async () => new Response(responseBytes, {
status: 200,
headers: { "content-type": "application/pdf" },
})) as typeof fetch;
try {
for (const [pdf, expectedStatus] of [[createPdf([""]), "no_text"], [createPdf(["Secret"], true), "encrypted"]] as const) {
responseBytes = pdf;
const requestBodies: any[] = [];
const client = {
messages: {
create: async (body: any) => {
requestBodies.push(body);
if (requestBodies.length === 1) {
return {
content: [{ type: "tool_use", id: "pdf_status_call", name: "fetch_url", input: { url: "https://example.com/report.pdf" } }],
usage: { input_tokens: 1, output_tokens: 1 },
};
}
return { content: [{ type: "text", text: "Unavailable" }], usage: { input_tokens: 1, output_tokens: 1 } };
},
},
};
await completeWithMessagesApi({ client: client as any, model: "claude-test", messages: [{ role: "user", content: "Read PDF" }] });
const toolResult = requestBodies[1]?.messages?.at(-1)?.content?.[0];
const fetched = JSON.parse(toolResult?.content ?? "{}");
assert.equal(fetched.ok, false);
assert.equal(fetched.pdfStatus, expectedStatus);
assert.equal(toolResult?.is_error, true);
assert.ok(fetched.text.length > 0);
}
} finally {
globalThis.fetch = originalFetch;
}
});
test("Messages API executes tool_use blocks and sends tool_result follow-up", async () => {
const originalFetch = globalThis.fetch;
const fetchCalls: Array<{ input: RequestInfo | URL; init?: RequestInit }> = [];
+37
View File
@@ -0,0 +1,37 @@
export function createPdf(pages: string[], encrypted = false): Uint8Array {
const fontId = 3 + pages.length * 2;
const objects = [
"<< /Type /Catalog /Pages 2 0 R >>",
`<< /Type /Pages /Kids [${pages.map((_, index) => `${3 + index * 2} 0 R`).join(" ")}] /Count ${pages.length} >>`,
];
for (let index = 0; index < pages.length; index += 1) {
const pageId = 3 + index * 2;
const contentId = pageId + 1;
const text = pages[index]!;
const operators = Array.from({ length: Math.ceil(text.length / 100) }, (_, partIndex) => {
const part = text.slice(partIndex * 100, (partIndex + 1) * 100);
const escaped = part.replaceAll("\\", "\\\\").replaceAll("(", "\\(").replaceAll(")", "\\)");
return `(${escaped}) Tj`;
});
const content = text ? `BT /F1 12 Tf 72 720 Td ${operators.join(" ")} ET` : "";
objects.push(
`<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Resources << /Font << /F1 ${fontId} 0 R >> >> /Contents ${contentId} 0 R >>`,
`<< /Length ${Buffer.byteLength(content)} >>\nstream\n${content}\nendstream`,
);
}
objects.push("<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>");
const encryptionId = objects.length + 1;
if (encrypted) objects.push(`<< /Filter /Standard /V 1 /R 2 /O <${"00".repeat(32)}> /U <${"00".repeat(32)}> /P -4 >>`);
let output = "%PDF-1.4\n";
const offsets = [0];
objects.forEach((object, index) => {
offsets.push(Buffer.byteLength(output));
output += `${index + 1} 0 obj\n${object}\nendobj\n`;
});
const xrefOffset = Buffer.byteLength(output);
output += `xref\n0 ${objects.length + 1}\n0000000000 65535 f \n`;
for (const offset of offsets.slice(1)) output += `${String(offset).padStart(10, "0")} 00000 n \n`;
output += `trailer\n<< /Size ${objects.length + 1} /Root 1 0 R${encrypted ? ` /Encrypt ${encryptionId} 0 R` : ""} >>\nstartxref\n${xrefOffset}\n%%EOF`;
return new TextEncoder().encode(output);
}
+63
View File
@@ -0,0 +1,63 @@
import assert from "node:assert/strict";
import test from "node:test";
import { extractPdfText, hasPdfMagic } from "../src/llm/pdf-text.js";
import { createPdf } from "./pdf-fixture.js";
test("extracts selectable text with page markers and selected-page support", async () => {
const bytes = createPdf(["Quarterly revenue was 42.", "Costs were 18."]);
const result = await extractPdfText(bytes, [2]);
assert.equal(result.status, "ok");
assert.equal(result.pageCount, 2);
assert.deepEqual(result.pages, [2]);
assert.match(result.text, /--- Page 2 ---/);
assert.match(result.text, /Costs were 18\./);
assert.doesNotMatch(result.text, /Quarterly revenue/);
});
test("reports PDFs with no selectable text clearly", async () => {
const result = await extractPdfText(createPdf([""]));
assert.equal(result.status, "no_text");
assert.match(result.text, /No extractable text/);
});
test("reports encrypted PDFs clearly", async () => {
const result = await extractPdfText(createPdf(["Secret"], true));
assert.equal(result.status, "encrypted");
assert.match(result.text, /encrypted and requires a password/);
});
test("reports page-free PDFs and rejects invalid requested pages", async () => {
const empty = await extractPdfText(createPdf([]));
assert.equal(empty.status, "no_pages");
assert.match(empty.text, /no pages/);
const outOfRange = await extractPdfText(createPdf(["Only page"]), [2]);
assert.equal(outOfRange.status, "error");
assert.match(outOfRange.text, /has 1 pages/);
});
test("limits each extraction to 30 pages and preserves the full page count", async () => {
const result = await extractPdfText(createPdf(Array.from({ length: 31 }, (_, index) => `Text on page ${index + 1}.`)));
assert.equal(result.status, "ok");
assert.equal(result.pageCount, 31);
assert.equal(result.pages.length, 30);
assert.equal(result.pages.at(-1), 30);
});
test("caps accumulated extracted text at the caller limit", async () => {
const result = await extractPdfText(createPdf(["Long sentence. ".repeat(200)]), undefined, 50);
assert.equal(result.status, "ok");
assert.equal(result.truncated, true);
assert.ok(result.text.length <= 50);
});
test("terminates an over-time worker and returns an explicit timeout result", async () => {
const result = await extractPdfText(createPdf(["Small document"]), undefined, 12_000, 1);
assert.equal(result.status, "error");
assert.match(result.text, /time limit/);
});
test("recognizes PDF magic in a mislabeled or prefixed response", () => {
assert.equal(hasPdfMagic(new TextEncoder().encode("%PDF-1.4")), true);
assert.equal(hasPdfMagic(new TextEncoder().encode(`${" ".repeat(500)}%PDF-1.7`)), true);
assert.equal(hasPdfMagic(new TextEncoder().encode("<html>not a PDF</html>")), false);
});
+9
View File
@@ -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).
@@ -60,3 +61,11 @@ Client API contract docs:
- `/`: full Sybil app (sidebar + chat/search workspace)
- `/search?q=bitcoin+price`: standalone search page that renders only the search query box and results panel
## 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.
+1 -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" />
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"
+59 -95
View File
@@ -1,5 +1,6 @@
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 +29,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";
@@ -120,12 +122,6 @@ type ContextMenuState = {
item: SidebarSelection;
x: number;
y: number;
} | {
kind: "message";
chatId: string;
messageId: string;
x: number;
y: number;
};
type RenameChatDialogState = {
chatId: string;
@@ -202,6 +198,7 @@ type MobileWorkspaceSwipe = {
touchIdentifier: number;
startX: number;
startY: number;
startTimestamp: number;
lastX: number;
lastTimestamp: number;
velocityX: number;
@@ -555,15 +552,6 @@ function pickProviderModel(options: string[], preferred: string | null) {
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";
@@ -1809,8 +1797,11 @@ export default function App() {
};
const handleMobileWorkspaceTouchStart = (event: TargetedTouchEvent<HTMLElement>) => {
resetMobileWorkspaceSwipe();
if (
event.defaultPrevented ||
event.touches.length !== 1 ||
hasTextSelection() ||
!isMobileLayout() ||
isMobileSidebarOpen ||
isQuickQuestionOpen ||
@@ -1820,13 +1811,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 +1819,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 +1830,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 +1881,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;
@@ -2195,23 +2185,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;
@@ -3518,7 +3491,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"
)}
>
@@ -3741,11 +3714,12 @@ export default function App() {
</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 +3737,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 +3755,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 +3787,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 +3875,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 ? (
@@ -50,19 +50,23 @@ 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}
@@ -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,57 @@
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";
const receivedFormat = new Intl.DateTimeFormat(undefined, {
year: "numeric", month: "short", day: "numeric", hour: "numeric", minute: "2-digit",
});
const actionClass = "inline-flex h-10 items-center gap-1.5 rounded-md px-2 text-xs transition-colors hover:bg-violet-400/12 hover:text-violet-100 focus-visible:outline focus-visible:outline-2 focus-visible:outline-ring disabled:cursor-wait disabled:opacity-50";
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="text-muted-foreground" data-assistant-footer={message.id} data-mobile-swipe-ignore>
<div className="text-xs leading-5 [overflow-wrap:anywhere]">
{hasDate ? <><time className="whitespace-nowrap" 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="-ml-2 flex flex-wrap items-center gap-1" 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 className="h-3.5 w-3.5" aria-hidden="true" /> : <Copy className="h-3.5 w-3.5" 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 className="h-3.5 w-3.5" aria-hidden="true" />
<span>Fork</span>
</button> : null}
</div>
<span className={copyState === "failed" ? "block text-xs leading-5" : "sr-only"} 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>
);
+11
View File
@@ -462,6 +462,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;
}
+10 -11
View File
@@ -1,5 +1,6 @@
import { getApiBaseUrl, getAuthToken } from "./api";
import { ensureServiceWorker } from "../pwa";
import { browserPushOperation } from "./agent-push-errors.ts";
import {
AGENT_PUSH_STORAGE_KEY, AgentPushClient, agentPushAuthorityScope, agentPushCursor, agentPushSourceId,
createAgentPresenceReporter, createAgentPushController, parseAgentPushConsent, type AgentPushView, type PushSubscriptionHandle,
@@ -24,17 +25,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 +75,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 +90,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 };
+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;
+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;
}
+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 () => {
@@ -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 = [
{
+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);
});