fix(api): kill currentPortId persist race + dedupe admin/ports stampede
The dashboard and residential interest smoke tests were intermittently
failing with the page rendering empty/skeleton state. Root causes:
1. ui-store persisted currentPortId/Slug, but those are URL-derived state.
After login lands on /<first-port-by-name>/dashboard, localStorage holds
that port. Hard-navigating to /port-nimara/... rehydrated the store with
the stale id, and useQuery fired with the wrong port before
PortProvider's URL-sync useEffect could correct it. Drop both fields
from partialize — PortProvider re-derives them from the route every
navigation.
2. apiFetch's slug-to-port fallback fired N parallel /api/v1/admin/ports
calls when N components mounted simultaneously with an empty store.
Dedupe in-flight lookups so a stampede collapses into one round-trip.
Also tightened four flaky smoke tests that depended on a fixed 3s wait or
non-waiting isVisible({timeout}) — replaced with expect(...).toBeVisible
or expect.poll so they handle dev-mode JIT cold-start delays cleanly.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -10,21 +10,33 @@ export interface ApiFetchOptions extends Omit<RequestInit, 'body'> {
|
|||||||
* Avoids re-fetching `/api/v1/admin/ports` on every request when the Zustand
|
* Avoids re-fetching `/api/v1/admin/ports` on every request when the Zustand
|
||||||
* store hasn't hydrated yet (fresh browser context, e2e tests, hard reload). */
|
* store hasn't hydrated yet (fresh browser context, e2e tests, hard reload). */
|
||||||
const slugToIdCache = new Map<string, string>();
|
const slugToIdCache = new Map<string, string>();
|
||||||
|
/** Dedupe in-flight admin/ports lookups so a stampede of parallel apiFetch
|
||||||
|
* calls (typical on dashboard mount) collapses into a single network round-
|
||||||
|
* trip instead of N. */
|
||||||
|
let inFlightPortsLookup: Promise<Array<{ id: string; slug: string }> | null> | null = null;
|
||||||
|
|
||||||
async function resolvePortIdFromSlug(slug: string): Promise<string | null> {
|
async function resolvePortIdFromSlug(slug: string): Promise<string | null> {
|
||||||
const cached = slugToIdCache.get(slug);
|
const cached = slugToIdCache.get(slug);
|
||||||
if (cached) return cached;
|
if (cached) return cached;
|
||||||
try {
|
if (!inFlightPortsLookup) {
|
||||||
const res = await fetch('/api/v1/admin/ports', { credentials: 'include' });
|
inFlightPortsLookup = (async () => {
|
||||||
if (!res.ok) return null;
|
try {
|
||||||
const body = (await res.json()) as { data?: Array<{ id: string; slug: string }> };
|
const res = await fetch('/api/v1/admin/ports', { credentials: 'include' });
|
||||||
const port = body.data?.find((p) => p.slug === slug);
|
if (!res.ok) return null;
|
||||||
if (!port) return null;
|
const body = (await res.json()) as { data?: Array<{ id: string; slug: string }> };
|
||||||
slugToIdCache.set(slug, port.id);
|
return body.data ?? null;
|
||||||
return port.id;
|
} catch {
|
||||||
} catch {
|
return null;
|
||||||
return null;
|
}
|
||||||
|
})().finally(() => {
|
||||||
|
inFlightPortsLookup = null;
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
const ports = await inFlightPortsLookup;
|
||||||
|
const port = ports?.find((p) => p.slug === slug);
|
||||||
|
if (!port) return null;
|
||||||
|
slugToIdCache.set(slug, port.id);
|
||||||
|
return port.id;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -24,10 +24,12 @@ export const useUIStore = create<UIStore>()(
|
|||||||
}),
|
}),
|
||||||
{
|
{
|
||||||
name: 'pn-crm-ui',
|
name: 'pn-crm-ui',
|
||||||
|
// currentPortId/Slug are URL-derived, not user preferences. PortProvider
|
||||||
|
// re-populates them from the route on every navigation. Persisting them
|
||||||
|
// creates a hydration race where queries fire with a stale port id from
|
||||||
|
// the previous session before the URL-derived effect runs.
|
||||||
partialize: (state) => ({
|
partialize: (state) => ({
|
||||||
sidebarCollapsed: state.sidebarCollapsed,
|
sidebarCollapsed: state.sidebarCollapsed,
|
||||||
currentPortId: state.currentPortId,
|
|
||||||
currentPortSlug: state.currentPortSlug,
|
|
||||||
darkMode: state.darkMode,
|
darkMode: state.darkMode,
|
||||||
}),
|
}),
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { test, expect } from '@playwright/test';
|
import { test, expect } from '@playwright/test';
|
||||||
import { login, navigateTo, waitForSheet, PORT_SLUG } from './helpers';
|
import { login, navigateTo, waitForSheet } from './helpers';
|
||||||
|
|
||||||
test.describe('Interest Pipeline', () => {
|
test.describe('Interest Pipeline', () => {
|
||||||
test.beforeEach(async ({ page }) => {
|
test.beforeEach(async ({ page }) => {
|
||||||
@@ -9,7 +9,10 @@ test.describe('Interest Pipeline', () => {
|
|||||||
test('create a client and interest', async ({ page }) => {
|
test('create a client and interest', async ({ page }) => {
|
||||||
// First create a client
|
// First create a client
|
||||||
await navigateTo(page, '/clients');
|
await navigateTo(page, '/clients');
|
||||||
await page.getByRole('button', { name: /new client/i }).first().click();
|
await page
|
||||||
|
.getByRole('button', { name: /new client/i })
|
||||||
|
.first()
|
||||||
|
.click();
|
||||||
await waitForSheet(page);
|
await waitForSheet(page);
|
||||||
|
|
||||||
const clientName = `Pipeline Client ${Date.now()}`;
|
const clientName = `Pipeline Client ${Date.now()}`;
|
||||||
@@ -76,16 +79,31 @@ test.describe('Interest Pipeline', () => {
|
|||||||
test('interests page loads with data', async ({ page }) => {
|
test('interests page loads with data', async ({ page }) => {
|
||||||
await navigateTo(page, '/interests');
|
await navigateTo(page, '/interests');
|
||||||
await page.waitForLoadState('networkidle');
|
await page.waitForLoadState('networkidle');
|
||||||
await page.waitForTimeout(3000);
|
|
||||||
|
|
||||||
// Should see interests page content
|
// Should see interests page content
|
||||||
const heading = page.getByText(/interests/i).first();
|
const heading = page.getByText(/interests/i).first();
|
||||||
await expect(heading).toBeVisible({ timeout: 10_000 });
|
await expect(heading).toBeVisible({ timeout: 15_000 });
|
||||||
|
|
||||||
// Check for table or board view
|
// Wait for either the table or pipeline board to render (dev-mode JIT can
|
||||||
const hasTable = await page.locator('table').isVisible({ timeout: 3_000 }).catch(() => false);
|
// take >3s on first hit). `isVisible()` is non-waiting; use `expect.poll`
|
||||||
const hasBoard = await page.getByText(/open|board|kanban/i).isVisible({ timeout: 3_000 }).catch(() => false);
|
// to actually wait for one of the views to appear.
|
||||||
expect(hasTable || hasBoard).toBeTruthy();
|
await expect
|
||||||
|
.poll(
|
||||||
|
async () => {
|
||||||
|
const table = await page
|
||||||
|
.locator('table')
|
||||||
|
.isVisible()
|
||||||
|
.catch(() => false);
|
||||||
|
const board = await page
|
||||||
|
.locator('[data-testid="pipeline-board"], [class*="board"]')
|
||||||
|
.first()
|
||||||
|
.isVisible()
|
||||||
|
.catch(() => false);
|
||||||
|
return table || board;
|
||||||
|
},
|
||||||
|
{ timeout: 15_000 },
|
||||||
|
)
|
||||||
|
.toBe(true);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('interest detail page works', async ({ page }) => {
|
test('interest detail page works', async ({ page }) => {
|
||||||
|
|||||||
@@ -12,9 +12,10 @@ test.describe('Dashboard', () => {
|
|||||||
// navigate to the port-scoped dashboard to verify the real content renders.
|
// navigate to the port-scoped dashboard to verify the real content renders.
|
||||||
await navigateTo(page, '/');
|
await navigateTo(page, '/');
|
||||||
expect(page.url()).toContain(`/${PORT_SLUG}`);
|
expect(page.url()).toContain(`/${PORT_SLUG}`);
|
||||||
// Should see the dashboard shell (KPI cards are always rendered at the top)
|
// Should see the dashboard shell (KPI cards are always rendered at the top).
|
||||||
|
// Dev-mode JIT compilation can push first-hit render past 10s.
|
||||||
await expect(page.getByText(/total clients/i).first()).toBeVisible({
|
await expect(page.getByText(/total clients/i).first()).toBeVisible({
|
||||||
timeout: 10_000,
|
timeout: 15_000,
|
||||||
});
|
});
|
||||||
// Should NOT see the old placeholder text
|
// Should NOT see the old placeholder text
|
||||||
await expect(page.getByText('Coming in Layer'))
|
await expect(page.getByText('Coming in Layer'))
|
||||||
@@ -25,9 +26,11 @@ test.describe('Dashboard', () => {
|
|||||||
// Test 2: All 4 KPI cards render
|
// Test 2: All 4 KPI cards render
|
||||||
test('all 4 KPI cards render without errors', async ({ page }) => {
|
test('all 4 KPI cards render without errors', async ({ page }) => {
|
||||||
await navigateTo(page, '/');
|
await navigateTo(page, '/');
|
||||||
await page.waitForTimeout(3_000);
|
|
||||||
|
|
||||||
// Look for KPI-related text/elements — the cards should contain numbers or labels
|
// Wait for the KPI cards to actually render (dev mode JIT can take >3s on
|
||||||
|
// a cold dashboard hit). The cards expose stable label text we can poll on.
|
||||||
|
await expect(page.getByText('Total Clients')).toBeVisible({ timeout: 15_000 });
|
||||||
|
|
||||||
const cards = page.locator('[class*="card"], [data-testid*="kpi"]');
|
const cards = page.locator('[class*="card"], [data-testid*="kpi"]');
|
||||||
const cardCount = await cards.count();
|
const cardCount = await cards.count();
|
||||||
expect(cardCount).toBeGreaterThanOrEqual(4);
|
expect(cardCount).toBeGreaterThanOrEqual(4);
|
||||||
|
|||||||
@@ -27,7 +27,12 @@ test.describe('System Monitoring', () => {
|
|||||||
test('all BullMQ queues listed with stats', async ({ page }) => {
|
test('all BullMQ queues listed with stats', async ({ page }) => {
|
||||||
await login(page, 'super_admin');
|
await login(page, 'super_admin');
|
||||||
await navigateTo(page, '/admin/monitoring');
|
await navigateTo(page, '/admin/monitoring');
|
||||||
await page.waitForTimeout(3_000);
|
|
||||||
|
// Anchor on a queue-only name (not in sidebar) to confirm the panel
|
||||||
|
// has finished loading before counting matches.
|
||||||
|
await expect(page.getByText('webhooks', { exact: false }).first()).toBeVisible({
|
||||||
|
timeout: 15_000,
|
||||||
|
});
|
||||||
|
|
||||||
// Expected queue names from QUEUE_CONFIGS
|
// Expected queue names from QUEUE_CONFIGS
|
||||||
const queueNames = [
|
const queueNames = [
|
||||||
@@ -46,7 +51,7 @@ test.describe('System Monitoring', () => {
|
|||||||
let foundCount = 0;
|
let foundCount = 0;
|
||||||
for (const name of queueNames) {
|
for (const name of queueNames) {
|
||||||
const queueCard = page.getByText(name, { exact: false }).first();
|
const queueCard = page.getByText(name, { exact: false }).first();
|
||||||
if (await queueCard.isVisible({ timeout: 2_000 }).catch(() => false)) {
|
if (await queueCard.isVisible().catch(() => false)) {
|
||||||
foundCount++;
|
foundCount++;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -162,7 +162,13 @@ test.describe('Admin Features', () => {
|
|||||||
|
|
||||||
test('monitoring dashboard shows queue overview with expected queues', async ({ page }) => {
|
test('monitoring dashboard shows queue overview with expected queues', async ({ page }) => {
|
||||||
await navigateTo(page, '/admin/monitoring');
|
await navigateTo(page, '/admin/monitoring');
|
||||||
await page.waitForTimeout(3_000);
|
|
||||||
|
// Wait for the queue overview section to render. The queue cards expose
|
||||||
|
// names that don't appear in the sidebar (e.g. webhooks, maintenance) so
|
||||||
|
// we anchor on one of those to confirm the panel has loaded.
|
||||||
|
await expect(page.getByText('webhooks', { exact: false }).first()).toBeVisible({
|
||||||
|
timeout: 15_000,
|
||||||
|
});
|
||||||
|
|
||||||
// All 10 expected queue names from QUEUE_CONFIGS
|
// All 10 expected queue names from QUEUE_CONFIGS
|
||||||
const expectedQueues = [
|
const expectedQueues = [
|
||||||
@@ -181,7 +187,7 @@ test.describe('Admin Features', () => {
|
|||||||
let foundCount = 0;
|
let foundCount = 0;
|
||||||
for (const queueName of expectedQueues) {
|
for (const queueName of expectedQueues) {
|
||||||
const queueEl = page.getByText(queueName, { exact: false }).first();
|
const queueEl = page.getByText(queueName, { exact: false }).first();
|
||||||
const visible = await queueEl.isVisible({ timeout: 2_000 }).catch(() => false);
|
const visible = await queueEl.isVisible().catch(() => false);
|
||||||
if (visible) foundCount++;
|
if (visible) foundCount++;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user