P4-C: PWA installable, service worker push & campagne de fiabilité dialogues
- PWA: public/manifest.webmanifest + icon.svg + meta index.html (theme-color, apple-touch-icon) - public/sw.js: service worker push-only (push → showNotification tag=sessionId ; notificationclick → focus/ouvre /sessions/<id>) — pas de précache (hors périmètre) - lib/push.ts + stores/push.ts: enable/disable, abonnement VAPID, enregistrement SW au boot - DashboardView: toggle « Notifications » (gardé par pushSupported) + i18n en/fr - campagne de fiabilité (verdict S3): classification de tous les types de dialogue sur captures réelles (trust/permission×2/question) + refus Esc (deny-esc2) + plan (synthétique) - acceptance-p4.mjs: VAPID/auth/Origin, subscribe idempotent/unsubscribe, answer (rejets) Choix: SW écrit à la main plutôt que vite-plugin-pwa (qui tirait ~295 paquets Workbox + 2 vulns esbuild high pour un SW push-only). Zéro dépendance front nouvelle. 175 tests verts, acceptance p1..p4 ALL GREEN. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -4,6 +4,14 @@
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<meta name="color-scheme" content="dark" />
|
||||
<meta name="theme-color" content="#09090b" />
|
||||
<link rel="manifest" href="/manifest.webmanifest" />
|
||||
<link rel="icon" type="image/svg+xml" href="/icon.svg" />
|
||||
<!-- iOS : le Web Push n'est disponible qu'en PWA installée (« Ajouter à l'écran d'accueil ») -->
|
||||
<meta name="apple-mobile-web-app-capable" content="yes" />
|
||||
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />
|
||||
<meta name="apple-mobile-web-app-title" content="Arboretum" />
|
||||
<link rel="apple-touch-icon" href="/icon.svg" />
|
||||
<title>Arboretum</title>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
18
packages/web/public/icon.svg
Normal file
18
packages/web/public/icon.svg
Normal file
@@ -0,0 +1,18 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="512" height="512" viewBox="0 0 512 512" role="img" aria-label="Arboretum">
|
||||
<rect width="512" height="512" fill="#09090b"/>
|
||||
<!-- arbre / branches (worktrees) — tracé dans la zone sûre maskable (~80% central) -->
|
||||
<g fill="none" stroke="#34d399" stroke-width="22" stroke-linecap="round" stroke-linejoin="round">
|
||||
<!-- tronc -->
|
||||
<path d="M256 420 V232"/>
|
||||
<!-- branche gauche -->
|
||||
<path d="M256 300 L168 212"/>
|
||||
<!-- branche droite -->
|
||||
<path d="M256 268 L344 180"/>
|
||||
</g>
|
||||
<!-- nœuds (sessions) -->
|
||||
<g fill="#34d399">
|
||||
<circle cx="256" cy="156" r="34"/>
|
||||
<circle cx="160" cy="196" r="26"/>
|
||||
<circle cx="352" cy="164" r="26"/>
|
||||
</g>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 727 B |
13
packages/web/public/manifest.webmanifest
Normal file
13
packages/web/public/manifest.webmanifest
Normal file
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"name": "Arboretum",
|
||||
"short_name": "Arboretum",
|
||||
"description": "A self-hosted dashboard for your git worktrees and Claude Code sessions.",
|
||||
"start_url": "/",
|
||||
"scope": "/",
|
||||
"display": "standalone",
|
||||
"background_color": "#09090b",
|
||||
"theme_color": "#09090b",
|
||||
"icons": [
|
||||
{ "src": "/icon.svg", "sizes": "any", "type": "image/svg+xml", "purpose": "any maskable" }
|
||||
]
|
||||
}
|
||||
52
packages/web/public/sw.js
Normal file
52
packages/web/public/sw.js
Normal file
@@ -0,0 +1,52 @@
|
||||
// Service worker Arboretum (P4-C) : Web Push + clic de notification.
|
||||
// Volontairement minimal — pas de précache offline (hors périmètre P4) : son seul rôle est de
|
||||
// recevoir les push (session passée en `waiting`) et d'ouvrir/focus la vue session au clic.
|
||||
|
||||
self.addEventListener('push', (event) => {
|
||||
let data = {};
|
||||
try {
|
||||
data = event.data ? event.data.json() : {};
|
||||
} catch {
|
||||
data = {};
|
||||
}
|
||||
const title = data.title || 'Arboretum';
|
||||
const options = {
|
||||
body: data.body || 'A session needs your input.',
|
||||
tag: data.sessionId || 'arboretum', // remplace la notif précédente de la même session
|
||||
data: { url: data.url || '/' },
|
||||
icon: '/icon.svg',
|
||||
badge: '/icon.svg',
|
||||
requireInteraction: true, // ignoré sur iOS, respecté ailleurs
|
||||
};
|
||||
event.waitUntil(self.registration.showNotification(title, options));
|
||||
});
|
||||
|
||||
self.addEventListener('notificationclick', (event) => {
|
||||
event.notification.close();
|
||||
const url = (event.notification.data && event.notification.data.url) || '/';
|
||||
const target = new URL(url, self.location.origin).href;
|
||||
event.waitUntil(
|
||||
(async () => {
|
||||
const clients = await self.clients.matchAll({ type: 'window', includeUncontrolled: true });
|
||||
for (const client of clients) {
|
||||
// un onglet de l'app est déjà ouvert : on le focus (et on y navigue si besoin)
|
||||
if ('focus' in client) {
|
||||
await client.focus();
|
||||
if (client.url !== target && 'navigate' in client) {
|
||||
try {
|
||||
await client.navigate(target);
|
||||
} catch {
|
||||
// navigate peut échouer selon le contexte ; le focus suffit
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
await self.clients.openWindow(target);
|
||||
})(),
|
||||
);
|
||||
});
|
||||
|
||||
// Pas de précache : on s'active immédiatement pour que le push soit opérationnel sans recharger.
|
||||
self.addEventListener('install', () => self.skipWaiting());
|
||||
self.addEventListener('activate', (event) => event.waitUntil(self.clients.claim()));
|
||||
@@ -97,6 +97,12 @@ export default {
|
||||
back: 'Sessions',
|
||||
notAttachable: 'This session runs outside Arboretum — fork it to interact, or resume it once it has stopped.',
|
||||
},
|
||||
push: {
|
||||
enable: 'Enable notifications',
|
||||
disable: 'Notifications on',
|
||||
denied: 'Notification permission denied — enable it in your browser settings.',
|
||||
unsupported: 'Push needs HTTPS (e.g. Tailscale Serve); on iOS, install the app to your home screen first.',
|
||||
},
|
||||
ws: {
|
||||
reconnecting: 'Connection lost — reconnecting…',
|
||||
},
|
||||
|
||||
@@ -100,6 +100,12 @@ const fr: typeof en = {
|
||||
notAttachable:
|
||||
'Cette session tourne hors d’Arboretum — dupliquez-la pour interagir, ou reprenez-la une fois arrêtée.',
|
||||
},
|
||||
push: {
|
||||
enable: 'Activer les notifications',
|
||||
disable: 'Notifications activées',
|
||||
denied: 'Permission de notification refusée — activez-la dans les réglages du navigateur.',
|
||||
unsupported: 'Le push nécessite HTTPS (ex. Tailscale Serve) ; sur iOS, installez d’abord l’app sur l’écran d’accueil.',
|
||||
},
|
||||
ws: {
|
||||
reconnecting: 'Connexion perdue — reconnexion…',
|
||||
},
|
||||
|
||||
70
packages/web/src/lib/push.ts
Normal file
70
packages/web/src/lib/push.ts
Normal file
@@ -0,0 +1,70 @@
|
||||
// Abonnement Web Push côté navigateur (P4-C). Enregistre le service worker, demande la permission,
|
||||
// s'abonne avec la clé VAPID publique du serveur, et transmet l'abonnement au daemon.
|
||||
import { api } from './api';
|
||||
import type { VapidKeyResponse } from '@arboretum/shared';
|
||||
|
||||
const SW_URL = '/sw.js';
|
||||
|
||||
/** Push nécessite service worker + PushManager + Notification (et un contexte sécurisé : localhost ou HTTPS). */
|
||||
export function pushSupported(): boolean {
|
||||
return 'serviceWorker' in navigator && 'PushManager' in window && 'Notification' in window;
|
||||
}
|
||||
|
||||
export function notificationPermission(): NotificationPermission {
|
||||
return 'Notification' in window ? Notification.permission : 'denied';
|
||||
}
|
||||
|
||||
export async function registerServiceWorker(): Promise<ServiceWorkerRegistration | null> {
|
||||
if (!('serviceWorker' in navigator)) return null;
|
||||
try {
|
||||
return await navigator.serviceWorker.register(SW_URL);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// La clé VAPID publique est transmise en base64url ; PushManager attend un BufferSource
|
||||
// adossé à un ArrayBuffer (pas SharedArrayBuffer) → on type explicitement le buffer.
|
||||
function urlBase64ToUint8Array(base64: string): Uint8Array<ArrayBuffer> {
|
||||
const padding = '='.repeat((4 - (base64.length % 4)) % 4);
|
||||
const b64 = (base64 + padding).replace(/-/g, '+').replace(/_/g, '/');
|
||||
const raw = atob(b64);
|
||||
const out = new Uint8Array(new ArrayBuffer(raw.length));
|
||||
for (let i = 0; i < raw.length; i++) out[i] = raw.charCodeAt(i);
|
||||
return out;
|
||||
}
|
||||
|
||||
export async function currentSubscription(): Promise<PushSubscription | null> {
|
||||
if (!pushSupported()) return null;
|
||||
const reg = await navigator.serviceWorker.ready;
|
||||
return reg.pushManager.getSubscription();
|
||||
}
|
||||
|
||||
export type EnableResult = 'enabled' | 'denied' | 'unsupported';
|
||||
|
||||
export async function enablePush(): Promise<EnableResult> {
|
||||
if (!pushSupported()) return 'unsupported';
|
||||
const permission = await Notification.requestPermission();
|
||||
if (permission !== 'granted') return 'denied';
|
||||
await registerServiceWorker();
|
||||
const reg = await navigator.serviceWorker.ready;
|
||||
const { key } = await api.get<VapidKeyResponse>('/api/v1/push/vapid-public-key');
|
||||
const sub =
|
||||
(await reg.pushManager.getSubscription()) ??
|
||||
(await reg.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: urlBase64ToUint8Array(key) }));
|
||||
const json = sub.toJSON();
|
||||
const keys = json.keys ?? {};
|
||||
await api.post('/api/v1/push/subscribe', { endpoint: sub.endpoint, keys: { p256dh: keys.p256dh ?? '', auth: keys.auth ?? '' } });
|
||||
return 'enabled';
|
||||
}
|
||||
|
||||
export async function disablePush(): Promise<void> {
|
||||
const sub = await currentSubscription();
|
||||
if (!sub) return;
|
||||
try {
|
||||
await api.post('/api/v1/push/unsubscribe', { endpoint: sub.endpoint });
|
||||
} catch {
|
||||
// le retrait local prime ; un échec réseau sur l'unsubscribe serveur n'est pas bloquant
|
||||
}
|
||||
await sub.unsubscribe();
|
||||
}
|
||||
@@ -3,6 +3,10 @@ import { createPinia } from 'pinia';
|
||||
import App from './App.vue';
|
||||
import { router } from './router';
|
||||
import { i18n } from './i18n';
|
||||
import { registerServiceWorker } from './lib/push';
|
||||
import './style.css';
|
||||
|
||||
createApp(App).use(createPinia()).use(router).use(i18n).mount('#app');
|
||||
|
||||
// PWA (P4-C) : enregistre le service worker des notifications push si l'environnement le permet.
|
||||
void registerServiceWorker();
|
||||
|
||||
42
packages/web/src/stores/push.ts
Normal file
42
packages/web/src/stores/push.ts
Normal file
@@ -0,0 +1,42 @@
|
||||
import { defineStore } from 'pinia';
|
||||
import { ref } from 'vue';
|
||||
import { currentSubscription, disablePush, enablePush, notificationPermission, pushSupported } from '../lib/push';
|
||||
|
||||
export const usePushStore = defineStore('push', () => {
|
||||
const supported = ref(pushSupported());
|
||||
const enabled = ref(false);
|
||||
const busy = ref(false);
|
||||
/** null | 'denied' | 'unsupported' | message d'erreur */
|
||||
const error = ref<string | null>(null);
|
||||
|
||||
async function refresh(): Promise<void> {
|
||||
supported.value = pushSupported();
|
||||
if (!supported.value) {
|
||||
enabled.value = false;
|
||||
return;
|
||||
}
|
||||
enabled.value = notificationPermission() === 'granted' && (await currentSubscription()) !== null;
|
||||
}
|
||||
|
||||
async function toggle(): Promise<void> {
|
||||
if (busy.value || !supported.value) return;
|
||||
busy.value = true;
|
||||
error.value = null;
|
||||
try {
|
||||
if (enabled.value) {
|
||||
await disablePush();
|
||||
enabled.value = false;
|
||||
} else {
|
||||
const r = await enablePush();
|
||||
enabled.value = r === 'enabled';
|
||||
if (r !== 'enabled') error.value = r;
|
||||
}
|
||||
} catch (e) {
|
||||
error.value = e instanceof Error ? e.message : String(e);
|
||||
} finally {
|
||||
busy.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
return { supported, enabled, busy, error, refresh, toggle };
|
||||
});
|
||||
@@ -7,10 +7,21 @@
|
||||
<div class="ml-auto flex items-center gap-2">
|
||||
<RouterLink :to="{ name: 'sessions' }" class="btn">{{ t('dashboard.allSessions') }}</RouterLink>
|
||||
<button class="btn" :disabled="store.loading" @click="store.fetchAll()">{{ t('sessions.refresh') }}</button>
|
||||
<button
|
||||
v-if="push.supported"
|
||||
class="btn"
|
||||
:class="push.enabled ? 'border-emerald-700 text-emerald-300' : ''"
|
||||
:disabled="push.busy"
|
||||
:title="pushErrorText"
|
||||
@click="push.toggle()"
|
||||
>
|
||||
{{ push.enabled ? t('push.disable') : t('push.enable') }}
|
||||
</button>
|
||||
<LanguageSwitcher />
|
||||
<button class="btn" @click="onLogout">{{ t('common.logout') }}</button>
|
||||
</div>
|
||||
</header>
|
||||
<p v-if="pushErrorText" class="text-xs text-amber-400">{{ pushErrorText }}</p>
|
||||
|
||||
<form class="flex flex-col gap-2 rounded-lg border border-zinc-800 bg-zinc-900/50 p-3 sm:flex-row sm:items-end" @submit.prevent="onAddRepo">
|
||||
<label class="flex flex-1 flex-col gap-1 text-xs text-zinc-400">
|
||||
@@ -33,12 +44,13 @@
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { onMounted, ref } from 'vue';
|
||||
import { computed, onMounted, ref } from 'vue';
|
||||
import { useRouter } from 'vue-router';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { useAuthStore } from '../stores/auth';
|
||||
import { useWorktreesStore } from '../stores/worktrees';
|
||||
import { useSessionsStore } from '../stores/sessions';
|
||||
import { usePushStore } from '../stores/push';
|
||||
import LanguageSwitcher from '../components/LanguageSwitcher.vue';
|
||||
import RepoSection from '../components/RepoSection.vue';
|
||||
|
||||
@@ -47,11 +59,19 @@ const router = useRouter();
|
||||
const auth = useAuthStore();
|
||||
const store = useWorktreesStore();
|
||||
const sessions = useSessionsStore();
|
||||
const push = usePushStore();
|
||||
|
||||
const newPath = ref('');
|
||||
const adding = ref(false);
|
||||
const addError = ref<string | null>(null);
|
||||
|
||||
// 'denied'/'unsupported' sont des clés i18n ; tout autre message d'erreur est affiché tel quel.
|
||||
const pushErrorText = computed(() => {
|
||||
const e = push.error;
|
||||
if (!e) return '';
|
||||
return e === 'denied' || e === 'unsupported' ? t(`push.${e}`) : e;
|
||||
});
|
||||
|
||||
onMounted(() => {
|
||||
void store.fetchAll();
|
||||
store.startRealtime();
|
||||
@@ -59,6 +79,7 @@ onMounted(() => {
|
||||
// suit leurs mises à jour temps réel pour que les badges d'état (busy/waiting/idle) restent live.
|
||||
void sessions.fetchSessions();
|
||||
sessions.startRealtime();
|
||||
void push.refresh();
|
||||
});
|
||||
|
||||
async function onAddRepo(): Promise<void> {
|
||||
|
||||
Reference in New Issue
Block a user