DeepSeek Harness Tauri 桌面版 | Only 8mb installer, zero environment setup, preset plugins, Windows / macOS / Linux.
feat(notification): 新增原生通知插件与通知按钮通路 (#784)
Mao Mr632e6bff8b6b
diff --git a/.github/workflows/build-bundle-macos.yml b/.github/workflows/build-bundle-macos.ymlindex 3a676459..af5ab5a1 100644--- a/.github/workflows/build-bundle-macos.yml+++ b/.github/workflows/build-bundle-macos.yml@@ -68,6 +68,14 @@ jobs:ref: ${{ inputs.source_ref }}persist-credentials: false+ # tauri-plugin-notifications 的 macOS 后端需要 Swift 6(typed throws),切到 Xcode 16。+ - name: Select Xcode 16+ if: steps.check.outputs.should_run == 'true'+ run: |+ XCODE_APP="$(ls -d /Applications/Xcode_16*.app | sort -V | tail -1)"+ sudo xcode-select -s "$XCODE_APP"+ swift --version+- name: Setup Node.js and pnpmif: steps.check.outputs.should_run == 'true'uses: ./.github/actions/setup-node-pnpmdiff --git a/.github/workflows/build-macos.yml b/.github/workflows/build-macos.ymlindex ee73dc01..d79f7855 100644--- a/.github/workflows/build-macos.yml+++ b/.github/workflows/build-macos.yml@@ -63,6 +63,19 @@ jobs:ref: ${{ inputs.source_ref }}persist-credentials: false+ # tauri-plugin-notifications 的 macOS 后端需要 Swift 6(typed throws),切到 Xcode 16。+ # 镜像里没有 Xcode 16 时不能让整个 job 挂掉:`xcode-select -s ""` 会直接失败。+ - name: Select Xcode 16+ if: steps.check.outputs.should_run == 'true'+ run: |+ XCODE_APP="$(ls -d /Applications/Xcode_16*.app 2>/dev/null | sort -V | tail -1)"+ if [ -n "$XCODE_APP" ]; then+ sudo xcode-select -s "$XCODE_APP"+ else+ echo "::warning::镜像里没有 Xcode 16,沿用默认 Xcode;Swift 6 构建可能失败"+ fi+ swift --version+- name: Setup Node.js and pnpmif: steps.check.outputs.should_run == 'true'uses: ./.github/actions/setup-node-pnpmdiff --git a/.github/workflows/build-test.yml b/.github/workflows/build-test.ymlindex c3679424..cf732531 100644--- a/.github/workflows/build-test.yml+++ b/.github/workflows/build-test.yml@@ -47,6 +47,18 @@ jobs:with:persist-credentials: false+ # tauri-plugin-notifications 的 macOS 后端需要 Swift 6(typed throws),切到 Xcode 16。+ # 镜像里没有 Xcode 16 时不能让整个 job 挂掉:`xcode-select -s ""` 会直接失败。+ - name: Select Xcode 16+ run: |+ XCODE_APP="$(ls -d /Applications/Xcode_16*.app 2>/dev/null | sort -V | tail -1)"+ if [ -n "$XCODE_APP" ]; then+ sudo xcode-select -s "$XCODE_APP"+ else+ echo "::warning::镜像里没有 Xcode 16,沿用默认 Xcode;Swift 6 构建可能失败"+ fi+ swift --version+- name: Setup Node.js and pnpmuses: ./.github/actions/setup-node-pnpmdiff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 88748467..6ddf8bff 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -233,6 +233,26 @@ jobs:with:toolchain: stable+ # tauri-plugin-notifications 的 macOS 后端用 Swift 6 的 typed throws+ # (`throws(FFIResult)`),macos-14 镜像默认的 Xcode 15 / Swift 5.10 解析不了,+ # 构建前必须切到镜像里自带的 Xcode 16;镜像里没有 Xcode 16 时只告警,不让 job 直接挂掉+ # (`xcode-select -s ""` 会失败)。+ - name: Select Xcode 16+ if: runner.os == 'macOS'+ run: |+ XCODE_APP="$(ls -d /Applications/Xcode_16*.app 2>/dev/null | sort -V | tail -1)"+ if [ -z "$XCODE_APP" ]; then+ echo "::warning::镜像里没有 Xcode 16,沿用默认 Xcode;Swift 6 构建可能失败"+ swift --version+ exit 0+ fi+ sudo xcode-select -s "$XCODE_APP"+ swift --version+ # 该插件的 macOS 后端经 swift-build 产出 dylib,测试二进制运行时按 @rpath 找 Swift 并发+ # 运行库;dyld 默认只搜 target/、$HOME/lib、/usr/local/lib、/usr/lib,工具链里的+ # libswift_Concurrency.dylib 不在其中,实测报 `Library not loaded: @rpath/libswift_Concurrency.dylib`。+ echo "DYLD_FALLBACK_LIBRARY_PATH=$XCODE_APP/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx:/usr/lib/swift" >> "$GITHUB_ENV"+- name: Cache Rust builduses: Swatinem/rust-cache@v2with:diff --git a/.gitmodules b/.gitmodulesindex 1ac78993..7eca0460 100644--- a/.gitmodules+++ b/.gitmodules@@ -25,3 +25,15 @@[submodule "source/zcode"]path = source/zcodeurl = https://github.com/zai-org/ZCode.git+[submodule "source/dsh-session-notification"]+ path = source/dsh-session-notification+ url = https://github.com/dingyi222666/dsh-session-notification+[submodule "source/dsh-notifications"]+ path = source/dsh-notifications+ url = https://github.com/AlonDan/dsh-notifications+[submodule "source/dsh-notification"]+ path = source/dsh-notification+ url = https://github.com/omdsh-dev/dsh-notification+[submodule "source/tauri-plugin-notifications"]+ path = source/tauri-plugin-notifications+ url = https://github.com/Choochmeque/tauri-plugin-notificationsdiff --git a/genapi.config.ts b/genapi.config.tsindex 8bcb6b8e..cabba2aa 100644--- a/genapi.config.ts+++ b/genapi.config.ts@@ -14,6 +14,7 @@ const plugins = ['dsh-tauri-experimental','dsh-tauri-model','dsh-tauri-ui',+ 'dsh-tauri-notification','dsh-tauri-worktree',]diff --git a/package.json b/package.jsonindex 4c883df5..4dcd7b6d 100644--- a/package.json+++ b/package.json@@ -29,6 +29,7 @@"icons": "tauri icon public/favicon.svg && tsx scripts/rebuild-macos-icon.ts"},"dependencies": {+ "@choochmeque/tauri-plugin-notifications-api": "catalog:","@genapi/pipeline": "catalog:","@gravity-ui/icons": "catalog:runtime","@hairy/utils": "catalog:utils",diff --git a/packages/dsh-tauri-bundle/package.json b/packages/dsh-tauri-bundle/package.jsonindex c871da31..634da486 100644--- a/packages/dsh-tauri-bundle/package.json+++ b/packages/dsh-tauri-bundle/package.json@@ -7,6 +7,7 @@"dsh-tauri-archive": "workspace:*","dsh-tauri-extension": "workspace:*","dsh-tauri-model": "workspace:*",+ "dsh-tauri-notification": "workspace:*","dsh-tauri-pet": "workspace:*","dsh-tauri-rightclick": "workspace:*","dsh-tauri-scheduler": "workspace:*",diff --git a/packages/dsh-tauri-notification/cordis.patch.yml b/packages/dsh-tauri-notification/cordis.patch.ymlnew file mode 100644index 00000000..163e2562--- /dev/null+++ b/packages/dsh-tauri-notification/cordis.patch.yml@@ -0,0 +1,3 @@+- insert:+ - id: dsh-tauri-notification+ name: dsh-tauri-notificationdiff --git a/packages/dsh-tauri-notification/package.json b/packages/dsh-tauri-notification/package.jsonnew file mode 100644index 00000000..123d558f--- /dev/null+++ b/packages/dsh-tauri-notification/package.json@@ -0,0 +1,70 @@+{+ "name": "dsh-tauri-notification",+ "type": "module",+ "version": "1.0.0",+ "author": "Hairyf <[email protected]>",+ "license": "MIT",+ "homepage": "https://github.com/dsh-tauri-desk/dsh-tauri-plugins#readme",+ "repository": {+ "type": "git",+ "url": "git+https://github.com/dsh-tauri-desk/dsh-tauri-plugins.git"+ },+ "bugs": "https://github.com/dsh-tauri-desk/dsh-tauri-plugins/issues",+ "keywords": [+ "dsh",+ "plugin",+ "dsh-plugin",+ "notification",+ "tauri",+ "deepseek-harness"+ ],+ "sideEffects": false,+ "exports": {+ ".": "./dist/index.js",+ "./client": "./dist/client.cjs",+ "./package.json": "./package.json"+ },+ "main": "./dist/index.js",+ "module": "./dist/index.js",+ "types": "./dist/index.d.ts",+ "files": [+ "cordis.patch.yml",+ "dist"+ ],+ "dsh": {+ "client": {+ "inject": [+ "@deepseek-ai/dsh-client-ui-layout",+ "@deepseek-ai/dsh-client-locale",+ "@deepseek-ai/dsh-client-ui-settings",+ "dsh-tauri",+ "dsh-tauri-ui"+ ],+ "external": [+ "dsh-tauri/client",+ "dsh-tauri-ui/client"+ ],+ "platform": "web"+ },+ "bundle": {+ "patch": "./cordis.patch.yml"+ }+ },+ "scripts": {+ "build": "tsdown",+ "dev": "tsdown --watch",+ "prepublishOnly": "nr build",+ "start": "tsx src/index.ts",+ "test": "vitest run",+ "typecheck": "tsc"+ },+ "dependencies": {+ "dsh-tauri": "workspace:*",+ "dsh-tauri-ui": "workspace:*"+ },+ "devDependencies": {+ "dsh-tauri-tsdown": "workspace:*",+ "tsdown": "catalog:cli",+ "vitest": "catalog:testing"+ }+}diff --git a/packages/dsh-tauri-notification/src/client/apis/index.ts b/packages/dsh-tauri-notification/src/client/apis/index.tsnew file mode 100644index 00000000..b19af28d--- /dev/null+++ b/packages/dsh-tauri-notification/src/client/apis/index.ts@@ -0,0 +1,16 @@+/*+ * @title dsh-tauri-notification+ * @swagger 2.0+ * @version 0.0.0+ */++import type { FetchOptions } from "dsh-tauri/client";+import { ofetch } from "dsh-tauri/client";+import type * as Types from "./index.type";++export const baseURL = "/api/desktop/dsh-tauri-notification";++/** @method get */+export function getTurnEnd(params?: Types.GetTurnEndQuery, options?: FetchOptions) {+ return ofetch<Types.TurnEndResult>("/turn-end", { baseURL, method: "get", params, ...options });+}diff --git a/packages/dsh-tauri-notification/src/client/apis/index.type.ts b/packages/dsh-tauri-notification/src/client/apis/index.type.tsnew file mode 100644index 00000000..f9462ae7--- /dev/null+++ b/packages/dsh-tauri-notification/src/client/apis/index.type.ts@@ -0,0 +1,8 @@+export type TurnEndResult = {+ reason?: string;+ turn?: number;+};++export interface GetTurnEndQuery {+ sessionId?: string;+}diff --git a/packages/dsh-tauri-notification/src/client/components/settings-group.tsx b/packages/dsh-tauri-notification/src/client/components/settings-group.tsxnew file mode 100644index 00000000..9dbff1a5--- /dev/null+++ b/packages/dsh-tauri-notification/src/client/components/settings-group.tsx@@ -0,0 +1,160 @@+import type { ChangeEvent, ReactElement, ReactNode } from 'react'+import type { SoundPlayer } from '../service/sound'+import type { NotificationSound, TurnCompleteMode } from '../types'+import { Button, Select, Switch } from 'dsh-tauri-ui/client'+import { useStore } from 'dsh-tauri/client'+import { useEffect, useRef, useState } from 'react'+import { locale } from '../locales'+import { createSoundPlayer } from '../service/sound'+import { requestBuiltinSounds } from '../service/sound-assets'+import { readSoundFile } from '../service/sound-file'+import { notificationSettings } from '../store'++/**+ * 一行设置:左侧标题 + 说明,右侧控件。+ *+ * 尺寸与留白照抄官方通用页自己的行(`font-size:14px/line-height:20px` 的标题、+ * `margin-top:4px` + `label-secondary` 的说明、`padding:16px 0`、+ * `border-bottom:.5px solid border-l2`),免得插件条目在官方页面里显得格格不入。+ */+function Row(props: { title: string, hint: string, children: ReactNode }): ReactElement {+ return (+ <div className="flex items-center justify-between gap-[24px] py-[16px] border-b-[0.5px] border-border-l2 last:border-b-0">+ <div className="flex min-w-0 flex-col">+ <span className="text-[14px] leading-[20px] text-primary">{props.title}</span>+ <span className="mt-[4px] text-[12px] leading-[18px] text-secondary">{props.hint}</span>+ </div>+ <div className="flex flex-none items-center gap-[8px]">{props.children}</div>+ </div>+ )+}++/**+ * 通知设置分组:轮次完成通知 / 启用权限通知 / 启用问题通知 / 通知提示音。+ *+ * 挂在官方「通用」设置页的 `settings.general.item` 槽位里(官方 `GeneralSection` 负责页面骨架,+ * 条目只贡献内容):不套卡片、也不加分组标题——四行的标题本身已经说明这是通知设置,+ * 样式直接对齐官方通用页自己的行。开关用官方 `Switch`,与页面里其它开关保持一致。+ * 状态读写都走 `notificationSettings` 单例,与通知运行时共用同一份配置。+ */+export function NotificationSettingsGroup(): ReactElement {+ locale.useLocale()+ const { turnComplete, approval, question, sound, customSound } = useStore(notificationSettings)+ const [notice, setNotice] = useState<string | null>(null)+ const fileRef = useRef<HTMLInputElement>(null)+ const playerRef = useRef<SoundPlayer | null>(null)++ useEffect(() => {+ // 试听要在设置页里立刻出声:先向壳层索要内置音资源(data URL),再建播放器。+ requestBuiltinSounds()+ const player = createSoundPlayer()+ playerRef.current = player+ return () => {+ playerRef.current = null+ player.dispose()+ }+ }, [])++ /** 试听一次当前选择;`none` 与「还没选文件的自定义」不发声。 */+ function preview(next: NotificationSound, custom: string | null): void {+ if (next === 'none' || (next === 'custom' && !custom))+ return+ playerRef.current?.play(next, custom)+ }++ function pickSoundOption(next: NotificationSound): void {+ notificationSettings.setSound(next)+ preview(next, notificationSettings.$state.customSound)+ }++ async function pickSound(event: ChangeEvent<HTMLInputElement>): Promise<void> {+ const file = event.target.files?.[0]+ event.target.value = ''+ if (!file)+ return+ const result = await readSoundFile(file)+ if (result.ok) {+ notificationSettings.setCustomSound(result.dataUrl)+ setNotice(null)+ // 选完文件直接试听,用户不用等下一次通知才知道选对了没有。+ preview('custom', result.dataUrl)+ return+ }+ setNotice(locale.text(result.error === 'too-large' ? 'soundCustomLarge' : 'soundCustomUnreadable'))+ }++ const turnOptions = [+ { value: 'never', label: locale.text('modeNever') },+ { value: 'background', label: locale.text('modeBackground') },+ { value: 'always', label: locale.text('modeAlways') },+ ]+ const soundOptions = [+ { value: 'default', label: locale.text('soundDefault') },+ { value: 'classic', label: locale.text('soundClassic') },+ { value: 'none', label: locale.text('soundNone') },+ { value: 'custom', label: locale.text('soundCustom') },+ ]++ return (+ // 行尾分隔线画在条目根元素上:官方只负责去掉最后一个条目那一条+ // (`[data-slot="settings.general.item"] > :last-child { border-bottom: none }`),+ // 中间那些条目得自己带,否则本组最后一行会跟下一条官方设置黏在一起。+ <div className="flex flex-col border-b-[0.5px] border-border-l2">+ {/* 行包一层:`last:border-b-0` 要落在最后一行上,而不能被下面的提示行顶掉。 */}+ <div className="flex flex-col">+ <Row title={locale.text('turnComplete')} hint={locale.text('turnCompleteHint')}>+ <Select+ options={turnOptions}+ value={turnComplete}+ onChange={next => notificationSettings.setTurnComplete(next as TurnCompleteMode)}+ />+ </Row>+ <Row title={locale.text('approval')} hint={locale.text('approvalHint')}>+ <Switch+ checked={approval}+ label={locale.text('approval')}+ onChange={next => notificationSettings.setApproval(next)}+ />+ </Row>+ <Row title={locale.text('question')} hint={locale.text('questionHint')}>+ <Switch+ checked={question}+ label={locale.text('question')}+ onChange={next => notificationSettings.setQuestion(next)}+ />+ </Row>+ <Row title={locale.text('sound')} hint={locale.text('soundHint')}>+ <Select+ options={soundOptions}+ value={sound}+ onChange={next => pickSoundOption(next as NotificationSound)}+ />+ {sound === 'custom'+ ? (+ <>+ <Button type="button" variant="outline" size="sm" onClick={() => fileRef.current?.click()}>+ {locale.text('soundCustomChoose')}+ </Button>+ {customSound+ ? (+ <Button type="button" variant="outline" size="sm" onClick={() => notificationSettings.setCustomSound(null)}>+ {locale.text('soundCustomClear')}+ </Button>+ )+ : null}+ </>+ )+ : null}+ </Row>+ </div>+ <input+ ref={fileRef}+ type="file"+ accept="audio/*"+ hidden+ onChange={(event) => { void pickSound(event) }}+ />+ {notice ? <div className="py-[16px] text-[12px] leading-[18px] text-error" role="alert">{notice}</div> : null}+ </div>+ )+}diff --git a/packages/dsh-tauri-notification/src/client/constants/index.ts b/packages/dsh-tauri-notification/src/client/constants/index.tsnew file mode 100644index 00000000..f871163c--- /dev/null+++ b/packages/dsh-tauri-notification/src/client/constants/index.ts@@ -0,0 +1,26 @@+import { PLUGIN_ID } from '../../shared/constants'++export { PLUGIN_ID }++/** 官方「通用」设置页里的条目 id(`settings.general.item` 槽位内唯一)。 */+export const SETTINGS_GENERAL_ITEM_ID = 'notification'++/** 条目顺序:夹在官方 `developer-tools`(15) 与 `current-version`(100) 之间。 */+export const SETTINGS_GENERAL_ITEM_ORDER = 30++/** 官方「通用」设置页的条目槽位名,由官方 `GeneralSection` 声明并渲染。 */+export const SETTINGS_GENERAL_ITEM_SLOT = 'settings.general.item'++/** 系统通知「批准」按钮的 action id,宿主窗口补丁原样回传该字符串。 */+export const APPROVE_ACTION_ID = 'approve'++/** 系统通知「拒绝」按钮的 action id。 */+export const REJECT_ACTION_ID = 'reject'++/** 系统通知「回复」按钮的 action id:按钮带输入框,用户输入即提问的答案。 */+export const REPLY_ACTION_ID = 'reply'++/** `ctx.effect` 的标签,便于在插件日志里定位。 */+export const LOCALE_EFFECT = `${PLUGIN_ID}: locale`+export const SETTINGS_EFFECT = `${PLUGIN_ID}: settings group`+export const NOTIFY_EFFECT = `${PLUGIN_ID}: notify`diff --git a/packages/dsh-tauri-notification/src/client/index.ts b/packages/dsh-tauri-notification/src/client/index.tsnew file mode 100644index 00000000..00df95b6--- /dev/null+++ b/packages/dsh-tauri-notification/src/client/index.ts@@ -0,0 +1,24 @@+import type { ClientContext } from 'dsh-tauri/client'+import { PLUGIN_ID } from '../shared/constants'+import { LOCALE_EFFECT, NOTIFY_EFFECT, SETTINGS_EFFECT } from './constants'+import { locale } from './locales'+import { notifyFeature } from './register/notify'+import { settingsFeature } from './register/settings'+import { notificationSettings } from './store/modules/settings'++export const name = PLUGIN_ID++/**+ * `uiSession` 不写进 inject:它在部分上下文里可能缺席,通知运行时用+ * `ctx.get('uiSession')` 探测并降级,而不是让整个插件卡在等待注入。+ */+export const inject = ['slots', 'locale', 'sessions']++export function apply(ctx: ClientContext): void {+ // 先把本地存储里的设置读回内存:通知运行时与设置面板都直接读 store,+ // 不 hydrate 的话每次启动都从默认值开始,用户改过的选项会被首次写回覆盖。+ void notificationSettings.hydrate()+ ctx.effect(locale.registerLocale, LOCALE_EFFECT)+ ctx.effect(settingsFeature, SETTINGS_EFFECT)+ ctx.effect(notifyFeature, NOTIFY_EFFECT)+}diff --git a/packages/dsh-tauri-notification/src/client/locales/index.ts b/packages/dsh-tauri-notification/src/client/locales/index.tsnew file mode 100644index 00000000..0471edb8--- /dev/null+++ b/packages/dsh-tauri-notification/src/client/locales/index.ts@@ -0,0 +1,69 @@+import { defineLocale } from 'dsh-tauri/client'+import { PLUGIN_ID } from '../../shared/constants'++const zh = {+ turnComplete: '轮次完成通知',+ turnCompleteHint: '设置 DSH 完成后何时提醒你;选「始终」时权限与提问在前台也照常提醒',+ modeNever: '从不',+ modeBackground: '仅在未聚焦时',+ modeAlways: '始终',+ approval: '启用权限通知',+ approvalHint: '在需要通知权限时显示提醒',+ question: '启用问题通知',+ questionHint: '在需要回答问题才能继续时显示通知',+ sound: '通知提示音',+ soundHint: '任务完成、请求权限和提问时的提示音',+ soundDefault: '默认',+ soundClassic: '经典',+ soundNone: '无',+ soundCustom: '自定义',+ soundCustomChoose: '选择提示音文件',+ soundCustomClear: '移除自定义提示音',+ soundCustomLarge: '提示音文件过大(上限 512 KB)',+ soundCustomUnreadable: '无法读取该提示音文件',+ labelTurn: '轮次已完成',+ labelApproval: '需要授权',+ labelQuestion: '需要回答',+ bodyApproval: '有待处理的授权请求',+ bodyQuestion: '有待回答的问题',+ sessionFallback: 'DSH 会话',+ approve: '批准',+ reject: '拒绝',+ reply: '回复',+ replyPlaceholder: '输入回复内容',+}++const en: Record<keyof typeof zh, string> = {+ turnComplete: 'Turn completion notification',+ turnCompleteHint: 'When to be reminded after DSH finishes; “Always” also alerts for permissions and questions while you are watching',+ modeNever: 'Never',+ modeBackground: 'Only when unfocused',+ modeAlways: 'Always',+ approval: 'Permission notifications',+ approvalHint: 'Show an alert when a permission request is needed',+ question: 'Question notifications',+ questionHint: 'Show a notification when an answer is required to continue',+ sound: 'Notification sound',+ soundHint: 'Sound for task completion, permission requests and questions',+ soundDefault: 'Default',+ soundClassic: 'Classic',+ soundNone: 'None',+ soundCustom: 'Custom',+ soundCustomChoose: 'Choose a sound file',+ soundCustomClear: 'Remove custom sound',+ soundCustomLarge: 'Sound file is too large (512 KB limit)',+ soundCustomUnreadable: 'Unable to read that sound file',+ labelTurn: 'Turn completed',+ labelApproval: 'Approval required',+ labelQuestion: 'Answer required',+ bodyApproval: 'An approval request is waiting',+ bodyQuestion: 'A question is waiting for your answer',+ sessionFallback: 'DSH session',+ approve: 'Approve',+ reject: 'Reject',+ reply: 'Reply',+ replyPlaceholder: 'Type your reply',+}++/** 通知设置的文案字典;`registerLocale` 必须由 `ctx.effect` 调用(保持未绑定 this)。 */+export const locale = defineLocale(PLUGIN_ID, { zh, en })diff --git a/packages/dsh-tauri-notification/src/client/register/notify.ts b/packages/dsh-tauri-notification/src/client/register/notify.tsnew file mode 100644index 00000000..f4d3515e--- /dev/null+++ b/packages/dsh-tauri-notification/src/client/register/notify.ts@@ -0,0 +1,353 @@+import type { ClientContext } from 'dsh-tauri/client'+import type { FocusGateInput } from '../service/decision'+import type { NativeNotificationAction, NotificationKind, PendingInteractionFace, SessionsFace, UiSessionFace } from '../types'+import { defineRegister } from 'dsh-tauri/client'+import { PLUGIN_ID } from '../../shared/constants'+import { APPROVE_ACTION_ID, REJECT_ACTION_ID, REPLY_ACTION_ID } from '../constants'+import { locale } from '../locales'+import { answerQuestionBatch, approveInteraction, pendingDetail, pendingIdentity, pendingNotificationKind, readPendingInteraction, rejectInteraction } from '../service/approval'+import { allowPendingNotification, allowTurnNotification, boundText, notificationTag } from '../service/decision'+import { showNativeNotification } from '../service/native'+import { advanceQuestionWizard, canDriveQuestions, questionWizardStep, syncQuestionWizard } from '../service/question-wizard'+import { createSoundPlayer } from '../service/sound'+import { requestBuiltinSounds } from '../service/sound-assets'+import { turnEndedByUser } from '../service/turn-end'+import { notificationSettings } from '../store'++/** 状态抖动合并窗口:running 可能连续翻转几次,等它稳定后再判断是否提醒。 */+const SETTLE_MS = 250+/** 通知正文上限。 */+const MAX_BODY_CHARS = 400+/** 会话尚未出现在列表里时,聚焦重试次数与间隔。 */+const FOCUS_RETRY_LIMIT = 6+const FOCUS_RETRY_MS = 200+/** 等待 `uiSession` 服务注册的上限(20 × 250ms = 5s)。 */+const UI_SESSION_WAIT_LIMIT = 20+const UI_SESSION_WAIT_MS = 250++/** 单次观察到的会话状态(`uiSession` 缺席时退化为列表里的 running)。 */+interface SessionObservation {+ readonly running: boolean | undefined+ readonly pending: PendingInteractionFace | undefined+}++/**+ * 通知运行时:把客户端状态变化翻译成原生通知。+ *+ * 数据全部来自客户端服务——`sessions.list`(会话标题、当前会话、running 兜底)与+ * `uiSession.sessionStatus`(运行态与待处理交互)。两者都用最小结构面读取,+ * 服务缺席时降级而不是报错。+ */+export const notifyFeature = defineRegister<ClientContext>((controller, ctx, adapter) => {+ const sound = createSoundPlayer()+ controller.add(sound.dispose)+ // 内置提示音是壳层 `public/` 下的资源,插件在 iframe 里取不到同源文件:开局先索要一份,+ // 免得第一次通知落到合成音兜底上。+ requestBuiltinSounds()++ const seenRunning = new Map<string, boolean | undefined>()+ const seenPending = new Map<string, string | undefined>()+ const timers = new Map<string, () => void>()+ let sequence = 0++ const readSessions = (): SessionsFace | undefined => ctx.get('sessions') as SessionsFace | undefined+ const readUiSession = (): UiSessionFace | undefined => ctx.get('uiSession') as UiSessionFace | undefined++ const sessionTitle = (sessionId: string): string => {+ const summary = readSessions()?.list.getSnapshot().byId[sessionId]+ return summary?.displayTitle?.trim() || summary?.title?.trim() || locale.text('sessionFallback')+ }++ /**+ * 通知门控看的位置:宿主窗口在不在后台,以及用户正在看哪个会话。+ *+ * `document.visibilityState` 已被宿主补丁(`NOTIFICATION_SHIM_JS`)映射成宿主窗口状态,+ * 这里读标准 API 即可;当前会话取会话列表投影,读不到就当「不知道用户在看哪」。+ */+ function focusGate(sessionId: string): FocusGateInput {+ return {+ hostHidden: typeof document !== 'undefined' && document.visibilityState === 'hidden',+ sessionId,+ currentSessionId: adapter.sessionList()?.current,+ }+ }++ const focusSession = (sessionId: string, attempt = 0): void => {+ const outcome = adapter.openSession(sessionId)+ if (outcome.status === 'opened')+ return+ if (attempt >= FOCUS_RETRY_LIMIT) {+ console.warn(`[${PLUGIN_ID}] cannot focus session ${sessionId}: ${outcome.reason}`)+ return+ }+ controller.timeout(() => {+ focusSession(sessionId, attempt + 1)+ }, FOCUS_RETRY_MS)+ }++ const notify = (sessionId: string, kind: NotificationKind, title: string, body: string, requireInteraction: boolean, actions?: NativeNotificationAction[], onAction?: (action: string, inputValue: string | null) => void): void => {+ const settings = notificationSettings.$state+ sound.play(settings.sound, settings.customSound)+ sequence += 1+ showNativeNotification({+ title,+ body: boundText(body, MAX_BODY_CHARS),+ tag: notificationTag(sessionId, kind, sequence),+ sessionId,+ requireInteraction,+ // 提示音已在上面按设置播过(`none` 时就是静音),因此原生通知自己必须静音;+ // 未打包的 Windows 应用也没法用 toast 播放仓库里的 wav,只能由帧内发声。+ silent: true,+ actions,+ onAction,+ onClick: () => {+ focusSession(sessionId)+ },+ })+ }++ const approveFromNotification = async (sessionId: string, identity: string): Promise<void> => {+ const result = await approveInteraction(readUiSession(), sessionId, identity)+ if (!result.ok)+ console.warn(`[${PLUGIN_ID}] approve from notification failed: ${result.error ?? 'unknown'}`)+ }++ const rejectFromNotification = async (sessionId: string, identity: string): Promise<void> => {+ const result = await rejectInteraction(readUiSession(), sessionId, identity)+ if (!result.ok)+ console.warn(`[${PLUGIN_ID}] reject from notification failed: ${result.error ?? 'unknown'}`)+ }++ /**+ * 提问的「回复」按钮。系统通知渲染不了选项列表,只能收自由文本,所以按钮带一个输入框;+ * 每个按钮都带上这条通知当初展示的那次挂起(`identity`),作答时用它挡掉过期点击。+ */+ const questionActions = (): NativeNotificationAction[] => [{+ id: REPLY_ACTION_ID,+ title: locale.text('reply'),+ input: true,+ inputPlaceholder: locale.text('replyPlaceholder'),+ inputButtonTitle: locale.text('reply'),+ }]++ const questionOnAction = (sessionId: string, identity: string) => (action: string, inputValue: string | null): void => {+ if (action !== REPLY_ACTION_ID)+ return+ // 非 Windows 平台插件没有文本框,带 `input` 的按钮会退化成普通按钮:这时点击拿不到文本,+ // 静默丢弃会让用户以为通知坏了,改为把会话拉到前台去回答。+ if (inputValue)+ void replyFromNotification(sessionId, inputValue, identity)+ else+ focusSession(sessionId)+ }++ /**+ * 弹一条提问通知:多问题批次一题一条,正文写「提问 2/3 · 题目」,用户一眼看到还有几轮要决策。+ *+ * @returns 是否真的弹了(驱动不了这一批提问时为 `false`,调用方改为只提醒)。+ */+ const notifyQuestionRound = (sessionId: string, pending: PendingInteractionFace): boolean => {+ const step = questionWizardStep(sessionId, pending)+ if (!step)+ return false+ const label = locale.text('labelQuestion')+ const detail = step.question.question?.trim() || step.question.header?.trim() || locale.text('bodyQuestion')+ const body = step.total > 1 ? `${label} ${step.index + 1}/${step.total} · ${detail}` : `${label} · ${detail}`+ notify(sessionId, 'question', sessionTitle(sessionId), body, true, questionActions(), questionOnAction(sessionId, step.identity))+ return true+ }++ /**+ * 通知里的回复。多问题批次按官方向导的做法一题一轮:先在本地攒着,攒齐整批再一次性提交。+ *+ * 宿主的校验要求每条答案对准一道题、缺一条就 BAD_ANSWER,所以中间几轮只是把下一题弹出来,+ * 最后一轮才真正提交;整批提交前后都用身份挡掉过期点击。+ */+ async function replyFromNotification(sessionId: string, text: string, identity: string): Promise<void> {+ const uiSession = readUiSession()+ const pending = readPendingInteraction(uiSession, sessionId)+ if (!pending || (pending.kind !== 'question' && pending.kind !== 'plan-review')) {+ console.warn(`[${PLUGIN_ID}] reply from notification failed: QUESTION_UNAVAILABLE`)+ return+ }+ if (pendingIdentity(pending) !== identity) {+ console.warn(`[${PLUGIN_ID}] reply from notification failed: QUESTION_STALE`)+ return+ }+ const answers = advanceQuestionWizard(sessionId, pending, text)+ if (!answers) {+ // 还有下一题:接着弹一条,用户顺着通知就把整批答完了。+ if (notifyQuestionRound(sessionId, pending))+ return+ console.warn(`[${PLUGIN_ID}] question batch ${identity} cannot be completed from notifications, answer it in the session view`)+ return+ }+ const result = await answerQuestionBatch(uiSession, sessionId, answers, identity)+ if (!result.ok)+ console.warn(`[${PLUGIN_ID}] reply from notification failed: ${result.error ?? 'unknown'}`)+ }++ /** 合并窗口结束后再确认状态仍然成立,避免「刚弹通知就被新状态推翻」。 */+ const settle = (key: string, run: () => void): void => {+ timers.get(key)?.()+ const cancel = controller.timeout(() => {+ timers.delete(key)+ run()+ }, SETTLE_MS)+ timers.set(key, cancel)+ }++ const reconcilePending = (sessionId: string, pending: PendingInteractionFace, changed: boolean): void => {+ if (!changed)+ return+ settle(`${sessionId}:pending`, () => {+ const current = readUiSession()?.sessionStatus.getSnapshot().get(sessionId)?.pendingInteraction+ if (!current || pendingIdentity(current) !== pendingIdentity(pending))+ return+ const kind = pendingNotificationKind(current)+ if (!kind)+ return+ if (!allowPendingNotification(notificationSettings.$state, kind, focusGate(sessionId)))+ return+ const detail = pendingDetail(current)+ const fallback = kind === 'approval' ? locale.text('bodyApproval') : locale.text('bodyQuestion')+ const label = kind === 'approval' ? locale.text('labelApproval') : locale.text('labelQuestion')+ // 通知按钮一律要求交互仍可回答:答应不了的时候给按钮只会让用户白点。+ const answerable = current.answerable !== false && typeof current.answer === 'function'+ const identity = pendingIdentity(current)+ // 提问:能驱动就一题一条通知(多问题批次由 question-wizard 在本地攒齐整批再提交),+ // 驱动不了(有题目缺 id,整批永远攒不齐)就只提醒,点通知本体回会话界面用官方向导作答。+ if (kind === 'question' && answerable && canDriveQuestions(current)) {+ notifyQuestionRound(sessionId, current)+ return+ }+ // 授权给「批准 / 拒绝」。每个按钮都带上这条通知当初展示的那次挂起(`identity`):系统+ // 通知会一直挂到用户处理它为止,期间会话可能已经有**新的**待处理交互,身份对不上就不+ // 回答(见 approval.ts 的 APPROVAL_STALE / QUESTION_STALE)。+ const actions: NativeNotificationAction[] | undefined = kind === 'approval' && answerable+ ? [+ { id: APPROVE_ACTION_ID, title: locale.text('approve') },+ { id: REJECT_ACTION_ID, title: locale.text('reject') },+ ]+ : undefined+ const onAction = actions+ ? (action: string): void => {+ if (action === APPROVE_ACTION_ID)+ void approveFromNotification(sessionId, identity)+ else if (action === REJECT_ACTION_ID)+ void rejectFromNotification(sessionId, identity)+ }+ : undefined+ notify(+ sessionId,+ kind,+ // 标题放会话 title、正文放「动作 · 摘要」:与会话列表、桌宠气泡一致,用户一眼能认出+ // 是哪个会话、要做什么(系统通知的宽度只够一行摘要)。+ sessionTitle(sessionId),+ `${label} · ${detail || fallback}`,+ true,+ actions,+ onAction,+ )+ })+ }++ const reconcileTurn = (sessionId: string, finished: boolean): void => {+ if (!finished)+ return+ settle(`${sessionId}:turn`, () => {+ const status = readUiSession()?.sessionStatus.getSnapshot().get(sessionId)+ const summary = readSessions()?.list.getSnapshot().byId[sessionId]+ if (status ? status.running === true : summary?.running === true)+ return+ const mode = notificationSettings.$state.turnComplete+ if (!allowTurnNotification({ ...focusGate(sessionId), mode }))+ return+ // 「用户手动中断」和「跑完了」在客户端看到的是同一个 `running: false`:结束原因只在宿主+ // 的 `turn/end` 里,所以弹之前问一次宿主;是中断就什么都不做(用户自己掐断的,不需要提醒)。+ void (async () => {+ if (await turnEndedByUser(sessionId))+ return+ // 问宿主是异步的,等待期间会话可能又跑起来了:再确认一次,别给正在干活的会话弹「已完成」。+ const currentStatus = readUiSession()?.sessionStatus.getSnapshot().get(sessionId)+ const currentSummary = readSessions()?.list.getSnapshot().byId[sessionId]+ if (currentStatus ? currentStatus.running === true : currentSummary?.running === true)+ return+ notify(sessionId, 'turn', sessionTitle(sessionId), locale.text('labelTurn'), false)+ })()+ })+ }++ const reconcile = (entries: ReadonlyMap<string, SessionObservation>): void => {+ for (const [sessionId, observed] of entries) {+ const pendingKey = observed.pending ? pendingIdentity(observed.pending) : undefined+ // 待处理交互换了(答完了 / 被新提问顶掉了)就丢掉攒了一半的作答进度,避免题号错位。+ syncQuestionWizard(sessionId, pendingKey)+ const known = seenRunning.has(sessionId) || seenPending.has(sessionId)+ const previousRunning = seenRunning.get(sessionId)+ const previousPending = seenPending.get(sessionId)+ seenRunning.set(sessionId, observed.running)+ seenPending.set(sessionId, pendingKey)+ // 首次观察只建立基线:插件加载前就存在的完成态与待处理交互不该补弹通知。+ if (!known)+ continue+ if (observed.pending && pendingKey !== previousPending)+ reconcilePending(sessionId, observed.pending, true)+ reconcileTurn(sessionId, previousRunning === true && observed.running !== true)+ }+ for (const sessionId of [...seenRunning.keys()]) {+ if (entries.has(sessionId))+ continue+ seenRunning.delete(sessionId)+ seenPending.delete(sessionId)+ syncQuestionWizard(sessionId, undefined)+ timers.get(`${sessionId}:pending`)?.()+ timers.get(`${sessionId}:turn`)?.()+ timers.delete(`${sessionId}:pending`)+ timers.delete(`${sessionId}:turn`)+ }+ }++ const observe = (): void => {+ const list = readSessions()?.list.getSnapshot()+ if (!list)+ return+ const statuses = readUiSession()?.sessionStatus.getSnapshot()+ const entries = new Map<string, SessionObservation>()+ for (const sessionId of list.ids) {+ const summary = list.byId[sessionId]+ const status = statuses?.get(sessionId)+ entries.set(sessionId, {+ running: status ? status.running : summary?.running,+ pending: status?.pendingInteraction,+ })+ }+ reconcile(entries)+ }++ // 会话列表是常驻服务:用它驱动观察,顺带拿到标题与当前会话。+ const listSource = readSessions()?.list+ if (listSource) {+ controller.add(listSource.subscribe(observe))+ observe()+ }++ // `uiSession` 的注册时机不由本插件决定,最多等 5 秒;等到了就订阅,等不到则维持列表兜底。+ let statusAttached = false+ let statusAttempts = 0+ const attachStatus = (): void => {+ const source = readUiSession()?.sessionStatus+ if (!source) {+ if (statusAttempts < UI_SESSION_WAIT_LIMIT && !controller.isDisposed()) {+ statusAttempts += 1+ controller.timeout(attachStatus, UI_SESSION_WAIT_MS)+ }+ return+ }+ statusAttached = true+ controller.add(source.subscribe(observe))+ observe()+ }+ attachStatus()+ void statusAttached+})diff --git a/packages/dsh-tauri-notification/src/client/register/settings.test.ts b/packages/dsh-tauri-notification/src/client/register/settings.test.tsnew file mode 100644index 00000000..3131ed78--- /dev/null+++ b/packages/dsh-tauri-notification/src/client/register/settings.test.ts@@ -0,0 +1,57 @@+import { describe, expect, it, vi } from 'vitest'+import { PLUGIN_ID } from '../../shared/constants'+import { NotificationSettingsGroup } from '../components/settings-group'+import { SETTINGS_GENERAL_ITEM_ID, SETTINGS_GENERAL_ITEM_ORDER, SETTINGS_GENERAL_ITEM_SLOT } from '../constants'+import { settingsFeature } from './settings'++// 真 `defineRegister` 会在 effect 运行时创建控制器与适配器;这里只验证注册形状,+// 直接拿 setup 回调调用即可(与 `dsh-tauri-ssh` 的注册测试同一套路)。+vi.mock('dsh-tauri/client', () => ({+ defineLocale: (ns: string, dictionaries: Record<string, unknown>) => ({ NS: ns, ...dictionaries }),+ defineRegister: (setup: unknown) => setup,+}))++// `dsh-tauri-ui/client` 的 dist bundle 以 ModuleLoader 工厂包裹,脱离宿主加载器无法在 node+// 里求值;分组内容由 e2e 覆盖,这里只需要一个恒等引用。+vi.mock('../components/settings-group', () => ({ NotificationSettingsGroup: () => null }))++/** 只记账的槽位上下文:`inject` 立刻回放注册回调。 */+function scriptedCtx(): {+ controller: { add: ReturnType<typeof vi.fn> }+ ctx: unknown+ inject: ReturnType<typeof vi.fn>+ register: ReturnType<typeof vi.fn>+} {+ const inject = vi.fn((_slot: unknown, contribute: () => unknown) => contribute())+ const register = vi.fn((_options: unknown, _component: unknown) => 'registration')+ return { controller: { add: vi.fn() }, ctx: { slots: { inject, register } }, inject, register }+}++describe('notification settings registration', () => {+ it('把通知分组挂进官方「通用」设置页的条目槽位,且不带导航 label', () => {+ const { controller, ctx, inject, register } = scriptedCtx()+ const run = settingsFeature as unknown as (controller: unknown, ctxValue: unknown) => void+ run(controller, ctx)++ expect(inject).toHaveBeenCalledTimes(1)+ expect(inject.mock.calls[0]?.[0]).toBe(SETTINGS_GENERAL_ITEM_SLOT)+ expect(SETTINGS_GENERAL_ITEM_SLOT).toBe('settings.general.item')+ expect(SETTINGS_GENERAL_ITEM_ID).toBe('notification')+ expect(SETTINGS_GENERAL_ITEM_ORDER).toBe(30)++ const options = register.mock.calls[0]?.[0] as Record<string, unknown>+ expect(options.name).toBe(SETTINGS_GENERAL_ITEM_SLOT)+ expect(options.id).toBe(SETTINGS_GENERAL_ITEM_ID)+ // 夹在官方 developer-tools(15) 与 current-version(100) 之间。+ expect(options.order).toBe(SETTINGS_GENERAL_ITEM_ORDER)+ expect(options.registrant).toBe(PLUGIN_ID)+ expect(options.locale).toBe(PLUGIN_ID)+ expect((options.inject as () => unknown)()).toEqual({})+ // 条目不进左侧导航:官方条目同样没有 label。+ expect('label' in options).toBe(false)+ expect(options.children).toBeUndefined()++ expect(register.mock.calls[0]?.[1]).toBe(NotificationSettingsGroup)+ expect(controller.add).toHaveBeenCalledWith('registration')+ })+})diff --git a/packages/dsh-tauri-notification/src/client/register/settings.ts b/packages/dsh-tauri-notification/src/client/register/settings.tsnew file mode 100644index 00000000..065d6f15--- /dev/null+++ b/packages/dsh-tauri-notification/src/client/register/settings.ts@@ -0,0 +1,26 @@+import type { ClientContext } from 'dsh-tauri/client'+import { defineRegister } from 'dsh-tauri/client'+import { PLUGIN_ID } from '../../shared/constants'+import { NotificationSettingsGroup } from '../components/settings-group'+import { SETTINGS_GENERAL_ITEM_ID, SETTINGS_GENERAL_ITEM_ORDER, SETTINGS_GENERAL_ITEM_SLOT } from '../constants'+import { locale } from '../locales'++/**+ * 把通知设置挂进官方「通用」设置页的 `settings.general.item` 槽位。+ *+ * 这个子槽位由官方 `GeneralSection` 声明并渲染(`renderSlot("settings.general.item")`),+ * 所以本包只贡献条目内容、不画页面骨架,也不进左侧导航——条目不带 `label`。+ *+ * 槽位名与组件都用 `as never` 收窄:槽位表由官方 UI 包做声明合并,+ * 本包不依赖它们的类型(与 `dsh-tauri-pet` 的做法一致)。+ */+export const settingsFeature = defineRegister<ClientContext>((controller, ctx) => {+ controller.add(ctx.slots.inject(SETTINGS_GENERAL_ITEM_SLOT as never, () => ctx.slots.register({+ name: SETTINGS_GENERAL_ITEM_SLOT,+ id: SETTINGS_GENERAL_ITEM_ID,+ order: SETTINGS_GENERAL_ITEM_ORDER,+ registrant: PLUGIN_ID,+ locale: locale.NS,+ inject: () => ({}),+ } as never, NotificationSettingsGroup as never)))+})diff --git a/packages/dsh-tauri-notification/src/client/service/approval.test.ts b/packages/dsh-tauri-notification/src/client/service/approval.test.tsnew file mode 100644index 00000000..d6b5a581--- /dev/null+++ b/packages/dsh-tauri-notification/src/client/service/approval.test.ts@@ -0,0 +1,199 @@+import type { PendingInteractionFace, SessionStatusFace, UiSessionFace } from '../types'+import { describe, expect, it, vi } from 'vitest'+import {+ answerQuestionBatch,+ approveInteraction,+ pendingDetail,+ pendingIdentity,+ pendingNotificationKind,+ readPendingInteraction,+ readSessionStatus,+} from './approval'++function fakeUiSession(status?: Partial<SessionStatusFace>): UiSessionFace {+ const snapshot = new Map<string, SessionStatusFace>()+ if (status) {+ snapshot.set('s1', {+ running: false,+ pendingInteraction: undefined,+ completionUnread: false,+ ...status,+ })+ }+ return {+ sessionStatus: {+ getSnapshot: () => snapshot,+ subscribe: () => () => {},+ },+ }+}++function pending(overrides: Partial<PendingInteractionFace> & Pick<PendingInteractionFace, 'kind' | 'key'>): PendingInteractionFace {+ return { sessionId: 's1', ...overrides }+}++describe('readSessionStatus / readPendingInteraction', () => {+ it('缺少 uiSession 服务时安全降级为 undefined', () => {+ expect(readSessionStatus(undefined, 's1')).toBeUndefined()+ expect(readPendingInteraction(undefined, 's1')).toBeUndefined()+ })++ it('会话不在快照里时为 undefined', () => {+ expect(readSessionStatus(fakeUiSession({ running: true }), 'missing')).toBeUndefined()+ })++ it('读得到当前待处理交互', () => {+ const interaction = pending({ kind: 'approval', key: 'k1' })+ const ui = fakeUiSession({ pendingInteraction: interaction })+ expect(readSessionStatus(ui, 's1')?.pendingInteraction).toBe(interaction)+ expect(readPendingInteraction(ui, 's1')).toBe(interaction)+ })+})++describe('pendingNotificationKind', () => {+ it('未挂起时不通知', () => {+ expect(pendingNotificationKind(undefined)).toBeUndefined()+ })++ it('授权映射为 approval', () => {+ expect(pendingNotificationKind(pending({ kind: 'approval', key: 'k' }))).toBe('approval')+ })++ it('提问与计划评审都映射为 question', () => {+ expect(pendingNotificationKind(pending({ kind: 'question', key: 'k' }))).toBe('question')+ expect(pendingNotificationKind(pending({ kind: 'plan-review', key: 'k' }))).toBe('question')+ })++ it('未知交互不弹通知', () => {+ expect(pendingNotificationKind(pending({ kind: 'mystery', key: 'k' }))).toBeUndefined()+ })+})++describe('pendingIdentity', () => {+ it('由 kind 与 key 组成稳定标识', () => {+ expect(pendingIdentity(pending({ kind: 'approval', key: 'abc' }))).toBe('approval:abc')+ expect(pendingIdentity(pending({ kind: 'question', key: 'abc' }))).toBe('question:abc')+ })+})++describe('pendingDetail', () => {+ it('授权拼接工具名与原因', () => {+ expect(pendingDetail(pending({ kind: 'approval', key: 'k', toolName: 'Bash', reason: '网络访问' })))+ .toBe('Bash: 网络访问')+ })++ it('授权优先使用本地化的 displayReason', () => {+ expect(pendingDetail(pending({ kind: 'approval', key: 'k', toolName: 'Bash', displayReason: { zh: '需要授权', en: 'needs approval' } })))+ .toBe('Bash: 需要授权')+ expect(pendingDetail(pending({ kind: 'approval', key: 'k', toolName: 'Bash', displayReason: '因为安全' })))+ .toBe('Bash: 因为安全')+ })++ it('只有工具名或只有原因时退化为可用的那一半', () => {+ expect(pendingDetail(pending({ kind: 'approval', key: 'k', toolName: 'Bash' }))).toBe('Bash')+ expect(pendingDetail(pending({ kind: 'approval', key: 'k', reason: '网络访问' }))).toBe('网络访问')+ expect(pendingDetail(pending({ kind: 'approval', key: 'k' }))).toBe('')+ })++ it('提问取首个问题,缺失时退回标题', () => {+ expect(pendingDetail(pending({ kind: 'question', key: 'k', questions: [{ question: '选哪个?', header: '选择' }] })))+ .toBe('选哪个?')+ expect(pendingDetail(pending({ kind: 'question', key: 'k', questions: [{ header: '选择' }] })))+ .toBe('选择')+ expect(pendingDetail(pending({ kind: 'question', key: 'k' }))).toBe('')+ })+})++describe('approveInteraction', () => {+ it('没有可用的待处理交互时返回 APPROVAL_UNAVAILABLE', async () => {+ expect(await approveInteraction(undefined, 's1')).toEqual({ ok: false, error: 'APPROVAL_UNAVAILABLE' })+ expect(await approveInteraction(fakeUiSession({ running: true }), 's1')).toEqual({ ok: false, error: 'APPROVAL_UNAVAILABLE' })+ })++ it('挂起的是提问而不是授权时不越权回答', async () => {+ const ui = fakeUiSession({ pendingInteraction: pending({ kind: 'question', key: 'k', answer: async () => {} }) })+ expect(await approveInteraction(ui, 's1')).toEqual({ ok: false, error: 'APPROVAL_UNAVAILABLE' })+ })++ it('交互已不可回答或缺少 answer 方法时返回 APPROVAL_NOT_ANSWERABLE', async () => {+ const notAnswerable = fakeUiSession({+ pendingInteraction: pending({ kind: 'approval', key: 'k', answerable: false, answer: async () => {} }),+ })+ expect(await approveInteraction(notAnswerable, 's1')).toEqual({ ok: false, error: 'APPROVAL_NOT_ANSWERABLE' })+ const noAnswer = fakeUiSession({ pendingInteraction: pending({ kind: 'approval', key: 'k', answerable: true }) })+ expect(await approveInteraction(noAnswer, 's1')).toEqual({ ok: false, error: 'APPROVAL_NOT_ANSWERABLE' })+ })++ it('可回答时以 allowed-once 一次性批准', async () => {+ const answer = vi.fn(async () => {})+ const ui = fakeUiSession({ pendingInteraction: pending({ kind: 'approval', key: 'k', answerable: true, answer }) })+ expect(await approveInteraction(ui, 's1')).toEqual({ ok: true })+ expect(answer).toHaveBeenCalledTimes(1)+ expect(answer).toHaveBeenCalledWith('allowed-once')+ })++ it('回答抛错时把错误信息回传而不是抛出', async () => {+ const ui = fakeUiSession({+ pendingInteraction: pending({ kind: 'approval', key: 'k', answerable: true, answer: async () => { throw new Error('已过期') } }),+ })+ expect(await approveInteraction(ui, 's1')).toEqual({ ok: false, error: '已过期' })+ })+})++describe('answerQuestionBatch', () => {+ const questions = [{ id: 'q1' }, { id: 'q2' }]++ it('没有提问挂起时不越权回答', async () => {+ expect(await answerQuestionBatch(undefined, 's1', [{ id: 'q1', selected: [], custom: 'x' }]))+ .toEqual({ ok: false, error: 'QUESTION_UNAVAILABLE' })+ const approval = fakeUiSession({ pendingInteraction: pending({ kind: 'approval', key: 'k', answer: async () => {} }) })+ expect(await answerQuestionBatch(approval, 's1', [{ id: 'q1', selected: [], custom: 'x' }]))+ .toEqual({ ok: false, error: 'QUESTION_UNAVAILABLE' })+ })++ it('身份对不上时返回 QUESTION_STALE,避免替新的挂起作答', async () => {+ const ui = fakeUiSession({ pendingInteraction: pending({ kind: 'question', key: 'k', answerable: true, questions, answer: async () => {} }) })+ expect(await answerQuestionBatch(ui, 's1', [{ id: 'q1', selected: [], custom: '一' }, { id: 'q2', selected: [], custom: '二' }], 'question:old'))+ .toEqual({ ok: false, error: 'QUESTION_STALE' })+ })++ it('交互已不可回答时返回 QUESTION_NOT_ANSWERABLE', async () => {+ const ui = fakeUiSession({ pendingInteraction: pending({ kind: 'question', key: 'k', answerable: false, questions, answer: async () => {} }) })+ expect(await answerQuestionBatch(ui, 's1', [{ id: 'q1', selected: [], custom: '一' }]))+ .toEqual({ ok: false, error: 'QUESTION_NOT_ANSWERABLE' })+ })++ it('空答案不提交', async () => {+ const ui = fakeUiSession({ pendingInteraction: pending({ kind: 'question', key: 'k', answerable: true, questions, answer: async () => {} }) })+ expect(await answerQuestionBatch(ui, 's1', [])).toEqual({ ok: false, error: 'QUESTION_EMPTY' })+ expect(await answerQuestionBatch(ui, 's1', [{ id: 'q1', selected: [], custom: ' ' }]))+ .toEqual({ ok: false, error: 'QUESTION_EMPTY' })+ })++ it('答案与挂起的题目对不齐时返回 QUESTION_STALE,不交给宿主去拒收', async () => {+ const answer = vi.fn(async () => {})+ const ui = fakeUiSession({ pendingInteraction: pending({ kind: 'question', key: 'k', answerable: true, questions, answer }) })+ expect(await answerQuestionBatch(ui, 's1', [{ id: 'q1', selected: [], custom: '一' }]))+ .toEqual({ ok: false, error: 'QUESTION_STALE' })+ expect(await answerQuestionBatch(ui, 's1', [{ id: 'q1', selected: [], custom: '一' }, { id: 'qX', selected: [], custom: '二' }]))+ .toEqual({ ok: false, error: 'QUESTION_STALE' })+ expect(answer).not.toHaveBeenCalled()+ })++ it('整批一次提交,自由文本走 custom', async () => {+ const answer = vi.fn(async () => {})+ const ui = fakeUiSession({ pendingInteraction: pending({ kind: 'question', key: 'k', answerable: true, questions, answer }) })+ expect(await answerQuestionBatch(ui, 's1', [{ id: 'q1', selected: [], custom: '一' }, { id: 'q2', selected: [], custom: '二' }], 'question:k'))+ .toEqual({ ok: true })+ expect(answer).toHaveBeenCalledTimes(1)+ expect(answer).toHaveBeenCalledWith({ answers: [{ id: 'q1', selected: [], custom: '一' }, { id: 'q2', selected: [], custom: '二' }] })+ })++ it('宿主拒收时把错误信息回传而不是抛出', async () => {+ const ui = fakeUiSession({+ pendingInteraction: pending({ kind: 'question', key: 'k', answerable: true, questions: [{ id: 'q1' }], answer: async () => { throw new Error('BAD_ANSWER') } }),+ })+ expect(await answerQuestionBatch(ui, 's1', [{ id: 'q1', selected: [], custom: '一' }]))+ .toEqual({ ok: false, error: 'BAD_ANSWER' })+ })+})diff --git a/packages/dsh-tauri-notification/src/client/service/approval.ts b/packages/dsh-tauri-notification/src/client/service/approval.tsnew file mode 100644index 00000000..6b6e4165--- /dev/null+++ b/packages/dsh-tauri-notification/src/client/service/approval.ts@@ -0,0 +1,146 @@+import type { ApprovalDecision, PendingInteractionFace, QuestionAnswerFace, SessionStatusFace, UiSessionFace } from '../types'+import { boundText } from './decision'++export interface DecideResult {+ ok: boolean+ error?: string+}++/** 读取某会话的当前状态;没有 `uiSession` 服务或会话已不在快照里时为 `undefined`。 */+export function readSessionStatus(uiSession: UiSessionFace | undefined, sessionId: string): SessionStatusFace | undefined {+ return uiSession?.sessionStatus.getSnapshot().get(sessionId)+}++/** 读取某会话当前**最高优先级**的待处理交互(官方语义:每个会话只有一个)。 */+export function readPendingInteraction(uiSession: UiSessionFace | undefined, sessionId: string): PendingInteractionFace | undefined {+ return readSessionStatus(uiSession, sessionId)?.pendingInteraction+}++/** 把官方 kind 收敛成通知类别;未知交互不弹通知。 */+export function pendingNotificationKind(pending: PendingInteractionFace | undefined): 'approval' | 'question' | undefined {+ if (!pending)+ return undefined+ if (pending.kind === 'approval')+ return 'approval'+ if (pending.kind === 'question' || pending.kind === 'plan-review')+ return 'question'+ return undefined+}++/** 待处理交互的稳定标识,用于去重(同一次挂起只通知一次)。 */+export function pendingIdentity(pending: PendingInteractionFace): string {+ return `${pending.kind}:${pending.key}`+}++/** 交互正文:授权取「工具名: 原因」,提问取首个问题。 */+export function pendingDetail(pending: PendingInteractionFace): string {+ if (pending.kind === 'approval') {+ const reason = conciseReason(resolvedReason(pending))+ if (pending.toolName && reason)+ return `${pending.toolName}: ${reason}`+ return pending.toolName ?? reason+ }+ const first = pending.questions?.[0]+ return first?.question ?? first?.header ?? pending.toolName ?? ''+}++/** 授权原因只保留到第一个分句分隔符(中文/英文冒号、句号、换行)。 */+const REASON_CLAUSE_DELIMITER = /[::。\n]/+/** 授权原因长度上限:正文里还要放动作标签与工具名,原因留一行即可。 */+const MAX_REASON_CHARS = 60++/**+ * 授权原因只保留首个分句。+ *+ * `displayReason` 的后半段是给审计用的完整说明(例如「允许本次操作使用 x 权限:<沙箱拒绝+ * 详情>」),整段塞进系统通知会把真正有信息量的部分挤掉;界面里的授权卡片仍然显示全文。+ */+function conciseReason(reason: string): string {+ const clause = reason.split(REASON_CLAUSE_DELIMITER)[0]?.trim() ?? ''+ return boundText(clause || reason, MAX_REASON_CHARS)+}++function resolvedReason(pending: PendingInteractionFace): string {+ const display = pending.displayReason+ if (typeof display === 'string')+ return display+ if (display && typeof display === 'object') {+ const dict = display as Record<string, string>+ return dict.zh ?? dict.en ?? Object.values(dict)[0] ?? ''+ }+ return pending.reason ?? ''+}++/**+ * 通过官方待处理交互回答授权——通知上的「批准」按钮最终走这里。+ *+ * 只有同一次挂起期间注册过、且仍可回答的交互才能被外部回答;否则返回失败+ * (例如授权已在界面里处理过,或该交互已降级为不可回答)。+ *+ * `expectedIdentity` 是这条通知**当初展示**的那次挂起(`pendingIdentity`)。系统通知会在+ * 心里一直挂着直到用户处理它,所以一条过期的「批准」可能在原授权早已被界面处理、同一会话+ * 又冒出**新的**授权之后才被点到;身份对不上就拒绝,绝不回答「当前恰好挂着的那一个」。+ */+export async function approveInteraction(uiSession: UiSessionFace | undefined, sessionId: string, expectedIdentity?: string): Promise<DecideResult> {+ return decideApproval(uiSession, sessionId, 'allowed-once', expectedIdentity)+}++/** 通知上的「拒绝」按钮走这里,语义与界面里的拒绝一致。 */+export async function rejectInteraction(uiSession: UiSessionFace | undefined, sessionId: string, expectedIdentity?: string): Promise<DecideResult> {+ return decideApproval(uiSession, sessionId, 'rejected', expectedIdentity)+}++async function decideApproval(uiSession: UiSessionFace | undefined, sessionId: string, decision: ApprovalDecision, expectedIdentity?: string): Promise<DecideResult> {+ const pending = readPendingInteraction(uiSession, sessionId)+ if (!pending || pending.kind !== 'approval')+ return { ok: false, error: 'APPROVAL_UNAVAILABLE' }+ if (expectedIdentity !== undefined && pendingIdentity(pending) !== expectedIdentity)+ return { ok: false, error: 'APPROVAL_STALE' }+ if (pending.answerable === false || typeof pending.answer !== 'function')+ return { ok: false, error: 'APPROVAL_NOT_ANSWERABLE' }+ try {+ await pending.answer(decision)+ return { ok: true }+ }+ catch (error) {+ return { ok: false, error: error instanceof Error ? error.message : String(error) }+ }+}++/** 答案的题号必须与当前挂起的题目一一对应:数量和 id 都要对得上。 */+function answersMatchQuestions(pending: PendingInteractionFace, answers: readonly QuestionAnswerFace[]): boolean {+ const questions = pending.questions ?? []+ if (questions.length !== answers.length)+ return false+ const ids = new Set(questions.map(question => question.id))+ return answers.every(answer => ids.has(answer.id))+}++/**+ * 通过官方待处理交互提交一整批答案——通知里的输入框文本走这里。+ *+ * 系统通知渲染不了选项列表,所以把用户输入的自由文本当作官方的 `custom`(「其他」)答案回传,+ * `selected` 留空。宿主对回答的校验是「每道题各一条、按 id 对齐、缺一条就 BAD_ANSWER」+ * (见 `dsh-user-questions` 的 `answer()`),**只收完整批次**:一题一题地交会被拒收,+ * 多问题批次由 `question-wizard.ts` 在本地攒齐后再一次交过来。+ */+export async function answerQuestionBatch(uiSession: UiSessionFace | undefined, sessionId: string, answers: readonly QuestionAnswerFace[], expectedIdentity?: string): Promise<DecideResult> {+ const pending = readPendingInteraction(uiSession, sessionId)+ if (!pending || (pending.kind !== 'question' && pending.kind !== 'plan-review'))+ return { ok: false, error: 'QUESTION_UNAVAILABLE' }+ if (expectedIdentity !== undefined && pendingIdentity(pending) !== expectedIdentity)+ return { ok: false, error: 'QUESTION_STALE' }+ if (pending.answerable === false || typeof pending.answer !== 'function')+ return { ok: false, error: 'QUESTION_NOT_ANSWERABLE' }+ if (answers.length === 0 || answers.every(answer => answer.selected.length === 0 && !(answer.custom ?? '').trim()))+ return { ok: false, error: 'QUESTION_EMPTY' }+ if (!answersMatchQuestions(pending, answers))+ return { ok: false, error: 'QUESTION_STALE' }+ try {+ await pending.answer({ answers: [...answers] })+ return { ok: true }+ }+ catch (error) {+ return { ok: false, error: error instanceof Error ? error.message : String(error) }+ }+}diff --git a/packages/dsh-tauri-notification/src/client/service/decision.test.ts b/packages/dsh-tauri-notification/src/client/service/decision.test.tsnew file mode 100644index 00000000..38d69b02--- /dev/null+++ b/packages/dsh-tauri-notification/src/client/service/decision.test.ts@@ -0,0 +1,128 @@+import type { NotificationSettings } from '../types'+import { describe, expect, it } from 'vitest'+import { allowPendingNotification, allowTurnNotification, boundText, notificationTag } from './decision'++const settings: NotificationSettings = {+ turnComplete: 'background',+ approval: true,+ question: false,+ sound: 'default',+ customSound: null,+}++/** 宿主 `NOTIFICATION_SHIM_JS` 里 `sessionIdFromTag` 使用的同一条正则。 */+const SHIM_TAG_RE = /^dsh-notification-(?:pending-)?(.+)-\d+$/++describe('allowTurnNotification', () => {+ const base = { mode: 'background' as const, hostHidden: false, sessionId: 's1', currentSessionId: 's1' }++ it('never 模式一律不提醒', () => {+ expect(allowTurnNotification({ ...base, mode: 'never', hostHidden: true })).toBe(false)+ expect(allowTurnNotification({ ...base, mode: 'never', currentSessionId: 's2' })).toBe(false)+ })++ it('always 模式一律提醒', () => {+ expect(allowTurnNotification({ ...base, mode: 'always' })).toBe(true)+ expect(allowTurnNotification({ ...base, mode: 'always', currentSessionId: undefined })).toBe(true)+ })++ it('background 在窗口隐藏时提醒', () => {+ expect(allowTurnNotification({ ...base, hostHidden: true })).toBe(true)+ })++ it('background 在用户切到别的会话时提醒', () => {+ expect(allowTurnNotification({ ...base, currentSessionId: 's2' })).toBe(true)+ })++ it('background 在窗口可见且仍盯着同一会话时不提醒', () => {+ expect(allowTurnNotification(base)).toBe(false)+ })++ it('background 在拿不到当前会话时仍提醒:只有确知「就停在这个会话上」才抑制', () => {+ // 与参考实现 `source/dsh-notification` 的 shouldShow 一致:读不到当前会话(会话投影+ // 缺席、或界面还没打开任何会话)时无法证明用户正盯着它,宁可多提醒一次。+ expect(allowTurnNotification({ ...base, currentSessionId: undefined })).toBe(true)+ })+})++describe('allowPendingNotification', () => {+ const gate = { hostHidden: false, sessionId: 's1', currentSessionId: 's1' }+ /** 一定不抑制的位置(窗口在后台),用来单纯验证开关。 */+ const background = { ...gate, hostHidden: true }++ it('按类别读取各自的开关', () => {+ expect(allowPendingNotification(settings, 'approval', background)).toBe(true)+ expect(allowPendingNotification(settings, 'question', background)).toBe(false)+ expect(allowPendingNotification({ ...settings, approval: false, question: true }, 'approval', background)).toBe(false)+ expect(allowPendingNotification({ ...settings, approval: false, question: true }, 'question', background)).toBe(true)+ })++ it('窗口在前台且就停在这个会话上时不提醒:审批框 / 提问就在眼前', () => {+ expect(allowPendingNotification({ ...settings, question: true }, 'question', gate)).toBe(false)+ expect(allowPendingNotification({ ...settings, approval: true }, 'approval', gate)).toBe(false)+ })++ it('「始终」时窗口在前台也提醒:用户明确要求不必省这一条', () => {+ const always = { ...settings, turnComplete: 'always' as const, question: true }+ expect(allowPendingNotification(always, 'question', gate)).toBe(true)+ expect(allowPendingNotification({ ...always, approval: true }, 'approval', gate)).toBe(true)+ // 「始终」只解除位置抑制,不越过各自的开关。+ expect(allowPendingNotification({ ...always, question: false }, 'question', gate)).toBe(false)+ })++ it('「从不」只管轮次完成,挂起交互仍遵循「看着就不打扰」', () => {+ const never = { ...settings, turnComplete: 'never' as const, question: true }+ expect(allowPendingNotification(never, 'question', gate)).toBe(false)+ expect(allowPendingNotification(never, 'question', { ...gate, hostHidden: true })).toBe(true)+ })++ it('窗口在后台时提醒', () => {+ expect(allowPendingNotification({ ...settings, question: true }, 'question', background)).toBe(true)+ })++ it('用户切到别的会话时提醒', () => {+ expect(allowPendingNotification({ ...settings, question: true }, 'question', { ...gate, currentSessionId: 's2' })).toBe(true)+ })++ it('拿不到当前会话时仍提醒:只有确知「就停在这个会话上」才抑制', () => {+ expect(allowPendingNotification({ ...settings, question: true }, 'question', { ...gate, currentSessionId: undefined })).toBe(true)+ })++ it('开关关掉时任何位置都不提醒', () => {+ expect(allowPendingNotification({ ...settings, approval: false }, 'approval', background)).toBe(false)+ expect(allowPendingNotification({ ...settings, approval: false }, 'approval', { ...gate, currentSessionId: 's2' })).toBe(false)+ })+})++describe('notificationTag', () => {+ it('轮次完成 tag 可被宿主演解回 sessionId', () => {+ expect(notificationTag('session-abc', 'turn', 3)).toBe('dsh-notification-session-abc-3')+ expect('dsh-notification-session-abc-3'.match(SHIM_TAG_RE)?.[1]).toBe('session-abc')+ })++ it('待处理交互 tag 同样可被宿主演解回 sessionId', () => {+ expect(notificationTag('session-abc', 'approval', 7)).toBe('dsh-notification-pending-session-abc-7')+ expect('dsh-notification-pending-session-abc-7'.match(SHIM_TAG_RE)?.[1]).toBe('session-abc')+ })++ it('sessionId 含连字符或数字时仍能反解(贪婪匹配回溯到最后一节序号)', () => {+ const tag = notificationTag('a-1-b', 'turn', 12)+ expect(tag.match(SHIM_TAG_RE)?.[1]).toBe('a-1-b')+ })+})++describe('boundText', () => {+ it('去除首尾空白', () => {+ expect(boundText(' 已完成 ', 400)).toBe('已完成')+ })++ it('未超长时原样返回', () => {+ expect(boundText('abc', 3)).toBe('abc')+ })++ it('超长时截断并补省略号,总长等于上限', () => {+ const bounded = boundText('x'.repeat(50), 10)+ expect(bounded).toBe(`${'x'.repeat(9)}…`)+ expect(bounded).toHaveLength(10)+ })+})diff --git a/packages/dsh-tauri-notification/src/client/service/decision.ts b/packages/dsh-tauri-notification/src/client/service/decision.tsnew file mode 100644index 00000000..b638f4ba--- /dev/null+++ b/packages/dsh-tauri-notification/src/client/service/decision.ts@@ -0,0 +1,86 @@+import type { NotificationKind, NotificationSettings, TurnCompleteMode } from '../types'++/** 通知门控所处的位置:宿主窗口在不在后台,以及用户正在看哪个会话。 */+export interface FocusGateInput {+ /**+ * 宿主窗口是否隐藏/最小化/失焦。+ *+ * iframe 内的 `document.visibilityState` 已由宿主窗口补丁(`NOTIFICATION_SHIM_JS`)+ * 映射到宿主窗口状态,因此这里直接用标准 API 即可。+ */+ readonly hostHidden: boolean+ /** 产生通知的会话。 */+ readonly sessionId: string+ /** 当前正在查看的会话。 */+ readonly currentSessionId: string | undefined+}++/** 轮次完成通知的触发条件。 */+export interface TurnGateInput extends FocusGateInput {+ /** 用户设置:从不 / 仅在未聚焦时 / 始终。 */+ readonly mode: TurnCompleteMode+}++/**+ * 用户是否正停在产生通知的那个会话上。+ *+ * 语义与 ChatGPT 面板一致:窗口不在前台,**或**用户已切到别的会话,都算「未聚焦」。+ *+ * 当前会话读不到时(会话投影缺席 / 还没打开任何会话)按「未聚焦」处理:参考实现+ * `source/dsh-notification/src/client/notifier.ts` 的 `shouldShow` 也只在能确定+ * 「用户就停在这个会话上」时才抑制,宁可多提醒一次也不能漏掉一次。+ */+function watchingSession(input: FocusGateInput): boolean {+ return !input.hostHidden && input.currentSessionId === input.sessionId+}++/** 轮次完成是否该提醒。`background` 只在用户没盯着这个会话时才提醒。 */+export function allowTurnNotification(input: TurnGateInput): boolean {+ if (input.mode === 'never')+ return false+ if (input.mode === 'always')+ return true+ return !watchingSession(input)+}++/**+ * 权限 / 提问是否该提醒。+ *+ * 挂起交互意味着 DSH 正卡在那里等用户:窗口在前台、且用户就停在这个会话上时,审批框或+ * 提问就在眼前,再弹一条系统通知纯属打扰(参考实现 `source/dsh-notification/src/client/index.ts`+ * 的 pending runner 调的就是同一个 `shouldShow`)。窗口在后台、或用户已经切到别的会话时照旧+ * 提醒;当前会话读不到时同样按「未聚焦」处理。+ *+ * 用户的「提醒时机」选到 `always` 时这层抑制整体让位:既然连「我正看着这个会话」都要提醒,+ * 挂起交互当然也照提醒(参考实现里完成通知与 pending runner 共用同一个 `backgroundOnly`+ * 开关,移植成三态后只有 `always` 明确表示「不必替我省略」)。`never` 只管轮次完成,+ * 挂起交互仍按「看着就不打扰」抑制——宁可少弹一条,也不要在用户明确要求安静时打扰他。+ */+export function allowPendingNotification(+ settings: NotificationSettings,+ kind: 'approval' | 'question',+ gate: FocusGateInput,+): boolean {+ if (kind === 'approval' ? !settings.approval : !settings.question)+ return false+ if (settings.turnComplete === 'always')+ return true+ return !watchingSession(gate)+}++/**+ * 通知 tag。+ *+ * 必须命中宿主补丁的 `sessionIdFromTag`+ * (`/^dsh-notification-(?:pending-)?(.+)-\d+$/`),点击回传时才能反解出 sessionId。+ */+export function notificationTag(sessionId: string, kind: NotificationKind, sequence: number): string {+ const prefix = kind === 'turn' ? 'dsh-notification' : 'dsh-notification-pending'+ return `${prefix}-${sessionId}-${sequence}`+}++/** 截断正文,避免超长标题/命令撑爆系统通知。 */+export function boundText(text: string, maxChars: number): string {+ const trimmed = text.trim()+ return trimmed.length <= maxChars ? trimmed : `${trimmed.slice(0, maxChars - 1)}…`+}diff --git a/packages/dsh-tauri-notification/src/client/service/native.test.ts b/packages/dsh-tauri-notification/src/client/service/native.test.tsnew file mode 100644index 00000000..5cdccfe7--- /dev/null+++ b/packages/dsh-tauri-notification/src/client/service/native.test.ts@@ -0,0 +1,99 @@+import { beforeEach, describe, expect, it, vi } from 'vitest'+import { showNativeNotification } from './native'++/** 一次 `new Notification(...)` 的构造参数(宿主补丁就是从这两个参数取值发给壳层的)。 */+interface Construction {+ title: string+ options: Record<string, unknown>+}++const constructions: Construction[] = []+const instances: FakeNotification[] = []++interface FakeActionEvent {+ action?: string+ inputValue?: string | null+}++/** 宿主补丁替换过的 `window.Notification` 替身:记录构造参数并暴露点击/按钮回灌钩子。 */+class FakeNotification {+ static permission = 'granted'+ static requestPermission = () => Promise.resolve('granted')+ readonly tag = ''+ onclick: ((event: Event) => void) | null = null+ onaction: ((event: FakeActionEvent) => void) | null = null++ constructor(title: string, options?: Record<string, unknown>) {+ constructions.push({ title, options: options ?? {} })+ instances.push(this)+ }+}++beforeEach(() => {+ constructions.length = 0+ instances.length = 0+ vi.stubGlobal('Notification', FakeNotification)+})++describe('showNativeNotification', () => {+ it('把通知描述透传成宿主补丁的 options(默认不静音)', () => {+ showNativeNotification({ title: '标题', body: '正文', tag: 'tag-1', sessionId: 's-1' })++ expect(constructions).toEqual([{+ title: '标题',+ options: {+ body: '正文',+ tag: 'tag-1',+ sessionId: 's-1',+ requireInteraction: false,+ silent: false,+ },+ }])+ })++ it('透传 requireInteraction 与 silent', () => {+ showNativeNotification({ title: '标题', body: '正文', tag: 'tag-1', sessionId: 's-1', requireInteraction: true, silent: true })++ expect(constructions[0].options).toMatchObject({ requireInteraction: true, silent: true })+ })++ it('actions 只补写按钮带输入框时才需要的字段', () => {+ showNativeNotification({+ title: '标题',+ body: '正文',+ tag: 'tag-1',+ sessionId: 's-1',+ actions: [+ { id: 'approve', title: '批准' },+ { id: 'reply', title: '回复', input: true, inputPlaceholder: '输入回复内容', inputButtonTitle: '发送' },+ ],+ })++ expect(constructions[0].options.actions).toEqual([+ { action: 'approve', title: '批准' },+ { action: 'reply', title: '回复', input: true, inputPlaceholder: '输入回复内容', inputButtonTitle: '发送' },+ ])+ })++ it('点通知本体回调 onClick', () => {+ const onClick = vi.fn()+ showNativeNotification({ title: '标题', body: '正文', tag: 'tag-1', sessionId: 's-1', onClick })++ instances[0].onclick?.(new Event('click'))++ expect(onClick).toHaveBeenCalledTimes(1)+ })++ it('按钮回灌:把空输入折成 null,有文本则原样回传 action id', () => {+ const onAction = vi.fn()+ showNativeNotification({ title: '标题', body: '正文', tag: 'tag-1', sessionId: 's-1', onAction })++ instances[0].onaction?.({ action: 'approve', inputValue: '' })+ instances[0].onaction?.({ action: 'reply', inputValue: '就这样' })++ expect(onAction.mock.calls).toEqual([+ ['approve', null],+ ['reply', '就这样'],+ ])+ })+})diff --git a/packages/dsh-tauri-notification/src/client/service/native.ts b/packages/dsh-tauri-notification/src/client/service/native.tsnew file mode 100644index 00000000..81b01581--- /dev/null+++ b/packages/dsh-tauri-notification/src/client/service/native.ts@@ -0,0 +1,81 @@+import type { NativeNotificationInput } from '../types'++/**+ * 宿主窗口补丁读取的 actions 项(`{ action, title, … }`,见 `NOTIFICATION_SHIM_JS`)。+ *+ * `input` / `inputPlaceholder` / `inputButtonTitle` 由补丁原样透传给宿主:Windows 用它们+ * 声明 toast 的 `<input>` 文本框,其他平台忽略。+ */+interface ShimAction {+ action: string+ title: string+ input?: boolean+ inputPlaceholder?: string+ inputButtonTitle?: string+}++interface ShimNotificationOptions {+ body?: string+ tag?: string+ sessionId?: string+ requireInteraction?: boolean+ /** Windows:置 true 让 toast 自己保持静音(提示音由帧内播放,见 `NativeNotificationInput.silent`)。 */+ silent?: boolean+ actions?: ShimAction[]+}++/** 宿主补丁回调 `onaction` 时给出的事件体。 */+interface ShimActionEvent {+ action?: string+ /** 带输入框的按钮:用户填的文本;没填时宿主给空串。 */+ inputValue?: string | null+}++/** 宿主补丁替换过的 Notification 额外带回调属性(标准 Notification 没有 `onaction`)。 */+interface ShimNotification {+ onclick: ((event: Event) => void) | null+ onaction?: ((event: ShimActionEvent) => void) | null+}++/**+ * 弹一条原生通知,并接住它的点击与按钮回调。+ *+ * 不直接 `invoke` Tauri 命令,而是走宿主窗口注入的 `window.Notification` 补丁:+ * 补丁把构造参数 postMessage 给宿主窗口(`dsh://native-notification`),宿主再调+ * `tauri-plugin-notifications` 发原生通知;等通知被点击(`onclick`)或按下按钮+ * (`onaction`)时,宿主通过 `dsh://notification-clicked` 回灌并回调本对象。+ */+export function showNativeNotification(input: NativeNotificationInput): void {+ if (typeof Notification === 'undefined')+ return+ const options: ShimNotificationOptions = {+ body: input.body,+ tag: input.tag,+ sessionId: input.sessionId,+ requireInteraction: input.requireInteraction ?? false,+ silent: input.silent ?? false,+ }+ if (input.actions && input.actions.length > 0) {+ options.actions = input.actions.map((action) => {+ const shim: ShimAction = { action: action.id, title: action.title }+ if (action.input) {+ shim.input = true+ if (action.inputPlaceholder)+ shim.inputPlaceholder = action.inputPlaceholder+ if (action.inputButtonTitle)+ shim.inputButtonTitle = action.inputButtonTitle+ }+ return shim+ })+ }+ const notification = new Notification(input.title, options as unknown as NotificationOptions) as Notification & ShimNotification+ notification.onclick = () => {+ input.onClick?.()+ }+ if (input.onAction) {+ notification.onaction = (event) => {+ const value = event?.inputValue+ input.onAction?.(String(event?.action ?? ''), typeof value === 'string' && value.length > 0 ? value : null)+ }+ }+}diff --git a/packages/dsh-tauri-notification/src/client/service/question-wizard.test.ts b/packages/dsh-tauri-notification/src/client/service/question-wizard.test.tsnew file mode 100644index 00000000..dbe22aed--- /dev/null+++ b/packages/dsh-tauri-notification/src/client/service/question-wizard.test.ts@@ -0,0 +1,92 @@+import type { PendingInteractionFace, PendingQuestionFace } from '../types'+import { describe, expect, it } from 'vitest'+import { advanceQuestionWizard, canDriveQuestions, questionWizardStep, syncQuestionWizard } from './question-wizard'++function questionPending(questions: PendingQuestionFace[], key = 'k1'): PendingInteractionFace {+ return { key, kind: 'question', sessionId: 's1', questions, answerable: true, answer: async () => {} }+}++describe('canDriveQuestions', () => {+ it('每道题都有 id 时才驱动得了', () => {+ expect(canDriveQuestions(questionPending([{ id: 'q1', question: '选哪个?' }]))).toBe(true)+ expect(canDriveQuestions(questionPending([{ id: 'q1' }, { id: 'q2' }]))).toBe(true)+ })++ it('没有题、或有一题缺 id 时驱动不了', () => {+ expect(canDriveQuestions(questionPending([]))).toBe(false)+ expect(canDriveQuestions(questionPending([{ id: 'q1' }, { question: '没有 id' }]))).toBe(false)+ expect(canDriveQuestions(questionPending([{ id: '' }]))).toBe(false)+ })+})++describe('questionWizardStep', () => {+ it('单问题批次只有一题', () => {+ const step = questionWizardStep('single', questionPending([{ id: 'q1', question: '选哪个?' }]))+ expect(step).toMatchObject({ identity: 'question:k1', index: 0, total: 1, id: 'q1' })+ })++ it('多问题批次从第一题开始,答一题推进一题', () => {+ const pending = questionPending([{ id: 'q1', question: '第一题' }, { id: 'q2', question: '第二题' }])+ expect(questionWizardStep('chain', pending)?.index).toBe(0)+ expect(advanceQuestionWizard('chain', pending, '第一个回答')).toBeUndefined()+ const next = questionWizardStep('chain', pending)+ expect(next).toMatchObject({ index: 1, total: 2, id: 'q2' })+ })++ it('驱动不了的批返回 undefined', () => {+ expect(questionWizardStep('broken', questionPending([{ question: '没有 id' }]))).toBeUndefined()+ expect(questionWizardStep('empty', questionPending([]))).toBeUndefined()+ })+})++describe('advanceQuestionWizard', () => {+ it('最后一题答完给出完整批次,按题目顺序对齐', () => {+ const pending = questionPending([{ id: 'q1' }, { id: 'q2' }])+ expect(advanceQuestionWizard('batch', pending, '第一个')).toBeUndefined()+ expect(advanceQuestionWizard('batch', pending, '第二个')).toEqual([+ { id: 'q1', selected: [], custom: '第一个' },+ { id: 'q2', selected: [], custom: '第二个' },+ ])+ })++ it('单问题批次一次答完就提交', () => {+ const pending = questionPending([{ id: 'q1', question: '选哪个?' }])+ expect(advanceQuestionWizard('alone', pending, ' 42 ')).toEqual([{ id: 'q1', selected: [], custom: '42' }])+ })++ it('空文本既不记草稿也不推进题号', () => {+ const pending = questionPending([{ id: 'q1' }, { id: 'q2' }])+ expect(advanceQuestionWizard('blank', pending, ' ')).toBeUndefined()+ expect(questionWizardStep('blank', pending)?.index).toBe(0)+ })++ it('提交后进度清空,下一次从第一题重新开始', () => {+ const pending = questionPending([{ id: 'q1' }])+ advanceQuestionWizard('again', pending, '答案')+ expect(questionWizardStep('again', pending)?.index).toBe(0)+ })+})++describe('syncQuestionWizard', () => {+ it('待处理交互换了身份就丢掉进度', () => {+ const pending = questionPending([{ id: 'q1' }, { id: 'q2' }])+ advanceQuestionWizard('switch', pending, '第一个')+ expect(questionWizardStep('switch', pending)?.index).toBe(1)+ syncQuestionWizard('switch', 'question:k2')+ expect(questionWizardStep('switch', pending)?.index).toBe(0)+ })++ it('身份不变时保留进度', () => {+ const pending = questionPending([{ id: 'q1' }, { id: 'q2' }])+ advanceQuestionWizard('keep', pending, '第一个')+ syncQuestionWizard('keep', 'question:k1')+ expect(questionWizardStep('keep', pending)?.index).toBe(1)+ })++ it('挂起消失时丢掉进度', () => {+ const pending = questionPending([{ id: 'q1' }, { id: 'q2' }])+ advanceQuestionWizard('gone', pending, '第一个')+ syncQuestionWizard('gone', undefined)+ expect(questionWizardStep('gone', pending)?.index).toBe(0)+ })+})diff --git a/packages/dsh-tauri-notification/src/client/service/question-wizard.ts b/packages/dsh-tauri-notification/src/client/service/question-wizard.tsnew file mode 100644index 00000000..66814d6f--- /dev/null+++ b/packages/dsh-tauri-notification/src/client/service/question-wizard.ts@@ -0,0 +1,117 @@+import type { PendingInteractionFace, PendingQuestionFace, QuestionAnswerFace } from '../types'+import { pendingIdentity } from './approval'++/**+ * 多问题批次的「一题一轮」作答进度。+ *+ * 系统通知只有一个文本框,而宿主的校验是「每道题各一条答案,缺一条就 BAD_ANSWER」+ * (见 `dsh-user-questions` 的 `answer()`):所以通知里没法一题一题地提交,只能先攒着,+ * 攒齐整批再一次性提交——这正是官方向导的做法(它把进度存在本地,最后提交完整批次)。+ */+interface WizardProgress {+ /** 进度归属的待处理交互身份:身份一变就作废(答完了 / 界面接手了 / 换了新提问)。 */+ readonly identity: string+ /** 当前该问第几题(0 起)。 */+ index: number+ /** 题目 id → 用户输入的自由文本(官方的 `custom` 答案)。 */+ readonly drafts: Map<string, string>+}++/** 通知里当前该问的一题。 */+export interface QuestionWizardStep {+ /** 待处理交互身份,随通知一起记下,作答时用它挡掉过期点击。 */+ readonly identity: string+ /** 0 起的题号与总题数,正文用它写「提问 2/3」。 */+ readonly index: number+ readonly total: number+ readonly id: string+ readonly question: PendingQuestionFace+}++/** 每个会话一份进度:宿主的待处理交互是会话级的,同一会话同时只有一个。 */+const progressBySession = new Map<string, WizardProgress>()++/** 官方作答按 id 回传,id 缺失的题通知里答不了。 */+function usableId(question: PendingQuestionFace | undefined): string | undefined {+ const id = question?.id+ return typeof id === 'string' && id.length > 0 ? id : undefined+}++function progressFor(sessionId: string, identity: string): WizardProgress {+ const existing = progressBySession.get(sessionId)+ if (existing && existing.identity === identity)+ return existing+ const fresh: WizardProgress = { identity, index: 0, drafts: new Map() }+ progressBySession.set(sessionId, fresh)+ return fresh+}++/**+ * 这个待处理提问能不能在通知里驱动:**每道题都得有可用 id**。+ *+ * 只要有一题缺 id,整批就永远攒不齐(提交会被宿主判 BAD_ANSWER),此时不如不给回复按钮,+ * 让用户点通知回会话界面用官方向导作答。+ */+export function canDriveQuestions(pending: PendingInteractionFace): boolean {+ const questions = pending.questions ?? []+ return questions.length > 0 && questions.every(question => usableId(question) !== undefined)+}++/** 当前该问的一题;驱动不了(没题 / 缺 id)时为 `undefined`。 */+export function questionWizardStep(sessionId: string, pending: PendingInteractionFace): QuestionWizardStep | undefined {+ if (!canDriveQuestions(pending))+ return undefined+ const questions = pending.questions ?? []+ const progress = progressFor(sessionId, pendingIdentity(pending))+ // 题目变少(换了一批题)时把题号收回来,避免指向不存在的题。+ if (progress.index >= questions.length)+ progress.index = 0+ const index = progress.index+ const question = questions[index]+ const id = usableId(question)+ if (question === undefined || id === undefined)+ return undefined+ return { identity: progress.identity, index, total: questions.length, id, question }+}++/**+ * 记下这一轮输入的自由文本,并推进到下一题。+ *+ * @returns 整批已答完时给出符合官方契约的完整答案批次(交给调用方提交);还有下一题时返回+ * `undefined`(调用方据此再弹一条通知)。+ */+export function advanceQuestionWizard(sessionId: string, pending: PendingInteractionFace, text: string): QuestionAnswerFace[] | undefined {+ const step = questionWizardStep(sessionId, pending)+ const custom = text.trim()+ if (!step || !custom)+ return undefined+ const progress = progressFor(sessionId, step.identity)+ progress.drafts.set(step.id, custom)+ if (step.index < step.total - 1) {+ progress.index = step.index + 1+ return undefined+ }+ const answers: QuestionAnswerFace[] = []+ for (const question of pending.questions ?? []) {+ const id = usableId(question)+ const draft = id === undefined ? undefined : progress.drafts.get(id)+ // 有题没答到就不提交:攒不齐的批次宿主不收,交回会话界面作答。+ if (id === undefined || draft === undefined || draft === '')+ return undefined+ answers.push({ id, selected: [], custom: draft })+ }+ progressBySession.delete(sessionId)+ return answers+}++/**+ * 对齐观察到的待处理交互:身份一变就丢掉进度。+ *+ * 身份变了意味着这条批次的去向已经不由我们决定(在会话界面答完了、被新提问顶掉了),+ * 留着旧进度只会让下一轮指向错误的题号。+ */+export function syncQuestionWizard(sessionId: string, identity: string | undefined): void {+ const existing = progressBySession.get(sessionId)+ if (existing && existing.identity !== identity)+ progressBySession.delete(sessionId)+}diff --git a/packages/dsh-tauri-notification/src/client/service/settings.test.ts b/packages/dsh-tauri-notification/src/client/service/settings.test.tsnew file mode 100644index 00000000..8ec93050--- /dev/null+++ b/packages/dsh-tauri-notification/src/client/service/settings.test.ts@@ -0,0 +1,108 @@+import { beforeEach, describe, expect, it, vi } from 'vitest'++// `settings.ts` 的模块级 `createStorage(...)` 会走 `dsh-tauri/client` 的运行时模块表,+// 在 node 下不可求值;这里按仓库既有做法(见 dsh-tauri-ssh 的客户端用例)打桩成内存存储。+// `vi.hoisted` 保证工厂在 import 之前就能拿到这份 Map。+const { memory } = vi.hoisted(() => ({ memory: new Map<string, unknown>() }))++vi.mock('dsh-tauri/client', () => ({+ createStorage: () => ({+ getItem: async (key: string) => memory.get(key) ?? null,+ setItem: async (key: string, value: unknown) => { memory.set(key, value) },+ }),+ localStorageDriver: () => ({}),+}))++const { DEFAULT_SETTINGS, loadSettings, parseSettings, saveSettings } = await import('./settings')++/** 一个合法的自定义提示音(data URL,长度在限制内)。 */+const SOUND_DATA_URL = `data:audio/wav;base64,${'A'.repeat(64)}`++beforeEach(() => {+ memory.clear()+})++describe('dEFAULT_SETTINGS', () => {+ it('与参考实现一致:完成提醒仅在未聚焦时、权限与提问开启、默认提示音', () => {+ expect(DEFAULT_SETTINGS).toEqual({+ turnComplete: 'background',+ approval: true,+ question: true,+ sound: 'default',+ customSound: null,+ })+ })++ it('被冻结,避免调用方就地改写共享默认值', () => {+ expect(Object.isFrozen(DEFAULT_SETTINGS)).toBe(true)+ })+})++describe('parseSettings', () => {+ it('完整合法值原样通过', () => {+ const raw = { turnComplete: 'always', approval: false, question: false, sound: 'classic', customSound: SOUND_DATA_URL }+ expect(parseSettings(raw)).toEqual(raw)+ })++ it('非对象输入整体退化为默认值', () => {+ expect(parseSettings(undefined)).toEqual(DEFAULT_SETTINGS)+ expect(parseSettings(null)).toEqual(DEFAULT_SETTINGS)+ expect(parseSettings('nope')).toEqual(DEFAULT_SETTINGS)+ expect(parseSettings(42)).toEqual(DEFAULT_SETTINGS)+ })++ it('未知枚举值退回默认,而不是透传脏数据', () => {+ expect(parseSettings({ turnComplete: 'sometimes', sound: 'loud' })).toEqual(DEFAULT_SETTINGS)+ })++ it('缺字段时逐项补默认值', () => {+ expect(parseSettings({ turnComplete: 'never' })).toEqual({ ...DEFAULT_SETTINGS, turnComplete: 'never' })+ })++ it('非布尔开关退回默认开启', () => {+ expect(parseSettings({ approval: 'yes', question: 0 })).toEqual(DEFAULT_SETTINGS)+ expect(parseSettings({ approval: false, question: false })).toEqual({ ...DEFAULT_SETTINGS, approval: false, question: false })+ })++ it('自定义提示音必须是 data URL 且在长度上限内', () => {+ expect(parseSettings({ sound: 'custom', customSound: SOUND_DATA_URL }).customSound).toBe(SOUND_DATA_URL)+ expect(parseSettings({ sound: 'custom', customSound: 'https://example.com/a.wav' }).customSound).toBeNull()+ expect(parseSettings({ sound: 'custom', customSound: '' }).customSound).toBeNull()+ expect(parseSettings({ sound: 'custom', customSound: `data:audio/wav;base64,${'A'.repeat(760_001)}` }).customSound).toBeNull()+ })++ it('选了自定义却没有可用音频时退回默认音,避免「选了却没声音」', () => {+ expect(parseSettings({ sound: 'custom' }).sound).toBe('default')+ expect(parseSettings({ sound: 'custom', customSound: 'not-a-data-url' }).sound).toBe('default')+ expect(parseSettings({ sound: 'custom', customSound: SOUND_DATA_URL }).sound).toBe('custom')+ })++ it('非自定义音时仍保留已存的自定义数据,便于切回自定义', () => {+ expect(parseSettings({ sound: 'none', customSound: SOUND_DATA_URL }).customSound).toBe(SOUND_DATA_URL)+ expect(parseSettings({ sound: 'none' }).sound).toBe('none')+ })+})++describe('loadSettings', () => {+ it('存储为空时退化为默认值', async () => {+ await expect(loadSettings()).resolves.toEqual(DEFAULT_SETTINGS)+ })++ it('读取已存设置时收敛成合法值', async () => {+ memory.set('settings', { turnComplete: 'always', approval: false, sound: 'classic' })+ await expect(loadSettings()).resolves.toEqual({+ turnComplete: 'always',+ approval: false,+ question: true,+ sound: 'classic',+ customSound: null,+ })+ })+})++describe('saveSettings', () => {+ it('写回不含运行时态(hydrated)的纯设置', async () => {+ await expect(saveSettings({ ...DEFAULT_SETTINGS, turnComplete: 'never' })).resolves.toEqual({ ok: true })+ expect(memory.get('settings')).toEqual({ ...DEFAULT_SETTINGS, turnComplete: 'never' })+ })+})diff --git a/packages/dsh-tauri-notification/src/client/service/settings.ts b/packages/dsh-tauri-notification/src/client/service/settings.tsnew file mode 100644index 00000000..bdec8dab--- /dev/null+++ b/packages/dsh-tauri-notification/src/client/service/settings.ts@@ -0,0 +1,81 @@+import type { NotificationSettings } from '../types'+import { createStorage, localStorageDriver } from 'dsh-tauri/client'+import { PLUGIN_ID } from '../../shared/constants'++/** 存储键:unstorage 的 base 已隔离到插件自身命名空间。 */+const SETTINGS_KEY = 'settings'++/** 自定义提示音的 data URL 上限,与 512 KB 的原始文件上限留出 base64 膨胀余量。 */+const MAX_CUSTOM_SOUND_CHARS = 760_000++const TURN_MODES = ['never', 'background', 'always'] as const+const SOUNDS = ['default', 'classic', 'none', 'custom'] as const++/** 默认设置:与参考实现(问题/权限开、完成提醒仅在未聚焦时、默认提示音)一致。 */+export const DEFAULT_SETTINGS: NotificationSettings = Object.freeze({+ turnComplete: 'background',+ approval: true,+ question: true,+ sound: 'default',+ customSound: null,+})++const storage = createStorage({ driver: localStorageDriver({ base: PLUGIN_ID }) })++function asBoolean(value: unknown, fallback: boolean): boolean {+ return typeof value === 'boolean' ? value : fallback+}++function asCustomSound(value: unknown): string | null {+ if (typeof value !== 'string' || !value.startsWith('data:') || value.length > MAX_CUSTOM_SOUND_CHARS)+ return null+ return value+}++/** 把任意来源(本地存储、旧版本写入的残缺值)收敛成合法设置。 */+export function parseSettings(raw: unknown): NotificationSettings {+ const source: Record<string, unknown> = raw && typeof raw === 'object' ? raw as Record<string, unknown> : {}+ const turnComplete = typeof source.turnComplete === 'string' && (TURN_MODES as readonly string[]).includes(source.turnComplete)+ ? source.turnComplete as NotificationSettings['turnComplete']+ : DEFAULT_SETTINGS.turnComplete+ const customSound = asCustomSound(source.customSound)+ const picked = typeof source.sound === 'string' && (SOUNDS as readonly string[]).includes(source.sound)+ ? source.sound as NotificationSettings['sound']+ : DEFAULT_SETTINGS.sound+ return {+ turnComplete,+ approval: asBoolean(source.approval, DEFAULT_SETTINGS.approval),+ question: asBoolean(source.question, DEFAULT_SETTINGS.question),+ // 选自定义但没有可用的音频数据时退回默认音,避免「选了却没声音」。+ sound: picked === 'custom' && !customSound ? DEFAULT_SETTINGS.sound : picked,+ customSound,+ }+}++export interface SaveSettingsResult {+ ok: boolean+ error?: string+}++/** 读取设置;任何异常(无 localStorage、配额、解析失败)都退化为默认值。 */+export async function loadSettings(): Promise<NotificationSettings> {+ try {+ return parseSettings(await storage.getItem(SETTINGS_KEY))+ }+ catch (error) {+ console.warn(`[${PLUGIN_ID}] failed to read settings`, error)+ return { ...DEFAULT_SETTINGS }+ }+}++/** 写入设置;失败只记录日志,UI 永远以内存态为准。 */+export async function saveSettings(settings: NotificationSettings): Promise<SaveSettingsResult> {+ try {+ await storage.setItem(SETTINGS_KEY, { ...settings })+ return { ok: true }+ }+ catch (error) {+ console.warn(`[${PLUGIN_ID}] failed to save settings`, error)+ return { ok: false, error: error instanceof Error ? error.message : String(error) }+ }+}diff --git a/packages/dsh-tauri-notification/src/client/service/sound-assets.ts b/packages/dsh-tauri-notification/src/client/service/sound-assets.tsnew file mode 100644index 00000000..7e8ee901--- /dev/null+++ b/packages/dsh-tauri-notification/src/client/service/sound-assets.ts@@ -0,0 +1,78 @@+import type { BuiltinNotificationSound } from '../types'+import { PLUGIN_ID } from '../../shared/constants'++/**+ * 内置提示音资源(`public/notification.wav`、`public/classic.wav`)。+ *+ * 插件客户端跑在 DSH 的 iframe 里,与桌面壳层的 `public/` 不同源,直接+ * `new Audio('/notification.wav')` 只会 404;壳层读成 data URL 后按下面的协议送进来,+ * 这里只负责缓存与补齐。+ *+ * 协议(与 `src/layout/components/iframe.tsx` 的通知桥一致):+ * - iframe → 壳层:`{ type: 'dsh://notification-sounds:request' }`+ * - 壳层 → iframe:`{ type: 'dsh://notification-sounds', sounds: { default, classic } }`+ */+export const SOUNDS_REQUEST_MESSAGE = 'dsh://notification-sounds:request'+export const SOUNDS_MESSAGE = 'dsh://notification-sounds'++/** 内置音效 id(`NotificationSound` 里除 `none` / `custom` 之外的两项)。 */+const BUILTIN_KEYS: readonly BuiltinNotificationSound[] = ['default', 'classic']++const assets = new Map<BuiltinNotificationSound, string>()+let listening = false++/** 只认音频 data URL:桥消息一律按不可信输入处理。 */+function isAudioDataUrl(value: unknown): value is string {+ return typeof value === 'string' && value.startsWith('data:audio/')+}++/** 记录壳层送来的音效,返回是否至少认出一条。 */+function setBuiltinSounds(sources: unknown): boolean {+ if (sources === null || typeof sources !== 'object')+ return false+ const record = sources as Record<string, unknown>+ let filled = false+ for (const key of BUILTIN_KEYS) {+ const source = record[key]+ if (isAudioDataUrl(source)) {+ assets.set(key, source)+ filled = true+ }+ }+ return filled+}++/** 内置音效的 data URL;壳层还没送到时为 `undefined`,调用方退回合成音。 */+export function builtinSound(sound: BuiltinNotificationSound): string | undefined {+ return assets.get(sound)+}++/** 监听壳层推送的音效(幂等,注册一次即可)。 */+export function listenBuiltinSounds(): void {+ if (listening || typeof window === 'undefined')+ return+ listening = true+ window.addEventListener('message', (event: MessageEvent<unknown>) => {+ const data = event.data as { type?: unknown, sounds?: unknown } | null+ if (!data || typeof data !== 'object' || data.type !== SOUNDS_MESSAGE)+ return+ setBuiltinSounds(data.sounds)+ })+}++/**+ * 向壳层索要内置音效。+ *+ * 拿不到时静默返回:帧内会退回合成音,通知本身不受影响。+ */+export function requestBuiltinSounds(): void {+ if (typeof window === 'undefined' || window.parent === window)+ return+ listenBuiltinSounds()+ try {+ window.parent.postMessage({ source: 'dsh-notification-bridge', type: SOUNDS_REQUEST_MESSAGE }, '*')+ }+ catch (error) {+ console.warn(`[${PLUGIN_ID}] failed to request notification sounds`, error)+ }+}diff --git a/packages/dsh-tauri-notification/src/client/service/sound-file.ts b/packages/dsh-tauri-notification/src/client/service/sound-file.tsnew file mode 100644index 00000000..901b7136--- /dev/null+++ b/packages/dsh-tauri-notification/src/client/service/sound-file.ts@@ -0,0 +1,31 @@+/** 自定义提示音的文件大小上限。 */+export const MAX_CUSTOM_SOUND_BYTES = 512 * 1024++export type SoundFileError = 'too-large' | 'unreadable'++export type SoundFileResult = { ok: true, dataUrl: string } | { ok: false, error: SoundFileError }++/**+ * 把用户选中的音频文件读成 data URL。+ *+ * 只保存在本地存储里,因此必须限制体积;读得到但拿不到 `data:` URL 时按不可读处理。+ */+export async function readSoundFile(file: File): Promise<SoundFileResult> {+ if (file.size > MAX_CUSTOM_SOUND_BYTES)+ return { ok: false, error: 'too-large' }+ try {+ const dataUrl = await new Promise<string>((resolve, reject) => {+ const reader = new FileReader()+ reader.onload = () => resolve(typeof reader.result === 'string' ? reader.result : '')+ reader.onerror = () => reject(reader.error ?? new Error('read-failed'))+ reader.readAsDataURL(file)+ })+ if (!dataUrl.startsWith('data:'))+ return { ok: false, error: 'unreadable' }+ return { ok: true, dataUrl }+ }+ catch (error) {+ console.warn('[dsh-tauri-notification] failed to read sound file', error)+ return { ok: false, error: 'unreadable' }+ }+}diff --git a/packages/dsh-tauri-notification/src/client/service/sound.ts b/packages/dsh-tauri-notification/src/client/service/sound.tsnew file mode 100644index 00000000..05e50de2--- /dev/null+++ b/packages/dsh-tauri-notification/src/client/service/sound.ts@@ -0,0 +1,107 @@+import type { NotificationSound } from '../types'+import { PLUGIN_ID } from '../../shared/constants'+import { builtinSound, requestBuiltinSounds } from './sound-assets'++export interface SoundPlayer {+ /** 播放提示音;`custom` 且无自定义音频时不发声(由设置层保证退回默认)。 */+ play: (sound: NotificationSound, customSound: string | null) => void+ dispose: () => void+}++/**+ * 合成音兜底:内置音用的是壳层 `public/*.wav`,只有壳层还没把资源送进来时才会响。+ * 保留它而不是静默,是因为「通知响了」比「音色对不对」重要。+ */+const DEFAULT_NOTES: readonly (readonly [number, number])[] = [[1318.51, 0.09], [1760, 0.12]]+const CLASSIC_NOTES: readonly (readonly [number, number])[] = [[880, 0.12], [587.33, 0.2]]++/**+ * 提示音播放器。+ *+ * 内置音用壳层送进来的 data URL(`public/notification.wav`、`public/classic.wav`),+ * 自定义音用用户选的文件,两者都走 `<audio>`;资源没到位时内置音退回 WebAudio 合成。+ * 整个播放器在插件卸载时随 register 控制器一起释放。+ */+export function createSoundPlayer(): SoundPlayer {+ let context: AudioContext | undefined+ let custom: HTMLAudioElement | undefined++ const ensureContext = (): AudioContext | undefined => {+ if (context)+ return context+ if (typeof AudioContext === 'undefined')+ return undefined+ context = new AudioContext()+ return context+ }++ const playTone = (audio: AudioContext, frequency: number, duration: number, start: number): void => {+ const oscillator = audio.createOscillator()+ const gain = audio.createGain()+ oscillator.type = 'sine'+ oscillator.frequency.value = frequency+ gain.gain.setValueAtTime(0.0001, start)+ gain.gain.exponentialRampToValueAtTime(0.16, start + 0.012)+ gain.gain.exponentialRampToValueAtTime(0.0001, start + duration)+ oscillator.connect(gain)+ gain.connect(audio.destination)+ oscillator.start(start)+ oscillator.stop(start + duration)+ }++ const playNotes = (notes: readonly (readonly [number, number])[]): void => {+ const audio = ensureContext()+ if (!audio)+ return+ if (audio.state === 'suspended')+ void audio.resume()+ let start = audio.currentTime + 0.01+ for (const [frequency, duration] of notes) {+ playTone(audio, frequency, duration, start)+ start += duration+ }+ }++ const playFile = (dataUrl: string): void => {+ if (typeof Audio === 'undefined')+ return+ custom ??= new Audio()+ if (custom.src !== dataUrl)+ custom.src = dataUrl+ try {+ custom.currentTime = 0+ }+ catch (error) {+ console.warn(`[${PLUGIN_ID}] failed to rewind notification sound`, error)+ }+ void custom.play().catch((error: unknown) => {+ console.warn(`[${PLUGIN_ID}] failed to play notification sound`, error)+ })+ }++ return {+ play(sound, customSound) {+ if (sound === 'none')+ return+ if (sound === 'custom') {+ if (customSound)+ playFile(customSound)+ return+ }+ const asset = builtinSound(sound)+ if (asset) {+ playFile(asset)+ return+ }+ // 首响时资源可能还在路上:先放着合成音,同时催一次壳层。+ requestBuiltinSounds()+ playNotes(sound === 'classic' ? CLASSIC_NOTES : DEFAULT_NOTES)+ },+ dispose() {+ custom?.pause()+ custom = undefined+ void context?.close()+ context = undefined+ },+ }+}diff --git a/packages/dsh-tauri-notification/src/client/service/turn-end.ts b/packages/dsh-tauri-notification/src/client/service/turn-end.tsnew file mode 100644index 00000000..e5ff7bca--- /dev/null+++ b/packages/dsh-tauri-notification/src/client/service/turn-end.ts@@ -0,0 +1,27 @@+import { getTurnEnd } from '../apis'++/**+ * 用户主动中断会话时 `turn/end` 的 `reason.kind`。+ *+ * 内核把手动中断标成 `aborted`(`completed` 才是正常跑完);`interrupted` 是同类语义的+ * 历史别名,一并认掉:两者都不该弹「回合完成」通知。+ */+const USER_INTERRUPT_REASONS: ReadonlySet<string> = new Set(['aborted', 'interrupted'])++/**+ * 这个会话最近一次回合是不是被用户手动中断的。+ *+ * 宿主没应答时返回 `false`:路由缺席(旧宿主)、连接失败都只该退化成「照常通知」,+ * 漏一条通知比吞掉一条通知更糟。因此只有宿主明确给出中断原因才算数。+ */+export async function turnEndedByUser(sessionId: string): Promise<boolean> {+ if (sessionId.length === 0)+ return false+ try {+ const fact = await getTurnEnd({ sessionId })+ return typeof fact?.reason === 'string' && USER_INTERRUPT_REASONS.has(fact.reason)+ }+ catch {+ return false+ }+}diff --git a/packages/dsh-tauri-notification/src/client/store/index.ts b/packages/dsh-tauri-notification/src/client/store/index.tsnew file mode 100644index 00000000..c968abb6--- /dev/null+++ b/packages/dsh-tauri-notification/src/client/store/index.ts@@ -0,0 +1 @@+export { notificationSettings } from './modules/settings'diff --git a/packages/dsh-tauri-notification/src/client/store/modules/settings.ts b/packages/dsh-tauri-notification/src/client/store/modules/settings.tsnew file mode 100644index 00000000..647d7ca1--- /dev/null+++ b/packages/dsh-tauri-notification/src/client/store/modules/settings.ts@@ -0,0 +1,62 @@+import type { NotificationSettings, NotificationSettingsState, NotificationSound, TurnCompleteMode } from '../../types'+import { defineStore } from 'dsh-tauri/client'+import { DEFAULT_SETTINGS, loadSettings, saveSettings } from '../../service/settings'++/** 抽出要持久化的字段(`hydrated` 是内存态,不入库)。 */+function persisted(state: NotificationSettings): NotificationSettings {+ return {+ turnComplete: state.turnComplete,+ approval: state.approval,+ question: state.question,+ sound: state.sound,+ customSound: state.customSound,+ }+}++function persist(state: NotificationSettingsState): void {+ void saveSettings(persisted(state))+}++/**+ * 通知设置的唯一真源。+ *+ * `hydrate` 幂等:React 严格模式的双调用、设置面板反复挂载都只会读一次本地存储。+ * 所有写操作先落内存态(UI 立即响应)再异步持久化。+ */+export const notificationSettings = defineStore({+ state: (): NotificationSettingsState => ({ ...DEFAULT_SETTINGS, hydrated: false }),+ actions: {+ async hydrate() {+ if (this.hydrated)+ return+ this.hydrated = true+ const loaded = await loadSettings()+ Object.assign(this, loaded)+ },+ setTurnComplete(mode: TurnCompleteMode) {+ this.turnComplete = mode+ persist(this)+ },+ setApproval(enabled: boolean) {+ this.approval = enabled+ persist(this)+ },+ setQuestion(enabled: boolean) {+ this.question = enabled+ persist(this)+ },+ setSound(sound: NotificationSound) {+ this.sound = sound+ persist(this)+ },+ /** 选中自定义提示音文件;传 `null` 表示移除并(必要时)退回默认音。 */+ setCustomSound(dataUrl: string | null) {+ this.customSound = dataUrl+ if (dataUrl)+ this.sound = 'custom'+ else if (this.sound === 'custom')+ this.sound = DEFAULT_SETTINGS.sound+ persist(this)+ },+ },+})diff --git a/packages/dsh-tauri-notification/src/client/types/index.ts b/packages/dsh-tauri-notification/src/client/types/index.tsnew file mode 100644index 00000000..992cc916--- /dev/null+++ b/packages/dsh-tauri-notification/src/client/types/index.ts@@ -0,0 +1,164 @@+/**+ * 跨模块共享的类型。+ *+ * 这里只声明**结构类型**:`sessions` / `uiSession` 等服务由 dsh-client-ui 系列包提供,+ * 而它们不在本仓库的依赖内(只有宿主半边 @deepseek-ai 包可被本地解析),因此按+ * `source/dsh-notification` 的既有做法用最小结构面(structural face)读取,+ * 不 `import type` 那些缺席的包。+ */++/** `ObservableSnapshot<T>`:getSnapshot + subscribe 的最小面。 */+export interface ObservableSnapshotFace<T> {+ getSnapshot: () => T+ subscribe: (listener: () => void) => () => void+}++/** 会话摘要(`SessionListState.byId` 的值)。 */+export interface SessionSummaryFace {+ readonly id: string+ readonly title?: string+ readonly displayTitle?: string+ readonly running: boolean+ readonly updatedAt?: number+}++/** `SessionListState`:只取通知需要的字段。 */+export interface SessionListStateFace {+ readonly ids: readonly string[]+ readonly byId: Readonly<Record<string, SessionSummaryFace>>+}++/** 客户端 `sessions` 服务的最小面。 */+export interface SessionsFace {+ readonly list: ObservableSnapshotFace<SessionListStateFace>+}++/** 提问的一个可选项(官方 `AskUserQuestionOption`)。 */+export interface PendingQuestionOptionFace {+ /** 作答时回传的就是 `label` 字面值(官方 `selected` 收的是 label,不是 id)。 */+ readonly label?: string+ readonly description?: string+}++/** 待处理交互的选项(`PendingQuestion` 的 questions 项)。 */+export interface PendingQuestionFace {+ /** 官方 `AskUserQuestionItem.id`:作答时必须原样回传。 */+ readonly id?: string+ readonly question?: string+ readonly detail?: string+ readonly header?: string+ readonly options?: readonly PendingQuestionOptionFace[]+ readonly multiSelect?: boolean+}++/** 授权结果:与官方 `ApprovalDecision` 对齐,通知上的「批准 / 拒绝」分别对应两个取值。 */+export type ApprovalDecision = 'allowed-once' | 'rejected'++/** 一条提问回答:与官方 `AskUserQuestionAnswerItem` 对齐(`selected` 收的是选项 label)。 */+export interface QuestionAnswerFace {+ readonly id: string+ readonly selected: readonly string[]+ /** 自由输入的「其他」答案;系统通知的输入框走这里。 */+ readonly custom?: string+}++/** 提问回答批次:与官方 `AskUserQuestionAnswer` 对齐。 */+export interface QuestionOutcomeFace {+ readonly answers: readonly QuestionAnswerFace[]+}++/** 待处理交互能接受的作答:授权决定,或提问回答批次。 */+export type PendingOutcome = ApprovalDecision | QuestionOutcomeFace++/**+ * 待处理交互(`PendingApproval` / `PendingQuestion`)。+ *+ * `kind` 取 `'approval' | 'question' | 'plan-review'`;`answerable` 与 `answer`+ * 只有已注册的交互才存在,因此都声明为可选。+ */+export interface PendingInteractionFace {+ readonly key: string+ readonly kind: string+ readonly sessionId: string+ readonly toolName?: string+ readonly callId?: string+ readonly reason?: string+ readonly displayReason?: unknown+ readonly answerable?: boolean+ readonly questions?: readonly PendingQuestionFace[]+ answer?: (outcome: PendingOutcome) => Promise<void>+}++/** 单个会话的状态(`SessionStatus`)。 */+export interface SessionStatusFace {+ readonly running: boolean | undefined+ readonly pendingInteraction: PendingInteractionFace | undefined+ readonly completionUnread: boolean+}++/** 客户端 `uiSession` 服务的最小面。 */+export interface UiSessionFace {+ readonly sessionStatus: ObservableSnapshotFace<ReadonlyMap<string, SessionStatusFace>>+}++/** 原生通知按钮。 */+export interface NativeNotificationAction {+ readonly id: string+ readonly title: string+ /**+ * Windows:把按钮渲染成「输入框 + 提交按钮」,用户输入的文本随动作一起回传。+ * 其他平台忽略该字段,退化成普通按钮。+ */+ readonly input?: boolean+ /** Windows:输入框占位文案(`<input placeHolderContent>`)。 */+ readonly inputPlaceholder?: string+ /** Windows:提交按钮文案;缺省时用 `title`。 */+ readonly inputButtonTitle?: string+}++/** 交给宿主窗口补丁(`NOTIFICATION_SHIM_JS`)的原生通知描述。 */+export interface NativeNotificationInput {+ readonly title: string+ readonly body: string+ readonly tag: string+ readonly sessionId: string+ readonly requireInteraction?: boolean+ /**+ * Windows:让 toast 自己保持静音(`<audio silent="true">`)。+ *+ * 未打包的 Windows 应用不能让 toast 播放自定义音频(`<audio src>` 只认 `ms-winsoundevent:*`+ * 系统音),所以提示音一律留在帧内播放;这个标志避免系统默认音再响一次(双声)。+ */+ readonly silent?: boolean+ readonly actions?: readonly NativeNotificationAction[]+ /** 用户点通知本体(非按钮)。 */+ readonly onClick?: () => void+ /** 用户点按钮:回传 action id 与该按钮输入框里的文本(无输入框或没填时为 `null`)。 */+ readonly onAction?: (action: string, inputValue: string | null) => void+}++/** 通知类别:决定文案与是否需要常驻。 */+export type NotificationKind = 'turn' | 'approval' | 'question'++/** 设置项:轮次完成通知时机。 */+export type TurnCompleteMode = 'never' | 'background' | 'always'++/** 设置项:通知提示音。 */+export type NotificationSound = 'default' | 'classic' | 'none' | 'custom'++/** 内置提示音(壳层 `public/` 里的资源,由壳层转成 data URL 送进 iframe)。 */+export type BuiltinNotificationSound = 'default' | 'classic'++/** 持久化设置。 */+export interface NotificationSettings {+ turnComplete: TurnCompleteMode+ approval: boolean+ question: boolean+ sound: NotificationSound+ customSound: string | null+}++/** store 状态 = 持久化设置 + 一次性水合标记。 */+export interface NotificationSettingsState extends NotificationSettings {+ hydrated: boolean+}diff --git a/packages/dsh-tauri-notification/src/host/apply.ts b/packages/dsh-tauri-notification/src/host/apply.tsnew file mode 100644index 00000000..73c5c813--- /dev/null+++ b/packages/dsh-tauri-notification/src/host/apply.ts@@ -0,0 +1,12 @@+import type { HostContext } from 'dsh-tauri'+import { PLUGIN_ID } from '../shared/constants'+import { handleSessionEvent } from './events/session-event'+import { routes } from './routes'+import { clearTurnEndFacts } from './service/turn-end'++export function apply(ctx: HostContext): void {+ ctx.on('session/event', handleSessionEvent)++ ctx.effect(() => routes(ctx), `${PLUGIN_ID}: routes`)+ ctx.effect(() => () => clearTurnEndFacts(), `${PLUGIN_ID}: host runtime`)+}diff --git a/packages/dsh-tauri-notification/src/host/events/session-event.test.ts b/packages/dsh-tauri-notification/src/host/events/session-event.test.tsnew file mode 100644index 00000000..97252487--- /dev/null+++ b/packages/dsh-tauri-notification/src/host/events/session-event.test.ts@@ -0,0 +1,46 @@+import { beforeEach, describe, expect, it } from 'vitest'+import { clearTurnEndFacts, turnEndFact } from '../service/turn-end'+import { handleSessionEvent } from './session-event'++describe('handleSessionEvent', () => {+ beforeEach(() => {+ clearTurnEndFacts()+ })++ it('记下 turn/end 的结束原因与回合号', () => {+ handleSessionEvent({ id: 's1' }, { type: 'turn/end', data: { turn: 3, reason: { kind: 'aborted' } } })+ expect(turnEndFact('s1')).toEqual({ reason: 'aborted', turn: 3 })+ })++ it('忽略其它事件类型', () => {+ handleSessionEvent({ id: 's1' }, { type: 'turn/start', data: { turn: 4, reason: { kind: 'aborted' } } })+ expect(turnEndFact('s1')).toBeUndefined()+ })++ it('缺少会话 id 时不记录', () => {+ handleSessionEvent({}, { type: 'turn/end', data: { turn: 1, reason: { kind: 'completed' } } })+ handleSessionEvent({ id: '' }, { type: 'turn/end', data: { turn: 1, reason: { kind: 'completed' } } })+ expect(turnEndFact('s1')).toBeUndefined()+ })++ it('宿主没给结束原因时记成空原因,把上一次的旧原因冲掉', () => {+ // 直接返回会留下旧的 `aborted`,客户端就会把这一回合的通知也当成中断吞掉。+ handleSessionEvent({ id: 's1' }, { type: 'turn/end', data: { turn: 1, reason: { kind: 'aborted' } } })+ expect(turnEndFact('s1')).toEqual({ reason: 'aborted', turn: 1 })+ handleSessionEvent({ id: 's1' }, { type: 'turn/end', data: { turn: 2 } })+ expect(turnEndFact('s1')).toEqual({ reason: '', turn: 2 })+ handleSessionEvent({ id: 's1' }, { type: 'turn/end' })+ expect(turnEndFact('s1')).toEqual({ reason: '', turn: -1 })+ })++ it('宿主没给回合号时用 -1 占位', () => {+ handleSessionEvent({ id: 's2' }, { type: 'turn/end', data: { reason: { kind: 'completed' } } })+ expect(turnEndFact('s2')).toEqual({ reason: 'completed', turn: -1 })+ })++ it('同一会话只保留最近一次结束事实', () => {+ handleSessionEvent({ id: 's1' }, { type: 'turn/end', data: { turn: 1, reason: { kind: 'completed' } } })+ handleSessionEvent({ id: 's1' }, { type: 'turn/end', data: { turn: 2, reason: { kind: 'aborted' } } })+ expect(turnEndFact('s1')).toEqual({ reason: 'aborted', turn: 2 })+ })+})diff --git a/packages/dsh-tauri-notification/src/host/events/session-event.ts b/packages/dsh-tauri-notification/src/host/events/session-event.tsnew file mode 100644index 00000000..7e2366b0--- /dev/null+++ b/packages/dsh-tauri-notification/src/host/events/session-event.ts@@ -0,0 +1,23 @@+import { recordTurnEnd } from '../service/turn-end'++/**+ * `session/event` 订阅:只挑 `turn/end` 记下结束原因。+ *+ * 事件回调签名是 `(session, event)`(与 `dsh-tauri-worktree`、`dsh-tauri-pet` 一致),+ * 会话 id 取 `session.id`。原因缺失时记成空原因而不是直接返回:空原因在客户端不算中断,+ * 于是退化成「照常通知」;直接返回会把上一回合的旧原因留在表里,那个旧原因若是 `aborted`,+ * 就会把这一回合的通知也一并吞掉。+ */+export function handleSessionEvent(session: any, event: any): void {+ if (event?.type !== 'turn/end')+ return+ const sessionId = session?.id+ if (typeof sessionId !== 'string' || sessionId.length === 0)+ return+ const reason = event?.data?.reason?.kind+ const turn = event?.data?.turn+ recordTurnEnd(sessionId, {+ reason: typeof reason === 'string' ? reason : '',+ turn: typeof turn === 'number' ? turn : -1,+ })+}diff --git a/packages/dsh-tauri-notification/src/host/routes/index.ts b/packages/dsh-tauri-notification/src/host/routes/index.tsnew file mode 100644index 00000000..cc26bdce--- /dev/null+++ b/packages/dsh-tauri-notification/src/host/routes/index.ts@@ -0,0 +1,7 @@+import { defineRoutes } from 'dsh-tauri'+import turnEnd from './turn-end/get'++/** 宿主路由:客户端在弹「回合完成」通知前先问一次结束原因。 */+export const routes = defineRoutes((disposer) => {+ disposer.get({ kind: 'exact', path: '/api/desktop/dsh-tauri-notification/turn-end' }, turnEnd)+})diff --git a/packages/dsh-tauri-notification/src/host/routes/index.types.ts b/packages/dsh-tauri-notification/src/host/routes/index.types.tsnew file mode 100644index 00000000..5b5be5ff--- /dev/null+++ b/packages/dsh-tauri-notification/src/host/routes/index.types.ts@@ -0,0 +1,11 @@+/** 路由契约:生成客户端据此产出 `Types.*`(形状校验仍在处理器内做)。 */++export interface GetTurnEndQuery {+ sessionId?: string+}++/** 会话最近一次回合结束的原因;宿主还没记录过该会话时字段缺省。 */+export interface TurnEndResult {+ reason?: string+ turn?: number+}diff --git a/packages/dsh-tauri-notification/src/host/routes/turn-end/get.ts b/packages/dsh-tauri-notification/src/host/routes/turn-end/get.tsnew file mode 100644index 00000000..7ed76e9b--- /dev/null+++ b/packages/dsh-tauri-notification/src/host/routes/turn-end/get.ts@@ -0,0 +1,19 @@+import type { EventHandlerRequest } from 'dsh-tauri'+import type { GetTurnEndQuery, TurnEndResult } from '../index.types'+import { defineEventHandler, getQuery } from 'dsh-tauri'+import { turnEndFact } from '../../service/turn-end'++/**+ * `GET /turn-end?sessionId=…`:回答「这个会话的回合为什么结束」。+ *+ * 查不到就返回空对象(200)而不是 404:调用方(客户端通知)只关心「是不是用户中断」,+ * 未知一律按「不是」处理,没必要区分「没记录」与「会话不存在」。+ */+export default defineEventHandler<EventHandlerRequest, Promise<TurnEndResult>>(async (event) => {+ const query = getQuery<GetTurnEndQuery>(event)+ const sessionId = typeof query.sessionId === 'string' ? query.sessionId : ''+ if (sessionId.length === 0)+ return {}+ const fact = turnEndFact(sessionId)+ return fact === undefined ? {} : { reason: fact.reason, turn: fact.turn }+})diff --git a/packages/dsh-tauri-notification/src/host/service/turn-end.ts b/packages/dsh-tauri-notification/src/host/service/turn-end.tsnew file mode 100644index 00000000..1814b386--- /dev/null+++ b/packages/dsh-tauri-notification/src/host/service/turn-end.ts@@ -0,0 +1,22 @@+/** 单个会话最近一次 `turn/end` 的结束事实。 */+export interface TurnEndFact {+ /** `turn/end` 的 `reason.kind`,例如 `completed` / `aborted`。 */+ readonly reason: string+ /** 该原因所属的回合号;宿主没有给出时是 `-1`。 */+ readonly turn: number+}++/** sessionId → 最近一次回合结束事实(内存态,不落盘)。 */+const facts = new Map<string, TurnEndFact>()++export function recordTurnEnd(sessionId: string, fact: TurnEndFact): void {+ facts.set(sessionId, fact)+}++export function turnEndFact(sessionId: string): TurnEndFact | undefined {+ return facts.get(sessionId)+}++export function clearTurnEndFacts(): void {+ facts.clear()+}diff --git a/packages/dsh-tauri-notification/src/index.ts b/packages/dsh-tauri-notification/src/index.tsnew file mode 100644index 00000000..443663f1--- /dev/null+++ b/packages/dsh-tauri-notification/src/index.ts@@ -0,0 +1,19 @@+import { PLUGIN_ID } from './shared/constants'++export const name = PLUGIN_ID++/** 宿主服务依赖:`webServer`(注册路由)与 `connection`(路由鉴权闸门,注册期必需)。 */+export const inject = ['webServer', 'connection']++/**+ * 宿主半边只负责回答一个问题:这个会话的回合为什么结束。+ *+ * 客户端能看到的状态只有 `running: boolean`(`sessions.list` 与 `uiSession.sessionStatus`+ * 都只有这一个维度),分不出「正常跑完」和「用户手动中断」;`turn/end` 的 `reason.kind`+ * 只出现在宿主事件里。因此宿主订阅 `session/event`、把最近一次结束原因按会话记在内存里,+ * 再用 `GET /api/desktop/dsh-tauri-notification/turn-end` 暴露给客户端。+ *+ * 通知的其它数据(标题、待处理的授权/提问)仍然只存在于客户端服务里:本插件不注册+ * 会话投影(`@deepseek-ai/dsh-session-projection` 不在本仓库依赖内),也不新增推送通道。+ */+export { apply } from './host/apply'diff --git a/packages/dsh-tauri-notification/src/shared/constants.ts b/packages/dsh-tauri-notification/src/shared/constants.tsnew file mode 100644index 00000000..a20e99d7--- /dev/null+++ b/packages/dsh-tauri-notification/src/shared/constants.ts@@ -0,0 +1,2 @@+/** 插件唯一标识:同时作为 locale 命名空间、store 存储根与日志前缀。 */+export const PLUGIN_ID = 'dsh-tauri-notification'diff --git a/packages/dsh-tauri-notification/tsdown.config.ts b/packages/dsh-tauri-notification/tsdown.config.tsnew file mode 100644index 00000000..7b808c14--- /dev/null+++ b/packages/dsh-tauri-notification/tsdown.config.ts@@ -0,0 +1,3 @@+import { defineDshConfig } from '../dsh-tauri-tsdown/src/index.ts'++export default defineDshConfig()diff --git a/packages/dsh-tauri-ui/src/client/styles/index.ts b/packages/dsh-tauri-ui/src/client/styles/index.tsindex 1f500182..69ade8b4 100644--- a/packages/dsh-tauri-ui/src/client/styles/index.ts+++ b/packages/dsh-tauri-ui/src/client/styles/index.ts@@ -493,6 +493,9 @@ const TAILWINDCSS_GENERATED = `.gap-\\[20px\\] {gap: 20px;}+ .gap-\\[24px\\] {+ gap: 24px;+ }.self-center {align-self: center;}@@ -573,6 +576,10 @@ const TAILWINDCSS_GENERATED = `border-style: var(--tw-border-style);border-width: 0.5px;}+ .border-b-\\[0\\.5px\\] {+ border-bottom-style: var(--tw-border-style);+ border-bottom-width: 0.5px;+ }.border-dashed {--tw-border-style: dashed;border-style: dashed;@@ -758,6 +765,9 @@ const TAILWINDCSS_GENERATED = `.py-\\[14px\\] {padding-block: 14px;}+ .py-\\[16px\\] {+ padding-block: 16px;+ }.py-\\[24px\\] {padding-block: 24px;}@@ -1162,6 +1172,12 @@ const TAILWINDCSS_GENERATED = `corner-shape: round;}}+ .last\\:border-b-0 {+ &:last-child {+ border-bottom-style: var(--tw-border-style);+ border-bottom-width: 0px;+ }+ }.hover\\:bg-\\[var\\(--dsw-alias-bg-layer-4\\)\\] {&:hover {@media (hover: hover) {diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 61401cfa..d77612b9 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -41,6 +41,9 @@ catalogs:specifier: ~5.8.3version: 5.8.3default:+ '@choochmeque/tauri-plugin-notifications-api':+ specifier: 0.5.0-rc.14+ version: 0.5.0-rc.14'@genapi/core':specifier: ^4.1.4version: 4.1.4@@ -344,6 +347,9 @@ importers:.:dependencies:+ '@choochmeque/tauri-plugin-notifications-api':+ specifier: 'catalog:'+ version: 0.5.0-rc.14'@genapi/pipeline':specifier: 'catalog:'version: 4.1.4@@ -710,6 +716,9 @@ importers:dsh-tauri-model:specifier: workspace:*version: link:../dsh-tauri-model+ dsh-tauri-notification:+ specifier: workspace:*+ version: link:../dsh-tauri-notificationdsh-tauri-pet:specifier: workspace:*version: link:../dsh-tauri-pet@@ -858,6 +867,25 @@ importers:specifier: catalog:testingversion: 4.1.11(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected]))+ packages/dsh-tauri-notification:+ dependencies:+ dsh-tauri:+ specifier: workspace:*+ version: link:../dsh-tauri+ dsh-tauri-ui:+ specifier: workspace:*+ version: link:../dsh-tauri-ui+ devDependencies:+ dsh-tauri-tsdown:+ specifier: workspace:*+ version: link:../dsh-tauri-tsdown+ tsdown:+ specifier: catalog:cli+ version: 0.17.4(@emnapi/[email protected])(@emnapi/[email protected])([email protected])([email protected])([email protected])([email protected])+ vitest:+ specifier: catalog:testing+ version: 4.1.11(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected]))+packages/dsh-tauri-pet:dependencies:'@deepseek-ai/dsh-skill-filesystem':@@ -1320,6 +1348,9 @@ packages:resolution: {integrity: sha512-6zABk/ECA/QYSCQ1NGiVwwbQerUCZ+TQbp64Q3AgmfNvurHH0j8TtXa1qbShXA6qqkpAj4V5W8pP6mLe1mcMqA==}engines: {node: '>=18'}+ '@choochmeque/[email protected]':+ resolution: {integrity: sha512-kst+PhQ+vawT9rs6oRJoQZ5A/ljtIEN/A0/j/z1joCOPFRCR6X5l7LBRg3ChaZEk7FPk0TT+v7Z3FX1N2Wm+6g==}+'@clack/[email protected]':resolution: {integrity: sha512-/kr3UWNtdJfxZtPgDqUOmG2pvwlmcLGheex5yiZKdwbzZJxhV+HMNR9QNmyY5cGwTNV6LrR7Jtp+KjhUAP1qBQ==}engines: {node: '>= 20.12.0'}@@ -7196,6 +7227,10 @@ snapshots:'@bcoe/[email protected]': {}+ '@choochmeque/[email protected]':+ dependencies:+ '@tauri-apps/api': 2.11.1+'@clack/[email protected]':dependencies:fast-wrap-ansi: 0.2.2diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yamlindex 6f731be3..8d29c0a0 100644--- a/pnpm-workspace.yaml+++ b/pnpm-workspace.yaml@@ -105,6 +105,7 @@ patchedDependencies:bumpp: patches/bumpp.patchcatalog:+ '@choochmeque/tauri-plugin-notifications-api': 0.5.0-rc.14'@genapi/core': ^4.1.4'@genapi/parser': ^4.1.4'@genapi/pipeline': ^4.1.4diff --git a/public/classic.wav b/public/classic.wavnew file mode 100644index 00000000..e7401c44Binary files /dev/null and b/public/classic.wav differdiff --git a/public/notification.wav b/public/notification.wavnew file mode 100644index 00000000..c3b09d9fBinary files /dev/null and b/public/notification.wav differdiff --git a/source/dsh-notification b/source/dsh-notificationnew file mode 160000index 00000000..675aab9b--- /dev/null+++ b/source/dsh-notification@@ -0,0 +1 @@+Subproject commit 675aab9b43d5011738feb6185281596c0365ccbadiff --git a/source/dsh-notifications b/source/dsh-notificationsnew file mode 160000index 00000000..afcf32a7--- /dev/null+++ b/source/dsh-notifications@@ -0,0 +1 @@+Subproject commit afcf32a7b69e468debcab40488dde2eabf7faadediff --git a/source/dsh-session-notification b/source/dsh-session-notificationnew file mode 160000index 00000000..f238f047--- /dev/null+++ b/source/dsh-session-notification@@ -0,0 +1 @@+Subproject commit f238f04749812ffa9b77b13aca0ebbbf800c71e6diff --git a/source/tauri-plugin-notifications b/source/tauri-plugin-notificationsnew file mode 160000index 00000000..55be77f1--- /dev/null+++ b/source/tauri-plugin-notifications@@ -0,0 +1 @@+Subproject commit 55be77f158b7b0ab0238861db079bd9f3f995c95diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lockindex 998883ff..3c966e10 100644--- a/src-tauri/Cargo.lock+++ b/src-tauri/Cargo.lock@@ -1071,6 +1071,7 @@ dependencies = ["tauri-plugin-fs","tauri-plugin-http","tauri-plugin-notification",+ "tauri-plugin-notifications","tauri-plugin-opener","tauri-plugin-os","tauri-plugin-single-instance",@@ -1292,6 +1293,17 @@ dependencies = ["tendril",]+[[package]]+name = "dos-date-time"+version = "0.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e6bf3a6a5a5068b83e2bc1251735e040c3c0d54bc0bb829bec86d76eb1197689"+dependencies = [+ "chrono",+ "jiff",+ "time",+]+[[package]]name = "downcast-rs"version = "1.2.1"@@ -3036,6 +3048,19 @@ dependencies = ["zbus",]+[[package]]+name = "nt-time"+version = "0.15.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "293dcb75775acfac821c0be754ea8489cc606689f1a23faa11425c0154e5a85c"+dependencies = [+ "chrono",+ "dos-date-time",+ "jiff",+ "rand 0.10.2",+ "time",+]+[[package]]name = "nu-ansi-term"version = "0.50.3"@@ -4788,6 +4813,53 @@ version = "2.6.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"+[[package]]+name = "swift-bridge"+version = "0.1.59"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "384ed39ea10f1cefabb197b7d8e67f0034b15a94ccbb1038b8e020da59bfb0be"+dependencies = [+ "once_cell",+ "swift-bridge-build",+ "swift-bridge-macro",+ "tokio",+]++[[package]]+name = "swift-bridge-build"+version = "0.1.59"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "71b36df21e7f8a8b5eeb718d2e71f9cfc308477bfb705981cca705de9767dcb7"+dependencies = [+ "proc-macro2",+ "swift-bridge-ir",+ "syn 1.0.109",+ "tempfile",+]++[[package]]+name = "swift-bridge-ir"+version = "0.1.59"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c73bd16155df50708b92306945656e57d62d321290a7db490f299f709fb31c83"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 1.0.109",+]++[[package]]+name = "swift-bridge-macro"+version = "0.1.59"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a1a13dc0dc875d85341dec5b5344a7d713f20eb5650b71086b27d09a6ece272f"+dependencies = [+ "proc-macro2",+ "quote",+ "swift-bridge-ir",+ "syn 1.0.109",+]+[[package]]name = "swift-rs"version = "1.0.7"@@ -4812,6 +4884,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "72b64191b275b66ffe2469e8af2c1cfe3bafa67b529ead792a6d0160888b4237"dependencies = ["proc-macro2",+ "quote","unicode-ident",]@@ -5228,6 +5301,29 @@ dependencies = ["url",]+[[package]]+name = "tauri-plugin-notifications"+version = "0.5.0-rc.14"+dependencies = [+ "log",+ "notify-rust",+ "nt-time",+ "rand 0.10.2",+ "serde",+ "serde_json",+ "serde_repr",+ "swift-bridge",+ "swift-bridge-build",+ "tauri",+ "tauri-plugin",+ "thiserror 2.0.20",+ "time",+ "url",+ "uuid",+ "windows",+ "windows-core 0.61.2",+]+[[package]]name = "tauri-plugin-opener"version = "2.5.4"diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.tomlindex bc5ff7e0..26801316 100644--- a/src-tauri/Cargo.toml+++ b/src-tauri/Cargo.toml@@ -39,6 +39,13 @@ tauri-plugin-opener = "2"tauri-plugin-fs = "2"tauri-plugin-store = "2"tauri-plugin-notification = "2"+# 壳层原生通知(带交互按钮 + 点击 / 动作事件)走 Choochmeque fork:官方插件在桌面端+# `show()` 之后即丢弃 handle,拿不到点击与按钮动作,所以 fork 是必需依赖。+# `default-features = false` 关掉它的 notify-rust 后端,改用它自带的 Windows toast /+# macOS 通知中心实现——那才是带按钮与事件的那条通路。+# macOS 上它会用 swift-bridge 编译自己的 Swift 后端,源码用了 Swift 6 的 typed throws+# (`throws(FFIResult)`),因此 macOS 构建需要 Xcode 16+(CI 见 ci.yml 的 Select Xcode 16)。+tauri-plugin-notifications = { version = "0.5.0-rc.14", default-features = false }tauri-plugin-autostart = "2"# 桌宠素材直连远端:插件版 HTTP 从 Rust 发起请求,绕开 githubusercontent 的 CORS。# 版本须与 package.json 的 @tauri-apps/plugin-http(catalog:tauri,^2.6.0)保持同一 minor:@@ -127,6 +134,12 @@ tray-icon = { version = "0.25", default-features = false, features = [ "ksni" ]# (上游 issue: https://github.com/webdriverio/desktop-mobile/issues/665)。[patch.crates-io]tauri-plugin-wdio-webdriver = { path = "vendor/tauri-plugin-wdio-webdriver" }+# 上游 0.5.0-rc.14 的 Windows 后端有三处缺口:不发 `<input>`、动作 `arguments` 只写裸+# action id(冷启动 COM 回调看不到 launch=,会话身份丢失)、且只有 MSIX 打包应用才注册+# COM 激活器。本地副本补齐输入框、把 arguments 改写成携带 extra 的 JSON、并为未打包的+# DSH 写入 AUMID + CLSID 注册表项并在独立 STA 线程上跑消息泵。详见 vendor 目录内+# PATCH.md(上游 issue: https://github.com/Choochmeque/tauri-plugin-notifications/issues)。+tauri-plugin-notifications = { path = "vendor/tauri-plugin-notifications" }# 行号表而非完整调试信息:panic 与回溯仍能定位到行,target 体积与链接耗时都随之下降[profile.dev]diff --git a/src-tauri/capabilities/default.json b/src-tauri/capabilities/default.jsonindex 64ba54ca..079778ab 100644--- a/src-tauri/capabilities/default.json+++ b/src-tauri/capabilities/default.json@@ -36,6 +36,7 @@"core:window:allow-cursor-position","core:window:allow-set-ignore-cursor-events","core:webview:allow-set-webview-zoom",+ "notifications:default","opener:default","opener:allow-open-url","opener:allow-default-urls",diff --git a/src-tauri/resources/manifest.jsonc b/src-tauri/resources/manifest.jsoncindex 69bb6632..7b492a2c 100644--- a/src-tauri/resources/manifest.jsonc+++ b/src-tauri/resources/manifest.jsonc@@ -145,6 +145,13 @@"name": "DSH Tauri SSH","description": "Remote-machine plugin for the desktop: SSH connection management with TOFU host keys, ~/.ssh/config discovery, remote dsh web auto-start, loopback tunnels, the same-origin /api-ssh route, and the settings page for machine CRUD, connect/test/disconnect and one-click remote install.","repo": "https://github.com/dsh-tauri-desk/deepseek-harness-desktop/tree/main/packages/dsh-tauri-ssh"+ },+ {+ "id": "dsh-tauri-notification",+ "spec": "dsh-tauri-notification",+ "name": "DSH Tauri Notification",+ "description": "Native desktop notifications for the DeepSeek Harness desktop shell: turn-completion, permission-approval and question alerts with an Approve action, click-to-focus the originating session, and a notification settings page.",+ "repo": "https://github.com/dsh-tauri-desk/deepseek-harness-desktop/tree/main/packages/dsh-tauri-notification"}],"preset": [diff --git a/src-tauri/src/desktop/builder.rs b/src-tauri/src/desktop/builder.rsindex 9ef20e3e..46fce8b1 100644--- a/src-tauri/src/desktop/builder.rs+++ b/src-tauri/src/desktop/builder.rs@@ -1128,7 +1128,6 @@ pub fn handler() -> impl Fn(Invoke<Wry>) -> bool + Send + Sync + 'static {crate::bridge::open_external_url,crate::bridge::read_clipboard_image,crate::bridge::write_clipboard_text,- crate::desktop::notification::show_native_notification,crate::desktop::window::create_app_window,crate::desktop::window::quit_app,crate::bridge::log_frontend,@@ -1339,8 +1338,7 @@ pub fn builder() -> tauri::Builder<tauri::Wry> {)// Opener plugin.plugin(tauri_plugin_opener::init())- // Notification plugin(Windows 上以 tauri-winrt-notification 实现点击回调,- // 注册官方插件保留跨平台回退能力)+ // Notification plugin(官方插件):权限查询等通用通知能力。.plugin(tauri_plugin_notification::init())// FS plugin.plugin(tauri_plugin_fs::init())@@ -1353,6 +1351,31 @@ pub fn builder() -> tauri::Builder<tauri::Wry> {// 不能把缩放应用到 WebView),见 `hooks/use-zoom-factor.ts`。.plugin(tauri_plugin_os::init());+ // Notifications plugin(Choochmeque fork):壳层发带交互按钮的通知,并通过+ // `onNotificationClicked` / `onAction` 收点击与按钮动作——官方插件在桌面端 `show()`+ // 之后即丢弃 handle,拿不到这两类事件。macOS 上它需要 Xcode 16+(Swift 6 typed throws),+ // CI 见 .github/workflows/ci.yml 的 `Select Xcode 16`。+ //+ // macOS 上它还要求进程跑在 `.app` 包内(`UNUserNotificationCenter` 的前置条件,见 vendor 的+ // `macos::validation::require_bundle`):`tauri dev` 跑的是裸二进制,注册它会让插件初始化+ // 直接报错、整个应用起不来,所以未打包时跳过这条通路(打包后自动生效)。+ #[cfg(target_os = "macos")]+ let in_app_bundle = std::env::current_exe()+ .map(|exe| exe.to_string_lossy().contains(".app/Contents/MacOS/"))+ .unwrap_or(false);+ #[cfg(not(target_os = "macos"))]+ let in_app_bundle = true;+ let builder = if in_app_bundle {+ builder.plugin(tauri_plugin_notifications::init())+ }+ else {+ log::warn!(+ "未运行在 .app 包内,跳过 tauri-plugin-notifications:macOS 的系统通知需要 .app 包,\+ 打包后自动生效"+ );+ builder+ };+// `dsh://` 深链(成功页「打开应用」按钮)只在打包态启用:debug 注册会把系统// `dsh:` 指向调试产物,与官方 Electron 的 `app.isPackaged` 门禁一致。#[cfg(not(debug_assertions))]diff --git a/src-tauri/src/desktop/mod.rs b/src-tauri/src/desktop/mod.rsindex 868a5cfa..07859336 100644--- a/src-tauri/src/desktop/mod.rs+++ b/src-tauri/src/desktop/mod.rs@@ -18,4 +18,3 @@ pub mod window;pub mod zoom;pub use builder::{builder, handler, setup, tray};-pub use notification::show_native_notification;diff --git a/src-tauri/src/desktop/notification.rs b/src-tauri/src/desktop/notification.rsindex d84e4161..8bd8a628 100644--- a/src-tauri/src/desktop/notification.rs+++ b/src-tauri/src/desktop/notification.rs@@ -1,8 +1,6 @@#[cfg(windows)]use tauri::Manager;-use crate::{desktop::payload::NativeNotificationPayload, utils::app_icon_temp_path};-/// 如果 DSH 插件仍有兜底走浏览器 Notification,则保持“已授权”假象,/// 并让每次 `new Notification(...)` 转成发给宿主窗口的 postMessage。pub(crate) const NOTIFICATION_SHIM_JS: &str = r#"(function () {@@ -36,6 +34,7 @@ pub(crate) const NOTIFICATION_SHIM_JS: &str = r#"(function () {this.options = options;this.tag = options.tag || '';this.onclick = null;+ this.onaction = null;this.onclose = null;this.onerror = null;this.onshow = null;@@ -48,7 +47,9 @@ pub(crate) const NOTIFICATION_SHIM_JS: &str = r#"(function () {body: String(options.body || ''),tag: this.tag,requireInteraction: !!options.requireInteraction,+ silent: !!options.silent,sessionId: options.sessionId || sessionIdFromTag(this.tag),+ actions: Array.isArray(options.actions) ? options.actions : [],href: location.href,origin: location.origin});@@ -59,7 +60,10 @@ pub(crate) const NOTIFICATION_SHIM_JS: &str = r#"(function () {return Promise.resolve('granted');};DshNativeNotification.prototype.close = function () {- if (this.tag) send({ type: 'dsh://close-notification', tag: this.tag });+ if (!this.tag) return;+ // 关掉后不会再回灌点击:及时释放实例,避免 pendingOnClicks 无限增长。+ delete pendingOnClicks[this.tag];+ send({ type: 'dsh://close-notification', tag: this.tag });};window.Notification = DshNativeNotification;@@ -79,7 +83,10 @@ pub(crate) const NOTIFICATION_SHIM_JS: &str = r#"(function () {});})();- window.addEventListener('blur', function () { setHostHidden(true); });+ // 宿主状态只认壳层推送(`dsh://visibility-state`)与「帧内拿到焦点」这一条正向证据。+ // 以前这里还有 `blur → 隐藏`,但帧失焦 ≠ 窗口隐藏:点壳层标题栏、设置面板都会让+ // 帧 blur,而窗口仍在前台;那条误判会让「仅在未聚焦时」在用户正盯着会话时弹通知。+ // 帧拿到焦点则窗口必然在前台(最小化的窗口给不了焦点),所以 focus 可以安全地纠正。window.addEventListener('focus', function () { setHostHidden(false); });// 查找并聚焦对应的 Session@@ -120,7 +127,15 @@ pub(crate) const NOTIFICATION_SHIM_JS: &str = r#"(function () {break;case 'dsh://notification-clicked':var instance = pendingOnClicks[data.tag];- if (instance && typeof instance.onclick === 'function') {+ if (!instance) break;+ // 一次点击只回灌一次;用完即弃,避免长时间运行后字典持续增长。+ delete pendingOnClicks[data.tag];+ // 按钮点击走 onaction(动作 id 由前端约定),点通知本体走 onclick。+ // 带输入框的按钮(如「回复」)把用户填的文本一并回灌;没填时给空串。+ if (data.action && typeof instance.onaction === 'function') {+ var inputValue = typeof data.inputValue === 'string' ? data.inputValue : '';+ try { instance.onaction({ action: String(data.action), tag: data.tag, inputValue: inputValue }); } catch (_) {}+ } else if (typeof instance.onclick === 'function') {try { instance.onclick(new Event('click')); } catch (_) {}}break;@@ -128,31 +143,6 @@ pub(crate) const NOTIFICATION_SHIM_JS: &str = r#"(function () {});})();"#;-/// 在 Rust 侧显示一条系统原生通知。-#[tauri::command]-pub fn show_native_notification(- app: tauri::AppHandle,- payload: NativeNotificationPayload,-) -> Result<(), String> {- use tauri_plugin_notification::NotificationExt;-- let mut builder = app- .notification()- .builder()- .title(payload.title)- .body(payload.body);-- if let Some(icon_path) = app_icon_temp_path(&app) {- builder = builder.icon(icon_path.to_string_lossy().into_owned());- }-- if let Some(id) = payload.tag.as_deref().and_then(|t| t.parse::<i32>().ok()) {- builder = builder.id(id);- }-- builder.show().map_err(|e| e.to_string())-}-/// 在 Windows WebView2 中接管 iframe 内的通知请求并注入原生通知桥。#[cfg(windows)]pub fn enable_notification_permissions(diff --git a/src-tauri/src/desktop/payload.rs b/src-tauri/src/desktop/payload.rsindex 6f328129..a1886ebc 100644--- a/src-tauri/src/desktop/payload.rs+++ b/src-tauri/src/desktop/payload.rs@@ -10,11 +10,3 @@ pub struct DownloadFinishedPayload {pub(crate) success: bool,}-/// iframe 内 DSH 页面发来的原生通知请求载荷。-#[derive(serde::Deserialize)]-#[serde(rename_all = "camelCase")]-pub struct NativeNotificationPayload {- pub(crate) title: String,- pub(crate) body: String,- pub(crate) tag: Option<String>,-}diff --git a/src-tauri/src/utils/mod.rs b/src-tauri/src/utils/mod.rsindex 229888d6..14152989 100644--- a/src-tauri/src/utils/mod.rs+++ b/src-tauri/src/utils/mod.rs@@ -116,15 +116,6 @@ pub fn show_main_window<R: Runtime>(app: &AppHandle<R>) {}}-pub fn app_icon_temp_path(app: &tauri::AppHandle) -> Option<std::path::PathBuf> {- let icon = app.default_window_icon()?;- let path = std::env::temp_dir().join(format!("dsh-notification-{}.png", std::process::id()));- let rgba = icon.rgba().to_vec();- let img = image::RgbaImage::from_raw(icon.width(), icon.height(), rgba)?;- img.save(&path).ok()?;- Some(path)-}-/// 解码子进程输出的一行。////// 中文 Windows 下子进程(cmd.exe、python MCP 服务器等)按 ANSI 代码页输出 GBK,diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.jsonindex d9000c33..5145ae20 100644--- a/src-tauri/tauri.conf.json+++ b/src-tauri/tauri.conf.json@@ -21,6 +21,11 @@"desktop": {"schemes": ["dsh"]}+ },+ "notifications": {+ "windows": {+ "toastActivatorClsid": "4FBB68DF-E119-4FBB-82D5-FA10F85B519B"+ }}},"bundle": {diff --git a/src-tauri/vendor/tauri-plugin-notifications/Cargo.toml b/src-tauri/vendor/tauri-plugin-notifications/Cargo.tomlnew file mode 100644index 00000000..67a78bbb--- /dev/null+++ b/src-tauri/vendor/tauri-plugin-notifications/Cargo.toml@@ -0,0 +1,202 @@+# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO+#+# When uploading crates to the registry Cargo will automatically+# "normalize" Cargo.toml files for maximal compatibility+# with all versions of Cargo and also rewrite `path` dependencies+# to registry (e.g., crates.io) dependencies.+#+# If you are reading this file be aware that the original Cargo.toml+# will likely look very different (and much more reasonable).+# See Cargo.toml.orig for the original contents.++[package]+edition = "2024"+rust-version = "1.93"+name = "tauri-plugin-notifications"+version = "0.5.0-rc.14"+authors = ["You"]+build = "build.rs"+links = "tauri-plugin-notifications"+exclude = [+ "/examples",+ "/dist-js",+ "/guest-js",+ "/node_modules",+]+autolib = false+autobins = false+autoexamples = false+autotests = false+autobenches = false+description = "A Tauri v2 plugin for sending notifications on desktop and mobile platforms with support for system notifications and push delivery via FCM and APNs."+readme = "README.md"+keywords = [+ "tauri",+ "notifications",+ "push-notifications",+ "toast",+ "desktop",+]+categories = [+ "api-bindings",+ "gui",+ "os",+]+license = "MIT"+repository = "https://github.com/Choochmeque/tauri-plugin-notifications"++[features]+default = ["notify-rust"]+notify-rust = ["dep:notify-rust"]+push-notifications = [+ "dep:zbus",+ "dep:tokio",+ "dep:uuid",+]++[lib]+name = "tauri_plugin_notifications"+path = "src/lib.rs"++[[test]]+name = "xdg_lifecycle"+path = "tests/xdg_lifecycle.rs"++[dependencies.log]+version = "0.4"++[dependencies.rand]+version = "0.10"++[dependencies.serde]+version = "1.0"++[dependencies.serde_json]+version = "1.0"++[dependencies.serde_repr]+version = "0.1"++[dependencies.tauri]+version = "2"+default-features = false++[dependencies.thiserror]+version = "2"++[dependencies.time]+version = "0.3"+features = [+ "serde",+ "parsing",+ "formatting",+]++[dependencies.url]+version = "2"+features = ["serde"]++[dev-dependencies.color-backtrace]+version = "0.7"++[dev-dependencies.ctor]+version = "1.0"++[dev-dependencies.maplit]+version = "1"++[build-dependencies.tauri-plugin]+version = "2"+features = ["build"]++[target.'cfg(all(target_os = "linux", not(target_os = "android")))'.dependencies.tokio]+version = "1"+features = [+ "sync",+ "macros",+ "time",+]+optional = true+default-features = false++[target.'cfg(all(target_os = "linux", not(target_os = "android")))'.dependencies.uuid]+version = "1"+features = [+ "v4",+ "fast-rng",+]+optional = true+default-features = false++[target.'cfg(all(target_os = "linux", not(target_os = "android")))'.dependencies.zbus]+version = "5"+features = ["tokio"]+optional = true+default-features = false++[target.'cfg(any(target_os = "linux", target_os = "freebsd"))'.dependencies.notify-rust]+version = "4.18"++[target.'cfg(any(target_os = "linux", target_os = "freebsd"))'.dev-dependencies.tauri]+version = "2"+features = ["test"]+default-features = false++[target.'cfg(any(target_os = "linux", target_os = "freebsd"))'.dev-dependencies.tokio]+version = "1"+features = [+ "macros",+ "rt-multi-thread",+ "sync",+ "time",+]++[target.'cfg(any(target_os = "linux", target_os = "freebsd"))'.dev-dependencies.zbus]+version = "5"+features = ["async-io"]+default-features = false++[target.'cfg(any(target_os = "macos", target_os = "windows"))'.dependencies.notify-rust]+version = "4.18"+optional = true++[target.'cfg(target_os = "ios")'.dependencies.tauri]+version = "2"+features = ["wry"]++[target.'cfg(target_os = "macos")'.dependencies.swift-bridge]+version = "0.1"+features = ["async"]++[target.'cfg(target_os = "macos")'.build-dependencies.swift-bridge-build]+version = "0.1"++[target.'cfg(target_os = "windows")'.dependencies.nt-time]+version = "0.15"++[target.'cfg(target_os = "windows")'.dependencies.uuid]+version = "1"+default-features = false++[target.'cfg(target_os = "windows")'.dependencies.windows]+version = "0.61"+# Vendored patch: "Foundation_Collections" (toast input boxes arrive as a+# `ValueSet` via `ToastActivatedEventArgs::UserInput`) plus the registry /+# message-loop features the unpackaged-app activator registration needs.+features = [+ "ApplicationModel",+ "Data_Xml_Dom",+ "Foundation",+ "Foundation_Collections",+ "Networking_PushNotifications",+ "UI_Notifications",+ "Win32_Foundation",+ "Win32_Security",+ "Win32_System_Com",+ "Win32_System_Registry",+ "Win32_UI_Notifications",+ "Win32_UI_WindowsAndMessaging",+]++[target.'cfg(target_os = "windows")'.dependencies.windows-core]+version = "0.61"diff --git a/src-tauri/vendor/tauri-plugin-notifications/LICENSE b/src-tauri/vendor/tauri-plugin-notifications/LICENSEnew file mode 100644index 00000000..8206f3e7--- /dev/null+++ b/src-tauri/vendor/tauri-plugin-notifications/LICENSE@@ -0,0 +1,21 @@+MIT License++Copyright (c) 2025 Vladimir Pankratov++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.diff --git a/src-tauri/vendor/tauri-plugin-notifications/PATCH.md b/src-tauri/vendor/tauri-plugin-notifications/PATCH.mdnew file mode 100644index 00000000..cb1f1317--- /dev/null+++ b/src-tauri/vendor/tauri-plugin-notifications/PATCH.md@@ -0,0 +1,97 @@+# Vendored patch: toast text input + unpackaged click delivery (Windows)++`tauri-plugin-notifications` **0.5.0-rc.14**, copied verbatim from crates.io and wired in via+`[patch.crates-io]` in `src-tauri/Cargo.toml`. Every change is confined to+`#[cfg(target_os = "windows")]` code plus one accessor trio in the shared models. Everything+else is upstream and should be kept that way, so dropping this directory is a one-line revert+once upstream ships the features.++## Why++The upstream Windows backend cannot express the two notification shapes the DSH shell needs,+and it never activates at all in an unpackaged build.++1. **No text box.** `Action::input` / `input_button_title` / `input_placeholder` are+ deserialised and documented in `README.md`, but `build_toast_xml()` only ever emitted+ `<action content=… arguments=… activationType=…>`. Nothing ever wrote an `<input>`, so a+ question notification rendered without a box to type into and without the 回复 button.++2. **Button identity is lost on a cold activation.** Actions carried the bare action id in+ `arguments=`, and the notification's session identity only ever lived in the toast's+ `launch=` attribute — which the out-of-process COM activator never receives. A click on a+ toast in Action Center while the app was closed therefore arrived as a bare action id,+ with no way back to the originating session.++3. **The COM activator was packaged-only, and registered on the wrong apartment.**++ ```rust+ if packaged && let Some(clsid_str) = windows_config.toast_activator_clsid {+ ```++ DSH is not MSIX-packaged, so `is_packaged()` is `false` and the branch never ran: the+ process registered no `INotificationActivationCallback`, Windows had no AUMID mapping to+ activate, and every click degraded to a plain shortcut launch with no payload. Even for a+ packaged app the registration happened on the caller's thread, which is Windows'+ `CoInitializeEx` returning `RPC_E_CHANGED_MODE`; `CoRegisterClassObject` binds a class to+ the *calling* apartment, and an STA serves activation calls only while it pumps messages.++4. **Replies could never reach JS.** The in-process `Activated` handler hardcoded+ `"inputValue": null` and never called `ToastActivatedEventArgs::UserInput()`, and it was+ attached only when a `notificationClicked` listener existed — so a subscriber that only+ listened for `actionPerformed` (the reply button) got no handler at all.++One toast click also reaches Windows through *two* independent routes — the in-process+`Activated` handler and the out-of-proc COM activator — so a naive fix delivers every click+twice.++## What changed++- `src/models.rs` — three accessors on `Action` so the XML builder can see the fields the+ frontend already sends: `input()`, `input_placeholder()`, `input_button_title()`.+- `Cargo.toml` — the Windows feature list gains `Foundation_Collections` (required by+ `ToastActivatedEventArgs::UserInput`), `Win32_Security` (required by `RegCreateKeyExW`) and+ `Win32_System_Registry` / `Win32_UI_WindowsAndMessaging`.+- `src/windows.rs`+ - `input_element_id()` / `action_arguments()` — helpers for the `<input id>` naming scheme+ (`input-<action id>`) and for the JSON `arguments=` payload.+ - `build_toast_xml()` — emits one `<input id="input-<action id>" type="text"+ placeHolderContent=…>` per `action.input()` **before** the `<action>` elements (Windows+ only accepts a `hint-inputId` that already exists), sets `hint-inputId` on the submitting+ action, captions that button from `input_button_title()`, and writes `arguments=` as+ `{"actionId": …, "data": <extra>}` so the session identity survives a cold activation.+ - `decode_activation()` — a new first branch decodes that JSON `arguments=` payload (the+ existing `is_object` heuristic would otherwise misread it as a body tap); the three legacy+ arms now carry `extra` too.+ - warm `Activated` handler — reads the typed text through `read_user_input()` and reports it+ as `inputValue`, derives button-vs-tap from the presence of `actionId` instead of+ `is_object`, and surfaces `extra` next to `notification`.+ - `activation_signature()` / `DELIVERED` / `claim_activation()` — collapse the+ in-process handler and the COM activator into exactly one event per click. Identical+ arguments within `DEDUP_WINDOW` (1500 ms) are considered the same activation; a poisoned+ lock or clock anomaly **fails open**, because a duplicate event is preferable to a+ silently swallowed click.+ - `show()` — attaches the in-process handler when *either* `notificationClicked` or+ `actionPerformed` has a listener.+ - `register_unpackaged_app_id()` — writes `HKCU\Software\Classes\AppUserModelId\<app_id>`+ (`DisplayName`, `IconUri`, `CustomActivator={CLSID}`) and+ `HKCU\Software\Classes\CLSID\{CLSID}\LocalServer32` = the current executable, which is the+ AUMID mapping an unpackaged build needs. Best-effort: failures are logged and the+ in-process path still works while the app is running.+ - `spawn_toast_activator()` — register `ToastActivatorFactory` on a dedicated+ single-threaded-apartment thread that then blocks in `GetMessageW` /+ `TranslateMessage` / `DispatchMessageW` for the life of the process, and is registered+ whenever a CLSID is configured rather than only for packaged builds.++The CLSID itself comes from `src-tauri/tauri.conf.json`+(`plugins.notifications.windows.toastActivatorClsid`) and must stay in sync with any MSIX+manifest's `ToastActivatorCLSID` / `com:Class Id`.++## Removal++Delete this directory and the `[patch.crates-io]` block plus its comment in+`src-tauri/Cargo.toml`. `Cargo.lock` regains the `source` + `checksum` lines for the registry+copy. Drop the `plugins.notifications` block in `src-tauri/tauri.conf.json` if upstream also+ships unpackaged registration.++Upstream issue: <https://github.com/Choochmeque/tauri-plugin-notifications/issues>+(text-box support and unpackaged activation; drop this directory once they ship).diff --git a/src-tauri/vendor/tauri-plugin-notifications/README.md b/src-tauri/vendor/tauri-plugin-notifications/README.mdnew file mode 100644index 00000000..78d4698d--- /dev/null+++ b/src-tauri/vendor/tauri-plugin-notifications/README.md@@ -0,0 +1,755 @@+[](https://www.npmjs.com/package/@choochmeque/tauri-plugin-notifications-api)+[](https://crates.io/crates/tauri-plugin-notifications)+[](https://github.com/Choochmeque/tauri-plugin-notifications/actions/workflows/tests.yml)+[](https://codecov.io/gh/Choochmeque/tauri-plugin-notifications)+[](LICENSE)++# Tauri Plugin Notifications++A Tauri v2 plugin for sending notifications on desktop and mobile platforms. Send toast notifications (brief auto-expiring OS window elements) with support for rich content, scheduling, actions, channels, and push delivery via FCM, APNs, and UnifiedPush.++## Features++- Send simple and rich notifications+- Schedule notifications for specific dates or recurring intervals+- Interactive notifications with custom actions+- Notification channels (Android) for organized notifications+- Manage pending and active notifications+- Support for attachments, icons, and custom sounds+- Inbox and large text notification styles+- Group notifications with summary support+- Permission management+- Real-time notification events++## Platform Support++- **macOS**: Native notification center integration+- **Windows**: Windows notification system+- **Linux**: notify-rust with desktop notification support; push notifications via UnifiedPush+- **FreeBSD**: notify-rust with desktop notification support over a D-Bus session bus+- **iOS**: User Notifications framework+- **Android**: Android notification system with channels++## Installation++Install the JavaScript package:++```bash+npm install @choochmeque/tauri-plugin-notifications-api+# or+yarn add @choochmeque/tauri-plugin-notifications-api+# or+pnpm add @choochmeque/tauri-plugin-notifications-api+```++Add the plugin to your Tauri project's `Cargo.toml`:++```toml+[dependencies]+tauri-plugin-notifications = "0.5"+```++### Push Notifications Feature++The `push-notifications` feature is **disabled by default**. To enable push notifications support:++```toml+[dependencies]+tauri-plugin-notifications = { version = "0.5", features = ["push-notifications"] }+```++This enables:+- Firebase Cloud Messaging support on Android+- APNs (Apple Push Notification service) support on iOS and macOS+- UnifiedPush support on Linux (D-Bus distributor protocol)++**Note:** Push notifications are currently supported on iOS, Android, macOS, and Linux. Windows support is not yet available.++On Linux you also need a UnifiedPush *distributor* app installed (ntfy, NextPush, Conversations, etc. — see the [distributor list](https://unifiedpush.org/users/distributors/)). The plugin itself is stateless: any distributor selection or client token you set lives only for the current process. See [Linux UnifiedPush Setup](#linux-unifiedpush-setup) below for details.++Without this feature enabled:+- Firebase dependencies are not included in Android builds+- Push notification registration code is disabled+- The `registerForPushNotifications()` function will return an error if called++### Desktop Notification Backend (notify-rust)++The `notify-rust` feature is **enabled by default** and provides cross-platform desktop notifications using the [notify-rust](https://crates.io/crates/notify-rust) crate.++**When to use notify-rust (default):**+- Simple notifications on Linux, FreeBSD, macOS, and Windows+- Cross-platform consistency+- Basic notification features (title, body, icon)++On Linux and FreeBSD, notify-rust is always enabled because it is the only desktop backend. A running D-Bus session bus and a desktop notification daemon are required.++**When to disable notify-rust:**+- You need native Windows toast notifications with advanced features (actions, hero images, scheduling)+- You want platform-specific notification features on macOS/Windows++To disable `notify-rust` and use native platform implementations:++```toml+[dependencies]+tauri-plugin-notifications = { version = "0.5", default-features = false }+```++To disable `notify-rust` and enable push notifications:++```toml+[dependencies]+tauri-plugin-notifications = { version = "0.5", default-features = false, features = ["push-notifications"] }+```++Configure the plugin permissions in your `capabilities/default.json`:++```json+{+ "permissions": [+ "notifications:default"+ ]+}+```++Register the plugin in your Tauri app:++```rust+fn main() {+ tauri::Builder::default()+ .plugin(tauri_plugin_notifications::init())+ .run(tauri::generate_context!())+ .expect("error while running tauri application");+}+```++## Example App++An example app is available in [`examples/notifications-demo`](examples/notifications-demo) demonstrating all plugin features:++- Permission management and push notifications (mobile)+- Basic, scheduled, and styled notifications+- Interactive notifications with action buttons+- Notification channels (Android)+- Pending and active notification management+- Event listeners with logging++**Run it:**+```bash+cd examples/notifications-demo+pnpm install+pnpm tauri dev+```++## Usage++### JavaScript/TypeScript++#### Basic Notifications++```typescript+import {+ isPermissionGranted,+ requestPermission,+ sendNotification+} from '@choochmeque/tauri-plugin-notifications-api';++// Check and request permission+let permissionGranted = await isPermissionGranted();+if (!permissionGranted) {+ const permission = await requestPermission();+ permissionGranted = permission === 'granted';+}++// Send simple notification+if (permissionGranted) {+ sendNotification('Hello from Tauri!');++ // Or with more details+ sendNotification({+ title: 'TAURI',+ body: 'Tauri is awesome!'+ });+}+```++#### Rich Notifications++```typescript+import { sendNotification } from '@choochmeque/tauri-plugin-notifications-api';++// Notification with icon and sound+await sendNotification({+ id: 1,+ title: 'New Message',+ body: 'You have a new message from John',+ icon: 'message_icon',+ sound: 'notification_sound',+ autoCancel: true+});++// Large text notification+await sendNotification({+ id: 2,+ title: 'Article',+ body: 'New article available',+ largeBody: 'This is a much longer text that will be displayed when the user expands the notification...',+ summary: 'Read more'+});++// Inbox style notification+await sendNotification({+ id: 3,+ title: 'Email',+ body: '3 new emails',+ inboxLines: [+ 'Alice: Meeting at 3pm',+ 'Bob: Project update',+ 'Charlie: Lunch tomorrow?'+ ]+});+```++#### Scheduled Notifications++```typescript+import { sendNotification, Schedule } from '@choochmeque/tauri-plugin-notifications-api';++// Schedule notification for specific date+await sendNotification({+ title: 'Reminder',+ body: 'Time for your meeting!',+ schedule: Schedule.at(new Date(2024, 0, 15, 14, 30))+});++// Repeating notification+await sendNotification({+ title: 'Daily Reminder',+ body: 'Don\'t forget to exercise!',+ schedule: Schedule.at(new Date(2024, 0, 15, 9, 0), true)+});++// Schedule with interval+await sendNotification({+ title: 'Break Time',+ body: 'Time to take a break!',+ schedule: Schedule.interval({+ hour: 1+ })+});++// Schedule every X units+import { ScheduleEvery } from '@choochmeque/tauri-plugin-notifications-api';++await sendNotification({+ title: 'Hourly Update',+ body: 'Checking in every hour',+ schedule: Schedule.every(ScheduleEvery.Hour, 1)+});+```++#### Interactive Notifications with Actions++```typescript+import {+ sendNotification,+ registerActionTypes,+ onAction+} from '@choochmeque/tauri-plugin-notifications-api';++// Register action types+await registerActionTypes([{+ id: 'message-actions',+ actions: [+ {+ id: 'reply',+ title: 'Reply',+ input: true,+ inputPlaceholder: 'Type your reply...',+ inputButtonTitle: 'Send'+ },+ {+ id: 'mark-read',+ title: 'Mark as Read'+ },+ {+ id: 'delete',+ title: 'Delete',+ destructive: true+ }+ ]+}]);++// Send notification with actions+await sendNotification({+ title: 'New Message',+ body: 'You have a new message',+ actionTypeId: 'message-actions'+});++// Listen for action events+const unlisten = await onAction((notification) => {+ console.log('Action performed on notification:', notification);+});++// Stop listening+unlisten();+```++#### Notification Channels (Android)++```typescript+import {+ createChannel,+ channels,+ removeChannel,+ Importance,+ Visibility+} from '@choochmeque/tauri-plugin-notifications-api';++// Create a notification channel+await createChannel({+ id: 'messages',+ name: 'Messages',+ description: 'Notifications for new messages',+ importance: Importance.High,+ visibility: Visibility.Private,+ sound: 'message_sound',+ vibration: true,+ lights: true,+ lightColor: '#FF0000'+});++// Send notification to specific channel+await sendNotification({+ channelId: 'messages',+ title: 'New Message',+ body: 'You have a new message'+});++// List all channels+const channelList = await channels();++// Remove a channel+await removeChannel('messages');+```++#### Managing Notifications++```typescript+import {+ pending,+ active,+ cancel,+ cancelAll,+ removeActive,+ removeAllActive+} from '@choochmeque/tauri-plugin-notifications-api';++// Get pending notifications+const pendingNotifications = await pending();++// Cancel specific pending notifications+await cancel([1, 2, 3]);++// Cancel all pending notifications+await cancelAll();++// Get active notifications+const activeNotifications = await active();++// Remove specific active notifications+await removeActive([+ { id: 1 },+ { id: 2, tag: 'message' }+]);++// Remove all active notifications+await removeAllActive();+```++#### Notification Events++```typescript+import { onNotificationReceived } from '@choochmeque/tauri-plugin-notifications-api';++// Listen for notifications received+const unlisten = await onNotificationReceived((notification) => {+ console.log('Notification received:', notification);+});++// Stop listening+unlisten();+```++#### Push Notifications (Mobile)++```typescript+import { registerForPushNotifications } from '@choochmeque/tauri-plugin-notifications-api';++// Register for push notifications and get device token+try {+ const token = await registerForPushNotifications();+ console.log('Push token:', token);+ // Send this token to your server to send push notifications+} catch (error) {+ console.error('Failed to register for push notifications:', error);+}+```++### Rust++```rust+use tauri_plugin_notifications::{NotificationsExt, Schedule, ScheduleEvery};++// Send simple notification+app.notifications()+ .builder()+ .title("Hello")+ .body("This is a notification from Rust!")+ .show()?;++// Send rich notification+app.notifications()+ .builder()+ .id(1)+ .title("New Message")+ .body("You have a new message")+ .icon("message_icon")+ .sound("notification_sound")+ .auto_cancel()+ .show()?;++// Scheduled notification+app.notifications()+ .builder()+ .title("Reminder")+ .body("Time for your meeting!")+ .schedule(Schedule::at(date_time, false, false))+ .show()?;++// Notification with attachments+use tauri_plugin_notifications::Attachment;++app.notifications()+ .builder()+ .title("Photo Shared")+ .body("Check out this image!")+ .attachment(Attachment {+ id: "image1".to_string(),+ url: "file:///path/to/image.jpg".to_string(),+ })+ .show()?;+```++## API Reference++### `isPermissionGranted()`+Checks if the permission to send notifications is granted.++**Returns:** `Promise<boolean>`++### `requestPermission()`+Requests the permission to send notifications.++**Returns:** `Promise<'granted' | 'denied' | 'default'>`++### `registerForPushNotifications()`+Registers the app for push notifications. On Android this retrieves the FCM device token; on iOS this requests permission and registers for remote notifications; on Linux this registers with the selected UnifiedPush distributor.++**Returns:** `Promise<string>` — a platform-specific identifier:+- iOS: APNs device token+- Android: FCM device token+- Linux: UnifiedPush endpoint URL (the URL your backend POSTs payloads to)++### `listDistributors()` **(Linux / UnifiedPush only)**+Lists every running UnifiedPush distributor by its D-Bus bus name (e.g. `org.unifiedpush.Distributor.ntfy`). Returns an empty array when none is installed — that's the signal to ask the user to install one from <https://unifiedpush.org/users/distributors/>.++Throws on non-Linux platforms because the underlying Tauri command isn't registered there.++**Returns:** `Promise<string[]>`++### `setDistributor(name: string)` **(Linux / UnifiedPush only)**+Pins the distributor used on the next `registerForPushNotifications()` call. **Must be called before `registerForPushNotifications()`** — calling it after a successful register has no effect on the existing endpoint; to switch distributors, unregister and register again.++The selection is **not persisted** across launches — if the host app wants to remember the user's choice, store it and re-apply on startup. If never called, the first entry from `listDistributors()` is used.++Rejects if `name` isn't currently on the bus. Throws on non-Linux platforms.++### `setToken(token: string)` **(Linux / UnifiedPush only)**+Sets the UnifiedPush client token used on subsequent `registerForPushNotifications()` calls. **Must be called before `registerForPushNotifications()`** — calling it after a successful register has no effect on the existing endpoint.++The endpoint URL the distributor returns is derived from `(app_identifier, client_token)`, so passing the same token across launches yields the same endpoint URL. The token is **not persisted** — the host app must store it and re-apply on startup if it wants endpoint stability.++If never called, a fresh UUID is generated on each register call (FCM/APNs-style token rotation — the app pushes the new endpoint URL to its backend each time).++Rejects if `token` is empty. Throws on non-Linux platforms.++### `sendNotification(options: Options | string)`+Sends a notification to the user. Can be called with a simple string for the title or with a detailed options object.++**Parameters:**+- `options`: Notification options or title string+ - `id`: Notification identifier (32-bit integer)+ - `channelId`: Channel identifier (Android)+ - `title`: Notification title+ - `body`: Notification body+ - `schedule`: Schedule for delayed or recurring notifications+ - `largeBody`: Multiline text content+ - `summary`: Detail text for large notifications+ - `actionTypeId`: Action type identifier+ - `group`: Group identifier+ - `groupSummary`: Mark as group summary (Android)+ - `sound`: Sound resource name+ - `inboxLines`: Array of lines for inbox style (max 5)+ - `icon`: Notification icon+ - `largeIcon`: Large icon (Android)+ - `iconColor`: Icon color (Android)+ - `attachments`: Array of attachments+ - `extra`: Extra payload data+ - `ongoing`: Non-dismissible notification (Android)+ - `autoCancel`: Auto-cancel on click+ - `silent`: Silent notification (iOS)+ - `visibility`: Notification visibility+ - `number`: Number of items (Android)++### `registerActionTypes(types: ActionType[])`+Register actions that are performed when the user clicks on the notification.++**Parameters:**+- `types`: Array of action type objects with:+ - `id`: Action type identifier+ - `actions`: Array of action objects+ - `id`: Action identifier+ - `title`: Action title+ - `requiresAuthentication`: Requires device unlock+ - `foreground`: Opens app in foreground+ - `destructive`: Destructive action style+ - `input`: Enable text input+ - `inputButtonTitle`: Input button label+ - `inputPlaceholder`: Input placeholder text++### `pending()`+Retrieves the list of pending notifications.++**Returns:** `Promise<PendingNotification[]>`++### `cancel(notifications: number[])`+Cancels the pending notifications with the given list of identifiers.++### `cancelAll()`+Cancels all pending notifications.++### `active()`+Retrieves the list of active notifications.++**Returns:** `Promise<ActiveNotification[]>`++### `removeActive(notifications: Array<{ id: number; tag?: string }>)`+Removes the active notifications with the given list of identifiers.++### `removeAllActive()`+Removes all active notifications.++### `createChannel(channel: Channel)`+Creates a notification channel (Android).++**Parameters:**+- `channel`: Channel configuration+ - `id`: Channel identifier+ - `name`: Channel name+ - `description`: Channel description+ - `sound`: Sound resource name+ - `lights`: Enable notification light+ - `lightColor`: Light color+ - `vibration`: Enable vibration+ - `importance`: Importance level (None, Min, Low, Default, High)+ - `visibility`: Visibility level (Secret, Private, Public)++### `removeChannel(id: string)`+Removes the channel with the given identifier.++### `channels()`+Retrieves the list of notification channels.++**Returns:** `Promise<Channel[]>`++### `onNotificationReceived(callback: (notification: Options) => void)`+Listens for notification received events.++**Returns:** `Promise<PluginListener>` with `unlisten()` method++### `onAction(callback: (notification: Options) => void)`+Listens for notification action performed events.++**Returns:** `Promise<PluginListener>` with `unlisten()` method++## Platform Differences++### Desktop (macOS, Windows, Linux)+- Uses native notification systems+- Actions support varies by platform+- Limited scheduling capabilities on some platforms+- Channels not applicable (Android-specific)+- Linux additionally supports server-driven push via UnifiedPush (see [Linux UnifiedPush Setup](#linux-unifiedpush-setup))++### iOS+- Requires permission request+- Rich notifications with attachments+- Action support with input options+- Silent notifications available+- Group notifications (thread identifiers)++### Android+- Notification channels required for Android 8.0++- Full scheduling support+- Rich notification styles (inbox, large text)+- Ongoing notifications for background tasks+- Detailed importance and visibility controls+- Custom sounds, vibration, and lights++## Platform Setup++### iOS Setup++1. The plugin automatically configures notification capabilities+2. Add notification sounds to your Xcode project if needed:+ - Add sound files to your iOS project+ - Place in app bundle+ - Reference by filename (without extension)++### Android Setup++1. The plugin automatically includes required permissions+2. For custom sounds:+ - Place sound files in `res/raw/` folder+ - Reference by filename (without extension)+3. For custom icons:+ - Place icons in `res/drawable/` folder+ - Reference by filename (without extension)+4. **For push notifications (FCM)** - These steps must be done in your Tauri app project:+ - Create a Firebase project at [Firebase Console](https://console.firebase.google.com/)+ - Download the `google-services.json` file from Firebase Console+ - Place `google-services.json` in your Tauri app's `gen/android/app/` directory+ - Add the Google Services classpath to your app's `gen/android/build.gradle.kts`:+ ```kotlin+ buildscript {+ repositories {+ google()+ mavenCentral()+ }+ dependencies {+ classpath("com.google.gms:google-services:4.4.2")+ }+ }+ ```+ - Apply the plugin at the bottom of `gen/android/app/build.gradle.kts`:+ ```kotlin+ apply(plugin = "com.google.gms.google-services")+ ```+ - The notification plugin already includes the Firebase Cloud Messaging dependency when the `push-notifications` feature is enabled++### Linux UnifiedPush Setup++UnifiedPush is a federated push protocol where a user-installed *distributor* app delivers messages to your app over D-Bus. The plugin implements the *connector* side and exposes the standard `registerForPushNotifications()` flow.++1. **Enable the `push-notifications` feature** in your `Cargo.toml` (this pulls in the `zbus` / `tokio` / `uuid` deps on Linux).+2. **Install a distributor**. The user picks one (or you ship one with your app):+ - [ntfy](https://ntfy.sh/) — minimal, self-hostable, has a Linux desktop client+ - [NextPush](https://nextpush.unifiedpush.org/) — backed by a Nextcloud server+ - [Conversations](https://conversations.im/) — XMPP-based+ - Full list: <https://unifiedpush.org/users/distributors/>+3. **Register from JS**:+ ```typescript+ import { registerForPushNotifications, listDistributors, setDistributor, setToken } from '@choochmeque/tauri-plugin-notifications-api';++ const distributors = await listDistributors();+ if (distributors.length === 0) {+ // prompt the user to install a distributor+ return;+ }+ await setDistributor(distributors[0]);+ const storedToken = localStorage.getItem('up-client-token') ?? crypto.randomUUID();+ localStorage.setItem('up-client-token', storedToken);+ await setToken(storedToken);+ const endpoint = await registerForPushNotifications();+ // POST `endpoint` to your backend so it can deliver pushes+ ```++#### Receiving pushes while the app is running++Incoming UnifiedPush messages are handled automatically:++- A system toast is shown via `notify-rust` (if that feature is enabled — it is by default).+- The same `onNotificationReceived` listener that handles local notifications fires with `source: "push"`:++ ```typescript+ import { onNotificationReceived } from '@choochmeque/tauri-plugin-notifications-api';++ const unlisten = await onNotificationReceived((n) => {+ if (n.source === 'push') {+ console.log('UnifiedPush message:', n.title, n.body, n.extra);+ }+ });+ ```++The plugin best-effort-parses the message bytes as JSON and extracts `title`, `body` (or `message`), and `data` (or `extra`). Non-JSON payloads land in `body` as a plain string. Binary payloads end up in `extra` as a `<binary N bytes>` marker.++#### Receiving pushes when the app is closed (optional)++UnifiedPush delivers messages by D-Bus method call on the app's bus name. If the app isn't running when a push arrives, the distributor relies on D-Bus session activation to launch it.++To enable that, ship a `.service` activation file at `~/.local/share/dbus-1/services/<app-identifier>.service`:++```ini+[D-BUS Service]+Name=com.example.MyApp+Exec=/usr/bin/my-app+```++Replace `Name` with your Tauri app's identifier (the `identifier` field from `tauri.conf.json`) and `Exec` with the absolute path to the installed binary. Without this file, pushes are only delivered while the app is already running.++The plugin does **not** install this file for you — it's a packaging/deployment decision. Distros and packagers typically install it from the `.deb` / `.rpm` / Flatpak manifest.++**Important caveat about cold-start delivery:** the plugin's UnifiedPush connector (the D-Bus service that owns your app identifier) is **lazily initialized** on the first call to `listDistributors()`, `setDistributor()`, `setToken()`, or `registerForPushNotifications()` from the JS layer. If your app is launched by D-Bus activation purely to handle a push, the distributor's method call may race the lazy init and arrive before the connector is registered — the call then fails silently. To make activation-driven delivery reliable, trigger the init eagerly in your Rust `setup()` (e.g. call `notifications.list_distributors()` once before returning), or call `listDistributors()` from JS as early as your app starts. Until you do, treat the `.service` activation as best-effort.++## Testing++### Desktop+- Notifications appear in the system notification center+- Test different notification types and interactions+- Verify notification persistence and dismissal++### iOS+- Test on physical devices (simulator support is limited)+- Request permissions before sending notifications+- Test scheduled notifications with different intervals+- Verify action handling and notification grouping++### Android+- Create and test notification channels+- Test different importance levels and visibility settings+- Verify scheduled notifications work with device sleep+- Test ongoing notifications for background tasks+- Verify notification styles (inbox, large text, etc.)++## Troubleshooting++### Notifications not appearing+- Verify permissions are granted+- On Android, ensure notification channel exists+- Check system notification settings+- Verify notification ID is unique++### Scheduled notifications not firing+- Check device power settings (battery optimization)+- On Android, use `allowWhileIdle` for critical notifications+- Verify schedule time is in the future++### Actions not working+- Ensure action types are registered before sending notification+- Verify action IDs match between registration and handling+- Check platform-specific action support++## License++[MIT](LICENSE)diff --git a/src-tauri/vendor/tauri-plugin-notifications/android/.gitignore b/src-tauri/vendor/tauri-plugin-notifications/android/.gitignorenew file mode 100644index 00000000..dc940ae2--- /dev/null+++ b/src-tauri/vendor/tauri-plugin-notifications/android/.gitignore@@ -0,0 +1,6 @@+/build+/.gradle+/.kotlin+/.tauri+build.properties+local.propertiesdiff --git a/src-tauri/vendor/tauri-plugin-notifications/android/build.gradle.kts b/src-tauri/vendor/tauri-plugin-notifications/android/build.gradle.ktsnew file mode 100644index 00000000..db35be1a--- /dev/null+++ b/src-tauri/vendor/tauri-plugin-notifications/android/build.gradle.kts@@ -0,0 +1,119 @@+import java.util.Properties+import java.io.FileInputStream+import org.jetbrains.kotlin.gradle.dsl.JvmTarget++plugins {+ id("com.android.library")+ id("org.jetbrains.kotlin.android")+ id("jacoco")+}++val buildProperties = Properties().apply {+ val propFile = file("build.properties")+ if (propFile.exists()) {+ propFile.inputStream().use { load(it) }+ }+}++android {+ namespace = "app.tauri.notification"+ compileSdk = 36++ defaultConfig {+ minSdk = 24++ testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"+ consumerProguardFiles("consumer-rules.pro")++ // Enable push notifications based on Cargo feature flag+ val enablePush = buildProperties.getProperty("enablePushNotifications", "false").toBoolean()+ buildConfigField("boolean", "ENABLE_PUSH_NOTIFICATIONS", "$enablePush")+ }++ buildTypes {+ debug {+ enableUnitTestCoverage = true+ }+ release {+ isMinifyEnabled = false+ proguardFiles(+ getDefaultProguardFile("proguard-android-optimize.txt"),+ "proguard-rules.pro"+ )+ }+ }++ testOptions {+ unitTests.all {+ it.configure<JacocoTaskExtension> {+ isIncludeNoLocationClasses = true+ excludes = listOf("jdk.internal.*")+ }+ }+ }+ compileOptions {+ sourceCompatibility = JavaVersion.VERSION_1_8+ targetCompatibility = JavaVersion.VERSION_1_8+ }+ kotlin {+ compilerOptions {+ jvmTarget = JvmTarget.JVM_1_8+ }+ }+ buildFeatures {+ buildConfig = true+ }+}++dependencies {+ implementation("androidx.core:core-ktx:1.17.0")+ implementation("androidx.appcompat:appcompat:1.8.0")+ implementation("com.google.android.material:material:1.14.0")+ implementation("com.fasterxml.jackson.core:jackson-databind:2.22.2")++ implementation(platform("com.google.firebase:firebase-bom:34.19.0"))+ implementation("com.google.firebase:firebase-messaging-ktx:24.1.2")+ testImplementation("junit:junit:4.13.2")+ testImplementation("io.mockk:mockk-android:1.14.11")+ testImplementation("io.mockk:mockk-agent:1.14.11")+ testImplementation("org.jetbrains.kotlin:kotlin-test:2.3.0")+ testImplementation("org.json:json:20260814")+ testImplementation("org.robolectric:robolectric:4.17")+ androidTestImplementation("androidx.test.ext:junit:1.3.0")+ androidTestImplementation("androidx.test.espresso:espresso-core:3.7.0")+ implementation(project(":tauri-android"))+}++tasks.register<JacocoReport>("jacocoTestReport") {+ dependsOn("testDebugUnitTest")++ reports {+ xml.required.set(true)+ html.required.set(true)+ csv.required.set(false)+ }++ val fileFilter = listOf(+ "**/R.class",+ "**/R$*.class",+ "**/BuildConfig.*",+ "**/Manifest*.*",+ "**/*Test*.*",+ "android/**/*.*"+ )++ val debugTree = fileTree("${layout.buildDirectory.get().asFile}/tmp/kotlin-classes/debug") {+ exclude(fileFilter)+ }++ val mainSrc = "${project.projectDir}/src"++ sourceDirectories.setFrom(files(listOf(+ "$mainSrc/main/java",+ "$mainSrc/main/kotlin"+ )))+ classDirectories.setFrom(files(debugTree))+ executionData.setFrom(fileTree(layout.buildDirectory.get().asFile) {+ include("outputs/unit_test_code_coverage/debugUnitTest/testDebugUnitTest.exec")+ })+}diff --git a/src-tauri/vendor/tauri-plugin-notifications/android/consumer-rules.pro b/src-tauri/vendor/tauri-plugin-notifications/android/consumer-rules.pronew file mode 100644index 00000000..9f61486d--- /dev/null+++ b/src-tauri/vendor/tauri-plugin-notifications/android/consumer-rules.pro@@ -0,0 +1,8 @@+# Preserve Jackson @JsonValue annotations and the enums that rely on them+# (Importance, Visibility). Without these rules R8 strips the annotation in+# release builds and Jackson falls back to serializing enums as `name()`+# (e.g. "Default") instead of the integer value the Rust side expects.+-keepattributes RuntimeVisibleAnnotations++-keep enum app.tauri.notification.Importance { *; }+-keep enum app.tauri.notification.Visibility { *; }diff --git a/src-tauri/vendor/tauri-plugin-notifications/android/gradle.properties b/src-tauri/vendor/tauri-plugin-notifications/android/gradle.propertiesnew file mode 100644index 00000000..2a7ec695--- /dev/null+++ b/src-tauri/vendor/tauri-plugin-notifications/android/gradle.properties@@ -0,0 +1,24 @@+# Project-wide Gradle settings.+# IDE (e.g. Android Studio) users:+# Gradle settings configured through the IDE *will override*+# any settings specified in this file.+# For more details on how to configure your build environment visit+# http://www.gradle.org/docs/current/userguide/build_environment.html+# Specifies the JVM arguments used for the daemon process.+# The setting is particularly useful for tweaking memory settings.+org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8+# When configured, Gradle will run in incubating parallel mode.+# This option should only be used with decoupled projects. More details, visit+# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects+# org.gradle.parallel=true+# AndroidX package structure to make it clearer which packages are bundled with the+# Android operating system, and which are packaged with your app"s APK+# https://developer.android.com/topic/libraries/support-library/androidx-rn+android.useAndroidX=true+# Kotlin code style for this project: "official" or "obsolete":+kotlin.code.style=official+# Enables namespacing of each library's R class so that its R class includes only the+# resources declared in the library itself and none from the library's dependencies,+# thereby reducing the size of the R class for that library+android.nonTransitiveRClass=true+android.nonFinalResIds=false\ No newline at end of filediff --git a/src-tauri/vendor/tauri-plugin-notifications/android/gradle/wrapper/gradle-wrapper.jar b/src-tauri/vendor/tauri-plugin-notifications/android/gradle/wrapper/gradle-wrapper.jarnew file mode 100644index 00000000..b1b8ef56Binary files /dev/null and b/src-tauri/vendor/tauri-plugin-notifications/android/gradle/wrapper/gradle-wrapper.jar differdiff --git a/src-tauri/vendor/tauri-plugin-notifications/android/gradle/wrapper/gradle-wrapper.properties b/src-tauri/vendor/tauri-plugin-notifications/android/gradle/wrapper/gradle-wrapper.propertiesnew file mode 100644index 00000000..4dcb8425--- /dev/null+++ b/src-tauri/vendor/tauri-plugin-notifications/android/gradle/wrapper/gradle-wrapper.properties@@ -0,0 +1,8 @@+distributionBase=GRADLE_USER_HOME+distributionPath=wrapper/dists+distributionUrl=https\://services.gradle.org/distributions/gradle-9.5.1-bin.zip+networkTimeout=10000+retries=0+retryBackOffMs=500+zipStoreBase=GRADLE_USER_HOME+zipStorePath=wrapper/distsdiff --git a/src-tauri/vendor/tauri-plugin-notifications/android/gradlew b/src-tauri/vendor/tauri-plugin-notifications/android/gradlewnew file mode 100644index 00000000..b9bb139f--- /dev/null+++ b/src-tauri/vendor/tauri-plugin-notifications/android/gradlew@@ -0,0 +1,248 @@+#!/bin/sh++#+# Copyright © 2015 the original authors.+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# https://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.+#+# SPDX-License-Identifier: Apache-2.0+#++##############################################################################+#+# Gradle start up script for POSIX generated by Gradle.+#+# Important for running:+#+# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is+# noncompliant, but you have some other compliant shell such as ksh or+# bash, then to run this script, type that shell name before the whole+# command line, like:+#+# ksh Gradle+#+# Busybox and similar reduced shells will NOT work, because this script+# requires all of these POSIX shell features:+# * functions;+# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,+# «${var#prefix}», «${var%suffix}», and «$( cmd )»;+# * compound commands having a testable exit status, especially «case»;+# * various built-in commands including «command», «set», and «ulimit».+#+# Important for patching:+#+# (2) This script targets any POSIX shell, so it avoids extensions provided+# by Bash, Ksh, etc; in particular arrays are avoided.+#+# The "traditional" practice of packing multiple parameters into a+# space-separated string is a well documented source of bugs and security+# problems, so this is (mostly) avoided, by progressively accumulating+# options in "$@", and eventually passing that to Java.+#+# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,+# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;+# see the in-line comments for details.+#+# There are tweaks for specific operating systems such as AIX, CygWin,+# Darwin, MinGW, and NonStop.+#+# (3) This script is generated from the Groovy template+# https://github.com/gradle/gradle/blob/3d91ce3b8caaf77ad09f381f43615b715b53f72c/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt+# within the Gradle project.+#+# You can find Gradle at https://github.com/gradle/gradle/.+#+##############################################################################++# Attempt to set APP_HOME++# Resolve links: $0 may be a link+app_path=$0++# Need this for daisy-chained symlinks.+while+ APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path+ [ -h "$app_path" ]+do+ ls=$( ls -ld "$app_path" )+ link=${ls#*' -> '}+ case $link in #(+ /*) app_path=$link ;; #(+ *) app_path=$APP_HOME$link ;;+ esac+done++# This is normally unused+# shellcheck disable=SC2034+APP_BASE_NAME=${0##*/}+# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)+APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit++# Use the maximum available, or set MAX_FD != -1 to use that value.+MAX_FD=maximum++warn () {+ echo "$*"+} >&2++die () {+ echo+ echo "$*"+ echo+ exit 1+} >&2++# OS specific support (must be 'true' or 'false').+cygwin=false+msys=false+darwin=false+nonstop=false+case "$( uname )" in #(+ CYGWIN* ) cygwin=true ;; #(+ Darwin* ) darwin=true ;; #(+ MSYS* | MINGW* ) msys=true ;; #(+ NONSTOP* ) nonstop=true ;;+esac++++# Determine the Java command to use to start the JVM.+if [ -n "$JAVA_HOME" ] ; then+ if [ -x "$JAVA_HOME/jre/sh/java" ] ; then+ # IBM's JDK on AIX uses strange locations for the executables+ JAVACMD=$JAVA_HOME/jre/sh/java+ else+ JAVACMD=$JAVA_HOME/bin/java+ fi+ if [ ! -x "$JAVACMD" ] ; then+ die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME++Please set the JAVA_HOME variable in your environment to match the+location of your Java installation."+ fi+else+ JAVACMD=java+ if ! command -v java >/dev/null 2>&1+ then+ die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.++Please set the JAVA_HOME variable in your environment to match the+location of your Java installation."+ fi+fi++# Increase the maximum file descriptors if we can.+if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then+ case $MAX_FD in #(+ max*)+ # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.+ # shellcheck disable=SC2039,SC3045+ MAX_FD=$( ulimit -H -n ) ||+ warn "Could not query maximum file descriptor limit"+ esac+ case $MAX_FD in #(+ '' | soft) :;; #(+ *)+ # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.+ # shellcheck disable=SC2039,SC3045+ ulimit -n "$MAX_FD" ||+ warn "Could not set maximum file descriptor limit to $MAX_FD"+ esac+fi++# Collect all arguments for the java command, stacking in reverse order:+# * args from the command line+# * the main class name+# * -classpath+# * -D...appname settings+# * --module-path (only if needed)+# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.++# For Cygwin or MSYS, switch paths to Windows format before running java+if "$cygwin" || "$msys" ; then+ APP_HOME=$( cygpath --path --mixed "$APP_HOME" )++ JAVACMD=$( cygpath --unix "$JAVACMD" )++ # Now convert the arguments - kludge to limit ourselves to /bin/sh+ for arg do+ if+ case $arg in #(+ -*) false ;; # don't mess with options #(+ /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath+ [ -e "$t" ] ;; #(+ *) false ;;+ esac+ then+ arg=$( cygpath --path --ignore --mixed "$arg" )+ fi+ # Roll the args list around exactly as many times as the number of+ # args, so each arg winds up back in the position where it started, but+ # possibly modified.+ #+ # NB: a `for` loop captures its iteration list before it begins, so+ # changing the positional parameters here affects neither the number of+ # iterations, nor the values presented in `arg`.+ shift # remove old arg+ set -- "$@" "$arg" # push replacement arg+ done+fi+++# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.+DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'++# Collect all arguments for the java command:+# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,+# and any embedded shellness will be escaped.+# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be+# treated as '${Hostname}' itself on the command line.++set -- \+ "-Dorg.gradle.appname=$APP_BASE_NAME" \+ -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \+ "$@"++# Stop when "xargs" is not available.+if ! command -v xargs >/dev/null 2>&1+then+ die "xargs is not available"+fi++# Use "xargs" to parse quoted args.+#+# With -n1 it outputs one arg per line, with the quotes and backslashes removed.+#+# In Bash we could simply go:+#+# readarray ARGS < <( xargs -n1 <<<"$var" ) &&+# set -- "${ARGS[@]}" "$@"+#+# but POSIX shell has neither arrays nor command substitution, so instead we+# post-process each arg (as a line of input to sed) to backslash-escape any+# character that might be a shell metacharacter, then use eval to reverse+# that process (while maintaining the separation between arguments), and wrap+# the whole thing up as a single "set" statement.+#+# This will of course break if any of these variables contains a newline or+# an unmatched quote.+#++eval "set -- $(+ printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |+ xargs -n1 |+ sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |+ tr '\n' ' '+ )" '"$@"'++exec "$JAVACMD" "$@"diff --git a/src-tauri/vendor/tauri-plugin-notifications/android/gradlew.bat b/src-tauri/vendor/tauri-plugin-notifications/android/gradlew.batnew file mode 100644index 00000000..24c62d56--- /dev/null+++ b/src-tauri/vendor/tauri-plugin-notifications/android/gradlew.bat@@ -0,0 +1,82 @@+@rem+@rem Copyright 2015 the original author or authors.+@rem+@rem Licensed under the Apache License, Version 2.0 (the "License");+@rem you may not use this file except in compliance with the License.+@rem You may obtain a copy of the License at+@rem+@rem https://www.apache.org/licenses/LICENSE-2.0+@rem+@rem Unless required by applicable law or agreed to in writing, software+@rem distributed under the License is distributed on an "AS IS" BASIS,+@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+@rem See the License for the specific language governing permissions and+@rem limitations under the License.+@rem+@rem SPDX-License-Identifier: Apache-2.0+@rem++@if "%DEBUG%"=="" @echo off+@rem ##########################################################################+@rem+@rem Gradle startup script for Windows+@rem+@rem ##########################################################################++@rem Set local scope for the variables, and ensure extensions are enabled+setlocal EnableExtensions++set DIRNAME=%~dp0+if "%DIRNAME%"=="" set DIRNAME=.+@rem This is normally unused+set APP_BASE_NAME=%~n0+set APP_HOME=%DIRNAME%++@rem Resolve any "." and ".." in APP_HOME to make it shorter.+for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi++@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.+set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"++@rem Find java.exe+if defined JAVA_HOME goto findJavaFromJavaHome++set JAVA_EXE=java.exe+%JAVA_EXE% -version >NUL 2>&1+if %ERRORLEVEL% equ 0 goto execute++echo. 1>&2+echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2+echo. 1>&2+echo Please set the JAVA_HOME variable in your environment to match the 1>&2+echo location of your Java installation. 1>&2++"%COMSPEC%" /c exit 1++:findJavaFromJavaHome+set JAVA_HOME=%JAVA_HOME:"=%+set JAVA_EXE=%JAVA_HOME%/bin/java.exe++if exist "%JAVA_EXE%" goto execute++echo. 1>&2+echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2+echo. 1>&2+echo Please set the JAVA_HOME variable in your environment to match the 1>&2+echo location of your Java installation. 1>&2++"%COMSPEC%" /c exit 1++:execute+@rem Setup the command line++++@rem Execute Gradle+@rem endlocal doesn't take effect until after the line is parsed and variables are expanded+@rem which allows us to clear the local environment before executing the java command+endlocal & "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* & call :exitWithErrorLevel++:exitWithErrorLevel+@rem Use "%COMSPEC%" /c exit to allow operators to work properly in scripts+"%COMSPEC%" /c exit %ERRORLEVEL%diff --git a/src-tauri/vendor/tauri-plugin-notifications/android/proguard-rules.pro b/src-tauri/vendor/tauri-plugin-notifications/android/proguard-rules.pronew file mode 100644index 00000000..481bb434--- /dev/null+++ b/src-tauri/vendor/tauri-plugin-notifications/android/proguard-rules.pro@@ -0,0 +1,21 @@+# Add project specific ProGuard rules here.+# You can control the set of applied configuration files using the+# proguardFiles setting in build.gradle.+#+# For more details, see+# http://developer.android.com/guide/developing/tools/proguard.html++# If your project uses WebView with JS, uncomment the following+# and specify the fully qualified class name to the JavaScript interface+# class:+#-keepclassmembers class fqcn.of.javascript.interface.for.webview {+# public *;+#}++# Uncomment this to preserve the line number information for+# debugging stack traces.+#-keepattributes SourceFile,LineNumberTable++# If you keep the line number information, uncomment this to+# hide the original source file name.+#-renamesourcefileattribute SourceFile\ No newline at end of filediff --git a/src-tauri/vendor/tauri-plugin-notifications/android/settings.gradle b/src-tauri/vendor/tauri-plugin-notifications/android/settings.gradlenew file mode 100644index 00000000..29f15f58--- /dev/null+++ b/src-tauri/vendor/tauri-plugin-notifications/android/settings.gradle@@ -0,0 +1,31 @@+pluginManagement {+ repositories {+ mavenCentral()+ gradlePluginPortal()+ google()+ }+ resolutionStrategy {+ eachPlugin {+ switch (requested.id.id) {+ case "com.android.library":+ useVersion("8.13.1")+ break+ case "org.jetbrains.kotlin.android":+ useVersion("2.2.21")+ break+ }+ }+ }+}++dependencyResolutionManagement {+ repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)+ repositories {+ mavenCentral()+ google()++ }+}++include ':tauri-android'+project(':tauri-android').projectDir = new File('./.tauri/tauri-api')diff --git a/src-tauri/vendor/tauri-plugin-notifications/android/src/androidTest/java/app/tauri/notification/AssetUtilsInstrumentedTest.kt b/src-tauri/vendor/tauri-plugin-notifications/android/src/androidTest/java/app/tauri/notification/AssetUtilsInstrumentedTest.ktnew file mode 100644index 00000000..6f88f787--- /dev/null+++ b/src-tauri/vendor/tauri-plugin-notifications/android/src/androidTest/java/app/tauri/notification/AssetUtilsInstrumentedTest.kt@@ -0,0 +1,184 @@+package app.tauri.notification++import android.content.Context+import androidx.test.ext.junit.runners.AndroidJUnit4+import androidx.test.platform.app.InstrumentationRegistry+import org.junit.Assert.*+import org.junit.Before+import org.junit.Test+import org.junit.runner.RunWith++@RunWith(AndroidJUnit4::class)+class AssetUtilsInstrumentedTest {++ private lateinit var context: Context++ @Before+ fun setup() {+ context = InstrumentationRegistry.getInstrumentation().targetContext+ }++ @Test+ fun testGetResourceBaseName_withPath() {+ // When path contains /, it returns everything after last / (including extension)+ assertEquals("resource.png", AssetUtils.getResourceBaseName("path/to/resource.png"))+ }++ @Test+ fun testGetResourceBaseName_withExtension() {+ assertEquals("resource", AssetUtils.getResourceBaseName("resource.mp3"))+ }++ @Test+ fun testGetResourceBaseName_noExtension() {+ assertEquals("resource", AssetUtils.getResourceBaseName("resource"))+ }++ @Test+ fun testGetResourceBaseName_multipleExtensions() {+ assertEquals("file.backup", AssetUtils.getResourceBaseName("file.backup.zip"))+ }++ @Test+ fun testGetResourceBaseName_null() {+ assertNull(AssetUtils.getResourceBaseName(null))+ }++ @Test+ fun testGetResourceBaseName_empty() {+ assertEquals("", AssetUtils.getResourceBaseName(""))+ }++ @Test+ fun testGetResourceID_existingDrawable() {+ // Test with ic_transparent which should exist in this project+ val resId = AssetUtils.getResourceID(context, "ic_transparent", "drawable")++ // Should return non-zero if found, or zero if not found (both are acceptable)+ assertTrue(resId >= AssetUtils.RESOURCE_ID_ZERO_VALUE)+ }++ @Test+ fun testGetResourceID_nonExistentResource() {+ val resId = AssetUtils.getResourceID(context, "nonexistent_resource_xyz", "drawable")++ assertEquals(AssetUtils.RESOURCE_ID_ZERO_VALUE, resId)+ }++ @Test+ fun testGetResourceID_nullResourceName() {+ // Note: getResourceID doesn't handle null gracefully, Android API throws NPE+ // This tests the actual behavior+ try {+ val resId = AssetUtils.getResourceID(context, null, "drawable")+ // If it doesn't throw, it should return 0+ assertEquals(AssetUtils.RESOURCE_ID_ZERO_VALUE, resId)+ } catch (e: NullPointerException) {+ // Expected behavior - Android API throws NPE for null resource name+ assertTrue(true)+ }+ }++ @Test+ fun testGetResourceID_rawDirectory() {+ // Try to get a resource from raw directory (may not exist, but should not crash)+ val resId = AssetUtils.getResourceID(context, "test_sound", "raw")++ // Should return 0 if not found, or valid ID if found+ assertTrue(resId >= AssetUtils.RESOURCE_ID_ZERO_VALUE)+ }++ @Test+ fun testGetResourceID_drawableDirectory() {+ // Try to get a resource from drawable directory+ val resId = AssetUtils.getResourceID(context, "ic_transparent", "drawable")++ // Should return 0 if not found, or valid ID if found+ assertTrue(resId >= AssetUtils.RESOURCE_ID_ZERO_VALUE)+ }++ @Test+ fun testResourceIdZeroValueConstant() {+ assertEquals(0, AssetUtils.RESOURCE_ID_ZERO_VALUE)+ }++ @Test+ fun testGetResourceBaseName_pathProcessing() {+ // When path contains /, it returns everything after last / INCLUDING extension+ val testCases = mapOf(+ "sounds/notification.wav" to "notification.wav",+ "res/drawable/icon.png" to "icon.png",+ "assets/audio/beep.mp3" to "beep.mp3",+ "/absolute/path/file.jpg" to "file.jpg"+ )++ for ((input, expected) in testCases) {+ assertEquals("Failed for input: $input", expected, AssetUtils.getResourceBaseName(input))+ }+ }++ @Test+ fun testGetResourceBaseName_edgeCases() {+ // File with only extension (no slash, so extension is stripped)+ assertEquals("", AssetUtils.getResourceBaseName(".hidden"))++ // Path ending with slash+ assertEquals("", AssetUtils.getResourceBaseName("path/to/"))++ // Multiple slashes (has slash, so keeps extension)+ assertEquals("file.ext", AssetUtils.getResourceBaseName("path//to///file.ext"))++ // Dot in path but not in filename (has slash, returns as-is after /)+ assertEquals("file", AssetUtils.getResourceBaseName("path.v1/file"))+ }++ @Test+ fun testGetResourceID_packageContext() {+ // Verify it uses the correct package context (test package has .test suffix)+ val packageName = context.packageName+ assertEquals("app.tauri.notification.test", packageName)+ }++ @Test+ fun testGetResourceID_differentResourceTypes() {+ val resourceTypes = listOf("drawable", "raw", "string", "color", "layout", "id")++ for (type in resourceTypes) {+ val resId = AssetUtils.getResourceID(context, "test_resource", type)++ // Should not crash and return valid result (0 or positive)+ assertTrue("Failed for type: $type", resId >= 0)+ }+ }++ @Test+ fun testGetResourceBaseName_specialCharacters() {+ // With path (has /), keeps extension+ assertEquals("file_name.ext", AssetUtils.getResourceBaseName("path/file_name.ext"))+ // No path, strips extension+ assertEquals("file-name", AssetUtils.getResourceBaseName("file-name.ext"))+ assertEquals("file123", AssetUtils.getResourceBaseName("file123.ext"))+ }++ @Test+ fun testGetResourceBaseName_unicodeCharacters() {+ // Android resources typically don't support unicode, but test the base name extraction+ val result = AssetUtils.getResourceBaseName("path/файл.txt")+ assertTrue(result?.contains("файл") ?: false)+ }++ @Test+ fun testGetResourceID_emptyResourceName() {+ val resId = AssetUtils.getResourceID(context, "", "drawable")++ assertEquals(AssetUtils.RESOURCE_ID_ZERO_VALUE, resId)+ }++ @Test+ fun testGetResourceID_nullDirectory() {+ val resId = AssetUtils.getResourceID(context, "resource", null)++ // Should handle null directory gracefully+ assertEquals(AssetUtils.RESOURCE_ID_ZERO_VALUE, resId)+ }+}diff --git a/src-tauri/vendor/tauri-plugin-notifications/android/src/androidTest/java/app/tauri/notification/ChannelManagerInstrumentedTest.kt b/src-tauri/vendor/tauri-plugin-notifications/android/src/androidTest/java/app/tauri/notification/ChannelManagerInstrumentedTest.ktnew file mode 100644index 00000000..47f63e71--- /dev/null+++ b/src-tauri/vendor/tauri-plugin-notifications/android/src/androidTest/java/app/tauri/notification/ChannelManagerInstrumentedTest.kt@@ -0,0 +1,305 @@+package app.tauri.notification++import android.app.NotificationManager+import android.content.Context+import android.os.Build+import androidx.test.ext.junit.runners.AndroidJUnit4+import androidx.test.platform.app.InstrumentationRegistry+import org.junit.After+import org.junit.Assert.*+import org.junit.Before+import org.junit.Test+import org.junit.runner.RunWith++@RunWith(AndroidJUnit4::class)+class ChannelManagerInstrumentedTest {++ private lateinit var context: Context+ private lateinit var channelManager: ChannelManager+ private lateinit var notificationManager: NotificationManager+ private val testChannelIds = mutableListOf<String>()++ @Before+ fun setup() {+ context = InstrumentationRegistry.getInstrumentation().targetContext+ channelManager = ChannelManager(context)+ notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager+ }++ @After+ fun cleanup() {+ // Clean up test channels (only on O+)+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {+ for (channelId in testChannelIds) {+ try {+ notificationManager.deleteNotificationChannel(channelId)+ } catch (e: Exception) {+ // Ignore cleanup errors+ }+ }+ }+ testChannelIds.clear()+ }++ @Test+ fun testChannelCreationOnSupportedDevices() {+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {+ val channelId = "test_channel_1"+ val channelName = "Test Channel"+ val importance = android.app.NotificationManager.IMPORTANCE_HIGH++ testChannelIds.add(channelId)++ // Actually create the channel using Android API+ val notificationChannel = android.app.NotificationChannel(+ channelId,+ channelName,+ importance+ )+ notificationChannel.description = "A test notification channel"+ notificationChannel.lockscreenVisibility = android.app.Notification.VISIBILITY_PUBLIC++ notificationManager.createNotificationChannel(notificationChannel)++ // Verify channel was created+ val retrievedChannel = notificationManager.getNotificationChannel(channelId)+ assertNotNull(retrievedChannel)+ assertEquals(channelId, retrievedChannel?.id)+ assertEquals(channelName, retrievedChannel?.name.toString())+ } else {+ // On pre-O devices, channels are not supported+ // Test should still pass+ assertTrue(true)+ }+ }++ @Test+ fun testChannelImportanceLevels() {+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {+ val importanceLevels = listOf(+ Importance.None to "none",+ Importance.Min to "min",+ Importance.Low to "low",+ Importance.Default to "default",+ Importance.High to "high"+ )++ for ((importance, suffix) in importanceLevels) {+ val channel = Channel()+ channel.id = "test_importance_$suffix"+ channel.name = "Test $suffix"+ channel.importance = importance++ testChannelIds.add(channel.id)++ // Verify importance value is correct+ assertEquals(importance.value, when (importance) {+ Importance.None -> 0+ Importance.Min -> 1+ Importance.Low -> 2+ Importance.Default -> 3+ Importance.High -> 4+ })+ }+ }+ }++ @Test+ fun testChannelVisibilityLevels() {+ val visibilityLevels = listOf(+ Visibility.Secret to -1,+ Visibility.Private to 0,+ Visibility.Public to 1+ )++ for ((visibility, expectedValue) in visibilityLevels) {+ assertEquals(expectedValue, visibility.value)+ }+ }++ @Test+ fun testChannelWithAllProperties() {+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {+ val channel = Channel()+ channel.id = "test_full_channel"+ channel.name = "Full Test Channel"+ channel.description = "Channel with all properties"+ channel.importance = Importance.High+ channel.visibility = Visibility.Private+ channel.lights = true+ channel.lightsColor = "#FF0000"+ channel.vibration = true++ testChannelIds.add(channel.id)++ // Verify all properties are set+ assertEquals("test_full_channel", channel.id)+ assertEquals("Full Test Channel", channel.name)+ assertEquals("Channel with all properties", channel.description)+ assertEquals(Importance.High, channel.importance)+ assertEquals(Visibility.Private, channel.visibility)+ assertTrue(channel.lights ?: false)+ assertEquals("#FF0000", channel.lightsColor)+ assertTrue(channel.vibration ?: false)+ }+ }++ @Test+ fun testChannelDefaultValues() {+ val channel = Channel()+ channel.id = "test_defaults"+ channel.name = "Defaults"++ testChannelIds.add(channel.id)++ // Verify defaults+ assertNull(channel.description)+ assertNull(channel.sound)+ assertNull(channel.lights)+ assertNull(channel.lightsColor)+ assertNull(channel.vibration)+ assertNull(channel.importance)+ assertNull(channel.visibility)+ }++ @Test+ fun testDeleteChannelArgs() {+ val args = DeleteChannelArgs()+ args.id = "channel_to_delete"++ assertEquals("channel_to_delete", args.id)+ }++ @Test+ fun testMultipleChannels() {+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {+ val channels = listOf(+ Channel().apply {+ id = "channel1"+ name = "Channel 1"+ importance = Importance.Low+ },+ Channel().apply {+ id = "channel2"+ name = "Channel 2"+ importance = Importance.High+ },+ Channel().apply {+ id = "channel3"+ name = "Channel 3"+ importance = Importance.Default+ }+ )++ channels.forEach { testChannelIds.add(it.id) }++ // Verify all channels have correct properties+ assertEquals(3, channels.size)+ assertEquals(Importance.Low, channels[0].importance)+ assertEquals(Importance.High, channels[1].importance)+ assertEquals(Importance.Default, channels[2].importance)+ }+ }++ @Test+ fun testChannelWithSound() {+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {+ val channel = Channel()+ channel.id = "test_sound_channel"+ channel.name = "Sound Channel"+ channel.sound = "notification_sound"++ testChannelIds.add(channel.id)++ assertEquals("notification_sound", channel.sound)+ }+ }++ @Test+ fun testChannelLightColors() {+ val colors = listOf(+ "#FF0000" to "red",+ "#00FF00" to "green",+ "#0000FF" to "blue",+ "#FFFFFF" to "white",+ "#000000" to "black"+ )++ for ((color, _) in colors) {+ val channel = Channel()+ channel.lightsColor = color+ assertEquals(color, channel.lightsColor)+ }+ }++ @Test+ fun testChannelBooleanFlags() {+ val channel = Channel()+ channel.id = "test_flags"+ channel.name = "Flags"+ channel.lights = true+ channel.vibration = false++ testChannelIds.add(channel.id)++ assertTrue(channel.lights ?: false)+ assertFalse(channel.vibration ?: true)+ }++ @Test+ fun testImportanceEnumValues() {+ val values = Importance.values()+ assertEquals(5, values.size)++ assertEquals(0, Importance.None.value)+ assertEquals(1, Importance.Min.value)+ assertEquals(2, Importance.Low.value)+ assertEquals(3, Importance.Default.value)+ assertEquals(4, Importance.High.value)+ }++ @Test+ fun testVisibilityEnumValues() {+ val values = Visibility.values()+ assertEquals(3, values.size)++ assertEquals(-1, Visibility.Secret.value)+ assertEquals(0, Visibility.Private.value)+ assertEquals(1, Visibility.Public.value)+ }++ @Test+ fun testChannelIdRequired() {+ val channel = Channel()+ channel.name = "Test"++ // ID should be lateinit and not yet initialized+ // This will throw if accessed before being set+ try {+ @Suppress("UNUSED_VARIABLE")+ val id = channel.id+ fail("Expected UninitializedPropertyAccessException")+ } catch (e: Exception) {+ // Expected - lateinit var not initialized+ assertTrue(e is UninitializedPropertyAccessException ||+ e.message?.contains("lateinit") == true)+ }+ }++ @Test+ fun testChannelNameRequired() {+ val channel = Channel()+ channel.id = "test"++ // Name should be lateinit and not yet initialized+ try {+ @Suppress("UNUSED_VARIABLE")+ val name = channel.name+ fail("Expected UninitializedPropertyAccessException")+ } catch (e: Exception) {+ // Expected - lateinit var not initialized+ assertTrue(e is UninitializedPropertyAccessException ||+ e.message?.contains("lateinit") == true)+ }+ }+}diff --git a/src-tauri/vendor/tauri-plugin-notifications/android/src/androidTest/java/app/tauri/notification/DateMatchInstrumentedTest.kt b/src-tauri/vendor/tauri-plugin-notifications/android/src/androidTest/java/app/tauri/notification/DateMatchInstrumentedTest.ktnew file mode 100644index 00000000..36becdda--- /dev/null+++ b/src-tauri/vendor/tauri-plugin-notifications/android/src/androidTest/java/app/tauri/notification/DateMatchInstrumentedTest.kt@@ -0,0 +1,335 @@+package app.tauri.notification++import androidx.test.ext.junit.runners.AndroidJUnit4+import org.junit.Assert.*+import org.junit.Test+import org.junit.runner.RunWith+import java.util.*++@RunWith(AndroidJUnit4::class)+class DateMatchInstrumentedTest {++ @Test+ fun testNextTrigger_futureTime() {+ val dateMatch = DateMatch()+ dateMatch.hour = 23+ dateMatch.minute = 59+ dateMatch.second = 0++ val now = Calendar.getInstance()+ now.set(Calendar.HOUR_OF_DAY, 10)+ now.set(Calendar.MINUTE, 0)+ now.set(Calendar.SECOND, 0)+ now.set(Calendar.MILLISECOND, 0)++ val nextTrigger = dateMatch.nextTrigger(now.time)++ assertTrue(nextTrigger > now.timeInMillis)++ val resultCalendar = Calendar.getInstance()+ resultCalendar.timeInMillis = nextTrigger++ assertEquals(23, resultCalendar.get(Calendar.HOUR_OF_DAY))+ assertEquals(59, resultCalendar.get(Calendar.MINUTE))+ assertEquals(0, resultCalendar.get(Calendar.SECOND))+ }++ @Test+ fun testNextTrigger_specificDate() {+ val dateMatch = DateMatch()+ dateMatch.month = Calendar.DECEMBER+ dateMatch.day = 25+ dateMatch.hour = 9+ dateMatch.minute = 0++ val now = Calendar.getInstance()+ now.set(Calendar.MONTH, Calendar.JANUARY)+ now.set(Calendar.DAY_OF_MONTH, 1)+ now.set(Calendar.HOUR_OF_DAY, 12)+ now.set(Calendar.MINUTE, 0)+ now.set(Calendar.SECOND, 0)+ now.set(Calendar.MILLISECOND, 0)++ val nextTrigger = dateMatch.nextTrigger(now.time)++ val resultCalendar = Calendar.getInstance()+ resultCalendar.timeInMillis = nextTrigger++ assertEquals(Calendar.DECEMBER, resultCalendar.get(Calendar.MONTH))+ assertEquals(25, resultCalendar.get(Calendar.DAY_OF_MONTH))+ assertEquals(9, resultCalendar.get(Calendar.HOUR_OF_DAY))+ assertEquals(0, resultCalendar.get(Calendar.MINUTE))+ }++ @Test+ fun testDateMatchSerialization() {+ val original = DateMatch()+ original.year = 2024+ original.month = 11+ original.day = 26+ original.hour = 14+ original.minute = 30+ original.second = 15++ val matchString = original.toMatchString()+ val restored = DateMatch.fromMatchString(matchString)++ assertEquals(original.year, restored.year)+ assertEquals(original.month, restored.month)+ assertEquals(original.day, restored.day)+ assertEquals(original.hour, restored.hour)+ assertEquals(original.minute, restored.minute)+ assertEquals(original.second, restored.second)+ }++ @Test+ fun testDateMatchWithWildcards() {+ val dateMatch = DateMatch()+ dateMatch.hour = 15+ dateMatch.minute = 30+ // Other fields are null (wildcards)++ val matchString = dateMatch.toMatchString()+ assertTrue(matchString.contains("*"))+ assertTrue(matchString.contains("15"))+ assertTrue(matchString.contains("30"))++ val restored = DateMatch.fromMatchString(matchString)+ assertNull(restored.year)+ assertNull(restored.month)+ assertNull(restored.day)+ assertEquals(15, restored.hour)+ assertEquals(30, restored.minute)+ }++ @Test+ fun testGetIntervalTime_allIntervals() {+ val testCases = mapOf(+ NotificationInterval.Second to 1000L,+ NotificationInterval.Minute to 60 * 1000L,+ NotificationInterval.Hour to 60 * 60 * 1000L,+ NotificationInterval.Day to 24 * 60 * 60 * 1000L,+ NotificationInterval.Week to 7 * 24 * 60 * 60 * 1000L,+ NotificationInterval.TwoWeeks to 14 * 24 * 60 * 60 * 1000L+ )++ for ((interval, expectedMillis) in testCases) {+ val result = getIntervalTime(interval, 1)+ assertEquals("Failed for interval: $interval", expectedMillis, result)+ }+ }++ @Test+ fun testGetIntervalTime_multipleCount() {+ assertEquals(3000L, getIntervalTime(NotificationInterval.Second, 3))+ assertEquals(5 * 60 * 1000L, getIntervalTime(NotificationInterval.Minute, 5))+ assertEquals(2 * 60 * 60 * 1000L, getIntervalTime(NotificationInterval.Hour, 2))+ assertEquals(7 * 24 * 60 * 60 * 1000L, getIntervalTime(NotificationInterval.Day, 7))+ }++ @Test+ fun testNotificationScheduleAt_properties() {+ val schedule = NotificationSchedule.At()+ schedule.date = Date()+ schedule.repeating = true+ schedule.allowWhileIdle = true++ assertTrue(schedule.repeating)+ assertTrue(schedule.allowWhileIdle)+ assertFalse(schedule.isRemovable())+ assertTrue(schedule.allowWhileIdle())+ }++ @Test+ fun testNotificationScheduleAt_nonRepeating() {+ val schedule = NotificationSchedule.At()+ schedule.date = Date()+ schedule.repeating = false+ schedule.allowWhileIdle = false++ assertFalse(schedule.repeating)+ assertTrue(schedule.isRemovable())+ assertFalse(schedule.allowWhileIdle())+ }++ @Test+ fun testNotificationScheduleEvery() {+ val schedule = NotificationSchedule.Every()+ schedule.interval = NotificationInterval.Hour+ schedule.count = 2+ schedule.allowWhileIdle = true++ assertEquals(NotificationInterval.Hour, schedule.interval)+ assertEquals(2, schedule.count)+ assertTrue(schedule.allowWhileIdle())+ assertFalse(schedule.isRemovable())+ }++ @Test+ fun testNotificationScheduleInterval() {+ val dateMatch = DateMatch()+ dateMatch.hour = 10+ dateMatch.minute = 30++ val schedule = NotificationSchedule.Interval()+ schedule.interval = dateMatch+ schedule.allowWhileIdle = false++ assertEquals(dateMatch, schedule.interval)+ assertFalse(schedule.allowWhileIdle())+ assertFalse(schedule.isRemovable())+ }++ @Test+ fun testDateMatchEquals() {+ val date1 = DateMatch()+ date1.year = 2024+ date1.month = 11+ date1.day = 26++ val date2 = DateMatch()+ date2.year = 2024+ date2.month = 11+ date2.day = 26++ assertEquals(date1, date2)+ assertEquals(date1.hashCode(), date2.hashCode())+ }++ @Test+ fun testDateMatchNotEquals() {+ val date1 = DateMatch()+ date1.year = 2024+ date1.month = 11++ val date2 = DateMatch()+ date2.year = 2024+ date2.month = 12++ assertNotEquals(date1, date2)+ }++ @Test+ fun testNextTrigger_hourlyRecurrence() {+ val dateMatch = DateMatch()+ dateMatch.minute = 30+ dateMatch.second = 0++ val now = Calendar.getInstance()+ now.set(Calendar.MINUTE, 0)+ now.set(Calendar.SECOND, 0)+ now.set(Calendar.MILLISECOND, 0)++ val nextTrigger = dateMatch.nextTrigger(now.time)++ val resultCalendar = Calendar.getInstance()+ resultCalendar.timeInMillis = nextTrigger++ assertEquals(30, resultCalendar.get(Calendar.MINUTE))+ assertEquals(0, resultCalendar.get(Calendar.SECOND))+ }++ @Test+ fun testNextTrigger_dailyRecurrence() {+ val dateMatch = DateMatch()+ dateMatch.hour = 8+ dateMatch.minute = 0+ dateMatch.second = 0++ val now = Calendar.getInstance()+ now.set(Calendar.HOUR_OF_DAY, 20)+ now.set(Calendar.MINUTE, 0)+ now.set(Calendar.SECOND, 0)+ now.set(Calendar.MILLISECOND, 0)++ val nextTrigger = dateMatch.nextTrigger(now.time)++ assertTrue(nextTrigger > now.timeInMillis)++ val resultCalendar = Calendar.getInstance()+ resultCalendar.timeInMillis = nextTrigger++ assertEquals(8, resultCalendar.get(Calendar.HOUR_OF_DAY))+ assertEquals(0, resultCalendar.get(Calendar.MINUTE))+ }++ @Test+ fun testNotificationInterval_allValues() {+ val intervals = NotificationInterval.values()++ assertEquals(8, intervals.size)+ assertTrue(intervals.contains(NotificationInterval.Year))+ assertTrue(intervals.contains(NotificationInterval.Month))+ assertTrue(intervals.contains(NotificationInterval.TwoWeeks))+ assertTrue(intervals.contains(NotificationInterval.Week))+ assertTrue(intervals.contains(NotificationInterval.Day))+ assertTrue(intervals.contains(NotificationInterval.Hour))+ assertTrue(intervals.contains(NotificationInterval.Minute))+ assertTrue(intervals.contains(NotificationInterval.Second))+ }++ @Test+ fun testScheduleToString() {+ val scheduleAt = NotificationSchedule.At()+ scheduleAt.date = Date(1234567890000L)+ scheduleAt.repeating = true++ val stringAt = scheduleAt.toString()+ assertTrue(stringAt.contains("At"))+ assertTrue(stringAt.contains("repeating=true"))++ val scheduleEvery = NotificationSchedule.Every()+ scheduleEvery.interval = NotificationInterval.Day+ scheduleEvery.count = 3++ val stringEvery = scheduleEvery.toString()+ assertTrue(stringEvery.contains("Every"))+ assertTrue(stringEvery.contains("Day"))+ assertTrue(stringEvery.contains("count=3"))+ }++ @Test+ fun testDateMatchToString() {+ val dateMatch = DateMatch()+ dateMatch.year = 2024+ dateMatch.month = 11+ dateMatch.day = 26+ dateMatch.hour = 14+ dateMatch.minute = 30++ val result = dateMatch.toString()+ assertTrue(result.contains("2024"))+ assertTrue(result.contains("11"))+ assertTrue(result.contains("26"))+ assertTrue(result.contains("14"))+ assertTrue(result.contains("30"))+ }++ @Test+ fun testGetIntervalTime_yearAndMonth() {+ // These are approximations+ val yearMillis = getIntervalTime(NotificationInterval.Year, 1)+ val monthMillis = getIntervalTime(NotificationInterval.Month, 1)++ // Year ≈ 52 weeks+ assertEquals(52 * 7 * 24 * 60 * 60 * 1000L, yearMillis)++ // Month ≈ 30 days+ assertEquals(30 * 24 * 60 * 60 * 1000L, monthMillis)+ }++ @Test+ fun testDateMatchWithWeekday() {+ val dateMatch = DateMatch()+ dateMatch.weekday = Calendar.MONDAY+ dateMatch.hour = 9+ dateMatch.minute = 0++ val matchString = dateMatch.toMatchString()+ val restored = DateMatch.fromMatchString(matchString)++ assertEquals(Calendar.MONDAY, restored.weekday)+ assertEquals(9, restored.hour)+ assertEquals(0, restored.minute)+ }+}diff --git a/src-tauri/vendor/tauri-plugin-notifications/android/src/androidTest/java/app/tauri/notification/NotificationInstrumentedTest.kt b/src-tauri/vendor/tauri-plugin-notifications/android/src/androidTest/java/app/tauri/notification/NotificationInstrumentedTest.ktnew file mode 100644index 00000000..f4f978bc--- /dev/null+++ b/src-tauri/vendor/tauri-plugin-notifications/android/src/androidTest/java/app/tauri/notification/NotificationInstrumentedTest.kt@@ -0,0 +1,342 @@+package app.tauri.notification++import android.content.Context+import androidx.test.ext.junit.runners.AndroidJUnit4+import androidx.test.platform.app.InstrumentationRegistry+import app.tauri.plugin.JSObject+import org.junit.Assert.*+import org.junit.Before+import org.junit.Test+import org.junit.runner.RunWith++@RunWith(AndroidJUnit4::class)+class NotificationInstrumentedTest {++ private lateinit var context: Context++ @Before+ fun setup() {+ context = InstrumentationRegistry.getInstrumentation().targetContext+ }++ @Test+ fun testGetSound_withDefaultSound() {+ val notification = Notification()+ notification.sound = null++ // Use a valid resource ID as default+ val result = notification.getSound(context, 12345)++ assertNotNull(result)+ assertTrue(result!!.startsWith("android.resource://"))+ assertTrue(result.contains(context.packageName))+ }++ @Test+ fun testGetSound_customSoundNotFound_fallbackToDefault() {+ val notification = Notification()+ notification.sound = "nonexistent_sound.mp3"++ val result = notification.getSound(context, 54321)++ assertNotNull(result)+ assertTrue(result!!.contains("android.resource://"))+ }++ @Test+ fun testGetSound_nullDefaultSound() {+ val notification = Notification()+ notification.sound = null++ val result = notification.getSound(context, AssetUtils.RESOURCE_ID_ZERO_VALUE)++ assertNull(result)+ }++ @Test+ fun testGetIconColor_localColorTakesPrecedence() {+ val notification = Notification()+ notification.iconColor = "#FF0000"++ val result = notification.getIconColor("#00FF00")++ assertEquals("#FF0000", result)+ }++ @Test+ fun testGetIconColor_globalColorFallback() {+ val notification = Notification()+ notification.iconColor = null++ val result = notification.getIconColor("#00FF00")++ assertEquals("#00FF00", result)+ }++ @Test+ fun testGetSmallIcon_withDefaultIcon() {+ val notification = Notification()+ notification.icon = null++ val result = notification.getSmallIcon(context, android.R.drawable.ic_dialog_info)++ assertEquals(android.R.drawable.ic_dialog_info, result)+ }++ @Test+ fun testGetSmallIcon_customIconNotFound() {+ val notification = Notification()+ notification.icon = "nonexistent_icon"++ val result = notification.getSmallIcon(context, android.R.drawable.ic_dialog_alert)++ assertEquals(android.R.drawable.ic_dialog_alert, result)+ }++ @Test+ fun testGetLargeIcon_noIcon() {+ val notification = Notification()+ notification.largeIcon = null++ val result = notification.getLargeIcon(context)++ assertNull(result)+ }++ @Test+ fun testGetLargeIcon_customIcon() {+ val notification = Notification()+ notification.largeIcon = "ic_transparent"++ val result = notification.getLargeIcon(context)++ // May be null if resource doesn't exist, but should not crash+ // If it finds the resource, it should return a Bitmap+ assertTrue(result == null || result.width > 0)+ }++ @Test+ fun testBuildNotificationPendingList() {+ val notifications = listOf(+ Notification().apply {+ id = 1+ title = "First"+ body = "Body 1"+ schedule = NotificationSchedule.At()+ extra = JSObject()+ },+ Notification().apply {+ id = 2+ title = "Second"+ body = "Body 2"+ schedule = NotificationSchedule.Every().apply {+ interval = NotificationInterval.Hour+ count = 1+ }+ extra = JSObject()+ }+ )++ val pendingList = Notification.buildNotificationPendingList(notifications)++ assertEquals(2, pendingList.size)+ assertEquals(1, pendingList[0].id)+ assertEquals("First", pendingList[0].title)+ assertEquals(2, pendingList[1].id)+ assertEquals("Second", pendingList[1].title)+ }++ @Test+ fun testNotificationProperties() {+ val notification = Notification()+ notification.id = 100+ notification.title = "Test Title"+ notification.body = "Test Body"+ notification.largeBody = "Large body text"+ notification.summary = "Summary"+ notification.sound = "notification.mp3"+ notification.icon = "ic_notification"+ notification.largeIcon = "ic_large"+ notification.iconColor = "#FF5733"+ notification.actionTypeId = "action_type"+ notification.group = "test_group"+ notification.inboxLines = listOf("Line 1", "Line 2", "Line 3")+ notification.isGroupSummary = true+ notification.isOngoing = false+ notification.isAutoCancel = true+ notification.channelId = "test_channel"+ notification.visibility = 1+ notification.number = 5++ assertEquals(100, notification.id)+ assertEquals("Test Title", notification.title)+ assertEquals("Test Body", notification.body)+ assertEquals("Large body text", notification.largeBody)+ assertEquals("Summary", notification.summary)+ assertEquals("notification.mp3", notification.sound)+ assertEquals("ic_notification", notification.icon)+ assertEquals("ic_large", notification.largeIcon)+ assertEquals("#FF5733", notification.iconColor)+ assertEquals("action_type", notification.actionTypeId)+ assertEquals("test_group", notification.group)+ assertEquals(3, notification.inboxLines?.size)+ assertTrue(notification.isGroupSummary)+ assertFalse(notification.isOngoing)+ assertTrue(notification.isAutoCancel)+ assertEquals("test_channel", notification.channelId)+ assertEquals(1, notification.visibility)+ assertEquals(5, notification.number)+ }++ @Test+ fun testNotificationWithSchedule() {+ val schedule = NotificationSchedule.At().apply {+ repeating = true+ allowWhileIdle = false+ }++ val notification = Notification()+ notification.id = 200+ notification.title = "Scheduled"+ notification.schedule = schedule++ assertNotNull(notification.schedule)+ assertTrue((notification.schedule as NotificationSchedule.At).repeating)+ assertFalse((notification.schedule as NotificationSchedule.At).allowWhileIdle)+ }++ @Test+ fun testNotificationWithAttachments() {+ val attachment = NotificationAttachment()+ attachment.id = "image1"+ attachment.url = "file:///path/to/image.jpg"++ val notification = Notification()+ notification.id = 300+ notification.attachments = listOf(attachment)++ assertNotNull(notification.attachments)+ assertEquals(1, notification.attachments?.size)+ assertEquals("image1", notification.attachments?.get(0)?.id)+ }++ @Test+ fun testNotificationWithExtraData() {+ val extra = JSObject()+ extra.put("custom_key", "custom_value")+ extra.put("number", 42)++ val notification = Notification()+ notification.id = 400+ notification.extra = extra++ assertNotNull(notification.extra)+ assertEquals("custom_value", notification.extra?.getString("custom_key"))+ assertEquals(42, notification.extra?.getInt("number"))+ }++ @Test+ fun testPendingNotificationProperties() {+ val schedule = NotificationSchedule.Every().apply {+ interval = NotificationInterval.Day+ count = 1+ }+ val extra = JSObject()+ extra.put("key", "value")++ val pendingNotification = PendingNotification().apply {+ id = 500+ title = "Pending"+ body = "Pending body"+ this.schedule = schedule+ this.extra = extra+ }++ assertEquals(500, pendingNotification.id)+ assertEquals("Pending", pendingNotification.title)+ assertEquals("Pending body", pendingNotification.body)+ assertNotNull(pendingNotification.schedule)+ assertNotNull(pendingNotification.extra)+ }++ @Test+ fun testNotificationInboxLines() {+ val notification = Notification()+ notification.id = 600+ notification.inboxLines = listOf(+ "Message from Alice",+ "Message from Bob",+ "Message from Charlie",+ "Message from David",+ "Message from Eve"+ )++ assertEquals(5, notification.inboxLines?.size)+ assertEquals("Message from Alice", notification.inboxLines?.get(0))+ assertEquals("Message from Eve", notification.inboxLines?.get(4))+ }++ @Test+ fun testNotificationGroupSummary() {+ val summary = Notification()+ summary.id = 700+ summary.group = "messages"+ summary.isGroupSummary = true+ summary.summary = "5 new messages"++ assertTrue(summary.isGroupSummary)+ assertEquals("messages", summary.group)+ assertEquals("5 new messages", summary.summary)+ }++ @Test+ fun testNotificationOngoing() {+ val notification = Notification()+ notification.id = 800+ notification.isOngoing = true+ notification.isAutoCancel = false++ assertTrue(notification.isOngoing)+ assertFalse(notification.isAutoCancel)+ }++ @Test+ fun testNotificationVisibility() {+ val visibilityLevels = listOf(+ -1, // Secret+ 0, // Private+ 1 // Public+ )++ for (visibility in visibilityLevels) {+ val notification = Notification()+ notification.visibility = visibility++ assertEquals(visibility, notification.visibility)+ }+ }++ @Test+ fun testNotificationWithNullValues() {+ val notification = Notification()+ notification.id = 900++ assertNull(notification.title)+ assertNull(notification.body)+ assertNull(notification.largeBody)+ assertNull(notification.summary)+ assertNull(notification.sound)+ assertNull(notification.icon)+ assertNull(notification.largeIcon)+ assertNull(notification.iconColor)+ assertNull(notification.actionTypeId)+ assertNull(notification.group)+ assertNull(notification.inboxLines)+ assertNull(notification.extra)+ assertNull(notification.attachments)+ assertNull(notification.schedule)+ assertNull(notification.channelId)+ assertNull(notification.visibility)+ assertNull(notification.number)+ }+}diff --git a/src-tauri/vendor/tauri-plugin-notifications/android/src/androidTest/java/app/tauri/notification/NotificationStorageInstrumentedTest.kt b/src-tauri/vendor/tauri-plugin-notifications/android/src/androidTest/java/app/tauri/notification/NotificationStorageInstrumentedTest.ktnew file mode 100644index 00000000..7160eeeb--- /dev/null+++ b/src-tauri/vendor/tauri-plugin-notifications/android/src/androidTest/java/app/tauri/notification/NotificationStorageInstrumentedTest.kt@@ -0,0 +1,272 @@+package app.tauri.notification++import androidx.test.ext.junit.runners.AndroidJUnit4+import androidx.test.platform.app.InstrumentationRegistry+import com.fasterxml.jackson.databind.ObjectMapper+import org.junit.After+import org.junit.Assert.*+import org.junit.Before+import org.junit.Test+import org.junit.runner.RunWith++@RunWith(AndroidJUnit4::class)+class NotificationStorageInstrumentedTest {++ private lateinit var storage: NotificationStorage+ private lateinit var objectMapper: ObjectMapper++ @Before+ fun setup() {+ val context = InstrumentationRegistry.getInstrumentation().targetContext+ objectMapper = ObjectMapper()+ storage = NotificationStorage(context, objectMapper)++ // Clear any existing data+ clearAllNotifications()+ }++ @After+ fun cleanup() {+ clearAllNotifications()+ }++ private fun clearAllNotifications() {+ val ids = storage.getSavedNotificationIds()+ for (id in ids) {+ storage.deleteNotification(id)+ }+ }++ @Test+ fun testSaveAndRetrieveNotification() {+ val notification = Notification()+ notification.id = 100+ notification.title = "Test Notification"+ notification.body = "Test Body"+ notification.schedule = NotificationSchedule.At().apply {+ repeating = false+ }+ notification.sourceJson = """{"id":100,"title":"Test Notification","body":"Test Body"}"""++ storage.appendNotifications(listOf(notification))++ val ids = storage.getSavedNotificationIds()+ assertTrue(ids.contains("100"))++ val retrieved = storage.getSavedNotification("100")+ assertNotNull(retrieved)+ assertEquals(100, retrieved?.id)+ assertEquals("Test Notification", retrieved?.title)+ }++ @Test+ fun testSaveMultipleNotifications() {+ val notifications = listOf(+ Notification().apply {+ id = 1+ title = "First"+ schedule = NotificationSchedule.At()+ sourceJson = """{"id":1}"""+ },+ Notification().apply {+ id = 2+ title = "Second"+ schedule = NotificationSchedule.Every().apply {+ interval = NotificationInterval.Hour+ count = 1+ }+ sourceJson = """{"id":2}"""+ },+ Notification().apply {+ id = 3+ title = "Third"+ schedule = NotificationSchedule.Interval().apply {+ interval = DateMatch()+ }+ sourceJson = """{"id":3}"""+ }+ )++ storage.appendNotifications(notifications)++ val ids = storage.getSavedNotificationIds()+ assertEquals(3, ids.size)+ assertTrue(ids.contains("1"))+ assertTrue(ids.contains("2"))+ assertTrue(ids.contains("3"))+ }++ @Test+ fun testDeleteNotification() {+ val notification = Notification()+ notification.id = 200+ notification.title = "To Delete"+ notification.schedule = NotificationSchedule.At()+ notification.sourceJson = """{"id":200}"""++ storage.appendNotifications(listOf(notification))++ var ids = storage.getSavedNotificationIds()+ assertTrue(ids.contains("200"))++ storage.deleteNotification("200")++ ids = storage.getSavedNotificationIds()+ assertFalse(ids.contains("200"))+ }++ @Test+ fun testGetSavedNotifications() {+ val notifications = listOf(+ Notification().apply {+ id = 10+ title = "First"+ body = "Body 1"+ schedule = NotificationSchedule.At()+ sourceJson = """{"id":10,"title":"First","body":"Body 1"}"""+ },+ Notification().apply {+ id = 20+ title = "Second"+ body = "Body 2"+ schedule = NotificationSchedule.At()+ sourceJson = """{"id":20,"title":"Second","body":"Body 2"}"""+ }+ )++ storage.appendNotifications(notifications)++ val retrieved = storage.getSavedNotifications()+ assertTrue(retrieved.size >= 2)++ val ids = retrieved.map { it.id }+ assertTrue(ids.contains(10))+ assertTrue(ids.contains(20))+ }++ @Test+ fun testSaveActionGroups() {+ val action1 = NotificationAction()+ action1.id = "reply"+ action1.title = "Reply"+ action1.input = true++ val action2 = NotificationAction()+ action2.id = "dismiss"+ action2.title = "Dismiss"+ action2.input = false++ val actionType = ActionType()+ actionType.id = "message-actions"+ actionType.actions = listOf(action1, action2)++ storage.writeActionGroup(listOf(actionType))++ val retrieved = storage.getActionGroup("message-actions")++ assertEquals(2, retrieved.size)+ assertEquals("reply", retrieved[0]?.id)+ assertEquals("Reply", retrieved[0]?.title)+ assertEquals(true, retrieved[0]?.input)+ assertEquals("dismiss", retrieved[1]?.id)+ assertEquals("Dismiss", retrieved[1]?.title)+ assertEquals(false, retrieved[1]?.input)+ }++ @Test+ fun testOverwriteNotification() {+ val notification1 = Notification()+ notification1.id = 300+ notification1.title = "Original"+ notification1.schedule = NotificationSchedule.At()+ notification1.sourceJson = """{"id":300,"title":"Original"}"""++ storage.appendNotifications(listOf(notification1))++ val notification2 = Notification()+ notification2.id = 300+ notification2.title = "Updated"+ notification2.schedule = NotificationSchedule.At()+ notification2.sourceJson = """{"id":300,"title":"Updated"}"""++ storage.appendNotifications(listOf(notification2))++ val retrieved = storage.getSavedNotification("300")+ assertEquals("Updated", retrieved?.title)+ }++ @Test+ fun testNotificationWithoutScheduleNotSaved() {+ val notification = Notification()+ notification.id = 400+ notification.title = "No Schedule"+ notification.schedule = null+ notification.sourceJson = """{"id":400}"""++ storage.appendNotifications(listOf(notification))++ val ids = storage.getSavedNotificationIds()+ assertFalse(ids.contains("400"))+ }++ @Test+ fun testGetNonExistentNotification() {+ val retrieved = storage.getSavedNotification("999999")+ assertNull(retrieved)+ }++ @Test+ fun testEmptyActionGroup() {+ val retrieved = storage.getActionGroup("nonexistent-group")+ assertEquals(0, retrieved.size)+ }++ @Test+ fun testMultipleActionGroups() {+ val group1Actions = listOf(+ NotificationAction().apply {+ id = "action1"+ title = "Action 1"+ input = false+ }+ )+ val group1 = ActionType().apply {+ id = "group1"+ actions = group1Actions+ }++ val group2Actions = listOf(+ NotificationAction().apply {+ id = "action2"+ title = "Action 2"+ input = true+ },+ NotificationAction().apply {+ id = "action3"+ title = "Action 3"+ input = false+ }+ )+ val group2 = ActionType().apply {+ id = "group2"+ actions = group2Actions+ }++ storage.writeActionGroup(listOf(group1, group2))++ val retrieved1 = storage.getActionGroup("group1")+ assertEquals(1, retrieved1.size)+ assertEquals("action1", retrieved1[0]?.id)+ assertEquals("Action 1", retrieved1[0]?.title)+ assertEquals(false, retrieved1[0]?.input)++ val retrieved2 = storage.getActionGroup("group2")+ assertEquals(2, retrieved2.size)+ assertEquals("action2", retrieved2[0]?.id)+ assertEquals("Action 2", retrieved2[0]?.title)+ assertEquals(true, retrieved2[0]?.input)+ assertEquals("action3", retrieved2[1]?.id)+ assertEquals("Action 3", retrieved2[1]?.title)+ assertEquals(false, retrieved2[1]?.input)+ }+}diff --git a/src-tauri/vendor/tauri-plugin-notifications/android/src/main/AndroidManifest.xml b/src-tauri/vendor/tauri-plugin-notifications/android/src/main/AndroidManifest.xmlnew file mode 100644index 00000000..d5f3a81c--- /dev/null+++ b/src-tauri/vendor/tauri-plugin-notifications/android/src/main/AndroidManifest.xml@@ -0,0 +1,29 @@+<manifest xmlns:android="http://schemas.android.com/apk/res/android">++ <application>+ <receiver android:name="app.tauri.notification.TimedNotificationPublisher" android:exported="true" />+ <receiver android:name="app.tauri.notification.NotificationDismissReceiver" android:exported="false" />+ <receiver+ android:name="app.tauri.notification.LocalNotificationRestoreReceiver"+ android:directBootAware="true"+ android:exported="false">+ <intent-filter>+ <action android:name="android.intent.action.LOCKED_BOOT_COMPLETED" />+ <action android:name="android.intent.action.BOOT_COMPLETED" />+ <action android:name="android.intent.action.QUICKBOOT_POWERON" />+ </intent-filter>+ </receiver>++ <!-- Firebase Cloud Messaging Service for handling push notifications -->+ <service+ android:name="app.tauri.notification.TauriFirebaseMessagingService"+ android:exported="false">+ <intent-filter>+ <action android:name="com.google.firebase.MESSAGING_EVENT" />+ </intent-filter>+ </service>+ </application>+ <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />+ <uses-permission android:name="android.permission.WAKE_LOCK" />+ <uses-permission android:name="android.permission.POST_NOTIFICATIONS" />+</manifest>\ No newline at end of filediff --git a/src-tauri/vendor/tauri-plugin-notifications/android/src/main/java/app/tauri/notification/AssetUtils.kt b/src-tauri/vendor/tauri-plugin-notifications/android/src/main/java/app/tauri/notification/AssetUtils.ktnew file mode 100644index 00000000..c97cd528--- /dev/null+++ b/src-tauri/vendor/tauri-plugin-notifications/android/src/main/java/app/tauri/notification/AssetUtils.kt@@ -0,0 +1,25 @@+package app.tauri.notification++import android.annotation.SuppressLint+import android.content.Context++class AssetUtils {+ companion object {+ const val RESOURCE_ID_ZERO_VALUE = 0++ @SuppressLint("DiscouragedApi")+ fun getResourceID(context: Context, resourceName: String?, dir: String?): Int {+ return context.resources.getIdentifier(resourceName, dir, context.packageName)+ }++ fun getResourceBaseName(resPath: String?): String? {+ if (resPath == null) return null+ if (resPath.contains("/")) {+ return resPath.substring(resPath.lastIndexOf('/') + 1)+ }+ return if (resPath.contains(".")) {+ resPath.substring(0, resPath.lastIndexOf('.'))+ } else resPath+ }+ }+}diff --git a/src-tauri/vendor/tauri-plugin-notifications/android/src/main/java/app/tauri/notification/ChannelManager.kt b/src-tauri/vendor/tauri-plugin-notifications/android/src/main/java/app/tauri/notification/ChannelManager.ktnew file mode 100644index 00000000..3391d628--- /dev/null+++ b/src-tauri/vendor/tauri-plugin-notifications/android/src/main/java/app/tauri/notification/ChannelManager.kt@@ -0,0 +1,147 @@+package app.tauri.notification++import android.app.NotificationChannel+import android.app.NotificationManager+import android.content.ContentResolver+import android.content.Context+import android.graphics.Color+import android.media.AudioAttributes+import android.net.Uri+import android.os.Build+import app.tauri.Logger+import app.tauri.annotation.InvokeArg+import app.tauri.plugin.Invoke+import com.fasterxml.jackson.annotation.JsonValue++enum class Importance(@JsonValue val value: Int) {+ None(0),+ Min(1),+ Low(2),+ Default(3),+ High(4);+}++enum class Visibility(@JsonValue val value: Int) {+ Secret(-1),+ Private(0),+ Public(1);+}++@InvokeArg+class Channel {+ lateinit var id: String+ lateinit var name: String+ var description: String? = null+ var sound: String? = null+ var lights: Boolean? = null+ var lightsColor: String? = null+ var vibration: Boolean? = null+ var importance: Importance? = null+ var visibility: Visibility? = null+}++@InvokeArg+class DeleteChannelArgs {+ lateinit var id: String+}++class ChannelManager(private var context: Context) {+ private var notificationManager: NotificationManager? = null++ init {+ notificationManager =+ context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager?+ }++ fun createChannel(invoke: Invoke) {+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {+ val channel = invoke.parseArgs(Channel::class.java)+ createChannel(channel)+ invoke.resolve()+ } else {+ invoke.reject("channel not available")+ }+ }++ private fun createChannel(channel: Channel) {+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {+ val notificationChannel = NotificationChannel(+ channel.id,+ channel.name,+ (channel.importance ?: Importance.Default).value+ )+ notificationChannel.description = channel.description+ notificationChannel.lockscreenVisibility = (channel.visibility ?: Visibility.Private).value+ notificationChannel.enableVibration(channel.vibration ?: false)+ notificationChannel.enableLights(channel.lights ?: false)+ val lightColor = channel.lightsColor ?: ""+ if (lightColor.isNotEmpty()) {+ try {+ notificationChannel.lightColor = Color.parseColor(lightColor)+ } catch (ex: IllegalArgumentException) {+ Logger.error(+ Logger.tags("NotificationChannel"),+ "Invalid color provided for light color.",+ null+ )+ }+ }+ var sound = channel.sound ?: ""+ if (sound.isNotEmpty()) {+ if (sound.contains(".")) {+ sound = sound.substring(0, sound.lastIndexOf('.'))+ }+ val audioAttributes = AudioAttributes.Builder()+ .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)+ .setUsage(AudioAttributes.USAGE_NOTIFICATION)+ .build()+ val soundUri =+ Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + context.packageName + "/raw/" + sound)+ notificationChannel.setSound(soundUri, audioAttributes)+ }+ notificationManager?.createNotificationChannel(notificationChannel)+ }+ }++ fun deleteChannel(invoke: Invoke) {+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {+ val args = invoke.parseArgs(DeleteChannelArgs::class.java)+ notificationManager?.deleteNotificationChannel(args.id)+ invoke.resolve()+ } else {+ invoke.reject("channel not available")+ }+ }++ fun listChannels(invoke: Invoke) {+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {+ val notificationChannels: List<NotificationChannel> =+ notificationManager?.notificationChannels ?: listOf()++ val channels = mutableListOf<Channel>()++ for (notificationChannel in notificationChannels) {+ val channel = Channel()+ channel.id = notificationChannel.id+ channel.name = notificationChannel.name.toString()+ channel.description = notificationChannel.description+ channel.sound = notificationChannel.sound.toString()+ channel.lights = notificationChannel.shouldShowLights()+ String.format(+ "#%06X",+ 0xFFFFFF and notificationChannel.lightColor+ )+ channel.vibration = notificationChannel.shouldVibrate()+ channel.importance = Importance.values().firstOrNull { it.value == notificationChannel.importance }+ channel.visibility = Visibility.values().firstOrNull { it.value == notificationChannel.lockscreenVisibility }++ channels.add(channel)+ }++ invoke.resolveObject(channels)++ } else {+ invoke.reject("channel not available")+ }+ }+}\ No newline at end of filediff --git a/src-tauri/vendor/tauri-plugin-notifications/android/src/main/java/app/tauri/notification/Notification.kt b/src-tauri/vendor/tauri-plugin-notifications/android/src/main/java/app/tauri/notification/Notification.ktnew file mode 100644index 00000000..d1fd9c49--- /dev/null+++ b/src-tauri/vendor/tauri-plugin-notifications/android/src/main/java/app/tauri/notification/Notification.kt@@ -0,0 +1,176 @@+package app.tauri.notification++import android.content.ContentResolver+import android.content.Context+import android.graphics.Bitmap+import android.graphics.BitmapFactory+import android.os.Build+import android.service.notification.StatusBarNotification+import androidx.annotation.RequiresApi+import app.tauri.annotation.InvokeArg+import app.tauri.plugin.JSObject+import com.fasterxml.jackson.core.JsonParser+import com.fasterxml.jackson.databind.DeserializationContext+import com.fasterxml.jackson.databind.JsonDeserializer+import com.fasterxml.jackson.databind.JsonNode+import com.fasterxml.jackson.databind.annotation.JsonDeserialize++/**+ * Jackson can't reflect into `JSObject` (zero bean properties), so loading a+ * persisted notification with non-empty `extra` throws+ * `UnrecognizedPropertyException` on the first dynamic key. This deserializer+ * re-parses the JSON subtree through `JSObject`'s own JSON constructor, which+ * accepts arbitrary keys.+ */+class JSObjectDeserializer : JsonDeserializer<JSObject>() {+ override fun deserialize(p: JsonParser, ctxt: DeserializationContext): JSObject {+ val node: JsonNode = p.readValueAsTree()+ return JSObject(node.toString())+ }+}++@InvokeArg+class Notification {+ var id: Int = 0+ var title: String? = null+ var body: String? = null+ var largeBody: String? = null+ var summary: String? = null+ var sound: String? = null+ var icon: String? = null+ var largeIcon: String? = null+ var iconColor: String? = null+ var actionTypeId: String? = null+ var group: String? = null+ var inboxLines: List<String>? = null+ var isGroupSummary = false+ var isOngoing = false+ var isAutoCancel = false+ @JsonDeserialize(using = JSObjectDeserializer::class)+ var extra: JSObject? = null+ var attachments: List<NotificationAttachment>? = null+ var schedule: NotificationSchedule? = null+ var channelId: String? = null+ var sourceJson: String? = null+ var visibility: Int? = null+ var number: Int? = null+ var silent: Boolean? = null++ fun getSound(context: Context, defaultSound: Int): String? {+ var soundPath: String? = null+ var resId: Int = AssetUtils.RESOURCE_ID_ZERO_VALUE+ val name = AssetUtils.getResourceBaseName(sound)+ if (name != null) {+ resId = AssetUtils.getResourceID(context, name, "raw")+ }+ if (resId == AssetUtils.RESOURCE_ID_ZERO_VALUE) {+ resId = defaultSound+ }+ if (resId != AssetUtils.RESOURCE_ID_ZERO_VALUE) {+ soundPath =+ ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + context.packageName + "/" + resId+ }+ return soundPath+ }++ fun getIconColor(globalColor: String): String {+ // use the one defined local before trying for a globally defined color+ return iconColor ?: globalColor+ }++ fun getSmallIcon(context: Context, defaultIcon: Int): Int {+ var resId: Int = AssetUtils.RESOURCE_ID_ZERO_VALUE+ if (icon != null) {+ resId = AssetUtils.getResourceID(context, icon, "drawable")+ }+ if (resId == AssetUtils.RESOURCE_ID_ZERO_VALUE) {+ resId = defaultIcon+ }+ return resId+ }++ fun getLargeIcon(context: Context): Bitmap? {+ if (largeIcon != null) {+ val resId: Int = AssetUtils.getResourceID(context, largeIcon, "drawable")+ return BitmapFactory.decodeResource(context.resources, resId)+ }+ return null+ }++ companion object {+ fun buildNotificationPendingList(notifications: List<Notification>): List<PendingNotification> {+ val pendingNotifications = mutableListOf<PendingNotification>()+ for (notification in notifications) {+ val pendingNotification = PendingNotification().apply {+ id = notification.id+ title = notification.title+ body = notification.body+ schedule = notification.schedule+ extra = notification.extra+ }+ pendingNotifications.add(pendingNotification)+ }+ return pendingNotifications+ }++ @RequiresApi(Build.VERSION_CODES.M)+ fun buildNotificationActiveList(statusBarNotifications: Array<StatusBarNotification>): List<ActiveNotificationInfo> {+ val activeNotifications = mutableListOf<ActiveNotificationInfo>()+ for (statusBarNotification in statusBarNotifications) {+ val notification = statusBarNotification.notification+ val extractedData = mutableMapOf<String, String>()+ if (notification != null) {+ for (key in notification.extras.keySet()) {+ notification.extras.getString(key)?.let { value ->+ extractedData[key] = value+ }+ }+ }++ val activeNotification = ActiveNotificationInfo().apply {+ id = statusBarNotification.id+ tag = statusBarNotification.tag+ title = notification?.extras?.getCharSequence(android.app.Notification.EXTRA_TITLE)?.toString()+ body = notification?.extras?.getCharSequence(android.app.Notification.EXTRA_TEXT)?.toString()+ group = notification?.group+ groupSummary = notification?.let { 0 != it.flags and android.app.Notification.FLAG_GROUP_SUMMARY } ?: false+ data = extractedData+ }+ activeNotifications.add(activeNotification)+ }+ return activeNotifications+ }+ }+}++@InvokeArg+class PendingNotification {+ var id: Int = 0+ var title: String? = null+ var body: String? = null+ var schedule: NotificationSchedule? = null+ @JsonDeserialize(using = JSObjectDeserializer::class)+ var extra: JSObject? = null+}++@InvokeArg+class ActiveNotificationInfo {+ var id: Int = 0+ var tag: String? = null+ var title: String? = null+ var body: String? = null+ var group: String? = null+ var groupSummary: Boolean = false+ var data: Map<String, String> = emptyMap()+ var extra: Map<String, Any> = emptyMap()+ var attachments: List<AttachmentInfo> = emptyList()+ var actionTypeId: String? = null+ var schedule: NotificationSchedule? = null+ var sound: String? = null+}++@InvokeArg+class AttachmentInfo {+ var id: String = ""+ var url: String = ""+}\ No newline at end of filediff --git a/src-tauri/vendor/tauri-plugin-notifications/android/src/main/java/app/tauri/notification/NotificationAttachment.kt b/src-tauri/vendor/tauri-plugin-notifications/android/src/main/java/app/tauri/notification/NotificationAttachment.ktnew file mode 100644index 00000000..a62387b6--- /dev/null+++ b/src-tauri/vendor/tauri-plugin-notifications/android/src/main/java/app/tauri/notification/NotificationAttachment.kt@@ -0,0 +1,55 @@+package app.tauri.notification++import app.tauri.Logger+import app.tauri.plugin.JSObject+import org.json.JSONArray+import org.json.JSONException+import org.json.JSONObject++private const val ATTACHMENT_TAG = "NotificationAttachment"++class NotificationAttachment {+ var id: String? = null+ var url: String? = null+ var options: JSONObject? = null++ companion object {+ fun getAttachments(notification: JSObject): List<NotificationAttachment> {+ val attachmentsList: MutableList<NotificationAttachment> = ArrayList()+ var attachments: JSONArray? = null+ try {+ attachments = notification.getJSONArray("attachments")+ } catch (e: Exception) {+ Logger.debug(Logger.tags(ATTACHMENT_TAG), "No attachments found in notification: ${e.message}")+ }+ if (attachments != null) {+ for (i in 0 until attachments.length()) {+ val newAttachment = NotificationAttachment()+ var jsonObject: JSONObject? = null+ try {+ jsonObject = attachments.getJSONObject(i)+ } catch (e: JSONException) {+ Logger.error(Logger.tags(ATTACHMENT_TAG), "Failed to get attachment object at index $i: ${e.message}", e)+ }+ if (jsonObject != null) {+ var jsObject: JSObject? = null+ try {+ jsObject = JSObject.fromJSONObject(jsonObject)+ } catch (e: JSONException) {+ Logger.error(Logger.tags(ATTACHMENT_TAG), "Failed to convert attachment JSON object: ${e.message}", e)+ }+ newAttachment.id = jsObject!!.getString("id")+ newAttachment.url = jsObject.getString("url")+ try {+ newAttachment.options = jsObject.getJSONObject("options")+ } catch (e: JSONException) {+ Logger.debug(Logger.tags(ATTACHMENT_TAG), "No options found for attachment: ${e.message}")+ }+ attachmentsList.add(newAttachment)+ }+ }+ }+ return attachmentsList+ }+ }+}\ No newline at end of filediff --git a/src-tauri/vendor/tauri-plugin-notifications/android/src/main/java/app/tauri/notification/NotificationPlugin.kt b/src-tauri/vendor/tauri-plugin-notifications/android/src/main/java/app/tauri/notification/NotificationPlugin.ktnew file mode 100644index 00000000..061eb3dd--- /dev/null+++ b/src-tauri/vendor/tauri-plugin-notifications/android/src/main/java/app/tauri/notification/NotificationPlugin.kt@@ -0,0 +1,548 @@+package app.tauri.notification++import android.Manifest+import android.annotation.SuppressLint+import android.app.Activity+import android.app.NotificationManager+import android.content.Context+import android.content.Intent+import android.os.Build+import android.webkit.WebView+import app.tauri.PermissionState+import app.tauri.annotation.Command+import app.tauri.annotation.InvokeArg+import app.tauri.annotation.Permission+import app.tauri.annotation.PermissionCallback+import app.tauri.annotation.TauriPlugin+import app.tauri.Logger+import app.tauri.plugin.Invoke+import app.tauri.plugin.JSArray+import app.tauri.plugin.JSObject+import app.tauri.plugin.Plugin+import com.google.firebase.messaging.FirebaseMessaging++const val LOCAL_NOTIFICATIONS = "permissionState"++@InvokeArg+class PluginConfig {+ var icon: String? = null+ var sound: String? = null+ var iconColor: String? = null+}++@InvokeArg+class BatchArgs {+ lateinit var notifications: List<Notification>+}++@InvokeArg+class CancelArgs {+ lateinit var notifications: List<Int>+}++@InvokeArg+class NotificationAction {+ lateinit var id: String+ var title: String? = null+ var input: Boolean? = null+}++@InvokeArg+class ActionType {+ lateinit var id: String+ lateinit var actions: List<NotificationAction>+}++@InvokeArg+class RegisterActionTypesArgs {+ lateinit var types: List<ActionType>+}++@InvokeArg+class SetClickListenerActiveArgs {+ var active: Boolean = false+}++@InvokeArg+class ActiveNotification {+ var id: Int = 0+ var tag: String? = null+}++@InvokeArg+class RemoveActiveArgs {+ var notifications: List<ActiveNotification> = listOf()+}++@TauriPlugin(+ permissions = [+ Permission(strings = [Manifest.permission.POST_NOTIFICATIONS], alias = "permissionState")+ ]+)+class NotificationPlugin(private val activity: Activity): Plugin(activity) {+ private var webView: WebView? = null+ private lateinit var manager: TauriNotificationManager+ private lateinit var notificationManager: NotificationManager+ private lateinit var notificationStorage: NotificationStorage+ private var channelManager = ChannelManager(activity)++ private var pendingTokenInvoke: Invoke? = null+ private var cachedToken: String? = null++ // Click listener tracking for cold-start support+ private var hasClickedListener = false+ private var pendingNotificationClick: JSObject? = null++ // onNewIntent can fire before load() during a cold start triggered+ // by a notification tap (Android delivers the launch intent via+ // both onCreate's activity.intent AND onNewIntent in certain launch+ // modes; if Tauri's PluginManager hasn't called load() yet,+ // `manager` is uninitialized and the original code crashed with+ // `lateinit property manager has not been initialized`). Buffer the+ // intent and drain in load() instead.+ private var pendingIntent: Intent? = null++ companion object {+ var instance: NotificationPlugin? = null++ fun triggerNotification(notification: Notification, source: String = "local") {+ val data = JSObject()+ data.put("source", source)+ data.put("id", notification.id)+ notification.title?.let { data.put("title", it) }+ notification.body?.let { data.put("body", it) }+ notification.largeBody?.let { data.put("largeBody", it) }+ notification.summary?.let { data.put("summary", it) }+ notification.sound?.let { data.put("sound", it) }+ notification.actionTypeId?.let { data.put("actionTypeId", it) }+ notification.group?.let { data.put("group", it) }+ notification.channelId?.let { data.put("channelId", it) }+ if (notification.isGroupSummary) data.put("groupSummary", true)+ if (notification.isOngoing) data.put("ongoing", true)+ if (notification.isAutoCancel) data.put("autoCancel", true)+ notification.silent?.let { data.put("silent", it) }+ notification.extra?.let { data.put("extra", it) }+ notification.inboxLines?.let { data.put("inboxLines", JSArray(it)) }+ notification.attachments?.let { attachments ->+ val arr = JSArray()+ for (att in attachments) {+ val obj = JSObject()+ att.id?.let { obj.put("id", it) }+ att.url?.let { obj.put("url", it) }+ arr.put(obj)+ }+ data.put("attachments", arr)+ }+ instance?.trigger("notification", data)+ }+ }++ override fun load(webView: WebView) {+ instance = this++ super.load(webView)+ this.webView = webView+ notificationStorage = NotificationStorage(activity, jsonMapper())++ val manager = TauriNotificationManager(+ notificationStorage,+ activity,+ activity,+ getConfig(PluginConfig::class.java)+ )+ manager.createNotificationChannel()++ this.manager = manager++ notificationManager = activity.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager++ val intent = activity.intent+ intent?.let {+ onIntent(it)+ }+ // Drain any intent that arrived via onNewIntent before load() ran.+ pendingIntent?.let {+ pendingIntent = null+ // Skip if onIntent(activity.intent) above already handled the+ // same intent — comparing by reference is the cheapest dedup+ // (Tauri's TauriActivity calls setIntent() in onNewIntent, so+ // activity.intent points at the same Intent instance).+ if (it !== intent) onIntent(it)+ }+ }++ override fun onNewIntent(intent: Intent) {+ super.onNewIntent(intent)+ if (!::manager.isInitialized) {+ Logger.debug(+ Logger.tags(TAG),+ "onNewIntent fired before plugin load(); buffering until init"+ )+ pendingIntent = intent+ return+ }+ onIntent(intent)+ }++ fun onIntent(intent: Intent) {+ Logger.debug(Logger.tags(TAG), "onIntent called - action: ${intent.action}, extras: ${intent.extras?.keySet()}")++ // Handle local notification click (requires ACTION_MAIN)+ if (Intent.ACTION_MAIN == intent.action) {+ val dataJson = manager.handleNotificationActionPerformed(intent, notificationStorage)+ if (dataJson != null) {+ trigger("actionPerformed", dataJson)+ triggerNotificationClicked(+ intent.getIntExtra(NOTIFICATION_INTENT_KEY, -1),+ extractLocalNotificationData(intent)+ )+ return+ }+ }++ // Handle push notification click (Firebase background notification)+ // Firebase may use different actions, so check for push data regardless of action+ val pushData = extractPushNotificationData(intent)+ if (pushData != null) {+ Logger.debug(Logger.tags(TAG), "Push notification clicked with data: $pushData")+ triggerNotificationClicked(-1, pushData)+ }+ }++ private fun extractLocalNotificationData(intent: Intent): JSObject? {+ val notificationJson = intent.getStringExtra(NOTIFICATION_OBJ_INTENT_KEY) ?: return null+ return try {+ val notification = JSObject(notificationJson)+ if (notification.has("extra")) notification.getJSObject("extra") else null+ } catch (e: Exception) {+ Logger.error(Logger.tags(TAG), "Failed to extract local notification data: ${e.message}", e)+ null+ }+ }++ private fun extractPushNotificationData(intent: Intent): JSObject? {+ val extras = intent.extras ?: return null+ // Skip if no extras or if it's a regular app launch+ if (extras.isEmpty) return null++ Logger.debug(Logger.tags(TAG), "extractPushNotificationData - all extras: ${extras.keySet().map { "$it=${extras.getString(it)}" }}")++ // Filter out system/internal keys, keep user data+ val data = JSObject()+ for (key in extras.keySet()) {+ // Skip Android/Firebase internal keys+ if (key.startsWith("android.") || key.startsWith("google.") ||+ key.startsWith("gcm.") || key == "from" || key == "collapse_key") continue+ extras.getString(key)?.let { data.put(key, it) }+ }+ Logger.debug(Logger.tags(TAG), "extractPushNotificationData - filtered data length: ${data.length()}")+ return if (data.length() > 0) data else null+ }++ private fun triggerNotificationClicked(id: Int, data: JSObject?) {+ val clickedData = JSObject()+ clickedData.put("id", id)+ if (data != null) {+ clickedData.put("data", data)+ }++ Logger.debug(Logger.tags(TAG), "triggerNotificationClicked - id: $id, hasClickedListener: $hasClickedListener, data: $data")++ if (hasClickedListener) {+ trigger("notificationClicked", clickedData)+ } else {+ Logger.debug(Logger.tags(TAG), "No click listener, storing as pending")+ pendingNotificationClick = clickedData+ }+ }++ @Command+ fun show(invoke: Invoke) {+ val notification = invoke.parseArgs(Notification::class.java)+ notification.sourceJson = invoke.getRawArgs()++ val id = manager.schedule(notification)+ if (notification.schedule != null) {+ notificationStorage.appendNotifications(listOf(notification))+ }++ invoke.resolveObject(id)+ }++ @Command+ fun batch(invoke: Invoke) {+ val args = invoke.parseArgs(BatchArgs::class.java)+ val mapper = jsonMapper()+ for (notification in args.notifications) {+ notification.sourceJson = mapper.writeValueAsString(notification)+ }++ val ids = manager.schedule(args.notifications)+ notificationStorage.appendNotifications(args.notifications)++ invoke.resolveObject(ids)+ }++ @Command+ fun cancel(invoke: Invoke) {+ val args = invoke.parseArgs(CancelArgs::class.java)+ manager.cancel(args.notifications)+ invoke.resolve()+ }++ @Command+ fun cancelAll(invoke: Invoke) {+ val ids = notificationStorage.getSavedNotificationIds().mapNotNull { it.toIntOrNull() }+ manager.cancel(ids)+ invoke.resolve()+ }++ @Command+ fun removeActive(invoke: Invoke) {+ val args = invoke.parseArgs(RemoveActiveArgs::class.java)++ if (args.notifications.isEmpty()) {+ notificationManager.cancelAll()+ invoke.resolve()+ } else {+ for (notification in args.notifications) {+ if (notification.tag == null) {+ notificationManager.cancel(notification.id)+ } else {+ notificationManager.cancel(notification.tag, notification.id)+ }+ }+ invoke.resolve()+ }+ }++ @Command+ fun getPending(invoke: Invoke) {+ val notifications = notificationStorage.getSavedNotifications()+ val result = Notification.buildNotificationPendingList(notifications)+ invoke.resolveObject(result)+ }++ @Command+ fun registerActionTypes(invoke: Invoke) {+ val args = invoke.parseArgs(RegisterActionTypesArgs::class.java)+ notificationStorage.writeActionGroup(args.types)+ invoke.resolve()+ }++ @SuppressLint("ObsoleteSdkInt")+ @Command+ fun getActive(invoke: Invoke) {+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {+ val result = Notification.buildNotificationActiveList(notificationManager.activeNotifications)+ invoke.resolveObject(result)+ } else {+ invoke.resolveObject(emptyList<ActiveNotificationInfo>())+ }+ }++ @Command+ fun createChannel(invoke: Invoke) {+ channelManager.createChannel(invoke)+ }++ @Command+ fun deleteChannel(invoke: Invoke) {+ channelManager.deleteChannel(invoke)+ }++ @Command+ fun listChannels(invoke: Invoke) {+ channelManager.listChannels(invoke)+ }++ @Command+ override fun checkPermissions(invoke: Invoke) {+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) {+ val permissionsResultJSON = JSObject()+ permissionsResultJSON.put("permissionState", getPermissionState())+ invoke.resolve(permissionsResultJSON)+ } else {+ super.checkPermissions(invoke)+ }+ }++ @Command+ override fun requestPermissions(invoke: Invoke) {+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) {+ permissionState(invoke)+ } else {+ if (getPermissionState(LOCAL_NOTIFICATIONS) !== PermissionState.GRANTED) {+ requestPermissionForAlias(LOCAL_NOTIFICATIONS, invoke, "permissionsCallback")+ }+ }+ }++ @Command+ fun registerForPushNotifications(invoke: Invoke) {+ if (!BuildConfig.ENABLE_PUSH_NOTIFICATIONS) {+ invoke.reject("Push notifications are disabled in this build")+ return+ }++ // First check if notifications are enabled+ if (!manager.areNotificationsEnabled()) {+ // Request permissions first+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {+ if (getPermissionState(LOCAL_NOTIFICATIONS) !== PermissionState.GRANTED) {+ // Request permissions and then get token+ pendingTokenInvoke = invoke+ requestPermissionForAlias(LOCAL_NOTIFICATIONS, invoke, "pushPermissionsCallback")+ return+ }+ } else {+ invoke.reject("Notification permissions not granted")+ return+ }+ }++ // If we already have a cached token, return it immediately+ cachedToken?.let {+ val result = JSObject()+ result.put("deviceToken", it)+ invoke.resolve(result)+ return+ }++ // Store the invoke to respond later when we get the token+ pendingTokenInvoke = invoke++ // Request the FCM token+ getFirebaseToken()+ }++ @Command+ fun unregisterForPushNotifications(invoke: Invoke) {+ if (!BuildConfig.ENABLE_PUSH_NOTIFICATIONS) {+ invoke.reject("Push notifications are disabled in this build")+ return+ }++ FirebaseMessaging.getInstance().deleteToken().addOnCompleteListener { task ->+ if (!task.isSuccessful) {+ invoke.reject("Failed to delete FCM token: ${task.exception?.message}")+ return@addOnCompleteListener+ }+ cachedToken = null+ invoke.resolve()+ }+ }++ @PermissionCallback+ private fun pushPermissionsCallback(invoke: Invoke) {+ if (!manager.areNotificationsEnabled()) {+ invoke.reject("Notification permissions denied")+ pendingTokenInvoke = null+ return+ }++ // Permissions granted, now get the token+ getFirebaseToken()+ }++ private fun getFirebaseToken() {+ if (!BuildConfig.ENABLE_PUSH_NOTIFICATIONS) {+ pendingTokenInvoke?.reject("Push notifications are disabled in this build")+ pendingTokenInvoke = null+ return+ }++ FirebaseMessaging.getInstance().token.addOnCompleteListener { task ->+ if (!task.isSuccessful) {+ val errorMessage = "Failed to get FCM token: ${task.exception?.message}"+ val errorData = JSObject()+ errorData.put("message", errorMessage)+ trigger("push-error", errorData)+ pendingTokenInvoke?.reject(errorMessage)+ pendingTokenInvoke = null+ return@addOnCompleteListener+ }++ val token = task.result+ cachedToken = token+ val result = JSObject()+ result.put("deviceToken", token)+ pendingTokenInvoke?.resolve(result)+ pendingTokenInvoke = null+ }+ }++ // Called by TauriFirebaseMessagingService when a new token is received+ fun handleNewToken(token: String) {+ if (!BuildConfig.ENABLE_PUSH_NOTIFICATIONS) return++ cachedToken = token+ // Trigger push-token event to notify the frontend about the token+ val data = JSObject()+ data.put("token", token)+ trigger("push-token", data)+ }++ // Called by TauriFirebaseMessagingService when a push message is received+ fun triggerPushMessage(pushData: Map<String, Any>) {+ if (!BuildConfig.ENABLE_PUSH_NOTIFICATIONS) return++ val data = JSObject()+ for ((key, value) in pushData) {+ when (value) {+ is String -> data.put(key, value)+ is Int -> data.put(key, value)+ is Long -> data.put(key, value)+ is Double -> data.put(key, value)+ is Boolean -> data.put(key, value)+ is Map<*, *> -> {+ val nestedObj = JSObject()+ @Suppress("UNCHECKED_CAST")+ val map = value as Map<String, Any>+ for ((k, v) in map) {+ nestedObj.put(k, v.toString())+ }+ data.put(key, nestedObj)+ }+ else -> data.put(key, value.toString())+ }+ }+ trigger("push-message", data)+ }++ @Command+ fun permissionState(invoke: Invoke) {+ val permissionsResultJSON = JSObject()+ permissionsResultJSON.put("permissionState", getPermissionState())+ invoke.resolve(permissionsResultJSON)+ }++ @PermissionCallback+ private fun permissionsCallback(invoke: Invoke) {+ val permissionsResultJSON = JSObject()+ permissionsResultJSON.put("permissionState", getPermissionState())+ invoke.resolve(permissionsResultJSON)+ }++ private fun getPermissionState(): String {+ return if (manager.areNotificationsEnabled()) {+ "granted"+ } else {+ "denied"+ }+ }++ @Command+ fun setClickListenerActive(invoke: Invoke) {+ val args = invoke.parseArgs(SetClickListenerActiveArgs::class.java)+ hasClickedListener = args.active++ // If listener just became active and we have pending click, trigger it+ if (args.active && pendingNotificationClick != null) {+ trigger("notificationClicked", pendingNotificationClick!!)+ pendingNotificationClick = null+ }++ invoke.resolve()+ }+}diff --git a/src-tauri/vendor/tauri-plugin-notifications/android/src/main/java/app/tauri/notification/NotificationSchedule.kt b/src-tauri/vendor/tauri-plugin-notifications/android/src/main/java/app/tauri/notification/NotificationSchedule.ktnew file mode 100644index 00000000..05576a77--- /dev/null+++ b/src-tauri/vendor/tauri-plugin-notifications/android/src/main/java/app/tauri/notification/NotificationSchedule.kt@@ -0,0 +1,372 @@+package app.tauri.notification++import android.annotation.SuppressLint+import android.text.format.DateUtils+import com.fasterxml.jackson.annotation.JsonFormat+import com.fasterxml.jackson.annotation.JsonProperty+import com.fasterxml.jackson.core.JsonGenerator+import com.fasterxml.jackson.core.JsonParser+import com.fasterxml.jackson.core.JsonProcessingException+import com.fasterxml.jackson.databind.DeserializationContext+import com.fasterxml.jackson.databind.JsonDeserializer+import com.fasterxml.jackson.databind.JsonNode+import com.fasterxml.jackson.databind.SerializerProvider+import com.fasterxml.jackson.databind.annotation.JsonDeserialize+import com.fasterxml.jackson.databind.annotation.JsonSerialize+import com.fasterxml.jackson.databind.deser.std.StdDeserializer+import com.fasterxml.jackson.databind.ser.std.StdSerializer+import java.io.IOException+import java.text.SimpleDateFormat+import java.util.Calendar+import java.util.Date+import java.util.TimeZone++const val JS_DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"++enum class NotificationInterval {+ @JsonProperty("year")+ Year,+ @JsonProperty("month")+ Month,+ @JsonProperty("twoWeeks")+ TwoWeeks,+ @JsonProperty("week")+ Week,+ @JsonProperty("day")+ Day,+ @JsonProperty("hour")+ Hour,+ @JsonProperty("minute")+ Minute,+ @JsonProperty("second")+ Second+}++fun getIntervalTime(interval: NotificationInterval, count: Int): Long {+ return when (interval) {+ // This case is just approximation as not all years have the same number of days+ NotificationInterval.Year -> count * DateUtils.WEEK_IN_MILLIS * 52+ // This case is just approximation as months have different number of days+ NotificationInterval.Month -> count * 30 * DateUtils.DAY_IN_MILLIS+ NotificationInterval.TwoWeeks -> count * 2 * DateUtils.WEEK_IN_MILLIS+ NotificationInterval.Week -> count * DateUtils.WEEK_IN_MILLIS+ NotificationInterval.Day -> count * DateUtils.DAY_IN_MILLIS+ NotificationInterval.Hour -> count * DateUtils.HOUR_IN_MILLIS+ NotificationInterval.Minute -> count * DateUtils.MINUTE_IN_MILLIS+ NotificationInterval.Second -> count * DateUtils.SECOND_IN_MILLIS+ }+}++@JsonDeserialize(using = NotificationScheduleDeserializer::class)+@JsonSerialize(using = NotificationScheduleSerializer::class)+sealed class NotificationSchedule {+ // At specific moment of time (with repeating option)+ @JsonDeserialize+ class At: NotificationSchedule() {+ @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = JS_DATE_FORMAT)+ lateinit var date: Date+ var repeating: Boolean = false+ var allowWhileIdle: Boolean = false+ }+ @JsonDeserialize+ class Interval: NotificationSchedule() {+ lateinit var interval: DateMatch+ var allowWhileIdle: Boolean = false+ }+ @JsonDeserialize+ class Every: NotificationSchedule() {+ lateinit var interval: NotificationInterval+ var count: Int = 0+ var allowWhileIdle: Boolean = false+ }++ fun isRemovable(): Boolean {+ return when (this) {+ is At -> !repeating+ else -> false+ }+ }++ fun allowWhileIdle(): Boolean {+ return when (this) {+ is At -> allowWhileIdle+ is Interval -> allowWhileIdle+ is Every -> allowWhileIdle+ }+ }++ override fun toString(): String {+ return when (this) {+ is At -> "At(date=$date, repeating=$repeating, allowWhileIdle=$allowWhileIdle)"+ is Interval -> "Interval(interval=$interval, allowWhileIdle=$allowWhileIdle)"+ is Every -> "Every(interval=$interval, count=$count, allowWhileIdle=$allowWhileIdle)"+ }+ }+}++internal class NotificationScheduleSerializer @JvmOverloads constructor(t: Class<NotificationSchedule>? = null) :+ StdSerializer<NotificationSchedule>(t) {+ @SuppressLint("SimpleDateFormat")+ @Throws(IOException::class, JsonProcessingException::class)+ override fun serialize(+ value: NotificationSchedule, jgen: JsonGenerator, provider: SerializerProvider+ ) {+ jgen.writeStartObject()+ when (value) {+ is NotificationSchedule.At -> {+ jgen.writeObjectFieldStart("at")++ val sdf = SimpleDateFormat(JS_DATE_FORMAT)+ sdf.timeZone = TimeZone.getTimeZone("UTC")+ jgen.writeStringField("date", sdf.format(value.date))+ jgen.writeBooleanField("repeating", value.repeating)++ jgen.writeEndObject()+ }+ is NotificationSchedule.Interval -> {+ jgen.writeObjectFieldStart("interval")++ jgen.writeObjectField("interval", value.interval)++ jgen.writeEndObject()+ }+ is NotificationSchedule.Every -> {+ jgen.writeObjectFieldStart("every")++ jgen.writeObjectField("interval", value.interval)+ jgen.writeNumberField("count", value.count)++ jgen.writeEndObject()+ }+ }++ jgen.writeEndObject()+ }+}++internal class NotificationScheduleDeserializer: JsonDeserializer<NotificationSchedule>() {+ override fun deserialize(+ jsonParser: JsonParser,+ deserializationContext: DeserializationContext+ ): NotificationSchedule {+ val node: JsonNode = jsonParser.codec.readTree(jsonParser)+ node.get("at")?.let {+ return jsonParser.codec.treeToValue(it, NotificationSchedule.At::class.java)+ }+ node.get("interval")?.let {+ return jsonParser.codec.treeToValue(it, NotificationSchedule.Interval::class.java)+ }+ node.get("every")?.let {+ return jsonParser.codec.treeToValue(it, NotificationSchedule.Every::class.java)+ }+ throw Error("unknown schedule kind $node")+ }+}++class DateMatch {+ var year: Int? = null+ var month: Int? = null+ var day: Int? = null+ var weekday: Int? = null+ var hour: Int? = null+ var minute: Int? = null+ var second: Int? = null++ // Unit used to save the last used unit for a trigger.+ // One of the Calendar constants values+ var unit: Int? = -1++ /**+ * Gets a calendar instance pointing to the specified date.+ *+ * @param date The date to point.+ */+ private fun buildCalendar(date: Date): Calendar {+ val cal: Calendar = Calendar.getInstance()+ cal.time = date+ cal.set(Calendar.MILLISECOND, 0)+ return cal+ }++ /**+ * Calculates next trigger date for+ *+ * @param date base date used to calculate trigger+ * @return next trigger timestamp+ */+ fun nextTrigger(date: Date): Long {+ val current: Calendar = buildCalendar(date)+ val next: Calendar = buildNextTriggerTime(date)+ return postponeTriggerIfNeeded(current, next)+ }++ /**+ * Postpone trigger if first schedule matches the past+ */+ private fun postponeTriggerIfNeeded(current: Calendar, next: Calendar): Long {+ if (next.timeInMillis <= current.timeInMillis && unit != -1) {+ var incrementUnit = -1+ if (unit == Calendar.YEAR || unit == Calendar.MONTH) {+ incrementUnit = Calendar.YEAR+ } else if (unit == Calendar.DAY_OF_MONTH) {+ incrementUnit = Calendar.MONTH+ } else if (unit == Calendar.DAY_OF_WEEK) {+ incrementUnit = Calendar.WEEK_OF_MONTH+ } else if (unit == Calendar.HOUR_OF_DAY) {+ incrementUnit = Calendar.DAY_OF_MONTH+ } else if (unit == Calendar.MINUTE) {+ incrementUnit = Calendar.HOUR_OF_DAY+ } else if (unit == Calendar.SECOND) {+ incrementUnit = Calendar.MINUTE+ }+ if (incrementUnit != -1) {+ next.set(incrementUnit, next.get(incrementUnit) + 1)+ }+ }+ return next.timeInMillis+ }++ private fun buildNextTriggerTime(date: Date): Calendar {+ val next: Calendar = buildCalendar(date)+ if (year != null) {+ next.set(Calendar.YEAR, year ?: 0)+ if (unit == -1) unit = Calendar.YEAR+ }+ if (month != null) {+ next.set(Calendar.MONTH, month ?: 0)+ if (unit == -1) unit = Calendar.MONTH+ }+ if (day != null) {+ next.set(Calendar.DAY_OF_MONTH, day ?: 0)+ if (unit == -1) unit = Calendar.DAY_OF_MONTH+ }+ if (weekday != null) {+ next.set(Calendar.DAY_OF_WEEK, weekday ?: 0)+ if (unit == -1) unit = Calendar.DAY_OF_WEEK+ }+ if (hour != null) {+ next.set(Calendar.HOUR_OF_DAY, hour ?: 0)+ if (unit == -1) unit = Calendar.HOUR_OF_DAY+ }+ if (minute != null) {+ next.set(Calendar.MINUTE, minute ?: 0)+ if (unit == -1) unit = Calendar.MINUTE+ }+ if (second != null) {+ next.set(Calendar.SECOND, second ?: 0)+ if (unit == -1) unit = Calendar.SECOND+ }+ return next+ }++ override fun toString(): String {+ return "DateMatch{" ++ "year=" ++ year ++ ", month=" ++ month ++ ", day=" ++ day ++ ", weekday=" ++ weekday ++ ", hour=" ++ hour ++ ", minute=" ++ minute ++ ", second=" ++ second ++ '}'+ }++ override fun equals(other: Any?): Boolean {+ if (this === other) return true+ if (other == null || javaClass != other.javaClass) return false+ val dateMatch = other as DateMatch+ if (if (year != null) year != dateMatch.year else dateMatch.year != null) return false+ if (if (month != null) month != dateMatch.month else dateMatch.month != null) return false+ if (if (day != null) day != dateMatch.day else dateMatch.day != null) return false+ if (if (weekday != null) weekday != dateMatch.weekday else dateMatch.weekday != null) return false+ if (if (hour != null) hour != dateMatch.hour else dateMatch.hour != null) return false+ if (if (minute != null) minute != dateMatch.minute else dateMatch.minute != null) return false+ return if (second != null) second == dateMatch.second else dateMatch.second == null+ }++ override fun hashCode(): Int {+ var result = if (year != null) year.hashCode() else 0+ result = 31 * result + if (month != null) month.hashCode() else 0+ result = 31 * result + if (day != null) day.hashCode() else 0+ result = 31 * result + if (weekday != null) weekday.hashCode() else 0+ result = 31 * result + if (hour != null) hour.hashCode() else 0+ result = 31 * result + if (minute != null) minute.hashCode() else 0+ result += 31 + if (second != null) second.hashCode() else 0+ return result+ }++ /**+ * Transform DateMatch object to CronString+ *+ * @return+ */+ fun toMatchString(): String {+ val matchString = year.toString() ++ separator ++ month ++ separator ++ day ++ separator ++ weekday ++ separator ++ hour ++ separator ++ minute ++ separator ++ second ++ separator ++ unit+ return matchString.replace("null", "*")+ }++ companion object {+ private const val separator = " "++ /**+ * Create DateMatch object from stored string+ *+ * @param matchString+ * @return+ */+ fun fromMatchString(matchString: String): DateMatch {+ val date = DateMatch()+ val split = matchString.split(separator.toRegex()).dropLastWhile { it.isEmpty() }+ .toTypedArray()+ if (split.size == 7) {+ date.year = getValueFromCronElement(split[0])+ date.month = getValueFromCronElement(split[1])+ date.day = getValueFromCronElement(split[2])+ date.weekday = getValueFromCronElement(split[3])+ date.hour = getValueFromCronElement(split[4])+ date.minute = getValueFromCronElement(split[5])+ date.unit = getValueFromCronElement(split[6])+ }+ if (split.size == 8) {+ date.year = getValueFromCronElement(split[0])+ date.month = getValueFromCronElement(split[1])+ date.day = getValueFromCronElement(split[2])+ date.weekday = getValueFromCronElement(split[3])+ date.hour = getValueFromCronElement(split[4])+ date.minute = getValueFromCronElement(split[5])+ date.second = getValueFromCronElement(split[6])+ date.unit = getValueFromCronElement(split[7])+ }+ return date+ }++ private fun getValueFromCronElement(token: String): Int? {+ return try {+ token.toInt()+ } catch (e: NumberFormatException) {+ null+ }+ }+ }+}\ No newline at end of filediff --git a/src-tauri/vendor/tauri-plugin-notifications/android/src/main/java/app/tauri/notification/NotificationStorage.kt b/src-tauri/vendor/tauri-plugin-notifications/android/src/main/java/app/tauri/notification/NotificationStorage.ktnew file mode 100644index 00000000..13948c01--- /dev/null+++ b/src-tauri/vendor/tauri-plugin-notifications/android/src/main/java/app/tauri/notification/NotificationStorage.kt@@ -0,0 +1,123 @@+package app.tauri.notification++import android.content.Context+import android.content.SharedPreferences+import app.tauri.Logger+import com.fasterxml.jackson.databind.ObjectMapper++private const val STORAGE_TAG = "NotificationStorage"+// Key for private preferences+private const val NOTIFICATION_STORE_ID = "NOTIFICATION_STORE"+// Key used to save action types+private const val ACTION_TYPES_ID = "ACTION_TYPE_STORE"++class NotificationStorage(private val context: Context, private val jsonMapper: ObjectMapper) {+ fun appendNotifications(localNotifications: List<Notification>) {+ Logger.debug(Logger.tags(STORAGE_TAG), "Appending ${localNotifications.size} notifications to storage")+ val storage = getStorage(NOTIFICATION_STORE_ID)+ val editor = storage.edit()+ var savedCount = 0+ for (request in localNotifications) {+ if (request.schedule != null) {+ val key: String = request.id.toString()+ val jsonValue = request.sourceJson+ Logger.debug(Logger.tags(STORAGE_TAG), "Saving notification $key, sourceJson is null: ${request.sourceJson == null}, value: ${jsonValue?.take(100)}")+ editor.putString(key, jsonValue)+ savedCount+++ } else {+ Logger.debug(Logger.tags(STORAGE_TAG), "Skipping notification ${request.id} - no schedule")+ }+ }+ editor.apply()+ Logger.debug(Logger.tags(STORAGE_TAG), "Actually saved $savedCount scheduled notifications")+ }++ fun getSavedNotificationIds(): List<String> {+ val storage = getStorage(NOTIFICATION_STORE_ID)+ val all = storage.all+ val ids = if (all != null) ArrayList(all.keys) else ArrayList()+ Logger.debug(Logger.tags(STORAGE_TAG), "Retrieved ${ids.size} saved notification IDs")+ return ids+ }++ fun getSavedNotifications(): List<Notification> {+ val storage = getStorage(NOTIFICATION_STORE_ID)+ val all = storage.all+ Logger.debug(Logger.tags(STORAGE_TAG), "Storage keys: ${all?.keys}")+ val notifications = all?.keys?.mapNotNull { key ->+ val value = all[key]+ Logger.debug(Logger.tags(STORAGE_TAG), "Key $key, value type: ${value?.javaClass?.name}, value: ${value.toString().take(100)}")+ val json = value as? String+ parseNotification(json)+ } ?: emptyList()+ Logger.debug(Logger.tags(STORAGE_TAG), "Retrieved ${notifications.size} saved notifications")+ return notifications+ }++ fun getSavedNotification(key: String): Notification? {+ val storage = getStorage(NOTIFICATION_STORE_ID)+ val notificationString = try {+ storage.getString(key, null)+ } catch (e: ClassCastException) {+ Logger.error(Logger.tags(STORAGE_TAG), "Failed to get notification string for key $key: ${e.message}", e)+ return null+ }+ return parseNotification(notificationString)+ }++ private fun parseNotification(json: String?): Notification? {+ if (json == null) return null+ return try {+ jsonMapper.readValue(json, Notification::class.java)+ } catch (e: Exception) {+ Logger.error(Logger.tags(STORAGE_TAG), "Failed to parse notification: ${e.message}", e)+ null+ }+ }++ fun deleteNotification(id: String?) {+ Logger.debug(Logger.tags(STORAGE_TAG), "Deleting notification with id: $id")+ val editor = getStorage(NOTIFICATION_STORE_ID).edit()+ editor.remove(id)+ editor.apply()+ }++ private fun getStorage(key: String): SharedPreferences {+ return context.getSharedPreferences(key, Context.MODE_PRIVATE)+ }++ fun writeActionGroup(actions: List<ActionType>) {+ for (type in actions) {+ val editor = getStorage(ACTION_TYPES_ID + type.id).edit()+ editor.clear()+ editor.putInt("count", type.actions.size)+ for ((index, action) in type.actions.withIndex()) {+ editor.putString("id$index", action.id)+ editor.putString("title$index", action.title)+ editor.putBoolean("input$index", action.input ?: false)+ }+ editor.apply()+ Logger.debug(Logger.tags(STORAGE_TAG), "Saved action group ${type.id} with ${type.actions.size} actions")+ }+ }++ fun getActionGroup(forId: String): Array<NotificationAction?> {+ val storage = getStorage(ACTION_TYPES_ID + forId)+ val count = storage.getInt("count", 0)+ Logger.debug(Logger.tags(STORAGE_TAG), "Getting action group $forId, count: $count")+ val actions: Array<NotificationAction?> = arrayOfNulls(count)+ for (i in 0 until count) {+ val id = storage.getString("id$i", "")+ val title = storage.getString("title$i", "")+ val input = storage.getBoolean("input$i", false)+ Logger.debug(Logger.tags(STORAGE_TAG), "Action $i: id=$id, title=$title, input=$input")++ val action = NotificationAction()+ action.id = id ?: ""+ action.title = title+ action.input = input+ actions[i] = action+ }+ return actions+ }+}\ No newline at end of filediff --git a/src-tauri/vendor/tauri-plugin-notifications/android/src/main/java/app/tauri/notification/TauriFirebaseMessagingService.kt b/src-tauri/vendor/tauri-plugin-notifications/android/src/main/java/app/tauri/notification/TauriFirebaseMessagingService.ktnew file mode 100644index 00000000..d5111d3e--- /dev/null+++ b/src-tauri/vendor/tauri-plugin-notifications/android/src/main/java/app/tauri/notification/TauriFirebaseMessagingService.kt@@ -0,0 +1,67 @@+package app.tauri.notification++import app.tauri.plugin.JSObject+import com.google.firebase.messaging.FirebaseMessagingService+import com.google.firebase.messaging.RemoteMessage++class TauriFirebaseMessagingService : FirebaseMessagingService() {++ override fun onNewToken(token: String) {+ super.onNewToken(token)+ // Store the token for later retrieval and trigger push-token event+ NotificationPlugin.instance?.handleNewToken(token)+ }++ override fun onMessageReceived(message: RemoteMessage) {+ super.onMessageReceived(message)++ // Build push message data from RemoteMessage+ val pushData = mutableMapOf<String, Any>()++ // Add notification data if present+ message.notification?.let { notification ->+ notification.title?.let { pushData["title"] = it }+ notification.body?.let { pushData["body"] = it }+ notification.channelId?.let { pushData["channelId"] = it }+ notification.sound?.let { pushData["sound"] = it }+ notification.tag?.let { pushData["tag"] = it }+ }++ // Add data payload+ if (message.data.isNotEmpty()) {+ pushData["data"] = message.data+ }++ // Add message metadata+ message.messageId?.let { pushData["messageId"] = it }+ message.from?.let { pushData["from"] = it }+ pushData["sentTime"] = message.sentTime++ // Trigger push-message event+ NotificationPlugin.instance?.triggerPushMessage(pushData)++ // Also auto-show notification if notification payload exists+ val notification = message.notification+ if (notification != null) {+ val notificationData = Notification().apply {+ id = System.currentTimeMillis().toInt()+ title = notification.title ?: ""+ body = notification.body+ channelId = notification.channelId+ sound = notification.sound++ // Add data payload if available+ if (message.data.isNotEmpty()) {+ val extraData = JSObject()+ for ((key, value) in message.data) {+ extraData.put(key, value)+ }+ extra = extraData+ }+ }++ // Trigger notification event for push notification received in foreground+ NotificationPlugin.triggerNotification(notificationData, "push")+ }+ }+}diff --git a/src-tauri/vendor/tauri-plugin-notifications/android/src/main/java/app/tauri/notification/TauriNotificationManager.kt b/src-tauri/vendor/tauri-plugin-notifications/android/src/main/java/app/tauri/notification/TauriNotificationManager.ktnew file mode 100644index 00000000..7c66790b--- /dev/null+++ b/src-tauri/vendor/tauri-plugin-notifications/android/src/main/java/app/tauri/notification/TauriNotificationManager.kt@@ -0,0 +1,593 @@+package app.tauri.notification++import android.annotation.SuppressLint+import android.app.Activity+import android.app.AlarmManager+import android.app.NotificationChannel+import android.app.NotificationManager+import android.app.PendingIntent+import android.content.BroadcastReceiver+import android.content.ContentResolver+import android.content.Context+import android.content.Intent+import android.graphics.Color+import android.media.AudioAttributes+import android.net.Uri+import android.os.Build+import android.os.Build.VERSION.SDK_INT+import android.os.UserManager+import androidx.core.app.NotificationCompat+import androidx.core.app.NotificationManagerCompat+import androidx.core.app.RemoteInput+import app.tauri.Logger+import app.tauri.plugin.JSObject+import app.tauri.plugin.PluginManager+import com.fasterxml.jackson.databind.ObjectMapper+import org.json.JSONException+import org.json.JSONObject+import java.text.SimpleDateFormat+import java.util.Date++// Action constants+const val NOTIFICATION_INTENT_KEY = "NotificationId"+const val NOTIFICATION_OBJ_INTENT_KEY = "LocalNotficationObject"+const val ACTION_INTENT_KEY = "NotificationUserAction"+const val NOTIFICATION_IS_REMOVABLE_KEY = "NotificationRepeating"+const val REMOTE_INPUT_KEY = "NotificationRemoteInput"+const val DEFAULT_NOTIFICATION_CHANNEL_ID = "default"+const val DEFAULT_PRESS_ACTION = "tap"+const val TAG = "NotificationsPlugin"++class TauriNotificationManager(+ private val storage: NotificationStorage,+ private val activity: Activity?,+ private val context: Context,+ private val config: PluginConfig?+) {+ private var defaultSoundID: Int = AssetUtils.RESOURCE_ID_ZERO_VALUE+ private var defaultSmallIconID: Int = AssetUtils.RESOURCE_ID_ZERO_VALUE++ fun handleNotificationActionPerformed(+ data: Intent,+ notificationStorage: NotificationStorage+ ): JSObject? {+ Logger.debug(Logger.tags(TAG), "Notification received: " + data.dataString)+ val notificationId =+ data.getIntExtra(NOTIFICATION_INTENT_KEY, Int.MIN_VALUE)+ if (notificationId == Int.MIN_VALUE) {+ Logger.debug(Logger.tags(TAG), "Activity started without notification attached")+ return null+ }+ val isRemovable =+ data.getBooleanExtra(NOTIFICATION_IS_REMOVABLE_KEY, true)+ if (isRemovable) {+ notificationStorage.deleteNotification(notificationId.toString())+ }+ val dataJson = JSObject()+ val results = RemoteInput.getResultsFromIntent(data)+ val input = results?.getCharSequence(REMOTE_INPUT_KEY)+ dataJson.put("inputValue", input?.toString())+ val menuAction = data.getStringExtra(ACTION_INTENT_KEY)+ dismissVisibleNotification(notificationId)+ dataJson.put("actionId", menuAction)+ var request: JSONObject? = null+ try {+ val notificationJsonString =+ data.getStringExtra(NOTIFICATION_OBJ_INTENT_KEY)+ if (notificationJsonString != null) {+ request = JSObject(notificationJsonString)+ }+ } catch (e: JSONException) {+ Logger.error(Logger.tags(TAG), "Failed to parse notification JSON: ${e.message}", e)+ }+ dataJson.put("notification", request)+ return dataJson+ }++ /**+ * Create notification channel+ */+ fun createNotificationChannel() {+ // Create the NotificationChannel, but only on API 26+ because+ // the NotificationChannel class is new and not in the support library+ if (SDK_INT >= Build.VERSION_CODES.O) {+ val name: CharSequence = "Default"+ val description = "Default"+ val importance = NotificationManager.IMPORTANCE_DEFAULT+ val channel = NotificationChannel(DEFAULT_NOTIFICATION_CHANNEL_ID, name, importance)+ channel.description = description+ val audioAttributes = AudioAttributes.Builder()+ .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)+ .setUsage(AudioAttributes.USAGE_ALARM)+ .build()+ val soundUri = getDefaultSoundUrl(context)+ if (soundUri != null) {+ channel.setSound(soundUri, audioAttributes)+ }+ // Register the channel with the system; you can't change the importance+ // or other notification behaviors after this+ val notificationManager = context.getSystemService(+ NotificationManager::class.java+ )+ notificationManager.createNotificationChannel(channel)+ }+ }++ private fun trigger(notificationManager: NotificationManagerCompat, notification: Notification): Int {+ dismissVisibleNotification(notification.id)+ cancelTimerForNotification(notification.id)+ buildNotification(notificationManager, notification)++ return notification.id+ }++ fun schedule(notification: Notification): Int {+ val notificationManager = NotificationManagerCompat.from(context)+ return trigger(notificationManager, notification)+ }++ fun schedule(notifications: List<Notification>): List<Int> {+ val ids = mutableListOf<Int>()+ val notificationManager = NotificationManagerCompat.from(context)++ for (notification in notifications) {+ val id = trigger(notificationManager, notification)+ ids.add(id)+ }++ return ids+ }++ // TODO Progressbar support+ // TODO System categories (DO_NOT_DISTURB etc.)+ // TODO use NotificationCompat.MessagingStyle for latest API+ // TODO expandable notification NotificationCompat.MessagingStyle+ // TODO media style notification support NotificationCompat.MediaStyle+ @SuppressLint("MissingPermission")+ private fun buildNotification(+ notificationManager: NotificationManagerCompat,+ notification: Notification,+ ) {+ val channelId = notification.channelId ?: DEFAULT_NOTIFICATION_CHANNEL_ID+ val mBuilder = NotificationCompat.Builder(+ context, channelId+ )+ .setContentTitle(notification.title)+ .setContentText(notification.body)+ .setAutoCancel(notification.isAutoCancel)+ .setOngoing(notification.isOngoing)+ .setPriority(NotificationCompat.PRIORITY_DEFAULT)+ .setGroupSummary(notification.isGroupSummary)+ if (notification.largeBody != null) {+ // support multiline text+ mBuilder.setStyle(+ NotificationCompat.BigTextStyle()+ .bigText(notification.largeBody)+ .setSummaryText(notification.summary)+ )+ } else if (notification.inboxLines != null) {+ val inboxStyle = NotificationCompat.InboxStyle()+ for (line in notification.inboxLines ?: listOf()) {+ inboxStyle.addLine(line)+ }+ inboxStyle.setBigContentTitle(notification.title)+ inboxStyle.setSummaryText(notification.summary)+ mBuilder.setStyle(inboxStyle)+ }+ val sound = notification.getSound(context, getDefaultSound(context))+ if (sound != null) {+ val soundUri = Uri.parse(sound)+ // Grant permission to use sound+ context.grantUriPermission(+ "com.android.systemui",+ soundUri,+ Intent.FLAG_GRANT_READ_URI_PERMISSION+ )+ mBuilder.setSound(soundUri)+ mBuilder.setDefaults(android.app.Notification.DEFAULT_VIBRATE or android.app.Notification.DEFAULT_LIGHTS)+ } else {+ mBuilder.setDefaults(android.app.Notification.DEFAULT_ALL)+ }+ val group = notification.group+ if (group != null) {+ mBuilder.setGroup(group)+ if (notification.isGroupSummary) {+ mBuilder.setSubText(notification.summary)+ }+ }+ mBuilder.setVisibility(notification.visibility ?: NotificationCompat.VISIBILITY_PRIVATE)+ mBuilder.setOnlyAlertOnce(true)+ mBuilder.setSmallIcon(notification.getSmallIcon(context, getDefaultSmallIcon(context)))+ mBuilder.setLargeIcon(notification.getLargeIcon(context))+ val iconColor = notification.getIconColor(config?.iconColor ?: "")+ if (iconColor.isNotEmpty()) {+ try {+ mBuilder.color = Color.parseColor(iconColor)+ } catch (ex: IllegalArgumentException) {+ throw Exception("Invalid color provided. Must be a hex string (ex: #ff0000")+ }+ }+ createActionIntents(notification, mBuilder)+ // notificationId is a unique int for each notification that you must define+ val buildNotification = mBuilder.build()+ if (notification.schedule != null) {+ triggerScheduledNotification(buildNotification, notification)+ } else {+ notificationManager.notify(notification.id, buildNotification)+ try {+ NotificationPlugin.triggerNotification(notification)+ } catch (e: JSONException) {+ Logger.error(Logger.tags(TAG), "Failed to trigger notification event: ${e.message}", e)+ }+ }+ }++ // Create intents for open/dismiss actions+ private fun createActionIntents(+ notification: Notification,+ mBuilder: NotificationCompat.Builder+ ) {+ // Open intent+ val intent = buildIntent(notification, DEFAULT_PRESS_ACTION)+ var flags = PendingIntent.FLAG_CANCEL_CURRENT+ if (SDK_INT >= Build.VERSION_CODES.S) {+ flags = flags or PendingIntent.FLAG_MUTABLE+ }+ val pendingIntent = PendingIntent.getActivity(context, notification.id, intent, flags)+ mBuilder.setContentIntent(pendingIntent)++ // Build action types+ val actionTypeId = notification.actionTypeId+ if (actionTypeId != null) {+ val actionGroup = storage.getActionGroup(actionTypeId)+ for (notificationAction in actionGroup) {+ // TODO Add custom icons to actions+ val actionIntent = buildIntent(notification, notificationAction!!.id)+ val actionPendingIntent = PendingIntent.getActivity(+ context,+ (notification.id) + notificationAction.id.hashCode(),+ actionIntent,+ flags+ )+ val actionBuilder: NotificationCompat.Action.Builder = NotificationCompat.Action.Builder(+ R.drawable.ic_transparent,+ notificationAction.title,+ actionPendingIntent+ )+ if (notificationAction.input == true) {+ val remoteInput = RemoteInput.Builder(REMOTE_INPUT_KEY).setLabel(+ notificationAction.title+ ).build()+ actionBuilder.addRemoteInput(remoteInput)+ }+ mBuilder.addAction(actionBuilder.build())+ }+ }++ // Dismiss intent+ val dissmissIntent = Intent(+ context,+ NotificationDismissReceiver::class.java+ )+ dissmissIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK+ dissmissIntent.putExtra(NOTIFICATION_INTENT_KEY, notification.id)+ dissmissIntent.putExtra(ACTION_INTENT_KEY, "dismiss")+ val schedule = notification.schedule+ dissmissIntent.putExtra(+ NOTIFICATION_IS_REMOVABLE_KEY,+ schedule == null || schedule.isRemovable()+ )+ flags = 0+ if (SDK_INT >= Build.VERSION_CODES.S) {+ flags = PendingIntent.FLAG_MUTABLE+ }+ val deleteIntent =+ PendingIntent.getBroadcast(context, notification.id, dissmissIntent, flags)+ mBuilder.setDeleteIntent(deleteIntent)+ }++ private fun buildIntent(notification: Notification, action: String?): Intent {+ val intent = if (activity != null) {+ Intent(context, activity.javaClass)+ } else {+ val packageName = context.packageName+ context.packageManager.getLaunchIntentForPackage(packageName)!!+ }+ intent.action = Intent.ACTION_MAIN+ intent.addCategory(Intent.CATEGORY_LAUNCHER)+ intent.flags = Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_CLEAR_TOP+ intent.putExtra(NOTIFICATION_INTENT_KEY, notification.id)+ intent.putExtra(ACTION_INTENT_KEY, action)+ intent.putExtra(NOTIFICATION_OBJ_INTENT_KEY, notification.sourceJson)+ val schedule = notification.schedule+ intent.putExtra(NOTIFICATION_IS_REMOVABLE_KEY, schedule == null || schedule.isRemovable())+ return intent+ }++ /**+ * Build a notification trigger, such as triggering each N seconds, or+ * on a certain date "shape" (such as every first of the month)+ */+ // TODO support different AlarmManager.RTC modes depending on priority+ @SuppressLint("SimpleDateFormat")+ private fun triggerScheduledNotification(notification: android.app.Notification, request: Notification) {+ val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager+ val schedule = request.schedule+ val notificationIntent = Intent(+ context,+ TimedNotificationPublisher::class.java+ )+ notificationIntent.putExtra(NOTIFICATION_INTENT_KEY, request.id)+ notificationIntent.putExtra(TimedNotificationPublisher.NOTIFICATION_KEY, notification)+ var flags = PendingIntent.FLAG_CANCEL_CURRENT+ if (SDK_INT >= Build.VERSION_CODES.S) {+ flags = flags or PendingIntent.FLAG_MUTABLE+ }+ var pendingIntent =+ PendingIntent.getBroadcast(context, request.id, notificationIntent, flags)++ when (schedule) {+ is NotificationSchedule.At -> {+ if (schedule.date.time < Date().time) {+ Logger.error(Logger.tags(TAG), "Scheduled time must be *after* current time", null)+ return+ }+ if (schedule.repeating) {+ val interval: Long = schedule.date.time - Date().time+ alarmManager.setRepeating(AlarmManager.RTC, schedule.date.time, interval, pendingIntent)+ } else {+ setExactIfPossible(alarmManager, schedule, schedule.date.time, pendingIntent)+ }+ }+ is NotificationSchedule.Interval -> {+ val trigger = schedule.interval.nextTrigger(Date())+ notificationIntent.putExtra(TimedNotificationPublisher.CRON_KEY, schedule.interval.toMatchString())+ pendingIntent =+ PendingIntent.getBroadcast(context, request.id, notificationIntent, flags)+ setExactIfPossible(alarmManager, schedule, trigger, pendingIntent)+ val sdf = SimpleDateFormat("yyyy/MM/dd HH:mm:ss")+ Logger.debug(+ Logger.tags(TAG),+ "notification " + request.id + " will next fire at " + sdf.format(Date(trigger))+ )+ }+ is NotificationSchedule.Every -> {+ val everyInterval = getIntervalTime(schedule.interval, schedule.count)+ val startTime: Long = Date().time + everyInterval+ alarmManager.setRepeating(AlarmManager.RTC, startTime, everyInterval, pendingIntent)+ }+ else -> {}+ }+ }++ @SuppressLint("ObsoleteSdkInt", "MissingPermission")+ private fun setExactIfPossible(+ alarmManager: AlarmManager,+ schedule: NotificationSchedule,+ trigger: Long,+ pendingIntent: PendingIntent+ ) {+ Logger.debug(Logger.tags(TAG), "Scheduling notification for " + Date(trigger).toString())++ if (SDK_INT >= Build.VERSION_CODES.S && !alarmManager.canScheduleExactAlarms()) {+ Logger.warn(Logger.tags(TAG), "SCHEDULE_EXACT_ALARM permission not granted. Using inexact alarm.")++ if (SDK_INT >= Build.VERSION_CODES.M && schedule.allowWhileIdle()) {+ alarmManager.setAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, trigger, pendingIntent)+ } else {+ alarmManager[AlarmManager.RTC, trigger] = pendingIntent+ }+ } else {+ if (SDK_INT >= Build.VERSION_CODES.M && schedule.allowWhileIdle()) {+ alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, trigger, pendingIntent)+ } else {+ alarmManager.setExact(AlarmManager.RTC, trigger, pendingIntent)+ }+ }+ }++ fun cancel(notifications: List<Int>) {+ for (id in notifications) {+ dismissVisibleNotification(id)+ cancelTimerForNotification(id)+ storage.deleteNotification(id.toString())+ }+ }++ private fun cancelTimerForNotification(notificationId: Int) {+ val intent = Intent(context, TimedNotificationPublisher::class.java)+ var flags = 0+ if (SDK_INT >= Build.VERSION_CODES.S) {+ flags = PendingIntent.FLAG_MUTABLE+ }+ val pi = PendingIntent.getBroadcast(context, notificationId, intent, flags)+ if (pi != null) {+ val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager+ alarmManager.cancel(pi)+ }+ }++ private fun dismissVisibleNotification(notificationId: Int) {+ val notificationManager = NotificationManagerCompat.from(+ context+ )+ notificationManager.cancel(notificationId)+ }++ fun areNotificationsEnabled(): Boolean {+ val notificationManager = NotificationManagerCompat.from(context)+ return notificationManager.areNotificationsEnabled()+ }++ private fun getDefaultSoundUrl(context: Context): Uri? {+ val soundId = getDefaultSound(context)+ return if (soundId != AssetUtils.RESOURCE_ID_ZERO_VALUE) {+ Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + context.packageName + "/" + soundId)+ } else null+ }++ private fun getDefaultSound(context: Context): Int {+ if (defaultSoundID != AssetUtils.RESOURCE_ID_ZERO_VALUE) return defaultSoundID+ var resId: Int = AssetUtils.RESOURCE_ID_ZERO_VALUE+ val soundConfigResourceName = AssetUtils.getResourceBaseName(config?.sound)+ if (soundConfigResourceName != null) {+ resId = AssetUtils.getResourceID(context, soundConfigResourceName, "raw")+ }+ defaultSoundID = resId+ return resId+ }++ private fun getDefaultSmallIcon(context: Context): Int {+ if (defaultSmallIconID != AssetUtils.RESOURCE_ID_ZERO_VALUE) return defaultSmallIconID+ var resId: Int = AssetUtils.RESOURCE_ID_ZERO_VALUE+ val smallIconConfigResourceName = AssetUtils.getResourceBaseName(config?.icon)+ if (smallIconConfigResourceName != null) {+ resId = AssetUtils.getResourceID(context, smallIconConfigResourceName, "drawable")+ }+ if (resId == AssetUtils.RESOURCE_ID_ZERO_VALUE) {+ resId = android.R.drawable.ic_dialog_info+ }+ defaultSmallIconID = resId+ return resId+ }+}++class NotificationDismissReceiver : BroadcastReceiver() {+ override fun onReceive(context: Context, intent: Intent) {+ val intExtra =+ intent.getIntExtra(NOTIFICATION_INTENT_KEY, Int.MIN_VALUE)+ if (intExtra == Int.MIN_VALUE) {+ Logger.error(Logger.tags(TAG), "Invalid notification dismiss operation", null)+ return+ }+ val isRemovable =+ intent.getBooleanExtra(NOTIFICATION_IS_REMOVABLE_KEY, true)+ if (isRemovable) {+ val notificationStorage = NotificationStorage(context, ObjectMapper())+ notificationStorage.deleteNotification(intExtra.toString())+ }+ }+}++class TimedNotificationPublisher : BroadcastReceiver() {+ /**+ * Restore and present notification+ */+ override fun onReceive(context: Context, intent: Intent) {+ val notificationManager =+ context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager+ val notification = if (SDK_INT >= Build.VERSION_CODES.TIRAMISU) {+ intent.getParcelableExtra(+ NOTIFICATION_KEY,+ android.app.Notification::class.java+ )+ } else {+ getParcelableExtraLegacy(intent, NOTIFICATION_KEY)+ }+ notification?.`when` = System.currentTimeMillis()+ val id = intent.getIntExtra(NOTIFICATION_INTENT_KEY, Int.MIN_VALUE)+ if (id == Int.MIN_VALUE) {+ Logger.error(Logger.tags(TAG), "No valid id supplied", null)+ return+ }+ if (notification == null) {+ Logger.error(Logger.tags(TAG), "No notification object in intent", null)+ return+ }+ val storage = NotificationStorage(context, ObjectMapper())++ // Check if notification still exists in storage (might have been cancelled)+ val savedNotification = storage.getSavedNotification(id.toString())+ if (savedNotification == null) {+ // Notification was cancelled, don't show or reschedule+ Logger.debug(Logger.tags(TAG), "Notification $id was cancelled, skipping")+ return+ }++ NotificationPlugin.triggerNotification(savedNotification)+ notificationManager.notify(id, notification)+ if (!rescheduleNotificationIfNeeded(context, intent, id)) {+ storage.deleteNotification(id.toString())+ }+ }++ @Suppress("DEPRECATION")+ private fun getParcelableExtraLegacy(intent: Intent, string: String): android.app.Notification? {+ return intent.getParcelableExtra(string)+ }++ @SuppressLint("MissingPermission", "SimpleDateFormat")+ private fun rescheduleNotificationIfNeeded(context: Context, intent: Intent, id: Int): Boolean {+ val dateString = intent.getStringExtra(CRON_KEY)+ if (dateString != null) {+ val date = DateMatch.fromMatchString(dateString)+ val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager+ val trigger = date.nextTrigger(Date())+ val clone = intent.clone() as Intent+ var flags = PendingIntent.FLAG_CANCEL_CURRENT+ if (SDK_INT >= Build.VERSION_CODES.S) {+ flags = flags or PendingIntent.FLAG_MUTABLE+ }+ val pendingIntent = PendingIntent.getBroadcast(context, id, clone, flags)+ if (SDK_INT >= Build.VERSION_CODES.S && !alarmManager.canScheduleExactAlarms()) {+ alarmManager[AlarmManager.RTC, trigger] = pendingIntent+ } else {+ alarmManager.setExact(AlarmManager.RTC, trigger, pendingIntent)+ }+ val sdf = SimpleDateFormat("yyyy/MM/dd HH:mm:ss")+ Logger.debug(+ Logger.tags(TAG),+ "notification " + id + " will next fire at " + sdf.format(Date(trigger))+ )+ return true+ }+ return false+ }++ companion object {+ var NOTIFICATION_KEY = "NotificationPublisher.notification"+ var CRON_KEY = "NotificationPublisher.cron"+ }+}++class LocalNotificationRestoreReceiver : BroadcastReceiver() {+ @SuppressLint("ObsoleteSdkInt")+ override fun onReceive(context: Context, intent: Intent) {+ if (SDK_INT >= Build.VERSION_CODES.N) {+ val um = context.getSystemService(+ UserManager::class.java+ )+ if (um == null || !um.isUserUnlocked) return+ }+ val storage = NotificationStorage(context, ObjectMapper())+ val ids = storage.getSavedNotificationIds()+ val notifications = mutableListOf<Notification>()+ val updatedNotifications = mutableListOf<Notification>()+ for (id in ids) {+ val notification = storage.getSavedNotification(id) ?: continue+ val schedule = notification.schedule+ if (schedule != null && schedule is NotificationSchedule.At) {+ val at: Date = schedule.date+ if (at.before(Date())) {+ // modify the scheduled date in order to show notifications that would have been delivered while device was off.+ val newDateTime = Date().time + 15 * 1000+ schedule.date = Date(newDateTime)+ updatedNotifications.add(notification)+ }+ }+ notifications.add(notification)+ }+ if (updatedNotifications.size > 0) {+ storage.appendNotifications(updatedNotifications)+ }++ var config: PluginConfig? = null+ try {+ config = PluginManager.loadConfig(context, "notification", PluginConfig::class.java)+ } catch (e: Exception) {+ Logger.error(Logger.tags(TAG), "Failed to load notification plugin config: ${e.message}", e)+ }+ val notificationManager = TauriNotificationManager(storage, null, context, config)+ notificationManager.schedule(notifications)+ }+}diff --git a/src-tauri/vendor/tauri-plugin-notifications/android/src/main/res/drawable/ic_transparent.xml b/src-tauri/vendor/tauri-plugin-notifications/android/src/main/res/drawable/ic_transparent.xmlnew file mode 100644index 00000000..fc1779e2--- /dev/null+++ b/src-tauri/vendor/tauri-plugin-notifications/android/src/main/res/drawable/ic_transparent.xml@@ -0,0 +1,12 @@+<?xml version="1.0" encoding="utf-8"?>+<vector xmlns:android="http://schemas.android.com/apk/res/android"+ android:width="16dp"+ android:height="16dp"+ android:viewportHeight="108"+ android:viewportWidth="108">++ <path+ android:width="1dp"+ android:color="@android:color/transparent" />++</vector>diff --git a/src-tauri/vendor/tauri-plugin-notifications/android/src/test/java/app/tauri/notification/ChannelManagerTest.kt b/src-tauri/vendor/tauri-plugin-notifications/android/src/test/java/app/tauri/notification/ChannelManagerTest.ktnew file mode 100644index 00000000..0caeb9fb--- /dev/null+++ b/src-tauri/vendor/tauri-plugin-notifications/android/src/test/java/app/tauri/notification/ChannelManagerTest.kt@@ -0,0 +1,276 @@+package app.tauri.notification++import org.junit.Assert.*+import org.junit.Test++class ChannelManagerTest {++ @Test+ fun testImportance_values() {+ assertEquals(0, Importance.None.value)+ assertEquals(1, Importance.Min.value)+ assertEquals(2, Importance.Low.value)+ assertEquals(3, Importance.Default.value)+ assertEquals(4, Importance.High.value)+ }++ @Test+ fun testImportance_ordinal() {+ val values = Importance.values()+ assertEquals(5, values.size)+ assertEquals(Importance.None, values[0])+ assertEquals(Importance.Min, values[1])+ assertEquals(Importance.Low, values[2])+ assertEquals(Importance.Default, values[3])+ assertEquals(Importance.High, values[4])+ }++ @Test+ fun testVisibility_values() {+ assertEquals(-1, Visibility.Secret.value)+ assertEquals(0, Visibility.Private.value)+ assertEquals(1, Visibility.Public.value)+ }++ @Test+ fun testVisibility_ordinal() {+ val values = Visibility.values()+ assertEquals(3, values.size)+ assertEquals(Visibility.Secret, values[0])+ assertEquals(Visibility.Private, values[1])+ assertEquals(Visibility.Public, values[2])+ }++ @Test+ fun testChannel_properties() {+ val channel = Channel()+ channel.id = "test_channel"+ channel.name = "Test Channel"+ channel.description = "A test notification channel"+ channel.sound = "notification_sound"+ channel.lights = true+ channel.lightsColor = "#FF0000"+ channel.vibration = true+ channel.importance = Importance.High+ channel.visibility = Visibility.Private++ assertEquals("test_channel", channel.id)+ assertEquals("Test Channel", channel.name)+ assertEquals("A test notification channel", channel.description)+ assertEquals("notification_sound", channel.sound)+ assertEquals(true, channel.lights)+ assertEquals("#FF0000", channel.lightsColor)+ assertEquals(true, channel.vibration)+ assertEquals(Importance.High, channel.importance)+ assertEquals(Visibility.Private, channel.visibility)+ }++ @Test+ fun testChannel_nullableProperties() {+ val channel = Channel()+ channel.id = "minimal_channel"+ channel.name = "Minimal"++ assertEquals("minimal_channel", channel.id)+ assertEquals("Minimal", channel.name)+ assertNull(channel.description)+ assertNull(channel.sound)+ assertNull(channel.lights)+ assertNull(channel.lightsColor)+ assertNull(channel.vibration)+ assertNull(channel.importance)+ assertNull(channel.visibility)+ }++ @Test+ fun testChannel_defaultImportance() {+ val channel = Channel()+ channel.id = "default_channel"+ channel.name = "Default"++ val importance = channel.importance ?: Importance.Default+ assertEquals(Importance.Default, importance)+ }++ @Test+ fun testChannel_defaultVisibility() {+ val channel = Channel()+ channel.id = "default_channel"+ channel.name = "Default"++ val visibility = channel.visibility ?: Visibility.Private+ assertEquals(Visibility.Private, visibility)+ }++ @Test+ fun testChannel_allImportanceLevels() {+ val channels = listOf(+ Channel().apply {+ id = "none"+ name = "None"+ importance = Importance.None+ },+ Channel().apply {+ id = "min"+ name = "Min"+ importance = Importance.Min+ },+ Channel().apply {+ id = "low"+ name = "Low"+ importance = Importance.Low+ },+ Channel().apply {+ id = "default"+ name = "Default"+ importance = Importance.Default+ },+ Channel().apply {+ id = "high"+ name = "High"+ importance = Importance.High+ }+ )++ assertEquals(5, channels.size)+ assertEquals(Importance.None, channels[0].importance)+ assertEquals(Importance.Min, channels[1].importance)+ assertEquals(Importance.Low, channels[2].importance)+ assertEquals(Importance.Default, channels[3].importance)+ assertEquals(Importance.High, channels[4].importance)+ }++ @Test+ fun testChannel_allVisibilityLevels() {+ val channels = listOf(+ Channel().apply {+ id = "secret"+ name = "Secret"+ visibility = Visibility.Secret+ },+ Channel().apply {+ id = "private"+ name = "Private"+ visibility = Visibility.Private+ },+ Channel().apply {+ id = "public"+ name = "Public"+ visibility = Visibility.Public+ }+ )++ assertEquals(3, channels.size)+ assertEquals(Visibility.Secret, channels[0].visibility)+ assertEquals(Visibility.Private, channels[1].visibility)+ assertEquals(Visibility.Public, channels[2].visibility)+ }++ @Test+ fun testChannel_soundWithExtension() {+ val channel = Channel()+ channel.id = "sound_channel"+ channel.name = "Sound"+ channel.sound = "notification.mp3"++ assertEquals("notification.mp3", channel.sound)+ }++ @Test+ fun testChannel_lightsColorFormats() {+ val channel1 = Channel()+ channel1.id = "hex_color"+ channel1.name = "Hex"+ channel1.lightsColor = "#FF0000"++ val channel2 = Channel()+ channel2.id = "short_hex"+ channel2.name = "Short"+ channel2.lightsColor = "#F00"++ val channel3 = Channel()+ channel3.id = "rgba"+ channel3.name = "RGBA"+ channel3.lightsColor = "#FF0000FF"++ assertEquals("#FF0000", channel1.lightsColor)+ assertEquals("#F00", channel2.lightsColor)+ assertEquals("#FF0000FF", channel3.lightsColor)+ }++ @Test+ fun testChannel_booleanFlags() {+ val channel = Channel()+ channel.id = "flags"+ channel.name = "Flags"+ channel.lights = false+ channel.vibration = false++ assertFalse(channel.lights ?: true)+ assertFalse(channel.vibration ?: true)+ }++ @Test+ fun testDeleteChannelArgs() {+ val args = DeleteChannelArgs()+ args.id = "channel_to_delete"++ assertEquals("channel_to_delete", args.id)+ }++ @Test+ fun testImportance_valueOf() {+ assertEquals(Importance.None, Importance.valueOf("None"))+ assertEquals(Importance.Min, Importance.valueOf("Min"))+ assertEquals(Importance.Low, Importance.valueOf("Low"))+ assertEquals(Importance.Default, Importance.valueOf("Default"))+ assertEquals(Importance.High, Importance.valueOf("High"))+ }++ @Test+ fun testVisibility_valueOf() {+ assertEquals(Visibility.Secret, Visibility.valueOf("Secret"))+ assertEquals(Visibility.Private, Visibility.valueOf("Private"))+ assertEquals(Visibility.Public, Visibility.valueOf("Public"))+ }++ @Test+ fun testChannel_complexConfiguration() {+ val channel = Channel()+ channel.id = "messages"+ channel.name = "Messages"+ channel.description = "Notifications for new messages"+ channel.importance = Importance.High+ channel.visibility = Visibility.Private+ channel.sound = "message_sound"+ channel.vibration = true+ channel.lights = true+ channel.lightsColor = "#0000FF"++ assertEquals("messages", channel.id)+ assertEquals("Messages", channel.name)+ assertEquals("Notifications for new messages", channel.description)+ assertEquals(Importance.High, channel.importance)+ assertEquals(Visibility.Private, channel.visibility)+ assertEquals("message_sound", channel.sound)+ assertTrue(channel.vibration ?: false)+ assertTrue(channel.lights ?: false)+ assertEquals("#0000FF", channel.lightsColor)+ }++ @Test+ fun testChannel_emptyStrings() {+ val channel = Channel()+ channel.id = ""+ channel.name = ""+ channel.description = ""+ channel.sound = ""+ channel.lightsColor = ""++ assertEquals("", channel.id)+ assertEquals("", channel.name)+ assertEquals("", channel.description)+ assertEquals("", channel.sound)+ assertEquals("", channel.lightsColor)+ }+}diff --git a/src-tauri/vendor/tauri-plugin-notifications/android/src/test/java/app/tauri/notification/DateMatchTest.kt b/src-tauri/vendor/tauri-plugin-notifications/android/src/test/java/app/tauri/notification/DateMatchTest.ktnew file mode 100644index 00000000..24deb3c5--- /dev/null+++ b/src-tauri/vendor/tauri-plugin-notifications/android/src/test/java/app/tauri/notification/DateMatchTest.kt@@ -0,0 +1,285 @@+package app.tauri.notification++import org.junit.Assert.*+import org.junit.Test+import java.util.*++class DateMatchTest {++ @Test+ fun testDateMatch_equals_identical() {+ val date1 = DateMatch()+ date1.year = 2024+ date1.month = 5+ date1.day = 15++ val date2 = DateMatch()+ date2.year = 2024+ date2.month = 5+ date2.day = 15++ assertEquals(date1, date2)+ }++ @Test+ fun testDateMatch_equals_different() {+ val date1 = DateMatch()+ date1.year = 2024+ date1.month = 5++ val date2 = DateMatch()+ date2.year = 2024+ date2.month = 6++ assertNotEquals(date1, date2)+ }++ @Test+ fun testDateMatch_equals_sameInstance() {+ val date = DateMatch()+ date.year = 2024++ assertEquals(date, date)+ }++ @Test+ fun testDateMatch_equals_null() {+ val date = DateMatch()+ date.year = 2024++ assertNotEquals(date, null)+ }++ @Test+ fun testDateMatch_hashCode_identical() {+ val date1 = DateMatch()+ date1.year = 2024+ date1.month = 5+ date1.hour = 10++ val date2 = DateMatch()+ date2.year = 2024+ date2.month = 5+ date2.hour = 10++ assertEquals(date1.hashCode(), date2.hashCode())+ }++ @Test+ fun testDateMatch_hashCode_different() {+ val date1 = DateMatch()+ date1.year = 2024++ val date2 = DateMatch()+ date2.year = 2025++ assertNotEquals(date1.hashCode(), date2.hashCode())+ }++ @Test+ fun testDateMatch_toString() {+ val date = DateMatch()+ date.year = 2024+ date.month = 11+ date.day = 26+ date.hour = 14+ date.minute = 30+ date.second = 0++ val result = date.toString()+ assertTrue(result.contains("year=2024"))+ assertTrue(result.contains("month=11"))+ assertTrue(result.contains("day=26"))+ assertTrue(result.contains("hour=14"))+ assertTrue(result.contains("minute=30"))+ assertTrue(result.contains("second=0"))+ }++ @Test+ fun testDateMatch_toMatchString_allFields() {+ val date = DateMatch()+ date.year = 2024+ date.month = 5+ date.day = 15+ date.weekday = 2+ date.hour = 10+ date.minute = 30+ date.second = 0+ date.unit = Calendar.HOUR_OF_DAY++ val result = date.toMatchString()+ assertEquals("2024 5 15 2 10 30 0 11", result)+ }++ @Test+ fun testDateMatch_toMatchString_partialFields() {+ val date = DateMatch()+ date.hour = 10+ date.minute = 30++ val result = date.toMatchString()+ assertTrue(result.contains("*"))+ assertTrue(result.contains("10"))+ assertTrue(result.contains("30"))+ }++ @Test+ fun testDateMatch_fromMatchString_allFields() {+ val matchString = "2024 5 15 2 10 30 0 11"+ val date = DateMatch.fromMatchString(matchString)++ assertEquals(2024, date.year)+ assertEquals(5, date.month)+ assertEquals(15, date.day)+ assertEquals(2, date.weekday)+ assertEquals(10, date.hour)+ assertEquals(30, date.minute)+ assertEquals(0, date.second)+ assertEquals(11, date.unit)+ }++ @Test+ fun testDateMatch_fromMatchString_withWildcards() {+ val matchString = "* * 15 * 10 30 * -1"+ val date = DateMatch.fromMatchString(matchString)++ assertNull(date.year)+ assertNull(date.month)+ assertEquals(15, date.day)+ assertNull(date.weekday)+ assertEquals(10, date.hour)+ assertEquals(30, date.minute)+ assertNull(date.second)+ assertEquals(-1, date.unit)+ }++ @Test+ fun testDateMatch_fromMatchString_sevenFields() {+ val matchString = "2024 5 15 2 10 30 11"+ val date = DateMatch.fromMatchString(matchString)++ assertEquals(2024, date.year)+ assertEquals(5, date.month)+ assertEquals(15, date.day)+ assertEquals(2, date.weekday)+ assertEquals(10, date.hour)+ assertEquals(30, date.minute)+ assertEquals(11, date.unit)+ assertNull(date.second)+ }++ @Test+ fun testDateMatch_nextTrigger_futureDate() {+ val date = DateMatch()+ date.hour = 23+ date.minute = 59++ val calendar = Calendar.getInstance()+ calendar.set(Calendar.HOUR_OF_DAY, 10)+ calendar.set(Calendar.MINUTE, 0)+ calendar.set(Calendar.SECOND, 0)+ calendar.set(Calendar.MILLISECOND, 0)++ val baseDate = calendar.time+ val nextTrigger = date.nextTrigger(baseDate)++ assertTrue(nextTrigger > baseDate.time)+ }++ @Test+ fun testDateMatch_nextTrigger_specificHourAndMinute() {+ val date = DateMatch()+ date.hour = 15+ date.minute = 30++ val calendar = Calendar.getInstance()+ calendar.set(Calendar.HOUR_OF_DAY, 10)+ calendar.set(Calendar.MINUTE, 0)+ calendar.set(Calendar.SECOND, 0)+ calendar.set(Calendar.MILLISECOND, 0)++ val baseDate = calendar.time+ val nextTrigger = date.nextTrigger(baseDate)++ val resultCalendar = Calendar.getInstance()+ resultCalendar.timeInMillis = nextTrigger++ assertEquals(15, resultCalendar.get(Calendar.HOUR_OF_DAY))+ assertEquals(30, resultCalendar.get(Calendar.MINUTE))+ }++ @Test+ fun testGetIntervalTime_year() {+ val result = getIntervalTime(NotificationInterval.Year, 1)+ assertEquals(52 * 7 * 24 * 60 * 60 * 1000L, result)+ }++ @Test+ fun testGetIntervalTime_month() {+ val result = getIntervalTime(NotificationInterval.Month, 1)+ assertEquals(30 * 24 * 60 * 60 * 1000L, result)+ }++ @Test+ fun testGetIntervalTime_twoWeeks() {+ val result = getIntervalTime(NotificationInterval.TwoWeeks, 1)+ assertEquals(14 * 24 * 60 * 60 * 1000L, result)+ }++ @Test+ fun testGetIntervalTime_week() {+ val result = getIntervalTime(NotificationInterval.Week, 1)+ assertEquals(7 * 24 * 60 * 60 * 1000L, result)+ }++ @Test+ fun testGetIntervalTime_day() {+ val result = getIntervalTime(NotificationInterval.Day, 1)+ assertEquals(24 * 60 * 60 * 1000L, result)+ }++ @Test+ fun testGetIntervalTime_hour() {+ val result = getIntervalTime(NotificationInterval.Hour, 1)+ assertEquals(60 * 60 * 1000L, result)+ }++ @Test+ fun testGetIntervalTime_minute() {+ val result = getIntervalTime(NotificationInterval.Minute, 1)+ assertEquals(60 * 1000L, result)+ }++ @Test+ fun testGetIntervalTime_second() {+ val result = getIntervalTime(NotificationInterval.Second, 1)+ assertEquals(1000L, result)+ }++ @Test+ fun testGetIntervalTime_multipleCount() {+ val result = getIntervalTime(NotificationInterval.Hour, 3)+ assertEquals(3 * 60 * 60 * 1000L, result)+ }++ @Test+ fun testDateMatch_roundTripSerialization() {+ val original = DateMatch()+ original.year = 2024+ original.month = 11+ original.day = 26+ original.hour = 14+ original.minute = 30+ original.second = 15++ val matchString = original.toMatchString()+ val restored = DateMatch.fromMatchString(matchString)++ assertEquals(original.year, restored.year)+ assertEquals(original.month, restored.month)+ assertEquals(original.day, restored.day)+ assertEquals(original.hour, restored.hour)+ assertEquals(original.minute, restored.minute)+ assertEquals(original.second, restored.second)+ }+}diff --git a/src-tauri/vendor/tauri-plugin-notifications/android/src/test/java/app/tauri/notification/NotificationAttachmentTest.kt b/src-tauri/vendor/tauri-plugin-notifications/android/src/test/java/app/tauri/notification/NotificationAttachmentTest.ktnew file mode 100644index 00000000..851516cc--- /dev/null+++ b/src-tauri/vendor/tauri-plugin-notifications/android/src/test/java/app/tauri/notification/NotificationAttachmentTest.kt@@ -0,0 +1,260 @@+package app.tauri.notification++import app.tauri.plugin.JSObject+import org.json.JSONArray+import org.json.JSONObject+import org.junit.Assert.*+import org.junit.Test+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner++@RunWith(RobolectricTestRunner::class)+class NotificationAttachmentTest {++ @Test+ fun testGetAttachments_singleAttachment() {+ val attachmentJson = JSONObject()+ attachmentJson.put("id", "attachment1")+ attachmentJson.put("url", "file:///path/to/image.jpg")++ val attachmentsArray = JSONArray()+ attachmentsArray.put(attachmentJson)++ val notification = JSObject()+ notification.put("attachments", attachmentsArray)++ val result = NotificationAttachment.getAttachments(notification)++ assertEquals(1, result.size)+ assertEquals("attachment1", result[0].id)+ assertEquals("file:///path/to/image.jpg", result[0].url)+ assertNull(result[0].options)+ }++ @Test+ fun testGetAttachments_multipleAttachments() {+ val attachment1 = JSONObject()+ attachment1.put("id", "attachment1")+ attachment1.put("url", "file:///path/to/image1.jpg")++ val attachment2 = JSONObject()+ attachment2.put("id", "attachment2")+ attachment2.put("url", "file:///path/to/image2.png")++ val attachment3 = JSONObject()+ attachment3.put("id", "attachment3")+ attachment3.put("url", "file:///path/to/video.mp4")++ val attachmentsArray = JSONArray()+ attachmentsArray.put(attachment1)+ attachmentsArray.put(attachment2)+ attachmentsArray.put(attachment3)++ val notification = JSObject()+ notification.put("attachments", attachmentsArray)++ val result = NotificationAttachment.getAttachments(notification)++ assertEquals(3, result.size)+ assertEquals("attachment1", result[0].id)+ assertEquals("attachment2", result[1].id)+ assertEquals("attachment3", result[2].id)+ }++ @Test+ fun testGetAttachments_withOptions() {+ val options = JSONObject()+ options.put("thumbnail", true)+ options.put("quality", 0.8)++ val attachmentJson = JSONObject()+ attachmentJson.put("id", "attachment1")+ attachmentJson.put("url", "file:///path/to/image.jpg")+ attachmentJson.put("options", options)++ val attachmentsArray = JSONArray()+ attachmentsArray.put(attachmentJson)++ val notification = JSObject()+ notification.put("attachments", attachmentsArray)++ val result = NotificationAttachment.getAttachments(notification)++ assertEquals(1, result.size)+ assertEquals("attachment1", result[0].id)+ assertNotNull(result[0].options)+ assertEquals(true, result[0].options?.getBoolean("thumbnail"))+ assertEquals(0.8, result[0].options?.getDouble("quality") ?: 0.0, 0.001)+ }++ @Test+ fun testGetAttachments_emptyArray() {+ val attachmentsArray = JSONArray()++ val notification = JSObject()+ notification.put("attachments", attachmentsArray)++ val result = NotificationAttachment.getAttachments(notification)++ assertEquals(0, result.size)+ }++ @Test+ fun testGetAttachments_noAttachmentsField() {+ val notification = JSObject()++ val result = NotificationAttachment.getAttachments(notification)++ assertEquals(0, result.size)+ }++ @Test+ fun testGetAttachments_invalidArrayElement() {+ val attachmentsArray = JSONArray()+ attachmentsArray.put("invalid string")+ attachmentsArray.put(123)++ val notification = JSObject()+ notification.put("attachments", attachmentsArray)++ val result = NotificationAttachment.getAttachments(notification)++ assertEquals(0, result.size)+ }++ @Test+ fun testGetAttachments_mixedValidInvalid() {+ val validAttachment = JSONObject()+ validAttachment.put("id", "valid")+ validAttachment.put("url", "file:///valid.jpg")++ val attachmentsArray = JSONArray()+ attachmentsArray.put(validAttachment)+ attachmentsArray.put("invalid")+ attachmentsArray.put(validAttachment)++ val notification = JSObject()+ notification.put("attachments", attachmentsArray)++ val result = NotificationAttachment.getAttachments(notification)++ assertEquals(2, result.size)+ assertEquals("valid", result[0].id)+ assertEquals("valid", result[1].id)+ }++ @Test+ fun testGetAttachments_missingIdField() {+ val attachmentJson = JSONObject()+ attachmentJson.put("url", "file:///path/to/image.jpg")++ val attachmentsArray = JSONArray()+ attachmentsArray.put(attachmentJson)++ val notification = JSObject()+ notification.put("attachments", attachmentsArray)++ val result = NotificationAttachment.getAttachments(notification)++ assertEquals(1, result.size)+ assertTrue(result[0].id.isNullOrEmpty())+ assertEquals("file:///path/to/image.jpg", result[0].url)+ }++ @Test+ fun testGetAttachments_missingUrlField() {+ val attachmentJson = JSONObject()+ attachmentJson.put("id", "attachment1")++ val attachmentsArray = JSONArray()+ attachmentsArray.put(attachmentJson)++ val notification = JSObject()+ notification.put("attachments", attachmentsArray)++ val result = NotificationAttachment.getAttachments(notification)++ assertEquals(1, result.size)+ assertEquals("attachment1", result[0].id)+ assertTrue(result[0].url.isNullOrEmpty())+ }++ @Test+ fun testGetAttachments_emptyStrings() {+ val attachmentJson = JSONObject()+ attachmentJson.put("id", "")+ attachmentJson.put("url", "")++ val attachmentsArray = JSONArray()+ attachmentsArray.put(attachmentJson)++ val notification = JSObject()+ notification.put("attachments", attachmentsArray)++ val result = NotificationAttachment.getAttachments(notification)++ assertEquals(1, result.size)+ assertEquals("", result[0].id)+ assertEquals("", result[0].url)+ }++ @Test+ fun testGetAttachments_differentUrlFormats() {+ val attachment1 = JSONObject()+ attachment1.put("id", "http")+ attachment1.put("url", "http://example.com/image.jpg")++ val attachment2 = JSONObject()+ attachment2.put("id", "https")+ attachment2.put("url", "https://example.com/image.jpg")++ val attachment3 = JSONObject()+ attachment3.put("id", "file")+ attachment3.put("url", "file:///local/path/image.jpg")++ val attachment4 = JSONObject()+ attachment4.put("id", "content")+ attachment4.put("url", "content://media/external/images/1")++ val attachmentsArray = JSONArray()+ attachmentsArray.put(attachment1)+ attachmentsArray.put(attachment2)+ attachmentsArray.put(attachment3)+ attachmentsArray.put(attachment4)++ val notification = JSObject()+ notification.put("attachments", attachmentsArray)++ val result = NotificationAttachment.getAttachments(notification)++ assertEquals(4, result.size)+ assertEquals("http://example.com/image.jpg", result[0].url)+ assertEquals("https://example.com/image.jpg", result[1].url)+ assertEquals("file:///local/path/image.jpg", result[2].url)+ assertEquals("content://media/external/images/1", result[3].url)+ }++ @Test+ fun testNotificationAttachment_properties() {+ val attachment = NotificationAttachment()+ attachment.id = "test_id"+ attachment.url = "test_url"++ val options = JSONObject()+ options.put("key", "value")+ attachment.options = options++ assertEquals("test_id", attachment.id)+ assertEquals("test_url", attachment.url)+ assertEquals("value", attachment.options?.getString("key"))+ }++ @Test+ fun testNotificationAttachment_nullProperties() {+ val attachment = NotificationAttachment()++ assertNull(attachment.id)+ assertNull(attachment.url)+ assertNull(attachment.options)+ }+}diff --git a/src-tauri/vendor/tauri-plugin-notifications/android/src/test/java/app/tauri/notification/NotificationScheduleTest.kt b/src-tauri/vendor/tauri-plugin-notifications/android/src/test/java/app/tauri/notification/NotificationScheduleTest.ktnew file mode 100644index 00000000..d3876bdd--- /dev/null+++ b/src-tauri/vendor/tauri-plugin-notifications/android/src/test/java/app/tauri/notification/NotificationScheduleTest.kt@@ -0,0 +1,119 @@+package app.tauri.notification++import org.junit.Assert.*+import org.junit.Test+import java.util.*++class NotificationScheduleTest {++ @Test+ fun testScheduleAt_isRemovable_nonRepeating() {+ val schedule = NotificationSchedule.At()+ schedule.date = Date()+ schedule.repeating = false++ assertTrue(schedule.isRemovable())+ }++ @Test+ fun testScheduleAt_isRemovable_repeating() {+ val schedule = NotificationSchedule.At()+ schedule.date = Date()+ schedule.repeating = true++ assertFalse(schedule.isRemovable())+ }++ @Test+ fun testScheduleInterval_isRemovable() {+ val schedule = NotificationSchedule.Interval()+ schedule.interval = DateMatch()++ assertFalse(schedule.isRemovable())+ }++ @Test+ fun testScheduleEvery_isRemovable() {+ val schedule = NotificationSchedule.Every()+ schedule.interval = NotificationInterval.Hour+ schedule.count = 1++ assertFalse(schedule.isRemovable())+ }++ @Test+ fun testScheduleAt_allowWhileIdle_true() {+ val schedule = NotificationSchedule.At()+ schedule.allowWhileIdle = true++ assertTrue(schedule.allowWhileIdle())+ }++ @Test+ fun testScheduleAt_allowWhileIdle_false() {+ val schedule = NotificationSchedule.At()+ schedule.allowWhileIdle = false++ assertFalse(schedule.allowWhileIdle())+ }++ @Test+ fun testScheduleInterval_allowWhileIdle() {+ val schedule = NotificationSchedule.Interval()+ schedule.allowWhileIdle = true+ schedule.interval = DateMatch()++ assertTrue(schedule.allowWhileIdle())+ }++ @Test+ fun testScheduleEvery_allowWhileIdle() {+ val schedule = NotificationSchedule.Every()+ schedule.allowWhileIdle = true+ schedule.interval = NotificationInterval.Day+ schedule.count = 1++ assertTrue(schedule.allowWhileIdle())+ }++ @Test+ fun testScheduleAt_toString() {+ val schedule = NotificationSchedule.At()+ val date = Date(1234567890000L)+ schedule.date = date+ schedule.repeating = true+ schedule.allowWhileIdle = true++ val result = schedule.toString()+ assertTrue(result.contains("At"))+ assertTrue(result.contains("repeating=true"))+ assertTrue(result.contains("allowWhileIdle=true"))+ }++ @Test+ fun testScheduleInterval_toString() {+ val schedule = NotificationSchedule.Interval()+ val dateMatch = DateMatch()+ dateMatch.hour = 10+ schedule.interval = dateMatch+ schedule.allowWhileIdle = false++ val result = schedule.toString()+ assertTrue(result.contains("Interval"))+ assertTrue(result.contains("allowWhileIdle=false"))+ }++ @Test+ fun testScheduleEvery_toString() {+ val schedule = NotificationSchedule.Every()+ schedule.interval = NotificationInterval.Week+ schedule.count = 2+ schedule.allowWhileIdle = true++ val result = schedule.toString()+ assertTrue(result.contains("Every"))+ assertTrue(result.contains("interval=Week"))+ assertTrue(result.contains("count=2"))+ assertTrue(result.contains("allowWhileIdle=true"))+ }+}diff --git a/src-tauri/vendor/tauri-plugin-notifications/android/src/test/java/app/tauri/notification/NotificationStorageTest.kt b/src-tauri/vendor/tauri-plugin-notifications/android/src/test/java/app/tauri/notification/NotificationStorageTest.ktnew file mode 100644index 00000000..b7b204c8--- /dev/null+++ b/src-tauri/vendor/tauri-plugin-notifications/android/src/test/java/app/tauri/notification/NotificationStorageTest.kt@@ -0,0 +1,281 @@+package app.tauri.notification++import android.content.Context+import android.content.SharedPreferences+import com.fasterxml.jackson.databind.ObjectMapper+import io.mockk.*+import org.junit.Assert.*+import org.junit.Before+import org.junit.Test+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner++@RunWith(RobolectricTestRunner::class)+class NotificationStorageTest {++ private lateinit var mockContext: Context+ private lateinit var mockSharedPreferences: SharedPreferences+ private lateinit var mockEditor: SharedPreferences.Editor+ private lateinit var objectMapper: ObjectMapper+ private lateinit var notificationStorage: NotificationStorage++ @Before+ fun setup() {+ mockContext = mockk()+ mockSharedPreferences = mockk()+ mockEditor = mockk(relaxed = true)+ objectMapper = ObjectMapper()+ notificationStorage = NotificationStorage(mockContext, objectMapper)++ every { mockContext.getSharedPreferences(any(), any()) } returns mockSharedPreferences+ every { mockSharedPreferences.edit() } returns mockEditor+ every { mockEditor.apply() } just Runs+ }++ @Test+ fun testAppendNotifications_withSchedule() {+ val notification = Notification()+ notification.id = 1+ notification.title = "Test Notification"+ notification.body = "Test Body"+ notification.schedule = NotificationSchedule.At().apply {+ repeating = false+ }+ notification.sourceJson = """{"id":1,"title":"Test Notification"}"""++ every { mockEditor.putString("1", notification.sourceJson) } returns mockEditor++ notificationStorage.appendNotifications(listOf(notification))++ verify { mockEditor.putString("1", notification.sourceJson) }+ verify { mockEditor.apply() }+ }++ @Test+ fun testAppendNotifications_withoutSchedule() {+ val notification = Notification()+ notification.id = 1+ notification.title = "Test Notification"+ notification.schedule = null+ notification.sourceJson = """{"id":1,"title":"Test Notification"}"""++ notificationStorage.appendNotifications(listOf(notification))++ verify(exactly = 0) { mockEditor.putString(any(), any()) }+ verify { mockEditor.apply() }+ }++ @Test+ fun testAppendNotifications_multipleNotifications() {+ val notification1 = Notification()+ notification1.id = 1+ notification1.schedule = NotificationSchedule.At()+ notification1.sourceJson = """{"id":1}"""++ val notification2 = Notification()+ notification2.id = 2+ notification2.schedule = NotificationSchedule.Every().apply {+ interval = NotificationInterval.Hour+ count = 1+ }+ notification2.sourceJson = """{"id":2}"""++ every { mockEditor.putString(any(), any()) } returns mockEditor++ notificationStorage.appendNotifications(listOf(notification1, notification2))++ verify { mockEditor.putString("1", """{"id":1}""") }+ verify { mockEditor.putString("2", """{"id":2}""") }+ verify { mockEditor.apply() }+ }++ @Test+ fun testGetSavedNotificationIds_withNotifications() {+ val mockMap = mapOf("1" to "notification1", "2" to "notification2", "3" to "notification3")+ every { mockSharedPreferences.all } returns mockMap++ val result = notificationStorage.getSavedNotificationIds()++ assertEquals(3, result.size)+ assertTrue(result.contains("1"))+ assertTrue(result.contains("2"))+ assertTrue(result.contains("3"))+ }++ @Test+ fun testGetSavedNotificationIds_empty() {+ every { mockSharedPreferences.all } returns null++ val result = notificationStorage.getSavedNotificationIds()++ assertEquals(0, result.size)+ }++ @Test+ fun testGetSavedNotifications_validJson() {+ val mockMap = mapOf("1" to "invalid json")+ every { mockSharedPreferences.all } returns mockMap++ val result = notificationStorage.getSavedNotifications()++ // Jackson deserialization is complex, just verify method doesn't crash+ assertTrue(result.size >= 0)+ }++ @Test+ fun testGetSavedNotifications_invalidJson() {+ val mockMap = mapOf("1" to "invalid json data")+ every { mockSharedPreferences.all } returns mockMap++ val result = notificationStorage.getSavedNotifications()++ assertEquals(0, result.size)+ }++ @Test+ fun testGetSavedNotifications_mixedValidInvalid() {+ val mockMap = mapOf(+ "1" to "invalid1",+ "2" to "invalid json",+ "3" to "invalid2"+ )+ every { mockSharedPreferences.all } returns mockMap++ val result = notificationStorage.getSavedNotifications()++ // Invalid JSON should be filtered out+ assertTrue(result.size >= 0)+ }++ @Test+ fun testGetSavedNotification_notExists() {+ every { mockSharedPreferences.getString("99", null) } returns null++ val result = notificationStorage.getSavedNotification("99")++ assertNull(result)+ }++ @Test+ fun testGetSavedNotification_classCastException() {+ every { mockSharedPreferences.getString("1", null) } throws ClassCastException()++ val result = notificationStorage.getSavedNotification("1")++ assertNull(result)+ }++ @Test+ fun testDeleteNotification() {+ every { mockEditor.remove("123") } returns mockEditor++ notificationStorage.deleteNotification("123")++ verify { mockEditor.remove("123") }+ verify { mockEditor.apply() }+ }++ @Test+ fun testDeleteNotification_null() {+ every { mockEditor.remove(null) } returns mockEditor++ notificationStorage.deleteNotification(null)++ verify { mockEditor.remove(null) }+ verify { mockEditor.apply() }+ }++ @Test+ fun testWriteActionGroup_singleAction() {+ val action = NotificationAction()+ action.id = "action1"+ action.title = "Action 1"+ action.input = true++ val actionType = ActionType()+ actionType.id = "type1"+ actionType.actions = listOf(action)++ every { mockEditor.clear() } returns mockEditor+ every { mockEditor.putInt(any(), any()) } returns mockEditor+ every { mockEditor.putString(any(), any()) } returns mockEditor+ every { mockEditor.putBoolean(any(), any()) } returns mockEditor++ notificationStorage.writeActionGroup(listOf(actionType))++ verify { mockEditor.clear() }+ verify { mockEditor.putInt("count", 1) }+ verify { mockEditor.apply() }+ }++ @Test+ fun testWriteActionGroup_multipleActions() {+ val action1 = NotificationAction()+ action1.id = "action1"+ action1.title = "Action 1"+ action1.input = false++ val action2 = NotificationAction()+ action2.id = "action2"+ action2.title = "Action 2"+ action2.input = true++ val actionType = ActionType()+ actionType.id = "type1"+ actionType.actions = listOf(action1, action2)++ every { mockEditor.clear() } returns mockEditor+ every { mockEditor.putInt(any(), any()) } returns mockEditor+ every { mockEditor.putString(any(), any()) } returns mockEditor+ every { mockEditor.putBoolean(any(), any()) } returns mockEditor++ notificationStorage.writeActionGroup(listOf(actionType))++ verify { mockEditor.putInt("count", 2) }+ verify { mockEditor.apply() }+ }++ @Test+ fun testGetActionGroup() {+ every { mockSharedPreferences.getInt("count", 0) } returns 2+ every { mockSharedPreferences.getString("id0", "") } returns "action1"+ every { mockSharedPreferences.getString("title0", "") } returns "Title 1"+ every { mockSharedPreferences.getBoolean("input0", false) } returns false+ every { mockSharedPreferences.getString("id1", "") } returns "action2"+ every { mockSharedPreferences.getString("title1", "") } returns "Title 2"+ every { mockSharedPreferences.getBoolean("input1", false) } returns true++ val result = notificationStorage.getActionGroup("type1")++ assertEquals(2, result.size)+ assertEquals("action1", result[0]?.id)+ assertEquals("Title 1", result[0]?.title)+ assertEquals(false, result[0]?.input)+ assertEquals("action2", result[1]?.id)+ assertEquals("Title 2", result[1]?.title)+ assertEquals(true, result[1]?.input)+ }++ @Test+ fun testGetActionGroup_empty() {+ every { mockSharedPreferences.getInt("count", 0) } returns 0++ val result = notificationStorage.getActionGroup("emptyType")++ assertEquals(0, result.size)+ }++ @Test+ fun testGetActionGroup_nullValues() {+ every { mockSharedPreferences.getInt("count", 0) } returns 1+ every { mockSharedPreferences.getString("id0", "") } returns null+ every { mockSharedPreferences.getString("title0", "") } returns null+ every { mockSharedPreferences.getBoolean("input0", false) } returns false++ val result = notificationStorage.getActionGroup("type1")++ assertEquals(1, result.size)+ assertEquals("", result[0]?.id)+ assertNull(result[0]?.title)+ }+}diff --git a/src-tauri/vendor/tauri-plugin-notifications/android/src/test/java/app/tauri/notification/NotificationTest.kt b/src-tauri/vendor/tauri-plugin-notifications/android/src/test/java/app/tauri/notification/NotificationTest.ktnew file mode 100644index 00000000..0fc59c8e--- /dev/null+++ b/src-tauri/vendor/tauri-plugin-notifications/android/src/test/java/app/tauri/notification/NotificationTest.kt@@ -0,0 +1,433 @@+package app.tauri.notification++import android.content.Context+import android.content.res.Resources+import android.graphics.Bitmap+import android.graphics.BitmapFactory+import app.tauri.plugin.JSObject+import com.fasterxml.jackson.annotation.JsonAutoDetect+import com.fasterxml.jackson.annotation.PropertyAccessor+import com.fasterxml.jackson.databind.DeserializationFeature+import com.fasterxml.jackson.databind.ObjectMapper+import io.mockk.*+import org.json.JSONObject+import org.junit.Assert.*+import org.junit.Before+import org.junit.Test+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner++@RunWith(RobolectricTestRunner::class)+class NotificationTest {++ private lateinit var mockContext: Context+ private lateinit var mockResources: Resources++ @Before+ fun setup() {+ mockContext = mockk()+ mockResources = mockk()+ every { mockContext.resources } returns mockResources+ every { mockContext.packageName } returns "app.tauri.notification.test"+ }++ @Test+ fun testGetSound_customSound() {+ val notification = Notification()+ notification.sound = "custom_sound.mp3"++ every { mockResources.getIdentifier("custom_sound", "raw", "app.tauri.notification.test") } returns 12345++ val result = notification.getSound(mockContext, 999)++ assertEquals("android.resource://app.tauri.notification.test/12345", result)+ }++ @Test+ fun testGetSound_defaultSound() {+ val notification = Notification()+ notification.sound = null++ val result = notification.getSound(mockContext, 999)++ assertEquals("android.resource://app.tauri.notification.test/999", result)+ }++ @Test+ fun testGetSound_invalidCustomSound_fallbackToDefault() {+ val notification = Notification()+ notification.sound = "nonexistent_sound"++ every { mockResources.getIdentifier("nonexistent_sound", "raw", "app.tauri.notification.test") } returns 0++ val result = notification.getSound(mockContext, 999)++ assertEquals("android.resource://app.tauri.notification.test/999", result)+ }++ @Test+ fun testGetSound_soundWithPath() {+ val notification = Notification()+ notification.sound = "sounds/notification.wav"++ // AssetUtils.getResourceBaseName returns "notification.wav" for "sounds/notification.wav"+ // because it extracts after "/" but doesn't strip extension in that case+ every { mockResources.getIdentifier("notification.wav", "raw", "app.tauri.notification.test") } returns 54321++ val result = notification.getSound(mockContext, 999)++ assertEquals("android.resource://app.tauri.notification.test/54321", result)+ }++ @Test+ fun testGetSound_zeroDefaultSound() {+ val notification = Notification()+ notification.sound = null++ val result = notification.getSound(mockContext, 0)++ assertNull(result)+ }++ @Test+ fun testGetIconColor_localColor() {+ val notification = Notification()+ notification.iconColor = "#FF0000"++ val result = notification.getIconColor("#00FF00")++ assertEquals("#FF0000", result)+ }++ @Test+ fun testGetIconColor_globalColor() {+ val notification = Notification()+ notification.iconColor = null++ val result = notification.getIconColor("#00FF00")++ assertEquals("#00FF00", result)+ }++ @Test+ fun testGetSmallIcon_customIcon() {+ val notification = Notification()+ notification.icon = "custom_icon"++ every { mockResources.getIdentifier("custom_icon", "drawable", "app.tauri.notification.test") } returns 12345++ val result = notification.getSmallIcon(mockContext, 999)++ assertEquals(12345, result)+ }++ @Test+ fun testGetSmallIcon_defaultIcon() {+ val notification = Notification()+ notification.icon = null++ val result = notification.getSmallIcon(mockContext, 999)++ assertEquals(999, result)+ }++ @Test+ fun testGetSmallIcon_invalidCustomIcon_fallbackToDefault() {+ val notification = Notification()+ notification.icon = "nonexistent_icon"++ every { mockResources.getIdentifier("nonexistent_icon", "drawable", "app.tauri.notification.test") } returns 0++ val result = notification.getSmallIcon(mockContext, 999)++ assertEquals(999, result)+ }++ @Test+ fun testGetLargeIcon_validIcon() {+ mockkStatic(BitmapFactory::class)+ val mockBitmap = mockk<Bitmap>()++ val notification = Notification()+ notification.largeIcon = "large_icon"++ every { mockResources.getIdentifier("large_icon", "drawable", "app.tauri.notification.test") } returns 54321+ every { BitmapFactory.decodeResource(mockResources, 54321) } returns mockBitmap++ val result = notification.getLargeIcon(mockContext)++ assertNotNull(result)+ assertEquals(mockBitmap, result)++ unmockkStatic(BitmapFactory::class)+ }++ @Test+ fun testGetLargeIcon_nullIcon() {+ val notification = Notification()+ notification.largeIcon = null++ val result = notification.getLargeIcon(mockContext)++ assertNull(result)+ }++ @Test+ fun testBuildNotificationPendingList_singleNotification() {+ val notification = Notification()+ notification.id = 1+ notification.title = "Test Title"+ notification.body = "Test Body"+ notification.schedule = NotificationSchedule.At()+ notification.extra = JSObject()++ val pendingList = Notification.buildNotificationPendingList(listOf(notification))++ assertEquals(1, pendingList.size)+ assertEquals(1, pendingList[0].id)+ assertEquals("Test Title", pendingList[0].title)+ assertEquals("Test Body", pendingList[0].body)+ assertNotNull(pendingList[0].schedule)+ assertNotNull(pendingList[0].extra)+ }++ @Test+ fun testBuildNotificationPendingList_multipleNotifications() {+ val notification1 = Notification()+ notification1.id = 1+ notification1.title = "Title 1"+ notification1.body = "Body 1"++ val notification2 = Notification()+ notification2.id = 2+ notification2.title = "Title 2"+ notification2.body = "Body 2"++ val notification3 = Notification()+ notification3.id = 3+ notification3.title = "Title 3"+ notification3.body = "Body 3"++ val pendingList = Notification.buildNotificationPendingList(+ listOf(notification1, notification2, notification3)+ )++ assertEquals(3, pendingList.size)+ assertEquals(1, pendingList[0].id)+ assertEquals(2, pendingList[1].id)+ assertEquals(3, pendingList[2].id)+ }++ @Test+ fun testBuildNotificationPendingList_emptyList() {+ val pendingList = Notification.buildNotificationPendingList(emptyList())++ assertEquals(0, pendingList.size)+ }++ @Test+ fun testBuildNotificationPendingList_nullValues() {+ val notification = Notification()+ notification.id = 1+ notification.title = null+ notification.body = null+ notification.schedule = null+ notification.extra = null++ val pendingList = Notification.buildNotificationPendingList(listOf(notification))++ assertEquals(1, pendingList.size)+ assertEquals(1, pendingList[0].id)+ assertNull(pendingList[0].title)+ assertNull(pendingList[0].body)+ assertNull(pendingList[0].schedule)+ assertNull(pendingList[0].extra)+ }++ @Test+ fun testNotificationProperties() {+ val notification = Notification()+ notification.id = 42+ notification.title = "Title"+ notification.body = "Body"+ notification.largeBody = "Large Body"+ notification.summary = "Summary"+ notification.sound = "sound"+ notification.icon = "icon"+ notification.largeIcon = "large_icon"+ notification.iconColor = "#FF0000"+ notification.actionTypeId = "action_type"+ notification.group = "group"+ notification.inboxLines = listOf("Line 1", "Line 2")+ notification.isGroupSummary = true+ notification.isOngoing = true+ notification.isAutoCancel = false+ notification.extra = JSObject()+ notification.attachments = emptyList()+ notification.schedule = NotificationSchedule.At()+ notification.channelId = "channel"+ notification.sourceJson = "{}"+ notification.visibility = 1+ notification.number = 5++ assertEquals(42, notification.id)+ assertEquals("Title", notification.title)+ assertEquals("Body", notification.body)+ assertEquals("Large Body", notification.largeBody)+ assertEquals("Summary", notification.summary)+ assertEquals("sound", notification.sound)+ assertEquals("icon", notification.icon)+ assertEquals("large_icon", notification.largeIcon)+ assertEquals("#FF0000", notification.iconColor)+ assertEquals("action_type", notification.actionTypeId)+ assertEquals("group", notification.group)+ assertEquals(2, notification.inboxLines?.size)+ assertTrue(notification.isGroupSummary)+ assertTrue(notification.isOngoing)+ assertFalse(notification.isAutoCancel)+ assertNotNull(notification.extra)+ assertNotNull(notification.attachments)+ assertNotNull(notification.schedule)+ assertEquals("channel", notification.channelId)+ assertEquals("{}", notification.sourceJson)+ assertEquals(1, notification.visibility)+ assertEquals(5, notification.number)+ }++ /**+ * Proves that Jackson's ObjectMapper cannot properly serialize a Notification+ * with a JSObject (extends org.json.JSONObject) in its `extra` field.+ * Jackson treats JSONObject as a regular Java bean, so the "extra" field+ * loses its intended {"key":"value"} content. This was the root cause of+ * foreground push notifications not triggering onNotificationReceived.+ */+ @Test+ fun testJacksonSerializationOfNotificationWithExtra_broken() {+ val objectMapper = ObjectMapper()+ .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)+ .enable(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES)+ .setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY)++ val notification = Notification()+ notification.id = 1+ notification.title = "Test"+ notification.body = "Body"+ notification.extra = JSObject().apply { put("key", "value") }++ // Jackson serializes JSObject as a Java bean, not as a JSON map+ val json = objectMapper.writeValueAsString(notification)+ val parsed = JSONObject(json)++ // The extra field either doesn't contain the expected key/value,+ // or is serialized as bean internals instead of {"key":"value"}+ val extraField = parsed.opt("extra")+ val isCorrect = try {+ val extra = parsed.getJSONObject("extra")+ extra.has("key") && extra.getString("key") == "value"+ } catch (e: Exception) {+ false+ }+ assertFalse("Jackson should NOT correctly serialize JSObject extra field", isCorrect)+ }++ /**+ * Verifies that the fixed triggerNotification() builds a correct JSObject+ * using manual construction + Plugin.trigger() instead of triggerObject().+ * This uses the same serialization path as Channel.send(JSObject).+ */+ @Test+ fun testTriggerNotificationBuildsCorrectJSObject() {+ val notification = Notification()+ notification.id = 42+ notification.title = "Push Title"+ notification.body = "Push Body"+ notification.channelId = "test-channel"+ notification.sound = "default"+ notification.isGroupSummary = true+ notification.extra = JSObject().apply {+ put("key", "value")+ put("nested", "data")+ }+ notification.inboxLines = listOf("Line 1", "Line 2")++ // Reproduce what the fixed triggerNotification() does+ val data = JSObject()+ data.put("id", notification.id)+ notification.title?.let { data.put("title", it) }+ notification.body?.let { data.put("body", it) }+ notification.largeBody?.let { data.put("largeBody", it) }+ notification.summary?.let { data.put("summary", it) }+ notification.sound?.let { data.put("sound", it) }+ notification.actionTypeId?.let { data.put("actionTypeId", it) }+ notification.group?.let { data.put("group", it) }+ notification.channelId?.let { data.put("channelId", it) }+ if (notification.isGroupSummary) data.put("groupSummary", true)+ if (notification.isOngoing) data.put("ongoing", true)+ if (notification.isAutoCancel) data.put("autoCancel", true)+ notification.silent?.let { data.put("silent", it) }+ notification.extra?.let { data.put("extra", it) }++ // Verify it produces valid JSON via PluginResult (the Channel.send path)+ val json = data.toString()+ val parsed = JSONObject(json)++ assertEquals(42, parsed.getInt("id"))+ assertEquals("Push Title", parsed.getString("title"))+ assertEquals("Push Body", parsed.getString("body"))+ assertEquals("test-channel", parsed.getString("channelId"))+ assertEquals("default", parsed.getString("sound"))+ assertTrue(parsed.getBoolean("groupSummary"))+ assertFalse(parsed.has("ongoing"))+ assertFalse(parsed.has("autoCancel"))++ val extra = parsed.getJSONObject("extra")+ assertEquals("value", extra.getString("key"))+ assertEquals("data", extra.getString("nested"))+ }++ @Test+ fun testTriggerNotification_sourceDefaultsToLocal() {+ val data = JSObject()+ val source = "local" // default parameter value+ data.put("source", source)+ data.put("id", 1)++ val json = data.toString()+ val parsed = JSONObject(json)++ assertEquals("local", parsed.getString("source"))+ }++ @Test+ fun testTriggerNotification_sourceCanBePush() {+ val data = JSObject()+ val source = "push"+ data.put("source", source)+ data.put("id", 1)++ val json = data.toString()+ val parsed = JSONObject(json)++ assertEquals("push", parsed.getString("source"))+ }++ @Test+ fun testPendingNotification_properties() {+ val schedule = NotificationSchedule.At()+ val extra = JSObject()++ val pendingNotification = PendingNotification().apply {+ id = 10+ title = "Pending Title"+ body = "Pending Body"+ this.schedule = schedule+ this.extra = extra+ }++ assertEquals(10, pendingNotification.id)+ assertEquals("Pending Title", pendingNotification.title)+ assertEquals("Pending Body", pendingNotification.body)+ assertEquals(schedule, pendingNotification.schedule)+ assertEquals(extra, pendingNotification.extra)+ }+}diff --git a/src-tauri/vendor/tauri-plugin-notifications/build.rs b/src-tauri/vendor/tauri-plugin-notifications/build.rsnew file mode 100644index 00000000..1b782809--- /dev/null+++ b/src-tauri/vendor/tauri-plugin-notifications/build.rs@@ -0,0 +1,233 @@+#[cfg(target_os = "macos")]+use std::{path::PathBuf, process::Command};++const COMMANDS: &[&str] = &[+ "register_listener",+ "remove_listener",+ "notify",+ "request_permission",+ "is_permission_granted",+ "register_for_push_notifications",+ "unregister_for_push_notifications",+ "register_action_types",+ "cancel",+ "cancel_all",+ "get_pending",+ "remove_active",+ "remove_all",+ "get_active",+ "check_permissions",+ "show",+ "batch",+ "list_channels",+ "delete_channel",+ "create_channel",+ "permission_state",+ "set_click_listener_active",+ "list_distributors",+ "set_distributor",+ "set_token",+];++fn main() {+ // Check if push-notifications feature is enabled+ let enable_push = cfg!(feature = "push-notifications");++ // Generate build.properties file for Android+ if std::env::var("TARGET")+ .unwrap_or_default()+ .contains("android")+ {+ let properties_content = format!("enablePushNotifications={enable_push}");+ std::fs::write("android/build.properties", properties_content)+ .expect("Failed to write build.properties");+ }++ // Generate marker file for iOS/macOS Swift build+ // Package.swift reads this file to conditionally enable ENABLE_PUSH_NOTIFICATIONS+ let ios_marker_path = std::path::Path::new("ios/.push-notifications-enabled");+ let macos_marker_path = std::path::Path::new("macos/.push-notifications-enabled");+ if enable_push {+ std::fs::write(ios_marker_path, "").expect("Failed to write iOS push marker file");+ std::fs::write(macos_marker_path, "").expect("Failed to write macOS push marker file");+ } else {+ if ios_marker_path.exists() {+ std::fs::remove_file(ios_marker_path).ok();+ }+ if macos_marker_path.exists() {+ std::fs::remove_file(macos_marker_path).ok();+ }+ }++ let result = tauri_plugin::Builder::new(COMMANDS)+ .android_path("android")+ .ios_path("ios")+ .try_build();++ // when building documentation for Android the plugin build result is always Err() and is irrelevant to the crate documentation build+ if !(cfg!(docsrs)+ && std::env::var("TARGET")+ .expect("Failed to get TARGET environment variable")+ .contains("android"))+ {+ result.expect("Failed to build Tauri plugin");+ }++ #[cfg(target_os = "macos")]+ {+ // Only run macOS-specific build steps when building for macOS+ if std::env::var("CARGO_CFG_TARGET_OS").unwrap_or_default() == "macos" {+ // Rebuild when target architecture or deployment target changes+ println!("cargo:rerun-if-env-changed=CARGO_CFG_TARGET_ARCH");+ println!("cargo:rerun-if-env-changed=MACOSX_DEPLOYMENT_TARGET");++ let bridges = vec!["src/macos.rs"];+ for path in &bridges {+ println!("cargo:rerun-if-changed={path}");+ }++ println!("cargo:rerun-if-changed=macos/Sources/NotificationPlugin.swift");++ swift_bridge_build::parse_bridges(bridges)+ .write_all_concatenated(swift_bridge_out_dir(), env!("CARGO_PKG_NAME"));++ compile_swift();++ println!("cargo:rustc-link-lib=static=tauri-plugin-notifications");+ println!(+ "cargo:rustc-link-search={}",+ swift_library_static_lib_dir()+ .to_str()+ .expect("Swift library path must be valid UTF-8")+ );+ }+ }+}++#[cfg(target_os = "macos")]+fn compile_swift() {+ let swift_package_dir = manifest_dir().join("macos");+ let target_triple = swift_target_triple();++ let mut cmd = Command::new("swift");++ cmd.current_dir(&swift_package_dir)+ .arg("build")+ // Build into OUT_DIR (under target/) instead of the default `.build`+ // inside the crate source. Source-tree writes don't survive a clean+ // registry re-extraction / cache restore, which leaves cargo's+ // fingerprint saying "built" while the linked artifact is gone.+ .args([+ "--scratch-path",+ swift_build_dir()+ .to_str()+ .expect("Swift build path must be valid UTF-8"),+ ])+ .args(["--triple", &target_triple])+ .args([+ "-Xswiftc",+ "-import-objc-header",+ "-Xswiftc",+ swift_source_dir()+ .join("bridging-header.h")+ .to_str()+ .expect("Bridging header path must be valid UTF-8"),+ ]);++ if is_release_build() {+ cmd.args(["-c", "release"]);+ }++ let exit_status = cmd+ .spawn()+ .expect("Failed to spawn swift build command")+ .wait_with_output()+ .expect("Failed to wait for swift build output");++ assert!(+ exit_status.status.success(),+ r"+Swift build failed for target: {}+Stderr: {}+Stdout: {}+",+ target_triple,+ String::from_utf8(exit_status.stderr).expect("Stderr must be valid UTF-8"),+ String::from_utf8(exit_status.stdout).expect("Stdout must be valid UTF-8"),+ );+}++#[cfg(target_os = "macos")]+fn swift_bridge_out_dir() -> PathBuf {+ generated_code_dir()+}++#[cfg(target_os = "macos")]+fn manifest_dir() -> PathBuf {+ let manifest_dir = std::env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR must be set");+ PathBuf::from(manifest_dir)+}++#[cfg(target_os = "macos")]+fn out_dir() -> PathBuf {+ let out_dir = std::env::var("OUT_DIR").expect("OUT_DIR must be set");+ PathBuf::from(out_dir)+}++/// `SwiftPM` scratch (build) directory, under `OUT_DIR` so it lives in `target/`+/// and is covered by cargo's fingerprint and any build cache.+#[cfg(target_os = "macos")]+fn swift_build_dir() -> PathBuf {+ out_dir().join("swift-build")+}++#[cfg(target_os = "macos")]+fn is_release_build() -> bool {+ std::env::var("PROFILE").expect("PROFILE must be set") == "release"+}++#[cfg(target_os = "macos")]+fn swift_source_dir() -> PathBuf {+ manifest_dir().join("macos/Sources")+}++#[cfg(target_os = "macos")]+fn generated_code_dir() -> PathBuf {+ swift_source_dir().join("generated")+}++#[cfg(target_os = "macos")]+fn target_arch() -> String {+ std::env::var("CARGO_CFG_TARGET_ARCH").expect("CARGO_CFG_TARGET_ARCH must be set")+}++#[cfg(target_os = "macos")]+fn swift_arch() -> &'static str {+ match target_arch().as_str() {+ "aarch64" => "arm64",+ "x86_64" => "x86_64",+ arch => panic!("Unsupported architecture for macOS: {arch}"),+ }+}++#[cfg(target_os = "macos")]+fn macos_deployment_target() -> String {+ std::env::var("MACOSX_DEPLOYMENT_TARGET").unwrap_or_else(|_| "13.0".to_string())+}++#[cfg(target_os = "macos")]+fn swift_target_triple() -> String {+ format!("{}-apple-macosx{}", swift_arch(), macos_deployment_target())+}++#[cfg(target_os = "macos")]+fn swift_library_static_lib_dir() -> PathBuf {+ let debug_or_release = if is_release_build() {+ "release"+ } else {+ "debug"+ };++ let arch_dir = format!("{}-apple-macosx", swift_arch());+ swift_build_dir().join(format!("{arch_dir}/{debug_or_release}"))+}diff --git a/src-tauri/vendor/tauri-plugin-notifications/ios/.gitignore b/src-tauri/vendor/tauri-plugin-notifications/ios/.gitignorenew file mode 100644index 00000000..ffdb745c--- /dev/null+++ b/src-tauri/vendor/tauri-plugin-notifications/ios/.gitignore@@ -0,0 +1,14 @@+.DS_Store+/.build+/Packages+/*.xcodeproj+/*.xcresult+xcuserdata/+DerivedData/+.swiftpm/config/registries.json+.swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata+.netrc+.swiftpm+Package.resolved+coverage.json+.push-notifications-enableddiff --git a/src-tauri/vendor/tauri-plugin-notifications/ios/Package.swift b/src-tauri/vendor/tauri-plugin-notifications/ios/Package.swiftnew file mode 100644index 00000000..7a3e0c63--- /dev/null+++ b/src-tauri/vendor/tauri-plugin-notifications/ios/Package.swift@@ -0,0 +1,48 @@+// swift-tools-version:5.7++import PackageDescription+import Foundation++// Check if push notifications feature is enabled via marker file from Rust build+let enablePushNotifications = FileManager.default.fileExists(+ atPath: URL(fileURLWithPath: #file).deletingLastPathComponent()+ .appendingPathComponent(".push-notifications-enabled").path+)++var swiftSettings: [SwiftSetting] = []+if enablePushNotifications {+ swiftSettings.append(.define("ENABLE_PUSH_NOTIFICATIONS"))+}++let package = Package(+ name: "tauri-plugin-notifications",+ platforms: [+ .macOS(.v13),+ .iOS(.v15),+ ],+ products: [+ // Products define the executables and libraries a package produces, and make them visible to other packages.+ .library(+ name: "tauri-plugin-notifications",+ type: .static,+ targets: ["tauri-plugin-notifications"])+ ],+ dependencies: [+ .package(name: "Tauri", path: "../.tauri/tauri-api")+ ],+ targets: [+ // Targets are the basic building blocks of a package. A target can define a module or a test suite.+ // Targets can depend on other targets in this package, and on products in packages this package depends on.+ .target(+ name: "tauri-plugin-notifications",+ dependencies: [+ .byName(name: "Tauri")+ ],+ path: "Sources",+ swiftSettings: swiftSettings),+ .testTarget(+ name: "PluginTests",+ dependencies: ["tauri-plugin-notifications", .byName(name: "Tauri")]+ ),+ ]+)diff --git a/src-tauri/vendor/tauri-plugin-notifications/ios/README.md b/src-tauri/vendor/tauri-plugin-notifications/ios/README.mdnew file mode 100644index 00000000..f4900bdd--- /dev/null+++ b/src-tauri/vendor/tauri-plugin-notifications/ios/README.md@@ -0,0 +1,3 @@+# Tauri Plugin {{ plugin_name_original }}++A description of this package.diff --git a/src-tauri/vendor/tauri-plugin-notifications/ios/Sources/AppDelegateSwizzler.swift b/src-tauri/vendor/tauri-plugin-notifications/ios/Sources/AppDelegateSwizzler.swiftnew file mode 100644index 00000000..0bb1c964--- /dev/null+++ b/src-tauri/vendor/tauri-plugin-notifications/ios/Sources/AppDelegateSwizzler.swift@@ -0,0 +1,111 @@+import UIKit+import Tauri+import ObjectiveC.runtime++#if ENABLE_PUSH_NOTIFICATIONS++enum AppDelegateSwizzler {+ static weak var plugin: NotificationPlugin?++ static func swizzlePushCallbacks() {+ guard let app = UIApplication.shared as UIApplication?,+ let delegate = app.delegate else { return }++ // didRegisterForRemoteNotificationsWithDeviceToken+ swizzle(+ type(of: delegate),+ #selector(UIApplicationDelegate.application(_:didRegisterForRemoteNotificationsWithDeviceToken:)),+ #selector(PushForwarder.ta_application(_:didRegisterForRemoteNotificationsWithDeviceToken:))+ )++ // didFailToRegisterForRemoteNotificationsWithError+ swizzle(+ type(of: delegate),+ #selector(UIApplicationDelegate.application(_:didFailToRegisterForRemoteNotificationsWithError:)),+ #selector(PushForwarder.ta_application(_:didFailToRegisterForRemoteNotificationsWithError:))+ )++ // didReceiveRemoteNotification (silent/background)+ swizzle(+ type(of: delegate),+ #selector(UIApplicationDelegate.application(_:didReceiveRemoteNotification:fetchCompletionHandler:)),+ #selector(PushForwarder.ta_application(_:didReceiveRemoteNotification:fetchCompletionHandler:))+ )+ }++ private static func swizzle(_ cls: AnyClass, _ original: Selector, _ replacement: Selector) {+ guard+ let swizzledMethod = class_getInstanceMethod(PushForwarder.self, replacement)+ else { return }++ if let originalMethod = class_getInstanceMethod(cls, original) {+ // Original method exists - exchange implementations+ method_exchangeImplementations(originalMethod, swizzledMethod)+ } else {+ // Original method doesn't exist - add our method+ class_addMethod(+ cls,+ original,+ method_getImplementation(swizzledMethod),+ method_getTypeEncoding(swizzledMethod)+ )+ }+ }+}++/// A helper that hosts the swizzled implementations.+/// NOTE: These method names must exactly match the selectors we swizzle.+final class PushForwarder: NSObject, UIApplicationDelegate {+ // Token success+ @objc func ta_application(_ application: UIApplication,+ didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {+ // Convert token to hex string+ let hex = deviceToken.map { String(format: "%02x", $0) }.joined()++ // Notify plugin about token+ AppDelegateSwizzler.plugin?.handlePushTokenReceived(hex)++ // Also emit event for JS/Rust listeners+ try? AppDelegateSwizzler.plugin?.trigger("push-token", data: ["token": hex])++ // Call original only if it was swapped (not added)+ if responds(to: #selector(ta_application(_:didRegisterForRemoteNotificationsWithDeviceToken:))) {+ self.ta_application(application, didRegisterForRemoteNotificationsWithDeviceToken: deviceToken)+ }+ }++ // Token failure+ @objc func ta_application(_ application: UIApplication,+ didFailToRegisterForRemoteNotificationsWithError error: Error) {+ // Notify plugin about error+ AppDelegateSwizzler.plugin?.handlePushTokenError(error)++ // Also emit event for JS/Rust listeners+ try? AppDelegateSwizzler.plugin?.trigger("push-error", data: ["message": error.localizedDescription])++ // Call original only if it was swapped (not added)+ if responds(to: #selector(ta_application(_:didFailToRegisterForRemoteNotificationsWithError:))) {+ self.ta_application(application, didFailToRegisterForRemoteNotificationsWithError: error)+ }+ }++ // Background/remote (silent) payloads+ @objc func ta_application(_ application: UIApplication,+ didReceiveRemoteNotification userInfo: [AnyHashable : Any],+ fetchCompletionHandler completion: @escaping (UIBackgroundFetchResult) -> Void) {+ // Emit event for push message+ if let jsData = JSTypes.coerceDictionaryToJSObject(userInfo) {+ try? AppDelegateSwizzler.plugin?.trigger("push-message", data: jsData)+ }++ // Call original only if it was swapped (not added)+ if responds(to: #selector(ta_application(_:didReceiveRemoteNotification:fetchCompletionHandler:))) {+ self.ta_application(application, didReceiveRemoteNotification: userInfo, fetchCompletionHandler: completion)+ } else {+ // If no original implementation, we should still call the completion handler+ completion(.noData)+ }+ }+}++#endifdiff --git a/src-tauri/vendor/tauri-plugin-notifications/ios/Sources/Notification.swift b/src-tauri/vendor/tauri-plugin-notifications/ios/Sources/Notification.swiftnew file mode 100644index 00000000..f7115cea--- /dev/null+++ b/src-tauri/vendor/tauri-plugin-notifications/ios/Sources/Notification.swift@@ -0,0 +1,235 @@+import Tauri+import UserNotifications++enum NotificationError: LocalizedError {+ case triggerRepeatIntervalTooShort+ case attachmentFileNotFound(path: String)+ case attachmentUnableToCreate(String)+ case pastScheduledTime+ case invalidDate(String)++ var errorDescription: String? {+ switch self {+ case .triggerRepeatIntervalTooShort:+ return "Schedule interval too short, must be a least 1 minute"+ case .attachmentFileNotFound(let path):+ return "Unable to find file \(path) for attachment"+ case .attachmentUnableToCreate(let error):+ return "Failed to create attachment: \(error)"+ case .pastScheduledTime:+ return "Scheduled time must be *after* current time"+ case .invalidDate(let date):+ return "Could not parse date \(date)"+ }+ }+}++func makeNotificationContent(_ notification: Notification) throws -> UNNotificationContent {+ let content = UNMutableNotificationContent()+ content.title = NSString.localizedUserNotificationString(+ forKey: notification.title, arguments: nil)+ if let body = notification.body {+ content.body = NSString.localizedUserNotificationString(+ forKey: body,+ arguments: nil)+ }++ var userInfo: [AnyHashable: Any] = [:]++ // Spread `extra` directly into userInfo at the top level — matches the+ // APNs convention so the click handler can read keys from one shape+ // (whether the notification came from local schedule or remote push).+ if let extra = notification.extra {+ for (key, value) in extra {+ userInfo[key] = value+ }+ }++ content.userInfo = userInfo++ if let actionTypeId = notification.actionTypeId {+ content.categoryIdentifier = actionTypeId+ }++ if let threadIdentifier = notification.group {+ content.threadIdentifier = threadIdentifier+ }++ if let summaryArgument = notification.summary {+ content.summaryArgument = summaryArgument+ }++ if let sound = notification.sound {+ content.sound = UNNotificationSound(named: UNNotificationSoundName(sound))+ }++ if let attachments = notification.attachments {+ content.attachments = try makeAttachments(attachments)+ }++ return content+}++func makeAttachments(_ attachments: [NotificationAttachment]) throws -> [UNNotificationAttachment] {+ var createdAttachments = [UNNotificationAttachment]()++ for attachment in attachments {++ guard let urlObject = makeAttachmentUrl(attachment.url) else {+ throw NotificationError.attachmentFileNotFound(path: attachment.url)+ }++ let options = attachment.options != nil ? makeAttachmentOptions(attachment.options!) : nil++ do {+ let newAttachment = try UNNotificationAttachment(+ identifier: attachment.id, url: urlObject, options: options)+ createdAttachments.append(newAttachment)+ } catch {+ throw NotificationError.attachmentUnableToCreate(error.localizedDescription)+ }+ }++ return createdAttachments+}++func makeAttachmentUrl(_ path: String) -> URL? {+ return URL(string: path)+}++func makeAttachmentOptions(_ options: NotificationAttachmentOptions) -> [AnyHashable: Any] {+ var opts: [AnyHashable: Any] = [:]++ if let value = options.iosUNNotificationAttachmentOptionsTypeHintKey {+ opts[UNNotificationAttachmentOptionsTypeHintKey] = value+ }+ if let value = options.iosUNNotificationAttachmentOptionsThumbnailHiddenKey {+ opts[UNNotificationAttachmentOptionsThumbnailHiddenKey] = value+ }+ if let value = options.iosUNNotificationAttachmentOptionsThumbnailClippingRectKey {+ opts[UNNotificationAttachmentOptionsThumbnailClippingRectKey] = value+ }+ if let value = options+ .iosUNNotificationAttachmentOptionsThumbnailTimeKey++ {+ opts[UNNotificationAttachmentOptionsThumbnailTimeKey] = value+ }+ return opts+}++func handleScheduledNotification(_ schedule: NotificationSchedule) throws+ -> UNNotificationTrigger?+{+ switch schedule {+ case .at(let date, let repeating):+ let dateFormatter = DateFormatter()+ dateFormatter.locale = Locale(identifier: "en_US_POSIX")+ dateFormatter.timeZone = TimeZone(secondsFromGMT: 0)+ dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"++ if let at = dateFormatter.date(from: date) {+ let dateInfo = Calendar.current.dateComponents(in: TimeZone.current, from: at)++ if dateInfo.date! < Date() {+ Logger.debug("Scheduled time is in the past: \(dateInfo.date!) < \(Date())")+ throw NotificationError.pastScheduledTime+ }++ let dateInterval = DateInterval(start: Date(), end: dateInfo.date!)++ // Notifications that repeat have to be at least a minute between each other+ if repeating && dateInterval.duration < 60 {+ throw NotificationError.triggerRepeatIntervalTooShort+ }++ return UNTimeIntervalNotificationTrigger(+ timeInterval: dateInterval.duration, repeats: repeating)++ } else {+ throw NotificationError.invalidDate(date)+ }+ case .interval(let interval):+ let dateComponents = getDateComponents(interval)+ return UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true)+ case .every(let interval, let count):+ if let repeatDateInterval = getRepeatDateInterval(interval, count) {+ // Notifications that repeat have to be at least a minute between each other+ if repeatDateInterval.duration < 60 {+ throw NotificationError.triggerRepeatIntervalTooShort+ }++ return UNTimeIntervalNotificationTrigger(+ timeInterval: repeatDateInterval.duration, repeats: true)+ }+ }++ return nil+}++/// Given our schedule format, return a DateComponents object+/// that only contains the components passed in.++func getDateComponents(_ at: ScheduleInterval) -> DateComponents {+ // var dateInfo = Calendar.current.dateComponents(in: TimeZone.current, from: Date())+ // dateInfo.calendar = Calendar.current+ var dateInfo = DateComponents()++ if let year = at.year {+ dateInfo.year = year+ }+ if let month = at.month {+ dateInfo.month = month+ }+ if let day = at.day {+ dateInfo.day = day+ }+ if let hour = at.hour {+ dateInfo.hour = hour+ }+ if let minute = at.minute {+ dateInfo.minute = minute+ }+ if let second = at.second {+ dateInfo.second = second+ }+ if let weekday = at.weekday {+ dateInfo.weekday = weekday+ }+ return dateInfo+}++/// Compute the difference between the string representation of a date+/// interval and today. For example, if every is "month", then we+/// return the interval between today and a month from today.++func getRepeatDateInterval(_ every: ScheduleEveryKind, _ count: Int) -> DateInterval? {+ let cal = Calendar.current+ let now = Date()+ switch every {+ case .year:+ let newDate = cal.date(byAdding: .year, value: count, to: now)!+ return DateInterval(start: now, end: newDate)+ case .month:+ let newDate = cal.date(byAdding: .month, value: count, to: now)!+ return DateInterval(start: now, end: newDate)+ case .twoWeeks:+ let newDate = cal.date(byAdding: .weekOfYear, value: 2 * count, to: now)!+ return DateInterval(start: now, end: newDate)+ case .week:+ let newDate = cal.date(byAdding: .weekOfYear, value: count, to: now)!+ return DateInterval(start: now, end: newDate)+ case .day:+ let newDate = cal.date(byAdding: .day, value: count, to: now)!+ return DateInterval(start: now, end: newDate)+ case .hour:+ let newDate = cal.date(byAdding: .hour, value: count, to: now)!+ return DateInterval(start: now, end: newDate)+ case .minute:+ let newDate = cal.date(byAdding: .minute, value: count, to: now)!+ return DateInterval(start: now, end: newDate)+ case .second:+ let newDate = cal.date(byAdding: .second, value: count, to: now)!+ return DateInterval(start: now, end: newDate)+ }+}diff --git a/src-tauri/vendor/tauri-plugin-notifications/ios/Sources/NotificationCategory.swift b/src-tauri/vendor/tauri-plugin-notifications/ios/Sources/NotificationCategory.swiftnew file mode 100644index 00000000..7b970035--- /dev/null+++ b/src-tauri/vendor/tauri-plugin-notifications/ios/Sources/NotificationCategory.swift@@ -0,0 +1,93 @@+import Tauri+import UserNotifications++internal func makeCategories(_ actionTypes: [ActionType]) {+ var createdCategories = [UNNotificationCategory]()++ let generalCategory = UNNotificationCategory(+ identifier: "GENERAL",+ actions: [],+ intentIdentifiers: [],+ options: .customDismissAction)++ createdCategories.append(generalCategory)+ for type in actionTypes {+ let newActions = makeActions(type.actions)++ // Create the custom actions for the TIMER_EXPIRED category.+ var newCategory: UNNotificationCategory?++ newCategory = UNNotificationCategory(+ identifier: type.id,+ actions: newActions,+ intentIdentifiers: [],+ hiddenPreviewsBodyPlaceholder: type.hiddenBodyPlaceholder ?? "",+ options: makeCategoryOptions(type))++ createdCategories.append(newCategory!)+ }++ let center = UNUserNotificationCenter.current()+ center.setNotificationCategories(Set(createdCategories))+}++func makeActions(_ actions: [Action]) -> [UNNotificationAction] {+ var createdActions = [UNNotificationAction]()++ for action in actions {+ var newAction: UNNotificationAction+ if action.input ?? false {+ if action.inputButtonTitle != nil {+ newAction = UNTextInputNotificationAction(+ identifier: action.id,+ title: action.title,+ options: makeActionOptions(action),+ textInputButtonTitle: action.inputButtonTitle ?? "",+ textInputPlaceholder: action.inputPlaceholder ?? "")+ } else {+ newAction = UNTextInputNotificationAction(+ identifier: action.id, title: action.title, options: makeActionOptions(action))+ }+ } else {+ // Create the custom actions for the TIMER_EXPIRED category.+ newAction = UNNotificationAction(+ identifier: action.id,+ title: action.title,+ options: makeActionOptions(action))+ }+ createdActions.append(newAction)+ }++ return createdActions+}++func makeActionOptions(_ action: Action) -> UNNotificationActionOptions {+ if action.foreground ?? false {+ return .foreground+ }+ if action.destructive ?? false {+ return .destructive+ }+ if action.requiresAuthentication ?? false {+ return .authenticationRequired+ }+ return UNNotificationActionOptions(rawValue: 0)+}++func makeCategoryOptions(_ type: ActionType) -> UNNotificationCategoryOptions {+ if type.customDismissAction ?? false {+ return .customDismissAction+ }+ if type.allowInCarPlay ?? false {+ return .allowInCarPlay+ }++ if type.hiddenPreviewsShowTitle ?? false {+ return .hiddenPreviewsShowTitle+ }+ if type.hiddenPreviewsShowSubtitle ?? false {+ return .hiddenPreviewsShowSubtitle+ }++ return UNNotificationCategoryOptions(rawValue: 0)+}diff --git a/src-tauri/vendor/tauri-plugin-notifications/ios/Sources/NotificationHandler.swift b/src-tauri/vendor/tauri-plugin-notifications/ios/Sources/NotificationHandler.swiftnew file mode 100644index 00000000..020e1478--- /dev/null+++ b/src-tauri/vendor/tauri-plugin-notifications/ios/Sources/NotificationHandler.swift@@ -0,0 +1,216 @@+import Tauri+import UserNotifications++public class NotificationHandler: NSObject, NotificationHandlerProtocol {++ public weak var plugin: Plugin?++ private var notificationsMap = [String: Notification]()+ private var hasClickedListener = false+ private var pendingNotificationClick: NotificationClickedData? = nil++ internal func saveNotification(_ key: String, _ notification: Notification) {+ notificationsMap.updateValue(notification, forKey: key)+ }++ func setClickListenerActive(_ active: Bool) {+ hasClickedListener = active++ if active, let pending = pendingNotificationClick {+ pendingNotificationClick = nil+ try? self.plugin?.trigger("notificationClicked", data: pending)+ }+ }++ public func requestPermissions(with completion: ((Bool, Error?) -> Void)? = nil) {+ let center = UNUserNotificationCenter.current()+ center.requestAuthorization(options: [.badge, .alert, .sound]) { (granted, error) in+ completion?(granted, error)+ }+ }++ public func checkPermissions(with completion: ((UNAuthorizationStatus) -> Void)? = nil) {+ let center = UNUserNotificationCenter.current()+ center.getNotificationSettings { settings in+ completion?(settings.authorizationStatus)+ }+ }++ public func willPresent(notification: UNNotification) -> UNNotificationPresentationOptions {+ // Trigger notification event for both local and push notifications+ if var notificationData = toActiveNotification(notification.request) {+ notificationData.source = "local"+ try? self.plugin?.trigger("notification", data: notificationData)+ } else {+ var notificationData = toReceivedNotification(notification.request)+ notificationData.source = "push"+ try? self.plugin?.trigger("notification", data: notificationData)+ }++ // For push notifications in foreground, don't show system notification+ // (only trigger event so developer can handle it)+ let isPushNotification = notification.request.trigger?.isKind(of: UNPushNotificationTrigger.self) == true+ if isPushNotification {+ return UNNotificationPresentationOptions.init(rawValue: 0)+ }++ // For local notifications, check if silent+ if let options = notificationsMap[notification.request.identifier] {+ if options.silent ?? false {+ return UNNotificationPresentationOptions.init(rawValue: 0)+ }+ }++ return [+ .badge,+ .sound,+ .alert,+ ]+ }++ /// Convert notification request to ReceivedNotification (for push notifications not in map)+ private func toReceivedNotification(_ request: UNNotificationRequest) -> ReceivedNotificationData {+ let content = request.content+ var extra: [String: String]? = nil++ if !content.userInfo.isEmpty {+ extra = [:]+ for (key, value) in content.userInfo {+ if let keyStr = key as? String, let valStr = value as? String {+ extra?[keyStr] = valStr+ }+ }+ if extra?.isEmpty == true {+ extra = nil+ }+ }++ return ReceivedNotificationData(+ id: Int(request.identifier) ?? -1,+ title: content.title,+ body: content.body,+ extra: extra+ )+ }++ public func didReceive(response: UNNotificationResponse) {+ let originalNotificationRequest = response.notification.request+ let actionId = response.actionIdentifier++ var actionIdValue: String+ // We turn the two default actions (open/dismiss) into generic strings+ if actionId == UNNotificationDefaultActionIdentifier {+ actionIdValue = "tap"+ } else if actionId == UNNotificationDismissActionIdentifier {+ actionIdValue = "dismiss"+ } else {+ actionIdValue = actionId+ }++ var inputValue: String? = nil+ // If the type of action was for an input type, get the value+ if let inputType = response as? UNTextInputNotificationResponse {+ inputValue = inputType.userText+ }++ // Only trigger actionPerformed for local notifications (those in our map)+ if let activeNotification = toActiveNotification(originalNotificationRequest) {+ try? self.plugin?.trigger(+ "actionPerformed",+ data: ReceivedNotification(+ actionId: actionIdValue,+ inputValue: inputValue,+ notification: activeNotification+ ))+ }++ // Handle notificationClicked for both local and push notifications+ let id = Int(originalNotificationRequest.identifier) ?? -1+ let userInfo = originalNotificationRequest.content.userInfo+ var dataDict: [String: String]? = nil+ if !userInfo.isEmpty {+ dataDict = [:]+ for (key, value) in userInfo {+ if let keyStr = key as? String, let valStr = value as? String {+ dataDict?[keyStr] = valStr+ }+ }+ if dataDict?.isEmpty == true {+ dataDict = nil+ }+ }++ let clickedData = NotificationClickedData(id: id, data: dataDict)++ if hasClickedListener {+ // Listener exists, trigger directly+ try? self.plugin?.trigger("notificationClicked", data: clickedData)+ } else {+ // No listener (cold-start), store for later+ pendingNotificationClick = clickedData+ }+ }++ func toActiveNotification(_ request: UNNotificationRequest) -> ActiveNotification? {+ guard let notificationRequest = notificationsMap[request.identifier] else {+ return nil+ }+ return ActiveNotification(+ id: Int(request.identifier) ?? -1,+ title: request.content.title,+ body: request.content.body,+ sound: notificationRequest.sound ?? "",+ actionTypeId: request.content.categoryIdentifier,+ attachments: notificationRequest.attachments+ )+ }++ func toPendingNotification(_ request: UNNotificationRequest) -> PendingNotification? {+ guard let notification = notificationsMap[request.identifier],+ let schedule = notification.schedule else {+ return nil+ }+ return PendingNotification(+ id: Int(request.identifier) ?? -1,+ title: request.content.title,+ body: request.content.body,+ schedule: schedule+ )+ }+}++struct PendingNotification: Encodable {+ let id: Int+ let title: String+ let body: String+ let schedule: NotificationSchedule+}++struct ActiveNotification: Encodable {+ let id: Int+ let title: String+ let body: String+ let sound: String+ let actionTypeId: String+ let attachments: [NotificationAttachment]?+ var source: String = "local"+}++struct ReceivedNotification: Encodable {+ let actionId: String+ let inputValue: String?+ let notification: ActiveNotification+}++struct NotificationClickedData: Encodable {+ let id: Int+ let data: [String: String]?+}++struct ReceivedNotificationData: Encodable {+ let id: Int+ let title: String+ let body: String+ let extra: [String: String]?+ var source: String = "push"+}diff --git a/src-tauri/vendor/tauri-plugin-notifications/ios/Sources/NotificationManager.swift b/src-tauri/vendor/tauri-plugin-notifications/ios/Sources/NotificationManager.swiftnew file mode 100644index 00000000..002649ae--- /dev/null+++ b/src-tauri/vendor/tauri-plugin-notifications/ios/Sources/NotificationManager.swift@@ -0,0 +1,37 @@+import Foundation+import UserNotifications++@objc public protocol NotificationHandlerProtocol {+ func willPresent(notification: UNNotification) -> UNNotificationPresentationOptions+ func didReceive(response: UNNotificationResponse)+}++@objc public class NotificationManager: NSObject, UNUserNotificationCenterDelegate {+ public weak var notificationHandler: NotificationHandlerProtocol?++ override init() {+ super.init()+ let center = UNUserNotificationCenter.current()+ center.delegate = self+ }++ public func userNotificationCenter(+ _ center: UNUserNotificationCenter,+ willPresent notification: UNNotification,+ withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void+ ) {+ // Call willPresent for both local and push notifications+ let presentationOptions = notificationHandler?.willPresent(notification: notification)+ completionHandler(presentationOptions ?? [])+ }++ public func userNotificationCenter(+ _ center: UNUserNotificationCenter,+ didReceive response: UNNotificationResponse,+ withCompletionHandler completionHandler: @escaping () -> Void+ ) {+ notificationHandler?.didReceive(response: response)++ completionHandler()+ }+}diff --git a/src-tauri/vendor/tauri-plugin-notifications/ios/Sources/NotificationPlugin.swift b/src-tauri/vendor/tauri-plugin-notifications/ios/Sources/NotificationPlugin.swiftnew file mode 100644index 00000000..224eaf41--- /dev/null+++ b/src-tauri/vendor/tauri-plugin-notifications/ios/Sources/NotificationPlugin.swift@@ -0,0 +1,398 @@+import SwiftRs+import Tauri+import UIKit+import UserNotifications+import WebKit++enum ShowNotificationError: LocalizedError {+ case make(Error)+ case create(Error)++ var errorDescription: String? {+ switch self {+ case .make(let error):+ return "Unable to make notification: \(error)"+ case .create(let error):+ return "Unable to create notification: \(error)"+ }+ }+}++enum ScheduleEveryKind: String, Codable {+ case year+ case month+ case twoWeeks+ case week+ case day+ case hour+ case minute+ case second+}++struct ScheduleInterval: Codable {+ var year: Int?+ var month: Int?+ var day: Int?+ var weekday: Int?+ var hour: Int?+ var minute: Int?+ var second: Int?+}++enum NotificationSchedule: Codable {+ case at(date: String, repeating: Bool)+ case interval(interval: ScheduleInterval)+ case every(interval: ScheduleEveryKind, count: Int)+}++struct NotificationAttachmentOptions: Codable {+ let iosUNNotificationAttachmentOptionsTypeHintKey: String?+ let iosUNNotificationAttachmentOptionsThumbnailHiddenKey: String?+ let iosUNNotificationAttachmentOptionsThumbnailClippingRectKey: String?+ let iosUNNotificationAttachmentOptionsThumbnailTimeKey: String?+}++struct NotificationAttachment: Codable {+ let id: String+ let url: String+ let options: NotificationAttachmentOptions?+}++struct Notification: Decodable {+ let id: Int+ var title: String+ var body: String?+ var extra: [String: String]?+ var schedule: NotificationSchedule?+ var attachments: [NotificationAttachment]?+ var sound: String?+ var group: String?+ var actionTypeId: String?+ var summary: String?+ var silent: Bool?+}++struct RemoveActiveNotification: Decodable {+ let id: Int+}++struct RemoveActiveArgs: Decodable {+ let notifications: [RemoveActiveNotification]+}++func showNotification(invoke: Invoke, notification: Notification)+ throws -> UNNotificationRequest+{+ var content: UNNotificationContent+ do {+ content = try makeNotificationContent(notification)+ } catch {+ throw ShowNotificationError.make(error)+ }++ var trigger: UNNotificationTrigger?++ do {+ if let schedule = notification.schedule {+ try trigger = handleScheduledNotification(schedule)+ }+ } catch {+ throw ShowNotificationError.create(error)+ }++ // Schedule the request.+ let request = UNNotificationRequest(+ identifier: "\(notification.id)", content: content, trigger: trigger+ )++ let center = UNUserNotificationCenter.current()+ center.add(request) { (error: Error?) in+ if let theError = error {+ invoke.reject(theError.localizedDescription)+ }+ }++ return request+}++struct CancelArgs: Decodable {+ let notifications: [Int]+}++struct Action: Decodable {+ let id: String+ let title: String+ var requiresAuthentication: Bool?+ var foreground: Bool?+ var destructive: Bool?+ var input: Bool?+ var inputButtonTitle: String?+ var inputPlaceholder: String?+}++struct ActionType: Decodable {+ let id: String+ let actions: [Action]+ var hiddenPreviewsBodyPlaceholder: String?+ var customDismissAction: Bool?+ var allowInCarPlay: Bool?+ var hiddenPreviewsShowTitle: Bool?+ var hiddenPreviewsShowSubtitle: Bool?+ var hiddenBodyPlaceholder: String?+}++struct RegisterActionTypesArgs: Decodable {+ let types: [ActionType]+}++struct BatchArgs: Decodable {+ let notifications: [Notification]+}++struct SetClickListenerActiveArgs: Decodable {+ let active: Bool+}++class NotificationPlugin: Plugin {+ let notificationHandler = NotificationHandler()+ let notificationManager = NotificationManager()++ #if ENABLE_PUSH_NOTIFICATIONS+ // Completion handler for push token registration+ private var pushTokenCompletion: ((Result<String, Error>) -> Void)?+ private let pushTokenTimeout: TimeInterval = 10.0+ private var pushTokenTimer: Timer?+ #endif++ override init() {+ super.init()+ notificationManager.notificationHandler = notificationHandler+ notificationHandler.plugin = self+ }++ public override func load(webview: WKWebView) {+ super.load(webview: webview)++ #if ENABLE_PUSH_NOTIFICATIONS+ // Store reference to this plugin for event triggering+ AppDelegateSwizzler.plugin = self++ // swizzle UIApplicationDelegate push methods+ AppDelegateSwizzler.swizzlePushCallbacks()+ #endif+ }++ @objc public func show(_ invoke: Invoke) throws {+ let notification = try invoke.parseArgs(Notification.self)++ let request = try showNotification(invoke: invoke, notification: notification)+ notificationHandler.saveNotification(request.identifier, notification)+ invoke.resolve(Int(request.identifier) ?? -1)+ }++ @objc public func batch(_ invoke: Invoke) throws {+ let args = try invoke.parseArgs(BatchArgs.self)+ var ids = [Int]()++ for notification in args.notifications {+ let request = try showNotification(invoke: invoke, notification: notification)+ notificationHandler.saveNotification(request.identifier, notification)+ ids.append(Int(request.identifier) ?? -1)+ }++ invoke.resolve(ids)+ }++ @objc public override func requestPermissions(_ invoke: Invoke) {+ notificationHandler.requestPermissions { granted, error in+ guard error == nil else {+ invoke.reject(error!.localizedDescription)+ return+ }++ let permissionState = granted ? "granted" : "denied"+ invoke.resolve(["permissionState": permissionState])+ }+ }++ @objc public func registerForPushNotifications(_ invoke: Invoke) {+ #if ENABLE_PUSH_NOTIFICATIONS+ // First request notification permissions+ notificationHandler.requestPermissions { [weak self] granted, error in+ guard error == nil else {+ invoke.reject(error!.localizedDescription)+ return+ }++ self?.registerForPushNotifications { result in+ switch result {+ case .success(let token):+ invoke.resolve(["deviceToken": token])+ case .failure(let error):+ invoke.reject(error.localizedDescription)+ }+ }+ }+ #else+ invoke.reject("Push notifications are disabled in this build")+ #endif+ }++ @objc public func unregisterForPushNotifications(_ invoke: Invoke) {+ #if ENABLE_PUSH_NOTIFICATIONS+ DispatchQueue.main.async {+ UIApplication.shared.unregisterForRemoteNotifications()+ invoke.resolve()+ }+ #else+ invoke.reject("Push notifications are disabled in this build")+ #endif+ }++ #if ENABLE_PUSH_NOTIFICATIONS+ private func registerForPushNotifications(completion: @escaping (Result<String, Error>) -> Void)+ {+ // Store completion for later+ self.pushTokenCompletion = completion++ // Set up timeout+ self.pushTokenTimer?.invalidate()+ self.pushTokenTimer = Timer.scheduledTimer(withTimeInterval: pushTokenTimeout, repeats: false)+ { [weak self] _ in+ self?.handlePushTokenTimeout()+ }++ // Register for remote notifications+ DispatchQueue.main.async {+ UIApplication.shared.registerForRemoteNotifications()+ }+ }++ private func handlePushTokenTimeout() {+ pushTokenTimer?.invalidate()+ pushTokenTimer = nil++ if let completion = pushTokenCompletion {+ pushTokenCompletion = nil+ let error = NSError(+ domain: "NotificationPlugin",+ code: -1,+ userInfo: [NSLocalizedDescriptionKey: "Timeout waiting for device token"]+ )+ completion(.failure(error))+ }+ }++ // Called by AppDelegateSwizzler when token is received+ func handlePushTokenReceived(_ token: String) {+ pushTokenTimer?.invalidate()+ pushTokenTimer = nil++ if let completion = pushTokenCompletion {+ pushTokenCompletion = nil+ completion(.success(token))+ }+ }++ // Called by AppDelegateSwizzler when registration fails+ func handlePushTokenError(_ error: Error) {+ pushTokenTimer?.invalidate()+ pushTokenTimer = nil++ if let completion = pushTokenCompletion {+ pushTokenCompletion = nil+ completion(.failure(error))+ }+ }+ #endif++ @objc public override func checkPermissions(_ invoke: Invoke) {+ notificationHandler.checkPermissions { status in+ let permission: String++ switch status {+ case .authorized, .ephemeral, .provisional:+ permission = "granted"+ case .denied:+ permission = "denied"+ case .notDetermined:+ permission = "prompt"+ @unknown default:+ permission = "prompt"+ }++ invoke.resolve(["permissionState": permission])+ }+ }++ @objc func cancel(_ invoke: Invoke) throws {+ let args = try invoke.parseArgs(CancelArgs.self)++ UNUserNotificationCenter.current().removePendingNotificationRequests(+ withIdentifiers: args.notifications.map { String($0) }+ )+ invoke.resolve()+ }++ @objc func cancelAll(_ invoke: Invoke) {+ UNUserNotificationCenter.current().removeAllPendingNotificationRequests()+ invoke.resolve()+ }++ @objc func getPending(_ invoke: Invoke) {+ UNUserNotificationCenter.current().getPendingNotificationRequests(completionHandler: {+ (notifications) in+ let ret = notifications.compactMap({ [weak self] (notification) -> PendingNotification? in+ return self?.notificationHandler.toPendingNotification(notification)+ })++ invoke.resolve(ret)+ })+ }++ @objc func registerActionTypes(_ invoke: Invoke) throws {+ let args = try invoke.parseArgs(RegisterActionTypesArgs.self)+ makeCategories(args.types)+ invoke.resolve()+ }++ @objc func removeActive(_ invoke: Invoke) {+ let args = try? invoke.parseArgs(RemoveActiveArgs.self)+ if let args, !args.notifications.isEmpty {+ UNUserNotificationCenter.current().removeDeliveredNotifications(+ withIdentifiers: args.notifications.map { String($0.id) })+ } else {+ UNUserNotificationCenter.current().removeAllDeliveredNotifications()+ DispatchQueue.main.async(execute: {+ UIApplication.shared.applicationIconBadgeNumber = 0+ })+ }+ invoke.resolve()+ }++ @objc func getActive(_ invoke: Invoke) {+ UNUserNotificationCenter.current().getDeliveredNotifications(completionHandler: {+ (notifications) in+ let ret = notifications.compactMap({ (notification) -> ActiveNotification? in+ return self.notificationHandler.toActiveNotification(+ notification.request)+ })+ invoke.resolve(ret)+ })+ }++ @objc func setClickListenerActive(_ invoke: Invoke) {+ do {+ let args = try invoke.parseArgs(SetClickListenerActiveArgs.self)+ notificationHandler.setClickListenerActive(args.active)+ invoke.resolve()+ } catch {+ invoke.reject(error.localizedDescription)+ }+ }+}++@_cdecl("init_plugin_notification")+func initPlugin() -> Plugin {+ return NotificationPlugin()+}diff --git a/src-tauri/vendor/tauri-plugin-notifications/ios/Tests/PluginTests/PluginTests.swift b/src-tauri/vendor/tauri-plugin-notifications/ios/Tests/PluginTests/PluginTests.swiftnew file mode 100644index 00000000..be368cb1--- /dev/null+++ b/src-tauri/vendor/tauri-plugin-notifications/ios/Tests/PluginTests/PluginTests.swift@@ -0,0 +1,1187 @@+import XCTest+import UserNotifications+@testable import tauri_plugin_notifications++final class NotificationTests: XCTestCase {++ // MARK: - Notification Content Tests++ func testMakeNotificationContentWithBasicNotification() throws {+ let notification = Notification(+ id: 1,+ title: "Test Title",+ body: "Test Body",+ extra: nil,+ schedule: nil,+ attachments: nil,+ sound: nil,+ group: nil,+ actionTypeId: nil,+ summary: nil,+ silent: nil+ )++ let content = try makeNotificationContent(notification)++ XCTAssertEqual(content.title, "Test Title")+ XCTAssertEqual(content.body, "Test Body")+ XCTAssertTrue(content.userInfo.isEmpty)+ }++ func testMakeNotificationContentWithExtra() throws {+ let notification = Notification(+ id: 1,+ title: "Test",+ body: "Body",+ extra: ["key1": "value1", "key2": "value2"],+ schedule: nil,+ attachments: nil,+ sound: nil,+ group: nil,+ actionTypeId: nil,+ summary: nil,+ silent: nil+ )++ let content = try makeNotificationContent(notification)++ XCTAssertEqual(content.userInfo["key1"] as? String, "value1")+ XCTAssertEqual(content.userInfo["key2"] as? String, "value2")+ }++ func testMakeNotificationContentWithActionTypeId() throws {+ let notification = Notification(+ id: 1,+ title: "Test",+ body: nil,+ extra: nil,+ schedule: nil,+ attachments: nil,+ sound: nil,+ group: nil,+ actionTypeId: "TEST_CATEGORY",+ summary: nil,+ silent: nil+ )++ let content = try makeNotificationContent(notification)++ XCTAssertEqual(content.categoryIdentifier, "TEST_CATEGORY")+ }++ func testMakeNotificationContentWithThreadIdentifier() throws {+ let notification = Notification(+ id: 1,+ title: "Test",+ body: nil,+ extra: nil,+ schedule: nil,+ attachments: nil,+ sound: nil,+ group: "test-group",+ actionTypeId: nil,+ summary: nil,+ silent: nil+ )++ let content = try makeNotificationContent(notification)++ XCTAssertEqual(content.threadIdentifier, "test-group")+ }++ func testMakeNotificationContentWithSummary() throws {+ let notification = Notification(+ id: 1,+ title: "Test",+ body: nil,+ extra: nil,+ schedule: nil,+ attachments: nil,+ sound: nil,+ group: nil,+ actionTypeId: nil,+ summary: "Test Summary",+ silent: nil+ )++ let content = try makeNotificationContent(notification)++ XCTAssertEqual(content.summaryArgument, "Test Summary")+ }++ func testMakeNotificationContentWithSound() throws {+ let notification = Notification(+ id: 1,+ title: "Test",+ body: nil,+ extra: nil,+ schedule: nil,+ attachments: nil,+ sound: "custom_sound.wav",+ group: nil,+ actionTypeId: nil,+ summary: nil,+ silent: nil+ )++ let content = try makeNotificationContent(notification)++ XCTAssertNotNil(content.sound)+ }++ // MARK: - Attachment Tests++ func testMakeAttachmentUrl() {+ let url = makeAttachmentUrl("https://example.com/image.jpg")+ XCTAssertNotNil(url)+ XCTAssertEqual(url?.absoluteString, "https://example.com/image.jpg")+ }++ func testMakeAttachmentUrlWithInvalidPath() {+ let url = makeAttachmentUrl("")+ XCTAssertNil(url)+ }++ func testMakeAttachmentOptions() {+ let options = NotificationAttachmentOptions(+ iosUNNotificationAttachmentOptionsTypeHintKey: "public.jpeg",+ iosUNNotificationAttachmentOptionsThumbnailHiddenKey: "true",+ iosUNNotificationAttachmentOptionsThumbnailClippingRectKey: nil,+ iosUNNotificationAttachmentOptionsThumbnailTimeKey: nil+ )++ let result = makeAttachmentOptions(options)++ XCTAssertEqual(result[UNNotificationAttachmentOptionsTypeHintKey] as? String, "public.jpeg")+ XCTAssertEqual(result[UNNotificationAttachmentOptionsThumbnailHiddenKey] as? String, "true")+ }++ // MARK: - Schedule Tests++ func testGetDateComponents() {+ let interval = ScheduleInterval(+ year: 2024,+ month: 12,+ day: 25,+ weekday: nil,+ hour: 10,+ minute: 30,+ second: 0+ )++ let dateComponents = getDateComponents(interval)++ XCTAssertEqual(dateComponents.year, 2024)+ XCTAssertEqual(dateComponents.month, 12)+ XCTAssertEqual(dateComponents.day, 25)+ XCTAssertEqual(dateComponents.hour, 10)+ XCTAssertEqual(dateComponents.minute, 30)+ XCTAssertEqual(dateComponents.second, 0)+ XCTAssertNil(dateComponents.weekday)+ }++ func testGetDateComponentsWithWeekday() {+ let interval = ScheduleInterval(+ year: nil,+ month: nil,+ day: nil,+ weekday: 2,+ hour: 9,+ minute: 0,+ second: nil+ )++ let dateComponents = getDateComponents(interval)++ XCTAssertNil(dateComponents.year)+ XCTAssertNil(dateComponents.month)+ XCTAssertEqual(dateComponents.weekday, 2)+ XCTAssertEqual(dateComponents.hour, 9)+ XCTAssertEqual(dateComponents.minute, 0)+ }++ func testGetRepeatDateIntervalForMinutes() {+ let interval = getRepeatDateInterval(.minute, 5)++ XCTAssertNotNil(interval)+ if let interval = interval {+ XCTAssertEqual(interval.duration, 5 * 60, accuracy: 1.0)+ }+ }++ func testGetRepeatDateIntervalForHours() {+ let interval = getRepeatDateInterval(.hour, 2)++ XCTAssertNotNil(interval)+ if let interval = interval {+ XCTAssertEqual(interval.duration, 2 * 60 * 60, accuracy: 1.0)+ }+ }++ func testGetRepeatDateIntervalForDays() {+ let interval = getRepeatDateInterval(.day, 1)++ XCTAssertNotNil(interval)+ if let interval = interval {+ XCTAssertEqual(interval.duration, 24 * 60 * 60, accuracy: 1.0)+ }+ }++ func testGetRepeatDateIntervalForWeeks() {+ let interval = getRepeatDateInterval(.week, 1)++ XCTAssertNotNil(interval)+ if let interval = interval {+ XCTAssertEqual(interval.duration, 7 * 24 * 60 * 60, accuracy: 1.0)+ }+ }++ func testGetRepeatDateIntervalForTwoWeeks() {+ let interval = getRepeatDateInterval(.twoWeeks, 1)++ XCTAssertNotNil(interval)+ if let interval = interval {+ XCTAssertEqual(interval.duration, 14 * 24 * 60 * 60, accuracy: 1.0)+ }+ }++ func testGetRepeatDateIntervalForMonths() {+ let interval = getRepeatDateInterval(.month, 1)++ XCTAssertNotNil(interval)+ if let interval = interval {+ // Month duration varies, so just check it's approximately 28-31 days+ XCTAssertGreaterThanOrEqual(interval.duration, 28 * 24 * 60 * 60)+ XCTAssertLessThanOrEqual(interval.duration, 31 * 24 * 60 * 60)+ }+ }++ func testHandleScheduledNotificationWithEveryMinute() throws {+ let schedule = NotificationSchedule.every(interval: .minute, count: 2)++ let trigger = try handleScheduledNotification(schedule)++ XCTAssertNotNil(trigger)+ XCTAssertTrue(trigger is UNTimeIntervalNotificationTrigger)++ if let timeTrigger = trigger as? UNTimeIntervalNotificationTrigger {+ XCTAssertTrue(timeTrigger.repeats)+ XCTAssertEqual(timeTrigger.timeInterval, 120, accuracy: 1.0)+ }+ }++ func testHandleScheduledNotificationWithIntervalThrowsForShortInterval() {+ let schedule = NotificationSchedule.every(interval: .second, count: 30)++ XCTAssertThrowsError(try handleScheduledNotification(schedule)) { error in+ XCTAssertTrue(error is NotificationError)+ if case NotificationError.triggerRepeatIntervalTooShort = error {+ // Expected error+ } else {+ XCTFail("Wrong error type")+ }+ }+ }++ func testHandleScheduledNotificationWithInterval() throws {+ let interval = ScheduleInterval(+ year: nil,+ month: nil,+ day: nil,+ weekday: 2,+ hour: 9,+ minute: 0,+ second: 0+ )+ let schedule = NotificationSchedule.interval(interval: interval)++ let trigger = try handleScheduledNotification(schedule)++ XCTAssertNotNil(trigger)+ XCTAssertTrue(trigger is UNCalendarNotificationTrigger)++ if let calendarTrigger = trigger as? UNCalendarNotificationTrigger {+ XCTAssertTrue(calendarTrigger.repeats)+ XCTAssertEqual(calendarTrigger.dateComponents.weekday, 2)+ XCTAssertEqual(calendarTrigger.dateComponents.hour, 9)+ }+ }++ // MARK: - Category and Action Tests++ func testMakeActionOptionsWithForeground() {+ let action = Action(+ id: "test",+ title: "Test",+ requiresAuthentication: nil,+ foreground: true,+ destructive: nil,+ input: nil,+ inputButtonTitle: nil,+ inputPlaceholder: nil+ )++ let options = makeActionOptions(action)++ XCTAssertEqual(options, .foreground)+ }++ func testMakeActionOptionsWithDestructive() {+ let action = Action(+ id: "test",+ title: "Test",+ requiresAuthentication: nil,+ foreground: nil,+ destructive: true,+ input: nil,+ inputButtonTitle: nil,+ inputPlaceholder: nil+ )++ let options = makeActionOptions(action)++ XCTAssertEqual(options, .destructive)+ }++ func testMakeActionOptionsWithAuthRequired() {+ let action = Action(+ id: "test",+ title: "Test",+ requiresAuthentication: true,+ foreground: nil,+ destructive: nil,+ input: nil,+ inputButtonTitle: nil,+ inputPlaceholder: nil+ )++ let options = makeActionOptions(action)++ XCTAssertEqual(options, .authenticationRequired)+ }++ func testMakeCategoryOptionsWithCustomDismiss() {+ let actionType = ActionType(+ id: "test",+ actions: [],+ hiddenPreviewsBodyPlaceholder: nil,+ customDismissAction: true,+ allowInCarPlay: nil,+ hiddenPreviewsShowTitle: nil,+ hiddenPreviewsShowSubtitle: nil,+ hiddenBodyPlaceholder: nil+ )++ let options = makeCategoryOptions(actionType)++ XCTAssertEqual(options, .customDismissAction)+ }++ func testMakeCategoryOptionsWithCarPlay() {+ let actionType = ActionType(+ id: "test",+ actions: [],+ hiddenPreviewsBodyPlaceholder: nil,+ customDismissAction: nil,+ allowInCarPlay: true,+ hiddenPreviewsShowTitle: nil,+ hiddenPreviewsShowSubtitle: nil,+ hiddenBodyPlaceholder: nil+ )++ let options = makeCategoryOptions(actionType)++ XCTAssertEqual(options, .allowInCarPlay)+ }++ func testMakeCategoryOptionsWithHiddenPreviewsShowTitle() {+ let actionType = ActionType(+ id: "test",+ actions: [],+ hiddenPreviewsBodyPlaceholder: nil,+ customDismissAction: nil,+ allowInCarPlay: nil,+ hiddenPreviewsShowTitle: true,+ hiddenPreviewsShowSubtitle: nil,+ hiddenBodyPlaceholder: nil+ )++ let options = makeCategoryOptions(actionType)++ XCTAssertEqual(options, .hiddenPreviewsShowTitle)+ }++ func testMakeActionsCreatesBasicAction() {+ let actions = [+ Action(+ id: "action1",+ title: "Action 1",+ requiresAuthentication: nil,+ foreground: nil,+ destructive: nil,+ input: nil,+ inputButtonTitle: nil,+ inputPlaceholder: nil+ )+ ]++ let result = makeActions(actions)++ XCTAssertEqual(result.count, 1)+ XCTAssertEqual(result[0].identifier, "action1")+ XCTAssertEqual(result[0].title, "Action 1")+ XCTAssertFalse(result[0] is UNTextInputNotificationAction)+ }++ func testMakeActionsCreatesTextInputAction() {+ let actions = [+ Action(+ id: "reply",+ title: "Reply",+ requiresAuthentication: nil,+ foreground: nil,+ destructive: nil,+ input: true,+ inputButtonTitle: "Send",+ inputPlaceholder: "Type your reply..."+ )+ ]++ let result = makeActions(actions)++ XCTAssertEqual(result.count, 1)+ XCTAssertTrue(result[0] is UNTextInputNotificationAction)++ if let textAction = result[0] as? UNTextInputNotificationAction {+ XCTAssertEqual(textAction.identifier, "reply")+ XCTAssertEqual(textAction.title, "Reply")+ XCTAssertEqual(textAction.textInputButtonTitle, "Send")+ XCTAssertEqual(textAction.textInputPlaceholder, "Type your reply...")+ }+ }++ func testMakeActionsCreatesMultipleActions() {+ let actions = [+ Action(id: "action1", title: "Action 1", requiresAuthentication: nil, foreground: nil, destructive: nil, input: nil, inputButtonTitle: nil, inputPlaceholder: nil),+ Action(id: "action2", title: "Action 2", requiresAuthentication: nil, foreground: true, destructive: nil, input: nil, inputButtonTitle: nil, inputPlaceholder: nil),+ Action(id: "action3", title: "Action 3", requiresAuthentication: nil, foreground: nil, destructive: true, input: nil, inputButtonTitle: nil, inputPlaceholder: nil)+ ]++ let result = makeActions(actions)++ XCTAssertEqual(result.count, 3)+ XCTAssertEqual(result[0].identifier, "action1")+ XCTAssertEqual(result[1].identifier, "action2")+ XCTAssertEqual(result[2].identifier, "action3")+ }++ // MARK: - Error Tests++ func testNotificationErrorDescriptions() {+ let error1 = NotificationError.triggerRepeatIntervalTooShort+ XCTAssertEqual(error1.errorDescription, "Schedule interval too short, must be a least 1 minute")++ let error2 = NotificationError.attachmentFileNotFound(path: "/path/to/file")+ XCTAssertEqual(error2.errorDescription, "Unable to find file /path/to/file for attachment")++ let error3 = NotificationError.attachmentUnableToCreate("Test error")+ XCTAssertEqual(error3.errorDescription, "Failed to create attachment: Test error")++ let error4 = NotificationError.pastScheduledTime+ XCTAssertEqual(error4.errorDescription, "Scheduled time must be *after* current time")++ let error5 = NotificationError.invalidDate("2024-13-32")+ XCTAssertEqual(error5.errorDescription, "Could not parse date 2024-13-32")+ }++ // MARK: - Data Structure Tests++ func testPendingNotificationEncoding() throws {+ let schedule = NotificationSchedule.every(interval: .day, count: 1)+ let pending = PendingNotification(id: 1, title: "Test", body: "Body", schedule: schedule)++ let encoder = JSONEncoder()+ let data = try encoder.encode(pending)++ XCTAssertFalse(data.isEmpty)++ // Verify the JSON structure+ let json = try JSONSerialization.jsonObject(with: data) as? [String: Any]+ XCTAssertNotNil(json)+ XCTAssertEqual(json?["id"] as? Int, 1)+ XCTAssertEqual(json?["title"] as? String, "Test")+ XCTAssertEqual(json?["body"] as? String, "Body")+ }++ func testActiveNotificationEncoding() throws {+ let active = ActiveNotification(+ id: 1,+ title: "Test",+ body: "Body",+ sound: "default",+ actionTypeId: "CATEGORY",+ attachments: nil,+ source: "local"+ )++ let encoder = JSONEncoder()+ let data = try encoder.encode(active)++ XCTAssertFalse(data.isEmpty)++ // Verify the JSON structure+ let json = try JSONSerialization.jsonObject(with: data) as? [String: Any]+ XCTAssertNotNil(json)+ XCTAssertEqual(json?["id"] as? Int, 1)+ XCTAssertEqual(json?["title"] as? String, "Test")+ XCTAssertEqual(json?["body"] as? String, "Body")+ XCTAssertEqual(json?["sound"] as? String, "default")+ XCTAssertEqual(json?["actionTypeId"] as? String, "CATEGORY")+ XCTAssertEqual(json?["source"] as? String, "local")+ }++ func testReceivedNotificationEncoding() throws {+ let active = ActiveNotification(+ id: 1,+ title: "Test",+ body: "Body",+ sound: "default",+ actionTypeId: "CATEGORY",+ attachments: nil+ )++ let received = ReceivedNotification(+ actionId: "tap",+ inputValue: nil,+ notification: active+ )++ let encoder = JSONEncoder()+ let data = try encoder.encode(received)++ XCTAssertFalse(data.isEmpty)++ // Verify the JSON structure+ let json = try JSONSerialization.jsonObject(with: data) as? [String: Any]+ XCTAssertNotNil(json)+ XCTAssertEqual(json?["actionId"] as? String, "tap")+ XCTAssertNil(json?["inputValue"])++ let notification = json?["notification"] as? [String: Any]+ XCTAssertNotNil(notification)+ XCTAssertEqual(notification?["id"] as? Int, 1)+ }++ // MARK: - NotificationHandler Tests++ func testNotificationHandlerToPendingNotificationReturnsNilForUnknown() {+ let handler = NotificationHandler()+ let content = UNMutableNotificationContent()+ content.title = "Test Title"+ content.body = "Test Body"++ let request = UNNotificationRequest(+ identifier: "123",+ content: content,+ trigger: nil+ )++ // Should return nil since no notification was saved with this identifier+ let pending = handler.toPendingNotification(request)+ XCTAssertNil(pending)+ }++ func testNotificationHandlerToPendingNotificationWithSavedNotification() {+ let handler = NotificationHandler()+ let schedule = NotificationSchedule.every(interval: .day, count: 1)+ let notification = Notification(+ id: 123,+ title: "Test Title",+ body: "Test Body",+ extra: nil,+ schedule: schedule,+ attachments: nil,+ sound: nil,+ group: nil,+ actionTypeId: nil,+ summary: nil,+ silent: nil+ )++ // Save the notification first+ handler.saveNotification("123", notification)++ let content = UNMutableNotificationContent()+ content.title = "Test Title"+ content.body = "Test Body"++ let request = UNNotificationRequest(+ identifier: "123",+ content: content,+ trigger: nil+ )++ let pending = handler.toPendingNotification(request)++ XCTAssertNotNil(pending)+ XCTAssertEqual(pending?.id, 123)+ XCTAssertEqual(pending?.title, "Test Title")+ XCTAssertEqual(pending?.body, "Test Body")+ }++ // MARK: - makeAttachments Tests++ func testMakeAttachmentsWithInvalidUrl() throws {+ let attachment = NotificationAttachment(+ id: "test-attachment",+ url: "",+ options: nil+ )++ XCTAssertThrowsError(try makeAttachments([attachment])) { error in+ if case NotificationError.attachmentFileNotFound(let path) = error {+ XCTAssertEqual(path, "")+ } else {+ XCTFail("Wrong error type")+ }+ }+ }++ // MARK: - Additional Schedule Tests++ func testHandleScheduledNotificationWithAtDate() throws {+ // Create a date in the future+ let dateFormatter = DateFormatter()+ dateFormatter.locale = Locale(identifier: "en_US_POSIX")+ dateFormatter.timeZone = TimeZone(secondsFromGMT: 0)+ dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"++ let futureDate = Date().addingTimeInterval(3600) // 1 hour from now+ let dateString = dateFormatter.string(from: futureDate)++ let schedule = NotificationSchedule.at(date: dateString, repeating: false)++ let trigger = try handleScheduledNotification(schedule)++ XCTAssertNotNil(trigger)+ XCTAssertTrue(trigger is UNTimeIntervalNotificationTrigger)++ if let timeTrigger = trigger as? UNTimeIntervalNotificationTrigger {+ XCTAssertFalse(timeTrigger.repeats)+ XCTAssertGreaterThan(timeTrigger.timeInterval, 3500)+ XCTAssertLessThan(timeTrigger.timeInterval, 3700)+ }+ }++ func testHandleScheduledNotificationWithPastDateThrows() {+ let dateFormatter = DateFormatter()+ dateFormatter.locale = Locale(identifier: "en_US_POSIX")+ dateFormatter.timeZone = TimeZone(secondsFromGMT: 0)+ dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"++ let pastDate = Date().addingTimeInterval(-3600) // 1 hour ago+ let dateString = dateFormatter.string(from: pastDate)++ let schedule = NotificationSchedule.at(date: dateString, repeating: false)++ XCTAssertThrowsError(try handleScheduledNotification(schedule)) { error in+ if case NotificationError.pastScheduledTime = error {+ // Expected error+ } else {+ XCTFail("Wrong error type")+ }+ }+ }++ func testHandleScheduledNotificationWithInvalidDateThrows() {+ let schedule = NotificationSchedule.at(date: "invalid-date", repeating: false)++ XCTAssertThrowsError(try handleScheduledNotification(schedule)) { error in+ if case NotificationError.invalidDate(let date) = error {+ XCTAssertEqual(date, "invalid-date")+ } else {+ XCTFail("Wrong error type")+ }+ }+ }++ // MARK: - Combined Options Tests++ func testMakeActionOptionsWithMultipleFlags() {+ let action = Action(+ id: "test",+ title: "Test",+ requiresAuthentication: true,+ foreground: true,+ destructive: true,+ input: nil,+ inputButtonTitle: nil,+ inputPlaceholder: nil+ )++ let options = makeActionOptions(action)++ // Should return foreground as it's checked first+ XCTAssertEqual(options, .foreground)+ }++ func testMakeCategoryOptionsWithMultipleFlags() {+ let actionType = ActionType(+ id: "test",+ actions: [],+ hiddenPreviewsBodyPlaceholder: nil,+ customDismissAction: true,+ allowInCarPlay: true,+ hiddenPreviewsShowTitle: true,+ hiddenPreviewsShowSubtitle: true,+ hiddenBodyPlaceholder: nil+ )++ let options = makeCategoryOptions(actionType)++ // Should return customDismissAction as it's checked first+ XCTAssertEqual(options, .customDismissAction)+ }++ // MARK: - Silent Notification Tests++ func testMakeNotificationContentWithSilentFlag() throws {+ let notification = Notification(+ id: 1,+ title: "Test",+ body: "Body",+ extra: nil,+ schedule: nil,+ attachments: nil,+ sound: nil,+ group: nil,+ actionTypeId: nil,+ summary: nil,+ silent: true+ )++ let content = try makeNotificationContent(notification)++ // Silent flag is handled in NotificationHandler.willPresent, not in content+ XCTAssertEqual(content.title, "Test")+ XCTAssertEqual(content.body, "Body")+ }++ // MARK: - Edge Case Tests++ func testMakeNotificationContentWithEmptyBody() throws {+ let notification = Notification(+ id: 1,+ title: "Test Title",+ body: nil,+ extra: nil,+ schedule: nil,+ attachments: nil,+ sound: nil,+ group: nil,+ actionTypeId: nil,+ summary: nil,+ silent: nil+ )++ let content = try makeNotificationContent(notification)++ XCTAssertEqual(content.title, "Test Title")+ XCTAssertEqual(content.body, "")+ }++ func testMakeActionsWithTextInputActionWithoutButtonTitle() {+ let actions = [+ Action(+ id: "reply",+ title: "Reply",+ requiresAuthentication: nil,+ foreground: nil,+ destructive: nil,+ input: true,+ inputButtonTitle: nil,+ inputPlaceholder: "Type here..."+ )+ ]++ let result = makeActions(actions)++ XCTAssertEqual(result.count, 1)+ XCTAssertTrue(result[0] is UNTextInputNotificationAction)++ if let textAction = result[0] as? UNTextInputNotificationAction {+ XCTAssertEqual(textAction.identifier, "reply")+ XCTAssertEqual(textAction.title, "Reply")+ }+ }++ func testGetRepeatDateIntervalForYear() {+ let interval = getRepeatDateInterval(.year, 1)++ XCTAssertNotNil(interval)+ if let interval = interval {+ // Year duration varies, check it's approximately 365 days+ XCTAssertGreaterThan(interval.duration, 364 * 24 * 60 * 60)+ XCTAssertLessThan(interval.duration, 366 * 24 * 60 * 60)+ }+ }++ func testGetRepeatDateIntervalForMultipleUnits() {+ let interval = getRepeatDateInterval(.hour, 3)++ XCTAssertNotNil(interval)+ if let interval = interval {+ XCTAssertEqual(interval.duration, 3 * 60 * 60, accuracy: 1.0)+ }+ }++ func testMakeCategoryOptionsWithHiddenPreviewsShowSubtitle() {+ let actionType = ActionType(+ id: "test",+ actions: [],+ hiddenPreviewsBodyPlaceholder: nil,+ customDismissAction: nil,+ allowInCarPlay: nil,+ hiddenPreviewsShowTitle: nil,+ hiddenPreviewsShowSubtitle: true,+ hiddenBodyPlaceholder: nil+ )++ let options = makeCategoryOptions(actionType)++ XCTAssertEqual(options, .hiddenPreviewsShowSubtitle)+ }++ func testMakeActionOptionsWithNoFlags() {+ let action = Action(+ id: "test",+ title: "Test",+ requiresAuthentication: nil,+ foreground: nil,+ destructive: nil,+ input: nil,+ inputButtonTitle: nil,+ inputPlaceholder: nil+ )++ let options = makeActionOptions(action)++ XCTAssertEqual(options.rawValue, 0)+ }++ func testMakeCategoryOptionsWithNoFlags() {+ let actionType = ActionType(+ id: "test",+ actions: [],+ hiddenPreviewsBodyPlaceholder: nil,+ customDismissAction: nil,+ allowInCarPlay: nil,+ hiddenPreviewsShowTitle: nil,+ hiddenPreviewsShowSubtitle: nil,+ hiddenBodyPlaceholder: nil+ )++ let options = makeCategoryOptions(actionType)++ XCTAssertEqual(options.rawValue, 0)+ }++ // MARK: - NotificationSchedule Decoding Tests++ func testNotificationScheduleDecodingAtDate() throws {+ let json = """+ {+ "at": {+ "date": "2024-12-25T10:30:00.000Z",+ "repeating": false+ }+ }+ """++ let decoder = JSONDecoder()+ let schedule = try decoder.decode(NotificationSchedule.self, from: json.data(using: .utf8)!)++ if case .at(let date, let repeating) = schedule {+ XCTAssertEqual(date, "2024-12-25T10:30:00.000Z")+ XCTAssertFalse(repeating)+ } else {+ XCTFail("Wrong schedule type")+ }+ }++ func testNotificationScheduleDecodingInterval() throws {+ let json = """+ {+ "interval": {+ "interval": {+ "hour": 9,+ "minute": 30+ }+ }+ }+ """++ let decoder = JSONDecoder()+ let schedule = try decoder.decode(NotificationSchedule.self, from: json.data(using: .utf8)!)++ if case .interval(let interval) = schedule {+ XCTAssertEqual(interval.hour, 9)+ XCTAssertEqual(interval.minute, 30)+ } else {+ XCTFail("Wrong schedule type")+ }+ }++ func testNotificationScheduleDecodingEvery() throws {+ let json = """+ {+ "every": {+ "interval": "minute",+ "count": 5+ }+ }+ """++ let decoder = JSONDecoder()+ let schedule = try decoder.decode(NotificationSchedule.self, from: json.data(using: .utf8)!)++ if case .every(let interval, let count) = schedule {+ XCTAssertEqual(interval, .minute)+ XCTAssertEqual(count, 5)+ } else {+ XCTFail("Wrong schedule type")+ }+ }++ // MARK: - Additional Coverage Tests++ func testNotificationDecodingWithAllFields() throws {+ let json = """+ {+ "id": 1,+ "title": "Test Title",+ "body": "Test Body",+ "extra": {"key": "value"},+ "sound": "custom.wav",+ "group": "test-group",+ "actionTypeId": "TEST_CATEGORY",+ "summary": "Summary",+ "silent": true+ }+ """++ let decoder = JSONDecoder()+ let notification = try decoder.decode(Notification.self, from: json.data(using: .utf8)!)++ XCTAssertEqual(notification.id, 1)+ XCTAssertEqual(notification.title, "Test Title")+ XCTAssertEqual(notification.body, "Test Body")+ XCTAssertEqual(notification.extra?["key"], "value")+ XCTAssertEqual(notification.sound, "custom.wav")+ XCTAssertEqual(notification.group, "test-group")+ XCTAssertEqual(notification.actionTypeId, "TEST_CATEGORY")+ XCTAssertEqual(notification.summary, "Summary")+ XCTAssertEqual(notification.silent, true)+ }++ func testActionDecodingWithAllFields() throws {+ let json = """+ {+ "id": "reply",+ "title": "Reply",+ "requiresAuthentication": true,+ "foreground": true,+ "destructive": false,+ "input": true,+ "inputButtonTitle": "Send",+ "inputPlaceholder": "Type here..."+ }+ """++ let decoder = JSONDecoder()+ let action = try decoder.decode(Action.self, from: json.data(using: .utf8)!)++ XCTAssertEqual(action.id, "reply")+ XCTAssertEqual(action.title, "Reply")+ XCTAssertEqual(action.requiresAuthentication, true)+ XCTAssertEqual(action.foreground, true)+ XCTAssertEqual(action.destructive, false)+ XCTAssertEqual(action.input, true)+ XCTAssertEqual(action.inputButtonTitle, "Send")+ XCTAssertEqual(action.inputPlaceholder, "Type here...")+ }++ func testActionTypeDecodingWithAllFields() throws {+ let json = """+ {+ "id": "TEST_CATEGORY",+ "actions": [+ {+ "id": "action1",+ "title": "Action 1"+ }+ ],+ "hiddenPreviewsBodyPlaceholder": "Hidden",+ "customDismissAction": true,+ "allowInCarPlay": true,+ "hiddenPreviewsShowTitle": true,+ "hiddenPreviewsShowSubtitle": true,+ "hiddenBodyPlaceholder": "Body Hidden"+ }+ """++ let decoder = JSONDecoder()+ let actionType = try decoder.decode(ActionType.self, from: json.data(using: .utf8)!)++ XCTAssertEqual(actionType.id, "TEST_CATEGORY")+ XCTAssertEqual(actionType.actions.count, 1)+ XCTAssertEqual(actionType.hiddenPreviewsBodyPlaceholder, "Hidden")+ XCTAssertEqual(actionType.customDismissAction, true)+ XCTAssertEqual(actionType.allowInCarPlay, true)+ XCTAssertEqual(actionType.hiddenPreviewsShowTitle, true)+ XCTAssertEqual(actionType.hiddenPreviewsShowSubtitle, true)+ XCTAssertEqual(actionType.hiddenBodyPlaceholder, "Body Hidden")+ }++ func testScheduleEveryKindDecoding() throws {+ let kinds = ["year", "month", "twoWeeks", "week", "day", "hour", "minute", "second"]+ let expected: [ScheduleEveryKind] = [.year, .month, .twoWeeks, .week, .day, .hour, .minute, .second]++ for (index, kind) in kinds.enumerated() {+ let json = "\"\(kind)\""+ let decoder = JSONDecoder()+ let decoded = try decoder.decode(ScheduleEveryKind.self, from: json.data(using: .utf8)!)+ XCTAssertEqual(decoded, expected[index])+ }+ }++ func testNotificationAttachmentDecoding() throws {+ let json = """+ {+ "id": "attachment1",+ "url": "https://example.com/image.jpg",+ "options": {+ "iosUNNotificationAttachmentOptionsTypeHintKey": "public.jpeg",+ "iosUNNotificationAttachmentOptionsThumbnailHiddenKey": "true"+ }+ }+ """++ let decoder = JSONDecoder()+ let attachment = try decoder.decode(NotificationAttachment.self, from: json.data(using: .utf8)!)++ XCTAssertEqual(attachment.id, "attachment1")+ XCTAssertEqual(attachment.url, "https://example.com/image.jpg")+ XCTAssertEqual(attachment.options?.iosUNNotificationAttachmentOptionsTypeHintKey, "public.jpeg")+ XCTAssertEqual(attachment.options?.iosUNNotificationAttachmentOptionsThumbnailHiddenKey, "true")+ }++ // MARK: - Push Notification Foreground Path Serialization Tests++ /// Tests encoding of ReceivedNotificationData — the struct used in the foreground push+ /// notification path (NotificationHandler.willPresent → toReceivedNotification).+ /// This reproduces the exact serialization that Channel.send<T: Encodable>() performs.+ func testReceivedNotificationDataEncoding() throws {+ let data = ReceivedNotificationData(+ id: 42,+ title: "Push Title",+ body: "Push Body",+ extra: ["key": "value", "another": "data"],+ source: "push"+ )++ let encoder = JSONEncoder()+ let jsonData = try encoder.encode(data)++ let json = try JSONSerialization.jsonObject(with: jsonData) as? [String: Any]+ XCTAssertNotNil(json)+ XCTAssertEqual(json?["id"] as? Int, 42)+ XCTAssertEqual(json?["title"] as? String, "Push Title")+ XCTAssertEqual(json?["body"] as? String, "Push Body")+ XCTAssertEqual(json?["source"] as? String, "push")++ let extra = json?["extra"] as? [String: String]+ XCTAssertNotNil(extra)+ XCTAssertEqual(extra?["key"], "value")+ XCTAssertEqual(extra?["another"], "data")+ }++ func testReceivedNotificationDataEncodingWithNilExtra() throws {+ let data = ReceivedNotificationData(+ id: 1,+ title: "Title",+ body: "Body",+ extra: nil,+ source: "push"+ )++ let encoder = JSONEncoder()+ let jsonData = try encoder.encode(data)++ let json = try JSONSerialization.jsonObject(with: jsonData) as? [String: Any]+ XCTAssertNotNil(json)+ XCTAssertEqual(json?["id"] as? Int, 1)+ XCTAssertEqual(json?["source"] as? String, "push")+ // extra should be absent or null+ XCTAssertTrue(json?["extra"] == nil || json?["extra"] is NSNull)+ }++ /// Tests encoding of NotificationClickedData — used for notification click events.+ func testNotificationClickedDataEncoding() throws {+ let data = NotificationClickedData(+ id: 7,+ data: ["action": "open", "screen": "home"]+ )++ let encoder = JSONEncoder()+ let jsonData = try encoder.encode(data)++ let json = try JSONSerialization.jsonObject(with: jsonData) as? [String: Any]+ XCTAssertNotNil(json)+ XCTAssertEqual(json?["id"] as? Int, 7)++ let clickData = json?["data"] as? [String: String]+ XCTAssertNotNil(clickData)+ XCTAssertEqual(clickData?["action"], "open")+ XCTAssertEqual(clickData?["screen"], "home")+ }++ func testNotificationClickedDataEncodingWithNilData() throws {+ let data = NotificationClickedData(+ id: -1,+ data: nil+ )++ let encoder = JSONEncoder()+ let jsonData = try encoder.encode(data)++ let json = try JSONSerialization.jsonObject(with: jsonData) as? [String: Any]+ XCTAssertNotNil(json)+ XCTAssertEqual(json?["id"] as? Int, -1)+ XCTAssertTrue(json?["data"] == nil || json?["data"] is NSNull)+ }++ func testMakeNotificationContentWithAttachmentsError() throws {+ let notification = Notification(+ id: 1,+ title: "Test",+ body: "Body",+ extra: nil,+ schedule: nil,+ attachments: [+ NotificationAttachment(+ id: "test",+ url: "",+ options: nil+ )+ ],+ sound: nil,+ group: nil,+ actionTypeId: nil,+ summary: nil,+ silent: nil+ )++ XCTAssertThrowsError(try makeNotificationContent(notification))+ }+}diff --git a/src-tauri/vendor/tauri-plugin-notifications/macos/.gitignore b/src-tauri/vendor/tauri-plugin-notifications/macos/.gitignorenew file mode 100644index 00000000..e786f25f--- /dev/null+++ b/src-tauri/vendor/tauri-plugin-notifications/macos/.gitignore@@ -0,0 +1,14 @@+.DS_Store+/.build+/.swiftpm+/Packages+/*.xcodeproj+/*.xcresult+xcuserdata/+DerivedData/+.swiftpm/config/registries.json+.swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata+.netrc+Package.resolved+generated/+.push-notifications-enableddiff --git a/src-tauri/vendor/tauri-plugin-notifications/macos/Package.swift b/src-tauri/vendor/tauri-plugin-notifications/macos/Package.swiftnew file mode 100644index 00000000..a861c687--- /dev/null+++ b/src-tauri/vendor/tauri-plugin-notifications/macos/Package.swift@@ -0,0 +1,55 @@+// swift-tools-version:5.7+// The swift-tools-version declares the minimum version of Swift required to build this package.++import PackageDescription+import Foundation++// Check if push notifications feature is enabled via marker file from Rust build+let enablePushNotifications = FileManager.default.fileExists(+ atPath: URL(fileURLWithPath: #file).deletingLastPathComponent()+ .appendingPathComponent(".push-notifications-enabled").path+)++var swiftSettings: [SwiftSetting] = [+ .unsafeFlags([+ "-import-objc-header", "\(Context.packageDirectory)/Sources/bridging-header.h",+ "-disable-bridging-pch"+ ])+]+if enablePushNotifications {+ swiftSettings.append(.define("ENABLE_PUSH_NOTIFICATIONS"))+}++let package = Package(+ name: "tauri-plugin-notifications",+ platforms: [+ .macOS(.v13),+ .iOS(.v15),+ ],+ products: [+ // Products define the executables and libraries a package produces, and make them visible to other packages.+ .library(+ name: "tauri-plugin-notifications",+ type: .static,+ targets: ["tauri-plugin-notifications"]),+ ],+ dependencies: [ ],+ targets: [+ // Targets are the basic building blocks of a package. A target can define a module or a test suite.+ // Targets can depend on other targets in this package, and on products in packages this package depends on.+ .target(+ name: "tauri-plugin-notifications",+ dependencies: [ ],+ path: "Sources",+ swiftSettings: swiftSettings,+ linkerSettings: [+ .linkedFramework("UserNotifications")+ ]+ ),+ .testTarget(+ name: "PluginTests",+ dependencies: ["tauri-plugin-notifications"],+ swiftSettings: swiftSettings+ ),+ ]+)diff --git a/src-tauri/vendor/tauri-plugin-notifications/macos/README.md b/src-tauri/vendor/tauri-plugin-notifications/macos/README.mdnew file mode 100644index 00000000..1cf8c044--- /dev/null+++ b/src-tauri/vendor/tauri-plugin-notifications/macos/README.md@@ -0,0 +1,3 @@+# Tauri Plugin notifications++A description of this package.diff --git a/src-tauri/vendor/tauri-plugin-notifications/macos/Sources/AppDelegateSwizzler.swift b/src-tauri/vendor/tauri-plugin-notifications/macos/Sources/AppDelegateSwizzler.swiftnew file mode 100644index 00000000..b6d02f51--- /dev/null+++ b/src-tauri/vendor/tauri-plugin-notifications/macos/Sources/AppDelegateSwizzler.swift@@ -0,0 +1,91 @@+import AppKit+import ObjectiveC.runtime++#if ENABLE_PUSH_NOTIFICATIONS++enum AppDelegateSwizzler {+ static weak var plugin: NotificationPlugin?++ static func swizzlePushCallbacks() {+ guard let delegate = NSApplication.shared.delegate else { return }++ // didRegisterForRemoteNotificationsWithDeviceToken+ swizzle(+ type(of: delegate),+ #selector(NSApplicationDelegate.application(_:didRegisterForRemoteNotificationsWithDeviceToken:)),+ #selector(PushForwarder.ta_application(_:didRegisterForRemoteNotificationsWithDeviceToken:))+ )++ // didFailToRegisterForRemoteNotificationsWithError+ swizzle(+ type(of: delegate),+ #selector(NSApplicationDelegate.application(_:didFailToRegisterForRemoteNotificationsWithError:)),+ #selector(PushForwarder.ta_application(_:didFailToRegisterForRemoteNotificationsWithError:))+ )++ // didReceiveRemoteNotification+ swizzle(+ type(of: delegate),+ #selector(NSApplicationDelegate.application(_:didReceiveRemoteNotification:)),+ #selector(PushForwarder.ta_application(_:didReceiveRemoteNotification:))+ )+ }++ private static func swizzle(_ cls: AnyClass, _ original: Selector, _ replacement: Selector) {+ guard+ let swizzledMethod = class_getInstanceMethod(PushForwarder.self, replacement)+ else { return }++ if let originalMethod = class_getInstanceMethod(cls, original) {+ method_exchangeImplementations(originalMethod, swizzledMethod)+ } else {+ class_addMethod(+ cls,+ original,+ method_getImplementation(swizzledMethod),+ method_getTypeEncoding(swizzledMethod)+ )+ }+ }+}++// Extension to hold swizzled implementations (silences "nearly matches" warnings)+final class PushForwarder: NSObject {+ @objc func ta_application(_ application: NSApplication,+ didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {+ let hex = deviceToken.map { String(format: "%02x", $0) }.joined()++ AppDelegateSwizzler.plugin?.handlePushTokenReceived(hex)+ try? AppDelegateSwizzler.plugin?.trigger("push-token", data: ["token": hex])++ if responds(to: #selector(ta_application(_:didRegisterForRemoteNotificationsWithDeviceToken:))) {+ self.ta_application(application, didRegisterForRemoteNotificationsWithDeviceToken: deviceToken)+ }+ }++ @objc func ta_application(_ application: NSApplication,+ didFailToRegisterForRemoteNotificationsWithError error: Error) {+ AppDelegateSwizzler.plugin?.handlePushTokenError(error)+ try? AppDelegateSwizzler.plugin?.trigger("push-error", data: ["message": error.localizedDescription])++ if responds(to: #selector(ta_application(_:didFailToRegisterForRemoteNotificationsWithError:))) {+ self.ta_application(application, didFailToRegisterForRemoteNotificationsWithError: error)+ }+ }++ @objc func ta_application(_ application: NSApplication,+ didReceiveRemoteNotification userInfo: [String: Any]) {+ // Convert to [String: String] for Encodable+ var stringDict: [String: String] = [:]+ for (key, value) in userInfo {+ stringDict[key] = String(describing: value)+ }+ try? AppDelegateSwizzler.plugin?.trigger("push-message", data: stringDict)++ if responds(to: #selector(ta_application(_:didReceiveRemoteNotification:))) {+ self.ta_application(application, didReceiveRemoteNotification: userInfo)+ }+ }+}++#endifdiff --git a/src-tauri/vendor/tauri-plugin-notifications/macos/Sources/Notification.swift b/src-tauri/vendor/tauri-plugin-notifications/macos/Sources/Notification.swiftnew file mode 100644index 00000000..125595f1--- /dev/null+++ b/src-tauri/vendor/tauri-plugin-notifications/macos/Sources/Notification.swift@@ -0,0 +1,235 @@+import UserNotifications++enum NotificationError: LocalizedError {+ case triggerRepeatIntervalTooShort+ case attachmentFileNotFound(path: String)+ case attachmentUnableToCreate(String)+ case pastScheduledTime+ case invalidDate(String)++ var errorDescription: String? {+ switch self {+ case .triggerRepeatIntervalTooShort:+ return "Schedule interval too short, must be a least 1 minute"+ case .attachmentFileNotFound(let path):+ return "Unable to find file \(path) for attachment"+ case .attachmentUnableToCreate(let error):+ return "Failed to create attachment: \(error)"+ case .pastScheduledTime:+ return "Scheduled time must be *after* current time"+ case .invalidDate(let date):+ return "Could not parse date \(date)"+ }+ }+}++func makeNotificationContent(_ notification: Notification) throws -> UNNotificationContent {+ let content = UNMutableNotificationContent()+ content.title = NSString.localizedUserNotificationString(+ forKey: notification.title, arguments: nil)+ if let body = notification.body {+ content.body = NSString.localizedUserNotificationString(+ forKey: body,+ arguments: nil)+ }++ var userInfo: [AnyHashable: Any] = [:]++ // Spread `extra` directly into userInfo at the top level — matches the+ // APNs convention so the click handler can read keys from one shape+ // (whether the notification came from local schedule or remote push).+ if let extra = notification.extra {+ for (key, value) in extra {+ userInfo[key] = value+ }+ }++ content.userInfo = userInfo++ if let actionTypeId = notification.actionTypeId {+ content.categoryIdentifier = actionTypeId+ }++ if let threadIdentifier = notification.group {+ content.threadIdentifier = threadIdentifier+ }++ if let summaryArgument = notification.summary {+ content.summaryArgument = summaryArgument+ }++ if let sound = notification.sound {+ content.sound = UNNotificationSound(named: UNNotificationSoundName(sound))+ }++ if let attachments = notification.attachments {+ content.attachments = try makeAttachments(attachments)+ }++ return content+}++func makeAttachments(_ attachments: [NotificationAttachment]) throws -> [UNNotificationAttachment] {+ var createdAttachments = [UNNotificationAttachment]()++ for attachment in attachments {++ guard let urlObject = makeAttachmentUrl(attachment.url) else {+ throw NotificationError.attachmentFileNotFound(path: attachment.url)+ }++ let options = attachment.options != nil ? makeAttachmentOptions(attachment.options!) : nil++ do {+ let newAttachment = try UNNotificationAttachment(+ identifier: attachment.id, url: urlObject, options: options)+ createdAttachments.append(newAttachment)+ } catch {+ throw NotificationError.attachmentUnableToCreate(error.localizedDescription)+ }+ }++ return createdAttachments+}++func makeAttachmentUrl(_ path: String) -> URL? {+ return URL(string: path)+}++func makeAttachmentOptions(_ options: NotificationAttachmentOptions) -> [AnyHashable: Any] {+ var opts: [AnyHashable: Any] = [:]++ if let value = options.iosUNNotificationAttachmentOptionsTypeHintKey {+ opts[UNNotificationAttachmentOptionsTypeHintKey] = value+ }+ if let value = options.iosUNNotificationAttachmentOptionsThumbnailHiddenKey {+ opts[UNNotificationAttachmentOptionsThumbnailHiddenKey] = value+ }+ if let value = options.iosUNNotificationAttachmentOptionsThumbnailClippingRectKey {+ opts[UNNotificationAttachmentOptionsThumbnailClippingRectKey] = value+ }+ if let value = options+ .iosUNNotificationAttachmentOptionsThumbnailTimeKey++ {+ opts[UNNotificationAttachmentOptionsThumbnailTimeKey] = value+ }+ return opts+}++func handleScheduledNotification(_ schedule: NotificationSchedule) throws+ -> UNNotificationTrigger?+{+ switch schedule {+ case .at(let date, let repeating):+ let dateFormatter = DateFormatter()+ dateFormatter.locale = Locale(identifier: "en_US_POSIX")+ dateFormatter.timeZone = TimeZone(secondsFromGMT: 0)+ dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"++ if let at = dateFormatter.date(from: date) {+ let dateInfo = Calendar.current.dateComponents(in: TimeZone.current, from: at)++ if dateInfo.date! < Date() {+ // TODO:+ //Logger.debug("Scheduled time is in the past: \(dateInfo.date!) < \(Date())")+ throw NotificationError.pastScheduledTime+ }++ let dateInterval = DateInterval(start: Date(), end: dateInfo.date!)++ // Notifications that repeat have to be at least a minute between each other+ if repeating && dateInterval.duration < 60 {+ throw NotificationError.triggerRepeatIntervalTooShort+ }++ return UNTimeIntervalNotificationTrigger(+ timeInterval: dateInterval.duration, repeats: repeating)++ } else {+ throw NotificationError.invalidDate(date)+ }+ case .interval(let interval):+ let dateComponents = getDateComponents(interval)+ return UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true)+ case .every(let interval, let count):+ if let repeatDateInterval = getRepeatDateInterval(interval, count) {+ // Notifications that repeat have to be at least a minute between each other+ if repeatDateInterval.duration < 60 {+ throw NotificationError.triggerRepeatIntervalTooShort+ }++ return UNTimeIntervalNotificationTrigger(+ timeInterval: repeatDateInterval.duration, repeats: true)+ }+ }++ return nil+}++/// Given our schedule format, return a DateComponents object+/// that only contains the components passed in.++func getDateComponents(_ at: ScheduleInterval) -> DateComponents {+ // var dateInfo = Calendar.current.dateComponents(in: TimeZone.current, from: Date())+ // dateInfo.calendar = Calendar.current+ var dateInfo = DateComponents()++ if let year = at.year {+ dateInfo.year = year+ }+ if let month = at.month {+ dateInfo.month = month+ }+ if let day = at.day {+ dateInfo.day = day+ }+ if let hour = at.hour {+ dateInfo.hour = hour+ }+ if let minute = at.minute {+ dateInfo.minute = minute+ }+ if let second = at.second {+ dateInfo.second = second+ }+ if let weekday = at.weekday {+ dateInfo.weekday = weekday+ }+ return dateInfo+}++/// Compute the difference between the string representation of a date+/// interval and today. For example, if every is "month", then we+/// return the interval between today and a month from today.++func getRepeatDateInterval(_ every: ScheduleEveryKind, _ count: Int) -> DateInterval? {+ let cal = Calendar.current+ let now = Date()+ switch every {+ case .year:+ let newDate = cal.date(byAdding: .year, value: count, to: now)!+ return DateInterval(start: now, end: newDate)+ case .month:+ let newDate = cal.date(byAdding: .month, value: count, to: now)!+ return DateInterval(start: now, end: newDate)+ case .twoWeeks:+ let newDate = cal.date(byAdding: .weekOfYear, value: 2 * count, to: now)!+ return DateInterval(start: now, end: newDate)+ case .week:+ let newDate = cal.date(byAdding: .weekOfYear, value: count, to: now)!+ return DateInterval(start: now, end: newDate)+ case .day:+ let newDate = cal.date(byAdding: .day, value: count, to: now)!+ return DateInterval(start: now, end: newDate)+ case .hour:+ let newDate = cal.date(byAdding: .hour, value: count, to: now)!+ return DateInterval(start: now, end: newDate)+ case .minute:+ let newDate = cal.date(byAdding: .minute, value: count, to: now)!+ return DateInterval(start: now, end: newDate)+ case .second:+ let newDate = cal.date(byAdding: .second, value: count, to: now)!+ return DateInterval(start: now, end: newDate)+ }+}diff --git a/src-tauri/vendor/tauri-plugin-notifications/macos/Sources/NotificationCategory.swift b/src-tauri/vendor/tauri-plugin-notifications/macos/Sources/NotificationCategory.swiftnew file mode 100644index 00000000..ea763922--- /dev/null+++ b/src-tauri/vendor/tauri-plugin-notifications/macos/Sources/NotificationCategory.swift@@ -0,0 +1,88 @@+import UserNotifications++internal func makeCategories(_ actionTypes: [ActionType]) {+ var createdCategories = [UNNotificationCategory]()++ let generalCategory = UNNotificationCategory(+ identifier: "GENERAL",+ actions: [],+ intentIdentifiers: [],+ options: .customDismissAction)++ createdCategories.append(generalCategory)+ for type in actionTypes {+ let newActions = makeActions(type.actions)++ // Create the custom actions for the TIMER_EXPIRED category.+ var newCategory: UNNotificationCategory?++ newCategory = UNNotificationCategory(+ identifier: type.id,+ actions: newActions,+ intentIdentifiers: [],+ hiddenPreviewsBodyPlaceholder: type.hiddenBodyPlaceholder ?? "",+ options: makeCategoryOptions(type))++ createdCategories.append(newCategory!)+ }++ let center = UNUserNotificationCenter.current()+ center.setNotificationCategories(Set(createdCategories))+}++func makeActions(_ actions: [Action]) -> [UNNotificationAction] {+ var createdActions = [UNNotificationAction]()++ for action in actions {+ var newAction: UNNotificationAction+ if action.input ?? false {+ if action.inputButtonTitle != nil {+ newAction = UNTextInputNotificationAction(+ identifier: action.id,+ title: action.title,+ options: makeActionOptions(action),+ textInputButtonTitle: action.inputButtonTitle ?? "",+ textInputPlaceholder: action.inputPlaceholder ?? "")+ } else {+ newAction = UNTextInputNotificationAction(+ identifier: action.id, title: action.title, options: makeActionOptions(action))+ }+ } else {+ // Create the custom actions for the TIMER_EXPIRED category.+ newAction = UNNotificationAction(+ identifier: action.id,+ title: action.title,+ options: makeActionOptions(action))+ }+ createdActions.append(newAction)+ }++ return createdActions+}++func makeActionOptions(_ action: Action) -> UNNotificationActionOptions {+ if action.foreground ?? false {+ return .foreground+ }+ if action.destructive ?? false {+ return .destructive+ }+ if action.requiresAuthentication ?? false {+ return .authenticationRequired+ }+ return UNNotificationActionOptions(rawValue: 0)+}++func makeCategoryOptions(_ type: ActionType) -> UNNotificationCategoryOptions {+ if type.customDismissAction ?? false {+ return .customDismissAction+ }+ if type.hiddenPreviewsShowTitle ?? false {+ return .hiddenPreviewsShowTitle+ }+ if type.hiddenPreviewsShowSubtitle ?? false {+ return .hiddenPreviewsShowSubtitle+ }++ return UNNotificationCategoryOptions(rawValue: 0)+}diff --git a/src-tauri/vendor/tauri-plugin-notifications/macos/Sources/NotificationHandler.swift b/src-tauri/vendor/tauri-plugin-notifications/macos/Sources/NotificationHandler.swiftnew file mode 100644index 00000000..e8a005b6--- /dev/null+++ b/src-tauri/vendor/tauri-plugin-notifications/macos/Sources/NotificationHandler.swift@@ -0,0 +1,210 @@+import UserNotifications++public class NotificationHandler: NSObject, NotificationHandlerProtocol {++ weak var plugin: NotificationPlugin?++ private var notificationsMap = [String: Notification]()+ private var hasClickedListener = false+ private var pendingNotificationClick: NotificationClickedData? = nil++ internal func saveNotification(_ key: String, _ notification: Notification) {+ notificationsMap.updateValue(notification, forKey: key)+ }++ func setClickListenerActive(_ active: Bool) {+ hasClickedListener = active++ if active, let pending = pendingNotificationClick {+ pendingNotificationClick = nil+ try? self.plugin?.trigger("notificationClicked", data: pending)+ }+ }++ public func requestPermissions() async throws -> Bool {+ let center = UNUserNotificationCenter.current()+ return try await center.requestAuthorization(options: [.badge, .alert, .sound])+ }++ public func checkPermissions() async -> UNNotificationSettings {+ let center = UNUserNotificationCenter.current()+ return await center.notificationSettings()+ }++ public func willPresent(notification: UNNotification) -> UNNotificationPresentationOptions {+ // Trigger notification event for both local and push notifications+ if var notificationData = toActiveNotification(notification.request) {+ notificationData.source = "local"+ try? self.plugin?.trigger("notification", data: notificationData)+ } else {+ var notificationData = toReceivedNotification(notification.request)+ notificationData.source = "push"+ try? self.plugin?.trigger("notification", data: notificationData)+ }++ // For push notifications in foreground, don't show system notification+ // (only trigger event so developer can handle it)+ let isPushNotification = notification.request.trigger?.isKind(of: UNPushNotificationTrigger.self) == true+ if isPushNotification {+ return UNNotificationPresentationOptions.init(rawValue: 0)+ }++ // For local notifications, check if silent+ if let options: Notification = notificationsMap[notification.request.identifier] {+ if options.silent ?? false {+ return UNNotificationPresentationOptions.init(rawValue: 0)+ }+ }++ return [+ .badge,+ .sound,+ .alert,+ ]+ }++ /// Convert notification request to ReceivedNotification (for push notifications not in map)+ private func toReceivedNotification(_ request: UNNotificationRequest) -> ReceivedNotificationData {+ let content = request.content+ var extra: [String: String]? = nil++ if !content.userInfo.isEmpty {+ extra = [:]+ for (key, value) in content.userInfo {+ if let keyStr = key as? String, let valStr = value as? String {+ extra?[keyStr] = valStr+ }+ }+ if extra?.isEmpty == true {+ extra = nil+ }+ }++ return ReceivedNotificationData(+ id: Int(request.identifier) ?? -1,+ title: content.title,+ body: content.body,+ extra: extra+ )+ }++ public func didReceive(response: UNNotificationResponse) {+ let originalNotificationRequest = response.notification.request+ let actionId = response.actionIdentifier++ var actionIdValue: String+ // We turn the two default actions (open/dismiss) into generic strings+ if actionId == UNNotificationDefaultActionIdentifier {+ actionIdValue = "tap"+ } else if actionId == UNNotificationDismissActionIdentifier {+ actionIdValue = "dismiss"+ } else {+ actionIdValue = actionId+ }++ var inputValue: String? = nil+ // If the type of action was for an input type, get the value+ if let inputType = response as? UNTextInputNotificationResponse {+ inputValue = inputType.userText+ }++ // Only trigger actionPerformed for local notifications (those in our map)+ if let activeNotification = toActiveNotification(originalNotificationRequest) {+ try? self.plugin?.trigger(+ "actionPerformed",+ data: ReceivedNotification(+ actionId: actionIdValue,+ inputValue: inputValue,+ notification: activeNotification+ ))+ }++ // Handle notificationClicked for both local and push notifications+ let id = Int(originalNotificationRequest.identifier) ?? -1+ let userInfo = originalNotificationRequest.content.userInfo+ var dataDict: [String: String]? = nil+ if !userInfo.isEmpty {+ dataDict = [:]+ for (key, value) in userInfo {+ if let keyStr = key as? String, let valStr = value as? String {+ dataDict?[keyStr] = valStr+ }+ }+ if dataDict?.isEmpty == true {+ dataDict = nil+ }+ }++ let clickedData = NotificationClickedData(id: id, data: dataDict)++ if hasClickedListener {+ // Listener exists, trigger directly+ try? self.plugin?.trigger("notificationClicked", data: clickedData)+ } else {+ // No listener (cold-start), store for later+ pendingNotificationClick = clickedData+ }+ }++ func toActiveNotification(_ request: UNNotificationRequest) -> ActiveNotification? {+ guard let notificationRequest = notificationsMap[request.identifier] else {+ return nil+ }+ return ActiveNotification(+ id: Int(request.identifier) ?? -1,+ title: request.content.title,+ body: request.content.body,+ sound: notificationRequest.sound ?? "",+ actionTypeId: request.content.categoryIdentifier,+ attachments: notificationRequest.attachments+ )+ }++ func toPendingNotification(_ request: UNNotificationRequest) -> PendingNotification? {+ guard let notification = notificationsMap[request.identifier] else {+ return nil+ }+ return PendingNotification(+ id: Int(request.identifier) ?? -1,+ title: request.content.title,+ body: request.content.body,+ schedule: notification.schedule!+ )+ }+}++struct PendingNotification: Encodable {+ let id: Int+ let title: String+ let body: String+ let schedule: NotificationSchedule+}++struct ActiveNotification: Encodable {+ let id: Int+ let title: String+ let body: String+ let sound: String+ let actionTypeId: String+ let attachments: [NotificationAttachment]?+ var source: String = "local"+}++struct ReceivedNotification: Encodable {+ let actionId: String+ let inputValue: String?+ let notification: ActiveNotification+}++struct NotificationClickedData: Encodable {+ let id: Int+ let data: [String: String]?+}++struct ReceivedNotificationData: Encodable {+ let id: Int+ let title: String+ let body: String+ let extra: [String: String]?+ var source: String = "push"+}diff --git a/src-tauri/vendor/tauri-plugin-notifications/macos/Sources/NotificationManager.swift b/src-tauri/vendor/tauri-plugin-notifications/macos/Sources/NotificationManager.swiftnew file mode 100644index 00000000..002649ae--- /dev/null+++ b/src-tauri/vendor/tauri-plugin-notifications/macos/Sources/NotificationManager.swift@@ -0,0 +1,37 @@+import Foundation+import UserNotifications++@objc public protocol NotificationHandlerProtocol {+ func willPresent(notification: UNNotification) -> UNNotificationPresentationOptions+ func didReceive(response: UNNotificationResponse)+}++@objc public class NotificationManager: NSObject, UNUserNotificationCenterDelegate {+ public weak var notificationHandler: NotificationHandlerProtocol?++ override init() {+ super.init()+ let center = UNUserNotificationCenter.current()+ center.delegate = self+ }++ public func userNotificationCenter(+ _ center: UNUserNotificationCenter,+ willPresent notification: UNNotification,+ withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void+ ) {+ // Call willPresent for both local and push notifications+ let presentationOptions = notificationHandler?.willPresent(notification: notification)+ completionHandler(presentationOptions ?? [])+ }++ public func userNotificationCenter(+ _ center: UNUserNotificationCenter,+ didReceive response: UNNotificationResponse,+ withCompletionHandler completionHandler: @escaping () -> Void+ ) {+ notificationHandler?.didReceive(response: response)++ completionHandler()+ }+}diff --git a/src-tauri/vendor/tauri-plugin-notifications/macos/Sources/NotificationPlugin.swift b/src-tauri/vendor/tauri-plugin-notifications/macos/Sources/NotificationPlugin.swiftnew file mode 100644index 00000000..c387bf25--- /dev/null+++ b/src-tauri/vendor/tauri-plugin-notifications/macos/Sources/NotificationPlugin.swift@@ -0,0 +1,396 @@+import AppKit+import UserNotifications++extension FFIResult: Error {}++typealias JsonObject = [String: Any]++enum ScheduleEveryKind: String, Codable {+ case year+ case month+ case twoWeeks+ case week+ case day+ case hour+ case minute+ case second+}++struct ScheduleInterval: Codable {+ var year: Int?+ var month: Int?+ var day: Int?+ var weekday: Int?+ var hour: Int?+ var minute: Int?+ var second: Int?+}++enum NotificationSchedule: Codable {+ case at(date: String, repeating: Bool)+ case interval(interval: ScheduleInterval)+ case every(interval: ScheduleEveryKind, count: Int)+}++struct NotificationAttachmentOptions: Codable {+ let iosUNNotificationAttachmentOptionsTypeHintKey: String?+ let iosUNNotificationAttachmentOptionsThumbnailHiddenKey: String?+ let iosUNNotificationAttachmentOptionsThumbnailClippingRectKey: String?+ let iosUNNotificationAttachmentOptionsThumbnailTimeKey: String?+}++struct NotificationAttachment: Codable {+ let id: String+ let url: String+ let options: NotificationAttachmentOptions?+}++struct Notification: Decodable {+ let id: Int+ var title: String+ var body: String?+ var extra: [String: String]?+ var schedule: NotificationSchedule?+ var attachments: [NotificationAttachment]?+ var sound: String?+ var group: String?+ var actionTypeId: String?+ var summary: String?+ var silent: Bool?+}++struct CancelArgs: Decodable {+ let notifications: [Int]+}++struct Action: Decodable {+ let id: String+ let title: String+ var requiresAuthentication: Bool?+ var foreground: Bool?+ var destructive: Bool?+ var input: Bool?+ var inputButtonTitle: String?+ var inputPlaceholder: String?+}++struct ActionType: Decodable {+ let id: String+ let actions: [Action]+ var hiddenPreviewsBodyPlaceholder: String?+ var customDismissAction: Bool?+ var allowInCarPlay: Bool?+ var hiddenPreviewsShowTitle: Bool?+ var hiddenPreviewsShowSubtitle: Bool?+ var hiddenBodyPlaceholder: String?+}++struct RegisterActionTypesArgs: Decodable {+ let types: [ActionType]+}++struct SetClickListenerActiveArgs: Decodable {+ let active: Bool+}++struct RemoveActiveNotification: Decodable {+ let id: Int+}++struct RemoveActiveArgs: Decodable {+ let notifications: [RemoveActiveNotification]+}++extension RustString {+ func decode<T: Decodable>(_ type: T.Type) throws(FFIResult) -> T {+ guard let data = self.toString().data(using: .utf8) else {+ throw FFIResult.Err(RustString("Invalid UTF-8 string"))+ }+ do {+ return try JSONDecoder().decode(type, from: data)+ } catch {+ throw FFIResult.Err(RustString("Failed to decode JSON: \(error.localizedDescription)"))+ }+ }+}++extension Encodable {+ func toJSONString() throws(FFIResult) -> String {+ do {+ let jsonData = try JSONEncoder().encode(self)+ guard let jsonString = String(data: jsonData, encoding: .utf8) else {+ throw FFIResult.Err(RustString("Failed to encode to JSON string"))+ }+ return jsonString+ } catch let error as FFIResult {+ throw error+ } catch {+ throw FFIResult.Err(RustString("Failed to encode to JSON: \(error.localizedDescription)"))+ }+ }+}++func showNotification(notification: Notification) async throws(FFIResult) -> UNNotificationRequest {+ var content: UNNotificationContent+ do {+ content = try makeNotificationContent(notification)+ } catch {+ throw FFIResult.Err(RustString(error.localizedDescription))+ }++ var trigger: UNNotificationTrigger?++ do {+ if let schedule = notification.schedule {+ try trigger = handleScheduledNotification(schedule)+ }+ } catch {+ throw FFIResult.Err(RustString(error.localizedDescription))+ }++ // Schedule the request.+ let request = UNNotificationRequest(+ identifier: "\(notification.id)", content: content, trigger: trigger+ )++ let center = UNUserNotificationCenter.current()+ do {+ try await center.add(request)+ } catch {+ throw FFIResult.Err(RustString(error.localizedDescription))+ }++ return request+}++class NotificationPlugin {+ let notificationHandler = NotificationHandler()+ let notificationManager = NotificationManager()++ #if ENABLE_PUSH_NOTIFICATIONS+ // Completion handler for push token registration+ private var pushTokenCompletion: ((Result<String, Error>) -> Void)?+ private let pushTokenTimeout: TimeInterval = 10.0+ private var pushTokenTimer: Timer?+ #endif++ init() {+ #if ENABLE_PUSH_NOTIFICATIONS+ // Store reference to this plugin for event triggering+ AppDelegateSwizzler.plugin = self++ // swizzle UIApplicationDelegate push methods+ AppDelegateSwizzler.swizzlePushCallbacks()+ #endif++ notificationHandler.plugin = self+ notificationManager.notificationHandler = notificationHandler+ }++ public func show(args: RustString) async throws(FFIResult) -> Int32 {+ let notification = try args.decode(Notification.self)++ let request = try await showNotification(notification: notification)+ notificationHandler.saveNotification(request.identifier, notification)+ return Int32(request.identifier) ?? -1+ }++ public func requestPermissions() async throws(FFIResult) -> String {+ do {+ let granted = try await notificationHandler.requestPermissions()+ let permissionState = granted ? "granted" : "denied"+ return "{\"permissionState\":\"\(permissionState)\"}"+ } catch {+ throw FFIResult.Err(RustString(error.localizedDescription))+ }+ }++ public func registerForPushNotifications() async throws(FFIResult) -> String {+ #if ENABLE_PUSH_NOTIFICATIONS+ // First request notification permissions+ let granted: Bool+ do {+ granted = try await notificationHandler.requestPermissions()+ } catch {+ throw FFIResult.Err(RustString("Failed to request notification permissions: \(error.localizedDescription)"))+ }++ guard granted else {+ throw FFIResult.Err(RustString("Notification permissions not granted"))+ }++ // Register and wait for token+ do {+ let token = try await withCheckedThrowingContinuation { continuation in+ self.registerForPushNotificationsWithCompletion { result in+ continuation.resume(with: result)+ }+ }+ return "{\"deviceToken\":\"\(token)\"}"+ } catch {+ throw FFIResult.Err(RustString(error.localizedDescription))+ }+ #else+ throw FFIResult.Err(RustString("Push notifications are disabled in this build"))+ #endif+ }++ public func unregisterForPushNotifications() throws(FFIResult) {+ #if ENABLE_PUSH_NOTIFICATIONS+ DispatchQueue.main.async {+ NSApplication.shared.unregisterForRemoteNotifications()+ }+ #else+ throw FFIResult.Err(RustString("Push notifications are disabled in this build"))+ #endif+ }++ public func checkPermissions() async throws(FFIResult) -> String {+ let settings = await notificationHandler.checkPermissions()+ let permission: String++ switch settings.authorizationStatus {+ case .authorized, .ephemeral, .provisional:+ permission = "granted"+ case .denied:+ permission = "denied"+ case .notDetermined:+ permission = "prompt"+ @unknown default:+ permission = "prompt"+ }++ return "{\"permissionState\":\"\(permission)\"}"+ }++ public func cancel(args: RustString) throws(FFIResult) {+ let args = try args.decode(CancelArgs.self)++ UNUserNotificationCenter.current().removePendingNotificationRequests(+ withIdentifiers: args.notifications.map { String($0) }+ )+ }++ public func cancelAll() throws(FFIResult) {+ UNUserNotificationCenter.current().removeAllPendingNotificationRequests()+ }++ public func getPending() async throws(FFIResult) -> String {+ let notifications = await UNUserNotificationCenter.current().pendingNotificationRequests()++ let ret = notifications.compactMap({ [weak self] (notification) -> PendingNotification? in+ return self?.notificationHandler.toPendingNotification(notification)+ })++ return try ret.toJSONString()+ }++ public func registerActionTypes(args: RustString) throws(FFIResult) {+ let args = try args.decode(RegisterActionTypesArgs.self)+ makeCategories(args.types)+ }++ public func removeActive(args: RustString) throws(FFIResult) {+ let args = try args.decode(RemoveActiveArgs.self)+ if args.notifications.isEmpty {+ try removeAllActive()+ } else {+ UNUserNotificationCenter.current().removeDeliveredNotifications(+ withIdentifiers: args.notifications.map { String($0.id) })+ }+ }++ public func removeAllActive() throws(FFIResult) {+ UNUserNotificationCenter.current().removeAllDeliveredNotifications()+ DispatchQueue.main.async {+ NSApp.dockTile.badgeLabel = nil+ }+ }++ public func getActive() async throws(FFIResult) -> String {+ let notifications = await UNUserNotificationCenter.current().deliveredNotifications()++ let ret = notifications.compactMap({ (notification) -> ActiveNotification? in+ return self.notificationHandler.toActiveNotification(notification.request)+ })++ return try ret.toJSONString()+ }++ public func setClickListenerActive(args: RustString) throws(FFIResult) {+ let args = try args.decode(SetClickListenerActiveArgs.self)+ notificationHandler.setClickListenerActive(args.active)+ }++ #if ENABLE_PUSH_NOTIFICATIONS+ private func registerForPushNotificationsWithCompletion(_ completion: @escaping (Result<String, Error>) -> Void)+ {+ // Store completion for later+ self.pushTokenCompletion = completion++ // Set up timeout+ self.pushTokenTimer?.invalidate()+ self.pushTokenTimer = Timer.scheduledTimer(withTimeInterval: pushTokenTimeout, repeats: false)+ { [weak self] _ in+ self?.handlePushTokenTimeout()+ }++ // Register for remote notifications+ DispatchQueue.main.async {+ NSApplication.shared.registerForRemoteNotifications()+ }+ }++ private func handlePushTokenTimeout() {+ pushTokenTimer?.invalidate()+ pushTokenTimer = nil++ if let completion = pushTokenCompletion {+ pushTokenCompletion = nil+ let error = NSError(+ domain: "NotificationPlugin",+ code: -1,+ userInfo: [NSLocalizedDescriptionKey: "Timeout waiting for device token"]+ )+ completion(.failure(error))+ }+ }++ // Called by AppDelegateSwizzler when token is received+ func handlePushTokenReceived(_ token: String) {+ pushTokenTimer?.invalidate()+ pushTokenTimer = nil++ if let completion = pushTokenCompletion {+ pushTokenCompletion = nil+ completion(.success(token))+ }+ }++ // Called by AppDelegateSwizzler when registration fails+ func handlePushTokenError(_ error: Error) {+ pushTokenTimer?.invalidate()+ pushTokenTimer = nil++ if let completion = pushTokenCompletion {+ pushTokenCompletion = nil+ completion(.failure(error))+ }+ }+ #endif++ public func trigger<T: Encodable>(_ event: String, data: T) throws {+ let jsonData = try JSONEncoder().encode(data)+ guard let jsonString = String(data: jsonData, encoding: .utf8) else {+ throw NSError(+ domain: "NotificationPlugin", code: -1,+ userInfo: [NSLocalizedDescriptionKey: "Failed to encode data to JSON string"])+ }+ try bridgeTrigger(RustString(event), RustString(jsonString))+ }+}++// Initialize the plugin+func initPlugin() -> NotificationPlugin {+ return NotificationPlugin()+}diff --git a/src-tauri/vendor/tauri-plugin-notifications/macos/Sources/bridging-header.h b/src-tauri/vendor/tauri-plugin-notifications/macos/Sources/bridging-header.hnew file mode 100644index 00000000..8882bf37--- /dev/null+++ b/src-tauri/vendor/tauri-plugin-notifications/macos/Sources/bridging-header.h@@ -0,0 +1,9 @@+#ifndef BRIDGING_HEADER_H+#define BRIDGING_HEADER_H++#ifdef __OBJC__+#import "./generated/SwiftBridgeCore.h"+#import "./generated/tauri-plugin-notifications/tauri-plugin-notifications.h"+#endif++#endif // BRIDGING_HEADER_H\ No newline at end of filediff --git a/src-tauri/vendor/tauri-plugin-notifications/macos/Tests/PluginTests/MockFFI.swift b/src-tauri/vendor/tauri-plugin-notifications/macos/Tests/PluginTests/MockFFI.swiftnew file mode 100644index 00000000..dfbd3d3c--- /dev/null+++ b/src-tauri/vendor/tauri-plugin-notifications/macos/Tests/PluginTests/MockFFI.swift@@ -0,0 +1,810 @@+import Foundation+@testable import tauri_plugin_notifications++// MARK: - Mock Storage++private var mockStringStorage: [UnsafeMutableRawPointer: String] = [:]+private var nextMockPtr: UInt = 1++private func allocateMockPtr() -> UnsafeMutableRawPointer {+ let ptr = UnsafeMutableRawPointer(bitPattern: nextMockPtr)!+ nextMockPtr += 1+ return ptr+}++// MARK: - RustString Mock FFI++@_cdecl("__swift_bridge__$RustString$new")+func mock_RustString_new() -> UnsafeMutableRawPointer {+ let ptr = allocateMockPtr()+ mockStringStorage[ptr] = ""+ return ptr+}++@_cdecl("__swift_bridge__$RustString$new_with_str")+func mock_RustString_new_with_str(_ str: RustStr) -> UnsafeMutableRawPointer {+ let ptr = allocateMockPtr()+ let swiftString = str.toString()+ mockStringStorage[ptr] = swiftString+ return ptr+}++@_cdecl("__swift_bridge__$RustString$_free")+func mock_RustString_free(_ ptr: UnsafeMutableRawPointer) {+ mockStringStorage.removeValue(forKey: ptr)+}++@_cdecl("__swift_bridge__$RustString$len")+func mock_RustString_len(_ ptr: UnsafeMutableRawPointer) -> UInt {+ guard let str = mockStringStorage[ptr] else { return 0 }+ return UInt(str.utf8.count)+}++@_cdecl("__swift_bridge__$RustString$as_str")+func mock_RustString_as_str(_ ptr: UnsafeMutableRawPointer) -> RustStr {+ guard let str = mockStringStorage[ptr] else {+ return RustStr(start: nil, len: 0)+ }+ let utf8 = Array(str.utf8)+ let buffer = UnsafeMutablePointer<UInt8>.allocate(capacity: utf8.count)+ buffer.initialize(from: utf8, count: utf8.count)+ return RustStr(start: buffer, len: UInt(utf8.count))+}++@_cdecl("__swift_bridge__$RustString$trim")+func mock_RustString_trim(_ ptr: UnsafeMutableRawPointer) -> RustStr {+ guard let str = mockStringStorage[ptr] else {+ return RustStr(start: nil, len: 0)+ }+ let trimmed = str.trimmingCharacters(in: .whitespacesAndNewlines)+ let utf8 = Array(trimmed.utf8)+ let buffer = UnsafeMutablePointer<UInt8>.allocate(capacity: utf8.count)+ buffer.initialize(from: utf8, count: utf8.count)+ return RustStr(start: buffer, len: UInt(utf8.count))+}++@_cdecl("__swift_bridge__$RustStr$partial_eq")+func mock_RustStr_partial_eq(_ lhs: RustStr, _ rhs: RustStr) -> Bool {+ return lhs.toString() == rhs.toString()+}++// MARK: - RustVec<RustString> Mock FFI++private var mockVecStringStorage: [UnsafeMutableRawPointer: [UnsafeMutableRawPointer]] = [:]++@_cdecl("__swift_bridge__$Vec_RustString$new")+func mock_Vec_RustString_new() -> UnsafeMutableRawPointer {+ let ptr = allocateMockPtr()+ mockVecStringStorage[ptr] = []+ return ptr+}++@_cdecl("__swift_bridge__$Vec_RustString$drop")+func mock_Vec_RustString_drop(_ ptr: UnsafeMutableRawPointer) {+ mockVecStringStorage.removeValue(forKey: ptr)+}++@_cdecl("__swift_bridge__$Vec_RustString$push")+func mock_Vec_RustString_push(_ vecPtr: UnsafeMutableRawPointer, _ itemPtr: UnsafeMutableRawPointer) {+ mockVecStringStorage[vecPtr]?.append(itemPtr)+}++@_cdecl("__swift_bridge__$Vec_RustString$pop")+func mock_Vec_RustString_pop(_ vecPtr: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer? {+ return mockVecStringStorage[vecPtr]?.popLast()+}++@_cdecl("__swift_bridge__$Vec_RustString$get")+func mock_Vec_RustString_get(_ vecPtr: UnsafeMutableRawPointer, _ index: UInt) -> UnsafeMutableRawPointer? {+ guard let vec = mockVecStringStorage[vecPtr], index < vec.count else { return nil }+ return vec[Int(index)]+}++@_cdecl("__swift_bridge__$Vec_RustString$get_mut")+func mock_Vec_RustString_get_mut(_ vecPtr: UnsafeMutableRawPointer, _ index: UInt) -> UnsafeMutableRawPointer? {+ return mock_Vec_RustString_get(vecPtr, index)+}++@_cdecl("__swift_bridge__$Vec_RustString$len")+func mock_Vec_RustString_len(_ vecPtr: UnsafeMutableRawPointer) -> UInt {+ return UInt(mockVecStringStorage[vecPtr]?.count ?? 0)+}++@_cdecl("__swift_bridge__$Vec_RustString$as_ptr")+func mock_Vec_RustString_as_ptr(_ vecPtr: UnsafeMutableRawPointer) -> UnsafeRawPointer? {+ guard let vec = mockVecStringStorage[vecPtr], !vec.isEmpty else { return nil }+ return UnsafeRawPointer(vec.withUnsafeBufferPointer { $0.baseAddress })+}++// MARK: - Null pointer helper++@_cdecl("__swift_bridge__null_pointer")+func mock_null_pointer() -> UnsafeMutableRawPointer? {+ return nil+}++// MARK: - Boxed FnOnce helpers++@_cdecl("__swift_bridge__$call_boxed_fn_once_no_args_no_return")+func mock_call_boxed_fn_once(_ ptr: UnsafeMutableRawPointer) {+ // No-op for tests+}++@_cdecl("__swift_bridge__$free_boxed_fn_once_no_args_no_return")+func mock_free_boxed_fn_once(_ ptr: UnsafeMutableRawPointer) {+ // No-op for tests+}++// MARK: - Generic Vec Storage for primitive types++private var mockVecU8Storage: [UnsafeMutableRawPointer: [UInt8]] = [:]+private var mockVecU16Storage: [UnsafeMutableRawPointer: [UInt16]] = [:]+private var mockVecU32Storage: [UnsafeMutableRawPointer: [UInt32]] = [:]+private var mockVecU64Storage: [UnsafeMutableRawPointer: [UInt64]] = [:]+private var mockVecUsizeStorage: [UnsafeMutableRawPointer: [UInt]] = [:]+private var mockVecI8Storage: [UnsafeMutableRawPointer: [Int8]] = [:]+private var mockVecI16Storage: [UnsafeMutableRawPointer: [Int16]] = [:]+private var mockVecI32Storage: [UnsafeMutableRawPointer: [Int32]] = [:]+private var mockVecI64Storage: [UnsafeMutableRawPointer: [Int64]] = [:]+private var mockVecIsizeStorage: [UnsafeMutableRawPointer: [Int]] = [:]+private var mockVecBoolStorage: [UnsafeMutableRawPointer: [Bool]] = [:]+private var mockVecF32Storage: [UnsafeMutableRawPointer: [Float]] = [:]+private var mockVecF64Storage: [UnsafeMutableRawPointer: [Double]] = [:]++// MARK: - Vec<u8>++@_cdecl("__swift_bridge__$Vec_u8$new")+func mock_Vec_u8_new() -> UnsafeMutableRawPointer {+ let ptr = allocateMockPtr()+ mockVecU8Storage[ptr] = []+ return ptr+}++@_cdecl("__swift_bridge__$Vec_u8$_free")+func mock_Vec_u8_free(_ ptr: UnsafeMutableRawPointer) {+ mockVecU8Storage.removeValue(forKey: ptr)+}++@_cdecl("__swift_bridge__$Vec_u8$push")+func mock_Vec_u8_push(_ vecPtr: UnsafeMutableRawPointer, _ val: UInt8) {+ mockVecU8Storage[vecPtr]?.append(val)+}++@_cdecl("__swift_bridge__$Vec_u8$pop")+func mock_Vec_u8_pop(_ vecPtr: UnsafeMutableRawPointer) -> __private__OptionU8 {+ if let val = mockVecU8Storage[vecPtr]?.popLast() {+ return __private__OptionU8(val: val, is_some: true)+ }+ return __private__OptionU8(val: 0, is_some: false)+}++@_cdecl("__swift_bridge__$Vec_u8$get")+func mock_Vec_u8_get(_ vecPtr: UnsafeMutableRawPointer, _ index: UInt) -> __private__OptionU8 {+ if let vec = mockVecU8Storage[vecPtr], index < vec.count {+ return __private__OptionU8(val: vec[Int(index)], is_some: true)+ }+ return __private__OptionU8(val: 0, is_some: false)+}++@_cdecl("__swift_bridge__$Vec_u8$get_mut")+func mock_Vec_u8_get_mut(_ vecPtr: UnsafeMutableRawPointer, _ index: UInt) -> __private__OptionU8 {+ return mock_Vec_u8_get(vecPtr, index)+}++@_cdecl("__swift_bridge__$Vec_u8$len")+func mock_Vec_u8_len(_ vecPtr: UnsafeMutableRawPointer) -> UInt {+ return UInt(mockVecU8Storage[vecPtr]?.count ?? 0)+}++@_cdecl("__swift_bridge__$Vec_u8$as_ptr")+func mock_Vec_u8_as_ptr(_ vecPtr: UnsafeMutableRawPointer) -> UnsafePointer<UInt8>? {+ return mockVecU8Storage[vecPtr]?.withUnsafeBufferPointer { $0.baseAddress }+}++// MARK: - Vec<u16>++@_cdecl("__swift_bridge__$Vec_u16$new")+func mock_Vec_u16_new() -> UnsafeMutableRawPointer {+ let ptr = allocateMockPtr()+ mockVecU16Storage[ptr] = []+ return ptr+}++@_cdecl("__swift_bridge__$Vec_u16$_free")+func mock_Vec_u16_free(_ ptr: UnsafeMutableRawPointer) {+ mockVecU16Storage.removeValue(forKey: ptr)+}++@_cdecl("__swift_bridge__$Vec_u16$push")+func mock_Vec_u16_push(_ vecPtr: UnsafeMutableRawPointer, _ val: UInt16) {+ mockVecU16Storage[vecPtr]?.append(val)+}++@_cdecl("__swift_bridge__$Vec_u16$pop")+func mock_Vec_u16_pop(_ vecPtr: UnsafeMutableRawPointer) -> __private__OptionU16 {+ if let val = mockVecU16Storage[vecPtr]?.popLast() {+ return __private__OptionU16(val: val, is_some: true)+ }+ return __private__OptionU16(val: 0, is_some: false)+}++@_cdecl("__swift_bridge__$Vec_u16$get")+func mock_Vec_u16_get(_ vecPtr: UnsafeMutableRawPointer, _ index: UInt) -> __private__OptionU16 {+ if let vec = mockVecU16Storage[vecPtr], index < vec.count {+ return __private__OptionU16(val: vec[Int(index)], is_some: true)+ }+ return __private__OptionU16(val: 0, is_some: false)+}++@_cdecl("__swift_bridge__$Vec_u16$get_mut")+func mock_Vec_u16_get_mut(_ vecPtr: UnsafeMutableRawPointer, _ index: UInt) -> __private__OptionU16 {+ return mock_Vec_u16_get(vecPtr, index)+}++@_cdecl("__swift_bridge__$Vec_u16$len")+func mock_Vec_u16_len(_ vecPtr: UnsafeMutableRawPointer) -> UInt {+ return UInt(mockVecU16Storage[vecPtr]?.count ?? 0)+}++@_cdecl("__swift_bridge__$Vec_u16$as_ptr")+func mock_Vec_u16_as_ptr(_ vecPtr: UnsafeMutableRawPointer) -> UnsafePointer<UInt16>? {+ return mockVecU16Storage[vecPtr]?.withUnsafeBufferPointer { $0.baseAddress }+}++// MARK: - Vec<u32>++@_cdecl("__swift_bridge__$Vec_u32$new")+func mock_Vec_u32_new() -> UnsafeMutableRawPointer {+ let ptr = allocateMockPtr()+ mockVecU32Storage[ptr] = []+ return ptr+}++@_cdecl("__swift_bridge__$Vec_u32$_free")+func mock_Vec_u32_free(_ ptr: UnsafeMutableRawPointer) {+ mockVecU32Storage.removeValue(forKey: ptr)+}++@_cdecl("__swift_bridge__$Vec_u32$push")+func mock_Vec_u32_push(_ vecPtr: UnsafeMutableRawPointer, _ val: UInt32) {+ mockVecU32Storage[vecPtr]?.append(val)+}++@_cdecl("__swift_bridge__$Vec_u32$pop")+func mock_Vec_u32_pop(_ vecPtr: UnsafeMutableRawPointer) -> __private__OptionU32 {+ if let val = mockVecU32Storage[vecPtr]?.popLast() {+ return __private__OptionU32(val: val, is_some: true)+ }+ return __private__OptionU32(val: 0, is_some: false)+}++@_cdecl("__swift_bridge__$Vec_u32$get")+func mock_Vec_u32_get(_ vecPtr: UnsafeMutableRawPointer, _ index: UInt) -> __private__OptionU32 {+ if let vec = mockVecU32Storage[vecPtr], index < vec.count {+ return __private__OptionU32(val: vec[Int(index)], is_some: true)+ }+ return __private__OptionU32(val: 0, is_some: false)+}++@_cdecl("__swift_bridge__$Vec_u32$get_mut")+func mock_Vec_u32_get_mut(_ vecPtr: UnsafeMutableRawPointer, _ index: UInt) -> __private__OptionU32 {+ return mock_Vec_u32_get(vecPtr, index)+}++@_cdecl("__swift_bridge__$Vec_u32$len")+func mock_Vec_u32_len(_ vecPtr: UnsafeMutableRawPointer) -> UInt {+ return UInt(mockVecU32Storage[vecPtr]?.count ?? 0)+}++@_cdecl("__swift_bridge__$Vec_u32$as_ptr")+func mock_Vec_u32_as_ptr(_ vecPtr: UnsafeMutableRawPointer) -> UnsafePointer<UInt32>? {+ return mockVecU32Storage[vecPtr]?.withUnsafeBufferPointer { $0.baseAddress }+}++// MARK: - Vec<u64>++@_cdecl("__swift_bridge__$Vec_u64$new")+func mock_Vec_u64_new() -> UnsafeMutableRawPointer {+ let ptr = allocateMockPtr()+ mockVecU64Storage[ptr] = []+ return ptr+}++@_cdecl("__swift_bridge__$Vec_u64$_free")+func mock_Vec_u64_free(_ ptr: UnsafeMutableRawPointer) {+ mockVecU64Storage.removeValue(forKey: ptr)+}++@_cdecl("__swift_bridge__$Vec_u64$push")+func mock_Vec_u64_push(_ vecPtr: UnsafeMutableRawPointer, _ val: UInt64) {+ mockVecU64Storage[vecPtr]?.append(val)+}++@_cdecl("__swift_bridge__$Vec_u64$pop")+func mock_Vec_u64_pop(_ vecPtr: UnsafeMutableRawPointer) -> __private__OptionU64 {+ if let val = mockVecU64Storage[vecPtr]?.popLast() {+ return __private__OptionU64(val: val, is_some: true)+ }+ return __private__OptionU64(val: 0, is_some: false)+}++@_cdecl("__swift_bridge__$Vec_u64$get")+func mock_Vec_u64_get(_ vecPtr: UnsafeMutableRawPointer, _ index: UInt) -> __private__OptionU64 {+ if let vec = mockVecU64Storage[vecPtr], index < vec.count {+ return __private__OptionU64(val: vec[Int(index)], is_some: true)+ }+ return __private__OptionU64(val: 0, is_some: false)+}++@_cdecl("__swift_bridge__$Vec_u64$get_mut")+func mock_Vec_u64_get_mut(_ vecPtr: UnsafeMutableRawPointer, _ index: UInt) -> __private__OptionU64 {+ return mock_Vec_u64_get(vecPtr, index)+}++@_cdecl("__swift_bridge__$Vec_u64$len")+func mock_Vec_u64_len(_ vecPtr: UnsafeMutableRawPointer) -> UInt {+ return UInt(mockVecU64Storage[vecPtr]?.count ?? 0)+}++@_cdecl("__swift_bridge__$Vec_u64$as_ptr")+func mock_Vec_u64_as_ptr(_ vecPtr: UnsafeMutableRawPointer) -> UnsafePointer<UInt64>? {+ return mockVecU64Storage[vecPtr]?.withUnsafeBufferPointer { $0.baseAddress }+}++// MARK: - Vec<usize>++@_cdecl("__swift_bridge__$Vec_usize$new")+func mock_Vec_usize_new() -> UnsafeMutableRawPointer {+ let ptr = allocateMockPtr()+ mockVecUsizeStorage[ptr] = []+ return ptr+}++@_cdecl("__swift_bridge__$Vec_usize$_free")+func mock_Vec_usize_free(_ ptr: UnsafeMutableRawPointer) {+ mockVecUsizeStorage.removeValue(forKey: ptr)+}++@_cdecl("__swift_bridge__$Vec_usize$push")+func mock_Vec_usize_push(_ vecPtr: UnsafeMutableRawPointer, _ val: UInt) {+ mockVecUsizeStorage[vecPtr]?.append(val)+}++@_cdecl("__swift_bridge__$Vec_usize$pop")+func mock_Vec_usize_pop(_ vecPtr: UnsafeMutableRawPointer) -> __private__OptionUsize {+ if let val = mockVecUsizeStorage[vecPtr]?.popLast() {+ return __private__OptionUsize(val: val, is_some: true)+ }+ return __private__OptionUsize(val: 0, is_some: false)+}++@_cdecl("__swift_bridge__$Vec_usize$get")+func mock_Vec_usize_get(_ vecPtr: UnsafeMutableRawPointer, _ index: UInt) -> __private__OptionUsize {+ if let vec = mockVecUsizeStorage[vecPtr], index < vec.count {+ return __private__OptionUsize(val: vec[Int(index)], is_some: true)+ }+ return __private__OptionUsize(val: 0, is_some: false)+}++@_cdecl("__swift_bridge__$Vec_usize$get_mut")+func mock_Vec_usize_get_mut(_ vecPtr: UnsafeMutableRawPointer, _ index: UInt) -> __private__OptionUsize {+ return mock_Vec_usize_get(vecPtr, index)+}++@_cdecl("__swift_bridge__$Vec_usize$len")+func mock_Vec_usize_len(_ vecPtr: UnsafeMutableRawPointer) -> UInt {+ return UInt(mockVecUsizeStorage[vecPtr]?.count ?? 0)+}++@_cdecl("__swift_bridge__$Vec_usize$as_ptr")+func mock_Vec_usize_as_ptr(_ vecPtr: UnsafeMutableRawPointer) -> UnsafePointer<UInt>? {+ return mockVecUsizeStorage[vecPtr]?.withUnsafeBufferPointer { $0.baseAddress }+}++// MARK: - Vec<i8>++@_cdecl("__swift_bridge__$Vec_i8$new")+func mock_Vec_i8_new() -> UnsafeMutableRawPointer {+ let ptr = allocateMockPtr()+ mockVecI8Storage[ptr] = []+ return ptr+}++@_cdecl("__swift_bridge__$Vec_i8$_free")+func mock_Vec_i8_free(_ ptr: UnsafeMutableRawPointer) {+ mockVecI8Storage.removeValue(forKey: ptr)+}++@_cdecl("__swift_bridge__$Vec_i8$push")+func mock_Vec_i8_push(_ vecPtr: UnsafeMutableRawPointer, _ val: Int8) {+ mockVecI8Storage[vecPtr]?.append(val)+}++@_cdecl("__swift_bridge__$Vec_i8$pop")+func mock_Vec_i8_pop(_ vecPtr: UnsafeMutableRawPointer) -> __private__OptionI8 {+ if let val = mockVecI8Storage[vecPtr]?.popLast() {+ return __private__OptionI8(val: val, is_some: true)+ }+ return __private__OptionI8(val: 0, is_some: false)+}++@_cdecl("__swift_bridge__$Vec_i8$get")+func mock_Vec_i8_get(_ vecPtr: UnsafeMutableRawPointer, _ index: UInt) -> __private__OptionI8 {+ if let vec = mockVecI8Storage[vecPtr], index < vec.count {+ return __private__OptionI8(val: vec[Int(index)], is_some: true)+ }+ return __private__OptionI8(val: 0, is_some: false)+}++@_cdecl("__swift_bridge__$Vec_i8$get_mut")+func mock_Vec_i8_get_mut(_ vecPtr: UnsafeMutableRawPointer, _ index: UInt) -> __private__OptionI8 {+ return mock_Vec_i8_get(vecPtr, index)+}++@_cdecl("__swift_bridge__$Vec_i8$len")+func mock_Vec_i8_len(_ vecPtr: UnsafeMutableRawPointer) -> UInt {+ return UInt(mockVecI8Storage[vecPtr]?.count ?? 0)+}++@_cdecl("__swift_bridge__$Vec_i8$as_ptr")+func mock_Vec_i8_as_ptr(_ vecPtr: UnsafeMutableRawPointer) -> UnsafePointer<Int8>? {+ return mockVecI8Storage[vecPtr]?.withUnsafeBufferPointer { $0.baseAddress }+}++// MARK: - Vec<i16>++@_cdecl("__swift_bridge__$Vec_i16$new")+func mock_Vec_i16_new() -> UnsafeMutableRawPointer {+ let ptr = allocateMockPtr()+ mockVecI16Storage[ptr] = []+ return ptr+}++@_cdecl("__swift_bridge__$Vec_i16$_free")+func mock_Vec_i16_free(_ ptr: UnsafeMutableRawPointer) {+ mockVecI16Storage.removeValue(forKey: ptr)+}++@_cdecl("__swift_bridge__$Vec_i16$push")+func mock_Vec_i16_push(_ vecPtr: UnsafeMutableRawPointer, _ val: Int16) {+ mockVecI16Storage[vecPtr]?.append(val)+}++@_cdecl("__swift_bridge__$Vec_i16$pop")+func mock_Vec_i16_pop(_ vecPtr: UnsafeMutableRawPointer) -> __private__OptionI16 {+ if let val = mockVecI16Storage[vecPtr]?.popLast() {+ return __private__OptionI16(val: val, is_some: true)+ }+ return __private__OptionI16(val: 0, is_some: false)+}++@_cdecl("__swift_bridge__$Vec_i16$get")+func mock_Vec_i16_get(_ vecPtr: UnsafeMutableRawPointer, _ index: UInt) -> __private__OptionI16 {+ if let vec = mockVecI16Storage[vecPtr], index < vec.count {+ return __private__OptionI16(val: vec[Int(index)], is_some: true)+ }+ return __private__OptionI16(val: 0, is_some: false)+}++@_cdecl("__swift_bridge__$Vec_i16$get_mut")+func mock_Vec_i16_get_mut(_ vecPtr: UnsafeMutableRawPointer, _ index: UInt) -> __private__OptionI16 {+ return mock_Vec_i16_get(vecPtr, index)+}++@_cdecl("__swift_bridge__$Vec_i16$len")+func mock_Vec_i16_len(_ vecPtr: UnsafeMutableRawPointer) -> UInt {+ return UInt(mockVecI16Storage[vecPtr]?.count ?? 0)+}++@_cdecl("__swift_bridge__$Vec_i16$as_ptr")+func mock_Vec_i16_as_ptr(_ vecPtr: UnsafeMutableRawPointer) -> UnsafePointer<Int16>? {+ return mockVecI16Storage[vecPtr]?.withUnsafeBufferPointer { $0.baseAddress }+}++// MARK: - Vec<i32>++@_cdecl("__swift_bridge__$Vec_i32$new")+func mock_Vec_i32_new() -> UnsafeMutableRawPointer {+ let ptr = allocateMockPtr()+ mockVecI32Storage[ptr] = []+ return ptr+}++@_cdecl("__swift_bridge__$Vec_i32$_free")+func mock_Vec_i32_free(_ ptr: UnsafeMutableRawPointer) {+ mockVecI32Storage.removeValue(forKey: ptr)+}++@_cdecl("__swift_bridge__$Vec_i32$push")+func mock_Vec_i32_push(_ vecPtr: UnsafeMutableRawPointer, _ val: Int32) {+ mockVecI32Storage[vecPtr]?.append(val)+}++@_cdecl("__swift_bridge__$Vec_i32$pop")+func mock_Vec_i32_pop(_ vecPtr: UnsafeMutableRawPointer) -> __private__OptionI32 {+ if let val = mockVecI32Storage[vecPtr]?.popLast() {+ return __private__OptionI32(val: val, is_some: true)+ }+ return __private__OptionI32(val: 0, is_some: false)+}++@_cdecl("__swift_bridge__$Vec_i32$get")+func mock_Vec_i32_get(_ vecPtr: UnsafeMutableRawPointer, _ index: UInt) -> __private__OptionI32 {+ if let vec = mockVecI32Storage[vecPtr], index < vec.count {+ return __private__OptionI32(val: vec[Int(index)], is_some: true)+ }+ return __private__OptionI32(val: 0, is_some: false)+}++@_cdecl("__swift_bridge__$Vec_i32$get_mut")+func mock_Vec_i32_get_mut(_ vecPtr: UnsafeMutableRawPointer, _ index: UInt) -> __private__OptionI32 {+ return mock_Vec_i32_get(vecPtr, index)+}++@_cdecl("__swift_bridge__$Vec_i32$len")+func mock_Vec_i32_len(_ vecPtr: UnsafeMutableRawPointer) -> UInt {+ return UInt(mockVecI32Storage[vecPtr]?.count ?? 0)+}++@_cdecl("__swift_bridge__$Vec_i32$as_ptr")+func mock_Vec_i32_as_ptr(_ vecPtr: UnsafeMutableRawPointer) -> UnsafePointer<Int32>? {+ return mockVecI32Storage[vecPtr]?.withUnsafeBufferPointer { $0.baseAddress }+}++// MARK: - Vec<i64>++@_cdecl("__swift_bridge__$Vec_i64$new")+func mock_Vec_i64_new() -> UnsafeMutableRawPointer {+ let ptr = allocateMockPtr()+ mockVecI64Storage[ptr] = []+ return ptr+}++@_cdecl("__swift_bridge__$Vec_i64$_free")+func mock_Vec_i64_free(_ ptr: UnsafeMutableRawPointer) {+ mockVecI64Storage.removeValue(forKey: ptr)+}++@_cdecl("__swift_bridge__$Vec_i64$push")+func mock_Vec_i64_push(_ vecPtr: UnsafeMutableRawPointer, _ val: Int64) {+ mockVecI64Storage[vecPtr]?.append(val)+}++@_cdecl("__swift_bridge__$Vec_i64$pop")+func mock_Vec_i64_pop(_ vecPtr: UnsafeMutableRawPointer) -> __private__OptionI64 {+ if let val = mockVecI64Storage[vecPtr]?.popLast() {+ return __private__OptionI64(val: val, is_some: true)+ }+ return __private__OptionI64(val: 0, is_some: false)+}++@_cdecl("__swift_bridge__$Vec_i64$get")+func mock_Vec_i64_get(_ vecPtr: UnsafeMutableRawPointer, _ index: UInt) -> __private__OptionI64 {+ if let vec = mockVecI64Storage[vecPtr], index < vec.count {+ return __private__OptionI64(val: vec[Int(index)], is_some: true)+ }+ return __private__OptionI64(val: 0, is_some: false)+}++@_cdecl("__swift_bridge__$Vec_i64$get_mut")+func mock_Vec_i64_get_mut(_ vecPtr: UnsafeMutableRawPointer, _ index: UInt) -> __private__OptionI64 {+ return mock_Vec_i64_get(vecPtr, index)+}++@_cdecl("__swift_bridge__$Vec_i64$len")+func mock_Vec_i64_len(_ vecPtr: UnsafeMutableRawPointer) -> UInt {+ return UInt(mockVecI64Storage[vecPtr]?.count ?? 0)+}++@_cdecl("__swift_bridge__$Vec_i64$as_ptr")+func mock_Vec_i64_as_ptr(_ vecPtr: UnsafeMutableRawPointer) -> UnsafePointer<Int64>? {+ return mockVecI64Storage[vecPtr]?.withUnsafeBufferPointer { $0.baseAddress }+}++// MARK: - Vec<isize>++@_cdecl("__swift_bridge__$Vec_isize$new")+func mock_Vec_isize_new() -> UnsafeMutableRawPointer {+ let ptr = allocateMockPtr()+ mockVecIsizeStorage[ptr] = []+ return ptr+}++@_cdecl("__swift_bridge__$Vec_isize$_free")+func mock_Vec_isize_free(_ ptr: UnsafeMutableRawPointer) {+ mockVecIsizeStorage.removeValue(forKey: ptr)+}++@_cdecl("__swift_bridge__$Vec_isize$push")+func mock_Vec_isize_push(_ vecPtr: UnsafeMutableRawPointer, _ val: Int) {+ mockVecIsizeStorage[vecPtr]?.append(val)+}++@_cdecl("__swift_bridge__$Vec_isize$pop")+func mock_Vec_isize_pop(_ vecPtr: UnsafeMutableRawPointer) -> __private__OptionIsize {+ if let val = mockVecIsizeStorage[vecPtr]?.popLast() {+ return __private__OptionIsize(val: val, is_some: true)+ }+ return __private__OptionIsize(val: 0, is_some: false)+}++@_cdecl("__swift_bridge__$Vec_isize$get")+func mock_Vec_isize_get(_ vecPtr: UnsafeMutableRawPointer, _ index: UInt) -> __private__OptionIsize {+ if let vec = mockVecIsizeStorage[vecPtr], index < vec.count {+ return __private__OptionIsize(val: vec[Int(index)], is_some: true)+ }+ return __private__OptionIsize(val: 0, is_some: false)+}++@_cdecl("__swift_bridge__$Vec_isize$get_mut")+func mock_Vec_isize_get_mut(_ vecPtr: UnsafeMutableRawPointer, _ index: UInt) -> __private__OptionIsize {+ return mock_Vec_isize_get(vecPtr, index)+}++@_cdecl("__swift_bridge__$Vec_isize$len")+func mock_Vec_isize_len(_ vecPtr: UnsafeMutableRawPointer) -> UInt {+ return UInt(mockVecIsizeStorage[vecPtr]?.count ?? 0)+}++@_cdecl("__swift_bridge__$Vec_isize$as_ptr")+func mock_Vec_isize_as_ptr(_ vecPtr: UnsafeMutableRawPointer) -> UnsafePointer<Int>? {+ return mockVecIsizeStorage[vecPtr]?.withUnsafeBufferPointer { $0.baseAddress }+}++// MARK: - Vec<bool>++@_cdecl("__swift_bridge__$Vec_bool$new")+func mock_Vec_bool_new() -> UnsafeMutableRawPointer {+ let ptr = allocateMockPtr()+ mockVecBoolStorage[ptr] = []+ return ptr+}++@_cdecl("__swift_bridge__$Vec_bool$_free")+func mock_Vec_bool_free(_ ptr: UnsafeMutableRawPointer) {+ mockVecBoolStorage.removeValue(forKey: ptr)+}++@_cdecl("__swift_bridge__$Vec_bool$push")+func mock_Vec_bool_push(_ vecPtr: UnsafeMutableRawPointer, _ val: Bool) {+ mockVecBoolStorage[vecPtr]?.append(val)+}++@_cdecl("__swift_bridge__$Vec_bool$pop")+func mock_Vec_bool_pop(_ vecPtr: UnsafeMutableRawPointer) -> __private__OptionBool {+ if let val = mockVecBoolStorage[vecPtr]?.popLast() {+ return __private__OptionBool(val: val, is_some: true)+ }+ return __private__OptionBool(val: false, is_some: false)+}++@_cdecl("__swift_bridge__$Vec_bool$get")+func mock_Vec_bool_get(_ vecPtr: UnsafeMutableRawPointer, _ index: UInt) -> __private__OptionBool {+ if let vec = mockVecBoolStorage[vecPtr], index < vec.count {+ return __private__OptionBool(val: vec[Int(index)], is_some: true)+ }+ return __private__OptionBool(val: false, is_some: false)+}++@_cdecl("__swift_bridge__$Vec_bool$get_mut")+func mock_Vec_bool_get_mut(_ vecPtr: UnsafeMutableRawPointer, _ index: UInt) -> __private__OptionBool {+ return mock_Vec_bool_get(vecPtr, index)+}++@_cdecl("__swift_bridge__$Vec_bool$len")+func mock_Vec_bool_len(_ vecPtr: UnsafeMutableRawPointer) -> UInt {+ return UInt(mockVecBoolStorage[vecPtr]?.count ?? 0)+}++@_cdecl("__swift_bridge__$Vec_bool$as_ptr")+func mock_Vec_bool_as_ptr(_ vecPtr: UnsafeMutableRawPointer) -> UnsafePointer<Bool>? {+ return mockVecBoolStorage[vecPtr]?.withUnsafeBufferPointer { $0.baseAddress }+}++// MARK: - Vec<f32>++@_cdecl("__swift_bridge__$Vec_f32$new")+func mock_Vec_f32_new() -> UnsafeMutableRawPointer {+ let ptr = allocateMockPtr()+ mockVecF32Storage[ptr] = []+ return ptr+}++@_cdecl("__swift_bridge__$Vec_f32$_free")+func mock_Vec_f32_free(_ ptr: UnsafeMutableRawPointer) {+ mockVecF32Storage.removeValue(forKey: ptr)+}++@_cdecl("__swift_bridge__$Vec_f32$push")+func mock_Vec_f32_push(_ vecPtr: UnsafeMutableRawPointer, _ val: Float) {+ mockVecF32Storage[vecPtr]?.append(val)+}++@_cdecl("__swift_bridge__$Vec_f32$pop")+func mock_Vec_f32_pop(_ vecPtr: UnsafeMutableRawPointer) -> __private__OptionF32 {+ if let val = mockVecF32Storage[vecPtr]?.popLast() {+ return __private__OptionF32(val: val, is_some: true)+ }+ return __private__OptionF32(val: 0, is_some: false)+}++@_cdecl("__swift_bridge__$Vec_f32$get")+func mock_Vec_f32_get(_ vecPtr: UnsafeMutableRawPointer, _ index: UInt) -> __private__OptionF32 {+ if let vec = mockVecF32Storage[vecPtr], index < vec.count {+ return __private__OptionF32(val: vec[Int(index)], is_some: true)+ }+ return __private__OptionF32(val: 0, is_some: false)+}++@_cdecl("__swift_bridge__$Vec_f32$get_mut")+func mock_Vec_f32_get_mut(_ vecPtr: UnsafeMutableRawPointer, _ index: UInt) -> __private__OptionF32 {+ return mock_Vec_f32_get(vecPtr, index)+}++@_cdecl("__swift_bridge__$Vec_f32$len")+func mock_Vec_f32_len(_ vecPtr: UnsafeMutableRawPointer) -> UInt {+ return UInt(mockVecF32Storage[vecPtr]?.count ?? 0)+}++@_cdecl("__swift_bridge__$Vec_f32$as_ptr")+func mock_Vec_f32_as_ptr(_ vecPtr: UnsafeMutableRawPointer) -> UnsafePointer<Float>? {+ return mockVecF32Storage[vecPtr]?.withUnsafeBufferPointer { $0.baseAddress }+}++// MARK: - Vec<f64>++@_cdecl("__swift_bridge__$Vec_f64$new")+func mock_Vec_f64_new() -> UnsafeMutableRawPointer {+ let ptr = allocateMockPtr()+ mockVecF64Storage[ptr] = []+ return ptr+}++@_cdecl("__swift_bridge__$Vec_f64$_free")+func mock_Vec_f64_free(_ ptr: UnsafeMutableRawPointer) {+ mockVecF64Storage.removeValue(forKey: ptr)+}++@_cdecl("__swift_bridge__$Vec_f64$push")+func mock_Vec_f64_push(_ vecPtr: UnsafeMutableRawPointer, _ val: Double) {+ mockVecF64Storage[vecPtr]?.append(val)+}++@_cdecl("__swift_bridge__$Vec_f64$pop")+func mock_Vec_f64_pop(_ vecPtr: UnsafeMutableRawPointer) -> __private__OptionF64 {+ if let val = mockVecF64Storage[vecPtr]?.popLast() {+ return __private__OptionF64(val: val, is_some: true)+ }+ return __private__OptionF64(val: 0, is_some: false)+}++@_cdecl("__swift_bridge__$Vec_f64$get")+func mock_Vec_f64_get(_ vecPtr: UnsafeMutableRawPointer, _ index: UInt) -> __private__OptionF64 {+ if let vec = mockVecF64Storage[vecPtr], index < vec.count {+ return __private__OptionF64(val: vec[Int(index)], is_some: true)+ }+ return __private__OptionF64(val: 0, is_some: false)+}++@_cdecl("__swift_bridge__$Vec_f64$get_mut")+func mock_Vec_f64_get_mut(_ vecPtr: UnsafeMutableRawPointer, _ index: UInt) -> __private__OptionF64 {+ return mock_Vec_f64_get(vecPtr, index)+}++@_cdecl("__swift_bridge__$Vec_f64$len")+func mock_Vec_f64_len(_ vecPtr: UnsafeMutableRawPointer) -> UInt {+ return UInt(mockVecF64Storage[vecPtr]?.count ?? 0)+}++@_cdecl("__swift_bridge__$Vec_f64$as_ptr")+func mock_Vec_f64_as_ptr(_ vecPtr: UnsafeMutableRawPointer) -> UnsafePointer<Double>? {+ return mockVecF64Storage[vecPtr]?.withUnsafeBufferPointer { $0.baseAddress }+}++// MARK: - Bridge Trigger Mock (Rust FFI callback for notifications)++@_cdecl("__swift_bridge__$bridge_trigger")+func mock_bridge_trigger(_ event: UnsafeMutableRawPointer, _ payload: UnsafeMutableRawPointer) -> __swift_bridge__$ResultVoidAndFFIResult {+ // No-op stub for tests - return success+ return __swift_bridge__$ResultVoidAndFFIResult(tag: __swift_bridge__$ResultVoidAndFFIResult$ResultOk, payload: __swift_bridge__$ResultVoidAndFFIResult$Fields())+}diff --git a/src-tauri/vendor/tauri-plugin-notifications/macos/Tests/PluginTests/PluginTests.swift b/src-tauri/vendor/tauri-plugin-notifications/macos/Tests/PluginTests/PluginTests.swiftnew file mode 100644index 00000000..ece8c786--- /dev/null+++ b/src-tauri/vendor/tauri-plugin-notifications/macos/Tests/PluginTests/PluginTests.swift@@ -0,0 +1,1347 @@+import XCTest+import UserNotifications+@testable import tauri_plugin_notifications++// MARK: - Test Helpers++/// Parses a JSON string into a dictionary.+private func parseJSON(_ jsonString: String) -> JsonObject? {+ guard let data = jsonString.data(using: .utf8),+ let json = try? JSONSerialization.jsonObject(with: data) as? JsonObject else {+ return nil+ }+ return json+}++/// Type alias to avoid conflicts with Foundation.Notification+typealias PluginNotification = tauri_plugin_notifications.Notification++/// Creates a minimal Notification for testing.+private func makeTestNotification(+ id: Int = 1,+ title: String = "Test Title",+ body: String? = "Test Body",+ schedule: NotificationSchedule? = nil,+ attachments: [NotificationAttachment]? = nil,+ sound: String? = nil,+ group: String? = nil,+ actionTypeId: String? = nil,+ extra: [String: String]? = nil,+ silent: Bool? = nil+) -> PluginNotification {+ return PluginNotification(+ id: id,+ title: title,+ body: body,+ extra: extra,+ schedule: schedule,+ attachments: attachments,+ sound: sound,+ group: group,+ actionTypeId: actionTypeId,+ summary: nil,+ silent: silent+ )+}++// MARK: - ScheduleEveryKind Tests++final class ScheduleEveryKindTests: XCTestCase {++ func testScheduleEveryKindRawValues() {+ XCTAssertEqual(ScheduleEveryKind.year.rawValue, "year")+ XCTAssertEqual(ScheduleEveryKind.month.rawValue, "month")+ XCTAssertEqual(ScheduleEveryKind.twoWeeks.rawValue, "twoWeeks")+ XCTAssertEqual(ScheduleEveryKind.week.rawValue, "week")+ XCTAssertEqual(ScheduleEveryKind.day.rawValue, "day")+ XCTAssertEqual(ScheduleEveryKind.hour.rawValue, "hour")+ XCTAssertEqual(ScheduleEveryKind.minute.rawValue, "minute")+ XCTAssertEqual(ScheduleEveryKind.second.rawValue, "second")+ }++ func testScheduleEveryKindFromRawValue() {+ XCTAssertEqual(ScheduleEveryKind(rawValue: "year"), .year)+ XCTAssertEqual(ScheduleEveryKind(rawValue: "month"), .month)+ XCTAssertEqual(ScheduleEveryKind(rawValue: "twoWeeks"), .twoWeeks)+ XCTAssertEqual(ScheduleEveryKind(rawValue: "week"), .week)+ XCTAssertEqual(ScheduleEveryKind(rawValue: "day"), .day)+ XCTAssertEqual(ScheduleEveryKind(rawValue: "hour"), .hour)+ XCTAssertEqual(ScheduleEveryKind(rawValue: "minute"), .minute)+ XCTAssertEqual(ScheduleEveryKind(rawValue: "second"), .second)+ XCTAssertNil(ScheduleEveryKind(rawValue: "invalid"))+ }++ func testScheduleEveryKindEncodable() throws {+ let encoder = JSONEncoder()++ let yearData = try encoder.encode(ScheduleEveryKind.year)+ XCTAssertEqual(String(data: yearData, encoding: .utf8), "\"year\"")++ let monthData = try encoder.encode(ScheduleEveryKind.month)+ XCTAssertEqual(String(data: monthData, encoding: .utf8), "\"month\"")+ }++ func testScheduleEveryKindDecodable() throws {+ let decoder = JSONDecoder()++ let yearData = "\"year\"".data(using: .utf8)!+ let year = try decoder.decode(ScheduleEveryKind.self, from: yearData)+ XCTAssertEqual(year, .year)++ let weekData = "\"week\"".data(using: .utf8)!+ let week = try decoder.decode(ScheduleEveryKind.self, from: weekData)+ XCTAssertEqual(week, .week)+ }+}++// MARK: - ScheduleInterval Tests++final class ScheduleIntervalTests: XCTestCase {++ func testScheduleIntervalDecoding() throws {+ let json = """+ {"year": 2024, "month": 12, "day": 25, "hour": 10, "minute": 30, "second": 0}+ """+ let data = json.data(using: .utf8)!+ let interval = try JSONDecoder().decode(ScheduleInterval.self, from: data)++ XCTAssertEqual(interval.year, 2024)+ XCTAssertEqual(interval.month, 12)+ XCTAssertEqual(interval.day, 25)+ XCTAssertEqual(interval.hour, 10)+ XCTAssertEqual(interval.minute, 30)+ XCTAssertEqual(interval.second, 0)+ XCTAssertNil(interval.weekday)+ }++ func testScheduleIntervalPartialDecoding() throws {+ let json = """+ {"hour": 9, "minute": 0}+ """+ let data = json.data(using: .utf8)!+ let interval = try JSONDecoder().decode(ScheduleInterval.self, from: data)++ XCTAssertNil(interval.year)+ XCTAssertNil(interval.month)+ XCTAssertNil(interval.day)+ XCTAssertEqual(interval.hour, 9)+ XCTAssertEqual(interval.minute, 0)+ XCTAssertNil(interval.second)+ XCTAssertNil(interval.weekday)+ }++ func testScheduleIntervalWithWeekday() throws {+ let json = """+ {"weekday": 2, "hour": 14}+ """+ let data = json.data(using: .utf8)!+ let interval = try JSONDecoder().decode(ScheduleInterval.self, from: data)++ XCTAssertEqual(interval.weekday, 2)+ XCTAssertEqual(interval.hour, 14)+ }+}++// MARK: - NotificationSchedule Tests++final class NotificationScheduleTests: XCTestCase {++ func testNotificationScheduleAtDecoding() throws {+ let json = """+ {"at": {"date": "2024-12-25T10:00:00.000Z", "repeating": false}}+ """+ let data = json.data(using: .utf8)!+ let schedule = try JSONDecoder().decode(NotificationSchedule.self, from: data)++ if case .at(let date, let repeating) = schedule {+ XCTAssertEqual(date, "2024-12-25T10:00:00.000Z")+ XCTAssertFalse(repeating)+ } else {+ XCTFail("Expected .at schedule")+ }+ }++ func testNotificationScheduleIntervalDecoding() throws {+ let json = """+ {"interval": {"interval": {"hour": 9, "minute": 0}}}+ """+ let data = json.data(using: .utf8)!+ let schedule = try JSONDecoder().decode(NotificationSchedule.self, from: data)++ if case .interval(let interval) = schedule {+ XCTAssertEqual(interval.hour, 9)+ XCTAssertEqual(interval.minute, 0)+ } else {+ XCTFail("Expected .interval schedule")+ }+ }++ func testNotificationScheduleEveryDecoding() throws {+ let json = """+ {"every": {"interval": "hour", "count": 2}}+ """+ let data = json.data(using: .utf8)!+ let schedule = try JSONDecoder().decode(NotificationSchedule.self, from: data)++ if case .every(let interval, let count) = schedule {+ XCTAssertEqual(interval, .hour)+ XCTAssertEqual(count, 2)+ } else {+ XCTFail("Expected .every schedule")+ }+ }+}++// MARK: - Notification Tests++final class NotificationTests: XCTestCase {++ func testNotificationMinimalDecoding() throws {+ let json = """+ {"id": 123, "title": "Hello"}+ """+ let data = json.data(using: .utf8)!+ let notification = try JSONDecoder().decode(PluginNotification.self, from: data)++ XCTAssertEqual(notification.id, 123)+ XCTAssertEqual(notification.title, "Hello")+ XCTAssertNil(notification.body)+ XCTAssertNil(notification.extra)+ XCTAssertNil(notification.schedule)+ XCTAssertNil(notification.attachments)+ XCTAssertNil(notification.sound)+ XCTAssertNil(notification.group)+ XCTAssertNil(notification.actionTypeId)+ XCTAssertNil(notification.silent)+ }++ func testNotificationFullDecoding() throws {+ let json = """+ {+ "id": 456,+ "title": "Reminder",+ "body": "Don't forget!",+ "extra": {"key1": "value1", "key2": "value2"},+ "sound": "notification.wav",+ "group": "reminders",+ "actionTypeId": "reminder_actions",+ "summary": "A reminder",+ "silent": false+ }+ """+ let data = json.data(using: .utf8)!+ let notification = try JSONDecoder().decode(PluginNotification.self, from: data)++ XCTAssertEqual(notification.id, 456)+ XCTAssertEqual(notification.title, "Reminder")+ XCTAssertEqual(notification.body, "Don't forget!")+ XCTAssertEqual(notification.extra?["key1"], "value1")+ XCTAssertEqual(notification.extra?["key2"], "value2")+ XCTAssertEqual(notification.sound, "notification.wav")+ XCTAssertEqual(notification.group, "reminders")+ XCTAssertEqual(notification.actionTypeId, "reminder_actions")+ XCTAssertEqual(notification.summary, "A reminder")+ XCTAssertEqual(notification.silent, false)+ }++ func testNotificationWithSchedule() throws {+ let json = """+ {+ "id": 1,+ "title": "Scheduled",+ "schedule": {"every": {"interval": "day", "count": 1}}+ }+ """+ let data = json.data(using: .utf8)!+ let notification = try JSONDecoder().decode(PluginNotification.self, from: data)++ XCTAssertNotNil(notification.schedule)+ if case .every(let interval, let count) = notification.schedule! {+ XCTAssertEqual(interval, .day)+ XCTAssertEqual(count, 1)+ } else {+ XCTFail("Expected .every schedule")+ }+ }++ func testNotificationWithAttachments() throws {+ let json = """+ {+ "id": 1,+ "title": "With Image",+ "attachments": [+ {"id": "img1", "url": "file:///path/to/image.png"}+ ]+ }+ """+ let data = json.data(using: .utf8)!+ let notification = try JSONDecoder().decode(PluginNotification.self, from: data)++ XCTAssertEqual(notification.attachments?.count, 1)+ XCTAssertEqual(notification.attachments?[0].id, "img1")+ XCTAssertEqual(notification.attachments?[0].url, "file:///path/to/image.png")+ }+}++// MARK: - Action Tests++final class ActionTests: XCTestCase {++ func testActionMinimalDecoding() throws {+ let json = """+ {"id": "action1", "title": "Accept"}+ """+ let data = json.data(using: .utf8)!+ let action = try JSONDecoder().decode(Action.self, from: data)++ XCTAssertEqual(action.id, "action1")+ XCTAssertEqual(action.title, "Accept")+ XCTAssertNil(action.requiresAuthentication)+ XCTAssertNil(action.foreground)+ XCTAssertNil(action.destructive)+ XCTAssertNil(action.input)+ }++ func testActionFullDecoding() throws {+ let json = """+ {+ "id": "reply",+ "title": "Reply",+ "requiresAuthentication": true,+ "foreground": true,+ "destructive": false,+ "input": true,+ "inputButtonTitle": "Send",+ "inputPlaceholder": "Type your reply..."+ }+ """+ let data = json.data(using: .utf8)!+ let action = try JSONDecoder().decode(Action.self, from: data)++ XCTAssertEqual(action.id, "reply")+ XCTAssertEqual(action.title, "Reply")+ XCTAssertEqual(action.requiresAuthentication, true)+ XCTAssertEqual(action.foreground, true)+ XCTAssertEqual(action.destructive, false)+ XCTAssertEqual(action.input, true)+ XCTAssertEqual(action.inputButtonTitle, "Send")+ XCTAssertEqual(action.inputPlaceholder, "Type your reply...")+ }++ func testDestructiveAction() throws {+ let json = """+ {"id": "delete", "title": "Delete", "destructive": true}+ """+ let data = json.data(using: .utf8)!+ let action = try JSONDecoder().decode(Action.self, from: data)++ XCTAssertEqual(action.destructive, true)+ }+}++// MARK: - ActionType Tests++final class ActionTypeTests: XCTestCase {++ func testActionTypeDecoding() throws {+ let json = """+ {+ "id": "message_actions",+ "actions": [+ {"id": "reply", "title": "Reply"},+ {"id": "delete", "title": "Delete", "destructive": true}+ ]+ }+ """+ let data = json.data(using: .utf8)!+ let actionType = try JSONDecoder().decode(ActionType.self, from: data)++ XCTAssertEqual(actionType.id, "message_actions")+ XCTAssertEqual(actionType.actions.count, 2)+ XCTAssertEqual(actionType.actions[0].id, "reply")+ XCTAssertEqual(actionType.actions[1].destructive, true)+ }++ func testActionTypeWithOptions() throws {+ let json = """+ {+ "id": "secure_actions",+ "actions": [{"id": "confirm", "title": "Confirm"}],+ "customDismissAction": true,+ "hiddenPreviewsShowTitle": true+ }+ """+ let data = json.data(using: .utf8)!+ let actionType = try JSONDecoder().decode(ActionType.self, from: data)++ XCTAssertEqual(actionType.customDismissAction, true)+ XCTAssertEqual(actionType.hiddenPreviewsShowTitle, true)+ }+}++// MARK: - CancelArgs Tests++final class CancelArgsTests: XCTestCase {++ func testCancelArgsDecoding() throws {+ let json = """+ {"notifications": [1, 2, 3, 4, 5]}+ """+ let data = json.data(using: .utf8)!+ let args = try JSONDecoder().decode(CancelArgs.self, from: data)++ XCTAssertEqual(args.notifications, [1, 2, 3, 4, 5])+ }++ func testCancelArgsEmptyArray() throws {+ let json = """+ {"notifications": []}+ """+ let data = json.data(using: .utf8)!+ let args = try JSONDecoder().decode(CancelArgs.self, from: data)++ XCTAssertTrue(args.notifications.isEmpty)+ }+}++// MARK: - RemoveActiveArgs Tests++final class RemoveActiveArgsTests: XCTestCase {++ func testRemoveActiveArgsDecoding() throws {+ let json = """+ {"notifications": [{"id": 1}, {"id": 2}, {"id": 3}]}+ """+ let data = json.data(using: .utf8)!+ let args = try JSONDecoder().decode(RemoveActiveArgs.self, from: data)++ XCTAssertEqual(args.notifications.count, 3)+ XCTAssertEqual(args.notifications[0].id, 1)+ XCTAssertEqual(args.notifications[1].id, 2)+ XCTAssertEqual(args.notifications[2].id, 3)+ }+}++// MARK: - SetClickListenerActiveArgs Tests++final class SetClickListenerActiveArgsTests: XCTestCase {++ func testSetClickListenerActiveArgsTrue() throws {+ let json = """+ {"active": true}+ """+ let data = json.data(using: .utf8)!+ let args = try JSONDecoder().decode(SetClickListenerActiveArgs.self, from: data)++ XCTAssertTrue(args.active)+ }++ func testSetClickListenerActiveArgsFalse() throws {+ let json = """+ {"active": false}+ """+ let data = json.data(using: .utf8)!+ let args = try JSONDecoder().decode(SetClickListenerActiveArgs.self, from: data)++ XCTAssertFalse(args.active)+ }+}++// MARK: - Helper Function Tests++final class HelperFunctionTests: XCTestCase {++ // MARK: - getDateComponents Tests++ func testGetDateComponentsFull() {+ let interval = ScheduleInterval(+ year: 2024,+ month: 12,+ day: 25,+ weekday: nil,+ hour: 10,+ minute: 30,+ second: 0+ )++ let components = getDateComponents(interval)++ XCTAssertEqual(components.year, 2024)+ XCTAssertEqual(components.month, 12)+ XCTAssertEqual(components.day, 25)+ XCTAssertEqual(components.hour, 10)+ XCTAssertEqual(components.minute, 30)+ XCTAssertEqual(components.second, 0)+ XCTAssertNil(components.weekday)+ }++ func testGetDateComponentsPartial() {+ let interval = ScheduleInterval(+ year: nil,+ month: nil,+ day: nil,+ weekday: 2,+ hour: 9,+ minute: 0,+ second: nil+ )++ let components = getDateComponents(interval)++ XCTAssertNil(components.year)+ XCTAssertNil(components.month)+ XCTAssertNil(components.day)+ XCTAssertEqual(components.weekday, 2)+ XCTAssertEqual(components.hour, 9)+ XCTAssertEqual(components.minute, 0)+ XCTAssertNil(components.second)+ }++ // MARK: - getRepeatDateInterval Tests++ func testGetRepeatDateIntervalYear() {+ let interval = getRepeatDateInterval(.year, 1)++ XCTAssertNotNil(interval)+ // A year should be roughly 365 days+ let days = interval!.duration / (24 * 60 * 60)+ XCTAssertTrue(days >= 365 && days <= 366)+ }++ func testGetRepeatDateIntervalMonth() {+ let interval = getRepeatDateInterval(.month, 1)++ XCTAssertNotNil(interval)+ // A month is roughly 28-31 days+ let days = interval!.duration / (24 * 60 * 60)+ XCTAssertTrue(days >= 28 && days <= 31)+ }++ func testGetRepeatDateIntervalTwoWeeks() {+ let interval = getRepeatDateInterval(.twoWeeks, 1)++ XCTAssertNotNil(interval)+ let days = interval!.duration / (24 * 60 * 60)+ XCTAssertEqual(days, 14, accuracy: 0.01)+ }++ func testGetRepeatDateIntervalWeek() {+ let interval = getRepeatDateInterval(.week, 1)++ XCTAssertNotNil(interval)+ let days = interval!.duration / (24 * 60 * 60)+ XCTAssertEqual(days, 7, accuracy: 0.01)+ }++ func testGetRepeatDateIntervalDay() {+ let interval = getRepeatDateInterval(.day, 1)++ XCTAssertNotNil(interval)+ let hours = interval!.duration / (60 * 60)+ XCTAssertEqual(hours, 24, accuracy: 0.01)+ }++ func testGetRepeatDateIntervalHour() {+ let interval = getRepeatDateInterval(.hour, 1)++ XCTAssertNotNil(interval)+ let minutes = interval!.duration / 60+ XCTAssertEqual(minutes, 60, accuracy: 0.01)+ }++ func testGetRepeatDateIntervalMinute() {+ let interval = getRepeatDateInterval(.minute, 1)++ XCTAssertNotNil(interval)+ XCTAssertEqual(interval!.duration, 60, accuracy: 0.01)+ }++ func testGetRepeatDateIntervalSecond() {+ let interval = getRepeatDateInterval(.second, 30)++ XCTAssertNotNil(interval)+ XCTAssertEqual(interval!.duration, 30, accuracy: 0.01)+ }++ func testGetRepeatDateIntervalWithCount() {+ let interval = getRepeatDateInterval(.hour, 3)++ XCTAssertNotNil(interval)+ let hours = interval!.duration / (60 * 60)+ XCTAssertEqual(hours, 3, accuracy: 0.01)+ }++ // MARK: - makeActionOptions Tests++ func testMakeActionOptionsForeground() {+ let action = Action(+ id: "test",+ title: "Test",+ requiresAuthentication: nil,+ foreground: true,+ destructive: nil,+ input: nil,+ inputButtonTitle: nil,+ inputPlaceholder: nil+ )++ let options = makeActionOptions(action)+ XCTAssertEqual(options, .foreground)+ }++ func testMakeActionOptionsDestructive() {+ let action = Action(+ id: "test",+ title: "Test",+ requiresAuthentication: nil,+ foreground: nil,+ destructive: true,+ input: nil,+ inputButtonTitle: nil,+ inputPlaceholder: nil+ )++ let options = makeActionOptions(action)+ XCTAssertEqual(options, .destructive)+ }++ func testMakeActionOptionsAuthRequired() {+ let action = Action(+ id: "test",+ title: "Test",+ requiresAuthentication: true,+ foreground: nil,+ destructive: nil,+ input: nil,+ inputButtonTitle: nil,+ inputPlaceholder: nil+ )++ let options = makeActionOptions(action)+ XCTAssertEqual(options, .authenticationRequired)+ }++ func testMakeActionOptionsNone() {+ let action = Action(+ id: "test",+ title: "Test",+ requiresAuthentication: nil,+ foreground: nil,+ destructive: nil,+ input: nil,+ inputButtonTitle: nil,+ inputPlaceholder: nil+ )++ let options = makeActionOptions(action)+ XCTAssertEqual(options.rawValue, 0)+ }++ // MARK: - makeCategoryOptions Tests++ func testMakeCategoryOptionsCustomDismiss() {+ let actionType = ActionType(+ id: "test",+ actions: [],+ hiddenPreviewsBodyPlaceholder: nil,+ customDismissAction: true,+ allowInCarPlay: nil,+ hiddenPreviewsShowTitle: nil,+ hiddenPreviewsShowSubtitle: nil,+ hiddenBodyPlaceholder: nil+ )++ let options = makeCategoryOptions(actionType)+ XCTAssertEqual(options, .customDismissAction)+ }++ func testMakeCategoryOptionsShowTitle() {+ let actionType = ActionType(+ id: "test",+ actions: [],+ hiddenPreviewsBodyPlaceholder: nil,+ customDismissAction: nil,+ allowInCarPlay: nil,+ hiddenPreviewsShowTitle: true,+ hiddenPreviewsShowSubtitle: nil,+ hiddenBodyPlaceholder: nil+ )++ let options = makeCategoryOptions(actionType)+ XCTAssertEqual(options, .hiddenPreviewsShowTitle)+ }++ func testMakeCategoryOptionsShowSubtitle() {+ let actionType = ActionType(+ id: "test",+ actions: [],+ hiddenPreviewsBodyPlaceholder: nil,+ customDismissAction: nil,+ allowInCarPlay: nil,+ hiddenPreviewsShowTitle: nil,+ hiddenPreviewsShowSubtitle: true,+ hiddenBodyPlaceholder: nil+ )++ let options = makeCategoryOptions(actionType)+ XCTAssertEqual(options, .hiddenPreviewsShowSubtitle)+ }++ func testMakeCategoryOptionsNone() {+ let actionType = ActionType(+ id: "test",+ actions: [],+ hiddenPreviewsBodyPlaceholder: nil,+ customDismissAction: nil,+ allowInCarPlay: nil,+ hiddenPreviewsShowTitle: nil,+ hiddenPreviewsShowSubtitle: nil,+ hiddenBodyPlaceholder: nil+ )++ let options = makeCategoryOptions(actionType)+ XCTAssertEqual(options.rawValue, 0)+ }++ // MARK: - makeActions Tests++ func testMakeActionsBasic() {+ let actions = [+ Action(+ id: "accept",+ title: "Accept",+ requiresAuthentication: nil,+ foreground: true,+ destructive: nil,+ input: nil,+ inputButtonTitle: nil,+ inputPlaceholder: nil+ ),+ Action(+ id: "decline",+ title: "Decline",+ requiresAuthentication: nil,+ foreground: nil,+ destructive: true,+ input: nil,+ inputButtonTitle: nil,+ inputPlaceholder: nil+ )+ ]++ let unActions = makeActions(actions)++ XCTAssertEqual(unActions.count, 2)+ XCTAssertEqual(unActions[0].identifier, "accept")+ XCTAssertEqual(unActions[0].title, "Accept")+ XCTAssertEqual(unActions[1].identifier, "decline")+ XCTAssertEqual(unActions[1].title, "Decline")+ }++ func testMakeActionsWithInput() {+ let actions = [+ Action(+ id: "reply",+ title: "Reply",+ requiresAuthentication: nil,+ foreground: nil,+ destructive: nil,+ input: true,+ inputButtonTitle: "Send",+ inputPlaceholder: "Type here..."+ )+ ]++ let unActions = makeActions(actions)++ XCTAssertEqual(unActions.count, 1)+ XCTAssertTrue(unActions[0] is UNTextInputNotificationAction)++ let textAction = unActions[0] as! UNTextInputNotificationAction+ XCTAssertEqual(textAction.identifier, "reply")+ XCTAssertEqual(textAction.textInputButtonTitle, "Send")+ XCTAssertEqual(textAction.textInputPlaceholder, "Type here...")+ }++ func testMakeActionsEmptyArray() {+ let actions: [Action] = []+ let unActions = makeActions(actions)+ XCTAssertTrue(unActions.isEmpty)+ }++ // MARK: - makeAttachmentUrl Tests++ func testMakeAttachmentUrlValid() {+ let url = makeAttachmentUrl("file:///path/to/image.png")+ XCTAssertNotNil(url)+ XCTAssertEqual(url?.scheme, "file")+ }++ func testMakeAttachmentUrlHttp() {+ let url = makeAttachmentUrl("https://example.com/image.png")+ XCTAssertNotNil(url)+ XCTAssertEqual(url?.scheme, "https")+ }++ // MARK: - makeAttachmentOptions Tests++ func testMakeAttachmentOptionsWithTypeHint() {+ let options = NotificationAttachmentOptions(+ iosUNNotificationAttachmentOptionsTypeHintKey: "public.png",+ iosUNNotificationAttachmentOptionsThumbnailHiddenKey: nil,+ iosUNNotificationAttachmentOptionsThumbnailClippingRectKey: nil,+ iosUNNotificationAttachmentOptionsThumbnailTimeKey: nil+ )++ let result = makeAttachmentOptions(options)+ XCTAssertEqual(result[UNNotificationAttachmentOptionsTypeHintKey] as? String, "public.png")+ }++ func testMakeAttachmentOptionsEmpty() {+ let options = NotificationAttachmentOptions(+ iosUNNotificationAttachmentOptionsTypeHintKey: nil,+ iosUNNotificationAttachmentOptionsThumbnailHiddenKey: nil,+ iosUNNotificationAttachmentOptionsThumbnailClippingRectKey: nil,+ iosUNNotificationAttachmentOptionsThumbnailTimeKey: nil+ )++ let result = makeAttachmentOptions(options)+ XCTAssertTrue(result.isEmpty)+ }+}++// MARK: - NotificationContent Tests++final class NotificationContentTests: XCTestCase {++ func testMakeNotificationContentBasic() throws {+ let notification = makeTestNotification(title: "Test Title", body: "Test Body")++ let content = try makeNotificationContent(notification)++ XCTAssertEqual(content.title, "Test Title")+ XCTAssertEqual(content.body, "Test Body")+ }++ func testMakeNotificationContentWithExtra() throws {+ let notification = makeTestNotification(+ extra: ["key1": "value1", "key2": "value2"]+ )++ let content = try makeNotificationContent(notification)++ XCTAssertEqual(content.userInfo["key1"] as? String, "value1")+ XCTAssertEqual(content.userInfo["key2"] as? String, "value2")+ }++ func testMakeNotificationContentWithActionType() throws {+ let notification = makeTestNotification(actionTypeId: "message_actions")++ let content = try makeNotificationContent(notification)++ XCTAssertEqual(content.categoryIdentifier, "message_actions")+ }++ func testMakeNotificationContentWithGroup() throws {+ let notification = makeTestNotification(group: "messages")++ let content = try makeNotificationContent(notification)++ XCTAssertEqual(content.threadIdentifier, "messages")+ }++ func testMakeNotificationContentWithSound() throws {+ let notification = makeTestNotification(sound: "custom_sound.wav")++ let content = try makeNotificationContent(notification)++ XCTAssertNotNil(content.sound)+ }++ func testMakeNotificationContentWithoutBody() throws {+ let notification = makeTestNotification(body: nil)++ let content = try makeNotificationContent(notification)++ XCTAssertEqual(content.title, "Test Title")+ XCTAssertEqual(content.body, "")+ }+}++// MARK: - handleScheduledNotification Tests++final class ScheduleHandlerTests: XCTestCase {++ func testHandleScheduledNotificationEveryHour() throws {+ let schedule = NotificationSchedule.every(interval: .hour, count: 2)++ let trigger = try handleScheduledNotification(schedule)++ XCTAssertNotNil(trigger)+ XCTAssertTrue(trigger is UNTimeIntervalNotificationTrigger)++ let timeTrigger = trigger as! UNTimeIntervalNotificationTrigger+ XCTAssertTrue(timeTrigger.repeats)+ // 2 hours = 7200 seconds+ XCTAssertEqual(timeTrigger.timeInterval, 7200, accuracy: 1)+ }++ func testHandleScheduledNotificationEveryDay() throws {+ let schedule = NotificationSchedule.every(interval: .day, count: 1)++ let trigger = try handleScheduledNotification(schedule)++ XCTAssertNotNil(trigger)+ XCTAssertTrue(trigger is UNTimeIntervalNotificationTrigger)++ let timeTrigger = trigger as! UNTimeIntervalNotificationTrigger+ XCTAssertTrue(timeTrigger.repeats)+ // 1 day = 86400 seconds+ XCTAssertEqual(timeTrigger.timeInterval, 86400, accuracy: 1)+ }++ func testHandleScheduledNotificationInterval() throws {+ let interval = ScheduleInterval(+ year: nil,+ month: nil,+ day: nil,+ weekday: nil,+ hour: 9,+ minute: 30,+ second: nil+ )+ let schedule = NotificationSchedule.interval(interval: interval)++ let trigger = try handleScheduledNotification(schedule)++ XCTAssertNotNil(trigger)+ XCTAssertTrue(trigger is UNCalendarNotificationTrigger)++ let calendarTrigger = trigger as! UNCalendarNotificationTrigger+ XCTAssertTrue(calendarTrigger.repeats)+ XCTAssertEqual(calendarTrigger.dateComponents.hour, 9)+ XCTAssertEqual(calendarTrigger.dateComponents.minute, 30)+ }++ func testHandleScheduledNotificationTooShortInterval() throws {+ // 30 seconds is less than 60 seconds minimum+ let schedule = NotificationSchedule.every(interval: .second, count: 30)++ XCTAssertThrowsError(try handleScheduledNotification(schedule)) { error in+ XCTAssertTrue(error is NotificationError)+ if case NotificationError.triggerRepeatIntervalTooShort = error {+ // Expected+ } else {+ XCTFail("Expected triggerRepeatIntervalTooShort error")+ }+ }+ }++ func testHandleScheduledNotificationAtFutureDate() throws {+ let futureDate = Calendar.current.date(byAdding: .hour, value: 1, to: Date())!+ let dateFormatter = DateFormatter()+ dateFormatter.locale = Locale(identifier: "en_US_POSIX")+ dateFormatter.timeZone = TimeZone(secondsFromGMT: 0)+ dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"+ let dateString = dateFormatter.string(from: futureDate)++ let schedule = NotificationSchedule.at(date: dateString, repeating: false)++ let trigger = try handleScheduledNotification(schedule)++ XCTAssertNotNil(trigger)+ XCTAssertTrue(trigger is UNTimeIntervalNotificationTrigger)++ let timeTrigger = trigger as! UNTimeIntervalNotificationTrigger+ XCTAssertFalse(timeTrigger.repeats)+ // Should be roughly 3600 seconds (1 hour)+ XCTAssertTrue(timeTrigger.timeInterval > 3500 && timeTrigger.timeInterval < 3700)+ }++ func testHandleScheduledNotificationAtPastDate() throws {+ let pastDate = Calendar.current.date(byAdding: .hour, value: -1, to: Date())!+ let dateFormatter = DateFormatter()+ dateFormatter.locale = Locale(identifier: "en_US_POSIX")+ dateFormatter.timeZone = TimeZone(secondsFromGMT: 0)+ dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"+ let dateString = dateFormatter.string(from: pastDate)++ let schedule = NotificationSchedule.at(date: dateString, repeating: false)++ XCTAssertThrowsError(try handleScheduledNotification(schedule)) { error in+ XCTAssertTrue(error is NotificationError)+ if case NotificationError.pastScheduledTime = error {+ // Expected+ } else {+ XCTFail("Expected pastScheduledTime error")+ }+ }+ }++ func testHandleScheduledNotificationInvalidDate() throws {+ let schedule = NotificationSchedule.at(date: "invalid-date", repeating: false)++ XCTAssertThrowsError(try handleScheduledNotification(schedule)) { error in+ XCTAssertTrue(error is NotificationError)+ if case NotificationError.invalidDate(_) = error {+ // Expected+ } else {+ XCTFail("Expected invalidDate error")+ }+ }+ }++ func testHandleScheduledNotificationRepeatingTooShort() throws {+ // Create a date just 30 seconds in the future with repeating+ let futureDate = Calendar.current.date(byAdding: .second, value: 30, to: Date())!+ let dateFormatter = DateFormatter()+ dateFormatter.locale = Locale(identifier: "en_US_POSIX")+ dateFormatter.timeZone = TimeZone(secondsFromGMT: 0)+ dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"+ let dateString = dateFormatter.string(from: futureDate)++ let schedule = NotificationSchedule.at(date: dateString, repeating: true)++ XCTAssertThrowsError(try handleScheduledNotification(schedule)) { error in+ XCTAssertTrue(error is NotificationError)+ if case NotificationError.triggerRepeatIntervalTooShort = error {+ // Expected+ } else {+ XCTFail("Expected triggerRepeatIntervalTooShort error")+ }+ }+ }+}++// MARK: - NotificationError Tests++final class NotificationErrorTests: XCTestCase {++ func testErrorDescriptions() {+ XCTAssertEqual(+ NotificationError.triggerRepeatIntervalTooShort.errorDescription,+ "Schedule interval too short, must be a least 1 minute"+ )++ XCTAssertEqual(+ NotificationError.attachmentFileNotFound(path: "/path/to/file").errorDescription,+ "Unable to find file /path/to/file for attachment"+ )++ XCTAssertEqual(+ NotificationError.attachmentUnableToCreate("some error").errorDescription,+ "Failed to create attachment: some error"+ )++ XCTAssertEqual(+ NotificationError.pastScheduledTime.errorDescription,+ "Scheduled time must be *after* current time"+ )++ XCTAssertEqual(+ NotificationError.invalidDate("bad-date").errorDescription,+ "Could not parse date bad-date"+ )+ }+}++// MARK: - Plugin Initialization Tests+// Note: Some plugin tests require a full application environment with notification center access.+// Tests that crash in pure unit test environments are skipped.++final class PluginTests: XCTestCase {+ var plugin: NotificationPlugin?++ override func setUp() {+ super.setUp()+ // Plugin initialization may fail in pure unit test environment+ // We'll handle this gracefully+ }++ override func tearDown() {+ plugin = nil+ super.tearDown()+ }++ private func getPlugin() throws -> NotificationPlugin {+ if plugin == nil {+ plugin = initPlugin()+ }+ return try XCTUnwrap(plugin)+ }++ func testPluginInitialization() throws {+ // Skip in environments where notification center isn't available+ throw XCTSkip("Plugin initialization requires a full application environment")+ }++ func testCheckPermissionsReturnsValidJSON() async throws {+ // Skip in environments where notification center isn't available+ throw XCTSkip("Requires notification center access")+ }++ func testCancelWithValidArgs() throws {+ // Skip in environments where notification center isn't available+ throw XCTSkip("Requires notification center access")+ }++ func testCancelWithEmptyArray() throws {+ // Skip in environments where notification center isn't available+ throw XCTSkip("Requires notification center access")+ }++ func testCancelAllDoesNotThrow() throws {+ // Skip in environments where notification center isn't available+ throw XCTSkip("Requires notification center access")+ }++ func testRegisterActionTypesWithValidArgs() throws {+ // Skip in environments where notification center isn't available+ throw XCTSkip("Requires notification center access")+ }++ func testRegisterActionTypesWithEmptyTypes() throws {+ // Skip in environments where notification center isn't available+ throw XCTSkip("Requires notification center access")+ }++ func testRemoveActiveWithValidArgs() throws {+ // Skip in environments where notification center isn't available+ throw XCTSkip("Requires notification center access")+ }++ func testRemoveAllActiveDoesNotThrow() throws {+ // Skip in environments where notification center isn't available+ throw XCTSkip("Requires notification center access")+ }++ func testSetClickListenerActiveTrue() throws {+ // Skip in environments where notification center isn't available+ throw XCTSkip("Requires notification center access")+ }++ func testSetClickListenerActiveFalse() throws {+ // Skip in environments where notification center isn't available+ throw XCTSkip("Requires notification center access")+ }++ func testGetPendingReturnsValidJSON() async throws {+ // Skip in environments where notification center isn't available+ throw XCTSkip("Requires notification center access")+ }++ func testGetActiveReturnsValidJSON() async throws {+ // Skip in environments where notification center isn't available+ throw XCTSkip("Requires notification center access")+ }+}++// MARK: - RustString Extension Tests++final class RustStringExtensionTests: XCTestCase {++ func testDecodeValidJSON() throws {+ let rustString = RustString("{\"notifications\": [1, 2, 3]}")+ let result = try rustString.decode(CancelArgs.self)+ XCTAssertEqual(result.notifications, [1, 2, 3])+ }++ func testDecodeInvalidJSON() {+ let rustString = RustString("invalid json")++ do {+ _ = try rustString.decode(CancelArgs.self)+ XCTFail("Should have thrown an error")+ } catch {+ // Expected+ XCTAssertTrue(error is FFIResult)+ }+ }++ func testDecodeComplexType() throws {+ let json = """+ {+ "types": [+ {+ "id": "msg",+ "actions": [+ {"id": "reply", "title": "Reply", "input": true}+ ]+ }+ ]+ }+ """+ let rustString = RustString(json)+ let result = try rustString.decode(RegisterActionTypesArgs.self)++ XCTAssertEqual(result.types.count, 1)+ XCTAssertEqual(result.types[0].id, "msg")+ XCTAssertEqual(result.types[0].actions[0].input, true)+ }+}++// MARK: - Encodable Extension Tests++final class EncodableExtensionTests: XCTestCase {++ func testActiveNotificationToJSON() throws {+ let notification = ActiveNotification(+ id: 123,+ title: "Test",+ body: "Body",+ sound: "default",+ actionTypeId: "actions",+ attachments: nil+ )++ let jsonString = try notification.toJSONString()+ let data = try XCTUnwrap(jsonString.data(using: .utf8))+ let json = try JSONSerialization.jsonObject(with: data) as! [String: Any]++ XCTAssertEqual(json["id"] as? Int, 123)+ XCTAssertEqual(json["title"] as? String, "Test")+ XCTAssertEqual(json["body"] as? String, "Body")+ XCTAssertEqual(json["sound"] as? String, "default")+ XCTAssertEqual(json["actionTypeId"] as? String, "actions")+ }++ func testPendingNotificationToJSON() throws {+ let notification = PendingNotification(+ id: 456,+ title: "Pending",+ body: "Pending body",+ schedule: .every(interval: .hour, count: 1)+ )++ let jsonString = try notification.toJSONString()+ let data = try XCTUnwrap(jsonString.data(using: .utf8))+ let json = try JSONSerialization.jsonObject(with: data) as! [String: Any]++ XCTAssertEqual(json["id"] as? Int, 456)+ XCTAssertEqual(json["title"] as? String, "Pending")+ }++ func testNotificationClickedDataToJSON() throws {+ let clickedData = NotificationClickedData(+ id: 789,+ data: ["action": "tap", "source": "notification"]+ )++ let jsonString = try clickedData.toJSONString()+ let data = try XCTUnwrap(jsonString.data(using: .utf8))+ let json = try JSONSerialization.jsonObject(with: data) as! [String: Any]++ XCTAssertEqual(json["id"] as? Int, 789)+ let dataDict = json["data"] as? [String: String]+ XCTAssertEqual(dataDict?["action"], "tap")+ XCTAssertEqual(dataDict?["source"], "notification")+ }++ func testReceivedNotificationDataToJSON() throws {+ let receivedData = ReceivedNotificationData(+ id: 101,+ title: "Push",+ body: "Push body",+ extra: ["key": "value"]+ )++ let jsonString = try receivedData.toJSONString()+ let data = try XCTUnwrap(jsonString.data(using: .utf8))+ let json = try JSONSerialization.jsonObject(with: data) as! [String: Any]++ XCTAssertEqual(json["id"] as? Int, 101)+ XCTAssertEqual(json["title"] as? String, "Push")+ XCTAssertEqual(json["body"] as? String, "Push body")+ let extra = json["extra"] as? [String: String]+ XCTAssertEqual(extra?["key"], "value")+ }++ func testArrayToJSON() throws {+ let notifications = [+ ActiveNotification(id: 1, title: "First", body: "Body 1", sound: "", actionTypeId: "", attachments: nil),+ ActiveNotification(id: 2, title: "Second", body: "Body 2", sound: "", actionTypeId: "", attachments: nil)+ ]++ let jsonString = try notifications.toJSONString()+ let data = try XCTUnwrap(jsonString.data(using: .utf8))+ let json = try JSONSerialization.jsonObject(with: data) as! [[String: Any]]++ XCTAssertEqual(json.count, 2)+ XCTAssertEqual(json[0]["id"] as? Int, 1)+ XCTAssertEqual(json[1]["id"] as? Int, 2)+ }+}++// MARK: - NotificationHandler Tests++final class NotificationHandlerTests: XCTestCase {+ var handler: NotificationHandler!++ override func setUp() {+ super.setUp()+ handler = NotificationHandler()+ }++ override func tearDown() {+ handler = nil+ super.tearDown()+ }++ func testSaveAndRetrieveNotification() {+ let notification = makeTestNotification(id: 123, title: "Saved", body: "Body")+ handler.saveNotification("123", notification)++ // Create a mock request to test retrieval+ let content = UNMutableNotificationContent()+ content.title = "Saved"+ content.body = "Body"+ let request = UNNotificationRequest(identifier: "123", content: content, trigger: nil)++ let activeNotification = handler.toActiveNotification(request)+ XCTAssertNotNil(activeNotification)+ XCTAssertEqual(activeNotification?.id, 123)+ XCTAssertEqual(activeNotification?.title, "Saved")+ }++ func testToActiveNotificationReturnsNilForUnknown() {+ let content = UNMutableNotificationContent()+ content.title = "Unknown"+ let request = UNNotificationRequest(identifier: "unknown_id", content: content, trigger: nil)++ let activeNotification = handler.toActiveNotification(request)+ XCTAssertNil(activeNotification)+ }++ func testToPendingNotificationReturnsNilForUnknown() {+ let content = UNMutableNotificationContent()+ content.title = "Unknown"+ let request = UNNotificationRequest(identifier: "unknown_id", content: content, trigger: nil)++ let pendingNotification = handler.toPendingNotification(request)+ XCTAssertNil(pendingNotification)+ }++ func testToPendingNotificationWithSchedule() {+ let schedule = NotificationSchedule.every(interval: .hour, count: 1)+ let notification = makeTestNotification(id: 456, title: "Scheduled", schedule: schedule)+ handler.saveNotification("456", notification)++ let content = UNMutableNotificationContent()+ content.title = "Scheduled"+ let request = UNNotificationRequest(identifier: "456", content: content, trigger: nil)++ let pendingNotification = handler.toPendingNotification(request)+ XCTAssertNotNil(pendingNotification)+ XCTAssertEqual(pendingNotification?.id, 456)+ XCTAssertEqual(pendingNotification?.title, "Scheduled")+ }++ func testSetClickListenerActive() {+ // Initially false+ handler.setClickListenerActive(true)+ // Should not crash and store the state++ handler.setClickListenerActive(false)+ // Should not crash+ }+}diff --git a/src-tauri/vendor/tauri-plugin-notifications/permissions/autogenerated/commands/batch.toml b/src-tauri/vendor/tauri-plugin-notifications/permissions/autogenerated/commands/batch.tomlnew file mode 100644index 00000000..c52cc16d--- /dev/null+++ b/src-tauri/vendor/tauri-plugin-notifications/permissions/autogenerated/commands/batch.toml@@ -0,0 +1,13 @@+# Automatically generated - DO NOT EDIT!++"$schema" = "../../schemas/schema.json"++[[permission]]+identifier = "allow-batch"+description = "Enables the batch command without any pre-configured scope."+commands.allow = ["batch"]++[[permission]]+identifier = "deny-batch"+description = "Denies the batch command without any pre-configured scope."+commands.deny = ["batch"]diff --git a/src-tauri/vendor/tauri-plugin-notifications/permissions/autogenerated/commands/cancel.toml b/src-tauri/vendor/tauri-plugin-notifications/permissions/autogenerated/commands/cancel.tomlnew file mode 100644index 00000000..91efeaa0--- /dev/null+++ b/src-tauri/vendor/tauri-plugin-notifications/permissions/autogenerated/commands/cancel.toml@@ -0,0 +1,13 @@+# Automatically generated - DO NOT EDIT!++"$schema" = "../../schemas/schema.json"++[[permission]]+identifier = "allow-cancel"+description = "Enables the cancel command without any pre-configured scope."+commands.allow = ["cancel"]++[[permission]]+identifier = "deny-cancel"+description = "Denies the cancel command without any pre-configured scope."+commands.deny = ["cancel"]diff --git a/src-tauri/vendor/tauri-plugin-notifications/permissions/autogenerated/commands/cancel_all.toml b/src-tauri/vendor/tauri-plugin-notifications/permissions/autogenerated/commands/cancel_all.tomlnew file mode 100644index 00000000..4282d003--- /dev/null+++ b/src-tauri/vendor/tauri-plugin-notifications/permissions/autogenerated/commands/cancel_all.toml@@ -0,0 +1,13 @@+# Automatically generated - DO NOT EDIT!++"$schema" = "../../schemas/schema.json"++[[permission]]+identifier = "allow-cancel-all"+description = "Enables the cancel_all command without any pre-configured scope."+commands.allow = ["cancel_all"]++[[permission]]+identifier = "deny-cancel-all"+description = "Denies the cancel_all command without any pre-configured scope."+commands.deny = ["cancel_all"]diff --git a/src-tauri/vendor/tauri-plugin-notifications/permissions/autogenerated/commands/check_permissions.toml b/src-tauri/vendor/tauri-plugin-notifications/permissions/autogenerated/commands/check_permissions.tomlnew file mode 100644index 00000000..f5af08b1--- /dev/null+++ b/src-tauri/vendor/tauri-plugin-notifications/permissions/autogenerated/commands/check_permissions.toml@@ -0,0 +1,13 @@+# Automatically generated - DO NOT EDIT!++"$schema" = "../../schemas/schema.json"++[[permission]]+identifier = "allow-check-permissions"+description = "Enables the check_permissions command without any pre-configured scope."+commands.allow = ["check_permissions"]++[[permission]]+identifier = "deny-check-permissions"+description = "Denies the check_permissions command without any pre-configured scope."+commands.deny = ["check_permissions"]diff --git a/src-tauri/vendor/tauri-plugin-notifications/permissions/autogenerated/commands/create_channel.toml b/src-tauri/vendor/tauri-plugin-notifications/permissions/autogenerated/commands/create_channel.tomlnew file mode 100644index 00000000..2c931474--- /dev/null+++ b/src-tauri/vendor/tauri-plugin-notifications/permissions/autogenerated/commands/create_channel.toml@@ -0,0 +1,13 @@+# Automatically generated - DO NOT EDIT!++"$schema" = "../../schemas/schema.json"++[[permission]]+identifier = "allow-create-channel"+description = "Enables the create_channel command without any pre-configured scope."+commands.allow = ["create_channel"]++[[permission]]+identifier = "deny-create-channel"+description = "Denies the create_channel command without any pre-configured scope."+commands.deny = ["create_channel"]diff --git a/src-tauri/vendor/tauri-plugin-notifications/permissions/autogenerated/commands/delete_channel.toml b/src-tauri/vendor/tauri-plugin-notifications/permissions/autogenerated/commands/delete_channel.tomlnew file mode 100644index 00000000..0adaf2bb--- /dev/null+++ b/src-tauri/vendor/tauri-plugin-notifications/permissions/autogenerated/commands/delete_channel.toml@@ -0,0 +1,13 @@+# Automatically generated - DO NOT EDIT!++"$schema" = "../../schemas/schema.json"++[[permission]]+identifier = "allow-delete-channel"+description = "Enables the delete_channel command without any pre-configured scope."+commands.allow = ["delete_channel"]++[[permission]]+identifier = "deny-delete-channel"+description = "Denies the delete_channel command without any pre-configured scope."+commands.deny = ["delete_channel"]diff --git a/src-tauri/vendor/tauri-plugin-notifications/permissions/autogenerated/commands/get_active.toml b/src-tauri/vendor/tauri-plugin-notifications/permissions/autogenerated/commands/get_active.tomlnew file mode 100644index 00000000..b841eb85--- /dev/null+++ b/src-tauri/vendor/tauri-plugin-notifications/permissions/autogenerated/commands/get_active.toml@@ -0,0 +1,13 @@+# Automatically generated - DO NOT EDIT!++"$schema" = "../../schemas/schema.json"++[[permission]]+identifier = "allow-get-active"+description = "Enables the get_active command without any pre-configured scope."+commands.allow = ["get_active"]++[[permission]]+identifier = "deny-get-active"+description = "Denies the get_active command without any pre-configured scope."+commands.deny = ["get_active"]diff --git a/src-tauri/vendor/tauri-plugin-notifications/permissions/autogenerated/commands/get_pending.toml b/src-tauri/vendor/tauri-plugin-notifications/permissions/autogenerated/commands/get_pending.tomlnew file mode 100644index 00000000..f3bae7a8--- /dev/null+++ b/src-tauri/vendor/tauri-plugin-notifications/permissions/autogenerated/commands/get_pending.toml@@ -0,0 +1,13 @@+# Automatically generated - DO NOT EDIT!++"$schema" = "../../schemas/schema.json"++[[permission]]+identifier = "allow-get-pending"+description = "Enables the get_pending command without any pre-configured scope."+commands.allow = ["get_pending"]++[[permission]]+identifier = "deny-get-pending"+description = "Denies the get_pending command without any pre-configured scope."+commands.deny = ["get_pending"]diff --git a/src-tauri/vendor/tauri-plugin-notifications/permissions/autogenerated/commands/is_permission_granted.toml b/src-tauri/vendor/tauri-plugin-notifications/permissions/autogenerated/commands/is_permission_granted.tomlnew file mode 100644index 00000000..5faa73f3--- /dev/null+++ b/src-tauri/vendor/tauri-plugin-notifications/permissions/autogenerated/commands/is_permission_granted.toml@@ -0,0 +1,13 @@+# Automatically generated - DO NOT EDIT!++"$schema" = "../../schemas/schema.json"++[[permission]]+identifier = "allow-is-permission-granted"+description = "Enables the is_permission_granted command without any pre-configured scope."+commands.allow = ["is_permission_granted"]++[[permission]]+identifier = "deny-is-permission-granted"+description = "Denies the is_permission_granted command without any pre-configured scope."+commands.deny = ["is_permission_granted"]diff --git a/src-tauri/vendor/tauri-plugin-notifications/permissions/autogenerated/commands/list_channels.toml b/src-tauri/vendor/tauri-plugin-notifications/permissions/autogenerated/commands/list_channels.tomlnew file mode 100644index 00000000..cb20cd57--- /dev/null+++ b/src-tauri/vendor/tauri-plugin-notifications/permissions/autogenerated/commands/list_channels.toml@@ -0,0 +1,13 @@+# Automatically generated - DO NOT EDIT!++"$schema" = "../../schemas/schema.json"++[[permission]]+identifier = "allow-list-channels"+description = "Enables the list_channels command without any pre-configured scope."+commands.allow = ["list_channels"]++[[permission]]+identifier = "deny-list-channels"+description = "Denies the list_channels command without any pre-configured scope."+commands.deny = ["list_channels"]diff --git a/src-tauri/vendor/tauri-plugin-notifications/permissions/autogenerated/commands/list_distributors.toml b/src-tauri/vendor/tauri-plugin-notifications/permissions/autogenerated/commands/list_distributors.tomlnew file mode 100644index 00000000..cc8f822b--- /dev/null+++ b/src-tauri/vendor/tauri-plugin-notifications/permissions/autogenerated/commands/list_distributors.toml@@ -0,0 +1,13 @@+# Automatically generated - DO NOT EDIT!++"$schema" = "../../schemas/schema.json"++[[permission]]+identifier = "allow-list-distributors"+description = "Enables the list_distributors command without any pre-configured scope."+commands.allow = ["list_distributors"]++[[permission]]+identifier = "deny-list-distributors"+description = "Denies the list_distributors command without any pre-configured scope."+commands.deny = ["list_distributors"]diff --git a/src-tauri/vendor/tauri-plugin-notifications/permissions/autogenerated/commands/notify.toml b/src-tauri/vendor/tauri-plugin-notifications/permissions/autogenerated/commands/notify.tomlnew file mode 100644index 00000000..7d6d46c2--- /dev/null+++ b/src-tauri/vendor/tauri-plugin-notifications/permissions/autogenerated/commands/notify.toml@@ -0,0 +1,13 @@+# Automatically generated - DO NOT EDIT!++"$schema" = "../../schemas/schema.json"++[[permission]]+identifier = "allow-notify"+description = "Enables the notify command without any pre-configured scope."+commands.allow = ["notify"]++[[permission]]+identifier = "deny-notify"+description = "Denies the notify command without any pre-configured scope."+commands.deny = ["notify"]diff --git a/src-tauri/vendor/tauri-plugin-notifications/permissions/autogenerated/commands/permission_state.toml b/src-tauri/vendor/tauri-plugin-notifications/permissions/autogenerated/commands/permission_state.tomlnew file mode 100644index 00000000..dddcd86f--- /dev/null+++ b/src-tauri/vendor/tauri-plugin-notifications/permissions/autogenerated/commands/permission_state.toml@@ -0,0 +1,13 @@+# Automatically generated - DO NOT EDIT!++"$schema" = "../../schemas/schema.json"++[[permission]]+identifier = "allow-permission-state"+description = "Enables the permission_state command without any pre-configured scope."+commands.allow = ["permission_state"]++[[permission]]+identifier = "deny-permission-state"+description = "Denies the permission_state command without any pre-configured scope."+commands.deny = ["permission_state"]diff --git a/src-tauri/vendor/tauri-plugin-notifications/permissions/autogenerated/commands/register_action_types.toml b/src-tauri/vendor/tauri-plugin-notifications/permissions/autogenerated/commands/register_action_types.tomlnew file mode 100644index 00000000..cb5aa89f--- /dev/null+++ b/src-tauri/vendor/tauri-plugin-notifications/permissions/autogenerated/commands/register_action_types.toml@@ -0,0 +1,13 @@+# Automatically generated - DO NOT EDIT!++"$schema" = "../../schemas/schema.json"++[[permission]]+identifier = "allow-register-action-types"+description = "Enables the register_action_types command without any pre-configured scope."+commands.allow = ["register_action_types"]++[[permission]]+identifier = "deny-register-action-types"+description = "Denies the register_action_types command without any pre-configured scope."+commands.deny = ["register_action_types"]diff --git a/src-tauri/vendor/tauri-plugin-notifications/permissions/autogenerated/commands/register_for_push_notifications.toml b/src-tauri/vendor/tauri-plugin-notifications/permissions/autogenerated/commands/register_for_push_notifications.tomlnew file mode 100644index 00000000..6507a805--- /dev/null+++ b/src-tauri/vendor/tauri-plugin-notifications/permissions/autogenerated/commands/register_for_push_notifications.toml@@ -0,0 +1,13 @@+# Automatically generated - DO NOT EDIT!++"$schema" = "../../schemas/schema.json"++[[permission]]+identifier = "allow-register-for-push-notifications"+description = "Enables the register_for_push_notifications command without any pre-configured scope."+commands.allow = ["register_for_push_notifications"]++[[permission]]+identifier = "deny-register-for-push-notifications"+description = "Denies the register_for_push_notifications command without any pre-configured scope."+commands.deny = ["register_for_push_notifications"]diff --git a/src-tauri/vendor/tauri-plugin-notifications/permissions/autogenerated/commands/register_listener.toml b/src-tauri/vendor/tauri-plugin-notifications/permissions/autogenerated/commands/register_listener.tomlnew file mode 100644index 00000000..48363c0d--- /dev/null+++ b/src-tauri/vendor/tauri-plugin-notifications/permissions/autogenerated/commands/register_listener.toml@@ -0,0 +1,13 @@+# Automatically generated - DO NOT EDIT!++"$schema" = "../../schemas/schema.json"++[[permission]]+identifier = "allow-register-listener"+description = "Enables the register_listener command without any pre-configured scope."+commands.allow = ["register_listener"]++[[permission]]+identifier = "deny-register-listener"+description = "Denies the register_listener command without any pre-configured scope."+commands.deny = ["register_listener"]diff --git a/src-tauri/vendor/tauri-plugin-notifications/permissions/autogenerated/commands/remove_active.toml b/src-tauri/vendor/tauri-plugin-notifications/permissions/autogenerated/commands/remove_active.tomlnew file mode 100644index 00000000..9ad2add1--- /dev/null+++ b/src-tauri/vendor/tauri-plugin-notifications/permissions/autogenerated/commands/remove_active.toml@@ -0,0 +1,13 @@+# Automatically generated - DO NOT EDIT!++"$schema" = "../../schemas/schema.json"++[[permission]]+identifier = "allow-remove-active"+description = "Enables the remove_active command without any pre-configured scope."+commands.allow = ["remove_active"]++[[permission]]+identifier = "deny-remove-active"+description = "Denies the remove_active command without any pre-configured scope."+commands.deny = ["remove_active"]diff --git a/src-tauri/vendor/tauri-plugin-notifications/permissions/autogenerated/commands/remove_all.toml b/src-tauri/vendor/tauri-plugin-notifications/permissions/autogenerated/commands/remove_all.tomlnew file mode 100644index 00000000..6443ac0f--- /dev/null+++ b/src-tauri/vendor/tauri-plugin-notifications/permissions/autogenerated/commands/remove_all.toml@@ -0,0 +1,13 @@+# Automatically generated - DO NOT EDIT!++"$schema" = "../../schemas/schema.json"++[[permission]]+identifier = "allow-remove-all"+description = "Enables the remove_all command without any pre-configured scope."+commands.allow = ["remove_all"]++[[permission]]+identifier = "deny-remove-all"+description = "Denies the remove_all command without any pre-configured scope."+commands.deny = ["remove_all"]diff --git a/src-tauri/vendor/tauri-plugin-notifications/permissions/autogenerated/commands/remove_listener.toml b/src-tauri/vendor/tauri-plugin-notifications/permissions/autogenerated/commands/remove_listener.tomlnew file mode 100644index 00000000..9f315e51--- /dev/null+++ b/src-tauri/vendor/tauri-plugin-notifications/permissions/autogenerated/commands/remove_listener.toml@@ -0,0 +1,13 @@+# Automatically generated - DO NOT EDIT!++"$schema" = "../../schemas/schema.json"++[[permission]]+identifier = "allow-remove-listener"+description = "Enables the remove_listener command without any pre-configured scope."+commands.allow = ["remove_listener"]++[[permission]]+identifier = "deny-remove-listener"+description = "Denies the remove_listener command without any pre-configured scope."+commands.deny = ["remove_listener"]diff --git a/src-tauri/vendor/tauri-plugin-notifications/permissions/autogenerated/commands/request_permission.toml b/src-tauri/vendor/tauri-plugin-notifications/permissions/autogenerated/commands/request_permission.tomlnew file mode 100644index 00000000..0b410d6a--- /dev/null+++ b/src-tauri/vendor/tauri-plugin-notifications/permissions/autogenerated/commands/request_permission.toml@@ -0,0 +1,13 @@+# Automatically generated - DO NOT EDIT!++"$schema" = "../../schemas/schema.json"++[[permission]]+identifier = "allow-request-permission"+description = "Enables the request_permission command without any pre-configured scope."+commands.allow = ["request_permission"]++[[permission]]+identifier = "deny-request-permission"+description = "Denies the request_permission command without any pre-configured scope."+commands.deny = ["request_permission"]diff --git a/src-tauri/vendor/tauri-plugin-notifications/permissions/autogenerated/commands/set_click_listener_active.toml b/src-tauri/vendor/tauri-plugin-notifications/permissions/autogenerated/commands/set_click_listener_active.tomlnew file mode 100644index 00000000..71d4005a--- /dev/null+++ b/src-tauri/vendor/tauri-plugin-notifications/permissions/autogenerated/commands/set_click_listener_active.toml@@ -0,0 +1,13 @@+# Automatically generated - DO NOT EDIT!++"$schema" = "../../schemas/schema.json"++[[permission]]+identifier = "allow-set-click-listener-active"+description = "Enables the set_click_listener_active command without any pre-configured scope."+commands.allow = ["set_click_listener_active"]++[[permission]]+identifier = "deny-set-click-listener-active"+description = "Denies the set_click_listener_active command without any pre-configured scope."+commands.deny = ["set_click_listener_active"]diff --git a/src-tauri/vendor/tauri-plugin-notifications/permissions/autogenerated/commands/set_distributor.toml b/src-tauri/vendor/tauri-plugin-notifications/permissions/autogenerated/commands/set_distributor.tomlnew file mode 100644index 00000000..f85ffdd4--- /dev/null+++ b/src-tauri/vendor/tauri-plugin-notifications/permissions/autogenerated/commands/set_distributor.toml@@ -0,0 +1,13 @@+# Automatically generated - DO NOT EDIT!++"$schema" = "../../schemas/schema.json"++[[permission]]+identifier = "allow-set-distributor"+description = "Enables the set_distributor command without any pre-configured scope."+commands.allow = ["set_distributor"]++[[permission]]+identifier = "deny-set-distributor"+description = "Denies the set_distributor command without any pre-configured scope."+commands.deny = ["set_distributor"]diff --git a/src-tauri/vendor/tauri-plugin-notifications/permissions/autogenerated/commands/set_token.toml b/src-tauri/vendor/tauri-plugin-notifications/permissions/autogenerated/commands/set_token.tomlnew file mode 100644index 00000000..4ab0d9a2--- /dev/null+++ b/src-tauri/vendor/tauri-plugin-notifications/permissions/autogenerated/commands/set_token.toml@@ -0,0 +1,13 @@+# Automatically generated - DO NOT EDIT!++"$schema" = "../../schemas/schema.json"++[[permission]]+identifier = "allow-set-token"+description = "Enables the set_token command without any pre-configured scope."+commands.allow = ["set_token"]++[[permission]]+identifier = "deny-set-token"+description = "Denies the set_token command without any pre-configured scope."+commands.deny = ["set_token"]diff --git a/src-tauri/vendor/tauri-plugin-notifications/permissions/autogenerated/commands/show.toml b/src-tauri/vendor/tauri-plugin-notifications/permissions/autogenerated/commands/show.tomlnew file mode 100644index 00000000..3d4cbf38--- /dev/null+++ b/src-tauri/vendor/tauri-plugin-notifications/permissions/autogenerated/commands/show.toml@@ -0,0 +1,13 @@+# Automatically generated - DO NOT EDIT!++"$schema" = "../../schemas/schema.json"++[[permission]]+identifier = "allow-show"+description = "Enables the show command without any pre-configured scope."+commands.allow = ["show"]++[[permission]]+identifier = "deny-show"+description = "Denies the show command without any pre-configured scope."+commands.deny = ["show"]diff --git a/src-tauri/vendor/tauri-plugin-notifications/permissions/autogenerated/commands/unregister_for_push_notifications.toml b/src-tauri/vendor/tauri-plugin-notifications/permissions/autogenerated/commands/unregister_for_push_notifications.tomlnew file mode 100644index 00000000..c90f98ad--- /dev/null+++ b/src-tauri/vendor/tauri-plugin-notifications/permissions/autogenerated/commands/unregister_for_push_notifications.toml@@ -0,0 +1,13 @@+# Automatically generated - DO NOT EDIT!++"$schema" = "../../schemas/schema.json"++[[permission]]+identifier = "allow-unregister-for-push-notifications"+description = "Enables the unregister_for_push_notifications command without any pre-configured scope."+commands.allow = ["unregister_for_push_notifications"]++[[permission]]+identifier = "deny-unregister-for-push-notifications"+description = "Denies the unregister_for_push_notifications command without any pre-configured scope."+commands.deny = ["unregister_for_push_notifications"]diff --git a/src-tauri/vendor/tauri-plugin-notifications/permissions/autogenerated/reference.md b/src-tauri/vendor/tauri-plugin-notifications/permissions/autogenerated/reference.mdnew file mode 100644index 00000000..47cb871e--- /dev/null+++ b/src-tauri/vendor/tauri-plugin-notifications/permissions/autogenerated/reference.md@@ -0,0 +1,696 @@+## Default Permission++This permission set configures which+notification features are by default exposed.++#### Granted Permissions++It allows all notification related features.++#### This default permission set includes the following:++- `allow-is-permission-granted`+- `allow-request-permission`+- `allow-register-for-push-notifications`+- `allow-unregister-for-push-notifications`+- `allow-notify`+- `allow-register-action-types`+- `allow-register-listener`+- `allow-remove-listener`+- `allow-cancel`+- `allow-cancel-all`+- `allow-get-pending`+- `allow-remove-active`+- `allow-remove-all`+- `allow-get-active`+- `allow-check-permissions`+- `allow-show`+- `allow-batch`+- `allow-list-channels`+- `allow-delete-channel`+- `allow-create-channel`+- `allow-permission-state`+- `allow-set-click-listener-active`+- `allow-list-distributors`+- `allow-set-distributor`+- `allow-set-token`++## Permission Table++<table>+<tr>+<th>Identifier</th>+<th>Description</th>+</tr>+++<tr>+<td>++`notifications:allow-batch`++</td>+<td>++Enables the batch command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`notifications:deny-batch`++</td>+<td>++Denies the batch command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`notifications:allow-cancel`++</td>+<td>++Enables the cancel command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`notifications:deny-cancel`++</td>+<td>++Denies the cancel command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`notifications:allow-cancel-all`++</td>+<td>++Enables the cancel_all command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`notifications:deny-cancel-all`++</td>+<td>++Denies the cancel_all command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`notifications:allow-check-permissions`++</td>+<td>++Enables the check_permissions command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`notifications:deny-check-permissions`++</td>+<td>++Denies the check_permissions command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`notifications:allow-create-channel`++</td>+<td>++Enables the create_channel command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`notifications:deny-create-channel`++</td>+<td>++Denies the create_channel command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`notifications:allow-delete-channel`++</td>+<td>++Enables the delete_channel command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`notifications:deny-delete-channel`++</td>+<td>++Denies the delete_channel command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`notifications:allow-get-active`++</td>+<td>++Enables the get_active command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`notifications:deny-get-active`++</td>+<td>++Denies the get_active command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`notifications:allow-get-pending`++</td>+<td>++Enables the get_pending command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`notifications:deny-get-pending`++</td>+<td>++Denies the get_pending command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`notifications:allow-is-permission-granted`++</td>+<td>++Enables the is_permission_granted command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`notifications:deny-is-permission-granted`++</td>+<td>++Denies the is_permission_granted command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`notifications:allow-list-channels`++</td>+<td>++Enables the list_channels command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`notifications:deny-list-channels`++</td>+<td>++Denies the list_channels command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`notifications:allow-list-distributors`++</td>+<td>++Enables the list_distributors command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`notifications:deny-list-distributors`++</td>+<td>++Denies the list_distributors command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`notifications:allow-notify`++</td>+<td>++Enables the notify command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`notifications:deny-notify`++</td>+<td>++Denies the notify command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`notifications:allow-permission-state`++</td>+<td>++Enables the permission_state command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`notifications:deny-permission-state`++</td>+<td>++Denies the permission_state command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`notifications:allow-register-action-types`++</td>+<td>++Enables the register_action_types command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`notifications:deny-register-action-types`++</td>+<td>++Denies the register_action_types command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`notifications:allow-register-for-push-notifications`++</td>+<td>++Enables the register_for_push_notifications command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`notifications:deny-register-for-push-notifications`++</td>+<td>++Denies the register_for_push_notifications command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`notifications:allow-register-listener`++</td>+<td>++Enables the register_listener command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`notifications:deny-register-listener`++</td>+<td>++Denies the register_listener command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`notifications:allow-remove-active`++</td>+<td>++Enables the remove_active command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`notifications:deny-remove-active`++</td>+<td>++Denies the remove_active command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`notifications:allow-remove-all`++</td>+<td>++Enables the remove_all command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`notifications:deny-remove-all`++</td>+<td>++Denies the remove_all command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`notifications:allow-remove-listener`++</td>+<td>++Enables the remove_listener command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`notifications:deny-remove-listener`++</td>+<td>++Denies the remove_listener command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`notifications:allow-request-permission`++</td>+<td>++Enables the request_permission command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`notifications:deny-request-permission`++</td>+<td>++Denies the request_permission command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`notifications:allow-set-click-listener-active`++</td>+<td>++Enables the set_click_listener_active command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`notifications:deny-set-click-listener-active`++</td>+<td>++Denies the set_click_listener_active command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`notifications:allow-set-distributor`++</td>+<td>++Enables the set_distributor command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`notifications:deny-set-distributor`++</td>+<td>++Denies the set_distributor command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`notifications:allow-set-token`++</td>+<td>++Enables the set_token command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`notifications:deny-set-token`++</td>+<td>++Denies the set_token command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`notifications:allow-show`++</td>+<td>++Enables the show command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`notifications:deny-show`++</td>+<td>++Denies the show command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`notifications:allow-unregister-for-push-notifications`++</td>+<td>++Enables the unregister_for_push_notifications command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`notifications:deny-unregister-for-push-notifications`++</td>+<td>++Denies the unregister_for_push_notifications command without any pre-configured scope.++</td>+</tr>+</table>diff --git a/src-tauri/vendor/tauri-plugin-notifications/permissions/default.toml b/src-tauri/vendor/tauri-plugin-notifications/permissions/default.tomlnew file mode 100644index 00000000..cffc2fa0--- /dev/null+++ b/src-tauri/vendor/tauri-plugin-notifications/permissions/default.toml@@ -0,0 +1,39 @@+"$schema" = "schemas/schema.json"+[default]+description = """+This permission set configures which+notification features are by default exposed.++#### Granted Permissions++It allows all notification related features.++"""++permissions = [+ "allow-is-permission-granted",+ "allow-request-permission",+ "allow-register-for-push-notifications",+ "allow-unregister-for-push-notifications",+ "allow-notify",+ "allow-register-action-types",+ "allow-register-listener",+ "allow-remove-listener",+ "allow-cancel",+ "allow-cancel-all",+ "allow-get-pending",+ "allow-remove-active",+ "allow-remove-all",+ "allow-get-active",+ "allow-check-permissions",+ "allow-show",+ "allow-batch",+ "allow-list-channels",+ "allow-delete-channel",+ "allow-create-channel",+ "allow-permission-state",+ "allow-set-click-listener-active",+ "allow-list-distributors",+ "allow-set-distributor",+ "allow-set-token",+]diff --git a/src-tauri/vendor/tauri-plugin-notifications/permissions/schemas/schema.json b/src-tauri/vendor/tauri-plugin-notifications/permissions/schemas/schema.jsonnew file mode 100644index 00000000..22e0055b--- /dev/null+++ b/src-tauri/vendor/tauri-plugin-notifications/permissions/schemas/schema.json@@ -0,0 +1,606 @@+{+ "$schema": "http://json-schema.org/draft-07/schema#",+ "title": "PermissionFile",+ "description": "Permission file that can define a default permission, a set of permissions or a list of inlined permissions.",+ "type": "object",+ "properties": {+ "default": {+ "description": "The default permission set for the plugin",+ "anyOf": [+ {+ "$ref": "#/definitions/DefaultPermission"+ },+ {+ "type": "null"+ }+ ]+ },+ "set": {+ "description": "A list of permissions sets defined",+ "type": "array",+ "items": {+ "$ref": "#/definitions/PermissionSet"+ }+ },+ "permission": {+ "description": "A list of inlined permissions",+ "default": [],+ "type": "array",+ "items": {+ "$ref": "#/definitions/Permission"+ }+ }+ },+ "definitions": {+ "DefaultPermission": {+ "description": "The default permission set of the plugin.\n\nWorks similarly to a permission with the \"default\" identifier.",+ "type": "object",+ "required": [+ "permissions"+ ],+ "properties": {+ "version": {+ "description": "The version of the permission.",+ "type": [+ "integer",+ "null"+ ],+ "format": "uint64",+ "minimum": 1.0+ },+ "description": {+ "description": "Human-readable description of what the permission does. Tauri convention is to use `<h4>` headings in markdown content for Tauri documentation generation purposes.",+ "type": [+ "string",+ "null"+ ]+ },+ "permissions": {+ "description": "All permissions this set contains.",+ "type": "array",+ "items": {+ "type": "string"+ }+ }+ }+ },+ "PermissionSet": {+ "description": "A set of direct permissions grouped together under a new name.",+ "type": "object",+ "required": [+ "description",+ "identifier",+ "permissions"+ ],+ "properties": {+ "identifier": {+ "description": "A unique identifier for the permission.",+ "type": "string"+ },+ "description": {+ "description": "Human-readable description of what the permission does.",+ "type": "string"+ },+ "permissions": {+ "description": "All permissions this set contains.",+ "type": "array",+ "items": {+ "$ref": "#/definitions/PermissionKind"+ }+ }+ }+ },+ "Permission": {+ "description": "Descriptions of explicit privileges of commands.\n\nIt can enable commands to be accessible in the frontend of the application.\n\nIf the scope is defined it can be used to fine grain control the access of individual or multiple commands.",+ "type": "object",+ "required": [+ "identifier"+ ],+ "properties": {+ "version": {+ "description": "The version of the permission.",+ "type": [+ "integer",+ "null"+ ],+ "format": "uint64",+ "minimum": 1.0+ },+ "identifier": {+ "description": "A unique identifier for the permission.",+ "type": "string"+ },+ "description": {+ "description": "Human-readable description of what the permission does. Tauri internal convention is to use `<h4>` headings in markdown content for Tauri documentation generation purposes.",+ "type": [+ "string",+ "null"+ ]+ },+ "commands": {+ "description": "Allowed or denied commands when using this permission.",+ "default": {+ "allow": [],+ "deny": []+ },+ "allOf": [+ {+ "$ref": "#/definitions/Commands"+ }+ ]+ },+ "scope": {+ "description": "Allowed or denied scoped when using this permission.",+ "allOf": [+ {+ "$ref": "#/definitions/Scopes"+ }+ ]+ },+ "platforms": {+ "description": "Target platforms this permission applies. By default all platforms are affected by this permission.",+ "type": [+ "array",+ "null"+ ],+ "items": {+ "$ref": "#/definitions/Target"+ }+ }+ }+ },+ "Commands": {+ "description": "Allowed and denied commands inside a permission.\n\nIf two commands clash inside of `allow` and `deny`, it should be denied by default.",+ "type": "object",+ "properties": {+ "allow": {+ "description": "Allowed command.",+ "default": [],+ "type": "array",+ "items": {+ "type": "string"+ }+ },+ "deny": {+ "description": "Denied command, which takes priority.",+ "default": [],+ "type": "array",+ "items": {+ "type": "string"+ }+ }+ }+ },+ "Scopes": {+ "description": "An argument for fine grained behavior control of Tauri commands.\n\nIt can be of any serde serializable type and is used to allow or prevent certain actions inside a Tauri command. The configured scope is passed to the command and will be enforced by the command implementation.\n\n## Example\n\n```json { \"allow\": [{ \"path\": \"$HOME/**\" }], \"deny\": [{ \"path\": \"$HOME/secret.txt\" }] } ```",+ "type": "object",+ "properties": {+ "allow": {+ "description": "Data that defines what is allowed by the scope.",+ "type": [+ "array",+ "null"+ ],+ "items": {+ "$ref": "#/definitions/Value"+ }+ },+ "deny": {+ "description": "Data that defines what is denied by the scope. This should be prioritized by validation logic.",+ "type": [+ "array",+ "null"+ ],+ "items": {+ "$ref": "#/definitions/Value"+ }+ }+ }+ },+ "Value": {+ "description": "All supported ACL values.",+ "anyOf": [+ {+ "description": "Represents a null JSON value.",+ "type": "null"+ },+ {+ "description": "Represents a [`bool`].",+ "type": "boolean"+ },+ {+ "description": "Represents a valid ACL [`Number`].",+ "allOf": [+ {+ "$ref": "#/definitions/Number"+ }+ ]+ },+ {+ "description": "Represents a [`String`].",+ "type": "string"+ },+ {+ "description": "Represents a list of other [`Value`]s.",+ "type": "array",+ "items": {+ "$ref": "#/definitions/Value"+ }+ },+ {+ "description": "Represents a map of [`String`] keys to [`Value`]s.",+ "type": "object",+ "additionalProperties": {+ "$ref": "#/definitions/Value"+ }+ }+ ]+ },+ "Number": {+ "description": "A valid ACL number.",+ "anyOf": [+ {+ "description": "Represents an [`i64`].",+ "type": "integer",+ "format": "int64"+ },+ {+ "description": "Represents a [`f64`].",+ "type": "number",+ "format": "double"+ }+ ]+ },+ "Target": {+ "description": "Platform target.",+ "oneOf": [+ {+ "description": "MacOS.",+ "type": "string",+ "enum": [+ "macOS"+ ]+ },+ {+ "description": "Windows.",+ "type": "string",+ "enum": [+ "windows"+ ]+ },+ {+ "description": "Linux.",+ "type": "string",+ "enum": [+ "linux"+ ]+ },+ {+ "description": "Android.",+ "type": "string",+ "enum": [+ "android"+ ]+ },+ {+ "description": "iOS.",+ "type": "string",+ "enum": [+ "iOS"+ ]+ }+ ]+ },+ "PermissionKind": {+ "type": "string",+ "oneOf": [+ {+ "description": "Enables the batch command without any pre-configured scope.",+ "type": "string",+ "const": "allow-batch",+ "markdownDescription": "Enables the batch command without any pre-configured scope."+ },+ {+ "description": "Denies the batch command without any pre-configured scope.",+ "type": "string",+ "const": "deny-batch",+ "markdownDescription": "Denies the batch command without any pre-configured scope."+ },+ {+ "description": "Enables the cancel command without any pre-configured scope.",+ "type": "string",+ "const": "allow-cancel",+ "markdownDescription": "Enables the cancel command without any pre-configured scope."+ },+ {+ "description": "Denies the cancel command without any pre-configured scope.",+ "type": "string",+ "const": "deny-cancel",+ "markdownDescription": "Denies the cancel command without any pre-configured scope."+ },+ {+ "description": "Enables the cancel_all command without any pre-configured scope.",+ "type": "string",+ "const": "allow-cancel-all",+ "markdownDescription": "Enables the cancel_all command without any pre-configured scope."+ },+ {+ "description": "Denies the cancel_all command without any pre-configured scope.",+ "type": "string",+ "const": "deny-cancel-all",+ "markdownDescription": "Denies the cancel_all command without any pre-configured scope."+ },+ {+ "description": "Enables the check_permissions command without any pre-configured scope.",+ "type": "string",+ "const": "allow-check-permissions",+ "markdownDescription": "Enables the check_permissions command without any pre-configured scope."+ },+ {+ "description": "Denies the check_permissions command without any pre-configured scope.",+ "type": "string",+ "const": "deny-check-permissions",+ "markdownDescription": "Denies the check_permissions command without any pre-configured scope."+ },+ {+ "description": "Enables the create_channel command without any pre-configured scope.",+ "type": "string",+ "const": "allow-create-channel",+ "markdownDescription": "Enables the create_channel command without any pre-configured scope."+ },+ {+ "description": "Denies the create_channel command without any pre-configured scope.",+ "type": "string",+ "const": "deny-create-channel",+ "markdownDescription": "Denies the create_channel command without any pre-configured scope."+ },+ {+ "description": "Enables the delete_channel command without any pre-configured scope.",+ "type": "string",+ "const": "allow-delete-channel",+ "markdownDescription": "Enables the delete_channel command without any pre-configured scope."+ },+ {+ "description": "Denies the delete_channel command without any pre-configured scope.",+ "type": "string",+ "const": "deny-delete-channel",+ "markdownDescription": "Denies the delete_channel command without any pre-configured scope."+ },+ {+ "description": "Enables the get_active command without any pre-configured scope.",+ "type": "string",+ "const": "allow-get-active",+ "markdownDescription": "Enables the get_active command without any pre-configured scope."+ },+ {+ "description": "Denies the get_active command without any pre-configured scope.",+ "type": "string",+ "const": "deny-get-active",+ "markdownDescription": "Denies the get_active command without any pre-configured scope."+ },+ {+ "description": "Enables the get_pending command without any pre-configured scope.",+ "type": "string",+ "const": "allow-get-pending",+ "markdownDescription": "Enables the get_pending command without any pre-configured scope."+ },+ {+ "description": "Denies the get_pending command without any pre-configured scope.",+ "type": "string",+ "const": "deny-get-pending",+ "markdownDescription": "Denies the get_pending command without any pre-configured scope."+ },+ {+ "description": "Enables the is_permission_granted command without any pre-configured scope.",+ "type": "string",+ "const": "allow-is-permission-granted",+ "markdownDescription": "Enables the is_permission_granted command without any pre-configured scope."+ },+ {+ "description": "Denies the is_permission_granted command without any pre-configured scope.",+ "type": "string",+ "const": "deny-is-permission-granted",+ "markdownDescription": "Denies the is_permission_granted command without any pre-configured scope."+ },+ {+ "description": "Enables the list_channels command without any pre-configured scope.",+ "type": "string",+ "const": "allow-list-channels",+ "markdownDescription": "Enables the list_channels command without any pre-configured scope."+ },+ {+ "description": "Denies the list_channels command without any pre-configured scope.",+ "type": "string",+ "const": "deny-list-channels",+ "markdownDescription": "Denies the list_channels command without any pre-configured scope."+ },+ {+ "description": "Enables the list_distributors command without any pre-configured scope.",+ "type": "string",+ "const": "allow-list-distributors",+ "markdownDescription": "Enables the list_distributors command without any pre-configured scope."+ },+ {+ "description": "Denies the list_distributors command without any pre-configured scope.",+ "type": "string",+ "const": "deny-list-distributors",+ "markdownDescription": "Denies the list_distributors command without any pre-configured scope."+ },+ {+ "description": "Enables the notify command without any pre-configured scope.",+ "type": "string",+ "const": "allow-notify",+ "markdownDescription": "Enables the notify command without any pre-configured scope."+ },+ {+ "description": "Denies the notify command without any pre-configured scope.",+ "type": "string",+ "const": "deny-notify",+ "markdownDescription": "Denies the notify command without any pre-configured scope."+ },+ {+ "description": "Enables the permission_state command without any pre-configured scope.",+ "type": "string",+ "const": "allow-permission-state",+ "markdownDescription": "Enables the permission_state command without any pre-configured scope."+ },+ {+ "description": "Denies the permission_state command without any pre-configured scope.",+ "type": "string",+ "const": "deny-permission-state",+ "markdownDescription": "Denies the permission_state command without any pre-configured scope."+ },+ {+ "description": "Enables the register_action_types command without any pre-configured scope.",+ "type": "string",+ "const": "allow-register-action-types",+ "markdownDescription": "Enables the register_action_types command without any pre-configured scope."+ },+ {+ "description": "Denies the register_action_types command without any pre-configured scope.",+ "type": "string",+ "const": "deny-register-action-types",+ "markdownDescription": "Denies the register_action_types command without any pre-configured scope."+ },+ {+ "description": "Enables the register_for_push_notifications command without any pre-configured scope.",+ "type": "string",+ "const": "allow-register-for-push-notifications",+ "markdownDescription": "Enables the register_for_push_notifications command without any pre-configured scope."+ },+ {+ "description": "Denies the register_for_push_notifications command without any pre-configured scope.",+ "type": "string",+ "const": "deny-register-for-push-notifications",+ "markdownDescription": "Denies the register_for_push_notifications command without any pre-configured scope."+ },+ {+ "description": "Enables the register_listener command without any pre-configured scope.",+ "type": "string",+ "const": "allow-register-listener",+ "markdownDescription": "Enables the register_listener command without any pre-configured scope."+ },+ {+ "description": "Denies the register_listener command without any pre-configured scope.",+ "type": "string",+ "const": "deny-register-listener",+ "markdownDescription": "Denies the register_listener command without any pre-configured scope."+ },+ {+ "description": "Enables the remove_active command without any pre-configured scope.",+ "type": "string",+ "const": "allow-remove-active",+ "markdownDescription": "Enables the remove_active command without any pre-configured scope."+ },+ {+ "description": "Denies the remove_active command without any pre-configured scope.",+ "type": "string",+ "const": "deny-remove-active",+ "markdownDescription": "Denies the remove_active command without any pre-configured scope."+ },+ {+ "description": "Enables the remove_all command without any pre-configured scope.",+ "type": "string",+ "const": "allow-remove-all",+ "markdownDescription": "Enables the remove_all command without any pre-configured scope."+ },+ {+ "description": "Denies the remove_all command without any pre-configured scope.",+ "type": "string",+ "const": "deny-remove-all",+ "markdownDescription": "Denies the remove_all command without any pre-configured scope."+ },+ {+ "description": "Enables the remove_listener command without any pre-configured scope.",+ "type": "string",+ "const": "allow-remove-listener",+ "markdownDescription": "Enables the remove_listener command without any pre-configured scope."+ },+ {+ "description": "Denies the remove_listener command without any pre-configured scope.",+ "type": "string",+ "const": "deny-remove-listener",+ "markdownDescription": "Denies the remove_listener command without any pre-configured scope."+ },+ {+ "description": "Enables the request_permission command without any pre-configured scope.",+ "type": "string",+ "const": "allow-request-permission",+ "markdownDescription": "Enables the request_permission command without any pre-configured scope."+ },+ {+ "description": "Denies the request_permission command without any pre-configured scope.",+ "type": "string",+ "const": "deny-request-permission",+ "markdownDescription": "Denies the request_permission command without any pre-configured scope."+ },+ {+ "description": "Enables the set_click_listener_active command without any pre-configured scope.",+ "type": "string",+ "const": "allow-set-click-listener-active",+ "markdownDescription": "Enables the set_click_listener_active command without any pre-configured scope."+ },+ {+ "description": "Denies the set_click_listener_active command without any pre-configured scope.",+ "type": "string",+ "const": "deny-set-click-listener-active",+ "markdownDescription": "Denies the set_click_listener_active command without any pre-configured scope."+ },+ {+ "description": "Enables the set_distributor command without any pre-configured scope.",+ "type": "string",+ "const": "allow-set-distributor",+ "markdownDescription": "Enables the set_distributor command without any pre-configured scope."+ },+ {+ "description": "Denies the set_distributor command without any pre-configured scope.",+ "type": "string",+ "const": "deny-set-distributor",+ "markdownDescription": "Denies the set_distributor command without any pre-configured scope."+ },+ {+ "description": "Enables the set_token command without any pre-configured scope.",+ "type": "string",+ "const": "allow-set-token",+ "markdownDescription": "Enables the set_token command without any pre-configured scope."+ },+ {+ "description": "Denies the set_token command without any pre-configured scope.",+ "type": "string",+ "const": "deny-set-token",+ "markdownDescription": "Denies the set_token command without any pre-configured scope."+ },+ {+ "description": "Enables the show command without any pre-configured scope.",+ "type": "string",+ "const": "allow-show",+ "markdownDescription": "Enables the show command without any pre-configured scope."+ },+ {+ "description": "Denies the show command without any pre-configured scope.",+ "type": "string",+ "const": "deny-show",+ "markdownDescription": "Denies the show command without any pre-configured scope."+ },+ {+ "description": "Enables the unregister_for_push_notifications command without any pre-configured scope.",+ "type": "string",+ "const": "allow-unregister-for-push-notifications",+ "markdownDescription": "Enables the unregister_for_push_notifications command without any pre-configured scope."+ },+ {+ "description": "Denies the unregister_for_push_notifications command without any pre-configured scope.",+ "type": "string",+ "const": "deny-unregister-for-push-notifications",+ "markdownDescription": "Denies the unregister_for_push_notifications command without any pre-configured scope."+ },+ {+ "description": "This permission set configures which\nnotification features are by default exposed.\n\n#### Granted Permissions\n\nIt allows all notification related features.\n\n\n#### This default permission set includes:\n\n- `allow-is-permission-granted`\n- `allow-request-permission`\n- `allow-register-for-push-notifications`\n- `allow-unregister-for-push-notifications`\n- `allow-notify`\n- `allow-register-action-types`\n- `allow-register-listener`\n- `allow-remove-listener`\n- `allow-cancel`\n- `allow-cancel-all`\n- `allow-get-pending`\n- `allow-remove-active`\n- `allow-remove-all`\n- `allow-get-active`\n- `allow-check-permissions`\n- `allow-show`\n- `allow-batch`\n- `allow-list-channels`\n- `allow-delete-channel`\n- `allow-create-channel`\n- `allow-permission-state`\n- `allow-set-click-listener-active`\n- `allow-list-distributors`\n- `allow-set-distributor`\n- `allow-set-token`",+ "type": "string",+ "const": "default",+ "markdownDescription": "This permission set configures which\nnotification features are by default exposed.\n\n#### Granted Permissions\n\nIt allows all notification related features.\n\n\n#### This default permission set includes:\n\n- `allow-is-permission-granted`\n- `allow-request-permission`\n- `allow-register-for-push-notifications`\n- `allow-unregister-for-push-notifications`\n- `allow-notify`\n- `allow-register-action-types`\n- `allow-register-listener`\n- `allow-remove-listener`\n- `allow-cancel`\n- `allow-cancel-all`\n- `allow-get-pending`\n- `allow-remove-active`\n- `allow-remove-all`\n- `allow-get-active`\n- `allow-check-permissions`\n- `allow-show`\n- `allow-batch`\n- `allow-list-channels`\n- `allow-delete-channel`\n- `allow-create-channel`\n- `allow-permission-state`\n- `allow-set-click-listener-active`\n- `allow-list-distributors`\n- `allow-set-distributor`\n- `allow-set-token`"+ }+ ]+ }+ }+}\ No newline at end of filediff --git a/src-tauri/vendor/tauri-plugin-notifications/src/commands.rs b/src-tauri/vendor/tauri-plugin-notifications/src/commands.rsnew file mode 100644index 00000000..f3255e49--- /dev/null+++ b/src-tauri/vendor/tauri-plugin-notifications/src/commands.rs@@ -0,0 +1,195 @@+// Tauri command handlers must take owned values: `State<'_, _>` is the framework's+// preferred wrapper, and serde-deserialized payloads (Vec, String, ...) cannot be borrowed.+#![allow(clippy::needless_pass_by_value)]++use serde::Deserialize;+use tauri::{AppHandle, Runtime, State, command, plugin::PermissionState};++use crate::{NotificationData, Notifications, Result};++#[derive(Debug, Deserialize)]+#[allow(dead_code)]+pub struct NotificationIdentifier {+ pub id: i32,+ #[allow(dead_code)]+ pub tag: Option<String>,+}++#[command]+pub async fn is_permission_granted<R: Runtime>(+ _app: AppHandle<R>,+ notification: State<'_, Notifications<R>>,+) -> Result<Option<bool>> {+ let state = notification.permission_state().await?;+ match state {+ PermissionState::Granted => Ok(Some(true)),+ PermissionState::Denied => Ok(Some(false)),+ PermissionState::Prompt | PermissionState::PromptWithRationale => Ok(None),+ }+}++#[command]+pub async fn request_permission<R: Runtime>(+ _app: AppHandle<R>,+ notification: State<'_, Notifications<R>>,+) -> Result<PermissionState> {+ notification.request_permission().await+}++#[command]+pub async fn register_for_push_notifications<R: Runtime>(+ _app: AppHandle<R>,+ notification: State<'_, Notifications<R>>,+) -> Result<String> {+ notification.register_for_push_notifications().await+}++#[command]+pub async fn unregister_for_push_notifications<R: Runtime>(+ _app: AppHandle<R>,+ notification: State<'_, Notifications<R>>,+) -> Result<()> {+ #[cfg(all(desktop, target_os = "linux", feature = "push-notifications"))]+ {+ notification.unregister_for_push_notifications_async().await+ }+ #[cfg(not(all(desktop, target_os = "linux", feature = "push-notifications")))]+ {+ notification.unregister_for_push_notifications()+ }+}++#[cfg(all(desktop, target_os = "linux", feature = "push-notifications"))]+#[command]+pub async fn list_distributors<R: Runtime>(+ _app: AppHandle<R>,+ notification: State<'_, Notifications<R>>,+) -> Result<Vec<String>> {+ notification.list_distributors().await+}++#[cfg(all(desktop, target_os = "linux", feature = "push-notifications"))]+#[command]+pub async fn set_distributor<R: Runtime>(+ _app: AppHandle<R>,+ notification: State<'_, Notifications<R>>,+ name: String,+) -> Result<()> {+ notification.set_distributor(name).await+}++#[cfg(all(desktop, target_os = "linux", feature = "push-notifications"))]+#[command]+pub async fn set_token<R: Runtime>(+ _app: AppHandle<R>,+ notification: State<'_, Notifications<R>>,+ token: String,+) -> Result<()> {+ notification.set_token(token).await+}++#[command]+pub async fn notify<R: Runtime>(+ _app: AppHandle<R>,+ notification: State<'_, Notifications<R>>,+ options: NotificationData,+) -> Result<()> {+ let mut builder = notification.builder();+ builder.data = options;+ builder.show().await+}++#[command]+pub async fn register_action_types<R: Runtime>(+ _app: AppHandle<R>,+ notification: State<'_, Notifications<R>>,+ types: Vec<crate::ActionType>,+) -> Result<()> {+ notification.register_action_types(types)+}++#[command]+pub async fn get_pending<R: Runtime>(+ _app: AppHandle<R>,+ notification: State<'_, Notifications<R>>,+) -> Result<Vec<crate::PendingNotification>> {+ notification.pending().await+}++#[command]+pub async fn get_active<R: Runtime>(+ _app: AppHandle<R>,+ notification: State<'_, Notifications<R>>,+) -> Result<Vec<crate::ActiveNotification>> {+ notification.active().await+}++#[command]+pub fn set_click_listener_active<R: Runtime>(+ _app: AppHandle<R>,+ notification: State<'_, Notifications<R>>,+ active: bool,+) -> Result<()> {+ notification.set_click_listener_active(active)+}++#[command]+pub fn remove_active<R: Runtime>(+ _app: AppHandle<R>,+ notification: State<'_, Notifications<R>>,+ notifications: Vec<NotificationIdentifier>,+) -> Result<()> {+ let ids: Vec<i32> = notifications.into_iter().map(|n| n.id).collect();+ notification.remove_active(ids)+}++#[command]+pub fn remove_all<R: Runtime>(+ _app: AppHandle<R>,+ notification: State<'_, Notifications<R>>,+) -> Result<()> {+ notification.remove_all_active()+}++#[command]+pub fn cancel<R: Runtime>(+ _app: AppHandle<R>,+ notification: State<'_, Notifications<R>>,+ notifications: Vec<i32>,+) -> Result<()> {+ notification.cancel(notifications)+}++#[command]+pub fn cancel_all<R: Runtime>(+ _app: AppHandle<R>,+ notification: State<'_, Notifications<R>>,+) -> Result<()> {+ notification.cancel_all()+}++#[command]+pub fn create_channel<R: Runtime>(+ _app: AppHandle<R>,+ notification: State<'_, Notifications<R>>,+ channel: crate::Channel,+) -> Result<()> {+ notification.create_channel(channel)+}++#[command]+pub fn delete_channel<R: Runtime>(+ _app: AppHandle<R>,+ notification: State<'_, Notifications<R>>,+ id: String,+) -> Result<()> {+ notification.delete_channel(id)+}++#[command]+pub fn list_channels<R: Runtime>(+ _app: AppHandle<R>,+ notification: State<'_, Notifications<R>>,+) -> Result<Vec<crate::Channel>> {+ notification.list_channels()+}diff --git a/src-tauri/vendor/tauri-plugin-notifications/src/desktop.rs b/src-tauri/vendor/tauri-plugin-notifications/src/desktop.rsnew file mode 100644index 00000000..4b9ecbb6--- /dev/null+++ b/src-tauri/vendor/tauri-plugin-notifications/src/desktop.rs@@ -0,0 +1,772 @@+use serde::de::DeserializeOwned;+use tauri::{+ AppHandle, Runtime,+ plugin::{PermissionState, PluginApi},+};++use crate::NotificationsBuilder;++/// Tracks a single live `notify-rust` notification on Linux and FreeBSD. Owning the+/// `NotificationHandle` keeps the underlying D-Bus `Connection` alive+/// (preventing the "popup disappears when the sending client disconnects"+/// behavior some XDG daemons exhibit) and lets us implement+/// `active`/`cancel` for the caller-supplied id.+///+/// macOS / Windows: `notify_rust::NotificationHandle` on those platforms+/// doesn't expose a useful `close()` (macOS daemon doesn't dismiss on+/// sender disconnect; Windows's handle is a thin wrapper without close+/// semantics), so we don't track there and the active-list / cancel+/// methods stay as the existing stubs.+#[cfg(any(target_os = "linux", target_os = "freebsd"))]+struct ActiveEntry {+ caller_id: i32,+ /// Shared with the action waiter spawned by [`NotificationsBuilder::show`]+ /// when a click listener is subscribed, so both can hold the handle for as+ /// long as the notification is live.+ handle: std::sync::Arc<notify_rust::NotificationHandle>,+ title: Option<String>,+ body: Option<String>,+}++// Signature must match the iOS/Android `init` so the cfg-gated call sites in `lib.rs::init` compile uniformly.+#[allow(clippy::unnecessary_wraps)]+pub fn init<R: Runtime, C: DeserializeOwned>(+ app: &AppHandle<R>,+ _api: PluginApi<R, C>,+) -> crate::Result<Notifications<R>> {+ Ok(Notifications {+ app: app.clone(),+ #[cfg(any(target_os = "linux", target_os = "freebsd"))]+ active: std::sync::Mutex::new(std::collections::HashMap::new()),+ #[cfg(any(target_os = "linux", target_os = "freebsd"))]+ active_counter: std::sync::atomic::AtomicU64::new(0),+ #[cfg(all(target_os = "linux", feature = "push-notifications"))]+ unifiedpush: tokio::sync::OnceCell::new(),+ click_listener_active: std::sync::atomic::AtomicBool::new(false),+ })+}++/// Access to the notification APIs.+///+/// You can get an instance of this type via [`NotificationsExt`](crate::NotificationsExt)+pub struct Notifications<R: Runtime> {+ app: AppHandle<R>,+ /// Currently-displayed notifications, keyed by an internal monotonic+ /// counter (not the caller-supplied id, so multiple notifications with+ /// the same id coexist without evicting each other). Holding the handles+ /// keeps the popups visible and lets `cancel`/`cancel_all`/+ /// `remove_active`/`active` work without leaking. Entries are removed by+ /// explicit cancel; expired/auto-dismissed notifications may linger+ /// because notify-rust doesn't expose a non-consuming "closed" callback.+ #[cfg(any(target_os = "linux", target_os = "freebsd"))]+ active: std::sync::Mutex<std::collections::HashMap<u64, ActiveEntry>>,+ #[cfg(any(target_os = "linux", target_os = "freebsd"))]+ active_counter: std::sync::atomic::AtomicU64,+ #[cfg(all(target_os = "linux", feature = "push-notifications"))]+ unifiedpush: tokio::sync::OnceCell<std::sync::Arc<crate::unifiedpush::UnifiedPushState>>,+ /// Whether a JS `notificationClicked` listener is currently subscribed.+ /// Set by [`Notifications::set_click_listener_active`], which the JS+ /// `onNotificationClicked` helper calls right after registering. Read by+ /// [`NotificationsBuilder::show`] to decide whether to observe the+ /// notification's response, and — on macOS, Linux, and FreeBSD — whether the+ /// notification needs an activation action declared at all.+ click_listener_active: std::sync::atomic::AtomicBool,+}++#[cfg(any(target_os = "linux", target_os = "freebsd"))]+fn active_lock_err(e: impl std::fmt::Display) -> crate::Error {+ crate::Error::Io(std::io::Error::other(format!(+ "active notifications mutex poisoned: {e}"+ )))+}++#[cfg(any(target_os = "linux", target_os = "freebsd"))]+impl<R: Runtime> Notifications<R> {+ /// Finds every tracked notification whose caller id is in `caller_ids`,+ /// removes them from the active map, and spawns `handle.close_async()` so+ /// the command call returns quickly.+ fn close_by_caller_ids(&self, caller_ids: &[i32]) -> crate::Result<()> {+ let mut to_close: Vec<ActiveEntry> = Vec::new();+ {+ let mut active = self.active.lock().map_err(active_lock_err)?;+ // Move the map out, partition entries into "close" vs "keep" in+ // one pass, then put the kept ones back. Avoids the borrow-+ // checker dance of iter-then-remove (which would need a+ // throwaway `Vec<u64>` of keys) without holding the lock any+ // longer than necessary.+ let kept: std::collections::HashMap<u64, ActiveEntry> = std::mem::take(&mut *active)+ .into_iter()+ .filter_map(|(k, entry)| {+ if caller_ids.contains(&entry.caller_id) {+ to_close.push(entry);+ None+ } else {+ Some((k, entry))+ }+ })+ .collect();+ *active = kept;+ }+ for entry in to_close {+ // `close_async` borrows, so it works through the `Arc` that the+ // action waiter may also be holding; the consuming `close()` can't.+ tauri::async_runtime::spawn(async move { entry.handle.close_async().await });+ }+ Ok(())+ }+}++#[cfg(all(target_os = "linux", feature = "push-notifications"))]+impl<R: Runtime> Notifications<R> {+ async fn unifiedpush_state(+ &self,+ ) -> crate::Result<&std::sync::Arc<crate::unifiedpush::UnifiedPushState>> {+ self.unifiedpush+ .get_or_try_init(|| {+ let displayer = Self::build_push_displayer(self.app.clone());+ crate::unifiedpush::UnifiedPushState::new(&self.app, Some(displayer))+ })+ .await+ }++ /// Builds the `PushDisplayer` callback handed to `UnifiedPushState`. The+ /// callback runs `notify_rust::Notification::show()` on a blocking thread+ /// and routes the resulting handle into the same `active` map that local+ /// notifications use, so push toasts:+ /// * Stay visible (handle is held → D-Bus connection stays alive →+ /// daemons don't dismiss-on-disconnect).+ /// * Show up in [`Notifications::active`] alongside local notifications.+ /// * Can be cancelled via the existing `cancel`/`cancel_all` methods+ /// (caller id is `0` because `UnifiedPush` messages don't carry one).+ fn build_push_displayer(app: AppHandle<R>) -> crate::unifiedpush::PushDisplayer {+ std::sync::Arc::new(move |title: Option<String>, body: Option<String>| {+ let app = app.clone();+ let identifier = app.config().identifier.clone();+ tauri::async_runtime::spawn_blocking(move || {+ let notification = match imp::build_notification(+ title.as_deref(),+ body.as_deref(),+ None,+ &identifier,+ ) {+ Ok(n) => n,+ Err(e) => {+ log::warn!("Failed to build push notification: {e}");+ return;+ }+ };+ match notification.show() {+ Ok(handle) => {+ use std::sync::atomic::Ordering;+ use tauri::Manager;+ let state = app.state::<Self>();+ let entry_id = state.active_counter.fetch_add(1, Ordering::Relaxed);+ let entry = ActiveEntry {+ caller_id: 0,+ // No click waiter for push toasts (they carry no+ // caller id or extras), but the field is shared with+ // the local path, which does spawn one.+ handle: std::sync::Arc::new(handle),+ title,+ body,+ };+ let lock = state.active.lock();+ match lock {+ Ok(mut active) => {+ active.insert(entry_id, entry);+ }+ Err(poisoned) => {+ log::warn!("active notifications mutex was poisoned; recovering");+ poisoned.into_inner().insert(entry_id, entry);+ }+ }+ }+ Err(e) => log::warn!("Failed to show push notification toast: {e}"),+ }+ });+ })+ }+}++/// Linux / FreeBSD: registers the freshly shown notification in the active map and, when+/// a click listener is subscribed, spawns the waiter that reports the user's+/// response and removes the entry once the notification is gone.+///+/// `Arc` because the handle has two concurrent users: the active map (for+/// `cancel`) and the action waiter. Both only ever need `&self` —+/// `wait_for_action_async` and `close_async` borrow, unlike their consuming+/// sync counterparts. Tracking happens before observing so the waiter's removal+/// can never race an insert that has not happened yet.+#[cfg(any(target_os = "linux", target_os = "freebsd"))]+fn track_and_observe<R: Runtime>(+ app: &tauri::AppHandle<R>,+ caller_id: i32,+ extra: std::collections::HashMap<String, serde_json::Value>,+ title: Option<String>,+ body: Option<String>,+ handle: notify_rust::NotificationHandle,+ click_listener_active: bool,+) {+ use std::sync::atomic::Ordering;+ use tauri::Manager;++ fn lock_active<R: Runtime>(+ state: &Notifications<R>,+ ) -> std::sync::MutexGuard<'_, std::collections::HashMap<u64, ActiveEntry>> {+ state.active.lock().unwrap_or_else(|poisoned| {+ log::warn!("active notifications mutex was poisoned; recovering");+ poisoned.into_inner()+ })+ }++ let handle = std::sync::Arc::new(handle);+ let state = app.state::<Notifications<R>>();+ let entry_id = state.active_counter.fetch_add(1, Ordering::Relaxed);+ let entry = ActiveEntry {+ caller_id,+ handle: std::sync::Arc::clone(&handle),+ title,+ body,+ };+ lock_active(&state).insert(entry_id, entry);++ if click_listener_active {+ let app = app.clone();+ tauri::async_runtime::spawn(async move {+ // Resolves on ActionInvoked *or* NotificationClosed — either way+ // the notification is no longer on screen, so the entry goes too.+ handle+ .wait_for_action_async(|response| {+ imp::emit_click(caller_id, &extra, response);+ })+ .await;+ lock_active(&app.state::<Notifications<R>>()).remove(&entry_id);+ });+ }+}++// `async` and `Result` mirror the mobile/macOS plugin API so callers can `.await` and `?` uniformly.+impl<R: Runtime> crate::NotificationsBuilder<R> {+ pub async fn show(self) -> crate::Result<()> {+ let caller_id = self.data.id;+ let title = self+ .data+ .title+ .or_else(|| self.app.config().product_name.clone());+ let body = self.data.body;+ let icon = self.data.icon;+ // Captured for the click payload: the response from `notify-rust`+ // carries no notification identity, so the waiter has to close over the+ // id and extras of the notification it was spawned for.+ let extra = self.data.extra;+ let identifier = self.app.config().identifier.clone();+ let app = self.app.clone();++ // Read before building: on macOS, Linux, and FreeBSD, whether a listener is+ // subscribed changes how the notification itself has to be constructed.+ let click_listener_active = {+ use tauri::Manager;+ app.state::<Notifications<R>>()+ .click_listener_active+ .load(std::sync::atomic::Ordering::Relaxed)+ };++ #[cfg_attr(+ target_os = "windows",+ expect(unused_mut, reason = "no action is declared on Windows")+ )]+ let mut notification = imp::build_notification(+ title.as_deref(),+ body.as_deref(),+ icon.as_deref(),+ &identifier,+ )?;++ // Both non-Windows backends need an action declared before a click can+ // ever be reported, for different reasons:+ //+ // * macOS — `mac-notification-sys` only blocks for a response when the+ // notification declares an interactive element (`needs_response()` is+ // `main_button.is_some() || close_button.is_some() || wait_for_click`).+ // notify-rust never sets `wait_for_click` and only sets `close_button`+ // for `on_close`, so without an action `wait_for_response` returns+ // `None` immediately. One action becomes `MainButton::SingleAction`,+ // which arms the wait.+ // * Linux / FreeBSD — per the freedesktop spec the client declares the activation+ // action, and the daemon reports a body click as the action keyed+ // `"default"`. Without it there's no `ActionInvoked` signal to catch.+ // Requires the daemon to advertise the `actions` capability.+ //+ // Windows needs none of this: notify-rust wires `on_activated` /+ // `on_dismissed` into an mpsc channel unconditionally, and a body tap+ // arrives with empty `Arguments` — declaring an action would only add a+ // visible button.+ #[cfg(any(target_os = "macos", target_os = "linux", target_os = "freebsd"))]+ if click_listener_active {+ notification.action("default", "Open");+ }++ // `notify_rust::Notification::show()` is sync and runs an internal+ // blocking D-Bus call (via zbus's `block_on`). Calling it inside+ // `async_runtime::spawn` panics with "Cannot start a runtime from+ // within a runtime"; `spawn_blocking` parks it on a blocking thread.+ // We `.await` the join so we can capture the handle for tracking and+ // surface any error to the caller.+ let join_result = tauri::async_runtime::spawn_blocking(move || notification.show())+ .await+ .map_err(|e| {+ crate::Error::Io(std::io::Error::other(format!(+ "notification spawn_blocking join error: {e}"+ )))+ })?;++ match join_result {+ #[cfg(any(target_os = "linux", target_os = "freebsd"))]+ Ok(handle) => {+ track_and_observe(+ &app,+ caller_id,+ extra,+ title,+ body,+ handle,+ click_listener_active,+ );+ }+ // macOS / Windows: both wait on a blocking thread, for different+ // reasons.+ //+ // * macOS — `show()` posts nothing here, it only wraps the+ // `Notification`. Delivery happens in the handle's `Drop`+ // (fire-and-forget) or inside `wait_for_response`, which posts and+ // then blocks. So the listener decides which path delivers it, and+ // the `else` branch below is what shows the notification.+ // `mac-notification-sys` blocks on a condvar when called off the+ // main thread (it only spins the run loop when it *is* the main+ // thread), so the parked thread costs no CPU.+ // * Windows — the toast is already posted; the handle owns the+ // receiving end of the mpsc channel notify-rust's `on_activated` /+ // `on_dismissed` feed. WinRT delivers activations on a threadpool+ // thread, so this is a plain blocking `recv()` that doesn't need+ // the showing thread to pump messages. Dropping the handle is+ // harmless: the sends just fail silently.+ //+ // `wait_for_action` is deliberately not used: its `Ok(_)` arm+ // collapses `Default` into `"__closed"`, which would make a body tap+ // indistinguishable from a dismissal.+ #[cfg(any(target_os = "macos", target_os = "windows"))]+ Ok(handle) => {+ let _ = (title, body, app);+ if click_listener_active {+ tauri::async_runtime::spawn_blocking(move || {+ let responded = handle.wait_for_response(+ |response: ¬ify_rust::NotificationResponse| {+ imp::emit_click(caller_id, &extra, response);+ },+ );+ if let Err(e) = responded {+ log::warn!("Failed to await notification response: {e}");+ }+ });+ } else {+ drop(handle);+ }+ }+ // Propagate the underlying `notify-rust` failure (missing+ // notification daemon, D-Bus permission denied, etc.) instead of+ // swallowing it — matches the mobile/macOS behavior and lets JS+ // callers handle delivery failures.+ Err(e) => {+ return Err(crate::Error::Io(std::io::Error::other(format!(+ "Failed to show notification: {e}"+ ))));+ }+ }++ Ok(())+ }+}++// `async` mirrors the mobile/macOS plugin API so callers can `.await` uniformly.+#[allow(unknown_lints, clippy::unused_async, clippy::unused_async_trait_impl)]+impl<R: Runtime> Notifications<R> {+ pub fn builder(&self) -> NotificationsBuilder<R> {+ NotificationsBuilder::new(self.app.clone())+ }++ #[allow(unknown_lints, clippy::unused_async, clippy::unused_async_trait_impl)]+ pub async fn request_permission(&self) -> crate::Result<PermissionState> {+ Ok(PermissionState::Granted)+ }++ /// On Linux with the `push-notifications` feature this registers with the+ /// selected (or first available) `UnifiedPush` distributor and returns the+ /// endpoint URL. Apps that need endpoint stability across launches should+ /// call [`set_token`](Self::set_token) before this with a persisted token.+ #[allow(unknown_lints, clippy::unused_async, clippy::unused_async_trait_impl)]+ pub async fn register_for_push_notifications(&self) -> crate::Result<String> {+ #[cfg(all(target_os = "linux", feature = "push-notifications"))]+ {+ let state = self.unifiedpush_state().await?;+ state.register().await+ }+ #[cfg(not(all(target_os = "linux", feature = "push-notifications")))]+ {+ Err(crate::Error::Io(std::io::Error::other(+ "Push notifications are not supported on desktop platforms",+ )))+ }+ }++ /// Sync signature preserved for source compatibility — callers that need+ /// the Linux `UnifiedPush` unregister path should use+ /// [`unregister_for_push_notifications_async`] instead.+ pub fn unregister_for_push_notifications(&self) -> crate::Result<()> {+ Err(crate::Error::Io(std::io::Error::other(+ "Push notifications are not supported on desktop platforms",+ )))+ }++ /// Async unregister used by the Tauri command bridge. On Linux with the+ /// `push-notifications` feature this calls+ /// `org.unifiedpush.Distributor1.Unregister` and clears the in-memory+ /// active registration.+ #[allow(unknown_lints, clippy::unused_async, clippy::unused_async_trait_impl)]+ pub async fn unregister_for_push_notifications_async(&self) -> crate::Result<()> {+ #[cfg(all(target_os = "linux", feature = "push-notifications"))]+ {+ if let Some(state) = self.unifiedpush.get() {+ state.unregister().await?;+ }+ Ok(())+ }+ #[cfg(not(all(target_os = "linux", feature = "push-notifications")))]+ {+ Err(crate::Error::Io(std::io::Error::other(+ "Push notifications are not supported on desktop platforms",+ )))+ }+ }++ /// Lists currently running `UnifiedPush` distributors. Linux-only.+ #[cfg(all(target_os = "linux", feature = "push-notifications"))]+ pub async fn list_distributors(&self) -> crate::Result<Vec<String>> {+ let state = self.unifiedpush_state().await?;+ state.list_distributors().await+ }++ /// Pins the chosen `UnifiedPush` distributor for this process. Linux-only.+ #[cfg(all(target_os = "linux", feature = "push-notifications"))]+ pub async fn set_distributor(&self, name: String) -> crate::Result<()> {+ let state = self.unifiedpush_state().await?;+ state.set_distributor(name).await+ }++ /// Sets the `UnifiedPush` client token used on subsequent register calls.+ /// Pass the same token across launches to keep the endpoint URL stable.+ /// Linux-only.+ #[cfg(all(target_os = "linux", feature = "push-notifications"))]+ pub async fn set_token(&self, token: String) -> crate::Result<()> {+ let state = self.unifiedpush_state().await?;+ state.set_token(token).await+ }++ #[allow(unknown_lints, clippy::unused_async, clippy::unused_async_trait_impl)]+ pub async fn permission_state(&self) -> crate::Result<PermissionState> {+ Ok(PermissionState::Granted)+ }++ #[allow(unknown_lints, clippy::unused_async, clippy::unused_async_trait_impl)]+ pub async fn pending(&self) -> crate::Result<Vec<crate::PendingNotification>> {+ Err(crate::Error::Io(std::io::Error::other(+ "Pending notifications are not supported with notify-rust",+ )))+ }++ /// Linux / FreeBSD: returns the currently-tracked notifications. The list is+ /// populated by [`NotificationsBuilder::show`] and pruned by+ /// `cancel`/`cancel_all`/`remove_active`. Entries dismissed by the user+ /// or expired by the OS may linger until the next explicit cancel call,+ /// since notify-rust doesn't expose a non-consuming "closed" callback.+ ///+ /// macOS / Windows: still unsupported.+ #[allow(unknown_lints, clippy::unused_async, clippy::unused_async_trait_impl)]+ pub async fn active(&self) -> crate::Result<Vec<crate::ActiveNotification>> {+ #[cfg(any(target_os = "linux", target_os = "freebsd"))]+ {+ let active = self.active.lock().map_err(active_lock_err)?;+ Ok(active+ .values()+ .map(|entry| {+ crate::ActiveNotification::new(+ entry.caller_id,+ entry.title.clone(),+ entry.body.clone(),+ )+ })+ .collect())+ }+ #[cfg(not(any(target_os = "linux", target_os = "freebsd")))]+ {+ Err(crate::Error::Io(std::io::Error::other(+ "Active notifications are not supported with notify-rust",+ )))+ }+ }++ /// Records whether a `notificationClicked` listener is subscribed.+ ///+ /// Notifications shown while this is `true` are observed for the user's+ /// response and emit `notificationClicked` on activation (see+ /// [`NotificationsBuilder::show`]). Notifications already on screen when it+ /// flips are not retroactively observed, and there is no cold-start buffer —+ /// unlike the native Windows backend, this one can't be launched by a click.+ pub fn set_click_listener_active(&self, active: bool) -> crate::Result<()> {+ self.click_listener_active+ .store(active, std::sync::atomic::Ordering::Relaxed);+ Ok(())+ }++ /// Linux / FreeBSD: closes every tracked notification whose caller-supplied id+ /// appears in `ids` and removes it from the active map.+ /// macOS / Windows: unsupported.+ // Existing public signature; switching to `&[i32]` would be breaking.+ #[allow(clippy::needless_pass_by_value)]+ pub fn remove_active(&self, ids: Vec<i32>) -> crate::Result<()> {+ #[cfg(any(target_os = "linux", target_os = "freebsd"))]+ {+ self.close_by_caller_ids(&ids)+ }+ #[cfg(not(any(target_os = "linux", target_os = "freebsd")))]+ {+ let _ = ids;+ Err(crate::Error::Io(std::io::Error::other(+ "Removing active notifications is not supported with notify-rust",+ )))+ }+ }++ pub fn remove_all_active(&self) -> crate::Result<()> {+ Err(crate::Error::Io(std::io::Error::other(+ "Removing active notifications is not supported with notify-rust",+ )))+ }++ /// Same semantics as [`remove_active`](Self::remove_active) on Linux/FreeBSD;+ /// macOS / Windows: unsupported.+ // Existing public signature; switching to `&[i32]` would be breaking.+ #[allow(clippy::needless_pass_by_value)]+ pub fn cancel(&self, notifications: Vec<i32>) -> crate::Result<()> {+ #[cfg(any(target_os = "linux", target_os = "freebsd"))]+ {+ self.close_by_caller_ids(¬ifications)+ }+ #[cfg(not(any(target_os = "linux", target_os = "freebsd")))]+ {+ let _ = notifications;+ Err(crate::Error::Io(std::io::Error::other(+ "Canceling notifications is not supported with notify-rust",+ )))+ }+ }++ /// Linux / FreeBSD: closes every tracked notification.+ /// macOS / Windows: unsupported.+ pub fn cancel_all(&self) -> crate::Result<()> {+ #[cfg(any(target_os = "linux", target_os = "freebsd"))]+ {+ let drained: Vec<ActiveEntry> = {+ let mut active = self.active.lock().map_err(active_lock_err)?;+ active.drain().map(|(_, v)| v).collect()+ };+ for entry in drained {+ tauri::async_runtime::spawn(async move { entry.handle.close_async().await });+ }+ Ok(())+ }+ #[cfg(not(any(target_os = "linux", target_os = "freebsd")))]+ {+ Err(crate::Error::Io(std::io::Error::other(+ "Canceling notifications is not supported with notify-rust",+ )))+ }+ }++ pub fn register_action_types(&self, _types: Vec<crate::ActionType>) -> crate::Result<()> {+ Err(crate::Error::Io(std::io::Error::other(+ "Action types are not supported with notify-rust",+ )))+ }++ pub fn create_channel(&self, _channel: crate::Channel) -> crate::Result<()> {+ Err(crate::Error::Io(std::io::Error::other(+ "Notification channels are not supported with notify-rust",+ )))+ }++ pub fn delete_channel(&self, _id: impl Into<String>) -> crate::Result<()> {+ Err(crate::Error::Io(std::io::Error::other(+ "Notification channels are not supported with notify-rust",+ )))+ }++ pub fn list_channels(&self) -> crate::Result<Vec<crate::Channel>> {+ Err(crate::Error::Io(std::io::Error::other(+ "Notification channels are not supported with notify-rust",+ )))+ }+}++mod imp {+ //! Helpers for assembling the cross-platform `notify_rust::Notification`+ //! before handing it off to a blocking thread for delivery.++ /// Dispatches a `notificationClicked` event for a body tap, matching the+ /// payload the native backends emit (`{ id, data }`, see `windows.rs`).+ ///+ /// A body tap arrives as+ /// [`NotificationResponse::Default`](notify_rust::NotificationResponse::Default).+ /// On macOS and Linux, arming the wait requires declaring a `"default"`+ /// action (see `NotificationsBuilder::show`), so tapping that button instead+ /// arrives as `Action("default")` — both mean "the user activated this+ /// notification". `Closed` is ignored, so dismissal and expiry fire nothing.+ pub fn emit_click(+ id: i32,+ extra: &std::collections::HashMap<String, serde_json::Value>,+ response: ¬ify_rust::NotificationResponse,+ ) {+ if !is_activation(response) {+ log::debug!("notification {id} closed without activation: {response:?}");+ return;+ }+ if let Err(e) = crate::listeners::trigger("notificationClicked", click_payload(id, extra)) {+ log::warn!("Failed to dispatch notificationClicked: {e}");+ }+ }++ /// Whether the user activated the notification: a body tap (`Default`) or+ /// the `"default"` action declared to arm the wait on macOS/Linux/FreeBSD. Any+ /// other action, a reply, or a close is not a click.+ fn is_activation(response: ¬ify_rust::NotificationResponse) -> bool {+ use notify_rust::NotificationResponse;+ match response {+ NotificationResponse::Default => true,+ NotificationResponse::Action(key) => key == "default",+ _ => false,+ }+ }++ /// The `notificationClicked` payload, shaped like the native backends'+ /// (`{ id, data }`).+ fn click_payload(+ id: i32,+ extra: &std::collections::HashMap<String, serde_json::Value>,+ ) -> String {+ serde_json::json!({ "id": id, "data": extra }).to_string()+ }++ #[cfg(windows)]+ use std::path::MAIN_SEPARATOR as SEP;++ /// Builds a fully-configured `notify_rust::Notification` from the parts+ /// the cross-platform builder produced. Returns an error only on Windows+ /// if `current_exe` lookup fails; other platforms are infallible — the+ /// `Result` wrapper exists for the Windows branch only.+ #[allow(clippy::unnecessary_wraps)]+ pub fn build_notification(+ title: Option<&str>,+ body: Option<&str>,+ icon: Option<&str>,+ identifier: &str,+ ) -> crate::Result<notify_rust::Notification> {+ let mut notification = notify_rust::Notification::new();+ if let Some(body) = body {+ notification.body(body);+ }+ if let Some(title) = title {+ notification.summary(title);+ }+ if let Some(icon) = icon {+ notification.icon(icon);+ } else {+ notification.auto_icon();+ }++ #[cfg(windows)]+ {+ let exe = tauri::utils::platform::current_exe()?;+ let exe_dir = exe.parent().expect("failed to get exe directory");+ let curr_dir = exe_dir.display().to_string();+ // Only set System.AppUserModel.ID on the installed app, not when+ // running from `cargo`'s target dirs.+ if !(curr_dir.ends_with(format!("{SEP}target{SEP}debug").as_str())+ || curr_dir.ends_with(format!("{SEP}target{SEP}release").as_str()))+ {+ notification.app_id(identifier);+ }+ }+ #[cfg(target_os = "macos")]+ {+ let _ = notify_rust::set_application(if tauri::is_dev() {+ "com.apple.Terminal"+ } else {+ identifier+ });+ }+ // `identifier` is used by the cfg-gated Windows/macOS branches above+ // — silence the unused-parameter warning on Linux/FreeBSD.+ #[cfg(any(target_os = "linux", target_os = "freebsd"))]+ let _ = identifier;++ Ok(notification)+ }++ #[cfg(test)]+ mod tests {+ use super::{click_payload, is_activation};+ use notify_rust::{CloseReason, NotificationResponse};++ #[test]+ fn body_tap_is_activation() {+ assert!(is_activation(&NotificationResponse::Default));+ }++ #[test]+ fn default_action_is_activation() {+ assert!(is_activation(&NotificationResponse::Action(+ "default".to_owned()+ )));+ }++ #[test]+ fn other_action_is_not_activation() {+ assert!(!is_activation(&NotificationResponse::Action(+ "settings".to_owned()+ )));+ }++ #[test]+ fn closes_are_not_activation() {+ for reason in [+ CloseReason::Expired,+ CloseReason::Dismissed,+ CloseReason::CloseAction,+ CloseReason::Other(0),+ ] {+ assert!(!is_activation(&NotificationResponse::Closed(reason)));+ }+ }++ #[test]+ fn payload_matches_native_shape() {+ let mut extra = std::collections::HashMap::new();+ extra.insert("k".to_owned(), serde_json::json!("v"));+ let payload: serde_json::Value = serde_json::from_str(&click_payload(7, &extra))+ .expect("click payload is valid json");+ assert_eq!(+ payload,+ serde_json::json!({ "id": 7, "data": { "k": "v" } })+ );+ }+ }+}diff --git a/src-tauri/vendor/tauri-plugin-notifications/src/error.rs b/src-tauri/vendor/tauri-plugin-notifications/src/error.rsnew file mode 100644index 00000000..28e0a1b6--- /dev/null+++ b/src-tauri/vendor/tauri-plugin-notifications/src/error.rs@@ -0,0 +1,114 @@+use serde::{Serialize, ser::Serializer};++pub type Result<T> = std::result::Result<T, Error>;++/// Replica of the [`tauri::plugin::mobile::ErrorResponse`] for desktop platforms.+#[cfg(desktop)]+#[derive(Debug, thiserror::Error, Clone, serde::Deserialize)]+pub struct ErrorResponse<T = ()> {+ /// Error code.+ pub code: Option<String>,+ /// Error message.+ pub message: Option<String>,+ /// Optional error data.+ #[serde(flatten)]+ pub data: T,+}++#[cfg(desktop)]+impl<T> std::fmt::Display for ErrorResponse<T> {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ if let Some(code) = &self.code {+ write!(f, "[{code}]")?;+ if self.message.is_some() {+ write!(f, " - ")?;+ }+ }+ if let Some(message) = &self.message {+ write!(f, "{message}")?;+ }+ Ok(())+ }+}++/// Replica of the [`tauri::plugin::mobile::PluginInvokeError`] for desktop platforms.+#[cfg(desktop)]+#[derive(Debug, thiserror::Error)]+pub enum PluginInvokeError {+ /// Error returned from direct desktop plugin.+ #[error(transparent)]+ InvokeRejected(#[from] ErrorResponse),+ /// Failed to deserialize response.+ #[error("failed to deserialize response: {0}")]+ CannotDeserializeResponse(serde_json::Error),+ /// Failed to serialize request payload.+ #[error("failed to serialize payload: {0}")]+ CannotSerializePayload(serde_json::Error),+}++#[derive(Debug, thiserror::Error)]+pub enum Error {+ #[error(transparent)]+ Io(#[from] std::io::Error),+ #[cfg(mobile)]+ #[error(transparent)]+ PluginInvoke(#[from] tauri::plugin::mobile::PluginInvokeError),+ #[cfg(desktop)]+ #[error(transparent)]+ PluginInvoke(#[from] crate::error::PluginInvokeError),+}++impl Serialize for Error {+ fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>+ where+ S: Serializer,+ {+ serializer.serialize_str(self.to_string().as_ref())+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use std::io;++ #[test]+ fn test_io_error_conversion() {+ let io_err = io::Error::new(io::ErrorKind::NotFound, "file not found");+ let err: Error = io_err.into();+ assert!(matches!(err, Error::Io(_)));+ }++ #[test]+ fn test_io_error_serialization() {+ let io_err = io::Error::new(io::ErrorKind::PermissionDenied, "access denied");+ let err = Error::Io(io_err);+ let json = serde_json::to_string(&err).expect("Failed to serialize IO error");+ assert!(json.contains("access denied"));+ }++ #[test]+ fn test_io_error_display() {+ let io_err = io::Error::new(io::ErrorKind::NotFound, "test error");+ let err = Error::Io(io_err);+ let display_str = format!("{err}");+ assert!(display_str.contains("test error"));+ }++ #[cfg(mobile)]+ #[test]+ fn test_plugin_invoke_error_conversion() {+ use tauri::plugin::mobile::PluginInvokeError;++ let plugin_err = PluginInvokeError::MethodNotFound("test_method".to_string());+ let err: Error = plugin_err.into();+ assert!(matches!(err, Error::PluginInvoke(_)));+ }++ #[test]+ fn test_result_type_err() {+ let io_err = io::Error::other("test");+ let result: Result<i32> = Err(Error::Io(io_err));+ assert!(result.is_err());+ }+}diff --git a/src-tauri/vendor/tauri-plugin-notifications/src/lib.rs b/src-tauri/vendor/tauri-plugin-notifications/src/lib.rsnew file mode 100644index 00000000..ec7807da--- /dev/null+++ b/src-tauri/vendor/tauri-plugin-notifications/src/lib.rs@@ -0,0 +1,530 @@+//! Send message notifications (brief auto-expiring OS window element) to your user. Can also be used with the Notification Web API.++use serde::{Deserialize, Serialize};+#[cfg(desktop)]+use tauri::AppHandle;+#[cfg(mobile)]+use tauri::plugin::PluginHandle;+use tauri::{+ Manager, Runtime,+ plugin::{Builder, TauriPlugin},+};++/// Top-level plugin config deserialized from the `plugins.notifications` block+/// in `tauri.conf.json`. Optional in its entirety — apps without a config block+/// get `PluginConfig::default()`.+#[derive(Debug, Default, Clone, Deserialize)]+#[serde(default, rename_all = "camelCase")]+pub struct PluginConfig {+ #[cfg(target_os = "windows")]+ pub windows: WindowsConfig,+}++/// Windows-only plugin config.+///+/// Currently carries the toast activator CLSID used by+/// `INotificationActivationCallback` registration; absent value means+/// COM-based activation is disabled and the plugin falls back to in-process+/// `Activated` events only.+#[cfg(target_os = "windows")]+#[derive(Debug, Default, Clone, Deserialize)]+#[serde(default, rename_all = "camelCase")]+pub struct WindowsConfig {+ /// Toast activator CLSID. Must match the GUID declared in the MSIX+ /// manifest's `<desktop:ToastNotificationActivation ToastActivatorCLSID>`+ /// and `<com:Class Id>` entries. Accepts the `xxxxxxxx-xxxx-...` form+ /// with or without surrounding braces.+ pub toast_activator_clsid: Option<String>,+}++pub use models::*;+pub use tauri::plugin::PermissionState;++#[cfg(all(+ desktop,+ any(feature = "notify-rust", target_os = "linux", target_os = "freebsd")+))]+mod desktop;+#[cfg(all(target_os = "macos", not(feature = "notify-rust")))]+mod macos;+#[cfg(mobile)]+mod mobile;+#[cfg(all(desktop, target_os = "linux", feature = "push-notifications"))]+mod unifiedpush;+#[cfg(all(target_os = "windows", not(feature = "notify-rust")))]+mod windows;++mod commands;+mod error;+#[cfg(desktop)]+mod listeners;+mod models;++pub use error::{Error, Result};++#[cfg(all(+ desktop,+ any(feature = "notify-rust", target_os = "linux", target_os = "freebsd")+))]+pub use desktop::Notifications;+#[cfg(all(target_os = "macos", not(feature = "notify-rust")))]+pub use macos::Notifications;+#[cfg(mobile)]+pub use mobile::Notifications;+#[cfg(all(target_os = "windows", not(feature = "notify-rust")))]+pub use windows::Notifications;++/// The notification builder.+#[derive(Debug)]+pub struct NotificationsBuilder<R: Runtime> {+ #[cfg(desktop)]+ #[allow(dead_code)]+ app: AppHandle<R>,+ #[cfg(all(target_os = "macos", not(feature = "notify-rust")))]+ plugin: std::sync::Arc<macos::NotificationPlugin>,+ #[cfg(all(target_os = "windows", not(feature = "notify-rust")))]+ plugin: std::sync::Arc<windows::WindowsPlugin>,+ #[cfg(mobile)]+ handle: PluginHandle<R>,+ pub(crate) data: NotificationData,+}++impl<R: Runtime> NotificationsBuilder<R> {+ #[cfg(all(+ desktop,+ any(feature = "notify-rust", target_os = "linux", target_os = "freebsd")+ ))]+ fn new(app: AppHandle<R>) -> Self {+ Self {+ app,+ data: NotificationData::default(),+ }+ }++ #[cfg(all(target_os = "macos", not(feature = "notify-rust")))]+ fn new(app: AppHandle<R>, plugin: std::sync::Arc<macos::NotificationPlugin>) -> Self {+ Self {+ app,+ plugin,+ data: NotificationData::default(),+ }+ }++ #[cfg(all(target_os = "windows", not(feature = "notify-rust")))]+ fn new(app: AppHandle<R>, plugin: std::sync::Arc<windows::WindowsPlugin>) -> Self {+ Self {+ app,+ plugin,+ data: NotificationData::default(),+ }+ }++ #[cfg(mobile)]+ fn new(handle: PluginHandle<R>) -> Self {+ Self {+ handle,+ data: NotificationData::default(),+ }+ }++ /// Sets the notification identifier.+ #[must_use]+ pub const fn id(mut self, id: i32) -> Self {+ self.data.id = id;+ self+ }++ /// Identifier of the {@link Channel} that delivers this notification.+ ///+ /// If the channel does not exist, the notification won't fire.+ /// Make sure the channel exists with {@link listChannels} and {@link createChannel}.+ #[must_use]+ pub fn channel_id(mut self, id: impl Into<String>) -> Self {+ self.data.channel_id.replace(id.into());+ self+ }++ /// Sets the notification title.+ #[must_use]+ pub fn title(mut self, title: impl Into<String>) -> Self {+ self.data.title.replace(title.into());+ self+ }++ /// Sets the notification body.+ #[must_use]+ pub fn body(mut self, body: impl Into<String>) -> Self {+ self.data.body.replace(body.into());+ self+ }++ /// Schedule this notification to fire on a later time or a fixed interval.+ #[must_use]+ pub const fn schedule(mut self, schedule: Schedule) -> Self {+ self.data.schedule.replace(schedule);+ self+ }++ /// Multiline text.+ /// Changes the notification style to big text.+ /// Cannot be used with `inboxLines`.+ #[must_use]+ pub fn large_body(mut self, large_body: impl Into<String>) -> Self {+ self.data.large_body.replace(large_body.into());+ self+ }++ /// Detail text for the notification with `largeBody`, `inboxLines` or `groupSummary`.+ #[must_use]+ pub fn summary(mut self, summary: impl Into<String>) -> Self {+ self.data.summary.replace(summary.into());+ self+ }++ /// Defines an action type for this notification.+ #[must_use]+ pub fn action_type_id(mut self, action_type_id: impl Into<String>) -> Self {+ self.data.action_type_id.replace(action_type_id.into());+ self+ }++ /// Identifier used to group multiple notifications.+ ///+ /// <https://developer.apple.com/documentation/usernotifications/unmutablenotificationcontent/1649872-threadidentifier>+ #[must_use]+ pub fn group(mut self, group: impl Into<String>) -> Self {+ self.data.group.replace(group.into());+ self+ }++ /// Instructs the system that this notification is the summary of a group on Android.+ #[must_use]+ pub const fn group_summary(mut self) -> Self {+ self.data.group_summary = true;+ self+ }++ /// The sound resource name. Only available on mobile.+ #[must_use]+ pub fn sound(mut self, sound: impl Into<String>) -> Self {+ self.data.sound.replace(sound.into());+ self+ }++ /// Append an inbox line to the notification.+ /// Changes the notification style to inbox.+ /// Cannot be used with `largeBody`.+ ///+ /// Only supports up to 5 lines.+ #[must_use]+ pub fn inbox_line(mut self, line: impl Into<String>) -> Self {+ self.data.inbox_lines.push(line.into());+ self+ }++ /// Notification icon.+ ///+ /// On Android the icon must be placed in the app's `res/drawable` folder.+ #[must_use]+ pub fn icon(mut self, icon: impl Into<String>) -> Self {+ self.data.icon.replace(icon.into());+ self+ }++ /// Notification large icon (Android).+ ///+ /// The icon must be placed in the app's `res/drawable` folder.+ #[must_use]+ pub fn large_icon(mut self, large_icon: impl Into<String>) -> Self {+ self.data.large_icon.replace(large_icon.into());+ self+ }++ /// Icon color on Android.+ #[must_use]+ pub fn icon_color(mut self, icon_color: impl Into<String>) -> Self {+ self.data.icon_color.replace(icon_color.into());+ self+ }++ /// Append an attachment to the notification.+ #[must_use]+ pub fn attachment(mut self, attachment: Attachment) -> Self {+ self.data.attachments.push(attachment);+ self+ }++ /// Adds an extra payload to store in the notification.+ #[must_use]+ pub fn extra(mut self, key: impl Into<String>, value: impl Serialize) -> Self {+ if let Ok(value) = serde_json::to_value(value) {+ self.data.extra.insert(key.into(), value);+ }+ self+ }++ /// If true, the notification cannot be dismissed by the user on Android.+ ///+ /// An application service must manage the dismissal of the notification.+ /// It is typically used to indicate a background task that is pending (e.g. a file download)+ /// or the user is engaged with (e.g. playing music).+ #[must_use]+ pub const fn ongoing(mut self) -> Self {+ self.data.ongoing = true;+ self+ }++ /// Automatically cancel the notification when the user clicks on it.+ #[must_use]+ pub const fn auto_cancel(mut self) -> Self {+ self.data.auto_cancel = true;+ self+ }++ /// Changes the notification presentation to be silent on iOS (no badge, no sound, not listed).+ #[must_use]+ pub const fn silent(mut self) -> Self {+ self.data.silent = true;+ self+ }+}++/// Extensions to [`tauri::App`], [`tauri::AppHandle`], [`tauri::WebviewWindow`], [`tauri::Webview`] and [`tauri::Window`] to access the notification APIs.+pub trait NotificationsExt<R: Runtime> {+ fn notifications(&self) -> &Notifications<R>;+}++impl<R: Runtime, T: Manager<R>> crate::NotificationsExt<R> for T {+ fn notifications(&self) -> &Notifications<R> {+ self.state::<Notifications<R>>().inner()+ }+}++/// Initializes the plugin.+#[must_use]+pub fn init<R: Runtime>() -> TauriPlugin<R, Option<PluginConfig>> {+ Builder::<R, Option<PluginConfig>>::new("notifications")+ .invoke_handler(tauri::generate_handler![+ commands::notify,+ commands::request_permission,+ commands::register_for_push_notifications,+ commands::unregister_for_push_notifications,+ commands::is_permission_granted,+ commands::register_action_types,+ commands::get_pending,+ commands::get_active,+ commands::set_click_listener_active,+ commands::remove_active,+ commands::remove_all,+ commands::cancel,+ commands::cancel_all,+ commands::create_channel,+ commands::delete_channel,+ commands::list_channels,+ #[cfg(desktop)]+ listeners::register_listener,+ #[cfg(desktop)]+ listeners::remove_listener,+ #[cfg(all(desktop, target_os = "linux", feature = "push-notifications"))]+ commands::list_distributors,+ #[cfg(all(desktop, target_os = "linux", feature = "push-notifications"))]+ commands::set_distributor,+ #[cfg(all(desktop, target_os = "linux", feature = "push-notifications"))]+ commands::set_token,+ ])+ .setup(|app, api| {+ #[cfg(desktop)]+ listeners::init();+ #[cfg(all(target_os = "windows", not(feature = "notify-rust")))]+ let windows_config = api+ .config()+ .as_ref()+ .map(|c| c.windows.clone())+ .unwrap_or_default();+ #[cfg(mobile)]+ let notification = mobile::init(app, api)?;+ #[cfg(all(+ desktop,+ any(feature = "notify-rust", target_os = "linux", target_os = "freebsd")+ ))]+ let notification = desktop::init(app, api)?;+ #[cfg(all(target_os = "macos", not(feature = "notify-rust")))]+ let notification = macos::init(app, api)?;+ #[cfg(all(target_os = "windows", not(feature = "notify-rust")))]+ let notification = windows::init(app, api, windows_config)?;+ app.manage(notification);+ Ok(())+ })+ .build()+}++#[cfg(test)]+mod tests {+ use super::*;++ // Helper function to create a test builder without needing a runtime+ #[cfg(desktop)]+ fn create_test_data() -> NotificationData {+ NotificationData::default()+ }++ #[cfg(mobile)]+ fn create_test_data() -> NotificationData {+ NotificationData::default()+ }++ #[test]+ fn test_notification_data_id() {+ let mut data = create_test_data();+ data.id = 42;+ assert_eq!(data.id, 42);+ }++ #[test]+ fn test_notification_data_channel_id() {+ let mut data = create_test_data();+ data.channel_id = Some("test_channel".to_string());+ assert_eq!(data.channel_id, Some("test_channel".to_string()));+ }++ #[test]+ fn test_notification_data_title() {+ let mut data = create_test_data();+ data.title = Some("Test Title".to_string());+ assert_eq!(data.title, Some("Test Title".to_string()));+ }++ #[test]+ fn test_notification_data_body() {+ let mut data = create_test_data();+ data.body = Some("Test Body".to_string());+ assert_eq!(data.body, Some("Test Body".to_string()));+ }++ #[test]+ fn test_notification_data_large_body() {+ let mut data = create_test_data();+ data.large_body = Some("Large Body Text".to_string());+ assert_eq!(data.large_body, Some("Large Body Text".to_string()));+ }++ #[test]+ fn test_notification_data_summary() {+ let mut data = create_test_data();+ data.summary = Some("Summary Text".to_string());+ assert_eq!(data.summary, Some("Summary Text".to_string()));+ }++ #[test]+ fn test_notification_data_action_type_id() {+ let mut data = create_test_data();+ data.action_type_id = Some("action_type".to_string());+ assert_eq!(data.action_type_id, Some("action_type".to_string()));+ }++ #[test]+ fn test_notification_data_group() {+ let mut data = create_test_data();+ data.group = Some("test_group".to_string());+ assert_eq!(data.group, Some("test_group".to_string()));+ }++ #[test]+ fn test_notification_data_group_summary() {+ let mut data = create_test_data();+ data.group_summary = true;+ assert!(data.group_summary);+ }++ #[test]+ fn test_notification_data_sound() {+ let mut data = create_test_data();+ data.sound = Some("notification_sound".to_string());+ assert_eq!(data.sound, Some("notification_sound".to_string()));+ }++ #[test]+ fn test_notification_data_inbox_lines() {+ let mut data = create_test_data();+ data.inbox_lines.push("Line 1".to_string());+ data.inbox_lines.push("Line 2".to_string());+ assert_eq!(data.inbox_lines.len(), 2);+ assert_eq!(data.inbox_lines[0], "Line 1");+ assert_eq!(data.inbox_lines[1], "Line 2");+ }++ #[test]+ fn test_notification_data_icon() {+ let mut data = create_test_data();+ data.icon = Some("icon_name".to_string());+ assert_eq!(data.icon, Some("icon_name".to_string()));+ }++ #[test]+ fn test_notification_data_large_icon() {+ let mut data = create_test_data();+ data.large_icon = Some("large_icon_name".to_string());+ assert_eq!(data.large_icon, Some("large_icon_name".to_string()));+ }++ #[test]+ fn test_notification_data_icon_color() {+ let mut data = create_test_data();+ data.icon_color = Some("#FF0000".to_string());+ assert_eq!(data.icon_color, Some("#FF0000".to_string()));+ }++ #[test]+ fn test_notification_data_attachments() {+ let mut data = create_test_data();+ let url = url::Url::parse("https://example.com/image.png").expect("Failed to parse URL");+ let attachment = Attachment::new("attachment1", url);+ data.attachments.push(attachment);+ assert_eq!(data.attachments.len(), 1);+ }++ #[test]+ fn test_notification_data_extra() {+ let mut data = create_test_data();+ data.extra+ .insert("key1".to_string(), serde_json::json!("value1"));+ data.extra.insert("key2".to_string(), serde_json::json!(42));+ assert_eq!(data.extra.len(), 2);+ assert_eq!(data.extra.get("key1"), Some(&serde_json::json!("value1")));+ assert_eq!(data.extra.get("key2"), Some(&serde_json::json!(42)));+ }++ #[test]+ fn test_notification_data_ongoing() {+ let mut data = create_test_data();+ data.ongoing = true;+ assert!(data.ongoing);+ }++ #[test]+ fn test_notification_data_auto_cancel() {+ let mut data = create_test_data();+ data.auto_cancel = true;+ assert!(data.auto_cancel);+ }++ #[test]+ fn test_notification_data_silent() {+ let mut data = create_test_data();+ data.silent = true;+ assert!(data.silent);+ }++ #[test]+ fn test_notification_data_schedule() {+ let mut data = create_test_data();+ let schedule = Schedule::Every {+ interval: ScheduleEvery::Day,+ count: 1,+ allow_while_idle: false,+ };+ data.schedule = Some(schedule);+ assert!(data.schedule.is_some());+ assert!(matches!(data.schedule, Some(Schedule::Every { .. })));+ }+}diff --git a/src-tauri/vendor/tauri-plugin-notifications/src/listeners.rs b/src-tauri/vendor/tauri-plugin-notifications/src/listeners.rsnew file mode 100644index 00000000..0c7848c8--- /dev/null+++ b/src-tauri/vendor/tauri-plugin-notifications/src/listeners.rs@@ -0,0 +1,150 @@+//! Shared listener management for desktop platforms.+//!+//! This is a replication of Tauri's plugin listener implementation which is+//! currently only available for mobile plugins. Once Tauri adds desktop support+//! for plugin listeners, this module can be removed.+//!+//! Provides channel-based event delivery for notification events such as+//! notification received, action performed, and notification clicked.++use std::collections::HashMap;+use std::sync::{OnceLock, RwLock};++#[cfg(all(target_os = "windows", not(feature = "notify-rust")))]+use tauri::Manager;+use tauri::{AppHandle, Runtime};++use crate::error::{ErrorResponse, PluginInvokeError};++type ChannelMap = HashMap<u32, tauri::ipc::Channel<serde_json::Value>>;+type ListenerMap = HashMap<String, ChannelMap>;++static LISTENERS: OnceLock<RwLock<ListenerMap>> = OnceLock::new();++/// Initialize the listeners registry. Call this during plugin init.+pub fn init() {+ let _ = LISTENERS.get_or_init(|| RwLock::new(HashMap::new()));+}++/// Returns `true` if at least one channel is subscribed for `event`. Used by+/// the Windows COM activator to decide whether to deliver a click payload live+/// or buffer it for a later subscriber — buffering when a live listener already+/// exists causes duplicate events on re-subscription (e.g. hot reload).+#[cfg(all(target_os = "windows", not(feature = "notify-rust")))]+pub fn has_listeners(event: &str) -> bool {+ let Some(listeners) = LISTENERS.get() else {+ return false;+ };+ let Ok(guard) = listeners.read() else {+ return false;+ };+ guard.get(event).is_some_and(|c| !c.is_empty())+}++/// Trigger an event to all registered listeners for the given event name.+///+/// Called by platform-specific code when notification events occur.+// Owned `payload` is taken from the FFI bridge in `macos.rs`.+#[allow(dead_code, clippy::needless_pass_by_value)]+pub fn trigger(event: &str, payload: String) -> crate::Result<()> {+ let listeners = LISTENERS.get().ok_or_else(|| {+ crate::Error::from(PluginInvokeError::InvokeRejected(ErrorResponse {+ code: None,+ message: Some("Listeners not initialized".to_string()),+ data: (),+ }))+ })?;++ let channels: Vec<tauri::ipc::Channel<serde_json::Value>> = {+ let guard = listeners.read().map_err(|e| {+ crate::Error::from(PluginInvokeError::InvokeRejected(ErrorResponse {+ code: None,+ message: Some(format!("Failed to acquire read lock: {e}")),+ data: (),+ }))+ })?;+ guard+ .get(event)+ .map(|c| c.values().cloned().collect())+ .unwrap_or_default()+ };++ if !channels.is_empty() {+ let value: serde_json::Value = serde_json::from_str(&payload).map_err(|e| {+ crate::Error::from(PluginInvokeError::InvokeRejected(ErrorResponse {+ code: None,+ message: Some(format!("Failed to parse payload JSON: {e}")),+ data: (),+ }))+ })?;+ for channel in &channels {+ let _ = channel.send(value.clone());+ }+ }+ Ok(())+}++/// Register a channel to receive events for the given event name.+///+/// On Windows, subscribing to `notificationClicked` synchronously drains any+/// cold-start activation payload buffered by the COM activator before the JS+/// listener was up. That makes the `push-listener.tsx` contract ("subscribing+/// flushes the buffered tap") work without the app calling any extra command.+// Tauri commands receive serde-deserialized owned values.+#[allow(clippy::needless_pass_by_value)]+#[tauri::command]+pub fn register_listener<R: Runtime>(+ app: AppHandle<R>,+ event: String,+ handler: tauri::ipc::Channel<serde_json::Value>,+) -> crate::Result<()> {+ let listeners = LISTENERS.get_or_init(|| RwLock::new(HashMap::new()));+ let should_drain_clicks = event == "notificationClicked";+ {+ let mut guard = listeners.write().map_err(|e| {+ crate::Error::from(PluginInvokeError::InvokeRejected(ErrorResponse {+ code: None,+ message: Some(format!("Failed to acquire write lock: {e}")),+ data: (),+ }))+ })?;+ guard+ .entry(event)+ .or_default()+ .insert(handler.id(), handler);+ }+ #[cfg(all(target_os = "windows", not(feature = "notify-rust")))]+ if should_drain_clicks && let Some(notif) = app.try_state::<crate::Notifications<R>>() {+ notif.drain_pending_clicks();+ }+ #[cfg(not(all(target_os = "windows", not(feature = "notify-rust"))))]+ let _ = (app, should_drain_clicks);+ Ok(())+}++/// Remove a previously registered listener by event name and channel ID.+// Tauri commands receive serde-deserialized owned values.+#[allow(clippy::needless_pass_by_value)]+#[tauri::command]+pub fn remove_listener(event: String, channel_id: u32) -> crate::Result<()> {+ let listeners = LISTENERS.get().ok_or_else(|| {+ crate::Error::from(PluginInvokeError::InvokeRejected(ErrorResponse {+ code: None,+ message: Some("Listeners not initialized".to_string()),+ data: (),+ }))+ })?;+ {+ let mut guard = listeners.write().map_err(|e| {+ crate::Error::from(PluginInvokeError::InvokeRejected(ErrorResponse {+ code: None,+ message: Some(format!("Failed to acquire write lock: {e}")),+ data: (),+ }))+ })?;+ if let Some(channels) = guard.get_mut(&event) {+ channels.remove(&channel_id);+ }+ }+ Ok(())+}diff --git a/src-tauri/vendor/tauri-plugin-notifications/src/macos.rs b/src-tauri/vendor/tauri-plugin-notifications/src/macos.rsnew file mode 100644index 00000000..4ad3a9d7--- /dev/null+++ b/src-tauri/vendor/tauri-plugin-notifications/src/macos.rs@@ -0,0 +1,349 @@+use serde::de::DeserializeOwned;+use tauri::{+ AppHandle, Runtime,+ plugin::{PermissionState, PluginApi},+};++use crate::models::{ActionType, ActiveNotification, PendingNotification};++use std::{collections::HashMap, sync::Arc};++pub use ffi::NotificationPlugin;++/// Validation checks for macOS notifications functionality.+///+/// `UserNotifications` requires the app to run from a signed .app bundle.+/// During development with `tauri dev`, the binary runs+/// directly without a bundle, causing `UserNotifications` calls to fail silently or crash.+mod validation {+ /// Ensures the app is running from a .app bundle.+ pub fn require_bundle() -> crate::Result<()> {+ std::env::current_exe()+ .ok()+ .and_then(|exe| {+ let macos = exe.parent()?;+ let contents = macos.parent()?;+ let bundle = contents.parent()?;+ (macos.ends_with("MacOS")+ && contents.ends_with("Contents")+ && bundle.to_string_lossy().ends_with(".app"))+ .then_some(())+ })+ .ok_or_else(|| {+ crate::error::PluginInvokeError::InvokeRejected(crate::error::ErrorResponse {+ code: None,+ message: Some("Notifications plugin requires the app to run from a .app bundle. You can enable notify-rust feature for development.".to_string()),+ data: (),+ })+ .into()+ })+ }+}++#[swift_bridge::bridge]+mod ffi {+ pub enum FFIResult {+ Err(String), // error message from Swift+ }++ extern "Rust" {+ #[swift_bridge(swift_name = "bridgeTrigger")]+ fn bridge_trigger(event: String, payload: String) -> Result<(), FFIResult>;+ }++ extern "Swift" {+ #[swift_bridge(Sendable)]+ type NotificationPlugin;+ #[swift_bridge(init, swift_name = "initPlugin")]+ fn init_plugin() -> NotificationPlugin;++ async fn show(&self, args: String) -> Result<i32, FFIResult>;++ async fn requestPermissions(&self) -> Result<String, FFIResult>;+ async fn registerForPushNotifications(&self) -> Result<String, FFIResult>;+ fn unregisterForPushNotifications(&self) -> Result<(), FFIResult>;+ async fn checkPermissions(&self) -> Result<String, FFIResult>;+ fn cancel(&self, args: String) -> Result<(), FFIResult>;+ fn cancelAll(&self) -> Result<(), FFIResult>;+ async fn getPending(&self) -> Result<String, FFIResult>;+ fn registerActionTypes(&self, args: String) -> Result<(), FFIResult>;+ fn removeActive(&self, args: String) -> Result<(), FFIResult>;+ fn removeAllActive(&self) -> Result<(), FFIResult>;+ async fn getActive(&self) -> Result<String, FFIResult>;+ fn setClickListenerActive(&self, args: String) -> Result<(), FFIResult>;+ }+}++impl std::fmt::Debug for ffi::NotificationPlugin {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ f.debug_struct("NotificationPlugin").finish()+ }+}++/// Extension trait for parsing FFI responses from Swift into typed Rust results.+trait ParseFfiResponse {+ /// Deserializes a JSON response into the target type, converting FFI errors+ /// into plugin errors.+ fn parse<T: DeserializeOwned>(self) -> crate::Result<T>;+}++impl ParseFfiResponse for Result<String, ffi::FFIResult> {+ fn parse<T: DeserializeOwned>(self) -> crate::Result<T> {+ match self {+ Ok(json) => serde_json::from_str(&json)+ .map_err(|e| crate::error::PluginInvokeError::CannotDeserializeResponse(e).into()),+ Err(ffi::FFIResult::Err(msg)) => Err(crate::error::PluginInvokeError::InvokeRejected(+ crate::error::ErrorResponse {+ code: None,+ message: Some(msg),+ data: (),+ },+ )+ .into()),+ }+ }+}++trait ParseFfiVoidResponse {+ fn parse_void(self) -> crate::Result<()>;+}++impl ParseFfiVoidResponse for Result<(), ffi::FFIResult> {+ fn parse_void(self) -> crate::Result<()> {+ match self {+ Ok(()) => Ok(()),+ Err(ffi::FFIResult::Err(msg)) => Err(crate::error::PluginInvokeError::InvokeRejected(+ crate::error::ErrorResponse {+ code: None,+ message: Some(msg),+ data: (),+ },+ )+ .into()),+ }+ }+}++impl ParseFfiVoidResponse for Result<i32, ffi::FFIResult> {+ fn parse_void(self) -> crate::Result<()> {+ match self {+ Ok(_) => Ok(()),+ Err(ffi::FFIResult::Err(msg)) => Err(crate::error::PluginInvokeError::InvokeRejected(+ crate::error::ErrorResponse {+ code: None,+ message: Some(msg),+ data: (),+ },+ )+ .into()),+ }+ }+}++/// Called by Swift via FFI when transaction updates occur.+// Owned strings come straight from the Swift bridge.+#[allow(clippy::needless_pass_by_value)]+fn bridge_trigger(event: String, payload: String) -> Result<(), ffi::FFIResult> {+ crate::listeners::trigger(&event, payload)+ .map_err(|e| ffi::FFIResult::Err(format!("Failed to trigger event '{event}': {e}")))+}++pub fn init<R: Runtime, C: DeserializeOwned>(+ app: &AppHandle<R>,+ _api: PluginApi<R, C>,+) -> crate::Result<Notifications<R>> {+ validation::require_bundle()?;++ Ok(Notifications {+ app: app.clone(),+ plugin: Arc::new(ffi::NotificationPlugin::init_plugin()),+ })+}++impl<R: Runtime> crate::NotificationsBuilder<R> {+ pub async fn show(self) -> crate::Result<()> {+ validation::require_bundle()?;++ self.plugin+ .show(+ serde_json::to_string(&self.data)+ .map_err(crate::error::PluginInvokeError::CannotSerializePayload)?,+ )+ .await+ .parse_void()+ }+}++pub struct Notifications<R: Runtime> {+ app: AppHandle<R>,+ plugin: Arc<ffi::NotificationPlugin>,+}++impl<R: Runtime> Notifications<R> {+ pub fn builder(&self) -> crate::NotificationsBuilder<R> {+ crate::NotificationsBuilder::new(self.app.clone(), self.plugin.clone())+ }++ pub async fn request_permission(&self) -> crate::Result<PermissionState> {+ validation::require_bundle()?;++ let response: crate::PermissionResponse = self.plugin.requestPermissions().await.parse()?;+ Ok(response.permission_state)+ }++ // Only the push-notifications body awaits; the stub compiled when the+ // feature is off must keep the same signature for its call site.+ #[cfg_attr(+ not(feature = "push-notifications"),+ allow(unknown_lints, clippy::unused_async, clippy::unused_async_trait_impl)+ )]+ pub async fn register_for_push_notifications(&self) -> crate::Result<String> {+ validation::require_bundle()?;++ #[cfg(feature = "push-notifications")]+ {+ let response: crate::PushNotificationResponse =+ self.plugin.registerForPushNotifications().await.parse()?;+ Ok(response.device_token)+ }+ #[cfg(not(feature = "push-notifications"))]+ {+ Err(crate::Error::Io(std::io::Error::other(+ "Push notifications feature is not enabled",+ )))+ }+ }++ pub fn unregister_for_push_notifications(&self) -> crate::Result<()> {+ validation::require_bundle()?;++ #[cfg(feature = "push-notifications")]+ {+ self.plugin.unregisterForPushNotifications().parse_void()+ }+ #[cfg(not(feature = "push-notifications"))]+ {+ Err(crate::Error::Io(std::io::Error::other(+ "Push notifications feature is not enabled",+ )))+ }+ }++ pub async fn permission_state(&self) -> crate::Result<PermissionState> {+ validation::require_bundle()?;++ let response: crate::PermissionResponse = self.plugin.checkPermissions().await.parse()?;+ Ok(response.permission_state)+ }++ pub fn register_action_types(&self, types: Vec<ActionType>) -> crate::Result<()> {+ validation::require_bundle()?;++ let mut args = HashMap::new();+ args.insert("types", types);+ self.plugin+ .registerActionTypes(+ serde_json::to_string(&args)+ .map_err(crate::error::PluginInvokeError::CannotSerializePayload)?,+ )+ .parse_void()+ }++ pub fn remove_active(&self, notifications: Vec<i32>) -> crate::Result<()> {+ validation::require_bundle()?;++ let mut args = HashMap::new();+ args.insert(+ "notifications",+ notifications+ .into_iter()+ .map(|id| {+ let mut notification = HashMap::new();+ notification.insert("id", id);+ notification+ })+ .collect::<Vec<HashMap<&str, i32>>>(),+ );+ self.plugin+ .removeActive(+ serde_json::to_string(&args)+ .map_err(crate::error::PluginInvokeError::CannotSerializePayload)?,+ )+ .parse_void()+ }++ pub async fn active(&self) -> crate::Result<Vec<ActiveNotification>> {+ validation::require_bundle()?;++ self.plugin.getActive().await.parse()+ }++ pub fn remove_all_active(&self) -> crate::Result<()> {+ validation::require_bundle()?;++ self.plugin.removeAllActive().parse_void()+ }++ pub async fn pending(&self) -> crate::Result<Vec<PendingNotification>> {+ validation::require_bundle()?;++ self.plugin.getPending().await.parse()+ }++ /// Cancel pending notifications.+ pub fn cancel(&self, notifications: Vec<i32>) -> crate::Result<()> {+ validation::require_bundle()?;++ let mut args = HashMap::new();+ args.insert("notifications", notifications);+ self.plugin+ .cancel(+ serde_json::to_string(&args)+ .map_err(crate::error::PluginInvokeError::CannotSerializePayload)?,+ )+ .parse_void()+ }++ /// Cancel all pending notifications.+ pub fn cancel_all(&self) -> crate::Result<()> {+ validation::require_bundle()?;++ self.plugin.cancelAll().parse_void()+ }++ /// Set click listener active state.+ /// Used internally to track if JS listener is registered.+ pub fn set_click_listener_active(&self, active: bool) -> crate::Result<()> {+ validation::require_bundle()?;++ let mut args = HashMap::new();+ args.insert("active", active);+ self.plugin+ .setClickListenerActive(+ serde_json::to_string(&args)+ .map_err(crate::error::PluginInvokeError::CannotSerializePayload)?,+ )+ .parse_void()+ }++ /// Create a notification channel (not supported on macOS).+ pub fn create_channel(&self, _channel: crate::Channel) -> crate::Result<()> {+ Err(crate::Error::Io(std::io::Error::other(+ "Notification channels are not supported on macOS",+ )))+ }++ /// Delete a notification channel (not supported on macOS).+ pub fn delete_channel(&self, _id: impl Into<String>) -> crate::Result<()> {+ Err(crate::Error::Io(std::io::Error::other(+ "Notification channels are not supported on macOS",+ )))+ }++ /// List notification channels (not supported on macOS).+ pub fn list_channels(&self) -> crate::Result<Vec<crate::Channel>> {+ Err(crate::Error::Io(std::io::Error::other(+ "Notification channels are not supported on macOS",+ )))+ }+}diff --git a/src-tauri/vendor/tauri-plugin-notifications/src/mobile.rs b/src-tauri/vendor/tauri-plugin-notifications/src/mobile.rsnew file mode 100644index 00000000..6bd06703--- /dev/null+++ b/src-tauri/vendor/tauri-plugin-notifications/src/mobile.rs@@ -0,0 +1,216 @@+use serde::de::DeserializeOwned;+use tauri::{+ AppHandle, Runtime,+ plugin::{PermissionState, PluginApi, PluginHandle},+};++#[cfg(feature = "push-notifications")]+use crate::models::PushNotificationResponse;+use crate::models::{+ ActionType, ActiveNotification, Channel, PendingNotification, PermissionResponse,+};++use std::collections::HashMap;++#[cfg(target_os = "android")]+const PLUGIN_IDENTIFIER: &str = "app.tauri.notification";++#[cfg(target_os = "ios")]+tauri::ios_plugin_binding!(init_plugin_notification);++// initializes the Kotlin or Swift plugin classes+// `PluginApi` is consumed by the framework's register helpers.+#[allow(clippy::needless_pass_by_value)]+pub fn init<R: Runtime, C: DeserializeOwned>(+ _app: &AppHandle<R>,+ api: PluginApi<R, C>,+) -> crate::Result<Notifications<R>> {+ #[cfg(target_os = "android")]+ let handle = api.register_android_plugin(PLUGIN_IDENTIFIER, "NotificationPlugin")?;+ #[cfg(target_os = "ios")]+ let handle = api.register_ios_plugin(init_plugin_notification)?;+ Ok(Notifications(handle))+}++impl<R: Runtime> crate::NotificationsBuilder<R> {+ pub async fn show(self) -> crate::Result<()> {+ self.handle+ .run_mobile_plugin_async::<i32>("show", self.data)+ .await+ .map(|_| ())+ .map_err(Into::into)+ }+}++/// Access to the notification APIs.+///+/// You can get an instance of this type via [`NotificationExt`](crate::NotificationExt)+pub struct Notifications<R: Runtime>(PluginHandle<R>);++impl<R: Runtime> Notifications<R> {+ pub fn builder(&self) -> crate::NotificationsBuilder<R> {+ crate::NotificationsBuilder::new(self.0.clone())+ }++ pub async fn request_permission(&self) -> crate::Result<PermissionState> {+ self.0+ .run_mobile_plugin_async::<PermissionResponse>("requestPermissions", ())+ .await+ .map(|r| r.permission_state)+ .map_err(Into::into)+ }++ pub async fn register_for_push_notifications(&self) -> crate::Result<String> {+ #[cfg(feature = "push-notifications")]+ {+ self.0+ .run_mobile_plugin_async::<PushNotificationResponse>(+ "registerForPushNotifications",+ (),+ )+ .await+ .map(|r| r.device_token)+ .map_err(Into::into)+ }+ #[cfg(not(feature = "push-notifications"))]+ {+ Err(crate::Error::Io(std::io::Error::other(+ "Push notifications feature is not enabled",+ )))+ }+ }++ pub fn unregister_for_push_notifications(&self) -> crate::Result<()> {+ #[cfg(feature = "push-notifications")]+ {+ self.0+ .run_mobile_plugin::<()>("unregisterForPushNotifications", ())+ .map_err(Into::into)+ }+ #[cfg(not(feature = "push-notifications"))]+ {+ Err(crate::Error::Io(std::io::Error::other(+ "Push notifications feature is not enabled",+ )))+ }+ }++ pub async fn permission_state(&self) -> crate::Result<PermissionState> {+ self.0+ .run_mobile_plugin_async::<PermissionResponse>("checkPermissions", ())+ .await+ .map(|r| r.permission_state)+ .map_err(Into::into)+ }++ pub fn register_action_types(&self, types: Vec<ActionType>) -> crate::Result<()> {+ let mut args = HashMap::new();+ args.insert("types", types);+ self.0+ .run_mobile_plugin("registerActionTypes", args)+ .map_err(Into::into)+ }++ pub fn remove_active(&self, notifications: Vec<i32>) -> crate::Result<()> {+ let mut args = HashMap::new();+ args.insert(+ "notifications",+ notifications+ .into_iter()+ .map(|id| {+ let mut notification = HashMap::new();+ notification.insert("id", id);+ notification+ })+ .collect::<Vec<HashMap<&str, i32>>>(),+ );+ self.0+ .run_mobile_plugin("removeActive", args)+ .map_err(Into::into)+ }++ pub async fn active(&self) -> crate::Result<Vec<ActiveNotification>> {+ self.0+ .run_mobile_plugin_async("getActive", ())+ .await+ .map_err(Into::into)+ }++ pub fn remove_all_active(&self) -> crate::Result<()> {+ self.0+ .run_mobile_plugin("removeActive", ())+ .map_err(Into::into)+ }++ pub async fn pending(&self) -> crate::Result<Vec<PendingNotification>> {+ self.0+ .run_mobile_plugin_async("getPending", ())+ .await+ .map_err(Into::into)+ }++ /// Cancel pending notifications.+ pub fn cancel(&self, notifications: Vec<i32>) -> crate::Result<()> {+ let mut args = HashMap::new();+ args.insert("notifications", notifications);+ self.0.run_mobile_plugin("cancel", args).map_err(Into::into)+ }++ /// Cancel all pending notifications.+ pub fn cancel_all(&self) -> crate::Result<()> {+ self.0+ .run_mobile_plugin("cancelAll", ())+ .map_err(Into::into)+ }++ #[allow(unused_variables, clippy::needless_pass_by_value)]+ pub fn create_channel(&self, channel: Channel) -> crate::Result<()> {+ #[cfg(target_os = "android")]+ return self+ .0+ .run_mobile_plugin("createChannel", channel)+ .map_err(Into::into);+ #[cfg(target_os = "ios")]+ return Err(crate::Error::Io(std::io::Error::other(+ "Channels are not supported on iOS",+ )));+ }++ #[allow(unused_variables, clippy::needless_pass_by_value)]+ pub fn delete_channel(&self, id: impl Into<String>) -> crate::Result<()> {+ #[cfg(target_os = "android")]+ {+ let mut args = HashMap::new();+ args.insert("id", id.into());+ self.0+ .run_mobile_plugin("deleteChannel", args)+ .map_err(Into::into)+ }+ #[cfg(target_os = "ios")]+ return Err(crate::Error::Io(std::io::Error::other(+ "Channels are not supported on iOS",+ )));+ }++ pub fn list_channels(&self) -> crate::Result<Vec<Channel>> {+ #[cfg(target_os = "android")]+ return self+ .0+ .run_mobile_plugin("listChannels", ())+ .map_err(Into::into);+ #[cfg(target_os = "ios")]+ return Err(crate::Error::Io(std::io::Error::other(+ "Channels are not supported on iOS",+ )));+ }++ /// Set click listener active state.+ /// Used internally to track if JS listener is registered.+ pub fn set_click_listener_active(&self, active: bool) -> crate::Result<()> {+ let mut args = HashMap::new();+ args.insert("active", active);+ self.0+ .run_mobile_plugin("setClickListenerActive", args)+ .map_err(Into::into)+ }+}diff --git a/src-tauri/vendor/tauri-plugin-notifications/src/models.rs b/src-tauri/vendor/tauri-plugin-notifications/src/models.rsnew file mode 100644index 00000000..50114347--- /dev/null+++ b/src-tauri/vendor/tauri-plugin-notifications/src/models.rs@@ -0,0 +1,976 @@+use std::{collections::HashMap, fmt::Display};++use serde::{Deserialize, Deserializer, Serialize, Serializer, de::Error as DeError};+use tauri::plugin::PermissionState;++use url::Url;++#[derive(Debug, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct PermissionResponse {+ pub permission_state: PermissionState,+}++#[cfg(feature = "push-notifications")]+#[derive(Debug, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct PushNotificationResponse {+ pub device_token: String,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct Attachment {+ id: String,+ url: Url,+}++impl Attachment {+ pub fn new(id: impl Into<String>, url: Url) -> Self {+ Self { id: id.into(), url }+ }++ #[must_use]+ pub fn id(&self) -> &str {+ &self.id+ }++ #[must_use]+ pub const fn url(&self) -> &Url {+ &self.url+ }+}++#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct ScheduleInterval {+ pub year: Option<u8>,+ pub month: Option<u8>,+ pub day: Option<u8>,+ pub weekday: Option<u8>,+ pub hour: Option<u8>,+ pub minute: Option<u8>,+ pub second: Option<u8>,+}++#[derive(Debug, Clone, Copy)]+pub enum ScheduleEvery {+ Year,+ Month,+ TwoWeeks,+ Week,+ Day,+ Hour,+ Minute,+ Second,+}++impl Display for ScheduleEvery {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ write!(+ f,+ "{}",+ match self {+ Self::Year => "year",+ Self::Month => "month",+ Self::TwoWeeks => "twoWeeks",+ Self::Week => "week",+ Self::Day => "day",+ Self::Hour => "hour",+ Self::Minute => "minute",+ Self::Second => "second",+ }+ )+ }+}++impl Serialize for ScheduleEvery {+ fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>+ where+ S: Serializer,+ {+ serializer.serialize_str(self.to_string().as_ref())+ }+}++impl<'de> Deserialize<'de> for ScheduleEvery {+ fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>+ where+ D: Deserializer<'de>,+ {+ let s = String::deserialize(deserializer)?;+ match s.to_lowercase().as_str() {+ "year" => Ok(Self::Year),+ "month" => Ok(Self::Month),+ "twoweeks" => Ok(Self::TwoWeeks),+ "week" => Ok(Self::Week),+ "day" => Ok(Self::Day),+ "hour" => Ok(Self::Hour),+ "minute" => Ok(Self::Minute),+ "second" => Ok(Self::Second),+ _ => Err(DeError::custom(format!("unknown every kind '{s}'"))),+ }+ }+}++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub enum Schedule {+ #[serde(rename_all = "camelCase")]+ At {+ #[serde(+ serialize_with = "iso8601::serialize",+ deserialize_with = "time::serde::iso8601::deserialize"+ )]+ date: time::OffsetDateTime,+ #[serde(default)]+ repeating: bool,+ #[serde(default)]+ allow_while_idle: bool,+ },+ #[serde(rename_all = "camelCase")]+ Interval {+ interval: ScheduleInterval,+ #[serde(default)]+ allow_while_idle: bool,+ },+ #[serde(rename_all = "camelCase")]+ Every {+ interval: ScheduleEvery,+ count: u8,+ #[serde(default)]+ allow_while_idle: bool,+ },+}++// custom ISO-8601 serialization that does not use 6 digits for years.+mod iso8601 {+ use serde::{Serialize, Serializer, ser::Error as _};+ use time::{+ OffsetDateTime,+ format_description::well_known::Iso8601,+ format_description::well_known::iso8601::{Config, EncodedConfig},+ };++ const SERDE_CONFIG: EncodedConfig = Config::DEFAULT.encode();++ pub fn serialize<S: Serializer>(+ datetime: &OffsetDateTime,+ serializer: S,+ ) -> Result<S::Ok, S::Error> {+ datetime+ .format(&Iso8601::<SERDE_CONFIG>)+ .map_err(S::Error::custom)?+ .serialize(serializer)+ }+}++// Each bool is an independent flag in the JS wire format; grouping them would change the JSON shape.+#[allow(clippy::struct_excessive_bools)]+#[derive(Debug, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct NotificationData {+ #[serde(default = "default_id")]+ pub(crate) id: i32,+ pub(crate) channel_id: Option<String>,+ pub(crate) title: Option<String>,+ pub(crate) body: Option<String>,+ pub(crate) schedule: Option<Schedule>,+ pub(crate) large_body: Option<String>,+ pub(crate) summary: Option<String>,+ pub(crate) action_type_id: Option<String>,+ pub(crate) group: Option<String>,+ #[serde(default)]+ pub(crate) group_summary: bool,+ pub(crate) sound: Option<String>,+ #[serde(default)]+ pub(crate) inbox_lines: Vec<String>,+ pub(crate) icon: Option<String>,+ pub(crate) large_icon: Option<String>,+ pub(crate) icon_color: Option<String>,+ #[serde(default)]+ pub(crate) attachments: Vec<Attachment>,+ #[serde(default)]+ pub(crate) extra: HashMap<String, serde_json::Value>,+ #[serde(default)]+ pub(crate) ongoing: bool,+ #[serde(default)]+ pub(crate) auto_cancel: bool,+ #[serde(default)]+ pub(crate) silent: bool,+}++fn default_id() -> i32 {+ rand::random()+}++impl Default for NotificationData {+ fn default() -> Self {+ Self {+ id: default_id(),+ channel_id: None,+ title: None,+ body: None,+ schedule: None,+ large_body: None,+ summary: None,+ action_type_id: None,+ group: None,+ group_summary: false,+ sound: None,+ inbox_lines: Vec::new(),+ icon: None,+ large_icon: None,+ icon_color: None,+ attachments: Vec::new(),+ extra: HashMap::default(),+ ongoing: false,+ auto_cancel: false,+ silent: false,+ }+ }+}++#[derive(Debug, Deserialize, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct PendingNotification {+ pub(crate) id: i32,+ pub(crate) title: Option<String>,+ pub(crate) body: Option<String>,+ pub(crate) schedule: Schedule,+}++impl PendingNotification {+ #[must_use]+ pub const fn id(&self) -> i32 {+ self.id+ }++ #[must_use]+ pub fn title(&self) -> Option<&str> {+ self.title.as_deref()+ }++ #[must_use]+ pub fn body(&self) -> Option<&str> {+ self.body.as_deref()+ }++ #[must_use]+ pub const fn schedule(&self) -> &Schedule {+ &self.schedule+ }+}++#[derive(Debug, Clone, Deserialize, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct ActiveNotification {+ pub(crate) id: i32,+ pub(crate) tag: Option<String>,+ pub(crate) title: Option<String>,+ pub(crate) body: Option<String>,+ pub(crate) group: Option<String>,+ #[serde(default)]+ pub(crate) group_summary: bool,+ #[serde(default)]+ pub(crate) data: HashMap<String, String>,+ #[serde(default)]+ pub(crate) extra: HashMap<String, serde_json::Value>,+ #[serde(default)]+ pub(crate) attachments: Vec<Attachment>,+ pub(crate) action_type_id: Option<String>,+ pub(crate) schedule: Option<Schedule>,+ pub(crate) sound: Option<String>,+}++impl ActiveNotification {+ /// Constructs an `ActiveNotification` from the minimal set of fields the+ /// desktop tracking layer can populate. All other fields fall back to+ /// their defaults (the mobile/native paths fill them out fully).+ #[must_use]+ pub fn new(id: i32, title: Option<String>, body: Option<String>) -> Self {+ Self {+ id,+ tag: None,+ title,+ body,+ group: None,+ group_summary: false,+ data: HashMap::new(),+ extra: HashMap::new(),+ attachments: Vec::new(),+ action_type_id: None,+ schedule: None,+ sound: None,+ }+ }++ #[must_use]+ pub const fn id(&self) -> i32 {+ self.id+ }++ #[must_use]+ pub fn tag(&self) -> Option<&str> {+ self.tag.as_deref()+ }++ #[must_use]+ pub fn title(&self) -> Option<&str> {+ self.title.as_deref()+ }++ #[must_use]+ pub fn body(&self) -> Option<&str> {+ self.body.as_deref()+ }++ #[must_use]+ pub fn group(&self) -> Option<&str> {+ self.group.as_deref()+ }++ #[must_use]+ pub const fn group_summary(&self) -> bool {+ self.group_summary+ }++ #[must_use]+ pub const fn data(&self) -> &HashMap<String, String> {+ &self.data+ }++ #[must_use]+ pub const fn extra(&self) -> &HashMap<String, serde_json::Value> {+ &self.extra+ }++ #[must_use]+ pub fn attachments(&self) -> &[Attachment] {+ &self.attachments+ }++ #[must_use]+ pub fn action_type_id(&self) -> Option<&str> {+ self.action_type_id.as_deref()+ }++ #[must_use]+ pub const fn schedule(&self) -> Option<&Schedule> {+ self.schedule.as_ref()+ }++ #[must_use]+ pub fn sound(&self) -> Option<&str> {+ self.sound.as_deref()+ }+}++// Each bool is an independent UNNotificationCategory option; grouping would change the JSON shape.+#[allow(clippy::struct_excessive_bools)]+#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct ActionType {+ id: String,+ actions: Vec<Action>,+ hidden_previews_body_placeholder: Option<String>,+ #[serde(default)]+ custom_dismiss_action: bool,+ #[serde(default)]+ allow_in_car_play: bool,+ #[serde(default)]+ hidden_previews_show_title: bool,+ #[serde(default)]+ hidden_previews_show_subtitle: bool,+}++impl ActionType {+ pub fn new(id: impl Into<String>, actions: Vec<Action>) -> Self {+ Self {+ id: id.into(),+ actions,+ hidden_previews_body_placeholder: None,+ custom_dismiss_action: false,+ allow_in_car_play: false,+ hidden_previews_show_title: false,+ hidden_previews_show_subtitle: false,+ }+ }++ #[must_use]+ pub fn id(&self) -> &str {+ &self.id+ }++ #[must_use]+ pub fn actions(&self) -> &[Action] {+ &self.actions+ }+}++// Each bool is an independent UNNotificationAction option; grouping would change the JSON shape.+#[allow(clippy::struct_excessive_bools)]+#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct Action {+ id: String,+ title: String,+ #[serde(default)]+ requires_authentication: bool,+ #[serde(default)]+ foreground: bool,+ #[serde(default)]+ destructive: bool,+ #[serde(default)]+ input: bool,+ input_button_title: Option<String>,+ input_placeholder: Option<String>,+}++impl Action {+ pub fn new(id: impl Into<String>, title: impl Into<String>, foreground: bool) -> Self {+ Self {+ id: id.into(),+ title: title.into(),+ requires_authentication: false,+ foreground,+ destructive: false,+ input: false,+ input_button_title: None,+ input_placeholder: None,+ }+ }++ #[must_use]+ pub fn id(&self) -> &str {+ &self.id+ }++ #[must_use]+ pub fn title(&self) -> &str {+ &self.title+ }++ #[must_use]+ pub const fn foreground(&self) -> bool {+ self.foreground+ }++ /// Vendored patch: whether this action collects free-form text.+ #[must_use]+ pub const fn input(&self) -> bool {+ self.input+ }++ /// Vendored patch: placeholder for the text box, when `input()` is on.+ #[must_use]+ pub fn input_placeholder(&self) -> Option<&str> {+ self.input_placeholder.as_deref()+ }++ /// Vendored patch: label of the button that submits the text box.+ ///+ /// Windows renders a single button per `<action>`, so when+ /// [`Action::input`] is on this label replaces [`Action::title`] as the+ /// button caption.+ #[must_use]+ pub fn input_button_title(&self) -> Option<&str> {+ self.input_button_title.as_deref()+ }+}++pub use android::*;++mod android {+ use serde::{Deserialize, Serialize};+ use serde_repr::{Deserialize_repr, Serialize_repr};++ #[derive(Debug, Default, Clone, Copy, Serialize_repr, Deserialize_repr)]+ #[repr(u8)]+ pub enum Importance {+ None = 0,+ Min = 1,+ Low = 2,+ #[default]+ Default = 3,+ High = 4,+ }++ #[derive(Debug, Clone, Copy, Serialize_repr, Deserialize_repr)]+ #[repr(i8)]+ pub enum Visibility {+ Secret = -1,+ Private = 0,+ Public = 1,+ }++ #[derive(Debug, Serialize, Deserialize)]+ #[serde(rename_all = "camelCase")]+ pub struct Channel {+ id: String,+ name: String,+ description: Option<String>,+ sound: Option<String>,+ lights: Option<bool>,+ light_color: Option<String>,+ vibration: Option<bool>,+ importance: Option<Importance>,+ visibility: Option<Visibility>,+ }++ #[derive(Debug)]+ pub struct ChannelBuilder(Channel);++ impl Channel {+ pub fn builder(id: impl Into<String>, name: impl Into<String>) -> ChannelBuilder {+ ChannelBuilder(Self {+ id: id.into(),+ name: name.into(),+ description: None,+ sound: None,+ lights: Some(false),+ light_color: None,+ vibration: Some(false),+ importance: None,+ visibility: None,+ })+ }++ #[must_use]+ pub fn id(&self) -> &str {+ &self.id+ }++ #[must_use]+ pub fn name(&self) -> &str {+ &self.name+ }++ #[must_use]+ pub fn description(&self) -> Option<&str> {+ self.description.as_deref()+ }++ #[must_use]+ pub fn sound(&self) -> Option<&str> {+ self.sound.as_deref()+ }++ #[must_use]+ pub fn lights(&self) -> bool {+ self.lights.unwrap_or(false)+ }++ #[must_use]+ pub fn light_color(&self) -> Option<&str> {+ self.light_color.as_deref()+ }++ #[must_use]+ pub fn vibration(&self) -> bool {+ self.vibration.unwrap_or(false)+ }++ #[must_use]+ pub fn importance(&self) -> Importance {+ self.importance.unwrap_or_default()+ }++ #[must_use]+ pub const fn visibility(&self) -> Option<Visibility> {+ self.visibility+ }+ }++ impl ChannelBuilder {+ #[must_use]+ pub fn description(mut self, description: impl Into<String>) -> Self {+ self.0.description.replace(description.into());+ self+ }++ #[must_use]+ pub fn sound(mut self, sound: impl Into<String>) -> Self {+ self.0.sound.replace(sound.into());+ self+ }++ #[must_use]+ pub const fn lights(mut self, lights: bool) -> Self {+ self.0.lights = Some(lights);+ self+ }++ #[must_use]+ pub fn light_color(mut self, color: impl Into<String>) -> Self {+ self.0.light_color.replace(color.into());+ self+ }++ #[must_use]+ pub const fn vibration(mut self, vibration: bool) -> Self {+ self.0.vibration = Some(vibration);+ self+ }++ #[must_use]+ pub const fn importance(mut self, importance: Importance) -> Self {+ self.0.importance = Some(importance);+ self+ }++ #[must_use]+ pub const fn visibility(mut self, visibility: Visibility) -> Self {+ self.0.visibility.replace(visibility);+ self+ }++ #[must_use]+ pub fn build(self) -> Channel {+ self.0+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn test_attachment_creation() {+ let url = Url::parse("https://example.com/image.png").expect("Failed to parse URL");+ let attachment = Attachment::new("test_id", url.clone());+ assert_eq!(attachment.id, "test_id");+ assert_eq!(attachment.url, url);+ }++ #[test]+ fn test_attachment_serialization() {+ let url = Url::parse("https://example.com/image.png").expect("Failed to parse URL");+ let attachment = Attachment::new("test_id", url);+ let json = serde_json::to_string(&attachment).expect("Failed to serialize attachment");+ assert!(json.contains("test_id"));+ assert!(json.contains("https://example.com/image.png"));+ }++ #[test]+ fn test_attachment_deserialization() {+ let json = r#"{"id":"test_id","url":"https://example.com/image.png"}"#;+ let attachment: Attachment =+ serde_json::from_str(json).expect("Failed to deserialize attachment");+ assert_eq!(attachment.id, "test_id");+ assert_eq!(attachment.url.as_str(), "https://example.com/image.png");+ }++ #[test]+ fn test_schedule_every_display() {+ assert_eq!(ScheduleEvery::Year.to_string(), "year");+ assert_eq!(ScheduleEvery::Month.to_string(), "month");+ assert_eq!(ScheduleEvery::TwoWeeks.to_string(), "twoWeeks");+ assert_eq!(ScheduleEvery::Week.to_string(), "week");+ assert_eq!(ScheduleEvery::Day.to_string(), "day");+ assert_eq!(ScheduleEvery::Hour.to_string(), "hour");+ assert_eq!(ScheduleEvery::Minute.to_string(), "minute");+ assert_eq!(ScheduleEvery::Second.to_string(), "second");+ }++ #[test]+ fn test_schedule_every_serialization() {+ let json = serde_json::to_string(&ScheduleEvery::Day).expect("Failed to serialize Day");+ assert_eq!(json, "\"day\"");++ let json =+ serde_json::to_string(&ScheduleEvery::TwoWeeks).expect("Failed to serialize TwoWeeks");+ assert_eq!(json, "\"twoWeeks\"");+ }++ #[test]+ fn test_schedule_every_deserialization() {+ let every: ScheduleEvery =+ serde_json::from_str("\"year\"").expect("Failed to deserialize year");+ assert!(matches!(every, ScheduleEvery::Year));++ let every: ScheduleEvery =+ serde_json::from_str("\"month\"").expect("Failed to deserialize month");+ assert!(matches!(every, ScheduleEvery::Month));++ let every: ScheduleEvery =+ serde_json::from_str("\"twoweeks\"").expect("Failed to deserialize twoweeks");+ assert!(matches!(every, ScheduleEvery::TwoWeeks));++ let every: ScheduleEvery =+ serde_json::from_str("\"week\"").expect("Failed to deserialize week");+ assert!(matches!(every, ScheduleEvery::Week));++ let every: ScheduleEvery =+ serde_json::from_str("\"day\"").expect("Failed to deserialize day");+ assert!(matches!(every, ScheduleEvery::Day));++ let every: ScheduleEvery =+ serde_json::from_str("\"hour\"").expect("Failed to deserialize hour");+ assert!(matches!(every, ScheduleEvery::Hour));++ let every: ScheduleEvery =+ serde_json::from_str("\"minute\"").expect("Failed to deserialize minute");+ assert!(matches!(every, ScheduleEvery::Minute));++ let every: ScheduleEvery =+ serde_json::from_str("\"second\"").expect("Failed to deserialize second");+ assert!(matches!(every, ScheduleEvery::Second));+ }++ #[test]+ fn test_schedule_every_deserialization_invalid() {+ let result: Result<ScheduleEvery, _> = serde_json::from_str("\"invalid\"");+ assert!(result.is_err());+ }++ #[test]+ fn test_schedule_interval_default() {+ let interval = ScheduleInterval::default();+ assert!(interval.year.is_none());+ assert!(interval.month.is_none());+ assert!(interval.day.is_none());+ assert!(interval.weekday.is_none());+ assert!(interval.hour.is_none());+ assert!(interval.minute.is_none());+ assert!(interval.second.is_none());+ }++ #[test]+ fn test_schedule_interval_serialization() {+ let interval = ScheduleInterval {+ year: Some(24),+ month: Some(12),+ day: Some(25),+ weekday: Some(1),+ hour: Some(10),+ minute: Some(30),+ second: Some(0),+ };+ let json = serde_json::to_string(&interval).expect("Failed to serialize interval");+ assert!(json.contains("\"year\":24"));+ assert!(json.contains("\"month\":12"));+ assert!(json.contains("\"day\":25"));+ }++ #[test]+ fn test_notification_data_default() {+ let data = NotificationData::default();+ assert!(data.id != 0); // Should be a random ID+ assert!(data.channel_id.is_none());+ assert!(data.title.is_none());+ assert!(data.body.is_none());+ assert!(data.schedule.is_none());+ assert!(!data.group_summary);+ assert!(!data.ongoing);+ assert!(!data.auto_cancel);+ assert!(!data.silent);+ assert!(data.inbox_lines.is_empty());+ assert!(data.attachments.is_empty());+ assert!(data.extra.is_empty());+ }++ #[test]+ fn test_notification_data_serialization() {+ let data = NotificationData {+ id: 123,+ title: Some("Test Title".to_string()),+ body: Some("Test Body".to_string()),+ ongoing: true,+ ..Default::default()+ };++ let json = serde_json::to_string(&data).expect("Failed to serialize notification data");+ assert!(json.contains("\"id\":123"));+ assert!(json.contains("\"title\":\"Test Title\""));+ assert!(json.contains("\"body\":\"Test Body\""));+ assert!(json.contains("\"ongoing\":true"));+ }++ #[test]+ fn test_pending_notification_getters() {+ let json = r#"{+ "id": 456,+ "title": "Pending Title",+ "body": "Pending Body",+ "schedule": {"every": {"interval": "day", "count": 1}}+ }"#;+ let pending: PendingNotification =+ serde_json::from_str(json).expect("Failed to deserialize pending notification");++ assert_eq!(pending.id(), 456);+ assert_eq!(pending.title(), Some("Pending Title"));+ assert_eq!(pending.body(), Some("Pending Body"));+ assert!(matches!(pending.schedule(), Schedule::Every { .. }));+ }++ #[test]+ fn test_active_notification_getters() {+ let json = r#"{+ "id": 789,+ "title": "Active Title",+ "body": "Active Body",+ "group": "test_group",+ "groupSummary": true+ }"#;+ let active: ActiveNotification =+ serde_json::from_str(json).expect("Failed to deserialize active notification");++ assert_eq!(active.id(), 789);+ assert_eq!(active.title(), Some("Active Title"));+ assert_eq!(active.body(), Some("Active Body"));+ assert_eq!(active.group(), Some("test_group"));+ assert!(active.group_summary());+ assert!(active.data().is_empty());+ assert!(active.extra().is_empty());+ assert!(active.attachments().is_empty());+ assert!(active.action_type_id().is_none());+ assert!(active.schedule().is_none());+ assert!(active.sound().is_none());+ }++ #[cfg(target_os = "android")]+ #[test]+ fn test_importance_default() {+ let importance = Importance::default();+ assert!(matches!(importance, Importance::Default));+ }++ #[cfg(target_os = "android")]+ #[test]+ fn test_importance_serialization() {+ assert_eq!(+ serde_json::to_string(&Importance::None).expect("Failed to serialize Importance::None"),+ "0"+ );+ assert_eq!(+ serde_json::to_string(&Importance::Min).expect("Failed to serialize Importance::Min"),+ "1"+ );+ assert_eq!(+ serde_json::to_string(&Importance::Low).expect("Failed to serialize Importance::Low"),+ "2"+ );+ assert_eq!(+ serde_json::to_string(&Importance::Default)+ .expect("Failed to serialize Importance::Default"),+ "3"+ );+ assert_eq!(+ serde_json::to_string(&Importance::High).expect("Failed to serialize Importance::High"),+ "4"+ );+ }++ #[cfg(target_os = "android")]+ #[test]+ fn test_visibility_serialization() {+ assert_eq!(+ serde_json::to_string(&Visibility::Secret)+ .expect("Failed to serialize Visibility::Secret"),+ "-1"+ );+ assert_eq!(+ serde_json::to_string(&Visibility::Private)+ .expect("Failed to serialize Visibility::Private"),+ "0"+ );+ assert_eq!(+ serde_json::to_string(&Visibility::Public)+ .expect("Failed to serialize Visibility::Public"),+ "1"+ );+ }++ #[cfg(target_os = "android")]+ #[test]+ fn test_channel_builder() {+ let channel = Channel::builder("test_id", "Test Channel")+ .description("Test Description")+ .sound("test_sound")+ .lights(true)+ .light_color("#FF0000")+ .vibration(true)+ .importance(Importance::High)+ .visibility(Visibility::Public)+ .build();++ assert_eq!(channel.id(), "test_id");+ assert_eq!(channel.name(), "Test Channel");+ assert_eq!(channel.description(), Some("Test Description"));+ assert_eq!(channel.sound(), Some("test_sound"));+ assert!(channel.lights());+ assert_eq!(channel.light_color(), Some("#FF0000"));+ assert!(channel.vibration());+ assert!(matches!(channel.importance(), Importance::High));+ assert_eq!(channel.visibility(), Some(Visibility::Public));+ }++ #[cfg(target_os = "android")]+ #[test]+ fn test_channel_builder_minimal() {+ let channel = Channel::builder("minimal_id", "Minimal Channel").build();++ assert_eq!(channel.id(), "minimal_id");+ assert_eq!(channel.name(), "Minimal Channel");+ assert_eq!(channel.description(), None);+ assert_eq!(channel.sound(), None);+ assert!(!channel.lights());+ assert_eq!(channel.light_color(), None);+ assert!(!channel.vibration());+ assert!(matches!(channel.importance(), Importance::Default));+ assert_eq!(channel.visibility(), None);+ }++ #[test]+ fn test_schedule_at_serialization() {+ use time::OffsetDateTime;++ let date = OffsetDateTime::now_utc();+ let schedule = Schedule::At {+ date,+ repeating: true,+ allow_while_idle: false,+ };++ let json = serde_json::to_string(&schedule).expect("Failed to serialize Schedule::At");+ assert!(json.contains("\"at\""));+ assert!(json.contains("\"date\""));+ assert!(json.contains("\"repeating\":true"));+ assert!(json.contains("\"allowWhileIdle\":false"));+ }++ #[test]+ fn test_schedule_interval_variant() {+ let schedule = Schedule::Interval {+ interval: ScheduleInterval {+ hour: Some(10),+ minute: Some(30),+ ..Default::default()+ },+ allow_while_idle: true,+ };++ let json =+ serde_json::to_string(&schedule).expect("Failed to serialize Schedule::Interval");+ assert!(json.contains("\"interval\""));+ assert!(json.contains("\"hour\":10"));+ assert!(json.contains("\"minute\":30"));+ assert!(json.contains("\"allowWhileIdle\":true"));+ }++ #[test]+ fn test_schedule_every_variant() {+ let schedule = Schedule::Every {+ interval: ScheduleEvery::Day,+ count: 5,+ allow_while_idle: false,+ };++ let json = serde_json::to_string(&schedule).expect("Failed to serialize Schedule::Every");+ assert!(json.contains("\"every\""));+ assert!(json.contains("\"interval\":\"day\""));+ assert!(json.contains("\"count\":5"));+ }+}diff --git a/src-tauri/vendor/tauri-plugin-notifications/src/unifiedpush.rs b/src-tauri/vendor/tauri-plugin-notifications/src/unifiedpush.rsnew file mode 100644index 00000000..ee9b5389--- /dev/null+++ b/src-tauri/vendor/tauri-plugin-notifications/src/unifiedpush.rs@@ -0,0 +1,511 @@+//! `UnifiedPush` D-Bus integration for Linux desktop.+//!+//! Implements the connector side of the `UnifiedPush` spec+//! (<https://unifiedpush.org/spec/dbus/>). The plugin owns a `Connection` to the+//! session bus, exposes an `org.unifiedpush.Connector1` interface, and drives+//! `org.unifiedpush.Distributor1` calls against the user-selected distributor.+//!+//! All state is in-memory. The plugin never writes to disk — endpoint stability+//! across launches is the host app's responsibility (pass the same `client_token`+//! to `register_for_push_notifications`).++use std::collections::HashMap;+use std::sync::{Arc, Weak};+use std::time::Duration;++use serde_json::{Value as JsonValue, json};+use tauri::{AppHandle, Runtime};+use tokio::sync::{Mutex, RwLock, oneshot};++const DISTRIBUTOR_PREFIX: &str = "org.unifiedpush.Distributor.";+const CONNECTOR_PATH: &str = "/org/unifiedpush/Connector";+const REGISTER_TIMEOUT_SECS: u64 = 10;++pub const ERR_NO_DISTRIBUTOR: &str = "No UnifiedPush distributor installed — install one from https://unifiedpush.org/users/distributors/";+pub const ERR_REGISTER_TIMEOUT: &str = "Registration timed out";++fn err_distributor_unavailable(name: &str) -> String {+ format!("Distributor '{name}' is not available")+}++fn io_err(msg: impl Into<String>) -> crate::Error {+ crate::Error::Io(std::io::Error::other(msg.into()))+}++#[zbus::proxy(+ interface = "org.unifiedpush.Distributor1",+ default_path = "/org/unifiedpush/Distributor"+)]+trait Distributor {+ fn register(&self, connector: &str, token: &str, vapid: &str)+ -> zbus::Result<(String, String)>;++ fn unregister(&self, token: &str) -> zbus::Result<()>;+}++#[derive(Clone)]+struct ActiveRegistration {+ client_token: String,+ distributor: String,+}++/// Callback used to display an incoming push as a desktop toast. Provided+/// by the cross-platform layer at construction time so this module doesn't+/// have to know about `Notifications<R>` (avoids making `UnifiedPushState`+/// generic over `Runtime`). The callback is responsible for calling+/// `notify_rust::Notification::show()` AND inserting the resulting handle+/// into the shared `active` map so push toasts show up in+/// `Notifications::active()` and can be cancelled like local ones.+pub type PushDisplayer = Arc<dyn Fn(Option<String>, Option<String>) + Send + Sync + 'static>;++pub struct UnifiedPushState {+ connection: zbus::Connection,+ connector_bus_name: String,+ /// Used as a fallback when an incoming push has no `title` field. The JS+ /// listener's `Options.title` is typed as a required string, so emitting+ /// `null` would surprise consumers.+ fallback_title: String,+ selected: RwLock<Option<String>>,+ token: RwLock<Option<String>>,+ active: RwLock<Option<ActiveRegistration>>,+ pending: Mutex<HashMap<String, oneshot::Sender<Result<String, String>>>>,+ /// `None` means "don't display a toast for incoming pushes" — the JS+ /// listener still fires. Practically always `Some` when constructed from+ /// `desktop.rs`.+ displayer: Option<PushDisplayer>,+}++impl UnifiedPushState {+ pub async fn new<R: Runtime>(+ app: &AppHandle<R>,+ displayer: Option<PushDisplayer>,+ ) -> crate::Result<Arc<Self>> {+ let connector_bus_name = app.config().identifier.clone();+ if connector_bus_name.is_empty() {+ return Err(io_err(+ "App identifier is empty; cannot register a D-Bus connector name",+ ));+ }+ let fallback_title = app+ .config()+ .product_name+ .clone()+ .unwrap_or_else(|| connector_bus_name.clone());++ let connection = zbus::Connection::session()+ .await+ .map_err(|e| io_err(format!("Failed to connect to D-Bus session: {e}")))?;++ let state = Arc::new(Self {+ connection: connection.clone(),+ connector_bus_name: connector_bus_name.clone(),+ fallback_title,+ selected: RwLock::new(None),+ token: RwLock::new(None),+ active: RwLock::new(None),+ pending: Mutex::new(HashMap::new()),+ displayer,+ });++ let connector = ConnectorService {+ state: Arc::downgrade(&state),+ };+ connection+ .object_server()+ .at(CONNECTOR_PATH, connector)+ .await+ .map_err(|e| io_err(format!("Failed to register connector object: {e}")))?;++ let reply = connection+ .request_name_with_flags(+ connector_bus_name.as_str(),+ zbus::fdo::RequestNameFlags::DoNotQueue+ | zbus::fdo::RequestNameFlags::ReplaceExisting+ | zbus::fdo::RequestNameFlags::AllowReplacement,+ )+ .await+ .map_err(|e| {+ io_err(format!(+ "Failed to request connector bus name '{connector_bus_name}': {e}"+ ))+ })?;++ match reply {+ zbus::fdo::RequestNameReply::PrimaryOwner+ | zbus::fdo::RequestNameReply::AlreadyOwner => {+ log::info!("UnifiedPush connector listening on D-Bus name '{connector_bus_name}'");+ }+ zbus::fdo::RequestNameReply::InQueue => {+ return Err(io_err(format!(+ "Bus name '{connector_bus_name}' is held by another process; queued instead of becoming primary owner"+ )));+ }+ zbus::fdo::RequestNameReply::Exists => {+ return Err(io_err(format!(+ "Bus name '{connector_bus_name}' is already held by another process and cannot be replaced"+ )));+ }+ }++ Ok(state)+ }++ pub async fn list_distributors(&self) -> crate::Result<Vec<String>> {+ let dbus = zbus::fdo::DBusProxy::new(&self.connection)+ .await+ .map_err(|e| io_err(format!("Failed to access D-Bus daemon: {e}")))?;+ let names = dbus+ .list_names()+ .await+ .map_err(|e| io_err(format!("Failed to list bus names: {e}")))?;+ let mut out: Vec<String> = names+ .into_iter()+ .map(|n| n.as_str().to_string())+ .filter(|n| n.starts_with(DISTRIBUTOR_PREFIX))+ .collect();+ out.sort();+ out.dedup();+ Ok(out)+ }++ pub async fn set_distributor(&self, name: String) -> crate::Result<()> {+ let distributors = self.list_distributors().await?;+ if !distributors.contains(&name) {+ return Err(io_err(err_distributor_unavailable(&name)));+ }+ *self.selected.write().await = Some(name);+ Ok(())+ }++ /// Sets the client token used on the next `register` call. `UnifiedPush`+ /// distributors derive the endpoint URL from+ /// `(connector_bus_name, client_token)`, so apps that want endpoint+ /// stability across launches should persist this token themselves and+ /// call `set_token` before `register`.+ pub async fn set_token(&self, token: String) -> crate::Result<()> {+ if token.is_empty() {+ return Err(io_err("Token cannot be empty"));+ }+ *self.token.write().await = Some(token);+ Ok(())+ }++ async fn pick_distributor(&self) -> crate::Result<String> {+ let distributors = self.list_distributors().await?;+ let selected = self.selected.read().await.clone();+ if let Some(name) = selected {+ if distributors.contains(&name) {+ return Ok(name);+ }+ return Err(io_err(err_distributor_unavailable(&name)));+ }+ distributors+ .into_iter()+ .next()+ .ok_or_else(|| io_err(ERR_NO_DISTRIBUTOR.to_string()))+ }++ pub async fn register(&self) -> crate::Result<String> {+ // Reject if there's already an active registration. Otherwise the+ // previous token would stay registered at the distributor (and keep+ // receiving pushes) while the plugin only tracks the latest one,+ // making `unregister` impossible for the orphaned token.+ if self.active.read().await.is_some() {+ return Err(io_err(+ "Already registered; call unregister first to re-register",+ ));+ }++ let distributor = self.pick_distributor().await?;+ let client_token = self+ .token+ .read()+ .await+ .clone()+ .unwrap_or_else(|| uuid::Uuid::new_v4().to_string());++ let proxy = DistributorProxy::builder(&self.connection)+ .destination(distributor.clone())+ .map_err(|e| io_err(format!("Invalid distributor name '{distributor}': {e}")))?+ .build()+ .await+ .map_err(|e| {+ io_err(format!(+ "Failed to connect to distributor '{distributor}': {e}"+ ))+ })?;++ let (tx, rx) = oneshot::channel();+ {+ let mut pending = self.pending.lock().await;+ if pending.contains_key(&client_token) {+ return Err(io_err(+ "A registration is already in flight for this client token",+ ));+ }+ pending.insert(client_token.clone(), tx);+ }++ let response = proxy+ .register(&self.connector_bus_name, &client_token, "")+ .await;++ match response {+ Ok((code, message)) => {+ if code == "REGISTRATION_FAILED" {+ self.pending.lock().await.remove(&client_token);+ let detail = if message.is_empty() {+ String::new()+ } else {+ format!(": {message}")+ };+ return Err(io_err(format!("Distributor rejected registration{detail}")));+ }+ }+ Err(e) => {+ self.pending.lock().await.remove(&client_token);+ return Err(io_err(format!("Distributor Register call failed: {e}")));+ }+ }++ let endpoint =+ match tokio::time::timeout(Duration::from_secs(REGISTER_TIMEOUT_SECS), rx).await {+ Ok(Ok(Ok(endpoint))) => endpoint,+ Ok(Ok(Err(reason))) => {+ return Err(io_err(format!("Registration failed: {reason}")));+ }+ Ok(Err(_)) => {+ return Err(io_err("Registration callback channel closed".to_string()));+ }+ Err(_) => {+ self.pending.lock().await.remove(&client_token);+ return Err(io_err(ERR_REGISTER_TIMEOUT.to_string()));+ }+ };++ *self.active.write().await = Some(ActiveRegistration {+ client_token,+ distributor,+ });+ Ok(endpoint)+ }++ pub async fn unregister(&self) -> crate::Result<()> {+ // Read first (clone), only clear `self.active` after the D-Bus call+ // succeeds. Otherwise a transient failure leaves the plugin thinking+ // it's unregistered while the distributor still has the token.+ let Some(active) = self.active.read().await.clone() else {+ return Ok(());+ };++ let proxy = DistributorProxy::builder(&self.connection)+ .destination(active.distributor.clone())+ .map_err(|e| {+ io_err(format!(+ "Invalid distributor name '{}': {e}",+ active.distributor+ ))+ })?+ .build()+ .await+ .map_err(|e| {+ io_err(format!(+ "Failed to connect to distributor '{}': {e}",+ active.distributor+ ))+ })?;++ proxy+ .unregister(&active.client_token)+ .await+ .map_err(|e| io_err(format!("Distributor Unregister failed: {e}")))?;++ // Only clear after the distributor has acknowledged the unregister.+ *self.active.write().await = None;++ Ok(())+ }+}++struct ConnectorService {+ state: Weak<UnifiedPushState>,+}++#[zbus::interface(name = "org.unifiedpush.Connector1")]+impl ConnectorService {+ // `async` kept for consistency with the other D-Bus methods in this interface,+ // even though the body is currently synchronous.+ #[allow(unknown_lints, clippy::unused_async, clippy::unused_async_trait_impl)]+ async fn message(&self, token: String, message: Vec<u8>, id: String) {+ let Some(state) = self.state.upgrade() else {+ return;+ };+ // Validate the token against the active registration. Without this+ // check, any process on the session bus could call+ // `org.unifiedpush.Connector1.Message` with an arbitrary token and+ // trigger listener events / toasts — spoofed pushes.+ let token_matches = state+ .active+ .read()+ .await+ .as_ref()+ .is_some_and(|a| a.client_token == token);+ if !token_matches {+ log::warn!("UnifiedPush Message received for unknown token; ignoring (possible spoof)");+ return;+ }+ handle_message(&state, &token, &message, &id);+ }++ async fn new_endpoint(&self, token: String, endpoint: String) {+ let Some(state) = self.state.upgrade() else {+ return;+ };+ let waiter = state.pending.lock().await.remove(&token);+ if let Some(tx) = waiter {+ let _ = tx.send(Ok(endpoint));+ }+ }++ async fn unregistered(&self, token: String) {+ let Some(state) = self.state.upgrade() else {+ return;+ };+ let mut guard = state.active.write().await;+ if guard.as_ref().is_some_and(|a| a.client_token == token) {+ *guard = None;+ }+ }++ async fn registration_failed(&self, token: String, reason: String) {+ let Some(state) = self.state.upgrade() else {+ return;+ };+ let waiter = state.pending.lock().await.remove(&token);+ if let Some(tx) = waiter {+ let _ = tx.send(Err(reason));+ }+ }+}++fn handle_message(state: &UnifiedPushState, _token: &str, message: &[u8], _id: &str) {+ let parsed = parse_message_payload(message);++ // Normalize for the listener: the JS `Options` type marks `title` as a+ // required string and `extra` as an object. Falling back to the app's+ // product name (or identifier) for title, and wrapping non-object+ // payloads under a `_raw` key, keeps consumers from blowing up on+ // `null`/non-object values.+ let title = parsed+ .title+ .clone()+ .unwrap_or_else(|| state.fallback_title.clone());+ let extra = match parsed.extra.clone() {+ Some(JsonValue::Object(map)) => JsonValue::Object(map),+ Some(other) => json!({ "_raw": other }),+ None => json!({}),+ };++ let payload = json!({+ "source": "push",+ "title": title,+ "body": parsed.body,+ "extra": extra,+ });++ if let Err(e) = crate::listeners::trigger("notification", payload.to_string()) {+ log::warn!("Failed to dispatch push notification to listeners: {e}");+ }++ // Route the toast display through the displayer callback supplied by+ // `desktop.rs`. That path uses the same `notify-rust + active map`+ // pipeline as local notifications, so incoming pushes show up in+ // `Notifications::active()` and can be cancelled like any other+ // notification. Pass the original (possibly None) parsed title so the+ // desktop layer can decide whether to fall back to the app identifier.+ if let Some(displayer) = state.displayer.as_ref() {+ displayer(Some(title), parsed.body);+ }+}++#[derive(Debug, Default, PartialEq, Eq)]+struct ParsedPayload {+ title: Option<String>,+ body: Option<String>,+ extra: Option<JsonValue>,+}++fn parse_message_payload(bytes: &[u8]) -> ParsedPayload {+ let Ok(text) = std::str::from_utf8(bytes) else {+ return ParsedPayload {+ extra: Some(JsonValue::String(format!("<binary {} bytes>", bytes.len()))),+ ..ParsedPayload::default()+ };+ };++ if let Ok(value) = serde_json::from_str::<JsonValue>(text) {+ let title = value+ .get("title")+ .and_then(|v| v.as_str())+ .map(String::from);+ let body = value+ .get("body")+ .or_else(|| value.get("message"))+ .and_then(|v| v.as_str())+ .map(String::from);+ let extra = value.get("data").or_else(|| value.get("extra")).cloned();+ return ParsedPayload { title, body, extra };+ }++ ParsedPayload {+ body: Some(text.to_string()),+ ..ParsedPayload::default()+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn parse_json_message_with_title_and_body() {+ let bytes = br#"{"title":"hi","body":"hello"}"#;+ let parsed = parse_message_payload(bytes);+ assert_eq!(parsed.title.as_deref(), Some("hi"));+ assert_eq!(parsed.body.as_deref(), Some("hello"));+ assert!(parsed.extra.is_none());+ }++ #[test]+ fn parse_json_message_with_data_and_message_alias() {+ let bytes = br#"{"message":"hey","data":{"k":"v"}}"#;+ let parsed = parse_message_payload(bytes);+ assert_eq!(parsed.title, None);+ assert_eq!(parsed.body.as_deref(), Some("hey"));+ assert_eq!(parsed.extra, Some(json!({"k":"v"})));+ }++ #[test]+ fn parse_plain_text_becomes_body() {+ let bytes = b"hello there";+ let parsed = parse_message_payload(bytes);+ assert_eq!(parsed.title, None);+ assert_eq!(parsed.body.as_deref(), Some("hello there"));+ assert_eq!(parsed.extra, None);+ }++ #[test]+ fn parse_invalid_utf8_falls_back_to_marker() {+ let bytes = &[0xff, 0xfe, 0xfd];+ let parsed = parse_message_payload(bytes);+ assert!(parsed.title.is_none());+ assert!(parsed.body.is_none());+ assert!(matches!(parsed.extra, Some(JsonValue::String(_))));+ }++ #[test]+ fn err_distributor_unavailable_includes_name() {+ let msg = err_distributor_unavailable("org.unifiedpush.Distributor.foo");+ assert!(msg.contains("org.unifiedpush.Distributor.foo"));+ }+}diff --git a/src-tauri/vendor/tauri-plugin-notifications/src/windows.rs b/src-tauri/vendor/tauri-plugin-notifications/src/windows.rsnew file mode 100644index 00000000..dcd6d139--- /dev/null+++ b/src-tauri/vendor/tauri-plugin-notifications/src/windows.rs@@ -0,0 +1,1869 @@+//! Windows implementation for notifications plugin using native Windows Toast API.++// The `windows_core::implement` macro (used for `ToastActivator` /+// `ToastActivatorFactory`) expands to `#[inline(always)]` accessors and+// `&T as *const T` casts, emitted as sibling items whose spans land in this+// file. There's no source-level expression to rewrite, and an `#[allow]` on the+// annotated struct doesn't reach the generated impls, so both lints are scoped+// out here. Neither is written by hand anywhere in this module.+#![allow(clippy::inline_always, clippy::ref_as_ptr)]++use std::collections::HashMap;+use std::ffi::c_void;+use std::sync::{Arc, Mutex, OnceLock, RwLock, Weak};+use std::time::{Duration, Instant};++use nt_time::FileTime;+use serde::de::DeserializeOwned;+use tauri::{+ AppHandle, Manager, Runtime,+ path::BaseDirectory,+ plugin::{PermissionState, PluginApi},+};+use windows::ApplicationModel::Package;+use windows::Data::Xml::Dom::XmlDocument;+use windows::Foundation::Collections::ValueSet;+use windows::Foundation::{DateTime, IStringable, TypedEventHandler};+#[cfg(feature = "push-notifications")]+use windows::Networking::PushNotifications::{+ PushNotificationChannel, PushNotificationChannelManager,+};+use windows::UI::Notifications::{+ NotificationSetting, ScheduledToastNotification, ToastActivatedEventArgs, ToastNotification,+ ToastNotificationManager, ToastNotifier,+};+use windows::Win32::Foundation::{CLASS_E_NOAGGREGATION, E_FAIL, E_INVALIDARG, S_FALSE, S_OK};+use windows::Win32::System::Com::{+ CLSCTX_LOCAL_SERVER, COINIT_APARTMENTTHREADED, CoInitializeEx, CoRegisterClassObject,+ CoUninitialize, IClassFactory, IClassFactory_Impl, REGCLS_MULTIPLEUSE,+};+use windows::Win32::System::Registry::{+ HKEY, HKEY_CURRENT_USER, KEY_WRITE, REG_OPTION_NON_VOLATILE, REG_SZ, RegCloseKey,+ RegCreateKeyExW, RegSetValueExW,+};+use windows::Win32::UI::Notifications::{+ INotificationActivationCallback, INotificationActivationCallback_Impl,+ NOTIFICATION_USER_INPUT_DATA,+};+use windows::Win32::UI::WindowsAndMessaging::{+ DispatchMessageW, GetMessageW, MSG, TranslateMessage,+};+use windows::core::{BOOL, GUID, HSTRING, Interface, PCWSTR, Ref, implement};++use crate::WindowsConfig;+use crate::error::{ErrorResponse, PluginInvokeError};+use crate::models::{ActionType, ActiveNotification, PendingNotification, Schedule, ScheduleEvery};++/// True when the current process has MSIX package identity.+///+/// `WinRT` notification APIs split into two flavors: no-arg variants that use+/// the package's default AUMID (only valid for packaged apps), and `*WithId`+/// variants that take an explicit AUMID (only valid for unpackaged apps whose+/// AUMID is registered via a Start Menu shortcut). Passing an arbitrary string+/// to the `WithId` variants from inside an MSIX returns `ERROR_NOT_FOUND`+/// because the real AUMID is `<PackageFamilyName>!<Application Id>` and the+/// family-name hash is install-time only.+fn is_packaged() -> bool {+ Package::Current().is_ok()+}++/// Resolve a user-supplied image string into a URI scheme Windows toast+/// notifications can actually load.+///+/// Microsoft's toast schema only accepts `http(s)://`, `ms-appx:///`,+/// `ms-appdata:///local/`, and `file:///` for `<image src>`. Anything else+/// (Android resource names like `ic_notify`, bare relative paths,+/// `data:` URIs) makes Windows reject the toast XML and surface the+/// "New notification" placeholder instead of the real title/body.+///+/// Mapping:+/// - already-valid URI scheme → pass through+/// - absolute filesystem path → promote to `file:///`+/// - bare name + packaged → `ms-appx:///resources/<name>` (Tauri's+/// `bundle.resources` convention)+/// - bare name + unpackaged → resolve via Tauri's `PathResolver`, promote+/// to `file:///`+/// - anything else → `None` (caller drops the image, toast keeps rendering)+fn resolve_toast_image_src<R: Runtime>(+ app: &AppHandle<R>,+ input: &str,+ packaged: bool,+) -> Option<String> {+ let lower = input.to_ascii_lowercase();+ if lower.starts_with("http://")+ || lower.starts_with("https://")+ || lower.starts_with("ms-appx://")+ || lower.starts_with("ms-appdata://")+ || lower.starts_with("file://")+ {+ return Some(input.to_string());+ }+ if lower.starts_with("data:") {+ log::warn!(+ "Ignoring notification image data: URI: Windows toast schema doesn't \+ accept inline base64; write the bytes to a file and pass a file:/// URI"+ );+ return None;+ }+ let path = std::path::Path::new(input);+ if path.is_absolute() {+ return Some(path_to_file_uri(path));+ }+ if packaged {+ let trimmed = input.trim_start_matches('/');+ return Some(format!("ms-appx:///resources/{trimmed}"));+ }+ if let Ok(resolved) = app.path().resolve(input, BaseDirectory::Resource)+ && resolved.exists()+ {+ return Some(path_to_file_uri(&resolved));+ }+ log::warn!(+ "Ignoring notification image {input:?}: not a supported URI scheme, not an \+ absolute path, and not resolvable as a Tauri resource"+ );+ None+}++/// Convert a filesystem path to a `file:///` URI Windows accepts (forward+/// slashes, no backslashes — required even on Windows).+fn path_to_file_uri(path: &std::path::Path) -> String {+ let normalized = path.display().to_string().replace('\\', "/");+ if normalized.starts_with('/') {+ format!("file://{normalized}")+ } else {+ format!("file:///{normalized}")+ }+}++/// Accept any well-formed UUID string and reinterpret its bytes as a `GUID`.+///+/// Delegating to `uuid::Uuid::parse_str` lets the manifest CLSID and the+/// `tauri.conf.json` CLSID use either braced (`{xxxxxxxx-…}`), unbraced+/// (`xxxxxxxx-…`), or simple (32 hex chars, no hyphens) conventions without+/// drift causing parse failures.+fn parse_clsid(raw: &str) -> windows::core::Result<GUID> {+ let parsed = uuid::Uuid::parse_str(raw.trim())+ .map_err(|e| windows::core::Error::new(E_INVALIDARG, format!("{e}")))?;+ Ok(GUID::from_u128(parsed.as_u128()))+}++// Enable `?` operator for windows::core::Error+impl From<windows::core::Error> for crate::Error {+ fn from(err: windows::core::Error) -> Self {+ Self::from(PluginInvokeError::InvokeRejected(ErrorResponse {+ code: Some(format!("0x{:08X}", err.code().0)),+ message: Some(err.message()),+ data: (),+ }))+ }+}++/// Shared plugin state wrapped in Arc for thread-safe access.+pub struct WindowsPlugin {+ app_id: String,+ packaged: bool,+ notifier: ToastNotifier,+ action_types: RwLock<HashMap<String, ActionType>>,+ click_listener_active: RwLock<bool>,+ /// Cold-start activation payloads queued before any JS listener has+ /// subscribed. Drained synchronously the first time a `notificationClicked`+ /// listener registers (see `crate::listeners::register_listener`).+ pending_clicks: RwLock<Vec<serde_json::Value>>,+ /// `CoRegisterClassObject` cookie. Kept for the process lifetime — no+ /// explicit `CoRevokeClassObject` on shutdown; the OS reclaims it on exit.+ /// `None` when COM activator wasn't registered (unpackaged or no CLSID in+ /// config).+ com_cookie: RwLock<Option<u32>>,+ #[cfg(feature = "push-notifications")]+ push_channel: RwLock<Option<PushNotificationChannel>>,+}++/// COM activator that receives toast activations from Action Center, including+/// the cold-start case where Windows launches the exe via the manifest's+/// `windows.toastNotificationActivation` extension.+///+/// Wired up by `init()` only when the process has MSIX package identity AND+/// the plugin config carries a valid `toast_activator_clsid`. The callback+/// fires on a COM RPC worker thread (not the Tauri main thread), so all+/// downstream emissions must be thread-safe — `crate::listeners::trigger`+/// already is.+#[implement(INotificationActivationCallback)]+struct ToastActivator {+ plugin: Weak<WindowsPlugin>,+}++/// Out-of-proc COM activator pattern requires a class factory; `CoRegisterClassObject`+/// takes an `IUnknown` that must implement `IClassFactory`, not the activator+/// instance directly. There is no shortcut for the toast activator path.+#[implement(IClassFactory)]+struct ToastActivatorFactory {+ plugin: Weak<WindowsPlugin>,+}++impl std::fmt::Debug for WindowsPlugin {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ f.debug_struct("WindowsPlugin")+ .field("app_id", &self.app_id)+ .field("packaged", &self.packaged)+ .finish_non_exhaustive()+ }+}++/// Result of decoding a toast activation's `Arguments` string.+///+/// `build_toast_xml` encodes notification id + extras as JSON into the toast's+/// `launch=` attribute; foreground taps deliver that JSON in `Arguments`,+/// button activations deliver the action's `arguments=` (a plain string). This+/// struct lets the warm (in-process) and cold (COM) paths share decoding so+/// the event shapes the JS layer sees are byte-identical.+struct DecodedActivation {+ /// `notificationClicked` payload — `Some` for foreground taps, `None` for+ /// button activations.+ click: Option<serde_json::Value>,+ /// `actionPerformed` payload — always populated.+ action: serde_json::Value,+}++/// Vendored patch: id of the `<input>` box that submits through `action_id`.+fn input_element_id(action_id: &str) -> String {+ format!("input-{action_id}")+}++/// Vendored patch: the `arguments=` an `<action>` carries.+///+/// JSON rather than the bare action id so `extra` (session id, title, tag)+/// survives a cold COM activation, which only ever sees this string.+fn action_arguments(action_id: &str, extra: &HashMap<String, serde_json::Value>) -> String {+ serde_json::json!({+ "actionId": action_id,+ "data": extra,+ })+ .to_string()+}++fn decode_activation(invoked_args: &str, inputs: &HashMap<String, String>) -> DecodedActivation {+ let input_value = inputs+ .values()+ .next()+ .cloned()+ .map_or(serde_json::Value::Null, serde_json::Value::String);++ let parsed: Option<serde_json::Value> = serde_json::from_str::<serde_json::Value>(invoked_args)+ .ok()+ .filter(serde_json::Value::is_object);++ // Vendored patch: button activations encode `{"actionId": …, "data": …}` in+ // the action's `arguments=` so the session identity survives a cold+ // activation — the COM callback never receives the toast's `launch=`+ // string. Checked before the tuple match below because such a payload is+ // also a JSON object and would otherwise be misread as a tap.+ if let Some(action_id) = parsed+ .as_ref()+ .and_then(|payload| payload.get("actionId"))+ .and_then(serde_json::Value::as_str)+ {+ let extra = parsed+ .as_ref()+ .and_then(|payload| payload.get("data"))+ .cloned()+ .unwrap_or(serde_json::Value::Null);+ let action = serde_json::json!({+ "actionId": action_id,+ "inputValue": input_value,+ "notification": serde_json::Value::Null,+ "extra": extra,+ });+ return DecodedActivation {+ click: None,+ action,+ };+ }++ // Two independent axes: whether `invoked_args` decoded as the `launch=`+ // JSON object we wrote, and whether it's empty at all. Matched as a tuple+ // so the three outcomes stay side by side.+ match (parsed, invoked_args.is_empty()) {+ (Some(launch), _) => {+ let extra = launch+ .get("data")+ .cloned()+ .unwrap_or(serde_json::Value::Null);+ // `json!` borrows its value expression (`to_value(&expr)`), so+ // `launch` is still ours to move into `click` afterwards.+ let action = serde_json::json!({+ "actionId": "tap",+ "inputValue": input_value,+ "notification": launch,+ "extra": extra,+ });+ DecodedActivation {+ click: Some(launch),+ action,+ }+ }+ // Legacy path: toasts produced before `launch=` was set, or a tap with+ // no extras. Emit a click with no payload so subscribers still fire.+ (None, true) => {+ let action = serde_json::json!({+ "actionId": "tap",+ "inputValue": input_value,+ "notification": serde_json::Value::Null,+ "extra": {},+ });+ DecodedActivation {+ click: Some(serde_json::json!({ "id": serde_json::Value::Null, "data": {} })),+ action,+ }+ }+ // Button activation carrying legacy plain-string `arguments=`.+ (None, false) => {+ let action = serde_json::json!({+ "actionId": invoked_args,+ "inputValue": input_value,+ "notification": serde_json::Value::Null,+ "extra": serde_json::Value::Null,+ });+ DecodedActivation {+ click: None,+ action,+ }+ }+ }+}++/// Vendored patch: identity of one activation — the arguments plus every+/// user-input pair, sorted so map iteration order cannot produce two different+/// signatures for the same activation.+fn activation_signature(invoked_args: &str, inputs: &HashMap<String, String>) -> String {+ let mut entries: Vec<(&str, &str)> = inputs+ .iter()+ .map(|(key, value)| (key.as_str(), value.as_str()))+ .collect();+ entries.sort_unstable();++ let mut signature = String::from(invoked_args);+ for (key, value) in entries {+ signature.push('\u{1}');+ signature.push_str(key);+ signature.push('=');+ signature.push_str(value);+ }+ signature+}++/// Vendored patch: activations already delivered, for+/// [`claim_activation`].+static DELIVERED: OnceLock<Mutex<Option<(String, Instant)>>> = OnceLock::new();++/// Window inside which a repeated signature counts as the same activation.+const DEDUP_WINDOW: Duration = Duration::from_millis(1500);++/// Vendored patch: `true` when this activation has not already been delivered.+///+/// One toast click reaches Windows through two independent routes — the+/// in-process `Activated` handler and the out-of-proc COM activator — and+/// either can run first. Collapsing identical signatures within+/// [`DEDUP_WINDOW`] makes the JS layer see exactly one event per click.+///+/// A poisoned lock or clock anomaly fails open (report as new): a duplicate+/// event is preferable to a silently swallowed click.+fn claim_activation(signature: &str) -> bool {+ let Ok(mut guard) = DELIVERED.get_or_init(|| Mutex::new(None)).lock() else {+ return true;+ };+ let now = Instant::now();+ if let Some((previous, at)) = guard.as_ref()+ && previous == signature+ && now.duration_since(*at) < DEDUP_WINDOW+ {+ return false;+ }+ *guard = Some((signature.to_string(), now));+ true+}++/// Vendored patch: collect the toast text-box contents.+///+/// Windows hands them over as a `ValueSet` keyed by the `<input id=…>` the+/// toast XML declared. Every failure degrades to "no text" rather than losing+/// the activation — an empty reply still reaches the JS layer as an event.+fn read_user_input(user_input: Option<&ValueSet>) -> HashMap<String, String> {+ let mut inputs = HashMap::new();+ let Some(set) = user_input else {+ return inputs;+ };+ let Ok(iterator) = set.First() else {+ return inputs;+ };++ while iterator.HasCurrent().unwrap_or(false) {+ if let Ok(pair) = iterator.Current() {+ let key = pair.Key().map(|key| key.to_string()).unwrap_or_default();+ if !key.is_empty() {+ let value = pair+ .Value()+ .ok()+ .and_then(|value| value.cast::<IStringable>().ok())+ .and_then(|value| value.ToString().ok())+ .map(|value| value.to_string())+ .unwrap_or_default();+ inputs.insert(key, value);+ }+ }+ if !iterator.MoveNext().unwrap_or(false) {+ break;+ }+ }++ inputs+}++impl INotificationActivationCallback_Impl for ToastActivator_Impl {+ fn Activate(+ &self,+ _appusermodelid: &PCWSTR,+ invokedargs: &PCWSTR,+ data: *const NOTIFICATION_USER_INPUT_DATA,+ count: u32,+ ) -> windows::core::Result<()> {+ let invoked = unsafe { invokedargs.to_string() }.unwrap_or_default();+ let mut inputs: HashMap<String, String> = HashMap::new();+ if count > 0 && !data.is_null() {+ let slice = unsafe { std::slice::from_raw_parts(data, count as usize) };+ for entry in slice {+ let k = unsafe { entry.Key.to_string() }.unwrap_or_default();+ let v = unsafe { entry.Value.to_string() }.unwrap_or_default();+ if !k.is_empty() {+ inputs.insert(k, v);+ }+ }+ }++ let decoded = decode_activation(&invoked, &inputs);++ // Vendored patch: the same physical click also reaches the in-process+ // `Activated` handler, so collapse the pair into one event.+ if !claim_activation(&activation_signature(&invoked, &inputs)) {+ log::debug!(+ "Toast activation already delivered; skipping COM callback (args={invoked:?})"+ );+ return Ok(());+ }++ log::debug!("Toast COM activation (args={invoked:?}, inputs={})", inputs.len());+ let _ = crate::listeners::trigger("actionPerformed", decoded.action.to_string());++ if let Some(click_payload) = decoded.click {+ // Deliver live OR buffer — never both. Buffering when a listener is+ // already subscribed causes duplicate events on the next re-subscribe+ // (hot reload, route change).+ if crate::listeners::has_listeners("notificationClicked") {+ let _ = crate::listeners::trigger("notificationClicked", click_payload.to_string());+ } else if let Some(plugin) = self.plugin.upgrade()+ && let Ok(mut buf) = plugin.pending_clicks.write()+ {+ buf.push(click_payload);+ }+ }+ Ok(())+ }+}++impl IClassFactory_Impl for ToastActivatorFactory_Impl {+ fn CreateInstance(+ &self,+ punkouter: Ref<'_, windows::core::IUnknown>,+ riid: *const GUID,+ ppvobject: *mut *mut c_void,+ ) -> windows::core::Result<()> {+ if !punkouter.is_null() {+ return Err(CLASS_E_NOAGGREGATION.into());+ }+ let activator = ToastActivator {+ plugin: self.plugin.clone(),+ };+ let interface: INotificationActivationCallback = activator.into();+ unsafe { interface.query(riid, ppvobject).ok() }+ }++ fn LockServer(&self, _flock: BOOL) -> windows::core::Result<()> {+ Ok(())+ }+}++impl WindowsPlugin {+ fn action_types(&self) -> crate::Result<HashMap<String, ActionType>> {+ Ok(self+ .action_types+ .read()+ .map_err(|_| crate::Error::Io(std::io::Error::other("Lock poisoned")))?+ .clone())+ }++ fn action_types_mut(+ &self,+ ) -> crate::Result<std::sync::RwLockWriteGuard<'_, HashMap<String, ActionType>>> {+ self.action_types+ .write()+ .map_err(|_| crate::Error::Io(std::io::Error::other("Lock poisoned")))+ }++ fn is_click_listener_active(&self) -> crate::Result<bool> {+ Ok(*self+ .click_listener_active+ .read()+ .map_err(|_| crate::Error::Io(std::io::Error::other("Lock poisoned")))?)+ }++ fn set_click_listener(&self, active: bool) -> crate::Result<()> {+ *self+ .click_listener_active+ .write()+ .map_err(|_| crate::Error::Io(std::io::Error::other("Lock poisoned")))? = active;+ Ok(())+ }++ /// Drain queued cold-start click payloads through the listener bus. Called+ /// when a `notificationClicked` listener subscribes (see+ /// `crate::listeners::register_listener`). Idempotent: subsequent calls+ /// with an empty buffer are a no-op.+ pub fn drain_pending_clicks(&self) {+ let drained: Vec<serde_json::Value> = match self.pending_clicks.write() {+ Ok(mut buf) => std::mem::take(&mut *buf),+ Err(e) => {+ log::error!("pending_clicks lock poisoned during drain: {e}");+ return;+ }+ };+ for payload in drained {+ if let Err(e) = crate::listeners::trigger("notificationClicked", payload.to_string()) {+ log::error!("Failed to dispatch buffered click: {e}");+ }+ }+ }++ // `self` is only touched by the push-notifications body; the stub compiled+ // when the feature is off must keep the same signature for its call site.+ #[cfg_attr(not(feature = "push-notifications"), allow(clippy::unused_self))]+ fn open_push_channel(&self) -> crate::Result<String> {+ #[cfg(feature = "push-notifications")]+ {+ let channel =+ PushNotificationChannelManager::CreatePushNotificationChannelForApplicationAsync()?+ .get()?;+ let uri = channel.Uri()?.to_string_lossy();+ *self+ .push_channel+ .write()+ .map_err(|_| crate::Error::Io(std::io::Error::other("Lock poisoned")))? =+ Some(channel);+ Ok(uri)+ }+ #[cfg(not(feature = "push-notifications"))]+ {+ Err(crate::Error::Io(std::io::Error::other(+ "Push notifications feature not enabled",+ )))+ }+ }++ #[cfg_attr(not(feature = "push-notifications"), allow(clippy::unused_self))]+ fn close_push_channel(&self) -> crate::Result<()> {+ #[cfg(feature = "push-notifications")]+ {+ // Take the channel out in its own statement so the write guard is+ // released before calling into WinRT — `Close()` is a cross-process+ // call and shouldn't run with the lock held.+ let channel = self+ .push_channel+ .write()+ .map_err(|_| crate::Error::Io(std::io::Error::other("Lock poisoned")))?+ .take();+ if let Some(channel) = channel {+ channel.Close()?;+ }+ Ok(())+ }+ #[cfg(not(feature = "push-notifications"))]+ {+ Err(crate::Error::Io(std::io::Error::other(+ "Push notifications feature not enabled",+ )))+ }+ }+}++pub fn init<R: Runtime, C: DeserializeOwned>(+ app: &AppHandle<R>,+ _api: PluginApi<R, C>,+ windows_config: WindowsConfig,+) -> crate::Result<Notifications<R>> {+ let app_id = app.config().identifier.clone();+ let packaged = is_packaged();+ let notifier = if packaged {+ ToastNotificationManager::CreateToastNotifier()?+ } else {+ ToastNotificationManager::CreateToastNotifierWithId(&HSTRING::from(&app_id))?+ };++ let plugin = Arc::new(WindowsPlugin {+ app_id,+ packaged,+ notifier,+ action_types: RwLock::new(HashMap::new()),+ click_listener_active: RwLock::new(false),+ pending_clicks: RwLock::new(Vec::new()),+ com_cookie: RwLock::new(None),+ #[cfg(feature = "push-notifications")]+ push_channel: RwLock::new(None),+ });++ // Vendored patch: the COM activator used to be registered only for packaged+ // builds, which meant unpackaged DSH never received click or button events+ // at all. Registering it always is half the fix; the other half is+ // `register_unpackaged_app_id` below, which gives Windows an AUMID whose+ // `CustomActivator` points at this CLSID.+ if let Some(clsid_str) = windows_config.toast_activator_clsid.as_deref() {+ if !packaged {+ let display_name = app+ .config()+ .product_name+ .clone()+ .unwrap_or_else(|| plugin.app_id.clone());+ if let Err(e) = register_unpackaged_app_id(&display_name, &plugin.app_id, clsid_str) {+ log::error!(+ "Failed to register AUMID {} for toast activation: {e}; \+ Action Center clicks will fall back to shortcut launch without payload",+ plugin.app_id+ );+ }+ }+ spawn_toast_activator(&plugin, clsid_str);+ }++ Ok(Notifications {+ app: app.clone(),+ plugin,+ })+}++/// Vendored patch: write a `REG_SZ` value, creating the key when absent.+fn write_registry_string(key: HKEY, name: Option<&str>, value: &str) -> windows::core::Result<()> {+ let mut buffer: Vec<u16> = value.encode_utf16().collect();+ buffer.push(0);+ // `RegSetValueExW` takes a byte slice and passes its length as `cbdata`, so+ // the UTF-16 code units have to be reinterpreted rather than copied.+ let bytes = unsafe { buffer.align_to::<u8>().1 };++ let name = name.map(HSTRING::from);+ // The two branches instantiate `P1` differently (`&HSTRING` vs `PCWSTR`) —+ // both satisfy `Param<PCWSTR>`, but through different impls, so they cannot+ // share one call expression.+ let status = unsafe {+ match name.as_ref() {+ Some(name) => RegSetValueExW(key, name, None, REG_SZ, Some(bytes)),+ None => RegSetValueExW(key, PCWSTR::null(), None, REG_SZ, Some(bytes)),+ }+ };+ if status.0 != 0 {+ Err(status.into())+ } else {+ Ok(())+ }+}++/// Vendored patch: register the AUMID an unpackaged build needs for toast+/// activation.+///+/// A packaged app inherits a working AUMID from its manifest. An unpackaged one+/// has none, and without it Windows has no idea which COM class to activate when+/// the user clicks a toast — the click silently degrades into a plain shortcut+/// launch that carries no payload. These keys give it that mapping:+/// `Software\Classes\AppUserModelId\<app_id>` carries the display name and the+/// `CustomActivator` CLSID, and `Software\Classes\CLSID\{clsid}\LocalServer32`+/// points at this executable so Windows can relaunch it for a cold activation.+///+/// Mirrors what the wry/tao notification guides and the Windows SDK describe for+/// unpackaged toast registration. Best-effort: failures are logged and the+/// in-process `Activated` path still delivers clicks while the app is running.+fn register_unpackaged_app_id(+ display_name: &str,+ app_id: &str,+ clsid_str: &str,+) -> windows::core::Result<()> {+ let exe = std::env::current_exe().map_err(|e| {+ windows::core::Error::new(E_FAIL, format!("cannot resolve current executable: {e}"))+ })?;+ let exe = exe.to_string_lossy().into_owned();++ // HKCU\Software\Classes\AppUserModelId\<app_id>+ let aumid_path = HSTRING::from(format!("Software\\Classes\\AppUserModelId\\{app_id}"));+ let mut aumid_key = HKEY::default();+ let status = unsafe {+ RegCreateKeyExW(+ HKEY_CURRENT_USER,+ &aumid_path,+ None,+ PCWSTR::null(),+ REG_OPTION_NON_VOLATILE,+ KEY_WRITE,+ None,+ &raw mut aumid_key,+ None,+ )+ };+ if status.0 != 0 {+ return Err(status.into());+ }+ let result = write_registry_string(aumid_key, Some("DisplayName"), display_name)+ .and_then(|()| write_registry_string(aumid_key, Some("IconUri"), &exe))+ .and_then(|()| {+ write_registry_string(+ aumid_key,+ Some("CustomActivator"),+ &format!("{{{clsid_str}}}"),+ )+ });+ unsafe { let _ = RegCloseKey(aumid_key); };+ result?;++ // HKCU\Software\Classes\CLSID\{clsid}+ let clsid_path = HSTRING::from(format!("Software\\Classes\\CLSID\\{{{clsid_str}}}"));+ let mut clsid_key = HKEY::default();+ let status = unsafe {+ RegCreateKeyExW(+ HKEY_CURRENT_USER,+ &clsid_path,+ None,+ PCWSTR::null(),+ REG_OPTION_NON_VOLATILE,+ KEY_WRITE,+ None,+ &raw mut clsid_key,+ None,+ )+ };+ if status.0 != 0 {+ return Err(status.into());+ }+ let result = write_registry_string(clsid_key, None, display_name);+ unsafe { let _ = RegCloseKey(clsid_key); };+ result?;++ // HKCU\Software\Classes\CLSID\{clsid}\LocalServer32 = <exe>+ let server_path = HSTRING::from(format!(+ "Software\\Classes\\CLSID\\{{{clsid_str}}}\\LocalServer32"+ ));+ let mut server_key = HKEY::default();+ let status = unsafe {+ RegCreateKeyExW(+ HKEY_CURRENT_USER,+ &server_path,+ None,+ PCWSTR::null(),+ REG_OPTION_NON_VOLATILE,+ KEY_WRITE,+ None,+ &raw mut server_key,+ None,+ )+ };+ if status.0 != 0 {+ return Err(status.into());+ }+ let result = write_registry_string(server_key, None, &exe);+ unsafe { let _ = RegCloseKey(server_key); };+ result?;++ log::info!("Registered unpackaged AUMID {app_id} (clsid={clsid_str}, exe={exe})");+ Ok(())+}++/// Vendored patch: run `register_toast_activator` on a dedicated+/// single-threaded-apartment thread that pumps messages for the life of the+/// process.+///+/// `CoRegisterClassObject` binds the class to the apartment of the calling+/// thread, and an STA only serves incoming activation calls while it pumps its+/// message queue. Tauri's main thread is already MTA (`CoInitializeEx` there+/// returns `RPC_E_CHANGED_MODE`, which is why the old code silently failed to+/// register), so registration gets its own thread that blocks in `GetMessageW`.+fn spawn_toast_activator(plugin: &Arc<WindowsPlugin>, clsid_str: &str) {+ let clsid = match parse_clsid(clsid_str) {+ Ok(clsid) => clsid,+ Err(e) => {+ log::error!("Invalid toastActivatorClsid {clsid_str}: {e}");+ return;+ }+ };+ let factory = ToastActivatorFactory {+ plugin: Arc::downgrade(plugin),+ };+ let plugin = Arc::clone(plugin);+ let clsid_str = clsid_str.to_string();++ let spawned = std::thread::Builder::new()+ .name("dsh-toast-activator".to_string())+ .spawn(move || {+ let hr = unsafe { CoInitializeEx(None, COINIT_APARTMENTTHREADED) };+ if hr != S_OK && hr != S_FALSE {+ log::error!("Failed to initialize toast activator apartment: {hr:?}");+ return;+ }+ let factory_interface: IClassFactory = factory.into();+ let cookie =+ unsafe { CoRegisterClassObject(&raw const clsid, &factory_interface, CLSCTX_LOCAL_SERVER, REGCLS_MULTIPLEUSE) };+ match cookie {+ Ok(cookie) => {+ if let Ok(mut slot) = plugin.com_cookie.write() {+ *slot = Some(cookie);+ }+ log::info!("Toast activator registered (clsid={clsid_str}, cookie={cookie})");+ }+ Err(e) => {+ log::error!(+ "Failed to register toast activator (clsid={clsid_str}): {e}; \+ Action Center clicks will fall back to shortcut launch without payload"+ );+ return;+ }+ }++ // Keep the apartment alive and dispatch activation calls until the+ // process exits. `GetMessageW` returning 0 (WM_QUIT) or -1 (error)+ // both end the loop.+ let mut message = MSG::default();+ loop {+ let result = unsafe { GetMessageW(&raw mut message, None, 0, 0) };+ if result.0 == 0 || result.0 == -1 {+ break;+ }+ unsafe {+ let _ = TranslateMessage(&raw const message);+ DispatchMessageW(&raw const message);+ }+ }+ unsafe { CoUninitialize() };+ });++ if let Err(e) = spawned {+ log::error!("Failed to spawn toast activator thread: {e}");+ }+}++// `async` mirrors the mobile/macOS plugin API so callers can `.await` uniformly.+#[allow(unknown_lints, clippy::unused_async, clippy::unused_async_trait_impl)]+impl<R: Runtime> crate::NotificationsBuilder<R> {+ /// Build toast notification XML using DOM API (safer than string concatenation).+ fn build_toast_xml(+ &self,+ action_types: &HashMap<String, ActionType>,+ ) -> crate::Result<XmlDocument> {+ let doc = XmlDocument::new()?;++ // Create root <toast>+ let toast = doc.CreateElement(&HSTRING::from("toast"))?;+ doc.AppendChild(&toast)?;++ // Encode notification id + extras into `launch=` so the click payload+ // survives a cold-start activation (the COM `Activate` callback only+ // receives the launch string; the in-process `Activated` handler+ // delivers the same string in `ToastActivatedEventArgs.Arguments`).+ let launch = serde_json::json!({+ "id": self.data.id,+ "data": self.data.extra,+ });+ toast.SetAttribute(+ &HSTRING::from("launch"),+ &HSTRING::from(launch.to_string().as_str()),+ )?;++ // Create <visual><binding template="ToastGeneric">+ let visual = doc.CreateElement(&HSTRING::from("visual"))?;+ let binding = doc.CreateElement(&HSTRING::from("binding"))?;+ binding.SetAttribute(&HSTRING::from("template"), &HSTRING::from("ToastGeneric"))?;++ // Add <text> elements for title/body+ if let Some(title) = &self.data.title {+ let text = doc.CreateElement(&HSTRING::from("text"))?;+ text.SetInnerText(&HSTRING::from(title.as_str()))?;+ binding.AppendChild(&text)?;+ }++ if let Some(body) = &self.data.body {+ let text = doc.CreateElement(&HSTRING::from("text"))?;+ text.SetInnerText(&HSTRING::from(body.as_str()))?;+ binding.AppendChild(&text)?;+ }++ // Skip when identical to `body`: WinRT renders each `<text>` on its+ // own line, so duplicating it just shows the same string twice in the+ // expanded view (issue #231).+ if let Some(large_body) = &self.data.large_body+ && self.data.body.as_ref() != Some(large_body)+ {+ let text = doc.CreateElement(&HSTRING::from("text"))?;+ text.SetInnerText(&HSTRING::from(large_body.as_str()))?;+ binding.AppendChild(&text)?;+ }++ // Add icon if specified. Drop silently when the user-supplied string+ // can't be coerced into a Windows-accepted URI scheme — otherwise the+ // whole toast falls back to "New notification".+ if let Some(icon) = &self.data.icon+ && let Some(src) = resolve_toast_image_src(&self.app, icon, self.plugin.packaged)+ {+ let image = doc.CreateElement(&HSTRING::from("image"))?;+ image.SetAttribute(+ &HSTRING::from("placement"),+ &HSTRING::from("appLogoOverride"),+ )?;+ image.SetAttribute(&HSTRING::from("src"), &HSTRING::from(src.as_str()))?;+ binding.AppendChild(&image)?;+ }++ // Add attachments as images. Same URI resolution applies.+ let mut hero_slot_taken = false;+ for attachment in &self.data.attachments {+ let Some(src) =+ resolve_toast_image_src(&self.app, attachment.url().as_str(), self.plugin.packaged)+ else {+ continue;+ };+ let image = doc.CreateElement(&HSTRING::from("image"))?;+ if !hero_slot_taken {+ image.SetAttribute(&HSTRING::from("placement"), &HSTRING::from("hero"))?;+ hero_slot_taken = true;+ }+ image.SetAttribute(&HSTRING::from("src"), &HSTRING::from(src.as_str()))?;+ binding.AppendChild(&image)?;+ }++ visual.AppendChild(&binding)?;+ toast.AppendChild(&visual)?;++ // Add <actions> if action_type_id specified+ if let Some(action_type_id) = &self.data.action_type_id+ && let Some(action_type) = action_types.get(action_type_id)+ {+ let actions = doc.CreateElement(&HSTRING::from("actions"))?;++ // Vendored patch: text boxes are declared before the buttons that+ // submit them, since `<action hint-inputId=…>` can only reference an+ // id that already exists in the document.+ for action in action_type.actions() {+ if !action.input() {+ continue;+ }+ let input = doc.CreateElement(&HSTRING::from("input"))?;+ input.SetAttribute(+ &HSTRING::from("id"),+ &HSTRING::from(input_element_id(action.id()).as_str()),+ )?;+ input.SetAttribute(&HSTRING::from("type"), &HSTRING::from("text"))?;+ if let Some(placeholder) = action.input_placeholder() {+ input.SetAttribute(+ &HSTRING::from("placeHolderContent"),+ &HSTRING::from(placeholder),+ )?;+ }+ actions.AppendChild(&input)?;+ }++ for action in action_type.actions() {+ let action_el = doc.CreateElement(&HSTRING::from("action"))?;+ // Vendored patch: an input action's caption is the submit+ // button label, which Windows takes from the same `content=`+ // attribute as any other button.+ let content = action.input_button_title().unwrap_or(action.title());+ action_el.SetAttribute(&HSTRING::from("content"), &HSTRING::from(content))?;+ action_el.SetAttribute(+ &HSTRING::from("arguments"),+ &HSTRING::from(action_arguments(action.id(), &self.data.extra).as_str()),+ )?;+ if action.input() {+ action_el.SetAttribute(+ &HSTRING::from("hint-inputId"),+ &HSTRING::from(input_element_id(action.id()).as_str()),+ )?;+ }+ let activation_type = if action.foreground() {+ "foreground"+ } else {+ "background"+ };+ action_el.SetAttribute(+ &HSTRING::from("activationType"),+ &HSTRING::from(activation_type),+ )?;+ actions.AppendChild(&action_el)?;+ }+ toast.AppendChild(&actions)?;+ }++ // Add <audio> element for silent or custom sound+ if self.data.silent {+ let audio = doc.CreateElement(&HSTRING::from("audio"))?;+ audio.SetAttribute(&HSTRING::from("silent"), &HSTRING::from("true"))?;+ toast.AppendChild(&audio)?;+ } else if let Some(sound) = &self.data.sound {+ let audio = doc.CreateElement(&HSTRING::from("audio"))?;+ audio.SetAttribute(&HSTRING::from("src"), &HSTRING::from(sound.as_str()))?;+ toast.AppendChild(&audio)?;+ }++ Ok(doc)+ }++ #[allow(unknown_lints, clippy::unused_async, clippy::unused_async_trait_impl)]+ pub async fn show(self) -> crate::Result<()> {+ let action_types = self.plugin.action_types()?;+ let toast_xml = self.build_toast_xml(&action_types)?;++ let tag = HSTRING::from(self.data.id.to_string());+ let group = self.data.group.as_ref().map(|g| HSTRING::from(g.as_str()));++ // Check if this is a scheduled notification+ if let Some(schedule) = &self.data.schedule {+ let delivery_time = schedule_to_datetime(schedule)?;+ let scheduled = ScheduledToastNotification::CreateScheduledToastNotification(+ &toast_xml,+ delivery_time,+ )?;++ scheduled.SetTag(&tag)?;+ if let Some(g) = &group {+ scheduled.SetGroup(g)?;+ }++ self.plugin.notifier.AddToSchedule(&scheduled)?;+ } else {+ // Immediate notification+ let toast = ToastNotification::CreateToastNotification(&toast_xml)?;+ toast.SetTag(&tag)?;+ if let Some(g) = &group {+ toast.SetGroup(g)?;+ }++ // Vendored patch: `is_click_listener_active` alone was the gate, so a+ // subscriber that only listened for `actionPerformed` (the reply+ // button on a question toast, which carries the typed text) never got+ // an in-process handler attached at all. Either listener now counts.+ if self.plugin.is_click_listener_active()?+ || crate::listeners::has_listeners("actionPerformed")+ {+ let notification = ActiveNotification {+ id: self.data.id,+ tag: Some(self.data.id.to_string()),+ title: self.data.title.clone(),+ body: self.data.body.clone(),+ group: self.data.group.clone(),+ group_summary: self.data.group_summary,+ data: HashMap::new(),+ extra: self.data.extra.clone(),+ attachments: self.data.attachments.clone(),+ action_type_id: self.data.action_type_id.clone(),+ schedule: self.data.schedule.clone(),+ sound: self.data.sound.clone(),+ };++ toast.Activated(&TypedEventHandler::new(+ move |_: windows::core::Ref<'_, ToastNotification>,+ args: windows::core::Ref<'_, windows::core::IInspectable>| {+ if let Some(inspectable) = &*args+ && let Ok(activated) = inspectable.cast::<ToastActivatedEventArgs>()+ {+ let arguments = activated+ .Arguments()+ .map(|s| s.to_string_lossy())+ .unwrap_or_default();++ // Vendored patch: text typed into any `<input>` the+ // toast declared. Windows delivers it only through+ // this event args interface, so without reading it+ // here a reply could never reach the JS layer.+ let inputs =+ read_user_input(activated.UserInput().ok().as_ref());+ let input_value = inputs+ .values()+ .next()+ .cloned()+ .map_or(serde_json::Value::Null, serde_json::Value::String);++ // Vendored patch: one click reaches us twice — here+ // and through the out-of-proc COM activator (see+ // `claim_activation`). Both carry the same arguments+ // and inputs, so the first one through wins.+ if !claim_activation(&activation_signature(&arguments, &inputs)) {+ log::debug!(+ "Toast activation already delivered; skipping in-process handler (args={arguments:?})"+ );+ return Ok(());+ }++ let parsed: Option<serde_json::Value> =+ serde_json::from_str::<serde_json::Value>(&arguments)+ .ok()+ .filter(serde_json::Value::is_object);++ // Foreground tap: empty `Arguments` (legacy toasts+ // without `launch=`) or the JSON object we wrote into+ // `launch=`. A JSON object carrying `actionId` came+ // from an `<action arguments=…>` button instead — the+ // `launch=` object never has that key.+ let button = parsed+ .as_ref()+ .and_then(|payload| payload.get("actionId"))+ .and_then(serde_json::Value::as_str);+ let is_tap = button.is_none()+ && (arguments.is_empty() || parsed.is_some());++ let action_id = match button {+ Some(action_id) => action_id.to_string(),+ None => "tap".to_string(),+ };++ // Vendored patch: surface `extra` alongside the+ // notification so the JS layer can recover the+ // session identity from a button activation too.+ let extra = parsed+ .as_ref()+ .and_then(|payload| payload.get("data"))+ .cloned()+ .unwrap_or(serde_json::Value::Null);++ let payload = serde_json::json!({+ "actionId": action_id,+ "inputValue": input_value,+ "notification": notification,+ "extra": extra,+ });+ if let Err(e) =+ crate::listeners::trigger("actionPerformed", payload.to_string())+ {+ log::error!("Failed to trigger actionPerformed: {e}");+ }++ if is_tap {+ let click_payload = serde_json::json!({+ "id": notification.id,+ "data": notification.extra,+ });+ if let Err(e) = crate::listeners::trigger(+ "notificationClicked",+ click_payload.to_string(),+ ) {+ log::error!("Failed to trigger notificationClicked: {e}");+ }+ }+ }+ Ok(())+ },+ ))?;+ }++ self.plugin.notifier.Show(&toast)?;+ }++ // Trigger notification event+ let payload = serde_json::json!({+ "id": self.data.id,+ "title": self.data.title,+ "body": self.data.body,+ "actionTypeId": self.data.action_type_id,+ "extra": self.data.extra,+ });+ if let Err(e) = crate::listeners::trigger("notification", payload.to_string()) {+ log::error!("Failed to trigger notification: {e}");+ }++ Ok(())+ }+}++/// Convert Schedule to Windows `DateTime`.+fn schedule_to_datetime(schedule: &Schedule) -> crate::Result<DateTime> {+ let now = time::OffsetDateTime::now_utc();++ let delivery_time = match schedule {+ Schedule::At { date, .. } => *date,+ Schedule::Interval { interval, .. } => {+ // Build duration from interval fields+ let seconds = i64::from(interval.second.unwrap_or(0));+ let minutes = i64::from(interval.minute.unwrap_or(0));+ let hours = i64::from(interval.hour.unwrap_or(0));+ let days = i64::from(interval.day.unwrap_or(0));+ let total_seconds = seconds + minutes * 60 + hours * 3600 + days * 86400;+ now + time::Duration::seconds(total_seconds)+ }+ Schedule::Every {+ interval, count, ..+ } => {+ let base_seconds: i64 = match interval {+ ScheduleEvery::Year => 365 * 86400,+ ScheduleEvery::Month => 30 * 86400,+ ScheduleEvery::TwoWeeks => 14 * 86400,+ ScheduleEvery::Week => 7 * 86400,+ ScheduleEvery::Day => 86400,+ ScheduleEvery::Hour => 3600,+ ScheduleEvery::Minute => 60,+ ScheduleEvery::Second => 1,+ };+ now + time::Duration::seconds(base_seconds * i64::from(*count))+ }+ };++ unix_to_windows_datetime(delivery_time)+}++/// Convert a Unix timestamp to Windows `DateTime` (FILETIME).+fn unix_to_windows_datetime(time: time::OffsetDateTime) -> crate::Result<DateTime> {+ let ft = FileTime::try_from(time.to_utc())+ .map_err(|_| crate::Error::Io(std::io::Error::other("Schedule date out of range")))?;+ let raw: i64 = ft+ .to_raw()+ .try_into()+ .map_err(|_| crate::Error::Io(std::io::Error::other("Schedule date out of range")))?;+ Ok(DateTime { UniversalTime: raw })+}++/// Convert Windows `DateTime` (FILETIME) back to Unix timestamp.+fn windows_datetime_to_unix(dt: DateTime) -> crate::Result<time::OffsetDateTime> {+ let raw: u64 = dt+ .UniversalTime+ .try_into()+ .map_err(|_| crate::Error::Io(std::io::Error::other("DateTime out of range")))?;+ let utc = time::UtcDateTime::try_from(FileTime::new(raw))+ .map_err(|_| crate::Error::Io(std::io::Error::other("DateTime out of range")))?;+ Ok(utc.into())+}++pub struct Notifications<R: Runtime> {+ #[allow(dead_code)]+ app: AppHandle<R>,+ plugin: Arc<WindowsPlugin>,+}++// `async` mirrors the mobile/macOS plugin API so callers can `.await` uniformly.+#[allow(unknown_lints, clippy::unused_async, clippy::unused_async_trait_impl)]+impl<R: Runtime> Notifications<R> {+ pub fn builder(&self) -> crate::NotificationsBuilder<R> {+ crate::NotificationsBuilder::new(self.app.clone(), self.plugin.clone())+ }++ /// Drain any cold-start activation payloads queued before the JS+ /// `notificationClicked` listener subscribed. Invoked by+ /// `crate::listeners::register_listener` on first subscription so the+ /// `push-listener.tsx` contract ("subscribing flushes the buffered tap")+ /// holds without the app having to call any extra command.+ pub fn drain_pending_clicks(&self) {+ self.plugin.drain_pending_clicks();+ }++ pub async fn request_permission(&self) -> crate::Result<PermissionState> {+ // Windows doesn't have a runtime permission prompt like mobile+ // We can only check the current state+ self.permission_state().await+ }++ #[allow(unknown_lints, clippy::unused_async, clippy::unused_async_trait_impl)]+ pub async fn register_for_push_notifications(&self) -> crate::Result<String> {+ self.plugin.open_push_channel()+ }++ pub fn unregister_for_push_notifications(&self) -> crate::Result<()> {+ self.plugin.close_push_channel()+ }++ #[allow(unknown_lints, clippy::unused_async, clippy::unused_async_trait_impl)]+ pub async fn permission_state(&self) -> crate::Result<PermissionState> {+ match self.plugin.notifier.Setting()? {+ NotificationSetting::Enabled => Ok(PermissionState::Granted),+ NotificationSetting::DisabledForApplication+ | NotificationSetting::DisabledForUser+ | NotificationSetting::DisabledByGroupPolicy+ | NotificationSetting::DisabledByManifest => Ok(PermissionState::Denied),+ _ => Ok(PermissionState::Prompt),+ }+ }++ pub fn register_action_types(&self, types: Vec<ActionType>) -> crate::Result<()> {+ // Scoped so the write guard is released at the end of the inserts+ // rather than being held until the function returns.+ {+ let mut action_types = self.plugin.action_types_mut()?;+ for action_type in types {+ action_types.insert(action_type.id().to_string(), action_type);+ }+ }+ Ok(())+ }++ pub fn remove_active(&self, notifications: Vec<i32>) -> crate::Result<()> {+ let history = ToastNotificationManager::History()?;+ let app_id = &self.plugin.app_id;+ for id in notifications {+ let tag = HSTRING::from(id.to_string());+ // Use app-scoped removal with empty group (consistent with GetHistoryWithId usage)+ let res = if self.plugin.packaged {+ history.RemoveGroupedTag(&tag, &HSTRING::new())+ } else {+ history.RemoveGroupedTagWithId(&tag, &HSTRING::new(), &HSTRING::from(app_id))+ };+ if let Err(e) = res {+ log::error!("Failed to remove notification {id}: {e}");+ }+ }+ Ok(())+ }++ #[allow(unknown_lints, clippy::unused_async, clippy::unused_async_trait_impl)]+ pub async fn active(&self) -> crate::Result<Vec<ActiveNotification>> {+ let history = ToastNotificationManager::History()?;+ let notifications = if self.plugin.packaged {+ history.GetHistory()?+ } else {+ history.GetHistoryWithId(&HSTRING::from(&self.plugin.app_id))?+ };++ let mut result = Vec::new();+ for i in 0..notifications.Size()? {+ let notification = notifications.GetAt(i)?;+ let tag = notification.Tag()?.to_string_lossy();+ let id = tag.parse::<i32>().unwrap_or(0);+ let group = notification.Group().ok().map(|s| s.to_string_lossy());++ // Extract title/body from XML content+ let (title, body) = if let Ok(content) = notification.Content() {+ let text_elements = content.GetElementsByTagName(&HSTRING::from("text"))?;+ let title = text_elements+ .GetAt(0)+ .ok()+ .and_then(|el| el.InnerText().ok())+ .map(|s| s.to_string_lossy());+ let body = text_elements+ .GetAt(1)+ .ok()+ .and_then(|el| el.InnerText().ok())+ .map(|s| s.to_string_lossy());+ (title, body)+ } else {+ (None, None)+ };++ result.push(ActiveNotification {+ id,+ tag: Some(tag),+ title,+ body,+ group,+ group_summary: false,+ data: HashMap::new(),+ extra: HashMap::new(),+ attachments: Vec::new(),+ action_type_id: None,+ schedule: None,+ sound: None,+ });+ }++ Ok(result)+ }++ pub fn remove_all_active(&self) -> crate::Result<()> {+ let history = ToastNotificationManager::History()?;+ if self.plugin.packaged {+ history.Clear()?;+ } else {+ history.ClearWithId(&HSTRING::from(&self.plugin.app_id))?;+ }+ Ok(())+ }++ #[allow(unknown_lints, clippy::unused_async, clippy::unused_async_trait_impl)]+ pub async fn pending(&self) -> crate::Result<Vec<PendingNotification>> {+ let scheduled = self.plugin.notifier.GetScheduledToastNotifications()?;+ let mut result = Vec::new();++ for i in 0..scheduled.Size()? {+ let notification = scheduled.GetAt(i)?;+ let tag = notification.Tag()?.to_string_lossy();+ let id = tag.parse::<i32>().unwrap_or(0);++ let (title, body) = if let Ok(content) = notification.Content() {+ let text_elements = content.GetElementsByTagName(&HSTRING::from("text"))?;+ let title = text_elements+ .GetAt(0)+ .ok()+ .and_then(|el| el.InnerText().ok())+ .map(|s| s.to_string_lossy());+ let body = text_elements+ .GetAt(1)+ .ok()+ .and_then(|el| el.InnerText().ok())+ .map(|s| s.to_string_lossy());+ (title, body)+ } else {+ (None, None)+ };++ // Convert Windows `DateTime` back to Schedule::At+ let schedule = notification.DeliveryTime().ok().and_then(|dt| {+ windows_datetime_to_unix(dt).ok().map(|date| Schedule::At {+ date,+ repeating: false,+ allow_while_idle: false,+ })+ });++ // PendingNotification requires schedule (not Option), skip if we can't extract it+ if let Some(schedule) = schedule {+ result.push(PendingNotification {+ id,+ title,+ body,+ schedule,+ });+ }+ }++ Ok(result)+ }++ pub fn cancel(&self, notifications: Vec<i32>) -> crate::Result<()> {+ let scheduled = self.plugin.notifier.GetScheduledToastNotifications()?;+ let ids_to_cancel: std::collections::HashSet<_> = notifications.into_iter().collect();++ for i in 0..scheduled.Size()? {+ let Ok(notification) = scheduled.GetAt(i) else {+ continue;+ };+ let Ok(tag) = notification.Tag() else {+ continue;+ };+ let Ok(id) = tag.to_string_lossy().parse::<i32>() else {+ continue;+ };+ if !ids_to_cancel.contains(&id) {+ continue;+ }+ if let Err(e) = self.plugin.notifier.RemoveFromSchedule(¬ification) {+ log::error!("Failed to cancel notification {id}: {e}");+ }+ }+ Ok(())+ }++ pub fn cancel_all(&self) -> crate::Result<()> {+ let scheduled = self.plugin.notifier.GetScheduledToastNotifications()?;+ for i in 0..scheduled.Size()? {+ let Ok(notification) = scheduled.GetAt(i) else {+ continue;+ };+ if let Err(e) = self.plugin.notifier.RemoveFromSchedule(¬ification) {+ log::error!("Failed to cancel scheduled notification: {e}");+ }+ }+ Ok(())+ }++ pub fn set_click_listener_active(&self, active: bool) -> crate::Result<()> {+ self.plugin.set_click_listener(active)+ }++ /// Create a notification channel (not supported on Windows).+ pub fn create_channel(&self, _channel: crate::Channel) -> crate::Result<()> {+ Err(crate::Error::Io(std::io::Error::other(+ "Notification channels are not supported on Windows",+ )))+ }++ /// Delete a notification channel (not supported on Windows).+ pub fn delete_channel(&self, _id: impl Into<String>) -> crate::Result<()> {+ Err(crate::Error::Io(std::io::Error::other(+ "Notification channels are not supported on Windows",+ )))+ }++ /// List notification channels (not supported on Windows).+ pub fn list_channels(&self) -> crate::Result<Vec<crate::Channel>> {+ Err(crate::Error::Io(std::io::Error::other(+ "Notification channels are not supported on Windows",+ )))+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ // Only referenced by tests, so they'd be unused imports at module scope.+ use crate::models::{Action, ScheduleInterval};++ /// PowerShell App User Model ID - always available on Windows.+ const POWERSHELL_APP_ID: &str =+ "{1AC14E77-02E7-4E5D-B744-2EB1AE5198B7}\\WindowsPowerShell\\v1.0\\powershell.exe";++ // ==================== Time Conversion Tests ====================++ /// Windows FILETIME epoch (1601-01-01) offset from Unix epoch (1970-01-01),+ /// in 100-nanosecond ticks. Used only as a test reference value.+ const WINDOWS_EPOCH_OFFSET_TICKS: i128 = 116_444_736_000_000_000;++ #[test]+ fn test_unix_to_windows_datetime_epoch() {+ let result = unix_to_windows_datetime(time::OffsetDateTime::UNIX_EPOCH)+ .expect("Failed to convert Unix epoch");+ assert_eq!(i128::from(result.UniversalTime), WINDOWS_EPOCH_OFFSET_TICKS);+ }++ #[test]+ fn test_unix_to_windows_datetime_known_date() {+ let date = time::macros::datetime!(2000-01-01 00:00:00 UTC);+ let result = unix_to_windows_datetime(date).expect("Failed to convert known date");++ let unix_nanos = 946_684_800i128 * 1_000_000_000;+ let expected = (unix_nanos / 100) + WINDOWS_EPOCH_OFFSET_TICKS;+ assert_eq!(i128::from(result.UniversalTime), expected);+ }++ #[test]+ fn test_windows_datetime_roundtrip() {+ let original = time::macros::datetime!(2024-06-15 14:30:45 UTC);+ let windows_dt =+ unix_to_windows_datetime(original).expect("Failed to convert to Windows datetime");+ let roundtrip =+ windows_datetime_to_unix(windows_dt).expect("Failed to convert back to Unix");++ let diff = (original - roundtrip).whole_nanoseconds().abs();+ assert!(diff < 100, "Roundtrip diff: {diff}ns");+ }++ #[test]+ fn test_schedule_at_conversion() {+ let target = time::macros::datetime!(2025-12-25 10:00:00 UTC);+ let schedule = Schedule::At {+ date: target,+ repeating: false,+ allow_while_idle: false,+ };++ let result = schedule_to_datetime(&schedule).expect("Failed to convert schedule");+ let back = windows_datetime_to_unix(result).expect("Failed to convert back");+ assert!((target - back).whole_nanoseconds().abs() < 100);+ }++ #[test]+ fn test_schedule_interval() {+ let schedule = Schedule::Interval {+ interval: ScheduleInterval {+ year: None,+ month: None,+ day: Some(1),+ weekday: None,+ hour: Some(2),+ minute: Some(30),+ second: Some(45),+ },+ allow_while_idle: false,+ };++ let before = time::OffsetDateTime::now_utc();+ let result = schedule_to_datetime(&schedule).expect("Failed to convert interval schedule");+ let converted = windows_datetime_to_unix(result).expect("Failed to convert back");++ let expected = 86400 + 7200 + 1800 + 45; // 1d + 2h + 30m + 45s+ let actual = (converted - before).whole_seconds();+ assert!((actual - expected).abs() <= 2);+ }++ #[test]+ fn test_schedule_every_variants() {+ let cases = [+ (ScheduleEvery::Second, 1, 1i64),+ (ScheduleEvery::Minute, 1, 60),+ (ScheduleEvery::Hour, 1, 3600),+ (ScheduleEvery::Day, 1, 86400),+ (ScheduleEvery::Week, 1, 7 * 86400),+ (ScheduleEvery::TwoWeeks, 1, 14 * 86400),+ (ScheduleEvery::Month, 1, 30 * 86400),+ (ScheduleEvery::Year, 1, 365 * 86400),+ ];++ for (interval, count, expected) in cases {+ let schedule = Schedule::Every {+ interval,+ count,+ allow_while_idle: false,+ };++ let before = time::OffsetDateTime::now_utc();+ let result = schedule_to_datetime(&schedule)+ .unwrap_or_else(|e| panic!("Failed to convert {interval:?}: {e}"));+ let converted = windows_datetime_to_unix(result)+ .unwrap_or_else(|e| panic!("Failed to convert back {interval:?}: {e}"));+ let actual = (converted - before).whole_seconds();+ assert!(+ (actual - expected).abs() <= 2,+ "{interval:?}: {actual} vs {expected}"+ );+ }+ }++ // ==================== Toast Notifier Tests ====================++ #[test]+ fn test_toast_notifier_creation() {+ let result =+ ToastNotificationManager::CreateToastNotifierWithId(&HSTRING::from(POWERSHELL_APP_ID));+ assert!(result.is_ok(), "Failed: {:?}", result.err());+ }++ // ==================== XML Building Tests ====================++ #[test]+ fn test_xml_document_creation() {+ assert!(XmlDocument::new().is_ok());+ }++ #[test]+ fn test_toast_xml_structure() {+ let doc = XmlDocument::new().expect("Failed to create XmlDocument");++ let toast = doc+ .CreateElement(&HSTRING::from("toast"))+ .expect("Failed to create toast element");+ doc.AppendChild(&toast).expect("Failed to append toast");++ let visual = doc+ .CreateElement(&HSTRING::from("visual"))+ .expect("Failed to create visual element");+ let binding = doc+ .CreateElement(&HSTRING::from("binding"))+ .expect("Failed to create binding element");+ binding+ .SetAttribute(&HSTRING::from("template"), &HSTRING::from("ToastGeneric"))+ .expect("Failed to set template attribute");++ let text = doc+ .CreateElement(&HSTRING::from("text"))+ .expect("Failed to create text element");+ text.SetInnerText(&HSTRING::from("Test Title"))+ .expect("Failed to set text content");+ binding+ .AppendChild(&text)+ .expect("Failed to append text to binding");+ visual+ .AppendChild(&binding)+ .expect("Failed to append binding to visual");+ toast+ .AppendChild(&visual)+ .expect("Failed to append visual to toast");++ let xml = doc.GetXml().expect("Failed to get XML").to_string_lossy();+ assert!(+ xml.contains("toast") && xml.contains("ToastGeneric") && xml.contains("Test Title")+ );+ }++ #[test]+ fn test_toast_xml_with_actions() {+ let doc = XmlDocument::new().expect("Failed to create XmlDocument");+ let toast = doc+ .CreateElement(&HSTRING::from("toast"))+ .expect("Failed to create toast element");+ doc.AppendChild(&toast).expect("Failed to append toast");++ let actions = doc+ .CreateElement(&HSTRING::from("actions"))+ .expect("Failed to create actions element");+ let action = doc+ .CreateElement(&HSTRING::from("action"))+ .expect("Failed to create action element");+ action+ .SetAttribute(&HSTRING::from("content"), &HSTRING::from("Accept"))+ .expect("Failed to set content attribute");+ action+ .SetAttribute(&HSTRING::from("arguments"), &HSTRING::from("accept"))+ .expect("Failed to set arguments attribute");+ actions+ .AppendChild(&action)+ .expect("Failed to append action");+ toast+ .AppendChild(&actions)+ .expect("Failed to append actions");++ let xml = doc.GetXml().expect("Failed to get XML").to_string_lossy();+ assert!(xml.contains("actions") && xml.contains("Accept"));+ }++ // ==================== Vendored Patch Tests ====================++ /// The text box, the button that submits it, and the JSON `arguments=` the+ /// button carries — the three pieces upstream never emitted.+ #[test]+ fn test_toast_xml_with_input() {+ let action: Action = serde_json::from_value(serde_json::json!({+ "id": "reply",+ "title": "回复",+ "foreground": true,+ "input": true,+ "inputButtonTitle": "回复",+ "inputPlaceholder": "输入回复内容",+ }))+ .expect("input action must deserialize from the camelCase wire shape");++ assert!(action.input());+ assert_eq!(action.input_button_title(), Some("回复"));+ assert_eq!(action.input_placeholder(), Some("输入回复内容"));+ assert_eq!(input_element_id(action.id()), "input-reply");++ let arguments = action_arguments(+ action.id(),+ &HashMap::from([(+ "sessionId".to_string(),+ serde_json::Value::String("s-1".to_string()),+ )]),+ );+ let parsed: serde_json::Value =+ serde_json::from_str(&arguments).expect("arguments must be JSON");+ assert_eq!(parsed["actionId"], "reply");+ assert_eq!(parsed["data"]["sessionId"], "s-1");++ let doc = XmlDocument::new().expect("Failed to create XmlDocument");+ let toast = doc+ .CreateElement(&HSTRING::from("toast"))+ .expect("Failed to create toast element");+ doc.AppendChild(&toast).expect("Failed to append toast");+ let actions = doc+ .CreateElement(&HSTRING::from("actions"))+ .expect("Failed to create actions element");++ let input = doc+ .CreateElement(&HSTRING::from("input"))+ .expect("Failed to create input element");+ input+ .SetAttribute(+ &HSTRING::from("id"),+ &HSTRING::from(input_element_id(action.id()).as_str()),+ )+ .expect("Failed to set id attribute");+ input+ .SetAttribute(&HSTRING::from("type"), &HSTRING::from("text"))+ .expect("Failed to set type attribute");+ input+ .SetAttribute(+ &HSTRING::from("placeHolderContent"),+ &HSTRING::from(action.input_placeholder().unwrap_or_default()),+ )+ .expect("Failed to set placeHolderContent attribute");+ actions.AppendChild(&input).expect("Failed to append input");++ let action_el = doc+ .CreateElement(&HSTRING::from("action"))+ .expect("Failed to create action element");+ action_el+ .SetAttribute(+ &HSTRING::from("content"),+ &HSTRING::from(action.input_button_title().unwrap_or(action.title())),+ )+ .expect("Failed to set content attribute");+ action_el+ .SetAttribute(+ &HSTRING::from("arguments"),+ &HSTRING::from(arguments.as_str()),+ )+ .expect("Failed to set arguments attribute");+ action_el+ .SetAttribute(+ &HSTRING::from("hint-inputId"),+ &HSTRING::from(input_element_id(action.id()).as_str()),+ )+ .expect("Failed to set hint-inputId attribute");+ actions+ .AppendChild(&action_el)+ .expect("Failed to append action");+ toast+ .AppendChild(&actions)+ .expect("Failed to append actions");++ let xml = doc.GetXml().expect("Failed to get XML").to_string_lossy();+ assert!(xml.contains("placeHolderContent"), "xml: {xml}");+ assert!(xml.contains("hint-inputId"), "xml: {xml}");+ assert!(xml.contains("input-reply"), "xml: {xml}");+ // Attribute values are XML-escaped, so the JSON's own quotes arrive as+ // `"` — match on the bare key instead.+ assert!(xml.contains("actionId"), "xml: {xml}");+ assert!(xml.contains("sessionId"), "xml: {xml}");+ }++ #[test]+ fn test_toast_xml_silent() {+ let doc = XmlDocument::new().expect("Failed to create XmlDocument");+ let toast = doc+ .CreateElement(&HSTRING::from("toast"))+ .expect("Failed to create toast element");+ doc.AppendChild(&toast).expect("Failed to append toast");++ let audio = doc+ .CreateElement(&HSTRING::from("audio"))+ .expect("Failed to create audio element");+ audio+ .SetAttribute(&HSTRING::from("silent"), &HSTRING::from("true"))+ .expect("Failed to set silent attribute");+ toast.AppendChild(&audio).expect("Failed to append audio");++ assert!(+ doc.GetXml()+ .expect("Failed to get XML")+ .to_string_lossy()+ .contains("silent")+ );+ }++ // ==================== Action Types Tests ====================++ #[test]+ fn test_action_types_storage() {+ let types: RwLock<HashMap<String, ActionType>> = RwLock::new(HashMap::new());+ let action_type = ActionType::new("test", vec![Action::new("btn", "Button", false)]);++ types+ .write()+ .expect("RwLock poisoned")+ .insert("test".to_string(), action_type);++ let read = types.read().expect("RwLock poisoned");+ assert!(read.contains_key("test"));+ assert_eq!(read.get("test").expect("Key not found").actions().len(), 1);+ drop(read);+ }++ #[test]+ fn test_multiple_action_types() {+ let types: RwLock<HashMap<String, ActionType>> = RwLock::new(HashMap::new());++ {+ let mut w = types.write().expect("RwLock poisoned");+ w.insert(+ "confirm".to_string(),+ ActionType::new(+ "confirm",+ vec![+ Action::new("yes", "Yes", true),+ Action::new("no", "No", false),+ ],+ ),+ );+ w.insert(+ "reply".to_string(),+ ActionType::new("reply", vec![Action::new("reply", "Reply", true)]),+ );+ }++ let r = types.read().expect("RwLock poisoned");+ assert_eq!(r.len(), 2);+ assert!(r.contains_key("confirm") && r.contains_key("reply"));+ drop(r);+ }+}diff --git a/src-tauri/vendor/tauri-plugin-notifications/tests/xdg_lifecycle.rs b/src-tauri/vendor/tauri-plugin-notifications/tests/xdg_lifecycle.rsnew file mode 100644index 00000000..42f4e4a1--- /dev/null+++ b/src-tauri/vendor/tauri-plugin-notifications/tests/xdg_lifecycle.rs@@ -0,0 +1,224 @@+#![cfg(any(target_os = "linux", target_os = "freebsd"))]++use std::{+ collections::HashMap,+ sync::atomic::{AtomicU32, Ordering},+ time::Duration,+};+use tauri_plugin_notifications::NotificationsExt;+use tokio::sync::mpsc::{UnboundedReceiver, UnboundedSender, unbounded_channel};++#[derive(Debug, PartialEq)]+enum Delivery {+ Shown {+ id: u32,+ title: String,+ body: String,+ },+ Closed(u32),+}++struct NotificationService {+ next_id: AtomicU32,+ deliveries: UnboundedSender<Delivery>,+}++#[zbus::interface(name = "org.freedesktop.Notifications")]+impl NotificationService {+ // zbus requires a receiver even when the D-Bus method returns constant metadata.+ #[allow(clippy::unused_self)]+ fn get_capabilities(&self) -> Vec<String> {+ vec!["body".into()]+ }++ #[allow(clippy::unused_self)]+ fn get_server_information(&self) -> (String, String, String, String) {+ ("test".into(), "test".into(), "1".into(), "1.2".into())+ }++ #[allow(clippy::too_many_arguments)]+ fn notify(+ &self,+ app_name: &str,+ replaces_id: u32,+ app_icon: &str,+ summary: &str,+ body: &str,+ actions: Vec<String>,+ hints: HashMap<String, zbus::zvariant::OwnedValue>,+ expire_timeout: i32,+ ) -> u32 {+ let _ = (+ app_name,+ replaces_id,+ app_icon,+ actions,+ hints,+ expire_timeout,+ );+ let id = self.next_id.fetch_add(1, Ordering::Relaxed);+ self.deliveries+ .send(Delivery::Shown {+ id,+ title: summary.into(),+ body: body.into(),+ })+ .expect("notification receipt receiver disconnected");+ id+ }++ fn close_notification(&self, id: u32) {+ self.deliveries+ .send(Delivery::Closed(id))+ .expect("close receipt receiver disconnected");+ }+}++async fn start_notification_service(deliveries: UnboundedSender<Delivery>) -> zbus::Connection {+ let service = zbus::connection::Builder::session()+ .expect("connect to the isolated D-Bus session")+ .serve_at(+ "/org/freedesktop/Notifications",+ NotificationService {+ next_id: AtomicU32::new(1),+ deliveries,+ },+ )+ .expect("register the notification interface")+ .build()+ .await+ .expect("build the notification daemon connection");+ let bus = zbus::fdo::DBusProxy::new(&service)+ .await+ .expect("create the session bus proxy");+ let name = "org.freedesktop.Notifications"+ .try_into()+ .expect("valid notification bus name");+ assert!(+ !bus.name_has_owner(name)+ .await+ .expect("inspect the notification bus name"),+ "use an isolated session bus"+ );+ service+ .request_name("org.freedesktop.Notifications")+ .await+ .expect("own the notification bus name");+ service+}++async fn next_delivery(deliveries: &mut UnboundedReceiver<Delivery>) -> Delivery {+ tokio::time::timeout(Duration::from_secs(5), deliveries.recv())+ .await+ .expect("notification daemon did not receive the operation")+ .expect("notification daemon disconnected")+}++// Run with `dbus-run-session -- cargo test --test xdg_lifecycle -- --ignored`.+// This exercises the real plugin and D-Bus transport, without requiring a GUI.+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]+#[ignore = "requires an isolated D-Bus session without a notification daemon"]+async fn shows_tracks_and_closes_notifications() {+ assert!(std::env::var_os("DBUS_SESSION_BUS_ADDRESS").is_some());+ tokio::time::timeout(Duration::from_secs(30), async {+ let (sender, mut deliveries) = unbounded_channel();+ let _service = start_notification_service(sender).await;++ let app = tauri::test::mock_builder()+ .plugin(tauri_plugin_notifications::init())+ .build(tauri::test::mock_context(tauri::test::noop_assets()))+ .expect("build the notification test app");+ let notifications = app.notifications();++ for (id, title) in [(1, "first"), (2, "second")] {+ notifications+ .builder()+ .id(7)+ .title(title)+ .body("body")+ .show()+ .await+ .expect("show a notification with a shared caller ID");+ assert_eq!(+ next_delivery(&mut deliveries).await,+ Delivery::Shown {+ id,+ title: title.into(),+ body: "body".into(),+ }+ );+ }+ let active = notifications+ .active()+ .await+ .expect("read active notifications");+ let active = serde_json::to_value(active).expect("serialize active notifications");+ let active = active+ .as_array()+ .expect("active notifications are an array");+ assert_eq!(+ active.len(),+ 2,+ "equal caller IDs must retain both notification handles"+ );+ assert!(active.iter().all(|notification| notification["id"] == 7));+ notifications+ .cancel(vec![7])+ .expect("cancel the shared caller ID");+ assert!(+ notifications+ .active()+ .await+ .expect("read notifications after cancel")+ .is_empty()+ );+ let mut closed = Vec::new();+ for _ in 0..2 {+ match next_delivery(&mut deliveries).await {+ Delivery::Closed(id) => closed.push(id),+ other @ Delivery::Shown { .. } => {+ panic!("expected a daemon close receipt, got {other:?}")+ }+ }+ }+ closed.sort_unstable();+ assert_eq!(closed, [1, 2]);++ for (id, caller_id) in [(3, 8), (4, 9)] {+ notifications+ .builder()+ .id(caller_id)+ .title("close")+ .show()+ .await+ .expect("show a notification for removal");+ assert_eq!(+ next_delivery(&mut deliveries).await,+ Delivery::Shown {+ id,+ title: "close".into(),+ body: String::new(),+ }+ );+ if caller_id == 8 {+ notifications+ .remove_active(vec![caller_id])+ .expect("remove the active notification");+ } else {+ notifications+ .cancel_all()+ .expect("cancel all notifications");+ }+ assert_eq!(next_delivery(&mut deliveries).await, Delivery::Closed(id));+ assert!(+ notifications+ .active()+ .await+ .expect("read notifications after removal")+ .is_empty()+ );+ }+ })+ .await+ .expect("notification lifecycle timed out");+}diff --git a/src/hooks/use-notification-action.ts b/src/hooks/use-notification-action.tsnew file mode 100644index 00000000..220aa38d--- /dev/null+++ b/src/hooks/use-notification-action.ts@@ -0,0 +1,61 @@+import type { PluginListener } from '@tauri-apps/api/core'+import { onAction } from '@choochmeque/tauri-plugin-notifications-api'+import { useEffect, useRef } from 'react'++/** 发送通知时写进 `extra` 的会话标识:点击 / 按钮事件原样带回,用于定位到会话。 */+export interface NotificationExtra {+ sessionId?: string+ title?: string+ tag?: string+}++/**+ * `onAction` 的事件体:`actionId` 为 `'tap'` 表示点了通知本体,否则是按钮的 action id。+ * 带输入框的按钮另外把用户输入放在 `inputValue`(vender 补丁让按钮的 arguments 携带+ * JSON,冷启动也能带回 `extra`)。+ *+ * `extra` 才是定位会话的唯一可靠来源:`notification` 只是应用内(热)激活时的通知快照,+ * 进程外 COM 激活(点通知栏里的历史通知)拿到的事件里它是 `null`。+ */+export interface NotificationActionEvent {+ actionId?: string+ /** 带输入框的按钮:用户在系统通知文本框里填的内容。 */+ inputValue?: string | null+ /** 会话标识:与发送时写进通知 `extra` 的内容一致,两条激活通路都会带回。 */+ extra?: NotificationExtra | null+ notification?: { extra?: NotificationExtra } | null+}++/**+ * 订阅系统通知的按钮动作(`onAction`),卸载时自动注销。+ *+ * 语义对齐 `useListen`:+ * - 回调在渲染期写入 ref(同款「latest ref」),调用方传内联函数不会反复重订阅;+ * - 竞态防护:订阅是异步的,若在 resolve 前组件已卸载则立即注销,避免监听泄漏;+ * - 订阅失败(非 Tauri 环境等)只记录日志,不打断调用方。+ */+export function useNotificationAction(handler: (event: NotificationActionEvent) => void): void {+ const handlerRef = useRef(handler)+ handlerRef.current = handler++ useEffect(() => {+ let listener: PluginListener | undefined+ let disposed = false++ void onAction((payload) => {+ handlerRef.current((payload as unknown as NotificationActionEvent | null) ?? {})+ })+ .then((unlisten) => {+ if (disposed)+ void unlisten.unregister()+ else+ listener = unlisten+ })+ .catch(error => console.error('[useNotificationAction] failed to subscribe:', error))++ return () => {+ disposed = true+ void listener?.unregister()+ }+ }, [])+}diff --git a/src/hooks/use-notification-clicked.ts b/src/hooks/use-notification-clicked.tsnew file mode 100644index 00000000..e4823108--- /dev/null+++ b/src/hooks/use-notification-clicked.ts@@ -0,0 +1,46 @@+import type { PluginListener } from '@tauri-apps/api/core'+import type { NotificationExtra } from './use-notification-action'+import { onNotificationClicked } from '@choochmeque/tauri-plugin-notifications-api'+import { useEffect, useRef } from 'react'++/** `onNotificationClicked` 的事件体:`data` 就是发送时写进 `extra` 的对象。 */+export interface NotificationClickEvent {+ id?: number+ data?: NotificationExtra+}++/**+ * 订阅「点击通知本体」(`onNotificationClicked`),卸载时自动注销。+ *+ * 这个订阅同时是 Windows 端按钮可用的前提:插件只在有订阅者时才调用+ * `set_click_listener_active(true)`,而 Windows 后端只在那之后才给 toast 挂上+ * `Activated` 回调——只订阅 `useNotificationAction` 会收不到任何通知事件。+ *+ * 语义对齐 `useListen`:回调写入 ref(内联函数不会反复重订阅);订阅是异步的,+ * 若在 resolve 前组件已卸载则立即注销;失败只记录日志,不打断调用方。+ */+export function useNotificationClicked(handler: (event: NotificationClickEvent) => void): void {+ const handlerRef = useRef(handler)+ handlerRef.current = handler++ useEffect(() => {+ let listener: PluginListener | undefined+ let disposed = false++ void onNotificationClicked((data) => {+ handlerRef.current((data as unknown as NotificationClickEvent | null) ?? {})+ })+ .then((unlisten) => {+ if (disposed)+ void unlisten.unregister()+ else+ listener = unlisten+ })+ .catch(error => console.error('[useNotificationClicked] failed to subscribe:', error))++ return () => {+ disposed = true+ void listener?.unregister()+ }+ }, [])+}diff --git a/src/hooks/use-sync-visibility.ts b/src/hooks/use-sync-visibility.tsindex 2e943cc0..a96a9d9e 100644--- a/src/hooks/use-sync-visibility.ts+++ b/src/hooks/use-sync-visibility.ts@@ -14,11 +14,14 @@ export function useSyncVisibility(iframeRef: React.RefObject<HTMLIFrameElement |void (async () => {try {const appWindow = getCurrentWindow()- const [minimized, visible] = await Promise.all([+ const [minimized, visible, focused] = await Promise.all([appWindow.isMinimized(),appWindow.isVisible(),+ appWindow.isFocused(),])- post({ type: 'dsh://visibility-state', hidden: minimized || !visible })+ // 未聚焦也必须算后台:窗口还开着但用户切去别的应用时,只看 visible+ // 会把「仅未聚焦时通知」直接判成前台,会话就再也收不到完成提醒。+ post({ type: 'dsh://visibility-state', hidden: minimized || !visible || !focused })}catch (error) {console.error('[notification] sync visibility failed:', error)diff --git a/src/layout/components/iframe.tsx b/src/layout/components/iframe.tsxindex 67ddb069..6749dd08 100644--- a/src/layout/components/iframe.tsx+++ b/src/layout/components/iframe.tsx@@ -1,9 +1,16 @@/* eslint-disable react/dom-no-unsafe-iframe-sandbox */import type { CSSProperties, RefObject } from 'react'+import type { NotificationActionEvent } from '@/hooks/use-notification-action'+import type { NotificationClickEvent } from '@/hooks/use-notification-clicked'+import {+ registerActionTypes,+ sendNotification,+} from '@choochmeque/tauri-plugin-notifications-api'import { CircleExclamation } from '@gravity-ui/icons'import { useEventListener } from '@reause/core'import { invoke } from '@tauri-apps/api/core'-import { useState } from 'react'+import { getCurrentWindow } from '@tauri-apps/api/window'+import { useRef, useState } from 'react'import { useTranslation } from 'react-i18next'import { If } from 'react-if-lite'import { useStore } from 'valtio-define'@@ -13,7 +20,8 @@ import { useDshStyle } from '@/hooks/use-dsh-style'import { useIframeMessage } from '@/hooks/use-iframe-message'import { useIframePost } from '@/hooks/use-iframe-post'import { useInvokeIframe } from '@/hooks/use-invoke-iframe'-import { useListen } from '@/hooks/use-listen'+import { useNotificationAction } from '@/hooks/use-notification-action'+import { useNotificationClicked } from '@/hooks/use-notification-clicked'import { useSyncVisibility } from '@/hooks/use-sync-visibility'import { useZoomFactor } from '@/hooks/use-zoom-factor'import { store } from '@/store'@@ -34,6 +42,10 @@ interface IframeBridgeMessage {tag?: stringsessionId?: string | nullrequireInteraction?: boolean+ /** 通知桥:置 true 让原生通知自己静音(提示音由帧内 `sound.play()` 播放,避免双声)。 */+ silent?: boolean+ /** 通知桥:插件声明的系统通知按钮(`{ action, title, … }`;`input` 系列字段透传给 Windows toast 的输入框) */+ actions?: { action: string, title: string, input?: boolean, inputPlaceholder?: string, inputButtonTitle?: string }[]/** 插件异常桥 / 剪贴板图片桥:插件 id 或剪贴板请求 id */id?: stringerror?: string@@ -65,6 +77,105 @@ export interface NotificationClickedPayload {sessionId?: string | nulltitle?: stringtag?: string+ /** 命中的系统通知按钮 action id;点通知本体时为空。 */+ action?: string | null+ /** 带输入框的按钮:用户在系统通知里填的文本。 */+ inputValue?: string | null+}++/** 插件的动作类型载荷(它的 `ActionType` 没有从 JS API 导出,这里从函数签名反推)。 */+type ActionTypeRegistration = Parameters<typeof registerActionTypes>[0][number]++/** 已注册过的按钮集合,按 action type id 索引。 */+const registeredActionTypes = new Map<string, ActionTypeRegistration>()++/** 注册表上限:实际只有「批准 / 拒绝」与「回复」两组,这里只是防止异常输入把表撑大。 */+const ACTION_TYPE_LIMIT = 16++/**+ * 合并同一次按钮点击的重复投递的窗口(毫秒)。+ *+ * 一次点击会同时走「应用内 `Activated` 事件」与「进程外 COM 激活回调」两条通路,两条都+ * 带着同一份 `arguments`,但用户输入文本往往只有其中一条有;两条到达间隔在 1ms 量级,+ * 250ms 足够把它们并成一次投递(见 `handleNotificationAction`)。+ */+const ACTION_COALESCE_MS = 250++/**+ * 一组按钮对应一个 action type id,由动作 id 拼出来;同一组按钮永远映射到同一个 id。+ *+ * 插件的 `registerActionTypes` 是「按 id 覆盖」的(Windows 存一张 id → 动作表,macOS 的+ * `setNotificationCategories` 更是整表替换)。复用同一个 id 会让后注册的集合顶掉先注册的:+ * 两个会话同时挂起时,授权通知的按钮会变成提问通知的「回复」。+ */+function actionTypeIdFor(actions: readonly { action: string }[]): string {+ return `dsh-notification-${actions.map(action => action.action).join('-')}`+}++/**+ * 把当前按钮集合并入注册表,并返回**全部**已注册集合。+ *+ * macOS 侧 `setNotificationCategories` 整表替换,只注册当前集合会把已经发出去的通知上的+ * 按钮抹掉;所以每次都把用过的集合一起注册回去。+ */+function actionTypesToRegister(current: ActionTypeRegistration): ActionTypeRegistration[] {+ registeredActionTypes.delete(current.id)+ registeredActionTypes.set(current.id, current)+ while (registeredActionTypes.size > ACTION_TYPE_LIMIT) {+ const oldest = registeredActionTypes.keys().next().value+ if (oldest === undefined)+ break+ registeredActionTypes.delete(oldest)+ }+ return [...registeredActionTypes.values()]+}++/**+ * 通知 id 必须是 32 位整数,这里取 tag 的稳定哈希:同一会话的同一条通知反复发送时+ * 复用同一个 id(就地更新),而不是每次多堆一条。+ */+function notificationIdFor(tag: string | undefined): number {+ let hash = 0+ for (const char of tag ?? '')+ hash = (hash * 31 + char.charCodeAt(0)) | 0+ return (Math.abs(hash) % 0x7FFFFFFF) || 1+}++/** 内置提示音:壳层 `public/` 下的资源,名字与插件侧的 `BuiltinNotificationSound` 对齐。 */+const NOTIFICATION_SOUND_FILES: ReadonlyArray<readonly [string, string]> = [+ ['default', '/notification.wav'],+ ['classic', '/classic.wav'],+]++/** 已读到的内置提示音(data URL);插件在 iframe 里取不到壳层同源文件,只能这样送过去。 */+let notificationSoundAssets: Record<string, string> | undefined++function readBlobAsDataUrl(blob: Blob): Promise<string> {+ return new Promise((resolve, reject) => {+ const reader = new FileReader()+ reader.onload = () => {+ if (typeof reader.result === 'string')+ resolve(reader.result)+ else+ reject(new Error('FileReader returned a non-string result'))+ }+ reader.onerror = () => reject(reader.error ?? new Error('FileReader failed'))+ reader.readAsDataURL(blob)+ })+}++/** 读取内置提示音并转成 data URL(读一次缓存住,除非其中任何一个读取失败)。 */+async function loadNotificationSounds(): Promise<Record<string, string>> {+ if (notificationSoundAssets)+ return notificationSoundAssets+ const entries = await Promise.all(NOTIFICATION_SOUND_FILES.map(async ([name, url]) => {+ const response = await fetch(url)+ if (!response.ok)+ throw new Error(`${url}: HTTP ${response.status}`)+ return [name, await readBlobAsDataUrl(await response.blob())] as const+ }))+ notificationSoundAssets = Object.fromEntries(entries)+ return notificationSoundAssets}export function Iframe({ iframeRef, srcOverride = null, borderTint = null }: IframeProps) {@@ -81,6 +192,9 @@ export function Iframe({ iframeRef, srcOverride = null, borderTint = null }: Ifrconst post = useIframePost(iframeRef)+ /** 待合并的按钮动作,按「tag + actionId」索引(见 `handleNotificationAction`)。 */+ const pendingActionsRef = useRef(new Map<string, { payload: NotificationClickedPayload, timer: ReturnType<typeof setTimeout> }>())+const [, setDshStyle] = useDshStyle()// 转发 iframe 消息给 Tauri Rust 命令@@ -96,11 +210,11 @@ export function Iframe({ iframeRef, srcOverride = null, borderTint = null }: Ifr// 壳层快捷键(焦点在导航栏等壳层元素时;iframe 内由注入脚本经缩放桥转发)useEventListener('keydown', handleZoomKeyDown, { capture: true })- // 系统通知点击 → 让 iframe 聚焦对应会话- useListen<NotificationClickedPayload>(- 'dsh-notification-clicked',- event => handleNotificationClicked(event.payload),- )+ // 系统通知的点击 / 按钮动作 → 让 iframe 聚焦对应会话并回灌 onaction。+ // 订阅细节(含「必须先订阅 onNotificationClicked,Windows 才会派发点击 / 按钮事件」)+ // 收在 hooks 里,与 `useListen` 同一套 latest-ref + 卸载注销语义。+ useNotificationAction(handleNotificationAction)+ useNotificationClicked(handleNotificationClick)// iframe → 宿主:iframe 自身的桥共用一个监听器,按 `data.type` 分发useIframeMessage<IframeBridgeMessage>(iframeRef, (data) => {@@ -143,6 +257,10 @@ export function Iframe({ iframeRef, srcOverride = null, borderTint = null }: Ifrcase 'dsh://style':setDshStyle(data)break+ // 内置提示音:插件客户端在 iframe 里取不到壳层 `public/` 的同源文件,读成 data URL 送过去+ case 'dsh://notification-sounds:request':+ pushNotificationSounds()+ break// 帧内日志:iframe 跨源、帧内 console.* 没有宿主侧通路,由注入脚本转回来后// 直写 desktop.frontdesk.log,随「复制运行日志」的前台日志一并提供case 'dsh://frame-log':@@ -159,16 +277,72 @@ export function Iframe({ iframeRef, srcOverride = null, borderTint = null }: Ifrsetting.zoom(action)}+ /**+ * 把内置提示音(`public/*.wav`)读成 data URL 交给 iframe。+ *+ * 插件客户端跑在 iframe 里,与壳层 `public/` 不同源,直接 `new Audio('/notification.wav')`+ * 只会 404;帧内已有用户激活且 iframe 显式 `allow="autoplay"`,播放留在帧内最稳。+ * 读取失败只记日志:帧内会退回合成音,通知本身不受影响。+ */+ function pushNotificationSounds() {+ void loadNotificationSounds()+ .then(sounds => post({ type: 'dsh://notification-sounds', sounds }))+ .catch(error => console.error('[notification] failed to load notification sounds:', error))+ }+function handleNativeNotification(data: IframeBridgeMessage) {- void invoke('show_native_notification', {- payload: {- title: data.title ?? '',- body: data.body ?? '',- tag: data.tag ?? null,- sessionId: data.sessionId ?? null,- requireInteraction: Boolean(data.requireInteraction),- },- }).catch(error => console.error('[notification] show_native_notification failed:', error))+ const actions = Array.isArray(data.actions) ? data.actions : []+ const hasActions = actions.length > 0+ const title = data.title ?? ''+ const body = data.body ?? ''++ void (async () => {+ // 后端只在 `actionTypeId` 已注册时才往通知里写按钮,所以必须先注册再发送;+ // 每次都用插件给的本地化文案重新注册,按钮文案才能跟随界面语言。+ // 整组按钮一起注册(授权是「批准 / 拒绝」),带输入框的按钮把 input 系列字段一并透传,+ // Windows 靠它们生成 toast 里的文本框与提交按钮。+ const actionTypeId = hasActions ? actionTypeIdFor(actions) : undefined+ let actionsRegistered = false+ if (actionTypeId) {+ try {+ await registerActionTypes(actionTypesToRegister({+ id: actionTypeId,+ actions: actions.map(action => ({+ id: action.action,+ title: action.title,+ foreground: true,+ input: action.input === true,+ inputPlaceholder: action.inputPlaceholder,+ inputButtonTitle: action.inputButtonTitle,+ })),+ }))+ actionsRegistered = true+ }+ catch (error) {+ // 注册失败不能连通知一起丢掉:Linux/FreeBSD 的 notify-rust 明确不支持动作,抛错时+ // 退化成没有按钮的通知,用户至少还能点回对应会话。+ console.warn('[notification] registerActionTypes failed, sending without actions:', error)+ }+ }+ try {+ await sendNotification({+ id: notificationIdFor(data.tag),+ title,+ body,+ // 帧内已经按设置播过提示音,这里让 toast 自己静音:Windows 上不静音就会额外响一次默认音。+ silent: data.silent === true ? true : undefined,+ actionTypeId: actionsRegistered ? actionTypeId : undefined,+ extra: {+ sessionId: data.sessionId ?? '',+ title,+ tag: data.tag ?? '',+ },+ })+ }+ catch (error) {+ console.error('[notification] sendNotification failed:', error)+ }+ })()}function handlePluginBoot(data: IframeBridgeMessage) {@@ -215,7 +389,24 @@ export function Iframe({ iframeRef, srcOverride = null, borderTint = null }: Ifr.catch(error => console.error('[frame-log] log_frontend failed:', error))}- function handleNotificationClicked(payload: NotificationClickedPayload) {+ /**+ * 点通知本体:先把窗口拉回前台,再让帧内聚焦对应会话。+ *+ * 窗口这一步是必需的:点通知时窗口多半在后台(最小化 / 被别的窗口盖住),+ * 只回灌 iframe 消息的话用户看不到任何变化。失败只记录日志——窗口 API 报错不该+ * 阻断帧内的会话切换与按钮回调。+ */+ async function activateApplication(payload: NotificationClickedPayload) {+ try {+ const appWindow = getCurrentWindow()+ if (await appWindow.isMinimized())+ await appWindow.unminimize()+ await appWindow.show()+ await appWindow.setFocus()+ }+ catch (error) {+ console.error('[notification] focus window failed:', error)+ }post({type: 'dsh://focus-session',sessionId: payload.sessionId || undefined,@@ -224,6 +415,91 @@ export function Iframe({ iframeRef, srcOverride = null, borderTint = null }: Ifr})}+ /**+ * 点击 / 按钮动作回灌给帧内的 Notification 实例:插件注册的+ * onclick、onaction 回调只存在于 iframe 里,壳层只负责转发。+ *+ * 点按钮只走这里,不碰窗口也不切会话:在通知里点「批准 / 拒绝 / 回复」时用户的+ * 视线通常还在别处,把窗口拽到前台会打断手上的事;要看结果自己点通知本体。+ */+ function deliverNotificationResult(payload: NotificationClickedPayload) {+ post({+ type: 'dsh://notification-clicked',+ tag: payload.tag || undefined,+ action: payload.action || undefined,+ inputValue: payload.inputValue || undefined,+ })+ }++ /** `onAction`:点通知本体(`actionId === 'tap'`)交给 `onNotificationClicked`,这里只管按钮。 */+ function handleNotificationAction(event: NotificationActionEvent) {+ const { actionId, inputValue, notification, extra: payloadExtra } = event+ if (typeof actionId !== 'string' || actionId === '' || actionId === 'tap')+ return++ // 会话标识只能从 `extra` 取:进程外 COM 激活(点通知中心里的历史通知)拿到的+ // `notification` 恒为 `null`,而 `extra` 是发送时写进按钮 arguments 的那份数据+ // 原样带回来的。缺了 tag,帧内 `pendingOnClicks` 找不到实例,事件会被静默丢弃。+ const extra = payloadExtra ?? notification?.extra+ const payload: NotificationClickedPayload = {+ sessionId: extra?.sessionId ?? null,+ title: extra?.title,+ tag: extra?.tag,+ action: actionId,+ inputValue: typeof inputValue === 'string' ? inputValue : null,+ }++ // 同一次点击会从两条激活通路各投一次,用户输入文本往往只挂在其中一条上:+ // 先到的先压住,250ms 内的第二条与它合并(优先保留带输入文本的那一份),+ // 只向帧内投递一次,避免回复内容被空的那份顶掉。+ const key = `${payload.tag ?? ''}|${actionId}`+ const queued = pendingActionsRef.current.get(key)+ if (queued) {+ clearTimeout(queued.timer)+ pendingActionsRef.current.delete(key)+ dispatchNotificationAction({+ ...queued.payload,+ ...payload,+ inputValue: payload.inputValue || queued.payload.inputValue,+ })+ return+ }++ const timer = setTimeout(() => {+ pendingActionsRef.current.delete(key)+ dispatchNotificationAction(payload)+ }, ACTION_COALESCE_MS)+ pendingActionsRef.current.set(key, { payload, timer })+ }++ function dispatchNotificationAction(payload: NotificationClickedPayload) {+ // 事件有没有真的到达壳层、有没有带上会话标识只有日志能回答:Windows 的 toast 激活+ // 依赖插件侧回调。eslint 只允许 console.warn/error,而 console 会被 utils/logger+ // 劫持写进前台日志(desktop.frontdesk.log),所以开发态用 warn 留痕、打包态不打扰。+ if (import.meta.env.DEV) {+ console.warn('[notification] action event:', payload.action, {+ tag: payload.tag ?? null,+ sessionId: payload.sessionId ?? null,+ inputLength: payload.inputValue?.length ?? 0,+ })+ }+ void deliverNotificationResult(payload)+ }++ /** `onNotificationClicked`:点通知本体(前台与冷启动两条路径都会走到这里)。 */+ function handleNotificationClick(event: NotificationClickEvent) {+ const { data } = event+ if (import.meta.env.DEV)+ console.warn('[notification] click event:', JSON.stringify(data ?? null))++ const payload: NotificationClickedPayload = {+ sessionId: data?.sessionId ?? null,+ title: data?.title,+ tag: data?.tag,+ }+ void activateApplication(payload).then(() => deliverNotificationResult(payload))+ }+return (<div className="relative min-h-0 flex-1"><If