From 7c7a74db9f85459a862384f2b4c71284a557c8d8 Mon Sep 17 00:00:00 2001 From: sickerine Date: Tue, 1 Dec 2026 18:15:48 +0000 Subject: [PATCH 1/3] feat(workspaces): an address that names no workspace opens in the one used last --- app/layout.tsx | 12 +++++--- app/sign-in/[[...sign-in]]/page.tsx | 26 ++++++++--------- components/workspaces/item-home.tsx | 22 +++++++++++++-- components/workspaces/rail.tsx | 3 +- convex/workspaces/queries.ts | 6 ++-- lib/workspaces/href.ts | 13 +++++++-- lib/workspaces/look-cache.test.ts | 17 ++++++++++-- lib/workspaces/look-cache.ts | 30 ++++++++++++++++---- lib/workspaces/paths.test.ts | 31 ++++++++++++++++++++- lib/workspaces/paths.ts | 43 ++++++++++++++++++++++++++--- proxy.ts | 32 +++++++++++++++++++-- 11 files changed, 193 insertions(+), 42 deletions(-) diff --git a/app/layout.tsx b/app/layout.tsx index c8af27c66..56273ba51 100644 --- a/app/layout.tsx +++ b/app/layout.tsx @@ -31,9 +31,9 @@ import { PostHogIdentify } from "@/components/posthog-identify"; import { ResearchStateProvider } from "@/lib/research/provider"; import { SETUP_HEADER } from "@/lib/profile/setup"; import { LOOK_COOKIE, lookKey, readCache, WORKSPACE_HEADER } from "@/lib/workspaces/look-cache"; -import { ADDRESS_HEADER } from "@/lib/workspaces/paths"; +import { ADDRESS_HEADER, addressWorkspace } from "@/lib/workspaces/paths"; import { AssistantPanel } from "@/components/assistant/panel"; -import { ItemHome, WorkspaceGone } from "@/components/workspaces/item-home"; +import { ItemHome, TabWorkspace, WorkspaceGone } from "@/components/workspaces/item-home"; import { WorkspacesProvider } from "@/components/workspaces/parts"; import { QueryHighlightProvider } from "@/components/query-highlight"; import { QUERY_HIGHLIGHT_COOKIE } from "@/lib/search/boolean-query"; @@ -81,8 +81,10 @@ export default async function RootLayout({ cookies(), ]); // The rail as this browser last saw it, drawn from the first frame: the person and the address's workspace. None signed out. - const slug = requestHeaders.get(WORKSPACE_HEADER) || null; - const { me, looks } = readCache(requestCookies.get(LOOK_COOKIE)?.value, userId); + const { me, looks, last } = readCache(requestCookies.get(LOOK_COOKIE)?.value, userId); + // A page in no workspace, such as a paper's, is drawn in the organization the rail drew last (`TabWorkspace`). + const kept = addressWorkspace(requestHeaders.get(ADDRESS_HEADER)?.split("?")[0] ?? "/") === undefined ? (last ?? null) : null; + const slug = requestHeaders.get(WORKSPACE_HEADER) || kept; const look = looks[lookKey(slug)]; // Whether this page is a new account's profile setup instead, as the proxy decided before anything was rendered. const setupFirst = !!userId && requestHeaders.get(SETUP_HEADER) === "due"; @@ -113,6 +115,7 @@ export default async function RootLayout({ app's own providers, analytics or research state. */} {signingOut ? children : ( + @@ -145,6 +148,7 @@ export default async function RootLayout({ + )} diff --git a/app/sign-in/[[...sign-in]]/page.tsx b/app/sign-in/[[...sign-in]]/page.tsx index 0d474d51b..5bc5f8f26 100644 --- a/app/sign-in/[[...sign-in]]/page.tsx +++ b/app/sign-in/[[...sign-in]]/page.tsx @@ -1,23 +1,21 @@ -"use client"; - -import { useSearchParams } from "next/navigation"; +import { cookies } from "next/headers"; import { SignIn } from "@clerk/nextjs"; +import { lastOrganization, LOOK_COOKIE } from "@/lib/workspaces/look-cache"; +import { startIn } from "@/lib/workspaces/paths"; -export default function SignInPage() { - const searchParams = useSearchParams(); - const rawRedirect = searchParams.get("redirect_url"); +export default async function SignInPage({ searchParams }: { searchParams: Promise<{ redirect_url?: string | string[] }> }) { + const rawRedirect = (await searchParams).redirect_url; // Prevent open redirect — only allow relative paths within the same origin - const redirectUrl = - rawRedirect && rawRedirect.startsWith("/") && !rawRedirect.startsWith("//") - ? rawRedirect - : "/"; + const redirectUrl = typeof rawRedirect === "string" && rawRedirect.startsWith("/") && !rawRedirect.startsWith("//") ? rawRedirect : "/"; + // Signing in is arriving from outside: the home page, a search or a new report opens in the organization this + // browser used last, as the proxy does for a page loaded while signed in (proxy.ts `lastWorkspaceStart`). + const last = lastOrganization((await cookies()).get(LOOK_COOKIE)?.value); + const asked = new URL(redirectUrl, "http://address"); + const start = last ? startIn(last, asked.pathname, asked.searchParams) : null; return (
- +
); } diff --git a/components/workspaces/item-home.tsx b/components/workspaces/item-home.tsx index 8a6047b62..85266635c 100644 --- a/components/workspaces/item-home.tsx +++ b/components/workspaces/item-home.tsx @@ -1,10 +1,11 @@ "use client"; +import { useState, type ReactNode } from "react"; import { redirect, usePathname, useSearchParams } from "next/navigation"; import { api } from "@/convex/_generated/api"; import { useProtectedQuery } from "@/lib/auth/use-auth-query"; -import { useWorkspaceSlug, workspaceHref } from "@/lib/workspaces/href"; -import { bareWorkspacePath, outsiderTarget, pageItem } from "@/lib/workspaces/paths"; +import { KeptWorkspace, useWorkspaceSlug, workspaceHref } from "@/lib/workspaces/href"; +import { addressWorkspace, bareWorkspacePath, outsiderTarget, pageItem } from "@/lib/workspaces/paths"; import { useWorkspace } from "@/lib/workspaces/url"; type Item = NonNullable>; @@ -36,6 +37,20 @@ export function ItemHome() { return null; } +/** + * Keeps a tab in its workspace on a page that is in none, such as a paper's: the organization its address last + * named, or for a tab that opened on such a page, the one this browser's rail drew last (`first`, read from the + * rail's cookie as the page was drawn). An organization the person is no longer in gives way to their own workspace. + */ +export function TabWorkspace({ first, children }: { first: string | null; children: ReactNode }) { + const named = addressWorkspace(usePathname()); + const [last, setLast] = useState(named === undefined ? first : named); + if (named !== undefined && named !== last) setLast(named); + const kept = named === undefined ? last : null; + const member = useProtectedQuery(api.workspaces.queries.memberAt, kept ? { slug: kept } : "skip").data; + return {children}; +} + /** * Leaves an organization's page once the person can't act in it any more: they were removed, * they left in another tab, or it was deleted. They go to the same page in their own workspace, item and all, @@ -48,6 +63,7 @@ export function WorkspaceGone() { const params = useSearchParams(); // False once the server says they aren't in it; undefined while it's still being read. One being deleted is still theirs: the deletion may fail. const member = useProtectedQuery(api.workspaces.queries.memberAt, slug ? { slug } : "skip").data; - if (slug && member === false) redirect(outsiderTarget(pathname, params.size ? `?${params.toString()}` : "")); + // Only from an address that names the organization: a page in no workspace stays, in their own (`TabWorkspace`). + if (slug && member === false && addressWorkspace(pathname) === slug) redirect(outsiderTarget(pathname, params.size ? `?${params.toString()}` : "")); return null; } diff --git a/components/workspaces/rail.tsx b/components/workspaces/rail.tsx index d5efde1a5..3d9a71df8 100644 --- a/components/workspaces/rail.tsx +++ b/components/workspaces/rail.tsx @@ -197,7 +197,8 @@ export function SidebarContent({ firstWorkspace, onClose }: { firstWorkspace: Fi if (!look && !live) return; const next = writeCache(cache, userId, lookKey(slug), look, live); if (next && next !== raw) document.cookie = `${LOOK_COOKIE}=${next}; Path=/; Max-Age=${LOOK_KEPT_S}; SameSite=Lax`; - }, [userId, slug, loaded, live?.name, live?.imageUrl, liveExtracts, liveAuthors, livePublishes]); + // On every page it draws: the cookie also says which workspace was used last, and another tab may have said otherwise since. + }, [userId, slug, pathname, loaded, live?.name, live?.imageUrl, liveExtracts, liveAuthors, livePublishes]); const { currentQuery } = useCurrentQueryStore(); const { keywords } = useKeywordExpansionStore(); diff --git a/convex/workspaces/queries.ts b/convex/workspaces/queries.ts index d73aba1a4..42f9ac6b5 100644 --- a/convex/workspaces/queries.ts +++ b/convex/workspaces/queries.ts @@ -51,7 +51,7 @@ export const memberAt = query({ }, }); -const itemKind = v.union(v.literal("search"), v.literal("screening"), v.literal("extraction"), v.literal("collection"), v.literal("library"), v.literal("profile")); +const itemKind = v.union(v.literal("search"), v.literal("screening"), v.literal("extraction"), v.literal("collection"), v.literal("library"), v.literal("profile"), v.literal("report")); /** The workspaces a person acts in: their own, then their organizations'. */ async function workspacesOf(ctx: QueryCtx, user: Doc<"users">) { @@ -76,7 +76,9 @@ async function searchAt(ctx: QueryCtx, user: Doc<"users">, id: string, here: Id< } /** The workspace an item a page's address names is in, or null when there's none such. */ -async function itemWorkspace(ctx: QueryCtx, kind: "screening" | "extraction" | "collection" | "library" | "profile", id: string): Promise | null> { +async function itemWorkspace(ctx: QueryCtx, kind: "screening" | "extraction" | "collection" | "library" | "profile" | "report", id: string): Promise | null> { + // A report being published goes by its key, which its address carries (/publish?report=R…). + if (kind === "report") return (await ctx.db.query("reports").withIndex("by_key", (q) => q.eq("key", id)).unique())?.workspaceId ?? null; const table = ({ screening: "screeningJobs", extraction: "extractionJobs", collection: "collections", library: "evidenceLibraries", profile: "authorProfiles" } as const)[kind]; const docId = ctx.db.normalizeId(table, id); const item = docId ? await ctx.db.get(docId) : null; diff --git a/lib/workspaces/href.ts b/lib/workspaces/href.ts index 943e1c6d2..74f5abe46 100644 --- a/lib/workspaces/href.ts +++ b/lib/workspaces/href.ts @@ -4,7 +4,7 @@ // takes the organization's prefix, /o/, when the page is one of its. No Convex here, so any // component can link. -import { useCallback, useMemo } from "react"; +import { createContext, use, useCallback, useMemo } from "react"; import { useParams, useRouter } from "next/navigation"; import { workspaceHref } from "./paths"; @@ -12,10 +12,17 @@ import { workspaceHref } from "./paths"; // The rule itself is in ./paths, with the others; components link through here. export { workspaceHref }; -/** The organization a page's address names, or undefined in the person's own workspace. */ +/** The organization a tab stays in on a page that is in no workspace (components/workspaces/item-home.tsx `TabWorkspace`); none on any other page. */ +export const KeptWorkspace = createContext(undefined); + +/** + * The organization a page is in: the one its address names, or on a page that is in no workspace, the one its tab + * was in. Undefined in the person's own workspace. + */ export function useWorkspaceSlug(): string | undefined { const params = useParams(); - return typeof params?.slug === "string" ? params.slug : undefined; + const kept = use(KeptWorkspace); + return typeof params?.slug === "string" ? params.slug : kept; } /** `workspaceHref` for the workspace the page is in. */ diff --git a/lib/workspaces/look-cache.test.ts b/lib/workspaces/look-cache.test.ts index 546323f4b..cce669b1a 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, readCache, writeCache, type CachedLook } from "./look-cache"; +import { lastOrganization, lookCookieIn, readCache, 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" }; @@ -10,12 +10,25 @@ const ada = { name: "Ada", imageUrl: "https://img.clerk.com/ada" }; describe("the rail's cookie", () => { it("reads back what it keeps, for the account it was kept for only", () => { const cookie = writeCache({ looks: {} }, "user_ada", "lab-1", lab(1), ada)!; - expect(readCache(cookie, "user_ada")).toEqual({ me: ada, looks: { "lab-1": lab(1) } }); + expect(readCache(cookie, "user_ada")).toEqual({ me: ada, looks: { "lab-1": lab(1) }, last: "lab-1" }); expect(readCache(cookie, "user_bob")).toEqual({ looks: {} }); expect(readCache(cookie, null)).toEqual({ looks: {} }); expect(readCache(lookCookieIn(`theme=dark; workspace-looks=${cookie}; other=1`), "user_ada").looks).toEqual({ "lab-1": lab(1) }); }); + it("says which organization the rail drew last, and none once it drew the person's own workspace", () => { + const inLab = writeCache({ looks: {} }, "user_ada", "lab-1", lab(1), ada)!; + expect(readCache(inLab, "user_ada").last).toBe("lab-1"); + expect(readCache(inLab, "user_bob").last).toBeUndefined(); + // The sign-in page reads it before anyone is signed in. + expect(lastOrganization(inLab)).toBe("lab-1"); + const atHome = writeCache(readCache(inLab, "user_ada"), "user_ada", "~", own, undefined)!; + expect(readCache(atHome, "user_ada").last).toBeUndefined(); + expect(lastOrganization(atHome)).toBeUndefined(); + expect(lastOrganization("not json")).toBeUndefined(); + expect(lastOrganization(undefined)).toBeUndefined(); + }); + it("drops a colour, photo or section that isn't one, and anything that isn't a look", () => { const raw = JSON.stringify({ user: "user_ada", diff --git a/lib/workspaces/look-cache.ts b/lib/workspaces/look-cache.ts index 7eceb896a..fa21f6239 100644 --- a/lib/workspaces/look-cache.ts +++ b/lib/workspaces/look-cache.ts @@ -2,6 +2,8 @@ // photo, and each workspace's name, colour, logo and the sections it opens, so the server draws // the rail as it was from the page's first frame, before Clerk or the workspace load. The rail writes it whenever it reads them. It names the account it's for, so someone // else signing in on the same browser doesn't see it. +// It also keeps the organization the rail drew last (`last`): an address that names no workspace opens in that one +// (lib/workspaces/paths.ts `startIn`, `addressWorkspace`). /** The cookie the rail's looks are kept in. */ export const LOOK_COOKIE = "workspace-looks"; @@ -13,7 +15,8 @@ export const WORKSPACE_HEADER = "x-workspace-slug"; export type CachedLook = { kind: "personal" | "organization"; workspaceId: string; name: string; imageUrl?: string; colour?: string; extract?: true; author?: true; publish?: true }; /** The signed-in person, as the rail's account button shows them. */ export type CachedMe = { name: string; imageUrl?: string }; -export type LookCache = { me?: CachedMe; looks: Record }; +/** `last`: the organization the rail drew last, none when that was the person's own workspace. */ +export type LookCache = { me?: CachedMe; looks: Record; last?: string }; /** What the server knew when it drew the page: the address's workspace, who's signed in, and how the rail looked last time. */ export type FirstWorkspace = { slug: string | null; user?: string; me?: CachedMe; look?: CachedLook }; @@ -37,7 +40,7 @@ const photo = (value: unknown) => (typeof value === "string" && value.startsWith export function readCache(raw: string | undefined, user: string | null | undefined): LookCache { if (!raw || !user) return { looks: {} }; try { - const parsed = JSON.parse(raw.startsWith("%") ? decodeURIComponent(raw) : raw) as { user?: unknown; me?: Partial; looks?: unknown } | null; + const parsed = JSON.parse(raw.startsWith("%") ? decodeURIComponent(raw) : raw) as { user?: unknown; me?: Partial; looks?: unknown; last?: unknown } | null; if (parsed?.user !== user) return { looks: {} }; const looks: Record = {}; for (const [key, value] of Object.entries((parsed.looks ?? {}) as Record>)) { @@ -54,15 +57,30 @@ export function readCache(raw: string | undefined, user: string | null | undefin }; } const me = typeof parsed.me?.name === "string" ? { name: parsed.me.name, ...photo(parsed.me.imageUrl) } : undefined; - return { ...(me ? { me } : {}), looks }; + const last = lastIn(parsed); + return { ...(me ? { me } : {}), looks, ...(last ? { last } : {}) }; } catch { return { looks: {} }; } } +const lastIn = (parsed: { last?: unknown } | null) => (typeof parsed?.last === "string" && parsed.last && parsed.last !== OWN ? parsed.last : undefined); + +/** + * The organization this browser's rail drew last, whoever it was for: what the sign-in page goes by, before anyone + * is signed in. Someone else signing in is sent on from it to their own workspace (app/o/[slug]/layout.tsx). + */ +export function lastOrganization(raw: string | undefined) { + try { + return raw ? lastIn(JSON.parse(raw.startsWith("%") ? decodeURIComponent(raw) : raw) as { last?: unknown } | null) : undefined; + } catch { + return undefined; + } +} + /** - * The cookie's value for `user`, with `me` and the look kept under `key` newest, and the oldest - * organizations dropped, past KEPT or until it fits. Null when even that doesn't fit. + * The cookie's value for `user`, with `me` and the look kept under `key` newest, `key` as the workspace drawn last, + * and the oldest organizations dropped, past KEPT or until it fits. Null when even that doesn't fit. */ export function writeCache(cache: LookCache, user: string, key: string, look: CachedLook | undefined, me: CachedMe | undefined) { const { [key]: was, ...rest } = cache.looks; @@ -70,7 +88,7 @@ export function writeCache(cache: LookCache, user: string, key: string, look: Ca const keptMe = me ?? cache.me; const oldest = Object.keys(rest).filter((other) => other !== OWN); for (const old of oldest.splice(0, Math.max(0, oldest.length - (KEPT - 1)))) delete rest[old]; - const encode = () => encodeURIComponent(JSON.stringify({ user, ...(keptMe ? { me: keptMe } : {}), looks: { ...rest, ...(kept ? { [key]: kept } : {}) } })); + const encode = () => encodeURIComponent(JSON.stringify({ user, ...(keptMe ? { me: keptMe } : {}), looks: { ...rest, ...(kept ? { [key]: kept } : {}) }, ...(key === OWN ? {} : { last: key }) })); let value = encode(); while (value.length > MAX_VALUE && oldest.length) { delete rest[oldest.shift()!]; diff --git a/lib/workspaces/paths.test.ts b/lib/workspaces/paths.test.ts index a3ad8dfdf..7c1583a7c 100644 --- a/lib/workspaces/paths.test.ts +++ b/lib/workspaces/paths.test.ts @@ -4,7 +4,7 @@ import { existsSync, readdirSync } from "node:fs"; import path from "node:path"; import { expect, it } from "vitest"; -import { bareWorkspacePath, outsiderTarget, SECTIONS, switchTarget } from "./paths"; +import { addressWorkspace, bareWorkspacePath, outsiderTarget, SECTIONS, startIn, switchTarget } from "./paths"; const APP = path.resolve(__dirname, "../../app"); const ORGANIZATION = path.join(APP, "o/[slug]"); @@ -78,6 +78,35 @@ it("keeps the page where the workspace picked has it, opens the section where th expect(switchTarget(undefined, "/o/lab/settings/workspace/members", "")).toBe("/settings"); }); +it("starts the home page, a search and a new report in the organization used last, and leaves every other address where it is", () => { + const start = (address: string) => { + const url = new URL(address, "http://address"); + return startIn("lab", url.pathname, url.searchParams); + }; + expect(start("/")).toBe("/o/lab"); + expect(start("/results?q=tvet")).toBe("/o/lab/results"); + expect(start("/publish?code=EVENT")).toBe("/o/lab/publish"); + // A report under way is an item, opened where it is. + expect(start("/publish?report=R100001")).toBeNull(); + expect(start("/results/abc")).toBeNull(); + // A person's own pages go by their bare address in the site's emails and payment pages. + expect(start("/library")).toBeNull(); + expect(start("/settings/billing?checkout=done")).toBeNull(); + expect(start("/papers/W1")).toBeNull(); + expect(start("/o/club")).toBeNull(); +}); + +it("names the workspace of every address, and none for a page that is the same in each", () => { + expect(addressWorkspace("/o/lab/library")).toBe("lab"); + expect(addressWorkspace("/library")).toBeNull(); + expect(addressWorkspace("/shared")).toBeNull(); + expect(addressWorkspace("/papers/W1/a-title")).toBeUndefined(); + expect(addressWorkspace("/privacy")).toBeUndefined(); + // Such a page stays in the organization its tab was in: from it, a switch to the person's own workspace goes to their home page. + expect(switchTarget(undefined, "/papers/W1", "")).toBe("/"); + expect(switchTarget("lab", "/papers/W1", "")).toBe("/o/lab"); +}); + it("sends someone outside an organization to the same page and item in their own workspace, and its own settings to theirs (#653)", () => { expect(outsiderTarget("/o/lab/library", "?chat=abc")).toBe("/library?chat=abc"); expect(outsiderTarget("/o/lab/results/abc", "")).toBe("/results/abc"); diff --git a/lib/workspaces/paths.ts b/lib/workspaces/paths.ts index 19d3dc627..3638e94a0 100644 --- a/lib/workspaces/paths.ts +++ b/lib/workspaces/paths.ts @@ -19,6 +19,23 @@ const within = (path: string, section: string) => path === section || path.start /** An organization's own settings, which a person's own workspace has no page for. */ const ORGANIZATION_ONLY = "/settings/workspace"; +/** + * Pages that are in no workspace, the same whichever one the person works in: a paper's page and the policy pages. + * A tab that opens one stays in the workspace it was in (`addressWorkspace`). + */ +const NO_WORKSPACE = ["/papers", "/privacy", "/terms", "/cookie-policy", "/credits"]; + +/** + * The workspace a page's address names: an organization's slug under /o/, null for a person's own, and + * undefined for a page that is in none. The site's own links, emails and payment pages name a person's own pages by + * their bare address, so every bare address but those is theirs. + */ +export function addressWorkspace(pathname: string): string | null | undefined { + const slug = /^\/o\/([^/]+)/.exec(pathname)?.[1]; + if (slug) return slug; + return NO_WORKSPACE.some((page) => within(pathname, page)) ? undefined : null; +} + /** `path` in the workspace of `slug`: a workspace section's path, or the home page, under /o/; any other path as it is. */ export function workspaceHref(slug: string | undefined, path: string) { if (!slug || !path.startsWith("/") || path.startsWith(`/o/`)) return path; @@ -27,9 +44,9 @@ export function workspaceHref(slug: string | undefined, path: string) { return SECTIONS.some((section) => within(bare, section)) ? `/o/${slug}${path}` : path; } -type Item = { kind: "search" | "screening" | "extraction" | "collection" | "library" | "profile"; id: string }; +type Item = { kind: "search" | "screening" | "extraction" | "collection" | "library" | "profile" | "report"; id: string }; -/** The item a page shows, by its address: a search's results, a screening, an extraction, a collection, an Evidence Library or an author profile. */ +/** The item a page shows, by its address: a search's results, a screening, an extraction, a collection, an Evidence Library, an author profile or a report being published. */ export function pageItem(path: string, params: URLSearchParams): Item | null { const [, section, id, page] = path.split("/"); if (section === "results" && id) return { kind: "search", id: decodeURIComponent(id) }; @@ -41,11 +58,26 @@ export function pageItem(path: string, params: URLSearchParams): Item | null { const job = path === "/screening" ? params.get("job") : null; if (job && job !== "new") return { kind: "screening", id: job }; const collection = path === "/library" ? params.get("col") : null; - return collection ? { kind: "collection", id: collection } : null; + if (collection) return { kind: "collection", id: collection }; + const report = path === "/publish" ? params.get("report") : null; + return report ? { kind: "report", id: report } : null; +} + +/** The addresses that start something new: the home page, a search and a report. */ +const STARTS = ["/", "/results", "/publish"]; + +/** + * Where an address opens for someone who arrives at it from outside the site, and whose last workspace here was the + * organization `slug`: the home page, a search not yet run and a report not yet started open in that organization. + * Null for every other address: an organization's names it, an item opens where it is (`pageItem`, ItemHome), and a + * person's own pages go by their bare address (`addressWorkspace`). + */ +export function startIn(slug: string, pathname: string, params: URLSearchParams): string | null { + return STARTS.includes(pathname) && !pageItem(pathname, params) ? workspaceHref(slug, pathname) : null; } /** Where each kind of item's section starts. */ -const SECTION_OF: Record = { search: "/", screening: "/screening", extraction: "/extraction", collection: "/library", library: "/evidence-communities", profile: "/authors" }; +const SECTION_OF: Record = { search: "/", screening: "/screening", extraction: "/extraction", collection: "/library", library: "/evidence-communities", profile: "/authors", report: "/publish" }; /** * Where a switch to another workspace lands, which is always in that workspace, on a page it @@ -57,6 +89,8 @@ const SECTION_OF: Record = { search: "/", screening: "/scr * - the workspace's home when the page has no place there at all. Shared with me and the policy * pages are no organization's, and an organization's own settings aren't a person's: from * those a switch used to go nowhere, and left the rail in one workspace and the page in the other. + * A page in no workspace stays in the organization its tab was in, so from it a switch to the + * person's own workspace goes to their home page too. */ /** * Where an organization's address takes someone who isn't its member (#653): the same page, item @@ -71,6 +105,7 @@ export function outsiderTarget(pathname: string, search: string) { export function switchTarget(slug: string | undefined, pathname: string, search: string) { const path = bareWorkspacePath(pathname); if (!slug && within(path, ORGANIZATION_ONLY)) return "/settings"; + if (!slug && addressWorkspace(pathname) === undefined) return "/"; const item = pageItem(path, new URLSearchParams(search)); const target = workspaceHref(slug, item ? SECTION_OF[item.kind] : path); return slug && !within(target, `/o/${slug}`) ? `/o/${slug}` : target; diff --git a/proxy.ts b/proxy.ts index 664832a09..d7a873184 100644 --- a/proxy.ts +++ b/proxy.ts @@ -9,8 +9,8 @@ import { languageFromLink } from "@/i18n/link-language"; import { shouldProtectPath } from "@/lib/auth/proxy-policy"; import { isPublicFile } from "@/lib/auth/public-routes"; import { bareWorkLink } from "@/lib/search-params/bare-work-link"; -import { slugOf, WORKSPACE_HEADER } from "@/lib/workspaces/look-cache"; -import { ADDRESS_HEADER } from "@/lib/workspaces/paths"; +import { LOOK_COOKIE, readCache, slugOf, WORKSPACE_HEADER } from "@/lib/workspaces/look-cache"; +import { ADDRESS_HEADER, startIn } from "@/lib/workspaces/paths"; import { CITATION_FILES, type CitationFile } from "@/lib/citations/formats"; import { citeFilePath } from "@/lib/papers/page-address"; import { LINKED_CODE_COOKIE, LINKED_CODE_MAX_AGE, linkedCode } from "@/lib/reports/linked-code"; @@ -23,6 +23,9 @@ const authMiddleware = clerkMiddleware( if (shouldProtectPath(request.nextUrl.pathname)) { await auth.protect(); } + // Someone who arrives at the home page, a search or a new report starts in the organization they used last. + const start = await lastWorkspaceStart(auth, request); + if (start) return NextResponse.redirect(new URL(start, request.url)); // The workspace the address is in, for the root layout, which gets no route params: it draws // the rail as that workspace looked last time (lib/workspaces/look-cache.ts). const headers = new Headers(request.headers); @@ -70,6 +73,31 @@ async function profileSetup(auth: ClerkMiddlewareAuth, request: NextRequest): Pr } } +/** + * Where a page request goes instead, for someone who arrives from outside the site at an address that starts + * something new and names no workspace (lib/workspaces/paths.ts `startIn`): the same address in the organization this + * browser's rail drew last for them. Null for any other request. Only when the browser loads the page itself + * (`Sec-Fetch-Dest: document`): a link followed inside the site stays in the workspace its page is in, so a tab in a + * person's own workspace is never moved by what another tab did. An organization they are no longer in, or an + * answer that can't be had, lets the page through as it is: its layout would send them straight back here. + */ +async function lastWorkspaceStart(auth: ClerkMiddlewareAuth, request: NextRequest): Promise { + if (request.method !== "GET" || request.headers.get("sec-fetch-dest") !== "document") return null; + const raw = request.cookies.get(LOOK_COOKIE)?.value; + if (!raw) return null; + const { userId, getToken } = await auth(); + const last = readCache(raw, userId).last; + const target = last ? startIn(last, request.nextUrl.pathname, request.nextUrl.searchParams) : null; + if (!last || !target) return null; + try { + const token = await getToken({ template: "convex" }); + return token && (await fetchQuery(api.workspaces.queries.bySlug, { slug: last }, { token })) ? target + request.nextUrl.search : null; + } catch (error) { + console.error(JSON.stringify({ event: "last-workspace-start-failed", error: String(error).slice(0, 300) })); + return null; + } +} + function hasValidLocaleCookie(request: NextRequest): boolean { const raw = request.cookies.get(COOKIE_NAME)?.value; return !!raw && locales.includes(raw as (typeof locales)[number]); From 9e4efd1a77ec968e8a8b9c531e62cf6d667ca63f Mon Sep 17 00:00:00 2001 From: sickerine Date: Tue, 1 Dec 2026 18:30:53 +0000 Subject: [PATCH 2/3] fix(workspaces): the cross-family review: signing in lands by the account that signed in, and opening an item by the address's query counts as using its workspace --- app/sign-in/[[...sign-in]]/page.tsx | 26 ++++++++++++++------------ components/workspaces/rail.tsx | 6 ++++-- lib/workspaces/look-cache.test.ts | 8 ++------ lib/workspaces/look-cache.ts | 12 ------------ proxy.ts | 18 ++++++++++++++---- 5 files changed, 34 insertions(+), 36 deletions(-) diff --git a/app/sign-in/[[...sign-in]]/page.tsx b/app/sign-in/[[...sign-in]]/page.tsx index 5bc5f8f26..0d474d51b 100644 --- a/app/sign-in/[[...sign-in]]/page.tsx +++ b/app/sign-in/[[...sign-in]]/page.tsx @@ -1,21 +1,23 @@ -import { cookies } from "next/headers"; +"use client"; + +import { useSearchParams } from "next/navigation"; import { SignIn } from "@clerk/nextjs"; -import { lastOrganization, LOOK_COOKIE } from "@/lib/workspaces/look-cache"; -import { startIn } from "@/lib/workspaces/paths"; -export default async function SignInPage({ searchParams }: { searchParams: Promise<{ redirect_url?: string | string[] }> }) { - const rawRedirect = (await searchParams).redirect_url; +export default function SignInPage() { + const searchParams = useSearchParams(); + const rawRedirect = searchParams.get("redirect_url"); // Prevent open redirect — only allow relative paths within the same origin - const redirectUrl = typeof rawRedirect === "string" && rawRedirect.startsWith("/") && !rawRedirect.startsWith("//") ? rawRedirect : "/"; - // Signing in is arriving from outside: the home page, a search or a new report opens in the organization this - // browser used last, as the proxy does for a page loaded while signed in (proxy.ts `lastWorkspaceStart`). - const last = lastOrganization((await cookies()).get(LOOK_COOKIE)?.value); - const asked = new URL(redirectUrl, "http://address"); - const start = last ? startIn(last, asked.pathname, asked.searchParams) : null; + const redirectUrl = + rawRedirect && rawRedirect.startsWith("/") && !rawRedirect.startsWith("//") + ? rawRedirect + : "/"; return (
- +
); } diff --git a/components/workspaces/rail.tsx b/components/workspaces/rail.tsx index 3d9a71df8..a8ec87dde 100644 --- a/components/workspaces/rail.tsx +++ b/components/workspaces/rail.tsx @@ -128,6 +128,7 @@ export function SidebarContent({ firstWorkspace, onClose }: { firstWorkspace: Fi const pathname = usePathname(); const path = bareWorkspacePath(pathname); const searchParams = useSearchParams(); + const query = searchParams.toString(); const here = useWorkspace(); const loaded = useCurrentWorkspace(); // Invitations waiting for the person's answer: counted on Screening for screenings, and on Shared for every kind, so one is found without its email. @@ -197,8 +198,9 @@ export function SidebarContent({ firstWorkspace, onClose }: { firstWorkspace: Fi if (!look && !live) return; const next = writeCache(cache, userId, lookKey(slug), look, live); if (next && next !== raw) document.cookie = `${LOOK_COOKIE}=${next}; Path=/; Max-Age=${LOOK_KEPT_S}; SameSite=Lax`; - // On every page it draws: the cookie also says which workspace was used last, and another tab may have said otherwise since. - }, [userId, slug, pathname, loaded, live?.name, live?.imageUrl, liveExtracts, liveAuthors, livePublishes]); + // On every page it draws, an item opened by the address's query included: the cookie also says which workspace + // was used last, and another tab may have said otherwise since. + }, [userId, slug, pathname, query, loaded, live?.name, live?.imageUrl, liveExtracts, liveAuthors, livePublishes]); const { currentQuery } = useCurrentQueryStore(); const { keywords } = useKeywordExpansionStore(); diff --git a/lib/workspaces/look-cache.test.ts b/lib/workspaces/look-cache.test.ts index cce669b1a..c409b4563 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 { lastOrganization, lookCookieIn, readCache, writeCache, type CachedLook } from "./look-cache"; +import { lookCookieIn, readCache, 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" }; @@ -19,14 +19,10 @@ describe("the rail's cookie", () => { it("says which organization the rail drew last, and none once it drew the person's own workspace", () => { const inLab = writeCache({ looks: {} }, "user_ada", "lab-1", lab(1), ada)!; expect(readCache(inLab, "user_ada").last).toBe("lab-1"); + // Someone else signing in on the same browser starts in their own workspace. expect(readCache(inLab, "user_bob").last).toBeUndefined(); - // The sign-in page reads it before anyone is signed in. - expect(lastOrganization(inLab)).toBe("lab-1"); const atHome = writeCache(readCache(inLab, "user_ada"), "user_ada", "~", own, undefined)!; expect(readCache(atHome, "user_ada").last).toBeUndefined(); - expect(lastOrganization(atHome)).toBeUndefined(); - expect(lastOrganization("not json")).toBeUndefined(); - expect(lastOrganization(undefined)).toBeUndefined(); }); it("drops a colour, photo or section that isn't one, and anything that isn't a look", () => { diff --git a/lib/workspaces/look-cache.ts b/lib/workspaces/look-cache.ts index fa21f6239..9cc9d7446 100644 --- a/lib/workspaces/look-cache.ts +++ b/lib/workspaces/look-cache.ts @@ -66,18 +66,6 @@ export function readCache(raw: string | undefined, user: string | null | undefin const lastIn = (parsed: { last?: unknown } | null) => (typeof parsed?.last === "string" && parsed.last && parsed.last !== OWN ? parsed.last : undefined); -/** - * The organization this browser's rail drew last, whoever it was for: what the sign-in page goes by, before anyone - * is signed in. Someone else signing in is sent on from it to their own workspace (app/o/[slug]/layout.tsx). - */ -export function lastOrganization(raw: string | undefined) { - try { - return raw ? lastIn(JSON.parse(raw.startsWith("%") ? decodeURIComponent(raw) : raw) as { last?: unknown } | null) : undefined; - } catch { - return undefined; - } -} - /** * The cookie's value for `user`, with `me` and the look kept under `key` newest, `key` as the workspace drawn last, * and the oldest organizations dropped, past KEPT or until it fits. Null when even that doesn't fit. diff --git a/proxy.ts b/proxy.ts index d7a873184..f0a9b8f4f 100644 --- a/proxy.ts +++ b/proxy.ts @@ -73,16 +73,26 @@ async function profileSetup(auth: ClerkMiddlewareAuth, request: NextRequest): Pr } } +/** + * Whether a request was made from the sign-in page, which the browser says in its Referer. Only its path is read: + * behind the host's proxy this server doesn't know the site's own address to compare the rest with. + */ +function fromSignIn(request: NextRequest) { + const referer = request.headers.get("referer"); + return !!referer && URL.canParse(referer) && /^\/sign-in(\/|$)/.test(new URL(referer).pathname); +} + /** * Where a page request goes instead, for someone who arrives from outside the site at an address that starts * something new and names no workspace (lib/workspaces/paths.ts `startIn`): the same address in the organization this * browser's rail drew last for them. Null for any other request. Only when the browser loads the page itself - * (`Sec-Fetch-Dest: document`): a link followed inside the site stays in the workspace its page is in, so a tab in a - * person's own workspace is never moved by what another tab did. An organization they are no longer in, or an - * answer that can't be had, lets the page through as it is: its layout would send them straight back here. + * (`Sec-Fetch-Dest: document`) or comes from signing in: a link followed inside the site stays in the workspace its + * page is in, so a tab in a person's own workspace is never moved by what another tab did. An organization they are + * no longer in, or an answer that can't be had, lets the page through as it is: its layout would send them straight + * back here. */ async function lastWorkspaceStart(auth: ClerkMiddlewareAuth, request: NextRequest): Promise { - if (request.method !== "GET" || request.headers.get("sec-fetch-dest") !== "document") return null; + if (request.method !== "GET" || request.headers.has("next-action") || (request.headers.get("sec-fetch-dest") !== "document" && !fromSignIn(request))) return null; const raw = request.cookies.get(LOOK_COOKIE)?.value; if (!raw) return null; const { userId, getToken } = await auth(); From fe362e3a79e77ac88f0bb79f35310120b9f90fd0 Mon Sep 17 00:00:00 2001 From: sickerine Date: Tue, 1 Dec 2026 18:39:59 +0000 Subject: [PATCH 3/3] fix(workspaces): the bot review: a new report's address starts in the workspace used last, and every page says which workspace its tab is in, not only the rail, which a phone mounts only while its sheet is open --- app/layout.tsx | 3 ++- components/workspaces/item-home.tsx | 25 ++++++++++++++++++++++++- components/workspaces/rail.tsx | 12 +++--------- lib/workspaces/look-cache.test.ts | 15 +++++++++------ lib/workspaces/look-cache.ts | 24 ++++++++++++++++++------ lib/workspaces/paths.test.ts | 1 + lib/workspaces/paths.ts | 2 +- 7 files changed, 58 insertions(+), 24 deletions(-) diff --git a/app/layout.tsx b/app/layout.tsx index 56273ba51..ce9072a8d 100644 --- a/app/layout.tsx +++ b/app/layout.tsx @@ -33,7 +33,7 @@ import { SETUP_HEADER } from "@/lib/profile/setup"; import { LOOK_COOKIE, lookKey, readCache, WORKSPACE_HEADER } from "@/lib/workspaces/look-cache"; import { ADDRESS_HEADER, addressWorkspace } from "@/lib/workspaces/paths"; import { AssistantPanel } from "@/components/assistant/panel"; -import { ItemHome, TabWorkspace, WorkspaceGone } from "@/components/workspaces/item-home"; +import { ItemHome, LastWorkspace, TabWorkspace, WorkspaceGone } from "@/components/workspaces/item-home"; import { WorkspacesProvider } from "@/components/workspaces/parts"; import { QueryHighlightProvider } from "@/components/query-highlight"; import { QUERY_HIGHLIGHT_COOKIE } from "@/lib/search/boolean-query"; @@ -140,6 +140,7 @@ export default async function RootLayout({ + diff --git a/components/workspaces/item-home.tsx b/components/workspaces/item-home.tsx index 85266635c..33a175339 100644 --- a/components/workspaces/item-home.tsx +++ b/components/workspaces/item-home.tsx @@ -1,10 +1,12 @@ "use client"; -import { useState, type ReactNode } from "react"; +import { useEffect, useState, type ReactNode } from "react"; import { redirect, usePathname, useSearchParams } from "next/navigation"; +import { useAuth } from "@clerk/nextjs"; import { api } from "@/convex/_generated/api"; import { useProtectedQuery } from "@/lib/auth/use-auth-query"; import { KeptWorkspace, useWorkspaceSlug, workspaceHref } from "@/lib/workspaces/href"; +import { lookCookieIn, lookCookieOut, lookKey, readCache, usedLast, writeCache } from "@/lib/workspaces/look-cache"; import { addressWorkspace, bareWorkspacePath, outsiderTarget, pageItem } from "@/lib/workspaces/paths"; import { useWorkspace } from "@/lib/workspaces/url"; @@ -51,6 +53,27 @@ export function TabWorkspace({ first, children }: { first: string | null; childr return {children}; } +/** + * Says in the rail's cookie which workspace this tab is in, on every page it opens, an item opened by the address's + * query included: an address that names no workspace opens in the one used last (proxy.ts `lastWorkspaceStart`, + * `TabWorkspace`). Apart from the rail, which a phone mounts only while its sheet is open, and which redraws in a tab + * left open behind. + */ +export function LastWorkspace() { + const key = lookKey(useWorkspaceSlug()); + const pathname = usePathname(); + const query = useSearchParams().toString(); + const { userId } = useAuth(); + // The browser's cookies are the outside system: the proxy and the server read them on the next page load. + useEffect(() => { + if (!userId) return; + const raw = lookCookieIn(document.cookie); + const next = writeCache(usedLast(readCache(raw, userId), key), userId, key, undefined, undefined); + if (next && next !== raw) document.cookie = lookCookieOut(next); + }, [userId, key, pathname, query]); + return null; +} + /** * Leaves an organization's page once the person can't act in it any more: they were removed, * they left in another tab, or it was deleted. They go to the same page in their own workspace, item and all, diff --git a/components/workspaces/rail.tsx b/components/workspaces/rail.tsx index a8ec87dde..2188ae8f8 100644 --- a/components/workspaces/rail.tsx +++ b/components/workspaces/rail.tsx @@ -68,7 +68,7 @@ import { cn } from "@/lib/utils"; import { bareWorkspacePath, switchTarget } from "@/lib/workspaces/paths"; import { inWorkspace, useWorkspace, useWorkspaceScope } from "@/lib/workspaces/url"; import { useWorkspaceSlug } from "@/lib/workspaces/href"; -import { LOOK_COOKIE, lookCookieIn, lookKey, readCache, writeCache, type CachedLook, type CachedMe, type FirstWorkspace } from "@/lib/workspaces/look-cache"; +import { lookCookieIn, lookCookieOut, lookKey, readCache, writeCache, type CachedLook, type CachedMe, type FirstWorkspace } from "@/lib/workspaces/look-cache"; import { CreateOrganization, RoleOf, WorkspaceMenu } from "./switcher"; import { Framed, Opening, PlanChip, settingsHref, useCurrentWorkspace, useWorkspaces, workspaceTint, WorkspaceTile, type WorkspaceLook, type WorkspaceRow } from "./parts"; @@ -101,9 +101,6 @@ function ProgressRing({ value }: { value: number }) { ); } -/** A year: how long the browser keeps the rail's looks. */ -const LOOK_KEPT_S = 365 * 24 * 60 * 60; - /** * How the rail looked last time in this browser, for the person and the address's workspace: * what the server drew the page with (`first`), then the cookie as the address changes. Nothing @@ -128,7 +125,6 @@ export function SidebarContent({ firstWorkspace, onClose }: { firstWorkspace: Fi const pathname = usePathname(); const path = bareWorkspacePath(pathname); const searchParams = useSearchParams(); - const query = searchParams.toString(); const here = useWorkspace(); const loaded = useCurrentWorkspace(); // Invitations waiting for the person's answer: counted on Screening for screenings, and on Shared for every kind, so one is found without its email. @@ -197,10 +193,8 @@ export function SidebarContent({ firstWorkspace, onClose }: { firstWorkspace: Fi const look: CachedLook | undefined = loaded && (loaded.slug ?? null) === slug ? { kind: loaded.kind, workspaceId: loaded.workspaceId, name: loaded.name, ...(loaded.imageUrl ? { imageUrl: loaded.imageUrl } : {}), ...(loaded.colour ? { colour: loaded.colour } : {}), ...(extract ? { extract: true as const } : {}), ...(publish ? { publish: true as const } : {}), ...(author ? { author: true as const } : {}) } : undefined; if (!look && !live) return; const next = writeCache(cache, userId, lookKey(slug), look, live); - if (next && next !== raw) document.cookie = `${LOOK_COOKIE}=${next}; Path=/; Max-Age=${LOOK_KEPT_S}; SameSite=Lax`; - // On every page it draws, an item opened by the address's query included: the cookie also says which workspace - // was used last, and another tab may have said otherwise since. - }, [userId, slug, pathname, query, loaded, live?.name, live?.imageUrl, liveExtracts, liveAuthors, livePublishes]); + if (next && next !== raw) document.cookie = lookCookieOut(next); + }, [userId, slug, loaded, live?.name, live?.imageUrl, liveExtracts, liveAuthors, livePublishes]); const { currentQuery } = useCurrentQueryStore(); const { keywords } = useKeywordExpansionStore(); diff --git a/lib/workspaces/look-cache.test.ts b/lib/workspaces/look-cache.test.ts index c409b4563..037779737 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, readCache, writeCache, type CachedLook } from "./look-cache"; +import { lookCookieIn, readCache, 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" }; @@ -10,19 +10,22 @@ const ada = { name: "Ada", imageUrl: "https://img.clerk.com/ada" }; describe("the rail's cookie", () => { it("reads back what it keeps, for the account it was kept for only", () => { const cookie = writeCache({ looks: {} }, "user_ada", "lab-1", lab(1), ada)!; - expect(readCache(cookie, "user_ada")).toEqual({ me: ada, looks: { "lab-1": lab(1) }, last: "lab-1" }); + expect(readCache(cookie, "user_ada")).toEqual({ me: ada, looks: { "lab-1": lab(1) } }); expect(readCache(cookie, "user_bob")).toEqual({ looks: {} }); expect(readCache(cookie, null)).toEqual({ looks: {} }); expect(readCache(lookCookieIn(`theme=dark; workspace-looks=${cookie}; other=1`), "user_ada").looks).toEqual({ "lab-1": lab(1) }); }); - it("says which organization the rail drew last, and none once it drew the person's own workspace", () => { - const inLab = writeCache({ looks: {} }, "user_ada", "lab-1", lab(1), ada)!; + it("says which organization a tab was in last, and none once one was in the person's own workspace", () => { + const inLab = writeCache(usedLast({ looks: {} }, "lab-1"), "user_ada", "lab-1", undefined, undefined)!; expect(readCache(inLab, "user_ada").last).toBe("lab-1"); // Someone else signing in on the same browser starts in their own workspace. expect(readCache(inLab, "user_bob").last).toBeUndefined(); - const atHome = writeCache(readCache(inLab, "user_ada"), "user_ada", "~", own, undefined)!; - expect(readCache(atHome, "user_ada").last).toBeUndefined(); + // The rail redrawing a workspace, in a tab left open behind, doesn't make it the one used last. + const redrawn = writeCache(readCache(inLab, "user_ada"), "user_ada", "~", own, ada)!; + expect(readCache(redrawn, "user_ada").last).toBe("lab-1"); + const atHome = writeCache(usedLast(readCache(redrawn, "user_ada"), "~"), "user_ada", "~", undefined, undefined)!; + expect(readCache(atHome, "user_ada")).toEqual({ me: ada, looks: { "~": own } }); }); it("drops a colour, photo or section that isn't one, and anything that isn't a look", () => { diff --git a/lib/workspaces/look-cache.ts b/lib/workspaces/look-cache.ts index 9cc9d7446..b94546b9d 100644 --- a/lib/workspaces/look-cache.ts +++ b/lib/workspaces/look-cache.ts @@ -2,8 +2,9 @@ // photo, and each workspace's name, colour, logo and the sections it opens, so the server draws // the rail as it was from the page's first frame, before Clerk or the workspace load. The rail writes it whenever it reads them. It names the account it's for, so someone // else signing in on the same browser doesn't see it. -// It also keeps the organization the rail drew last (`last`): an address that names no workspace opens in that one -// (lib/workspaces/paths.ts `startIn`, `addressWorkspace`). +// It also keeps the organization a tab was in last (`last`): an address that names no workspace opens in that one +// (lib/workspaces/paths.ts `startIn`, `addressWorkspace`). Every page says it (components/workspaces/item-home.tsx +// `LastWorkspace`), apart from the rail, which a phone mounts only while its sheet is open. /** The cookie the rail's looks are kept in. */ export const LOOK_COOKIE = "workspace-looks"; @@ -15,7 +16,7 @@ export const WORKSPACE_HEADER = "x-workspace-slug"; export type CachedLook = { kind: "personal" | "organization"; workspaceId: string; name: string; imageUrl?: string; colour?: string; extract?: true; author?: true; publish?: true }; /** The signed-in person, as the rail's account button shows them. */ export type CachedMe = { name: string; imageUrl?: string }; -/** `last`: the organization the rail drew last, none when that was the person's own workspace. */ +/** `last`: the organization a tab was in last, none when that was the person's own workspace. */ export type LookCache = { me?: CachedMe; looks: Record; last?: string }; /** What the server knew when it drew the page: the address's workspace, who's signed in, and how the rail looked last time. */ @@ -67,8 +68,8 @@ export function readCache(raw: string | undefined, user: string | null | undefin const lastIn = (parsed: { last?: unknown } | null) => (typeof parsed?.last === "string" && parsed.last && parsed.last !== OWN ? parsed.last : undefined); /** - * The cookie's value for `user`, with `me` and the look kept under `key` newest, `key` as the workspace drawn last, - * and the oldest organizations dropped, past KEPT or until it fits. Null when even that doesn't fit. + * The cookie's value for `user`, with `me` and the look kept under `key` newest, and the oldest + * organizations dropped, past KEPT or until it fits. Null when even that doesn't fit. */ export function writeCache(cache: LookCache, user: string, key: string, look: CachedLook | undefined, me: CachedMe | undefined) { const { [key]: was, ...rest } = cache.looks; @@ -76,7 +77,7 @@ export function writeCache(cache: LookCache, user: string, key: string, look: Ca const keptMe = me ?? cache.me; const oldest = Object.keys(rest).filter((other) => other !== OWN); for (const old of oldest.splice(0, Math.max(0, oldest.length - (KEPT - 1)))) delete rest[old]; - const encode = () => encodeURIComponent(JSON.stringify({ user, ...(keptMe ? { me: keptMe } : {}), looks: { ...rest, ...(kept ? { [key]: kept } : {}) }, ...(key === OWN ? {} : { last: key }) })); + const encode = () => encodeURIComponent(JSON.stringify({ user, ...(keptMe ? { me: keptMe } : {}), looks: { ...rest, ...(kept ? { [key]: kept } : {}) }, ...(cache.last ? { last: cache.last } : {}) })); let value = encode(); while (value.length > MAX_VALUE && oldest.length) { delete rest[oldest.shift()!]; @@ -85,5 +86,16 @@ export function writeCache(cache: LookCache, user: string, key: string, look: Ca return value.length > MAX_VALUE ? null : value; } +/** `cache` with the workspace under `key` as the one used last. */ +export function usedLast(cache: LookCache, key: string): LookCache { + const { last: _, ...rest } = cache; + return key === OWN ? rest : { ...rest, last: key }; +} + +/** A year: how long the browser keeps the cookie. */ +const KEPT_S = 365 * 24 * 60 * 60; +/** What `document.cookie` is given to keep `value`. */ +export const lookCookieOut = (value: string) => `${LOOK_COOKIE}=${value}; Path=/; Max-Age=${KEPT_S}; SameSite=Lax`; + /** The cookie's raw value in a `document.cookie` string. */ export const lookCookieIn = (cookies: string) => cookies.split("; ").find((cookie) => cookie.startsWith(`${LOOK_COOKIE}=`))?.slice(LOOK_COOKIE.length + 1); diff --git a/lib/workspaces/paths.test.ts b/lib/workspaces/paths.test.ts index 7c1583a7c..a9b1cb510 100644 --- a/lib/workspaces/paths.test.ts +++ b/lib/workspaces/paths.test.ts @@ -86,6 +86,7 @@ it("starts the home page, a search and a new report in the organization used las expect(start("/")).toBe("/o/lab"); expect(start("/results?q=tvet")).toBe("/o/lab/results"); expect(start("/publish?code=EVENT")).toBe("/o/lab/publish"); + expect(start("/publish?report=new&step=agreement")).toBe("/o/lab/publish"); // A report under way is an item, opened where it is. expect(start("/publish?report=R100001")).toBeNull(); expect(start("/results/abc")).toBeNull(); diff --git a/lib/workspaces/paths.ts b/lib/workspaces/paths.ts index 3638e94a0..7a108a315 100644 --- a/lib/workspaces/paths.ts +++ b/lib/workspaces/paths.ts @@ -60,7 +60,7 @@ export function pageItem(path: string, params: URLSearchParams): Item | null { const collection = path === "/library" ? params.get("col") : null; if (collection) return { kind: "collection", id: collection }; const report = path === "/publish" ? params.get("report") : null; - return report ? { kind: "report", id: report } : null; + return report && report !== "new" ? { kind: "report", id: report } : null; } /** The addresses that start something new: the home page, a search and a report. */