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
38 changes: 38 additions & 0 deletions apps/editor/src/SdkEditorRoot.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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<typeof ready>((resolve) => { completeAssessment = resolve; });
h.controls.setHandler("assess", () => assessment);
render(<StrictMode><AppErrorBoundary><SdkEditorRoot sdk={h.mdbase}
renderNative={() => <p>Workspace ready</p>} /></AppErrorBoundary></StrictMode>);
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(<AppErrorBoundary><SdkEditorRoot sdk={h.mdbase} renderNative={() => <p>Workspace ready</p>} /></AppErrorBoundary>);
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);
Expand Down
23 changes: 22 additions & 1 deletion apps/editor/src/SdkEditorRoot.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -103,7 +107,8 @@ export function SdkEditorRoot({ sdk, renderNative, onFeedbackContext, privateCol
if (declaration && snapshot.links && editorPortalUrl() !== new URL(snapshot.links.account).origin) return <EditorEntryPage title={t`This collection link is invalid`}>
<Trans>Return to Collections and open the collection again.</Trans>
</EditorEntryPage>;
if (problem?.key === "application_failed") throw new Error(`Editor SDK invariant failed: ${snapshot.problem}`);
if (recheckingReadiness) return <OpeningScreen />;
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.
Expand All @@ -125,6 +130,22 @@ export function SdkEditorRoot({ sdk, renderNative, onFeedbackContext, privateCol
</div>;
}

function useReadinessRecheck(sdk: Mdbase, connection: EditorConnection | null) {
const attempted = useRef<EditorConnection | null>(null);
const [settled, setSettled] = useState<EditorConnection | null>(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;
}
Expand Down
34 changes: 34 additions & 0 deletions apps/editor/tests/editor-regressions.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down
46 changes: 46 additions & 0 deletions apps/editor/tests/fixtures/editor-regressions.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand All @@ -25,6 +26,47 @@ function render(content: React.ReactNode) {
root.render(<LocaleProvider runtime={editorLocaleRuntime}>{content}</LocaleProvider>);
}

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(<button onClick={() => channel.postMessage("approved")}>Approve access</button>);
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<void>((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(<AppErrorBoundary><SdkEditorRoot sdk={fixture.mdbase} /></AppErrorBoundary>);
}

async function start() {
if (scenario === "local-stack") {
// Served only by the loopback CLI/Chromium runner, with its own build-time trust.
Expand Down Expand Up @@ -60,6 +102,10 @@ async function start() {
render(<SdkEditorRoot sdk={sdk} />);
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" });
Expand Down
4 changes: 4 additions & 0 deletions changelog.d/editor-reauthorization-readiness.md
Original file line number Diff line number Diff line change
@@ -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.