From b4e46047bcc5db024f0c125c2b137688216cb74e Mon Sep 17 00:00:00 2001 From: clydian <297624398+clydian@users.noreply.github.com> Date: Wed, 25 Nov 2026 13:37:59 +0000 Subject: [PATCH 1/4] =?UTF-8?q?fix:=20=E5=BC=B1=E7=BD=91=E6=97=B6=E4=BF=9D?= =?UTF-8?q?=E7=95=99=E5=BD=93=E5=89=8D=E8=A7=86=E5=94=B1=E6=8C=91=E6=88=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../sight-singing-continuity.test.mjs | 124 +++++++ src/client/auth/application-identity.test.tsx | 16 + src/client/auth/application-identity.ts | 10 +- src/client/auth/session-recovery.test.tsx | 6 +- src/client/auth/session-recovery.ts | 8 +- src/client/routes/choir-page.tsx | 7 +- .../score-library/drive-library.test.ts | 15 + src/client/score-library/drive-library.ts | 8 +- src/client/settings/navigation-events.ts | 2 +- src/client/sight-singing/read.ts | 19 + .../sight-singing/result-publication.ts | 9 +- .../sight-singing/sight-singing-page.tsx | 324 +++++++++++------- src/client/sight-singing/use-melody-source.ts | 42 ++- src/i18n/messages/de/practice.json | 2 +- src/i18n/messages/en/practice.json | 2 +- src/i18n/messages/es-419/practice.json | 2 +- src/i18n/messages/fr/practice.json | 2 +- src/i18n/messages/it/practice.json | 2 +- src/i18n/messages/ja/practice.json | 2 +- src/i18n/messages/ko/practice.json | 2 +- src/i18n/messages/pt-BR/practice.json | 2 +- src/i18n/messages/zh-Hans/practice.json | 2 +- src/i18n/messages/zh-Hant-TW/practice.json | 2 +- 23 files changed, 444 insertions(+), 166 deletions(-) create mode 100644 browser-tests/sight-singing-continuity.test.mjs create mode 100644 src/client/sight-singing/read.ts diff --git a/browser-tests/sight-singing-continuity.test.mjs b/browser-tests/sight-singing-continuity.test.mjs new file mode 100644 index 00000000..8e03cc25 --- /dev/null +++ b/browser-tests/sight-singing-continuity.test.mjs @@ -0,0 +1,124 @@ +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 = `Alto + 1 + G2A3 + 4whole`; +const title = "弱网回归练习"; +const noConnection = "暂时无法连接,已保存的内容仍然保留。"; + +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 questions = `${fixture.origin}/api/choirs/${fixture.choirId}/sight-singing/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(); + 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); + + await page.route(questions, route => route.fulfill({ status: 403, json: { error: "permission_denied" } })); + await page.evaluate(() => window.dispatchEvent(new Event("focus"))); + 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); + + let failRead; + const gate = new Promise(resolve => { failRead = resolve; }); + await cold.route(questions, async route => { + await gate; + 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); + failRead(); + await expect(cold.getByText("无法加载云盘题目。", { exact: true })).toBeVisible(); + await cold.unroute(questions); + await cold.getByRole("button", { name: "重新加载", exact: true }).first().click(); + await expect(cold.getByRole("button", { name: new RegExp(title) })).toBeVisible(); +}); diff --git a/src/client/auth/application-identity.test.tsx b/src/client/auth/application-identity.test.tsx index 679ed068..a86f2281 100644 --- a/src/client/auth/application-identity.test.tsx +++ b/src/client/auth/application-identity.test.tsx @@ -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"); diff --git a/src/client/auth/application-identity.ts b/src/client/auth/application-identity.ts index 9b6486fe..ebd33cde 100644 --- a/src/client/auth/application-identity.ts +++ b/src/client/auth/application-identity.ts @@ -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 }); @@ -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; +} diff --git a/src/client/auth/session-recovery.test.tsx b/src/client/auth/session-recovery.test.tsx index e834f3d5..047b57c0 100644 --- a/src/client/auth/session-recovery.test.tsx +++ b/src/client/auth/session-recovery.test.tsx @@ -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(resolve => { finish = resolve; })); const manual = recoverSession(); expect(recoverSession()).toBe(manual); - expect(session.refetch).toHaveBeenCalledTimes(4); + expect(session.refetch).toHaveBeenCalledTimes(5); finish(); await manual; }); diff --git a/src/client/auth/session-recovery.ts b/src/client/auth/session-recovery.ts index 9a4f026d..520cd835 100644 --- a/src/client/auth/session-recovery.ts +++ b/src/client/auth/session-recovery.ts @@ -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); }; diff --git a/src/client/routes/choir-page.tsx b/src/client/routes/choir-page.tsx index 1054dbdc..f0b3e878 100644 --- a/src/client/routes/choir-page.tsx +++ b/src/client/routes/choir-page.tsx @@ -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 { @@ -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); diff --git a/src/client/score-library/drive-library.test.ts b/src/client/score-library/drive-library.test.ts index 45a6c5ab..20ed4024 100644 --- a/src/client/score-library/drive-library.test.ts +++ b/src/client/score-library/drive-library.test.ts @@ -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([ diff --git a/src/client/score-library/drive-library.ts b/src/client/score-library/drive-library.ts index f1bb0666..a1eba681 100644 --- a/src/client/score-library/drive-library.ts +++ b/src/client/score-library/drive-library.ts @@ -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) { diff --git a/src/client/settings/navigation-events.ts b/src/client/settings/navigation-events.ts index ed53f598..e0434988 100644 --- a/src/client/settings/navigation-events.ts +++ b/src/client/settings/navigation-events.ts @@ -9,7 +9,7 @@ const membershipChanges = new Set<() => void>(); export const membershipDirectoryRevision = () => membershipRevision; export function onMembershipDirectoryChange(listener: () => void) { membershipChanges.add(listener); return () => { membershipChanges.delete(listener); }; } function invalidateMembershipDirectory() { membershipRevision++; for (const listener of membershipChanges) listener(); } -export type DriveReadKind = "settings" | "management" | "permission-contacts" | "memberships" | "usage" | "shared-layers" | "shared-layer" | "layer-access" | "reading-defaults"; +export type DriveReadKind = "settings" | "management" | "permission-contacts" | "memberships" | "usage" | "shared-layers" | "shared-layer" | "layer-access" | "reading-defaults" | "sight-singing"; // In-memory identity only: never parse owner/drive/variant strings as dependencies. export interface DriveReadIdentity { owner: string | null; diff --git a/src/client/sight-singing/read.ts b/src/client/sight-singing/read.ts new file mode 100644 index 00000000..d92e7acc --- /dev/null +++ b/src/client/sight-singing/read.ts @@ -0,0 +1,19 @@ +import { diagnosticFetch, parseDiagnosticResponse } from '../diagnostics/diagnostics'; +import { SettingsRequestError } from '../settings/settings-request'; + +export const publishedPath = (drive: string) => `/api/choirs/${encodeURIComponent(drive)}/sight-singing/questions`; + +export function isSightSingingMemberDenied(error: unknown) { + return error instanceof SettingsRequestError && (error.status === 401 || error.status === 403); +} + +export async function readSightSinging(path: string, schema: { parse(value: unknown): T }, lifetime?: AbortSignal) { + const deadline = AbortSignal.timeout(15_000); + const signal = lifetime ? AbortSignal.any([lifetime, deadline]) : deadline; + const response = await diagnosticFetch(path, { signal }); + signal.throwIfAborted(); + if (!response.ok) throw new SettingsRequestError(response.status); + const data = await parseDiagnosticResponse(response, schema); + signal.throwIfAborted(); + return data; +} diff --git a/src/client/sight-singing/result-publication.ts b/src/client/sight-singing/result-publication.ts index 4e8f064c..def5f0e7 100644 --- a/src/client/sight-singing/result-publication.ts +++ b/src/client/sight-singing/result-publication.ts @@ -3,6 +3,7 @@ import { type SightSingingResultSubmission, } from '../../shared/sight-singing-results'; import { diagnosticFetch, parseDiagnosticResponse } from '../diagnostics/diagnostics'; +import { readSightSinging } from './read'; const resultPath = (choirId: string, questionId: string) => `/api/choirs/${encodeURIComponent(choirId)}/sight-singing/questions/${encodeURIComponent(questionId)}/results`; @@ -27,15 +28,11 @@ export async function readSightSingingResults(choirId: string, questionId: strin if (version !== undefined) query.set('version', String(version)); if (voice) query.set('voice', voice); if (speed !== undefined) query.set('speed', String(speed)); - const response = await diagnosticFetch(resultPath(choirId, questionId) + (query.size ? `?${query}` : ''), { signal }); - if (!response.ok) throw new Error('published_results_unavailable'); - return parseDiagnosticResponse(response, sightSingingResultsResponseSchema); + return readSightSinging(resultPath(choirId, questionId) + (query.size ? `?${query}` : ''), sightSingingResultsResponseSchema, signal); } export async function readSightSingingLeaderboard(choirId: string, signal?: AbortSignal) { - const response = await diagnosticFetch(`/api/choirs/${encodeURIComponent(choirId)}/sight-singing/leaderboard`, { signal }); - if (!response.ok) throw new Error('published_results_unavailable'); - return parseDiagnosticResponse(response, sightSingingLeaderboardSchema); + return readSightSinging(`/api/choirs/${encodeURIComponent(choirId)}/sight-singing/leaderboard`, sightSingingLeaderboardSchema, signal); } export async function withdrawSightSingingResult(choirId: string, questionId: string, userId: string, id: string, version: number) { diff --git a/src/client/sight-singing/sight-singing-page.tsx b/src/client/sight-singing/sight-singing-page.tsx index d2a593c3..0843792f 100644 --- a/src/client/sight-singing/sight-singing-page.tsx +++ b/src/client/sight-singing/sight-singing-page.tsx @@ -1,8 +1,8 @@ import { useLiveQuery } from 'dexie-react-hooks'; import { ChevronDown, ChevronRight, Pencil, Settings, Trophy, UsersRound, X } from 'lucide-react'; -import { useEffect, useId, useMemo, useRef, useState, type ReactNode } from 'react'; +import { useEffect, useId, useLayoutEffect, useMemo, useRef, useState, type ReactNode } from 'react'; import { Button, DialogTrigger, Heading, MenuItem, MenuTrigger, Modal, ModalOverlay, Popover, Switch } from 'react-aria-components'; -import { useParams } from 'react-router-dom'; +import { Link, useParams } from 'react-router-dom'; import { useAppLocale, useMessages } from '../../i18n'; import { attachmentAccept, attachmentFormat, attachmentNameSchema } from '../../shared/attachments'; import { scoreDisplayName } from '../../shared/score-display-name'; @@ -10,7 +10,8 @@ import type { ScoreSummary } from '../../shared/scores'; import { publishedQuestionResponseSchema, publishedQuestionsSchema, SIGHT_SINGING_QUESTION_NAME_MAX_LENGTH, SIGHT_SINGING_SCORE_MAX_BYTES, type PublishedQuestion, type QuestionPublication } from '../../shared/sight-singing'; import { diagnosticFetch, parseDiagnosticResponse } from '../diagnostics/diagnostics'; -import { useApplicationIdentity } from '../auth/application-identity'; +import { presentationSessionId, useApplicationIdentity, type ApplicationIdentity } from '../auth/application-identity'; +import { loginHref } from '../auth/login-return'; import { FloatingAddButton } from '../components/floating-add-button'; import { LoadingStatus } from '../components/loading-status'; import { TaskHeader } from '../components/task-header'; @@ -20,6 +21,7 @@ import { driveCacheOwnerKey, type DriveCacheOwnerKey } from '../score-library/dr import { useDriveLibraryResource } from '../score-library/use-drive-library'; import { Dialog, Menu } from '../navigation/overlays'; import { captureNavigationIdentity } from '../settings/navigation-events'; +import { useReadResource } from '../settings/use-read-resource'; import { ConfirmDialog } from '../settings/confirm-dialog'; import { ChallengeRun, type ResultSave, type VoiceOption } from './challenge-run'; import { useSightSingingScoreFormat } from './format-score'; @@ -29,33 +31,84 @@ import { ScoreBadges } from './score-badge'; import { publishSightSingingResult, readSightSingingLeaderboard, readSightSingingResults, withdrawSightSingingResult, type SightSingingResultFilters } from './result-publication'; import type { PublishedSightSingingResult, SightSingingLeaderboard, SightSingingResultSubmission } from '../../shared/sight-singing-results'; -import { publishedPath, useMelodySource, type MelodySource } from './use-melody-source'; +import { isSightSingingMemberDenied, publishedPath, readSightSinging } from './read'; +import { useMelodySource, type MelodySource } from './use-melody-source'; import './sight-singing.css'; import './sight-singing-workspace.css'; export default function SightSingingPage() { const { choirId = '' } = useParams(); const identity = useApplicationIdentity(); - const owner = driveCacheOwnerKey(identity.authenticatedUserId, choirId); - const sessionId = identity.authenticatedSessionId; - const t = useMessages('practice'); + const owner = driveCacheOwnerKey(identity.localUserId, choirId); + return ; +} + +function SightSingingAccess({ owner, choirId, identity }: { + owner: DriveCacheOwnerKey; choirId: string; identity: ApplicationIdentity; +}) { const online = useNetworkStatus(); - const { snapshot: { access } } = useDriveLibraryResource(owner, choirId, Boolean(sessionId), Boolean(sessionId), sessionId); - const userId = identity.authenticatedUserId; - const allowed = online && Boolean(sessionId && userId) && access.kind === 'opened' && access.isMember && !access.local && !access.choir.isPreviewEntry; - if (allowed && sessionId && userId) return ; + const [previousSession, setPreviousSession] = useState(identity.authenticatedSessionId); + const sessionId = presentationSessionId(identity, previousSession); + if (previousSession !== sessionId) setPreviousSession(sessionId); + const userId = identity.localUserId; + const authenticated = Boolean(identity.authenticatedSessionId); + const { library, snapshot: { access, reading, refreshMessage } } = + useDriveLibraryResource(owner, choirId, authenticated, Boolean(sessionId), sessionId); + const member = authenticated && access.kind === 'opened' && access.isMember && !access.local && !access.choir.isPreviewEntry; + const signedOut = identity.onlineState === 'signed-out' || reading.authority === 'signed-out'; + const driveDenied = reading.authority === 'revoked' + || access.kind === 'denied' || access.kind === 'not-found' || access.kind === 'join-required' + || access.kind === 'opened' && (access.retained === true || !access.local && (!access.isMember || access.choir.isPreviewEntry === true)); + const denied = signedOut || driveDenied; + const [admittedSession, setAdmittedSession] = useState(null); + const nextAdmission = denied || !sessionId ? null : member ? sessionId : admittedSession === sessionId ? admittedSession : null; + if (admittedSession !== nextAdmission) setAdmittedSession(nextAdmission); + const retryConnection = () => { + if (!navigator.onLine) return; + void (authenticated ? library.refresh() : identity.session.refetch()).catch(() => undefined); + }; + if (nextAdmission && userId && access.kind === 'opened') return ; + + return ; +} + +function ChallengeEntry({ choirId, denied, signedOut = false, loading = false, retry }: { + choirId: string; denied: boolean; signedOut?: boolean; loading?: boolean; retry: () => void; +}) { + const t = useMessages('practice'); + const entry = useMessages('entry'); return
- {online && (identity.restoring || sessionId && access.kind === 'loading') ? {t('sight.loading')} - :

{t('sight.needMember')}

} + {loading ? {t('sight.loading')} + : signedOut ?

{entry('identity.loginAgain')}

+ : denied ?

{t('sight.needMember')}

+ :

{entry('identity.unreachable')}{' '} +

}
; } -type DriveContext = { owner: DriveCacheOwnerKey; choirId: string; sessionId: string; userId: string; canPublishOfficial: boolean; scores: ScoreSummary[] }; +type DriveContext = { owner: DriveCacheOwnerKey; choirId: string; sessionId: string; userId: string; canPublishOfficial: boolean; scores: ScoreSummary[]; canReadCloud: boolean; retryConnection: () => void }; +type ChallengeReads = Pick & { onMemberDenied?: () => void }; + +function useChallengeRead({ owner, choirId, canReadCloud, onMemberDenied }: ChallengeReads, variant: string, + load: (signal: AbortSignal) => Promise, enabled = true) { + return useReadResource({ owner, driveId: choirId, kind: 'sight-singing', variant }, async signal => { + try { return await load(signal); } + catch (error) { + if (!signal.aborted && isSightSingingMemberDenied(error)) onMemberDenied?.(); + throw error; + } + }, undefined, 0, canReadCloud && enabled); +} + type SourceMode = 'saved' | 'library' | 'upload'; const versionTag = (version: number) => `V${version}`; @@ -77,43 +130,54 @@ function publisherLabel(publisher: PublishedQuestion['publisher'], t: ReturnType function QuestionLibrary({ driveName, ...props }: DriveContext & { driveName: string }) { const t = useMessages('practice'); const questions = useLiveQuery(() => readQuestions(props.owner, props.choirId).catch(() => null), [props.owner, props.choirId]); - const [published, setPublished] = useState(); - const [reload, setReload] = useState(0); - const [board, setBoard] = useState<{ reload: number; leaderboard: SightSingingLeaderboard | null }>(); + const published = useChallengeRead(props, 'questions', signal => + readSightSinging(publishedPath(props.choirId), publishedQuestionsSchema, signal)); + const denied = published.authority === 'signed-out' || published.authority === 'revoked'; + const reads = { ...props, onMemberDenied: published.clear }; + const board = useChallengeRead(reads, 'leaderboard', signal => readSightSingingLeaderboard(props.choirId, signal), !denied); const [selection, setSelection] = useState<{ question?: PublishedQuestion; legacy?: SightSingingQuestion } | null>(null); const [pitchTraceEnabled, setPitchTraceEnabled] = useState(false); + const refresh = () => { + if (!props.canReadCloud) { props.retryConnection(); return; } + void published.refresh().catch(() => undefined); + void board.refresh().catch(() => undefined); + }; + const { refresh: refreshQuestions } = published; + const { refresh: refreshBoard } = board; useEffect(() => { - const controller = new AbortController(); - void diagnosticFetch(publishedPath(props.choirId), { signal: controller.signal }).then(async response => { - if (!response.ok) throw new Error('questions_unavailable'); - const payload = await parseDiagnosticResponse(response, publishedQuestionsSchema); - if (!controller.signal.aborted) setPublished(payload.questions); - }).catch(() => { if (!controller.signal.aborted) setPublished(null); }); - return () => controller.abort(); - }, [props.choirId, reload]); - useEffect(() => { - const controller = new AbortController(); - void readSightSingingLeaderboard(props.choirId, controller.signal).then(payload => { - if (!controller.signal.aborted) setBoard({ reload, leaderboard: payload }); - }).catch(() => { - if (!controller.signal.aborted) setBoard({ reload, leaderboard: null }); - }); - return () => controller.abort(); - }, [props.choirId, reload]); - const ranked = board?.reload === reload ? board.leaderboard : undefined; - if (selection) return { setSelection(null); setReload(value => value + 1); }} />; - const legacyQuestions = questions?.filter(question => !published?.some(item => item.id === question.id)); + if (!props.canReadCloud) return; + const verify = () => { + if (document.visibilityState !== 'visible') return; + void refreshQuestions().catch(() => undefined); + if (!denied) void refreshBoard().catch(() => undefined); + }; + window.addEventListener('focus', verify); + document.addEventListener('visibilitychange', verify); + return () => { + window.removeEventListener('focus', verify); + document.removeEventListener('visibilitychange', verify); + }; + }, [props.canReadCloud, denied, refreshQuestions, refreshBoard]); + if (denied) { + if (selection) setSelection(null); + return ; + } + if (selection) return { setSelection(null); refresh(); }} />; + const legacyQuestions = questions?.filter(question => !published.data?.questions.some(item => item.id === question.id)); + const listPending = props.canReadCloud && !published.data && !published.error; + const boardPending = props.canReadCloud && !board.data && !board.error; return
- {ranked === null &&

{t('sight.publishedResultsError')}

} - {published === undefined ? {t('sight.loading')} - : published === null ?

{t('sight.publishedError')}

- : setSelection({ question })} />} + {(published.error || !published.data && !listPending) &&

{t('sight.publishedError')}{' '} +

} + {published.data && (board.error || !board.data && !boardPending) &&

{t('sight.publishedResultsError')}{' '} +

} + {listPending && {t('sight.loading')}} + {published.data && setSelection({ question })} />}
{questions === null ?

{t('sight.storageError')}

: Boolean(legacyQuestions?.length) &&
@@ -158,8 +222,8 @@ function RankBadge({ place, tied }: { place: number; tied: boolean }) { ; } -function QuestionList({ questions, leaderboard, choirId, open }: { - questions: PublishedQuestion[]; leaderboard?: SightSingingLeaderboard | null; choirId: string; +function QuestionList({ questions, leaderboard, reads, open }: { + questions: PublishedQuestion[]; leaderboard?: SightSingingLeaderboard | null; reads: ChallengeReads; open: (question: PublishedQuestion) => void; }) { const t = useMessages('practice'); @@ -172,33 +236,18 @@ function QuestionList({ questions, leaderboard, choirId, open }: { const counts = leaderboard?.participants && new Map(leaderboard.participants.map(item => [item.questionId, item.count])); return questions.length ?
    {questions.map(question => open(question)} />)}
:

{t('sight.noPublished')}

; } -function QuestionCard({ question, top, count, choirId, ready, open }: { +function QuestionCard({ question, top, count, reads, ready, open }: { question: PublishedQuestion; top?: SightSingingLeaderboard['results']; count?: number; ready: boolean; open: () => void; - choirId: string; + reads: ChallengeReads; }) { const t = useMessages('practice'); - const formatScore = useSightSingingScoreFormat(); const rankingId = useId(); const [expanded, setExpanded] = useState(false); - const [retry, setRetry] = useState(0); - const [details, setDetails] = useState<{ retry: number; rows: PublishedSightSingingResult[] | null }>(); - useEffect(() => { - if (!expanded) return; - const controller = new AbortController(); - void readSightSingingResults(choirId, question.id, {}, controller.signal).then(payload => { - if (!controller.signal.aborted) setDetails({ retry, rows: payload.results }); - }).catch(() => { - if (!controller.signal.aborted) setDetails({ retry, rows: null }); - }); - return () => controller.abort(); - }, [expanded, choirId, question.id, retry]); - const loaded = details?.retry === retry ? details.rows : undefined; - const rows = expanded ? loaded : top; const showDetailsButton = expanded || Boolean(top?.length); const showVersions = question.version > 1; return
  • @@ -211,34 +260,51 @@ function QuestionCard({ question, top, count, choirId, ready, open }: { {count !== undefined && } {showDetailsButton && }
  • }
    - {rows?.length ?
      - {rankScores(rows).map(({ row, place, tied }) =>
    1. - -
      -
      {row.displayName} - - - {t('sight.takeScore', { score: formatScore(row.score) })} - -
      - {expanded && {row.voiceName}{showVersions && ` · ${versionTag(row.version)}`} - {` · ${row.speed.toFixed(2)}×`}} -
      -
    2. )} -
    : expanded && rows === undefined ? {t('sight.loading')} - : rows === null ?

    {t('sight.publishedResultsError')}{' '} -

    - :

    {expanded || ready ? t('sight.noCardScores') : '—'}

    } + {expanded ? + : }
    ; } +function ExpandedQuestionRanks({ reads, question }: { reads: ChallengeReads; question: PublishedQuestion }) { + const t = useMessages('practice'); + const details = useChallengeRead(reads, `card:${question.id}`, signal => + readSightSingingResults(reads.choirId, question.id, {}, signal)); + if (details.data) return 1} />; + if (reads.canReadCloud && !details.error) return {t('sight.loading')}; + return

    {t('sight.publishedResultsError')}{' '} + +

    ; +} + +function QuestionRanks({ rows, ready, expanded, showVersions }: { + rows?: SightSingingLeaderboard['results']; ready: boolean; expanded?: boolean; showVersions?: boolean; +}) { + const t = useMessages('practice'); + const formatScore = useSightSingingScoreFormat(); + return rows?.length ?
      + {rankScores(rows).map(({ row, place, tied }) =>
    1. + +
      +
      {row.displayName} + + + {t('sight.takeScore', { score: formatScore(row.score) })} + +
      + {expanded && {row.voiceName}{showVersions && ` · ${versionTag(row.version)}`} + {` · ${row.speed.toFixed(2)}×`}} +
      +
    2. )} +
    :

    {ready ? t('sight.noCardScores') : '—'}

    ; +} + function PracticePanel({ title, icon, compact, children }: { title: string; icon: ReactNode; compact?: boolean; children: ReactNode; }) { @@ -292,40 +358,34 @@ function PublishedResultRow({ row, place, tied, showVersions, onRemove }: { ; } -function PublishedResults({ choirId, questionId, version, generation, userId }: { - choirId: string; questionId: string; version: number; generation: number; userId: string; +function PublishedResults({ reads, questionId, version, generation, userId }: { + reads: ChallengeReads; questionId: string; version: number; generation: number; userId: string; }) { + const { choirId, canReadCloud } = reads; const t = useMessages('practice'); const showVersions = version > 1; const speedFilterId = useId(); const [filters, setFilters] = useState({}); const [voices, setVoices] = useState([]); - const [retry, setRetry] = useState(0); - const [state, setState] = useState<{ generation: number; retry: number; filters: SightSingingResultFilters; - rows: PublishedSightSingingResult[] | null }>(); const [removing, setRemoving] = useState(null); const [busy, setBusy] = useState(false); const [withdrawFailed, setWithdrawFailed] = useState(false); + const results = useChallengeRead(reads, JSON.stringify(['results', questionId, filters]), signal => + readSightSingingResults(choirId, questionId, filters, signal)); + const rows = results.data?.results; + const { refresh } = results; + const refreshResults = () => { void refresh().catch(() => undefined); }; useEffect(() => { - const controller = new AbortController(); - void readSightSingingResults(choirId, questionId, filters, controller.signal).then(payload => { - if (controller.signal.aborted) return; - setState({ generation, retry, filters, rows: payload.results }); - setVoices(payload.voices); - }).catch(() => { - if (!controller.signal.aborted) setState({ generation, retry, filters, rows: null }); - }); - return () => controller.abort(); - }, [choirId, questionId, filters, generation, retry]); - const rows = state?.generation === generation && state.retry === retry && state.filters === filters - ? state.rows : undefined; + if (canReadCloud) void refresh().catch(() => undefined); + }, [canReadCloud, refresh, generation]); + if (results.data?.voices && results.data.voices !== voices) setVoices(results.data.voices); const removeLabel = (edition: number) => showVersions ? t('sight.withdrawResult', { version: versionTag(edition) }) : t('sight.withdrawAction'); const withdraw = async () => { - if (!removing || busy) return; + if (!removing || busy || !results.canMutate) return; setBusy(true); setWithdrawFailed(false); try { await withdrawSightSingingResult(choirId, questionId, userId, removing.id, removing.version); - setRetry(value => value + 1); + refreshResults(); } catch { setWithdrawFailed(true); } finally { @@ -357,11 +417,11 @@ function PublishedResults({ choirId, questionId, version, generation, userId }: {withdrawFailed &&

    {t('sight.withdrawFailed')}

    } - {rows === undefined ? {t('sight.loading')} - : rows === null ?

    {t('sight.publishedResultsError')}

    + {!rows && canReadCloud && !results.error ? {t('sight.loading')} + : !rows ?

    {t('sight.publishedResultsError')}

    : rows.length === 0 ?

    {t('sight.publishedResultsEmpty')}

    :
      {rankScores(rows).map(({ row, place, tied }) => - setRemoving(row)} /> + { if (results.canMutate) setRemoving(row); }} /> )}
    } setRemoving(null)} confirmation={removing && { title: removeLabel(removing.version), message: t('sight.withdrawDescription'), @@ -370,13 +430,14 @@ function PublishedResults({ choirId, questionId, version, generation, userId }: ; } -function QuestionWorkspace({ owner, choirId, sessionId, userId, canPublishOfficial, scores, question, legacy, onBack, +function QuestionWorkspace({ owner, choirId, sessionId, userId, canPublishOfficial, scores, canReadCloud, retryConnection, onMemberDenied, question, legacy, onBack, pitchTraceEnabled, setPitchTraceEnabled }: DriveContext & { - question?: PublishedQuestion; legacy?: SightSingingQuestion; onBack: () => void; + question?: PublishedQuestion; legacy?: SightSingingQuestion; onBack: () => void; onMemberDenied: () => void; pitchTraceEnabled: boolean; setPitchTraceEnabled: (enabled: boolean) => void; }) { const t = useMessages('practice'); const { locale } = useAppLocale(); + const entry = useMessages('entry'); const id = useId(); const heading = useRef(null); const [saved, setSaved] = useState(question); @@ -399,15 +460,30 @@ function QuestionWorkspace({ owner, choirId, sessionId, userId, canPublishOffici const [failed, setFailed] = useState(false); const saveLifetime = useRef(null); const resultLifetimes = useRef(new Set()); + // A take can finish after the render that started it has lost cloud access. + const cloudAvailable = useRef(false); + useLayoutEffect(() => { + cloudAvailable.current = canReadCloud; + return () => { cloudAvailable.current = false; }; + }, [canReadCloud]); useEffect(() => { const pending = resultLifetimes.current; return () => { saveLifetime.current?.abort(); for (const controller of pending) controller.abort(); }; }, []); + useEffect(() => { + if (canReadCloud) return; + if (saveLifetime.current) { + saveLifetime.current.abort(); + setSaving(false); + setFailed(true); + } + for (const controller of resultLifetimes.current) controller.abort(); + }, [canReadCloud]); const visibleSource = editing ? sourceMode : 'saved'; const candidates = useMemo(() => scores.filter(score => (score.musicXmlCount ?? score.attachmentCount ?? 0) > 0), [scores]); const score = visibleSource === 'library' ? candidates.find(row => row.id === scoreId) : undefined; - const attachments = useLibraryAttachments(choirId, score ? [score] : [], Boolean(score), sessionId, owner); + const attachments = useLibraryAttachments(choirId, score ? [score] : [], Boolean(score) && canReadCloud, sessionId, owner); const files = attachments.items.filter(file => file.kind === 'musicxml' && !file.trashExpiresAt) .sort((left, right) => Number(right.source === 'generated') - Number(left.source === 'generated')); const fileKey = (file: (typeof files)[number]) => `${file.id}:${file.revision}`; @@ -420,7 +496,7 @@ function QuestionWorkspace({ owner, choirId, sessionId, userId, canPublishOffici source = saved ? { kind: 'cloud', ...snapshot } : { kind: 'local', owner, ...snapshot }; } else if (visibleSource === 'upload' && upload) source = { kind: 'upload', choirId, locale, ...upload }; else if (visibleSource === 'library' && score && attachment) source = { kind: 'library', playback: { attachment, score, choirId, ownerKey: owner, sessionId } }; - const loaded = useMelodySource(source); + const loaded = useMelodySource(source, canReadCloud, onMemberDenied); const { bytes: loadedBytes, name: loadedName } = loaded; const last = lastChoice ?? (loaded.document?.visits.length ?? 1) - 1; const options = useMemo(() => { @@ -464,7 +540,7 @@ function QuestionWorkspace({ owner, choirId, sessionId, userId, canPublishOffici const title = titleOverride ?? (scoreName && nameRange ? questionNameWithRange(scoreName, nameRange) : ''); const editable = saved?.canEdit ?? canPublishOfficial; const save = async () => { - if (!title.trim() || !source || !loadedBytes || !loadedName || !selected || saveLifetime.current || (saved && !editable)) return; + if (!canReadCloud || !title.trim() || !source || !loadedBytes || !loadedName || !selected || saveLifetime.current || (saved && !editable)) return; const controller = new AbortController(); saveLifetime.current = controller; const current = captureNavigationIdentity(); @@ -487,7 +563,7 @@ function QuestionWorkspace({ owner, choirId, sessionId, userId, canPublishOffici form.set('file', new Blob([loadedBytes]), loadedName); body = form; } - const response = await diagnosticFetch(`${publishedPath(choirId)}/${questionId}`, { method: 'PUT', signal: controller.signal, headers, body }); + const response = await diagnosticFetch(`${publishedPath(choirId)}/${questionId}`, { method: 'PUT', signal: AbortSignal.any([controller.signal, AbortSignal.timeout(30_000)]), headers, body }); if (!response.ok) throw new Error('publish_question_failed'); const { question: next } = await parseDiagnosticResponse(response, publishedQuestionResponseSchema); if (!controller.signal.aborted && current()) { @@ -495,16 +571,19 @@ function QuestionWorkspace({ owner, choirId, sessionId, userId, canPublishOffici setScoreId(next.scoreId ?? ''); setFileChoice(next.attachmentId ? `${next.attachmentId}:${next.revision}` : ''); setSaved(next); setSourceMode('saved'); setUpload(null); setEditing(false); } - } catch { if (!controller.signal.aborted && current()) setFailed(true); } + } catch { if (!controller.signal.aborted) setFailed(true); } finally { saveLifetime.current = null; if (!controller.signal.aborted) setSaving(false); } }; const recordResult = async (attempt: SightSingingResultSubmission): Promise => { - if (!saved) throw new Error('result_question_missing'); + if (!saved || !cloudAvailable.current || !navigator.onLine) throw new Error('result_publication_unavailable'); const controller = new AbortController(), current = captureNavigationIdentity(); resultLifetimes.current.add(controller); try { - const result = await publishSightSingingResult(choirId, saved.id, userId, attempt, controller.signal); - if (!controller.signal.aborted && current()) setResultGeneration(value => value + 1); + const signal = AbortSignal.any([controller.signal, AbortSignal.timeout(30_000)]); + const result = await publishSightSingingResult(choirId, saved.id, userId, attempt, signal); + signal.throwIfAborted(); + if (!current()) throw new Error('result_publication_unconfirmed'); + setResultGeneration(value => value + 1); return result; } finally { resultLifetimes.current.delete(controller); @@ -527,7 +606,7 @@ function QuestionWorkspace({ owner, choirId, sessionId, userId, canPublishOffici {canEdit && } {saved && }