Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions apps/web/CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ bun run generate-routes # tsr generate — regenerates routeTree.gen.ts
- Outside it: `index.tsx` (a redirect into the workspace; the public pages live in `apps/site`, see `docs/domains/deployment.md`), `login.tsx`, `choose-organization.tsx` (the workspace chooser for a link such as `/:org/settings`; see `docs/domains/authentication.md`), `accept-invite/$invitationId.tsx`, `no-access.tsx`, `device.tsx` (approves a CLI login) and `cli/` (the install scripts and binary downloads).
- Server routes: `api/auth/$.ts` (better-auth), `api/login.ts`, `api/mcp-login.ts`, `api/github/setup.ts`, `api/slack/callback.ts`, `api/files/$.ts`, `api/assistant/stream.ts`, `api/mcp/$orgSlug.ts`, `[.]well-known/oauth-*.ts`, `api/v1/projects` + `api/v1/time-entries` (cookie-authed REST reads), and `api/v1/{meta,me,session}`, `api/v1/me/devices` (the mobile app's phone, see `docs/domains/mobile.md`) + `api/v1/orgs/$orgSlug/*` (the CLI's API). `api/v1/openapi[.]json.ts` serves the OpenAPI document that `lib/openapi.ts` builds, and `api-docs.tsx` renders it with Scalar. **A new `api/v1` route needs an entry in `OPERATIONS`** — `lib/openapi.test.ts` fails until the two lists match, and each response schema there is checked against its `@farmer/core/api` type at compile time. That API takes two bearer credentials — a device-flow session token and a personal API token (`fmr_…`, Preferences → API tokens, `components/api-tokens-settings.tsx`); `docs/domains/api-tokens.md` has the rules, including the read-only 403 in `serve` and the `session` scheme that lets `/api-docs` send requests as the signed-in reader (`?org=` on the OpenAPI route; never add CORS headers to `api/v1`). All of that auth lives in `server/api-auth.ts` — deliberately NOT `server/auth.ts`, see the client-bundle rule below.
- `reports.tsx` is the shell. Its four tabs — Time, Overtime, Tracking (`compliance`) and Absence — are declared in `components/reports/search.ts` and live in `components/reports/`. `periodSearch` there is shared with the project page.
- `src/client.tsx` — the custom client entry that TanStack Start picks up by name. It is the default entry plus an `onRecoverableError` that captures hydration errors in PostHog (see `docs/domains/deployment.md`).
- `src/server/` — thin `createServerFn` wrappers, one file per aggregate, mirroring `services/`. **Auth is attached via middleware** (`sessionMiddleware` / `orgMiddleware` / `orgAdminMiddleware` from `server/auth.ts`), read from the handler's `context` — never by calling `requireOrgContext()` inline, so the protection is part of the function's declared shape. `auth.ts` itself is the only place the bare helpers are called, because route `beforeLoad`s need them. `orgMiddleware` re-checks membership inside its `.server()` callback rather than in a shared helper: a top-level function body in `auth.ts` ships to the browser, so a deferred `import("@farmer/core/services")` there becomes a real client chunk.
- `src/queries/` — TanStack Query `queryOptions` factories, one per aggregate; loaders prefetch, components read via `useSuspenseQuery`. **Every key names its organization**: factories take the slug first (`timeEntriesRangeQuery(orgSlug, from, to)`) and spread their root from `queryKeys(orgSlug)` in `queries/keys.ts`; invalidations name the same root. Components get the slug from `useOrgSlug()`, loaders from `params.orgSlug`. Never write a bare `queryKey: ["…"]` literal and never drop the org — an org-blind key is an answer from the previous workspace. Server functions are deliberately NOT generated from a shared declaration — see `docs/adr/0001-no-server-function-generator.md`.
- `src/components/ui/` — shadcn on **Base UI** (`@base-ui/react`), not Radix (`components.json` style is `base-nova`). Composition uses the `render` prop, not `asChild`. The project picker (grouped by client) and task picker (grouped by `taskGroup`) are in `components/pickers/`. The task picker leaves out the tasks the person switched off (`pickers/your-tasks.tsx`, also Preferences → Your tasks), search included, except the task already chosen and Recent; its grouped list ends in Edit list.
Expand Down
42 changes: 42 additions & 0 deletions apps/web/src/client.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import { StartClient } from "@tanstack/react-start/client";
import posthog from "posthog-js";
import { StrictMode, startTransition } from "react";
import { type HydrationOptions, hydrateRoot } from "react-dom/client";

const TRANSLATED = ["translated-ltr", "translated-rtl"];

/**
* Report an error that React recovered from, such as a hydration mismatch
* (React error #418). The production message names no component, so the
* event holds the component stack. Chrome's page translation edits the DOM
* and the `lang` attribute, so the event says if it was on.
*
* Not `reportError`: React's default handler calls it, and the `error` event
* that it fires is already captured by posthog-js. This handler replaces
* the default, so each error is captured one time.
*/
const onRecoverableError: NonNullable<
HydrationOptions["onRecoverableError"]
> = (error, errorInfo) => {
if (posthog.__loaded) {
const classes = document.documentElement.classList;
posthog.captureException(error, {
react_component_stack: errorInfo.componentStack,
html_lang: document.documentElement.lang,
html_translated: TRANSLATED.some((name) => classes.contains(name)),
pathname: location.pathname,
});
}
console.error(error);
};

// The default entry of TanStack Start, plus `onRecoverableError`.
startTransition(() => {
hydrateRoot(
document,
<StrictMode>
<StartClient />
</StrictMode>,
{ onRecoverableError },
);
});
129 changes: 126 additions & 3 deletions apps/web/src/lib/capture-failure.test.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,17 @@
import { describe, expect, test } from "bun:test";
import { describe, expect, spyOn, test } from "bun:test";

import { captureFailure } from "./capture-failure";
import { PostHog } from "posthog-node";

import { captureFailure, SLOW_SERVER_FN_MS } from "./capture-failure";
import * as posthogServer from "./posthog-server";

const META = { id: "abc", name: "fn", filename: "file.ts" };

const run = (error: Error) =>
captureFailure(
{
next: () => Promise.reject(error),
serverFnMeta: { name: "fn", filename: "file.ts" },
serverFnMeta: META,
},
// No request here: the capture fails, and the error must still come out.
() => {
Expand All @@ -26,3 +31,121 @@ describe("captureFailure", () => {
expect(await run(error).catch((e) => e)).toBe(error);
});
});

describe("slow server functions", () => {
const client = new PostHog("test-token", { disabled: true });
const capture = spyOn(client, "capture").mockImplementation(() => {});

/** Run a call that takes `ms` on a fake clock, with the request `headers`. */
const call = async (ms: number, headers: Headers, fails = false) => {
let clock = 0;
const now = spyOn(performance, "now").mockImplementation(() => clock);
try {
await captureFailure(
{
next: () => {
clock += ms;
return fails ? Promise.reject(new Error("x")) : Promise.resolve(1);
},
serverFnMeta: META,
},
() => headers,
).catch(() => {});
} finally {
now.mockRestore();
}
};

const events = () => capture.mock.calls.map(([message]) => message);

/** The report is a background task: wait until PostHog got an event of
* this duration. Reports run in call order, so earlier ones are in. */
const waitForEventOf = async (durationMs: number) => {
const deadline = Date.now() + 5000;
while (
!events().some((e) => e.properties?.duration_ms === durationMs) &&
Date.now() < deadline
) {
await Bun.sleep(5);
}
return events();
};

const withClient = async (run: () => Promise<void>) => {
capture.mockClear();
const getClient = spyOn(posthogServer, "getPostHogClient").mockReturnValue(
client,
);
try {
await run();
} finally {
getClient.mockRestore();
}
};

test("a fast call sends nothing and a slow call sends one event", () =>
withClient(async () => {
await call(SLOW_SERVER_FN_MS - 1, new Headers());
await call(SLOW_SERVER_FN_MS, new Headers());
const sent = await waitForEventOf(SLOW_SERVER_FN_MS);
expect(sent).toHaveLength(1);
expect(sent[0]).toMatchObject({
event: "server_fn_slow",
properties: {
server_fn_id: "abc",
server_fn_name: "fn",
duration_ms: SLOW_SERVER_FN_MS,
threw: false,
},
});
}));

test("a slow call that throws is reported as one that threw", () =>
withClient(async () => {
await call(SLOW_SERVER_FN_MS, new Headers(), true);
const sent = await waitForEventOf(SLOW_SERVER_FN_MS);
expect(sent).toMatchObject([{ properties: { threw: true } }]);
}));

/** A call that ends after `endMs` real time; the pending mark is `markMs`. */
const lateCall = async (markMs: number, endMs: number, headers: Headers) => {
await captureFailure(
{
next: () => Bun.sleep(endMs).then(() => 1),
serverFnMeta: META,
},
() => headers,
markMs,
);
};

test("a call still pending at the mark sends one pending event", () =>
withClient(async () => {
await lateCall(10, 60, new Headers());
const sent = await waitForEventOf(10);
// The finish of the same call sends no second event.
await Bun.sleep(50);
expect(events()).toHaveLength(1);
expect(sent[0]).toMatchObject({
event: "server_fn_slow",
properties: { server_fn_id: "abc", duration_ms: 10, pending: true },
});
}));

test("a call that ends before the mark sends no pending event", () =>
withClient(async () => {
await lateCall(50, 1, new Headers());
await Bun.sleep(100);
expect(events()).toHaveLength(0);
}));

test("two slow calls of one request send one event", () =>
withClient(async () => {
const headers = new Headers();
await call(SLOW_SERVER_FN_MS, headers);
await call(SLOW_SERVER_FN_MS, headers);
// Another request gets its own event.
await call(2 * SLOW_SERVER_FN_MS, new Headers());
expect(await waitForEventOf(2 * SLOW_SERVER_FN_MS)).toHaveLength(2);
}));
});
64 changes: 52 additions & 12 deletions apps/web/src/lib/capture-failure.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import type { ServerFnCall } from "./posthog-api";

