Skip to content

The agent that grows with you

feat(webapp): flash the tab and show browser notifications for attention events

Teknium18d8b4a65d2e
diff --git a/apps/desktop/src/app/settings/notifications-settings.tsx b/apps/desktop/src/app/settings/notifications-settings.tsx
index 7e6299c41fe..ea709b718c4 100644
--- a/apps/desktop/src/app/settings/notifications-settings.tsx
+++ b/apps/desktop/src/app/settings/notifications-settings.tsx
@@ -1,11 +1,13 @@
import { useStore } from '@nanostores/react'
-import type { ReactNode } from 'react'
+import { type ReactNode, useState } from 'react'
import { Button } from '@/components/ui/button'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { useI18n } from '@/i18n'
+import { browserNotificationPermission, requestBrowserNotificationPermission } from '@/lib/browser-notifications'
import { COMPLETION_SOUND_VARIANTS, previewCompletionSound } from '@/lib/completion-sound'
import { triggerHaptic } from '@/lib/haptics'
+import { hostHas } from '@/lib/host-capabilities'
import { Bell, Play } from '@/lib/icons'
import { cn } from '@/lib/utils'
import { $completionSoundVariantId, setCompletionSoundVariantId } from '@/store/completion-sound'
@@ -30,6 +32,34 @@ function Caption({ children, className }: { children: ReactNode; className?: str
return <p className={cn(CAPTION, className)}>{children}</p>
}
+/** Webapp only: the browser's notification permission, asked from this click
+ * and never on page load. The tab title flashes whatever the answer. */
+function BrowserPermissionRow() {
+ const { t } = useI18n()
+ const copy = t.settings.notifications.browserPermission
+ const [permission, setPermission] = useState(browserNotificationPermission)
+
+ return (
+ <ListRow
+ action={
+ permission === 'default' ? (
+ <Button
+ onClick={() => void requestBrowserNotificationPermission().then(setPermission)}
+ size="sm"
+ type="button"
+ variant="outline"
+ >
+ {copy.allow}
+ </Button>
+ ) : undefined
+ }
+ description={copy.states[permission]}
+ id={settingElementId(SETTING_IDS.notifications.browserPermission)}
+ title={copy.title}
+ />
+ )
+}
+
interface NotificationsSettingsProps {
subpage?: string
}
@@ -47,6 +77,11 @@ export function NotificationsSettings({ subpage }: NotificationsSettingsProps =
const runTest = async () => {
triggerHaptic('open')
+
+ if (hostHas('browserNotifications')) {
+ await requestBrowserNotificationPermission()
+ }
+
const ok = await sendTestNativeNotification(copy.testTitle, copy.testBody)
notify({ kind: ok ? 'info' : 'error', message: ok ? copy.testSent : copy.testUnsupported })
}
@@ -66,6 +101,8 @@ export function NotificationsSettings({ subpage }: NotificationsSettingsProps =
onChange={setNativeNotifyEnabled}
/>
+ {hostHas('browserNotifications') && <BrowserPermissionRow />}
+
{NATIVE_NOTIFICATION_KINDS.map(kind => (
<ToggleRow
checked={prefs.enabled && prefs.kinds[kind]}
diff --git a/apps/desktop/src/app/settings/settings-manifest.ts b/apps/desktop/src/app/settings/settings-manifest.ts
index a6bd6ef8496..01e136b4d0d 100644
--- a/apps/desktop/src/app/settings/settings-manifest.ts
+++ b/apps/desktop/src/app/settings/settings-manifest.ts
@@ -1,4 +1,5 @@
import type { Translations } from '@/i18n'
+import { hostHas } from '@/lib/host-capabilities'
import { NATIVE_NOTIFICATION_KINDS } from '@/store/native-notifications'
import { canUseQuickEntry } from '@/store/quick-entry'
import { TRANSLUCENCY_SUPPORTED } from '@/store/translucency'
@@ -209,6 +210,15 @@ export const SETTINGS_MANIFEST = {
} satisfies SettingDefinition
])
),
+ browserPermission: {
+ subpage: 'alerts',
+ keywords: ['notifications', 'browser', 'permission', 'allow', 'tab', 'flash'],
+ available: () => hostHas('browserNotifications'),
+ copy: t => ({
+ label: t.settings.notifications.browserPermission.title,
+ description: t.settings.notifications.browserPermission.states.default
+ })
+ },
muteSounds: {
subpage: 'sounds',
keywords: ['mute', 'silence', 'quiet', 'sound', 'chime', 'wake', 'haptics'],
diff --git a/apps/desktop/src/i18n/de_notifications.ts b/apps/desktop/src/i18n/de_notifications.ts
index eb81fa21e64..5809907bee4 100644
--- a/apps/desktop/src/i18n/de_notifications.ts
+++ b/apps/desktop/src/i18n/de_notifications.ts
@@ -35,6 +35,18 @@ export const deNotifications = {
description: 'Ein Desktop-Plugin hat eine Benachrichtigung gesendet, während Hermes im Hintergrund war.'
}
},
+ browserPermission: {
+ title: 'Browser-Benachrichtigungen',
+ allow: 'Erlauben',
+ states: {
+ default:
+ 'Hinweise dieses Browsers anzeigen, während der Tab im Hintergrund ist. Bis du es erlaubst, blinkt nur der Tab-Titel.',
+ granted: 'Erlaubt. Hinweise erscheinen, während dieser Tab im Hintergrund ist; der Tab-Titel blinkt ebenfalls.',
+ denied: 'In den Website-Einstellungen dieses Browsers blockiert. Der Tab-Titel blinkt trotzdem.',
+ insecure: 'Erfordert HTTPS, etwa über Tailscale serve. Über reines HTTP blinkt nur der Tab-Titel.',
+ unsupported: 'Dieser Browser kann keine Benachrichtigungen anzeigen. Der Tab-Titel blinkt trotzdem.'
+ }
+ },
test: 'Testbenachrichtigung senden',
testTitle: 'Hermes',
testBody: 'Benachrichtigungen funktionieren.',
diff --git a/apps/desktop/src/i18n/en_notifications.ts b/apps/desktop/src/i18n/en_notifications.ts
index 238fd912e6a..10758a35ab5 100644
--- a/apps/desktop/src/i18n/en_notifications.ts
+++ b/apps/desktop/src/i18n/en_notifications.ts
@@ -35,6 +35,18 @@ export const enNotifications = {
description: 'A desktop plugin sent a notification while Hermes was in the background.'
}
},
+ browserPermission: {
+ title: 'Browser notifications',
+ allow: 'Allow',
+ states: {
+ default:
+ 'Show alerts from this browser while the tab is in the background. Until you allow it, only the tab title flashes.',
+ granted: 'Allowed. Alerts show while this tab is in the background; the tab title flashes too.',
+ denied: "Blocked in this browser's site settings. The tab title still flashes.",
+ insecure: 'Needs HTTPS, such as Tailscale serve. Over plain HTTP the tab title still flashes.',
+ unsupported: 'This browser cannot show notifications. The tab title still flashes.'
+ }
+ },
test: 'Send test notification',
testTitle: 'Hermes',
testBody: 'Notifications are working.',
diff --git a/apps/desktop/src/i18n/es_notifications.ts b/apps/desktop/src/i18n/es_notifications.ts
index ed2a3f5338b..7eb35199b32 100644
--- a/apps/desktop/src/i18n/es_notifications.ts
+++ b/apps/desktop/src/i18n/es_notifications.ts
@@ -35,6 +35,19 @@ export const esNotifications = {
description: 'Un complemento de escritorio envió una notificación mientras Hermes estaba en segundo plano.'
}
},
+ browserPermission: {
+ title: 'Notificaciones del navegador',
+ allow: 'Permitir',
+ states: {
+ default:
+ 'Muestra avisos de este navegador mientras la pestaña está en segundo plano. Hasta que lo permitas, solo parpadea el título de la pestaña.',
+ granted:
+ 'Permitido. Los avisos aparecen mientras esta pestaña está en segundo plano; el título de la pestaña también parpadea.',
+ denied: 'Bloqueado en la configuración del sitio de este navegador. El título de la pestaña sigue parpadeando.',
+ insecure: 'Requiere HTTPS, como Tailscale serve. Con HTTP simple solo parpadea el título de la pestaña.',
+ unsupported: 'Este navegador no puede mostrar notificaciones. El título de la pestaña sigue parpadeando.'
+ }
+ },
test: 'Enviar notificación de prueba',
testTitle: 'Hermes',
testBody: 'Las notificaciones funcionan.',
diff --git a/apps/desktop/src/i18n/fr_notifications.ts b/apps/desktop/src/i18n/fr_notifications.ts
index ff0358c1307..2116e919748 100644
--- a/apps/desktop/src/i18n/fr_notifications.ts
+++ b/apps/desktop/src/i18n/fr_notifications.ts
@@ -35,6 +35,19 @@ export const frNotifications = {
description: 'Un plugin desktop a envoyé une notification pendant que Hermes était en arrière-plan.'
}
},
+ browserPermission: {
+ title: 'Notifications du navigateur',
+ allow: 'Autoriser',
+ states: {
+ default:
+ "Affiche des alertes de ce navigateur quand l'onglet est en arrière-plan. Tant que vous ne l'autorisez pas, seul le titre de l'onglet clignote.",
+ granted:
+ "Autorisé. Les alertes s'affichent quand cet onglet est en arrière-plan ; le titre de l'onglet clignote aussi.",
+ denied: "Bloqué dans les paramètres du site de ce navigateur. Le titre de l'onglet clignote quand même.",
+ insecure: "Nécessite HTTPS, par exemple Tailscale serve. En HTTP simple, seul le titre de l'onglet clignote.",
+ unsupported: "Ce navigateur ne peut pas afficher de notifications. Le titre de l'onglet clignote quand même."
+ }
+ },
test: 'Envoyer une notification de test',
testTitle: 'Hermes',
testBody: 'Les notifications fonctionnent.',
diff --git a/apps/desktop/src/i18n/ja_notifications.ts b/apps/desktop/src/i18n/ja_notifications.ts
index 42fec004949..d48b2feee01 100644
--- a/apps/desktop/src/i18n/ja_notifications.ts
+++ b/apps/desktop/src/i18n/ja_notifications.ts
@@ -35,6 +35,18 @@ export const jaNotifications = {
description: 'Hermes がバックグラウンドの間に、デスクトッププラグインが通知を送信しました。'
}
},
+ browserPermission: {
+ title: 'ブラウザー通知',
+ allow: '許可',
+ states: {
+ default:
+ 'タブがバックグラウンドにある間、このブラウザーで通知を表示します。許可するまではタブのタイトルだけが点滅します。',
+ granted: '許可済み。このタブがバックグラウンドにある間に通知が表示され、タブのタイトルも点滅します。',
+ denied: 'このブラウザーのサイト設定でブロックされています。タブのタイトルは引き続き点滅します。',
+ insecure: 'HTTPS(Tailscale serve など)が必要です。通常の HTTP ではタブのタイトルだけが点滅します。',
+ unsupported: 'このブラウザーは通知を表示できません。タブのタイトルは引き続き点滅します。'
+ }
+ },
test: 'テスト通知を送信',
testTitle: 'Hermes',
testBody: '通知は正常に動作しています。',
diff --git a/apps/desktop/src/i18n/ru_notifications.ts b/apps/desktop/src/i18n/ru_notifications.ts
index 054cfdd0698..f5c5caa3bfb 100644
--- a/apps/desktop/src/i18n/ru_notifications.ts
+++ b/apps/desktop/src/i18n/ru_notifications.ts
@@ -35,6 +35,18 @@ export const ruNotifications = {
description: 'Плагин приложения отправил уведомление, пока Hermes был в фоне.'
}
},
+ browserPermission: {
+ title: 'Уведомления браузера',
+ allow: 'Разрешить',
+ states: {
+ default:
+ 'Показывать оповещения браузера, пока вкладка в фоне. Пока вы не разрешите, мигает только заголовок вкладки.',
+ granted: 'Разрешено. Оповещения появляются, пока эта вкладка в фоне; заголовок вкладки тоже мигает.',
+ denied: 'Заблокировано в настройках сайта в этом браузере. Заголовок вкладки всё равно мигает.',
+ insecure: 'Нужен HTTPS, например Tailscale serve. По обычному HTTP мигает только заголовок вкладки.',
+ unsupported: 'Этот браузер не умеет показывать уведомления. Заголовок вкладки всё равно мигает.'
+ }
+ },
test: 'Отправить тестовое уведомление',
testTitle: 'Hermes',
testBody: 'Уведомления работают.',
diff --git a/apps/desktop/src/i18n/types_notifications.ts b/apps/desktop/src/i18n/types_notifications.ts
index 5b268d4d776..726afdecedb 100644
--- a/apps/desktop/src/i18n/types_notifications.ts
+++ b/apps/desktop/src/i18n/types_notifications.ts
@@ -9,6 +9,11 @@ export interface NotificationSettingsTranslations {
'approval' | 'backgroundDone' | 'credits' | 'input' | 'plugin' | 'turnDone' | 'turnError',
{ label: string; description: string }
>
+ browserPermission: {
+ title: string
+ allow: string
+ states: Record<'default' | 'denied' | 'granted' | 'insecure' | 'unsupported', string>
+ }
test: string
testTitle: string
testBody: string
diff --git a/apps/desktop/src/i18n/zh_notifications.ts b/apps/desktop/src/i18n/zh_notifications.ts
index 314383a9766..14db9c96f13 100644
--- a/apps/desktop/src/i18n/zh_notifications.ts
+++ b/apps/desktop/src/i18n/zh_notifications.ts
@@ -35,6 +35,17 @@ export const zhNotifications = {
description: 'Hermes 在后台时,桌面插件发送了通知。'
}
},
+ browserPermission: {
+ title: '浏览器通知',
+ allow: '允许',
+ states: {
+ default: '标签页在后台时由此浏览器显示提醒。在你允许之前,只有标签页标题会闪烁。',
+ granted: '已允许。此标签页在后台时会显示提醒,标签页标题也会闪烁。',
+ denied: '已在此浏览器的网站设置中被阻止。标签页标题仍会闪烁。',
+ insecure: '需要 HTTPS,例如 Tailscale serve。使用普通 HTTP 时只有标签页标题会闪烁。',
+ unsupported: '此浏览器无法显示通知。标签页标题仍会闪烁。'
+ }
+ },
test: '发送测试通知',
testTitle: 'Hermes',
testBody: '通知工作正常。',
diff --git a/apps/desktop/src/lib/browser-desktop-bridge.ts b/apps/desktop/src/lib/browser-desktop-bridge.ts
index 0e94550a1ee..84fd73319d4 100644
--- a/apps/desktop/src/lib/browser-desktop-bridge.ts
+++ b/apps/desktop/src/lib/browser-desktop-bridge.ts
@@ -7,6 +7,7 @@ import { createBrowserConnectionBridge } from '@/lib/browser-connection'
import { createBrowserDesktopPluginsBridge } from '@/lib/browser-desktop-plugins'
import { createBrowserFilesBridge } from '@/lib/browser-files'
import { WEBAPP_LAUNCH_REQUIRED } from '@/lib/browser-launch-session'
+import { onBrowserFocusSession, showBrowserNotification } from '@/lib/browser-notifications'
import { createBrowserProfileBridge } from '@/lib/browser-profile'
import { createBrowserSettings } from '@/lib/browser-settings'
import { createBrowserTerminal } from '@/lib/browser-terminal'
@@ -33,14 +34,20 @@ import { tagRegistrySessionResponse } from '../../electron/profile-session-routi
* only safe browser equivalents for machine-level capabilities.
*/
export function installBrowserDesktopBridge(): boolean {
- if (window.hermesDesktop) {return false}
+ if (window.hermesDesktop) {
+ return false
+ }
const bootstrap = browserBootstrap()
- if (!bootstrap) {return false}
+ if (!bootstrap) {
+ return false
+ }
// A gated host's opener waits for this window to say it booted (createBrowserWindowOpener).
- if (!bootstrap.privateSession) {announceWebappWindow()}
+ if (!bootstrap.privateSession) {
+ announceWebappWindow()
+ }
const api = <T>(request: HermesApiRequest) => browserApi<T>(bootstrap, request)
@@ -83,7 +90,9 @@ export function installBrowserDesktopBridge(): boolean {
const openExternal = async (url: string) => {
const target = externalUrlTarget(url)
- if (target?.kind === 'web') {window.open(target.url, '_blank', 'noopener,noreferrer')}
+ if (target?.kind === 'web') {
+ window.open(target.url, '_blank', 'noopener,noreferrer')
+ }
}
const uploads = createBrowserUploadsBridge({ api, bootstrap, currentProfile, objectUrls, previewUrls })
@@ -111,16 +120,8 @@ export function installBrowserDesktopBridge(): boolean {
return { count: query && find?.call(window, query) ? 1 : 0 }
},
- notify: async ({ title, body }: { title?: string; body?: string }) => {
- if (!('Notification' in window)) {return false}
-
- if (Notification.permission === 'default') {await Notification.requestPermission()}
-
- if (Notification.permission !== 'granted') {return false}
- new Notification(title || 'Hermes', { body })
-
- return true
- },
+ notify: async payload => showBrowserNotification(payload),
+ onFocusSession: onBrowserFocusSession,
openExternal,
openPreviewInBrowser: async url => {
// Only this install's sandbox wrappers may open as same-origin blobs.
@@ -137,7 +138,10 @@ export function installBrowserDesktopBridge(): boolean {
},
settings: createBrowserSettings({ basePath: bootstrap.basePath, currentProfile }),
requestMicrophoneAccess: async () => {
- if (!navigator.mediaDevices?.getUserMedia) {return false}
+ if (!navigator.mediaDevices?.getUserMedia) {
+ return false
+ }
+
const stream = await navigator.mediaDevices.getUserMedia({ audio: true })
stream.getTracks().forEach(track => track.stop())
@@ -151,7 +155,9 @@ export function installBrowserDesktopBridge(): boolean {
// The chat's sign-in view for a launch-link tab. Behind the sign-in gate the next ticket
// request already takes the tab to the login page.
onSignedOut: () => {
- if (!bootstrap.authRequired) {failDesktopBoot(WEBAPP_LAUNCH_REQUIRED)}
+ if (!bootstrap.authRequired) {
+ failDesktopBoot(WEBAPP_LAUNCH_REQUIRED)
+ }
}
}),
...createBrowserProfileBridge({ basePath: bootstrap.basePath, currentProfile, openWindow }),
diff --git a/apps/desktop/src/lib/browser-notifications.ts b/apps/desktop/src/lib/browser-notifications.ts
new file mode 100644
index 00000000000..93923697121
--- /dev/null
+++ b/apps/desktop/src/lib/browser-notifications.ts
@@ -0,0 +1,86 @@
+/**
+ * The Webapp's half of `hermesDesktop.notify`: what Electron's notification IPC
+ * does in main, done with the browser's Notification API.
+ *
+ * Permission is asked only from a click in Settings (browsers ignore or
+ * penalise prompts that no gesture started), so an event arriving before the
+ * user opted in shows nothing here and the tab-title flash carries it alone.
+ * The API needs a secure context: Tailscale serve (https) and localhost have
+ * it, a plain-http LAN address does not.
+ */
+
+import { flagTabAttention } from '@/store/browser-tab-attention'
+
+export type BrowserNotificationPermission = 'default' | 'denied' | 'granted' | 'insecure' | 'unsupported'
+
+export function browserNotificationPermission(): BrowserNotificationPermission {
+ if (typeof window === 'undefined') {
+ return 'unsupported'
+ }
+
+ if (!window.isSecureContext) {
+ return 'insecure'
+ }
+
+ return 'Notification' in window ? Notification.permission : 'unsupported'
+}
+
+/** Call from a click handler only. */
+export async function requestBrowserNotificationPermission(): Promise<BrowserNotificationPermission> {
+ if (browserNotificationPermission() === 'default') {
+ await Notification.requestPermission()
+ }
+
+ return browserNotificationPermission()
+}
+
+type FocusSessionListener = (sessionId: string) => void
+
+const focusSessionListeners = new Set<FocusSessionListener>()
+
+/** Same contract as Electron's `onFocusSession`: a notification click names the session to open. */
+export function onBrowserFocusSession(callback: FocusSessionListener): () => void {
+ focusSessionListeners.add(callback)
+
+ return () => focusSessionListeners.delete(callback)
+}
+
+export interface BrowserNotifyPayload {
+ body?: string
+ focusSessionId?: string
+ kind?: string
+ sessionId?: string
+ tag?: string
+ title?: string
+}
+
+/** Flash the tab, then show a browser notification when the user allowed it. */
+export function showBrowserNotification(payload: BrowserNotifyPayload): boolean {
+ const title = payload.title || 'Hermes'
+
+ flagTabAttention(title)
+
+ if (browserNotificationPermission() !== 'granted') {
+ return false
+ }
+
+ const focusSessionId = payload.focusSessionId || payload.sessionId
+
+ const notification = new Notification(title, {
+ body: payload.body,
+ // One OS entry per session+kind: a replayed event replaces, never stacks.
+ tag: `hermes:${payload.kind ?? ''}:${focusSessionId ?? payload.tag ?? ''}`
+ })
+
+ notification.onclick = () => {
+ // A click on our own notification is the user's request to come back.
+ window.focus()
+ notification.close()
+
+ if (focusSessionId) {
+ focusSessionListeners.forEach(listener => listener(focusSessionId))
+ }
+ }
+
+ return true
+}
diff --git a/apps/desktop/src/lib/host-capabilities.ts b/apps/desktop/src/lib/host-capabilities.ts
index df5eb12b516..bfcf2ff620e 100644
--- a/apps/desktop/src/lib/host-capabilities.ts
+++ b/apps/desktop/src/lib/host-capabilities.ts
@@ -17,6 +17,8 @@ import { isBrowserHostedDesktop } from '@/lib/platform'
type Host = 'browser' | 'native'
export const HOST_CAPABILITIES = Object.freeze({
+ /** OS notifications go through the browser's Notification API and its per-site permission. */
+ browserNotifications: 'browser',
/** Mouse back/forward buttons are the app's to handle; a browser tab keeps its own history. */
appMouseHistoryButtons: 'native',
/** The browser opens its own context menu, which the app menu must cancel or let through. */
diff --git a/apps/desktop/src/store/browser-tab-attention.ts b/apps/desktop/src/store/browser-tab-attention.ts
new file mode 100644
index 00000000000..654b60fecaa
--- /dev/null
+++ b/apps/desktop/src/store/browser-tab-attention.ts
@@ -0,0 +1,126 @@
+/**
+ * Tab attention for the Webapp: while the tab is in the background and an
+ * event that would raise an OS notification arrives, the tab title alternates
+ * between that notification's title and the normal one, and the favicon wears
+ * a dot, until the user comes back to the tab. The browser counterpart of
+ * Electron's `flashFrame`; it never focuses or navigates on its own.
+ */
+
+import { atom } from 'nanostores'
+
+import { hostHas } from '@/lib/host-capabilities'
+
+const FLASH_INTERVAL_MS = 1000
+const BADGE_COLOR = '#f59e0b'
+
+/** The text shown in place of the normal title right now; null shows the normal title. */
+export const $tabFlashText = atom<null | string>(null)
+
+let label: null | string = null
+let timer: null | ReturnType<typeof setInterval> = null
+const originalIconHrefs = new Map<HTMLLinkElement, string>()
+
+function userIsAway(): boolean {
+ return document.hidden || (typeof document.hasFocus === 'function' && !document.hasFocus())
+}
+
+function iconLinks(): HTMLLinkElement[] {
+ return Array.from(document.querySelectorAll<HTMLLinkElement>('link[rel~="icon"]'))
+}
+
+function badgeFavicon(): void {
+ const links = iconLinks()
+ const source = links[0]?.href
+
+ if (!source || originalIconHrefs.size) {
+ return
+ }
+
+ links.forEach(link => originalIconHrefs.set(link, link.href))
+
+ const image = new Image()
+
+ image.onload = () => {
+ // The flash may have ended while the icon loaded.
+ if (!originalIconHrefs.size) {
+ return
+ }
+
+ const size = 64
+ const canvas = document.createElement('canvas')
+
+ canvas.width = size
+ canvas.height = size
+ const context = canvas.getContext('2d')
+
+ if (!context) {
+ return
+ }
+
+ context.drawImage(image, 0, 0, size, size)
+ context.beginPath()
+ context.arc(size * 0.75, size * 0.25, size * 0.22, 0, Math.PI * 2)
+ context.fillStyle = BADGE_COLOR
+ context.fill()
+ context.lineWidth = size * 0.06
+ context.strokeStyle = '#ffffff'
+ context.stroke()
+ const badged = canvas.toDataURL('image/png')
+
+ originalIconHrefs.forEach((_, link) => (link.href = badged))
+ }
+
+ image.src = source
+}
+
+function restoreFavicon(): void {
+ originalIconHrefs.forEach((href, link) => (link.href = href))
+ originalIconHrefs.clear()
+}
+
+function stop(): void {
+ if (timer) {
+ clearInterval(timer)
+ }
+
+ timer = null
+ label = null
+ $tabFlashText.set(null)
+ restoreFavicon()
+ window.removeEventListener('focus', onReturn)
+ document.removeEventListener('visibilitychange', onReturn)
+}
+
+function onReturn(): void {
+ if (!userIsAway()) {
+ stop()
+ }
+}
+
+/** Start (or retarget) the flash for a notification titled `text`. A no-op
+ * while the user is looking at the tab, and outside a browser host. */
+export function flagTabAttention(text: string): void {
+ if (typeof document === 'undefined' || !hostHas('tabTitleStatus') || !userIsAway()) {
+ return
+ }
+
+ label = text
+ $tabFlashText.set(text)
+ badgeFavicon()
+
+ if (timer) {
+ return
+ }
+
+ window.addEventListener('focus', onReturn)
+ document.addEventListener('visibilitychange', onReturn)
+ timer = setInterval(() => {
+ if (!userIsAway()) {
+ stop()
+
+ return
+ }
+
+ $tabFlashText.set($tabFlashText.get() === null ? label : null)
+ }, FLASH_INTERVAL_MS)
+}
diff --git a/apps/desktop/src/store/browser-tab-title.ts b/apps/desktop/src/store/browser-tab-title.ts
index 8feb5d9604c..03f44ced80b 100644
--- a/apps/desktop/src/store/browser-tab-title.ts
+++ b/apps/desktop/src/store/browser-tab-title.ts
@@ -21,6 +21,7 @@ import { computed } from 'nanostores'
import { $workspaceOwnerLabels, workspaceOwnerTitle } from '@/components/pane-shell/workspace-scope'
import { hostHas } from '@/lib/host-capabilities'
+import { $tabFlashText } from './browser-tab-attention'
import { normalizeProfileKey } from './profile'
import { $sessions, sessionMatchesStoredId } from './session'
import { $unreadSessionCount } from './session-dot-state'
@@ -87,7 +88,10 @@ export function installBrowserTabTitle(): () => void {
return () => {}
}
- return $browserTabTitle.subscribe(title => {
+ // A background attention flash alternates its text with the status title.
+ const $shown = computed([$browserTabTitle, $tabFlashText], (status, flash) => flash ?? status)
+
+ return $shown.subscribe(title => {
if (document.title !== title) {
document.title = title
}
diff --git a/locales/_keys.desktop.json b/locales/_keys.desktop.json
index e4a257a2003..38dc4b7b473 100644
--- a/locales/_keys.desktop.json
+++ b/locales/_keys.desktop.json
@@ -3986,6 +3986,13 @@
"settings.nav.providers",
"settings.nav.sessions",
"settings.nav.vault",
+ "settings.notifications.browserPermission.allow",
+ "settings.notifications.browserPermission.states.default",
+ "settings.notifications.browserPermission.states.denied",
+ "settings.notifications.browserPermission.states.granted",
+ "settings.notifications.browserPermission.states.insecure",
+ "settings.notifications.browserPermission.states.unsupported",
+ "settings.notifications.browserPermission.title",
"settings.notifications.completionSoundDesc",
"settings.notifications.completionSoundPreview",
"settings.notifications.completionSoundTitle",