⭐️⭐️⭐️ Open-source, self-hosted alternative to Linear and Plane. Project management and issue tracking where teams and AI agents work side by side to plan and ship products.
TypeScript agenticagileai-agentsbug-reportingbug-trackerganttissue-trackerjirajira-alternativekanbanlinearlinear-alternativeopen-sourceproduct-managementproject-managementroadmapself-hostedsprint-planningteam-collaborationtrello-alternative
feat(web): show the unread total on the app icon badge (#533)
Allie4f83bd35eb36
diff --git a/apps/web/src/components/layout/Shell.tsx b/apps/web/src/components/layout/Shell.tsxindex c740f7ba..ba387767 100644--- a/apps/web/src/components/layout/Shell.tsx+++ b/apps/web/src/components/layout/Shell.tsx@@ -13,6 +13,7 @@ import { usePermissions } from '@/hooks/usePermissions';import { useSettingsNavGroups } from '@/hooks/useSettingsNavGroups';import { useShellProject } from '@/hooks/useShellProject';import { useShellRoute } from '@/hooks/useShellRoute';+import { useAppBadge } from '@/hooks/useAppBadge';import { useProjectRouteSync } from '@/hooks/useProjectRouteSync';import { projectPath, issuePath } from '@/utils/paths';import { defaultsFromFilters, type NewIssueDefaults } from '@/utils/project';@@ -58,6 +59,7 @@ export default function Shell({errorMsg,forbidden,} = useShellProject(projectKey, route.activeViewId);+ useAppBadge(projects.map((item) => item.id));const teamId = project?.project.teamId;const issueRefs = useMemo(() => projects.filter((item) => item.teamId === teamId).map((item) => item.ref),diff --git a/apps/web/src/hooks/useAppBadge.test.tsx b/apps/web/src/hooks/useAppBadge.test.tsxnew file mode 100644index 00000000..e57f875c--- /dev/null+++ b/apps/web/src/hooks/useAppBadge.test.tsx@@ -0,0 +1,108 @@+import assert from 'node:assert/strict';+import { afterEach, beforeEach, describe, it } from 'node:test';+import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { JSDOM } from 'jsdom';+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';+import { SyncProvider } from '@/context/syncContext';+import { useAppBadge } from './useAppBadge';++const replacedGlobals = ['window', 'document', 'navigator', 'fetch', 'IS_REACT_ACT_ENVIRONMENT'];++let dom: JSDOM;+let root: Root;+let client: QueryClient;+let saved: Map<string, PropertyDescriptor | undefined>;+let unread: number;+let rev: number;+let badge: (number | 'cleared')[];+let requests: string[];++function Probe({ projectIds }: { projectIds: number[] }) {+ useAppBadge(projectIds);+ return null;+}++function setGlobal(name: string, value: unknown) {+ Object.defineProperty(globalThis, name, { configurable: true, writable: true, value });+}++function json(body: unknown): Response {+ return new Response(JSON.stringify(body), { headers: { 'content-type': 'application/json' } });+}++async function settle() {+ for (let i = 0; i < 10; i++) await act(() => new Promise((r) => setTimeout(r, 5)));+}++async function render(projectIds: number[]) {+ await act(async () =>+ root.render(+ <QueryClientProvider client={client}>+ <SyncProvider>+ <Probe projectIds={projectIds} />+ </SyncProvider>+ </QueryClientProvider>,+ ),+ );+ await settle();+}++beforeEach(() => {+ saved = new Map(replacedGlobals.map((n) => [n, Object.getOwnPropertyDescriptor(globalThis, n)]));+ dom = new JSDOM('<!doctype html><div id="root"></div>', { url: 'http://web.test/' });+ unread = 2;+ rev = 1;+ badge = [];+ requests = [];+ const nav = dom.window.navigator as Navigator & Record<string, unknown>;+ nav.setAppBadge = async (n?: number) => void badge.push(n ?? 0);+ nav.clearAppBadge = async () => void badge.push('cleared');+ setGlobal('window', dom.window);+ setGlobal('document', dom.window.document);+ setGlobal('navigator', nav);+ setGlobal('IS_REACT_ACT_ENVIRONMENT', true);+ setGlobal('fetch', async (input: string) => {+ const path = new URL(input).pathname + new URL(input).search;+ requests.push(path);+ if (path.startsWith('/sync/rev')) return json({ revs: { 'inbox:7': String(rev) } });+ if (path === '/notifications/unread') return json({ unread });+ return json({});+ });+ client = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ root = createRoot(dom.window.document.getElementById('root')!);+});++afterEach(() => {+ act(() => root.unmount());+ client.clear();+ for (const [name, descriptor] of saved) {+ if (descriptor) Object.defineProperty(globalThis, name, descriptor);+ else delete (globalThis as Record<string, unknown>)[name];+ }+});++describe('useAppBadge', () => {+ it('shows the unread total across projects on the app icon', async () => {+ await render([7, 8]);+ assert.deepEqual(badge, [2]);+ assert.ok(requests.includes('/notifications/unread'));+ assert.ok(requests.some((p) => p.startsWith('/sync/rev') && p.includes('inbox:8')));+ });++ it('clears the badge when an inbox scope moves and nothing is unread', async () => {+ await render([7]);+ unread = 0;+ rev = 2;+ await act(() => client.invalidateQueries({ queryKey: ['sync', 'rev'] }));+ await settle();+ assert.deepEqual(badge, [2, 'cleared']);+ });++ it('does nothing where the browser has no Badging API', async () => {+ delete (dom.window.navigator as unknown as Record<string, unknown>).setAppBadge;+ await render([7]);+ assert.deepEqual(badge, []);+ assert.ok(!requests.includes('/notifications/unread'));+ });+});diff --git a/apps/web/src/hooks/useAppBadge.ts b/apps/web/src/hooks/useAppBadge.tsnew file mode 100644index 00000000..e04e314a--- /dev/null+++ b/apps/web/src/hooks/useAppBadge.ts@@ -0,0 +1,40 @@+import { useEffect } from 'react';+import { useQuery } from '@tanstack/react-query';+import { useSyncSubscribe } from '@/context/syncContext';+import { getUnreadCount } from '@/lib/api/endpoints/notifications';+import { qk } from '@/services/queryKeys';+import { revScope } from '@/utils/revScopes';++// Shows the signed-in user's unread notifications, across every project, on the app+// icon through the Badging API: the Dock or taskbar badge of the installed web app, or+// of a desktop shell that forwards it. Refetched when any project's inbox scope moves.+// Where the browser has no Badging API it does nothing and fetches nothing.+export function useAppBadge(projectIds: number[]) {+ const supported = typeof navigator !== 'undefined' && 'setAppBadge' in navigator;+ const subscribe = useSyncSubscribe();+ const ids = projectIds.join(',');++ useEffect(() => {+ if (!supported || !ids) return;+ const unsubscribe = ids+ .split(',')+ .map((id) =>+ subscribe({ scope: revScope.inbox(Number(id)), targets: [qk.notificationsUnreadTotal] }),+ );+ return () => unsubscribe.forEach((off) => off());+ }, [supported, ids, subscribe]);++ const { data: unread } = useQuery({+ queryKey: qk.notificationsUnreadTotal,+ queryFn: () => getUnreadCount(),+ enabled: supported,+ select: (d) => d.unread,+ });++ useEffect(() => {+ if (!supported || unread == null) return;+ const update = unread > 0 ? navigator.setAppBadge(unread) : navigator.clearAppBadge();+ // A browser may refuse the badge (no permission, not installed); the app works on.+ update.catch(() => {});+ }, [supported, unread]);+}diff --git a/apps/web/src/lib/api/endpoints/notifications.ts b/apps/web/src/lib/api/endpoints/notifications.tsindex 8614eec3..7c4204e9 100644--- a/apps/web/src/lib/api/endpoints/notifications.ts+++ b/apps/web/src/lib/api/endpoints/notifications.ts@@ -67,9 +67,12 @@ export const listNotifications = (return request<NotificationPage>(`/notifications?${q.toString()}`);};-// Unread count for the sidebar badge, refetched when the inbox scope moves.-export const getUnreadCount = (projectId: number) =>- request<{ unread: number }>(`/notifications/unread?projectId=${projectId}`);+// Unread count for the sidebar badge, refetched when the inbox scope moves. Without a+// project it counts every project's, for the app icon badge.+export const getUnreadCount = (projectId?: number) =>+ request<{ unread: number }>(+ projectId == null ? '/notifications/unread' : `/notifications/unread?projectId=${projectId}`,+ );export const setNotificationRead = (id: number, read: boolean) =>request<void>(`/notifications/${id}/read`, { method: 'POST', body: JSON.stringify({ read }) });diff --git a/apps/web/src/services/queryKeys.ts b/apps/web/src/services/queryKeys.tsindex d76fcd85..42b6fb63 100644--- a/apps/web/src/services/queryKeys.ts+++ b/apps/web/src/services/queryKeys.ts@@ -273,6 +273,8 @@ export const qk = {notifications: (projectKey: string, filters?: unknown) =>['notifications', projectKey, filters ?? {}] as const,notificationsUnread: (projectKey: string) => ['notificationsUnread', projectKey] as const,+ // The unread count across every project (the app icon badge).+ notificationsUnreadTotal: ['notificationsUnreadTotal'] as const,// The signed-in user's WebAuthn passkeys (account security page).passkeys: ['passkeys'] as const,// The signed-in user's connected external accounts (accounts page): the linked