Skip to content

A one-of-a-kind resume builder that keeps your privacy in mind. Completely secure, customizable, portable, open-source and free forever. Try it out today!

perf(applications): reduce list payloads and load details on demand (#3684)

Lihan YANG0fd5e4e7ed3c
diff --git a/apps/mobile/scripts/applications-summary.test.mjs b/apps/mobile/scripts/applications-summary.test.mjs
new file mode 100644
index 000000000..6c888a3b7
--- /dev/null
+++ b/apps/mobile/scripts/applications-summary.test.mjs
@@ -0,0 +1,396 @@
+import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
+import { createRequire } from "node:module";
+
+const serverRequire = createRequire(new URL("../../server/package.json", import.meta.url));
+const { transformSync } = createRequire(serverRequire.resolve("tsx"))("esbuild");
+const { QueryClient, QueryObserver } = createRequire(new URL("../package.json", import.meta.url))(
+ "@tanstack/react-query",
+);
+
+function load(path, mocks = {}) {
+ const module = { exports: {} };
+ const code = transformSync(readFileSync(new URL("../src/" + path, import.meta.url), "utf8"), {
+ loader: path.endsWith(".tsx") ? "tsx" : "ts",
+ format: "cjs",
+ }).code;
+ new Function("require", "module", "exports", code)(
+ (name) => {
+ assert.ok(name in mocks, "Missing boundary: " + name);
+ return mocks[name];
+ },
+ module,
+ module.exports,
+ );
+ return module.exports;
+}
+
+const stages = load("features/applications/stages.ts", {
+ "@lingui/core/macro": { t: String },
+});
+const nextStep = load("features/applications/next-step.ts", {
+ "./stages": stages,
+ "@/ui": {},
+ "@lingui/core/macro": { plural: (value, forms) => forms.other.replace("#", String(value)), t: String },
+});
+const list = load("features/applications/list.ts", {
+ "./next-step": nextStep,
+ "./stages": stages,
+});
+const schedule = {
+ zonedParts(value) {
+ const date = new Date(value);
+ return { date: date.toISOString().slice(0, 10) };
+ },
+};
+const calendar = load("features/applications-board/calendar.ts", {
+ "../reminders/schedule.ts": schedule,
+});
+const insights = load("features/applications-board/insights.ts", {
+ "../reminders/schedule.ts": schedule,
+});
+
+const stage = (id, value, at) => ({ id, type: "stage", stage: value, at });
+const interview = (id, at) => ({
+ id,
+ type: "interview",
+ at,
+ kind: "technical",
+ durationMinutes: 60,
+ location: "Remote",
+ notes: "Bring examples",
+ participants: [],
+ audience: "other",
+ timezone: "UTC",
+});
+const full = [
+ {
+ id: "app-a",
+ company: "Acme",
+ role: "Engineer",
+ location: "Remote",
+ salary: null,
+ status: "interview",
+ closedReason: null,
+ resumeId: "resume-a",
+ coverLetterId: null,
+ requirements: ["TypeScript"],
+ source: "Referral",
+ sourceUrl: "https://example.com/job",
+ jobDescription: "large posting body",
+ postingSource: null,
+ matchScore: 90,
+ aiMetadata: { extracted: true },
+ notes: "private note",
+ resumeFileUrl: null,
+ resumeFileName: null,
+ coverLetterUrl: null,
+ coverLetterName: null,
+ followUpAt: null,
+ followUpNote: null,
+ tags: ["priority"],
+ contacts: [{ name: "Recruiter", role: "", type: "", email: "[email protected]", phone: "" }],
+ activity: [
+ stage("stage-a", "applied", "2026-01-01"),
+ stage("stage-b", "interview", "2026-01-03"),
+ interview("interview-a", "2026-01-05T10:00:00.000Z"),
+ { id: "note-a", type: "note", at: "2026-01-02", text: "private note" },
+ ],
+ appliedAt: new Date("2026-01-01T00:00:00.000Z"),
+ createdAt: new Date("2026-01-01T00:00:00.000Z"),
+ updatedAt: new Date("2026-01-04T00:00:00.000Z"),
+ },
+ {
+ id: "app-b",
+ company: "Beta",
+ role: "Designer",
+ location: null,
+ salary: null,
+ status: "closed",
+ closedReason: "not-selected",
+ resumeId: null,
+ coverLetterId: null,
+ requirements: [],
+ source: "Inbound",
+ sourceUrl: null,
+ jobDescription: "closed posting",
+ postingSource: null,
+ matchScore: null,
+ aiMetadata: null,
+ notes: "closed note",
+ resumeFileUrl: null,
+ resumeFileName: null,
+ coverLetterUrl: null,
+ coverLetterName: null,
+ followUpAt: null,
+ followUpNote: null,
+ tags: [],
+ contacts: [],
+ activity: [
+ stage("stage-c", "applied", "2026-01-02"),
+ { id: "note-b", type: "note", at: "2026-01-03", text: "closed" },
+ ],
+ appliedAt: new Date("2026-01-02T00:00:00.000Z"),
+ createdAt: new Date("2026-01-02T00:00:00.000Z"),
+ updatedAt: new Date("2026-01-03T00:00:00.000Z"),
+ },
+];
+
+const omittedSummaryFields = new Set([
+ "jobDescription",
+ "requirements",
+ "postingSource",
+ "aiMetadata",
+ "notes",
+ "resumeFileUrl",
+ "resumeFileName",
+ "coverLetterUrl",
+ "coverLetterName",
+ "sentResumeVersionId",
+ "sentCoverLetterVersionId",
+ "sentCheckScore",
+]);
+const summary = full.map((application) =>
+ Object.fromEntries(
+ Object.entries(application)
+ .filter(([key]) => !omittedSummaryFields.has(key))
+ .map(([key, value]) => [key, key === "activity" ? value.filter((entry) => entry.type !== "note") : value]),
+ ),
+);
+const fullFiltered = list.filterApplications(full, { search: "engineer", tag: "", showClosed: false });
+const summaryFiltered = list.filterApplications(summary, { search: "engineer", tag: "", showClosed: false });
+assert.deepEqual(
+ summaryFiltered.map(({ id }) => id),
+ fullFiltered.map(({ id }) => id),
+);
+
+const fullGroups = list.groupApplications(full, "next", "desc", new Date("2026-01-04T00:00:00.000Z"));
+const summaryGroups = list.groupApplications(summary, "next", "desc", new Date("2026-01-04T00:00:00.000Z"));
+assert.deepEqual(
+ summaryGroups.map((group) => [group.status, group.data.map(({ id }) => id)]),
+ fullGroups.map((group) => [group.status, group.data.map(({ id }) => id)]),
+);
+
+const fullEvents = calendar.collectEvents(full, "UTC");
+const summaryEvents = calendar.collectEvents(summary, "UTC");
+assert.deepEqual(
+ summaryEvents.map(({ id, day }) => [id, day]),
+ fullEvents.map(({ id, day }) => [id, day]),
+);
+
+const tailored = (application) => application.resumeId === "resume-a";
+const fullOutcomes = insights.computeOutcomes(full, tailored);
+const summaryOutcomes = insights.computeOutcomes(summary, tailored);
+assert.deepEqual(summaryOutcomes, fullOutcomes);
+assert.deepEqual(insights.countSources(summary), insights.countSources(full));
+assert.deepEqual(
+ insights.computeTimeline(summary, { now: new Date("2026-01-10T00:00:00.000Z"), timeZone: "UTC", weekStartsOn: 0 }),
+ insights.computeTimeline(full, { now: new Date("2026-01-10T00:00:00.000Z"), timeZone: "UTC", weekStartsOn: 0 }),
+);
+
+const orpc = {
+ applications: {
+ listSummary: { queryOptions: ({ input }) => ({ queryKey: ["applications", "summary", input] }) },
+ getById: { queryOptions: ({ input }) => ({ queryKey: ["applications", "detail", input] }) },
+ create: { mutationOptions: () => ({}) },
+ update: { mutationOptions: () => ({}) },
+ delete: { mutationOptions: () => ({}) },
+ bulkUpdate: { mutationOptions: () => ({}) },
+ bulkDelete: { mutationOptions: () => ({}) },
+ import: { mutationOptions: () => ({}) },
+ stats: { queryKey: () => ["applications", "stats"] },
+ tags: { queryKey: () => ["applications", "tags"] },
+ key: () => ["applications"],
+ },
+ documents: { list: { key: () => ["documents"] } },
+};
+let capturedQuery;
+let listRows = [{ ...summary[0], initialDetail: full[0] }];
+const invalidations = [];
+const cleanups = [];
+const detailKey = ["applications", "detail", { id: "app-a" }, "server-a"];
+const queryClient = new QueryClient();
+const originalInvalidateQueries = queryClient.invalidateQueries.bind(queryClient);
+queryClient.invalidateQueries = async (filters) => {
+ invalidations.push(filters.queryKey);
+ return originalInvalidateQueries(filters);
+};
+const queries = load("features/applications/queries.ts", {
+ react: {
+ useEffect: (effect) => {
+ const cleanup = effect();
+ if (cleanup) cleanups.push(cleanup);
+ },
+ useCallback: (callback) => callback,
+ useRef: (value) => ({ current: value }),
+ },
+ "@tanstack/react-query": {
+ useMutation: (options) => options,
+ useQuery: (options) => {
+ capturedQuery = options;
+ return options.queryKey?.[1] === "summary" ? { ...options, data: listRows, dataUpdatedAt: 500 } : options;
+ },
+ useQueryClient: () => queryClient,
+ },
+ "@/api/client": { orpc },
+ "@/auth/session": { getServer: () => "server-a", useSession: () => ({ status: "signed-in", server: "server-a" }) },
+ "@/features/reminders": { syncReminders: async () => undefined },
+});
+const syncListRows = () => {
+ queryClient.setQueryData(queries.applicationsListQueryKey("server-a"), listRows, { updatedAt: 500 });
+};
+syncListRows();
+
+assert.deepEqual(queries.applicationsListQueryOptions("server-a").queryKey, [
+ "applications",
+ "summary",
+ { includeInitialDetails: 3 },
+ "server-a",
+]);
+assert.deepEqual(queries.applicationsListQueryOptions("server-b").queryKey, [
+ "applications",
+ "summary",
+ { includeInitialDetails: 3 },
+ "server-b",
+]);
+assert.deepEqual(queries.applicationDetailQueryOptions("app-a", "server-a").queryKey, detailKey);
+queries.useApplication("app-a");
+assert.deepEqual(capturedQuery.initialData, full[0]);
+assert.equal(capturedQuery.staleTime, undefined);
+assert.equal(capturedQuery.initialDataUpdatedAt, 500);
+listRows = [{ ...summary[0], initialDetail: { ...full[0], status: "closed" } }];
+syncListRows();
+queries.useApplication("app-a");
+assert.equal(capturedQuery.initialData, undefined);
+const oldDetail = { ...full[0], notes: "old", updatedAt: new Date("2026-01-01T00:00:00.000Z") };
+const newerDetail = { ...full[0], notes: "newer", updatedAt: new Date("2026-01-03T00:00:00.000Z") };
+queryClient.setQueryData(detailKey, newerDetail, { updatedAt: 700 });
+listRows = [{ ...summary[0], initialDetail: oldDetail }];
+syncListRows();
+queries.useApplications();
+await Promise.resolve();
+assert.equal(queryClient.getQueryData(detailKey).notes, "newer");
+queryClient.setQueryData(detailKey, oldDetail, { updatedAt: 700 });
+listRows = [{ ...summary[0], initialDetail: newerDetail }];
+syncListRows();
+queries.useApplications();
+await new Promise((resolve) => setImmediate(resolve));
+assert.equal(queryClient.getQueryData(detailKey).notes, "newer");
+queryClient.setQueryData(detailKey, oldDetail);
+let resolveOld;
+const oldRequest = queryClient.fetchQuery({
+ queryKey: detailKey,
+ queryFn: () =>
+ new Promise((resolve) => {
+ resolveOld = resolve;
+ }),
+});
+queries.useApplications();
+resolveOld(oldDetail);
+await oldRequest.catch(() => undefined);
+assert.equal(queryClient.getQueryData(detailKey).notes, "newer");
+const mutations = queries.useApplicationMutations();
+mutations.update.onSettled(undefined, undefined, { id: "app-a" });
+assert.ok(invalidations.some((key) => key[0] === "applications"));
+const observerClient = new QueryClient();
+const cachedDetail = { ...full[0], resumeFileUrl: "/uploads/resume.pdf", resumeFileName: "resume.pdf" };
+const observerKey = ["application-detail", cachedDetail.id];
+observerClient.setQueryData(observerKey, cachedDetail);
+const observer = new QueryObserver(observerClient, {
+ queryKey: observerKey,
+ queryFn: async () => {
+ throw new Error("refresh failed");
+ },
+ retry: false,
+ staleTime: 0,
+});
+await observer.refetch();
+const failedRefresh = observer.getCurrentResult();
+assert.equal(failedRefresh.isError, true);
+assert.equal(failedRefresh.data?.id, cachedDetail.id);
+assert.equal(Boolean(failedRefresh.data), true);
+assert.equal(failedRefresh.data?.resumeFileUrl, "/uploads/resume.pdf");
+observer.destroy();
+observerClient.clear();
+const refreshBase = { ...full[0], notes: "cached newer", updatedAt: new Date("2026-01-03T00:00:00.000Z") };
+queryClient.setQueryData(detailKey, refreshBase, { updatedAt: 700 });
+let resolveRefresh;
+const refreshObserver = new QueryObserver(queryClient, {
+ queryKey: detailKey,
+ queryFn: () =>
+ new Promise((resolve) => {
+ resolveRefresh = resolve;
+ }),
+ retry: false,
+});
+const unsubscribeRefresh = refreshObserver.subscribe(() => {});
+const refreshRequest = refreshObserver.refetch();
+await Promise.resolve();
+assert.equal(refreshObserver.getCurrentResult().fetchStatus, "fetching");
+listRows = [{ ...summary[0], initialDetail: oldDetail }];
+syncListRows();
+queries.useApplications();
+assert.equal(refreshObserver.getCurrentResult().fetchStatus, "fetching");
+const refreshed = { ...refreshBase, notes: "refreshed latest", updatedAt: new Date("2026-01-05T00:00:00.000Z") };
+resolveRefresh(refreshed);
+await refreshRequest;
+assert.equal(queryClient.getQueryData(detailKey).notes, "refreshed latest");
+unsubscribeRefresh();
+refreshObserver.destroy();
+queryClient.clear();
+const prefetchCalls = [];
+const pendingPrefetches = new Map();
+orpc.applications.getById.queryOptions = ({ input }) => ({
+ queryKey: ["applications", "detail", input],
+ queryFn: () => {
+ prefetchCalls.push(input.id);
+ return new Promise((resolve, reject) => pendingPrefetches.set(input.id, { resolve, reject }));
+ },
+});
+queryClient.setDefaultOptions({ queries: { retry: false } });
+const onVisible = queries.useApplicationDetailPrefetch();
+const visible = (...ids) =>
+ onVisible({ viewableItems: [{ item: { title: "Interview" } }, ...ids.map((id) => ({ item: { id } }))] });
+const waitForPrefetch = () => new Promise((resolve) => setTimeout(resolve, 150));
+const finishPrefetches = async () => {
+ for (const [id, pending] of pendingPrefetches) pending.resolve({ ...full[0], id });
+ pendingPrefetches.clear();
+ await new Promise((resolve) => setImmediate(resolve));
+};
+visible("skipped");
+visible("visible-a", "visible-b", "not-in-first-two");
+await waitForPrefetch();
+assert.deepEqual(prefetchCalls, ["visible-a", "visible-b"]);
+visible("visible-c", "visible-d");
+await waitForPrefetch();
+assert.equal(prefetchCalls.length, 2, "only two detail requests may run concurrently");
+await finishPrefetches();
+for (let offset = 2; offset < 14; offset += 2) {
+ visible("visible-" + offset, "visible-" + (offset + 1));
+ await waitForPrefetch();
+ await finishPrefetches();
+}
+assert.equal(prefetchCalls.length, 14, "completed requests free slots for later visible applications");
+visible("visible-a", "visible-b");
+await waitForPrefetch();
+assert.equal(prefetchCalls.length, 14, "cached details do not need another prefetch");
+queryClient.clear();
+const onRetryVisible = queries.useApplicationDetailPrefetch();
+const retryVisible = () => onRetryVisible({ viewableItems: [{ item: { id: "retry" } }] });
+retryVisible();
+await waitForPrefetch();
+pendingPrefetches.get("retry").reject(new Error("temporary failure"));
+pendingPrefetches.clear();
+await new Promise((resolve) => setImmediate(resolve));
+retryVisible();
+await waitForPrefetch();
+assert.equal(prefetchCalls.filter((id) => id === "retry").length, 2, "failed prefetch does not block retry");
+await finishPrefetches();
+onRetryVisible({ viewableItems: [{ item: { id: "unmounted" } }] });
+for (const cleanup of cleanups) cleanup();
+await waitForPrefetch();
+assert.ok(!prefetchCalls.includes("unmounted"), "unmount cancels the pending prefetch timer");
+queryClient.clear();
+console.log(
+ "PASS summary preserves filtered/grouped/calendar/insights results, detail lookup, and server-isolated query keys",
+);
diff --git a/apps/mobile/scripts/experience.test.mjs b/apps/mobile/scripts/experience.test.mjs
index 0da6e8843..cf2558c84 100644
--- a/apps/mobile/scripts/experience.test.mjs
+++ b/apps/mobile/scripts/experience.test.mjs
@@ -337,7 +337,11 @@ const { ApplicationsListScreen } = load("features/applications/list-screen.tsx",
"./error": { applicationError: String },
"./list": listLogic,
"./next-step": { getNextStep: () => ({}), describeNextStep: () => ({ title: "Saved" }) },
- "./queries": { useApplications: () => ({ data: applications }), useApplicationMutations: () => ({}) },
+ "./queries": {
+ useApplications: () => ({ data: applications }),
+ useApplicationMutations: () => ({}),
+ useApplicationDetailPrefetch: () => () => {},
+ },
"./stages": { PIPELINE: [], CLOSED_REASONS: [], getStageColor: () => "gray", getStageLabel: (value) => value },
"@/auth/session": { useSession: () => ({ status: "signed-in", server: "fixture" }) },
"@/features/application-detail/hooks": { useUserTime: () => ({ timeZone: "UTC" }) },
diff --git a/apps/mobile/src/features/application-detail/hooks.ts b/apps/mobile/src/features/application-detail/hooks.ts
index ddf44b681..9dc924cbd 100644
--- a/apps/mobile/src/features/application-detail/hooks.ts
+++ b/apps/mobile/src/features/application-detail/hooks.ts
@@ -53,7 +53,10 @@ export function useDetailMutations(applicationId: string) {
}
/** The notification for one interview. The body has no time in it, so a timezone change needs no reschedule. */
-export const interviewReminder = (application: Application, entry: InterviewTimelineEntry): ReminderTarget => ({
+export const interviewReminder = (
+ application: Pick<Application, "id" | "company" | "role">,
+ entry: InterviewTimelineEntry,
+): ReminderTarget => ({
kind: "interview",
applicationId: application.id,
entryId: entry.id,
@@ -63,7 +66,9 @@ export const interviewReminder = (application: Application, entry: InterviewTime
});
/** The notification for the follow-up; it fires at the follow-up itself (09:00 that day). */
-export const followUpReminder = (application: Application): ReminderTarget | null =>
+export const followUpReminder = (
+ application: Pick<Application, "id" | "company" | "role" | "followUpAt" | "followUpNote">,
+): ReminderTarget | null =>
application.followUpAt
? {
kind: "follow-up",
@@ -75,7 +80,9 @@ export const followUpReminder = (application: Application): ReminderTarget | nul
: null;
/** Everything that may have a reminder; a closed application has none. */
-export function reminderTargets(application: Application): ReminderTarget[] {
+export function reminderTargets(
+ application: Pick<Application, "id" | "status" | "activity" | "company" | "role" | "followUpAt" | "followUpNote">,
+): ReminderTarget[] {
if (application.status === "closed") return [];
const followUp = followUpReminder(application);
return [
diff --git a/apps/mobile/src/features/application-detail/interview-sheet.tsx b/apps/mobile/src/features/application-detail/interview-sheet.tsx
index 32679fc8f..e62ee2cee 100644
--- a/apps/mobile/src/features/application-detail/interview-sheet.tsx
+++ b/apps/mobile/src/features/application-detail/interview-sheet.tsx
@@ -1,4 +1,4 @@
-import type { Application } from "@/features/applications/types";
+import type { Application, ApplicationSummary } from "@/features/applications/types";
import type { InterviewKind, InterviewTimelineEntry } from "@reactive-resume/schema/applications/data";
import { useLingui } from "@lingui/react/macro";
import { useQueryClient } from "@tanstack/react-query";
@@ -104,7 +104,7 @@ function draftFrom(interview: InterviewTimelineEntry, fallbackZone: string): Dra
}
type InterviewSheetProps = {
- application: Application;
+ application: ApplicationSummary;
/** The interview to edit, or null to schedule a new one. */
interview: InterviewTimelineEntry | null;
open: boolean;
diff --git a/apps/mobile/src/features/application-detail/sheets.tsx b/apps/mobile/src/features/application-detail/sheets.tsx
index e9baea1d4..20af971e7 100644
--- a/apps/mobile/src/features/application-detail/sheets.tsx
+++ b/apps/mobile/src/features/application-detail/sheets.tsx
@@ -1,4 +1,4 @@
-import type { Application } from "@/features/applications/types";
+import type { Application, ApplicationSummary } from "@/features/applications/types";
import type { ReminderTarget } from "@/features/reminders";
import type {
ApplicationClosedReason,
@@ -14,7 +14,7 @@ import { WallClockField } from "./date-field";
import { followUpReminder, leadLabel, useDocuments, useUserTime } from "./hooks";
import { followUpDay } from "@/features/applications-board/calendar";
import { applicationError } from "@/features/applications/error";
-import { useApplicationMutations } from "@/features/applications/queries";
+import { useApplication, useApplicationMutations } from "@/features/applications/queries";
import { CLOSED_REASONS, getClosedReasonLabel } from "@/features/applications/stages";
import { DEFAULT_LEAD, followUpStart, REMINDER_LEADS, useReminders } from "@/features/reminders";
import {
@@ -35,12 +35,13 @@ import {
} from "@/ui";
type SheetBaseProps = { open: boolean; onClose: () => void };
-type ApplicationSheetProps = SheetBaseProps & { application: Application };
+type ApplicationActionSheetProps = SheetBaseProps & { application: ApplicationSummary };
+type ApplicationContentSheetProps = SheetBaseProps & { application: Application };
const today = () => new Date().toLocaleDateString("en-CA");
/** "Close this application": one reason, kept for Insights. */
-export function CloseSheet({ application, open, onClose }: ApplicationSheetProps) {
+export function CloseSheet({ application, open, onClose }: ApplicationActionSheetProps) {
const { t } = useLingui();
const { space } = useTheme();
const { update } = useApplicationMutations();
@@ -89,7 +90,7 @@ export function CloseSheet({ application, open, onClose }: ApplicationSheetProps
}
/** Saved → Applied: the date and the documents actually sent; their current versions are kept. */
-export function MarkAppliedSheet({ application, open, onClose }: ApplicationSheetProps) {
+export function MarkAppliedSheet({ application, open, onClose }: ApplicationActionSheetProps) {
const { t } = useLingui();
return (
<Sheet open={open} onClose={onClose} title={t`Mark as applied`}>
@@ -98,10 +99,11 @@ export function MarkAppliedSheet({ application, open, onClose }: ApplicationShee
);
}
-function MarkAppliedForm({ application, onClose }: Omit<ApplicationSheetProps, "open">) {
+function MarkAppliedForm({ application, onClose }: Omit<ApplicationActionSheetProps, "open">) {
const { t } = useLingui();
const { space } = useTheme();
const { update } = useApplicationMutations();
+ const detail = useApplication(application.id);
const documents = useDocuments();
const [date, setDate] = useState(today);
const [resumeId, setResumeId] = useState(application.resumeId ?? "");
@@ -134,17 +136,17 @@ function MarkAppliedForm({ application, onClose }: Omit<ApplicationSheetProps, "
options={options("letter")}
onChange={setLetterId}
/>
- {application.resumeFileUrl ? (
+ {detail.data?.resumeFileUrl ? (
<ListRow
- title={t`Submitted attached resume: ${application.resumeFileName ?? "PDF"}`}
+ title={t`Submitted attached resume: ${detail.data.resumeFileName ?? "PDF"}`}
trailing={
<Switch label={t`Submitted attached resume`} value={resumeFileSent} onValueChange={setResumeFileSent} />
}
/>
) : null}
- {application.coverLetterUrl ? (
+ {detail.data?.coverLetterUrl ? (
<ListRow
- title={t`Submitted attached cover letter: ${application.coverLetterName ?? "PDF"}`}
+ title={t`Submitted attached cover letter: ${detail.data.coverLetterName ?? "PDF"}`}
trailing={
<Switch
label={t`Submitted attached cover letter`}
@@ -154,13 +156,20 @@ function MarkAppliedForm({ application, onClose }: Omit<ApplicationSheetProps, "
}
/>
) : null}
+ {detail.isError ? (
+ <Banner
+ tone="danger"
+ message={t`Couldn't load this. Check your connection and try again.`}
+ action={{ label: t`Retry loading applications`, onPress: () => void detail.refetch() }}
+ />
+ ) : null}
{update.error ? <Banner tone="danger" message={t`Couldn't record submission. Try again.`} /> : null}
<Button
fullWidth
size="lg"
label={t`Confirm applied`}
loading={update.isPending}
- disabled={!date}
+ disabled={!date || !detail.data}
onPress={() =>
update.mutate(
{
@@ -182,7 +191,7 @@ function MarkAppliedForm({ application, onClose }: Omit<ApplicationSheetProps, "
}
/** The follow-up: a day and what to do, shown as the next step until done, with an optional local reminder. */
-export function FollowUpSheet({ application, open, onClose }: ApplicationSheetProps) {
+export function FollowUpSheet({ application, open, onClose }: ApplicationActionSheetProps) {
const { t } = useLingui();
return (
<Sheet open={open} onClose={onClose} title={t`Follow-up`}>
@@ -191,7 +200,7 @@ export function FollowUpSheet({ application, open, onClose }: ApplicationSheetPr
);
}
-function FollowUpForm({ application, onClose }: Omit<ApplicationSheetProps, "open">) {
+function FollowUpForm({ application, onClose }: Omit<ApplicationActionSheetProps, "open">) {
const { t } = useLingui();
const { space } = useTheme();
const { timeZone } = useUserTime();
@@ -333,7 +342,7 @@ export function ReminderSheet({ target, subtitle, open, onClose, onShareIcs }: R
}
/** The saved posting: its link, provenance, what it asks for, and its editable text. */
-export function PostingSheet({ application, open, onClose }: ApplicationSheetProps) {
+export function PostingSheet({ application, open, onClose }: ApplicationContentSheetProps) {
return (
<Sheet open={open} onClose={onClose} detents={[0.9]} title={`${application.role} · ${application.company}`}>
{open ? <PostingBody application={application} onClose={onClose} /> : null}
@@ -341,7 +350,7 @@ export function PostingSheet({ application, open, onClose }: ApplicationSheetPro
);
}
-function PostingBody({ application, onClose }: Omit<ApplicationSheetProps, "open">) {
+function PostingBody({ application, onClose }: Omit<ApplicationContentSheetProps, "open">) {
const { t } = useLingui();
const { space } = useTheme();
const { update } = useApplicationMutations();
@@ -399,7 +408,7 @@ function PostingBody({ application, onClose }: Omit<ApplicationSheetProps, "open
const EMPTY_CONTACT = { name: "", role: "", type: "", email: "", phone: "" };
/** Contacts: the list with remove, and a form to add one, checked with the API's schema before saving. */
-export function ContactsSheet({ application, open, onClose }: ApplicationSheetProps) {
+export function ContactsSheet({ application, open, onClose }: ApplicationContentSheetProps) {
const { t } = useLingui();
const { space } = useTheme();
const { update } = useApplicationMutations();
diff --git a/apps/mobile/src/features/applications-board/board-screen.tsx b/apps/mobile/src/features/applications-board/board-screen.tsx
index c12df3c34..381509641 100644
--- a/apps/mobile/src/features/applications-board/board-screen.tsx
+++ b/apps/mobile/src/features/applications-board/board-screen.tsx
@@ -1,5 +1,5 @@
import type { ColumnRect, PendingMove } from "./board";
-import type { Application } from "@/features/applications/types";
+import type { ApplicationSummary as Application } from "@/features/applications/types";
import type { ApplicationStatus } from "@reactive-resume/schema/applications/data";
import type { ComponentRef } from "react";
import type { ScrollView } from "react-native";
@@ -562,6 +562,7 @@ function BoardCard({ application, onMove }: BoardCardProps) {
const { space } = useTheme();
const { timeZone } = useUserTime();
const next = describeNextStep(getNextStep(application), application, i18n.locale, timeZone);
+
return (
<Card>
<Pressable
diff --git a/apps/mobile/src/features/applications-board/calendar-screen.tsx b/apps/mobile/src/features/applications-board/calendar-screen.tsx
index 5ff5ecff0..455ac09bd 100644
--- a/apps/mobile/src/features/applications-board/calendar-screen.tsx
+++ b/apps/mobile/src/features/applications-board/calendar-screen.tsx
@@ -1,5 +1,5 @@
import type { CalendarEvent } from "./calendar";
-import type { Application } from "@/features/applications/types";
+import type { ApplicationSummary as Application } from "@/features/applications/types";
import type { InterviewTimelineEntry } from "@reactive-resume/schema/applications/data";
import { plural } from "@lingui/core/macro";
import { useLingui } from "@lingui/react/macro";
diff --git a/apps/mobile/src/features/applications-board/calendar.ts b/apps/mobile/src/features/applications-board/calendar.ts
index 3b648ed0f..29e724a8b 100644
--- a/apps/mobile/src/features/applications-board/calendar.ts
+++ b/apps/mobile/src/features/applications-board/calendar.ts
@@ -1,7 +1,7 @@
// Calendar maths for interviews and follow-ups. Days are calendar dates ("2026-10-19") on the user's clock (their
// profile timezone), not the device's, so an interview lands on the same day as the detail screen shows it.
// Pure: Node runs it in the M5-T3 scenarios.
-import type { Application } from "../applications/types";
+import type { ApplicationSummary as Application } from "../applications/types";
import type { InterviewTimelineEntry } from "@reactive-resume/schema/applications/data";
import { zonedParts } from "../reminders/schedule.ts";
diff --git a/apps/mobile/src/features/applications-board/insights.ts b/apps/mobile/src/features/applications-board/insights.ts
index 69692f211..a49ae8ae3 100644
--- a/apps/mobile/src/features/applications-board/insights.ts
+++ b/apps/mobile/src/features/applications-board/insights.ts
@@ -1,7 +1,7 @@
// Insights maths, ported from apps/web/src/features/applications/insights.ts. Everything derives from the shared
// applications list (it holds every application, closed ones included), so the figures match the server's stats
// without a second query. Weeks are bucketed on the user's clock. Pure: Node runs it in the M5-T3 scenarios.
-import type { Application } from "../applications/types";
+import type { ApplicationSummary as Application } from "../applications/types";
import type { ApplicationStatus } from "@reactive-resume/schema/applications/data";
import { zonedParts } from "../reminders/schedule.ts";
diff --git a/apps/mobile/src/features/applications/list-screen.tsx b/apps/mobile/src/features/applications/list-screen.tsx
index a80ec94e9..31bbcdc0c 100644
--- a/apps/mobile/src/features/applications/list-screen.tsx
+++ b/apps/mobile/src/features/applications/list-screen.tsx
@@ -10,7 +10,7 @@ import { AddApplicationSheet } from "./add-sheet";
import { applicationError } from "./error";
import { filterApplications, groupApplications, visibleSelection } from "./list";
import { describeNextStep, getNextStep } from "./next-step";
-import { useApplicationMutations, useApplications } from "./queries";
+import { useApplicationDetailPrefetch, useApplicationMutations, useApplications } from "./queries";
import { CLOSED_REASONS, getClosedReasonLabel, getStageColor, getStageLabel, PIPELINE } from "./stages";
import { useSession } from "@/auth/session";
import { useUserTime } from "@/features/application-detail/hooks";
@@ -37,6 +37,8 @@ import {
} from "@/ui";
import { usePullRefresh } from "@/ui/use-pull-refresh";
+const VIEWABILITY_CONFIG = { itemVisiblePercentThreshold: 30 };
+
export function ApplicationsListScreen() {
const session = useSession();
const { space } = useTheme();
@@ -84,6 +86,7 @@ function ApplicationsList() {
const filtersActive = Boolean(search.trim() || tag || showClosed);
const groups = groupApplications(filtered, sort, direction);
const selectedIds = visibleSelection(groups, collapsed, selected);
+ const onViewableItemsChanged = useApplicationDetailPrefetch();
const tags = [...new Set(applications.flatMap((item) => item.tags))].sort();
const changeFilters = (change: () => void) => {
change();
@@ -255,6 +258,8 @@ function ApplicationsList() {
}))
}
keyExtractor={(item) => item.id}
+ onViewableItemsChanged={onViewableItemsChanged}
+ viewabilityConfig={VIEWABILITY_CONFIG}
keyboardShouldPersistTaps="handled"
refreshControl={<RefreshControl {...pull} tintColor={colors.accent} colors={[colors.accent]} />}
stickySectionHeadersEnabled={false}
diff --git a/apps/mobile/src/features/applications/list.ts b/apps/mobile/src/features/applications/list.ts
index 71f883ec5..5b23672dc 100644
--- a/apps/mobile/src/features/applications/list.ts
+++ b/apps/mobile/src/features/applications/list.ts
@@ -1,4 +1,4 @@
-import type { Application } from "./types";
+import type { ApplicationSummary as Application } from "./types";
import type { ApplicationStatus } from "@reactive-resume/schema/applications/data";
import { getNextStep } from "./next-step";
import { LIST_ORDER } from "./stages";
diff --git a/apps/mobile/src/features/applications/next-step.ts b/apps/mobile/src/features/applications/next-step.ts
index f6a1d0e5b..db6e6a9cd 100644
--- a/apps/mobile/src/features/applications/next-step.ts
+++ b/apps/mobile/src/features/applications/next-step.ts
@@ -1,4 +1,4 @@
-import type { Application } from "./types";
+import type { ApplicationSummary as Application } from "./types";
import type { IconName } from "@/ui";
import type { InterviewTimelineEntry } from "@reactive-resume/schema/applications/data";
import { plural, t } from "@lingui/core/macro";
diff --git a/apps/mobile/src/features/applications/queries.ts b/apps/mobile/src/features/applications/queries.ts
index 55b5a0be7..370fe8104 100644
--- a/apps/mobile/src/features/applications/queries.ts
+++ b/apps/mobile/src/features/applications/queries.ts
@@ -1,12 +1,14 @@
-import type { Application } from "./types";
+import type { Application, ApplicationSummary } from "./types";
+import type { ListViewToken } from "react-native";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
+import { useCallback, useEffect, useRef } from "react";
import { orpc } from "@/api/client";
import { getServer, useSession } from "@/auth/session";
import { syncReminders } from "@/features/reminders";
/** Same unfiltered list for list, board, calendar and detail; isolated by server. */
export const applicationsListQueryOptions = (server = getServer()) => {
- const options = orpc.applications.list.queryOptions({ input: {} });
+ const options = orpc.applications.listSummary.queryOptions({ input: { includeInitialDetails: 3 } });
return { ...options, queryKey: [...options.queryKey, server] };
};
export const applicationsListQueryKey = (server = getServer()) => applicationsListQueryOptions(server).queryKey;
@@ -17,18 +19,83 @@ export const applicationDetailQueryOptions = (id: string, server = getServer())
export const applicationDetailQueryKey = (id: string, server = getServer()) =>
applicationDetailQueryOptions(id, server).queryKey;
+function getInitialApplicationDetail(summary: ApplicationSummary | undefined) {
+ const detail = summary?.initialDetail;
+ return detail && detail.status === summary.status && detail.closedReason === summary.closedReason
+ ? detail
+ : undefined;
+}
+
export function useApplications() {
const session = useSession();
- return useQuery({ ...applicationsListQueryOptions(session.server), enabled: session.status === "signed-in" });
+ const queryClient = useQueryClient();
+ const query = useQuery({ ...applicationsListQueryOptions(session.server), enabled: session.status === "signed-in" });
+
+ useEffect(() => {
+ if (!query.data || session.status !== "signed-in") return;
+ const listUpdatedAt = query.dataUpdatedAt;
+ for (const application of query.data) {
+ const initialDetail = getInitialApplicationDetail(application);
+ if (!initialDetail) continue;
+ const detailKey = applicationDetailQueryOptions(application.id, session.server).queryKey;
+ const existing = queryClient.getQueryData<Application>(detailKey);
+ if (existing && existing.updatedAt.getTime() >= initialDetail.updatedAt.getTime()) continue;
+ void queryClient.cancelQueries({ queryKey: detailKey }, { revert: false });
+ queryClient.setQueryData(detailKey, initialDetail, { updatedAt: listUpdatedAt });
+ }
+ }, [query.data, query.dataUpdatedAt, queryClient, session.server, session.status]);
+
+ return query;
}
export function useApplication(id: string) {
const session = useSession();
+ const queryClient = useQueryClient();
+ const listKey = applicationsListQueryKey(session.server);
+ const summary = queryClient.getQueryData<ApplicationSummary[]>(listKey)?.find((application) => application.id === id);
+ const listUpdatedAt = queryClient.getQueryState(listKey)?.dataUpdatedAt;
+ const initialDetail = getInitialApplicationDetail(summary);
+
return useQuery({
...applicationDetailQueryOptions(id, session.server),
enabled: session.status === "signed-in" && !!id,
+ initialData: initialDetail,
+ ...(listUpdatedAt !== undefined ? { initialDataUpdatedAt: listUpdatedAt } : {}),
});
}
+export function useApplicationDetailPrefetch() {
+ const queryClient = useQueryClient();
+ const prefetchInFlight = useRef(new Set<string>());
+ const prefetchTimer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
+ const onViewableItemsChanged = useCallback(
+ ({ viewableItems }: { viewableItems: ListViewToken[] }) => {
+ clearTimeout(prefetchTimer.current);
+ // Section headers also appear in viewability callbacks, without an application ID.
+ const ids = viewableItems.flatMap(({ item }) => (typeof item.id === "string" ? [item.id] : [])).slice(0, 2);
+ prefetchTimer.current = setTimeout(() => {
+ for (const id of ids) {
+ const options = applicationDetailQueryOptions(id);
+ if (
+ prefetchInFlight.current.has(id) ||
+ queryClient.getQueryData(options.queryKey) ||
+ queryClient.getQueryState(options.queryKey)?.fetchStatus === "fetching"
+ )
+ continue;
+ if (prefetchInFlight.current.size >= 2) break;
+ prefetchInFlight.current.add(id);
+ void queryClient
+ .fetchQuery(options)
+ .catch(() => {})
+ .finally(() => prefetchInFlight.current.delete(id));
+ }
+ }, 120);
+ },
+ [queryClient],
+ );
+ useEffect(() => () => clearTimeout(prefetchTimer.current), []);
+ return onViewableItemsChanged;
+}
+
/** Invalidates all application views, tags, stats and linked document summaries after writes. */
export function useInvalidateApplications() {
const queryClient = useQueryClient();
@@ -57,8 +124,8 @@ export function useApplicationMutations() {
onMutate: async (input) => {
const listKey = applicationsListQueryKey();
await queryClient.cancelQueries({ queryKey: listKey });
- const previous = queryClient.getQueryData<Application[]>(listKey);
- queryClient.setQueryData<Application[]>(listKey, (rows) =>
+ const previous = queryClient.getQueryData<ApplicationSummary[]>(listKey);
+ queryClient.setQueryData<ApplicationSummary[]>(listKey, (rows) =>
rows?.map((row) =>
row.id === input.id
? {
diff --git a/apps/mobile/src/features/applications/types.ts b/apps/mobile/src/features/applications/types.ts
index 95c68525b..849b0762f 100644
--- a/apps/mobile/src/features/applications/types.ts
+++ b/apps/mobile/src/features/applications/types.ts
@@ -1,3 +1,4 @@
import type { RouterOutput } from "@/api/client";
export type Application = RouterOutput["applications"]["list"][number];
+export type ApplicationSummary = RouterOutput["applications"]["listSummary"][number];
diff --git a/apps/mobile/src/features/career/scheduling.ts b/apps/mobile/src/features/career/scheduling.ts
index af39502a5..6c6d11239 100644
--- a/apps/mobile/src/features/career/scheduling.ts
+++ b/apps/mobile/src/features/career/scheduling.ts
@@ -1,4 +1,4 @@
-import type { Application } from "@/features/applications/types";
+import type { ApplicationSummary as Application } from "@/features/applications/types";
import { fromZonedDateTime } from "@reactive-resume/utils/timezone";
export function toZoned(at: Date, timeZone: string) {
diff --git a/apps/mobile/src/features/documents/document-sheets.tsx b/apps/mobile/src/features/documents/document-sheets.tsx
index 89936383e..9cb6f1a2c 100644
--- a/apps/mobile/src/features/documents/document-sheets.tsx
+++ b/apps/mobile/src/features/documents/document-sheets.tsx
@@ -33,7 +33,7 @@ export function DocumentSheets({ value, onClose, onChange, onSelect }: DocumentS
const [name, setName] = useState(first?.name ?? "");
const shared = sharedTags(value.documents);
const [tags, setTags] = useState(shared);
- const options = orpc.applications.list.queryOptions({ input: {} });
+ const options = orpc.applications.listSummary.queryOptions({ input: {} });
const applications = useQuery({
...options,
queryKey: [...options.queryKey, session.server],
diff --git a/apps/mobile/src/features/documents/new-document.tsx b/apps/mobile/src/features/documents/new-document.tsx
index 7e2504558..188b46a35 100644
--- a/apps/mobile/src/features/documents/new-document.tsx
+++ b/apps/mobile/src/features/documents/new-document.tsx
@@ -47,7 +47,7 @@ export function NewDocument() {
const mounted = useRef(true);
const abort = useRef<AbortController | null>(null);
const cached = useRef<File | null>(null);
- const options = orpc.applications.list.queryOptions({ input: {} });
+ const options = orpc.applications.listSummary.queryOptions({ input: {} });
const applications = useQuery({
...options,
queryKey: [...options.queryKey, session.server],
diff --git a/apps/mobile/src/features/letters/write.tsx b/apps/mobile/src/features/letters/write.tsx
index 4290e2b68..eda1cab94 100644
--- a/apps/mobile/src/features/letters/write.tsx
+++ b/apps/mobile/src/features/letters/write.tsx
@@ -1,6 +1,6 @@
import type { RelinkResult } from "./save";
import type { LetterDocument } from "@/draft/types";
-import type { Application } from "@/features/applications/types";
+import type { ApplicationSummary as Application } from "@/features/applications/types";
import type { WritableDraft } from "immer";
import type { ReactNode } from "react";
import { plural, t } from "@lingui/core/macro";
diff --git a/apps/web/src/features/applications/components/application-actions-menu.tsx b/apps/web/src/features/applications/components/application-actions-menu.tsx
index 5764e2138..c67e19c9b 100644
--- a/apps/web/src/features/applications/components/application-actions-menu.tsx
+++ b/apps/web/src/features/applications/components/application-actions-menu.tsx
@@ -1,4 +1,4 @@
-import type { Application } from "../types";
+import type { ApplicationSummary } from "../types";
import { t } from "@lingui/core/macro";
import { Trans } from "@lingui/react/macro";
import { Button } from "@reactive-resume/ui/components/button";
@@ -22,7 +22,7 @@ import { useConfirm } from "@/hooks/use-confirm";
// bubble synthetic events through the React tree, so a menu item's click would otherwise reach the card.
const stop = (event: React.SyntheticEvent) => event.stopPropagation();
-type ApplicationActionsMenuProps = { application: Application; className?: string };
+type ApplicationActionsMenuProps = { application: ApplicationSummary; className?: string };
/** A card's ⋯ menu, the keyboard alternative to dragging: Move to…, Close…, and Delete after asking. */
export function ApplicationActionsMenu({ application, className }: ApplicationActionsMenuProps) {
diff --git a/apps/web/src/features/applications/components/application-card.tsx b/apps/web/src/features/applications/components/application-card.tsx
index 7a24d17c2..a8a0060e5 100644
--- a/apps/web/src/features/applications/components/application-card.tsx
+++ b/apps/web/src/features/applications/components/application-card.tsx
@@ -1,4 +1,4 @@
-import type { Application } from "../types";
+import type { ApplicationSummary } from "../types";
import { useLingui } from "@lingui/react";
import { Icon } from "@reactive-resume/ui/components/icon";
import { cn } from "@reactive-resume/utils/style";
@@ -6,7 +6,7 @@ import { describeNextStep, getNextStep } from "../next-step";
import { ApplicationActionsMenu } from "./application-actions-menu";
type ApplicationCardProps = {
- application: Application;
+ application: ApplicationSummary;
onClick?: () => void;
/** The ⋯ menu (Move to…, Close…, Delete); cards dragged in the overlay go without. */
withMenu?: boolean;
@@ -20,6 +20,7 @@ export function ApplicationCard({ application, onClick, withMenu = false, draggi
return (
<div
+ data-application-id={application.id}
className={cn(
"group relative grid gap-2 rounded-lg border border-line bg-surface p-3 shadow-e1 transition-[border-color,scale] duration-quick ease-enter hover:border-line-2 active:not-has-[[data-slot=button]:active]:scale-[0.98]",
// The overlay card lifts as it's picked up and settles flat again while the drop animation flies it home.
@@ -36,6 +37,7 @@ export function ApplicationCard({ application, onClick, withMenu = false, draggi
</span>
<button
type="button"
+ data-application-open
onClick={onClick}
className="grid min-w-0 flex-1 text-start after:absolute after:inset-0 after:rounded-lg"
>
diff --git a/apps/web/src/features/applications/components/application-detail-sheet.tsx b/apps/web/src/features/applications/components/application-detail-sheet.tsx
index 60de52b70..9659a32d9 100644
--- a/apps/web/src/features/applications/components/application-detail-sheet.tsx
+++ b/apps/web/src/features/applications/components/application-detail-sheet.tsx
@@ -1,4 +1,4 @@
-import type { Application } from "../types";
+import type { Application, ApplicationSummary } from "../types";
import type { InterviewTimelineEntry } from "@reactive-resume/schema/applications/data";
import { t } from "@lingui/core/macro";
import { useLingui } from "@lingui/react";
@@ -28,6 +28,7 @@ import { toast } from "@reactive-resume/ui/components/toast";
import { useBreakpoint } from "@reactive-resume/ui/hooks/use-breakpoint";
import { cn } from "@reactive-resume/utils/style";
import { daysInStage } from "../next-step";
+import { applicationDetailQueryOptions, getInitialApplicationDetail } from "../queries";
import { getClosedReasonLabel, getNextStage, getStageColor, getStageLabel, PIPELINE } from "../stages";
import { useApplicationActions, useInvalidateApplications } from "../use-application-actions";
import { ApplicationNotes } from "./application-notes";
@@ -44,7 +45,7 @@ import { isImeComposing } from "@/libs/keyboard";
import { orpc } from "@/libs/orpc/client";
type DetailSheetProps = {
- application: Application | null;
+ application: ApplicationSummary | null;
onOpenChange: (open: boolean) => void;
onEditDetails: (application: Application) => void;
};
@@ -57,13 +58,15 @@ export function ApplicationDetailSheet({ application, onOpenChange, onEditDetail
const phone = useBreakpoint() === "mobile";
// Closing keeps the last application on screen until the sheet has slid away.
const [shown, onOpenChangeComplete] = useClosingValue(application);
- const { data } = useQuery({
- ...orpc.applications.getById.queryOptions({ input: { id: shown?.id ?? "" } }),
+ const initialDetail = getInitialApplicationDetail(shown);
+ const { data, isError, isFetching, isPending, refetch } = useQuery({
+ ...applicationDetailQueryOptions(shown?.id ?? ""),
// Fetch only while open; while closing, the cached copy keeps showing.
enabled: Boolean(application),
- ...(shown ? { placeholderData: shown } : {}),
+ initialData: initialDetail,
+ initialDataUpdatedAt: 0,
});
- const current = data ?? shown;
+ const current = data;
return (
<Sheet open={Boolean(application)} onOpenChange={onOpenChange} onOpenChangeComplete={onOpenChangeComplete}>
@@ -72,13 +75,25 @@ export function ApplicationDetailSheet({ application, onOpenChange, onEditDetail
closeLabel={t`Close`}
className={cn("gap-0", phone ? "h-svh" : "data-[side=right]:sm:max-w-[480px]")}
>
- {current && (
+ {current ? (
<Detail
key={current.id}
application={current}
onEditDetails={onEditDetails}
onDeleted={() => onOpenChange(false)}
/>
+ ) : (
+ <div className="grid gap-2 p-5">
+ <SheetTitle>{shown?.role}</SheetTitle>
+ <SheetDescription aria-live="polite">
+ {isError ? t`Couldn't load this. Your saved data hasn't changed.` : t`Loading…`}
+ </SheetDescription>
+ {isError && (
+ <Button variant="secondary" disabled={isFetching || isPending} onClick={() => void refetch()}>
+ <Trans>Try again</Trans>
+ </Button>
+ )}
+ </div>
)}
</SheetContent>
</Sheet>
diff --git a/apps/web/src/features/applications/components/application-form-sheet.test.tsx b/apps/web/src/features/applications/components/application-form-sheet.test.tsx
index d7df180bd..2cd882228 100644
--- a/apps/web/src/features/applications/components/application-form-sheet.test.tsx
+++ b/apps/web/src/features/applications/components/application-form-sheet.test.tsx
@@ -19,7 +19,7 @@ vi.mock("@/libs/orpc/client", () => ({
orpc: {
resume: { list: { queryOptions: () => ({ queryKey: ["resume", "list"], queryFn: async () => [] }) } },
applications: {
- list: { queryKey: () => ["applications", "list"] },
+ listSummary: { queryKey: () => ["applications", "summary"] },
tags: {
queryOptions: () => ({ queryKey: ["applications", "tags"], queryFn: async () => [] }),
queryKey: () => ["applications", "tags"],
diff --git a/apps/web/src/features/applications/components/board.tsx b/apps/web/src/features/applications/components/board.tsx
index 84f9ecc20..5096ee4d1 100644
--- a/apps/web/src/features/applications/components/board.tsx
+++ b/apps/web/src/features/applications/components/board.tsx
@@ -1,4 +1,4 @@
-import type { Application } from "../types";
+import type { ApplicationSummary } from "../types";
import type { DragEndEvent, DragStartEvent } from "@dnd-kit/core";
import type { ApplicationStatus } from "@reactive-resume/schema/applications/data";
import {
@@ -31,9 +31,9 @@ import { ApplicationCard } from "./application-card";
import { DRAG_SETTLE } from "@/libs/motion";
type BoardProps = {
- applications: Application[];
+ applications: ApplicationSummary[];
showClosed: boolean;
- onOpen: (application: Application) => void;
+ onOpen: (application: ApplicationSummary) => void;
};
// While the overlay settles, the real card waits hidden in its new slot and the overlay's tilt eases off.
@@ -50,7 +50,7 @@ export function ApplicationBoard({ applications, showClosed, onOpen }: BoardProp
const { moveTo, close } = useApplicationActions();
const reduceMotion = useReducedMotion();
const [activeId, setActiveId] = useState<string | null>(null);
- const [closing, setClosing] = useState<Application | null>(null);
+ const [closing, setClosing] = useState<ApplicationSummary | null>(null);
// The list query publishes the optimistic move a task after the drop (TanStack Query notifies on a timeout), so
// until it does the board shows the dropped card in its new column itself. Otherwise the card blinks back to its
// old column for a frame, and the drop animation would fly there.
@@ -65,14 +65,14 @@ export function ApplicationBoard({ applications, showClosed, onOpen }: BoardProp
) {
setPendingMove(null);
}
- const statusOf = (application: Application) =>
+ const statusOf = (application: ApplicationSummary) =>
pendingMove?.id === application.id ? pendingMove.to : application.status;
// A small activation distance so a click still opens the detail sheet instead of starting a drag.
const sensors = useSensors(useSensor(PointerSensor, { activationConstraint: { distance: 5 } }));
const stages: ApplicationStatus[] = showClosed ? [...PIPELINE, "closed"] : [...PIPELINE];
- const byStage = new Map<ApplicationStatus, Application[]>(stages.map((stage) => [stage, []]));
+ const byStage = new Map<ApplicationStatus, ApplicationSummary[]>(stages.map((stage) => [stage, []]));
for (const application of applications) byStage.get(statusOf(application))?.push(application);
const active = activeId ? applications.find((application) => application.id === activeId) : null;
@@ -143,8 +143,8 @@ const COLUMN_PAGE_SIZE = 50;
type ColumnProps = {
stage: ApplicationStatus;
- applications: Application[];
- onOpen: (application: Application) => void;
+ applications: ApplicationSummary[];
+ onOpen: (application: ApplicationSummary) => void;
};
function Column({ stage, applications, onOpen }: ColumnProps) {
@@ -184,7 +184,7 @@ function Column({ stage, applications, onOpen }: ColumnProps) {
);
}
-type DraggableCardProps = { application: Application; onOpen: (application: Application) => void };
+type DraggableCardProps = { application: ApplicationSummary; onOpen: (application: ApplicationSummary) => void };
// Re-renders with every drag context change; the closure here stays stable, so the card itself doesn't.
function DraggableCard({ application, onOpen }: DraggableCardProps) {
diff --git a/apps/web/src/features/applications/components/calendar-view.tsx b/apps/web/src/features/applications/components/calendar-view.tsx
index 1b72d6702..eb0d043ed 100644
--- a/apps/web/src/features/applications/components/calendar-view.tsx
+++ b/apps/web/src/features/applications/components/calendar-view.tsx
@@ -1,5 +1,5 @@
import type { ScheduledInterview } from "../interviews";
-import type { Application } from "../types";
+import type { ApplicationSummary } from "../types";
import type { InterviewTimelineEntry } from "@reactive-resume/schema/applications/data";
import { t } from "@lingui/core/macro";
import { useLingui } from "@lingui/react";
@@ -25,14 +25,14 @@ const MAX_CHIPS_PER_DAY = 3;
type DialogState =
| { open: false }
- | { open: true; application: Application | null; interview: InterviewTimelineEntry | null; day: Date | null };
+ | { open: true; application: ApplicationSummary | null; interview: InterviewTimelineEntry | null; day: Date | null };
type ApplicationCalendarProps = {
// Applications matching the page filters; their interviews are shown.
- applications: Application[];
+ applications: ApplicationSummary[];
// Every application, offered by the "schedule interview" picker.
- allApplications: Application[];
- onOpen: (application: Application) => void;
+ allApplications: ApplicationSummary[];
+ onOpen: (application: ApplicationSummary) => void;
};
export function ApplicationCalendar({ applications, allApplications, onOpen }: ApplicationCalendarProps) {
@@ -294,6 +294,7 @@ function UpcomingCard({ item, timeRange, locale, onEdit, onOpenApplication }: Up
return (
<div
data-upcoming-interview={item.interview.id}
+ data-application-id={item.application.id}
className="relative overflow-hidden rounded-xl border border-line bg-surface ps-4 text-sm"
>
<span className="absolute inset-y-0 start-0 w-1" style={{ background: kind?.color }} />
@@ -313,7 +314,12 @@ function UpcomingCard({ item, timeRange, locale, onEdit, onOpenApplication }: Up
</span>
)}
</button>
- <button type="button" className="mb-2 text-xs text-accent-text hover:underline" onClick={onOpenApplication}>
+ <button
+ type="button"
+ data-application-open
+ className="mb-2 text-xs text-accent-text hover:underline"
+ onClick={onOpenApplication}
+ >
<Trans>View application</Trans>
</button>
</div>
diff --git a/apps/web/src/features/applications/components/insights-view.tsx b/apps/web/src/features/applications/components/insights-view.tsx
index eb365805b..90bb085e5 100644
--- a/apps/web/src/features/applications/components/insights-view.tsx
+++ b/apps/web/src/features/applications/components/insights-view.tsx
@@ -1,4 +1,4 @@
-import type { Application } from "../types";
+import type { ApplicationSummary } from "../types";
import { plural, t } from "@lingui/core/macro";
import { Plural, Trans } from "@lingui/react/macro";
import { useQuery } from "@tanstack/react-query";
@@ -26,7 +26,7 @@ export function InsightsSkeleton() {
);
}
-export function ApplicationInsights({ applications }: { applications: Application[] }) {
+export function ApplicationInsights({ applications }: { applications: ApplicationSummary[] }) {
const { data } = useQuery(orpc.applications.stats.queryOptions({}));
const { data: documents } = useQuery(orpc.documents.list.queryOptions({ input: { trashed: false } }));
@@ -35,7 +35,7 @@ export function ApplicationInsights({ applications }: { applications: Applicatio
(documents ?? []).flatMap((document) => (document.application ? [[document.id, document.application.id]] : [])),
);
const outcomes = computeOutcomes(applications, (application) =>
- Boolean(application.resumeId && madeFor.get(application.resumeId) === (application as Application).id),
+ Boolean(application.resumeId && madeFor.get(application.resumeId) === (application as ApplicationSummary).id),
);
// Sending history includes applications that later closed, and excludes jobs never sent.
diff --git a/apps/web/src/features/applications/components/interview-dialog.tsx b/apps/web/src/features/applications/components/interview-dialog.tsx
index 7c834f021..4020ea649 100644
--- a/apps/web/src/features/applications/components/interview-dialog.tsx
+++ b/apps/web/src/features/applications/components/interview-dialog.tsx
@@ -1,4 +1,4 @@
-import type { Application } from "../types";
+import type { ApplicationSummary } from "../types";
import type { InterviewKind, InterviewTimelineEntry } from "@reactive-resume/schema/applications/data";
import { t } from "@lingui/core/macro";
import { Trans } from "@lingui/react/macro";
@@ -129,9 +129,9 @@ type InterviewDialogProps = {
onOpenChange: (open: boolean) => void;
// The application the interview belongs to. When omitted, an application picker is shown
// (used by the calendar, where no application is selected yet).
- application?: Application | null;
+ application?: ApplicationSummary | null;
// Applications offered by the picker when `application` is omitted.
- applications?: Application[];
+ applications?: ApplicationSummary[];
// Set when editing an existing interview.
interview?: InterviewTimelineEntry | null;
// Pre-selects this day when scheduling (e.g. a day clicked on the calendar).
@@ -265,7 +265,7 @@ export function InterviewDialog({
const deleteInterview = () => {
if (!editing) return;
const applicationId = draft.applicationId;
- const drop = (item: Application) =>
+ const drop = <T extends Pick<ApplicationSummary, "id" | "activity">>(item: T) =>
item.id === applicationId
? { ...item, activity: item.activity.filter((entry) => entry.id !== editing.id) }
: item;
diff --git a/apps/web/src/features/applications/components/list-view.tsx b/apps/web/src/features/applications/components/list-view.tsx
index c1167c8c1..babf1117a 100644
--- a/apps/web/src/features/applications/components/list-view.tsx
+++ b/apps/web/src/features/applications/components/list-view.tsx
@@ -1,4 +1,4 @@
-import type { Application } from "../types";
+import type { ApplicationSummary } from "../types";
import type { ApplicationStatus } from "@reactive-resume/schema/applications/data";
import { plural, t } from "@lingui/core/macro";
import { useLingui } from "@lingui/react";
@@ -32,13 +32,13 @@ import { orpc } from "@/libs/orpc/client";
type SortKey = "role" | "next" | "updated";
type Sort = { key: SortKey; direction: "asc" | "desc" };
-const nextStepTime = (application: Application) => {
+const nextStepTime = (application: ApplicationSummary) => {
const step = getNextStep(application);
return step.kind === "interview" || step.kind === "follow-up" ? step.at.getTime() : Number.POSITIVE_INFINITY;
};
// Sort keys are computed once per row, not once per comparison.
-const sortValue: Record<SortKey, (application: Application) => string | number> = {
+const sortValue: Record<SortKey, (application: ApplicationSummary) => string | number> = {
role: (application) => application.role,
next: nextStepTime,
updated: (application) => new Date(application.updatedAt).getTime(),
@@ -48,10 +48,10 @@ const compareValues = (a: string | number, b: string | number) =>
typeof a === "string" && typeof b === "string" ? a.localeCompare(b) : Number(a) - Number(b);
type ListViewProps = {
- applications: Application[];
+ applications: ApplicationSummary[];
showClosed: boolean;
selectedId: string | null;
- onOpen: (application: Application) => void;
+ onOpen: (application: ApplicationSummary) => void;
};
/**
@@ -80,7 +80,7 @@ export function ApplicationList({ applications, showClosed, selectedId, onOpen }
const groups = useMemo(() => {
const sign = sort.direction === "asc" ? 1 : -1;
const keys = new Map(applications.map((application) => [application.id, sortValue[sort.key](application)]));
- const key = (application: Application) => keys.get(application.id) ?? 0;
+ const key = (application: ApplicationSummary) => keys.get(application.id) ?? 0;
return LIST_ORDER.filter((status) => status !== "closed" || showClosed)
.map((status) => ({
status,
@@ -229,12 +229,12 @@ export function ApplicationList({ applications, showClosed, selectedId, onOpen }
}
type ApplicationRowProps = {
- application: Application;
+ application: ApplicationSummary;
phone: boolean;
selected: boolean;
checked: boolean;
onCheck: (id: string) => void;
- onOpen: (application: Application) => void;
+ onOpen: (application: ApplicationSummary) => void;
};
// Memoized with id-taking callbacks, so one row's change doesn't re-render the other rows.
@@ -261,7 +261,7 @@ const ApplicationRow = memo(function ApplicationRow({
);
const openButton = (
- <button type="button" className="grid min-w-0 cursor-pointer text-start">
+ <button type="button" data-application-open className="grid min-w-0 cursor-pointer text-start">
<span className="truncate font-medium">{application.role}</span>
<span className="truncate text-xs text-ink-3">
{phone
@@ -274,6 +274,7 @@ const ApplicationRow = memo(function ApplicationRow({
if (phone) {
return (
<tr
+ data-application-id={application.id}
onClick={() => onOpen(application)}
className={cn("cursor-pointer border-b border-line", selected && "bg-accent-soft/50")}
>
@@ -290,6 +291,7 @@ const ApplicationRow = memo(function ApplicationRow({
return (
<tr
+ data-application-id={application.id}
onClick={() => onOpen(application)}
className={cn(
"cursor-pointer border-b border-line transition-colors duration-quick hover:bg-hover",
diff --git a/apps/web/src/features/applications/insights.ts b/apps/web/src/features/applications/insights.ts
index 8f15df09a..c712e3417 100644
--- a/apps/web/src/features/applications/insights.ts
+++ b/apps/web/src/features/applications/insights.ts
@@ -1,4 +1,4 @@
-import type { Application } from "./types";
+import type { ApplicationSummary } from "./types";
import type { ApplicationStatus } from "@reactive-resume/schema/applications/data";
import { STAGES } from "@reactive-resume/schema/applications/data";
import { PIPELINE } from "./stages";
@@ -85,7 +85,7 @@ export function computeTimeline(applications: readonly OutcomeSource[], weeks =
return buckets.map(({ label, count }) => ({ label, count }));
}
-type OutcomeSource = Pick<Application, "status" | "closedReason" | "activity" | "appliedAt" | "resumeId">;
+type OutcomeSource = Pick<ApplicationSummary, "status" | "closedReason" | "activity" | "appliedAt" | "resumeId">;
const DAY_MS = 86_400_000;
const REPLY_STAGES = new Set<ApplicationStatus>(["screening", "interview", "offer"]);
diff --git a/apps/web/src/features/applications/interviews.ts b/apps/web/src/features/applications/interviews.ts
index 6282af114..895de7c11 100644
--- a/apps/web/src/features/applications/interviews.ts
+++ b/apps/web/src/features/applications/interviews.ts
@@ -1,9 +1,9 @@
-import type { Application } from "./types";
+import type { ApplicationSummary } from "./types";
import type { InterviewKind, InterviewTimelineEntry } from "@reactive-resume/schema/applications/data";
import { INTERVIEW_KINDS } from "@reactive-resume/schema/applications/data";
export type ScheduledInterview = {
- application: Application;
+ application: ApplicationSummary;
interview: InterviewTimelineEntry;
start: Date;
end: Date;
@@ -11,11 +11,11 @@ export type ScheduledInterview = {
export const interviewKindOf = (kind: InterviewKind) => INTERVIEW_KINDS.find((item) => item.value === kind);
-export const isInterview = (entry: Application["activity"][number]): entry is InterviewTimelineEntry =>
+export const isInterview = (entry: ApplicationSummary["activity"][number]): entry is InterviewTimelineEntry =>
entry.type === "interview";
// Every interview across the given applications, soonest first.
-export function collectInterviews(applications: Application[]): ScheduledInterview[] {
+export function collectInterviews(applications: ApplicationSummary[]): ScheduledInterview[] {
return applications
.flatMap((application) =>
application.activity.filter(isInterview).map((interview) => {
diff --git a/apps/web/src/features/applications/next-step.ts b/apps/web/src/features/applications/next-step.ts
index a5e41333c..38c3551f6 100644
--- a/apps/web/src/features/applications/next-step.ts
+++ b/apps/web/src/features/applications/next-step.ts
@@ -1,4 +1,4 @@
-import type { Application } from "./types";
+import type { ApplicationSummary } from "./types";
import type { InterviewTimelineEntry } from "@reactive-resume/schema/applications/data";
import type { IconName } from "@reactive-resume/ui/components/icon";
import { plural, t } from "@lingui/core/macro";
@@ -10,7 +10,7 @@ const DAY_MS = 86_400_000;
/** Days without a reply after applying before a follow-up is suggested. */
const FOLLOW_UP_AFTER_DAYS = 10;
-type NextStepSource = Pick<Application, "status" | "activity" | "followUpAt" | "followUpNote" | "appliedAt">;
+type NextStepSource = Pick<ApplicationSummary, "status" | "activity" | "followUpAt" | "followUpNote" | "appliedAt">;
/**
* What an application needs next, derived rather than stored: the earliest interview still to come, else the
@@ -25,7 +25,7 @@ export type NextStep =
| { kind: "closed" };
/** When the application entered its current stage (its latest entry for that stage), or when it was added. */
-function stageSince(application: Pick<Application, "status" | "activity" | "appliedAt">): Date {
+function stageSince(application: Pick<ApplicationSummary, "status" | "activity" | "appliedAt">): Date {
const entries = application.activity
.filter((entry) => entry.type === "stage" && entry.stage === application.status)
.map((entry) => new Date(entry.at).getTime());
@@ -35,8 +35,10 @@ function stageSince(application: Pick<Application, "status" | "activity" | "appl
const daysBetween = (from: Date, to: Date) => Math.max(0, Math.floor((to.getTime() - from.getTime()) / DAY_MS));
/** Whole days the application has spent in its current stage. */
-export const daysInStage = (application: Pick<Application, "status" | "activity" | "appliedAt">, now = new Date()) =>
- daysBetween(stageSince(application), now);
+export const daysInStage = (
+ application: Pick<ApplicationSummary, "status" | "activity" | "appliedAt">,
+ now = new Date(),
+) => daysBetween(stageSince(application), now);
export function getNextStep(application: NextStepSource, now = new Date()): NextStep {
if (application.status === "closed") return { kind: "closed" };
@@ -73,7 +75,7 @@ const formatWhen = (date: Date, locale: string, withTime: boolean) =>
/** How a next step reads in the list, on cards and in the detail sheet. */
export function describeNextStep(
step: NextStep,
- application: Pick<Application, "status" | "closedReason">,
+ application: Pick<ApplicationSummary, "status" | "closedReason">,
locale: string,
): NextStepText {
switch (step.kind) {
diff --git a/apps/web/src/features/applications/queries.test.ts b/apps/web/src/features/applications/queries.test.ts
new file mode 100644
index 000000000..1d45680ce
--- /dev/null
+++ b/apps/web/src/features/applications/queries.test.ts
@@ -0,0 +1,149 @@
+import type { Application, ApplicationSummary } from "./types";
+import { describe, expect, it, vi } from "vite-plus/test";
+import { QueryClient, QueryObserver } from "@tanstack/react-query";
+
+const mocks = vi.hoisted(() => ({
+ query: (key: readonly unknown[]) => ({
+ queryOptions: ({ input }: { input: unknown }) => ({ queryKey: [...key, input] }),
+ queryKey: ({ input }: { input: unknown }) => [...key, input],
+ }),
+}));
+vi.mock("@/libs/orpc/client", () => ({
+ orpc: {
+ applications: {
+ listSummary: mocks.query(["applications", "summary"]),
+ list: mocks.query(["applications"]),
+ getById: mocks.query(["applications", "detail"]),
+ },
+ },
+}));
+
+import { applicationDetailQueryKey, hydrateApplicationDetail } from "./queries";
+
+const detail = (updatedAt: string, notes: string): Application =>
+ ({
+ id: "a",
+ status: "applied",
+ closedReason: null,
+ updatedAt: new Date(updatedAt),
+ notes,
+ }) as Application;
+
+const summary = (initialDetail: Application): ApplicationSummary =>
+ ({
+ id: "a",
+ status: "applied",
+ closedReason: null,
+ initialDetail,
+ }) as ApplicationSummary;
+
+describe("application detail cache hydration", () => {
+ it("replaces older cache with newer server detail and refreshes it on first open", () => {
+ const client = new QueryClient();
+ const key = applicationDetailQueryKey("a");
+ client.setQueryData(key, detail("2026-10-01T00:00:00Z", "old"));
+ const current = detail("2026-10-02T00:00:00Z", "new");
+
+ hydrateApplicationDetail(client, summary(current));
+ expect(client.getQueryData<Application>(key)?.notes).toBe("new");
+ expect(client.getQueryState(key)?.dataUpdatedAt).toBe(0);
+ });
+
+ it("never lets an older refreshed list overwrite newer cached detail", () => {
+ const client = new QueryClient();
+ const key = applicationDetailQueryKey("a");
+ client.setQueryData(key, detail("2026-10-02T00:00:00Z", "new"));
+ const old = detail("2026-10-01T00:00:00Z", "old");
+
+ const updatedAt = client.getQueryState(key)?.dataUpdatedAt;
+ hydrateApplicationDetail(client, summary(old));
+ expect(client.getQueryData<Application>(key)?.notes).toBe("new");
+ expect(client.getQueryState(key)?.dataUpdatedAt).toBe(updatedAt);
+ });
+
+ it("does not hydrate a detail whose stage no longer matches optimistic list state", () => {
+ const client = new QueryClient();
+ const old = detail("2026-10-01T00:00:00Z", "old");
+ const closed = { ...summary(old), status: "closed" } as ApplicationSummary;
+
+ hydrateApplicationDetail(client, closed);
+ expect(client.getQueryData<Application>(applicationDetailQueryKey("a"))).toBeUndefined();
+ });
+
+ it("cancels an older in-flight response before accepting refreshed list detail", async () => {
+ const client = new QueryClient();
+ const key = applicationDetailQueryKey("a");
+ let resolveOld!: (value: Application) => void;
+ const oldFetch = client.fetchQuery({
+ queryKey: key,
+ queryFn: () =>
+ new Promise<Application>((resolve) => {
+ resolveOld = resolve;
+ }),
+ });
+ await Promise.resolve();
+ const current = detail("2026-10-02T00:00:00Z", "new");
+ hydrateApplicationDetail(client, summary(current));
+ resolveOld(detail("2026-10-01T00:00:00Z", "old"));
+ await oldFetch.catch(() => undefined);
+ expect(client.getQueryData<Application>(key)?.notes).toBe("new");
+ });
+
+ it("keeps a newer detail refresh running when an older list arrives", async () => {
+ const client = new QueryClient();
+ const key = applicationDetailQueryKey("a");
+ client.setQueryData(key, detail("2026-10-02T00:00:00Z", "cached"));
+ let resolveRefresh!: (value: Application) => void;
+ const refresh = client.fetchQuery({
+ queryKey: key,
+ queryFn: () =>
+ new Promise<Application>((resolve) => {
+ resolveRefresh = resolve;
+ }),
+ });
+ hydrateApplicationDetail(client, summary(detail("2026-10-01T00:00:00Z", "old")));
+ expect(client.getQueryState(key)?.fetchStatus).toBe("fetching");
+ resolveRefresh(detail("2026-10-03T00:00:00Z", "refreshed"));
+ await refresh;
+ expect(client.getQueryData<Application>(key)?.notes).toBe("refreshed");
+ });
+
+ it("shows stale initial detail immediately, refreshes once, then reuses fetched cache", async () => {
+ const client = new QueryClient();
+ const key = applicationDetailQueryKey("a");
+ const initial = detail("2026-10-01T00:00:00Z", "initial");
+ hydrateApplicationDetail(client, summary(initial));
+ let calls = 0;
+ const observer = new QueryObserver<Application>(client, {
+ queryKey: key,
+ staleTime: 60_000,
+ queryFn: async () => {
+ calls += 1;
+ return detail("2026-10-02T00:00:00Z", "refreshed");
+ },
+ });
+ const seen: string[] = [];
+ const unsubscribe = observer.subscribe((result) => {
+ if (result.data) seen.push(result.data.notes ?? "");
+ });
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ expect(seen[0]).toBe("initial");
+ expect(calls).toBe(1);
+ expect(client.getQueryData<Application>(key)?.notes).toBe("refreshed");
+ unsubscribe();
+ observer.destroy();
+
+ const second = new QueryObserver<Application>(client, {
+ queryKey: key,
+ staleTime: 60_000,
+ queryFn: async () => {
+ calls += 1;
+ return detail("2026-10-03T00:00:00Z", "unexpected");
+ },
+ });
+ second.subscribe(() => undefined);
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ expect(calls).toBe(1);
+ second.destroy();
+ });
+});
diff --git a/apps/web/src/features/applications/queries.ts b/apps/web/src/features/applications/queries.ts
index a2ccdfd04..e657c6267 100644
--- a/apps/web/src/features/applications/queries.ts
+++ b/apps/web/src/features/applications/queries.ts
@@ -1,8 +1,33 @@
+import type { Application, ApplicationSummary } from "./types";
+import type { QueryClient } from "@tanstack/react-query";
import { orpc } from "@/libs/orpc/client";
-// A single source of truth for the applications list query so the query key stays identical
+// A single source of truth for the lightweight applications list query so the query key stays identical
// across the board (optimistic drag), the detail panel, and the route.
-const LIST_INPUT = {} as const;
+const LIST_INPUT = { includeInitialDetails: 3 } as const;
+const FULL_LIST_INPUT = {} as const;
-export const applicationsListQueryOptions = () => orpc.applications.list.queryOptions({ input: LIST_INPUT });
-export const applicationsListQueryKey = () => orpc.applications.list.queryKey({ input: LIST_INPUT });
+export const applicationsListQueryOptions = () => orpc.applications.listSummary.queryOptions({ input: LIST_INPUT });
+export const applicationsListQueryKey = () => orpc.applications.listSummary.queryKey({ input: LIST_INPUT });
+export const applicationsFullListQueryOptions = () => orpc.applications.list.queryOptions({ input: FULL_LIST_INPUT });
+
+export const applicationDetailQueryOptions = (id: string) => orpc.applications.getById.queryOptions({ input: { id } });
+export const applicationDetailQueryKey = (id: string) => applicationDetailQueryOptions(id).queryKey;
+
+export function getInitialApplicationDetail(summary: ApplicationSummary | null | undefined) {
+ const detail = summary?.initialDetail;
+ return detail && detail.status === summary.status && detail.closedReason === summary.closedReason
+ ? detail
+ : undefined;
+}
+
+export function hydrateApplicationDetail(queryClient: QueryClient, summary: ApplicationSummary) {
+ const detail = getInitialApplicationDetail(summary);
+ if (!detail) return;
+ const detailKey = applicationDetailQueryOptions(summary.id).queryKey;
+ const existing = queryClient.getQueryData<Application>(detailKey);
+ if (existing && existing.updatedAt.getTime() >= detail.updatedAt.getTime()) return;
+ void queryClient.cancelQueries({ queryKey: detailKey }, { revert: false });
+ // List snapshots render immediately, then refresh on the first detail open.
+ queryClient.setQueryData(detailKey, detail, { updatedAt: 0 });
+}
diff --git a/apps/web/src/features/applications/types.ts b/apps/web/src/features/applications/types.ts
index e5f6e83a8..26f48718b 100644
--- a/apps/web/src/features/applications/types.ts
+++ b/apps/web/src/features/applications/types.ts
@@ -1,3 +1,4 @@
import type { RouterOutput } from "@/libs/orpc/client";
export type Application = RouterOutput["applications"]["list"][number];
+export type ApplicationSummary = RouterOutput["applications"]["listSummary"][number];
diff --git a/apps/web/src/features/applications/use-application-actions.ts b/apps/web/src/features/applications/use-application-actions.ts
index 8f0eb9552..7d7cbdfc1 100644
--- a/apps/web/src/features/applications/use-application-actions.ts
+++ b/apps/web/src/features/applications/use-application-actions.ts
@@ -1,4 +1,4 @@
-import type { Application } from "./types";
+import type { ApplicationSummary } from "./types";
import type { ApplicationClosedReason, ApplicationStatus } from "@reactive-resume/schema/applications/data";
import { t } from "@lingui/core/macro";
import { useMutation, useQueryClient } from "@tanstack/react-query";
@@ -34,10 +34,10 @@ export function useApplicationActions() {
...orpc.applications.update.mutationOptions(),
onMutate: async (input) => {
await queryClient.cancelQueries({ queryKey: listKey });
- const previous = queryClient.getQueryData<Application[]>(listKey);
+ const previous = queryClient.getQueryData<ApplicationSummary[]>(listKey);
const status = input.status as ApplicationStatus | undefined;
- queryClient.setQueryData<Application[]>(listKey, (rows) =>
- rows?.map((row): Application =>
+ queryClient.setQueryData<ApplicationSummary[]>(listKey, (rows) =>
+ rows?.map((row): ApplicationSummary =>
row.id === input.id
? {
...row,
@@ -77,9 +77,9 @@ export function useApplicationActions() {
return {
update,
remove,
- moveTo: (application: Pick<Application, "id">, status: ApplicationStatus) =>
+ moveTo: (application: Pick<ApplicationSummary, "id">, status: ApplicationStatus) =>
update.mutate({ id: application.id, status }),
- close: (application: Pick<Application, "id">, closedReason: ApplicationClosedReason) =>
+ close: (application: Pick<ApplicationSummary, "id">, closedReason: ApplicationClosedReason) =>
update.mutate({ id: application.id, status: "closed", closedReason }),
};
}
diff --git a/apps/web/src/features/command-palette/pages/resumes.tsx b/apps/web/src/features/command-palette/pages/resumes.tsx
index b077dc1f2..56860bcbe 100644
--- a/apps/web/src/features/command-palette/pages/resumes.tsx
+++ b/apps/web/src/features/command-palette/pages/resumes.tsx
@@ -13,7 +13,7 @@ import { useDialogStore } from "@/dialogs/store";
import { applicationsListQueryOptions } from "@/features/applications/queries";
import { orpc } from "@/libs/orpc/client";
-type Application = RouterOutput["applications"]["list"][number];
+type Application = RouterOutput["applications"]["listSummary"][number];
type Thread = RouterOutput["agent"]["threads"]["list"][number];
type SearchPage = "resumes" | "applications" | "threads";
type SearchPageProps = { page: SearchPage };
diff --git a/apps/web/src/features/resume/editor/check/job-match.test.tsx b/apps/web/src/features/resume/editor/check/job-match.test.tsx
new file mode 100644
index 000000000..4c903cce1
--- /dev/null
+++ b/apps/web/src/features/resume/editor/check/job-match.test.tsx
@@ -0,0 +1,73 @@
+// @vitest-environment happy-dom
+import { fireEvent, render, screen, waitFor } from "@testing-library/react";
+import { expect, it, vi } from "vite-plus/test";
+import { i18n } from "@lingui/core";
+import { I18nProvider } from "@lingui/react";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { defaultResumeData } from "@reactive-resume/schema/resume/default";
+
+const api = vi.hoisted(() => ({
+ application: { id: "job-a", company: "Example", role: "Engineer", jobDescription: null as string | null },
+ update: vi.fn(async (input: { jobDescription: string }) => {
+ api.application = { ...api.application, jobDescription: input.jobDescription };
+ return api.application;
+ }),
+}));
+vi.mock("@/libs/orpc/client", () => ({
+ orpc: {
+ applications: {
+ getById: {
+ queryKey: ({ input }: { input: { id: string } }) => ["applications", "detail", input],
+ queryOptions: ({ input }: { input: { id: string } }) => ({
+ queryKey: ["applications", "detail", input],
+ queryFn: async () => api.application,
+ }),
+ },
+ listSummary: { queryKey: () => ["applications", "summary"] },
+ update: { mutationOptions: () => ({ mutationFn: api.update }) },
+ },
+ documents: { linkApplication: { mutationOptions: () => ({ mutationFn: vi.fn() }) } },
+ },
+}));
+vi.mock("@/features/resume/builder/draft", () => ({
+ useCurrentBuilderResumeSelector: (select: (resume: { id: string; applicationId: string }) => unknown) =>
+ select({ id: "resume-a", applicationId: "job-a" }),
+ useIsResumeLocked: () => false,
+ usePatchResume: () => vi.fn(),
+}));
+vi.mock("@/features/assistant/open", () => ({ openAssistantFrom: vi.fn() }));
+vi.mock("./actions", () => ({ checkStateOf: vi.fn(), editWithUndo: vi.fn() }));
+vi.mock("@reactive-resume/resume/ats-pdf", () => ({ matchJobDescription: () => ({ terms: [] }) }));
+
+import { JobMatchTab, useJobMatch } from "./job-match";
+
+function Match() {
+ const match = useJobMatch(undefined);
+ return (
+ <>
+ <output data-testid="posting">{match.posting}</output>
+ <JobMatchTab match={match} data={defaultResumeData} />
+ </>
+ );
+}
+
+it("matches a newly saved posting without reopening the linked application", async () => {
+ i18n.loadAndActivate({ locale: "en", messages: {} });
+ const client = new QueryClient({ defaultOptions: { queries: { staleTime: 60_000, retry: false } } });
+ client.setQueryData(["applications", "detail", { id: "job-a" }], api.application);
+ const view = render(
+ <QueryClientProvider client={client}>
+ <I18nProvider i18n={i18n}>
+ <Match />
+ </I18nProvider>
+ </QueryClientProvider>,
+ );
+ fireEvent.change(screen.getByRole("textbox", { name: "Job posting" }), {
+ target: { value: "TypeScript engineer" },
+ });
+ fireEvent.click(screen.getByRole("button", { name: "Save to the application" }));
+ await waitFor(() => expect(api.update).toHaveBeenCalled());
+ await waitFor(() => expect(screen.getByTestId("posting").textContent).toBe("TypeScript engineer"));
+ view.unmount();
+ client.clear();
+});
diff --git a/apps/web/src/features/resume/editor/check/job-match.tsx b/apps/web/src/features/resume/editor/check/job-match.tsx
index 4b136ca44..d2207c5ae 100644
--- a/apps/web/src/features/resume/editor/check/job-match.tsx
+++ b/apps/web/src/features/resume/editor/check/job-match.tsx
@@ -52,9 +52,12 @@ const loadAtsPdf = () => import("@reactive-resume/resume/ats-pdf");
export function useJobMatch(data: ResumeData | undefined): JobMatch {
const applicationId = useCurrentBuilderResumeSelector((resume) => resume.applicationId ?? null);
const pasted = useEditorStore((state) => state.pastedPosting);
- const { data: applications } = useQuery(applicationsListQueryOptions());
- const application = applications?.find((entry) => entry.id === applicationId) ?? null;
- const posting = application ? (application.jobDescription ?? "").trim() : pasted.trim();
+ const { data: application } = useQuery({
+ ...orpc.applications.getById.queryOptions({ input: { id: applicationId ?? "" } }),
+ enabled: Boolean(applicationId),
+ });
+ const selectedApplication = application ?? null;
+ const posting = selectedApplication ? (selectedApplication.jobDescription ?? "").trim() : pasted.trim();
// The matcher (stemmer and skill aliases) loads only once there's a posting to match.
const { data: engine } = useQuery({
@@ -82,7 +85,7 @@ export function useJobMatch(data: ResumeData | undefined): JobMatch {
};
}, [engine, posting, resumeText, hiddenTerms]);
- return { application, posting, result, hiddenTerms: hiddenTerms ?? [] };
+ return { application: selectedApplication, posting, result, hiddenTerms: hiddenTerms ?? [] };
}
/** The first spelling of a term the posting uses, as it writes it ("Figma", not "figma"). */
@@ -419,7 +422,13 @@ function NoPosting({ application }: { application: JobMatch["application"] }) {
const queryClient = useQueryClient();
const { mutate: savePosting, isPending: saving } = useMutation({
...orpc.applications.update.mutationOptions(),
- onSuccess: () => queryClient.invalidateQueries({ queryKey: applicationsListQueryKey() }),
+ onSuccess: (_data, input) =>
+ Promise.all([
+ queryClient.invalidateQueries({ queryKey: applicationsListQueryKey() }),
+ queryClient.invalidateQueries({
+ queryKey: orpc.applications.getById.queryKey({ input: { id: input.id } }),
+ }),
+ ]),
onError: (error) => toastError(error, t`Couldn't save the posting. Try again.`),
});
diff --git a/apps/web/src/routes/builder/letter/-components/write-panel.tsx b/apps/web/src/routes/builder/letter/-components/write-panel.tsx
index 7e555d51f..635f34630 100644
--- a/apps/web/src/routes/builder/letter/-components/write-panel.tsx
+++ b/apps/web/src/routes/builder/letter/-components/write-panel.tsx
@@ -1,4 +1,4 @@
-import type { Application } from "@/features/applications/types";
+import type { ApplicationSummary } from "@/features/applications/types";
import type { LetterDraft } from "@/features/letters/store";
import type { CoverLetter } from "@reactive-resume/schema/cover-letter/data";
import type { CSSProperties, ReactElement, ReactNode } from "react";
@@ -112,8 +112,8 @@ export function LetterWritePanel() {
type ForSectionProps = {
letter: CoverLetter;
- application: Application | null;
- applications: Application[];
+ application: ApplicationSummary | null;
+ applications: ApplicationSummary[];
disabled: boolean;
};
@@ -121,7 +121,7 @@ type ForSectionProps = {
function ForSection({ letter, application, applications, disabled }: ForSectionProps) {
const choices = applications.filter((item) => item.status !== "closed" || item.id === application?.id);
- const choose = (next: Application | null) =>
+ const choose = (next: ApplicationSummary | null) =>
void updateLetter({
applicationId: next?.id ?? null,
// The recipient comes from the application: its company, and its first contact when it has one.
@@ -208,7 +208,7 @@ function ForSection({ letter, application, applications, disabled }: ForSectionP
);
}
-type LetterSectionProps = { letter: CoverLetter; application: Application | null; disabled: boolean };
+type LetterSectionProps = { letter: CoverLetter; application: ApplicationSummary | null; disabled: boolean };
/** TO: name or team, company and date for structured letters; older (freeform) letters keep their recipient block. */
function ToSection({ letter, application, disabled }: LetterSectionProps) {
@@ -455,7 +455,12 @@ function LetterFramingField({ letter, field, defaultValue, disabled }: LetterFra
);
}
-type EmptyBodyProps = { letter: CoverLetter; application: Application | null; disabled: boolean; onWrite: () => void };
+type EmptyBodyProps = {
+ letter: CoverLetter;
+ application: ApplicationSummary | null;
+ disabled: boolean;
+ onWrite: () => void;
+};
function EmptyBody({ letter, application, disabled, onWrite }: EmptyBodyProps) {
const providerState = useHasUsableAiProvider();
@@ -509,7 +514,7 @@ function EmptyBody({ letter, application, disabled, onWrite }: EmptyBodyProps) {
type DraftBoxProps = {
draft: Exclude<LetterDraft, { phase: "idle" }>;
letter: CoverLetter;
- application: Application | null;
+ application: ApplicationSummary | null;
onKeep: (text: string) => void;
};
diff --git a/apps/web/src/routes/dashboard/-components/app-shell.tsx b/apps/web/src/routes/dashboard/-components/app-shell.tsx
index 337c9d911..033e48a29 100644
--- a/apps/web/src/routes/dashboard/-components/app-shell.tsx
+++ b/apps/web/src/routes/dashboard/-components/app-shell.tsx
@@ -16,7 +16,6 @@ import { getInitials } from "@reactive-resume/utils/string";
import { cn } from "@reactive-resume/utils/style";
import { MobileTabIndicator } from "@/components/layout/mobile-tab-indicator";
import { useDialogStore } from "@/dialogs/store";
-import { applicationsListQueryOptions } from "@/features/applications/queries";
import { GuestBanner } from "@/features/auth/components/guest-banner";
import { useCommandPaletteStore } from "@/features/command-palette/store";
import { isEditableElementFocused } from "@/features/resume/builder/draft";
@@ -32,7 +31,7 @@ type NavItem = {
function useNavItems() {
const { data: counts } = useQuery(orpc.documents.counts.queryOptions());
- const { data: applications } = useQuery(applicationsListQueryOptions());
+ const { data: applicationStats } = useQuery(orpc.applications.stats.queryOptions({}));
const { data: notifications } = useQuery(orpc.career.notifications.queryOptions({ input: {} }));
const items: NavItem[] = [
@@ -46,7 +45,13 @@ function useNavItems() {
to: "/dashboard/applications",
icon: "briefcase",
label: t`Applications`,
- ...(applications ? { count: applications.filter((application) => application.status !== "closed").length } : {}),
+ ...(applicationStats
+ ? {
+ count: applicationStats.byStage
+ .filter((row) => row.status !== "closed")
+ .reduce((total, row) => total + row.count, 0),
+ }
+ : {}),
},
];
const unread = notifications?.filter((notification) => !notification.readAt).length ?? 0;
diff --git a/apps/web/src/routes/dashboard/applications/index.tsx b/apps/web/src/routes/dashboard/applications/index.tsx
index 0e7ff7fef..d6e68abf0 100644
--- a/apps/web/src/routes/dashboard/applications/index.tsx
+++ b/apps/web/src/routes/dashboard/applications/index.tsx
@@ -1,9 +1,9 @@
-import type { Application } from "@/features/applications/types";
+import type { Application, ApplicationSummary } from "@/features/applications/types";
import { t } from "@lingui/core/macro";
import { Plural, Trans } from "@lingui/react/macro";
-import { useQuery } from "@tanstack/react-query";
+import { useQuery, useQueryClient } from "@tanstack/react-query";
import { createFileRoute, stripSearchParams, useNavigate } from "@tanstack/react-router";
-import { useDeferredValue, useEffect, useState } from "react";
+import { useCallback, useDeferredValue, useEffect, useRef, useState } from "react";
import z from "zod";
import { Button } from "@reactive-resume/ui/components/button";
import {
@@ -29,7 +29,13 @@ import { ImportApplicationsSheet } from "@/features/applications/components/impo
import { ApplicationInsights, InsightsSkeleton } from "@/features/applications/components/insights-view";
import { ApplicationList } from "@/features/applications/components/list-view";
import { getNextStep } from "@/features/applications/next-step";
-import { applicationsListQueryOptions } from "@/features/applications/queries";
+import {
+ applicationDetailQueryOptions,
+ applicationsFullListQueryOptions,
+ applicationsListQueryOptions,
+ hydrateApplicationDetail,
+} from "@/features/applications/queries";
+import { toastError } from "@/libs/error-message";
import { ENTER_CLASS } from "@/libs/motion";
const VIEWS = ["list", "board", "insights", "calendar"] as const;
@@ -53,7 +59,7 @@ export const Route = createFileRoute("/dashboard/applications/")({
});
/** Search reads role, company, location, contacts and tags. */
-function matches(application: Application, query: string) {
+function matches(application: ApplicationSummary, query: string) {
if (!query) return true;
const haystack = [
application.role,
@@ -76,12 +82,75 @@ function RouteComponent() {
const [adding, setAdding] = useState(false);
const [importing, setImporting] = useState(false);
const [exporting, setExporting] = useState(false);
+ const [exportLoading, setExportLoading] = useState(false);
const [editing, setEditing] = useState<Application | null>(null);
const [selectedId, setSelectedId] = useState<string | null>(null);
// Views animate in only after a switch, never on the page's first render.
const [viewSwitched, setViewSwitched] = useState(false);
const { data: applications, isPending, isError, isFetching, refetch } = useQuery(applicationsListQueryOptions());
+ const queryClient = useQueryClient();
+ const { data: fullApplications } = useQuery({ ...applicationsFullListQueryOptions(), enabled: exporting });
+
+ const PREFETCH_LIMIT = 12;
+ const prefetchInFlight = useRef(new Set<string>());
+ const prefetch = useCallback(
+ (id: string) => {
+ const options = applicationDetailQueryOptions(id);
+ if (
+ prefetchInFlight.current.has(id) ||
+ prefetchInFlight.current.size >= PREFETCH_LIMIT ||
+ queryClient.getQueryData(options.queryKey) ||
+ queryClient.getQueryState(options.queryKey)?.fetchStatus === "fetching"
+ )
+ return;
+ prefetchInFlight.current.add(id);
+ void queryClient
+ .fetchQuery(options)
+ .catch(() => {})
+ .finally(() => prefetchInFlight.current.delete(id));
+ },
+ [queryClient],
+ );
+
+ useEffect(() => {
+ if (!applications) return;
+ for (const application of applications) hydrateApplicationDetail(queryClient, application);
+ }, [applications, queryClient]);
+
+ useEffect(() => {
+ let timer: number | undefined;
+ const openControl = (target: EventTarget | null) =>
+ target instanceof Element ? target.closest<HTMLElement>("[data-application-open]") : null;
+ const onPointerOver = (event: PointerEvent) => {
+ const open = openControl(event.target);
+ if (!open || open.contains(event.relatedTarget as Node | null)) return;
+ const id = open.closest<HTMLElement>("[data-application-id]")?.dataset.applicationId;
+ if (!id) return;
+ window.clearTimeout(timer);
+ timer = window.setTimeout(() => prefetch(id), 120);
+ };
+ const onPointerOut = (event: PointerEvent) => {
+ const open = openControl(event.target);
+ if (open && !open.contains(event.relatedTarget as Node | null)) window.clearTimeout(timer);
+ };
+ const onFocusIn = (event: FocusEvent) => {
+ const id = openControl(event.target)?.closest<HTMLElement>("[data-application-id]")?.dataset.applicationId;
+ if (id) {
+ window.clearTimeout(timer);
+ prefetch(id);
+ }
+ };
+ document.addEventListener("pointerover", onPointerOver);
+ document.addEventListener("pointerout", onPointerOut);
+ document.addEventListener("focusin", onFocusIn);
+ return () => {
+ document.removeEventListener("pointerover", onPointerOver);
+ document.removeEventListener("pointerout", onPointerOut);
+ document.removeEventListener("focusin", onFocusIn);
+ window.clearTimeout(timer);
+ };
+ }, [prefetch]);
const setSearch = (patch: Partial<Search>) =>
void navigate({ resetScroll: false, search: (prev: Search) => ({ ...prev, ...patch }) });
@@ -111,8 +180,25 @@ function RouteComponent() {
const shown: View = phone && (view === "board" || view === "calendar") ? "list" : view;
const empty = !!applications && applications.length === 0;
// Hoisted so the compiler keeps one function; inline, it changes with every keystroke and re-renders each row.
- const openApplication = (application: Application) => setSelectedId(application.id);
+ const openApplication = (application: ApplicationSummary) => {
+ hydrateApplicationDetail(queryClient, application);
+ setSelectedId(application.id);
+ };
const noMatches = !!applications && !empty && text && filtered.length === 0;
+ const filteredIds = new Set(filtered.map((application) => application.id));
+ const filteredFullApplications = fullApplications?.filter((application) => filteredIds.has(application.id)) ?? [];
+ const openExport = async () => {
+ if (exportLoading) return;
+ setExportLoading(true);
+ try {
+ await queryClient.fetchQuery({ ...applicationsFullListQueryOptions(), staleTime: 0 });
+ setExporting(true);
+ } catch (error) {
+ toastError(error, t`Couldn't load this. Your saved data hasn't changed.`);
+ } finally {
+ setExportLoading(false);
+ }
+ };
return (
<div className="mx-auto grid w-full max-w-[1180px] content-start gap-5 px-8 py-8 max-sm:px-4 max-sm:py-5">
@@ -130,7 +216,7 @@ function RouteComponent() {
<DropdownMenuItem onClick={() => setImporting(true)}>
<Trans>Import from CSV…</Trans>
</DropdownMenuItem>
- <DropdownMenuItem disabled={empty || !applications} onClick={() => setExporting(true)}>
+ <DropdownMenuItem disabled={empty || !applications || exportLoading} onClick={() => void openExport()}>
<Trans>Export to CSV…</Trans>
</DropdownMenuItem>
</DropdownMenuContent>
@@ -283,8 +369,8 @@ function RouteComponent() {
<ExportApplicationsSheet
open={exporting}
onOpenChange={setExporting}
- applications={applications ?? []}
- filtered={filtered.filter((application) => closed || application.status !== "closed")}
+ applications={fullApplications ?? []}
+ filtered={filteredFullApplications.filter((application) => closed || application.status !== "closed")}
/>
<ApplicationDetailSheet
application={selected}
@@ -308,11 +394,13 @@ function readDismissed(): string[] {
}
}
+type FollowUpNudgeProps = { applications: ApplicationSummary[]; onOpen: (id: string) => void };
+
/**
* The follow-up nudge: the application waiting longest without a reply (10+ days since applying). Dismissing it is
* remembered on this device; it doesn't come back for that application.
*/
-function FollowUpNudge({ applications, onOpen }: { applications: Application[]; onOpen: (id: string) => void }) {
+function FollowUpNudge({ applications, onOpen }: FollowUpNudgeProps) {
const [dismissed, setDismissed] = useState(readDismissed);
const dismissedIds = new Set(dismissed);
@@ -341,6 +429,7 @@ function FollowUpNudge({ applications, onOpen }: { applications: Application[];
return (
<div
key={waiting.application.id}
+ data-application-id={waiting.application.id}
role="status"
className={cn(
ENTER_CLASS,
@@ -355,7 +444,7 @@ function FollowUpNudge({ applications, onOpen }: { applications: Application[];
other={`${company}: no reply for # days. A short follow-up is usually fine now.`}
/>
</span>
- <Button size="sm" variant="secondary" onClick={() => onOpen(waiting.application.id)}>
+ <Button size="sm" variant="secondary" data-application-open onClick={() => onOpen(waiting.application.id)}>
<Trans>Open</Trans>
</Button>
<Button size="icon-sm" variant="ghost" aria-label={t`Dismiss`} onClick={dismiss} className="text-warn-text">
diff --git a/docs/guides/using-the-api.mdx b/docs/guides/using-the-api.mdx
index 27d468c58..fea4eced2 100644
--- a/docs/guides/using-the-api.mdx
+++ b/docs/guides/using-the-api.mdx
@@ -178,6 +178,10 @@ Exports accept `pdf`, `docx`, `md` or `json` and return a downloadable file. The
Collection endpoints support `limit` (1–100) and `offset` (zero-based). For existing array responses, omitting both preserves the complete array for compatibility. Supplying only `offset` selects a page size of 20. The `X-Total-Count` header reports the total before slicing; paginated responses also include `X-Limit` and `X-Offset`. The cover-letter list retains its existing `{ items, total }` response and default pagination.
+Applications also expose `GET /applications/summary` for list views. It accepts the same `status`, `tags`, `limit` and `offset` parameters as `GET /applications`, but returns only lightweight list fields and stage/interview activity; job descriptions, notes, requirements, AI metadata and uploaded document fields are omitted. Use `GET /applications/{id}` when you need one application's full details. The original `/applications` response remains unchanged for integrations that need the complete application object.
+
+Set `includeInitialDetails` (0–6) to attach full `initialDetail` objects for the first few applications in the web and mobile default list orders. A value of N includes the union of each client's first N rows, so at most 2N rows receive full details; closed applications are excluded unless explicitly selected with `status`. Omit the parameter to keep the response entirely lightweight.
+
```bash
curl "https://rxresu.me/api/openapi/resumes?limit=20&offset=20" \
-H "x-api-key: YOUR_API_KEY" -i
diff --git a/docs/spec.json b/docs/spec.json
index c2f57725e..ecaceef87 100644
--- a/docs/spec.json
+++ b/docs/spec.json
@@ -16113,6 +16113,1136 @@
]
}
},
+ "/applications/summary": {
+ "get": {
+ "operationId": "listApplicationSummaries",
+ "summary": "List application summaries",
+ "description": "Returns lightweight application summaries for list views. Full descriptions, notes, documents and timeline notes are omitted; use the application endpoint for full detail. When includeInitialDetails is N, up to 2N full details may be attached as initialDetail: the union of the first N candidates under web and mobile ordering, with closed applications excluded unless status is provided.",
+ "tags": [
+ "Applications"
+ ],
+ "parameters": [
+ {
+ "name": "limit",
+ "in": "query",
+ "schema": {
+ "type": "integer",
+ "minimum": 1,
+ "maximum": 100,
+ "description": "Maximum results (1–100). Omit both pagination fields for the legacy complete list."
+ },
+ "allowEmptyValue": true,
+ "allowReserved": true
+ },
+ {
+ "name": "offset",
+ "in": "query",
+ "schema": {
+ "type": "integer",
+ "minimum": 0,
+ "maximum": 9007199254740991,
+ "description": "Zero-based offset. Defaults to 0; limit defaults to 20 when only offset is given."
+ },
+ "allowEmptyValue": true,
+ "allowReserved": true
+ },
+ {
+ "name": "status",
+ "in": "query",
+ "schema": {
+ "enum": [
+ "saved",
+ "applied",
+ "screening",
+ "interview",
+ "offer",
+ "closed"
+ ],
+ "type": "string"
+ },
+ "allowEmptyValue": true,
+ "allowReserved": true
+ },
+ {
+ "name": "tags",
+ "in": "query",
+ "schema": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ },
+ "style": "deepObject",
+ "explode": true,
+ "allowEmptyValue": true,
+ "allowReserved": true
+ },
+ {
+ "name": "includeInitialDetails",
+ "in": "query",
+ "schema": {
+ "type": "integer",
+ "minimum": 0,
+ "maximum": 6
+ },
+ "allowEmptyValue": true,
+ "allowReserved": true
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "A list of lightweight application summaries.",
+ "content": {
+ "application/json": {
+ "schema": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "properties": {
+ "id": {
+ "type": "string",
+ "description": "The ID of the application."
+ },
+ "company": {
+ "type": "string",
+ "minLength": 1,
+ "description": "The company applied to."
+ },
+ "role": {
+ "type": "string",
+ "minLength": 1,
+ "description": "The role / job title."
+ },
+ "location": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "salary": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "status": {
+ "enum": [
+ "saved",
+ "applied",
+ "screening",
+ "interview",
+ "offer",
+ "closed"
+ ],
+ "type": "string",
+ "description": "The current pipeline stage. `closed` ends it, with a reason."
+ },
+ "closedReason": {
+ "anyOf": [
+ {
+ "enum": [
+ "accepted",
+ "not-selected",
+ "withdrew",
+ "accepted-other",
+ "no-response"
+ ],
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Why a closed application ended: accepted, not-selected, withdrew, accepted-other or no-response."
+ },
+ "resumeId": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "The linked Reactive Resume, if any."
+ },
+ "coverLetterId": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "The linked saved cover letter, if any."
+ },
+ "source": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "tags": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ },
+ "sourceUrl": {
+ "anyOf": [
+ {
+ "type": "string",
+ "format": "uri"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "matchScore": {
+ "anyOf": [
+ {
+ "type": "integer",
+ "minimum": 0,
+ "maximum": 100
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "followUpAt": {
+ "anyOf": [
+ {
+ "type": "string",
+ "format": "date-time",
+ "x-native-type": "date"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "followUpNote": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "contacts": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "properties": {
+ "name": {
+ "type": "string",
+ "minLength": 1
+ },
+ "role": {
+ "type": "string",
+ "default": ""
+ },
+ "type": {
+ "type": "string",
+ "default": ""
+ },
+ "email": {
+ "type": "string",
+ "default": ""
+ },
+ "phone": {
+ "type": "string",
+ "default": ""
+ }
+ },
+ "required": [
+ "name"
+ ]
+ }
+ },
+ "activity": {
+ "type": "array",
+ "items": {
+ "anyOf": [
+ {
+ "type": "object",
+ "properties": {
+ "id": {
+ "type": "string",
+ "minLength": 1
+ },
+ "at": {
+ "type": "string",
+ "format": "date-time",
+ "x-native-type": "date"
+ },
+ "type": {
+ "const": "stage"
+ },
+ "stage": {
+ "enum": [
+ "saved",
+ "applied",
+ "screening",
+ "interview",
+ "offer",
+ "closed"
+ ],
+ "type": "string"
+ }
+ },
+ "required": [
+ "id",
+ "at",
+ "type",
+ "stage"
+ ]
+ },
+ {
+ "type": "object",
+ "properties": {
+ "id": {
+ "type": "string",
+ "minLength": 1
+ },
+ "at": {
+ "type": "string",
+ "format": "date-time",
+ "x-native-type": "date"
+ },
+ "type": {
+ "const": "note"
+ },
+ "text": {
+ "type": "string",
+ "minLength": 1
+ }
+ },
+ "required": [
+ "id",
+ "at",
+ "type",
+ "text"
+ ]
+ },
+ {
+ "type": "object",
+ "properties": {
+ "id": {
+ "type": "string",
+ "minLength": 1
+ },
+ "at": {
+ "type": "string",
+ "format": "date-time",
+ "x-native-type": "date"
+ },
+ "type": {
+ "const": "interview"
+ },
+ "kind": {
+ "enum": [
+ "screening",
+ "technical",
+ "behavioral",
+ "onsite",
+ "other"
+ ],
+ "type": "string"
+ },
+ "durationMinutes": {
+ "type": "integer",
+ "minimum": 5,
+ "maximum": 1440,
+ "default": 60
+ },
+ "location": {
+ "type": "string",
+ "maxLength": 500,
+ "default": ""
+ },
+ "notes": {
+ "type": "string",
+ "maxLength": 5000,
+ "default": ""
+ },
+ "participants": {
+ "type": "array",
+ "maxItems": 20,
+ "items": {
+ "type": "object",
+ "properties": {
+ "name": {
+ "type": "string",
+ "minLength": 1,
+ "maxLength": 200
+ },
+ "role": {
+ "type": "string",
+ "maxLength": 200,
+ "default": ""
+ },
+ "profileUrl": {
+ "type": "string",
+ "maxLength": 2048,
+ "format": "uri"
+ }
+ },
+ "required": [
+ "name"
+ ]
+ },
+ "default": []
+ },
+ "audience": {
+ "enum": [
+ "recruiter",
+ "hiring-manager",
+ "practitioner",
+ "panel",
+ "other"
+ ],
+ "type": "string",
+ "default": "other"
+ },
+ "timezone": {
+ "type": "string",
+ "minLength": 1,
+ "maxLength": 100,
+ "default": "UTC"
+ }
+ },
+ "required": [
+ "id",
+ "at",
+ "type",
+ "kind"
+ ]
+ }
+ ]
+ }
+ },
+ "appliedAt": {
+ "type": "string",
+ "format": "date-time",
+ "x-native-type": "date"
+ },
+ "createdAt": {
+ "type": "string",
+ "format": "date-time",
+ "x-native-type": "date"
+ },
+ "updatedAt": {
+ "type": "string",
+ "format": "date-time",
+ "x-native-type": "date"
+ },
+ "initialDetail": {
+ "type": "object",
+ "properties": {
+ "id": {
+ "type": "string",
+ "description": "The ID of the application."
+ },
+ "company": {
+ "type": "string",
+ "minLength": 1,
+ "description": "The company applied to."
+ },
+ "role": {
+ "type": "string",
+ "minLength": 1,
+ "description": "The role / job title."
+ },
+ "location": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "salary": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "status": {
+ "enum": [
+ "saved",
+ "applied",
+ "screening",
+ "interview",
+ "offer",
+ "closed"
+ ],
+ "type": "string",
+ "description": "The current pipeline stage. `closed` ends it, with a reason."
+ },
+ "closedReason": {
+ "anyOf": [
+ {
+ "enum": [
+ "accepted",
+ "not-selected",
+ "withdrew",
+ "accepted-other",
+ "no-response"
+ ],
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Why a closed application ended: accepted, not-selected, withdrew, accepted-other or no-response."
+ },
+ "resumeId": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "The linked Reactive Resume, if any."
+ },
+ "coverLetterId": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "The linked saved cover letter, if any."
+ },
+ "sentResumeVersionId": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "The version of the linked resume saved when the application was sent (reached Applied)."
+ },
+ "sentCheckScore": {
+ "anyOf": [
+ {
+ "type": "integer",
+ "minimum": -9007199254740991,
+ "maximum": 9007199254740991
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "The resume's Check score when it was sent, out of 100."
+ },
+ "sentCoverLetterVersionId": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "The version of the linked letter saved when the application was sent."
+ },
+ "source": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "tags": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ },
+ "sourceUrl": {
+ "anyOf": [
+ {
+ "type": "string",
+ "format": "uri"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "jobDescription": {
+ "anyOf": [
+ {
+ "type": "string",
+ "maxLength": 20000
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "postingSource": {
+ "anyOf": [
+ {
+ "type": "object",
+ "properties": {
+ "method": {
+ "enum": [
+ "paste",
+ "builtin",
+ "firecrawl",
+ "tavily",
+ "exa"
+ ],
+ "type": "string"
+ },
+ "format": {
+ "enum": [
+ "text",
+ "markdown"
+ ],
+ "type": "string"
+ },
+ "requestedUrl": {
+ "type": "string",
+ "format": "uri"
+ },
+ "resolvedUrl": {
+ "type": "string",
+ "format": "uri"
+ },
+ "retrievedAt": {
+ "type": "string",
+ "format": "date-time"
+ },
+ "providerFetchedAt": {
+ "type": "string",
+ "format": "date-time"
+ },
+ "truncated": {
+ "type": "boolean"
+ },
+ "completeness": {
+ "enum": [
+ "unknown",
+ "incomplete"
+ ],
+ "type": "string"
+ },
+ "fallbackReason": {
+ "enum": [
+ "unsafe-url",
+ "unreachable",
+ "not-a-page",
+ "too-large",
+ "auth",
+ "quota",
+ "malformed",
+ "empty",
+ "challenge",
+ "timeout",
+ "unavailable",
+ "rate-limit"
+ ],
+ "type": "string"
+ }
+ },
+ "required": [
+ "method",
+ "format",
+ "truncated",
+ "completeness"
+ ]
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "requirements": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ },
+ "description": "What the posting asks for, as read when the application was added."
+ },
+ "matchScore": {
+ "anyOf": [
+ {
+ "type": "integer",
+ "minimum": 0,
+ "maximum": 100
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "aiMetadata": {
+ "anyOf": [
+ {
+ "type": "object",
+ "propertyNames": {
+ "type": "string"
+ },
+ "additionalProperties": {}
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "notes": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "resumeFileUrl": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "resumeFileName": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "coverLetterUrl": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "coverLetterName": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "followUpAt": {
+ "anyOf": [
+ {
+ "type": "string",
+ "format": "date-time",
+ "x-native-type": "date"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "followUpNote": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "contacts": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "properties": {
+ "name": {
+ "type": "string",
+ "minLength": 1
+ },
+ "role": {
+ "type": "string",
+ "default": ""
+ },
+ "type": {
+ "type": "string",
+ "default": ""
+ },
+ "email": {
+ "type": "string",
+ "default": ""
+ },
+ "phone": {
+ "type": "string",
+ "default": ""
+ }
+ },
+ "required": [
+ "name"
+ ]
+ }
+ },
+ "activity": {
+ "type": "array",
+ "items": {
+ "anyOf": [
+ {
+ "type": "object",
+ "properties": {
+ "id": {
+ "type": "string",
+ "minLength": 1
+ },
+ "at": {
+ "type": "string",
+ "format": "date-time",
+ "x-native-type": "date"
+ },
+ "type": {
+ "const": "stage"
+ },
+ "stage": {
+ "enum": [
+ "saved",
+ "applied",
+ "screening",
+ "interview",
+ "offer",
+ "closed"
+ ],
+ "type": "string"
+ }
+ },
+ "required": [
+ "id",
+ "at",
+ "type",
+ "stage"
+ ]
+ },
+ {
+ "type": "object",
+ "properties": {
+ "id": {
+ "type": "string",
+ "minLength": 1
+ },
+ "at": {
+ "type": "string",
+ "format": "date-time",
+ "x-native-type": "date"
+ },
+ "type": {
+ "const": "note"
+ },
+ "text": {
+ "type": "string",
+ "minLength": 1
+ }
+ },
+ "required": [
+ "id",
+ "at",
+ "type",
+ "text"
+ ]
+ },
+ {
+ "type": "object",
+ "properties": {
+ "id": {
+ "type": "string",
+ "minLength": 1
+ },
+ "at": {
+ "type": "string",
+ "format": "date-time",
+ "x-native-type": "date"
+ },
+ "type": {
+ "const": "interview"
+ },
+ "kind": {
+ "enum": [
+ "screening",
+ "technical",
+ "behavioral",
+ "onsite",
+ "other"
+ ],
+ "type": "string"
+ },
+ "durationMinutes": {
+ "type": "integer",
+ "minimum": 5,
+ "maximum": 1440,
+ "default": 60
+ },
+ "location": {
+ "type": "string",
+ "maxLength": 500,
+ "default": ""
+ },
+ "notes": {
+ "type": "string",
+ "maxLength": 5000,
+ "default": ""
+ },
+ "participants": {
+ "type": "array",
+ "maxItems": 20,
+ "items": {
+ "type": "object",
+ "properties": {
+ "name": {
+ "type": "string",
+ "minLength": 1,
+ "maxLength": 200
+ },
+ "role": {
+ "type": "string",
+ "maxLength": 200,
+ "default": ""
+ },
+ "profileUrl": {
+ "type": "string",
+ "maxLength": 2048,
+ "format": "uri"
+ }
+ },
+ "required": [
+ "name"
+ ]
+ },
+ "default": []
+ },
+ "audience": {
+ "enum": [
+ "recruiter",
+ "hiring-manager",
+ "practitioner",
+ "panel",
+ "other"
+ ],
+ "type": "string",
+ "default": "other"
+ },
+ "timezone": {
+ "type": "string",
+ "minLength": 1,
+ "maxLength": 100,
+ "default": "UTC"
+ }
+ },
+ "required": [
+ "id",
+ "at",
+ "type",
+ "kind"
+ ]
+ }
+ ]
+ }
+ },
+ "appliedAt": {
+ "type": "string",
+ "format": "date-time",
+ "x-native-type": "date"
+ },
+ "createdAt": {
+ "type": "string",
+ "format": "date-time",
+ "x-native-type": "date"
+ },
+ "updatedAt": {
+ "type": "string",
+ "format": "date-time",
+ "x-native-type": "date"
+ }
+ },
+ "required": [
+ "id",
+ "company",
+ "role",
+ "location",
+ "salary",
+ "status",
+ "closedReason",
+ "resumeId",
+ "coverLetterId",
+ "sentResumeVersionId",
+ "sentCheckScore",
+ "sentCoverLetterVersionId",
+ "source",
+ "tags",
+ "sourceUrl",
+ "jobDescription",
+ "postingSource",
+ "requirements",
+ "matchScore",
+ "aiMetadata",
+ "notes",
+ "resumeFileUrl",
+ "resumeFileName",
+ "coverLetterUrl",
+ "coverLetterName",
+ "followUpAt",
+ "followUpNote",
+ "contacts",
+ "activity",
+ "appliedAt",
+ "createdAt",
+ "updatedAt"
+ ]
+ }
+ },
+ "required": [
+ "id",
+ "company",
+ "role",
+ "location",
+ "salary",
+ "status",
+ "closedReason",
+ "resumeId",
+ "coverLetterId",
+ "source",
+ "tags",
+ "sourceUrl",
+ "matchScore",
+ "followUpAt",
+ "followUpNote",
+ "contacts",
+ "activity",
+ "appliedAt",
+ "createdAt",
+ "updatedAt"
+ ]
+ }
+ }
+ }
+ },
+ "headers": {
+ "X-Total-Count": {
+ "description": "Total matching results before pagination.",
+ "schema": {
+ "type": "integer"
+ }
+ },
+ "X-Limit": {
+ "description": "Page size, when pagination is requested.",
+ "schema": {
+ "type": "integer"
+ }
+ },
+ "X-Offset": {
+ "description": "Zero-based offset, when pagination is requested.",
+ "schema": {
+ "type": "integer"
+ }
+ }
+ }
+ },
+ "default": {
+ "description": "Structured API error. See status and code; do not branch on message text.",
+ "content": {
+ "application/json": {
+ "schema": {
+ "type": "object",
+ "required": [
+ "defined",
+ "code",
+ "status",
+ "message"
+ ],
+ "properties": {
+ "defined": {
+ "type": "boolean"
+ },
+ "code": {
+ "type": "string"
+ },
+ "status": {
+ "type": "integer"
+ },
+ "message": {
+ "type": "string"
+ },
+ "data": {}
+ }
+ }
+ }
+ }
+ }
+ },
+ "security": [
+ {
+ "apiKey": []
+ },
+ {
+ "bearerAuth": []
+ },
+ {
+ "cookieAuth": []
+ }
+ ],
+ "x-codeSamples": [
+ {
+ "lang": "bash",
+ "label": "cURL",
+ "source": "curl \"https://rxresu.me/api/openapi/applications/summary\" --header \"x-api-key: <api-key>\""
+ }
+ ]
+ }
+ },
"/applications/{id}": {
"get": {
"operationId": "getApplication",
diff --git a/packages/api/src/dto/application.ts b/packages/api/src/dto/application.ts
index 22bcaecc1..00d2b85ed 100644
--- a/packages/api/src/dto/application.ts
+++ b/packages/api/src/dto/application.ts
@@ -87,6 +87,34 @@ const applicationSchema = createSelectSchema(schema.application, {
updatedAt: z.date(),
});
+const applicationSummarySchema = applicationSchema.pick({
+ id: true,
+ company: true,
+ role: true,
+ location: true,
+ salary: true,
+ status: true,
+ closedReason: true,
+ resumeId: true,
+ coverLetterId: true,
+ source: true,
+ tags: true,
+ sourceUrl: true,
+ matchScore: true,
+ followUpAt: true,
+ followUpNote: true,
+ contacts: true,
+ activity: true,
+ appliedAt: true,
+ createdAt: true,
+ updatedAt: true,
+});
+
+const applicationSummaryWithInitialDetailSchema = applicationSummarySchema.extend({
+ /** A small number of full rows can be attached to the initial list response for eager detail rendering. */
+ initialDetail: applicationSchema.omit({ userId: true }).optional(),
+});
+
// Fields a client is allowed to set/change. `status`, `activity` and AI-owned fields are
// excluded here — status changes go through the auto-logging update path, activity through
// addNote, and AI fields are written only by the (reserved) AI procedures.
@@ -137,6 +165,19 @@ export const applicationDto = {
output: z.array(applicationSchema.omit({ userId: true })),
},
+ listSummary: {
+ input: z
+ .object({
+ ...paginationShape,
+ status: applicationStatusSchema.optional(),
+ tags: z.array(z.string()).optional(),
+ includeInitialDetails: z.number().int().min(0).max(6).optional(),
+ })
+ .optional()
+ .default({}),
+ output: z.array(applicationSummaryWithInitialDetailSchema),
+ },
+
getById: {
input: applicationSchema.pick({ id: true }),
output: applicationSchema.omit({ userId: true }),
diff --git a/packages/api/src/features/applications/crud.ts b/packages/api/src/features/applications/crud.ts
index e2b0417f0..70ed87f78 100644
--- a/packages/api/src/features/applications/crud.ts
+++ b/packages/api/src/features/applications/crud.ts
@@ -35,6 +35,36 @@ export const crudRouter = {
return items;
}),
+ listSummary: protectedProcedure
+ .route({
+ method: "GET",
+ path: "/applications/summary",
+ tags: ["Applications"],
+ operationId: "listApplicationSummaries",
+ summary: "List application summaries",
+ description:
+ "Returns lightweight application summaries for list views. Full descriptions, notes, documents and timeline notes are omitted; use the application endpoint for full detail. When includeInitialDetails is N, up to 2N full details may be attached as initialDetail: the union of the first N candidates under web and mobile ordering, with closed applications excluded unless status is provided.",
+ successDescription: "A list of lightweight application summaries.",
+ })
+ .input(applicationDto.listSummary.input)
+ .output(applicationDto.listSummary.output)
+ .handler(async ({ input, context }) => {
+ const { items, total } = await applicationService.listSummary({
+ userId: context.user.id,
+ ...(input.status ? { status: input.status } : {}),
+ ...(input.tags ? { tags: input.tags } : {}),
+ ...(input.limit !== undefined ? { limit: input.limit } : {}),
+ ...(input.offset !== undefined ? { offset: input.offset } : {}),
+ ...(input.includeInitialDetails !== undefined ? { includeInitialDetails: input.includeInitialDetails } : {}),
+ });
+ context.resHeaders?.set("X-Total-Count", String(total));
+ if (input.limit !== undefined || input.offset !== undefined) {
+ context.resHeaders?.set("X-Limit", String(input.limit ?? 20));
+ context.resHeaders?.set("X-Offset", String(input.offset ?? 0));
+ }
+ return items;
+ }),
+
getById: protectedProcedure
.route({
method: "GET",
diff --git a/packages/api/src/features/applications/pagination.test.ts b/packages/api/src/features/applications/pagination.test.ts
index 70be3314f..41351d097 100644
--- a/packages/api/src/features/applications/pagination.test.ts
+++ b/packages/api/src/features/applications/pagination.test.ts
@@ -7,6 +7,8 @@ import { application } from "@reactive-resume/db/schema";
const fixture = vi.hoisted(() => ({
query: vi.fn<(config: { text: string }, params: unknown[]) => Promise<{ rows: unknown[][] }>>(),
rows: [] as unknown[][],
+ fullRows: [] as unknown[][],
+ fullRowsActive: false,
total: 0,
}));
@@ -33,6 +35,8 @@ function row(id: string) {
company: "Example",
role: "Engineer",
status: "closed",
+ jobDescription: "full description",
+ notes: "private note",
tags: ["engineering"],
requirements: [],
contacts: [],
@@ -47,6 +51,54 @@ function row(id: string) {
return Object.keys(getTableColumns(application)).map((key) => values[key] ?? null);
}
+function summaryRow(id: string) {
+ return [
+ id,
+ "owner",
+ "Example",
+ "Engineer",
+ null,
+ null,
+ "closed",
+ "not-selected",
+ null,
+ null,
+ "referral",
+ ["engineering"],
+ "https://example.com/job",
+ 88,
+ null,
+ null,
+ [],
+ [
+ { id: "stage", type: "stage", stage: "applied", at: "2026-07-01T12:00:00.000Z" },
+ {
+ id: "interview",
+ type: "interview",
+ kind: "technical",
+ durationMinutes: 60,
+ location: "Remote",
+ notes: "Bring examples",
+ participants: [],
+ audience: "practitioner",
+ timezone: "UTC",
+ at: "2026-07-02T12:00:00.000Z",
+ },
+ ],
+ "2026-07-01T12:00:00.000Z",
+ "2026-07-01T12:00:00.000Z",
+ "2026-07-02T12:00:00.000Z",
+ ];
+}
+
+function candidateSummary(id: string, status: string, updatedAt: string) {
+ const value = summaryRow(id);
+ value[6] = status;
+ value[7] = null;
+ value[20] = updatedAt;
+ return value;
+}
+
function client() {
const resHeaders = new Headers();
return {
@@ -66,13 +118,186 @@ function queries() {
beforeEach(() => {
fixture.rows = [row("page-item")];
+ fixture.fullRows = fixture.rows;
+ fixture.fullRowsActive = false;
fixture.total = 42;
fixture.query.mockReset();
- fixture.query.mockImplementation(async ({ text }: { text: string }) => ({
- rows: text.includes("count(") ? [[fixture.total]] : fixture.rows,
+ fixture.query.mockImplementation(async ({ text }: { text: string }, params) => ({
+ rows: text.includes("count(")
+ ? [[fixture.total]]
+ : text.includes("jsonb_path_query_array")
+ ? fixture.rows
+ : fixture.fullRowsActive
+ ? fixture.fullRows.filter((values) => params.includes(values[0]))
+ : fixture.rows,
}));
});
+describe("application list summary", () => {
+ it("projects a lightweight row and keeps stage/interview activity", async () => {
+ fixture.rows = [summaryRow("summary-item")];
+ const { api, resHeaders } = client();
+ const items = await api.listSummary({ status: "closed", tags: ["engineering"], limit: 1, offset: 2 });
+
+ expect(items.map((item) => item.id)).toEqual(["summary-item"]);
+ expect(items[0]).not.toHaveProperty("jobDescription");
+ expect(items[0]).not.toHaveProperty("notes");
+ expect(items[0]).not.toHaveProperty("requirements");
+ expect(items[0]?.activity.map((entry) => entry.id)).toEqual(["interview", "stage"]);
+ expect(resHeaders.get("X-Total-Count")).toBe("42");
+ expect(resHeaders.get("X-Limit")).toBe("1");
+ expect(resHeaders.get("X-Offset")).toBe("2");
+
+ const page = queries().find((query) => !query.sql.includes("count("));
+ expect(page?.sql).toContain("jsonb_path_query_array");
+ expect(page?.sql).not.toContain('"job_description"');
+ expect(page?.sql).not.toContain('"notes"');
+ expect(page?.params).toEqual(["owner", "closed", ["engineering"], 1, 2]);
+ });
+});
+
+describe("application list summary completeness", () => {
+ it("returns complete filtered totals when pagination is omitted", async () => {
+ fixture.rows = [summaryRow("first"), summaryRow("second")];
+ const { api, resHeaders } = client();
+ const items = await api.listSummary({});
+
+ expect(items.map((item) => item.id)).toEqual(["first", "second"]);
+ expect(resHeaders.get("X-Total-Count")).toBe("2");
+ expect(resHeaders.has("X-Limit")).toBe(false);
+ expect(resHeaders.has("X-Offset")).toBe(false);
+ expect(queries()).toHaveLength(1);
+ expect(queries()[0]?.sql).not.toContain("limit");
+ expect(queries()[0]?.params).toEqual(["owner"]);
+ });
+
+ it("keeps the total when a requested page is empty", async () => {
+ fixture.rows = [];
+ const { api, resHeaders } = client();
+ expect(await api.listSummary({ limit: 20, offset: 100 })).toEqual([]);
+ expect(resHeaders.get("X-Total-Count")).toBe("42");
+ expect(resHeaders.get("X-Limit")).toBe("20");
+ expect(resHeaders.get("X-Offset")).toBe("100");
+ });
+
+ it("attaches a bounded set of full rows in default list order", async () => {
+ const candidate = summaryRow("initial-item");
+ candidate[6] = "interview";
+ candidate[7] = null;
+ fixture.rows = [candidate];
+ fixture.fullRows = [row("initial-item")];
+ fixture.fullRowsActive = true;
+ const { api } = client();
+ const items = await api.listSummary({ includeInitialDetails: 1 });
+
+ expect(items[0]?.initialDetail?.id).toBe("initial-item");
+ expect(items[0]?.initialDetail?.jobDescription).toBe("full description");
+ expect(items[0]).not.toHaveProperty("jobDescription");
+ expect(queries()).toHaveLength(2);
+ expect(queries()[1]?.sql).toContain(" in ");
+ });
+
+ it("attaches the web/mobile candidate union with one batch query", async () => {
+ const updatedAt = "2026-07-03T12:00:00.000Z";
+ const summaryRows = [
+ candidateSummary("interview-d", "interview", updatedAt),
+ candidateSummary("interview-c", "interview", updatedAt),
+ candidateSummary("interview-b", "interview", updatedAt),
+ candidateSummary("interview-a", "interview", updatedAt),
+ candidateSummary("offer-a", "offer", updatedAt),
+ candidateSummary("closed-a", "closed", updatedAt),
+ ];
+ fixture.rows = summaryRows;
+ fixture.fullRows = summaryRows.map(([id]) => row(String(id)));
+ fixture.fullRowsActive = true;
+ const { api } = client();
+ const items = await api.listSummary({ includeInitialDetails: 3 });
+
+ expect(items.map((item) => item.id)).toEqual(summaryRows.map(([id]) => id));
+ const attached = items
+ .filter((item) => item.initialDetail)
+ .map((item) => item.id)
+ .sort();
+ expect(attached).toEqual(["interview-a", "interview-b", "interview-c", "interview-d"]);
+ expect(items.find((item) => item.id === "closed-a")).not.toHaveProperty("initialDetail");
+ expect(items.every((item) => item.initialDetail?.id === item.id || !item.initialDetail)).toBe(true);
+ expect(queries()).toHaveLength(2);
+ expect(queries()[1]?.sql).toMatch(/ in /);
+ expect(queries()[1]?.params).toContain("owner");
+ });
+
+ it.each([
+ {
+ name: "a later timestamp group in one stage",
+ rows: [
+ ["interview-new", "interview", "2026-07-04T00:00:00Z"],
+ ["interview-c", "interview", "2026-07-03T00:00:00Z"],
+ ["interview-b", "interview", "2026-07-03T00:00:00Z"],
+ ["interview-a", "interview", "2026-07-03T00:00:00Z"],
+ ["offer-a", "offer", "2026-07-02T00:00:00Z"],
+ ],
+ expected: ["interview-a", "interview-b", "interview-c", "interview-new"],
+ },
+ {
+ name: "a cutoff in the next stage",
+ rows: [
+ ["offer-c", "offer", "2026-07-04T00:00:00Z"],
+ ["offer-b", "offer", "2026-07-04T00:00:00Z"],
+ ["offer-a", "offer", "2026-07-04T00:00:00Z"],
+ ["interview-a", "interview", "2026-07-03T00:00:00Z"],
+ ["saved-a", "saved", "2026-07-02T00:00:00Z"],
+ ],
+ expected: ["interview-a", "offer-a", "offer-b", "offer-c"],
+ },
+ ] as const)("preloads both clients' first rows across $name", async ({ rows, expected }) => {
+ fixture.rows = rows.map(([id, status, at]) => candidateSummary(id, status, at));
+ fixture.fullRows = rows.map(([id]) => row(id));
+ fixture.fullRowsActive = true;
+ const { api } = client();
+ const items = await api.listSummary({ includeInitialDetails: 3 });
+ expect(
+ items
+ .filter((item) => item.initialDetail)
+ .map((item) => item.id)
+ .sort(),
+ ).toEqual(expected);
+ expect(queries()[1]?.params).toHaveLength(expected.length + 1);
+ expect(queries()[1]?.params).toEqual(expect.arrayContaining(["owner", ...expected]));
+ expect(queries()).toHaveLength(2);
+ });
+
+ it("can preload closed rows when the caller explicitly filters for them", async () => {
+ fixture.rows = [summaryRow("closed-a")];
+ fixture.fullRows = [row("closed-a")];
+ fixture.fullRowsActive = true;
+ const { api } = client();
+ const items = await api.listSummary({ status: "closed", includeInitialDetails: 1 });
+ expect(items[0]?.initialDetail?.id).toBe("closed-a");
+ });
+
+ it("keeps summary response unchanged when initial details are omitted or zero", async () => {
+ fixture.rows = [summaryRow("summary-item")];
+ const { api } = client();
+ const omitted = await api.listSummary({});
+ expect(omitted[0]).not.toHaveProperty("initialDetail");
+ expect(queries()).toHaveLength(1);
+
+ fixture.query.mockReset();
+ fixture.query.mockImplementation(async ({ text }: { text: string }) => ({
+ rows: text.includes("count(") ? [[fixture.total]] : fixture.rows,
+ }));
+ const zero = await api.listSummary({ includeInitialDetails: 0 });
+ expect(zero[0]).not.toHaveProperty("initialDetail");
+ expect(queries()).toHaveLength(1);
+ });
+
+ it("rejects more than six initial details before querying", async () => {
+ const { api } = client();
+ await expect(api.listSummary({ includeInitialDetails: 7 })).rejects.toMatchObject({ code: "BAD_REQUEST" });
+ expect(fixture.query).not.toHaveBeenCalled();
+ });
+});
+
describe("application list pagination", () => {
it("returns the database page without slicing it again and preserves total headers", async () => {
const { api, resHeaders } = client();
@@ -112,6 +337,8 @@ describe("application list pagination", () => {
const items = await api.list(input);
expect(items.map((item) => item.id)).toEqual(["first", "second"]);
+ expect(items[0]?.jobDescription).toBe("full description");
+ expect(items[0]?.notes).toBe("private note");
expect(resHeaders.get("X-Total-Count")).toBe("2");
expect(resHeaders.has("X-Limit")).toBe(false);
expect(resHeaders.has("X-Offset")).toBe(false);
diff --git a/packages/api/src/features/applications/router.ts b/packages/api/src/features/applications/router.ts
index 680d1da22..4e342a78e 100644
--- a/packages/api/src/features/applications/router.ts
+++ b/packages/api/src/features/applications/router.ts
@@ -3,6 +3,7 @@ import { crudRouter } from "./crud";
export const applicationsRouter = {
list: crudRouter.list,
+ listSummary: crudRouter.listSummary,
getById: crudRouter.getById,
create: crudRouter.create,
import: crudRouter.import,
diff --git a/packages/api/src/features/applications/service.ts b/packages/api/src/features/applications/service.ts
index e53a66d0a..18c833b33 100644
--- a/packages/api/src/features/applications/service.ts
+++ b/packages/api/src/features/applications/service.ts
@@ -402,6 +402,32 @@ const stripUserId = <T extends { userId: string; activity?: ApplicationTimelineE
return rest.activity ? { ...rest, activity: sortTimeline(rest.activity) } : rest;
};
+const applicationSummarySelect = {
+ id: schema.application.id,
+ userId: schema.application.userId,
+ company: schema.application.company,
+ role: schema.application.role,
+ location: schema.application.location,
+ salary: schema.application.salary,
+ status: schema.application.status,
+ closedReason: schema.application.closedReason,
+ resumeId: schema.application.resumeId,
+ coverLetterId: schema.application.coverLetterId,
+ source: schema.application.source,
+ tags: schema.application.tags,
+ sourceUrl: schema.application.sourceUrl,
+ matchScore: schema.application.matchScore,
+ followUpAt: schema.application.followUpAt,
+ followUpNote: schema.application.followUpNote,
+ contacts: schema.application.contacts,
+ activity: sql<
+ ApplicationTimelineEntry[]
+ >`jsonb_path_query_array(${schema.application.activity}, '$[*] ? (@.type == "stage" || @.type == "interview")')`,
+ appliedAt: schema.application.appliedAt,
+ createdAt: schema.application.createdAt,
+ updatedAt: schema.application.updatedAt,
+};
+
export const applicationService = {
list: async (input: {
userId: string;
@@ -430,6 +456,75 @@ export const applicationService = {
return { items: rows.map(stripUserId), total: totals?.[0]?.total ?? rows.length };
},
+ listSummary: async (input: {
+ userId: string;
+ status?: ApplicationStatus;
+ tags?: string[];
+ limit?: number;
+ offset?: number;
+ includeInitialDetails?: number;
+ }) => {
+ const where = and(
+ eq(schema.application.userId, input.userId),
+ input.status ? eq(schema.application.status, input.status) : undefined,
+ input.tags && input.tags.length > 0 ? arrayContains(schema.application.tags, input.tags) : undefined,
+ );
+ const query = db
+ .select(applicationSummarySelect)
+ .from(schema.application)
+ .where(where)
+ .orderBy(sql`${schema.application.updatedAt} desc nulls last`, desc(schema.application.id));
+ const paged = input.limit !== undefined || input.offset !== undefined;
+ const [rows, totals] = await Promise.all([
+ paged ? query.limit(input.limit ?? 20).offset(input.offset ?? 0) : query,
+ paged ? db.select({ total: count() }).from(schema.application).where(where) : undefined,
+ ]);
+
+ const items = rows.map(stripUserId);
+ const initialDetailCount = input.includeInitialDetails ?? 0;
+ if (initialDetailCount === 0 || items.length === 0) {
+ return { items, total: totals?.[0]?.total ?? rows.length };
+ }
+
+ // Web keeps SQL order within each stage. Mobile differs only when the cutoff
+ // falls inside a timestamp tie, so only that group needs an ID sort.
+ const stageOrder: readonly ApplicationStatus[] = ["interview", "offer", "screening", "applied", "saved", "closed"];
+ const buckets = new Map<ApplicationStatus, typeof items>();
+ for (const item of items) {
+ if (item.status === "closed" && input.status === undefined) continue;
+ const bucket = buckets.get(item.status);
+ if (bucket) bucket.push(item);
+ else buckets.set(item.status, [item]);
+ }
+ const webCandidates = stageOrder.flatMap((status) => buckets.get(status) ?? []).slice(0, initialDetailCount);
+ const candidateIds = new Set(webCandidates.map((item) => item.id));
+ const boundary = webCandidates.at(-1);
+ if (boundary) {
+ const sameGroup = (item: (typeof items)[number]) =>
+ item.status === boundary.status && item.updatedAt.getTime() === boundary.updatedAt.getTime();
+ const mobileCount = webCandidates.filter(sameGroup).length;
+ const tied = items.filter(sameGroup);
+ for (const item of tied.toSorted((a, b) => a.id.localeCompare(b.id)).slice(0, mobileCount)) {
+ candidateIds.add(item.id);
+ }
+ }
+ if (candidateIds.size === 0) return { items, total: totals?.[0]?.total ?? rows.length };
+
+ // Fetch candidates together so the initial response adds one bounded query, never one query per row.
+ const fullRows = await db
+ .select()
+ .from(schema.application)
+ .where(and(eq(schema.application.userId, input.userId), inArray(schema.application.id, [...candidateIds])));
+ const details = new Map(fullRows.map((row) => [row.id, stripUserId(row)]));
+ return {
+ items: items.map((item) => {
+ const initialDetail = details.get(item.id);
+ return initialDetail ? { ...item, initialDetail } : item;
+ }),
+ total: totals?.[0]?.total ?? rows.length,
+ };
+ },
+
getById: async (input: { id: string; userId: string }) => {
return stripUserId(await requireOwned(input.id, input.userId));
},