diff --git a/CLAUDE.md b/CLAUDE.md index dcf1480..dd39fb0 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -23,6 +23,7 @@ npm run pack # build + npm pack du tarball git-arboretum node packages/server/scripts/acceptance-p1.mjs # acceptation E2E P1 (daemon réel + client WS réel) node packages/server/scripts/acceptance-p2.mjs # acceptation E2E P2 (découverte/reprise : faux ~/.claude + faux binaire claude) node packages/server/scripts/acceptance-p3.mjs # acceptation E2E P3 (worktrees : repo git tmp + hook + corrélation session) +node packages/server/scripts/acceptance-p4.mjs # acceptation E2E P4 (push : VAPID/subscribe + commande WS answer) ``` L'acceptation exige `npm run build` au préalable (elle lance `dist/index.js`) et utilise la commande `bash` plutôt que `claude` pour ne pas consommer de quota. diff --git a/package-lock.json b/package-lock.json index 20195bb..09a1be3 100644 --- a/package-lock.json +++ b/package-lock.json @@ -880,6 +880,19 @@ "node": ">=6.0.0" } }, + "node_modules/@jridgewell/source-map": { + "version": "0.3.11", + "resolved": "https://registry.npmjs.org/@jridgewell/source-map/-/source-map-0.3.11.tgz", + "integrity": "sha512-ZMp1V8ZFcPG5dIWnQLr3NSI1MiCU7UETdS/A0G8V/XWHvJv3ZsFqutJn1Y5RPmAPX6F3BiE397OqveU/9NCuIA==", + "dev": true, + "license": "MIT", + "optional": true, + "peer": true, + "dependencies": { + "@jridgewell/gen-mapping": "^0.3.5", + "@jridgewell/trace-mapping": "^0.3.25" + } + }, "node_modules/@jridgewell/sourcemap-codec": { "version": "1.5.5", "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz", @@ -2251,6 +2264,21 @@ "integrity": "sha512-2BjRTZxTPvheOvGbBslFSYOUkr+SjPtOnrLP33f+VIWLzezQpZcqVg7ja3L4dBXmzzgwT+a029jRx5PCi3JuiA==", "license": "MIT" }, + "node_modules/acorn": { + "version": "8.17.0", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.17.0.tgz", + "integrity": "sha512-xRQbDb9BnwDafYNn6Vwl839DYVjqXYb1XVGtWAZ1kcDc6iwAL4hg3B1dZlRiuENFeO2H53gFG3in621AdERVAg==", + "dev": true, + "license": "MIT", + "optional": true, + "peer": true, + "bin": { + "acorn": "bin/acorn" + }, + "engines": { + "node": ">=0.4.0" + } + }, "node_modules/agent-base": { "version": "7.1.4", "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.4.tgz", @@ -2448,6 +2476,15 @@ "integrity": "sha512-zRpUiDwd/xk6ADqPMATG8vc9VPrkck7T07OIx0gnjmJAnHnTVXNQG3vfvWNuiZIkwu9KrKdA1iJKfsfTVxE6NA==", "license": "BSD-3-Clause" }, + "node_modules/buffer-from": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz", + "integrity": "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==", + "dev": true, + "license": "MIT", + "optional": true, + "peer": true + }, "node_modules/cac": { "version": "6.7.14", "resolved": "https://registry.npmjs.org/cac/-/cac-6.7.14.tgz", @@ -2491,6 +2528,15 @@ "integrity": "sha512-jJ0bqzaylmJtVnNgzTeSOs8DPavpbYgEr/b0YL8/2GO3xJEhInFmhKMUnEJQjZumK7KXGFhUy89PrsJWlakBVg==", "license": "ISC" }, + "node_modules/commander": { + "version": "2.20.3", + "resolved": "https://registry.npmjs.org/commander/-/commander-2.20.3.tgz", + "integrity": "sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ==", + "dev": true, + "license": "MIT", + "optional": true, + "peer": true + }, "node_modules/content-disposition": { "version": "0.5.4", "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.4.tgz", @@ -4241,6 +4287,31 @@ "node": ">=0.10.0" } }, + "node_modules/source-map-support": { + "version": "0.5.21", + "resolved": "https://registry.npmjs.org/source-map-support/-/source-map-support-0.5.21.tgz", + "integrity": "sha512-uBHU3L3czsIyYXKX88fdrGovxdSCoTGDRZ6SYXtSRxLZUzHg5P/66Ht6uoUlHu9EZod+inXhKo3qQgwXUT/y1w==", + "dev": true, + "license": "MIT", + "optional": true, + "peer": true, + "dependencies": { + "buffer-from": "^1.0.0", + "source-map": "^0.6.0" + } + }, + "node_modules/source-map-support/node_modules/source-map": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", + "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", + "dev": true, + "license": "BSD-3-Clause", + "optional": true, + "peer": true, + "engines": { + "node": ">=0.10.0" + } + }, "node_modules/speakingurl": { "version": "14.0.1", "resolved": "https://registry.npmjs.org/speakingurl/-/speakingurl-14.0.1.tgz", @@ -4380,6 +4451,27 @@ "node": ">=6" } }, + "node_modules/terser": { + "version": "5.48.0", + "resolved": "https://registry.npmjs.org/terser/-/terser-5.48.0.tgz", + "integrity": "sha512-J/9An6vs9Us6wKRriSFXBWdRZapREHqFzdNUKk0pmu804EMR6dr6winwo7e5JDxN4xahxQsuysyYFwlwj4XN/Q==", + "dev": true, + "license": "BSD-2-Clause", + "optional": true, + "peer": true, + "dependencies": { + "@jridgewell/source-map": "^0.3.3", + "acorn": "^8.15.0", + "commander": "^2.20.0", + "source-map-support": "~0.5.20" + }, + "bin": { + "terser": "bin/terser" + }, + "engines": { + "node": ">=10" + } + }, "node_modules/thread-stream": { "version": "4.2.0", "resolved": "https://registry.npmjs.org/thread-stream/-/thread-stream-4.2.0.tgz", diff --git a/packages/server/scripts/acceptance-p4.mjs b/packages/server/scripts/acceptance-p4.mjs new file mode 100644 index 0000000..d5e5e0e --- /dev/null +++ b/packages/server/scripts/acceptance-p4.mjs @@ -0,0 +1,135 @@ +#!/usr/bin/env node +// Acceptation P4 (sans navigateur, sans quota Claude) : Web Push + commande WS `answer`. +// Vrai daemon. Couvre : garde auth + Origin sur les routes push, clé VAPID exposée, subscribe +// idempotent / malformé / unsubscribe, et la commande `answer` (rejets INVALID_ANSWER / +// NOT_CONTROLLING — la validation fine `select` vit dans les tests vitest sur fixtures). +import { spawn } from 'node:child_process'; +import { mkdtempSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join, dirname } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { createRequire } from 'node:module'; + +const require = createRequire(import.meta.url); +const WebSocket = require('ws'); + +const PORT = 7544; +const ORIGIN = `http://127.0.0.1:${PORT}`; +const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); +const serverDir = join(dirname(fileURLToPath(import.meta.url)), '..'); +const results = []; +const check = (name, ok, detail = '') => { + results.push({ name, ok, detail }); + console.log(`${ok ? '✅' : '❌'} ${name}${detail ? ` — ${detail}` : ''}`); +}; + +const tmp = mkdtempSync(join(tmpdir(), 'arb-accept-p4-')); + +const srv = spawn( + 'node', + [join(serverDir, 'dist', 'index.js'), '--port', String(PORT), '--db', join(tmp, 'a.db'), '--claude-home', join(tmp, 'claude')], + { env: { ...process.env, ARBORETUM_LOG: 'warn' }, stdio: ['ignore', 'pipe', 'pipe'] }, +); +let srvOut = ''; +srv.stdout.on('data', (d) => (srvOut += d)); +srv.stderr.on('data', (d) => (srvOut += d)); + +const j = (path, method, cookie, body) => + fetch(`${ORIGIN}${path}`, { + method, + headers: { Origin: ORIGIN, ...(cookie ? { Cookie: cookie } : {}), ...(body ? { 'Content-Type': 'application/json' } : {}) }, + ...(body ? { body: JSON.stringify(body) } : {}), + }); + +function wsClient(cookie) { + const ws = new WebSocket(`ws://127.0.0.1:${PORT}/ws`, { headers: { Origin: ORIGIN, Cookie: cookie } }); + const state = { msgs: [] }; + ws.on('message', (data, isBinary) => { + if (!isBinary) state.msgs.push(JSON.parse(String(data))); + }); + const waitMsg = async (pred, timeout = 8000) => { + const t0 = Date.now(); + while (Date.now() - t0 < timeout) { + const m = state.msgs.find(pred); + if (m) return m; + await sleep(50); + } + return null; + }; + return { ws, state, waitMsg, send: (m) => ws.send(JSON.stringify(m)) }; +} + +try { + await sleep(1500); + const token = /arb_[0-9a-f]+/.exec(srvOut)?.[0]; + check('boot + token bootstrap', !!token); + + // Garde d'auth globale : route push sans cookie → 401. + const noAuth = await j('/api/v1/push/vapid-public-key', 'GET', ''); + check('GET vapid-public-key sans cookie → 401', noAuth.status === 401); + + const login = await fetch(`${ORIGIN}/api/v1/auth/login`, { + method: 'POST', + headers: { 'Content-Type': 'application/json', Origin: ORIGIN }, + body: JSON.stringify({ token }), + }); + const cookie = login.headers.get('set-cookie')?.split(';')[0] ?? ''; + check('login → cookie', login.status === 200); + + // Check Origin strict : origine non autorisée (même avec cookie) → 403. + const badOrigin = await fetch(`${ORIGIN}/api/v1/push/vapid-public-key`, { headers: { Origin: 'http://evil.example', Cookie: cookie } }); + check('Origin invalide → 403', badOrigin.status === 403); + + // Clé VAPID publique exposée (sûre). + const vapid = await j('/api/v1/push/vapid-public-key', 'GET', cookie); + const vapidBody = await vapid.json(); + check('GET vapid-public-key → 200 + clé non triviale', vapid.status === 200 && typeof vapidBody.key === 'string' && vapidBody.key.length > 20); + + // Abonnement : 201, UPSERT idempotent, rejet du malformé, désabonnement. + const sub = { endpoint: 'https://push.example/endpoint-1', keys: { p256dh: 'BPp256dhKeyDummy', auth: 'authDummy' } }; + const s1 = await j('/api/v1/push/subscribe', 'POST', cookie, sub); + check('POST subscribe → 201', s1.status === 201); + const s2 = await j('/api/v1/push/subscribe', 'POST', cookie, sub); + check('subscribe idempotent (même endpoint) → 201', s2.status === 201); + const badSub = await j('/api/v1/push/subscribe', 'POST', cookie, { endpoint: 'x' }); + check('subscribe sans keys → 400', badSub.status === 400); + const uns = await j('/api/v1/push/unsubscribe', 'POST', cookie, { endpoint: sub.endpoint }); + check('POST unsubscribe → 200', uns.status === 200); + + // Commande WS `answer` : rejets sur une session bash managée (pas d'état waiting) et en observer. + const created = await j('/api/v1/sessions', 'POST', cookie, { cwd: tmp, command: 'bash' }); + const sess = (await created.json()).session; + check('POST /sessions bash → 201', created.status === 201 && sess?.command === 'bash'); + + const c = wsClient(cookie); + await new Promise((res, rej) => (c.ws.on('open', res), c.ws.on('error', rej))); + c.send({ type: 'hello', protocol: 1 }); + await c.waitMsg((m) => m.type === 'hello_ok'); + + c.send({ type: 'attach', sessionId: sess.id, mode: 'interactive', cols: 80, rows: 24 }); + const att = await c.waitMsg((m) => m.type === 'attached'); + check('attach interactive (contrôleur)', !!att && att.controlling === true); + + c.send({ type: 'answer', channel: att.channel, action: 'deny' }); + const invalid = await c.waitMsg((m) => m.type === 'error' && m.code === 'INVALID_ANSWER'); + check('answer sur session non-waiting → INVALID_ANSWER', !!invalid); + + c.send({ type: 'attach', sessionId: sess.id, mode: 'observer', cols: 80, rows: 24 }); + const obs = await c.waitMsg((m) => m.type === 'attached' && m.mode === 'observer'); + check('attach observer (read-only)', !!obs && obs.controlling === false); + c.send({ type: 'answer', channel: obs.channel, action: 'deny' }); + const notCtrl = await c.waitMsg((m) => m.type === 'error' && m.code === 'NOT_CONTROLLING' && m.channel === obs.channel); + check('answer en observer → NOT_CONTROLLING', !!notCtrl); + + c.ws.close(); +} catch (err) { + check('exception', false, String(err)); +} finally { + srv.kill('SIGTERM'); + await sleep(1500); + check('arrêt propre du daemon (SIGTERM)', srv.exitCode === 0 || srv.signalCode === null || srv.exitCode === null); + rmSync(tmp, { recursive: true, force: true }); + const failed = results.filter((r) => !r.ok); + console.log(failed.length === 0 ? '\nACCEPTANCE P4: ALL GREEN' : `\nACCEPTANCE P4: ${failed.length} FAILURE(S)`); + process.exit(failed.length === 0 ? 0 : 1); +} diff --git a/packages/server/test/dialog-detection.test.ts b/packages/server/test/dialog-detection.test.ts index 3203822..2206b61 100644 --- a/packages/server/test/dialog-detection.test.ts +++ b/packages/server/test/dialog-detection.test.ts @@ -2,6 +2,7 @@ import { describe, expect, it } from 'vitest'; import { readFileSync } from 'node:fs'; import { dirname, join } from 'node:path'; import { fileURLToPath } from 'node:url'; +import type { DialogKind } from '@arboretum/shared'; import { ScreenReader } from '../src/core/screen-reader.js'; import { classifyDialog, parseOptions, type ClassifiedDialog } from '../src/core/dialog-classifier.js'; @@ -77,3 +78,38 @@ describe('détection sur fixtures réelles S3 (replay headless)', () => { expect(seen.some((s) => s.dialog.kind === 'trust')).toBe(true); }); }); + +// Campagne de fiabilité P4-C : chaque type de dialogue ciblé par la supervision mobile doit être +// classifié de façon fiable (cf. « reste à faire P4 » du verdict S3 : couvrir le refus Esc et le plan). +describe('campagne de fiabilité P4-C — tous les types de dialogue', () => { + const realCaptures: Array<{ fixture: string; kind: DialogKind }> = [ + { fixture: 'trust.raw.log', kind: 'trust' }, + { fixture: 'perm-write2.raw.log', kind: 'permission' }, + { fixture: 'perm-bash2.raw.log', kind: 'permission' }, + { fixture: 'ask2.raw.log', kind: 'question' }, + ]; + for (const c of realCaptures) { + it(`${c.fixture} → ${c.kind} détecté (capture réelle)`, async () => { + const seen = await replay(c.fixture); + expect(seen.some((s) => s.dialog.kind === c.kind)).toBe(true); + }); + } + + it('refus par Esc (deny-esc2) : un dialogue est bien affiché avant l’annulation', async () => { + // un dialogue détecté = l'utilisateur peut répondre « deny » (Esc) depuis le mobile sans terminal. + const seen = await replay('deny-esc2.raw.log'); + expect(seen.length).toBeGreaterThan(0); + }); + + it('plan (synthétique — pas de capture réelle) : « Would you like to proceed? »', () => { + const d = classifyDialog([ + 'Here is my implementation plan:', + ' - step one', + '❯ 1. Yes, proceed', + '2. No, keep planning', + 'Would you like to proceed?', + ]); + expect(d?.kind).toBe('plan'); + expect(d?.options.find((o) => o.n === 1)).toMatchObject({ selected: true, label: 'Yes, proceed' }); + }); +}); diff --git a/packages/web/index.html b/packages/web/index.html index b60b18f..7a5507b 100644 --- a/packages/web/index.html +++ b/packages/web/index.html @@ -4,6 +4,14 @@ + + + + + + + + Arboretum diff --git a/packages/web/public/icon.svg b/packages/web/public/icon.svg new file mode 100644 index 0000000..fa1523c --- /dev/null +++ b/packages/web/public/icon.svg @@ -0,0 +1,18 @@ + + + + + + + + + + + + + + + + + + diff --git a/packages/web/public/manifest.webmanifest b/packages/web/public/manifest.webmanifest new file mode 100644 index 0000000..a4a1a3d --- /dev/null +++ b/packages/web/public/manifest.webmanifest @@ -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" } + ] +} diff --git a/packages/web/public/sw.js b/packages/web/public/sw.js new file mode 100644 index 0000000..80f8a49 --- /dev/null +++ b/packages/web/public/sw.js @@ -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())); diff --git a/packages/web/src/i18n/en.ts b/packages/web/src/i18n/en.ts index f0955cb..8565fbc 100644 --- a/packages/web/src/i18n/en.ts +++ b/packages/web/src/i18n/en.ts @@ -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…', }, diff --git a/packages/web/src/i18n/fr.ts b/packages/web/src/i18n/fr.ts index c4ba275..1665809 100644 --- a/packages/web/src/i18n/fr.ts +++ b/packages/web/src/i18n/fr.ts @@ -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…', }, diff --git a/packages/web/src/lib/push.ts b/packages/web/src/lib/push.ts new file mode 100644 index 0000000..fcbfde7 --- /dev/null +++ b/packages/web/src/lib/push.ts @@ -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 { + 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 { + 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 { + 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 { + 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('/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 { + 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(); +} diff --git a/packages/web/src/main.ts b/packages/web/src/main.ts index 7664ab4..8840521 100644 --- a/packages/web/src/main.ts +++ b/packages/web/src/main.ts @@ -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(); diff --git a/packages/web/src/stores/push.ts b/packages/web/src/stores/push.ts new file mode 100644 index 0000000..9bcaa67 --- /dev/null +++ b/packages/web/src/stores/push.ts @@ -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(null); + + async function refresh(): Promise { + supported.value = pushSupported(); + if (!supported.value) { + enabled.value = false; + return; + } + enabled.value = notificationPermission() === 'granted' && (await currentSubscription()) !== null; + } + + async function toggle(): Promise { + 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 }; +}); diff --git a/packages/web/src/views/DashboardView.vue b/packages/web/src/views/DashboardView.vue index 657b102..2705429 100644 --- a/packages/web/src/views/DashboardView.vue +++ b/packages/web/src/views/DashboardView.vue @@ -7,10 +7,21 @@
{{ t('dashboard.allSessions') }} +
+

{{ pushErrorText }}