diff --git a/apps/web/package.json b/apps/web/package.json index c34d9c1..ac8773d 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -1,6 +1,6 @@ { "name": "@pseudoeditor/web", - "version": "0.1.9", + "version": "2.0.0", "private": true, "description": "Next.js browser app and website for PseudoEditor.", "author": "Alex Xin LIU", @@ -27,7 +27,7 @@ "idb": "^8.0.3", "lucide-react": "^0.577.0", "monaco-editor": "^0.55.1", - "next": "16.4.3", + "next": "16.4.5", "posthog-js": "^1.440.0", "posthog-node": "^5.57.2", "react": "19.2.3", @@ -43,7 +43,7 @@ "@vitest/coverage-v8": "^4.1.11", "cross-env": "^10.1.0", "eslint": "^9.39.5", - "eslint-config-next": "16.4.3", + "eslint-config-next": "16.4.5", "jsdom": "^28.1.0", "tailwindcss": "^4.3.3", "typescript": "^5.9.3", diff --git a/apps/web/src/app/[locale]/app/page.test.tsx b/apps/web/src/app/[locale]/app/page.test.tsx index 314d1cb..150e246 100644 --- a/apps/web/src/app/[locale]/app/page.test.tsx +++ b/apps/web/src/app/[locale]/app/page.test.tsx @@ -120,6 +120,10 @@ vi.mock("@/lib/storage", () => ({ takeAccountSyncPending: vi.fn(() => false), takeRecoveredCopies: vi.fn(() => false), isAccountUnreachable: vi.fn(() => false), + takeGuestImported: vi.fn(() => false), + stashGuestDraft: vi.fn(), + isWorkspaceConflictError: vi.fn(() => false), + getWorkspaceTooLargeDetail: vi.fn(() => null), })); /** Makes loadWorkspace resolve to `workspace`. */ diff --git a/apps/web/src/app/[locale]/app/page.tsx b/apps/web/src/app/[locale]/app/page.tsx index a5bdf00..dc2a73a 100644 --- a/apps/web/src/app/[locale]/app/page.tsx +++ b/apps/web/src/app/[locale]/app/page.tsx @@ -389,6 +389,7 @@ export default function HomePage() { cloudSyncLoading: cloudSavingRequired ? authLoading : false, checkpointOwner: userId ?? null, recoveredFolderName: t.sync.recoveredFolder, + guestFolderName: t.sync.guestFolder, }); /* ── local state ── */ @@ -575,7 +576,9 @@ export default function HomePage() { ? t.save.failedKeptManual : saveError?.startsWith("Autosave failed") ? t.save.failedKeptAuto - : saveError; + : saveError?.startsWith("Too large: ") + ? t.sync.tooLarge(saveError.slice("Too large: ".length)) + : saveError; const flowchartVisible = showFlowchart; const currentSource = currentDocument?.source ?? ""; // The flowchart stays mounted while hidden; only feed it source updates while it is visible. @@ -1922,18 +1925,24 @@ export default function HomePage() { ); } if (!syncNotice) return null; - const unreachable = syncNotice === "account-unreachable"; + const needsReload = syncNotice === "account-unreachable" || syncNotice === "account-changed"; + const message = + syncNotice === "account-unreachable" + ? t.sync.accountUnreachable + : syncNotice === "account-changed" + ? t.sync.conflict + : syncNotice === "guest-imported" + ? t.sync.guestImported + : t.sync.recoveredCopies; return (
- - {unreachable ? t.sync.accountUnreachable : t.sync.recoveredCopies} - + {message}
); @@ -2233,7 +2242,7 @@ export default function HomePage() {
{renderSyncNotice()} - {saveError && syncNotice !== "account-unreachable" && {localizedSaveError}} + {saveError && syncNotice !== "account-unreachable" && syncNotice !== "account-changed" && {localizedSaveError}} {appNotice && (
{renderSyncNotice()} - {saveError && syncNotice !== "account-unreachable" && {localizedSaveError}} + {saveError && syncNotice !== "account-unreachable" && syncNotice !== "account-changed" && {localizedSaveError}} {appNotice && (
& { _id: string; clerkUserId: string }; + +/** Just enough of Convex's ctx for the workspace functions: one signed-in user and an in-memory table per name. */ +function createCtx(subject = "user_a") { + const tables = new Map(); + const table = (name: string) => tables.get(name) ?? tables.set(name, []).get(name)!; + let nextId = 0; + const ctx = { + auth: { getUserIdentity: async () => ({ subject, email: "student@example.com" }) }, + db: { + query: (name: string) => ({ + withIndex: (_index: string, build: (q: { eq: (field: string, value: unknown) => unknown }) => unknown) => { + let filter: [string, unknown] = ["", undefined]; + build({ eq: (field, value) => (filter = [field, value]) }); + return { unique: async () => table(name).find((row) => row[filter[0]] === filter[1]) ?? null }; + }, + }), + insert: async (name: string, value: Record) => { + const row = { ...value, _id: `${name}_${nextId++}` } as Row; + table(name).push(row); + return row._id; + }, + patch: async (id: string, value: Record) => { + for (const rows of tables.values()) { + const row = rows.find((candidate) => candidate._id === id); + if (row) Object.assign(row, value); + } + }, + }, + }; + return ctx; +} + +type Handler = { _handler: (ctx: unknown, args: Args) => Promise }; +const save = (saveCurrent as unknown as Handler, { ok: boolean; revision: number | null }>)._handler; +const read = (getCurrentSnapshot as unknown as Handler, { workspaceJson: string | null; revision: number } | null>)._handler; + +const user = { email: "student@example.com", firstName: null, lastName: null }; +const workspaceJson = (source: string, extra: Record = {}) => + JSON.stringify({ ...createDefaultWorkspace({ sampleSource: source }), ...extra }); + +describe("convex workspaces", () => { + it("bumps the revision on each save and refuses a save built on an older revision", async () => { + const ctx = createCtx(); + await expect(save(ctx, { user, workspaceJson: workspaceJson("OUTPUT 1"), expectedRevision: null })).resolves.toEqual({ ok: true, revision: 1 }); + await expect(save(ctx, { user, workspaceJson: workspaceJson("OUTPUT 2"), expectedRevision: 1 })).resolves.toEqual({ ok: true, revision: 2 }); + + // A second device still on revision 1 must not replace revision 2. + await expect(save(ctx, { user, workspaceJson: workspaceJson("OUTPUT stale"), expectedRevision: 1 })).resolves.toMatchObject({ ok: false, revision: 2 }); + // Nor may a client that thinks the account has no workspace yet. + await expect(save(ctx, { user, workspaceJson: workspaceJson("OUTPUT new"), expectedRevision: null })).resolves.toMatchObject({ ok: false }); + + const snapshot = await read(ctx, {}); + expect(snapshot?.revision).toBe(2); + expect(snapshot?.workspaceJson).toContain("OUTPUT 2"); + }); + + it("keeps last-write-wins for older clients that send no revision", async () => { + const ctx = createCtx(); + await save(ctx, { user, workspaceJson: workspaceJson("OUTPUT 1") }); + await expect(save(ctx, { user, workspaceJson: workspaceJson("OUTPUT 2") })).resolves.toEqual({ ok: true, revision: 2 }); + }); + + it("returns the workspace as text so data files with non-ASCII names can be read back", async () => { + const ctx = createCtx(); + await save(ctx, { user, workspaceJson: workspaceJson("OUTPUT 1", { virtualFiles: { "成绩.txt": ["90"] } }) }); + const snapshot = await read(ctx, {}); + expect(typeof snapshot?.workspaceJson).toBe("string"); + expect(JSON.parse(snapshot!.workspaceJson!).virtualFiles).toEqual({ "成绩.txt": ["90"] }); + }); +}); diff --git a/apps/web/src/app/api/workspace/route.test.ts b/apps/web/src/app/api/workspace/route.test.ts index cac8d78..0ad7de4 100644 --- a/apps/web/src/app/api/workspace/route.test.ts +++ b/apps/web/src/app/api/workspace/route.test.ts @@ -25,6 +25,7 @@ vi.mock("../../../../../../convex/_generated/api", () => ({ api: { workspaces: { getCurrent: "workspaces:getCurrent", + getCurrentSnapshot: "workspaces:getCurrentSnapshot", saveCurrent: "workspaces:saveCurrent", }, }, @@ -53,7 +54,7 @@ describe("/api/workspace", () => { convexToken: "convex-token", claims: { email: "alex@example.com" }, }); - mutationMock.mockResolvedValue("workspace_id"); + mutationMock.mockResolvedValue({ ok: true, revision: 1 }); const { PUT } = await import("./route"); const response = await PUT( @@ -75,6 +76,37 @@ describe("/api/workspace", () => { }, workspaceJson: expect.any(String), }); + await expect(response.json()).resolves.toEqual({ ok: true, revision: 1 }); + }); + + it("passes the expected revision to Convex and reports a conflicting save as 409", async () => { + const workspace = createDefaultWorkspace({ sampleSource: 'OUTPUT "Stale"' }); + authMock.mockResolvedValue({ userId: "user_123", convexToken: "convex-token", claims: { email: "alex@example.com" } }); + mutationMock.mockResolvedValue({ ok: false, conflict: true, revision: 4 }); + + const { PUT } = await import("./route"); + const response = await PUT( + new Request("https://app.test/api/workspace", { + method: "PUT", + body: JSON.stringify({ workspace, expectedRevision: 3 }), + }), + ); + + expect(mutationMock).toHaveBeenCalledWith("workspaces:saveCurrent", expect.objectContaining({ expectedRevision: 3 })); + expect(response.status).toBe(409); + await expect(response.json()).resolves.toMatchObject({ conflict: true }); + }); + + it("returns the account workspace and its revision, including data files with non-ASCII names", async () => { + const workspace = { ...createDefaultWorkspace({ sampleSource: 'OUTPUT "Cloud"' }), virtualFiles: { "成绩.txt": ["90"] } }; + authMock.mockResolvedValue({ userId: "user_123", convexToken: "convex-token", claims: { email: "alex@example.com" } }); + queryMock.mockResolvedValue({ workspaceJson: JSON.stringify(workspace), revision: 7 }); + + const { GET } = await import("./route"); + const response = await GET(new Request("https://app.test/api/workspace")); + + expect(queryMock).toHaveBeenCalledWith("workspaces:getCurrentSnapshot", {}); + await expect(response.json()).resolves.toEqual({ workspace, revision: 7 }); }); it("rejects malformed workspace bodies before Convex mutation", async () => { @@ -115,4 +147,24 @@ describe("/api/workspace", () => { expect(response.status).toBe(413); expect(mutationMock).not.toHaveBeenCalled(); }); + + it("refuses a request made for a different account than the one signed in", async () => { + const workspace = createDefaultWorkspace({ sampleSource: 'OUTPUT "Account A draft"' }); + authMock.mockResolvedValue({ userId: "user_b", convexToken: "convex-token", claims: { email: "b@example.com" } }); + + const { GET, PUT } = await import("./route"); + const put = await PUT( + new Request("https://app.test/api/workspace", { + method: "PUT", + headers: { "X-Workspace-Account": "user_a" }, + body: JSON.stringify({ workspace, expectedRevision: 1 }), + }), + ); + const get = await GET(new Request("https://app.test/api/workspace", { headers: { "X-Workspace-Account": "user_a" } })); + + expect(put.status).toBe(403); + expect(get.status).toBe(403); + expect(mutationMock).not.toHaveBeenCalled(); + expect(queryMock).not.toHaveBeenCalled(); + }); }); diff --git a/apps/web/src/app/api/workspace/route.ts b/apps/web/src/app/api/workspace/route.ts index 3f16ced..cbdb76c 100644 --- a/apps/web/src/app/api/workspace/route.ts +++ b/apps/web/src/app/api/workspace/route.ts @@ -25,6 +25,17 @@ function getConvexClient(authToken: string) { return new ConvexHttpClient(convexUrl, { auth: authToken }); } +/** + * The client names the account a request was made for. After an account switch a leftover request can carry the new + * account's sign-in, so a mismatch is refused instead of reading or overwriting the other account's workspace. + */ +function rejectOtherAccount(request: Request, userId: string) { + const intended = request.headers.get("x-workspace-account"); + return intended && intended !== userId + ? NextResponse.json({ error: "This request was made for a different account." }, { status: 403 }) + : null; +} + async function readWorkspaceRequestBody(request: Request) { const rawBody = await request.text(); if (getUtf8ByteLength(rawBody) > maxWorkspaceRequestBytes) { @@ -63,9 +74,17 @@ async function readWorkspaceRequestBody(request: Request) { }; } + // The revision the client last read (`null`: it saw no workspace). Older clients send none and keep last-write-wins. + const rawExpectedRevision = (body as { expectedRevision?: unknown }).expectedRevision; + const expectedRevision = + rawExpectedRevision === null || (typeof rawExpectedRevision === "number" && Number.isSafeInteger(rawExpectedRevision)) + ? rawExpectedRevision + : undefined; + return { ok: true as const, workspaceJson: validation.serializedWorkspace, + expectedRevision, }; } @@ -87,9 +106,18 @@ export async function GET(request: Request) { return NextResponse.json({ error: "Workspace authentication token is not configured." }, { status: 503 }); } - const workspace = await getConvexClient(requestAuth.convexToken).query(api.workspaces.getCurrent, {}); + const otherAccount = rejectOtherAccount(request, requestAuth.userId); + if (otherAccount) { + return otherAccount; + } + + const snapshot = await getConvexClient(requestAuth.convexToken).query(api.workspaces.getCurrentSnapshot, {}); + const workspace = snapshot?.workspaceJson ? (JSON.parse(snapshot.workspaceJson) as unknown) : null; - return NextResponse.json({ workspace }, { headers: { "Cache-Control": "private, no-store" } }); + return NextResponse.json( + { workspace, revision: snapshot ? snapshot.revision : null }, + { headers: { "Cache-Control": "private, no-store" } }, + ); } export async function PUT(request: Request) { @@ -113,15 +141,28 @@ export async function PUT(request: Request) { return NextResponse.json({ error: "Workspace authentication token is not configured." }, { status: 503 }); } + const otherAccount = rejectOtherAccount(request, requestAuth.userId); + if (otherAccount) { + return otherAccount; + } + const body = await readWorkspaceRequestBody(request); if (!body.ok) { return body.response; } - await getConvexClient(requestAuth.convexToken).mutation(api.workspaces.saveCurrent, { + const result = await getConvexClient(requestAuth.convexToken).mutation(api.workspaces.saveCurrent, { user: buildWorkspaceSyncUser(requestAuth.claims), workspaceJson: body.workspaceJson, + ...(body.expectedRevision !== undefined ? { expectedRevision: body.expectedRevision } : {}), }); - return NextResponse.json({ ok: true }); + if (!result.ok) { + return NextResponse.json( + { error: "The workspace changed in another tab or on another device.", conflict: true }, + { status: 409 }, + ); + } + + return NextResponse.json({ ok: true, revision: result.revision }); } diff --git a/apps/web/src/app/components/WorkspaceSidebar.tsx b/apps/web/src/app/components/WorkspaceSidebar.tsx index f0bfbe7..6187c5a 100644 --- a/apps/web/src/app/components/WorkspaceSidebar.tsx +++ b/apps/web/src/app/components/WorkspaceSidebar.tsx @@ -76,7 +76,7 @@ const CONTEXT_MENU_HEIGHT = 320; const CONTEXT_MENU_MARGIN = 14; const deleteKeyLabel = typeof navigator !== "undefined" && /mac|iphone|ipad/i.test(navigator.platform ?? "") ? "⌫" : "Del"; -const EXPLORER_RELEASE_LABEL = `${packageJson.version}-Preview`; +const EXPLORER_RELEASE_LABEL = `v${packageJson.version}`; const DRAG_EDGE_SCROLL_ZONE = 34; const DRAG_EDGE_SCROLL_STEP = 14; diff --git a/apps/web/src/app/hooks/useWorkspaceSession.test.tsx b/apps/web/src/app/hooks/useWorkspaceSession.test.tsx new file mode 100644 index 0000000..9738d4e --- /dev/null +++ b/apps/web/src/app/hooks/useWorkspaceSession.test.tsx @@ -0,0 +1,164 @@ +import { act, renderHook, waitFor } from "@testing-library/react"; +import { createDocument, createEmptyWorkspace, updateVirtualFiles, type WorkspaceState } from "@pseudoeditor/workspace"; +import { beforeEach, describe, expect, it, vi } from "vitest"; + +const storage = vi.hoisted(() => ({ + loadWorkspace: vi.fn(), + saveWorkspace: vi.fn(), + saveDeviceCheckpoint: vi.fn(), + stashGuestDraft: vi.fn(), + takeGuestImported: vi.fn(), + takeRecoveredCopies: vi.fn(), + takeAccountSyncPending: vi.fn(), + isAccountUnreachable: vi.fn(), + isWorkspaceConflictError: vi.fn(), + getWorkspaceTooLargeDetail: vi.fn(), +})); + +vi.mock("@/lib/storage", () => storage); +vi.mock("@/lib/analytics", () => ({ track: vi.fn() })); +const { runMock, compileMock } = vi.hoisted(() => ({ runMock: vi.fn(), compileMock: vi.fn() })); +vi.mock("@/runtime/executeRuntime", () => ({ pseudocodeRuntimeRunner: { run: runMock } })); +vi.mock("@/compiler", () => ({ compilePseudocode: compileMock })); + +import { useWorkspaceSession } from "./useWorkspaceSession"; + +describe("useWorkspaceSession", () => { + beforeEach(() => { + for (const mock of Object.values(storage)) mock.mockReset(); + runMock.mockReset(); + compileMock.mockReset(); + storage.loadWorkspace.mockImplementation(async () => createEmptyWorkspace()); + storage.saveWorkspace.mockResolvedValue(undefined); + storage.saveDeviceCheckpoint.mockResolvedValue(undefined); + storage.getWorkspaceTooLargeDetail.mockReturnValue(null); + storage.isWorkspaceConflictError.mockImplementation((error: unknown) => error instanceof Error && error.name === "WorkspaceConflictError"); + }); + + it("keeps a guest's files when they sign in, and tells them where the files went", async () => { + const { result, rerender } = renderHook( + ({ signedIn }: { signedIn: boolean }) => + useWorkspaceSession("", { + persistenceMode: signedIn ? "cloud" : "memory", + checkpointOwner: signedIn ? "user_a" : null, + guestFolderName: "Guest", + }), + { initialProps: { signedIn: false } }, + ); + await waitFor(() => expect(result.current.workspace).not.toBeNull()); + act(() => { + result.current.createDocumentInWorkspace(undefined, { name: "draft", source: 'OUTPUT "guest work"' }); + }); + + storage.takeGuestImported.mockReturnValueOnce(true); + rerender({ signedIn: true }); + + await waitFor(() => expect(result.current.syncNotice).toBe("guest-imported")); + const stashed = storage.stashGuestDraft.mock.calls.at(-1)?.[0] as WorkspaceState; + expect(Object.values(stashed.nodes).some((node) => node.type === "document" && node.source === 'OUTPUT "guest work"')).toBe(true); + // The guest work is stashed before the account load that imports it. + expect(storage.stashGuestDraft.mock.invocationCallOrder.at(-1)!).toBeLessThan(storage.loadWorkspace.mock.invocationCallOrder.at(-1)!); + expect(storage.loadWorkspace).toHaveBeenLastCalledWith("", expect.objectContaining({ mode: "cloud", checkpointOwner: "user_a", guestFolderName: "Guest" })); + }); + + it("asks for a reload when another tab or device saved first", async () => { + const conflict = Object.assign(new Error("changed"), { name: "WorkspaceConflictError" }); + storage.saveWorkspace.mockRejectedValue(conflict); + const { result } = renderHook(() => useWorkspaceSession("", { persistenceMode: "cloud", checkpointOwner: "user_a" })); + await waitFor(() => expect(result.current.workspace).not.toBeNull()); + + act(() => { + result.current.createDocumentInWorkspace(undefined, { name: "essay", source: "OUTPUT 1" }); + }); + + await waitFor(() => expect(result.current.syncNotice).toBe("account-changed")); + expect(result.current.saveError).not.toBeNull(); + }); + + it("says cloud saving is paused, and why, when the account refuses the workspace as too large", async () => { + const tooLarge = Object.assign(new Error("Workspace payload has too many nodes (501/500)."), { name: "WorkspaceTooLargeError" }); + storage.saveWorkspace.mockRejectedValue(tooLarge); + storage.getWorkspaceTooLargeDetail.mockImplementation((error: unknown) => (error === tooLarge ? tooLarge.message : null)); + const { result } = renderHook(() => useWorkspaceSession("", { persistenceMode: "cloud", checkpointOwner: "user_a" })); + await waitFor(() => expect(result.current.workspace).not.toBeNull()); + + act(() => { + result.current.createDocumentInWorkspace(undefined, { name: "essay", source: "OUTPUT 1" }); + }); + + await waitFor(() => expect(result.current.saveError).toBe("Too large: Workspace payload has too many nodes (501/500).")); + }); + + it("never lets a run started before signing in replace the account's data files", async () => { + const account = updateVirtualFiles(createDocument(createEmptyWorkspace(), { name: "essay", source: "OUTPUT 1" }), { + "results.txt": ["saved in the account"], + }); + storage.loadWorkspace.mockImplementation(async (_source: string, options: { mode?: string }) => + options.mode === "cloud" ? account : createEmptyWorkspace(), + ); + compileMock.mockReturnValue({ success: true, diagnostics: [], astJson: "{}" }); + let finishRun: (result: unknown) => void = () => {}; + runMock.mockImplementation(() => new Promise((resolve) => { finishRun = resolve; })); + const { result, rerender } = renderHook( + ({ signedIn }: { signedIn: boolean }) => + useWorkspaceSession("", { persistenceMode: signedIn ? "cloud" : "memory", checkpointOwner: signedIn ? "user_a" : null }), + { initialProps: { signedIn: false } }, + ); + await waitFor(() => expect(result.current.workspace).not.toBeNull()); + act(() => { + result.current.createDocumentInWorkspace(undefined, { name: "guest", source: 'OUTPUT "x"' }); + }); + + // The guest starts a run, then signs in while it is still running. + let run: Promise = Promise.resolve(); + act(() => { + run = result.current.runNow(); + }); + await waitFor(() => expect(runMock).toHaveBeenCalled()); + rerender({ signedIn: true }); + await waitFor(() => expect(result.current.workspace?.virtualFiles).toEqual({ "results.txt": ["saved in the account"] })); + + await act(async () => { + finishRun({ success: true, stdout: "done", stderr: "", diagnostics: [], virtualFiles: {} }); + await run; + }); + expect(result.current.workspace?.virtualFiles).toEqual({ "results.txt": ["saved in the account"] }); + }); + + it("drops a run whose workspace was replaced while it was still compiling", async () => { + const account = updateVirtualFiles(createDocument(createEmptyWorkspace(), { name: "essay", source: "OUTPUT 1" }), { + "results.txt": ["saved in the account"], + }); + storage.loadWorkspace.mockImplementation(async (_source: string, options: { mode?: string }) => + options.mode === "cloud" ? account : createEmptyWorkspace(), + ); + // Live diagnostics compile too, so hold every compile and release them all at once. + const pendingCompiles: Array<(result: unknown) => void> = []; + compileMock.mockImplementation(() => new Promise((resolve) => { pendingCompiles.push(resolve); })); + runMock.mockResolvedValue({ success: true, stdout: "done", stderr: "", diagnostics: [], virtualFiles: {} }); + const { result, rerender } = renderHook( + ({ signedIn }: { signedIn: boolean }) => + useWorkspaceSession("", { persistenceMode: signedIn ? "cloud" : "memory", checkpointOwner: signedIn ? "user_a" : null }), + { initialProps: { signedIn: false } }, + ); + await waitFor(() => expect(result.current.workspace).not.toBeNull()); + act(() => { + result.current.createDocumentInWorkspace(undefined, { name: "slow", source: 'OUTPUT "compiled slowly"' }); + }); + + let run: Promise = Promise.resolve(); + act(() => { + run = result.current.runNow(); + }); + await waitFor(() => expect(compileMock).toHaveBeenCalled()); + rerender({ signedIn: true }); + await waitFor(() => expect(result.current.workspace?.virtualFiles).toEqual({ "results.txt": ["saved in the account"] })); + + await act(async () => { + for (const finish of pendingCompiles) finish({ success: true, diagnostics: [], astJson: "{}" }); + await run; + }); + expect(runMock).not.toHaveBeenCalled(); + expect(result.current.workspace?.virtualFiles).toEqual({ "results.txt": ["saved in the account"] }); + }); +}); diff --git a/apps/web/src/app/hooks/useWorkspaceSession.ts b/apps/web/src/app/hooks/useWorkspaceSession.ts index 1855bad..cec3e35 100644 --- a/apps/web/src/app/hooks/useWorkspaceSession.ts +++ b/apps/web/src/app/hooks/useWorkspaceSession.ts @@ -37,11 +37,15 @@ import { import type { Diagnostic, RunTraceStep } from "@/compiler/types"; import { track } from "@/lib/analytics"; import { + getWorkspaceTooLargeDetail, isAccountUnreachable, + isWorkspaceConflictError, loadWorkspace, saveDeviceCheckpoint, saveWorkspace, + stashGuestDraft, takeAccountSyncPending, + takeGuestImported, takeRecoveredCopies, } from "@/lib/storage"; import type { WorkspacePersistenceMode } from "@/lib/platform"; @@ -92,6 +96,8 @@ interface WorkspaceSessionOptions { checkpointOwner?: string | null; /** Localized name of the folder that receives this device's versions after a sync conflict. */ recoveredFolderName?: string; + /** Localized name of the folder that receives the files written before signing in. */ + guestFolderName?: string; } interface PendingTerminalInput { @@ -166,6 +172,10 @@ export function useWorkspaceSession(defaultSource: string, options: WorkspaceSes useEffect(() => { recoveredFolderNameRef.current = options.recoveredFolderName; }, [options.recoveredFolderName]); + const guestFolderNameRef = useRef(options.guestFolderName); + useEffect(() => { + guestFolderNameRef.current = options.guestFolderName; + }, [options.guestFolderName]); const checkpointTimerRef = useRef(null); const checkpointFirstChangeAtRef = useRef(null); /** Wall-clock time of the latest workspace change; ties checkpoints and saves to the edits they contain. */ @@ -175,9 +185,13 @@ export function useWorkspaceSession(defaultSource: string, options: WorkspaceSes >(null); const [appNotice, setAppNotice] = useState(null); /** Account-sync situations the page explains (localized) right after loading. */ - const [syncNotice, setSyncNotice] = useState<"account-unreachable" | "recovered-copies" | null>(null); + const [syncNotice, setSyncNotice] = useState< + "account-unreachable" | "account-changed" | "recovered-copies" | "guest-imported" | null + >(null); const workspaceRef = useRef(null); + /** Changes whenever a different workspace is loaded (sign-in, sign-out, account switch). */ + const workspaceLoadGenerationRef = useRef(0); const saveTimerRef = useRef(null); const saveRequestIdRef = useRef(0); const activeSaveCountRef = useRef(0); @@ -227,6 +241,7 @@ export function useWorkspaceSession(defaultSource: string, options: WorkspaceSes let cancelled = false; loadedRef.current = false; workspaceRef.current = null; + workspaceLoadGenerationRef.current += 1; queueMicrotask(() => { if (cancelled) { @@ -242,7 +257,11 @@ export function useWorkspaceSession(defaultSource: string, options: WorkspaceSes ...(getCloudAuthTokenRef.current ? { getAuthToken: getCurrentCloudAuthToken } : {}), mode: persistenceMode, ...(checkpointOwnerRef.current - ? { checkpointOwner: checkpointOwnerRef.current, recoveredFolderName: recoveredFolderNameRef.current } + ? { + checkpointOwner: checkpointOwnerRef.current, + recoveredFolderName: recoveredFolderNameRef.current, + guestFolderName: guestFolderNameRef.current, + } : {}), }).then((loadedWorkspace) => { if (cancelled) { @@ -256,8 +275,16 @@ export function useWorkspaceSession(defaultSource: string, options: WorkspaceSes // Recovered edits (or an account that couldn't be read) still have to reach the account: sync through the // normal save path so "Unsaved", failures and the leave warning all reflect it until it is acknowledged. const owner = checkpointOwnerRef.current; + const recoveredCopies = takeRecoveredCopies(owner); + const guestImported = takeGuestImported(owner); setSyncNotice( - isAccountUnreachable(owner) ? "account-unreachable" : takeRecoveredCopies(owner) ? "recovered-copies" : null, + isAccountUnreachable(owner) + ? "account-unreachable" + : recoveredCopies + ? "recovered-copies" + : guestImported + ? "guest-imported" + : null, ); if (takeAccountSyncPending(owner)) { // Stamp the recovered snapshot as this tab's latest edit so its acknowledged save clears the checkpoint. @@ -273,6 +300,10 @@ export function useWorkspaceSession(defaultSource: string, options: WorkspaceSes cancelled = true; const owner = checkpointOwnerRef.current; const pendingWorkspace = workspaceRef.current; + // Signing in replaces the guest workspace with the account's: keep the guest's files so the load adds them. + if (persistenceMode === "memory" && pendingWorkspace && loadedRef.current) { + stashGuestDraft(pendingWorkspace, guestFolderNameRef.current); + } if (checkpointTimerRef.current !== null) { window.clearTimeout(checkpointTimerRef.current); checkpointTimerRef.current = null; @@ -342,10 +373,20 @@ export function useWorkspaceSession(defaultSource: string, options: WorkspaceSes setHasPendingSave(false); setLastSavedAt(Date.now()); return true; - } catch { + } catch (error) { + // Another tab or device saved first: further saves would be refused too, so ask for a reload, which keeps + // the account's version and adds this device's (checkpointed) changes beside it. + if (isWorkspaceConflictError(error)) setSyncNotice("account-changed"); if (saveRequestIdRef.current !== requestId) { return false; } + // Over a size limit nothing will upload until files are removed, so say which limit instead of "will retry". + const tooLargeDetail = getWorkspaceTooLargeDetail(error); + if (tooLargeDetail !== null) { + setSaveError(`Too large: ${tooLargeDetail}`); + setHasPendingSave(true); + return false; + } setSaveError( source === "manual" ? "Save failed. Changes remain on this device." @@ -443,6 +484,18 @@ export function useWorkspaceSession(defaultSource: string, options: WorkspaceSes [autoSaveDelayMs, persistWorkspace, persistenceMode, writeCheckpointNow], ); + // A guest leaving the page (often a sign-in redirect) keeps their files for the account load in this tab. + useEffect(() => { + if (typeof window === "undefined" || persistenceMode !== "memory") { + return; + } + const stashGuestWork = () => { + if (workspaceRef.current && loadedRef.current) stashGuestDraft(workspaceRef.current, guestFolderNameRef.current); + }; + window.addEventListener("pagehide", stashGuestWork); + return () => window.removeEventListener("pagehide", stashGuestWork); + }, [persistenceMode]); + // Save before the page can be discarded: mobile Safari often skips beforeunload for backgrounded tabs. useEffect(() => { if (typeof window === "undefined" || persistenceMode === "memory") { @@ -784,12 +837,17 @@ export function useWorkspaceSession(defaultSource: string, options: WorkspaceSes }, [compileSource, ensureTerminalTarget, isStillActiveSnapshot, updateTerminalOutput, updateWorkspaceCompileSummary]); const runNow = useCallback(async () => { + // A run belongs to the workspace it started in; if another loads meanwhile (sign-in, account switch), it stops. + const runLoadGeneration = workspaceLoadGenerationRef.current; const target = ensureTerminalTarget(); if (!target) { return; } const payload = await compileSource(target.workspace); + if (workspaceLoadGenerationRef.current !== runLoadGeneration) { + return; + } if (!payload) { updateTerminalOutput(target.panelId, "Create your first file to compile and run code."); return; @@ -938,7 +996,10 @@ export function useWorkspaceSession(defaultSource: string, options: WorkspaceSes } updateTerminalOutput(target.panelId, transcript.join("\n")); - applyWorkspaceUpdate((current) => updateVirtualFiles(current, latestVirtualFiles), "immediate"); + // A run started in another workspace (e.g. as a guest, before signing in) must not replace this one's files. + if (workspaceLoadGenerationRef.current === runLoadGeneration) { + applyWorkspaceUpdate((current) => updateVirtualFiles(current, latestVirtualFiles), "immediate"); + } return runtimeError ? ("runtime_error" as const) : ("success" as const); } finally { resolvePendingInput(null); diff --git a/apps/web/src/i18n/messages/editor.en.ts b/apps/web/src/i18n/messages/editor.en.ts index e0dff33..6f8c7a2 100644 --- a/apps/web/src/i18n/messages/editor.en.ts +++ b/apps/web/src/i18n/messages/editor.en.ts @@ -121,11 +121,12 @@ export const editorEn = { saveFailed: "Couldn't save your changes. Keep this tab open and try again.", localSaveFailed: "Couldn't save to this device. Keep this tab open and try again.", tooLarge: (detail: string) => `Cloud saving is paused because the workspace is over a size limit. ${detail}`, - conflict: "This workspace also changed in another tab or on another device. Your version is kept, and files that differ in the other version were copied into the \"Cloud copy\" folder.", + conflict: "This workspace was changed in another tab or on another device, so saving here is paused to avoid overwriting it. Your changes are kept on this device. Choose Reload to get both versions.", conflictFolder: "Cloud copy", guestFolder: "Guest", accountUnreachable: "Couldn't reach your account, so your work is kept on this device for now. Choose Retry to sync it.", retry: "Retry", + reload: "Reload", authRetryDiscards: "Retrying reloads the page, and changes made here since it opened will be lost. Copy anything you want to keep first. Retry now?", authUnavailable: "Couldn't load sign-in, so your saved files can't open and changes here won't be saved. Check your connection or content blocker, then choose Retry.", recoveredCopies: "Some changes saved only on this device couldn't be matched to your account's latest version. Your account's files are unchanged, and this device's versions are in the \"From this device\" folder so nothing is lost.", diff --git a/apps/web/src/i18n/messages/editor.zh.ts b/apps/web/src/i18n/messages/editor.zh.ts index b7ced28..0737389 100644 --- a/apps/web/src/i18n/messages/editor.zh.ts +++ b/apps/web/src/i18n/messages/editor.zh.ts @@ -24,10 +24,10 @@ export const editorZh: typeof editorEn = { saveFailed: "无法保存更改。请保持此标签页打开并重试。", localSaveFailed: "无法保存到此设备。请保持此标签页打开并重试。", tooLarge: (detail) => `工作区超出大小限制,已暂停云端保存。${detail}`, - conflict: "此工作区也在其他标签页或设备上被修改。已保留你的版本,另一版本中不同的文件已复制到“云端副本”文件夹。", + conflict: "此工作区已在其他标签页或设备上被修改,为避免覆盖,这里已暂停保存。你的更改保留在此设备上。点击“重新加载”即可获得两个版本。", conflictFolder: "云端副本", guestFolder: "访客", - accountUnreachable: "无法连接你的账户,作品暂时保存在此设备上。点击“重试”即可同步。", retry: "重试", authRetryDiscards: "重试会刷新页面,打开后在此处所做的更改将会丢失。请先复制需要保留的内容。现在重试吗?", authUnavailable: "无法加载登录服务,因此无法打开已保存的文件,此处的更改也不会被保存。请检查网络连接或内容拦截插件,然后点击“重试”。", recoveredCopies: "部分只保存在此设备上的更改无法与账户中的最新版本对应。账户中的文件保持不变,此设备上的版本已放入“来自此设备”文件夹,不会丢失任何内容。", recoveredFolder: "来自此设备", + accountUnreachable: "无法连接你的账户,作品暂时保存在此设备上。点击“重试”即可同步。", retry: "重试", reload: "重新加载", authRetryDiscards: "重试会刷新页面,打开后在此处所做的更改将会丢失。请先复制需要保留的内容。现在重试吗?", authUnavailable: "无法加载登录服务,因此无法打开已保存的文件,此处的更改也不会被保存。请检查网络连接或内容拦截插件,然后点击“重试”。", recoveredCopies: "部分只保存在此设备上的更改无法与账户中的最新版本对应。账户中的文件保持不变,此设备上的版本已放入“来自此设备”文件夹,不会丢失任何内容。", recoveredFolder: "来自此设备", guestImported: "登录前编写的文件已添加到“访客”文件夹。", }, }; diff --git a/apps/web/src/lib/seo-content.test.ts b/apps/web/src/lib/seo-content.test.ts index 2bfda94..74f089f 100644 --- a/apps/web/src/lib/seo-content.test.ts +++ b/apps/web/src/lib/seo-content.test.ts @@ -12,6 +12,6 @@ describe("blog posts", () => { it("lists the newest post first", () => { const dates = getPosts("en").map((post) => post.date); expect(dates).toEqual([...dates].sort().reverse()); - expect(getPosts("en")[0].slug).toBe("flowchart-mode-out-of-beta"); + expect(getPosts("en")[0].slug).toBe("pseudoeditor-v2"); }); }); diff --git a/apps/web/src/lib/seo-content.ts b/apps/web/src/lib/seo-content.ts index 18fe765..5a1392b 100644 --- a/apps/web/src/lib/seo-content.ts +++ b/apps/web/src/lib/seo-content.ts @@ -302,6 +302,50 @@ export const posts: SeoPost[] = [ }, ], }, + { + slug: "pseudoeditor-v2", + title: "PseudoEditor 2.0: a real IDE, with safer saving", + description: + "Errors as you type, keyboard shortcuts, a faster editor on phones and iPads, and protection against one tab overwriting another.", + date: "2026-11-19", + readingTime: "4 min read", + tags: ["Release", "Editor", "Announcement"], + sections: [ + { + heading: "Out of preview", + body: [ + "The Explorer used to say 0.1.9-Preview. It now says v2.0.0. Everything below shipped in November, and it all stays free.", + ], + }, + { + heading: "An editor that works like an IDE", + body: [ + "Compiler errors are underlined as you type, and the Problems list jumps to each one, so you no longer have to press Run to find them. In the desktop and tablet layouts, a status bar shows problems, save state, your line and column, and your exam syntax.", + "Run with Ctrl+Enter or F5. With a file open in the code editor, Ctrl+Shift+P opens the command palette (⌘↩ and ⇧⌘P on a Mac). Undo, the cursor, and the scroll position stay with each file when you switch between them. Settings has seven syntax colour schemes, including High contrast, each with a light and a dark version.", + ], + }, + { + heading: "Faster on phones and iPads", + body: [ + "On iPads and phones, the editor answers taps while it is still loading, where before it could freeze for a second. Run and switching files react sooner, and in our tests on a slowed-down browser the editor page started drawing about five times sooner.", + "If you've signed in before and a school filter blocks sign-in, the editor no longer spins forever. After about 15 seconds it opens a temporary workspace and explains that your saved files can't open and changes there won't be saved.", + ], + }, + { + heading: "Your work is safer", + body: [ + "On pseudoeditor.dev, files you write before signing in now come with you when you sign in from the same tab: they appear in a Guest folder in your account.", + "If you edit the same account in two tabs or on two devices, an out-of-date tab can no longer overwrite newer work. It pauses saving and offers Reload, which keeps your account's version and adds this device's edited files beside it. Tabs left open from before this update don't have this protection, so refresh them on every device before you keep editing. When you're signed in, each tab also keeps its own crash-recovery copy, and data files with names like 成绩.txt save and load correctly.", + ], + }, + { + heading: "One place to learn", + body: [ + "The Manual is now part of the Docs, under Pseudocode reference, and old Manual links open the Docs. Lesson has eight learning paths: Cambridge IGCSE, O Level, and AS & A Level, AP Computer Science Principles, AP Cybersecurity, AP Computer Science A, and IB Computer Science HL and SL, in English and Chinese.", + ], + }, + ], + }, ]; export type FaqItem = { question: string; answer: string }; diff --git a/apps/web/src/lib/seo-content.zh.ts b/apps/web/src/lib/seo-content.zh.ts index 278db3d..8307d21 100644 --- a/apps/web/src/lib/seo-content.zh.ts +++ b/apps/web/src/lib/seo-content.zh.ts @@ -257,6 +257,47 @@ export const postsZh: SeoPost[] = [ }, ], }, + { + slug: "pseudoeditor-v2", + title: "PseudoEditor 2.0:真正的 IDE,保存也更安全", + description: "边写边提示错误、键盘快捷键、手机和 iPad 上更快的编辑器,以及防止一个标签页覆盖另一个标签页的作品。", + date: "2026-11-19", + readingTime: "4 分钟阅读", + tags: ["版本发布", "编辑器", "公告"], + sections: [ + { + heading: "正式结束预览版", + body: ["文件浏览器里以前显示 0.1.9-Preview,现在显示 v2.0.0。下面的所有改进都在 11 月上线,而且全部免费。"], + }, + { + heading: "像 IDE 一样的编辑器", + body: [ + "编译错误会在你输入时标出,点击“问题”列表中的条目就能跳到对应位置,不用再点运行才发现错误。在桌面和平板布局中,状态栏会显示问题数、保存状态、当前行和列,以及你选择的考试语法。", + "按 Ctrl+Enter 或 F5 运行程序。在代码编辑器中打开文件后,按 Ctrl+Shift+P 可打开命令面板(Mac 上分别是 ⌘↩ 和 ⇧⌘P)。在文件之间切换时,每个文件的撤销记录、光标和滚动位置都会保留。设置中有七种语法配色方案,包括高对比度,每种都有浅色和深色版本。", + ], + }, + { + heading: "手机和 iPad 上更快", + body: [ + "在 iPad 和手机上,编辑器还在加载时就能响应点击,而以前可能会卡住一秒。运行和切换文件反应更快。在我们模拟慢速设备的浏览器测试中,编辑器页面开始显示的速度快了大约五倍。", + "如果你以前登录过,而学校的网络过滤拦截了登录,编辑器不会再一直转圈。大约 15 秒后,它会打开一个临时工作区,并说明已保存的文件无法打开,在这里的更改也不会被保存。", + ], + }, + { + heading: "作业更安全", + body: [ + "在 pseudoeditor.dev 上,如果你在同一个标签页中登录,登录前写的文件现在会跟着你:它们会出现在账户里的“访客”文件夹中。", + "如果你在两个标签页或两台设备上编辑同一个账户,过时的标签页不会再覆盖较新的作品。它会暂停保存并提供“重新加载”,保留账户中的版本,并把此设备上改过的文件放在旁边。在这次更新之前就打开的标签页没有这项保护,请先在每台设备上刷新它们,再继续编辑。登录后,每个标签页也有自己的崩溃恢复副本,像 成绩.txt 这样名字的数据文件也能正确保存和读取。", + ], + }, + { + heading: "在一个地方学习", + body: [ + "手册现在并入了文档中的“伪代码参考”,旧的手册链接会打开文档。“课堂”提供八条学习路径:IGCSE Computer Science、O Level Computer Science、AS & A Level Computer Science、AP Computer Science Principles、AP Cybersecurity、AP Computer Science A,以及 IB Computer Science HL 和 SL,均有中英文版本。", + ], + }, + ], + }, ]; export const faqZh: FaqItem[] = [ diff --git a/apps/web/src/lib/storage.test.ts b/apps/web/src/lib/storage.test.ts index aba9ea9..3a7dcd6 100644 --- a/apps/web/src/lib/storage.test.ts +++ b/apps/web/src/lib/storage.test.ts @@ -5,6 +5,7 @@ import { getActiveDocument, updateDocumentSource, updateVirtualFiles, + type WorkspaceState, } from "@pseudoeditor/workspace"; const dbStore = new Map(); @@ -16,6 +17,7 @@ interface MockDatabase { }; createObjectStore: ReturnType; get: (_storeName: string, key: string) => Promise; + getAllKeys: (_storeName: string) => Promise; put: (_storeName: string, value: unknown, key: string) => Promise; delete: (_storeName: string, key: string) => Promise; transaction: (_storeName: string, _mode: string) => { @@ -42,6 +44,9 @@ vi.mock("idb", () => ({ async get(_storeName: string, key: string) { return dbStore.get(key); }, + async getAllKeys() { + return [...dbStore.keys()]; + }, async put(_storeName: string, value: unknown, key: string) { dbStore.set(key, value); }, @@ -71,6 +76,18 @@ vi.mock("idb", () => ({ }), })); +/** Checkpoints are kept per tab (`unsynced::`); these find any tab's checkpoint for an account. */ +function checkpointKeys(owner: string) { + return [...dbStore.keys()].filter((key) => key === `unsynced:${owner}` || key.startsWith(`unsynced:${owner}:`)); +} +function hasCheckpoint(owner: string) { + return checkpointKeys(owner).length > 0; +} +function getCheckpoint(owner: string) { + const [key] = checkpointKeys(owner); + return key === undefined ? undefined : dbStore.get(key); +} + describe("workspace storage", () => { beforeEach(() => { dbStore.clear(); @@ -269,7 +286,7 @@ describe("workspace storage", () => { // The session syncs recovered edits itself (so its status reflects the outcome); storage just flags them. expect(storage.takeAccountSyncPending("user_a")).toBe(true); expect(storage.takeAccountSyncPending("user_a")).toBe(false); - expect(dbStore.has("unsynced:user_a")).toBe(true); + expect(hasCheckpoint("user_a")).toBe(true); }); it("never restores another account's checkpoint", async () => { @@ -286,7 +303,7 @@ describe("workspace storage", () => { const loaded = await storage.loadWorkspace('OUTPUT "Fallback"', { mode: "cloud", checkpointOwner: "user_b" }); expect(getActiveDocument(loaded)?.source).toBe('OUTPUT "B cloud"'); - expect(dbStore.has("unsynced:user_a")).toBe(true); + expect(hasCheckpoint("user_a")).toBe(true); }); it("drops the checkpoint once an account sync succeeds", async () => { @@ -297,7 +314,7 @@ describe("workspace storage", () => { const storage = await import("@/lib/storage"); await storage.saveDeviceCheckpoint(workspace, "user_a", 1000); await storage.saveWorkspace(workspace, { mode: "cloud", checkpointOwner: "user_a", editedAt: 1000 }); - expect(dbStore.has("unsynced:user_a")).toBe(false); + expect(hasCheckpoint("user_a")).toBe(false); }); it("keeps a checkpoint newer than the snapshot an account sync wrote", async () => { @@ -308,7 +325,7 @@ describe("workspace storage", () => { const storage = await import("@/lib/storage"); await storage.saveDeviceCheckpoint(workspace, "user_a", 2000); await storage.saveWorkspace(workspace, { mode: "cloud", checkpointOwner: "user_a", editedAt: 1000 }); - expect(dbStore.has("unsynced:user_a")).toBe(true); + expect(hasCheckpoint("user_a")).toBe(true); }); it("restores a newer checkpoint even when its change was a deletion", async () => { @@ -600,7 +617,7 @@ describe("workspace storage", () => { const recovered = await storage.loadWorkspace('OUTPUT "Fallback"', { mode: "cloud", checkpointOwner: "user_a" }); // What the session does: sync the recovered snapshot stamped as its latest edit. await storage.saveWorkspace(recovered, { mode: "cloud", checkpointOwner: "user_a", editedAt: Date.now() }); - expect(dbStore.has("unsynced:user_a")).toBe(false); + expect(hasCheckpoint("user_a")).toBe(false); }); it("moves a newer checkpoint's base forward when this tab's earlier save is acknowledged", async () => { @@ -633,14 +650,15 @@ describe("workspace storage", () => { }); const tabB = await import("@/lib/storage"); await tabB.saveDeviceCheckpoint(workspace, "user_a", 1000); - const before = dbStore.get("unsynced:user_a"); + const before = getCheckpoint("user_a"); + expect(before).toBeDefined(); vi.resetModules(); vi.mocked(fetch).mockResolvedValueOnce(new Response(JSON.stringify({ ok: true }), { status: 200 })); const tabA = await import("@/lib/storage"); await tabA.saveWorkspace(workspace, { mode: "cloud", checkpointOwner: "user_a", editedAt: 5000 }); - expect(dbStore.get("unsynced:user_a")).toEqual(before); + expect(getCheckpoint("user_a")).toEqual(before); }); it("copies only the files this device edited after its base version", async () => { @@ -712,7 +730,7 @@ describe("workspace storage", () => { vi.mocked(fetch).mockResolvedValueOnce(new Response(JSON.stringify({ workspace: synced }), { status: 200 })); const storage = await import("@/lib/storage"); await storage.loadWorkspace('OUTPUT "Fallback"', { mode: "cloud", checkpointOwner: "user_a" }); - await vi.waitFor(() => expect(dbStore.has("unsynced:user_a")).toBe(false)); + await vi.waitFor(() => expect(hasCheckpoint("user_a")).toBe(false)); }); it("keeps an edit made while an earlier save was in flight recoverable after that save is acknowledged", async () => { @@ -885,4 +903,356 @@ describe("workspace storage", () => { const headers = vi.mocked(fetch).mock.calls[0]?.[1]?.headers as Record; expect(headers.Authorization).toBe("Bearer account-A"); }); + it("keeps every tab's unsynced checkpoint and recovers all of them", async () => { + const account = createDocument(createEmptyWorkspace("2026-03-15T00:00:00.000Z"), { + name: "essay", id: "doc-essay", source: 'OUTPUT "v1"', now: "2026-03-15T00:00:00.000Z", + }); + const accountResponse = () => new Response(JSON.stringify({ workspace: account }), { status: 200 }); + const fetchMock = vi.mocked(fetch); + fetchMock.mockResolvedValueOnce(accountResponse()).mockResolvedValueOnce(accountResponse()).mockResolvedValueOnce(accountResponse()); + const later = (ms: number) => new Date(Date.now() + ms).toISOString(); + + // Two tabs open the account, then both edit before either syncs. + const tabA = await import("@/lib/storage"); + await tabA.loadWorkspace('OUTPUT "Fallback"', { mode: "cloud", checkpointOwner: "user_a" }); + vi.resetModules(); + const tabB = await import("@/lib/storage"); + await tabB.loadWorkspace('OUTPUT "Fallback"', { mode: "cloud", checkpointOwner: "user_a" }); + await tabA.saveDeviceCheckpoint(updateDocumentSource(account, "doc-essay", 'OUTPUT "Tab A"', later(1000)), "user_a", Date.now() + 1000); + await tabB.saveDeviceCheckpoint( + createDocument(account, { name: "notes", source: 'OUTPUT "Tab B"', now: later(2000) }), + "user_a", + Date.now() + 2000, + ); + expect(checkpointKeys("user_a")).toHaveLength(2); + + vi.resetModules(); + const reopened = await import("@/lib/storage"); + const loaded = await reopened.loadWorkspace('OUTPUT "Fallback"', { mode: "cloud", checkpointOwner: "user_a" }); + const sources = Object.values(loaded.nodes).flatMap((node) => (node.type === "document" ? [node.source] : [])); + expect(sources).toContain('OUTPUT "Tab A"'); + expect(sources).toContain('OUTPUT "Tab B"'); + expect(reopened.takeAccountSyncPending("user_a")).toBe(true); + // Both are now carried by the reopened tab's single checkpoint until its sync lands. + expect(checkpointKeys("user_a")).toHaveLength(1); + }); + + it("saves only over the account revision it last read and refuses to overwrite a newer one", async () => { + const account = createDocument(createEmptyWorkspace("2026-03-15T00:00:00.000Z"), { + name: "essay", id: "doc-essay", source: 'OUTPUT "v1"', now: "2026-03-15T00:00:00.000Z", + }); + const fetchMock = vi.mocked(fetch); + fetchMock + .mockResolvedValueOnce(new Response(JSON.stringify({ workspace: account, revision: 3 }), { status: 200 })) + .mockResolvedValueOnce(new Response(JSON.stringify({ ok: true, revision: 4 }), { status: 200 })) + .mockResolvedValueOnce(new Response(JSON.stringify({ error: "changed", conflict: true }), { status: 409 })); + const storage = await import("@/lib/storage"); + await storage.loadWorkspace('OUTPUT "Fallback"', { mode: "cloud", checkpointOwner: "user_a" }); + + const first = updateDocumentSource(account, "doc-essay", 'OUTPUT "v2"'); + await storage.saveWorkspace(first, { mode: "cloud", checkpointOwner: "user_a", editedAt: Date.now() }); + expect(JSON.parse(String(fetchMock.mock.calls[1]![1]!.body))).toMatchObject({ expectedRevision: 3 }); + + const second = updateDocumentSource(first, "doc-essay", 'OUTPUT "v3"'); + await storage.saveDeviceCheckpoint(second, "user_a", Date.now() + 1); + const rejected = storage.saveWorkspace(second, { mode: "cloud", checkpointOwner: "user_a", editedAt: Date.now() + 1 }); + await expect(rejected).rejects.toSatisfy(storage.isWorkspaceConflictError); + expect(JSON.parse(String(fetchMock.mock.calls[2]![1]!.body))).toMatchObject({ expectedRevision: 4 }); + // The refused edits stay on this device for the reload that brings both versions together. + expect(hasCheckpoint("user_a")).toBe(true); + }); + + it("adds the files written before signing in to the account and syncs them", async () => { + const account = createDocument(createEmptyWorkspace("2026-03-15T00:00:00.000Z"), { + name: "essay", source: 'OUTPUT "Account"', now: "2026-03-15T00:00:00.000Z", + }); + const guest = createDocument(createEmptyWorkspace(), { name: "draft", source: 'OUTPUT "Written as a guest"' }); + vi.mocked(fetch).mockResolvedValueOnce(new Response(JSON.stringify({ workspace: account, revision: 1 }), { status: 200 })); + const storage = await import("@/lib/storage"); + storage.stashGuestDraft(guest); + // A later empty guest workspace (e.g. the page reopened after a sign-in redirect) never replaces the draft. + storage.stashGuestDraft(createEmptyWorkspace()); + + const loaded = await storage.loadWorkspace('OUTPUT "Fallback"', { + mode: "cloud", checkpointOwner: "user_a", guestFolderName: "Guest", + }); + + const folder = Object.values(loaded.nodes).find((node) => node.type === "folder" && node.name === "Guest"); + const imported = Object.values(loaded.nodes).filter((node) => node.parentId === folder?.id); + expect(imported.map((node) => (node.type === "document" ? node.source : ""))).toEqual(['OUTPUT "Written as a guest"']); + expect(Object.values(loaded.nodes).some((node) => node.type === "document" && node.source === 'OUTPUT "Account"')).toBe(true); + expect(storage.takeGuestImported("user_a")).toBe(true); + expect(storage.takeAccountSyncPending("user_a")).toBe(true); + expect(hasCheckpoint("user_a")).toBe(true); + expect(window.sessionStorage.getItem("pseudoeditor-guest-draft")).toBeNull(); + }); + it("keeps a guest's data files when they sign in, never overwriting the account's own", async () => { + const account = updateVirtualFiles( + createDocument(createEmptyWorkspace("2026-03-15T00:00:00.000Z"), { name: "essay", source: "OUTPUT 1" }), + { "scores.txt": ["account"] }, + ); + const guest = updateVirtualFiles(createEmptyWorkspace(), { "scores.txt": ["90", "85"], "names.txt": ["Ada"] }); + vi.mocked(fetch).mockResolvedValueOnce(new Response(JSON.stringify({ workspace: account, revision: 1 }), { status: 200 })); + const storage = await import("@/lib/storage"); + storage.stashGuestDraft(guest); + + const loaded = await storage.loadWorkspace('OUTPUT "Fallback"', { + mode: "cloud", checkpointOwner: "user_a", guestFolderName: "Guest", + }); + + expect(loaded.virtualFiles).toEqual({ + "scores.txt": ["account"], + "scores (Guest).txt": ["90", "85"], + "names.txt": ["Ada"], + }); + expect(storage.takeAccountSyncPending("user_a")).toBe(true); + }); + + it("keeps this device's data-file edits as copies when the account changed elsewhere", async () => { + vi.useFakeTimers({ toFake: ["Date"] }); + vi.setSystemTime(new Date("2026-03-15T10:00:00.000Z")); + onTestFinished(() => { vi.useRealTimers(); }); + const atLoad = updateVirtualFiles( + createDocument(createEmptyWorkspace("2026-03-15T00:00:00.000Z"), { + name: "essay", id: "doc-essay", source: "OUTPUT 1", now: "2026-03-15T00:00:00.000Z", + }), + { "scores.txt": ["1"] }, + "2026-03-15T00:00:00.000Z", + ); + const changedElsewhere = updateDocumentSource(atLoad, "doc-essay", "OUTPUT 2", "2026-03-15T11:00:00.000Z"); + const fetchMock = vi.mocked(fetch); + fetchMock + .mockResolvedValueOnce(new Response(JSON.stringify({ workspace: atLoad }), { status: 200 })) + .mockResolvedValueOnce(new Response(JSON.stringify({ workspace: changedElsewhere }), { status: 200 })); + const storage = await import("@/lib/storage"); + await storage.loadWorkspace('OUTPUT "Fallback"', { mode: "cloud", checkpointOwner: "user_a" }); + // Only a data file changed on this device before it closed. + await storage.saveDeviceCheckpoint(updateVirtualFiles(atLoad, { "scores.txt": ["1", "2"] }), "user_a", Date.now()); + + const loaded = await storage.loadWorkspace('OUTPUT "Fallback"', { + mode: "cloud", checkpointOwner: "user_a", recoveredFolderName: "From this device", + }); + expect(loaded.virtualFiles).toEqual({ "scores.txt": ["1"], "scores (From this device).txt": ["1", "2"] }); + expect(storage.takeRecoveredCopies("user_a")).toBe(true); + }); + + it("never deletes a checkpoint another open tab updated while this tab was loading", async () => { + const account = createDocument(createEmptyWorkspace("2026-03-15T00:00:00.000Z"), { + name: "essay", id: "doc-essay", source: 'OUTPUT "v1"', now: "2026-03-15T00:00:00.000Z", + }); + const fetchMock = vi.mocked(fetch); + fetchMock.mockResolvedValueOnce(new Response(JSON.stringify({ workspace: account }), { status: 200 })); + const tabA = await import("@/lib/storage"); + await tabA.loadWorkspace('OUTPUT "Fallback"', { mode: "cloud", checkpointOwner: "user_a" }); + const later = (ms: number) => new Date(Date.now() + ms).toISOString(); + await tabA.saveDeviceCheckpoint(updateDocumentSource(account, "doc-essay", 'OUTPUT "A1"', later(1000)), "user_a", Date.now() + 1000); + + let releaseRead: (response: Response) => void = () => {}; + fetchMock.mockImplementationOnce(() => new Promise((resolve) => { releaseRead = resolve; })); + vi.resetModules(); + const tabB = await import("@/lib/storage"); + const loading = tabB.loadWorkspace('OUTPUT "Fallback"', { mode: "cloud", checkpointOwner: "user_a" }); + await vi.waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(2)); + // Tab A keeps typing while tab B's account read is in flight. + const newer = updateDocumentSource(account, "doc-essay", 'OUTPUT "A2"', later(2000)); + await tabA.saveDeviceCheckpoint(newer, "user_a", Date.now() + 2000); + releaseRead(new Response(JSON.stringify({ workspace: account }), { status: 200 })); + await loading; + + const sources = checkpointKeys("user_a").map((key) => { + const state = (dbStore.get(key) as { state: WorkspaceState }).state; + return state.nodes["doc-essay"]?.type === "document" ? state.nodes["doc-essay"].source : ""; + }); + expect(sources).toContain('OUTPUT "A2"'); + }); + + it("never hands a fresh revision to a save requested before the read", async () => { + const v1 = createDocument(createEmptyWorkspace("2026-03-15T00:00:00.000Z"), { + name: "essay", id: "doc-essay", source: 'OUTPUT "v1"', now: "2026-03-15T00:00:00.000Z", + }); + const fromOtherDevice = updateDocumentSource(v1, "doc-essay", 'OUTPUT "other device"'); + const fetchMock = vi.mocked(fetch); + fetchMock + .mockResolvedValueOnce(new Response(JSON.stringify({ workspace: v1, revision: 1 }), { status: 200 })) + .mockResolvedValueOnce(new Response(JSON.stringify({ error: "changed", conflict: true }), { status: 409 })) + .mockResolvedValueOnce(new Response(JSON.stringify({ workspace: fromOtherDevice, revision: 2 }), { status: 200 })); + const storage = await import("@/lib/storage"); + await storage.loadWorkspace('OUTPUT "Fallback"', { mode: "cloud", checkpointOwner: "user_a" }); + + // A save built on revision 1 is still waiting for its sign-in token when the workspace is read again. + let releaseToken: (token: string) => void = () => {}; + const tokenRequest = new Promise((resolve) => { releaseToken = resolve; }); + const stale = storage.saveWorkspace(updateDocumentSource(v1, "doc-essay", 'OUTPUT "stale"'), { + mode: "cloud", checkpointOwner: "user_a", editedAt: Date.now(), getAuthToken: () => tokenRequest, + }); + const reload = storage.loadWorkspace('OUTPUT "Fallback"', { mode: "cloud", checkpointOwner: "user_a" }); + releaseToken("token"); + + await expect(stale).rejects.toSatisfy(storage.isWorkspaceConflictError); + expect(JSON.parse(String(fetchMock.mock.calls[1]![1]!.body))).toMatchObject({ expectedRevision: 1 }); + await reload; + }); + it("never drops a guest's data file, even when the account is at the data-file limit", async () => { + const full = Object.fromEntries(Array.from({ length: 100 }, (_, index) => [`f${index}.txt`, ["x"]])); + const account = updateVirtualFiles(createDocument(createEmptyWorkspace(), { name: "essay", source: "OUTPUT 1" }), full); + const guest = updateVirtualFiles(createEmptyWorkspace(), { "mine.txt": ["typed as a guest"] }); + vi.mocked(fetch).mockResolvedValueOnce(new Response(JSON.stringify({ workspace: account, revision: 1 }), { status: 200 })); + const storage = await import("@/lib/storage"); + storage.stashGuestDraft(guest); + + const loaded = await storage.loadWorkspace('OUTPUT "Fallback"', { mode: "cloud", checkpointOwner: "user_a" }); + + // Over the save limit the account sync is refused (and explained), but the file stays on this device. + expect(loaded.virtualFiles["mine.txt"]).toEqual(["typed as a guest"]); + const checkpoint = getCheckpoint("user_a") as { state: WorkspaceState }; + expect(checkpoint.state.virtualFiles["mine.txt"]).toEqual(["typed as a guest"]); + }); + + it("shares one account load between overlapping callers so recovered work isn't loaded twice or lost", async () => { + const account = createDocument(createEmptyWorkspace("2026-03-15T00:00:00.000Z"), { name: "essay", source: "OUTPUT 1" }); + let releaseRead: (response: Response) => void = () => {}; + const fetchMock = vi.mocked(fetch); + fetchMock.mockImplementationOnce(() => new Promise((resolve) => { releaseRead = resolve; })); + const storage = await import("@/lib/storage"); + storage.stashGuestDraft(createDocument(createEmptyWorkspace(), { name: "draft", source: 'OUTPUT "guest"' })); + + // The editor is left and reopened while the first load is still waiting for the account. + const first = storage.loadWorkspace('OUTPUT "Fallback"', { mode: "cloud", checkpointOwner: "user_a" }); + const second = storage.loadWorkspace('OUTPUT "Fallback"', { mode: "cloud", checkpointOwner: "user_a" }); + await vi.waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(1)); + releaseRead(new Response(JSON.stringify({ workspace: account, revision: 1 }), { status: 200 })); + + const [a, b] = await Promise.all([first, second]); + expect(b).toBe(a); + expect(Object.values(b.nodes).some((node) => node.type === "document" && node.source === 'OUTPUT "guest"')).toBe(true); + expect(fetchMock).toHaveBeenCalledTimes(1); + }); + + it("reports which size limit the account refused a save for", async () => { + vi.mocked(fetch).mockResolvedValueOnce( + new Response(JSON.stringify({ error: "Workspace payload has too many virtual files (101/100)." }), { status: 413 }), + ); + const storage = await import("@/lib/storage"); + const save = storage.saveWorkspace(createEmptyWorkspace(), { mode: "cloud", checkpointOwner: "user_a", editedAt: 1 }); + const error = await save.then(() => null, (reason: unknown) => reason); + expect(storage.getWorkspaceTooLargeDetail(error)).toBe("Workspace payload has too many virtual files (101/100)."); + }); + it("leaves the guest draft to the account signed into last when an earlier account's load is abandoned", async () => { + const accountA = createDocument(createEmptyWorkspace(), { name: "a", source: 'OUTPUT "A"' }); + const accountB = createDocument(createEmptyWorkspace(), { name: "b", source: 'OUTPUT "B"' }); + let releaseA: (response: Response) => void = () => {}; + const fetchMock = vi.mocked(fetch); + fetchMock + .mockImplementationOnce(() => new Promise((resolve) => { releaseA = resolve; })) + .mockResolvedValueOnce(new Response(JSON.stringify({ workspace: accountB, revision: 1 }), { status: 200 })); + const storage = await import("@/lib/storage"); + + // A slow load for account A starts; the student signs out, writes guest work, then signs into B. + const abandoned = storage.loadWorkspace('OUTPUT "Fallback"', { mode: "cloud", checkpointOwner: "user_a" }); + await vi.waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(1)); + storage.stashGuestDraft(createDocument(createEmptyWorkspace(), { name: "draft", source: 'OUTPUT "guest"' })); + const loadB = storage.loadWorkspace('OUTPUT "Fallback"', { mode: "cloud", checkpointOwner: "user_b" }); + releaseA(new Response(JSON.stringify({ workspace: accountA, revision: 1 }), { status: 200 })); + + const [a, b] = await Promise.all([abandoned, loadB]); + const hasGuest = (state: WorkspaceState) => + Object.values(state.nodes).some((node) => node.type === "document" && node.source === 'OUTPUT "guest"'); + expect(hasGuest(a)).toBe(false); + expect(hasGuest(b)).toBe(true); + expect(storage.takeGuestImported("user_b")).toBe(true); + }); + + it("measures copies adopted from another tab from that tab's base, not from the load", async () => { + const account = createDocument(createEmptyWorkspace("2026-03-15T00:00:00.000Z"), { + name: "essay", id: "doc-essay", source: 'OUTPUT "v1"', now: "2026-03-15T00:00:00.000Z", + }); + const accountResponse = () => new Response(JSON.stringify({ workspace: account }), { status: 200 }); + const fetchMock = vi.mocked(fetch); + fetchMock.mockResolvedValueOnce(accountResponse()).mockResolvedValueOnce(accountResponse()); + const tabA = await import("@/lib/storage"); + await tabA.loadWorkspace('OUTPUT "Fallback"', { mode: "cloud", checkpointOwner: "user_a" }); + await tabA.saveDeviceCheckpoint( + createDocument(account, { name: "notes", source: 'OUTPUT "A"', now: new Date(Date.now() + 1000).toISOString() }), + "user_a", + Date.now() + 1000, + ); + const tabABase = (getCheckpoint("user_a") as { baseReadAt: number }).baseReadAt; + // The newest checkpoint (another tab's) holds nothing the account lacks, but was made on an older account version, + // so it is not restored and tab A's work is folded in on its own. + dbStore.set("unsynced:user_a:other-tab", { + owner: "user_a", state: account, editedAt: Date.now() + 5000, baseVersion: 1, baseReadAt: Date.now() + 5000, tabId: "other-tab", + }); + + vi.resetModules(); + const reopened = await import("@/lib/storage"); + const loaded = await reopened.loadWorkspace('OUTPUT "Fallback"', { mode: "cloud", checkpointOwner: "user_a" }); + expect(Object.values(loaded.nodes).some((node) => node.type === "document" && node.source === 'OUTPUT "A"')).toBe(true); + const [key] = checkpointKeys("user_a"); + expect((dbStore.get(key!) as { baseReadAt: number }).baseReadAt).toBe(tabABase); + }); + it("keeps every answer a guest wrote in this tab, not just the last workspace before signing in", async () => { + const account = createDocument(createEmptyWorkspace(), { name: "essay", source: "OUTPUT 1" }); + vi.mocked(fetch).mockResolvedValueOnce(new Response(JSON.stringify({ workspace: account, revision: 1 }), { status: 200 })); + const storage = await import("@/lib/storage"); + const firstQuestion = createDocument(createEmptyWorkspace(), { name: "q1", source: 'OUTPUT "my answer"' }); + storage.stashGuestDraft(firstQuestion); + // The guest opens another practice question (a fresh in-memory workspace) and edits again. + const secondQuestion = createDocument(createEmptyWorkspace(), { name: "q2", source: 'OUTPUT "starter"' }); + storage.stashGuestDraft(secondQuestion); + // The first answer edited again later keeps its newest text. + storage.stashGuestDraft(updateDocumentSource(firstQuestion, firstQuestion.activeDocumentId!, 'OUTPUT "my answer v2"')); + + const loaded = await storage.loadWorkspace('OUTPUT "Fallback"', { mode: "cloud", checkpointOwner: "user_a" }); + const sources = Object.values(loaded.nodes).flatMap((node) => (node.type === "document" ? [node.source] : [])); + expect(sources).toEqual(expect.arrayContaining(['OUTPUT "my answer v2"', 'OUTPUT "starter"'])); + expect(sources).not.toContain('OUTPUT "my answer"'); + }); + + it("lets signing out supersede an account load that is still running", async () => { + const accountA = createDocument(createEmptyWorkspace(), { name: "a", source: 'OUTPUT "A"' }); + const accountB = createDocument(createEmptyWorkspace(), { name: "b", source: 'OUTPUT "B"' }); + let releaseA: (response: Response) => void = () => {}; + const fetchMock = vi.mocked(fetch); + fetchMock + .mockImplementationOnce(() => new Promise((resolve) => { releaseA = resolve; })) + .mockResolvedValueOnce(new Response(JSON.stringify({ workspace: accountB, revision: 1 }), { status: 200 })); + const storage = await import("@/lib/storage"); + storage.stashGuestDraft(createDocument(createEmptyWorkspace(), { name: "draft", source: 'OUTPUT "guest"' })); + + const abandoned = storage.loadWorkspace('OUTPUT "Fallback"', { mode: "cloud", checkpointOwner: "user_a" }); + await vi.waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(1)); + await storage.loadWorkspace('OUTPUT "Fallback"', { mode: "memory" }); + releaseA(new Response(JSON.stringify({ workspace: accountA, revision: 1 }), { status: 200 })); + await abandoned; + + const b = await storage.loadWorkspace('OUTPUT "Fallback"', { mode: "cloud", checkpointOwner: "user_b" }); + expect(Object.values(b.nodes).some((node) => node.type === "document" && node.source === 'OUTPUT "guest"')).toBe(true); + }); + + it("names the account each cloud request was made for", async () => { + const workspace = createDocument(createEmptyWorkspace(), { name: "essay", source: "OUTPUT 1" }); + const fetchMock = vi.mocked(fetch); + fetchMock + .mockResolvedValueOnce(new Response(JSON.stringify({ workspace, revision: 1 }), { status: 200 })) + .mockResolvedValueOnce(new Response(JSON.stringify({ ok: true, revision: 2 }), { status: 200 })); + const storage = await import("@/lib/storage"); + await storage.loadWorkspace('OUTPUT "Fallback"', { mode: "cloud", checkpointOwner: "user_a" }); + await storage.saveWorkspace(workspace, { mode: "cloud", checkpointOwner: "user_a", editedAt: Date.now() }); + + for (const [, init] of fetchMock.mock.calls) { + expect((init!.headers as Record)["X-Workspace-Account"]).toBe("user_a"); + } + }); + + it("keeps a guest's earlier data file when another question writes one with the same name", async () => { + const account = createDocument(createEmptyWorkspace(), { name: "essay", source: "OUTPUT 1" }); + vi.mocked(fetch).mockResolvedValueOnce(new Response(JSON.stringify({ workspace: account, revision: 1 }), { status: 200 })); + const storage = await import("@/lib/storage"); + storage.stashGuestDraft(updateVirtualFiles(createDocument(createEmptyWorkspace(), { name: "q1", source: "OUTPUT 1" }), { "results.txt": ["q1 results"] }), "Guest"); + storage.stashGuestDraft(updateVirtualFiles(createDocument(createEmptyWorkspace(), { name: "q2", source: "OUTPUT 2" }), { "results.txt": ["q2 results"] }), "Guest"); + + const loaded = await storage.loadWorkspace('OUTPUT "Fallback"', { mode: "cloud", checkpointOwner: "user_a", guestFolderName: "Guest" }); + const contents = Object.values(loaded.virtualFiles).map((lines) => lines.join("\n")); + expect(contents).toEqual(expect.arrayContaining(["q1 results", "q2 results"])); + }); }); diff --git a/apps/web/src/lib/storage.ts b/apps/web/src/lib/storage.ts index f74f602..7bf3e4b 100644 --- a/apps/web/src/lib/storage.ts +++ b/apps/web/src/lib/storage.ts @@ -1,6 +1,12 @@ import { openDB } from "idb"; import type { WorkspaceState } from "@pseudoeditor/workspace"; -import { createDocument, createEmptyWorkspace, createFolder, migratePersistedWorkspace } from "@pseudoeditor/workspace"; +import { + createDocument, + createEmptyWorkspace, + createFolder, + migratePersistedWorkspace, + updateVirtualFiles, +} from "@pseudoeditor/workspace"; import type { WorkspacePersistenceMode } from "@/lib/platform"; const DB_NAME = "igcse-pseudocode-workspace"; @@ -24,10 +30,39 @@ interface WorkspaceStorageOptions { editedAt?: number; /** Name of the folder that receives this device's versions when they can't replace the account's. */ recoveredFolderName?: string; + /** Name of the folder that receives the files written before signing in. */ + guestFolderName?: string; } interface CloudWorkspaceResponse { workspace: unknown | null; + /** The account's server revision (`null`: no workspace yet). Missing from older servers. */ + revision?: number | null; +} + +/** The account changed (another tab or device saved) since this tab last read or wrote it. */ +export class WorkspaceConflictError extends Error { + constructor() { + super("The workspace changed in another tab or on another device."); + this.name = "WorkspaceConflictError"; + } +} + +export function isWorkspaceConflictError(error: unknown): boolean { + return error instanceof Error && error.name === "WorkspaceConflictError"; +} + +/** The account refused the workspace for being over a size limit; `message` says which limit. */ +export class WorkspaceTooLargeError extends Error { + constructor(message: string) { + super(message); + this.name = "WorkspaceTooLargeError"; + } +} + +/** The limit a save went over (the server's own wording), or null when the error is something else. */ +export function getWorkspaceTooLargeDetail(error: unknown): string | null { + return error instanceof Error && error.name === "WorkspaceTooLargeError" ? error.message : null; } function shouldResetWorkspaceForDevSession(): boolean { @@ -58,6 +93,8 @@ async function getDatabase() { } const CHECKPOINT_KEY_PREFIX = "unsynced:"; +const GUEST_DRAFT_SESSION_KEY = "pseudoeditor-guest-draft"; +export const GUEST_FOLDER_NAME = "Guest"; const ACCOUNT_CACHE_KEY_PREFIX = "current:"; /** Accounts whose cloud copy could not be read this session; their account writes wait for a successful read. */ const unreadableCloudOwners = new Set(); @@ -99,16 +136,63 @@ const TAB_ID = ? crypto.randomUUID() : `${Date.now()}-${Math.random().toString(36).slice(2)}`; +/** Each tab keeps its own checkpoint, so two tabs with unsynced edits never overwrite each other's. */ +function ownCheckpointKey(owner: string): string { + return `${CHECKPOINT_KEY_PREFIX}${owner}:${TAB_ID}`; +} + +/** The server revision this tab last read or wrote, per device cache key. Absent: unknown (older server). */ +const accountRevisions = new Map(); + /** The account snapshot (its fingerprint) this tab last read or wrote, and when by this device's clock. */ const accountBaseVersions = new Map(); -/** True when every document in the checkpoint already has the same text in the account (nothing left to sync). */ +function sameLines(a: string[] | undefined, b: string[]): boolean { + return !!a && a.length === b.length && a.every((line, index) => line === b[index]); +} + +/** + * True when every document in the checkpoint already has the same text in the account, and every data file the same + * contents (nothing left to sync). + */ function checkpointMatchesAccount(device: WorkspaceState, account: WorkspaceState): boolean { - return Object.values(device.nodes).every((node) => { + const documentsMatch = Object.values(device.nodes).every((node) => { if (node.type !== "document") return true; const accountNode = account.nodes[node.id]; return accountNode?.type === "document" && accountNode.source === node.source; }); + return ( + documentsMatch && + Object.entries(device.virtualFiles ?? {}).every(([name, lines]) => sameLines(account.virtualFiles?.[name], lines)) + ); +} + +/** + * Adds the device's data files (files programs read and write, which students can also edit) that `merged` lacks or + * holds with other contents. A differing one is added under a distinct name, so neither version is overwritten. + */ +function mergeVirtualFilesAsCopies(merged: WorkspaceState, device: WorkspaceState, label: string): WorkspaceState { + const files = { ...merged.virtualFiles }; + let changed = false; + for (const [name, lines] of Object.entries(device.virtualFiles ?? {})) { + if (sameLines(files[name], lines)) continue; + let target = name; + if (files[name]) { + const dot = name.lastIndexOf("."); + const stem = dot > 0 ? name.slice(0, dot) : name; + const extension = dot > 0 ? name.slice(dot) : ""; + for (let attempt = 1; ; attempt += 1) { + target = `${stem} (${attempt === 1 ? label : `${label} ${attempt}`})${extension}`; + if (!files[target] || sameLines(files[target], lines)) break; + } + if (files[target]) continue; // already copied on an earlier recovery + } + // Never dropped, even past the save limit: the work then stays on this device and the student is told why the + // account sync is paused. + files[target] = [...lines]; + changed = true; + } + return changed ? updateVirtualFiles(merged, files) : merged; } /** Accounts whose recovered device edits were added as copies because the account changed meanwhile. */ const recoveredCopyOwners = new Set(); @@ -136,7 +220,7 @@ function mergeCheckpointAsCopies( if (node.type !== "document") continue; const accountNode = account.nodes[node.id]; if (accountNode?.type === "document" && accountNode.source === node.source) continue; - if (editedAfter !== null && !(Date.parse(node.updatedAt) > editedAfter)) continue; + if (editedAfter !== null && !(Date.parse(node.updatedAt) >= editedAfter)) continue; if (!folderId) { merged = createFolder(merged, { name: folderName }); folderId = Object.values(merged.nodes).find( @@ -146,7 +230,7 @@ function mergeCheckpointAsCopies( } merged = createDocument(merged, { parentId: folderId, name: node.name, source: node.source }); } - return merged; + return mergeVirtualFilesAsCopies(merged, device, folderName); } /** @@ -180,26 +264,40 @@ function accountFingerprint(state: WorkspaceState): number { /** Records edits that have not reached the account yet, on this device only. */ export async function saveDeviceCheckpoint(state: WorkspaceState, owner: string, editedAt: number): Promise { const database = await getDatabase(); - const key = `${CHECKPOINT_KEY_PREFIX}${owner}`; const known = accountBaseVersions.get(owner); let baseVersion = known?.version ?? null; let baseReadAt = known?.readAt ?? null; if (unreadableCloudOwners.has(owner)) { // Edits made while the account can't be read build on whatever the existing checkpoint was based on. - const existing = (await database.get(STORE_NAME, key)) as DeviceCheckpoint | undefined; + const existing = (await database.get(STORE_NAME, ownCheckpointKey(owner))) as DeviceCheckpoint | undefined; baseVersion = typeof existing?.baseVersion === "number" ? existing.baseVersion : null; baseReadAt = typeof existing?.baseReadAt === "number" ? existing.baseReadAt : null; } const checkpoint: DeviceCheckpoint = { owner, state, editedAt, baseVersion, baseReadAt, tabId: TAB_ID }; - await database.put(STORE_NAME, checkpoint, key); + await database.put(STORE_NAME, checkpoint, ownCheckpointKey(owner)); } -async function readDeviceCheckpoint(owner: string): Promise { +type StoredCheckpoint = DeviceCheckpoint & { key: string }; + +/** Every tab's checkpoint for this account (and the single pre-per-tab one), newest edit first. */ +async function readDeviceCheckpoints(owner: string): Promise { const database = await getDatabase(); - const checkpoint = (await database.get(STORE_NAME, `${CHECKPOINT_KEY_PREFIX}${owner}`)) as DeviceCheckpoint | undefined; - return checkpoint?.owner === owner && typeof checkpoint.editedAt === "number" - ? { ...checkpoint, baseVersion: typeof checkpoint.baseVersion === "number" ? checkpoint.baseVersion : null } - : null; + const legacyKey = `${CHECKPOINT_KEY_PREFIX}${owner}`; + const keys = (await database.getAllKeys(STORE_NAME)).filter( + (key): key is string => typeof key === "string" && (key === legacyKey || key.startsWith(`${legacyKey}:`)), + ); + const checkpoints: StoredCheckpoint[] = []; + for (const key of keys) { + const checkpoint = (await database.get(STORE_NAME, key)) as DeviceCheckpoint | undefined; + if (checkpoint?.owner === owner && typeof checkpoint.editedAt === "number") { + checkpoints.push({ + ...checkpoint, + baseVersion: typeof checkpoint.baseVersion === "number" ? checkpoint.baseVersion : null, + key, + }); + } + } + return checkpoints.sort((a, b) => b.editedAt - a.editedAt); } /** Clears the checkpoint only if nothing newer than `upToEditedAt` was recorded since (a newer edit stays safe). */ @@ -207,10 +305,10 @@ async function clearDeviceCheckpoint( owner: string, upToEditedAt = Number.POSITIVE_INFINITY, acknowledged?: { version: number; readAt: number }, - options: { anyTab?: boolean } = {}, + options: { anyTab?: boolean; key?: string } = {}, ): Promise { const database = await getDatabase(); - const key = `${CHECKPOINT_KEY_PREFIX}${owner}`; + const key = options.key ?? ownCheckpointKey(owner); // Compare and delete in one transaction so a checkpoint written in between is never lost. const transaction = database.transaction(STORE_NAME, "readwrite"); const found = (await transaction.store.get(key)) as DeviceCheckpoint | undefined; @@ -251,11 +349,113 @@ export function takeAccountSyncPending(owner: string | null | undefined): boolea return accountSyncPendingOwners.delete(owner); } +/** The account load running for each device cache key, shared by overlapping callers. */ +const inFlightCloudLoads = new Map>(); + +/** Accounts that just received the files a guest wrote before signing in. */ +const guestImportOwners = new Set(); + +/** True once after a load that added the files written before signing in. */ +export function takeGuestImported(owner: string | null | undefined): boolean { + if (!owner) return false; + return guestImportOwners.delete(owner); +} + +/** + * Keeps a signed-out student's work for this tab (it survives a sign-in redirect), so signing in to save it adds it + * to the account instead of dropping it. Each stash adds to the earlier one (a guest who moves between practice + * questions keeps every answer); a document in both keeps its latest version. An empty workspace changes nothing. + */ +export function stashGuestDraft(state: WorkspaceState, copyLabel = GUEST_FOLDER_NAME): void { + if (typeof window === "undefined") return; + const hasWork = + Object.values(state.nodes).some((node) => node.type === "document" && node.source.trim() !== "") || + Object.values(state.virtualFiles ?? {}).some((lines) => lines.some((line) => line.trim() !== "")); + if (!hasWork) return; + try { + const earlierText = window.sessionStorage.getItem(GUEST_DRAFT_SESSION_KEY); + const earlier = earlierText ? parseGuestDraft(earlierText, "") : null; + let combined = state; + if (earlier) { + for (const node of Object.values(earlier.nodes)) { + if (node.type !== "document" || combined.nodes[node.id] || node.source.trim() === "") continue; + combined = createDocument(combined, { id: node.id, name: node.name, source: node.source, now: node.updatedAt }); + } + // Each guest visit starts a fresh workspace, so a same-named data file with other contents is earlier work + // (e.g. another question's results.txt): keep it as a copy rather than lose it. + combined = mergeVirtualFilesAsCopies(combined, earlier, copyLabel); + } + window.sessionStorage.setItem(GUEST_DRAFT_SESSION_KEY, JSON.stringify(combined)); + } catch { + /* storage blocked or full: nothing more can be kept */ + } +} + +function readGuestDraftText(): string | null { + if (typeof window === "undefined") return null; + try { + return window.sessionStorage.getItem(GUEST_DRAFT_SESSION_KEY); + } catch { + return null; + } +} + +function parseGuestDraft(text: string, sampleSource: string): WorkspaceState | null { + try { + return migratePersistedWorkspace(JSON.parse(text), { sampleSource }); + } catch { + return null; + } +} + +/** Clears the stashed draft only if it is still the one that was imported (newer guest work stays for later). */ +function clearGuestDraft(imported: string): void { + try { + if (window.sessionStorage.getItem(GUEST_DRAFT_SESSION_KEY) === imported) { + window.sessionStorage.removeItem(GUEST_DRAFT_SESSION_KEY); + } + } catch { + /* nothing to clear */ + } +} + +/** The account most recently asked to load; only its load may take the guest's draft. */ +let latestCloudLoadOwner: string | null = null; + +/** Adds the files written before signing in to the account's workspace, safe on this device until they sync. */ +async function importGuestDraft( + loaded: WorkspaceState, + owner: string, + draftText: string | null, + sampleSource: string, + cacheKey: string, + folderName: string, +): Promise { + // A load abandoned for another account or for signing out leaves the draft to whoever is current. + if (!draftText || owner !== latestCloudLoadOwner) return loaded; + const draft = parseGuestDraft(draftText, sampleSource); + if (!draft) return loaded; + const merged = mergeCheckpointAsCopies(loaded, draft, null, folderName); + if (merged !== loaded) { + const database = await getDatabase(); + await database.put(STORE_NAME, merged, cacheKey); + // The checkpoint keeps the imported files if the tab closes before the account sync lands. + await saveDeviceCheckpoint(merged, owner, Date.now()); + accountSyncPendingOwners.add(owner); + guestImportOwners.add(owner); + } + // Superseded while writing: the files are safe in this account's checkpoint, and stay stashed for the current one. + if (owner === latestCloudLoadOwner) clearGuestDraft(draftText); + return merged; +} + export async function loadWorkspace( sampleSource: string, options: WorkspaceStorageOptions = {}, ): Promise { const mode = options.mode ?? (options.syncToCloud ? "cloud" : "local"); + // Signing out (or any non-account load) supersedes an account load still running. + if (mode !== "cloud") latestCloudLoadOwner = null; if (mode === "memory") { return createEmptyWorkspace(); @@ -264,97 +464,174 @@ export async function loadWorkspace( if (mode === "cloud") { const owner = options.checkpointOwner ?? null; const cacheKey = deviceCacheKey(owner); - // Read the checkpoint before the cloud load overwrites the device cache. - const checkpoint = owner ? await readDeviceCheckpoint(owner).catch(() => null) : null; - const cloud = await loadWorkspaceFromCloud(sampleSource, options.getAuthToken, cacheKey); - const restoreCheckpoint = async (current: DeviceCheckpoint) => { - // Edits made after the last account sync (the tab closed or crashed first): keep them; the session syncs them - // straight away through its normal save path, so success or failure shows in the save status. - const restored = migratePersistedWorkspace(current.state, { sampleSource }); - const database = await getDatabase(); - await database.put(STORE_NAME, restored, cacheKey); - // This tab now carries these edits, so its acknowledged sync may clear the checkpoint. - await database.put( - STORE_NAME, - { ...current, state: restored, tabId: TAB_ID } satisfies DeviceCheckpoint, - `${CHECKPOINT_KEY_PREFIX}${current.owner}`, + latestCloudLoadOwner = owner; + // Recovery and guest import move work between stores, so two loads of one account must never interleave (e.g. + // leaving the editor and coming back before the first load finished): later callers share the running load. + const running = inFlightCloudLoads.get(cacheKey); + if (running) return running; + // The draft as it was when this load began: guest work written later is never taken by this load. + const draftText = readGuestDraftText(); + const load = (async () => { + const loaded = await loadCloudWorkspace(sampleSource, options); + return owner + ? importGuestDraft(loaded, owner, draftText, sampleSource, cacheKey, options.guestFolderName ?? GUEST_FOLDER_NAME) + : loaded; + })().finally(() => inFlightCloudLoads.delete(cacheKey)); + inFlightCloudLoads.set(cacheKey, load); + return load; + } + + return migrateWorkspace(sampleSource); +} + +async function loadCloudWorkspace(sampleSource: string, options: WorkspaceStorageOptions): Promise { + const owner = options.checkpointOwner ?? null; + const cacheKey = deviceCacheKey(owner); + const folderName = options.recoveredFolderName ?? RECOVERED_FOLDER_NAME; + // Read the checkpoints before the cloud load overwrites the device cache. + const checkpoints = owner ? await readDeviceCheckpoints(owner).catch(() => []) : []; + const checkpoint = checkpoints[0] ?? null; + const otherCheckpoints = checkpoints.slice(1); + const cloud = await loadWorkspaceFromCloud(sampleSource, options.getAuthToken, cacheKey, owner); + /** Adds the files other (closed) tabs changed but never synced, as copies, so none of their work is dropped. */ + const foldOtherCheckpoints = (state: WorkspaceState) => { + let merged = state; + for (const other of otherCheckpoints) { + const otherState = migratePersistedWorkspace(other.state, { sampleSource }); + if (checkpointMatchesAccount(otherState, merged)) continue; + merged = mergeCheckpointAsCopies( + merged, + otherState, + other.baseVersion === null ? null : (other.baseReadAt ?? null), + folderName, ); - accountSyncPendingOwners.add(current.owner); - return restored; - }; + } + if (merged !== state) recoveredCopyOwners.add(otherCheckpoints[0]!.owner); + return merged; + }; + const restoreCheckpoint = async (current: DeviceCheckpoint, alreadyFolded = false) => { + // Edits made after the last account sync (the tab closed or crashed first): keep them; the session syncs them + // straight away through its normal save path, so success or failure shows in the save status. + const migrated = migratePersistedWorkspace(current.state, { sampleSource }); + const restored = alreadyFolded ? migrated : foldOtherCheckpoints(migrated); + const database = await getDatabase(); + await database.put(STORE_NAME, restored, cacheKey); + // This tab now carries these edits (its own and any it adopted from other tabs' checkpoints), so its + // acknowledged sync may clear them. + const { owner: checkpointOwner, editedAt, baseVersion, baseReadAt } = current; + const ownKey = ownCheckpointKey(checkpointOwner); + await database.put( + STORE_NAME, + { + owner: checkpointOwner, + state: restored, + editedAt: Math.max(editedAt, ...otherCheckpoints.map((other) => other.editedAt)), + baseVersion, + baseReadAt, + tabId: TAB_ID, + } satisfies DeviceCheckpoint, + ownKey, + ); + for (const adopted of checkpoints) { + if (adopted.key === ownKey) continue; + // Delete only the version that was read: a tab still open may have checkpointed newer work since, which then + // stays for the next load. + const transaction = database.transaction(STORE_NAME, "readwrite"); + const stillStored = (await transaction.store.get(adopted.key)) as DeviceCheckpoint | undefined; + if (stillStored && stillStored.editedAt === adopted.editedAt) await transaction.store.delete(adopted.key); + await transaction.done; + } + accountSyncPendingOwners.add(checkpointOwner); + return restored; + }; - if (!cloud.ok) { - if (!owner) { - return migrateWorkspace(sampleSource); + if (!cloud.ok) { + if (!owner) { + return migrateWorkspace(sampleSource); + } + // The account could not be read (offline, server error). Open only this account's own device copy, and hold + // account writes until a read succeeds so a stale copy can never overwrite the real one. + unreadableCloudOwners.add(owner); + accountSyncPendingOwners.add(owner); + if (checkpoint) return restoreCheckpoint(checkpoint); + const ownCache = await readOwnCache(cacheKey, sampleSource); + return ownCache ?? createEmptyWorkspace(); + } + if (owner) unreadableCloudOwners.delete(owner); + + const cloudWorkspace = cloud.workspace; + if (cloudWorkspace) { + const accountVersion = accountFingerprint(cloudWorkspace); + if (owner) accountBaseVersions.set(owner, { version: accountVersion, readAt: Date.now() }); + // Restored edits are not in the account until their sync lands, so later checkpoints must keep measuring from + // when those edits began, not from this load (else a failed sync could let them be filtered out of recovery). + const keepRestoredBase = (restoring: DeviceCheckpoint) => { + if (owner) { + accountBaseVersions.set(owner, { + version: accountVersion, + readAt: restoring.baseVersion === null ? 0 : (restoring.baseReadAt ?? 0), + }); } - // The account could not be read (offline, server error). Open only this account's own device copy, and hold - // account writes until a read succeeds so a stale copy can never overwrite the real one. - unreadableCloudOwners.add(owner); - accountSyncPendingOwners.add(owner); - if (checkpoint) return restoreCheckpoint(checkpoint); - const ownCache = await readOwnCache(cacheKey, sampleSource); - return ownCache ?? createEmptyWorkspace(); + }; + if (checkpoint && checkpoint.baseVersion === accountVersion) { + // The account hasn't changed since these edits began: they are simply its next version. + keepRestoredBase(checkpoint); + return restoreCheckpoint(checkpoint); } - if (owner) unreadableCloudOwners.delete(owner); - - const cloudWorkspace = cloud.workspace; - if (cloudWorkspace) { - const accountVersion = accountFingerprint(cloudWorkspace); - if (owner) accountBaseVersions.set(owner, { version: accountVersion, readAt: Date.now() }); - // Restored edits are not in the account until their sync lands, so later checkpoints must keep measuring from - // when those edits began, not from this load (else a failed sync could let them be filtered out of recovery). - const keepRestoredBase = (restoring: DeviceCheckpoint) => { - if (owner) { - accountBaseVersions.set(owner, { - version: accountVersion, - readAt: restoring.baseVersion === null ? 0 : (restoring.baseReadAt ?? 0), - }); - } - }; - if (checkpoint && checkpoint.baseVersion === accountVersion) { - // The account hasn't changed since these edits began: they are simply its next version. + if (checkpoint) { + // The account moved on elsewhere (or these edits were made while it couldn't be read): never overwrite it, + // and never drop the device's work silently. Keep the account's version, add this device's changed files + // beside it, and tell the student. + const merged = mergeCheckpointAsCopies( + cloudWorkspace, + migratePersistedWorkspace(checkpoint.state, { sampleSource }), + checkpoint.baseVersion === null ? null : (checkpoint.baseReadAt ?? null), + options.recoveredFolderName ?? RECOVERED_FOLDER_NAME, + ); + if (merged !== cloudWorkspace) { + recoveredCopyOwners.add(checkpoint.owner); keepRestoredBase(checkpoint); - return restoreCheckpoint(checkpoint); + return restoreCheckpoint({ ...checkpoint, state: merged }); } - if (checkpoint) { - // The account moved on elsewhere (or these edits were made while it couldn't be read): never overwrite it, - // and never drop the device's work silently. Keep the account's version, add this device's changed files - // beside it, and tell the student. - const merged = mergeCheckpointAsCopies( - cloudWorkspace, - migratePersistedWorkspace(checkpoint.state, { sampleSource }), - checkpoint.baseVersion === null ? null : (checkpoint.baseReadAt ?? null), - options.recoveredFolderName ?? RECOVERED_FOLDER_NAME, - ); - if (merged !== cloudWorkspace) { - recoveredCopyOwners.add(checkpoint.owner); - keepRestoredBase(checkpoint); - return restoreCheckpoint({ ...checkpoint, state: merged }); + } + // Other tabs' unsynced files the account doesn't have yet are added as copies (their checkpoints are adopted). + const folded = otherCheckpoints.length > 0 ? foldOtherCheckpoints(cloudWorkspace) : cloudWorkspace; + if (owner && folded !== cloudWorkspace) { + // Measure from the oldest edits folded in (not from now), so a failed sync followed by a change elsewhere + // still recovers every copy made here. + const foldedBaseReadAt = Math.min( + ...otherCheckpoints.map((other) => (other.baseVersion === null ? 0 : (other.baseReadAt ?? 0))), + ); + accountBaseVersions.set(owner, { version: accountVersion, readAt: foldedBaseReadAt }); + return restoreCheckpoint( + { owner, state: folded, editedAt: 0, baseVersion: accountVersion, baseReadAt: foldedBaseReadAt }, + true, + ); + } + // A checkpoint the account already contains in full (its save landed but the reply never arrived) is done, + // whichever tab wrote it. One that still differs is kept, so its work is never deleted. + if (owner) { + for (const done of checkpoints) { + if (checkpointMatchesAccount(done.state, cloudWorkspace)) { + void clearDeviceCheckpoint(owner, done.editedAt, undefined, { anyTab: true, key: done.key }).catch(() => {}); } } - // A checkpoint the account already contains in full (its save landed but the reply never arrived) is done, - // whichever tab wrote it. One that still differs is kept, so its work is never deleted. - if (owner && checkpoint && checkpointMatchesAccount(checkpoint.state, cloudWorkspace)) { - void clearDeviceCheckpoint(owner, checkpoint.editedAt, undefined, { anyTab: true }).catch(() => {}); - } - return cloudWorkspace; - } - if (checkpoint) return restoreCheckpoint(checkpoint); - - // The account has no workspace yet. Only this account's own device copy may seed it: on a shared computer the - // unscoped cache belongs to whoever used it before, so a new account starts empty instead. - const seed = owner ? await readOwnCache(cacheKey, sampleSource) : await migrateWorkspace(sampleSource); - if (!seed) { - return createEmptyWorkspace(); } - const seedToken = options.getAuthToken ? await options.getAuthToken().catch(() => null) : null; - void enqueueCloudWrite(() => saveWorkspaceToCloud(seed, async () => seedToken)).catch(() => { - /* Keep local cache usable even when an initial cloud backfill fails. */ - }); - return seed; + return cloudWorkspace; } + if (checkpoint) return restoreCheckpoint(checkpoint); - return migrateWorkspace(sampleSource); + // The account has no workspace yet. Only this account's own device copy may seed it: on a shared computer the + // unscoped cache belongs to whoever used it before, so a new account starts empty instead. + const seed = owner ? await readOwnCache(cacheKey, sampleSource) : await migrateWorkspace(sampleSource); + if (!seed) { + return createEmptyWorkspace(); + } + const seedToken = options.getAuthToken ? await options.getAuthToken().catch(() => null) : null; + void enqueueCloudWrite(() => saveWorkspaceToCloud(seed, async () => seedToken, cacheKey, owner)).catch(() => { + /* Keep local cache usable even when an initial cloud backfill fails. */ + }); + return seed; } export async function saveWorkspace( @@ -387,7 +664,7 @@ export async function saveWorkspace( throw new Error("Your account couldn't be reached, so changes are kept on this device. Reload to sync them."); } const token = await tokenRequest; - await saveWorkspaceToCloud(state, async () => token); + await saveWorkspaceToCloud(state, async () => token, deviceCacheKey(owner), owner); if (options.checkpointOwner) { // The account now holds edits up to this snapshot's own edit time (not the reply's arrival time), so edits // made while the request was in flight still count as newer than the acknowledged base. @@ -448,16 +725,16 @@ export async function migrateWorkspace(sampleSource: string): Promise Promise, + getAuthToken: (() => Promise) | undefined, + owner: string | null, ): Promise { const token = getAuthToken ? await getAuthToken() : null; - if (!token) { - return baseHeaders; - } - return { ...baseHeaders, - Authorization: `Bearer ${token}`, + ...(token ? { Authorization: `Bearer ${token}` } : {}), + // The account this request was made for: after an account switch the sign-in belongs to someone else, and the + // server refuses rather than read or write the other account's workspace. + ...(owner ? { "X-Workspace-Account": owner } : {}), }; } @@ -468,18 +745,30 @@ async function loadWorkspaceFromCloud( sampleSource: string, getAuthToken: (() => Promise) | undefined, cacheKey: string, + owner: string | null, ): Promise { if (typeof window === "undefined") { return { ok: false }; } + // Reads wait behind this tab's queued account writes: a fresh revision must never be handed to a save that was + // requested (and built) before the read, or that save could overwrite the newer version it never saw. + return enqueueCloudWrite(() => readWorkspaceFromCloud(sampleSource, getAuthToken, cacheKey, owner)); +} + +async function readWorkspaceFromCloud( + sampleSource: string, + getAuthToken: (() => Promise) | undefined, + cacheKey: string, + owner: string | null, +): Promise { try { const response = await fetch("/api/workspace", { method: "GET", credentials: "same-origin", headers: await getCloudRequestHeaders({ Accept: "application/json", - }, getAuthToken), + }, getAuthToken, owner), }); if (!response.ok) { @@ -487,6 +776,11 @@ async function loadWorkspaceFromCloud( } const data = (await response.json()) as CloudWorkspaceResponse; + if (data.revision === null || typeof data.revision === "number") { + accountRevisions.set(cacheKey, data.revision); + } else { + accountRevisions.delete(cacheKey); + } if (!data.workspace) { return { ok: true, workspace: null }; } @@ -502,26 +796,48 @@ async function loadWorkspaceFromCloud( async function saveWorkspaceToCloud( state: WorkspaceState, - getAuthToken?: () => Promise, + getAuthToken: (() => Promise) | undefined, + cacheKey: string, + owner: string | null, ): Promise { + // Writes only over the revision this tab last saw; account writes are queued, so this is the latest one. + const expectedRevision = accountRevisions.get(cacheKey); const response = await fetch("/api/workspace", { method: "PUT", credentials: "same-origin", headers: await getCloudRequestHeaders({ "Content-Type": "application/json", - }, getAuthToken), - body: JSON.stringify({ workspace: state }), + }, getAuthToken, owner), + body: JSON.stringify( + accountRevisions.has(cacheKey) ? { workspace: state, expectedRevision } : { workspace: state }, + ), }); - if (!response.ok) { - let errorDetail = ""; + if (response.status === 409) { + throw new WorkspaceConflictError(); + } + + if (response.ok) { try { - const body = (await response.json()) as { error?: unknown }; - errorDetail = typeof body.error === "string" ? ` ${body.error}` : ""; + const body = (await response.json()) as { revision?: unknown }; + if (typeof body.revision === "number") accountRevisions.set(cacheKey, body.revision); } catch { - errorDetail = ""; + /* an older server sends no revision */ } + return; + } - throw new Error(`Unable to save workspace to Convex.${errorDetail}`); + let errorDetail = ""; + try { + const body = (await response.json()) as { error?: unknown }; + errorDetail = typeof body.error === "string" ? ` ${body.error}` : ""; + } catch { + errorDetail = ""; } + + if (response.status === 413) { + throw new WorkspaceTooLargeError(errorDetail.trim()); + } + + throw new Error(`Unable to save workspace to Convex.${errorDetail}`); } diff --git a/convex/schema.ts b/convex/schema.ts index c047bc1..6c8f161 100644 --- a/convex/schema.ts +++ b/convex/schema.ts @@ -13,6 +13,8 @@ export default defineSchema({ clerkUserId: v.string(), workspaceJson: v.optional(v.string()), workspace: v.optional(v.any()), + /** Bumped on every save so a client can only overwrite the version it last read. Missing on older rows: 0. */ + revision: v.optional(v.number()), updatedAt: v.number(), }).index("by_clerk_user", ["clerkUserId"]), }); diff --git a/convex/workspaces.ts b/convex/workspaces.ts index 83cae27..7f7d0d0 100644 --- a/convex/workspaces.ts +++ b/convex/workspaces.ts @@ -250,6 +250,7 @@ function readStoredWorkspace(workspaceDoc: { workspaceJson?: string; workspace?: } } +/** Kept for web deployments released before `getCurrentSnapshot`; new code reads the snapshot instead. */ export const getCurrent = query({ args: {}, handler: async (ctx) => { @@ -264,6 +265,39 @@ export const getCurrent = query({ }, }); +/** + * The account's workspace as JSON text plus its revision. Returned as text because Convex values only allow ASCII + * object keys, and the runtime's data files are keyed by student-chosen names such as "成绩.txt". + */ +export const getCurrentSnapshot = query({ + args: {}, + returns: v.union(v.null(), v.object({ workspaceJson: v.union(v.string(), v.null()), revision: v.number() })), + handler: async (ctx) => { + const clerkUserId = await requireAuthenticatedClerkUser(ctx); + + const workspace = await ctx.db + .query("workspaces") + .withIndex("by_clerk_user", (query) => query.eq("clerkUserId", clerkUserId)) + .unique(); + + if (!workspace) { + return null; + } + + // An unreadable stored copy reads as "no workspace" (as before), but keeps its revision so the next save can + // replace it. + const stored = readStoredWorkspace(workspace); + return { + workspaceJson: stored + ? typeof workspace.workspaceJson === "string" + ? workspace.workspaceJson + : JSON.stringify(stored) + : null, + revision: workspace.revision ?? 0, + }; + }, +}); + export const saveCurrent = mutation({ args: { user: v.object({ @@ -272,12 +306,30 @@ export const saveCurrent = mutation({ lastName: v.union(v.string(), v.null()), }), workspaceJson: v.string(), + /** + * The revision this save builds on (`null`: the client saw no workspace yet). When given, the save is refused if + * the account has moved on, so a stale tab or device can never silently replace newer work. + */ + expectedRevision: v.optional(v.union(v.number(), v.null())), }, + returns: v.union( + v.object({ ok: v.literal(true), revision: v.number() }), + v.object({ ok: v.literal(false), conflict: v.literal(true), revision: v.union(v.number(), v.null()) }), + ), handler: async (ctx, args) => { const identity = await requireAuthenticatedIdentity(ctx); const clerkUserId = identity.subject; parseWorkspaceJson(args.workspaceJson); + const existingWorkspace = await ctx.db + .query("workspaces") + .withIndex("by_clerk_user", (query) => query.eq("clerkUserId", clerkUserId)) + .unique(); + const currentRevision = existingWorkspace ? (existingWorkspace.revision ?? 0) : null; + if (args.expectedRevision !== undefined && args.expectedRevision !== currentRevision) { + return { ok: false as const, conflict: true as const, revision: currentRevision }; + } + // Prefer identity claims from the verified token over caller-supplied profile fields. const user = { email: typeof identity.email === "string" && identity.email ? identity.email : args.user.email, @@ -304,24 +356,22 @@ export const saveCurrent = mutation({ }); } - const existingWorkspace = await ctx.db - .query("workspaces") - .withIndex("by_clerk_user", (query) => query.eq("clerkUserId", clerkUserId)) - .unique(); - + const revision = (currentRevision ?? 0) + 1; if (existingWorkspace) { await ctx.db.patch(existingWorkspace._id, { workspace: undefined, workspaceJson: args.workspaceJson, + revision, + updatedAt: now, + }); + } else { + await ctx.db.insert("workspaces", { + clerkUserId, + workspaceJson: args.workspaceJson, + revision, updatedAt: now, }); - return existingWorkspace._id; } - - return await ctx.db.insert("workspaces", { - clerkUserId, - workspaceJson: args.workspaceJson, - updatedAt: now, - }); + return { ok: true as const, revision }; }, }); diff --git a/package.json b/package.json index 0004ec3..6d22203 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "pseudoeditor.dev", - "version": "0.1.9", + "version": "2.0.0", "private": true, "description": "PseudoEditor: free and open-source pseudo code editor and compiler.", "author": "Alex Xin LIU", @@ -28,7 +28,7 @@ "devDependencies": { "@types/node": "^20.19.43", "convex": "^1.45.0", - "next": "16.4.3", + "next": "16.4.5", "tsrs": "0.20.1-ts7.1.0-beta", "typescript": "^5.9.3", "vitest": "^4.1.11" diff --git a/packages/compiler/package.json b/packages/compiler/package.json index 4beb7ee..9051463 100644 --- a/packages/compiler/package.json +++ b/packages/compiler/package.json @@ -1,6 +1,6 @@ { "name": "@pseudoeditor/compiler", - "version": "0.1.9", + "version": "2.0.0", "private": true, "description": "Pseudocode compiler core — tokenizer, parser, semantics, and AST generation.", "main": "./src/index.ts", diff --git a/packages/workspace/package.json b/packages/workspace/package.json index da1f8ac..3a95337 100644 --- a/packages/workspace/package.json +++ b/packages/workspace/package.json @@ -1,6 +1,6 @@ { "name": "@pseudoeditor/workspace", - "version": "0.1.9", + "version": "2.0.0", "private": true, "description": "Shared workspace model and persistence helpers for Pseudocode Compiler.", "main": "./src/index.ts", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 7d4b84b..7be38a1 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -23,8 +23,8 @@ importers: specifier: ^1.45.0 version: 1.48.0(@clerk/react@6.18.2(react-dom@19.2.3(react@19.2.3))(react@19.2.3))(react@19.2.3) next: - specifier: 16.4.3 - version: 16.4.3(@babel/core@7.29.7)(@types/node@20.19.43)(babel-plugin-react-compiler@1.0.0)(react-dom@19.2.3(react@19.2.3))(react@19.2.3) + specifier: 16.4.5 + version: 16.4.5(@babel/core@7.29.7)(@types/node@20.19.43)(babel-plugin-react-compiler@1.0.0)(react-dom@19.2.3(react@19.2.3))(react@19.2.3) tsrs: specifier: 0.20.1-ts7.1.0-beta version: 0.20.1-ts7.1.0-beta @@ -42,7 +42,7 @@ importers: version: 4.24.2(react-dom@19.2.3(react@19.2.3))(react@19.2.3) '@clerk/nextjs': specifier: ^7.9.2 - version: 7.9.21(next@16.4.3(@babel/core@7.29.7)(@types/node@20.19.43)(babel-plugin-react-compiler@1.0.0)(react-dom@19.2.3(react@19.2.3))(react@19.2.3))(react-dom@19.2.3(react@19.2.3))(react@19.2.3) + version: 7.9.21(next@16.4.5(@babel/core@7.29.7)(@types/node@20.19.43)(babel-plugin-react-compiler@1.0.0)(react-dom@19.2.3(react@19.2.3))(react@19.2.3))(react-dom@19.2.3(react@19.2.3))(react@19.2.3) '@monaco-editor/react': specifier: ^4.7.0 version: 4.7.0(monaco-editor@0.55.1)(react-dom@19.2.3(react@19.2.3))(react@19.2.3) @@ -68,8 +68,8 @@ importers: specifier: ^0.55.1 version: 0.55.1 next: - specifier: 16.4.3 - version: 16.4.3(@babel/core@7.29.7)(@types/node@20.19.43)(babel-plugin-react-compiler@1.0.0)(react-dom@19.2.3(react@19.2.3))(react@19.2.3) + specifier: 16.4.5 + version: 16.4.5(@babel/core@7.29.7)(@types/node@20.19.43)(babel-plugin-react-compiler@1.0.0)(react-dom@19.2.3(react@19.2.3))(react@19.2.3) posthog-js: specifier: ^1.440.0 version: 1.440.0(@types/react@19.3.0)(react@19.2.3) @@ -111,8 +111,8 @@ importers: specifier: ^9.39.5 version: 9.39.5(jiti@2.7.0) eslint-config-next: - specifier: 16.4.3 - version: 16.4.3(@typescript-eslint/parser@8.59.1(eslint@9.39.5(jiti@2.7.0))(typescript@5.9.3))(eslint@9.39.5(jiti@2.7.0))(typescript@5.9.3) + specifier: 16.4.5 + version: 16.4.5(@typescript-eslint/parser@8.59.1(eslint@9.39.5(jiti@2.7.0))(typescript@5.9.3))(eslint@9.39.5(jiti@2.7.0))(typescript@5.9.3) jsdom: specifier: ^28.1.0 version: 28.1.0 @@ -766,60 +766,60 @@ packages: '@emnapi/core': ^1.7.1 '@emnapi/runtime': ^1.7.1 - '@next/env@16.4.3': - resolution: {integrity: sha512-a7tz1QCcWWkwC/rPJcPMJk/UNRu9CFhDd3OHYE5hddbJrs8BqRTalxI6GlKCWEGzRLHN+S/B7a4PAHCtm25aBQ==} + '@next/env@16.4.5': + resolution: {integrity: sha512-JwSPwpdkZL5VMl2jA/q+JI8MZdweAL3xmw5/tb9y/TLtmS0YXZnmYDzSihwk8xTj1OL+WM53gTqaj96yuLp6Xw==} - '@next/eslint-plugin-next@16.4.3': - resolution: {integrity: sha512-oxuC06wt/71h6ACYCV9GbKOfnf5a7VlRe/p80YHTut15TNgDEmynDnaq8t/xhy5rlvk7dhItIPs6H3rvIM4kyw==} + '@next/eslint-plugin-next@16.4.5': + resolution: {integrity: sha512-dNmc4y4En/34tWxaBFF2tG/R9GeiRwVPf7v8Az/Pqk8FcT4Uv0ePmrZKvWBL2nFy1QprPgJW+6XjfyV6jbRV3Q==} - '@next/swc-darwin-arm64@16.4.3': - resolution: {integrity: sha512-4yq5EXBt+VDtAZwTyfijaFp5D2C5oz3Ikw5a2kiX2K9nw72vrZX2q5UuAlkPtUMO1tQz6JTKpaKWjS7OOefTDQ==} + '@next/swc-darwin-arm64@16.4.5': + resolution: {integrity: sha512-W5TniBzWKASbNNwHZ/S/f1MxQUXU/LdjklVMWA0Ujbfl7SZnUzFls45hO0i/sF7Bx1jJBWp7WWmoQajXtX/O8A==} engines: {node: '>= 10'} cpu: [arm64] os: [darwin] - '@next/swc-darwin-x64@16.4.3': - resolution: {integrity: sha512-1Rvkn/LUhnEF8WxnRkOrqGhbwXui1bkWFxONKIbN+r7C+9KHDSZ+iUoj4CzymVMWUyZIyx9szcb9+kbKhD500A==} + '@next/swc-darwin-x64@16.4.5': + resolution: {integrity: sha512-uWq4qkHapBDS1oFltWS4YxTb9pLHAtLNcpbuK6SmRsebLYZqpBML/j/C0op+50JYGTpZgVL/DWNt/6oWlamrrw==} engines: {node: '>= 10'} cpu: [x64] os: [darwin] - '@next/swc-linux-arm64-gnu@16.4.3': - resolution: {integrity: sha512-dCKpXErGg3abUM6t5JTJV/ottVBTStJB5lRJTbgdUdQaQ+jNHiK56Hsc0YAEg/rinSh42hYG3HWiYmEMdilnxg==} + '@next/swc-linux-arm64-gnu@16.4.5': + resolution: {integrity: sha512-FdRcyOx5u5P51mlAqLB9EXdd8jZO5fsdHtk4BAQSkqOywCsbTNN/rmw+jO7pnmjNdAtu2AG46NzbCL2FPDrrgw==} engines: {node: '>= 10'} cpu: [arm64] os: [linux] libc: [glibc] - '@next/swc-linux-arm64-musl@16.4.3': - resolution: {integrity: sha512-WwYbhWkhYBvBtib1K4W0kL8MW2snBD2A5b3SN4vPpqalZbZs5+bQ1yzAdepVoOqrFfEW3dmREy4Zs1MrWcrFbw==} + '@next/swc-linux-arm64-musl@16.4.5': + resolution: {integrity: sha512-cyvmmgtRXR8aGVT86wi9Py53IlfyCx7P2fZxuAXAoTummDnhKtUyjrMeXfapqp4qgD+gT5RqyGD/VfA16jEK7Q==} engines: {node: '>= 10'} cpu: [arm64] os: [linux] libc: [musl] - '@next/swc-linux-x64-gnu@16.4.3': - resolution: {integrity: sha512-QymWvfUwDEC5/lpJOsxX5VAbyoR2D13+2Jsjz4be7gT4LPqEgdpkeLIR/HFfCLgKzoMhpJbp6I/JnogyNZHcaA==} + '@next/swc-linux-x64-gnu@16.4.5': + resolution: {integrity: sha512-hPc+Fl+N22DAvqZHq559NmamXboOX5Lu8I5Wl0DezfrhTk1Zz21NQeYoZDmNI/NjTcrdsVxM72Fzn2lI+Q+vAw==} engines: {node: '>= 10'} cpu: [x64] os: [linux] libc: [glibc] - '@next/swc-linux-x64-musl@16.4.3': - resolution: {integrity: sha512-Vmjd9D7DpA4Vv3cUlr82QWgJD/BQZmns801vtC5VWHg6jCIA4a5vMKpQnfrM2pyCrp2eV0ENdUg4PlN3bAc2Yw==} + '@next/swc-linux-x64-musl@16.4.5': + resolution: {integrity: sha512-gbACYE8IP/jlprNTpiWXHb8N9CofOzpnEwH2SrIz1dUbiJf1FbDssDupCAPeP1Taxe8mgG20sGZamJI7KFOdZw==} engines: {node: '>= 10'} cpu: [x64] os: [linux] libc: [musl] - '@next/swc-win32-arm64-msvc@16.4.3': - resolution: {integrity: sha512-lG1pPdPLk7gTyGb00n5JIMLdBJgjb+UEhSdZvFbhUMg0DyC6z4B7RnpSKF9VCd4imkLObVbXOFA0kFCpw7yFow==} + '@next/swc-win32-arm64-msvc@16.4.5': + resolution: {integrity: sha512-+8gj++ZMo8H20Xh2ijjNqyFk5LPLw0AC4Fs4Tq/G94rjjQXhOjN4jgSWsWKPFsyY26hfIeemJIwKtMxOsp5GBA==} engines: {node: '>= 10'} cpu: [arm64] os: [win32] - '@next/swc-win32-x64-msvc@16.4.3': - resolution: {integrity: sha512-NmQC9RkJdnPXRaMxtkCzobB3teVjqF33oSOnwDfi+XYGWWYpt+xlGK3mtktSKLbdjwaWbJu2OkkMiRFGUUncKg==} + '@next/swc-win32-x64-msvc@16.4.5': + resolution: {integrity: sha512-qNZj66pYXnaWLiF9R9GUbfBdrCv7kC6TaZfIwB2KH5WPc/8pEM3nVOj8hpQhWJU8S94rlH5MPDcX15+RrgUhiw==} engines: {node: '>= 10'} cpu: [x64] os: [win32] @@ -1839,8 +1839,8 @@ packages: resolution: {integrity: sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==} engines: {node: '>=10'} - eslint-config-next@16.4.3: - resolution: {integrity: sha512-j9IqBma6abp800frdUURaizYMgXOK+jNGyq6CsYcM9AxpSJs5D/TgMNGeAmRUilZvA7g9V1Tr71gNg9/SVTuMQ==} + eslint-config-next@16.4.5: + resolution: {integrity: sha512-mvh39zYLoNjpT5tVmf8xZu7i5lEOb5jN5cW6qD9OpeCp4GEEOeYta0Z2XyKiD0pYdlvm5/Td6Bi890maPRlIjg==} peerDependencies: eslint: '>=9.0.0' typescript: '>=3.3.1' @@ -2523,8 +2523,8 @@ packages: natural-compare@1.4.0: resolution: {integrity: sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw==} - next@16.4.3: - resolution: {integrity: sha512-OqxKTGi9u80FydydsMNYNjnuje9Au+kvHlt2GZ//ftdpDHm1dxKqAaENoOOTX5wKzn+9vaKUNIfZeyZUuLhCnA==} + next@16.4.5: + resolution: {integrity: sha512-rmdfsWosjTUO+6R0S3KokoIk6Kj0sWDRTe86tZHdqaWH/oXq/udX3/4xb+YQi7aWbyEFoglDU54kaifLCdXbBw==} engines: {node: '>=20.9.0'} hasBin: true peerDependencies: @@ -3438,12 +3438,12 @@ snapshots: - react - react-dom - '@clerk/nextjs@7.9.21(next@16.4.3(@babel/core@7.29.7)(@types/node@20.19.43)(babel-plugin-react-compiler@1.0.0)(react-dom@19.2.3(react@19.2.3))(react@19.2.3))(react-dom@19.2.3(react@19.2.3))(react@19.2.3)': + '@clerk/nextjs@7.9.21(next@16.4.5(@babel/core@7.29.7)(@types/node@20.19.43)(babel-plugin-react-compiler@1.0.0)(react-dom@19.2.3(react@19.2.3))(react@19.2.3))(react-dom@19.2.3(react@19.2.3))(react@19.2.3)': dependencies: '@clerk/backend': 3.26.3(react-dom@19.2.3(react@19.2.3))(react@19.2.3) '@clerk/react': 6.18.2(react-dom@19.2.3(react@19.2.3))(react@19.2.3) '@clerk/shared': 4.42.0(react-dom@19.2.3(react@19.2.3))(react@19.2.3) - next: 16.4.3(@babel/core@7.29.7)(@types/node@20.19.43)(babel-plugin-react-compiler@1.0.0)(react-dom@19.2.3(react@19.2.3))(react@19.2.3) + next: 16.4.5(@babel/core@7.29.7)(@types/node@20.19.43)(babel-plugin-react-compiler@1.0.0)(react-dom@19.2.3(react@19.2.3))(react@19.2.3) react: 19.2.3 react-dom: 19.2.3(react@19.2.3) server-only: 0.0.1 @@ -3820,37 +3820,37 @@ snapshots: '@tybys/wasm-util': 0.10.1 optional: true - '@next/env@16.4.3': {} + '@next/env@16.4.5': {} - '@next/eslint-plugin-next@16.4.3(eslint@9.39.5(jiti@2.7.0))': + '@next/eslint-plugin-next@16.4.5(eslint@9.39.5(jiti@2.7.0))': dependencies: '@eslint-community/eslint-utils': 4.9.1(eslint@9.39.5(jiti@2.7.0)) fast-glob: 3.3.1 transitivePeerDependencies: - eslint - '@next/swc-darwin-arm64@16.4.3': + '@next/swc-darwin-arm64@16.4.5': optional: true - '@next/swc-darwin-x64@16.4.3': + '@next/swc-darwin-x64@16.4.5': optional: true - '@next/swc-linux-arm64-gnu@16.4.3': + '@next/swc-linux-arm64-gnu@16.4.5': optional: true - '@next/swc-linux-arm64-musl@16.4.3': + '@next/swc-linux-arm64-musl@16.4.5': optional: true - '@next/swc-linux-x64-gnu@16.4.3': + '@next/swc-linux-x64-gnu@16.4.5': optional: true - '@next/swc-linux-x64-musl@16.4.3': + '@next/swc-linux-x64-musl@16.4.5': optional: true - '@next/swc-win32-arm64-msvc@16.4.3': + '@next/swc-win32-arm64-msvc@16.4.5': optional: true - '@next/swc-win32-x64-msvc@16.4.3': + '@next/swc-win32-x64-msvc@16.4.5': optional: true '@nodelib/fs.scandir@2.1.5': @@ -4912,13 +4912,13 @@ snapshots: escape-string-regexp@4.0.0: {} - eslint-config-next@16.4.3(@typescript-eslint/parser@8.59.1(eslint@9.39.5(jiti@2.7.0))(typescript@5.9.3))(eslint@9.39.5(jiti@2.7.0))(typescript@5.9.3): + eslint-config-next@16.4.5(@typescript-eslint/parser@8.59.1(eslint@9.39.5(jiti@2.7.0))(typescript@5.9.3))(eslint@9.39.5(jiti@2.7.0))(typescript@5.9.3): dependencies: - '@next/eslint-plugin-next': 16.4.3(eslint@9.39.5(jiti@2.7.0)) + '@next/eslint-plugin-next': 16.4.5(eslint@9.39.5(jiti@2.7.0)) eslint: 9.39.5(jiti@2.7.0) eslint-import-resolver-node: 0.3.10 - eslint-import-resolver-typescript: 3.10.1(eslint-plugin-import@2.32.0)(eslint@9.39.5(jiti@2.7.0)) - eslint-plugin-import: 2.32.0(@typescript-eslint/parser@8.59.1(eslint@9.39.5(jiti@2.7.0))(typescript@5.9.3))(eslint-import-resolver-typescript@3.10.1)(eslint@9.39.5(jiti@2.7.0)) + eslint-import-resolver-typescript: 3.10.1(eslint-plugin-import@2.32.0(@typescript-eslint/parser@8.59.1(eslint@9.39.5(jiti@2.7.0))(typescript@5.9.3))(eslint@9.39.5(jiti@2.7.0)))(eslint@9.39.5(jiti@2.7.0)) + eslint-plugin-import: 2.32.0(@typescript-eslint/parser@8.59.1(eslint@9.39.5(jiti@2.7.0))(typescript@5.9.3))(eslint-import-resolver-typescript@3.10.1(eslint-plugin-import@2.32.0(@typescript-eslint/parser@8.59.1(eslint@9.39.5(jiti@2.7.0))(typescript@5.9.3))(eslint@9.39.5(jiti@2.7.0)))(eslint@9.39.5(jiti@2.7.0)))(eslint@9.39.5(jiti@2.7.0)) eslint-plugin-jsx-a11y: 6.10.2(eslint@9.39.5(jiti@2.7.0)) eslint-plugin-react: 7.37.5(eslint@9.39.5(jiti@2.7.0)) eslint-plugin-react-hooks: 7.1.1(eslint@9.39.5(jiti@2.7.0)) @@ -4940,7 +4940,7 @@ snapshots: transitivePeerDependencies: - supports-color - eslint-import-resolver-typescript@3.10.1(eslint-plugin-import@2.32.0)(eslint@9.39.5(jiti@2.7.0)): + eslint-import-resolver-typescript@3.10.1(eslint-plugin-import@2.32.0(@typescript-eslint/parser@8.59.1(eslint@9.39.5(jiti@2.7.0))(typescript@5.9.3))(eslint@9.39.5(jiti@2.7.0)))(eslint@9.39.5(jiti@2.7.0)): dependencies: '@nolyfill/is-core-module': 1.0.39 debug: 4.4.3 @@ -4951,22 +4951,22 @@ snapshots: tinyglobby: 0.2.16 unrs-resolver: 1.11.1 optionalDependencies: - eslint-plugin-import: 2.32.0(@typescript-eslint/parser@8.59.1(eslint@9.39.5(jiti@2.7.0))(typescript@5.9.3))(eslint-import-resolver-typescript@3.10.1)(eslint@9.39.5(jiti@2.7.0)) + eslint-plugin-import: 2.32.0(@typescript-eslint/parser@8.59.1(eslint@9.39.5(jiti@2.7.0))(typescript@5.9.3))(eslint-import-resolver-typescript@3.10.1(eslint-plugin-import@2.32.0(@typescript-eslint/parser@8.59.1(eslint@9.39.5(jiti@2.7.0))(typescript@5.9.3))(eslint@9.39.5(jiti@2.7.0)))(eslint@9.39.5(jiti@2.7.0)))(eslint@9.39.5(jiti@2.7.0)) transitivePeerDependencies: - supports-color - eslint-module-utils@2.12.1(@typescript-eslint/parser@8.59.1(eslint@9.39.5(jiti@2.7.0))(typescript@5.9.3))(eslint-import-resolver-node@0.3.10)(eslint-import-resolver-typescript@3.10.1)(eslint@9.39.5(jiti@2.7.0)): + eslint-module-utils@2.12.1(@typescript-eslint/parser@8.59.1(eslint@9.39.5(jiti@2.7.0))(typescript@5.9.3))(eslint-import-resolver-node@0.3.10)(eslint-import-resolver-typescript@3.10.1(eslint-plugin-import@2.32.0(@typescript-eslint/parser@8.59.1(eslint@9.39.5(jiti@2.7.0))(typescript@5.9.3))(eslint@9.39.5(jiti@2.7.0)))(eslint@9.39.5(jiti@2.7.0)))(eslint@9.39.5(jiti@2.7.0)): dependencies: debug: 3.2.7 optionalDependencies: '@typescript-eslint/parser': 8.59.1(eslint@9.39.5(jiti@2.7.0))(typescript@5.9.3) eslint: 9.39.5(jiti@2.7.0) eslint-import-resolver-node: 0.3.10 - eslint-import-resolver-typescript: 3.10.1(eslint-plugin-import@2.32.0)(eslint@9.39.5(jiti@2.7.0)) + eslint-import-resolver-typescript: 3.10.1(eslint-plugin-import@2.32.0(@typescript-eslint/parser@8.59.1(eslint@9.39.5(jiti@2.7.0))(typescript@5.9.3))(eslint@9.39.5(jiti@2.7.0)))(eslint@9.39.5(jiti@2.7.0)) transitivePeerDependencies: - supports-color - eslint-plugin-import@2.32.0(@typescript-eslint/parser@8.59.1(eslint@9.39.5(jiti@2.7.0))(typescript@5.9.3))(eslint-import-resolver-typescript@3.10.1)(eslint@9.39.5(jiti@2.7.0)): + eslint-plugin-import@2.32.0(@typescript-eslint/parser@8.59.1(eslint@9.39.5(jiti@2.7.0))(typescript@5.9.3))(eslint-import-resolver-typescript@3.10.1(eslint-plugin-import@2.32.0(@typescript-eslint/parser@8.59.1(eslint@9.39.5(jiti@2.7.0))(typescript@5.9.3))(eslint@9.39.5(jiti@2.7.0)))(eslint@9.39.5(jiti@2.7.0)))(eslint@9.39.5(jiti@2.7.0)): dependencies: '@rtsao/scc': 1.1.0 array-includes: 3.1.9 @@ -4977,7 +4977,7 @@ snapshots: doctrine: 2.1.0 eslint: 9.39.5(jiti@2.7.0) eslint-import-resolver-node: 0.3.10 - eslint-module-utils: 2.12.1(@typescript-eslint/parser@8.59.1(eslint@9.39.5(jiti@2.7.0))(typescript@5.9.3))(eslint-import-resolver-node@0.3.10)(eslint-import-resolver-typescript@3.10.1)(eslint@9.39.5(jiti@2.7.0)) + eslint-module-utils: 2.12.1(@typescript-eslint/parser@8.59.1(eslint@9.39.5(jiti@2.7.0))(typescript@5.9.3))(eslint-import-resolver-node@0.3.10)(eslint-import-resolver-typescript@3.10.1(eslint-plugin-import@2.32.0(@typescript-eslint/parser@8.59.1(eslint@9.39.5(jiti@2.7.0))(typescript@5.9.3))(eslint@9.39.5(jiti@2.7.0)))(eslint@9.39.5(jiti@2.7.0)))(eslint@9.39.5(jiti@2.7.0)) hasown: 2.0.3 is-core-module: 2.16.1 is-glob: 4.0.3 @@ -5653,9 +5653,9 @@ snapshots: natural-compare@1.4.0: {} - next@16.4.3(@babel/core@7.29.7)(@types/node@20.19.43)(babel-plugin-react-compiler@1.0.0)(react-dom@19.2.3(react@19.2.3))(react@19.2.3): + next@16.4.5(@babel/core@7.29.7)(@types/node@20.19.43)(babel-plugin-react-compiler@1.0.0)(react-dom@19.2.3(react@19.2.3))(react@19.2.3): dependencies: - '@next/env': 16.4.3 + '@next/env': 16.4.5 '@swc/helpers': 0.5.23 baseline-browser-mapping: 2.11.21 caniuse-lite: 1.0.30001810 @@ -5664,14 +5664,14 @@ snapshots: react-dom: 19.2.3(react@19.2.3) styled-jsx: 5.1.6(@babel/core@7.29.7)(react@19.2.3) optionalDependencies: - '@next/swc-darwin-arm64': 16.4.3 - '@next/swc-darwin-x64': 16.4.3 - '@next/swc-linux-arm64-gnu': 16.4.3 - '@next/swc-linux-arm64-musl': 16.4.3 - '@next/swc-linux-x64-gnu': 16.4.3 - '@next/swc-linux-x64-musl': 16.4.3 - '@next/swc-win32-arm64-msvc': 16.4.3 - '@next/swc-win32-x64-msvc': 16.4.3 + '@next/swc-darwin-arm64': 16.4.5 + '@next/swc-darwin-x64': 16.4.5 + '@next/swc-linux-arm64-gnu': 16.4.5 + '@next/swc-linux-arm64-musl': 16.4.5 + '@next/swc-linux-x64-gnu': 16.4.5 + '@next/swc-linux-x64-musl': 16.4.5 + '@next/swc-win32-arm64-msvc': 16.4.5 + '@next/swc-win32-x64-msvc': 16.4.5 babel-plugin-react-compiler: 1.0.0 sharp: 0.35.5(@types/node@20.19.43) transitivePeerDependencies: