fix(mail): preserve latest status and job choices across request races
This commit is contained in:
@@ -144,6 +144,7 @@ export default function Correspondence({ jobId, jobContext }: { jobId: number; j
|
||||
|
||||
const [gmailStatus, setGmailStatus] = useState<GmailStatus | null>(null);
|
||||
const [gmailLoading, setGmailLoading] = useState(false);
|
||||
const gmailStatusRequest = useRef(0);
|
||||
const [gmailQuery, setGmailQuery] = useState("");
|
||||
const [gmailMatches, setGmailMatches] = useState<GmailJobMatchesResponse | null>(null);
|
||||
const [gmailMatchesLoading, setGmailMatchesLoading] = useState(false);
|
||||
@@ -155,6 +156,7 @@ export default function Correspondence({ jobId, jobContext }: { jobId: number; j
|
||||
const [availableJobs, setAvailableJobs] = useState<JobChoice[]>([]);
|
||||
const [jobChoiceQuery, setJobChoiceQuery] = useState("");
|
||||
const [jobChoicesLoading, setJobChoicesLoading] = useState(false);
|
||||
const jobChoicesRequest = useRef(0);
|
||||
const [manageThreadId, setManageThreadId] = useState<string | null>(null);
|
||||
const [manageTargetJobId, setManageTargetJobId] = useState<number>(jobId);
|
||||
const [manageNote, setManageNote] = useState("");
|
||||
@@ -198,16 +200,21 @@ export default function Correspondence({ jobId, jobContext }: { jobId: number; j
|
||||
}, [jobId]);
|
||||
|
||||
const loadGmailStatus = useCallback(async () => {
|
||||
const session = gmailOAuth.current;
|
||||
if (!session.active || session.jobId !== jobId) return;
|
||||
const generation = session.generation;
|
||||
const request = ++gmailStatusRequest.current;
|
||||
const active = () => session.active && session.jobId === jobId && session.generation === generation && gmailStatusRequest.current === request;
|
||||
try {
|
||||
setGmailLoading(true);
|
||||
const res = await api.get<GmailStatus>("/gmail/status");
|
||||
setGmailStatus(res.data);
|
||||
if (active()) setGmailStatus(res.data);
|
||||
} catch {
|
||||
setGmailStatus({ connected: false });
|
||||
if (active()) setGmailStatus({ connected: false });
|
||||
} finally {
|
||||
setGmailLoading(false);
|
||||
if (active()) setGmailLoading(false);
|
||||
}
|
||||
}, []);
|
||||
}, [jobId]);
|
||||
|
||||
const loadGmailMatches = useCallback(async (queryOverride?: string) => {
|
||||
const session = gmailOAuth.current;
|
||||
@@ -233,14 +240,19 @@ export default function Correspondence({ jobId, jobContext }: { jobId: number; j
|
||||
}, [jobId, toast]);
|
||||
|
||||
const loadAvailableJobs = useCallback(async (query?: string) => {
|
||||
const session = gmailOAuth.current;
|
||||
if (!session.active || session.jobId !== jobId) return;
|
||||
const generation = session.generation;
|
||||
const request = ++jobChoicesRequest.current;
|
||||
const active = () => session.active && session.jobId === jobId && session.generation === generation && jobChoicesRequest.current === request;
|
||||
try {
|
||||
setJobChoicesLoading(true);
|
||||
const res = await api.get<JobChoice[]>("/jobapplications/choices", { params: { q: query?.trim() || undefined, limit: 50 } });
|
||||
setAvailableJobs((res.data ?? []).filter((item) => item.id !== jobId));
|
||||
if (active()) setAvailableJobs((res.data ?? []).filter((item) => item.id !== jobId));
|
||||
} catch {
|
||||
setAvailableJobs([]);
|
||||
if (active()) setAvailableJobs([]);
|
||||
} finally {
|
||||
setJobChoicesLoading(false);
|
||||
if (active()) setJobChoicesLoading(false);
|
||||
}
|
||||
}, [jobId]);
|
||||
|
||||
@@ -314,8 +326,9 @@ export default function Correspondence({ jobId, jobContext }: { jobId: number; j
|
||||
|
||||
useEffect(() => {
|
||||
if (!manageThreadId) return;
|
||||
const requests = jobChoicesRequest;
|
||||
const timer = window.setTimeout(() => void loadAvailableJobs(jobChoiceQuery), jobChoiceQuery.trim() ? 250 : 0);
|
||||
return () => window.clearTimeout(timer);
|
||||
return () => { window.clearTimeout(timer); ++requests.current; };
|
||||
}, [jobChoiceQuery, loadAvailableJobs, manageThreadId]);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -454,6 +467,8 @@ export default function Correspondence({ jobId, jobContext }: { jobId: number; j
|
||||
try {
|
||||
await api.delete("/gmail/connection");
|
||||
if (!active()) return;
|
||||
++gmailStatusRequest.current;
|
||||
setGmailLoading(false);
|
||||
setGmailStatus({ connected: false });
|
||||
setGmailMatches(null);
|
||||
setLinkedThreadRefresh(null);
|
||||
|
||||
@@ -476,6 +476,112 @@ describe("correspondence Gmail import", () => {
|
||||
expect(await screen.findByText(/no messages yet/i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
describe("Gmail standalone read lifetime", () => {
|
||||
const oldChoices = { data: [{ id: 88, companyName: "Platform obsolete", jobTitle: "Old role" }] };
|
||||
const newChoices = { data: [{ id: 99, companyName: "Platform latest", jobTitle: "Current role" }] };
|
||||
async function openChoices() {
|
||||
gmailConnected = false;
|
||||
correspondenceMessages = [{ id: 700, jobApplicationId: 42, from: "Company", content: "Recorded correspondence", externalThreadId: "thread-1" }];
|
||||
const view = renderDialog();
|
||||
fireEvent.click(await screen.findByRole("button", { name: /manage thread-1/i }));
|
||||
const input = screen.getByRole("combobox", { name: translations.en.correspondenceMoveToJob });
|
||||
fireEvent.mouseDown(input);
|
||||
await waitFor(() => expect(mockedApi.get).toHaveBeenCalledWith("/jobapplications/choices", { params: { q: undefined, limit: 50 } }));
|
||||
return { view, input };
|
||||
}
|
||||
async function searchChoices(waitForSearch = true) {
|
||||
const older = deferred<any>(); const newer = deferred<any>();
|
||||
const original = mockedApi.get.getMockImplementation()!;
|
||||
mockedApi.get.mockImplementation((url: any, config?: any) => url === "/jobapplications/choices"
|
||||
? config?.params?.q ? newer.promise : older.promise : original(url, config));
|
||||
const controls = await openChoices();
|
||||
fireEvent.change(controls.input, { target: { value: "Platform" } });
|
||||
if (waitForSearch) await waitFor(() => expect(mockedApi.get).toHaveBeenCalledWith("/jobapplications/choices", { params: { q: "Platform", limit: 50 } }));
|
||||
return { ...controls, older, newer };
|
||||
}
|
||||
|
||||
test.each(["resolve", "reject"] as const)("an older choice %s cannot replace a newer completed query", async outcome => {
|
||||
const { older, newer } = await searchChoices();
|
||||
await act(async () => newer.resolve(newChoices));
|
||||
expect(await screen.findByRole("option", { name: /Platform latest/ })).toBeVisible();
|
||||
await act(async () => outcome === "resolve" ? older.resolve(oldChoices) : older.reject(new Error("obsolete choices")));
|
||||
expect(screen.getByRole("option", { name: /Platform latest/ })).toBeVisible();
|
||||
expect(screen.queryByRole("option", { name: /Platform obsolete/ })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
test.each(["resolve", "reject"] as const)("an older choice %s cannot end a newer query's loading state", async outcome => {
|
||||
const { older, newer } = await searchChoices();
|
||||
expect(screen.getByText("Loading…")).toBeVisible();
|
||||
await act(async () => outcome === "resolve" ? older.resolve(oldChoices) : older.reject(new Error("obsolete choices")));
|
||||
expect(screen.getByText("Loading…")).toBeVisible();
|
||||
await act(async () => newer.resolve(newChoices));
|
||||
expect(await screen.findByRole("option", { name: /Platform latest/ })).toBeVisible();
|
||||
expect(screen.queryByText("Loading…")).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
test("changing a choice query invalidates the previous read during debounce", async () => {
|
||||
jest.useFakeTimers();
|
||||
try {
|
||||
const { older, newer } = await searchChoices(false);
|
||||
await act(async () => older.resolve(oldChoices));
|
||||
expect(screen.queryByRole("option", { name: /Platform obsolete/ })).not.toBeInTheDocument();
|
||||
await act(async () => jest.advanceTimersByTime(250));
|
||||
expect(mockedApi.get).toHaveBeenCalledWith("/jobapplications/choices", { params: { q: "Platform", limit: 50 } });
|
||||
await act(async () => newer.resolve(newChoices));
|
||||
expect(await screen.findByRole("option", { name: /Platform latest/ })).toBeVisible();
|
||||
} finally { jest.useRealTimers(); }
|
||||
});
|
||||
|
||||
test.each(["resolve", "reject"] as const)("choice %s from a previous job cannot overwrite the current job's choices", async outcome => {
|
||||
const older = deferred<any>();
|
||||
const original = mockedApi.get.getMockImplementation()!;
|
||||
let reads = 0;
|
||||
mockedApi.get.mockImplementation((url: any, config?: any) => url === "/jobapplications/choices" && ++reads === 1 ? older.promise : original(url, config));
|
||||
const { view } = await openChoices();
|
||||
await act(async () => view.rerender(dialog(77)));
|
||||
expect(await screen.findByRole("option", { name: /Acme.*Backend Developer/ })).toBeVisible();
|
||||
await act(async () => outcome === "resolve" ? older.resolve({ data: [{ id: 77, companyName: "Beta", jobTitle: "Platform Engineer" }] }) : older.reject(new Error("old job choices")));
|
||||
expect(screen.getByRole("option", { name: /Acme.*Backend Developer/ })).toBeVisible();
|
||||
expect(screen.queryByRole("option", { name: /Beta.*Platform Engineer/ })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
test.each(["success", "failure"] as const)("a pending status read respects a disconnect %s", async outcome => {
|
||||
const pending = deferred<any>();
|
||||
const original = mockedApi.get.getMockImplementation()!;
|
||||
let statusReads = 0;
|
||||
mockedApi.get.mockImplementation((url: any, config?: any) => url === "/gmail/status" && ++statusReads === 2 ? pending.promise : original(url, config));
|
||||
correspondenceMessages = [{ id: 700, jobApplicationId: 42, from: "Company", content: "Linked record", externalThreadId: "thread-1" }];
|
||||
mockedApi.post.mockResolvedValue({ data: { imported: 0, hasLinkedThreads: true, threads: [] } } as any);
|
||||
if (outcome === "failure") mockedApi.delete.mockRejectedValueOnce(new Error("synthetic disconnect failure"));
|
||||
renderDialog();
|
||||
await waitFor(() => expect(statusReads).toBe(2));
|
||||
fireEvent.click(screen.getByRole("button", { name: translations.en.correspondenceImportEmail }));
|
||||
fireEvent.click(screen.getByRole("tab", { name: /^google$/i }));
|
||||
fireEvent.click(await screen.findByRole("button", { name: translations.en.correspondenceDisconnect }));
|
||||
expect(await screen.findByText(translations.en[outcome === "success" ? "googleUnlinked" : "correspondenceDisconnectFailed"])).toBeVisible();
|
||||
await act(async () => pending.resolve({ data: { connected: true, gmailAddress: "obsolete@example.test" } }));
|
||||
expect(screen.getByRole("button", { name: translations.en[outcome === "success" ? "correspondenceConnectGmail" : "correspondenceDisconnect"] })).toBeEnabled();
|
||||
expect(screen.queryByText(translations.en.correspondenceCheckingConnection)).not.toBeInTheDocument();
|
||||
if (outcome === "success") expect(screen.queryByText(/obsolete@example.test/)).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
test("a previous job's pending status cannot replace current disconnected status", async () => {
|
||||
gmailConnected = false;
|
||||
const pending = deferred<any>();
|
||||
const original = mockedApi.get.getMockImplementation()!;
|
||||
let reads = 0;
|
||||
mockedApi.get.mockImplementation((url: any, config?: any) => url === "/gmail/status" && ++reads === 1 ? pending.promise : original(url, config));
|
||||
const view = renderDialog();
|
||||
fireEvent.click(await screen.findByRole("button", { name: translations.en.correspondenceImportEmail }));
|
||||
fireEvent.click(screen.getByRole("tab", { name: /^google$/i }));
|
||||
await act(async () => view.rerender(dialog(77)));
|
||||
await act(async () => pending.resolve({ data: { connected: true, gmailAddress: "previous-job@example.test" } }));
|
||||
expect(screen.getByRole("button", { name: translations.en.correspondenceConnectGmail })).toBeEnabled();
|
||||
expect(screen.queryByText(/previous-job@example.test/)).not.toBeInTheDocument();
|
||||
expect(reads).toBe(2);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Gmail link management lifetime", () => {
|
||||
const actions = ["unlink", "relink", "disconnect"] as const;
|
||||
type Action = typeof actions[number];
|
||||
|
||||
Reference in New Issue
Block a user