From 0630995bb2b62c1524767ccab98a8d85d1926f5d Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Sun, 2 Aug 2026 02:13:57 +0000 Subject: [PATCH] =?UTF-8?q?OH11=20=E2=80=94=20SW=20static=20cache-first,?= =?UTF-8?q?=20logout=20campaignOps=20wipe,=20offline=20e2e?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Service worker: cache-first for same-origin /_next/static/ (before RSC guard) - Logout: clearCampaignOpsStorage (abort sync → outbox → persistence) then Cache API - E2E: full offline journey in campaignOpsOffline (write→reload→online→sync) - Docs: CHANGELOG + ops-hibrido spec; test:e2e:ops-hybrid script Closes #173 Co-authored-by: Francisco Solla --- docs/CHANGELOG-AGENTS.md | 4 ++ docs/plans/oh11-sw-e2e-docs.md | 14 ++-- docs/plans/ops-hibrido-rsc-local-spec.md | 2 +- package.json | 1 + playwright.config.ts | 1 + scripts/lib/e2e-affected-manifest.mjs | 4 +- .../opsSync/clearCampaignOpsStorage.ts | 19 ++++++ .../campaign/opsSync/opsEstimateOutbox.ts | 19 ++++++ .../campaign/opsSync/opsMirrorClient.ts | 33 ++++++++-- .../campaign/opsSync/opsMunicipalityOutbox.ts | 43 ++++++++++++ .../campaign/shell/CampaignSidebar.tsx | 2 + src/utilities/campaignPwa.ts | 8 +++ tests/e2e/campaignOpsOffline.e2e.spec.ts | 66 +++++++++++++++++-- tests/unit/campaignPwa.unit.spec.ts | 17 +++++ 14 files changed, 215 insertions(+), 18 deletions(-) create mode 100644 src/components/campaign/opsSync/clearCampaignOpsStorage.ts diff --git a/docs/CHANGELOG-AGENTS.md b/docs/CHANGELOG-AGENTS.md index 7c9c7199..13243f68 100644 --- a/docs/CHANGELOG-AGENTS.md +++ b/docs/CHANGELOG-AGENTS.md @@ -4,7 +4,11 @@ Conteúdo movido do `AGENTS.md` em 2026-07-30 (fatiamento do paradigma de agente --- +<<<<<<< HEAD **Recently resolved (2026-08-02):** **B120** (Issue #207) — municípios mobile: combobox multi-filtro (chips + typeahead) no lugar da pilha NativeSelect; overview KPI + aviso de sort só em `md+`; cards densificados (cobertura/nível + controles compactos). URL B18 intacta. Plano: [`municipios-mobile-filtro-combobox-densificar.md`](docs/plans/municipios-mobile-filtro-combobox-densificar.md). +======= +**Recently resolved (2026-08-02):** **OH11** (Issue #173) — SW cache-first para `/_next/static/` (chunks hashed, prefixo `campanha-`); logout limpa campaignOps na ordem abort sync → outbox → persistence → Cache API (`clearCampaignOpsStorage` + `clearCampaignPwaCaches`); e2e `campaignOpsOffline` com jornada write→reload→online→sync (`OPS_HYBRID=1`). Plano: [`oh11-sw-e2e-docs.md`](docs/plans/oh11-sw-e2e-docs.md). +>>>>>>> 66a7da6c (OH11 — SW static cache-first, logout campaignOps wipe, offline e2e) **Recently resolved (2026-08-02):** **OH10** (Issue #171) — writes municipality staff CAS (`baseUpdatedAt`) + outbox irmão (`opsMunicipalityOutbox`) para municipalityUpdate, declareVotes, tendência, engagement e advisors; flag OFF mantém caminhos actuais. Plano: [`oh10-municipality-writes-cas.md`](docs/plans/oh10-municipality-writes-cas.md). diff --git a/docs/plans/oh11-sw-e2e-docs.md b/docs/plans/oh11-sw-e2e-docs.md index 6231c960..392ff103 100644 --- a/docs/plans/oh11-sw-e2e-docs.md +++ b/docs/plans/oh11-sw-e2e-docs.md @@ -1,7 +1,7 @@ # OH11 — SW `/_next/static` cache-first + e2e offline + docs -Status: rascunho -Atualizado em: 2026-08-01 +Status: entregue +Atualizado em: 2026-08-02 Issue: #173 Priority: P1 Model: composer-2.5 @@ -42,9 +42,9 @@ Dados: N/A. - **Quota:** ~0,5 - **Aceite:** - - [ ] chunks `/_next/static/` servidos do cache na 2ª visita offline - - [ ] RSC/Flight nunca cacheado (pin existente mantido) - - [ ] logout limpa persistence + outbox + caches (ordem documentada no código) + - [x] chunks `/_next/static/` servidos do cache na 2ª visita offline + - [x] RSC/Flight nunca cacheado (pin existente mantido) + - [x] logout limpa persistence + outbox + caches (ordem documentada no código) - **Verify:** `pnpm gate:fast` + `campaignPwa.unit.spec.ts` - **Files:** `campaignPwa.ts`, `campaignPwaClient.ts`, spec unit - **Tamanho:** M @@ -53,8 +53,8 @@ Dados: N/A. - **Quota:** ~0,5 - **Aceite:** - - [ ] cenário write→reload→online→sync verde - - [ ] CHANGELOG + plano-mãe actualizados + - [x] cenário write→reload→online→sync verde + - [x] CHANGELOG + plano-mãe actualizados - **Verify:** `pnpm gate:fast` + e2e offline - **Files:** spec e2e, docs - **Tamanho:** M diff --git a/docs/plans/ops-hibrido-rsc-local-spec.md b/docs/plans/ops-hibrido-rsc-local-spec.md index ba663aea..9fffc993 100644 --- a/docs/plans/ops-hibrido-rsc-local-spec.md +++ b/docs/plans/ops-hibrido-rsc-local-spec.md @@ -56,7 +56,7 @@ Brief: - Documento-mãe que trava: arquitetura híbrida, escopo do snapshot, CAS/outbox, boundaries, critérios de aceite do projecto e ordem das Issues OH2–OH14. - Engenheiro júnior lê este doc + o plano da sua Issue e executa sem reunião. - Com `OPS_HYBRID=1` (entregas filhas): abrir `/campanha` sincroniza o snapshot; chrome “Actualizado”; offline renderiza do mirror; writes via outbox + CAS. -- CI sem `OPS_HYBRID` idêntica a `main`. +- CI sem `OPS_HYBRID` idêntica a `main`; jornada offline completa em `campaignOpsOffline.e2e.spec.ts` com `OPS_HYBRID=1` (OH11). ## Dados → decisão → apresentação diff --git a/package.json b/package.json index 19ee5fa7..dc58ed6d 100644 --- a/package.json +++ b/package.json @@ -66,6 +66,7 @@ "test": "pnpm run test:unit && pnpm run test:int", "test:all": "pnpm run test && pnpm run test:e2e", "test:e2e": "cross-env NODE_OPTIONS=\"--no-deprecation --conditions=react-server --import=tsx/esm\" playwright test --config=playwright.config.ts", + "test:e2e:ops-hybrid": "cross-env OPS_HYBRID=1 NODE_OPTIONS=\"--no-deprecation --conditions=react-server --import=tsx/esm\" playwright test --config=playwright.config.ts tests/e2e/campaignOpsOffline.e2e.spec.ts tests/e2e/campaignOpsEstimateOutbox.e2e.spec.ts", "test:e2e:affected": "node scripts/run-e2e-affected.mjs", "test:int": "cross-env NODE_OPTIONS=--no-deprecation vitest run --config ./vitest.config.mts", "test:unit": "cross-env NODE_OPTIONS=--no-deprecation DATABASE_URL=postgresql://invalid:invalid@127.0.0.1:1/unit_tests_must_not_connect vitest run --config ./vitest.unit.config.mts", diff --git a/playwright.config.ts b/playwright.config.ts index 1343f6f2..3033030f 100644 --- a/playwright.config.ts +++ b/playwright.config.ts @@ -119,6 +119,7 @@ export default defineConfig({ PAYLOAD_SECRET: process.env.PAYLOAD_SECRET ?? 'test-only-secret-not-used-in-production', NEXT_PUBLIC_SITE_URL: process.env.NEXT_PUBLIC_SITE_URL ?? baseURL, LIST_UNIFIED: process.env.LIST_UNIFIED ?? '', + OPS_HYBRID: process.env.OPS_HYBRID ?? '', }, }, }) diff --git a/scripts/lib/e2e-affected-manifest.mjs b/scripts/lib/e2e-affected-manifest.mjs index d8f6d051..034a413c 100644 --- a/scripts/lib/e2e-affected-manifest.mjs +++ b/scripts/lib/e2e-affected-manifest.mjs @@ -95,7 +95,7 @@ export const E2E_AFFECTED_MANIFEST = [ 'src/components/campaign/shared/Wizard', 'src/components/campaign/shared/useWizardBackHistory', ], - specs: ['campaign-pwa', 'campaignWizardChrome', 'campaignMunicipalities'], + specs: ['campaign-pwa', 'campaignWizardChrome', 'campaignMunicipalities', 'campaignOpsOffline'], }, // Domains without a dedicated e2e family still wake campaign home smoke so // the affected classifier cannot return mode=none on an unmapped domain dir. @@ -131,6 +131,6 @@ export const E2E_AFFECTED_MANIFEST = [ `${CAMPAIGN_APP}/perfil`, `${CAMPAIGN_APP}/quadro`, ], - specs: ['campaignHomeActions', 'campaignMunicipalities', 'campaignOpsEstimateOutbox'], + specs: ['campaignHomeActions', 'campaignMunicipalities', 'campaignOpsEstimateOutbox', 'campaignOpsOffline'], }, ] diff --git a/src/components/campaign/opsSync/clearCampaignOpsStorage.ts b/src/components/campaign/opsSync/clearCampaignOpsStorage.ts new file mode 100644 index 00000000..1c215934 --- /dev/null +++ b/src/components/campaign/opsSync/clearCampaignOpsStorage.ts @@ -0,0 +1,19 @@ +'use client' + +import { clearOpsEstimateOutboxForLogout } from '@/components/campaign/opsSync/opsEstimateOutbox' +import { + abortOpsMirrorSync, + clearOpsMirrorPersistenceForLogout, +} from '@/components/campaign/opsSync/opsMirrorClient' +import { clearOpsMunicipalityOutboxForLogout } from '@/components/campaign/opsSync/opsMunicipalityOutbox' + +/** + * Logout wipe for campaignOps mirror + outbox (OH1/OH11). + * + * Order: abort in-flight sync → outbox → persistence → (caller clears Cache API). + */ +export const clearCampaignOpsStorage = async (): Promise => { + abortOpsMirrorSync() + await Promise.all([clearOpsEstimateOutboxForLogout(), clearOpsMunicipalityOutboxForLogout()]) + await clearOpsMirrorPersistenceForLogout() +} diff --git a/src/components/campaign/opsSync/opsEstimateOutbox.ts b/src/components/campaign/opsSync/opsEstimateOutbox.ts index 554bc83d..1c1ee164 100644 --- a/src/components/campaign/opsSync/opsEstimateOutbox.ts +++ b/src/components/campaign/opsSync/opsEstimateOutbox.ts @@ -179,3 +179,22 @@ export const collectOpsEstimateOutboxKeys = (): Set => { } return keys } + +/** Logout wipe — outbox storage + in-memory rows (OH11). */ +export const clearOpsEstimateOutboxForLogout = async (): Promise => { + if (executorSingleton) { + try { + await executorSingleton.clearOutbox() + executorSingleton.dispose() + } catch { + // Best effort — private mode / torn-down storage. + } + executorSingleton = null + initPromise = null + } + for (const row of opsEstimateOutboxCollection.toArray) { + if (opsEstimateOutboxCollection.has(row.pledgeId)) { + opsEstimateOutboxCollection.delete(row.pledgeId) + } + } +} diff --git a/src/components/campaign/opsSync/opsMirrorClient.ts b/src/components/campaign/opsSync/opsMirrorClient.ts index a80fa51d..72f39756 100644 --- a/src/components/campaign/opsSync/opsMirrorClient.ts +++ b/src/components/campaign/opsSync/opsMirrorClient.ts @@ -55,6 +55,13 @@ let lastSyncedAtMirror: string | null = null let persistenceMode: OpsMirrorPersistenceMode | null = null let storeSingleton: OpsMirrorStore | null = null let bootPromise: Promise<{ mode: OpsMirrorPersistenceMode; hydrated: boolean }> | null = null +let activeSyncAbort: AbortController | null = null + +/** Abort an in-flight ops-sync fetch (logout — OH11). */ +export const abortOpsMirrorSync = (): void => { + activeSyncAbort?.abort() + activeSyncAbort = null +} const replaceCollectionRows = ( collection: { @@ -114,12 +121,22 @@ export const getOpsMirrorPersistenceMode = (): OpsMirrorPersistenceMode | null = export const getOpsMirrorLastSyncedAt = (): string | null => lastSyncedAtMirror +/** Logout wipe — persistence only; outbox cleared separately (OH11 order). */ +export const clearOpsMirrorPersistenceForLogout = async (): Promise => { + wipeOpsMirrorCollections() + bootPromise = null + const store = storeSingleton + storeSingleton = null + persistenceMode = null + if (store) { + await store.clear() + } +} + /** Test/DI seam — reset module singletons between unit cases. */ export const resetOpsMirrorClientForTests = async (): Promise => { - wipeOpsMirrorCollections() - storeSingleton = null - bootPromise = null - persistenceMode = null + abortOpsMirrorSync() + await clearOpsMirrorPersistenceForLogout() } const resolveOutboxKeys = (explicit?: ReadonlySet): ReadonlySet => { @@ -200,6 +217,8 @@ export type SyncOpsMirrorOptions = { export const syncOpsMirror = async (options: SyncOpsMirrorOptions = {}): Promise => { const fetchImpl = options.fetchImpl ?? fetch const store = options.store ?? storeSingleton + const controller = new AbortController() + activeSyncAbort = controller try { const response = await fetchImpl(OPS_SYNC_PATH, { @@ -207,6 +226,7 @@ export const syncOpsMirror = async (options: SyncOpsMirrorOptions = {}): Promise credentials: 'same-origin', headers: { Accept: 'application/json' }, cache: 'no-store', + signal: controller.signal, }) if (!response.ok) { @@ -251,11 +271,16 @@ export const syncOpsMirror = async (options: SyncOpsMirrorOptions = {}): Promise return { status: 'idle', lastSyncedAt: syncedAt } } catch (error) { + if (error instanceof DOMException && error.name === 'AbortError') { + return { status: 'idle', lastSyncedAt: lastSyncedAtMirror } + } const message = error instanceof Error ? error.message : String(error) return { status: 'error', lastSyncedAt: lastSyncedAtMirror, lastError: message, } + } finally { + if (activeSyncAbort === controller) activeSyncAbort = null } } diff --git a/src/components/campaign/opsSync/opsMunicipalityOutbox.ts b/src/components/campaign/opsSync/opsMunicipalityOutbox.ts index f66280a0..190286d4 100644 --- a/src/components/campaign/opsSync/opsMunicipalityOutbox.ts +++ b/src/components/campaign/opsSync/opsMunicipalityOutbox.ts @@ -654,3 +654,46 @@ export const discardOpsAdvisorsOutboxRow = (municipalityId: number): void => { advisorsOutboxCollection.delete(municipalityId) } } + +const wipeMunicipalityOutboxCollections = (): void => { + for (const row of declareVotesOutboxCollection.toArray) { + if (declareVotesOutboxCollection.has(row.id)) { + declareVotesOutboxCollection.delete(row.id) + } + } + for (const row of municipalityUpdateOutboxCollection.toArray) { + if (municipalityUpdateOutboxCollection.has(row.id)) { + municipalityUpdateOutboxCollection.delete(row.id) + } + } + for (const row of politicalTrendOutboxCollection.toArray) { + if (politicalTrendOutboxCollection.has(row.municipalityId)) { + politicalTrendOutboxCollection.delete(row.municipalityId) + } + } + for (const row of engagementLevelOutboxCollection.toArray) { + if (engagementLevelOutboxCollection.has(row.municipalityId)) { + engagementLevelOutboxCollection.delete(row.municipalityId) + } + } + for (const row of advisorsOutboxCollection.toArray) { + if (advisorsOutboxCollection.has(row.municipalityId)) { + advisorsOutboxCollection.delete(row.municipalityId) + } + } +} + +/** Logout wipe — outbox storage + in-memory rows (OH11). */ +export const clearOpsMunicipalityOutboxForLogout = async (): Promise => { + if (executorSingleton) { + try { + await executorSingleton.clearOutbox() + executorSingleton.dispose() + } catch { + // Best effort — private mode / torn-down storage. + } + executorSingleton = null + initPromise = null + } + wipeMunicipalityOutboxCollections() +} diff --git a/src/components/campaign/shell/CampaignSidebar.tsx b/src/components/campaign/shell/CampaignSidebar.tsx index a9e7b65b..872ddfb5 100644 --- a/src/components/campaign/shell/CampaignSidebar.tsx +++ b/src/components/campaign/shell/CampaignSidebar.tsx @@ -5,6 +5,7 @@ import { usePathname } from 'next/navigation' import { useState, type FormEvent, type ReactNode } from 'react' import { logoutCampaign } from '@/app/(campaign)/campanha/actions/auth' +import { clearCampaignOpsStorage } from '@/components/campaign/opsSync/clearCampaignOpsStorage' import { CampaignScopeBadge } from '@/components/campaign/shared/CampaignScopeBadge' import { CampaignUserAvatar } from '@/components/campaign/shared/CampaignUserAvatar' import { CampaignLogo } from '@/components/campaign/shell/campaign-logo' @@ -79,6 +80,7 @@ export const CampaignSidebar = ({ user }: { user: CampaignSidebarUser }) => { clearRecentVisits() clearLastActedMunicipality() clearMunicipalitySavedFilters() + await clearCampaignOpsStorage() await clearCampaignPwaCaches() // logoutCampaign redirects — no need to reset the pending flag on success. await logoutCampaign() diff --git a/src/utilities/campaignPwa.ts b/src/utilities/campaignPwa.ts index 7d68af02..9f5461a7 100644 --- a/src/utilities/campaignPwa.ts +++ b/src/utilities/campaignPwa.ts @@ -123,6 +123,8 @@ const isInvitePath = (pathname) => pathname.startsWith(SCOPE + '/convite'); const isCampaignIconPath = (pathname) => pathname.startsWith('/campaign-icons/'); +const isNextStaticPath = (pathname) => pathname.startsWith('/_next/static/'); + const isRscRequest = (request) => request.headers.get('RSC') === '1' || request.headers.has('Next-Router-State-Tree'); @@ -173,6 +175,12 @@ self.addEventListener('fetch', (event) => { return; } + // Hashed build chunks — cache-first so a revisit works offline (never RSC/Flight). + if (isNextStaticPath(url.pathname)) { + event.respondWith(cacheFirst(request)); + return; + } + if (!isCampaignPath(url.pathname)) return; if (request.mode === 'navigate') { diff --git a/tests/e2e/campaignOpsOffline.e2e.spec.ts b/tests/e2e/campaignOpsOffline.e2e.spec.ts index 27e7bfbb..23dd551d 100644 --- a/tests/e2e/campaignOpsOffline.e2e.spec.ts +++ b/tests/e2e/campaignOpsOffline.e2e.spec.ts @@ -1,14 +1,15 @@ import { expect, test } from './fixtures/campaignE2EFixtures.js' /** - * OH9 — dual-path municipality detail. Requires `OPS_HYBRID=1` on the - * Playwright webServer (compile-time). Default CI keeps the flag off so - * characterization / municipalities specs continue to pin the RSC path. + * OH9/OH11 — dual-path municipality detail + full offline journey. Requires + * `OPS_HYBRID=1` on the Playwright webServer (compile-time). Default CI keeps + * the flag off so characterization / municipalities specs continue to pin the + * RSC path. */ const opsHybridEnabled = process.env.OPS_HYBRID === '1' || process.env.OPS_HYBRID?.toLowerCase() === 'true' -test.describe('OH9 municipality detail dual-path (OPS_HYBRID)', () => { +test.describe('OH9/OH11 campaign ops offline (OPS_HYBRID)', () => { test.skip(!opsHybridEnabled, 'Set OPS_HYBRID=1 on the e2e webServer to run this dual-path.') test('offline swaps to Local header + pledges with honest online-only placeholder', async ({ @@ -65,4 +66,61 @@ test.describe('OH9 municipality detail dual-path (OPS_HYBRID)', () => { // Tab nav is RSC-only — Local path must not crash by remounting it. await expect(page.getByRole('link', { name: 'Visão geral' })).toHaveCount(0) }) + + test('open → sync → offline detail → write → reload → online → sync', async ({ + campaign, + page, + }) => { + const { fixtures } = campaign + const municipality = await fixtures.claimMunicipality() + const advisor = await fixtures.createCampaignUser('advisor', { + name: fixtures.value('Assessor OH11'), + }) + await campaign.payload.update({ + collection: 'municipality', + id: municipality.id, + data: { advisors: [advisor.id] }, + depth: 0, + }) + fixtures.touchMunicipality(municipality.id) + + const { leadershipId } = await fixtures.createStaffLeadership({ + namePrefix: 'Liderança OH11', + municipalities: [municipality], + supportStatus: 'engajado', + }) + await campaign.payload.create({ + collection: 'votePledge', + data: { + leadership: leadershipId, + municipality: municipality.id, + declaredVotes: 75, + }, + depth: 0, + }) + + await campaign.login(page, advisor.email!, advisor.password) + await page.goto(`${campaign.baseURL}/campanha/municipios/${municipality.slug}`) + await expect(page.getByRole('heading', { name: municipality.name })).toBeVisible() + + await page.waitForResponse( + (response) => + response.url().includes('/campanha/api/ops-sync') && response.request().method() === 'GET', + { timeout: 30_000 }, + ) + + await page.context().setOffline(true) + + await expect(page.getByRole('heading', { name: municipality.name })).toBeVisible() + await page.getByLabel('Média', { exact: true }).fill('42') + await page.getByLabel('Justificativa').fill('OH11 offline na estrada.') + await page.getByRole('button', { name: 'Salvar estimativa' }).click() + await expect(page.getByText('Pendente', { exact: true })).toBeVisible() + + await page.reload() + await expect(page.getByText('Pendente', { exact: true })).toBeVisible() + + await page.context().setOffline(false) + await expect(page.getByText('Média: 42')).toBeVisible({ timeout: 30_000 }) + }) }) diff --git a/tests/unit/campaignPwa.unit.spec.ts b/tests/unit/campaignPwa.unit.spec.ts index 3a0fe523..2fb1dfaa 100644 --- a/tests/unit/campaignPwa.unit.spec.ts +++ b/tests/unit/campaignPwa.unit.spec.ts @@ -42,6 +42,22 @@ describe('campaign PWA helpers', () => { expect(script).toContain('skipWaiting') expect(script).toContain('clients.claim') }) + + it('serves /_next/static with cache-first and never caches RSC or invite paths', () => { + const script = buildCampaignServiceWorkerScript('sha-test') + + expect(script).toContain('isNextStaticPath') + expect(script).toContain("pathname.startsWith('/_next/static/')") + + const staticBranch = script.indexOf('isNextStaticPath(url.pathname)') + const rscGuard = script.indexOf('if (isRscRequest(request)) return') + const inviteGuard = script.indexOf('if (isInvitePath(url.pathname)) return') + + expect(staticBranch).toBeGreaterThan(-1) + expect(rscGuard).toBeGreaterThan(staticBranch) + expect(inviteGuard).toBeGreaterThan(-1) + expect(inviteGuard).toBeLessThan(staticBranch) + }) }) describe('campaign PWA route handlers', () => { @@ -67,5 +83,6 @@ describe('campaign PWA route handlers', () => { expect(body).toContain('campanha-') expect(body).toContain(`SCOPE + '/convite'`) expect(body).toContain('isRscRequest') + expect(body).toContain('isNextStaticPath') }) })