Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
208 changes: 208 additions & 0 deletions browser-tests/sight-singing-continuity.test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,208 @@
import assert from "node:assert/strict";
import test from "node:test";
import { mkdtemp, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { chromium, expect } from "@playwright/test";
import { startStorageFixture } from "./storage-fixture.mjs";
import { practiceWave } from "../visual-report/practice-fixture.mjs";

const xml = `<score-partwise version="4.0"><part-list><score-part id="P1"><part-name>Alto</part-name></score-part></part-list>
<part id="P1"><measure number="1"><attributes><divisions>1</divisions><time><beats>4</beats><beat-type>4</beat-type></time>
<clef><sign>G</sign><line>2</line></clef></attributes><note><pitch><step>A</step><octave>3</octave></pitch>
<duration>4</duration><type>whole</type></note></measure></part></score-partwise>`;
const title = "弱网回归练习";
const noConnection = "暂时无法连接,已保存的内容仍然保留。";

async function holdNextRead(t, page, url) {
const snapshot = Promise.withResolvers();
const release = Promise.withResolvers();
let held = false;
t.after(() => release.resolve());
await page.route(url, async route => {
if (held || route.request().method() !== "GET") return route.fallback();
held = true;
const response = await route.fetch();
assert.equal(response.status(), 200);
snapshot.resolve(await response.json());
await release.promise;
await route.fulfill({ response }).catch(() => undefined);
});
return { snapshot: snapshot.promise, release: release.resolve };
}

test("a loaded sight-singing question survives offline and a failed identity refresh", { timeout: 90_000 }, async t => {
const fixture = await startStorageFixture({ authenticated: true, previewEntry: false });
let browser;
t.after(async () => { try { await browser?.close(); } finally { await fixture.stop(); } });
const directory = await mkdtemp(join(tmpdir(), "sight-singing-continuity-"));
t.after(() => rm(directory, { recursive: true, force: true }));
const tone = join(directory, "sight-singing-a3.wav");
await writeFile(tone, practiceWave());
browser = await chromium.launch({ args: ["--use-fake-device-for-media-stream", "--use-fake-ui-for-media-stream", `--use-file-for-fake-audio-capture=${tone}`] });
const context = await browser.newContext({ locale: "zh-CN", viewport: { width: 1024, height: 768 }, serviceWorkers: "allow" });
const owner = fixture.accounts[0];
const drive = `${fixture.origin}/choirs/${fixture.choirId}`;
const challengeApi = `${fixture.origin}/api/choirs/${fixture.choirId}/sight-singing`;
const questions = `${challengeApi}/questions`;
const question = `${questions}/${crypto.randomUUID()}`;
assert.equal((await context.request.post(`${fixture.origin}/api/auth/sign-in/email`, {
headers: { origin: fixture.origin }, data: { email: owner.email, password: owner.password },
})).status(), 200);
const seed = await context.request.put(question, {
headers: { "x-same-page-owner-user-id": owner.id },
multipart: {
fields: JSON.stringify({ title, first: 0, last: 0, expectedVersion: null }),
file: { name: "challenge.musicxml", mimeType: "application/vnd.recordare.musicxml+xml", buffer: Buffer.from(xml) },
},
});
assert.equal(seed.status(), 200, await seed.text());

const page = await context.newPage();
await page.goto(drive);
await page.evaluate(() => navigator.serviceWorker.ready.then(() => undefined));
// An installed shell may leave its first tab uncontrolled until navigation.
// Exercise a running shell whose precached worklet and soundfont can be read.
await page.reload();
assert.equal(await page.evaluate(() => Boolean(navigator.serviceWorker.controller)), true);
await page.getByRole("button", { name: "我的", exact: true }).click();
await page.getByRole("menuitem", { name: "视唱挑战", exact: true }).click();
await page.getByRole("button", { name: new RegExp(title) }).click();
const heading = page.getByRole("heading", { name: title, exact: true });
await expect(heading).toBeVisible();
const run = page.locator(".challenge-run");
await expect(run).toHaveAttribute("data-phase", "idle");

let publications = 0;
page.on("request", request => {
if (request.url() === `${question}/results` && request.method() === "POST") publications++;
});
await page.getByRole("button", { name: "开始唱", exact: true }).click();
await expect(run).toHaveAttribute("data-phase", "count");
await context.setOffline(true);
await expect(heading).toBeVisible();
await expect(run).toHaveAttribute("data-phase", "result", { timeout: 12_000 });
await expect(page.getByRole("alert").filter({ hasText: "成绩保存或发布失败。" })).toBeVisible();
await expect(page.locator(".challenge-replay-controls audio")).toHaveAttribute("src", /^blob:/);
await page.getByRole("button", { name: "回听演唱与钢琴答案", exact: true }).click();
await expect(run).toHaveAttribute("data-replaying", "true");
assert.equal(publications, 0);

let sessionDown = true;
await page.route("**/api/auth/get-session*", route => sessionDown
? route.fulfill({ status: 503, json: { message: "unavailable" } }) : route.continue());
const failedSession = page.waitForResponse(response => response.url().includes("/api/auth/get-session") && response.status() === 503);
await context.setOffline(false);
await failedSession;
await expect(run).toHaveAttribute("data-phase", "result");
await page.getByRole("button", { name: "再试一次", exact: true }).click();
await expect(run).toHaveAttribute("data-phase", "idle");
await page.getByRole("button", { name: "编辑题目", exact: true }).click();
const name = page.locator("input[name='title']");
await name.fill("保留未发布的题目名称");
const publish = page.getByRole("button", { name: "更新云盘题目", exact: true });
await expect(publish).toBeDisabled();
await expect(page.getByRole("status").filter({ hasText: noConnection })).toBeVisible();
// Hold the recovery read, then deliver a definitive denial to that same
// request. A focus event could legally coalesce with a read already running.
const revalidation = Promise.withResolvers();
await page.route(questions, async route => {
await revalidation.promise;
await route.fulfill({ status: 403, json: { error: "permission_denied" } });
});
t.after(() => revalidation.resolve());
sessionDown = false;
await page.getByRole("button", { name: "重试连接", exact: true }).click();
await expect(publish).toBeEnabled({ timeout: 12_000 });
await expect(name).toHaveValue("保留未发布的题目名称");
assert.equal(publications, 0);

revalidation.resolve();
await expect(page.getByText("视唱挑战仅对当前云盘成员开放。", { exact: true })).toBeVisible();
await expect(name).toHaveCount(0);
await page.unroute(questions);

// A fresh page with the same locally remembered owner cannot read the last
// question or infer membership without a successful remote response.
await context.setOffline(true);
const cold = await context.newPage();
await cold.goto(`${drive}/sight-singing`);
await expect(cold.getByRole("status").filter({ hasText: noConnection })).toBeVisible();
await expect(cold.getByRole("button", { name: new RegExp(title) })).toHaveCount(0);

const coldRead = Promise.withResolvers();
t.after(() => coldRead.resolve());
await cold.route(questions, async route => {
await coldRead.promise;
await route.fulfill({ status: 503, json: { error: "unavailable" } });
});
const read = cold.waitForRequest(questions);
await context.setOffline(false);
await read;
await expect(cold.getByText("正在读取…", { exact: true })).toBeVisible();
await expect(cold.getByText("这个云盘还没有已发布的题目。")).toHaveCount(0);
coldRead.resolve();
const unavailable = cold.getByRole("status").filter({ hasText: "无法加载云盘题目。" });
await expect(unavailable).toBeVisible();
await cold.unroute(questions);
await unavailable.getByRole("button", { name: "重新加载", exact: true }).click();
await expect(cold.getByRole("button", { name: new RegExp(title) })).toBeVisible();

await cold.getByRole("button", { name: new RegExp(title) }).click();
const resultsUrl = `${question}/results`;
const filteredUrl = `${resultsUrl}?speed=1`;
const posting = Promise.withResolvers();
const releasePost = Promise.withResolvers();
t.after(() => releasePost.resolve());
await cold.route(resultsUrl, async route => {
if (route.request().method() === "POST") {
posting.resolve();
await releasePost.promise;
}
await route.continue();
});
const oldResults = await holdNextRead(t, cold, filteredUrl);
await cold.getByRole("button", { name: "开始唱", exact: true }).click();
await posting.promise;
await cold.getByRole("button", { name: "最佳成绩", exact: true }).click();
const resultsPanel = cold.getByRole("dialog", { name: "最佳成绩", exact: true });
await resultsPanel.getByLabel("成绩速度").selectOption("1");
assert.deepEqual((await oldResults.snapshot).results, []);
const boardUrl = `${challengeApi}/leaderboard`;
const oldBoard = await holdNextRead(t, cold, boardUrl);

// The filtered GET captured the old server rows. A post-write GET must
// complete even while that pre-write response is still held.
const freshResults = cold.waitForResponse(filteredUrl, { timeout: 5_000 });
releasePost.resolve();
await expect(cold.getByRole("dialog", { name: "本次视唱", exact: true })).toBeVisible();
assert.equal((await (await freshResults).json()).results.length, 1);
oldResults.release();
await cold.getByRole("button", { name: "查看谱面", exact: true }).click();
const ownScore = resultsPanel.locator("li[data-own='true']");
await expect(ownScore).toHaveCount(1);
await expect(resultsPanel.getByLabel("成绩速度")).toHaveValue("1");

// Publication refreshed the board too. Hold that snapshot across withdrawal.
assert.equal((await oldBoard.snapshot).results.length, 1);
await ownScore.locator(".challenge-score-menu-trigger").click({ button: "right" });
await cold.getByRole("menuitem", { name: "撤下成绩", exact: true }).click();
const freshBoard = cold.waitForResponse(boardUrl, { timeout: 5_000 });
await cold.getByRole("dialog", { name: "撤下成绩", exact: true })
.getByRole("button", { name: "撤下成绩", exact: true }).click();
assert.deepEqual((await (await freshBoard).json()).results, []);
oldBoard.release();
await expect(resultsPanel.getByText("当前筛选下暂无成绩。")).toBeVisible();
await expect(resultsPanel.getByLabel("成绩速度")).toHaveValue("1");
await resultsPanel.getByRole("button", { name: "关闭", exact: true }).click();
await cold.getByRole("button", { name: "再试一次", exact: true }).click();

// Result publication has the same membership requirement as the GETs. A
// denial received from the write also closes a previously authorized view.
await cold.unroute(resultsUrl);
await cold.route(resultsUrl, route => route.request().method() === "POST"
? route.fulfill({ status: 403, json: { error: "permission_denied" } }) : route.continue());
await cold.getByRole("button", { name: "开始唱", exact: true }).click();
await expect(cold.getByText("视唱挑战仅对当前云盘成员开放。", { exact: true })).toBeVisible({ timeout: 12_000 });
await expect(cold.locator(".challenge-run")).toHaveCount(0);
});
16 changes: 16 additions & 0 deletions src/client/auth/application-identity.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,22 @@ it("retains the displayed owner through a session failure while local identity r
expect(result.current.authenticatedUserId).toBe("another-owner");
});

it("treats a forbidden session read as a definitive cloud denial", async () => {
const previous = { ...state };
state.owner = Promise.resolve("user:owner" as LocalWorkspaceOwnerKey);
state.data = null;
state.error = { status: 403 };
const { result, unmount } = renderHook(() => useApplicationIdentity());
try {
await waitFor(() => expect(result.current.localUserId).toBe("owner"));
expect(result.current.onlineState).toBe("signed-out");
expect(result.current.authenticatedSessionId).toBeNull();
} finally {
unmount();
Object.assign(state, previous);
}
});

it("distinguishes cold local-owner waiting from the same page after an online identity has warmed it", async () => {
const { useReaderWorkspace } = await import("../reader/use-reader-workspace");
const { activateAuthenticatedLocalOwner } = await import("../platform/local-workspace");
Expand Down
10 changes: 9 additions & 1 deletion src/client/auth/application-identity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ export function useApplicationIdentity() {
const session = blocked && !fence!.pending ? { ...remoteSession, data: null } : remoteSession;
const rememberedOwner = useLiveQuery(() => currentLocalOwnerKey().catch(() => null));
const onlineState: OnlineIdentityState = session.isPending ? "checking"
: session.error ? (session.error instanceof LocalSessionUnavailableError ? "local-unavailable" : session.error.status === 401 ? "signed-out" : "unreachable") : session.data?.user ? "authenticated" : "signed-out";
: session.error ? (session.error instanceof LocalSessionUnavailableError ? "local-unavailable" : [401, 403].includes(session.error.status ?? 0) ? "signed-out" : "unreachable") : session.data?.user ? "authenticated" : "signed-out";
const confirmedUserId = !blocked && onlineState === "authenticated" ? session.data!.user.id : null;
const sessionId = session.data?.session?.id;
const previousIdentity = useRef({ userId: confirmedUserId, sessionId });
Expand Down Expand Up @@ -47,3 +47,11 @@ export function useSettingsIdentity() {
return { userId: identity.localUserId,
ready: !identity.restoring && (identity.onlineState === "authenticated" || identity.onlineState === "signed-out") };
}

// The presentation session only scopes an already-mounted view. Only the
// authenticated session can authorize reads or writes.
export function presentationSessionId(identity: ApplicationIdentity, previous: string | null) {
if (identity.onlineState === "signed-out") return null;
if (identity.onlineState === "authenticated") return identity.authenticatedSessionId;
return identity.session.data?.session?.id ?? previous;
}
6 changes: 5 additions & 1 deletion src/client/auth/session-recovery.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,15 @@ it("bounds a foreground failure episode and shares manual concurrent retries", a
}
await act(() => vi.advanceTimersByTimeAsync(120_000));
expect(session.refetch).toHaveBeenCalledTimes(3);
act(() => window.dispatchEvent(new Event("offline")));
act(() => window.dispatchEvent(new Event("online")));
await act(() => vi.advanceTimersByTimeAsync(2_000));
expect(session.refetch).toHaveBeenCalledTimes(4);
let finish!: () => void;
session.refetch.mockReturnValue(new Promise<void>(resolve => { finish = resolve; }));
const manual = recoverSession();
expect(recoverSession()).toBe(manual);
expect(session.refetch).toHaveBeenCalledTimes(4);
expect(session.refetch).toHaveBeenCalledTimes(5);
finish(); await manual;
});

Expand Down
8 changes: 6 additions & 2 deletions src/client/auth/session-recovery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,13 +35,17 @@ export function useSessionRecovery(onlineState: OnlineIdentityState, isRefetchin
if (onlineState === "authenticated" && navigator.onLine && document.visibilityState === "visible") void recoverSession().catch(() => undefined);
else schedule();
};
const reconnect = () => {
if (transient) attempts.current = 0;
resume();
};
schedule();
window.addEventListener("online", resume);
window.addEventListener("online", reconnect);
window.addEventListener("offline", schedule);
document.addEventListener("visibilitychange", resume);
return () => {
clearTimeout(timer);
window.removeEventListener("online", resume);
window.removeEventListener("online", reconnect);
window.removeEventListener("offline", schedule);
document.removeEventListener("visibilitychange", resume);
};
Expand Down
7 changes: 2 additions & 5 deletions src/client/routes/choir-page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,8 @@ import { BackButton } from "../navigation/back-button";
import { PreparedScoreLink } from "../score-library/prepared-score-link";
import { useNetworkStatus } from "../platform/use-network-status";
import { rememberLastDrive, forgetLastDrive } from "../score-library/last-drive";
import { useApplicationIdentity } from "../auth/application-identity";
import { presentationSessionId as resolvePresentationSessionId, useApplicationIdentity, type ApplicationIdentity } from "../auth/application-identity";
import { IdentityNotice } from "../auth/local-entry";
import type { ApplicationIdentity } from "../auth/application-identity";
import { FileMusic, LoaderCircle } from "lucide-react";
import { lazy, Suspense, useCallback, useEffect, useState } from "react";
import {
Expand Down Expand Up @@ -80,9 +79,7 @@ function ChoirLibrary({ choirId, identity, cacheOwner }: { choirId: string; iden
const { session } = identity;
// A remembered session scopes the mounted view; only authenticatedUserId grants authority.
const [dialogSession, setDialogSession] = useState(session.data?.session?.id ?? null);
const presentationSessionId = identity.onlineState === "signed-out" ? null
: identity.onlineState === "authenticated" ? identity.authenticatedSessionId
: session.data?.session?.id ?? dialogSession;
const presentationSessionId = resolvePresentationSessionId(identity, dialogSession);
const userId = identity.localUserId ?? undefined;
const online = useNetworkStatus();
const { library, snapshot } = useDriveLibrary(cacheOwner, choirId, Boolean(identity.authenticatedUserId), !identity.restoring && (Boolean(userId) || identity.onlineState !== "checking"), presentationSessionId);
Expand Down
15 changes: 15 additions & 0 deletions src/client/score-library/drive-library.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -448,6 +448,21 @@ it("returns ten times without reading again, then quietly refreshes expired data
});


it("keeps the stored directory read-only when the first bootstrap explicitly requires authentication", async () => {
await activateAuthenticatedLocalOwner("one");
const { library: initial } = create(async () => opened());
await initial.refresh();
initial.stop();
clearDriveLibraryCache();
const { library } = create(async () => ({ kind: "failed", authenticationRequired: true }));
await library.refresh();
expect(library.getSnapshot()).toMatchObject({
access: { local: true, isMember: false },
reading: { authority: "signed-out", request: "idle" },
});
expect(library.getSnapshot().scores.map(score => score.fileName)).toEqual(["秋日.pdf"]);
});

describe("confirmed navigation changes across settings and directory consumers", () => {
const kinds: DriveReadKind[] = ["settings", "management", "permission-contacts", "memberships", "usage", "shared-layers", "shared-layer", "layer-access", "reading-defaults"];
it.each([
Expand Down
8 changes: 6 additions & 2 deletions src/client/score-library/drive-library.ts
Original file line number Diff line number Diff line change
Expand Up @@ -439,16 +439,20 @@ export class DriveLibrary {
}
return;
}
if (authenticationRequired) {
invalidateDriveLibrary(this.ownerKey, this.choirId);
this.publish({ reading: { request: "pending", authority: "signed-out" } });
}
let local: OpenedAccess | null;
try { local = await this.readLocal(signal); }
catch {
if (!signal.aborted) this.publish({ access: { kind: "failed" }, refreshMessage: t("driveLocalDirectoryUnreadable") });
if (!signal.aborted) this.publish({ access: { kind: "failed" }, refreshMessage: t(authenticationRequired ? "driveLibraryLoginHasExpiredLog" : "driveLocalDirectoryUnreadable") });
return;
}
if (signal.aborted) return;
this.publish({ access: local ?? { kind: "opened", local: true, isMember: false,
choir: readDriveSummary(this.ownerKey, this.choirId) ?? { id: this.choirId, name: t("drive"), guestAdmissionMode: "invite" },
result: { scores: [], permissions: { capabilities: noCapabilities() }, storage: { usedBytes: 0, limitBytes: 1 } } }, refreshMessage: t(refreshFailed) });
result: { scores: [], permissions: { capabilities: noCapabilities() }, storage: { usedBytes: 0, limitBytes: 1 } } }, refreshMessage: t(authenticationRequired ? "driveLibraryLoginHasExpiredLog" : refreshFailed) });
}

private updateView(update: Partial<LibraryView>) {
Expand Down
Loading