From 3719601c87e3c0a74402eba5da9326dfeb0f7705 Mon Sep 17 00:00:00 2001 From: sickerine Date: Sun, 6 Dec 2026 00:56:58 +0000 Subject: [PATCH 1/3] fix(workspaces): a switch is kept on the account at once, and a new browser no longer wipes it The first-use walker Daniel switched to his organization from the account menu, never reloaded, and the next day's new browser opened in his own workspace: the account was told only on a page load, which a switch doesn't make. The switch, and making a new organization, now tell it as they happen. Replaying it then showed the account wiped: a new browser's first page shows the person's own workspace before it has asked, the cookie remembered that, and the proxy told the account "own workspace". The proxy now tells the account only of organizations; moving back to one's own workspace is told by the switch itself. Checked on a local build against shared dev with Clerk's real sign-in page: day one signs in, switches from the menu and opens an own-workspace page; day two, on a new browser, signs in and lands in the organization, and /publish opens there too. --- components/workspaces/rail.tsx | 6 +++++- components/workspaces/switcher.tsx | 5 ++++- proxy.ts | 8 +++++--- 3 files changed, 14 insertions(+), 5 deletions(-) diff --git a/components/workspaces/rail.tsx b/components/workspaces/rail.tsx index 77ca079e3..562f1562b 100644 --- a/components/workspaces/rail.tsx +++ b/components/workspaces/rail.tsx @@ -10,7 +10,7 @@ import React, { useCallback, useEffect, useRef, useState, useTransition } from " import { SCREENINGS_PATH } from "@/lib/screening/links"; import { usePathname, useRouter, useSearchParams } from "next/navigation"; import { useAuth, useClerk, useUser } from "@clerk/nextjs"; -import { useQuery } from "convex/react"; +import { useMutation, useQuery } from "convex/react"; import { showStyledToast } from "@/components/ui/sonner"; import { useTheme } from "next-themes"; import { useFormatter, useTranslations } from "next-intl"; @@ -141,6 +141,9 @@ export function SidebarContent({ firstWorkspace, onClose }: { firstWorkspace: Fi const own = slug === null ? undefined : workspaces.list?.find((workspace) => workspace.kind === "personal"); const sharedWithYou = useProtectedQuery(api.sharing.shared.counts, own ? { workspaceId: own.workspaceId } : "skip").data?.total; const router = useRouter(); + // A switch is kept on the account as it is made, so another browser opens there too (convex/workspaces/lastUsed.ts): + // a switch changes the page without loading it, which the proxy would only hear of on the next page load. + const rememberWorkspace = useMutation(api.workspaces.lastUsed.remember); const [picked, setPicked] = useState(null); const [switching, startSwitch] = useTransition(); const loading = picked !== null && slug === (picked.slug ?? null) && loaded?.workspaceId !== picked.workspaceId; @@ -356,6 +359,7 @@ export function SidebarContent({ firstWorkspace, onClose }: { firstWorkspace: Fi onSwitch={(slug, to) => { close(); if (to) setPicked(to); + void rememberWorkspace({ slug: slug ?? null }).catch(() => undefined); startSwitch(() => router.push(switchTarget(slug, window.location.pathname, window.location.search.slice(1)))); }} onCreate={() => { diff --git a/components/workspaces/switcher.tsx b/components/workspaces/switcher.tsx index 0c8bd3ee3..b983e650b 100644 --- a/components/workspaces/switcher.tsx +++ b/components/workspaces/switcher.tsx @@ -16,7 +16,7 @@ import { IdentityAvatar } from "@/components/ui/identity-avatar"; import { RoleLabel } from "@/components/ui/identity"; import { Input } from "@/components/ui/input"; import { TooltipHint } from "@/components/ui/tooltip"; -import { useAction } from "convex/react"; +import { useAction, useMutation } from "convex/react"; import { api } from "@/convex/_generated/api"; import type { Id } from "@/convex/_generated/dataModel"; import { useProtectedQuery } from "@/lib/auth/use-auth-query"; @@ -263,6 +263,8 @@ function NewOrganization({ close }: { close: () => void }) { const tc = useTranslations("common"); const router = useRouter(); const create = useWorkspaceAction(api.organizations.manage.create); + // The new organization is where the person now works: kept on the account, as a switch is (rail.tsx). + const rememberWorkspace = useMutation(api.workspaces.lastUsed.remember); // The invitations go out from the organization just made, not the workspace the page is in. const inviteThere = useAction(api.organizations.manage.invite); const { name: freePlan } = usePlanOf({ kind: "organization", name: "" }); @@ -309,6 +311,7 @@ function NewOrganization({ close }: { close: () => void }) { // It's made: trying again would make another. Invitations that fail are sent again from its Members settings. if (invited.length) await inviteThere({ workspaceId: made.workspaceId, emails: invited, role: "member" }).catch((error) => showStyledToast("error", getErrorMessage(error, t("couldntInvite")))); close(); + void rememberWorkspace({ slug: made.slug }).catch(() => undefined); router.push(workspaceHref(made.slug, "/library")); }; return ( diff --git a/proxy.ts b/proxy.ts index 5633ec302..5676cab41 100644 --- a/proxy.ts +++ b/proxy.ts @@ -116,9 +116,11 @@ async function lastWorkspaceStart(auth: ClerkMiddlewareAuth, request: NextReques } /** - * Tells the person's account which workspace their browser remembers them last working in, when the account hasn't + * Tells the person's account which organization their browser remembers them last working in, when the account hasn't * been told yet: a new browser then opens there (`lastWorkspaceStart`). Only on a page load, and only when the cookie's - * `last` differs from what it says it told (`saved`), so a person who stays in one workspace sends nothing more. The + * `last` differs from what it says it told (`saved`), so a person who stays in one workspace sends nothing more. Their + * own workspace is never told from here: a new browser shows it on its first page before it has asked, and would wipe + * the organization the account remembers. Moving back to it is told by the workspace switch itself (rail.tsx). The * cookie's new value, with `saved`, is returned for the response to set; null when nothing was sent. A failure is * logged and lets the page through: it is tried again on the next page. */ @@ -129,7 +131,7 @@ async function keepOnAccount(auth: ClerkMiddlewareAuth, request: NextRequest): P if (!userId || !cookieIsTheirs(raw, userId)) return null; const cache = readCache(raw, userId); const slug = unsaved(cache); - if (slug === undefined) return null; + if (!slug) return null; try { const token = await getToken({ template: "convex" }); if (!token) return null; From 5dbd12f70816f31b1fe315720aad7bf733df4770 Mon Sep 17 00:00:00 2001 From: sickerine Date: Sun, 6 Dec 2026 01:01:45 +0000 Subject: [PATCH 2/3] fix(workspaces): note a switch told to the account in the cookie Codex review: with the cookie saying the account was told A, a switch to B told the account but left the note at A; moving back to A another way (an item moved there) then looked already told, and the account kept B. A switch now notes what it told, through one hook the switcher and new organizations share (lib/workspaces/remember.ts). --- components/workspaces/rail.tsx | 7 ++++--- components/workspaces/switcher.tsx | 7 ++++--- lib/workspaces/look-cache.test.ts | 17 ++++++++++++++++- lib/workspaces/look-cache.ts | 2 ++ lib/workspaces/remember.ts | 23 +++++++++++++++++++++++ 5 files changed, 49 insertions(+), 7 deletions(-) create mode 100644 lib/workspaces/remember.ts diff --git a/components/workspaces/rail.tsx b/components/workspaces/rail.tsx index 562f1562b..d168488fe 100644 --- a/components/workspaces/rail.tsx +++ b/components/workspaces/rail.tsx @@ -10,7 +10,8 @@ import React, { useCallback, useEffect, useRef, useState, useTransition } from " import { SCREENINGS_PATH } from "@/lib/screening/links"; import { usePathname, useRouter, useSearchParams } from "next/navigation"; import { useAuth, useClerk, useUser } from "@clerk/nextjs"; -import { useMutation, useQuery } from "convex/react"; +import { useQuery } from "convex/react"; +import { useRememberWorkspace } from "@/lib/workspaces/remember"; import { showStyledToast } from "@/components/ui/sonner"; import { useTheme } from "next-themes"; import { useFormatter, useTranslations } from "next-intl"; @@ -143,7 +144,7 @@ export function SidebarContent({ firstWorkspace, onClose }: { firstWorkspace: Fi const router = useRouter(); // A switch is kept on the account as it is made, so another browser opens there too (convex/workspaces/lastUsed.ts): // a switch changes the page without loading it, which the proxy would only hear of on the next page load. - const rememberWorkspace = useMutation(api.workspaces.lastUsed.remember); + const rememberWorkspace = useRememberWorkspace(); const [picked, setPicked] = useState(null); const [switching, startSwitch] = useTransition(); const loading = picked !== null && slug === (picked.slug ?? null) && loaded?.workspaceId !== picked.workspaceId; @@ -359,7 +360,7 @@ export function SidebarContent({ firstWorkspace, onClose }: { firstWorkspace: Fi onSwitch={(slug, to) => { close(); if (to) setPicked(to); - void rememberWorkspace({ slug: slug ?? null }).catch(() => undefined); + rememberWorkspace(slug ?? null); startSwitch(() => router.push(switchTarget(slug, window.location.pathname, window.location.search.slice(1)))); }} onCreate={() => { diff --git a/components/workspaces/switcher.tsx b/components/workspaces/switcher.tsx index b983e650b..4b1ca026e 100644 --- a/components/workspaces/switcher.tsx +++ b/components/workspaces/switcher.tsx @@ -16,7 +16,8 @@ import { IdentityAvatar } from "@/components/ui/identity-avatar"; import { RoleLabel } from "@/components/ui/identity"; import { Input } from "@/components/ui/input"; import { TooltipHint } from "@/components/ui/tooltip"; -import { useAction, useMutation } from "convex/react"; +import { useAction } from "convex/react"; +import { useRememberWorkspace } from "@/lib/workspaces/remember"; import { api } from "@/convex/_generated/api"; import type { Id } from "@/convex/_generated/dataModel"; import { useProtectedQuery } from "@/lib/auth/use-auth-query"; @@ -264,7 +265,7 @@ function NewOrganization({ close }: { close: () => void }) { const router = useRouter(); const create = useWorkspaceAction(api.organizations.manage.create); // The new organization is where the person now works: kept on the account, as a switch is (rail.tsx). - const rememberWorkspace = useMutation(api.workspaces.lastUsed.remember); + const rememberWorkspace = useRememberWorkspace(); // The invitations go out from the organization just made, not the workspace the page is in. const inviteThere = useAction(api.organizations.manage.invite); const { name: freePlan } = usePlanOf({ kind: "organization", name: "" }); @@ -311,7 +312,7 @@ function NewOrganization({ close }: { close: () => void }) { // It's made: trying again would make another. Invitations that fail are sent again from its Members settings. if (invited.length) await inviteThere({ workspaceId: made.workspaceId, emails: invited, role: "member" }).catch((error) => showStyledToast("error", getErrorMessage(error, t("couldntInvite")))); close(); - void rememberWorkspace({ slug: made.slug }).catch(() => undefined); + rememberWorkspace(made.slug); router.push(workspaceHref(made.slug, "/library")); }; return ( diff --git a/lib/workspaces/look-cache.test.ts b/lib/workspaces/look-cache.test.ts index 2df2a19ea..ad6ca00f3 100644 --- a/lib/workspaces/look-cache.test.ts +++ b/lib/workspaces/look-cache.test.ts @@ -1,7 +1,7 @@ // The rail's cookie (#651): it's the person's to change, sent with every request, and shared by // whoever signs in on the browser. import { describe, expect, it } from "vitest"; -import { lookCookieIn, lookKey, readCache, savedValue, unsaved, usedLast, writeCache, type CachedLook } from "./look-cache"; +import { lookCookieIn, lookKey, readCache, savedValue, toldValue, unsaved, usedLast, writeCache, type CachedLook } from "./look-cache"; const lab = (n: number): CachedLook => ({ kind: "organization", workspaceId: `w${n}`, name: `Lab ${n}`, colour: "#16a34a", extract: true }); const own: CachedLook = { kind: "personal", workspaceId: "w0", name: "Ada" }; @@ -78,3 +78,18 @@ describe("telling the account where the person last worked", () => { expect(unsaved(readCache(raw, user))).toBeUndefined(); }); }); + +describe("a switch told to the account as it is made", () => { + it("is noted, so moving back without the switcher is told again", () => { + const user = "user_ada"; + let raw = writeCache(usedLast(readCache(undefined, user), "lab"), user, "lab", undefined, undefined)!; + raw = savedValue(readCache(raw, user), user)!; + // The switcher tells the account of the board and notes it; the page then remembers the board. + raw = toldValue(readCache(raw, user), user, "board")!; + raw = writeCache(usedLast(readCache(raw, user), "board"), user, "board", undefined, undefined)!; + expect(unsaved(readCache(raw, user))).toBeUndefined(); + // Back in the lab by another way (an item moved there): the proxy tells the account again. + raw = writeCache(usedLast(readCache(raw, user), "lab"), user, "lab", undefined, undefined)!; + expect(unsaved(readCache(raw, user))).toBe("lab"); + }); +}); diff --git a/lib/workspaces/look-cache.ts b/lib/workspaces/look-cache.ts index 52a1d4907..1a3995816 100644 --- a/lib/workspaces/look-cache.ts +++ b/lib/workspaces/look-cache.ts @@ -106,6 +106,8 @@ export const unsaved = (cache: LookCache): string | null | undefined => ((cache. /** The cookie's value once the account has been told what `cache` remembers (`unsaved`). */ export const savedValue = (cache: LookCache, user: string) => writeCache({ ...cache, saved: cache.last ?? OWN }, user, OWN, undefined, undefined); +/** The cookie's value once the account has been told `slug` (null for the person's own workspace) by a switch, whatever the cookie remembers. */ +export const toldValue = (cache: LookCache, user: string, slug: string | null) => writeCache({ ...cache, saved: slug ?? OWN }, user, OWN, undefined, undefined); /** `cache` with the workspace under `key` as the one used last. */ export function usedLast(cache: LookCache, key: string): LookCache { diff --git a/lib/workspaces/remember.ts b/lib/workspaces/remember.ts new file mode 100644 index 000000000..3dd5372ea --- /dev/null +++ b/lib/workspaces/remember.ts @@ -0,0 +1,23 @@ +"use client"; + +// A workspace switch, told to the person's account as it is made (convex/workspaces/lastUsed.ts), so another browser +// opens there too. The cookie then notes what the account was told (`saved`), which the proxy reads to tell it again +// only when the browser moves on without a switch (proxy.ts `keepOnAccount`). +import { useAuth } from "@clerk/nextjs"; +import { useMutation } from "convex/react"; +import { api } from "@/convex/_generated/api"; +import { lookCookieIn, lookCookieOut, readCache, toldValue } from "./look-cache"; + +/** Tells the account the person now works in `slug`'s organization, or their own workspace for null. A failure is the proxy's to make up for on a later page load. */ +export function useRememberWorkspace() { + const { userId } = useAuth(); + const remember = useMutation(api.workspaces.lastUsed.remember); + return (slug: string | null) => + void remember({ slug }) + .then(() => { + if (!userId) return; + const next = toldValue(readCache(lookCookieIn(document.cookie), userId), userId, slug); + if (next) document.cookie = lookCookieOut(next); + }) + .catch(() => undefined); +} From 8e2eeb8ae1f360dcb436079c2f5484c1975b035d Mon Sep 17 00:00:00 2001 From: sickerine Date: Sun, 6 Dec 2026 01:11:52 +0000 Subject: [PATCH 3/3] test(workspaces): the sidebar's stand-in API has the account's last workspace The sidebar now tells the account of a switch (lib/workspaces/remember.ts); its test's stand-in for the generated API lacked that function. --- tests/components/app-sidebar.test.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/components/app-sidebar.test.tsx b/tests/components/app-sidebar.test.tsx index 2893df926..885e1315a 100644 --- a/tests/components/app-sidebar.test.tsx +++ b/tests/components/app-sidebar.test.tsx @@ -34,7 +34,7 @@ vi.mock("@/convex/_generated/api", () => ({ screening: { view: { rail: "screening:rail" } }, extraction: { queries: { jobs: { runningJob: "extraction:runningJob" } } }, organizations: { queries: { workspaces: "organizations:workspaces", myInvitations: "organizations:myInvitations" }, manage: { create: "create", invite: "invite", declineInvitation: "decline", confirmJoin: "confirmJoin" } }, - workspaces: { queries: { personal: "workspaces:personal", bySlug: "workspaces:bySlug" } }, + workspaces: { queries: { personal: "workspaces:personal", bySlug: "workspaces:bySlug" }, lastUsed: { remember: "workspaces:lastUsed:remember" } }, sharing: { shared: { counts: "sharing:counts" }, invitations: { waiting: "sharing:invitationsWaiting" } }, reports: { settings: { open: "reports:open" }, flow: { counts: "reports:counts", waitingElsewhere: "reports:waitingElsewhere" } }, },