DeepSeek Harness Tauri 桌面版 | Only 8mb installer, zero environment setup, preset plugins, Windows / macOS / Linux.
fix: request native permission before desktop notifications (#802)
Mao Mrfb1f6a3ad8c9
diff --git a/src/layout/components/iframe-notification.test.ts b/src/layout/components/iframe-notification.test.tsnew file mode 100644index 00000000..684017fc--- /dev/null+++ b/src/layout/components/iframe-notification.test.ts@@ -0,0 +1,171 @@+import type { RefObject } from 'react'+import { createElement } from 'react'+import { renderToStaticMarkup } from 'react-dom/server'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { Iframe } from './iframe'++const mocks = vi.hoisted(() => ({+ isPermissionGranted: vi.fn<() => Promise<boolean>>(),+ requestPermission: vi.fn<() => Promise<NotificationPermission>>(),+ registerActionTypes: vi.fn(),+ sendNotification: vi.fn(),+ onMessage: undefined as ((data: Record<string, unknown>) => void) | undefined,+}))++vi.mock('@choochmeque/tauri-plugin-notifications-api', () => mocks)+vi.mock('@reause/core', () => ({ useEventListener: vi.fn() }))+vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }))+vi.mock('valtio-define', () => ({ useStore: (value: unknown) => value }))+vi.mock('@/config/client', () => ({ queryClient: {} }))+vi.mock('@/config/query-keys', () => ({ queryKeys: {} }))+vi.mock('@/store', () => ({ store: { harness: { markIframeAlive: vi.fn() }, setting: {} } }))+vi.mock('@/hooks/use-dsh-style', () => ({ useDshStyle: () => [null, vi.fn()] }))+vi.mock('@/hooks/use-iframe-message', () => ({+ useIframeMessage: (_ref: unknown, handler: typeof mocks.onMessage) => { mocks.onMessage = handler },+}))+vi.mock('@/hooks/use-iframe-post', () => ({ useIframePost: () => vi.fn() }))+vi.mock('@/hooks/use-invoke-iframe', () => ({ useInvokeIframe: vi.fn() }))+vi.mock('@/hooks/use-notification-action', () => ({ useNotificationAction: vi.fn() }))+vi.mock('@/hooks/use-notification-clicked', () => ({ useNotificationClicked: vi.fn() }))+vi.mock('@/hooks/use-sync-visibility', () => ({ useSyncVisibility: vi.fn() }))+vi.mock('@/hooks/use-zoom-factor', () => ({ useZoomFactor: vi.fn() }))+vi.mock('./loadable', () => ({ Loadable: () => null }))++function notify(tag = 'dsh-notification-session-1') {+ if (!mocks.onMessage)+ throw new Error('Iframe message handler was not registered')+ mocks.onMessage({+ type: 'dsh://native-notification',+ title: 'Permission required',+ body: 'Approve the tool',+ sessionId: 'session',+ tag,+ silent: true,+ actions: [{ action: 'approve', title: 'Approve' }],+ })+}++async function settle() {+ await new Promise<void>(resolve => setImmediate(resolve))+}++beforeEach(() => {+ vi.resetAllMocks()+ mocks.isPermissionGranted.mockResolvedValue(true)+ mocks.requestPermission.mockResolvedValue('granted')+ mocks.registerActionTypes.mockResolvedValue(undefined)+ mocks.sendNotification.mockResolvedValue(undefined)+ vi.spyOn(console, 'error').mockImplementation(() => {})+ vi.spyOn(console, 'warn').mockImplementation(() => {})+ renderToStaticMarkup(createElement(Iframe, {+ iframeRef: { current: null } as RefObject<HTMLIFrameElement | null>,+ }))+})++afterEach(() => {+ mocks.onMessage = undefined+ vi.restoreAllMocks()+})++describe('iframe native notification authorization', () => {+ it('requests native permission before registering actions or sending the first notification', async () => {+ mocks.isPermissionGranted.mockResolvedValue(false)+ let grant: (value: NotificationPermission) => void = () => {+ throw new Error('Permission request did not start')+ }+ mocks.requestPermission.mockImplementation(() => new Promise((resolve) => {+ grant = resolve+ }))++ notify()+ await settle()+ expect(mocks.isPermissionGranted).toHaveBeenCalledOnce()+ expect(mocks.requestPermission).toHaveBeenCalledOnce()+ expect(mocks.registerActionTypes).not.toHaveBeenCalled()+ expect(mocks.sendNotification).not.toHaveBeenCalled()++ grant('granted')+ await settle()+ expect(mocks.registerActionTypes).toHaveBeenCalledWith([{+ id: 'dsh-notification-approve',+ actions: [{ id: 'approve', title: 'Approve', foreground: true, input: false }],+ }])+ expect(mocks.sendNotification).toHaveBeenCalledWith({+ id: 1525991148,+ title: 'Permission required',+ body: 'Approve the tool',+ silent: true,+ actionTypeId: 'dsh-notification-approve',+ extra: { sessionId: 'session', title: 'Permission required', tag: 'dsh-notification-session-1' },+ })+ })++ it('sends an already authorized notification without requesting permission again', async () => {+ notify()+ await settle()+ expect(mocks.isPermissionGranted).toHaveBeenCalledOnce()+ expect(mocks.requestPermission).not.toHaveBeenCalled()+ expect(mocks.sendNotification).toHaveBeenCalledOnce()+ })++ it.each(['denied', 'default'] as const)('does not send notifications when permission is %s', async (permission) => {+ mocks.isPermissionGranted.mockResolvedValue(false)+ mocks.requestPermission.mockResolvedValue(permission)+ notify()+ await settle()+ expect(mocks.requestPermission).toHaveBeenCalledOnce()+ expect(mocks.registerActionTypes).not.toHaveBeenCalled()+ expect(mocks.sendNotification).not.toHaveBeenCalled()+ })++ it('shares the pending authorization request between concurrent notifications', async () => {+ mocks.isPermissionGranted.mockResolvedValue(false)+ let grant: (value: NotificationPermission) => void = () => {+ throw new Error('Permission request did not start')+ }+ mocks.requestPermission.mockImplementation(() => new Promise((resolve) => {+ grant = resolve+ }))+ notify('first')+ notify('second')+ await settle()+ expect(mocks.isPermissionGranted).toHaveBeenCalledOnce()+ expect(mocks.requestPermission).toHaveBeenCalledOnce()+ expect(mocks.sendNotification).not.toHaveBeenCalled()+ grant('granted')+ await settle()+ expect(mocks.sendNotification.mock.calls.map(([options]) => options.extra.tag)).toEqual(['first', 'second'])+ })++ it.each(['check', 'request'] as const)('logs a failed permission %s without sending and retries the next notification', async (stage) => {+ const error = new Error('Native authorization unavailable')+ if (stage === 'check') {+ mocks.isPermissionGranted.mockRejectedValueOnce(error)+ }+ else {+ mocks.isPermissionGranted.mockResolvedValueOnce(false)+ mocks.requestPermission.mockRejectedValueOnce(error)+ }+ notify()+ await settle()+ expect(mocks.sendNotification).not.toHaveBeenCalled()+ expect(console.error).toHaveBeenCalledWith('[notification] permission request failed:', error)+ notify()+ await settle()+ expect(mocks.isPermissionGranted).toHaveBeenCalledTimes(2)+ expect(mocks.sendNotification).toHaveBeenCalledOnce()+ })++ it('rechecks native permission after the user changes system notification settings', async () => {+ mocks.isPermissionGranted.mockResolvedValueOnce(false)+ mocks.requestPermission.mockResolvedValueOnce('denied')+ notify()+ await settle()+ expect(mocks.sendNotification).not.toHaveBeenCalled()+ notify()+ await settle()+ expect(mocks.isPermissionGranted).toHaveBeenCalledTimes(2)+ expect(mocks.requestPermission).toHaveBeenCalledOnce()+ expect(mocks.sendNotification).toHaveBeenCalledOnce()+ })+})diff --git a/src/layout/components/iframe.tsx b/src/layout/components/iframe.tsxindex 6749dd08..d234891c 100644--- a/src/layout/components/iframe.tsx+++ b/src/layout/components/iframe.tsx@@ -3,7 +3,9 @@ import type { CSSProperties, RefObject } from 'react'import type { NotificationActionEvent } from '@/hooks/use-notification-action'import type { NotificationClickEvent } from '@/hooks/use-notification-clicked'import {+ isPermissionGranted,registerActionTypes,+ requestPermission,sendNotification,} from '@choochmeque/tauri-plugin-notifications-api'import { CircleExclamation } from '@gravity-ui/icons'@@ -92,6 +94,23 @@ const registeredActionTypes = new Map<string, ActionTypeRegistration>()/** 注册表上限:实际只有「批准 / 拒绝」与「回复」两组,这里只是防止异常输入把表撑大。 */const ACTION_TYPE_LIMIT = 16+let notificationPermissionRequest: Promise<boolean> | undefined++function ensureNotificationPermission(): Promise<boolean> {+ notificationPermissionRequest ??= (async () => {+ try {+ if (await isPermissionGranted())+ return true+ return await requestPermission() === 'granted'+ }+ catch (error) {+ console.error('[notification] permission request failed:', error)+ return false+ }+ })().finally(() => { notificationPermissionRequest = undefined })+ return notificationPermissionRequest+}+/*** 合并同一次按钮点击的重复投递的窗口(毫秒)。*@@ -297,6 +316,8 @@ export function Iframe({ iframeRef, srcOverride = null, borderTint = null }: Ifrconst body = data.body ?? ''void (async () => {+ if (!await ensureNotificationPermission())+ return// 后端只在 `actionTypeId` 已注册时才往通知里写按钮,所以必须先注册再发送;// 每次都用插件给的本地化文案重新注册,按钮文案才能跟随界面语言。// 整组按钮一起注册(授权是「批准 / 拒绝」),带输入框的按钮把 input 系列字段一并透传,