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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions apps/web/package.json
Original file line number Diff line number Diff line change
@@ -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",
Expand All @@ -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",
Expand All @@ -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",
Expand Down
4 changes: 4 additions & 0 deletions apps/web/src/app/[locale]/app/page.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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`. */
Expand Down
27 changes: 18 additions & 9 deletions apps/web/src/app/[locale]/app/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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 ── */
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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 (
<div className="flex items-center gap-3" role="status">
<span className={unreachable ? "text-[var(--red)]" : "text-[var(--text2)]"}>
{unreachable ? t.sync.accountUnreachable : t.sync.recoveredCopies}
</span>
<span className={needsReload ? "text-[var(--red)]" : "text-[var(--text2)]"}>{message}</span>
<button
type="button"
className="ui-btn ui-btn-secondary h-6 px-2 text-xs"
onClick={unreachable ? () => window.location.reload() : dismissSyncNotice}
onClick={needsReload ? () => window.location.reload() : dismissSyncNotice}
>
{unreachable ? t.sync.retry : t.common.dismiss}
{syncNotice === "account-unreachable" ? t.sync.retry : needsReload ? t.sync.reload : t.common.dismiss}
</button>
</div>
);
Expand Down Expand Up @@ -2233,7 +2242,7 @@ export default function HomePage() {
<div className="shrink-0 border-b border-[var(--separator)] bg-[var(--surface)] px-4 py-1.5">
<div className="flex flex-wrap items-center gap-3 text-[11px]">
{renderSyncNotice()}
{saveError && syncNotice !== "account-unreachable" && <span className="text-[var(--red)]">{localizedSaveError}</span>}
{saveError && syncNotice !== "account-unreachable" && syncNotice !== "account-changed" && <span className="text-[var(--red)]">{localizedSaveError}</span>}
{appNotice && (
<div className="flex items-center gap-3">
<span
Expand Down Expand Up @@ -2714,7 +2723,7 @@ export default function HomePage() {
<div className="shrink-0 border-b border-[var(--separator)] bg-[var(--surface)] px-4 py-1.5">
<div className="flex flex-wrap items-center gap-3 text-[11px]">
{renderSyncNotice()}
{saveError && syncNotice !== "account-unreachable" && <span className="text-[var(--red)]">{localizedSaveError}</span>}
{saveError && syncNotice !== "account-unreachable" && syncNotice !== "account-changed" && <span className="text-[var(--red)]">{localizedSaveError}</span>}
{appNotice && (
<div className="flex items-center gap-3">
<span
Expand Down
75 changes: 75 additions & 0 deletions apps/web/src/app/api/workspace/convexWorkspaces.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
import { createDefaultWorkspace } from "@pseudoeditor/workspace";
import { describe, expect, it } from "vitest";
import { getCurrentSnapshot, saveCurrent } from "../../../../../../convex/workspaces";

type Row = Record<string, unknown> & { _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<string, Row[]>();
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<string, unknown>) => {
const row = { ...value, _id: `${name}_${nextId++}` } as Row;
table(name).push(row);
return row._id;
},
patch: async (id: string, value: Record<string, unknown>) => {
for (const rows of tables.values()) {
const row = rows.find((candidate) => candidate._id === id);
if (row) Object.assign(row, value);
}
},
},
};
return ctx;
}

type Handler<Args, Result> = { _handler: (ctx: unknown, args: Args) => Promise<Result> };
const save = (saveCurrent as unknown as Handler<Record<string, unknown>, { ok: boolean; revision: number | null }>)._handler;
const read = (getCurrentSnapshot as unknown as Handler<Record<string, never>, { workspaceJson: string | null; revision: number } | null>)._handler;

const user = { email: "student@example.com", firstName: null, lastName: null };
const workspaceJson = (source: string, extra: Record<string, unknown> = {}) =>
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"] });
});
});
54 changes: 53 additions & 1 deletion apps/web/src/app/api/workspace/route.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ vi.mock("../../../../../../convex/_generated/api", () => ({
api: {
workspaces: {
getCurrent: "workspaces:getCurrent",
getCurrentSnapshot: "workspaces:getCurrentSnapshot",
saveCurrent: "workspaces:saveCurrent",
},
},
Expand Down Expand Up @@ -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(
Expand All @@ -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 () => {
Expand Down Expand Up @@ -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();
});
});
49 changes: 45 additions & 4 deletions apps/web/src/app/api/workspace/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down Expand Up @@ -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,
};
}

Expand All @@ -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) {
Expand All @@ -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 });
}
2 changes: 1 addition & 1 deletion apps/web/src/app/components/WorkspaceSidebar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down
Loading