1147 lines
51 KiB
JavaScript
1147 lines
51 KiB
JavaScript
/**
|
|
* Browser half of the session-notify bundle.
|
|
*
|
|
* One job: tell the user when a conversation needs attention. Three triggers —
|
|
* a conversation that stopped running, a pending tool approval, and a pending
|
|
* question or plan review — are derived from the client's own session state, and
|
|
* each one is delivered exactly once, through exactly one channel:
|
|
*
|
|
* - the Harness window not in the foreground → a system notification, raised
|
|
* through the page's Web `Notification` constructor. That is the only
|
|
* system-notification channel a plugin can reach: `@deepseek-ai/dsh-desktop-host`
|
|
* runs the Host half in a plain Node process rather than in Electron's main
|
|
* process, so the Host side has no `Notification` to call. The same Web API
|
|
* backs Windows, macOS, and Linux inside the Desktop shell, so delivery has no
|
|
* platform branch at all — only the settings row's *help text* names the
|
|
* platform's own notification settings.
|
|
* - the window in the foreground, and the finished conversation not the one on
|
|
* screen → a light in-app popup, because a desktop notification while you are
|
|
* looking at the app is noise.
|
|
*
|
|
* State comes exclusively from the slot props' standard selector hooks
|
|
* (`useSessions`, `useSessionStatus`) — the documented way for a plugin to read
|
|
* session data. Nothing here polls, folds session events, or reaches into
|
|
* another plugin. Styles are this package's own, following the shipped toast and
|
|
* switch surfaces and referencing theme tokens only, because a plugin must not
|
|
* import a Harness Client package.
|
|
*
|
|
* @module @dsh-plugin/session-notify/client
|
|
*/
|
|
|
|
window.__ModuleLoader__.load({
|
|
id: '@dsh-plugin/session-notify',
|
|
factory(require) {
|
|
const React = require('react')
|
|
const h = React.createElement
|
|
|
|
/** Locale namespace owned by this package. */
|
|
const NS = 'session-notify'
|
|
/** This package's name: the plugin manager keys a bundle's configuration by it. */
|
|
const PACKAGE_NAME = '@dsh-plugin/session-notify'
|
|
/** Trigger ids shared by the store, the copy table, and the settings row. */
|
|
const KINDS = ['completion', 'approval', 'question']
|
|
/** Pending-interaction kinds the Harness itself renders, and this plugin serves. */
|
|
const PENDING_KINDS = ['approval', 'question', 'plan-review']
|
|
/** Shortest gap between two deliveries, so parallel finishes cannot flood. */
|
|
const THROTTLE_MS = 1500
|
|
/** Settle delay before a completion is delivered, so a resumed run stays silent. */
|
|
const SETTLE_MS = 400
|
|
/** In-app popup lifetime, and how many may stack. */
|
|
const TOAST_DURATION_MS = 6000
|
|
const TOAST_LIMIT = 3
|
|
|
|
const zh = {
|
|
'notification.completion': '会话已完成',
|
|
'notification.approval': '需要授权',
|
|
'notification.question': '需要回答',
|
|
'body.completion': '{title} 已完成这一轮回答',
|
|
'body.approval': '{title}:工具 {tool} 正在等待你的授权',
|
|
'body.approvalPlain': '{title}:有工具正在等待你的授权',
|
|
'body.question': '{title}:正在等待你的回答',
|
|
'body.planReview': '{title}:计划正在等待你确认',
|
|
'body.untitled': '未命名会话',
|
|
'toast.view': '查看',
|
|
'toast.dismiss': '关闭',
|
|
'settings.title': '会话通知',
|
|
'settings.description': '窗口不在前台时用系统通知,窗口在前台时用应用内轻弹窗;正在看的那个会话完成后不打扰。',
|
|
'settings.permission.granted': '系统通知已开启',
|
|
'settings.permission.default': '尚未授予系统通知权限',
|
|
'settings.permission.denied': '系统通知已被系统设置关闭',
|
|
'settings.permission.unsupported': '当前环境不支持系统通知,仍会显示应用内轻弹窗',
|
|
'settings.permission.hint.plain': '请在系统通知设置中允许 DeepSeek Harness',
|
|
'settings.permission.hint.win': 'Windows 设置 → 系统 → 通知 → DeepSeek Harness',
|
|
'settings.permission.hint.mac': '系统设置 → 通知 → DeepSeek Harness',
|
|
'settings.permission.hint.linux': '在桌面环境的通知设置(GNOME / KDE)中允许 DeepSeek Harness',
|
|
'settings.action.allow': '允许通知',
|
|
'settings.action.test': '测试通知',
|
|
'settings.action.unsupported': '不可用',
|
|
'settings.permission.promptFailed': '无法请求通知权限:{message}',
|
|
'settings.health.watching': '正在监听会话状态',
|
|
'settings.health.noHooks': '未收到会话状态(通知不会触发)',
|
|
'settings.health.error': '监听会话状态出错:{message}',
|
|
'settings.health.starting': '正在等待会话列表',
|
|
'settings.kinds.label': '提醒内容',
|
|
'settings.kind.completion': '完成',
|
|
'settings.kind.approval': '授权',
|
|
'settings.kind.question': '提问',
|
|
'config.title': '会话通知',
|
|
'config.note': '只在会话需要你注意时提醒,而且只在 DSH 运行时。',
|
|
'config.section.kinds': '提醒内容',
|
|
'config.section.permission': '系统通知权限',
|
|
'config.section.status': '运行状态',
|
|
'config.saveNote': '开关保存在浏览器本地,重装插件不会丢失。',
|
|
}
|
|
const en = {
|
|
'notification.completion': 'Conversation finished',
|
|
'notification.approval': 'Approval required',
|
|
'notification.question': 'Answer needed',
|
|
'body.completion': '{title} finished this round',
|
|
'body.approval': '{title}: {tool} is waiting for your approval',
|
|
'body.approvalPlain': '{title}: a tool is waiting for your approval',
|
|
'body.question': '{title}: waiting for your answer',
|
|
'body.planReview': '{title}: a plan is waiting for your review',
|
|
'body.untitled': 'Untitled conversation',
|
|
'toast.view': 'View',
|
|
'toast.dismiss': 'Dismiss',
|
|
'settings.title': 'Session notifications',
|
|
'settings.description': 'A system notification while the window is in the background, a light in-app popup while it is in the foreground; the conversation on screen is never interrupted.',
|
|
'settings.permission.granted': 'System notifications are on',
|
|
'settings.permission.default': 'System notification permission has not been granted',
|
|
'settings.permission.denied': 'System notifications are switched off in system settings',
|
|
'settings.permission.unsupported': 'This environment cannot show system notifications; the in-app popup still works',
|
|
'settings.permission.hint.plain': 'Allow DeepSeek Harness in your system notification settings',
|
|
'settings.permission.hint.win': 'Windows Settings → System → Notifications → DeepSeek Harness',
|
|
'settings.permission.hint.mac': 'System Settings → Notifications → DeepSeek Harness',
|
|
'settings.permission.hint.linux': 'Allow DeepSeek Harness in your desktop notification settings (GNOME / KDE)',
|
|
'settings.action.allow': 'Allow notifications',
|
|
'settings.action.test': 'Test notification',
|
|
'settings.action.unsupported': 'Unavailable',
|
|
'settings.permission.promptFailed': 'Could not request notification permission: {message}',
|
|
'settings.health.watching': 'Watching session status',
|
|
'settings.health.noHooks': 'No session status received (notifications will not fire)',
|
|
'settings.health.error': 'Watching session status failed: {message}',
|
|
'settings.health.starting': 'Waiting for the session list',
|
|
'settings.kinds.label': 'Notify about',
|
|
'settings.kind.completion': 'Finished',
|
|
'settings.kind.approval': 'Approval',
|
|
'settings.kind.question': 'Questions',
|
|
'config.title': 'Session notifications',
|
|
'config.note': 'Alerts you when a conversation needs attention, while DSH is running.',
|
|
'config.section.kinds': 'What to notify about',
|
|
'config.section.permission': 'System notification permission',
|
|
'config.section.status': 'Status',
|
|
'config.saveNote': 'The switches are stored in this browser and survive reinstalling the plugin.',
|
|
}
|
|
|
|
/**
|
|
* Every declaration below belongs to this package. The popup copies the
|
|
* shipped toast surface (a fixed entry in the frame-wide overlay, the
|
|
* `--dsw-alias-toast-bg` / `--dsw-alias-toast-label` pair, `--dsw-radius-lg`,
|
|
* `--dsw-shadow-lv3`) and adds a title line above the text; the switch copies
|
|
* `Switch.module.css` behavior and proportion; the configuration sections
|
|
* follow the Plugin Manager page's own section rhythm (a column, 32px apart).
|
|
* Class names are renamed under `dsn-`; only the popup glyphs carry their own
|
|
* artwork colors.
|
|
*/
|
|
const CSS = `
|
|
.dsn-stack{position:fixed;top:40px;right:24px;z-index:1100;display:flex;flex-direction:column;align-items:flex-end;gap:8px;pointer-events:none}
|
|
@media (max-width:520px){.dsn-stack{right:12px}}
|
|
.dsn-toast{box-sizing:border-box;pointer-events:auto;display:flex;align-items:flex-start;gap:10px;width:max-content;max-width:min(420px,calc(100vw - 48px));padding:12px 12px 12px 16px;border-radius:var(--dsw-radius-lg);background:var(--dsw-alias-toast-bg);color:var(--dsw-alias-toast-label);font-size:14px;line-height:22px;box-shadow:var(--dsw-shadow-lv3);animation:dsn-toast-in 160ms ease-out}
|
|
@keyframes dsn-toast-in{from{opacity:0;transform:translateX(8px)}to{opacity:1;transform:translateX(0)}}
|
|
@media (prefers-reduced-motion: reduce){.dsn-toast{animation:none}}
|
|
.dsn-toast-icon{display:grid;place-items:center;flex:none;height:22px;color:var(--dsw-alias-state-warn-label)}
|
|
.dsn-toast-icon.is-completion{color:var(--dsw-alias-state-success-primary)}
|
|
.dsn-toast-icon.is-question{color:var(--dsw-alias-brand-primary)}
|
|
.dsn-toast-text{flex:1;min-width:0;display:flex;flex-direction:column;gap:2px}
|
|
.dsn-toast-title{font-weight:500;font-size:14px;line-height:22px}
|
|
.dsn-toast-desc{color:var(--dsw-alias-toast-label);opacity:.8;font-size:13px;line-height:20px;overflow-wrap:break-word}
|
|
.dsn-toast-actions{display:flex;align-items:center;gap:2px;flex:none}
|
|
.dsn-toast-action{display:inline-flex;align-items:center;height:28px;padding:0 8px;border:0;border-radius:var(--dsw-radius-sm);background:none;color:var(--dsw-static-deepseek-400);font:inherit;font-size:13px;line-height:20px;cursor:pointer}
|
|
.dsn-toast-action:hover{background:var(--dsw-alias-interactive-bg-hover)}
|
|
.dsn-toast-action:focus-visible{outline:var(--dsw-focus-ring-width) solid var(--dsw-focus-ring-color,var(--dsw-alias-state-business-primary));outline-offset:2px}
|
|
.dsn-toast-close{flex:none;display:inline-flex;align-items:center;justify-content:center;width:28px;height:28px;border:0;border-radius:var(--dsw-radius-sm);background:transparent;color:var(--dsw-alias-toast-label);opacity:.8;cursor:pointer}
|
|
.dsn-toast-close:hover{background:var(--dsw-alias-interactive-bg-hover);opacity:1}
|
|
.dsn-toast-close:focus-visible{outline:var(--dsw-focus-ring-width) solid var(--dsw-focus-ring-color,var(--dsw-alias-state-business-primary));outline-offset:2px}
|
|
.dsn-sections{display:flex;flex-direction:column;gap:24px}
|
|
.dsn-section{display:flex;flex-direction:column;gap:10px}
|
|
.dsn-section-title{margin:0;color:var(--dsw-alias-label-primary);font-size:14px;font-weight:500;line-height:22px}
|
|
.dsn-section-desc{margin:0;color:var(--dsw-alias-label-tertiary);font-size:12px;line-height:18px}
|
|
.dsn-row{display:flex;align-items:center;justify-content:space-between;gap:16px;padding:10px 0;border-bottom:.5px solid var(--dsw-alias-border-l2)}
|
|
.dsn-row:last-child{border-bottom:0}
|
|
.dsn-row-text{display:flex;flex-direction:column;gap:2px;min-width:0}
|
|
.dsn-row-title{color:var(--dsw-alias-label-primary);font-size:14px;line-height:22px}
|
|
.dsn-row-desc{color:var(--dsw-alias-label-tertiary);font-size:12px;line-height:18px}
|
|
.dsn-status{margin:0;color:var(--dsw-alias-label-secondary);font-size:12px;line-height:18px}
|
|
.dsn-status-error{color:var(--dsw-alias-state-error-primary)}
|
|
.dsn-switch{box-sizing:border-box;position:relative;flex:0 0 auto;width:36px;height:20px;padding:2px;border:0;border-radius:999px;background:var(--dsw-alias-border-l3);cursor:pointer}
|
|
.dsn-switch[aria-checked='true']{background:var(--dsw-alias-brand-primary)}
|
|
.dsn-switch:disabled{cursor:default;opacity:.5}
|
|
.dsn-switch:focus-visible{outline:var(--dsw-focus-ring-width) solid var(--dsw-focus-ring-color,var(--dsw-alias-state-business-primary));outline-offset:2px}
|
|
.dsn-thumb{display:block;width:16px;height:16px;border-radius:50%;background:var(--dsw-alias-label-primary-foreground);transition:transform 120ms ease}
|
|
.dsn-switch[aria-checked='false'] .dsn-thumb{background:var(--dsw-alias-switch-thumb)}
|
|
.dsn-switch[aria-checked='true'] .dsn-thumb{transform:translateX(16px)}
|
|
.dsn-button{box-sizing:border-box;display:inline-flex;align-items:center;justify-content:center;gap:4px;height:36px;padding:0 14px;border:.5px solid var(--dsw-alias-border-l3);border-radius:var(--dsw-radius-md);cursor:pointer;font-size:14px;line-height:22px;color:var(--dsw-alias-label-primary);background:transparent;flex:none}
|
|
.dsn-button:hover:not(:disabled){background:var(--dsw-alias-interactive-bg-hover)}
|
|
.dsn-button:disabled{cursor:not-allowed;opacity:.4}
|
|
.dsn-button:focus-visible{outline:var(--dsw-focus-ring-width) solid var(--dsw-focus-ring-color,var(--dsw-alias-state-business-primary));outline-offset:2px}
|
|
`
|
|
|
|
/** Bell glyph: this bundle's own artwork, drawn like the shipped outline set. */
|
|
function BellIcon({ size = 16 }) {
|
|
return h('svg', {
|
|
width: size, height: size, viewBox: '0 0 16 16', fill: 'none',
|
|
xmlns: 'http://www.w3.org/2000/svg', 'aria-hidden': true,
|
|
},
|
|
h('path', {
|
|
d: 'M8 2.35C5.7 2.35 3.83 4.22 3.83 6.52V9.02L3.06 11.1C2.99 11.29 3.13 11.48 3.33 11.48H12.67C12.87 11.48 13.01 11.29 12.94 11.1L12.17 9.02V6.52C12.17 4.22 10.3 2.35 8 2.35Z',
|
|
stroke: 'currentColor', strokeWidth: 1.2, strokeLinejoin: 'round',
|
|
}),
|
|
h('path', {
|
|
d: 'M6.3 12.75C6.52 13.66 7.2 14.28 8 14.28C8.8 14.28 9.48 13.66 9.7 12.75',
|
|
stroke: 'currentColor', strokeWidth: 1.2, strokeLinecap: 'round',
|
|
}))
|
|
}
|
|
|
|
/** Shield glyph for an approval request. */
|
|
function ShieldIcon({ size = 16 }) {
|
|
return h('svg', {
|
|
width: size, height: size, viewBox: '0 0 16 16', fill: 'none',
|
|
xmlns: 'http://www.w3.org/2000/svg', 'aria-hidden': true,
|
|
},
|
|
h('path', {
|
|
d: 'M8 1.9 13.1 3.7V7.9C13.1 11 11 13.3 8 14.2C5 13.3 2.9 11 2.9 7.9V3.7L8 1.9Z',
|
|
stroke: 'currentColor', strokeWidth: 1.2, strokeLinejoin: 'round',
|
|
}),
|
|
h('path', {
|
|
d: 'M5.9 8.05L7.35 9.5L10.15 6.6',
|
|
stroke: 'currentColor', strokeWidth: 1.2, strokeLinecap: 'round', strokeLinejoin: 'round',
|
|
}))
|
|
}
|
|
|
|
/** Question glyph for a pending question or plan review. */
|
|
function QuestionIcon({ size = 16 }) {
|
|
return h('svg', {
|
|
width: size, height: size, viewBox: '0 0 16 16', fill: 'none',
|
|
xmlns: 'http://www.w3.org/2000/svg', 'aria-hidden': true,
|
|
},
|
|
h('circle', { cx: 8, cy: 8, r: 6.15, stroke: 'currentColor', strokeWidth: 1.2 }),
|
|
h('path', {
|
|
d: 'M6.35 6.35C6.35 5.44 7.09 4.7 8 4.7C8.91 4.7 9.65 5.44 9.65 6.35C9.65 7.75 8 7.7 8 9.15',
|
|
stroke: 'currentColor', strokeWidth: 1.2, strokeLinecap: 'round',
|
|
}),
|
|
h('circle', { cx: 8, cy: 11.3, r: 0.85, fill: 'currentColor' }))
|
|
}
|
|
|
|
/** Close glyph, matching the primitives' own stroke weight and geometry. */
|
|
function CloseIcon({ size = 12 }) {
|
|
return h('svg', {
|
|
width: size, height: size, viewBox: '0 0 16 16', fill: 'none',
|
|
xmlns: 'http://www.w3.org/2000/svg', 'aria-hidden': true,
|
|
},
|
|
h('path', { d: 'M2.5 2.5L13.5 13.5', stroke: 'currentColor', strokeWidth: 1.4 }),
|
|
h('path', { d: 'M13.5 2.5L2.5 13.5', stroke: 'currentColor', strokeWidth: 1.4 }))
|
|
}
|
|
|
|
/** Select the per-trigger glyph. */
|
|
function KindIcon({ kind, size }) {
|
|
if (kind === 'approval') return h(ShieldIcon, { size })
|
|
if (kind === 'question') return h(QuestionIcon, { size })
|
|
return h(BellIcon, { size })
|
|
}
|
|
|
|
/** Minimal observable store: the shape React reads with useSyncExternalStore. */
|
|
function createStore(initial) {
|
|
let value = initial
|
|
const listeners = new Set()
|
|
return {
|
|
getSnapshot: () => value,
|
|
subscribe: (listener) => {
|
|
listeners.add(listener)
|
|
return () => {
|
|
listeners.delete(listener)
|
|
}
|
|
},
|
|
set: (next) => {
|
|
if (next === value) return
|
|
value = next
|
|
for (const listener of [...listeners]) listener()
|
|
},
|
|
}
|
|
}
|
|
|
|
/** Render one unknown failure as text. */
|
|
function text(error) {
|
|
return error instanceof Error ? error.message : String(error)
|
|
}
|
|
|
|
/** Log one contained diagnostic through the package-tagged console. */
|
|
function report(message) {
|
|
try {
|
|
console.error(`session-notify: ${message}`)
|
|
} catch {
|
|
/* a diagnostic never fails the plugin */
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Publish the resident observer's own health into the plugin store.
|
|
*
|
|
* A slot entry that silently receives nothing is the one failure this plugin
|
|
* cannot detect from the outside, so the observer records whether it is
|
|
* actually seeing session state and the settings row shows it. Repeated
|
|
* identical states publish nothing, and a state this is not `watching` also
|
|
* reaches the tagged console.
|
|
* @param store - the plugin's own store.
|
|
* @param next - the health state observed on this render.
|
|
*/
|
|
function applyHealth(store, next) {
|
|
const snapshot = store.getSnapshot()
|
|
const current = snapshot.health
|
|
if (current.state === next.state && current.message === next.message) return
|
|
if (current.state !== 'watching') report(`observer health: ${next.state} ${next.message}`)
|
|
store.set({ ...snapshot, health: next })
|
|
}
|
|
|
|
/** Permission lookup that never throws in a browser without the API. */
|
|
function notificationPermission() {
|
|
const Ctor = globalThis.Notification
|
|
if (typeof Ctor !== 'function') return 'unsupported'
|
|
const permission = Ctor.permission
|
|
if (permission === 'granted' || permission === 'denied' || permission === 'default') return permission
|
|
return 'default'
|
|
}
|
|
|
|
/** Read the window's live focus state rather than a cached value. */
|
|
function currentFocus() {
|
|
try {
|
|
return typeof document.hasFocus === 'function' ? document.hasFocus() : true
|
|
} catch {
|
|
return true
|
|
}
|
|
}
|
|
|
|
/** Focus the window without letting a refusal stop the navigation. */
|
|
function focusWindow() {
|
|
try {
|
|
globalThis.focus?.()
|
|
} catch {
|
|
/* focus is best effort on every platform */
|
|
}
|
|
}
|
|
|
|
/**
|
|
* The system-notification icon, built once: this deployment's own static URL
|
|
* when the page serves this package's assets, else the SVG inline. Icons are
|
|
* cosmetic on every platform, so each step is contained.
|
|
* @returns an icon URL, or undefined when neither form can be built.
|
|
*/
|
|
const systemIcon = (() => {
|
|
try {
|
|
const url = new URL('./icon.svg', document.baseURI).href
|
|
if (url !== '') return url
|
|
} catch {
|
|
/* fall through to the inline form */
|
|
}
|
|
try {
|
|
const svg = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><path d="M8 2.35C5.7 2.35 3.83 4.22 3.83 6.52V9.02L3.06 11.1C2.99 11.29 3.13 11.48 3.33 11.48H12.67C12.87 11.48 13.01 11.29 12.94 11.1L12.17 9.02V6.52C12.17 4.22 10.3 2.35 8 2.35Z" fill="none" stroke="%23247bbf" stroke-width="1.2"/><path d="M6.3 12.75C6.52 13.66 7.2 14.28 8 14.28C8.8 14.28 9.48 13.66 9.7 12.75" fill="none" stroke="%23247bbf" stroke-width="1.2" stroke-linecap="round"/></svg>'
|
|
return `data:image/svg+xml,${svg}`
|
|
} catch {
|
|
return undefined
|
|
}
|
|
})()
|
|
|
|
/** One best-effort platform hint, used for settings help text only. */
|
|
function platformKey() {
|
|
try {
|
|
const agent = navigator.userAgentData
|
|
const platform = String((agent?.platform ?? navigator.platform) || navigator.userAgent || '')
|
|
if (/win/i.test(platform)) return 'win'
|
|
if (/mac|iphone|ipad/i.test(platform)) return 'mac'
|
|
if (/linux|x11/i.test(platform)) return 'linux'
|
|
} catch {
|
|
/* an unreadable navigator keeps the neutral hint */
|
|
}
|
|
return 'plain'
|
|
}
|
|
|
|
/**
|
|
* Discriminate a pending interaction the client published. Only the three
|
|
* domains the Harness itself renders are served; anything else is ignored
|
|
* rather than guessed at.
|
|
* @param value - `status.pendingInteraction`.
|
|
* @returns a served kind, or undefined.
|
|
*/
|
|
function servedPendingKind(value) {
|
|
if (value === undefined || value === null || typeof value !== 'object') return undefined
|
|
const kind = value.kind
|
|
return typeof kind === 'string' && PENDING_KINDS.includes(kind) ? kind : undefined
|
|
}
|
|
|
|
/** Trim free text down to one popup line. */
|
|
function preview(value) {
|
|
if (typeof value !== 'string') return ''
|
|
const flat = value.replace(/\s+/g, ' ').trim()
|
|
return flat.length > 80 ? `${flat.slice(0, 79)}…` : flat
|
|
}
|
|
|
|
/** The first question text a pending interaction exposes, across its shapes. */
|
|
function questionText(interaction) {
|
|
if (interaction === null || typeof interaction !== 'object') return ''
|
|
const first = Array.isArray(interaction.questions) ? interaction.questions[0] : undefined
|
|
if (typeof first?.question === 'string') return preview(first.question)
|
|
if (typeof first?.text === 'string') return preview(first.text)
|
|
if (typeof interaction.question === 'string') return preview(interaction.question)
|
|
if (typeof interaction.prompt === 'string') return preview(interaction.prompt)
|
|
return preview(interaction.displayReason?.text ?? interaction.reason?.text ?? '')
|
|
}
|
|
|
|
/**
|
|
* Register this package's dictionaries with the locale service.
|
|
*
|
|
* Without this the service has no entry for the namespace and every
|
|
* `locale.bind(NS)` lookup answers with the key itself, so the settings row
|
|
* shows `settings.title` instead of its copy. The typed form takes every
|
|
* shipped locale in one call, and the older single-locale form stays
|
|
* supported as a fallback. Registration bumps the locale revision, so
|
|
* already-rendered entries pick the copy up without a reload.
|
|
* @param locale - the locale service, or undefined when this profile has none.
|
|
* @returns a disposer for whichever registrations were installed.
|
|
*/
|
|
function registerDictionaries(locale) {
|
|
if (locale === undefined || typeof locale.register !== 'function') return () => {}
|
|
const dictionaries = { zh, en }
|
|
try {
|
|
return locale.register(NS, dictionaries)
|
|
} catch {
|
|
const disposers = Object.entries(dictionaries).map(([id, dict]) => locale.register(NS, id, dict))
|
|
return () => {
|
|
for (const dispose of disposers) dispose?.()
|
|
}
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Build a translate function for one locale service: the service's own bound
|
|
* namespace first, then this package's dictionaries, then the key itself, so
|
|
* a missing seat degrades copy instead of rendering.
|
|
* @param locale - the locale service, or undefined when this profile has none.
|
|
* @returns a translate function with `{ name }` interpolation.
|
|
*/
|
|
function createTranslator(locale) {
|
|
return (key, params) => {
|
|
if (locale !== undefined && typeof locale.bind === 'function') {
|
|
try {
|
|
const bound = locale.bind(NS)
|
|
if (typeof bound === 'function') {
|
|
const translated = bound(key, params)
|
|
if (typeof translated === 'string' && translated !== key) return translated
|
|
}
|
|
} catch {
|
|
/* a locale service without this namespace still renders the fallback */
|
|
}
|
|
}
|
|
let language = ''
|
|
try {
|
|
const snapshot = locale?.getSnapshot?.()
|
|
language = String(snapshot?.active ?? '')
|
|
} catch {
|
|
language = ''
|
|
}
|
|
const dictionary = /^zh/i.test(language) ? zh : en
|
|
const template = dictionary[key] ?? zh[key] ?? en[key] ?? key
|
|
if (params === undefined) return template
|
|
return template.replace(/\{(\w+)\}/g, (match, name) => (
|
|
Object.prototype.hasOwnProperty.call(params, name) ? String(params[name]) : match
|
|
))
|
|
}
|
|
}
|
|
|
|
/** Storage key for this package's own preferences. */
|
|
const STORAGE_KEY = 'dsh-plugin/session-notify'
|
|
|
|
/**
|
|
* Read this package's stored trigger switches.
|
|
*
|
|
* These are browser preferences rather than cordis configuration, so they live
|
|
* in this origin's own storage instead of the profile's patch file: the plugin
|
|
* writes nothing into DSH's configuration, and every read is defensive because
|
|
* storage can be unavailable or hold something an older version wrote.
|
|
* @returns the stored switches, defaulting to everything on.
|
|
*/
|
|
function readStoredKinds() {
|
|
const kinds = { completion: true, approval: true, question: true }
|
|
try {
|
|
const raw = globalThis.localStorage?.getItem(STORAGE_KEY)
|
|
if (typeof raw !== 'string' || raw === '') return kinds
|
|
const stored = JSON.parse(raw)
|
|
for (const kind of KINDS) {
|
|
if (typeof stored?.[kind] === 'boolean') kinds[kind] = stored[kind]
|
|
}
|
|
} catch {
|
|
/* unreadable or foreign storage keeps the defaults */
|
|
}
|
|
return kinds
|
|
}
|
|
|
|
/** Store one trigger switch, ignoring storage that refuses to write. */
|
|
function writeStoredKinds(kinds) {
|
|
try {
|
|
globalThis.localStorage?.setItem(STORAGE_KEY, JSON.stringify(kinds))
|
|
} catch {
|
|
/* a refused write leaves the switches live for this page only */
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Install the plugin.
|
|
* @param ctx - Client root context providing `slots` and `locale`.
|
|
*/
|
|
function apply(ctx) {
|
|
const locale = ctx.get('locale')
|
|
const t = createTranslator(locale)
|
|
|
|
const store = createStore({
|
|
permission: notificationPermission(),
|
|
kinds: readStoredKinds(),
|
|
toasts: [],
|
|
promptError: '',
|
|
health: { state: 'starting', message: '' },
|
|
})
|
|
const notify = (message) => {
|
|
report(`session-notify: ${message}`)
|
|
}
|
|
/** Every component translates through this: the slot's own seat when the owner supplies one, else the locale service. */
|
|
const seatFor = (props) => (typeof props.t === 'function' ? props.t : t)
|
|
const state = {
|
|
runs: new Map(),
|
|
completionNotice: new Set(),
|
|
pendingNotice: new Map(),
|
|
pending: [],
|
|
settleTimer: 0,
|
|
lastDelivery: 0,
|
|
toastSeq: 0,
|
|
live: {
|
|
list: undefined,
|
|
status: undefined,
|
|
focus: true,
|
|
},
|
|
}
|
|
const timers = new Map()
|
|
let disposed = false
|
|
|
|
const publish = () => {
|
|
if (!disposed) store.set({ ...store.getSnapshot() })
|
|
}
|
|
|
|
// ------------------------------------------------------------------ copy
|
|
|
|
/** Build the delivered copy for one candidate. */
|
|
const copyFor = (candidate) => {
|
|
const title = candidate.title === '' ? t('body.untitled') : candidate.title
|
|
if (candidate.kind === 'completion') {
|
|
return { kind: 'completion', title: t('notification.completion'), body: t('body.completion', { title }) }
|
|
}
|
|
if (candidate.kind === 'question') {
|
|
const question = candidate.detail
|
|
return {
|
|
kind: 'question',
|
|
title: t('notification.question'),
|
|
body: question === '' ? t('body.question', { title }) : `${title} · ${question}`,
|
|
}
|
|
}
|
|
if (candidate.pendingKind === 'plan-review') {
|
|
return { kind: 'question', title: t('notification.question'), body: t('body.planReview', { title }) }
|
|
}
|
|
const tool = candidate.detail
|
|
return {
|
|
kind: 'approval',
|
|
title: t('notification.approval'),
|
|
body: tool === '' ? t('body.approvalPlain', { title }) : t('body.approval', { title, tool }),
|
|
}
|
|
}
|
|
|
|
/** Copy one session title, falling back to its identity. */
|
|
const titleOf = (summary, sessionId) => {
|
|
const title = typeof summary?.title === 'string' ? summary.title.trim() : ''
|
|
return title === '' ? sessionId.slice(0, 8) : title
|
|
}
|
|
|
|
// ---------------------------------------------------------------- popups
|
|
|
|
/** Drop one popup and cancel its lifetime timer. */
|
|
const closeToast = (id) => {
|
|
const timer = timers.get(id)
|
|
if (timer !== undefined) {
|
|
clearTimeout(timer)
|
|
timers.delete(id)
|
|
}
|
|
const snapshot = store.getSnapshot()
|
|
if (!snapshot.toasts.some((toast) => toast.id === id)) return
|
|
store.set({ ...snapshot, toasts: snapshot.toasts.filter((toast) => toast.id !== id) })
|
|
}
|
|
|
|
/** Arm one popup's lifetime; hovering calls `hold` first, then this again. */
|
|
const armToast = (id) => {
|
|
const timer = timers.get(id)
|
|
if (timer !== undefined) clearTimeout(timer)
|
|
timers.set(id, setTimeout(() => closeToast(id), TOAST_DURATION_MS))
|
|
}
|
|
|
|
/** Pause one popup's lifetime while the pointer rests on it. */
|
|
const holdToast = (id) => {
|
|
const timer = timers.get(id)
|
|
if (timer === undefined) return
|
|
clearTimeout(timer)
|
|
timers.delete(id)
|
|
}
|
|
|
|
/**
|
|
* Show one light in-app popup: the trigger as the title, the conversation
|
|
* and its detail as the description, so the heading says what happened and
|
|
* the line under it says where.
|
|
*/
|
|
const showToast = (candidate) => {
|
|
const notice = copyFor(candidate)
|
|
state.toastSeq += 1
|
|
const toast = {
|
|
id: `dsn-${String(state.toastSeq)}`,
|
|
kind: notice.kind,
|
|
title: notice.title,
|
|
body: notice.body,
|
|
sessionId: candidate.sessionId,
|
|
}
|
|
const snapshot = store.getSnapshot()
|
|
const next = [toast, ...snapshot.toasts]
|
|
for (const dropped of next.slice(TOAST_LIMIT)) {
|
|
const timer = timers.get(dropped.id)
|
|
if (timer !== undefined) {
|
|
clearTimeout(timer)
|
|
timers.delete(dropped.id)
|
|
}
|
|
}
|
|
store.set({ ...snapshot, toasts: next.slice(0, TOAST_LIMIT) })
|
|
armToast(toast.id)
|
|
}
|
|
|
|
// ---------------------------------------------------- system notification
|
|
|
|
/** Bring one conversation to the front, when the client exposes that operation. */
|
|
const openSession = (sessionId) => {
|
|
try {
|
|
ctx.get('uiWorkspace')?.openSession?.(sessionId)
|
|
} catch (error) {
|
|
notify(`could not open "${sessionId}": ${text(error)}`)
|
|
}
|
|
}
|
|
|
|
/** Raise one system notification, tolerating every refusal a browser may give. */
|
|
const systemNotify = (candidate, force) => {
|
|
const Ctor = globalThis.Notification
|
|
const permission = notificationPermission()
|
|
if (permission === 'unsupported') return false
|
|
if (!force && permission !== 'granted') return false
|
|
try {
|
|
const notice = copyFor(candidate)
|
|
const options = {
|
|
body: notice.body,
|
|
tag: `dsh-session-${candidate.sessionId}`,
|
|
requireInteraction: false,
|
|
}
|
|
if (systemIcon !== undefined) options.icon = systemIcon
|
|
const notification = new Ctor(notice.title, options)
|
|
notification.onclick = () => {
|
|
focusWindow()
|
|
openSession(candidate.sessionId)
|
|
try {
|
|
notification.close()
|
|
} catch {
|
|
/* close is best effort on every platform */
|
|
}
|
|
}
|
|
return true
|
|
} catch (error) {
|
|
notify(`system notification failed: ${text(error)}`)
|
|
return false
|
|
}
|
|
}
|
|
|
|
// -------------------------------------------------------------- delivery
|
|
|
|
/** Whether the user is looking at this exact conversation right now. */
|
|
const isOnScreen = (sessionId, list) => {
|
|
if (list === undefined) return false
|
|
for (const id of Object.keys(list.byId ?? {})) {
|
|
const summary = list.byId[id]
|
|
if (summary !== undefined && (summary.retainedBy?.mainView ?? 0) > 0) return id === sessionId
|
|
}
|
|
return false
|
|
}
|
|
|
|
/**
|
|
* Whether a queued candidate is still worth delivering. Read from the LIVE
|
|
* snapshot rather than the one captured when the transition was seen: a
|
|
* conversation that resumed in the settle window owes no alert, and the
|
|
* snapshot the transition was derived from still carries the pre-transition
|
|
* `running` flag of the session record.
|
|
*/
|
|
const stillWorth = (candidate) => {
|
|
const list = state.live.list
|
|
if (candidate.test === true || list === undefined) return true
|
|
const summary = list.byId?.[candidate.sessionId]
|
|
if (summary === undefined) return true
|
|
const status = state.live.status
|
|
const running = status?.get?.(candidate.sessionId)?.running ?? summary.running
|
|
return running !== true
|
|
}
|
|
|
|
/**
|
|
* Deliver one candidate through exactly one channel: the system
|
|
* notification while the window is in the background, the light popup while
|
|
* it is in the foreground, and nothing at all for the conversation on
|
|
* screen.
|
|
*/
|
|
const deliver = (candidate, ignoreThrottle) => {
|
|
if (ignoreThrottle !== true) {
|
|
const now = Date.now()
|
|
if (now - state.lastDelivery < THROTTLE_MS) return
|
|
state.lastDelivery = now
|
|
}
|
|
if (state.live.focus) {
|
|
if (!isOnScreen(candidate.sessionId, state.live.list)) showToast(candidate)
|
|
return
|
|
}
|
|
if (systemNotify(candidate, candidate.test === true)) return
|
|
if (candidate.test === true) showToast(candidate)
|
|
}
|
|
|
|
/**
|
|
* Take the delivery decision on a later tick, from the freshest state.
|
|
*/
|
|
const flushSettle = () => {
|
|
state.settleTimer = 0
|
|
const candidate = state.pending.shift()
|
|
if (disposed || candidate === undefined) return
|
|
if (!stillWorth(candidate)) return
|
|
deliver(candidate, false)
|
|
}
|
|
|
|
/** Hold one candidate for the settle tick, collapsing a burst onto one timer. */
|
|
const queue = (candidate) => {
|
|
state.pending.push(candidate)
|
|
if (state.settleTimer !== 0) return
|
|
state.settleTimer = setTimeout(() => flushSettle(), SETTLE_MS)
|
|
}
|
|
|
|
// ----------------------------------------------------------- observation
|
|
|
|
/**
|
|
* One derivation pass over the client's own session state: remember the
|
|
* freshest snapshot for the settle tick, compare it against what this page
|
|
* already observed, emit at most one candidate per transition, and let the
|
|
* settle tick decide delivery.
|
|
*/
|
|
const observe = (focus, list, status) => {
|
|
if (list === undefined || status === undefined) return
|
|
state.live = { list, status, focus }
|
|
const kinds = store.getSnapshot().kinds
|
|
for (const sessionId of Object.keys(list.byId ?? {})) {
|
|
const summary = list.byId[sessionId]
|
|
if (summary === undefined || summary.origin === 'subagent') continue
|
|
const sessionStatus = status.get(sessionId)
|
|
const running = sessionStatus?.running ?? summary.running
|
|
|
|
if (running === true) {
|
|
state.runs.set(sessionId, true)
|
|
state.completionNotice.delete(sessionId)
|
|
} else {
|
|
if (state.runs.get(sessionId) === true) {
|
|
state.runs.set(sessionId, false)
|
|
if (summary.blank !== true && !state.completionNotice.has(sessionId) && kinds.completion) {
|
|
state.completionNotice.add(sessionId)
|
|
queue({
|
|
kind: 'completion',
|
|
sessionId,
|
|
title: titleOf(summary, sessionId),
|
|
detail: '',
|
|
pendingKind: '',
|
|
})
|
|
}
|
|
} else if (!state.runs.has(sessionId)) {
|
|
state.runs.set(sessionId, false)
|
|
}
|
|
}
|
|
|
|
const interaction = sessionStatus?.pendingInteraction
|
|
const pendingKind = servedPendingKind(interaction)
|
|
if (pendingKind === undefined) {
|
|
state.pendingNotice.delete(sessionId)
|
|
continue
|
|
}
|
|
if (state.pendingNotice.get(sessionId) === pendingKind) continue
|
|
state.pendingNotice.set(sessionId, pendingKind)
|
|
const trigger = pendingKind === 'approval' ? 'approval' : 'question'
|
|
if (!kinds[trigger]) continue
|
|
queue({
|
|
kind: trigger,
|
|
sessionId,
|
|
title: titleOf(summary, sessionId),
|
|
detail: pendingKind === 'approval'
|
|
? String(interaction?.toolName ?? '')
|
|
: questionText(interaction),
|
|
pendingKind,
|
|
})
|
|
}
|
|
|
|
for (const sessionId of [...state.runs.keys()]) {
|
|
if (list.byId?.[sessionId] !== undefined) continue
|
|
state.runs.delete(sessionId)
|
|
state.completionNotice.delete(sessionId)
|
|
state.pendingNotice.delete(sessionId)
|
|
}
|
|
}
|
|
|
|
// --------------------------------------------------------------- actions
|
|
|
|
/** Raise one test notification through the channel the current state selects. */
|
|
const sendTest = () => {
|
|
const candidate = {
|
|
kind: 'completion',
|
|
sessionId: 'test',
|
|
title: t('settings.title'),
|
|
detail: '',
|
|
pendingKind: '',
|
|
test: true,
|
|
}
|
|
if (!currentFocus() && notificationPermission() === 'granted' && systemNotify(candidate, true)) return
|
|
showToast(candidate)
|
|
}
|
|
|
|
/** Request notification permission inside a user gesture, then report the outcome. */
|
|
const requestPermission = async () => {
|
|
const Ctor = globalThis.Notification
|
|
if (typeof Ctor !== 'function') {
|
|
publish()
|
|
return
|
|
}
|
|
try {
|
|
let result = Ctor.requestPermission()
|
|
if (result === undefined) {
|
|
result = new Promise((resolve) => {
|
|
Ctor.requestPermission((value) => resolve(value))
|
|
})
|
|
}
|
|
await result
|
|
} catch (error) {
|
|
const snapshot = store.getSnapshot()
|
|
store.set({ ...snapshot, promptError: t('settings.permission.promptFailed', { message: text(error) }) })
|
|
return
|
|
}
|
|
const snapshot = store.getSnapshot()
|
|
store.set({ ...snapshot, permission: notificationPermission(), promptError: '' })
|
|
if (notificationPermission() === 'granted') sendTest()
|
|
}
|
|
|
|
/** Toggle one trigger and remember the choice. */
|
|
const setKindEnabled = (kind, enabled) => {
|
|
const snapshot = store.getSnapshot()
|
|
const kinds = { ...snapshot.kinds, [kind]: enabled }
|
|
writeStoredKinds(kinds)
|
|
store.set({ ...snapshot, kinds })
|
|
}
|
|
|
|
// ----------------------------------------------------------- components
|
|
|
|
/** Subscribe to this plugin's own store from inside a component. */
|
|
function useOwnStore(source) {
|
|
return React.useSyncExternalStore(source.subscribe, source.getSnapshot, source.getSnapshot)
|
|
}
|
|
|
|
/** The window's focus state as a React value, kept current by the DOM's own events. */
|
|
function useFocus() {
|
|
const subscribe = React.useCallback((listener) => {
|
|
try {
|
|
window.addEventListener('focus', listener)
|
|
window.addEventListener('blur', listener)
|
|
} catch {
|
|
return () => {}
|
|
}
|
|
return () => {
|
|
window.removeEventListener('focus', listener)
|
|
window.removeEventListener('blur', listener)
|
|
}
|
|
}, [])
|
|
return React.useSyncExternalStore(subscribe, currentFocus, () => true)
|
|
}
|
|
|
|
/**
|
|
* The resident observer: one invisible entry in a root-scope slot, which is
|
|
* how a plugin reaches the session hooks without occupying visible UI. It
|
|
* renders `null`, and any failure in its own derivation is contained here so
|
|
* a slot entry can never crash.
|
|
*/
|
|
function NotifyObserver(props) {
|
|
const focus = useFocus()
|
|
const useSessions = props.useSessions
|
|
const useSessionStatus = props.useSessionStatus
|
|
const select = React.useCallback((snapshot) => snapshot, [])
|
|
const list = typeof useSessions === 'function' ? useSessions(select) : undefined
|
|
const status = typeof useSessionStatus === 'function' ? useSessionStatus(select) : undefined
|
|
React.useEffect(() => {
|
|
try {
|
|
if (typeof props.useSessions !== 'function' || typeof props.useSessionStatus !== 'function') {
|
|
applyHealth(store, { state: 'noHooks', message: '' })
|
|
return
|
|
}
|
|
if (list === undefined || status === undefined) {
|
|
applyHealth(store, { state: 'starting', message: '' })
|
|
return
|
|
}
|
|
observe(focus, list, status)
|
|
applyHealth(store, { state: 'watching', message: '' })
|
|
} catch (error) {
|
|
applyHealth(store, { state: 'error', message: text(error) })
|
|
}
|
|
})
|
|
return null
|
|
}
|
|
|
|
/** The light popup stack: the frame-wide overlay entry this package owns. */
|
|
function ToastLayer(props) {
|
|
const snapshot = useOwnStore(props.store)
|
|
const toasts = snapshot.toasts
|
|
const tr = seatFor(props)
|
|
React.useEffect(() => {
|
|
if (toasts.length === 0) return undefined
|
|
const onKeyDown = (event) => {
|
|
if (event.key !== 'Escape' || event.defaultPrevented) return
|
|
const top = toasts[0]
|
|
if (top === undefined) return
|
|
event.preventDefault()
|
|
props.dismiss(top.id)
|
|
}
|
|
document.addEventListener('keydown', onKeyDown)
|
|
return () => {
|
|
document.removeEventListener('keydown', onKeyDown)
|
|
}
|
|
}, [toasts, props])
|
|
if (toasts.length === 0) return null
|
|
return h(React.Fragment, null,
|
|
h('style', null, CSS),
|
|
h('div', { className: 'dsn-stack', role: 'region', 'aria-live': 'polite' },
|
|
toasts.map((toast) => h('div', {
|
|
key: toast.id,
|
|
className: 'dsn-toast',
|
|
role: toast.kind === 'completion' ? 'status' : 'alert',
|
|
onMouseEnter: () => props.hold(toast.id),
|
|
onMouseLeave: () => props.arm(toast.id),
|
|
},
|
|
h('span', { className: `dsn-toast-icon is-${toast.kind}` }, h(KindIcon, { kind: toast.kind, size: 16 })),
|
|
h('div', { className: 'dsn-toast-text' },
|
|
h('div', { className: 'dsn-toast-title' }, toast.title),
|
|
h('div', { className: 'dsn-toast-desc' }, toast.body)),
|
|
h('div', { className: 'dsn-toast-actions' },
|
|
h('button', {
|
|
type: 'button',
|
|
className: 'dsn-toast-action',
|
|
onClick: () => {
|
|
props.dismiss(toast.id)
|
|
props.open(toast.sessionId)
|
|
},
|
|
}, tr('toast.view')),
|
|
h('button', {
|
|
type: 'button',
|
|
className: 'dsn-toast-close',
|
|
'aria-label': tr('toast.dismiss'),
|
|
onClick: () => props.dismiss(toast.id),
|
|
}, h(CloseIcon, { size: 14 })))))))
|
|
}
|
|
|
|
/**
|
|
* One trigger switch row: the label says which notification it governs and
|
|
* the switch is the control, so the row never needs a second description.
|
|
*/
|
|
function KindRow(props) {
|
|
return h('div', { className: 'dsn-row' },
|
|
h('div', { className: 'dsn-row-text' },
|
|
h('div', { className: 'dsn-row-title' }, props.label)),
|
|
h('button', {
|
|
type: 'button',
|
|
role: 'switch',
|
|
className: 'dsn-switch',
|
|
'aria-checked': props.checked,
|
|
'aria-label': props.label,
|
|
disabled: props.disabled,
|
|
onClick: props.onToggle,
|
|
}, h('span', { className: 'dsn-thumb' })))
|
|
}
|
|
|
|
/**
|
|
* This plugin's configuration, rendered on its own page in the plugin
|
|
* manager (`plugins.bundle.config`, keyed by this package's name).
|
|
*
|
|
* The owner asks for two views: `summary` (a one-liner that stands in for
|
|
* the row's description) and `page` (the whole form). Everything visible here
|
|
* belongs to this package, including the platform-specific permission hint.
|
|
*/
|
|
function ConfigSection(props) {
|
|
const snapshot = useOwnStore(props.store)
|
|
const tr = seatFor(props)
|
|
if (props.view === 'summary') return h(React.Fragment, null, tr('settings.description'))
|
|
const permission = snapshot.permission
|
|
const supported = permission !== 'unsupported'
|
|
const failed = permission === 'denied' || snapshot.promptError !== ''
|
|
const statusKey = permission === 'granted'
|
|
? 'settings.permission.granted'
|
|
: permission === 'denied'
|
|
? 'settings.permission.denied'
|
|
: supported
|
|
? 'settings.permission.default'
|
|
: 'settings.permission.unsupported'
|
|
const permissionText = snapshot.promptError === ''
|
|
? `${tr(statusKey)}${permission === 'denied' || !supported ? ` · ${tr(`settings.permission.hint.${props.platform}`)}` : ''}`
|
|
: snapshot.promptError
|
|
const health = snapshot.health
|
|
const healthText = health.state === 'watching'
|
|
? tr('settings.health.watching')
|
|
: health.state === 'noHooks'
|
|
? tr('settings.health.noHooks')
|
|
: health.state === 'error'
|
|
? tr('settings.health.error', { message: health.message })
|
|
: tr('settings.health.starting')
|
|
const healthFailed = health.state !== 'watching' && health.state !== 'starting'
|
|
return h(React.Fragment, null,
|
|
h('style', null, CSS),
|
|
h('div', { className: 'dsn-sections' },
|
|
h('section', { className: 'dsn-section' },
|
|
h('h3', { className: 'dsn-section-title' }, tr('config.title')),
|
|
h('p', { className: 'dsn-section-desc' }, tr('config.note'))),
|
|
h('section', { className: 'dsn-section' },
|
|
h('h3', { className: 'dsn-section-title' }, tr('config.section.kinds')),
|
|
KINDS.map((kind) => h(KindRow, {
|
|
key: kind,
|
|
label: tr(`settings.kind.${kind}`),
|
|
checked: snapshot.kinds[kind] === true,
|
|
disabled: false,
|
|
onToggle: () => props.setKind(kind, snapshot.kinds[kind] !== true),
|
|
})),
|
|
h('p', { className: 'dsn-section-desc' }, tr('config.saveNote'))),
|
|
h('section', { className: 'dsn-section' },
|
|
h('h3', { className: 'dsn-section-title' }, tr('config.section.permission')),
|
|
h('div', { className: 'dsn-row' },
|
|
h('div', { className: 'dsn-row-text' },
|
|
h('p', {
|
|
className: `dsn-status${failed ? ' dsn-status-error' : ''}`,
|
|
role: failed ? 'alert' : 'status',
|
|
}, permissionText)),
|
|
h('button', {
|
|
type: 'button',
|
|
className: 'dsn-button',
|
|
disabled: !supported,
|
|
onClick: permission === 'granted' ? props.test : props.ask,
|
|
}, tr(!supported
|
|
? 'settings.action.unsupported'
|
|
: permission === 'granted' ? 'settings.action.test' : 'settings.action.allow')))),
|
|
h('section', { className: 'dsn-section' },
|
|
h('h3', { className: 'dsn-section-title' }, tr('config.section.status')),
|
|
h('div', { className: 'dsn-row' },
|
|
h('div', { className: 'dsn-row-text' },
|
|
h('p', {
|
|
className: `dsn-status${healthFailed ? ' dsn-status-error' : ''}`,
|
|
role: healthFailed ? 'alert' : 'status',
|
|
}, healthText))))))
|
|
}
|
|
|
|
// ---------------------------------------------------------- registration
|
|
|
|
/** Keep the page's own focus events owned by this plugin's effect. */
|
|
const installBridges = () => {
|
|
const onFocusChange = () => {
|
|
state.lastDelivery = 0
|
|
}
|
|
try {
|
|
window.addEventListener('focus', onFocusChange)
|
|
window.addEventListener('blur', onFocusChange)
|
|
} catch {
|
|
/* an unreadable window still delivers through live focus reads */
|
|
}
|
|
return () => {
|
|
try {
|
|
window.removeEventListener('focus', onFocusChange)
|
|
window.removeEventListener('blur', onFocusChange)
|
|
} catch {
|
|
/* nothing to detach */
|
|
}
|
|
if (state.settleTimer !== 0) {
|
|
clearTimeout(state.settleTimer)
|
|
state.settleTimer = 0
|
|
}
|
|
for (const timer of timers.values()) clearTimeout(timer)
|
|
timers.clear()
|
|
}
|
|
}
|
|
|
|
ctx.effect(() => registerDictionaries(locale), 'session-notify: dictionaries')
|
|
ctx.effect(() => installBridges(), 'session-notify: window focus')
|
|
ctx.effect(() => () => {
|
|
disposed = true
|
|
}, 'session-notify: disposal')
|
|
|
|
ctx.slots.inject('shell.overlay', () => ctx.slots.register({
|
|
name: 'shell.overlay',
|
|
id: `${NS}-toasts`,
|
|
order: 100,
|
|
locale: NS,
|
|
inject: () => ({
|
|
store,
|
|
dismiss: closeToast,
|
|
arm: armToast,
|
|
hold: holdToast,
|
|
open: (sessionId) => {
|
|
focusWindow()
|
|
openSession(sessionId)
|
|
},
|
|
}),
|
|
}, ToastLayer))
|
|
|
|
// This plugin's configuration lives on its own page in the plugin manager,
|
|
// keyed by this package's name — the seat the shipped experimental bundle
|
|
// uses for its own settings, and the one the plugin page renders between the
|
|
// bundle's description and its rows. It is deliberately NOT a General
|
|
// settings row: a plugin's options belong to the plugin.
|
|
ctx.slots.inject('plugins.bundle.config', () => ctx.slots.register({
|
|
name: 'plugins.bundle.config',
|
|
key: PACKAGE_NAME,
|
|
locale: NS,
|
|
inject: () => ({
|
|
store,
|
|
platform: platformKey(),
|
|
ask: requestPermission,
|
|
test: sendTest,
|
|
setKind: setKindEnabled,
|
|
}),
|
|
}, ConfigSection))
|
|
|
|
// The observer lives in the frame-wide overlay, NOT in `sidebar.panellist`.
|
|
//
|
|
// That owner does not merely render its entries: it also reads WHICH entries
|
|
// exist and turns each one into a sidebar panel button (id → panel id, label
|
|
// → button text, the entry itself → the glyph). A renderless entry there is
|
|
// therefore an extra, empty panel row in the left column — which is exactly
|
|
// how this plugin broke the sidebar once. The overlay is the non-generic
|
|
// seat: it is a floating layer whose entries routinely render nothing, so a
|
|
// `null`-rendering observer is an ordinary occupant, and it carries the same
|
|
// root-scope standard props (`useSessions`, `useSessionStatus`).
|
|
ctx.slots.inject('shell.overlay', () => ctx.slots.register({
|
|
name: 'shell.overlay',
|
|
id: `${NS}-watch`,
|
|
order: 101,
|
|
}, NotifyObserver))
|
|
}
|
|
|
|
return {
|
|
inject: ['slots', 'locale'],
|
|
apply,
|
|
}
|
|
},
|
|
})
|