Skip to content

Implement PWA auto-update strategy with silent cache cleanup and toast notification#4

Merged
will-aam merged 1 commit into
mainfrom
copilot/implement-cache-strategy-pwa
May 16, 2026
Merged

Implement PWA auto-update strategy with silent cache cleanup and toast notification#4
will-aam merged 1 commit into
mainfrom
copilot/implement-cache-strategy-pwa

Conversation

Copilot AI commented May 16, 2026

Copy link
Copy Markdown
Contributor

Implements the PWA cache management strategy from docs/PWA_CACHE_STRATEGY.md: the app now silently applies Service Worker updates without user intervention, clears stale caches automatically, and briefly notifies the user before reloading — all without touching localStorage (preserving theme preference).

Changes

  • next.config.mjs — Enabled register: true, skipWaiting: true, and cleanupOutdatedCaches: true on the @ducanh2912/next-pwa config. cleanupOutdatedCaches only purges Cache API storage, leaving localStorage intact.

  • components/pwa-updater.tsx — New "use client" component that binds to navigator.serviceWorker's controllerchange event, fires a sonner toast, then reloads after 1.5s:

navigator.serviceWorker.addEventListener("controllerchange", () => {
  toast.info("Atualização disponível", {
    description: "A aplicar a nova versão do Totten...",
    duration: 3000,
  });
  setTimeout(() => window.location.reload(), 1500);
});
  • app/layout.tsx — Mounts <PWAUpdater /> inside ThemeProvider in the root layout so the listener is active on every page. Also adds ?v=2 cache-busting to manifest and icon links to force re-fetch of PWA assets on deploy.
Original prompt

O usuário quer implementar a estratégia de cache e atualização automática de PWA documentada no arquivo PWA_CACHE_STRATEGY.md. O objetivo é garantir que o app se atualize silenciosamente e limpe o cache antigo do Service Worker, mas sem perder as preferências do usuário (como o tema escuro/claro salvo em localStorage/cookies), além de exibir um aviso visual (Toast) quando uma atualização estiver sendo aplicada.

Por favor, faça o seguinte no repositório will-aam/totten:

  1. Verifique a configuração do PWA no arquivo next.config.mjs ou next.config.ts/next.config.js. Garanta que as opções register: true, skipWaiting: true e cleanupOutdatedCaches: true estejam habilitadas. O cleanupOutdatedCaches limpa apenas o armazenamento de Cache API do Service Worker, não afetando o localStorage, o que atende perfeitamente ao requisito de não perder o tema.
  2. Crie ou atualize o componente de notificação de atualização (ex: components/pwa-updater.tsx ou similar). Ele deve rodar no cliente ("use client";), escutar o evento controllerchange do navigator.serviceWorker, exibir um toast informando sobre a atualização usando a biblioteca de toasts já existente no projeto (ex: sonner que faz parte da stack shadcn-ui no projeto) e dar o window.location.reload().
  3. Adicione esse novo componente PWAUpdater no layout principal (app/layout.tsx), para que o listener funcione em todas as páginas.
  4. (Opcional, mas recomendado na doc) Adicione/atualize o parâmetro de versão (?v=2 ou similar) nos links de manifesto e ícones se existirem no projeto, para forçar o cache busting.

The following is the prior conversation context from the user's chat exploration (may be truncated):

User: ```
"use client";

import { useState, useEffect, useRef, useCallback } from "react";
import useSWR from "swr";
import useSWRInfinite from "swr/infinite";
import Link from "next/link";
import { useSession } from "next-auth/react";
import { AdminHeader } from "@/components/admin-header";
import { PendingCheckInsCard } from "@/components/admin/pending-checkins-card";
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "@/components/ui/card";
import { Skeleton } from "@/components/ui/skeleton";
import {
CalendarCheck,
Group,
AlertTriangle,
Clock,
ChevronUp,
RefreshCw,
User,
} from "@boxicons/react";
import type { BoxIconProps } from "@boxicons/react";
import { cn } from "@/lib/utils";

const fetcher = (url: string) => fetch(url).then((r) => r.json());

type CheckIn = {
id: string;
client_id: string;
client_name: string;
date_time: string;
professional_name?: string | null;
};

function KpiCard({
title,
value,
description,
icon: Icon,
className,
}: {
title: string;
value: string | number;
description: string;
icon: React.ForwardRefExoticComponent<
BoxIconProps & React.RefAttributes

;
className?: string;
}) {
return (
<Card
className={cn(
"border-border shadow-sm flex flex-col justify-between",
className,
)}
>


{title}







{value}


{description}




);
}

function CheckInListItem({ checkIn }: { checkIn: CheckIn }) {
const date = new Date(checkIn.date_time);
const formattedDate = date.toLocaleDateString("pt-BR", {
day: "2-digit",
month: "short",
});
const formattedTime = date.toLocaleTimeString("pt-BR", {
hour: "2-digit",
minute: "2-digit",
});

const initial = checkIn.client_name
? checkIn.client_name.charAt(0).toUpperCase()
: "?";

return (


<Link
href={checkIn.client_id ? /admin/clients/${checkIn.client_id} : "#"}
className="flex items-center gap-3 md:gap-4 cursor-pointer hover:opacity-80 transition-opacity"
>

{initial}



{checkIn.clien...

This pull request was created from Copilot chat.

@vercel

vercel Bot commented May 16, 2026

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
totten Ready Ready Preview, Comment May 16, 2026 9:16pm

Copilot AI changed the title [WIP] Implement cache strategy and automatic update for PWA Implement PWA auto-update strategy with silent cache cleanup and toast notification May 16, 2026
Copilot AI requested a review from will-aam May 16, 2026 21:17
@will-aam will-aam marked this pull request as ready for review May 16, 2026 21:17
Copilot AI review requested due to automatic review settings May 16, 2026 21:17

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot wasn't able to review any files in this pull request.


💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

@will-aam will-aam merged commit a4593f3 into main May 16, 2026
3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants