feat(web): add lightweight workspace matching existing UI
This commit is contained in:
@@ -47,6 +47,18 @@ test('downloads bound concurrent bytes, validate hashes/types, cancel queued wor
|
||||
await assert.rejects(wrongType.download({...file,kind:'image',mimeType:'image/png'}),/type did not match/);
|
||||
});
|
||||
|
||||
test('downloads support older AbortSignals without throwIfAborted or reason', async () => {
|
||||
let calls = 0;
|
||||
const client = new AgentRoomClient({ fetch: async () => { calls++; return new Response('data'); } });
|
||||
const controller = new AbortController();
|
||||
Object.defineProperty(controller.signal, 'throwIfAborted', { value: undefined });
|
||||
Object.defineProperty(controller.signal, 'reason', { value: undefined });
|
||||
assert.equal(await (await client.download(file, controller.signal)).text(), 'data');
|
||||
controller.abort();
|
||||
await assert.rejects(client.download(file, controller.signal), error => error.name === 'AbortError');
|
||||
assert.equal(calls, 1, 'an already canceled download never starts another request');
|
||||
});
|
||||
|
||||
test('composer gates unsupported servers, count/type/size and batches before upload; preserves retry ID and remove races',async()=>{
|
||||
let capability, attempts=[], next=0, changed=0, finish;
|
||||
const queue=createAgentUploadQueue({capability:()=>capability,newId:()=>`upload-${++next}`,changed:()=>changed++,upload:async(_file,id,signal)=>{attempts.push({id,signal});if(attempts.length===1)throw new Error('Quota full');return new Promise(resolve=>finish=resolve);}});
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { browserUuid } from "../src/lib/browser-uuid.ts";
|
||||
|
||||
test("native UUID generation keeps the crypto receiver", () => {
|
||||
const source = {
|
||||
randomUUID() { assert.equal(this, source); return "native-id"; },
|
||||
getRandomValues() { assert.fail("native generation should be used"); },
|
||||
};
|
||||
assert.equal(browserUuid(source), "native-id");
|
||||
});
|
||||
|
||||
test("older browsers generate RFC 4122 version 4 UUIDs using secure random bytes", () => {
|
||||
const source = { getRandomValues(bytes) {
|
||||
assert.equal(this, source);
|
||||
assert.equal(bytes.length, 16);
|
||||
for (let i = 0; i < bytes.length; i++) bytes[i] = i;
|
||||
return bytes;
|
||||
} };
|
||||
assert.equal(browserUuid(source), "00010203-0405-4607-8809-0a0b0c0d0e0f");
|
||||
});
|
||||
|
||||
test("missing secure randomness never falls back to a guessable identifier", () => {
|
||||
assert.throws(() => browserUuid({}), /Secure browser identifiers are unavailable/);
|
||||
});
|
||||
@@ -0,0 +1,139 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { createHash } from "node:crypto";
|
||||
|
||||
// Local production preview only; every API call and socket is mocked.
|
||||
// PLAYWRIGHT_MODULE=/path/playwright-core/index.mjs CHROME_EXECUTABLE=/path/chrome
|
||||
// WEB_TEST_URL=http://127.0.0.1:5197 node tests/lite-agent.browser.mjs
|
||||
const { chromium } = await import(process.env.PLAYWRIGHT_MODULE || "playwright-core");
|
||||
const target = new URL(process.env.WEB_TEST_URL || "http://127.0.0.1:5197/");
|
||||
assert.ok(target.protocol === "http:" && ["localhost", "127.0.0.1", "[::1]"].includes(target.hostname));
|
||||
const browser = await chromium.launch({ headless: true, executablePath: process.env.CHROME_EXECUTABLE || undefined,
|
||||
...(process.env.BROWSER_NO_SANDBOX === "1" ? { args: ["--no-sandbox"] } : {}) });
|
||||
const context = await browser.newContext({ viewport: { width: 1000, height: 850 }, serviceWorkers: "block" });
|
||||
await context.addInitScript(() => {
|
||||
localStorage.setItem("sybil_admin_token", "lite-agent-fixture-token");
|
||||
// Exercise missing APIs on Chromium readers without emulating their rendering engine.
|
||||
Object.defineProperty(Crypto.prototype, "randomUUID", { configurable: true, value: undefined });
|
||||
delete Array.prototype.at;
|
||||
delete AbortSignal.prototype.throwIfAborted;
|
||||
});
|
||||
|
||||
const errors = [], requests = [], submissions = [], downloads = [], persistedBeforeSend = [];
|
||||
const sourceId = "00000000-0000-4000-8000-000000000001";
|
||||
const date = "2026-11-10T12:00:00.000Z";
|
||||
const idle = { state: "idle", isThinking: false, queued: 0, backgroundWorkers: 0, tools: [], queuedMessages: [] };
|
||||
const image = Buffer.from("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+a2ioAAAAASUVORK5CYII=", "base64");
|
||||
const attachment = { id: "att_12345678-1234-4234-8234-123456789abc", kind: "image", filename: "fixture.png", mimeType: "image/png",
|
||||
sizeBytes: image.length, sha256: createHash("sha256").update(image).digest("hex") };
|
||||
const history = [{ id: "outbound:1", role: "assistant", content: "A static **Agent reply**.\n\n",
|
||||
createdAt: date, name: null, metadata: { kind: "message", status: "complete", entryId: 1, agentAttachments: [attachment] } }];
|
||||
let cursor = 1, readCursor = "0", failedSend = false, live;
|
||||
const page = await context.newPage();
|
||||
page.on("pageerror", error => errors.push(error.message));
|
||||
await context.route("**/*", async route => {
|
||||
const request = route.request(), url = new URL(request.url()), path = url.pathname;
|
||||
requests.push(url.href);
|
||||
if (url.origin !== target.origin) return route.abort();
|
||||
if (!path.startsWith("/api/")) return route.continue();
|
||||
assert.equal(request.headers().authorization, "Bearer lite-agent-fixture-token");
|
||||
const method = request.method();
|
||||
let body;
|
||||
if (path.endsWith("/auth/session")) body = { authenticated: true, mode: "token" };
|
||||
else if (path.endsWith("/workspace-items")) body = { items: [] };
|
||||
else if (path.endsWith("/active-runs")) body = { chats: [], searches: [] };
|
||||
else if (path.endsWith("/models")) body = { providers: { openai: { models: ["fixture-model"], loadedAt: date, error: null } } };
|
||||
else if (path.endsWith("/chat-tools")) body = { tools: [] };
|
||||
else if (path.endsWith("/agent/messages") && method === "POST") {
|
||||
const submission = request.postDataJSON();
|
||||
submissions.push(submission);
|
||||
persistedBeforeSend.push(await page.evaluate(() => JSON.parse(sessionStorage.getItem("sybil.agent.optimistic-outbox.v1") || "[]")));
|
||||
if (!failedSend) { failedSend = true; return route.abort("internetdisconnected"); }
|
||||
const row = { id: `inbound:sybil:${submission.requestId}`, role: "user", content: submission.content,
|
||||
createdAt: date, name: null, metadata: { kind: "message", status: "complete", entryId: ++cursor } };
|
||||
history.push(row);
|
||||
live.send(JSON.stringify({ type: "messages", conversationId: "fixture-room", messages: [row], cursor: String(cursor), beforeCursor: String(cursor), hasMore: false }));
|
||||
body = { id: cursor, status: "placed", messageId: row.id };
|
||||
} else if (path.endsWith("/agent/messages")) {
|
||||
const after = url.searchParams.get("after");
|
||||
const messages = after === null ? history : history.filter(message => message.metadata.entryId > Number(after));
|
||||
body = { conversationId: "fixture-room", messages, cursor: String(cursor), beforeCursor: messages.length ? String(messages[0].metadata.entryId) : null, hasMore: false };
|
||||
} else if (path.endsWith("/read-state")) {
|
||||
if (method === "PUT") readCursor = request.postDataJSON().cursor;
|
||||
body = { sourceId, cursor: readCursor, updatedAt: null };
|
||||
} else if (path.endsWith("/agent")) body = { id: "fixture-room", title: "Sybil Agent", activity: idle, protocol: "pi-room.v1", websocket: "/v1/agent/ws" };
|
||||
else if (path.endsWith("/content")) {
|
||||
downloads.push(url.href);
|
||||
return route.fulfill({ contentType: "image/png", body: image });
|
||||
} else {
|
||||
assert.fail(`Unexpected API request ${method} ${path}`);
|
||||
}
|
||||
await route.fulfill({ json: body });
|
||||
});
|
||||
await context.routeWebSocket("**/api/v1/agent/ws", socket => {
|
||||
live = socket;
|
||||
socket.onMessage(raw => {
|
||||
const event = JSON.parse(String(raw));
|
||||
if (event.type === "auth") {
|
||||
assert.equal(event.token, "lite-agent-fixture-token");
|
||||
socket.send(JSON.stringify({ type: "ready", conversationId: "fixture-room" }));
|
||||
}
|
||||
});
|
||||
});
|
||||
const open = () => page.goto(new URL("/lite?agent=root", target).href, { waitUntil: "networkidle" });
|
||||
|
||||
try {
|
||||
await open();
|
||||
const composer = page.getByRole("textbox", { name: "Message Sybil Agent", exact: true });
|
||||
const send = page.getByRole("button", { name: "Send message", exact: true });
|
||||
await page.getByRole("status").filter({ hasText: /^Connected$/ }).waitFor();
|
||||
assert.equal(await page.getByRole("heading", { level: 1 }).count(), 1);
|
||||
assert.equal(await page.locator(".lite-agent img").count(), 0);
|
||||
assert.deepEqual(downloads, [], "attachments do not download automatically");
|
||||
assert.equal(requests.some(url => /character-|\/assets\/App-/.test(url)), false);
|
||||
assert.equal(requests.some(url => url.includes("never-fetch.invalid")), false);
|
||||
assert.equal(requests.some(url => url.includes("/presence/") || url.includes("/push/")), false, "lite does not start background push sessions");
|
||||
await composer.fill("A draft preserved on reload");
|
||||
await page.reload({ waitUntil: "networkidle" });
|
||||
await composer.waitFor();
|
||||
assert.equal(await composer.inputValue(), "A draft preserved on reload");
|
||||
await composer.fill("Durable message for offline retry");
|
||||
await send.click();
|
||||
await page.getByRole("button", { name: "Retry message", exact: true }).waitFor();
|
||||
assert.equal(await composer.inputValue(), "", "durable outbox owns a failed delivery after local save");
|
||||
assert.equal(submissions.length, 1);
|
||||
assert.match(submissions[0].requestId, /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/);
|
||||
assert.equal(persistedBeforeSend[0][0].requestId, submissions[0].requestId, "retry identity saved before POST");
|
||||
await page.reload({ waitUntil: "networkidle" });
|
||||
await page.getByRole("button", { name: "Retry message", exact: true }).click();
|
||||
await page.waitForFunction(() => document.querySelectorAll(".lite-agent .lite-error").length === 0);
|
||||
assert.equal(submissions.length, 2);
|
||||
assert.equal(submissions[1].requestId, submissions[0].requestId, "reload and retry keep one idempotent delivery identity");
|
||||
assert.equal(await page.locator(`[data-agent-message-id="inbound:sybil:${submissions[0].requestId}"]`).count(), 1);
|
||||
const download = page.waitForEvent("download");
|
||||
await page.getByRole("button", { name: "Download fixture.png", exact: true }).click();
|
||||
assert.equal((await download).suggestedFilename(), "fixture.png");
|
||||
assert.equal(downloads.length, 1);
|
||||
assert.ok(downloads.every(url => !url.includes("token")));
|
||||
assert.equal(await page.locator(".lite-agent img").count(), 0, "explicit download does not add an animated image preview");
|
||||
await page.setViewportSize({ width: 390, height: 844 });
|
||||
await composer.scrollIntoViewIfNeeded();
|
||||
assert.equal(await page.evaluate(() => document.documentElement.scrollWidth > window.innerWidth), false);
|
||||
assert.equal(await page.getByText("Start a conversation with Sybil.", { exact: true }).count(), 0);
|
||||
const ownBubble = page.locator(`[data-agent-message-id="inbound:sybil:${submissions[0].requestId}"] .message-bubble--user`);
|
||||
assert.equal(await ownBubble.count(), 1, "Agent reuses the original user bubble");
|
||||
assert.equal(await ownBubble.evaluate(element => getComputedStyle(element).borderBottomRightRadius), "5px");
|
||||
const viewport = page.viewportSize();
|
||||
const composerBox = await composer.boundingBox();
|
||||
assert.ok(composerBox.y >= 0 && composerBox.y + composerBox.height <= viewport.height, "Agent composer stays in the viewport");
|
||||
const motion = await page.locator(".lite-agent").evaluate(element => [...element.querySelectorAll("*")].some(node => {
|
||||
const style = getComputedStyle(node);
|
||||
return style.animationName !== "none" || (style.transitionDuration !== "0s" && style.transitionDuration !== "0s, 0s");
|
||||
}));
|
||||
assert.equal(motion, false, "Agent presentation has no animations or transitions");
|
||||
if (process.env.LITE_AGENT_SCREENSHOT) await page.screenshot({ path: process.env.LITE_AGENT_SCREENSHOT, fullPage: true });
|
||||
assert.deepEqual(errors, []);
|
||||
console.log("PASS Lite Agent: draft reload, durable failed send/retry, UUID fallback, explicit verified download, no media/push/animations, mobile layout");
|
||||
} finally {
|
||||
await context.close();
|
||||
await browser.close();
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { marked } from "marked";
|
||||
import { installLiteCompatibility } from "../src/lib/lite-compat.ts";
|
||||
|
||||
test("Markdown still renders on readers without native Array.at", () => {
|
||||
const original = Object.getOwnPropertyDescriptor(Array.prototype, "at");
|
||||
try {
|
||||
delete Array.prototype.at;
|
||||
installLiteCompatibility();
|
||||
assert.equal([1, 2, 3].at(-1), 3);
|
||||
assert.equal([1, 2, 3].at(-4), undefined);
|
||||
assert.equal([1, 2, 3].at(Infinity), undefined);
|
||||
assert.equal(Object.getOwnPropertyDescriptor(Array.prototype, "at").enumerable, false);
|
||||
const html = marked("## A reply\n\nFirst paragraph.\n\nSecond paragraph.\n\n| Name | Value |\n| --- | --- |\n| One | Two |");
|
||||
assert.match(html, /<h2>A reply<\/h2>/);
|
||||
assert.match(html, /<table>/);
|
||||
assert.match(html, /<td>Two<\/td>/);
|
||||
} finally {
|
||||
if (original) Object.defineProperty(Array.prototype, "at", original);
|
||||
else delete Array.prototype.at;
|
||||
}
|
||||
});
|
||||
|
||||
test("Lite keeps the browser's existing Array.at implementation", () => {
|
||||
const original = Array.prototype.at;
|
||||
installLiteCompatibility();
|
||||
assert.equal(Array.prototype.at, original);
|
||||
});
|
||||
@@ -0,0 +1,206 @@
|
||||
import assert from "node:assert/strict";
|
||||
|
||||
// All requests are fixtures. Run against a local production preview.
|
||||
const { chromium } = await import(process.env.PLAYWRIGHT_MODULE || "playwright-core");
|
||||
const target = new URL(process.env.WEB_TEST_URL || "http://127.0.0.1:5197/");
|
||||
assert.ok(target.protocol === "http:" && ["127.0.0.1", "localhost", "[::1]"].includes(target.hostname));
|
||||
const browser = await chromium.launch({ executablePath: process.env.CHROME_EXECUTABLE || undefined, headless: true,
|
||||
...(process.env.BROWSER_NO_SANDBOX === "1" ? { args: ["--no-sandbox"] } : {}) });
|
||||
const date = "2026-11-11T12:00:00Z";
|
||||
const message = (id, content) => ({ id, role: "assistant", content, createdAt: date, name: null, metadata: null });
|
||||
const makeChat = (id, title) => ({ id, title, parentChatId: null, titleGenerationPending: false, createdAt: date, updatedAt: date,
|
||||
starred: false, starredAt: null, initiatedProvider: "openai", initiatedModel: "reader", lastUsedProvider: "openai", lastUsedModel: "reader",
|
||||
additionalSystemPrompt: null, enabledTools: [], messages: [message(`${id}-initial`, `${title} initial answer`)] });
|
||||
const waitGate = () => { let release; const promise = new Promise(resolve => { release = resolve; }); return { promise, release }; };
|
||||
async function waitUntil(check) {
|
||||
const deadline = Date.now() + 10000;
|
||||
while (!check()) {
|
||||
assert.ok(Date.now() < deadline, "fixture request arrived before timeout");
|
||||
await new Promise(resolve => setTimeout(resolve, 20));
|
||||
}
|
||||
}
|
||||
|
||||
async function fixture(mode) {
|
||||
const context = await browser.newContext({ viewport: { width: 1100, height: 850 } });
|
||||
const a = makeChat("a", "Conversation A"), b = makeChat("b", "Conversation B");
|
||||
const state = { active: mode.startsWith("attach"), attachCalls: 0, delayedReads: 0, submissions: 0, searchSubmissions: 0,
|
||||
collectionReads: 0, holdB: false, gate: waitGate(), errors: [] };
|
||||
const search = { id: "draft-search", title: "Draft search", query: "draft query", createdAt: date, updatedAt: date,
|
||||
starred: false, starredAt: null, requestId: null, latencyMs: null, error: null, answerText: "Draft search completed",
|
||||
answerRequestId: null, answerCitations: null, answerError: null, results: [] };
|
||||
await context.addInitScript(() => localStorage.setItem("sybil_admin_token", "reader-token"));
|
||||
await context.route("**/*", async route => {
|
||||
const url = new URL(route.request().url());
|
||||
if (url.origin !== target.origin) return route.abort();
|
||||
if (!url.pathname.startsWith("/api/")) return route.continue();
|
||||
const path = url.pathname.slice(4);
|
||||
let body;
|
||||
if (path === "/v1/auth/session") body = { authenticated: true, mode: "token" };
|
||||
else if (path === "/v1/workspace-items") {
|
||||
state.collectionReads += 1;
|
||||
if (mode === "draft-navigation" && state.collectionReads === 1) await state.gate.promise;
|
||||
body = { items: [a, b].map(chat => ({ ...chat, type: "chat" })) };
|
||||
}
|
||||
else if (path === "/v1/models") body = { providers: { openai: { models: ["reader"], loadedAt: date, error: null } } };
|
||||
else if (path === "/v1/active-runs") body = { chats: state.active ? ["a"] : [], searches: [] };
|
||||
else if (path === "/v1/chats/a") body = { chat: a };
|
||||
else if (path === "/v1/chats/b") {
|
||||
if (state.holdB) { state.delayedReads += 1; await state.gate.promise; }
|
||||
body = { chat: b };
|
||||
}
|
||||
else if (path === "/v1/chat-completions/stream") {
|
||||
state.submissions += 1;
|
||||
await state.gate.promise;
|
||||
b.messages.push(message("late-send", "Late reply for conversation B"));
|
||||
return route.fulfill({ contentType: "text/event-stream", body: 'event: done\ndata: {"text":"Late reply for conversation B"}\n\n' }).catch(() => undefined);
|
||||
}
|
||||
else if (path === "/v1/searches" || path === "/v1/searches/draft-search") body = { search };
|
||||
else if (path === "/v1/searches/draft-search/run/stream") {
|
||||
state.searchSubmissions += 1;
|
||||
return route.fulfill({ contentType: "text/event-stream", body: `event: done\ndata: ${JSON.stringify({ search })}\n\n` });
|
||||
}
|
||||
else if (path === "/v1/chats/a/stream/attach") {
|
||||
state.attachCalls += 1;
|
||||
if (mode === "attach-race") {
|
||||
state.active = false; a.messages.push(message("finished", "Completed before attachment"));
|
||||
return route.fulfill({ status: 404, json: { message: "active chat stream not found" } });
|
||||
}
|
||||
if (mode === "attach-retry" && state.attachCalls === 1) {
|
||||
return route.fulfill({ status: 503, json: { message: "Connection is temporarily unavailable" } });
|
||||
}
|
||||
await state.gate.promise;
|
||||
state.active = false; a.messages.push(message("finished", "Recovered completed answer"));
|
||||
return route.fulfill({ contentType: "text/event-stream", body: 'event: done\ndata: {"text":"Recovered completed answer"}\n\n' });
|
||||
}
|
||||
else if (/\/agent\//.test(path)) body = {};
|
||||
else return route.fulfill({ status: 404, json: { message: `Unexpected fixture route ${path}` } });
|
||||
return route.fulfill({ json: body }).catch(() => undefined);
|
||||
});
|
||||
const page = await context.newPage();
|
||||
page.setDefaultTimeout(10000);
|
||||
page.on("pageerror", error => state.errors.push(error.message));
|
||||
await page.goto(new URL(mode === "draft-navigation" ? "/lite" : "/lite?chat=a", target).href);
|
||||
await page.getByRole("heading", { name: mode === "draft-navigation" ? "New chat" : "Conversation A", exact: true }).waitFor();
|
||||
return { context, page, state, a, b };
|
||||
}
|
||||
|
||||
try {
|
||||
{
|
||||
const { context, page, state } = await fixture("attach-success");
|
||||
await page.waitForFunction(() => document.querySelector("#lite-draft")?.disabled === true);
|
||||
await waitUntil(() => state.attachCalls === 1);
|
||||
assert.equal(state.attachCalls, 1);
|
||||
assert.equal(await page.getByRole("button", { name: "Send message", exact: true }).isDisabled(), true);
|
||||
assert.equal(await page.getByText("Recovered completed answer", { exact: true }).count(), 0);
|
||||
state.gate.release();
|
||||
await page.getByText("Recovered completed answer", { exact: true }).waitFor();
|
||||
await page.waitForFunction(() => !document.querySelector("#lite-draft").disabled);
|
||||
assert.deepEqual(state.errors, []);
|
||||
await context.close();
|
||||
}
|
||||
{
|
||||
const { context, page, state } = await fixture("attach-race");
|
||||
await page.getByText("Completed before attachment", { exact: true }).waitFor();
|
||||
await page.waitForFunction(() => !document.querySelector("#lite-draft").disabled);
|
||||
assert.equal(await page.getByRole("alert").count(), 0, "finished attachment race recovers quietly");
|
||||
assert.deepEqual(state.errors, []);
|
||||
await context.close();
|
||||
}
|
||||
{
|
||||
const { context, page, state } = await fixture("attach-retry");
|
||||
await page.getByRole("alert").filter({ hasText: "Connection is temporarily unavailable" }).waitFor();
|
||||
assert.equal(await page.getByRole("button", { name: "Refresh", exact: true }).isEnabled(), true, "remote work cannot disable recovery");
|
||||
assert.equal(await page.getByRole("button", { name: "New chat", exact: true }).isEnabled(), true, "failed attachment cannot trap navigation");
|
||||
state.gate.release();
|
||||
await page.getByRole("button", { name: "Refresh", exact: true }).click();
|
||||
await page.getByText("Recovered completed answer", { exact: true }).waitFor();
|
||||
assert.equal(state.attachCalls, 2);
|
||||
assert.deepEqual(state.errors, []);
|
||||
await context.close();
|
||||
}
|
||||
{
|
||||
const { context, page, state } = await fixture("navigation");
|
||||
await page.getByText("Conversation A initial answer", { exact: true }).waitFor();
|
||||
state.holdB = true;
|
||||
await page.locator(".lite-history-list button").filter({ hasText: "Conversation B" }).click();
|
||||
await page.waitForURL(/chat=b/);
|
||||
await page.waitForFunction(() => document.querySelector(".lite-status")?.textContent === "Loading…");
|
||||
await page.locator(".lite-history-list button").filter({ hasText: "Conversation A" }).click();
|
||||
await page.getByText("Conversation A initial answer", { exact: true }).waitFor();
|
||||
state.gate.release();
|
||||
await page.waitForTimeout(150);
|
||||
assert.equal(await page.getByText("Conversation B initial answer", { exact: true }).count(), 0, "late selection cannot overwrite the current transcript");
|
||||
assert.equal(new URL(page.url()).searchParams.get("chat"), "a");
|
||||
await page.goBack();
|
||||
await page.getByText("Conversation B initial answer", { exact: true }).waitFor();
|
||||
assert.equal(new URL(page.url()).searchParams.get("chat"), "b");
|
||||
assert.deepEqual(state.errors, []);
|
||||
await context.close();
|
||||
}
|
||||
{
|
||||
const { context, page, state } = await fixture("logout");
|
||||
state.holdB = true;
|
||||
await page.locator(".lite-history-list button").filter({ hasText: "Conversation B" }).click();
|
||||
await page.waitForURL(/chat=b/);
|
||||
await page.getByRole("button", { name: "Sign out", exact: true }).click();
|
||||
await page.getByRole("heading", { name: "Sign in to Sybil", exact: true }).waitFor();
|
||||
state.gate.release();
|
||||
await page.waitForTimeout(150);
|
||||
assert.equal(await page.getByText("Conversation B initial answer", { exact: true }).count(), 0, "late authenticated reads cannot repaint after sign out");
|
||||
assert.deepEqual(state.errors, []);
|
||||
await context.close();
|
||||
}
|
||||
{
|
||||
const { context, page, state } = await fixture("back-during-send");
|
||||
await page.locator(".lite-history-list button").filter({ hasText: "Conversation B" }).click();
|
||||
await page.getByText("Conversation B initial answer", { exact: true }).waitFor();
|
||||
await page.getByLabel("Message", { exact: true }).fill("A question only for conversation B");
|
||||
await page.getByRole("button", { name: "Send message", exact: true }).click();
|
||||
await page.waitForFunction(() => document.querySelector("#lite-draft")?.disabled === true);
|
||||
await waitUntil(() => state.submissions === 1);
|
||||
await page.goBack();
|
||||
await page.getByText("Conversation A initial answer", { exact: true }).waitFor();
|
||||
state.gate.release();
|
||||
await page.waitForTimeout(150);
|
||||
assert.equal(await page.getByLabel("Message", { exact: true }).inputValue(), "", "aborted send must not transplant a draft into another conversation");
|
||||
assert.equal(await page.getByText("Late reply for conversation B", { exact: true }).count(), 0);
|
||||
assert.equal(await page.getByText("A question only for conversation B", { exact: true }).count(), 0);
|
||||
assert.deepEqual(state.errors, []);
|
||||
await context.close();
|
||||
}
|
||||
{
|
||||
const { context, page, state, a } = await fixture("model-refresh");
|
||||
await page.getByText("Conversation A initial answer", { exact: true }).waitFor();
|
||||
await page.locator("summary").filter({ hasText: "Settings" }).click();
|
||||
await page.getByLabel("Model", { exact: true }).fill("my-next-model");
|
||||
await page.getByRole("button", { name: "Refresh", exact: true }).click();
|
||||
await page.waitForFunction(() => !document.querySelector("#lite-draft").disabled);
|
||||
assert.equal(await page.getByLabel("Model", { exact: true }).inputValue(), "my-next-model", "refresh preserves an unsent model choice");
|
||||
a.lastUsedModel = "updated-on-another-device";
|
||||
await page.getByRole("button", { name: "Refresh", exact: true }).click();
|
||||
await page.waitForFunction(() => document.querySelector('input[list="lite-model-options"]').value === "updated-on-another-device");
|
||||
await page.locator(".lite-history-list button").filter({ hasText: "Conversation B" }).click();
|
||||
await page.getByText("Conversation B initial answer", { exact: true }).waitFor();
|
||||
assert.equal(await page.getByLabel("Model", { exact: true }).inputValue(), "reader", "switching conversations restores its saved model");
|
||||
assert.deepEqual(state.errors, []);
|
||||
await context.close();
|
||||
}
|
||||
{
|
||||
const { context, page, state } = await fixture("draft-navigation");
|
||||
await waitUntil(() => state.collectionReads === 1);
|
||||
assert.equal(await page.getByLabel("Message", { exact: true }).isDisabled(), true);
|
||||
await page.getByRole("button", { name: "New search", exact: true }).click();
|
||||
await page.getByRole("heading", { name: "New search", exact: true }).waitFor();
|
||||
await waitUntil(() => state.collectionReads >= 2);
|
||||
await page.getByRole("button", { name: "New search", exact: true }).click();
|
||||
state.gate.release();
|
||||
await page.waitForFunction(() => !document.querySelector("#lite-draft").disabled);
|
||||
await page.getByLabel("Search the web", { exact: true }).fill("draft query");
|
||||
await page.getByRole("button", { name: "Search", exact: true }).click();
|
||||
await page.getByText("Draft search completed", { exact: true }).waitFor();
|
||||
assert.equal(state.searchSubmissions, 1);
|
||||
assert.deepEqual(state.errors, []);
|
||||
await context.close();
|
||||
}
|
||||
console.log("Lite recovery browser checks passed: active-stream attachment, completion race, retry, stale navigation, back, sign-out isolation, model selection and repeated draft navigation.");
|
||||
} finally { await browser.close(); }
|
||||
@@ -0,0 +1,194 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { mkdir } from "node:fs/promises";
|
||||
|
||||
// Run against npm run build && npm run preview; all API responses are local fixtures.
|
||||
const { chromium } = await import(process.env.PLAYWRIGHT_MODULE || "playwright-core");
|
||||
const target = new URL(process.env.WEB_TEST_URL || "http://127.0.0.1:5197/");
|
||||
assert.ok(target.protocol === "http:" && ["127.0.0.1", "localhost", "[::1]"].includes(target.hostname));
|
||||
const browser = await chromium.launch({ executablePath: process.env.CHROME_EXECUTABLE || undefined, headless: true,
|
||||
...(process.env.BROWSER_NO_SANDBOX === "1" ? { args: ["--no-sandbox"] } : {}) });
|
||||
const context = await browser.newContext({ viewport: { width: 1100, height: 900 } });
|
||||
const date = "2026-11-11T12:00:00.000Z";
|
||||
const markdown = "A response with **formatted text**.\n\n- First item\n- Second item\n\n| Name | Value |\n| --- | --- |\n| Example | Table content |\n\n```js\nconst longLine = '" + "wide-content-".repeat(35) + "';\n```\n\n";
|
||||
const message = (id, role, content, metadata = null) => ({ id, role, content, createdAt: date, name: null, metadata });
|
||||
const chat = { id: "chat-one", title: "Reader test conversation", parentChatId: null, titleGenerationPending: false,
|
||||
createdAt: date, updatedAt: date, starred: true, starredAt: date, initiatedProvider: "openai", initiatedModel: "reader-model",
|
||||
lastUsedProvider: "openai", lastUsedModel: "reader-model", additionalSystemPrompt: "Keep replies concise", enabledTools: [],
|
||||
messages: [message("user-one", "user", "Show a list, a table, and a code sample."), message("assistant-one", "assistant", markdown, { generation: { provider: "openai", model: "reader-model" } })] };
|
||||
const chats = new Map([[chat.id, chat]]);
|
||||
const searches = new Map();
|
||||
const calls = [], errors = [], requests = [], streamRequests = [];
|
||||
let failFirstStream = true, failNextStream = false;
|
||||
await context.addInitScript(() => {
|
||||
localStorage.setItem("sybil_admin_token", "lite-fixture-token");
|
||||
// Chromium readers can predate this built-in even though they support modules.
|
||||
delete Array.prototype.at;
|
||||
});
|
||||
await context.route("**/*", async route => {
|
||||
const url = new URL(route.request().url());
|
||||
requests.push(url.href);
|
||||
if (url.origin !== target.origin) return route.abort();
|
||||
if (!url.pathname.startsWith("/api/")) return route.continue();
|
||||
const path = url.pathname.slice(4), method = route.request().method();
|
||||
calls.push({ path, method });
|
||||
let body;
|
||||
if (path === "/v1/auth/session") body = { mode: "token", authenticated: true };
|
||||
else if (path === "/v1/workspace-items") {
|
||||
const items = [...chats.values()].map(chat => ({ ...chat, type: "chat" })).concat([...searches.values()].map(search => ({ ...search, type: "search" })));
|
||||
body = { items: url.searchParams.has("q") ? items.filter(item => item.title.includes(url.searchParams.get("q"))) : items, hasMore: false };
|
||||
}
|
||||
else if (path === "/v1/models") body = { providers: { openai: { models: ["reader-model", "another-model"], loadedAt: date, error: null } } };
|
||||
else if (path === "/v1/active-runs") body = { chats: [], searches: [] };
|
||||
else if (path === "/v1/chats" && method === "POST") {
|
||||
const created = { ...chat, id: `chat-${chats.size + 1}`, title: "New conversation", messages: [], starred: false, additionalSystemPrompt: null };
|
||||
chats.set(created.id, created); body = { chat: created };
|
||||
}
|
||||
else if (/^\/v1\/chats\/[^/]+$/.test(path)) body = { chat: chats.get(path.split("/").pop()) };
|
||||
else if (path.includes("/title")) body = { chat };
|
||||
else if (path === "/v1/chat-completions/stream") {
|
||||
const request = route.request().postDataJSON(); streamRequests.push(request);
|
||||
if (failFirstStream) { failFirstStream = false; return route.abort("failed"); }
|
||||
if (failNextStream) { failNextStream = false; return route.fulfill({ status: 503, json: { message: "Model is temporarily unavailable" } }); }
|
||||
assert.ok(request.clientRequestId);
|
||||
const selected = chats.get(request.chatId);
|
||||
const content = request.messages[request.messages.length - 1].content;
|
||||
await new Promise(resolve => setTimeout(resolve, 500));
|
||||
selected.messages.push(message(`user-${streamRequests.length}`, "user", content), message(`assistant-${streamRequests.length}`, "assistant", "The completed answer.", { generation: { provider: request.provider, model: request.model } }));
|
||||
return route.fulfill({ contentType: "text/event-stream", body: 'event: delta\ndata: {"text":"Do not paint partial tokens"}\n\nevent: done\ndata: {"text":"The completed answer."}\n\n' });
|
||||
}
|
||||
else if (path === "/v1/searches" && method === "POST") {
|
||||
const request = route.request().postDataJSON();
|
||||
const search = { id: "search-one", title: request.title, query: request.query, createdAt: date, updatedAt: date, starred: false, starredAt: null,
|
||||
requestId: null, latencyMs: null, error: null, answerText: null, answerRequestId: null, answerCitations: null, answerError: null, results: [] };
|
||||
searches.set(search.id, search); body = { search };
|
||||
}
|
||||
else if (path === "/v1/searches/search-one/run/stream") {
|
||||
const search = searches.get("search-one"); search.answerText = "A useful search answer.";
|
||||
search.results = [{ id: "result", title: "An original source", url: "https://example.test/source", text: "Source description", highlights: [], rank: 1 }];
|
||||
return route.fulfill({ contentType: "text/event-stream", body: `event: done\ndata: ${JSON.stringify({ search })}\n\n` });
|
||||
}
|
||||
else if (path === "/v1/searches/search-one") body = { search: searches.get("search-one") };
|
||||
else return route.fulfill({ status: 404, json: { message: `Unexpected fixture request ${method} ${path}` } });
|
||||
return route.fulfill({ json: body });
|
||||
});
|
||||
const page = await context.newPage();
|
||||
page.on("pageerror", error => errors.push(error.message));
|
||||
page.setDefaultTimeout(10000);
|
||||
async function openSidebar() {
|
||||
const trigger = page.getByRole("button", { name: "Open sidebar", exact: true });
|
||||
if (await trigger.isVisible()) await trigger.click();
|
||||
}
|
||||
async function selectNavigation(name) {
|
||||
await openSidebar();
|
||||
await page.getByRole("button", { name, exact: true }).click();
|
||||
}
|
||||
async function checkComposerLayout(width) {
|
||||
const scroll = page.locator(".lite-scroll");
|
||||
const before = await page.locator(".lite-composer-shell").boundingBox();
|
||||
assert.ok(before.y >= 0 && before.y + before.height <= page.viewportSize().height + 1, `composer visible at ${width}px`);
|
||||
await scroll.evaluate(element => { element.scrollTop = element.scrollHeight; });
|
||||
const after = await page.locator(".lite-composer-shell").boundingBox();
|
||||
assert.equal(after.y, before.y, "scrolling the transcript does not move the composer");
|
||||
await scroll.evaluate(element => { element.scrollTop = 0; });
|
||||
const pageHeight = await page.evaluate(() => ({ height: document.documentElement.scrollHeight, viewport: window.innerHeight }));
|
||||
assert.ok(pageHeight.height <= pageHeight.viewport + 1, `transcript content stays inside its scroller at ${width}px: ${JSON.stringify(pageHeight)}`);
|
||||
}
|
||||
try {
|
||||
await page.goto(new URL("/lite?chat=chat-one", target).href);
|
||||
await page.getByRole("heading", { name: chat.title, exact: true }).waitFor();
|
||||
await page.getByText("First item", { exact: true }).waitFor();
|
||||
assert.equal(await page.getByLabel("Model", { exact: true }).inputValue(), "reader-model");
|
||||
assert.equal(await page.locator(".lite-main img").count(), 0);
|
||||
assert.equal(await page.locator(".md-content table").count(), 1);
|
||||
const visuals = await page.evaluate(() => ({
|
||||
animated: [...document.querySelectorAll("*")].filter(el => getComputedStyle(el).animationName !== "none").length,
|
||||
overflow: document.documentElement.scrollWidth > window.innerWidth,
|
||||
background: getComputedStyle(document.documentElement).backgroundImage,
|
||||
}));
|
||||
assert.equal(visuals.animated, 0); assert.equal(visuals.overflow, false); assert.equal(visuals.background, "none");
|
||||
for (const text of ["What’s on your mind?", "Made for slower screens.", "A little space to think", "Your persistent assistant", "Find something useful", "What would you like to find?", "Clear text.", "Fewer distractions.", "Simple pages.", "Replies appear when complete."]) {
|
||||
assert.equal(await page.getByText(text, { exact: false }).count(), 0, `no added flavor text: ${text}`);
|
||||
}
|
||||
const bubble = await page.locator(".lite-message-user .message-bubble--user").first().evaluate(element => {
|
||||
const style = getComputedStyle(element), box = element.getBoundingClientRect(), row = element.closest(".lite-message").getBoundingClientRect();
|
||||
return { right: box.right, rowRight: row.right, width: box.width, rowWidth: row.width, bottomRightRadius: style.borderBottomRightRadius, background: style.backgroundImage };
|
||||
});
|
||||
assert.ok(Math.abs(bubble.right - bubble.rowRight) <= 1 && bubble.width < bubble.rowWidth, "user bubbles retain original right alignment and width limit");
|
||||
assert.equal(bubble.bottomRightRadius, "5px");
|
||||
assert.equal(bubble.background, "none");
|
||||
assert.equal(await page.locator('[data-assistant-footer="assistant-one"]').getByRole("button", { name: "Copy message", exact: true }).count(), 1);
|
||||
await checkComposerLayout(1100);
|
||||
if (process.env.LITE_ARTIFACT_DIR) {
|
||||
await mkdir(process.env.LITE_ARTIFACT_DIR, { recursive: true });
|
||||
await page.screenshot({ path: `${process.env.LITE_ARTIFACT_DIR}/lite-desktop.png`, fullPage: true });
|
||||
}
|
||||
// Selecting the current row must retain its loaded transcript.
|
||||
await page.locator(".lite-history-list button").filter({ hasText: chat.title }).click();
|
||||
await page.getByText("First item", { exact: true }).waitFor();
|
||||
await page.getByLabel("Message", { exact: true }).fill("A follow-up question");
|
||||
await page.getByRole("button", { name: "Send message", exact: true }).click();
|
||||
await page.getByText("The completed answer.", { exact: true }).waitFor();
|
||||
assert.equal(await page.getByLabel("Message", { exact: true }).inputValue(), "");
|
||||
assert.equal(await page.getByText("Do not paint partial tokens", { exact: true }).count(), 0);
|
||||
assert.equal(streamRequests.length, 2);
|
||||
assert.equal(streamRequests[0].clientRequestId, streamRequests[1].clientRequestId, "transport retry reuses submission ID");
|
||||
assert.deepEqual(streamRequests[0].messages, streamRequests[1].messages);
|
||||
|
||||
failNextStream = true;
|
||||
await page.getByLabel("Message", { exact: true }).fill("Preserve this draft");
|
||||
await page.getByRole("button", { name: "Send message", exact: true }).click();
|
||||
await page.getByRole("alert").filter({ hasText: "Model is temporarily unavailable" }).waitFor();
|
||||
assert.equal(await page.getByLabel("Message", { exact: true }).inputValue(), "Preserve this draft");
|
||||
const failedRequest = streamRequests[streamRequests.length - 1];
|
||||
await page.getByRole("button", { name: "Send message", exact: true }).click();
|
||||
await page.waitForFunction(() => document.querySelector("#lite-draft").value === "");
|
||||
assert.equal(streamRequests[streamRequests.length - 1].clientRequestId, failedRequest.clientRequestId);
|
||||
|
||||
for (const width of [320, 390, 600]) {
|
||||
await page.setViewportSize({ width, height: 844 });
|
||||
assert.equal(await page.evaluate(() => document.documentElement.scrollWidth > window.innerWidth), false, `no overflow at ${width}px`);
|
||||
await checkComposerLayout(width);
|
||||
await openSidebar();
|
||||
await page.getByLabel("Search history", { exact: true }).fill("Reader");
|
||||
const row = page.locator(".lite-history-list button").filter({ hasText: chat.title });
|
||||
await row.waitFor();
|
||||
await row.click();
|
||||
assert.equal(await page.getByRole("button", { name: "Open sidebar", exact: true }).getAttribute("aria-expanded"), "false");
|
||||
assert.equal(await page.locator(".lite-sidebar").evaluate(element => getComputedStyle(element).transitionDuration), "0s");
|
||||
if (process.env.LITE_ARTIFACT_DIR) await page.screenshot({ path: `${process.env.LITE_ARTIFACT_DIR}/lite-${width}.png`, fullPage: true });
|
||||
}
|
||||
|
||||
await selectNavigation("New chat");
|
||||
await page.getByRole("heading", { name: "New chat", exact: true }).waitFor();
|
||||
await page.waitForFunction(() => !document.querySelector("#lite-draft").disabled);
|
||||
assert.equal(await page.locator(".lite-scroll").textContent(), "", "new chats have an empty transcript without welcome copy");
|
||||
await page.getByLabel("Message", { exact: true }).fill("An unsent draft");
|
||||
await selectNavigation("New chat");
|
||||
assert.equal(await page.getByLabel("Message", { exact: true }).inputValue(), "");
|
||||
await page.getByLabel("Message", { exact: true }).fill("Start a new conversation");
|
||||
await page.getByRole("button", { name: "Send message", exact: true }).click();
|
||||
await page.getByText("The completed answer.", { exact: true }).waitFor();
|
||||
assert.ok(new URL(page.url()).searchParams.get("chat"));
|
||||
await selectNavigation("New search");
|
||||
await page.getByLabel("Search the web", { exact: true }).fill("e-ink reading");
|
||||
await page.getByRole("button", { name: "Search", exact: true }).click();
|
||||
await page.getByText("A useful search answer.", { exact: true }).waitFor();
|
||||
assert.equal(await page.getByRole("link", { name: "An original source" }).getAttribute("href"), "https://example.test/source");
|
||||
assert.equal(new URL(page.url()).searchParams.get("search"), "search-one");
|
||||
|
||||
assert.deepEqual(errors, []);
|
||||
assert.equal(requests.some(url => /character-|\/assets\/App-/.test(url)), false);
|
||||
assert.equal(await page.evaluate(() => Array.from(document.styleSheets).filter(sheet => !sheet.href || new URL(sheet.href).origin === location.origin)
|
||||
.some(sheet => Array.from(sheet.cssRules).some(rule => rule.cssText.includes(".tool-call-stack-shell")))), false, "full animation styles are not loaded");
|
||||
assert.equal(calls.some(call => /\/agent\//.test(call.path)), false, "chat/search does not open Agent or presence polling");
|
||||
console.log("Lite workspace browser checks passed: original bubbles/footer, no flavor text, fixed composer, chat/retry, history/search, mobile sidebar and isolated assets.");
|
||||
} catch (error) {
|
||||
console.error("Workspace fixture state", { ...(await page.evaluate(() => ({
|
||||
url: location.href, draft: document.querySelector("#lite-draft")?.value,
|
||||
disabled: document.querySelector("#lite-draft")?.disabled,
|
||||
title: document.querySelector("main h1")?.textContent,
|
||||
statuses: [...document.querySelectorAll('[role="status"]')].map(element => element.textContent),
|
||||
alerts: [...document.querySelectorAll('[role="alert"]')].map(element => element.textContent),
|
||||
}))), pageErrors: errors, streams: streamRequests.length, recentCalls: calls.slice(-12) });
|
||||
throw error;
|
||||
} finally { await browser.close(); }
|
||||
@@ -0,0 +1,100 @@
|
||||
import assert from "node:assert/strict";
|
||||
|
||||
// Run against a production preview; requests to the backend are mocked.
|
||||
// WEB_TEST_URL=http://127.0.0.1:5197 PLAYWRIGHT_MODULE=/path/to/playwright-core/index.mjs
|
||||
// CHROME_EXECUTABLE=/path/to/chrome node tests/ui-mode.browser.mjs
|
||||
const { chromium } = await import(process.env.PLAYWRIGHT_MODULE || "playwright-core");
|
||||
const target = new URL(process.env.WEB_TEST_URL || "http://127.0.0.1:5197/");
|
||||
assert.ok(target.protocol === "http:" && ["127.0.0.1", "localhost", "[::1]"].includes(target.hostname));
|
||||
const browser = await chromium.launch({
|
||||
executablePath: process.env.CHROME_EXECUTABLE || undefined,
|
||||
headless: true,
|
||||
...(process.env.BROWSER_NO_SANDBOX === "1" ? { args: ["--no-sandbox"] } : {}),
|
||||
});
|
||||
const kindle = "Mozilla/5.0 (X11; Linux armv7l) AppleWebKit/537.36 Chrome/87.0 Safari/537.36 Kindle/3.0";
|
||||
|
||||
async function fixture(options = {}) {
|
||||
const context = await browser.newContext({ viewport: { width: 600, height: 800 }, serviceWorkers: "block", ...options });
|
||||
const requests = [], errors = [];
|
||||
await context.route("**/*", async route => {
|
||||
const url = new URL(route.request().url());
|
||||
requests.push(url);
|
||||
if (url.origin !== target.origin) return route.abort();
|
||||
if (url.pathname.endsWith("/v1/auth/session")) {
|
||||
return route.fulfill({ status: 401, json: { message: "missing bearer token" } });
|
||||
}
|
||||
if (url.pathname.includes("/api/")) return route.fulfill({ json: {} });
|
||||
return route.continue();
|
||||
});
|
||||
const page = await context.newPage();
|
||||
page.on("pageerror", error => errors.push(error.message));
|
||||
const visit = async path => {
|
||||
requests.length = 0;
|
||||
await Promise.all([
|
||||
page.waitForResponse(response => response.url().endsWith("/v1/auth/session")),
|
||||
page.goto(new URL(path, target).href, { waitUntil: "networkidle" }),
|
||||
]);
|
||||
await page.locator('input[type="password"]').waitFor();
|
||||
};
|
||||
return { context, page, requests, errors, visit };
|
||||
}
|
||||
|
||||
try {
|
||||
const reader = await fixture({ userAgent: kindle });
|
||||
await reader.visit("/?chat=keep-this#reply");
|
||||
assert.equal(new URL(reader.page.url()).pathname, "/lite");
|
||||
assert.equal(new URL(reader.page.url()).search, "?chat=keep-this");
|
||||
assert.equal(new URL(reader.page.url()).hash, "#reply");
|
||||
const styles = await reader.page.evaluate(() => Array.from(document.styleSheets).map(sheet => sheet.href));
|
||||
assert.ok(styles.some(href => href && /lite.*\.css/.test(href)), "Lite has its own stylesheet");
|
||||
assert.ok(reader.requests.every(url => !/character-.*\.(gif|png)|\/App-[^/]+\.js|agent-conversation/.test(url.href)), "Lite does not download full presentation assets");
|
||||
assert.equal(await reader.page.locator(".lite-auth").evaluate(element => getComputedStyle(element).backgroundImage), "none");
|
||||
const liteTypography = await reader.page.evaluate(() => ({
|
||||
body: getComputedStyle(document.body).fontFamily,
|
||||
wordmark: getComputedStyle(document.querySelector(".sybil-wordmark")).fontFamily,
|
||||
}));
|
||||
assert.ok(reader.requests.some(url => url.hostname === "fonts.googleapis.com"), "both presentations request the existing font stylesheet");
|
||||
for (const text of ["A quieter workspace", "Simple pages.", "Clear text.", "No animations."]) {
|
||||
assert.equal(await reader.page.getByText(text, { exact: false }).count(), 0, `no added sign-in flavor text: ${text}`);
|
||||
}
|
||||
assert.equal(await reader.page.locator('meta[name="viewport"]').getAttribute("content"), "width=device-width, initial-scale=1, viewport-fit=cover");
|
||||
|
||||
await reader.visit("/?ui=full&chat=keep-this");
|
||||
assert.equal(new URL(reader.page.url()).pathname, "/");
|
||||
assert.deepEqual(await reader.page.evaluate(() => ({
|
||||
body: getComputedStyle(document.body).fontFamily,
|
||||
wordmark: getComputedStyle(document.querySelector(".sybil-wordmark")).fontFamily,
|
||||
})), liteTypography, "Lite preserves the original body and wordmark typefaces");
|
||||
assert.equal(await reader.page.evaluate(() => localStorage.getItem("sybil:ui-mode")), "full");
|
||||
await reader.visit("/");
|
||||
assert.equal(new URL(reader.page.url()).pathname, "/", "stored full choice wins over Kindle hint");
|
||||
await reader.visit("/lite?ui=lite");
|
||||
await reader.visit("/");
|
||||
assert.equal(new URL(reader.page.url()).pathname, "/lite", "explicit Lite choice persists");
|
||||
assert.deepEqual(reader.errors, []);
|
||||
await reader.context.close();
|
||||
|
||||
const dataSaver = await fixture();
|
||||
await dataSaver.context.addInitScript(() => Object.defineProperty(navigator, "connection", { value: { saveData: true } }));
|
||||
await dataSaver.visit("/");
|
||||
assert.equal(new URL(dataSaver.page.url()).pathname, "/lite");
|
||||
assert.deepEqual(dataSaver.errors, []);
|
||||
await dataSaver.context.close();
|
||||
|
||||
const blocked = await fixture();
|
||||
await blocked.context.addInitScript(() => Object.defineProperty(window, "localStorage", { get() { throw new Error("Storage denied"); } }));
|
||||
await blocked.visit("/?ui=lite");
|
||||
assert.equal(new URL(blocked.page.url()).pathname, "/lite");
|
||||
assert.deepEqual(blocked.errors, [], "denied storage does not prevent sign in");
|
||||
await blocked.context.close();
|
||||
|
||||
const failed = await fixture();
|
||||
await failed.context.route("**/assets/lite-route-page-*.js", route => route.abort());
|
||||
await failed.page.goto(new URL("/lite", target).href);
|
||||
await failed.page.getByRole("heading", { name: "Sybil could not load" }).waitFor();
|
||||
assert.equal(await failed.page.getByRole("button", { name: "Reload" }).count(), 1);
|
||||
await failed.context.close();
|
||||
console.log("UI routing, preference persistence, denied storage, isolated Lite assets and route failure recovery passed.");
|
||||
} finally {
|
||||
await browser.close();
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import {
|
||||
UI_MODE_STORAGE_KEY,
|
||||
buildUiModeUrl,
|
||||
persistUiModePreference,
|
||||
prefersLiteUi,
|
||||
readUiModePreference,
|
||||
resolveUiRoute,
|
||||
} from "../src/lib/ui-mode.ts";
|
||||
|
||||
const location = (path = "/") => new URL(path, "https://sybil.test");
|
||||
const reader = { userAgent: "Mozilla/5.0 (X11; Linux armv7l) AppleWebKit/531.2 Kindle/3.0" };
|
||||
|
||||
test("clear reader tokens and explicit data saving select Lite without treating all mobile devices as readers", () => {
|
||||
assert.equal(prefersLiteUi(reader), true);
|
||||
assert.equal(prefersLiteUi({ userAgent: "Kobo Touch" }), true);
|
||||
assert.equal(prefersLiteUi({ userAgent: "PocketBook/1.0" }), true);
|
||||
assert.equal(prefersLiteUi({ userAgent: "Mozilla/5.0 Silk/44.1 like Chrome/44.0" }), false);
|
||||
assert.equal(prefersLiteUi({ userAgent: "Mozilla/5.0 Kindle Fire Build/ABC" }), false);
|
||||
assert.equal(prefersLiteUi({ userAgent: "Mozilla/5.0 iPhone Mobile Safari" }), false);
|
||||
assert.equal(prefersLiteUi({ userAgent: "Mozilla/5.0 Android Mobile Chrome/140" }), false);
|
||||
assert.equal(prefersLiteUi({ saveData: true }), true);
|
||||
assert.equal(prefersLiteUi({}), false);
|
||||
});
|
||||
|
||||
test("automatic routing preserves deep links and hashes and only applies at the workspace entry", () => {
|
||||
assert.deepEqual(resolveUiRoute(location("/?chat=abc&extra=value#reply"), reader, null), {
|
||||
mode: "lite", url: "/lite?chat=abc&extra=value#reply", preference: null,
|
||||
});
|
||||
assert.equal(resolveUiRoute(location("/?agent=root"), reader, null).url, "/lite?agent=root");
|
||||
assert.equal(resolveUiRoute(location("/search?q=eink"), reader, "lite").url, "/search?q=eink");
|
||||
assert.equal(resolveUiRoute(location("/other"), reader, "lite").url, "/other");
|
||||
});
|
||||
|
||||
test("explicit preference wins over detection and storage; a direct Lite visit wins over stored full", () => {
|
||||
assert.deepEqual(resolveUiRoute(location("/?ui=full&chat=a"), reader, "lite"), {
|
||||
mode: "full", url: "/?ui=full&chat=a", preference: "full",
|
||||
});
|
||||
assert.equal(resolveUiRoute(location("/?ui=lite"), {}, "full").url, "/lite?ui=lite");
|
||||
assert.equal(resolveUiRoute(location("/lite?ui=full&chat=a"), reader, "lite").url, "/?ui=full&chat=a");
|
||||
assert.equal(resolveUiRoute(location("/lite/"), {}, "full").url, "/lite");
|
||||
assert.equal(resolveUiRoute(location("/"), {}, "lite").url, "/lite");
|
||||
assert.equal(resolveUiRoute(location("/"), reader, "full").url, "/");
|
||||
assert.equal(resolveUiRoute(location("/?ui=invalid"), {}, null).url, "/?ui=invalid");
|
||||
});
|
||||
|
||||
test("manual mode links preserve workspace selection, standalone query and hash", () => {
|
||||
assert.equal(buildUiModeUrl("lite", location("/?chat=abc&ui=full#reply")), "/lite?chat=abc&ui=lite#reply");
|
||||
assert.equal(buildUiModeUrl("full", location("/lite?search=abc&ui=lite")), "/?search=abc&ui=full");
|
||||
assert.equal(buildUiModeUrl("lite", location("/search?q=black+tea")), "/lite?q=black+tea&ui=lite");
|
||||
assert.equal(buildUiModeUrl("full", location("/lite?q=black+tea")), "/search?q=black+tea&ui=full");
|
||||
assert.equal(buildUiModeUrl("full", location("/lite?q=old&chat=current")), "/?q=old&chat=current&ui=full");
|
||||
assert.equal(resolveUiRoute(location("/lite?q=black+tea&ui=full"), {}, null).url, "/search?q=black+tea&ui=full");
|
||||
});
|
||||
|
||||
test("mode preference survives visits but denied or malformed storage cannot block startup", () => {
|
||||
const values = new Map();
|
||||
const storage = { getItem: key => values.get(key) ?? null, setItem: (key, value) => values.set(key, value) };
|
||||
assert.equal(readUiModePreference(storage), null);
|
||||
persistUiModePreference(storage, "lite");
|
||||
assert.equal(readUiModePreference(storage), "lite");
|
||||
values.set(UI_MODE_STORAGE_KEY, "unknown");
|
||||
assert.equal(readUiModePreference(storage), null);
|
||||
const blocked = { getItem() { throw new Error("denied"); }, setItem() { throw new Error("denied"); } };
|
||||
assert.equal(readUiModePreference(blocked), null);
|
||||
assert.doesNotThrow(() => persistUiModePreference(blocked, "full"));
|
||||
assert.equal(readUiModePreference(null), null);
|
||||
assert.doesNotThrow(() => persistUiModePreference(null, "lite"));
|
||||
});
|
||||
@@ -0,0 +1,65 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import {
|
||||
buildCompletionMessages, buildWorkspaceUrl, getModelOptions, getVisibleProviders,
|
||||
hasNewPersistedUserMessage, loadStoredModelPreferences, normalizeStoredModelPreferences,
|
||||
pickProviderModel, readSidebarSelectionFromUrl, saveModelPreferences,
|
||||
} from "../src/lib/workspace-domain.ts";
|
||||
|
||||
const attachment = { kind: "text", id: "notes", filename: "notes.txt", mimeType: "text/plain", sizeBytes: 4, text: "plan", truncated: false };
|
||||
const message = (id, role, content, metadata = null) => ({ id, role, content, metadata, createdAt: "2026-01-01T00:00:00Z", name: null });
|
||||
|
||||
test("both presentations submit provider history without UI tool logs and preserve attachments", () => {
|
||||
const history = [
|
||||
message("s", "system", "Be concise"),
|
||||
message("u", "user", "Read my notes", { attachments: [attachment] }),
|
||||
message("log", "tool", "Searching the web", { kind: "tool_call", toolCallId: "call-1" }),
|
||||
{ ...message("tool", "tool", "Provider tool result"), name: "web_search" },
|
||||
message("a", "assistant", "Here is the plan"),
|
||||
];
|
||||
const payload = buildCompletionMessages(history, "Continue", [attachment]);
|
||||
assert.deepEqual(payload.map(entry => entry.role), ["system", "user", "tool", "assistant", "user"]);
|
||||
assert.ok(!payload.some(entry => entry.id === "log"));
|
||||
assert.deepEqual(payload[1].attachments, [attachment]);
|
||||
assert.equal(payload[2].name, "web_search");
|
||||
assert.deepEqual(payload.at(-1), { role: "user", content: "Continue", attachments: [attachment] });
|
||||
assert.equal(history.length, 5);
|
||||
});
|
||||
|
||||
test("reconciliation recognizes only a new matching persisted user turn", () => {
|
||||
const old = message("old", "user", "Continue");
|
||||
const next = message("next", "user", "Continue", { attachments: [attachment] });
|
||||
const chat = { messages: [old, next] };
|
||||
assert.equal(hasNewPersistedUserMessage(chat, new Set(["old"]), "Continue", [attachment]), true);
|
||||
assert.equal(hasNewPersistedUserMessage(chat, new Set(["old", "next"]), "Continue", [attachment]), false);
|
||||
assert.equal(hasNewPersistedUserMessage(chat, new Set(["old"]), "Continue", []), false);
|
||||
assert.equal(hasNewPersistedUserMessage(chat, new Set(["old"]), "Different", [attachment]), false);
|
||||
});
|
||||
|
||||
test("model policy preserves custom selections and uses advertised provider models", () => {
|
||||
const catalog = { openai: { models: ["server-model"] }, "hermes-agent": { models: ["hermes"] } };
|
||||
assert.deepEqual(getModelOptions(catalog, "openai"), ["server-model"]);
|
||||
assert.equal(pickProviderModel(["server-model"], " custom-model "), "custom-model");
|
||||
assert.equal(pickProviderModel(["server-model"], null), "server-model");
|
||||
assert.ok(getVisibleProviders(catalog).includes("hermes-agent"));
|
||||
assert.ok(!getVisibleProviders({}).includes("hermes-agent"));
|
||||
assert.equal(normalizeStoredModelPreferences({ openai: " x ", xai: 123 }).openai, "x");
|
||||
assert.equal(normalizeStoredModelPreferences({ xai: 123 }).xai, null);
|
||||
});
|
||||
|
||||
test("selection URLs preserve interface choice and hash without stale selections", () => {
|
||||
globalThis.window = { location: { pathname: "/lite", search: "?ui=lite&chat=old&search=stale", hash: "#reply" } };
|
||||
try {
|
||||
assert.deepEqual(readSidebarSelectionFromUrl(), { kind: "chat", id: "old" });
|
||||
assert.equal(buildWorkspaceUrl({ kind: "agent", id: "root" }), "/lite?ui=lite&agent=root#reply");
|
||||
assert.equal(buildWorkspaceUrl(null), "/lite?ui=lite#reply");
|
||||
} finally { delete globalThis.window; }
|
||||
});
|
||||
|
||||
test("blocked storage does not prevent reading defaults or using model controls", () => {
|
||||
globalThis.window = { get localStorage() { throw new Error("Storage unavailable"); } };
|
||||
try {
|
||||
assert.equal(loadStoredModelPreferences().openai, null);
|
||||
assert.doesNotThrow(() => saveModelPreferences(normalizeStoredModelPreferences({ openai: "x" })));
|
||||
} finally { delete globalThis.window; }
|
||||
});
|
||||
Reference in New Issue
Block a user