/**
* Send the unexpected failure of a server function to PostHog error tracking.
*
Expand All @@ -6,7 +8,10 @@
* it: it runs after the throw and is never awaited. A failure of the capture
* is logged and dropped. Only a fault is captured: see `isServerFnFault`. The
* person is read from the session because the middleware runs before
* `orgMiddleware`, so it has no `ctx`.
* `orgMiddleware`, so it has no `ctx`. A call that takes `SLOW_SERVER_FN_MS`
* or more is reported in the same way, as a `server_fn_slow` event, also
* when it throws. A call still pending at `PENDING_SERVER_FN_MS` is reported
* then, with `pending: true`, and not again when it ends.
*
* `start.ts` reaches this module with a deferred `import()` inside the
* middleware callback, which TanStack strips from the client bundle. A static
Expand All @@ -18,34 +23,69 @@ export const captureFailure = async <T>(
serverFnMeta,
}: {
next: () => Promise<T>;
serverFnMeta: { name: string; filename: string };
serverFnMeta: { id: string; name: string; filename: string };
},
readHeaders: () => Headers,
pendingMs: number = PENDING_SERVER_FN_MS,
): Promise<T> => {
const start = performance.now();
let error: Error | null = null;
let threw = false;
let pendingReported = false;
// A call that never ends sends no report from `finally`, so report it here.
const timer = setTimeout(() => {
pendingReported = true;
reportInBackground(
{ error: null, threw: false, slowMs: pendingMs, pending: true },
serverFnMeta,
readHeaders,
);
}, pendingMs);
timer.unref();
try {
return await next();
} catch (error) {
if (error instanceof Error) {
reportInBackground(error, serverFnMeta, readHeaders);
}
throw error;
} catch (thrown) {
threw = true;
if (thrown instanceof Error) error = thrown;
throw thrown;
} finally {
clearTimeout(timer);
const durationMs = performance.now() - start;
reportInBackground(
{
error,
threw,
slowMs:
!pendingReported && durationMs >= SLOW_SERVER_FN_MS
? durationMs
: null,
pending: false,
},
serverFnMeta,
readHeaders,
);
}
};

/** A call at or over this duration is sent as a `server_fn_slow` event. */
export const SLOW_SERVER_FN_MS = 1000;

/** A call still pending at this mark is sent as a `server_fn_slow` event. */
export const PENDING_SERVER_FN_MS = 10_000;

const reportInBackground = (
error: Error,
meta: { name: string; filename: string },
call: ServerFnCall,
meta: { id: string; name: string; filename: string },
readHeaders: () => Headers,
): void => {
if (!call.error && call.slowMs === null) return;
const fail = (captureError: Error) =>
console.error("server function capture failed", captureError);
try {
// Read at once, while the request context is current.
const headers = readHeaders();
void import("./posthog-api")
.then(({ reportServerFnError }) =>
reportServerFnError(error, headers, meta),
)
.then(({ reportServerFnCall }) => reportServerFnCall(headers, meta, call))
.catch(fail);
} catch (captureError) {
console.error("server function capture failed", captureError);
Expand Down
Loading
Loading