diff --git a/components/workspaces/rail.tsx b/components/workspaces/rail.tsx index 77ca079e3..d168488fe 100644 --- a/components/workspaces/rail.tsx +++ b/components/workspaces/rail.tsx @@ -11,6 +11,7 @@ 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 { useRememberWorkspace } from "@/lib/workspaces/remember"; import { showStyledToast } from "@/components/ui/sonner"; import { useTheme } from "next-themes"; import { useFormatter, useTranslations } from "next-intl"; @@ -141,6 +142,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 = useRememberWorkspace(); const [picked, setPicked] = useState(null); const [switching, startSwitch] = useTransition(); const loading = picked !== null && slug === (picked.slug ?? null) && loaded?.workspaceId !== picked.workspaceId; @@ -356,6 +360,7 @@ export function SidebarContent({ firstWorkspace, onClose }: { firstWorkspace: Fi onSwitch={(slug, to) => { close(); if (to) setPicked(to); + 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 0c8bd3ee3..4b1ca026e 100644 --- a/components/workspaces/switcher.tsx +++ b/components/workspaces/switcher.tsx @@ -17,6 +17,7 @@ import { RoleLabel } from "@/components/ui/identity"; import { Input } from "@/components/ui/input"; import { TooltipHint } from "@/components/ui/tooltip"; 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"; @@ -263,6 +264,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 = 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: "" }); @@ -309,6 +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(); + 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); +} 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; 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" } }, },