diff --git a/apps/editor/src/SdkEditorRoot.test.tsx b/apps/editor/src/SdkEditorRoot.test.tsx index f75f20152..455c6ef6e 100644 --- a/apps/editor/src/SdkEditorRoot.test.tsx +++ b/apps/editor/src/SdkEditorRoot.test.tsx @@ -88,6 +88,44 @@ describe("SdkEditorRoot behind the shared collection gate", () => { } finally { error.mockRestore(); } }); + it("rechecks the approved connection when its readiness is missing after access is restored", async () => { + const h = await readyFixture(); + const ready = h.mdbase.getSnapshot(); + const missing = { ...ready, status: "blocked" as const, problem: "application_readiness_unavailable", + readiness: { ...ready.readiness, assessment: null } }; + let completeAssessment!: (value: typeof ready) => void; + const assessment = new Promise((resolve) => { completeAssessment = resolve; }); + h.controls.setHandler("assess", () => assessment); + render(

Workspace ready

} />
); + await screen.findByText("Workspace ready"); + + act(() => h.controls.publishSnapshot({ ...ready, status: "blocked", problem: "installation_scope_removed", selectedCollectionId: null })); + expect(screen.getByRole("button", { name: "Request access again" })).toBeInTheDocument(); + expect(h.calls("assess")).toHaveLength(0); + + act(() => h.controls.publishSnapshot(missing)); + expect(screen.getByText("Opening collection")).toBeInTheDocument(); + expect(screen.queryByText("Workspace ready")).not.toBeInTheDocument(); + expect(h.calls("assess")).toHaveLength(1); + await act(async () => completeAssessment(ready)); + expect(await screen.findByText("Workspace ready")).toBeInTheDocument(); + expect(h.calls("assess")).toHaveLength(1); + expect(h.calls("start")).toHaveLength(0); + expect(h.calls("close")).toHaveLength(0); + }); + + it("offers the SDK's reload action if the readiness recheck still fails", async () => { + const h = await readyFixture(); + const ready = h.mdbase.getSnapshot(); + h.controls.setHandler("assess", () => Promise.reject(new Error("Fixture readiness recheck failed"))); + render(

Workspace ready

} />
); + act(() => h.controls.publishSnapshot({ ...ready, status: "blocked", problem: "application_readiness_unavailable" })); + expect(await screen.findByRole("button", { name: /reload/i })).toBeInTheDocument(); + expect(screen.queryByText("mdbase editor needs to restart")).not.toBeInTheDocument(); + expect(h.calls("assess")).toHaveLength(1); + }); + it("StrictMode unmounting releases its subscriptions and never closes the SDK", async () => { const h = await testApp({ phase: "signed_out" }); const { sdk, subscriptions } = observed(h.mdbase); diff --git a/apps/editor/src/SdkEditorRoot.tsx b/apps/editor/src/SdkEditorRoot.tsx index ac15a7f09..83549515e 100644 --- a/apps/editor/src/SdkEditorRoot.tsx +++ b/apps/editor/src/SdkEditorRoot.tsx @@ -75,6 +75,10 @@ export function SdkEditorRoot({ sdk, renderNative, onFeedbackContext, privateCol const snapshot = useSyncExternalStore((listener) => sdk.subscribe(listener), () => sdk.getSnapshot(), () => sdk.getSnapshot()); // Developer-only detail (e.g. which manifest fields a registration refusal named): logs, never the screen. const problem = snapshot.status === "blocked" ? describeError(snapshot) : null; + const readinessMissing = snapshot.status === "blocked" && snapshot.problem === "application_readiness_unavailable"; + const readinessConnection = readinessMissing && snapshot.phase.kind === "problem" && snapshot.phase.problem.key === "application_failed" + && snapshot.selectedCollectionId ? sdk.connection(snapshot.selectedCollectionId) : null; + const recheckingReadiness = useReadinessRecheck(sdk, readinessConnection); const waiting = snapshot.phase.kind === "problem" && privateWaitReason(snapshot.phase.problem.key); const waitingHeading = waiting ? t`Waiting for your computer to serve this collection` : undefined; const developerMessage = problem?.developerMessage ?? null; @@ -103,7 +107,8 @@ export function SdkEditorRoot({ sdk, renderNative, onFeedbackContext, privateCol if (declaration && snapshot.links && editorPortalUrl() !== new URL(snapshot.links.account).origin) return Return to Collections and open the collection again. ; - if (problem?.key === "application_failed") throw new Error(`Editor SDK invariant failed: ${snapshot.problem}`); + if (recheckingReadiness) return ; + if (problem?.key === "application_failed" && !readinessMissing) throw new Error(`Editor SDK invariant failed: ${snapshot.problem}`); // Before connecting, the gate shows where the work is kept above the editor; // once a collection is open, it offers to bring that work in. The frame stacks // those lines above the editor without pushing it past the viewport. @@ -125,6 +130,22 @@ export function SdkEditorRoot({ sdk, renderNative, onFeedbackContext, privateCol ; } +function useReadinessRecheck(sdk: Mdbase, connection: EditorConnection | null) { + const attempted = useRef(null); + const [settled, setSettled] = useState(null); + useEffect(() => { + if (!connection?.isCurrent() || attempted.current === connection) return; + // An attached tab can have ports for the newly approved collection before + // it has a settled readiness assessment. Recheck that scope once. If it + // still can't open, the shared gate shows the SDK's reload action. + attempted.current = connection; + void sdk.assess().catch(() => {}).finally(() => { + if (attempted.current === connection) setSettled(connection); + }); + }, [sdk, connection]); + return connection !== settled && Boolean(connection?.isCurrent()); +} + function privateWaitReason(key?: string) { return key === "device_offline" || key === "device_not_serving" ? key : undefined; } diff --git a/apps/editor/tests/editor-regressions.spec.ts b/apps/editor/tests/editor-regressions.spec.ts index aa05fa9be..3e4945468 100644 --- a/apps/editor/tests/editor-regressions.spec.ts +++ b/apps/editor/tests/editor-regressions.spec.ts @@ -67,6 +67,40 @@ test("two tabs of the same Editor build share their workspace across reloads", a expect(leaders).toBe(1); }); +test("an already-open second Editor tab resumes editing after re-approval", async ({ context, page }) => { + const other = await context.newPage(); + await page.goto(`${fixture}?scenario=reauth-leader`); + await other.goto(`${fixture}?scenario=reauth-follower`); + const note = (tab: typeof page) => tab.getByRole("textbox", { name: "Note body" }); + await expect(note(page)).toBeEditable(); + await expect(note(other)).toHaveText("Before re-approval"); + const navigations: string[] = []; + const errors: string[] = []; + other.on("framenavigated", frame => { if (frame === other.mainFrame()) navigations.push(frame.url()); }); + other.on("pageerror", error => errors.push(error.message)); + + await page.evaluate(() => { + const channel = new BroadcastChannel("editor-reapproval-fixture"); + channel.postMessage("removed"); + channel.close(); + }); + await expect(note(other)).toHaveCount(0); + const popup = other.waitForEvent("popup"); + await other.getByRole("button", { name: "Request access again" }).click(); + const portal = await popup; + await portal.getByRole("button", { name: "Approve access" }).click(); + await expect(note(other)).toBeEditable(); + await expect(note(page)).toBeEditable(); + await note(other).fill("Saved after re-approval"); + type FixtureWindow = Window & { reapprovalFixture: import("@mdbase-dev/sdk/testing").TestApp }; + await expect.poll(() => other.evaluate(() => + (window as FixtureWindow).reapprovalFixture.replica().allRecords[0].body)).toBe("Saved after re-approval"); + expect(await other.evaluate(() => (window as FixtureWindow).reapprovalFixture.controls.observedActions() + .filter(call => call.action === "assess").length)).toBe(1); + expect(navigations).toEqual([]); + expect(errors).toEqual([]); +}); + test("history recognizes this Editor and describes the earliest external version", async ({ page }) => { await page.goto(fixture); await page.getByRole("button", { name: "Version history", exact: true }).click(); diff --git a/apps/editor/tests/fixtures/editor-regressions.tsx b/apps/editor/tests/fixtures/editor-regressions.tsx index 7bf949478..b9c779a4c 100644 --- a/apps/editor/tests/fixtures/editor-regressions.tsx +++ b/apps/editor/tests/fixtures/editor-regressions.tsx @@ -13,6 +13,7 @@ import { DirectEditor } from "../../direct/DirectEditor"; import { SdkEditorRoot } from "../../src/SdkEditorRoot"; import { editorLocaleRuntime } from "../../src/i18n/runtime"; import type { NoteVersion } from "../../src/model"; +import { AppErrorBoundary } from "../../src/AppErrorBoundary"; import manifest from "../../public/.well-known/mdbase-app.json"; const params = new URLSearchParams(location.search); @@ -25,6 +26,47 @@ function render(content: React.ReactNode) { root.render({content}); } +async function reapprovalFixture() { + // Exercise the mounted Editor boundary with the SDK's public test front door. + // The fixture controls the Portal outcome and the order of tab snapshots. + const channel = new BroadcastChannel("editor-reapproval-fixture"); + if (scenario === "reauth-portal") { + render(); + return; + } + const fixture = await createTestApp({ collections: [{ id: "55555555-5555-4555-8555-555555555555", name: "Shared notes", + records: [{ path: "note.md", body: "Before re-approval" }] }] }); + Object.assign(window, { reapprovalFixture: fixture }); + const ready = fixture.mdbase.getSnapshot(); + if (ready.phase.kind !== "ready" || ready.signIn?.state !== "paired") throw new Error("Expected a paired open collection"); + const previous = ready.phase.connection; + const replacement = { ...previous, generation: crypto.randomUUID(), + scope: { ...previous.scope, installation: "replacement-installation" }, isCurrent: () => true }; + const reapproved = { ...ready, signIn: { ...ready.signIn, installationId: replacement.scope.installation } }; + let completeApproval!: () => void; + const approval = new Promise((resolve) => { completeApproval = resolve; }); + fixture.controls.setHandler("approve", () => { + window.open("?scenario=reauth-portal", "reauth-portal"); + fixture.controls.publishSnapshot({ ...fixture.mdbase.getSnapshot(), status: "authorizing", problem: null }); + return approval; + }); + fixture.controls.setHandler("assess", () => reapproved); + channel.onmessage = ({ data }) => { + if (data === "removed") { + fixture.controls.publishSnapshot({ ...ready, status: "blocked", problem: "installation_scope_removed", + selectedCollectionId: null, collections: [] }); + } + if (data === "approved") { + fixture.controls.setConnections([replacement]); + fixture.controls.publishSnapshot(scenario === "reauth-follower" ? { ...reapproved, status: "blocked", + problem: "application_readiness_unavailable", + readiness: { ...reapproved.readiness, assessment: null } } : reapproved); + completeApproval(); + } + }; + render(); +} + async function start() { if (scenario === "local-stack") { // Served only by the loopback CLI/Chromium runner, with its own build-time trust. @@ -60,6 +102,10 @@ async function start() { render(); return; } + if (scenario === "reauth-leader" || scenario === "reauth-follower" || scenario === "reauth-portal") { + await reapprovalFixture(); + return; + } const waitingToOpen = scenario === "private-wait"; const fixture = await createTestApp({ collections: [{ name: "Test notes", contracts: [] }], phase: waitingToOpen ? { problem: "device_not_serving" } : "ready" }); diff --git a/changelog.d/editor-reauthorization-readiness.md b/changelog.d/editor-reauthorization-readiness.md new file mode 100644 index 000000000..bde63baa7 --- /dev/null +++ b/changelog.d/editor-reauthorization-readiness.md @@ -0,0 +1,4 @@ +## Fixed + +- Editor retries the collection readiness check after access is restored in an + open tab, so editing can resume without reloading the page.