From 1327ed1af981f67d0069b00175d2cac875bde187 Mon Sep 17 00:00:00 2001 From: Chris Scott <99081550+chriswritescode-dev@users.noreply.github.com> Date: Wed, 2 Sep 2026 00:52:25 -0400 Subject: [PATCH] feat(notifications): target one tab on click, deep-link worktree sessions, action-first payload The service worker broadcast every notification click on a BroadcastChannel, so every open tab navigated, and it focused the first client regardless of what it showed. It now picks the tab already on the target path, then the focused tab, then any visible tab, and posts NOTIFICATION_CLICK to that client only; the page subscribes through onNotificationClick. Notifications from OpenCode workspace and forge loop worktrees fell back to / because the directory is not a repos row; the service now resolves the parent repo through the shared OpenCode project id. Assistant sessions get the assistant=1 parameter the Assistant view requires. Payload puts the action in the title and the repo in the body, carries a timestamp and renotify, uses the 512px icon and a monochrome 96px badge, and the service worker types it with the shared schema, which gains priority, timestamp, and renotify. --- backend/src/routes/internal/notifications.ts | 1 + backend/src/services/notification.ts | 82 ++++--- .../test/services/notification-format.test.ts | 54 +++-- docs/features/notifications.md | 8 +- frontend/public/icons/badge-96x96.png | Bin 0 -> 560 bytes frontend/src/App.tsx | 18 +- frontend/src/lib/serviceWorker.test.ts | 66 ++++++ frontend/src/lib/serviceWorker.ts | 13 ++ frontend/src/sw.test.ts | 212 ++++++++++++++++++ frontend/src/sw.ts | 73 +++--- shared/src/schemas/notifications.ts | 3 + 11 files changed, 438 insertions(+), 92 deletions(-) create mode 100644 frontend/public/icons/badge-96x96.png create mode 100644 frontend/src/lib/serviceWorker.test.ts create mode 100644 frontend/src/sw.test.ts diff --git a/backend/src/routes/internal/notifications.ts b/backend/src/routes/internal/notifications.ts index 991c2a8a..229df221 100644 --- a/backend/src/routes/internal/notifications.ts +++ b/backend/src/routes/internal/notifications.ts @@ -37,6 +37,7 @@ export function createInternalNotificationRoutes(notificationService: Notificati title: parsed.data.title, body: parsed.data.body, tag: parsed.data.tag ?? `assistant-${Date.now()}`, + timestamp: Date.now(), data: { eventType: 'assistant.message', url: parsed.data.url ?? '/', diff --git a/backend/src/services/notification.ts b/backend/src/services/notification.ts index 48616579..11dcf975 100644 --- a/backend/src/services/notification.ts +++ b/backend/src/services/notification.ts @@ -14,8 +14,16 @@ import { } from "@opencode-manager/shared/notifications"; import { SettingsService } from "./settings"; import { sseAggregator, type SSEEvent } from "./sse-aggregator"; -import { getRepoByLocalPath, getRepoBySourcePath, getRepoName } from "../db/queries"; +import { + getRepoByLocalPath, + getRepoBySourcePath, + getRepoName, + listRepos, +} from "../db/queries"; +import type { Repo } from "../types/repo"; import { getReposPath } from "@opencode-manager/shared/config/env"; +import { ASSISTANT_REPO_ID } from "@opencode-manager/shared/utils"; +import { resolveProjectId } from "./project-id-resolver"; import path from "path"; interface VapidConfig { @@ -62,6 +70,16 @@ const EVENT_CONFIG: Record< const MAX_BODY_LENGTH = 140; +export function buildNotificationUrl( + repo: Pick | null, + sessionId: string | undefined +): string { + if (!repo) return "/"; + if (!sessionId) return `/repos/${repo.id}`; + const suffix = repo.id === ASSISTANT_REPO_ID ? "?assistant=1" : ""; + return `/repos/${repo.id}/sessions/${sessionId}${suffix}`; +} + export function buildEventNotificationPayload( event: SSEEvent, context: { @@ -75,12 +93,12 @@ export function buildEventNotificationPayload( const config = EVENT_CONFIG[event.type]; if (!config) return null; - const action = config.titleFn(event.properties); - const title = context.repoName - ? `${context.repoName}: ${action}` - : action; + const title = config.titleFn(event.properties); - const rawBody = config.bodyFn(event.properties); + const detail = config.bodyFn(event.properties); + const rawBody = context.repoName + ? `${context.repoName} · ${detail}` + : detail; const body = rawBody.length > MAX_BODY_LENGTH ? `${rawBody.slice(0, MAX_BODY_LENGTH - 1)}…` @@ -90,6 +108,8 @@ export function buildEventNotificationPayload( title, body, tag: `${event.type}-${context.sessionId ?? "global"}`, + timestamp: Date.now(), + renotify: true, data: { eventType: event.type, sessionId: context.sessionId, @@ -244,8 +264,29 @@ export class NotificationService { return rows.map((r) => r.user_id); } + private async resolveRepoForDirectory(directory: string): Promise { + const repo = + getRepoBySourcePath(this.db, path.resolve(directory)) ?? + getRepoByLocalPath(this.db, path.relative(getReposPath(), directory)); + if (repo) return repo; + + const projectId = await resolveProjectId(directory); + if (!projectId) return null; + + const readyRepos = listRepos(this.db).filter( + (candidate) => candidate.cloneStatus === "ready" + ); + for (const candidate of readyRepos) { + const candidateProjectId = await resolveProjectId(candidate.fullPath).catch( + () => null + ); + if (candidateProjectId === projectId) return candidate; + } + return null; + } + async handleSSEEvent( - _directory: string, + directory: string, event: SSEEvent ): Promise { const config = EVENT_CONFIG[event.type]; @@ -260,30 +301,17 @@ export class NotificationService { const userIds = this.getAllUserIds(); if (userIds.length === 0) return; - let notificationUrl = "/"; - let repoName = ""; - let repoId: number | undefined; - - if (_directory) { - const reposBasePath = getReposPath(); - const localPath = path.relative(reposBasePath, _directory); - const repo = getRepoBySourcePath(this.db, path.resolve(_directory)) ?? getRepoByLocalPath(this.db, localPath); - - if (repo) { - repoId = repo.id; - repoName = getRepoName(repo); - notificationUrl = sessionId - ? `/repos/${repo.id}/sessions/${sessionId}` - : `/repos/${repo.id}`; - } - } + const repo = directory ? await this.resolveRepoForDirectory(directory) : null; + const repoId = repo?.id; + const repoName = repo ? getRepoName(repo) : undefined; + const url = buildNotificationUrl(repo, sessionId); const payload = buildEventNotificationPayload(event, { - repoName: repoName || undefined, + repoName, repoId, sessionId, - directory: _directory, - url: notificationUrl, + directory, + url, }); if (!payload) return; diff --git a/backend/test/services/notification-format.test.ts b/backend/test/services/notification-format.test.ts index 64d19fa9..8dd71516 100644 --- a/backend/test/services/notification-format.test.ts +++ b/backend/test/services/notification-format.test.ts @@ -1,6 +1,7 @@ import { describe, it, expect } from 'vitest' import { getPermissionLabel, getPermissionDetail, getQuestionText } from '@opencode-manager/shared/notifications' -import { buildEventNotificationPayload } from '../../src/services/notification' +import { buildEventNotificationPayload, buildNotificationUrl } from '../../src/services/notification' +import { ASSISTANT_REPO_ID } from '@opencode-manager/shared/utils' const ctx = { repoName: 'oc-manager', repoId: 1, sessionId: 'ses_1', directory: '/abs/repo', url: '/repos/1/sessions/ses_1' } @@ -46,15 +47,17 @@ describe('getQuestionText', () => { }) describe('buildEventNotificationPayload', () => { - it('formats a bash permission as "{repo}: Run Command" + command body', () => { + it('formats a bash permission as "Run Command" title with repo-prefixed body', () => { const p = buildEventNotificationPayload( { type: 'permission.asked', properties: { permission: 'bash', metadata: { command: 'rm -rf node_modules' }, patterns: ['rm *'] } }, ctx, )! - expect(p.title).toBe('oc-manager: Run Command') - expect(p.body).toBe('rm -rf node_modules') + expect(p.title).toBe('Run Command') + expect(p.body).toBe('oc-manager · rm -rf node_modules') expect(p.tag).toBe('permission.asked-ses_1') expect(p.data?.eventType).toBe('permission.asked') + expect(p.renotify).toBe(true) + expect(typeof p.timestamp).toBe('number') }) it('formats an edit permission with the file path', () => { @@ -62,8 +65,8 @@ describe('buildEventNotificationPayload', () => { { type: 'permission.asked', properties: { permission: 'edit', metadata: { filePath: 'src/index.ts' } } }, ctx, )! - expect(p.title).toBe('oc-manager: Edit File') - expect(p.body).toBe('src/index.ts') + expect(p.title).toBe('Edit File') + expect(p.body).toBe('oc-manager · src/index.ts') }) it('uses "Approval required" body when no detail is available', () => { @@ -71,31 +74,31 @@ describe('buildEventNotificationPayload', () => { { type: 'permission.asked', properties: { permission: 'bash' } }, ctx, )! - expect(p.body).toBe('Approval required') + expect(p.body).toBe('oc-manager · Approval required') }) - it('formats a question as "{repo}: Question" + question text body', () => { + it('formats a question as "Question" title with repo-prefixed body', () => { const p = buildEventNotificationPayload( { type: 'question.asked', properties: { questions: [{ question: 'Deploy to prod?' }] } }, ctx, )! - expect(p.title).toBe('oc-manager: Question') - expect(p.body).toBe('Deploy to prod?') + expect(p.title).toBe('Question') + expect(p.body).toBe('oc-manager · Deploy to prod?') }) - it('formats session.error as "{repo}: Error" + error message', () => { + it('formats session.error as "Error" title with repo-prefixed body', () => { const p = buildEventNotificationPayload( { type: 'session.error', properties: { error: { message: 'boom' } } }, ctx, )! - expect(p.title).toBe('oc-manager: Error') - expect(p.body).toBe('boom') + expect(p.title).toBe('Error') + expect(p.body).toBe('oc-manager · boom') }) - it('formats session.idle as "{repo}: Session complete"', () => { + it('formats session.idle as "Session complete" with repo-prefixed body', () => { const p = buildEventNotificationPayload({ type: 'session.idle', properties: {} }, ctx)! - expect(p.title).toBe('oc-manager: Session complete') - expect(p.body).toBe('Your session has finished processing') + expect(p.title).toBe('Session complete') + expect(p.body).toBe('oc-manager · Your session has finished processing') }) it('omits the repo prefix when no repoName is provided', () => { @@ -104,6 +107,7 @@ describe('buildEventNotificationPayload', () => { { url: '/' }, )! expect(p.title).toBe('Run Command') + expect(p.body).toBe('ls') expect(p.tag).toBe('permission.asked-global') }) @@ -111,13 +115,29 @@ describe('buildEventNotificationPayload', () => { expect(buildEventNotificationPayload({ type: 'session.created', properties: {} }, ctx)).toBeNull() }) - it('truncates bodies longer than 140 chars with an ellipsis', () => { + it('truncates the prefixed body to 140 chars with an ellipsis', () => { const long = 'x'.repeat(300) const p = buildEventNotificationPayload( { type: 'permission.asked', properties: { permission: 'bash', metadata: { command: long } } }, ctx, )! expect(p.body.length).toBeLessThanOrEqual(140) + expect(p.body.startsWith('oc-manager · ')).toBe(true) expect(p.body.endsWith('…')).toBe(true) }) }) + +describe('buildNotificationUrl', () => { + it('returns "/" when repo is null', () => { + expect(buildNotificationUrl(null, 'ses_1')).toBe('/') + }) + it('returns the repo page when there is no session', () => { + expect(buildNotificationUrl({ id: 5 }, undefined)).toBe('/repos/5') + }) + it('returns the session page for a normal repo', () => { + expect(buildNotificationUrl({ id: 5 }, 'ses_1')).toBe('/repos/5/sessions/ses_1') + }) + it('appends ?assistant=1 for the assistant repo session', () => { + expect(buildNotificationUrl({ id: ASSISTANT_REPO_ID }, 'ses_1')).toBe('/repos/0/sessions/ses_1?assistant=1') + }) +}) diff --git a/docs/features/notifications.md b/docs/features/notifications.md index 8b3f45cc..cb62943c 100644 --- a/docs/features/notifications.md +++ b/docs/features/notifications.md @@ -11,7 +11,7 @@ Push notifications allow you to receive alerts on your mobile device or desktop - A **session encounters an error** during execution - A **session completes successfully** -Notifications are only sent when you don't have the app open (no SSE connections), preventing duplicate alerts while you're actively monitoring a session. +A notification is suppressed when a visible tab is already viewing the session that raised it, preventing duplicate alerts while you're actively monitoring that session. Subagent sessions never notify. ## Supported Events @@ -22,6 +22,12 @@ Notifications are only sent when you don't have the app open (no SSE connections | `sessionError` | Session encounters an error | Enabled | | `sessionIdle` | Session completes successfully | Disabled | +## Content and Click Behaviour + +The title is the action (`Run Command`, `Edit File`, `Question`, `Error`, `Session complete`) and the body is ` · `, for example `oc-manager · pnpm test`. Bodies are truncated to 140 characters. Permission and question notifications stay on screen until dismissed; every notification carries the event timestamp and re-alerts when a newer event for the same session replaces it. + +Clicking a notification opens the session that raised it (`/repos//sessions/`). The service worker prefers a tab already showing that session, then the focused tab, then any visible tab, and only that one tab navigates; with no tab open a new window is opened. Sessions running in OpenCode workspace worktrees or opencode-forge loop worktrees resolve to their parent repository through the shared OpenCode project id, and Assistant sessions open with the `assistant=1` parameter the Assistant view requires. + ## Browser Compatibility Push notifications require HTTPS (except on `localhost`) and browser support: diff --git a/frontend/public/icons/badge-96x96.png b/frontend/public/icons/badge-96x96.png new file mode 100644 index 0000000000000000000000000000000000000000..8376797410ba4a57afa8d6a46559b63ee467ea14 GIT binary patch literal 560 zcmeAS@N?(olHy`uVBq!ia0vp^2_VeD1|%QND7OGo3dtTpz6=aiY77hwEes65fI|H(?D8gRi>Fdh=ij#>&pHFXp zD+f?WwZt`|BqgyV)hf9t6-Y4{85o)A8d&NY7=;*^Seckx8JcJt7+4t?^j=@2gQ6if zKP5A*61RpwT~ZT(8Z_WGlw{_n7MCRE7U0&idcL(k0|TRgr;B4q#jUq@9JyKy1Q;Br z{{27wG54O{kci!K0xfBJd?$Bavw9Tsi+SHVh6u(DObM(9xEe$mv>Cz})<6XIKm5G! zQ~LWkRx3Esr7+Z9=AOx!e7cW4TDNx=Oh1Mqk_BYncjT6~zs~hVI0}auv*S+e`TOAB h{Y)loJ^^XEdq$7#=nBbSXMo|!;OXk;vd$@?2>_VDq { - const channel = new BroadcastChannel('notification-click') - channel.onmessage = (event: MessageEvent) => { - const data = event.data as { url?: string } | null | undefined - if (typeof data?.url === 'string') { - navigate(data.url) - } - } - return () => channel.close() - }, [navigate]) + useEffect( + () => + onNotificationClick((url) => { + if (window.location.pathname + window.location.search !== url) navigate(url) + }), + [navigate] + ) return ( diff --git a/frontend/src/lib/serviceWorker.test.ts b/frontend/src/lib/serviceWorker.test.ts new file mode 100644 index 00000000..7b8bf4d1 --- /dev/null +++ b/frontend/src/lib/serviceWorker.test.ts @@ -0,0 +1,66 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' + +vi.mock('../sw?worker', () => ({})) + +import { onNotificationClick } from './serviceWorker' + +function defineServiceWorkerTarget(target: EventTarget) { + Object.defineProperty(navigator, 'serviceWorker', { + value: target, + configurable: true, + }) +} + +describe('onNotificationClick', () => { + beforeEach(() => { + if ('serviceWorker' in navigator) { + Reflect.deleteProperty(navigator, 'serviceWorker') + } + }) + + it('calls the handler for NOTIFICATION_CLICK messages', () => { + const target = new EventTarget() + defineServiceWorkerTarget(target) + const handler = vi.fn() + + const unsubscribe = onNotificationClick(handler) + target.dispatchEvent( + new MessageEvent('message', { data: { type: 'NOTIFICATION_CLICK', url: '/x' } }) + ) + + expect(handler).toHaveBeenCalledWith('/x') + unsubscribe() + }) + + it('ignores messages with other types', () => { + const target = new EventTarget() + defineServiceWorkerTarget(target) + const handler = vi.fn() + + const unsubscribe = onNotificationClick(handler) + target.dispatchEvent(new MessageEvent('message', { data: { type: 'SW_UPDATED' } })) + target.dispatchEvent(new MessageEvent('message', { data: null })) + + expect(handler).not.toHaveBeenCalled() + unsubscribe() + }) + + it('stops calling the handler after unsubscribe', () => { + const target = new EventTarget() + defineServiceWorkerTarget(target) + const handler = vi.fn() + + const unsubscribe = onNotificationClick(handler) + unsubscribe() + target.dispatchEvent( + new MessageEvent('message', { data: { type: 'NOTIFICATION_CLICK', url: '/y' } }) + ) + + expect(handler).not.toHaveBeenCalled() + }) + + it('returns a no-op unsubscribe when service workers are unsupported', () => { + const unsubscribe = onNotificationClick(vi.fn()) + expect(() => unsubscribe()).not.toThrow() + }) +}) diff --git a/frontend/src/lib/serviceWorker.ts b/frontend/src/lib/serviceWorker.ts index 690c0880..bdd7acfe 100644 --- a/frontend/src/lib/serviceWorker.ts +++ b/frontend/src/lib/serviceWorker.ts @@ -97,6 +97,19 @@ export function registerServiceWorker(): void { .catch(() => {}); } +export function onNotificationClick(handler: (url: string) => void): () => void { + if (!("serviceWorker" in navigator)) return () => {}; + + const listener = (event: MessageEvent) => { + const data = event.data as { type?: string; url?: string } | null; + if (data?.type === "NOTIFICATION_CLICK" && typeof data.url === "string") { + handler(data.url); + } + }; + navigator.serviceWorker.addEventListener("message", listener); + return () => navigator.serviceWorker.removeEventListener("message", listener); +} + export async function getServiceWorkerRegistration(): Promise { if (!("serviceWorker" in navigator)) return null; return (await navigator.serviceWorker.getRegistration("/")) ?? null; diff --git a/frontend/src/sw.test.ts b/frontend/src/sw.test.ts new file mode 100644 index 00000000..613bdd3e --- /dev/null +++ b/frontend/src/sw.test.ts @@ -0,0 +1,212 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +type Listener = (event: unknown) => void + +const listeners: Record = {} + +function makeWorkerGlobalScope() { + const scope = { + addEventListener(type: string, listener: Listener) { + listeners[type] = listeners[type] ?? [] + listeners[type].push(listener) + }, + skipWaiting: vi.fn(async () => {}), + location: { origin: 'http://localhost' }, + registration: { + showNotification: vi.fn(async () => {}), + }, + clients: { + matchAll: vi.fn(async () => []), + openWindow: vi.fn(async () => ({})), + claim: vi.fn(async () => {}), + }, + } + ;(globalThis as Record).self = scope + ;(globalThis as Record).caches = { + open: vi.fn(async () => ({ addAll: vi.fn(async () => {}), put: vi.fn(async () => {}) })), + keys: vi.fn(async () => []), + match: vi.fn(async () => undefined), + delete: vi.fn(async () => true), + } + return scope +} + +function dispatch(type: string, event: unknown) { + const typeListeners = listeners[type] ?? [] + expect(typeListeners.length).toBeGreaterThan(0) + for (const listener of typeListeners) listener(event) +} + +async function dispatchAndWait(type: string, event: unknown) { + const promises: Promise[] = [] + const enriched = { + ...event, + waitUntil: (promise: Promise) => { + promises.push(promise) + }, + } + dispatch(type, enriched) + await Promise.all(promises) +} + +function makeClient(overrides: Partial & { url: string }) { + return { + focused: false, + visibilityState: 'visible', + postMessage: vi.fn(), + focus: vi.fn(async () => overrides), + ...overrides, + } +} + +describe('service worker notifications', () => { + let scope: ReturnType + + beforeEach(async () => { + vi.resetModules() + for (const key of Object.keys(listeners)) delete listeners[key] + scope = makeWorkerGlobalScope() + await import('./sw') + }) + + afterEach(() => { + vi.restoreAllMocks() + }) + + describe('push', () => { + it('shows high-priority notification with defaults from payload', async () => { + const payload = { + title: 'Permission requested', + body: 'A session needs approval', + tag: 'repo-1-session-1', + renotify: true, + timestamp: 123, + data: { + eventType: 'permission.asked', + url: '/repos/1/sessions/s', + }, + } + + await dispatchAndWait('push', { + data: { json: () => payload, text: () => '' }, + }) + + expect(scope.registration.showNotification).toHaveBeenCalledWith( + 'Permission requested', + expect.objectContaining({ + badge: '/icons/badge-96x96.png', + icon: '/icons/icon-512x512.png', + renotify: true, + timestamp: 123, + requireInteraction: true, + tag: 'repo-1-session-1', + }) + ) + }) + + it('does not require interaction for low-priority events', async () => { + const payload = { + title: 'Session idle', + body: 'Done', + tag: 'repo-1-session-1', + data: { eventType: 'session.idle' }, + } + + await dispatchAndWait('push', { + data: { json: () => payload, text: () => '' }, + }) + + expect(scope.registration.showNotification).toHaveBeenCalledWith( + 'Session idle', + expect.objectContaining({ requireInteraction: false, renotify: false }) + ) + }) + }) + + describe('notificationclick', () => { + it('posts message to the client already on the target pathname and focuses it', async () => { + const matchClient = makeClient({ url: 'http://localhost/repos/1/sessions/s' }) + const focusedClient = makeClient({ url: 'http://localhost/repos/1', focused: true }) + scope.clients.matchAll.mockResolvedValue([focusedClient, matchClient]) + + await dispatchAndWait('notificationclick', { + notification: { + close: vi.fn(), + data: { url: '/repos/1/sessions/s' }, + }, + }) + + expect(matchClient.postMessage).toHaveBeenCalledWith({ + type: 'NOTIFICATION_CLICK', + url: '/repos/1/sessions/s', + }) + expect(matchClient.focus).toHaveBeenCalled() + expect(focusedClient.postMessage).not.toHaveBeenCalled() + expect(focusedClient.focus).not.toHaveBeenCalled() + expect(scope.clients.openWindow).not.toHaveBeenCalled() + }) + + it('posts message to the focused client when no client matches the pathname', async () => { + const focusedClient = makeClient({ url: 'http://localhost/repos/2', focused: true }) + const otherClient = makeClient({ url: 'http://localhost/repos/3' }) + scope.clients.matchAll.mockResolvedValue([otherClient, focusedClient]) + + await dispatchAndWait('notificationclick', { + notification: { + close: vi.fn(), + data: { url: '/repos/1/sessions/s' }, + }, + }) + + expect(focusedClient.postMessage).toHaveBeenCalledWith({ + type: 'NOTIFICATION_CLICK', + url: '/repos/1/sessions/s', + }) + expect(focusedClient.focus).toHaveBeenCalled() + expect(otherClient.postMessage).not.toHaveBeenCalled() + expect(scope.clients.openWindow).not.toHaveBeenCalled() + }) + + it('opens a new window when there are no clients', async () => { + scope.clients.matchAll.mockResolvedValue([]) + + await dispatchAndWait('notificationclick', { + notification: { + close: vi.fn(), + data: { url: '/repos/1/sessions/s' }, + }, + }) + + expect(scope.clients.openWindow).toHaveBeenCalledWith('/repos/1/sessions/s') + }) + + it('ignores clients from other origins', async () => { + const foreignClient = makeClient({ url: 'https://evil.example/repos/1/sessions/s' }) + foreignClient.postMessage = vi.fn() + scope.clients.matchAll.mockResolvedValue([foreignClient]) + + await dispatchAndWait('notificationclick', { + notification: { + close: vi.fn(), + data: { url: '/repos/1/sessions/s' }, + }, + }) + + expect(foreignClient.postMessage).not.toHaveBeenCalled() + expect(scope.clients.openWindow).toHaveBeenCalledWith('/repos/1/sessions/s') + }) + + it('falls back to "/" when notification data url is missing', async () => { + scope.clients.matchAll.mockResolvedValue([]) + + await dispatchAndWait('notificationclick', { + notification: { + close: vi.fn(), + data: {}, + }, + }) + + expect(scope.clients.openWindow).toHaveBeenCalledWith('/') + }) + }) +}) diff --git a/frontend/src/sw.ts b/frontend/src/sw.ts index 434e7c1d..5d30c7c3 100644 --- a/frontend/src/sw.ts +++ b/frontend/src/sw.ts @@ -1,5 +1,7 @@ /// +import type { PushNotificationPayload } from "@opencode-manager/shared/types"; + const worker = self as unknown as ServiceWorkerGlobalScope & typeof globalThis; interface SwBuildGlobals { @@ -87,29 +89,17 @@ worker.addEventListener("fetch", (event) => { event.respondWith(cacheFirstAsset(request)); }); -interface PushNotificationData { - title: string; - body: string; - icon?: string; - badge?: string; - tag?: string; - data?: { - url?: string; - eventType?: string; - sessionId?: string; - directory?: string; - repoId?: number; - repoName?: string; - priority?: 'normal' | 'high'; - }; -} +type ShowNotificationOptions = NotificationOptions & { + renotify?: boolean; + timestamp?: number; +}; worker.addEventListener("push", (event) => { if (!event.data) return; - let payload: PushNotificationData; + let payload: PushNotificationPayload; try { - payload = event.data.json() as PushNotificationData; + payload = event.data.json() as PushNotificationPayload; } catch { payload = { title: "OpenCode Manager", @@ -118,11 +108,13 @@ worker.addEventListener("push", (event) => { }; } - const options: NotificationOptions = { + const options: ShowNotificationOptions = { body: payload.body, - icon: payload.icon ?? "/icons/icon-192x192.png", - badge: payload.badge ?? "/icons/icon-192x192.png", + icon: payload.icon ?? "/icons/icon-512x512.png", + badge: payload.badge ?? "/icons/badge-96x96.png", tag: payload.tag, + renotify: Boolean(payload.tag && payload.renotify), + ...(payload.timestamp !== undefined ? { timestamp: payload.timestamp } : {}), data: payload.data, requireInteraction: isHighPriority(payload.data?.eventType, payload.data?.priority), }; @@ -133,25 +125,32 @@ worker.addEventListener("push", (event) => { worker.addEventListener("notificationclick", (event) => { event.notification.close(); - const url = (event.notification.data?.url as string) ?? "/"; + const url = typeof event.notification.data?.url === "string" ? event.notification.data.url : "/"; - event.waitUntil( - worker.clients - .matchAll({ type: "window", includeUncontrolled: true }) - .then((clientList) => { - for (const client of clientList) { - if (new URL(client.url).origin === worker.location.origin) { - const channel = new BroadcastChannel("notification-click"); - channel.postMessage({ url }); - channel.close(); - return (client as WindowClient).focus(); - } - } - return worker.clients.openWindow(url); - }) - ); + event.waitUntil(openOrFocusClient(url)); }); +async function openOrFocusClient(url: string): Promise { + const clientList = await worker.clients.matchAll({ type: "window", includeUncontrolled: true }); + const clients = clientList.filter( + (client) => new URL(client.url).origin === worker.location.origin + ) as WindowClient[]; + const targetPathname = new URL(url, worker.location.origin).pathname; + const target = + clients.find((client) => new URL(client.url).pathname === targetPathname) ?? + clients.find((client) => client.focused) ?? + clients.find((client) => client.visibilityState === "visible") ?? + clients[0]; + + if (!target) { + await worker.clients.openWindow(url); + return; + } + + target.postMessage({ type: "NOTIFICATION_CLICK", url }); + await target.focus(); +} + function isHighPriority(eventType?: string, priority?: 'normal' | 'high'): boolean { return eventType === "permission.asked" || eventType === "question.asked" || priority === 'high'; } diff --git a/shared/src/schemas/notifications.ts b/shared/src/schemas/notifications.ts index 4726533e..9b8cb974 100644 --- a/shared/src/schemas/notifications.ts +++ b/shared/src/schemas/notifications.ts @@ -58,6 +58,8 @@ export const PushNotificationPayloadSchema = z.object({ icon: z.string().optional(), badge: z.string().optional(), tag: z.string().optional(), + timestamp: z.number().optional(), + renotify: z.boolean().optional(), data: z .object({ url: z.string().optional(), @@ -66,6 +68,7 @@ export const PushNotificationPayloadSchema = z.object({ directory: z.string().optional(), repoId: z.number().optional(), repoName: z.string().optional(), + priority: z.enum(["normal", "high"]).optional(), }) .optional(), });