import * as React from 'react'; import { CredentialActionIcon, CredentialBindingPanel } from '../../credential-binding.js'; import { installDingtalkStyles } from '../dingtalk/styles.js'; const h = React.createElement; const Button = React.forwardRef(function Button( { children, kind = 'secondary', className = '', ...props }, ref, ) { return h('button', { ...props, ref, type: 'button', className: `ddt-button ${className}`.trim(), 'data-kind': kind, }, children); }); function checkedTime(value) { if (!value) return '尚未检查'; try { return new Intl.DateTimeFormat('zh-CN', { hour: '2-digit', minute: '2-digit', second: '2-digit', }).format(new Date(value)); } catch { return '刚刚'; } } export function createTokenChannelSettings(definition) { const { channel, endpoints, api, LogoGlyph, installStyles, pageClass, avatarClass, connectionLabel, tokenPlaceholder, emptyTitle, emptyDescription, platformLabel, } = definition; function AccountCard({ account, busy, removing, onReconnect, onRequestRemove, onConfirmRemove, onCancelRemove }) { const state = busy === 'reconnect' ? 'connecting' : account.state; const tone = account.connected ? 'success' : state === 'error' ? 'error' : 'warning'; const stateLabel = account.connected ? '运行正常' : state === 'connecting' ? '正在连接' : '连接未就绪'; const summary = account.error?.message ?? (account.connected ? null : account.health.summary); const identity = account.bot.username ? `@${account.bot.username}` : account.bot.idMasked; return h('article', { className: 'ddt-card dim-botCard', 'data-bot-id': account.botId }, h('div', { className: 'ddt-cardBody dim-botCardBody' }, h('div', { className: 'ddt-accountTop dim-botCardTop' }, h('div', { className: 'ddt-accountIdentity dim-botIdentity' }, h('div', { className: `ddt-avatar dim-botAvatar ${avatarClass}`, 'aria-hidden': 'true' }, h(LogoGlyph, { size: 29 })), h('div', { className: 'dim-botName' }, h('h3', null, account.bot.name), h('p', null, identity))), h('div', { className: 'ddt-health dim-botHealth' }, h('span', { className: 'ddt-dot dim-healthDot', 'data-tone': tone }), h('span', null, stateLabel))), h('dl', { className: 'ddt-metrics dim-botMetrics' }, h('div', { className: 'ddt-metric dim-botMetric' }, h('dt', null, '消息通道'), h('dd', null, account.connected ? connectionLabel : '离线')), h('div', { className: 'ddt-metric dim-botMetric' }, h('dt', null, '最近检查'), h('dd', null, checkedTime(account.health.lastCheckedAt)))), h('div', { className: 'ddt-accountFooter dim-cardFooter' }, summary ? h('div', { className: 'ddt-summary dim-cardSummary' }, summary) : null, h('div', { className: 'ddt-actions dim-cardActions' }, h(Button, { className: 'dim-cardAction', onClick: onReconnect, disabled: Boolean(busy), }, busy === 'reconnect' ? '检查中…' : account.connected ? '检查连接' : '重试连接'), h(Button, { className: 'dim-cardAction', kind: 'danger', onClick: onRequestRemove, disabled: Boolean(busy), }, '移除接入')))), removing ? h('div', { className: 'ddt-confirm dim-confirm', role: 'alertdialog' }, h('strong', null, `从 DeepSeek Harness 移除“${account.bot.name}”?`), h('p', null, `这会停止消息连接,并删除本机保存的 Bot Token、机器人配置及会话映射。${platformLabel}中的机器人不会被自动删除。`), h('div', { className: 'ddt-actions dim-viewActions' }, h(Button, { onClick: onCancelRemove, disabled: Boolean(busy) }, '保留机器人'), h(Button, { kind: 'danger', onClick: onConfirmRemove, disabled: Boolean(busy) }, busy === 'delete' ? '正在移除…' : '确认移除接入'))) : null); } function SettingsTab({ rpcCall }) { const [model, setModel] = React.useState({ phase: 'loading', bots: [], totals: { configured: 0, connected: 0 }, error: null, }); const [credentialOpen, setCredentialOpen] = React.useState(false); const [credentialError, setCredentialError] = React.useState(null); const [busy, setBusy] = React.useState(false); const [busyByBot, setBusyByBot] = React.useState({}); const [removeTarget, setRemoveTarget] = React.useState(null); const mounted = React.useRef(true); React.useEffect(() => { const disposeDingtalk = installDingtalkStyles(); const disposeChannel = installStyles(); mounted.current = true; return () => { mounted.current = false; disposeChannel(); disposeDingtalk(); }; }, []); const invoke = React.useCallback(async (endpoint, payload = {}, signal) => { if (typeof rpcCall !== 'function') throw new TypeError(`${channel} 设置页缺少 RPC 连接`); return api.unwrapRpcResult(await rpcCall(endpoint, payload, signal)); }, [rpcCall]); const loadStatus = React.useCallback(async ({ signal, silent = false } = {}) => { if (!silent && mounted.current) setModel((current) => ({ ...current, phase: 'loading', error: null })); try { const snapshot = api.normalizeSnapshot(await invoke(endpoints.status, {}, signal)); if (!mounted.current || signal?.aborted) return; setModel({ phase: 'ready', bots: snapshot.bots, totals: snapshot.totals, error: null }); } catch (error) { if (error?.name !== 'AbortError' && mounted.current && !signal?.aborted) { setModel((current) => ({ ...current, phase: silent ? current.phase : 'error', error: api.presentError(error), })); } } }, [invoke]); React.useEffect(() => { const controller = new AbortController(); void loadStatus({ signal: controller.signal }); return () => controller.abort(); }, [loadStatus]); React.useEffect(() => { if (model.phase !== 'ready') return undefined; const controller = new AbortController(); const timer = window.setInterval( () => void loadStatus({ signal: controller.signal, silent: true }), 15_000, ); return () => { controller.abort(); window.clearInterval(timer); }; }, [loadStatus, model.phase]); const bindCredentials = React.useCallback(async ({ secret }) => { setBusy(true); setCredentialError(null); try { const snapshot = api.normalizeSnapshot(await invoke(endpoints.bindCredentials, { token: secret })); if (!mounted.current) return; setModel({ phase: 'ready', bots: snapshot.bots, totals: snapshot.totals, error: null }); setCredentialOpen(false); } catch (error) { if (mounted.current) setCredentialError(api.presentError(error)); } finally { if (mounted.current) setBusy(false); } }, [invoke]); const botAction = React.useCallback(async (account, operation, endpoint, payload) => { setBusyByBot((current) => ({ ...current, [account.botId]: operation })); try { const snapshot = api.normalizeSnapshot(await invoke(endpoint, payload)); if (mounted.current) { setModel({ phase: 'ready', bots: snapshot.bots, totals: snapshot.totals, error: null }); } } finally { if (mounted.current) setBusyByBot((current) => { const next = { ...current }; delete next[account.botId]; return next; }); } }, [invoke]); const botList = model.bots.length > 0 ? h('section', { className: 'dim-listSection' }, h('div', { className: 'ddt-listHeading dim-listHeading' }, h('h3', null, `已接入的 ${channel} 机器人`)), h('ul', { className: 'ddt-list dim-botList' }, model.bots.map((account) => h('li', { key: account.botId }, h(AccountCard, { account, busy: busyByBot[account.botId], removing: removeTarget === account.botId, onReconnect: () => void botAction( account, 'reconnect', endpoints.reconnectBot, { botId: account.botId }, ), onRequestRemove: () => setRemoveTarget(account.botId), onCancelRemove: () => setRemoveTarget(null), onConfirmRemove: async () => { await botAction(account, 'delete', endpoints.deleteBot, { botId: account.botId, confirm: true, }); if (mounted.current) setRemoveTarget(null); }, }))))) : null; return h('section', { className: `ddt-page ${pageClass} dim-channelPage`, 'aria-label': `${channel} 设置`, }, h('div', { className: 'ddt-heading' }, h('div', { className: 'ddt-tools' }, h('div', { className: 'dim-bindActions' }, h(Button, { kind: 'credential', className: 'dim-credentialButton', onClick: () => { setCredentialOpen((value) => !value); setCredentialError(null); }, disabled: busy, 'aria-pressed': credentialOpen, 'aria-label': `使用 Bot Token 接入 ${channel} 机器人`, }, h(CredentialActionIcon), credentialOpen ? '收起凭据' : '手动接入')), model.totals.configured > 0 ? h('div', { className: 'ddt-badge dim-onlineBadge' }, h('span', null, `${model.totals.connected} / ${model.totals.configured} 在线`)) : null)), model.phase === 'loading' ? h('div', { className: 'ddt-card ddt-loading dim-surfaceCard dim-loadingView', 'aria-busy': 'true', }, h('div', { className: 'ddt-spinner dim-spinner' }), `正在读取 ${channel} 机器人状态…`) : model.phase === 'error' ? h('div', { className: 'ddt-card dim-surfaceCard' }, h('div', { className: 'ddt-inlineError dim-inlineError' }, h('h3', null, `无法读取 ${channel} 机器人状态`), h('p', null, model.error?.message), h(Button, { onClick: () => void loadStatus() }, '重新读取'))) : h(React.Fragment, null, credentialOpen ? h(CredentialBindingPanel, { channel, secretLabel: 'Bot Token', secretPlaceholder: tokenPlaceholder, busy, error: credentialError, onSubmit: bindCredentials, onCancel: () => { setCredentialOpen(false); setCredentialError(null); }, }) : null, model.bots.length === 0 && !credentialOpen ? h('div', { className: 'ddt-card dim-surfaceCard' }, h('div', { className: 'ddt-cardBody ddt-empty dim-surfaceBody dim-emptyView' }, h('div', { className: 'dim-emptyCopy' }, h('div', { className: 'ddt-stateLabel dim-stateLabel' }, h('span', { className: 'ddt-dot dim-stateDot' }), h('span', null, `尚未接入 ${channel} 机器人`)), h('h3', null, emptyTitle), h('p', null, emptyDescription), h('div', { className: 'ddt-actions dim-viewActions' }, h(Button, { kind: 'primary', onClick: () => setCredentialOpen(true), }, '填写 Bot Token'))), h('div', { className: `ddt-brandMark dim-emptyBrand ${avatarClass}`, 'aria-hidden': 'true', }, h(LogoGlyph, { size: 64 })))) : null, botList)); } return { SettingsTab, AccountCard }; }