Skip to content

armgit / crm

Public Imported from GitHub
0

Comp AI CRM is an open source, CRM designed for AI agents. Agentic-first CRM.

TypeScript

refactor(proxy): streamline onboarding and research gate handling

Lewis Carhart14cb93285600
diff --git a/apps/app/components/app-header.tsx b/apps/app/components/app-header.tsx
index fd652e4e..0a402240 100644
--- a/apps/app/components/app-header.tsx
+++ b/apps/app/components/app-header.tsx
@@ -27,11 +27,25 @@ import { useTRPC } from "@/lib/trpc/client";
type User = { name: string; email: string; image: string | null };
+/**
+ * The workspace arrives named `CRM` until somebody types something else — the
+ * deliberate placeholder — so appending the product name to it read "CRM CRM".
+ * A workspace genuinely called "Acme CRM" has the same problem, which is why
+ * this tests the name rather than comparing it to the default.
+ */
+export function workspaceLabel(name: string | undefined): string {
+ const trimmed = name?.trim();
+
+ if (!trimmed) return "CRM";
+
+ return /\bcrm$/i.test(trimmed) ? trimmed : `${trimmed} CRM`;
+}
+
export function AppHeader({ user }: { user: User }) {
const { setOpen: setMobileNavOpen } = useMobileNav();
const trpc = useTRPC();
const workspace = useQuery(trpc.workspace.get.queryOptions());
- const name = workspace.data?.name;
+ const label = workspaceLabel(workspace.data?.name);
async function handleSignOut() {
const { error } = await signOut();
@@ -64,9 +78,7 @@ export function AppHeader({ user }: { user: User }) {
<Logo className="size-5" />
</Link>
<Separator orientation="vertical" className="mx-1 h-5 bg-transparent" />
- <span className="min-w-0 truncate font-medium text-sm">
- {name ? `${name} CRM` : "CRM"}
- </span>
+ <span className="min-w-0 truncate font-medium text-sm">{label}</span>
</div>
<div className="ml-auto flex shrink-0 items-center gap-1.5">
diff --git a/apps/app/lib/onboarding.ts b/apps/app/lib/onboarding.ts
index 5fb844c5..e9b57f77 100644
--- a/apps/app/lib/onboarding.ts
+++ b/apps/app/lib/onboarding.ts
@@ -1,16 +1,10 @@
-import type { NextRequest, NextResponse } from "next/server";
+import type { NextRequest } from "next/server";
import { API_URL } from "@/lib/env";
export const ONBOARDING_PATH = "/onboarding";
export const RESEARCH_PATH = "/onboarding/research";
-export const ONBOARDING_COOKIE = "crm.onboarded";
-
-export const RESEARCH_COOKIE = "crm.research";
-
-const COOKIE_MAX_AGE = 60 * 60 * 24 * 365;
-
const GATE_TIMEOUT_MS = 2_000;
export type Gate = "settled" | "required" | "unknown";
@@ -26,6 +20,7 @@ async function read<T>(
try {
const response = await fetch(`${API_URL}/api/trpc/${procedure}`, {
headers: { cookie },
+ cache: "no-store",
signal: AbortSignal.timeout(GATE_TIMEOUT_MS),
});
@@ -60,17 +55,3 @@ export async function readResearchGate(request: NextRequest): Promise<Gate> {
return key.configured ? "settled" : "required";
}
-
-export function settle(
- request: NextRequest,
- response: NextResponse,
- name: string,
-): void {
- response.cookies.set(name, "1", {
- httpOnly: true,
- sameSite: "lax",
- secure: request.nextUrl.protocol === "https:",
- path: "/",
- maxAge: COOKIE_MAX_AGE,
- });
-}
diff --git a/apps/app/proxy.ts b/apps/app/proxy.ts
index 999af5d7..374f7fad 100644
--- a/apps/app/proxy.ts
+++ b/apps/app/proxy.ts
@@ -2,14 +2,10 @@ import { AUTH_COOKIE_PREFIX } from "@crm/auth/cookies";
import { getSessionCookie } from "better-auth/cookies";
import { type NextRequest, NextResponse } from "next/server";
import {
- type Gate,
- ONBOARDING_COOKIE,
ONBOARDING_PATH,
- RESEARCH_COOKIE,
RESEARCH_PATH,
readOnboardingGate,
readResearchGate,
- settle,
} from "@/lib/onboarding";
const SIGN_IN_PATH = "/sign-in";
@@ -29,27 +25,21 @@ export async function proxy(request: NextRequest) {
if (isUngated(pathname)) return NextResponse.next();
- const onboarding = request.cookies.has(ONBOARDING_COOKIE)
- ? "settled"
- : await readOnboardingGate(request);
+ // Both answers, every time, and concurrently — so the gate costs one round
+ // trip rather than two, and neither answer can be stale.
+ const [onboarding, research] = await Promise.all([
+ readOnboardingGate(request),
+ readResearchGate(request),
+ ]);
- const settled = onboarding === "settled" ? [ONBOARDING_COOKIE] : [];
+ if (onboarding === "required") return sendTo(ONBOARDING_PATH, request);
+ if (research === "required") return sendTo(RESEARCH_PATH, request);
- if (onboarding === "required") {
- return remember(request, sendTo(ONBOARDING_PATH, request), ...settled);
- }
-
- const research = request.cookies.has(RESEARCH_COOKIE)
- ? "settled"
- : await readResearchGate(request);
-
- if (research === "required") {
- return remember(request, sendTo(RESEARCH_PATH, request), ...settled);
- }
-
- if (research === "settled") settled.push(RESEARCH_COOKIE);
+ const settled = onboarding === "settled" && research === "settled";
- return remember(request, past(request, onboarding, research), ...settled);
+ return settled && isSetup(pathname)
+ ? NextResponse.redirect(new URL("/", request.nextUrl))
+ : NextResponse.next();
}
function isUngated(pathname: string): boolean {
@@ -58,8 +48,8 @@ function isUngated(pathname: string): boolean {
);
}
-function home(request: NextRequest): NextResponse {
- return NextResponse.redirect(new URL("/", request.nextUrl));
+function isSetup(pathname: string): boolean {
+ return pathname === ONBOARDING_PATH || pathname === RESEARCH_PATH;
}
function sendTo(path: string, request: NextRequest): NextResponse {
@@ -68,30 +58,6 @@ function sendTo(path: string, request: NextRequest): NextResponse {
: NextResponse.redirect(new URL(path, request.nextUrl));
}
-function past(
- request: NextRequest,
- onboarding: Gate,
- research: Gate,
-): NextResponse {
- const done = onboarding === "settled" && research === "settled";
-
- const setup =
- request.nextUrl.pathname === ONBOARDING_PATH ||
- request.nextUrl.pathname === RESEARCH_PATH;
-
- return done && setup ? home(request) : NextResponse.next();
-}
-
-function remember(
- request: NextRequest,
- response: NextResponse,
- ...cookies: string[]
-): NextResponse {
- for (const name of cookies) settle(request, response, name);
-
- return response;
-}
-
export const config = {
matcher: [
"/((?!api|_next/static|_next/image|.*\\.(?:ico|png|svg|jpg|jpeg|gif|webp|webmanifest)$).*)",
diff --git a/apps/app/test/onboarding-gate.spec.ts b/apps/app/test/onboarding-gate.spec.ts
index 280e44f6..07320140 100644
--- a/apps/app/test/onboarding-gate.spec.ts
+++ b/apps/app/test/onboarding-gate.spec.ts
@@ -1,12 +1,7 @@
import { afterEach, describe, expect, it } from "bun:test";
import { AUTH_COOKIE_PREFIX } from "@crm/auth/cookies";
import { NextRequest } from "next/server";
-import {
- ONBOARDING_COOKIE,
- RESEARCH_COOKIE,
- readOnboardingGate,
- readResearchGate,
-} from "../lib/onboarding";
+import { readOnboardingGate, readResearchGate } from "../lib/onboarding";
import { proxy } from "../proxy";
const SESSION_COOKIE = `${AUTH_COOKIE_PREFIX}.session_token=abc.def`;
@@ -174,28 +169,31 @@ describe("proxy", () => {
).toBeNull();
});
- it("asks once, then remembers", async () => {
+ it("asks again on every request, and remembers nothing", async () => {
const calls = setup();
const first = await proxy(request("/companies", [SESSION_COOKIE]));
- for (const name of [ONBOARDING_COOKIE, RESEARCH_COOKIE]) {
- const marker = first.cookies.get(name);
- expect(marker?.value).toBe("1");
- expect(marker?.httpOnly).toBe(true);
- }
-
+ expect([...first.cookies.getAll()]).toHaveLength(0);
expect(calls).toEqual({ workspace: 1, research: 1 });
- await proxy(
- request("/companies", [
- SESSION_COOKIE,
- `${ONBOARDING_COOKIE}=1`,
- `${RESEARCH_COOKIE}=1`,
- ]),
- );
+ await proxy(request("/companies", [SESSION_COOKIE]));
- expect(calls).toEqual({ workspace: 1, research: 1 });
+ expect(calls).toEqual({ workspace: 2, research: 2 });
+ });
+
+ it("notices when the answer changes underneath it", async () => {
+ setup();
+ expect(
+ redirectedTo(await proxy(request("/companies", [SESSION_COOKIE]))),
+ ).toBeNull();
+
+ // A reset database, a removed key: the browser is carrying nothing that
+ // could keep saying the gate was satisfied.
+ setup({ onboarded: false });
+ expect(
+ redirectedTo(await proxy(request("/companies", [SESSION_COOKIE]))),
+ ).toBe("/onboarding");
});
it("takes a settled rep off both setup pages", async () => {
@@ -236,8 +234,6 @@ describe("proxy", () => {
const response = await proxy(request("/companies", [SESSION_COOKIE]));
expect(redirectedTo(response)).toBeNull();
- expect(response.cookies.get(ONBOARDING_COOKIE)).toBeUndefined();
- expect(response.cookies.get(RESEARCH_COOKIE)).toBeUndefined();
});
});
@@ -260,29 +256,19 @@ describe("the research key gate", () => {
).toBeNull();
});
- it("asks the first question first", async () => {
- const calls = setup({ onboarded: false, configured: false });
+ it("asks the first question first when both are outstanding", async () => {
+ setup({ onboarded: false, configured: false });
expect(
redirectedTo(await proxy(request("/companies", [SESSION_COOKIE]))),
).toBe("/onboarding");
-
- expect(calls.research).toBe(0);
- });
-
- it("does not settle the marker for a rep still being asked", async () => {
- setup({ configured: false });
-
- const response = await proxy(request("/companies", [SESSION_COOKIE]));
-
- expect(response.cookies.get(RESEARCH_COOKIE)).toBeUndefined();
});
- it("remembers the workspace answer even while the key is outstanding", async () => {
- setup({ configured: false });
-
- const response = await proxy(request("/companies", [SESSION_COOKIE]));
+ it("sends them on to the key once the workspace is named", async () => {
+ setup({ onboarded: true, configured: false });
- expect(response.cookies.get(ONBOARDING_COOKIE)?.value).toBe("1");
+ expect(
+ redirectedTo(await proxy(request("/onboarding", [SESSION_COOKIE]))),
+ ).toBe("/onboarding/research");
});
});
diff --git a/apps/app/test/workspace-label.spec.ts b/apps/app/test/workspace-label.spec.ts
new file mode 100644
index 00000000..22dcf4cf
--- /dev/null
+++ b/apps/app/test/workspace-label.spec.ts
@@ -0,0 +1,29 @@
+import { describe, expect, it } from "bun:test";
+import { DEFAULT_WORKSPACE_NAME } from "@crm/auth";
+import { workspaceLabel } from "../components/app-header";
+
+describe("what the header calls this install", () => {
+ it("does not say CRM twice before anybody has named the workspace", () => {
+ expect(workspaceLabel(DEFAULT_WORKSPACE_NAME)).toBe("CRM");
+ });
+
+ it("falls back to CRM while the workspace is still loading", () => {
+ expect(workspaceLabel(undefined)).toBe("CRM");
+ expect(workspaceLabel("")).toBe("CRM");
+ expect(workspaceLabel(" ")).toBe("CRM");
+ });
+
+ it("names the company once it has one", () => {
+ expect(workspaceLabel("Acme")).toBe("Acme CRM");
+ expect(workspaceLabel(" Acme ")).toBe("Acme CRM");
+ });
+
+ it("does not repeat a company that already ends in CRM", () => {
+ expect(workspaceLabel("Acme CRM")).toBe("Acme CRM");
+ expect(workspaceLabel("Acme crm")).toBe("Acme crm");
+ });
+
+ it("still appends to a name that merely contains the letters", () => {
+ expect(workspaceLabel("CRMSoft")).toBe("CRMSoft CRM");
+ });
+});
diff --git a/docs/api.md b/docs/api.md
index 90db5121..7a9a78a8 100644
--- a/docs/api.md
+++ b/docs/api.md
@@ -136,32 +136,41 @@ called, who works here, and what do we sell — and for nothing else.
[`@crm/db/workspace`](../packages/db/src/workspace.ts) are the only readers
and the only writer; `markOnboarded` keeps the first answer and preserves
every other key, because the blob is the plugin's, not ours.
-- **The gate is `proxy.ts`, and it is answered once per browser.** It used to
- live in `(app)/layout.tsx`, which meant a `workspace.get` round trip on every
- navigation into the app to re-establish a fact that changes once in the life
- of an install — and a second, opposing redirect on the `/onboarding` page to
- stop the first one looping. Two redirects pointing at each other is not a
- gate, it is a latch waiting for the two reads to disagree.
+- **The gate is `proxy.ts`, and it asks the server every time.** It used to
+ live in `(app)/layout.tsx`, with a second, opposing redirect on the
+ `/onboarding` page to stop the first one looping — two redirects pointing at
+ each other is not a gate, it is a latch waiting for the two reads to
+ disagree.
- **`getSessionCookie()` decides signed-in, not a session lookup.** That is
Better Auth's documented optimistic check for proxy, and it is all a
redirect needs; every page behind it still resolves the real session
server-side through `requireGoogleAccess()`.
- - **The answer is cached in an httpOnly `crm.onboarded` cookie**, so the
- common path costs nothing and the tRPC read happens once — twice for the
- person who actually fills the form in, since the cookie lands on the
- navigation after the mutation. The proxy is the only writer; the form does
- not set it, because two writers is how this went wrong in the first place.
- Forging the cookie skips a setup form and grants nothing, which is why it
- can be a cookie at all.
+ - **Nothing is cached in a cookie, and that is the second thing this got
+ wrong.** The answers were kept in httpOnly `crm.onboarded` and
+ `crm.research` markers with a year's life, on the reasoning that they
+ change once in the life of an install. They do not: reset the database and
+ both facts revert while the browser goes on insisting the gate was
+ satisfied — so a fresh workspace was never asked to name itself and never
+ asked for a key, and nothing anywhere said why. A cache with no
+ invalidation is only correct for a fact that cannot go back, and neither of
+ these is one.
+ - **Both reads run concurrently**, so asking every time costs one round trip
+ rather than two. Which question is asked *first* is still decided in order
+ — a rep who has not named the workspace is sent to `/onboarding`, not to
+ the key form — but there is no reason to wait for that answer before
+ starting the other read.
+ - **If the cost ever matters, cache it in the API**, where there is a place
+ to invalidate from: `settings.setResearchKey` and `WorkspaceService.update`
+ are the only two writers, and `cache-manager` is already the documented
+ pattern for exactly that shape. Do not put it back in the browser.
- **`/sign-in`, `/grant-access` and `/eve` are ungated.**
`requireGoogleAccess()` redirects to `/grant-access`, so gating it would
ping-pong against the onboarding redirect for anyone who signed in without
both scopes.
- - **An unreachable API fails open.** `readOnboardingGate` returns `unknown`
- on a non-200, a timeout or a parse failure, and an unknown gate lets the
- request through without writing the cookie. The alternative is an install
- that cannot reach its own API redirecting every request to a form that
- cannot be submitted.
+ - **An unreachable API fails open.** Each read returns `unknown` on a
+ non-200, a timeout or a parse failure, and an unknown gate lets the request
+ through. The alternative is an install that cannot reach its own API
+ redirecting every request to a form that cannot be submitted.
- **There is a second gate behind the first**, `/onboarding/research`, which
asks for the Context API key that gives the agent somewhere to look — see
[the environment rules](./environment.md#the-context-key-is-asked-for-not-configured).
@@ -196,6 +205,12 @@ called, who works here, and what do we sell — and for nothing else.
is empty with that behind it. It used to be derived from the sign-in domain,
which put `Trycomp` in the box as though somebody had typed it, and a guess
presented as an answer is a guess that gets accepted.
+ - **Anything printing the name beside the product name has to allow for
+ that.** The header renders `<name> CRM`, so the placeholder read `CRM CRM`
+ until somebody typed something else. `workspaceLabel` in
+ `components/app-header.tsx` tests the name rather than comparing it to the
+ default, because a workspace genuinely called `Acme CRM` has the same
+ problem and no comparison to `DEFAULT_WORKSPACE_NAME` would catch it.
- **The website is the field with a consequence.** Saving it queues the agent's
`workspace-profile` task, and what comes back is read into the opening context
of every session the agent runs — see