feat(web): add lightweight workspace matching existing UI

This commit is contained in:
2026-11-11 16:59:09 -08:00
parent bc92651509
commit b7fdf7a89c
37 changed files with 2415 additions and 291 deletions
+3 -1
View File
@@ -1,3 +1,5 @@
import { browserUuid } from "./browser-uuid.ts";
/** Agent descriptors are independent of ordinary chat's inline attachment schema. */
export type AgentAttachment = {
id: string; kind: "image" | "text" | "file"; filename: string; mimeType: string;
@@ -104,7 +106,7 @@ export function createAgentUploadQueue(options: {
const limit = image ? Math.min(6 * 1024 * 1024, cap.maxImageBytes) : Math.min(8 * 1024 * 1024, cap.maxFileBytes);
if (file.size > limit) throw new Error(`${file.name} exceeds the ${image ? "6" : "8"} MiB file limit.`);
}
const added = selected.map(file => ({ uploadId: (options.newId || (() => crypto.randomUUID()))(), file, filename: file.name, sizeBytes: file.size, mimeType: file.type, status: "waiting" as const }));
const added = selected.map(file => ({ uploadId: (options.newId || browserUuid)(), file, filename: file.name, sizeBytes: file.size, mimeType: file.type, status: "waiting" as const }));
for (const row of added) rows.set(row.uploadId, row);
try { persist(); } catch (error) { for (const row of added) rows.delete(row.uploadId); throw error; }
publish(); pump();
+2 -1
View File
@@ -1,6 +1,7 @@
import type { Message } from "./api";
import { agentAttachments, attachmentCaption, parseAgentAttachment, type AgentAttachment } from "./agent-attachments.ts";
import { compareAgentMessages, normalizeAgentMessage } from "./agent-messages.ts";
import { browserUuid } from "./browser-uuid.ts";
export const AGENT_OUTBOX_STORAGE_KEY = "sybil.agent.optimistic-outbox.v1";
export type AgentDeliveryStatus = "sending" | "queued" | "complete" | "failed" | "unconfirmed";
@@ -28,7 +29,7 @@ export function createAgentOptimisticOutbox(options: {
newId?: () => string;
now?: () => number;
}) {
const newId = options.newId || (() => crypto.randomUUID());
const newId = options.newId || browserUuid;
const now = options.now || Date.now;
const rows = new Map<string, AgentOutboxRow>();
const inFlight = new Map<string, Promise<void>>();
+1 -8
View File
@@ -1,20 +1,13 @@
import { getApiBaseUrl, getAuthToken } from "./api";
import { ensureServiceWorker } from "../pwa";
import { browserPushOperation } from "./agent-push-errors.ts";
import { browserUuid } from "./browser-uuid.ts";
import {
AGENT_PUSH_STORAGE_KEY, AgentPushClient, agentPushAuthorityScope, agentPushCursor, agentPushSourceId,
createAgentPresenceReporter, createAgentPushController, parseAgentPushConsent, type AgentPushView, type PushSubscriptionHandle,
} from "./agent-push.ts";
let sessionId: string | undefined;
function browserUuid() {
if (typeof globalThis.crypto?.randomUUID === "function") return crypto.randomUUID();
if (typeof globalThis.crypto?.getRandomValues !== "function") throw new Error("Secure browser identifiers are unavailable.");
const bytes = crypto.getRandomValues(new Uint8Array(16));
bytes[6] = bytes[6] & 15 | 64; bytes[8] = bytes[8] & 63 | 128;
const hex = Array.from(bytes, byte => byte.toString(16).padStart(2, "0")).join("");
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
}
/** A document UUID avoids duplicated sessionStorage IDs when the user duplicates a tab. */
export function getAgentPresenceSessionId() { try { return sessionId ||= browserUuid(); } catch { return undefined; } }
const api = new AgentPushClient({ baseUrl: getApiBaseUrl(), token: getAuthToken });
+8 -4
View File
@@ -40,6 +40,10 @@ export type AgentRoomEvent =
const object = (value: unknown): Record<string, unknown> | undefined => value !== null && typeof value === "object" && !Array.isArray(value)
? value as Record<string, unknown> : undefined;
const defined = (value: Record<string, unknown>) => Object.fromEntries(Object.entries(value).filter(([, item]) => item !== undefined));
function checkAborted(signal?: AbortSignal) {
// AbortSignal.throwIfAborted() is newer than the browsers supported by Lite.
if (signal?.aborted) throw signal.reason ?? new DOMException("Download canceled.", "AbortError");
}
export function normalizeAgentCursor(value: unknown): string {
if (typeof value !== "string" || !/^\d+$/.test(value)) throw new Error("Invalid agent message cursor.");
return BigInt(value).toString();
@@ -239,7 +243,7 @@ export class AgentRoomClient {
}
async download(attachment: AgentAttachment, signal?: AbortSignal): Promise<Blob> {
const file = parseAgentAttachment(attachment), headers = new Headers(), token = this.token();
signal?.throwIfAborted();
checkAborted(signal);
while (this.activeDownloads >= 2) {
await new Promise<void>((resolve, reject) => {
const cleanup = () => { this.downloadWaiters.delete(wake); signal?.removeEventListener("abort", abort); };
@@ -248,7 +252,7 @@ export class AgentRoomClient {
this.downloadWaiters.add(wake); signal?.addEventListener("abort", abort, { once: true });
if (signal?.aborted) abort();
});
signal?.throwIfAborted();
checkAborted(signal);
}
this.activeDownloads++;
try {
@@ -262,7 +266,7 @@ export class AgentRoomClient {
try {
for (;;) {
const { done, value } = await reader.read(); if (done) break;
signal?.throwIfAborted();
checkAborted(signal);
if (size + value.length > bytes.length) throw new Error("Attachment download exceeds its size limit.");
bytes.set(value, size); size += value.length;
}
@@ -272,7 +276,7 @@ export class AgentRoomClient {
if (sha256 !== file.sha256) throw new Error("Attachment checksum did not match.");
if (file.kind === "image" && response.headers.get("content-type")?.split(";")[0].trim() !== file.mimeType)
throw new Error("Attachment image type did not match.");
signal?.throwIfAborted();
checkAborted(signal);
if (token !== this.token()) throw new Error("Authentication changed. Retry the download.");
return new Blob([bytes], { type: response.headers.get("content-type") || "application/octet-stream" });
} finally {
+1 -42
View File
@@ -411,48 +411,7 @@ export async function deleteSearch(searchId: string) {
await api<{ deleted: true }>(`/v1/searches/${searchId}`, { method: "DELETE" });
}
export function getMessageAttachments(metadata: unknown): ChatAttachment[] {
if (!metadata || typeof metadata !== "object" || Array.isArray(metadata)) return [];
const attachments = (metadata as Record<string, unknown>).attachments;
if (!Array.isArray(attachments)) return [];
const parsed: ChatAttachment[] = [];
for (const entry of attachments) {
if (!entry || typeof entry !== "object" || Array.isArray(entry)) continue;
const record = entry as Record<string, unknown>;
const kind = record.kind;
const id = typeof record.id === "string" ? record.id : "";
const filename = typeof record.filename === "string" ? record.filename : "";
const mimeType = typeof record.mimeType === "string" ? record.mimeType : "";
const sizeBytes = typeof record.sizeBytes === "number" ? record.sizeBytes : 0;
if (kind === "image" && typeof record.dataUrl === "string" && (mimeType === "image/png" || mimeType === "image/jpeg")) {
parsed.push({
kind,
id,
filename,
mimeType,
sizeBytes,
dataUrl: record.dataUrl,
} satisfies ChatImageAttachment);
continue;
}
if (kind === "text" && typeof record.text === "string") {
parsed.push({
kind,
id,
filename,
mimeType,
sizeBytes,
text: record.text,
truncated: record.truncated === true,
} satisfies ChatTextAttachment);
}
}
return parsed;
}
export { getMessageAttachments } from "./chat-attachments";
type RunSearchStreamHandlers = {
onSearchResults?: (payload: { requestId: string | null; results: SearchResultItem[] }) => void;
+12
View File
@@ -0,0 +1,12 @@
type BrowserCrypto = Pick<Crypto, "getRandomValues"> & Partial<Pick<Crypto, "randomUUID">>;
/** Secure UUIDs also work on browsers that predate Crypto.randomUUID(). */
export function browserUuid(source: BrowserCrypto | undefined = typeof crypto === "undefined" ? undefined : crypto): string {
if (typeof source?.randomUUID === "function") return source.randomUUID();
if (typeof source?.getRandomValues !== "function") throw new Error("Secure browser identifiers are unavailable.");
const bytes = source.getRandomValues(new Uint8Array(16));
bytes[6] = bytes[6] & 15 | 64;
bytes[8] = bytes[8] & 63 | 128;
const hex = Array.from(bytes, byte => byte.toString(16).padStart(2, "0")).join("");
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
}
+44
View File
@@ -0,0 +1,44 @@
import type { ChatAttachment, ChatImageAttachment, ChatTextAttachment } from "./api";
export function getMessageAttachments(metadata: unknown): ChatAttachment[] {
if (!metadata || typeof metadata !== "object" || Array.isArray(metadata)) return [];
const attachments = (metadata as Record<string, unknown>).attachments;
if (!Array.isArray(attachments)) return [];
const parsed: ChatAttachment[] = [];
for (const entry of attachments) {
if (!entry || typeof entry !== "object" || Array.isArray(entry)) continue;
const record = entry as Record<string, unknown>;
const kind = record.kind;
const id = typeof record.id === "string" ? record.id : "";
const filename = typeof record.filename === "string" ? record.filename : "";
const mimeType = typeof record.mimeType === "string" ? record.mimeType : "";
const sizeBytes = typeof record.sizeBytes === "number" ? record.sizeBytes : 0;
if (kind === "image" && typeof record.dataUrl === "string" && (mimeType === "image/png" || mimeType === "image/jpeg")) {
parsed.push({
kind,
id,
filename,
mimeType,
sizeBytes,
dataUrl: record.dataUrl,
} satisfies ChatImageAttachment);
continue;
}
if (kind === "text" && typeof record.text === "string") {
parsed.push({
kind,
id,
filename,
mimeType,
sizeBytes,
text: record.text,
truncated: record.truncated === true,
} satisfies ChatTextAttachment);
}
}
return parsed;
}
+14
View File
@@ -0,0 +1,14 @@
/** Marked uses at() internally, including on Chromium-based readers predating it. */
export function installLiteCompatibility() {
if (!("at" in Array.prototype)) {
Object.defineProperty(Array.prototype, "at", {
configurable: true,
writable: true,
value: function at(this: unknown[], index: number) {
const offset = Math.trunc(Number(index)) || 0;
const position = offset < 0 ? this.length + offset : offset;
return position < 0 || position >= this.length ? undefined : this[position];
},
});
}
}
+62
View File
@@ -0,0 +1,62 @@
export type UiMode = "full" | "lite";
export type UiLocation = Pick<Location, "pathname" | "search" | "hash">;
type PreferenceStorage = Pick<Storage, "getItem" | "setItem">;
export const UI_MODE_STORAGE_KEY = "sybil:ui-mode";
export function parseUiMode(value: string | null): UiMode | null {
return value === "full" || value === "lite" ? value : null;
}
export function readUiModePreference(storage: PreferenceStorage | null): UiMode | null {
try {
return parseUiMode(storage?.getItem(UI_MODE_STORAGE_KEY) ?? null);
} catch {
return null;
}
}
export function persistUiModePreference(storage: PreferenceStorage | null, mode: UiMode) {
try {
storage?.setItem(UI_MODE_STORAGE_KEY, mode);
} catch {
// The explicit URL still works when private browsing blocks storage.
}
}
export function prefersLiteUi({ userAgent = "", saveData = false }: { userAgent?: string; saveData?: boolean }) {
// Silk is also a tablet/phone browser; it is not an e-ink signal by itself.
const isReader = /\b(?:Kindle|Kobo|PocketBook)\b/i.test(userAgent)
&& !/\b(?:Silk|Kindle Fire)\b/i.test(userAgent);
return saveData || isReader;
}
export function isLitePath(path: string) {
return path === "/lite" || path === "/lite/";
}
function fullPath(location: UiLocation) {
const params = new URLSearchParams(location.search);
const isStandaloneSearch = params.has("q") && !["chat", "search", "agent"].some(key => params.has(key));
return location.pathname === "/search" || (isLitePath(location.pathname) && isStandaloneSearch) ? "/search" : "/";
}
/** Ordinary links deliberately navigate documents, keeping the two stylesheets isolated. */
export function buildUiModeUrl(mode: UiMode, location: UiLocation = window.location) {
const params = new URLSearchParams(location.search);
params.set("ui", mode);
return `${mode === "lite" ? "/lite" : fullPath(location)}?${params.toString()}${location.hash}`;
}
/** Decide once at entry, before downloading either presentation. */
export function resolveUiRoute(
location: UiLocation,
hints: { userAgent?: string; saveData?: boolean },
storedPreference: UiMode | null,
) {
const explicit = parseUiMode(new URLSearchParams(location.search).get("ui"));
const mode = explicit ?? (isLitePath(location.pathname) ? "lite"
: location.pathname === "/" ? storedPreference ?? (prefersLiteUi(hints) ? "lite" : "full") : "full");
const path = mode === "lite" ? "/lite" : isLitePath(location.pathname) ? fullPath(location) : location.pathname;
return { mode, url: `${path}${location.search}${location.hash}`, preference: explicit };
}
+160
View File
@@ -0,0 +1,160 @@
import type { ChatAttachment, ChatDetail, CompletionRequestMessage, Message, ModelCatalogResponse, Provider } from "./api";
import type { SidebarSelection } from "./sidebar-selection";
import { getMessageAttachments } from "./chat-attachments.ts";
import { QUICK_QUESTION_DEFAULT_MODEL } from "./quick-question.ts";
export function readSidebarSelectionFromUrl(): SidebarSelection | null {
if (typeof window === "undefined") return null;
const params = new URLSearchParams(window.location.search);
if (params.get("agent") === "root") return { kind: "agent", id: "root" };
const chatId = params.get("chat")?.trim();
if (chatId) {
return { kind: "chat", id: chatId };
}
const searchId = params.get("search")?.trim();
if (searchId) {
return { kind: "search", id: searchId };
}
return null;
}
export function buildWorkspaceUrl(selection: SidebarSelection | null) {
if (typeof window === "undefined") return "/";
const params = new URLSearchParams(window.location.search);
params.delete("chat");
params.delete("search");
params.delete("agent");
if (selection) {
params.set(selection.kind, selection.id);
}
const query = params.toString();
return `${window.location.pathname}${query ? `?${query}` : ""}${window.location.hash}`;
}
export const PROVIDER_FALLBACK_MODELS: Record<Provider, string[]> = {
openai: ["gpt-4.1-mini", QUICK_QUESTION_DEFAULT_MODEL],
anthropic: ["claude-3-5-sonnet-latest"],
xai: ["grok-3-mini"],
gemini: ["gemini-3.5-flash", "gemini-flash-latest"],
"hermes-agent": ["hermes-agent"],
};
export const EMPTY_MODEL_CATALOG: ModelCatalogResponse["providers"] = {
openai: { models: [], loadedAt: null, error: null },
anthropic: { models: [], loadedAt: null, error: null },
xai: { models: [], loadedAt: null, error: null },
gemini: { models: [], loadedAt: null, error: null },
};
export const BASE_PROVIDERS: Provider[] = ["openai", "anthropic", "xai", "gemini"];
export const ALL_PROVIDERS: Provider[] = [...BASE_PROVIDERS, "hermes-agent"];
export const MODEL_PREFERENCES_STORAGE_KEY = "sybil:modelPreferencesByProvider";
export type ProviderModelPreferences = Record<Provider, string | null>;
export const EMPTY_MODEL_PREFERENCES: ProviderModelPreferences = {
openai: null,
anthropic: null,
xai: null,
gemini: null,
"hermes-agent": null,
};
export function createClientRequestId() {
if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
return crypto.randomUUID();
}
return `web-${Date.now()}-${Math.random().toString(36).slice(2)}`;
}
export function isRecoverableStreamDisconnect(error: unknown) {
if (error instanceof TypeError) return true;
const message = (error instanceof Error ? error.message : String(error)).toLowerCase();
return (
message.includes("failed to fetch") ||
message.includes("load failed") ||
message.includes("network error") ||
message.includes("networkerror") ||
message.includes("no response stream") ||
message.includes("stream disconnected before completion")
);
}
export function hasNewPersistedUserMessage(chat: ChatDetail, previousMessageIds: Set<string>, content: string, attachments: ChatAttachment[]) {
return chat.messages.some((message) => {
if (previousMessageIds.has(message.id) || message.role !== "user" || message.content !== content) return false;
const persistedAttachmentIds = new Set(getMessageAttachments(message.metadata).map((attachment) => attachment.id));
return attachments.length === persistedAttachmentIds.size && attachments.every((attachment) => persistedAttachmentIds.has(attachment.id));
});
}
export function getModelOptions(catalog: ModelCatalogResponse["providers"], provider: Provider) {
const providerModels = catalog[provider]?.models ?? [];
if (providerModels.length) return providerModels;
return PROVIDER_FALLBACK_MODELS[provider];
}
export function getVisibleProviders(catalog: ModelCatalogResponse["providers"]) {
return ALL_PROVIDERS.filter((provider) => provider !== "hermes-agent" || catalog[provider] !== undefined);
}
export function loadStoredModelPreferences() {
if (typeof window === "undefined") return EMPTY_MODEL_PREFERENCES;
try {
const raw = window.localStorage.getItem(MODEL_PREFERENCES_STORAGE_KEY);
if (!raw) return EMPTY_MODEL_PREFERENCES;
return normalizeStoredModelPreferences(JSON.parse(raw));
} catch {
return EMPTY_MODEL_PREFERENCES;
}
}
export function normalizeStoredProvider(value: unknown): Provider {
return value === "anthropic" || value === "xai" || value === "gemini" || value === "openai" || value === "hermes-agent"
? value
: "openai";
}
export function normalizeStoredModelPreferences(value: unknown): ProviderModelPreferences {
if (!value || typeof value !== "object" || Array.isArray(value)) return EMPTY_MODEL_PREFERENCES;
const parsed = value as Partial<Record<Provider, unknown>>;
return {
openai: typeof parsed.openai === "string" && parsed.openai.trim() ? parsed.openai.trim() : null,
anthropic: typeof parsed.anthropic === "string" && parsed.anthropic.trim() ? parsed.anthropic.trim() : null,
xai: typeof parsed.xai === "string" && parsed.xai.trim() ? parsed.xai.trim() : null,
gemini: typeof parsed.gemini === "string" && parsed.gemini.trim() ? parsed.gemini.trim() : null,
"hermes-agent":
typeof parsed["hermes-agent"] === "string" && parsed["hermes-agent"].trim() ? parsed["hermes-agent"].trim() : null,
};
}
export function pickProviderModel(options: string[], preferred: string | null) {
if (preferred?.trim()) return preferred.trim();
return options[0] ?? "";
}
/** Persisted tool activity is a UI log, not a provider conversation message. */
export function buildCompletionMessages(messages: Message[], content: string, attachments: ChatAttachment[] = []): CompletionRequestMessage[] {
return [
...messages.filter(message => {
const metadata = message.metadata;
return !metadata || typeof metadata !== "object" || Array.isArray(metadata) || (metadata as Record<string, unknown>).kind !== "tool_call";
}).map(message => {
const savedAttachments = getMessageAttachments(message.metadata);
return {
id: message.id,
role: message.role,
content: message.content,
...(message.name ? { name: message.name } : {}),
...(savedAttachments.length ? { attachments: savedAttachments } : {}),
};
}),
{ role: "user", content, ...(attachments.length ? { attachments } : {}) },
];
}
export function saveModelPreferences(preferences: ProviderModelPreferences) {
try { window.localStorage.setItem(MODEL_PREFERENCES_STORAGE_KEY, JSON.stringify(preferences)); }
catch { /* Browsers with unavailable storage can still use this session. */ }
}