diff --git a/components/reports/publish-flow.tsx b/components/reports/publish-flow.tsx
index d5e66cc74..51ac6df69 100644
--- a/components/reports/publish-flow.tsx
+++ b/components/reports/publish-flow.tsx
@@ -770,21 +770,25 @@ export function PublishFlow() {
* Reports ready in the person's other workspaces, said where they are looking: each workspace's Publish lists only
* its own. Every workspace that holds some has its line, so the lines add up to the count on Publish in the rail.
*/
-function WaitingElsewhere({ waiting, className }: { waiting: Array<{ name: string; slug: string | null; ready: number }>; className?: string }) {
+function WaitingElsewhere({ waiting, className }: { waiting: Array<{ name: string; slug: string | null; ready: number; unfinished: number }>; className?: string }) {
const t = useTranslations("publishReports.flow");
if (!waiting.length) return null;
return (
- {waiting.map(({ name, slug, ready }) => (
-
+ {/* A line for each workspace's ready reports, which wait on the person, and one for their own that aren't live yet,
+ which they may have lost: each opens that workspace's reports, the ready ones for the first. */}
+ {waiting.flatMap(({ name, slug, ready, unfinished }) => [
+ ...(ready ? [{ id: `${slug ?? ""}-ready`, words: slug ? t("waitingIn", { count: ready, name }) : t("waitingOwn", { count: ready }), href: `${slug ? `/o/${slug}` : ""}/publish?view=reports&show=ready`, count: ready }] : []),
+ ...(unfinished ? [{ id: `${slug ?? ""}-unfinished`, words: slug ? t("unfinishedIn", { count: unfinished, name }) : t("unfinishedOwn", { count: unfinished }), href: `${slug ? `/o/${slug}` : ""}/publish?view=reports`, count: unfinished }] : []),
+ ]).map(({ id, words, href, count }) => (
+
diff --git a/components/workspaces/item-home.tsx b/components/workspaces/item-home.tsx
index d0ad829c3..0da9a7b9d 100644
--- a/components/workspaces/item-home.tsx
+++ b/components/workspaces/item-home.tsx
@@ -65,7 +65,8 @@ export function LastWorkspace() {
const named = addressWorkspace(pathname);
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.
+ // The browser's cookies are the outside system: the proxy and the server read them on the next page load, and the
+ // proxy tells the person's account of a change (proxy.ts `keepOnAccount`).
useEffect(() => {
if (!userId || named === undefined) return;
const raw = lookCookieIn(document.cookie);
diff --git a/convex/_generated/api.d.ts b/convex/_generated/api.d.ts
index 148e3ab91..247c22803 100644
--- a/convex/_generated/api.d.ts
+++ b/convex/_generated/api.d.ts
@@ -553,6 +553,7 @@ import type * as webhooks_projections from "../webhooks/projections.js";
import type * as workpool from "../workpool.js";
import type * as workspaces_actor from "../workspaces/actor.js";
import type * as workspaces_create from "../workspaces/create.js";
+import type * as workspaces_lastUsed from "../workspaces/lastUsed.js";
import type * as workspaces_makers from "../workspaces/makers.js";
import type * as workspaces_move from "../workspaces/move.js";
import type * as workspaces_personal from "../workspaces/personal.js";
@@ -1130,6 +1131,7 @@ declare const fullApi: ApiFromModules<{
workpool: typeof workpool;
"workspaces/actor": typeof workspaces_actor;
"workspaces/create": typeof workspaces_create;
+ "workspaces/lastUsed": typeof workspaces_lastUsed;
"workspaces/makers": typeof workspaces_makers;
"workspaces/move": typeof workspaces_move;
"workspaces/personal": typeof workspaces_personal;
diff --git a/convex/lib/validators.ts b/convex/lib/validators.ts
index 40b6e8333..8e1fce3d4 100644
--- a/convex/lib/validators.ts
+++ b/convex/lib/validators.ts
@@ -104,6 +104,8 @@ export const userFields = {
locale: v.optional(v.string()),
/** When they finished or skipped the profile setup. Until either, a new account gets it in front of every page. */
onboarding: v.optional(v.object({ finishedAt: v.optional(v.number()), skippedAt: v.optional(v.number()) })),
+ /** The organization, by its address's slug, the person last worked in; none for their own workspace. A browser that has never been used remembers nothing, so it opens there (convex/workspaces/lastUsed.ts, proxy.ts). */
+ lastWorkspace: v.optional(v.string()),
createdAt: v.number(),
updatedAt: v.number(),
};
diff --git a/convex/reports/flow.test.ts b/convex/reports/flow.test.ts
index e66028783..50e789761 100644
--- a/convex/reports/flow.test.ts
+++ b/convex/reports/flow.test.ts
@@ -183,17 +183,18 @@ describe("a report's details sent under another licence", () => {
});
describe("reports that wait in a person's other workspaces", () => {
- it("tells an admin of the lab, from their own workspace, and tells a member nothing", async () => {
+ it("tells an admin of the lab, from their own workspace, and the member who made it that it isn't live yet", async () => {
const world = await setup();
await checked(world, [passed("byline"), passed("harm")], world.member, world.lab);
const ownOf = (clerkId: string) => world.t.run(async (ctx) => ensureWorkspace(ctx, { kind: "personal", userId: (await ctx.db.query("users").withIndex("by_clerk_id", (q) => q.eq("clerkId", clerkId)).unique())!._id }));
- expect(await world.orgAdmin.query(api.reports.flow.waitingElsewhere, { workspaceId: await ownOf("orgadmin") })).toEqual({ ready: 1, workspaces: [{ name: "Learning Lab", slug: "lab", ready: 1 }] });
+ expect(await world.orgAdmin.query(api.reports.flow.waitingElsewhere, { workspaceId: await ownOf("orgadmin") })).toEqual({ ready: 1, workspaces: [{ name: "Learning Lab", slug: "lab", ready: 1, unfinished: 0 }] });
// In the lab itself its own Publish says so, and a member activates nothing.
expect(await world.orgAdmin.query(api.reports.flow.waitingElsewhere, { workspaceId: world.lab })).toEqual({ ready: 0, workspaces: [] });
- expect(await world.member.query(api.reports.flow.waitingElsewhere, { workspaceId: await ownOf("member") })).toEqual({ ready: 0, workspaces: [] });
+ // A member activates nothing, but finds their own report from their own workspace, where they may have landed.
+ expect(await world.member.query(api.reports.flow.waitingElsewhere, { workspaceId: await ownOf("member") })).toEqual({ ready: 0, workspaces: [{ name: "Learning Lab", slug: "lab", ready: 0, unfinished: 1 }] });
// A person's own ready report is said in the lab, where they are only a member.
await checked(world, [passed("byline"), passed("harm")]);
- expect(await world.author.query(api.reports.flow.waitingElsewhere, { workspaceId: world.lab })).toEqual({ ready: 1, workspaces: [{ name: "", slug: null, ready: 1 }] });
+ expect(await world.author.query(api.reports.flow.waitingElsewhere, { workspaceId: world.lab })).toEqual({ ready: 1, workspaces: [{ name: "", slug: null, ready: 1, unfinished: 0 }] });
});
});
diff --git a/convex/reports/flow.ts b/convex/reports/flow.ts
index 0fd169b82..c815c0451 100644
--- a/convex/reports/flow.ts
+++ b/convex/reports/flow.ts
@@ -914,16 +914,17 @@ export const countsForAssistant = assistantQuery(countsAction);
const ELSEWHERE_REPORTS = 200;
/**
- * The reports that wait on the person in the workspaces they aren't looking at: their own, and each organization
- * they are an admin of. Someone in their own workspace is told there that their lab's report is ready, and the other
- * way round, since each workspace's Publish page lists only its own.
+ * The reports that wait on the person in the workspaces they aren't looking at: their own, and each organization they
+ * are in. Someone in their own workspace is told there that their lab's report is ready, or that their own report
+ * there isn't finished, and the other way round, since each workspace's Publish page lists only its own: a person who
+ * lands in the wrong workspace finds their report from here.
*/
export const waitingElsewhereAction = defineUserQuery({
path: "reports/flow:waitingElsewhere",
description:
- "The person's other workspaces that hold reports ready for them to activate on Openscholar: their own workspace and each organization they are an admin of, " +
- "leaving out the workspace asked from. It says how many are ready in all (`ready`) and names each workspace that holds some (`workspaces`): its name, " +
- "its address (`slug`, none for their own) and how many are ready there. `workspaces` is empty when nothing waits.",
+ "The person's other workspaces that hold reports waiting on them on Openscholar: their own workspace and each organization they are in, " +
+ "leaving out the workspace asked from. It says how many are ready for them to activate in all (`ready`, only in their own workspace and organizations they are an admin of) and names each workspace that holds some, or holds reports of theirs that aren't live yet (`workspaces`): its name, " +
+ "its address (`slug`, none for their own), how many are ready there and how many of their own aren't finished (`unfinished`: being worked on, checked, reviewed or declined). `workspaces` is empty when nothing waits.",
args: {},
returns: v.object({ ready: v.number(), /** Every one of them, so what the page names adds up to `ready`: the person's own first. */ workspaces: waitingWorkspacesValidator }),
run: async (ctx, { userId, workspaceId }) => {
@@ -932,22 +933,29 @@ export const waitingElsewhereAction = defineUserQuery({
const reviewed = await reviewedIn(ctx);
// Only reports that never went live can be ready, and a workspace holds few of those: its newest are looked at,
// since a ready report was worked on lately and old drafts weren't.
- const readyIn = async (id: Id<"workspaces">) =>
- (await ctx.db.query("reports").withIndex("by_workspaceId_and_activatedAt", (q) => q.eq("workspaceId", id).eq("activatedAt", undefined)).order("desc").take(ELSEWHERE_REPORTS)).filter((report) => stageOf(report, reviewed(id)) === "ready").length;
+ // The person's own reports that never went live, wherever they are, read once: a workspace's newest reports by others never hide them.
+ const mineUnlive = await ctx.db.query("reports").withIndex("by_ownerId_and_activatedAt", (q) => q.eq("ownerId", userId).eq("activatedAt", undefined)).order("desc").take(ELSEWHERE_REPORTS);
+ // Ready ones are the person's to activate only where they can: their own workspace, or an organization they run.
+ const waitingIn = async (id: Id<"workspaces">, activates: boolean) => {
+ const ready = (report: Doc<"reports">) => activates && stageOf(report, reviewed(id)) === "ready";
+ const others = activates ? await ctx.db.query("reports").withIndex("by_workspaceId_and_activatedAt", (q) => q.eq("workspaceId", id).eq("activatedAt", undefined)).order("desc").take(ELSEWHERE_REPORTS) : [];
+ return { ready: others.filter(ready).length, unfinished: mineUnlive.filter((report) => report.workspaceId === id && !ready(report)).length };
+ };
const own = await ctx.db.query("workspaces").withIndex("by_userId", (q) => q.eq("userId", userId)).unique();
- // ponytail: the first organizations a person is an admin of are asked about; an admin of more than these opens the rest to see.
+ // ponytail: the first organizations a person is in are asked about, those they run first, whose ready reports the
+ // sidebar counts; someone in more than these opens the rest to see.
const memberships = (await ctx.db.query("organizationMemberships").withIndex("by_clerkUserId_and_state", (q) => q.eq("clerkUserId", user.clerkId).eq("state", "active")).take(MAX_ORGANIZATIONS_PER_PERSON))
- .filter((membership) => membership.role === "org:admin")
+ .sort((a, b) => Number(b.role === "org:admin") - Number(a.role === "org:admin"))
.slice(0, ELSEWHERE_WORKSPACES);
const organizations = await Promise.all(
memberships.map(async (membership) => {
const organization = await ctx.db.get("organizations", membership.organizationId);
const workspace = organization?.state === "active" ? await ctx.db.query("workspaces").withIndex("by_organizationId", (q) => q.eq("organizationId", organization._id)).unique() : null;
- return organization && workspace && workspace._id !== workspaceId ? [{ name: organization.name, slug: organization.slug as string | null, ready: await readyIn(workspace._id) }] : [];
+ return organization && workspace && workspace._id !== workspaceId ? [{ name: organization.name, slug: organization.slug as string | null, ...(await waitingIn(workspace._id, membership.role === "org:admin")) }] : [];
}),
);
- const mine = own && own._id !== workspaceId ? [{ name: "", slug: null, ready: await readyIn(own._id) }] : [];
- const waiting = [...mine, ...organizations.flat()].filter((workspace) => workspace.ready > 0);
+ const mine = own && own._id !== workspaceId ? [{ name: "", slug: null, ...(await waitingIn(own._id, true)) }] : [];
+ const waiting = [...mine, ...organizations.flat()].filter((workspace) => workspace.ready > 0 || workspace.unfinished > 0);
return { ready: waiting.reduce((sum, workspace) => sum + workspace.ready, 0), workspaces: waiting };
},
});
diff --git a/convex/reports/validators.ts b/convex/reports/validators.ts
index dfe87fadc..d8008458c 100644
--- a/convex/reports/validators.ts
+++ b/convex/reports/validators.ts
@@ -575,7 +575,7 @@ export const reportRowsValidator = capped(v.array(authorRowValidator), REPORTS_P
/** How many of the organizations a person is an admin of are asked about for reports that wait on them. */
export const ELSEWHERE_WORKSPACES = 20;
/** The person's other workspaces that hold reports ready for them to activate: their own, and those organizations. */
-export const waitingWorkspacesValidator = capped(v.array(v.object({ name: v.string(), slug: v.union(v.string(), v.null()), ready: v.number() })), ELSEWHERE_WORKSPACES + 1);
+export const waitingWorkspacesValidator = capped(v.array(v.object({ name: v.string(), slug: v.union(v.string(), v.null()), ready: v.number(), /** The person's own reports there that aren't live yet and aren't theirs to activate now: being worked on, checked, reviewed or declined. */ unfinished: v.number() })), ELSEWHERE_WORKSPACES + 1);
/** A report's authors by name, as its signed agreement lists them. */
export const signerNamesValidator = capped(v.array(v.string()), DETAIL_CAPS.authors);
diff --git a/convex/schema.ts b/convex/schema.ts
index 6ef9ccb8d..ee25e5b2d 100644
--- a/convex/schema.ts
+++ b/convex/schema.ts
@@ -684,6 +684,8 @@ export default defineSchema({
.index("by_updatedAt_and_key", ["updatedAt", "key"])
// A workspace's reports that never went live, which go with it when it is deleted (workspaces/purge.ts).
.index("by_workspaceId_and_activatedAt", ["workspaceId", "activatedAt"])
+ // A person's own reports that never went live, wherever they are: Publish points to them from other workspaces (reports/flow.ts `waitingElsewhere`).
+ .index("by_ownerId_and_activatedAt", ["ownerId", "activatedAt"])
// Live reports by their titles, which Already published searches before anywhere else (reports/ownReports.ts): the
// very same title, in any script, and titles that share its words.
.index("by_status_and_title", ["status", "title"])
diff --git a/convex/workspaces/lastUsed.test.ts b/convex/workspaces/lastUsed.test.ts
new file mode 100644
index 000000000..c79e5b123
--- /dev/null
+++ b/convex/workspaces/lastUsed.test.ts
@@ -0,0 +1,25 @@
+// The organization a person last worked in, kept on their account for a browser that remembers nothing (proxy.ts).
+import { describe, expect, it } from "vitest";
+import { api } from "../_generated/api";
+import { setup } from "../reports/reports.test-support";
+
+describe("the workspace a person last worked in", () => {
+ it("is kept on their account, back to their own workspace too, and is forgotten once they leave the organization", async () => {
+ const { t, author, stranger } = await setup();
+ expect(await author.query(api.workspaces.lastUsed.get, {})).toBeNull();
+ await author.mutation(api.workspaces.lastUsed.remember, { slug: "lab" });
+ expect(await author.query(api.workspaces.lastUsed.get, {})).toBe("lab");
+ await author.mutation(api.workspaces.lastUsed.remember, { slug: null });
+ expect(await author.query(api.workspaces.lastUsed.get, {})).toBeNull();
+ // Someone who isn't a member is never sent there, whatever their account says.
+ await stranger.mutation(api.workspaces.lastUsed.remember, { slug: "lab" });
+ expect(await stranger.query(api.workspaces.lastUsed.get, {})).toBeNull();
+ // Nor is someone who left it.
+ await author.mutation(api.workspaces.lastUsed.remember, { slug: "lab" });
+ await t.run(async (ctx) => {
+ const membership = await ctx.db.query("organizationMemberships").filter((q) => q.eq(q.field("clerkUserId"), "author")).first();
+ await ctx.db.patch("organizationMemberships", membership!._id, { state: "revoked" });
+ });
+ expect(await author.query(api.workspaces.lastUsed.get, {})).toBeNull();
+ });
+});
diff --git a/convex/workspaces/lastUsed.ts b/convex/workspaces/lastUsed.ts
new file mode 100644
index 000000000..d19ade2bd
--- /dev/null
+++ b/convex/workspaces/lastUsed.ts
@@ -0,0 +1,39 @@
+// The organization a person last worked in, kept on their account (users.lastWorkspace) as well as in each browser's
+// cookie (lib/workspaces/look-cache.ts): a browser that has never been used, or has been cleared, asks here, so the
+// person starts where they left off on another device rather than in their own workspace (proxy.ts).
+import { v } from "convex/values";
+import { mutation, query } from "../lib/functions";
+import { getCurrentUser } from "../lib/auth";
+import { createError } from "../lib/errors";
+import { actorIn } from "./actor";
+import { organizationAt } from "../organizations/read";
+
+/** Slugs are short; a longer one isn't an organization's address. */
+const SLUG_MAX = 200;
+
+/** The slug of the organization the person last worked in, while they are still its member; null for their own workspace. */
+export const get = query({
+ args: {},
+ returns: v.union(v.string(), v.null()),
+ handler: async (ctx) => {
+ const user = await getCurrentUser(ctx);
+ const slug = user?.lastWorkspace;
+ if (!user || !slug) return null;
+ const organization = await organizationAt(ctx, slug);
+ const workspace = organization && (await ctx.db.query("workspaces").withIndex("by_organizationId", (q) => q.eq("organizationId", organization._id)).unique());
+ return workspace && (await actorIn(ctx, user, workspace._id)) ? slug : null;
+ },
+});
+
+/** Keeps the workspace a page was opened in as the one the person last worked in: an organization by its slug, or null for their own. */
+export const remember = mutation({
+ args: { slug: v.union(v.string(), v.null()) },
+ returns: v.null(),
+ handler: async (ctx, { slug }) => {
+ const user = await getCurrentUser(ctx);
+ if (!user) return null;
+ if (slug !== null && (!slug || slug.length > SLUG_MAX)) throw createError("VALIDATION_ERROR", "That isn't an organization's address.");
+ if ((user.lastWorkspace ?? null) !== slug) await ctx.db.patch("users", user._id, { lastWorkspace: slug ?? undefined });
+ return null;
+ },
+});
diff --git a/lib/workspaces/look-cache.test.ts b/lib/workspaces/look-cache.test.ts
index 037779737..2df2a19ea 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, usedLast, writeCache, type CachedLook } from "./look-cache";
+import { lookCookieIn, lookKey, readCache, savedValue, 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" };
@@ -59,3 +59,22 @@ describe("the rail's cookie", () => {
expect(Object.keys(cache.looks).length).toBeLessThan(7);
});
});
+
+describe("telling the account where the person last worked", () => {
+ it("asks once for each change, keeps what was told when the page writes the cookie again, and tells of their own workspace too", () => {
+ const user = "user_ada";
+ // A browser that remembers the lab, from before the account was told anything.
+ let raw = writeCache(usedLast(readCache(undefined, user), "lab"), user, "lab", undefined, undefined)!;
+ expect(unsaved(readCache(raw, user))).toBe("lab");
+ raw = savedValue(readCache(raw, user), user)!;
+ expect(unsaved(readCache(raw, user))).toBeUndefined();
+ // The page writes the cookie again on every page in the lab: nothing more to tell.
+ raw = writeCache(usedLast(readCache(raw, user), "lab"), user, "lab", undefined, undefined)!;
+ expect(unsaved(readCache(raw, user))).toBeUndefined();
+ // Back in their own workspace, the account is told so.
+ raw = writeCache(usedLast(readCache(raw, user), lookKey(null)), user, lookKey(null), undefined, undefined)!;
+ expect(unsaved(readCache(raw, user))).toBeNull();
+ raw = savedValue(readCache(raw, user), user)!;
+ expect(unsaved(readCache(raw, user))).toBeUndefined();
+ });
+});
diff --git a/lib/workspaces/look-cache.ts b/lib/workspaces/look-cache.ts
index b94546b9d..52a1d4907 100644
--- a/lib/workspaces/look-cache.ts
+++ b/lib/workspaces/look-cache.ts
@@ -16,8 +16,12 @@ 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 a tab was in last, none when that was the person's own workspace. */
-export type LookCache = { me?: CachedMe; looks: Record; last?: string };
+/**
+ * `last`: the organization a tab was in last, none when that was the person's own workspace. `saved`: what the
+ * person's account was last told of it (convex/workspaces/lastUsed.ts), OWN for their own workspace: the proxy tells
+ * it again when the two differ, so a new browser opens where they last worked.
+ */
+export type LookCache = { me?: CachedMe; looks: Record; last?: string; saved?: 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 };
@@ -41,7 +45,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; last?: unknown } | null;
+ const parsed = JSON.parse(raw.startsWith("%") ? decodeURIComponent(raw) : raw) as { user?: unknown; me?: Partial; looks?: unknown; last?: unknown; saved?: unknown } | null;
if (parsed?.user !== user) return { looks: {} };
const looks: Record = {};
for (const [key, value] of Object.entries((parsed.looks ?? {}) as Record>)) {
@@ -59,12 +63,23 @@ 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;
const last = lastIn(parsed);
- return { ...(me ? { me } : {}), looks, ...(last ? { last } : {}) };
+ const saved = typeof parsed.saved === "string" && parsed.saved ? parsed.saved : undefined;
+ return { ...(me ? { me } : {}), looks, ...(last ? { last } : {}), ...(saved ? { saved } : {}) };
} catch {
return { looks: {} };
}
}
+/** Whether the cookie is this person's: one that isn't remembers nothing of where they last worked, and the account is asked (proxy.ts). */
+export function cookieIsTheirs(raw: string | undefined, user: string | null | undefined) {
+ if (!raw || !user) return false;
+ try {
+ return (JSON.parse(raw.startsWith("%") ? decodeURIComponent(raw) : raw) as { user?: unknown } | null)?.user === user;
+ } catch {
+ return false;
+ }
+}
+
const lastIn = (parsed: { last?: unknown } | null) => (typeof parsed?.last === "string" && parsed.last && parsed.last !== OWN ? parsed.last : undefined);
/**
@@ -77,7 +92,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 } : {}) }, ...(cache.last ? { last: cache.last } : {}) }));
+ const encode = () => encodeURIComponent(JSON.stringify({ user, ...(keptMe ? { me: keptMe } : {}), looks: { ...rest, ...(kept ? { [key]: kept } : {}) }, ...(cache.last ? { last: cache.last } : {}), ...(cache.saved ? { saved: cache.saved } : {}) }));
let value = encode();
while (value.length > MAX_VALUE && oldest.length) {
delete rest[oldest.shift()!];
@@ -86,6 +101,12 @@ export function writeCache(cache: LookCache, user: string, key: string, look: Ca
return value.length > MAX_VALUE ? null : value;
}
+/** What the person's account should be told is the workspace they last worked in, when it hasn't been yet: an organization's slug, or null for their own. Undefined when it already knows. */
+export const unsaved = (cache: LookCache): string | null | undefined => ((cache.last ?? OWN) === cache.saved ? undefined : (cache.last ?? null));
+
+/** 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);
+
/** `cache` with the workspace under `key` as the one used last. */
export function usedLast(cache: LookCache, key: string): LookCache {
const { last: _, ...rest } = cache;
diff --git a/messages/en-GB.json b/messages/en-GB.json
index a5b1c844a..f8d016250 100644
--- a/messages/en-GB.json
+++ b/messages/en-GB.json
@@ -7098,6 +7098,8 @@
"waitingIn": "{count, plural, one {# report in {name} is ready for you to activate.} other {# reports in {name} are ready for you to activate.}}",
"waitingOwn": "{count, plural, one {# report in your own workspace is ready for you to activate.} other {# reports in your own workspace are ready for you to activate.}}",
"waitingOpen": "{count, plural, one {Open it} other {Open them}}",
+ "unfinishedIn": "{count, plural, one {You have # report in {name} that isn't live yet.} other {You have # reports in {name} that aren't live yet.}}",
+ "unfinishedOwn": "{count, plural, one {You have # report in your own workspace that isn't live yet.} other {You have # reports in your own workspace that aren't live yet.}}",
"registering": "{id, select, docid {The page is open now and can be shared. The DOCiD starts working once it is registered, usually within a few minutes.} other {The page is open now and can be shared. The DOI starts working once it is registered, usually within a few minutes.}}",
"requestFailed": "The request couldn't be sent.",
"reviewIntro": "A reviewer reads your report and what the checks said. Ask when you think a check got it wrong.",
diff --git a/messages/en-US.json b/messages/en-US.json
index aa9e0e6dd..3d8d9e6ca 100644
--- a/messages/en-US.json
+++ b/messages/en-US.json
@@ -7098,6 +7098,8 @@
"waitingIn": "{count, plural, one {# report in {name} is ready for you to activate.} other {# reports in {name} are ready for you to activate.}}",
"waitingOwn": "{count, plural, one {# report in your own workspace is ready for you to activate.} other {# reports in your own workspace are ready for you to activate.}}",
"waitingOpen": "{count, plural, one {Open it} other {Open them}}",
+ "unfinishedIn": "{count, plural, one {You have # report in {name} that isn't live yet.} other {You have # reports in {name} that aren't live yet.}}",
+ "unfinishedOwn": "{count, plural, one {You have # report in your own workspace that isn't live yet.} other {You have # reports in your own workspace that aren't live yet.}}",
"registering": "{id, select, docid {The page is open now and can be shared. The DOCiD starts working once it is registered, usually within a few minutes.} other {The page is open now and can be shared. The DOI starts working once it is registered, usually within a few minutes.}}",
"requestFailed": "The request couldn't be sent.",
"reviewIntro": "A reviewer reads your report and what the checks said. Ask when you think a check got it wrong.",
diff --git a/proxy.ts b/proxy.ts
index f0a9b8f4f..5633ec302 100644
--- a/proxy.ts
+++ b/proxy.ts
@@ -1,6 +1,6 @@
import { NextFetchEvent, NextRequest, NextResponse } from "next/server";
import { clerkMiddleware, type ClerkMiddlewareAuth } from "@clerk/nextjs/server";
-import { fetchQuery } from "convex/nextjs";
+import { fetchMutation, fetchQuery } from "convex/nextjs";
import { api } from "@/convex/_generated/api";
import { inFlow, isPage, SETUP_DONE_COOKIE, SETUP_HEADER, SETUP_PATH } from "@/lib/profile/setup";
import { locales } from "@/i18n/config";
@@ -9,7 +9,7 @@ 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 { LOOK_COOKIE, readCache, slugOf, WORKSPACE_HEADER } from "@/lib/workspaces/look-cache";
+import { LOOK_COOKIE, cookieIsTheirs, lookCookieOut, readCache, savedValue, slugOf, unsaved, 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";
@@ -42,6 +42,8 @@ const authMiddleware = clerkMiddleware(
}
const response = NextResponse.next({ request: { headers } });
if (setup.doneFor) response.cookies.set(SETUP_DONE_COOKIE, setup.doneFor, { maxAge: ONE_YEAR, path: "/", sameSite: "lax", httpOnly: true });
+ const told = await keepOnAccount(auth, request);
+ if (told) response.headers.append("Set-Cookie", lookCookieOut(told));
return response;
},
{
@@ -94,20 +96,51 @@ function fromSignIn(request: NextRequest) {
async function lastWorkspaceStart(auth: ClerkMiddlewareAuth, request: NextRequest): Promise {
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();
- const last = readCache(raw, userId).last;
- const target = last ? startIn(last, request.nextUrl.pathname, request.nextUrl.searchParams) : null;
- if (!last || !target) return null;
+ if (!userId) return null;
+ // A browser that remembers this person: its own memory, even of their own workspace. One that doesn't (a new
+ // device, cleared cookies, another person's cookie) asks the account, so they start where they last worked.
+ const known = cookieIsTheirs(raw, userId);
+ if (known && !readCache(raw, userId).last) 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;
+ if (!token) return null;
+ const last = known ? readCache(raw, userId).last! : await fetchQuery(api.workspaces.lastUsed.get, {}, { token });
+ const target = last ? startIn(last, request.nextUrl.pathname, request.nextUrl.searchParams) : null;
+ if (!last || !target) return null;
+ return !known || (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;
}
}
+/**
+ * Tells the person's account which workspace 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
+ * 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.
+ */
+async function keepOnAccount(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;
+ const { userId, getToken } = await auth();
+ if (!userId || !cookieIsTheirs(raw, userId)) return null;
+ const cache = readCache(raw, userId);
+ const slug = unsaved(cache);
+ if (slug === undefined) return null;
+ try {
+ const token = await getToken({ template: "convex" });
+ if (!token) return null;
+ await fetchMutation(api.workspaces.lastUsed.remember, { slug }, { token });
+ return savedValue(cache, userId);
+ } catch (error) {
+ console.error(JSON.stringify({ event: "last-workspace-keep-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]);
diff --git a/scripts/user-actions-exempt.json b/scripts/user-actions-exempt.json
index 686fd745c..ab1468696 100644
--- a/scripts/user-actions-exempt.json
+++ b/scripts/user-actions-exempt.json
@@ -84,6 +84,8 @@
"users/queries:me": "Who is signed in, for the page.",
"wallet/queries:isOriginAllowed": "The connect page's check that an external app's origin is allowed.",
"workspaces/queries:bySlug": "Which organization's workspace a page's address names, for the page's own calls. The assistant acts in its chat's workspace.",
+ "workspaces/lastUsed:get": "Which workspace a browser with no memory of its own opens a start page in, for the proxy. The assistant acts in its chat's workspace.",
+ "workspaces/lastUsed:remember": "Keeps the workspace a page was opened in as the one last worked in, written as pages open. Nothing a person asks for.",
"workspaces/queries:homeOf": "Which workspace an item a page's address names is in, for the page to open it there. The assistant names items by ID in its own workspace.",
"workspaces/queries:memberAt": "Whether the person is still a member of the organization a page's address names, for a page left open to leave it. The assistant acts in its chat's workspace.",
"workspaces/queries:personal": "The workspace a page outside an organization's address is in, for the page's own calls. The assistant acts in its chat's workspace.",