dsh-ant 0.0.0-stage → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/client.js ADDED
@@ -0,0 +1,4086 @@
1
+ window.__ModuleLoader__.load({
2
+ id: 'dsh-ant',
3
+ factory: (require) => {
4
+ var module = { exports: {} }
5
+ var exports = module.exports
6
+ const { createElement, useEffect, useRef, useState } = require('react')
7
+ const ANT_LOCALE_MESSAGES_PATH = '/api/ant-teams/locale-messages'
8
+ const ANT_LOCALE_IDS = ['es-ES', 'de-DE', 'ja-JP', 'pt-BR']
9
+ const LOCALIZED_PROPS = new Set(['aria-label', 'placeholder', 'title', 'alt'])
10
+ const RAW_LOCALE_TEXT = Symbol('ant.raw-locale-text')
11
+ let localeRuntime = null
12
+ let localeMetadata = {}
13
+ let localeTranslate = (key) => key
14
+ let localeMessagePatterns = []
15
+ const escapeRegExp = (value) => value.replace(/[.*+?^${}()|[\]\\]/gu, '\\$&')
16
+ const compileLocalePattern = (source) => {
17
+ const names = []
18
+ const pattern = source.split(/(\{[a-zA-Z][a-zA-Z0-9_]*\})/gu).map((part) => {
19
+ const placeholder = /^\{([a-zA-Z][a-zA-Z0-9_]*)\}$/u.exec(part)
20
+ if (!placeholder) return escapeRegExp(part)
21
+ names.push(placeholder[1])
22
+ return '([\\s\\S]*?)'
23
+ }).join('')
24
+ return { source, names, regex: new RegExp(`^${pattern}$`, 'u') }
25
+ }
26
+ const translateLocaleText = (value, params = {}) => {
27
+ if (typeof value !== 'string') return value
28
+ const translated = localeTranslate(value, params)
29
+ if (translated !== value) return translated
30
+ for (const entry of localeMessagePatterns) {
31
+ const match = entry.regex.exec(value)
32
+ if (!match) continue
33
+ const params = Object.fromEntries(entry.names.map((name, index) => [name, match[index + 1]]))
34
+ return localeTranslate(entry.source, params)
35
+ }
36
+ return value
37
+ }
38
+ const rawLocaleText = (value) => ({ [RAW_LOCALE_TEXT]: true, value })
39
+ const formatLocale = () => localeMetadata[localeRuntime?.getLocale?.().active]?.formatLocale || 'en-US'
40
+ const formatLocaleDirection = () => localeMetadata[localeRuntime?.getLocale?.().active]?.direction || 'ltr'
41
+ const formatLocaleNumber = (value) => new Intl.NumberFormat(formatLocale()).format(value)
42
+ const formatLocaleDate = (value, options) => new Date(value).toLocaleString(formatLocale(), options)
43
+ const localizedChild = (value) => {
44
+ if (Array.isArray(value)) return value.map(localizedChild)
45
+ if (value?.[RAW_LOCALE_TEXT]) return value.value
46
+ return typeof value === 'string' ? translateLocaleText(value) : value
47
+ }
48
+ const h = (type, props, ...children) => {
49
+ const localizedProps = props && typeof props === 'object' ? { ...props } : props
50
+ if (localizedProps) {
51
+ for (const key of LOCALIZED_PROPS) {
52
+ if (typeof localizedProps[key] === 'string') localizedProps[key] = translateLocaleText(localizedProps[key])
53
+ }
54
+ }
55
+ return createElement(type, localizedProps, ...children.map(localizedChild))
56
+ }
57
+ const confirmLocalized = (message) => window.confirm(translateLocaleText(message))
58
+ const promptLocalized = (message, ...args) => window.prompt(translateLocaleText(message), ...args)
59
+ const useLocaleRevision = () => {
60
+ const [, refresh] = useState(() => localeRuntime?.getLocale?.().revision || 0)
61
+ useEffect(() => localeRuntime?.subscribe?.(() => {
62
+ refresh(localeRuntime.getLocale().revision)
63
+ }), [])
64
+ }
65
+ const compactOpenaiProviderName = (name) => {
66
+ const value = typeof name === 'string' ? name.trim() : ''
67
+ if (!value) return value
68
+ const suffix = /\s*(?:[·•::|—–-]\s*)?(?:Responses|Chat Completions)$/iu
69
+ return value.replace(suffix, '').trim() || 'OpenAI'
70
+ }
71
+ const SERVICE_URL_STORAGE_KEY = 'ant-team-service-url'
72
+ const BRANDING_CACHE_PREFIX = 'ant-team-branding:'
73
+ const BRANDING_SYNC_PATH = '/api/ant-teams/branding'
74
+ const PROVIDER_ROUTES_STORAGE_KEY = 'ant-team-provider-routes'
75
+ const PROVIDER_SYNC_EXCLUSIONS_KEY = 'ant-team-provider-sync-exclusions'
76
+ const IMAGE_INPUT_OPT_OUTS_KEY = 'ant-team-image-input-opt-outs'
77
+ const DEVICE_ID_STORAGE_KEY = 'ant-team-device-id'
78
+ const DEFAULT_MODEL_INITIALIZED_KEY = 'ant-team-default-model-initialized'
79
+ const ANT_BUNDLE_PACKAGE_NAME = 'dsh-ant'
80
+ const ANT_SETTINGS_PANEL_ID = 'ant-settings'
81
+ const ANT_SETTINGS_SECTION_ID = 'ant-team'
82
+ const ANT_API_PROTOCOL_VERSIONS = [1]
83
+ const PLUGIN_INSTALL_RECORD_PREFIX = 'ant-reviewed-plugin-install:'
84
+ const ANT_SETTINGS_TAB_STORAGE_KEY = 'ant-settings-tab'
85
+ const ANT_SETTINGS_TABS = [
86
+ ['connection', '团队连接'], ['models', '团队模型'], ['collaboration', '协作'],
87
+ ['local', '本机与任务'], ['updates', '关于'],
88
+ ]
89
+ const loadAntSettingsTab = () => {
90
+ try {
91
+ const saved = localStorage.getItem(ANT_SETTINGS_TAB_STORAGE_KEY)
92
+ if (saved === 'bot-chat' || saved === 'capability') return 'collaboration'
93
+ return ANT_SETTINGS_TABS.some(([id]) => id === saved) ? saved : 'connection'
94
+ } catch { return 'connection' }
95
+ }
96
+ const extensionCategories = [
97
+ ['office', '办公文档'], ['development', '编程开发'], ['design', '设计与多媒体'],
98
+ ['data', '数据分析'], ['collaboration', '协作沟通'], ['content', '写作与营销'],
99
+ ['automation', '自动化与效率'], ['operations', '运维与安全'], ['other', '其他'],
100
+ ]
101
+ const extensionCategoryLabels = Object.fromEntries(extensionCategories)
102
+ const legacyMarketSkillCategories = {
103
+ 'ant-ppt-master': 'office', 'ant-frontend-slides': 'design', 'ant-slidev': 'development',
104
+ 'ant-word-docx': 'office', 'ant-excel-xlsx': 'office', 'ant-pdf': 'office',
105
+ 'ant-internal-comms': 'collaboration', 'ant-formatted-report-writer': 'office',
106
+ 'ant-agent-browser': 'automation', 'ant-vercel-react-best-practices': 'development',
107
+ 'ant-vercel-composition-patterns': 'development', 'ant-supabase-postgres-best-practices': 'data',
108
+ 'ant-diagnosing-bugs': 'development', 'ant-improve-codebase-architecture': 'development',
109
+ 'ant-code-review': 'development', 'ant-systematic-debugging': 'development',
110
+ 'ant-test-driven-development': 'development', 'ant-verification-before-completion': 'development',
111
+ 'ant-writing-plans': 'development', 'ant-to-spec': 'development', 'ant-skill-creator': 'automation',
112
+ 'ant-frontend-design': 'design', 'ant-web-design-guidelines': 'design',
113
+ 'ant-ui-ux-pro-max': 'design', 'ant-emil-design-eng': 'design',
114
+ 'ant-review-animations': 'design', 'ant-shadcn': 'design',
115
+ 'ant-theme-factory': 'design', 'ant-brand-guidelines': 'design',
116
+ 'ant-copywriting': 'content', 'ant-seo-audit': 'content', 'ant-brainstorming': 'content',
117
+ }
118
+ const categoryOf = (entry) => extensionCategoryLabels[entry?.category]
119
+ ? entry.category : legacyMarketSkillCategories[entry?.dsh_name] || 'other'
120
+ const categoryLabel = (category) => extensionCategoryLabels[category] || extensionCategoryLabels.other
121
+ const officialOfficeGuide = 'https://github.com/deepseek-ai/deepseek-harness/blob/dsh-v0.2.1-rc.2/packages/skill/skill-office/README.zh.md'
122
+ const officialOfficeEnglish = (skill) => `https://github.com/deepseek-ai/deepseek-harness/blob/dsh-v${skill.since}/packages/skill/skill-office/assets/${skill.name}/SKILL.md`
123
+ const officialOfficeSkills = [
124
+ { name: 'office', title: 'Office 办公入口', category: 'office', since: '0.2.1-rc.2', description: '根据任务选择 Word、PPT、Excel 或文件处理能力。', prompt: '帮我完成这份办公文件' },
125
+ { name: 'office-docx', title: 'Word 文档', category: 'office', since: '0.2.0-rc.2', description: '创建、修改和检查 DOCX 文档。', prompt: '帮我写一份 Word 报告' },
126
+ { name: 'office-pptx', title: 'PPT 演示', category: 'office', since: '0.2.0-rc.2', description: '创建、修改和检查 PPTX 演示文稿。', prompt: '帮我做一份项目汇报 PPT' },
127
+ { name: 'office-xlsx', title: 'Excel 表格', category: 'office', since: '0.2.0-rc.2', description: '创建、修改和检查 XLSX 工作簿。', prompt: '帮我整理这份 Excel 表格' },
128
+ { name: 'office-render', title: '文件预览', category: 'office', since: '0.2.1-rc.2', description: '把 Office 文件渲染成图片,检查实际外观。', prompt: '请预览这份文档并检查排版' },
129
+ { name: 'office-recalculate', title: '公式重算', category: 'office', since: '0.2.1-rc.2', description: '重新计算表格公式并核对结果。', prompt: '请重新计算这份表格的公式' },
130
+ { name: 'office-export-pdf', title: '导出 PDF', category: 'office', since: '0.2.1-rc.2', description: '将 Office 文件导出为 PDF。', prompt: '把这份 Word 文档导出成 PDF' },
131
+ ]
132
+ const curatedSkillIntroductions = {
133
+ "ant-ppt-master": {"ref": "c350bc31e6d43b7bcf5234183d650ba8f9f4c9d7", "description": "制作和编辑 PowerPoint 演示文稿。"},
134
+ "ant-frontend-slides": {"ref": "9906a34d640d2111f724544cbc50f7f130569ae1", "description": "制作浏览器中的动态 HTML 演示文稿。"},
135
+ "ant-slidev": {"ref": "73053ab2b9653ed475960301b56e1ce4439d9c75", "description": "用 Markdown 制作技术演示文稿。"},
136
+ "ant-word-docx": {"ref": "1.0.2", "description": "创建、阅读和修改 Word 文档,尽量保留原有样式。"},
137
+ "ant-excel-xlsx": {"ref": "1.0.2", "description": "分析和修改 Excel 表格、公式与格式。"},
138
+ "ant-pdf": {"ref": "6e9b3e3b8852f12bf965f888213470574b72803e", "description": "读取、创建、合并和处理 PDF 与表单。"},
139
+ "ant-internal-comms": {"ref": "dbd4588f9e1033efb41dad4bef2f7947c8993d44", "description": "撰写内部通知、项目更新、FAQ 和周报。"},
140
+ "ant-formatted-report-writer": {"ref": "97a13607d669157a4a16d5ba79b77f208319f7b9", "description": "把分析材料整理成结构清楚的业务报告。"},
141
+ "ant-agent-browser": {"ref": "dac13bb87468fe9d74a040d862720f6cc17a9565", "description": "操作网页、截图和页面检查。"},
142
+ "ant-vercel-react-best-practices": {"ref": "063bee94c3f4df8453406c830b0a7df0f2860278", "description": "优化 React 与 Next.js 性能。"},
143
+ "ant-vercel-composition-patterns": {"ref": "063bee94c3f4df8453406c830b0a7df0f2860278", "description": "设计可复用 React 组件。"},
144
+ "ant-supabase-postgres-best-practices": {"ref": "c9be0e931b7930f7d02126d04774d904c381e7d7", "description": "改进 SQL、索引、迁移和数据库安全。"},
145
+ "ant-diagnosing-bugs": {"ref": "5beb35b040e3de97e54fa9e386d7e42d15c295c2", "description": "建立复现信号并定位问题根因。"},
146
+ "ant-improve-codebase-architecture": {"ref": "5beb35b040e3de97e54fa9e386d7e42d15c295c2", "description": "识别模块耦合和重构机会。"},
147
+ "ant-code-review": {"ref": "5beb35b040e3de97e54fa9e386d7e42d15c295c2", "description": "按规范和原始需求审查代码差异。"},
148
+ "ant-systematic-debugging": {"ref": "bb92a77741419a4ab5f06e711a283343f1ada0c3", "description": "先找根因,再修改和复核。"},
149
+ "ant-test-driven-development": {"ref": "bb92a77741419a4ab5f06e711a283343f1ada0c3", "description": "先建立失败样例,再实现和重构。"},
150
+ "ant-verification-before-completion": {"ref": "bb92a77741419a4ab5f06e711a283343f1ada0c3", "description": "交付前用实际证据核对结论。"},
151
+ "ant-writing-plans": {"ref": "bb92a77741419a4ab5f06e711a283343f1ada0c3", "description": "将已明确需求拆成可执行计划。"},
152
+ "ant-to-spec": {"ref": "5beb35b040e3de97e54fa9e386d7e42d15c295c2", "description": "把已有讨论整理为产品和实现规格。"},
153
+ "ant-skill-creator": {"ref": "dbd4588f9e1033efb41dad4bef2f7947c8993d44", "description": "设计、打包和评估新技能。"},
154
+ "ant-frontend-design": {"ref": "dbd4588f9e1033efb41dad4bef2f7947c8993d44", "description": "设计更有辨识度的网页界面。"},
155
+ "ant-web-design-guidelines": {"ref": "063bee94c3f4df8453406c830b0a7df0f2860278", "description": "检查 UI、可访问性和交互细节。"},
156
+ "ant-ui-ux-pro-max": {"ref": "56ea9cf174ed86786187daa9de0e6247cb0747e4", "description": "检索配色、排版、动效和界面规则。"},
157
+ "ant-emil-design-eng": {"ref": "2d228630ba1446365f614a108cb8252f1feda202", "description": "改进界面动效、组件和交互细节。"},
158
+ "ant-review-animations": {"ref": "2d228630ba1446365f614a108cb8252f1feda202", "description": "按照原作者的标准检查动效实现。"},
159
+ "ant-shadcn": {"ref": "ba1503c64472b82256d9de95e2e62c5901a38e8b", "description": "搜索、组合和调整 shadcn/ui 组件。"},
160
+ "ant-theme-factory": {"ref": "dbd4588f9e1033efb41dad4bef2f7947c8993d44", "description": "为文档、页面和演示选择主题。"},
161
+ "ant-brand-guidelines": {"ref": "dbd4588f9e1033efb41dad4bef2f7947c8993d44", "description": "原作者自己的品牌色和字体规范。"},
162
+ "ant-copywriting": {"ref": "365b412152b9542499ca1439426f7fc3cc92bb65", "description": "撰写和改进页面、广告与产品文案。"},
163
+ "ant-seo-audit": {"ref": "365b412152b9542499ca1439426f7fc3cc92bb65", "description": "诊断网站搜索可见性与页面问题。"},
164
+ "ant-brainstorming": {"ref": "bb92a77741419a4ab5f06e711a283343f1ada0c3", "description": "澄清需求、比较方案和形成设计。"},
165
+ }
166
+ const hasChineseIntroduction = (value) => {
167
+ const text = typeof value === 'string' ? value : ''
168
+ const han = (text.match(/[\u3400-\u9fff]/gu) || []).length
169
+ return han >= 2 && han * 5 >= (text.match(/[A-Za-z]/gu) || []).length
170
+ }
171
+ const curatedSkillIntroduction = (skill) => {
172
+ const item = curatedSkillIntroductions[skill.dsh_name]
173
+ return item && item.ref === skill.source_ref ? item.description : null
174
+ }
175
+ const genericSkillIntroduction = '这项技能尚未提供中文介绍。请查看英文原文,或联系企业管理员补充。'
176
+ const skillIntroduction = (skill) => hasChineseIntroduction(skill.description)
177
+ ? skill.description : curatedSkillIntroduction(skill) || genericSkillIntroduction
178
+ const skillIntroductionDisplay = (skill, description) => description === genericSkillIntroduction
179
+ || description === curatedSkillIntroduction(skill) ? description : rawLocaleText(description)
180
+ const skillEnglishSource = (skill) => {
181
+ let url
182
+ try { url = new URL(skill.source_url) } catch { return null }
183
+ if (url.protocol !== 'https:' || url.username || url.password) return null
184
+ const parts = url.pathname.split('/').filter(Boolean)
185
+ const fixedRef = /^[a-f0-9]{40}$/iu.test(skill.source_ref || '') ? skill.source_ref : null
186
+ if (url.hostname === 'github.com' && parts.length >= 4 && parts[2] === 'tree' && fixedRef) {
187
+ return `https://github.com/${parts[0]}/${parts[1]}/blob/${fixedRef}/${parts.slice(4).join('/')}${parts.length > 4 ? '/' : ''}SKILL.md`
188
+ }
189
+ return null
190
+ }
191
+ const skillCategory = (skill) => categoryOf(skill)
192
+ const panelStyle = {
193
+ display: 'grid', alignContent: 'start', gap: 14, padding: 18,
194
+ border: '0.5px solid var(--dsw-alias-border-l2)', borderRadius: 14,
195
+ backgroundColor: 'var(--dsw-alias-bg-module-platform)', boxSizing: 'border-box',
196
+ }
197
+ const settingsPanelStyle = { ...panelStyle, border: '1px solid var(--dsw-alias-border-l2)', backgroundColor: 'var(--dsw-alias-bg-layer-1)' }
198
+ const infoNoticeStyle = {
199
+ display: 'grid', gap: 3, padding: '9px 11px', borderRadius: 8,
200
+ backgroundColor: 'var(--dsw-alias-state-business-tertiary)',
201
+ borderLeft: '3px solid var(--dsw-alias-state-business-primary)',
202
+ }
203
+ const warningNoticeStyle = {
204
+ display: 'grid', gap: 4, padding: '9px 11px', borderRadius: 8,
205
+ backgroundColor: 'var(--dsw-alias-state-warning-tertiary, var(--dsw-alias-bg-layer-2))',
206
+ borderLeft: '3px solid var(--dsw-alias-state-warning-primary, var(--dsw-alias-border-l2))',
207
+ }
208
+ const mutedTextStyle = { margin: 0, color: 'var(--dsw-alias-label-secondary)', fontSize: 13, lineHeight: 1.6 }
209
+ const feedbackNoticeStyle = { ...mutedTextStyle, position: 'sticky', top: 0, zIndex: 8,
210
+ padding: '9px 12px', border: '1px solid var(--dsw-alias-border-l2)', borderRadius: 8,
211
+ backgroundColor: 'var(--dsw-alias-bg-base)', boxShadow: '0 4px 14px #173d3510', overflowWrap: 'anywhere' }
212
+ const sectionTitleStyle = { margin: 0, fontSize: 16, fontWeight: 650, lineHeight: 1.4 }
213
+ const inputStyle = {
214
+ width: '100%', boxSizing: 'border-box', padding: '10px 12px',
215
+ color: 'var(--dsw-alias-label-primary)', backgroundColor: 'var(--dsw-specific-input-major)',
216
+ border: '0.5px solid var(--dsw-alias-border-l3)', borderRadius: 8,
217
+ }
218
+ const primaryButtonStyle = {
219
+ minHeight: 40, padding: '9px 14px', color: 'var(--dsw-alias-label-primary-foreground)', fontWeight: 600,
220
+ backgroundColor: 'var(--dsw-alias-state-business-primary)',
221
+ border: '0.5px solid var(--dsw-alias-state-business-primary)', borderRadius: 8,
222
+ cursor: 'pointer', whiteSpace: 'nowrap',
223
+ }
224
+ const secondaryButtonStyle = {
225
+ minHeight: 40, padding: '9px 14px', color: 'var(--dsw-alias-label-primary)', fontWeight: 500,
226
+ backgroundColor: 'var(--dsw-alias-button-primary-dimmed)',
227
+ border: '0.5px solid var(--dsw-alias-border-l2)', borderRadius: 8,
228
+ cursor: 'pointer',
229
+ }
230
+ const categoryButtonStyle = { ...secondaryButtonStyle, minHeight: 34, padding: '6px 12px', whiteSpace: 'nowrap' }
231
+ function ExtensionRequestNotice() {
232
+ return h('aside', { role: 'note', style: {
233
+ display: 'flex', alignItems: 'baseline', gap: 8, padding: '9px 12px',
234
+ borderRadius: 8, backgroundColor: 'var(--dsw-alias-bg-layer-2)',
235
+ color: 'var(--dsw-alias-label-secondary)', fontSize: 13, lineHeight: 1.6,
236
+ } },
237
+ h('strong', { style: { flexShrink: 0, color: 'var(--dsw-alias-label-primary)' } }, '提示'),
238
+ h('span', null, '没有找到想用的扩展,或插件没有安装按钮?联系企业管理员,说明用途或提供地址。已开放的扩展可直接安装;未经审核的版本请勿自行安装。'))
239
+ }
240
+ const normalizeServiceUrl = (value) => {
241
+ let url
242
+ try { url = new URL(value.trim()) } catch { return null }
243
+ const localHttp = url.protocol === 'http:' && ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname)
244
+ if ((url.protocol !== 'https:' && !localHttp) || url.username || url.password || url.search || url.hash || (url.pathname !== '/' && url.pathname !== '')) return null
245
+ return url.origin
246
+ }
247
+ const consoleUrl = (value) => {
248
+ const normalized = normalizeServiceUrl(value)
249
+ return normalized ? new URL('/console', normalized).toString() : null
250
+ }
251
+ const versionParts = (value) => {
252
+ if (typeof value !== 'string') return null
253
+ const match = /^(\d+)\.(\d+)\.(\d+)(?:-((?:0|[1-9]\d*|[0-9A-Za-z-]*[A-Za-z-][0-9A-Za-z-]*)(?:\.(?:0|[1-9]\d*|[0-9A-Za-z-]*[A-Za-z-][0-9A-Za-z-]*))*))?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/u.exec(value)
254
+ if (!match) return null
255
+ return { core: match.slice(1, 4), prerelease: match[4]?.split('.') ?? null }
256
+ }
257
+ const compareNumericVersionIdentifiers = (left, right) => {
258
+ const normalizedLeft = left.replace(/^0+(?=\d)/u, '')
259
+ const normalizedRight = right.replace(/^0+(?=\d)/u, '')
260
+ if (normalizedLeft.length !== normalizedRight.length) return normalizedLeft.length < normalizedRight.length ? -1 : 1
261
+ return normalizedLeft === normalizedRight ? 0 : normalizedLeft < normalizedRight ? -1 : 1
262
+ }
263
+ const newerVersion = (candidate, current) => {
264
+ const next = versionParts(candidate)
265
+ const installed = versionParts(current)
266
+ if (!next || !installed) return false
267
+ for (let index = 0; index < next.core.length; index += 1) {
268
+ const order = compareNumericVersionIdentifiers(next.core[index], installed.core[index])
269
+ if (order !== 0) return order > 0
270
+ }
271
+ if (!next.prerelease) return Boolean(installed.prerelease)
272
+ if (!installed.prerelease) return false
273
+ for (let index = 0; index < Math.max(next.prerelease.length, installed.prerelease.length); index += 1) {
274
+ const nextIdentifier = next.prerelease[index]
275
+ const installedIdentifier = installed.prerelease[index]
276
+ if (nextIdentifier === undefined) return false
277
+ if (installedIdentifier === undefined) return true
278
+ if (nextIdentifier === installedIdentifier) continue
279
+ const nextIsNumeric = /^\d+$/u.test(nextIdentifier)
280
+ const installedIsNumeric = /^\d+$/u.test(installedIdentifier)
281
+ if (nextIsNumeric && installedIsNumeric) {
282
+ return compareNumericVersionIdentifiers(nextIdentifier, installedIdentifier) > 0
283
+ }
284
+ if (nextIsNumeric !== installedIsNumeric) return !nextIsNumeric
285
+ return nextIdentifier > installedIdentifier
286
+ }
287
+ return false
288
+ }
289
+ function safeInstallDiagnostic(value) {
290
+ const text = typeof value === 'string' ? value
291
+ : [value?.name, value?.code, value?.message].filter((part) => part != null).join(' ')
292
+ return String(text || '')
293
+ .replace(/\b(Bearer|Basic)\s+[^\s,;]+/giu, '$1 [REDACTED]')
294
+ .replace(/([?&](?:access[_-]?token|refresh[_-]?token|token|api[_-]?key|secret|password|signature|authorization)=)[^&#\s]*/giu, '$1[REDACTED]')
295
+ .replace(/(["']?(?:access[_-]?token|refresh[_-]?token|token|api[_-]?key|client[_-]?secret|secret|password|authorization)["']?\s*[:=]\s*["']?)[^,"';\s}]+/giu, '$1[REDACTED]')
296
+ .replace(/(https?:\/\/)[^/\s?#@]+:[^@\s/]+@/giu, '$1[REDACTED]@')
297
+ .slice(0, 180)
298
+ }
299
+ const inject = ['slots', 'layout', 'pluginNavigation', 'remote', 'remote.credentials', 'remote.settings', 'remote.pluginManager', 'locale']
300
+
301
+ async function readLocalJsonResponse(response) {
302
+ if (response.status === 204) return null
303
+ const contentType = response.headers?.get?.('content-type') || ''
304
+ const isJson = /^(?:application|text)\/(?:[a-z0-9!#$&^_.+-]+\+)?json(?:\s*;|$)/iu.test(contentType.trim())
305
+ if (contentType && !isJson) {
306
+ if (response.status === 404) {
307
+ throw new Error('DSH 未找到 ANT 本地接口。请确认 ANT Bundle 已更新,并完全退出后重新启动 DSH。')
308
+ }
309
+ throw new Error(`DSH 返回了非 JSON 响应(HTTP ${response.status})。`)
310
+ }
311
+ try {
312
+ return await response.json()
313
+ } catch {
314
+ if (response.status === 404) {
315
+ throw new Error('DSH 未找到 ANT 本地接口。请确认 ANT Bundle 已更新,并完全退出后重新启动 DSH。')
316
+ }
317
+ throw new Error(`DSH 返回的 ANT 响应格式无效(HTTP ${response.status})。`)
318
+ }
319
+ }
320
+
321
+ function directInstallSpec(release) {
322
+ return release?.version && release?.package_name
323
+ ? `${release.package_name}@${release.version}`
324
+ : ''
325
+ }
326
+
327
+ function approvedArtifactUrl(release) {
328
+ const expectedPath = `/api/ant-bundles/${ANT_BUNDLE_PACKAGE_NAME === 'dsh-ant' ? 'dsh-ant/' : ''}${release?.version}/package.tgz`
329
+ let url
330
+ try { url = new URL(release?.artifact_url) } catch { return null }
331
+ return normalizeServiceUrl(url.origin) === url.origin
332
+ && !url.username && !url.password && !url.search && !url.hash
333
+ && url.pathname === expectedPath && release?.artifact_path === expectedPath
334
+ && /^[a-f0-9]{64}$/u.test(release?.artifact_sha256 || '')
335
+ ? url.href : null
336
+ }
337
+
338
+ function approvedPluginArtifactUrl(plugin) {
339
+ if (plugin?.status !== 'published' || typeof plugin.id !== 'string'
340
+ || !/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/iu.test(plugin.id)) return null
341
+ const expectedPath = `/api/plugin-artifacts/${plugin.id}/package.tgz`
342
+ let url
343
+ try { url = new URL(plugin.artifact_url) } catch { return null }
344
+ return normalizeServiceUrl(url.origin) === url.origin
345
+ && !url.username && !url.password && !url.search && !url.hash
346
+ && url.pathname === expectedPath && plugin.artifact_path === expectedPath
347
+ && /^[a-f0-9]{64}$/u.test(plugin.artifact_sha256 || '')
348
+ ? url.href : null
349
+ }
350
+
351
+ function pluginInstallSpec(plugin) {
352
+ if (plugin?.status !== 'published' || typeof plugin.package_name !== 'string'
353
+ || typeof plugin.version !== 'string' || !plugin.package_name || !plugin.version) return ''
354
+ return approvedPluginArtifactUrl(plugin) || directInstallSpec(plugin)
355
+ }
356
+
357
+ function previouslyInstalledReviewedPlugin(plugin) {
358
+ try { return localStorage.getItem(`${PLUGIN_INSTALL_RECORD_PREFIX}${plugin.id}`) === plugin.artifact_sha256 }
359
+ catch { return false }
360
+ }
361
+
362
+ function loadServiceUrl() {
363
+ try { return normalizeServiceUrl(localStorage.getItem(SERVICE_URL_STORAGE_KEY) || '') || '' } catch { return '' }
364
+ }
365
+
366
+ function savedDeviceId() {
367
+ try {
368
+ const existing = localStorage.getItem(DEVICE_ID_STORAGE_KEY)
369
+ return existing && /^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/iu.test(existing) ? existing : null
370
+ } catch { return null }
371
+ }
372
+
373
+ function loadDeviceId() {
374
+ const existing = savedDeviceId()
375
+ if (existing) return existing
376
+ const deviceId = crypto.randomUUID()
377
+ localStorage.setItem(DEVICE_ID_STORAGE_KEY, deviceId)
378
+ return deviceId
379
+ }
380
+
381
+ function imageInputOptOutPreferenceKey(rawServiceUrl) {
382
+ const normalized = normalizeServiceUrl(rawServiceUrl)
383
+ return normalized ? `${IMAGE_INPUT_OPT_OUTS_KEY}:${normalized}:${savedDeviceId() || ''}` : null
384
+ }
385
+
386
+ function readImageInputOptOuts(rawServiceUrl) {
387
+ const key = imageInputOptOutPreferenceKey(rawServiceUrl)
388
+ if (!key) return []
389
+ try {
390
+ const value = JSON.parse(localStorage.getItem(key) || '[]')
391
+ return Array.isArray(value) ? value.filter((item) => typeof item === 'string') : []
392
+ } catch { return [] }
393
+ }
394
+
395
+ function saveImageInputOptOuts(rawServiceUrl, modelKeys) {
396
+ const key = imageInputOptOutPreferenceKey(rawServiceUrl)
397
+ if (!key) return
398
+ try { localStorage.setItem(key, JSON.stringify([...new Set(modelKeys)])) } catch {}
399
+ }
400
+
401
+ function TeamServiceConfig({ remote, openInstalledPlugin }) {
402
+ useLocaleRevision()
403
+ const [activeTab, setActiveTab] = useState(loadAntSettingsTab)
404
+ const [serviceUrl, setServiceUrl] = useState(loadServiceUrl)
405
+ const [draft, setDraft] = useState(serviceUrl)
406
+ const [binding, setBinding] = useState({ state: 'checking', url: null })
407
+ const bindingRevision = useRef(0)
408
+ const [message, setMessage] = useState('')
409
+ const [pluginAlerts, setPluginAlerts] = useState([])
410
+ const [delegationRevision, setDelegationRevision] = useState(0)
411
+ const [updateSummary, setUpdateSummary] = useState(null)
412
+ const selectSettingsTab = (tab) => {
413
+ setActiveTab(tab)
414
+ try { localStorage.setItem(ANT_SETTINGS_TAB_STORAGE_KEY, tab) } catch {}
415
+ }
416
+ const moveSettingsTabFocus = (event, index) => {
417
+ const key = event.key
418
+ if (!['ArrowLeft', 'ArrowRight', 'Home', 'End'].includes(key)) return
419
+ event.preventDefault()
420
+ const step = key === 'ArrowLeft' ? -1 : key === 'ArrowRight' ? 1 : 0
421
+ const next = key === 'Home' ? 0 : key === 'End' ? ANT_SETTINGS_TABS.length - 1
422
+ : (index + step + ANT_SETTINGS_TABS.length) % ANT_SETTINGS_TABS.length
423
+ const [tab] = ANT_SETTINGS_TABS[next]
424
+ selectSettingsTab(tab)
425
+ event.currentTarget.parentElement?.querySelectorAll('[role="tab"]')?.[next]?.focus()
426
+ }
427
+ const updateNeedsAttention = ['available', 'artifact-missing', 'revoked', 'migration-required',
428
+ 'unknown', 'failed', 'installing', 'done'].includes(updateSummary?.state)
429
+ || updateSummary?.dshCompatibility?.state === 'incompatible'
430
+ const aboutNeedsAttention = updateNeedsAttention
431
+ || ['unknown', 'untested'].includes(updateSummary?.dshCompatibility?.state)
432
+ const aboutAttentionIsCritical = updateSummary?.state === 'revoked'
433
+ || updateSummary?.dshCompatibility?.state === 'incompatible'
434
+ useEffect(() => {
435
+ let disposed = false
436
+ const revision = bindingRevision.current
437
+ const current = () => !disposed && bindingRevision.current === revision
438
+ const inspectBinding = async () => {
439
+ try {
440
+ const response = await fetch('/api/ant-teams/connection-origin', { cache: 'no-store' })
441
+ const result = await readLocalJsonResponse(response)
442
+ if (!response.ok) throw new Error()
443
+ const pinned = result.service_url == null ? null : normalizeServiceUrl(result.service_url)
444
+ if (result.service_url != null && !pinned) throw new Error()
445
+ if (pinned) {
446
+ if (current()) {
447
+ setBinding({ state: 'ready', url: pinned })
448
+ setServiceUrl(pinned)
449
+ setDraft(pinned)
450
+ try { localStorage.setItem(SERVICE_URL_STORAGE_KEY, pinned) } catch {}
451
+ }
452
+ return
453
+ }
454
+ const described = await remote?.credentials?.describe?.(['ANT_MODEL_API_KEY'])
455
+ if (!described?.ok) throw new Error()
456
+ if (current()) setBinding({ state: described.value?.ANT_MODEL_API_KEY?.configured ? 'unverified' : 'ready', url: null })
457
+ } catch { if (current()) setBinding({ state: 'error', url: null }) }
458
+ }
459
+ void inspectBinding()
460
+ return () => { disposed = true }
461
+ }, [remote])
462
+ useEffect(() => {
463
+ let disposed = false
464
+ const inspect = async () => {
465
+ try {
466
+ const response = await fetch('/api/ant-teams/plugins', { cache: 'no-store' })
467
+ if (!response.ok) return
468
+ const catalog = await readLocalJsonResponse(response)
469
+ const listed = await remote?.pluginManager?.listBundles?.()
470
+ if (!listed?.ok || !Array.isArray(catalog.plugins)) return
471
+ const affected = catalog.plugins.flatMap((plugin) => {
472
+ if (plugin.status !== 'security_withdrawn') return []
473
+ const local = listed.value.find((bundle) => bundle.installed && bundle.name === plugin.package_name)
474
+ if (!local || (local.version && local.version !== plugin.version)) return []
475
+ return [{ ...plugin, versionUnknown: !local.version }]
476
+ })
477
+ if (!disposed) setPluginAlerts(affected)
478
+ } catch {}
479
+ }
480
+ void inspect()
481
+ const timer = setInterval(() => void inspect(), 5 * 60 * 1000)
482
+ return () => { disposed = true; clearInterval(timer) }
483
+ }, [remote])
484
+ const save = (event) => {
485
+ event.preventDefault()
486
+ if (binding.state !== 'ready' || binding.url) {
487
+ setMessage(binding.url ? '当前已连接团队;切换前请先在下方断开当前设备。' : '尚未核对这台 DSH 的团队绑定,不能修改地址。')
488
+ return
489
+ }
490
+ const normalized = normalizeServiceUrl(draft)
491
+ if (!normalized) {
492
+ setMessage('请输入 HTTPS 团队服务地址;本机测试可使用 localhost。')
493
+ return
494
+ }
495
+ try {
496
+ localStorage.setItem(SERVICE_URL_STORAGE_KEY, normalized)
497
+ setServiceUrl(normalized)
498
+ setDraft(normalized)
499
+ setMessage('团队服务地址已保存。')
500
+ } catch {
501
+ setMessage('浏览器无法保存此地址,请检查本地存储权限。')
502
+ }
503
+ }
504
+ const link = binding.state === 'ready' ? consoleUrl(binding.url || serviceUrl) : null
505
+ const bindingSummary = binding.state === 'checking' ? '正在确认这台 DSH 的团队连接…'
506
+ : binding.state === 'error' ? '暂时无法确认团队连接状态'
507
+ : binding.state === 'unverified' ? '本机有 ANT 凭证,但设备归属待核对'
508
+ : binding.url ? `团队服务已连接 · ${new URL(binding.url).host}` : '尚未连接团队服务'
509
+ const bindingReadyForSummary = binding.state === 'ready' && Boolean(binding.url)
510
+ const onConnectionChange = (url) => {
511
+ bindingRevision.current += 1
512
+ setBinding({ state: 'ready', url: url || null })
513
+ setDelegationRevision((value) => value + 1)
514
+ if (url) {
515
+ setServiceUrl(url)
516
+ setDraft(url)
517
+ try { localStorage.setItem(SERVICE_URL_STORAGE_KEY, url) } catch {}
518
+ }
519
+ }
520
+ const teamServicePanel = h('section', { style: { ...settingsPanelStyle, display: activeTab === 'connection' ? 'grid' : 'none' } },
521
+ h('div', null,
522
+ h('h3', { style: sectionTitleStyle }, '团队服务'),
523
+ h('p', { style: { ...mutedTextStyle, marginTop: 4 } }, '由团队管理员提供服务地址;管理员可在控制台管理成员、模型和协作设置。')),
524
+ h('form', { onSubmit: save, style: { display: 'grid', gridTemplateColumns: binding.url ? '1fr' : 'minmax(0, 1fr) auto', alignItems: 'end', gap: 10 } },
525
+ h('label', { htmlFor: 'ant-team-service-url', style: { gridColumn: '1 / -1', fontSize: 13, fontWeight: 550 } }, binding.url ? '当前连接的团队服务地址' : '服务地址'),
526
+ h('input', { id: 'ant-team-service-url', type: 'url', required: true, value: binding.url || draft,
527
+ readOnly: binding.state !== 'ready' || Boolean(binding.url), placeholder: 'https://ant.example.com',
528
+ onChange: (event) => { if (binding.state === 'ready' && !binding.url) setDraft(event.target.value) }, style: inputStyle }),
529
+ binding.url ? null : h('button', { type: 'submit', disabled: binding.state !== 'ready', style: primaryButtonStyle }, '保存地址')),
530
+ binding.url ? h('p', { style: mutedTextStyle }, '若要切换团队,请先在下方断开当前设备,再填写新地址并验证邮箱。') : null,
531
+ binding.state === 'checking' ? h('p', { role: 'status', style: mutedTextStyle }, '正在核对这台 DSH 绑定的团队…') : null,
532
+ binding.state === 'unverified' ? h('p', { role: 'status', style: mutedTextStyle }, '本机仍有 ANT 凭证,但无法核对所属团队。请联系原团队管理员核查并撤销旧设备;确认后可在下方断开或仅清理本机。') : null,
533
+ binding.state === 'error' ? h('p', { role: 'status', style: mutedTextStyle }, '暂时无法核对这台 DSH 的团队绑定,请重新打开 ANT 或联系管理员。') : null,
534
+ message ? h('p', { role: 'status', style: feedbackNoticeStyle }, message) : null,
535
+ link ? h('a', { href: link, target: '_blank', rel: 'noopener noreferrer', style: { color: 'var(--dsw-alias-link)', fontSize: 13 } }, '打开团队管理 ↗') : null)
536
+ return h('section', { dir: formatLocaleDirection(), style: { display: 'grid', gap: 16, width: '100%', maxWidth: 1120 } },
537
+ h('div', { style: { display: 'grid', gap: 4 } },
538
+ h('h2', { style: { margin: 0, fontSize: 20, fontWeight: 650, lineHeight: 1.35 } }, '团队与协作'),
539
+ h('p', { style: mutedTextStyle }, '管理团队连接、机器人聊天入口和本机任务授权。日常聊天保持自然;执行能力按你开放的范围核验。')),
540
+ h('div', { role: 'status', style: { display: 'flex', alignItems: 'center', justifyContent: 'space-between',
541
+ flexWrap: 'wrap', gap: 10, padding: '10px 12px', borderRadius: 8,
542
+ backgroundColor: bindingReadyForSummary ? 'var(--dsw-alias-state-success-tertiary)' : 'var(--dsw-alias-bg-layer-2)' } },
543
+ h('span', null, bindingSummary),
544
+ !bindingReadyForSummary ? h('button', { type: 'button', onClick: () => selectSettingsTab('connection'),
545
+ style: secondaryButtonStyle }, binding.state === 'error' ? '检查连接' : '查看连接设置')
546
+ : activeTab === 'connection' ? h('button', { type: 'button', onClick: () => selectSettingsTab('collaboration'),
547
+ style: secondaryButtonStyle }, '设置或管理机器人') : null),
548
+ h('div', { style: { position: 'sticky', top: 0, zIndex: 8, display: 'grid', gap: 8, padding: '6px 0',
549
+ backgroundColor: 'var(--dsw-alias-bg-base)' } },
550
+ pluginAlerts.length ? h('section', { role: 'alert', style: { ...settingsPanelStyle,
551
+ borderColor: 'var(--dsw-alias-label-danger, #d44)', maxHeight: '28vh', overflowY: 'auto' } },
552
+ h('h3', { style: sectionTitleStyle }, '已安装插件存在安全撤回公告'),
553
+ ...pluginAlerts.map((plugin) => h('p', { key: plugin.id, style: mutedTextStyle },
554
+ `${plugin.title} ${plugin.version}${plugin.versionUnknown ? '(本机版本暂无法读取,请核对是否受影响)' : ''}:${plugin.withdrawal_reason}`)),
555
+ ...pluginAlerts.map((plugin) => h('button', { key: `${plugin.id}-open`, type: 'button',
556
+ onClick: () => openInstalledPlugin(plugin.package_name), style: secondaryButtonStyle }, `在 DSH 中查看 ${plugin.title}`))) : null,
557
+ updateNeedsAttention ? h('section', { role: 'status', 'aria-live': 'polite', style: {
558
+ ...panelStyle, display: 'flex', alignItems: 'center', justifyContent: 'space-between', flexWrap: 'wrap',
559
+ gap: 12, padding: 12, borderColor: updateSummary.state === 'revoked'
560
+ || updateSummary.dshCompatibility?.state === 'incompatible'
561
+ ? 'var(--dsw-alias-state-error-primary)' : 'var(--dsw-alias-state-warning-primary, var(--dsw-alias-border-l2))',
562
+ backgroundColor: updateSummary.state === 'revoked' || updateSummary.dshCompatibility?.state === 'incompatible'
563
+ ? 'var(--dsw-alias-state-error-secondary, var(--dsw-alias-bg-module-platform))'
564
+ : 'var(--dsw-alias-state-warning-secondary, var(--dsw-alias-bg-module-platform))',
565
+ } },
566
+ h('div', { style: { display: 'grid', gap: 3, flex: '1 1 300px' } },
567
+ h('strong', null, updateSummary.dshCompatibility?.state === 'incompatible'
568
+ ? `当前 DSH ${updateSummary.dshCompatibility.runtime_version || ''} 与 ANT 不兼容`
569
+ : updateSummary.state === 'available'
570
+ ? `有新版 ANT:${updateSummary.currentVersion || '当前版本未知'} → ${updateSummary.version}`
571
+ : updateSummary.state === 'done' ? `ANT ${updateSummary.version} 已安装,需重启 DSH`
572
+ : updateSummary.state === 'revoked' ? '当前 ANT 安装包已撤回' : 'ANT 更新需要处理'),
573
+ h('span', { style: mutedTextStyle }, updateSummary.dshCompatibility?.state === 'incompatible'
574
+ ? updateSummary.dshCompatibility.message
575
+ : updateSummary.state === 'available'
576
+ ? '查看“关于”中的更新说明与兼容要求;安装后需重启 DSH。'
577
+ : updateSummary.state === 'done' ? '请完全退出并重新启动 DSH 后生效。'
578
+ : updateSummary.state === 'revoked' ? '打开“关于”查看安全处置方式。'
579
+ : updateSummary.state === 'artifact-missing' ? '新版安装包尚未审核,请联系管理员。'
580
+ : '打开“关于”查看处理方式。')),
581
+ h('button', { type: 'button', onClick: () => selectSettingsTab('updates'), style: primaryButtonStyle },
582
+ updateSummary.state === 'available' ? '查看更新与兼容性' : '查看兼容详情')) : null,
583
+ h('nav', { role: 'tablist', 'aria-label': 'ANT 插件设置', style: {
584
+ display: 'flex', gap: 4, overflowX: 'auto', borderBottom: '1px solid var(--dsw-alias-border-l2)',
585
+ } },
586
+ ...ANT_SETTINGS_TABS.map(([tab, label], index) => {
587
+ const showBadge = tab === 'updates' && aboutNeedsAttention
588
+ return h('button', { key: tab, id: `ant-settings-tab-${tab}`,
589
+ type: 'button', role: 'tab', tabIndex: activeTab === tab ? 0 : -1,
590
+ 'aria-controls': 'ant-settings-content', 'aria-selected': String(activeTab === tab),
591
+ onKeyDown: (event) => moveSettingsTabFocus(event, index), onClick: () => selectSettingsTab(tab),
592
+ style: { ...secondaryButtonStyle, minHeight: 38, padding: '7px 12px', whiteSpace: 'nowrap',
593
+ borderRadius: '8px 8px 0 0', color: activeTab === tab ? 'var(--dsw-alias-state-business-primary)' : secondaryButtonStyle.color,
594
+ border: '0', borderBottom: activeTab === tab ? '2px solid var(--dsw-alias-state-business-primary)' : '2px solid transparent',
595
+ backgroundColor: 'transparent',
596
+ } },
597
+ label,
598
+ showBadge ? h('span', { role: 'img', 'aria-label': '需处理', style: {
599
+ display: 'inline-block', width: 8, height: 8, marginInlineStart: 5, borderRadius: '50%',
600
+ backgroundColor: aboutAttentionIsCritical ? 'var(--dsw-alias-state-error-primary)'
601
+ : 'var(--dsw-alias-state-warning-primary, var(--dsw-alias-label-secondary))',
602
+ } }) : null)
603
+ }))),
604
+ h('div', { id: 'ant-settings-content', role: 'tabpanel', 'aria-labelledby': `ant-settings-tab-${activeTab}`,
605
+ style: { display: 'grid', gap: activeTab === 'connection' ? 12 : 0 } },
606
+ teamServicePanel,
607
+ h(ModelSyncFooter, { remote, serviceUrl, bindingReady: binding.state === 'ready', activeTab,
608
+ onServiceUrlChange: setServiceUrl, onConnectionChange,
609
+ onUpdateStateChange: setUpdateSummary, onSelectTab: selectSettingsTab }),
610
+ h(DelegationCards, { remote, revision: delegationRevision,
611
+ activeTab, onSelectTab: selectSettingsTab,
612
+ openImSettings: () => openInstalledPlugin('@xmanrui/dsh-im')})))
613
+ }
614
+
615
+ function DelegationCards({ remote, revision, activeTab, onSelectTab, openImSettings }) {
616
+ const [bots, setBots] = useState([])
617
+ const [enrolled, setEnrolled] = useState([])
618
+ const [groups, setGroups] = useState([])
619
+ const [cards, setCards] = useState([])
620
+ const [tasks, setTasks] = useState([])
621
+ const [executors, setExecutors] = useState([])
622
+ const [defaults, setDefaults] = useState(null)
623
+ const [localConcurrency, setLocalConcurrency] = useState(null)
624
+ const [repositoryCacheLimitGib, setRepositoryCacheLimitGib] = useState(10)
625
+ const [botId, setBotId] = useState('')
626
+ const [conversationKind, setConversationKind] = useState('dm')
627
+ const [groupId, setGroupId] = useState('')
628
+ const [ruleDescription, setRuleDescription] = useState('')
629
+ const recognizedBaselineRef = useRef(null)
630
+ const recognizedDescriptionRef = useRef(null)
631
+ const autoAnalyzeDescriptionRef = useRef(null)
632
+ const recognitionRequestRef = useRef(0)
633
+ const recognitionTimerRef = useRef(null)
634
+ const [recognitionBusy, setRecognitionBusy] = useState(false)
635
+ const [recognitionMessage, setRecognitionMessage] = useState('')
636
+ const [missingRequired, setMissingRequired] = useState([])
637
+ const [suggestions, setSuggestions] = useState([])
638
+ const [ruleExamples, setRuleExamples] = useState([])
639
+ const [title, setTitle] = useState('')
640
+ const [intent, setIntent] = useState('')
641
+ const [taskPrompt, setTaskPrompt] = useState('')
642
+ const [runner, setRunner] = useState('dsh')
643
+ const [reviewers, setReviewers] = useState(['dsh'])
644
+ const [parameters, setParameters] = useState([])
645
+ const [parallelAgentsOpen, setParallelAgentsOpen] = useState(false)
646
+ const [giteaToken, setGiteaToken] = useState('')
647
+ const [tokenConfigured, setTokenConfigured] = useState(false)
648
+ const [senderScope, setSenderScope] = useState('any')
649
+ const [senderIds, setSenderIds] = useState('')
650
+ const [days, setDays] = useState(7)
651
+ const [editingCardId, setEditingCardId] = useState(null)
652
+ const [editingExpiresAt, setEditingExpiresAt] = useState(null)
653
+ const [busy, setBusy] = useState(false)
654
+ const [loading, setLoading] = useState(true)
655
+ const [botLoadError, setBotLoadError] = useState(false)
656
+ const [loadFailures, setLoadFailures] = useState([])
657
+ const [createOpen, setCreateOpen] = useState(false)
658
+ const [message, setMessage] = useState('')
659
+ const [submissionError, setSubmissionError] = useState('')
660
+ const [draftNotice, setDraftNotice] = useState('')
661
+ const load = async () => {
662
+ setLoading(true)
663
+ setMessage('')
664
+ try {
665
+ const paths = ['bots', 'enrolled-bots', 'groups', 'cards', 'settings', 'executors', 'local-settings', 'status']
666
+ const responses = await Promise.all(paths.map((path) =>
667
+ fetch(`/api/ant-teams/delegation/${path}`, { cache: 'no-store',
668
+ ...(path === 'enrolled-bots' ? { headers: { 'x-ant-include-unbound': 'true' } } : {}) })
669
+ .catch(() => null)))
670
+ const data = await Promise.all(responses.map((response) => response
671
+ ? readLocalJsonResponse(response).catch(() => null) : null))
672
+ const valid = [
673
+ (value) => Array.isArray(value?.bots),
674
+ Array.isArray, Array.isArray, Array.isArray,
675
+ (value) => value && typeof value === 'object' && !Array.isArray(value),
676
+ Array.isArray,
677
+ (value) => value && typeof value === 'object' && !Array.isArray(value),
678
+ (value) => Array.isArray(value?.items),
679
+ ]
680
+ const readable = responses.map((response, index) => Boolean(response?.ok && valid[index](data[index])))
681
+ setLoadFailures(paths.filter((path, index) => !readable[index]))
682
+ setBots(readable[0] ? data[0].bots : [])
683
+ setBotLoadError(!readable[0])
684
+ setEnrolled(readable[1] ? data[1] : [])
685
+ setGroups(readable[2] ? data[2] : [])
686
+ setCards(readable[3] ? data[3] : [])
687
+ setDefaults(readable[4] ? data[4] : null)
688
+ setExecutors(readable[5] ? data[5] : [])
689
+ setLocalConcurrency(readable[6] ? data[6].max_concurrency : null)
690
+ setRepositoryCacheLimitGib(readable[6] ? data[6].repository_cache_limit_gib ?? 10 : 10)
691
+ setTasks(readable[7] ? data[7].items : [])
692
+ let credential = null
693
+ try { credential = await remote?.credentials?.describe?.(['ANT_GITEA_API_TOKEN']) } catch {}
694
+ setTokenConfigured(Boolean(credential?.ok && credential.value?.ANT_GITEA_API_TOKEN?.configured))
695
+ } finally { setLoading(false) }
696
+ }
697
+ useEffect(() => { void load().catch((error) => setMessage(error.message)) }, [remote, revision])
698
+ useEffect(() => { setMessage('') }, [activeTab])
699
+ const selectedBot = bots.find((bot) => bot.bot_id === botId)
700
+ const botConnected = Boolean(selectedBot?.available && selectedBot?.connected)
701
+ const selectedEnrollment = enrolled.find((bot) => bot.bot_fingerprint === selectedBot?.fingerprint)
702
+ const selectedGiteaOrigin = normalizeServiceUrl(selectedEnrollment?.gitea_origin)
703
+ const taskPrOrigins = [...new Set(parameters.filter((item) => item.kind === 'gitea_pr')
704
+ .map((item) => normalizeServiceUrl(item.gitea_origin)).filter(Boolean))]
705
+ const selectedEnrollmentBound = selectedEnrollment?.device_bound_to_current === true
706
+ const dmChatSettingAvailable = typeof selectedEnrollment?.dm_chat_enabled === 'boolean'
707
+ const dmChatEnabled = selectedEnrollment?.dm_chat_enabled !== false
708
+ const dmChatStatus = !selectedBot ? '先选择机器人'
709
+ : loadFailures.includes('enrolled-bots') ? '暂时无法读取'
710
+ : !selectedEnrollmentBound ? '先绑定本机'
711
+ : !dmChatSettingAvailable ? '需升级服务端' : dmChatEnabled ? '已开启' : '已关闭'
712
+ const dmChatDescription = !selectedBot ? '选择机器人后查看或修改私聊设置。'
713
+ : loadFailures.includes('enrolled-bots') ? '暂时无法读取私聊设置,请刷新状态后再试。'
714
+ : !selectedEnrollmentBound ? '请先把机器人绑定到这台 DSH,再修改私聊设置。'
715
+ : !dmChatSettingAvailable ? '当前团队服务端尚未提供私聊开关,请先升级服务端。'
716
+ : dmChatEnabled
717
+ ? '允许此机器人接收私聊;任务仍按已开放的规则执行。'
718
+ : '新私聊消息不会交给 DSH;已提交任务仍会在原私聊回复。已开放能力不撤销,重新开启后未过期能力恢复触发。'
719
+ const availableGroups = groups.filter((group) => group.bot_fingerprint === selectedBot?.fingerprint)
720
+ const groupLabel = (group) => {
721
+ if (!group) return ''
722
+ const name = typeof group?.group_name === 'string' ? group.group_name.trim() : ''
723
+ return name ? `${name}(${group.group_code.slice(-2)})` : group.group_code
724
+ }
725
+ const groupChatLoadFailed = loadFailures.includes('groups')
726
+ const activeCards = cards.filter((card) => !card.revoked_at && card.expires_at * 1000 > Date.now())
727
+ const connectedBots = bots.filter((bot) => bot.available && bot.connected)
728
+ const authorizationLoadError = loadFailures.includes('cards')
729
+ const enrollmentLoadError = loadFailures.includes('enrolled-bots')
730
+ const enrolledCount = enrolled.filter((item) => item.device_bound_to_current
731
+ && connectedBots.some((bot) => bot.fingerprint === item.bot_fingerprint)).length
732
+ const selectedTaskCount = activeCards.filter((card) => card.bot_fingerprint === selectedBot?.fingerprint).length
733
+ const collaborationStatus = loading ? '正在读取机器人与任务状态…'
734
+ : botLoadError ? '暂时无法读取机器人状态。请刷新后再试。'
735
+ : connectedBots.length === 0 ? '尚未发现已连接的机器人。请先在 DSH-IM 中连接飞书机器人。'
736
+ : selectedBot && !botConnected ? `“${selectedBot.name}”当前离线;请先在 DSH-IM 恢复连接。`
737
+ : enrollmentLoadError ? selectedBot
738
+ ? `“${selectedBot.name}”已连接;暂时无法确认协作是否已启用,请刷新状态。`
739
+ : '机器人已连接;协作启用状态暂未读取,请刷新状态。'
740
+ : selectedBot && !selectedEnrollmentBound ? selectedEnrollment
741
+ ? `“${selectedBot.name}”已连接;原协作配置尚未绑定到这台 DSH,请在本机重新启用。若原设备令牌曾被撤销,旧任务权限已关闭,绑定后需重新开放。`
742
+ : `“${selectedBot.name}”已连接;请先启用本机协作。`
743
+ : enrolledCount === 0 ? '机器人已连接;请选择并启用协作。'
744
+ : !selectedBot ? '已有协作机器人;请选择一台,查看已开放的能力和聊天范围。'
745
+ : authorizationLoadError ? `“${selectedBot.name}”已启用协作;已开放任务暂未读取,请刷新状态。`
746
+ : !dmChatEnabled ? `“${selectedBot.name}”已启用协作;私聊已关闭,群聊仍按各自设置工作。`
747
+ : selectedTaskCount === 0 ? `“${selectedBot.name}”已启用协作;下一步开放一项能力。你也可以先私聊自测普通聊天。`
748
+ : `“${selectedBot.name}”已启用协作 · ${selectedTaskCount} 项能力已开放。可以私聊自测。`
749
+ const nativeReviewerSelected = reviewers.some((item) => ['codex', 'claude-code'].includes(item))
750
+ const hasPrParameter = parameters.some((item) => item.kind === 'gitea_pr')
751
+ const hasSelectedPrRule = activeCards.some((card) => card.bot_fingerprint === selectedBot?.fingerprint
752
+ && Array.isArray(card.parameters) && card.parameters.some((rule) => rule.kind === 'gitea_pr'))
753
+ const showPrSecuritySettings = Boolean(selectedBot
754
+ && (hasPrParameter || hasSelectedPrRule))
755
+ const selectedGroupSummary = groupLabel(availableGroups.find((group) => group.group_id === groupId)) || groupId
756
+ const codexAvailable = executors.some((item) => item.id === 'codex' && item.available)
757
+ const claudeCodeAvailable = executors.some((item) => item.id === 'claude-code' && item.available)
758
+ const dshAvailable = executors.some((item) => item.id === 'dsh' && item.available)
759
+ const nativePrUnavailableReason = executors.find((item) => item.reason)?.reason || null
760
+ const reviewerLabel = (id) => ({ dsh: 'DSH', codex: 'Codex', 'claude-code': 'Claude Code' })[id] || id
761
+ const cardReviewerSummary = (card) => {
762
+ const selected = Array.isArray(card.reviewers) && card.reviewers.length ? card.reviewers : [card.runner]
763
+ const unavailable = selected.filter((runner) => runner !== 'dsh')
764
+ if (card.runner !== 'dsh') return translateLocaleText('{executor} 默认执行方暂不可用',
765
+ { executor: reviewerLabel(card.runner) })
766
+ return unavailable.length
767
+ ? translateLocaleText('默认 DSH;{executors} 暂不可用',
768
+ { executors: unavailable.map(reviewerLabel).join('、') })
769
+ : translateLocaleText('DSH 任务 Agent')
770
+ }
771
+ const requesterSummary = senderScope === 'allowlist'
772
+ ? translateLocaleText('仅指定成员:{member_ids}',
773
+ { member_ids: senderIds.trim() || translateLocaleText('尚未填写成员 ID') })
774
+ : translateLocaleText(conversationKind === 'group' ? '群内所有成员' : '任何能私聊此机器人的人')
775
+ const resultRouteSummary = translateLocaleText(conversationKind === 'group'
776
+ ? '回复到原群(群内可见)' : '回复到发起任务的私聊')
777
+ const ruleSummaryCurrent = recognizedDescriptionRef.current === ruleDescription.trim()
778
+ const ruleSummaryPending = Boolean(ruleDescription.trim() && !ruleSummaryCurrent)
779
+ const ruleSummaryReady = Boolean(ruleSummaryCurrent && (title || intent || parameters.length || taskPrompt))
780
+ const missingHarnessInputs = [...new Set([
781
+ ...missingRequired,
782
+ ...(parameters.some((rule) => rule.kind === 'gitea_pr'
783
+ && (typeof rule.gitea_origin !== 'string' || !normalizeServiceUrl(rule.gitea_origin) || !rule.repository))
784
+ ? ['PR 来源和仓库'] : []),
785
+ ])]
786
+ const parameterSummary = (rule) => {
787
+ const parts = [rule.required === false ? '可选' : '必填']
788
+ const choices = Array.isArray(rule.choices) ? rule.choices
789
+ : typeof rule.choices === 'string' ? rule.choices.split(/[,,\n]/u).map((item) => item.trim()).filter(Boolean) : []
790
+ if (rule.kind === 'gitea_pr' && rule.repository) parts.push(`仓库 ${rule.repository}`)
791
+ if (rule.kind === 'gitea_pr' && rule.gitea_origin) parts.push(`来源 ${rule.gitea_origin}`)
792
+ if (rule.kind === 'git_sha') parts.push('可指定 Head SHA;未指定时用最新 Head')
793
+ else if (rule.kind === 'choice' && choices.length) parts.push(`选项 ${choices.join('、')}`)
794
+ else if (rule.kind === 'integer') {
795
+ const minValue = rule.min == null || rule.min === '' ? null : Number(rule.min)
796
+ const maxValue = rule.max == null || rule.max === '' ? null : Number(rule.max)
797
+ const minimum = minValue != null && Number.isFinite(minValue) ? minValue : null
798
+ const maximum = maxValue != null && Number.isFinite(maxValue) ? maxValue : null
799
+ if (minimum != null && maximum != null) parts.push(`范围 ${minimum}–${maximum}`)
800
+ else if (minimum != null) parts.push(`最少 ${minimum}`)
801
+ else if (maximum != null) parts.push(`最多 ${maximum}`)
802
+ } else if (rule.kind === 'text' && rule.max != null && rule.max !== ''
803
+ && Number.isFinite(Number(rule.max))) {
804
+ parts.push(`文字最多 ${Number(rule.max)} 字节`)
805
+ }
806
+ return `${rule.description?.trim() || rule.name}(${parts.join(';')})`
807
+ }
808
+ const recognizedInputsSummary = parameters.length
809
+ ? `请求时还需提供:${parameters.map(parameterSummary).join(';')}`
810
+ : '无需额外参数,按请求中的内容处理'
811
+ const ruleSummaryNarrative = ruleSummaryReady
812
+ ? `${intent.trim() || title.trim()}${taskPrompt.trim() ? `;${taskPrompt.trim()}` : ''};${recognizedInputsSummary}`
813
+ : '识别后会用一段摘要呈现系统理解的任务。'
814
+ const executorSummary = translateLocaleText(runner === 'codex' ? 'DSH Codex 子 Agent'
815
+ : runner === 'claude-code' ? 'DSH Claude Code 子 Agent' : 'DSH · 当前授权模型'
816
+ )
817
+ const parallelAgentsSummary = reviewers.filter((item) => item !== runner).map(reviewerLabel).join('、')
818
+ const cardBlockReason = enrollmentLoadError ? '暂时无法核对机器人是否已启用协作,请刷新状态后再试。'
819
+ : !botConnected || !selectedEnrollmentBound ? '先在上方把机器人绑定到这台 DSH。'
820
+ : loadFailures.includes('settings') || defaults?.task_rule_schema_version !== 3
821
+ ? '团队服务端尚未支持 AI 任务 Harness 与运行时授权核验;请先升级 ANT 服务端。'
822
+ : !ruleDescription.trim() ? '请先用自然语言描述要做的任务。'
823
+ : recognizedDescriptionRef.current !== ruleDescription.trim()
824
+ ? 'AI 正在根据最新描述检查任务 Harness;分析完成后再开放。'
825
+ : !title.trim() || !intent.trim() || !taskPrompt.trim() ? '等待 AI 生成任务理解和处理要求。'
826
+ : missingHarnessInputs.length ? `任务范围还有必需信息未明确:${missingHarnessInputs.join('、')}。请补充描述。`
827
+ : conversationKind === 'group' && loadFailures.includes('groups') ? '暂时无法核对目标群,请刷新状态后再试。'
828
+ : conversationKind === 'group' && !groupId ? '请在“请求范围”中选择目标群;若列表为空,让群成员先 @机器人,再刷新群列表。'
829
+ : senderScope === 'allowlist' && !senderIds.trim() ? '请填写可请求成员的 IM ID。'
830
+ : reviewers.some((item) => item !== 'dsh')
831
+ ? '当前只允许 DSH 执行协作任务。请将默认执行方改为 DSH,并移除未获准的外部 Agent。'
832
+ : parameters.some((rule) => rule.kind === 'gitea_pr') && !tokenConfigured ? '请先在“本机与任务”中保存本机 Gitea 只读令牌。'
833
+ : parameters.some((rule) => rule.kind === 'gitea_pr'
834
+ && (typeof rule.gitea_origin !== 'string' || !normalizeServiceUrl(rule.gitea_origin) || !rule.repository))
835
+ ? 'PR 来源或仓库尚未从自然语言描述中明确识别,请补充完整的 PR 来源链接或仓库。'
836
+ : parameters.some((rule) => rule.kind === 'gitea_pr'
837
+ && selectedGiteaOrigin && normalizeServiceUrl(rule.gitea_origin) !== selectedGiteaOrigin)
838
+ ? `${translateLocaleText('任务描述中的 Gitea 来源必须与此机器人的连接器主机一致({origin});为保护令牌,ANT 不会向其他主机发送凭据。', { origin: selectedGiteaOrigin })} ${translateLocaleText('请在描述中改用该主机下的 PR 链接并重新分析。')}`
839
+ : taskPrOrigins.length > 1
840
+ ? '同一任务中的 PR 资源必须来自同一个 Gitea 主机。'
841
+ : nativeReviewerSelected && (parameters.filter((rule) => rule.kind === 'gitea_pr').length !== 1
842
+ || parameters.some((rule) => !['gitea_pr', 'git_sha'].includes(rule.kind)))
843
+ ? 'Codex 和 Claude Code 当前只支持一个 Gitea PR 资源连接器;任务具体做审查、总结或解释仍由自然语言描述决定。'
844
+ : nativeReviewerSelected && !parameters.find((rule) => rule.kind === 'gitea_pr')?.required
845
+ ? '使用本机 Provider 时,Gitea PR 资源必须是必填项。'
846
+ : reviewers.includes('dsh') && !dshAvailable
847
+ ? '这台 DSH 尚未准备好任务执行器。'
848
+ : ''
849
+ const loadNames = { bots: '机器人', 'enrolled-bots': '协作启用状态', groups: '群聊列表',
850
+ cards: '任务授权', settings: '团队默认值', executors: '本机执行器',
851
+ 'local-settings': '本机设置', status: '最近任务' }
852
+ const changeReviewer = (id, enabled) => {
853
+ const next = enabled ? [...reviewers, id] : reviewers.filter((item) => item !== id)
854
+ if (!next.length) { setMessage('至少保留一位任务执行 Agent。'); return }
855
+ setReviewers([...new Set(next)])
856
+ if (!next.includes(runner)) setRunner(next[0])
857
+ }
858
+ const selectRunner = (id) => {
859
+ setRunner(id)
860
+ setReviewers((current) => current.length > 1
861
+ ? [...new Set([...current, id])]
862
+ : [id])
863
+ }
864
+ const startNewCard = (context = {}) => {
865
+ setEditingCardId(null); setEditingExpiresAt(null)
866
+ setSubmissionError('')
867
+ setDraftNotice('')
868
+ setRecognitionMessage('')
869
+ recognizedBaselineRef.current = null
870
+ recognizedDescriptionRef.current = null
871
+ autoAnalyzeDescriptionRef.current = null
872
+ recognitionRequestRef.current += 1
873
+ setRuleDescription('')
874
+ setMissingRequired([]); setSuggestions([]); setRuleExamples([])
875
+ setTitle(''); setIntent(''); setTaskPrompt(''); setRunner('dsh')
876
+ setReviewers(['dsh']); setParallelAgentsOpen(false)
877
+ setParameters([]); setConversationKind(context.conversationKind || 'dm')
878
+ setGroupId(context.groupId || '')
879
+ setSenderScope('any'); setSenderIds(''); setDays(7); setCreateOpen(true)
880
+ if (context.botId) setBotId(context.botId)
881
+ }
882
+ const taskRuleDraftFromCard = (card, title) => {
883
+ const rules = (card.parameters || []).map((rule) => ({
884
+ name: rule.name, kind: rule.kind, required: rule.required,
885
+ description: rule.description || '', min: rule.min == null ? '' : String(rule.min),
886
+ max: rule.max == null ? '' : String(rule.max),
887
+ choices: Array.isArray(rule.choices) ? rule.choices.join(', ') : String(rule.choices ?? ''),
888
+ gitea_origin: rule.gitea_origin || '', repository: rule.repository || '',
889
+ }))
890
+ if (rules.some((rule) => rule.kind === 'gitea_pr')) {
891
+ const headIndex = rules.findIndex((rule) => rule.name === 'head_sha')
892
+ const headRule = { name: 'head_sha', kind: 'git_sha', required: false,
893
+ description: 'PR Head SHA(可选;未指定时使用任务开始处理时的最新 Head)',
894
+ min: '', max: '', choices: '', gitea_origin: '', repository: '' }
895
+ if (headIndex >= 0 && rules[headIndex].kind === 'git_sha') rules[headIndex] = headRule
896
+ else if (headIndex < 0 && rules.length < 12) rules.push(headRule)
897
+ }
898
+ return { title: title || '', intent: card.intent || '', task_prompt: card.task_prompt || '',
899
+ parameters: rules, examples: Array.isArray(card.examples) ? card.examples : [],
900
+ missing_required: [], suggestions: [] }
901
+ }
902
+ const editCard = (card, copy = false) => {
903
+ setSubmissionError('')
904
+ setBotId(card.bot_id)
905
+ setRecognitionMessage('')
906
+ autoAnalyzeDescriptionRef.current = null
907
+ recognitionRequestRef.current += 1
908
+ setEditingCardId(copy ? null : card.id); setEditingExpiresAt(copy ? null : card.expires_at)
909
+ const taskDraft = taskRuleDraftFromCard(card, copy ? `${card.title.slice(0, 94)}(副本)` : card.title)
910
+ recognizedBaselineRef.current = taskDraft
911
+ const existingDescription = card.rule_description || ''
912
+ recognizedDescriptionRef.current = existingDescription.trim() || null
913
+ setDraftNotice(existingDescription.trim() ? ''
914
+ : '这项旧任务没有自然语言描述。请补充任务描述,让 AI 生成 Harness 后再开放。')
915
+ setRuleDescription(existingDescription)
916
+ setMissingRequired([]); setSuggestions(taskDraft.suggestions); setRuleExamples(taskDraft.examples)
917
+ setTitle(taskDraft.title)
918
+ if (copy) setDays(7)
919
+ setIntent(taskDraft.intent)
920
+ setTaskPrompt(taskDraft.task_prompt); setRunner(card.runner)
921
+ setReviewers(Array.isArray(card.reviewers) && card.reviewers.length ? card.reviewers : [card.runner])
922
+ setParallelAgentsOpen(false)
923
+ setParameters(taskDraft.parameters)
924
+ setConversationKind(card.conversation_kind); setGroupId(card.conversation_id || '')
925
+ setSenderScope(card.sender_scope); setSenderIds((card.sender_ids || []).join(', '))
926
+ setCreateOpen(true)
927
+ }
928
+ const applyRuleDraft = (draft) => {
929
+ setTitle(draft.title)
930
+ setIntent(draft.intent)
931
+ setTaskPrompt(draft.task_prompt)
932
+ setParameters(draft.parameters)
933
+ setMissingRequired(draft.missing_required || [])
934
+ setSuggestions(draft.suggestions || [])
935
+ setRuleExamples(draft.examples || [])
936
+ }
937
+ const identifyRule = async (description = ruleDescription) => {
938
+ const requestedDescription = description.trim()
939
+ if (!requestedDescription) {
940
+ setRecognitionMessage('先描述这项任务何时触发、要做什么以及涉及哪些资料。')
941
+ return
942
+ }
943
+ if (recognitionTimerRef.current) clearTimeout(recognitionTimerRef.current)
944
+ const requestNumber = ++recognitionRequestRef.current
945
+ setRecognitionBusy(true); setMessage(''); setRecognitionMessage('AI 正在分析必需范围、可选条件和执行方式…')
946
+ try {
947
+ const response = await fetch('/api/ant-teams/delegation/recognize', {
948
+ method: 'POST', headers: { 'content-type': 'application/json' },
949
+ body: JSON.stringify({ description: requestedDescription }),
950
+ })
951
+ const result = await readLocalJsonResponse(response)
952
+ if (!response.ok) throw new Error(result.message || '规则识别失败。')
953
+ const candidate = {
954
+ title: typeof result.title === 'string' ? result.title : '',
955
+ intent: typeof result.intent === 'string' ? result.intent : '',
956
+ task_prompt: typeof result.task_prompt === 'string' ? result.task_prompt : '',
957
+ missing_required: Array.isArray(result.missing_required) ? result.missing_required : [],
958
+ suggestions: Array.isArray(result.suggestions) ? result.suggestions : [],
959
+ examples: Array.isArray(result.examples) ? result.examples : [],
960
+ parameters: Array.isArray(result.parameters) ? result.parameters.map((rule) => ({
961
+ name: typeof rule?.name === 'string' ? rule.name : '',
962
+ kind: typeof rule?.kind === 'string' ? rule.kind : 'text',
963
+ required: rule?.required !== false,
964
+ description: typeof rule?.description === 'string' ? rule.description : '',
965
+ min: rule?.min == null ? '' : String(rule.min),
966
+ max: rule?.max == null ? '' : String(rule.max),
967
+ choices: Array.isArray(rule?.choices) ? rule.choices.join(', ')
968
+ : typeof rule?.choices === 'string' ? rule.choices : '',
969
+ gitea_origin: typeof rule?.gitea_origin === 'string' ? rule.gitea_origin : '',
970
+ repository: typeof rule?.repository === 'string' ? rule.repository : '',
971
+ })) : [],
972
+ }
973
+ if (candidate.parameters.some((rule) => rule.kind === 'gitea_pr')) {
974
+ const headIndex = candidate.parameters.findIndex((rule) => rule.name === 'head_sha')
975
+ if (headIndex >= 0 && candidate.parameters[headIndex].kind !== 'git_sha') {
976
+ throw new Error('PR Head SHA 与另一项请求信息重名,请调整任务描述后重新分析。')
977
+ }
978
+ const headRule = { name: 'head_sha', kind: 'git_sha', required: false,
979
+ description: 'PR Head SHA(可选;未指定时使用任务开始处理时的最新 Head)',
980
+ min: '', max: '', choices: '', gitea_origin: '', repository: '' }
981
+ if (headIndex >= 0) candidate.parameters[headIndex] = headRule
982
+ else {
983
+ if (candidate.parameters.length >= 12) throw new Error('PR 任务包含的信息项过多,请简化描述后重新分析。')
984
+ candidate.parameters.push(headRule)
985
+ }
986
+ }
987
+ if (requestNumber !== recognitionRequestRef.current || requestedDescription !== ruleDescription.trim()) return
988
+ if (!candidate.title || !candidate.intent || !candidate.task_prompt) {
989
+ throw new Error('AI 返回的任务理解不完整。请补充描述后重试。')
990
+ }
991
+ const previous = recognizedBaselineRef.current
992
+ applyRuleDraft(candidate)
993
+ recognizedBaselineRef.current = candidate
994
+ recognizedDescriptionRef.current = requestedDescription
995
+ setRecognitionMessage(previous
996
+ ? 'AI 已更新任务理解。请复核必需信息、可选建议和运行方式;任务仍未开放。'
997
+ : 'AI 已生成待复核的任务 Harness。检查摘要和范围后再开放。')
998
+ } catch (error) {
999
+ if (requestNumber === recognitionRequestRef.current) setRecognitionMessage(error.message)
1000
+ } finally {
1001
+ if (requestNumber === recognitionRequestRef.current) setRecognitionBusy(false)
1002
+ }
1003
+ }
1004
+ useEffect(() => {
1005
+ if (autoAnalyzeDescriptionRef.current !== ruleDescription || !ruleDescription.trim()) return undefined
1006
+ const description = ruleDescription
1007
+ recognitionTimerRef.current = setTimeout(() => {
1008
+ if (autoAnalyzeDescriptionRef.current === description) void identifyRule(description)
1009
+ }, 900)
1010
+ return () => clearTimeout(recognitionTimerRef.current)
1011
+ }, [ruleDescription])
1012
+ const saveGiteaToken = async () => {
1013
+ if (!giteaToken.trim()) return
1014
+ setBusy(true)
1015
+ try {
1016
+ const result = await remote.credentials.set('ANT_GITEA_API_TOKEN', giteaToken.trim())
1017
+ if (!result?.ok) throw new Error('DSH 无法安全保存 Gitea 令牌。')
1018
+ setGiteaToken(''); setTokenConfigured(true)
1019
+ setMessage('Gitea 令牌已保存在这台 DSH,不会提交给 ANT 服务端。')
1020
+ } catch (error) { setMessage(error.message) }
1021
+ finally { setBusy(false) }
1022
+ }
1023
+ const enrollBot = async () => {
1024
+ if (!selectedBot) return
1025
+ const origin = selectedEnrollment?.gitea_origin || ''
1026
+ setBusy(true)
1027
+ try {
1028
+ const response = await fetch('/api/ant-teams/delegation/enrolled-bots', {
1029
+ method: 'POST', headers: { 'content-type': 'application/json' },
1030
+ body: JSON.stringify({ bot_id: selectedBot.bot_id, bot_fingerprint: selectedBot.fingerprint,
1031
+ gitea_origin: origin }),
1032
+ })
1033
+ const result = await readLocalJsonResponse(response)
1034
+ if (!response.ok) throw new Error(result.message || '协作机器人启用失败。')
1035
+ await load()
1036
+ setMessage('协作机器人已启用。你可以分别设置私聊和群聊,再开放需要的能力。')
1037
+ } catch (error) { setMessage(error.message) }
1038
+ finally { setBusy(false) }
1039
+ }
1040
+ const saveGroupChat = async (enabled, targetGroupId) => {
1041
+ if (!selectedBot || !selectedEnrollmentBound || !targetGroupId.trim()) return
1042
+ const targetHasTasks = activeCards.some((card) => card.bot_fingerprint === selectedBot.fingerprint
1043
+ && card.conversation_kind === 'group' && card.conversation_id === targetGroupId)
1044
+ if (!confirmLocalized(enabled
1045
+ ? targetHasTasks
1046
+ ? '这个群当前因任务授权可以聊天。要在任务到期后仍允许普通聊天吗?聊天会使用团队模型额度。'
1047
+ : '允许这个群与机器人自然聊天?群成员仍不能执行未开放的能力,聊天会使用团队模型额度。'
1048
+ : '关闭这个群的普通聊天?已有能力不会自动撤销。')) return
1049
+ setBusy(true)
1050
+ try {
1051
+ const response = await fetch('/api/ant-teams/delegation/groups', {
1052
+ method: 'PUT', headers: { 'content-type': 'application/json' },
1053
+ body: JSON.stringify({ bot_id: selectedBot.bot_id,
1054
+ bot_fingerprint: selectedBot.fingerprint, group_id: targetGroupId.trim(), enabled }),
1055
+ })
1056
+ if (!response.ok) {
1057
+ const result = await readLocalJsonResponse(response)
1058
+ throw new Error(result.message || '群聊设置保存失败。')
1059
+ }
1060
+ await load()
1061
+ setMessage(enabled ? '这个群现在可以与机器人聊天;可执行能力仍需逐项开放。' : '已关闭这个群的普通聊天。')
1062
+ } catch (error) { setMessage(error.message) }
1063
+ finally { setBusy(false) }
1064
+ }
1065
+ const saveDmChat = async (enabled) => {
1066
+ if (!selectedBot || !selectedEnrollmentBound || !dmChatSettingAvailable) return
1067
+ if (!confirmLocalized(enabled
1068
+ ? '开启后,此机器人会在私聊中正常对话;私聊任务仍逐项按已开放规则核验。'
1069
+ : '关闭后,新私聊消息不会进入 DSH,包括普通聊天、任务请求和状态查询。关闭前已提交的任务不会被撤销,仍按原私聊回复。已开放的私聊能力不会删除;重新开启后,未过期的能力会恢复触发。群聊设置不受影响。')) return
1070
+ setBusy(true)
1071
+ try {
1072
+ const response = await fetch('/api/ant-teams/delegation/dm-chat', {
1073
+ method: 'PUT', headers: { 'content-type': 'application/json' },
1074
+ body: JSON.stringify({ bot_id: selectedBot.bot_id,
1075
+ bot_fingerprint: selectedBot.fingerprint, enabled }),
1076
+ })
1077
+ if (!response.ok) {
1078
+ const result = await readLocalJsonResponse(response)
1079
+ throw new Error(result.message || '私聊设置保存失败。')
1080
+ }
1081
+ await load()
1082
+ setMessage(enabled ? '已开启此机器人的私聊。' : '已关闭此机器人的私聊;群聊设置保持不变。')
1083
+ } catch (error) { setMessage(error.message) }
1084
+ finally { setBusy(false) }
1085
+ }
1086
+ const saveLocalProcessingSettings = async (event) => {
1087
+ event.preventDefault()
1088
+ setBusy(true)
1089
+ try {
1090
+ const response = await fetch('/api/ant-teams/delegation/local-settings', {
1091
+ method: 'PUT', headers: { 'content-type': 'application/json' },
1092
+ body: JSON.stringify({
1093
+ max_concurrency: localConcurrency === '' ? null : Number(localConcurrency),
1094
+ repository_cache_limit_gib: Number(repositoryCacheLimitGib),
1095
+ }),
1096
+ })
1097
+ const result = await readLocalJsonResponse(response)
1098
+ if (!response.ok) throw new Error(result.message || '本机处理设置保存失败。')
1099
+ setLocalConcurrency(result.max_concurrency)
1100
+ setRepositoryCacheLimitGib(result.repository_cache_limit_gib)
1101
+ setMessage('本机并发设置已保存;仓库缓存上限保留原值。')
1102
+ } catch (error) { setMessage(error.message) }
1103
+ finally { setBusy(false) }
1104
+ }
1105
+ const focusAfterTabChange = (tab, elementId) => {
1106
+ onSelectTab(tab)
1107
+ window.requestAnimationFrame?.(() => {
1108
+ const target = window.document?.getElementById(elementId)
1109
+ target?.scrollIntoView?.({ behavior: 'smooth', block: 'start' })
1110
+ target?.focus?.({ preventScroll: true })
1111
+ })
1112
+ }
1113
+ const goToSetupStep = (index) => {
1114
+ if (index === 0) return focusAfterTabChange('collaboration', selectedBot ? 'ant-bot-selector' : 'ant-chat-entry')
1115
+ if (index === 1) return focusAfterTabChange('collaboration',
1116
+ selectedEnrollmentBound && botConnected ? 'ant-group-task-status' : 'ant-chat-scope-panel')
1117
+ if (index === 2 && (authorizationLoadError || selectedTaskCount > 0)) {
1118
+ return focusAfterTabChange('collaboration', 'ant-capability-list')
1119
+ }
1120
+ if (index === 2) {
1121
+ startNewCard()
1122
+ return focusAfterTabChange('collaboration', 'ant-new-task-summary')
1123
+ }
1124
+ setCreateOpen(true)
1125
+ focusAfterTabChange('collaboration', 'ant-authorization-review')
1126
+ }
1127
+ const collaborationGridStyle = {
1128
+ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(min(100%, 300px), 1fr))', gap: 12,
1129
+ }
1130
+ const collaborationSettingsGridStyle = {
1131
+ ...collaborationGridStyle, gridTemplateColumns: 'repeat(auto-fit, minmax(min(100%, 420px), 1fr))',
1132
+ }
1133
+ const collaborationCardStyle = { ...settingsPanelStyle, padding: 12, gap: 10 }
1134
+ const setupStepper = h('section', { 'aria-label': '首次设置引导', style: { display: 'grid', gap: 6 } },
1135
+ h('p', { style: mutedTextStyle }, '首次设置可按顺序完成;你也可以直接切换页面。普通聊天不需要先开放任务。'),
1136
+ h('ol', { 'aria-label': '设置步骤', style: { display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(min(100%, 150px), 1fr))',
1137
+ gap: 8, padding: 0, margin: 0, listStyle: 'none' } },
1138
+ ...[
1139
+ { label: '机器人和设备', detail: !selectedBot ? '选择已连接的机器人' : !botConnected ? '检查 DSH-IM 连接' : selectedEnrollmentBound ? '已绑定到这台 DSH' : '绑定到这台 DSH' },
1140
+ { label: '聊天入口', detail: !selectedBot || !selectedEnrollmentBound ? '绑定设备后设置私聊和群聊' : groupChatLoadFailed ? '群列表暂不可用,请刷新状态' : `${dmChatEnabled ? '私聊可用' : '私聊已关闭'} · ${availableGroups.length} 个已发现群` },
1141
+ { label: '开放能力', detail: !botConnected || !selectedEnrollmentBound ? '完成机器人绑定后再开放' : authorizationLoadError ? '授权列表暂不可读,请刷新状态' : selectedTaskCount ? `${selectedTaskCount} 项已开放,可查看或停止` : '按需要创建任务' },
1142
+ { label: '复核授权', detail: authorizationLoadError ? '先确认已保存授权' : createOpen ? '检查请求范围后确认' : selectedTaskCount ? '查看已开放范围' : '请求人、执行方和期限' },
1143
+ ].map((step, index) => {
1144
+ const currentStep = !botConnected || !selectedEnrollmentBound ? 0 : createOpen ? 3 : selectedTaskCount ? 4 : 2
1145
+ const state = index < currentStep ? '完成' : index === currentStep ? '当前' : '待完成'
1146
+ return h('li', { key: step.label, style: { minWidth: 0 } },
1147
+ h('button', { type: 'button', 'aria-current': state === '当前' ? 'step' : undefined,
1148
+ onClick: () => goToSetupStep(index), style: { width: '100%', minHeight: 70, display: 'grid', gap: 3,
1149
+ padding: '8px 10px', textAlign: 'left', color: mutedTextStyle.color,
1150
+ backgroundColor: 'var(--dsw-alias-bg-layer-1)', cursor: 'pointer',
1151
+ border: '0', borderTop: `2px solid ${state === '完成' ? 'var(--dsw-alias-state-success-primary)' : state === '当前' ? 'var(--dsw-alias-state-business-primary)' : 'var(--dsw-alias-border-l2)'}`,
1152
+ borderRadius: 0 } },
1153
+ h('span', { style: { display: 'flex', justifyContent: 'space-between', gap: 6, alignItems: 'center' } },
1154
+ h('strong', { style: { fontSize: 13, fontWeight: 600 } }, step.label),
1155
+ h('span', { style: { fontSize: 12, color: mutedTextStyle.color } }, state)),
1156
+ h('span', { style: mutedTextStyle }, step.detail)))
1157
+ })))
1158
+ const chatScopePanel = h('section', { id: 'ant-chat-scope-panel', tabIndex: -1, style: collaborationCardStyle },
1159
+ h('strong', null, '私聊入口'),
1160
+ h('label', { style: { display: 'flex', gap: 8, alignItems: 'center', padding: 10, borderRadius: 8,
1161
+ border: '1px solid var(--dsw-alias-border-l2)', backgroundColor: 'var(--dsw-alias-bg-layer-1)' } },
1162
+ h('input', { type: 'checkbox', checked: dmChatEnabled,
1163
+ disabled: busy || !selectedBot || !selectedEnrollmentBound || enrollmentLoadError || !dmChatSettingAvailable,
1164
+ onChange: (event) => void saveDmChat(event.target.checked), 'aria-label': '允许机器人私聊' }),
1165
+ h('strong', null, '允许私聊普通聊天'), h('span', { style: mutedTextStyle }, dmChatStatus)),
1166
+ h('p', { style: mutedTextStyle }, dmChatDescription))
1167
+ const createCard = async (event) => {
1168
+ event.preventDefault()
1169
+ setDraftNotice('')
1170
+ setSubmissionError('')
1171
+ const reject = (reason) => {
1172
+ const localizedReason = translateLocaleText(reason)
1173
+ setSubmissionError(localizedReason); setMessage(localizedReason)
1174
+ }
1175
+ if (!selectedBot || !botConnected || !selectedEnrollmentBound) { reject('请先在这台 DSH 绑定选中的协作机器人。'); return }
1176
+ if (reviewers.some((item) => item !== 'dsh')) {
1177
+ reject('当前无法核验外部子 Agent 的逐任务文件、Git 和网络权限;请将任务执行方设为 DSH。'); return
1178
+ }
1179
+ if (editingCardId && (!editingExpiresAt || editingExpiresAt <= Math.floor(Date.now() / 1000))) {
1180
+ reject('这项能力已到期,无法继续编辑;请返回后重新开放一项能力。'); return
1181
+ }
1182
+ if (!ruleDescription.trim() || !title.trim() || !intent.trim() || !taskPrompt.trim()) {
1183
+ reject('请填写任务描述并点击“识别规则”,检查摘要后再开放。'); return
1184
+ }
1185
+ const bytes = (value) => new TextEncoder().encode(value).length
1186
+ if (bytes(ruleDescription.trim()) > 4000 || bytes(title.trim()) > 100
1187
+ || bytes(intent.trim()) > 1000 || bytes(taskPrompt.trim()) > 4000) {
1188
+ reject('任务描述或识别摘要过长,请缩短描述并重新识别。'); return
1189
+ }
1190
+ const normalized = parameters.map((rule) => ({ name: rule.name.trim(), kind: rule.kind,
1191
+ description: rule.description.trim() || null,
1192
+ required: rule.required, min: rule.min == null || rule.min === '' ? null : Number(rule.min),
1193
+ max: rule.max == null || rule.max === '' ? null : Number(rule.max),
1194
+ choices: rule.kind === 'choice' ? (Array.isArray(rule.choices) ? rule.choices
1195
+ : String(rule.choices ?? '').split(/[,,\n]/u)).map((item) => item.trim()).filter(Boolean) : null,
1196
+ gitea_origin: rule.kind === 'gitea_pr'
1197
+ ? (typeof rule.gitea_origin === 'string' ? normalizeServiceUrl(rule.gitea_origin) : null) : null,
1198
+ repository: rule.kind === 'gitea_pr' ? rule.repository.trim().toLowerCase() : null }))
1199
+ if (normalized.some((rule) => !/^[A-Za-z][A-Za-z0-9_]{0,31}$/u.test(rule.name))) {
1200
+ reject('没能从描述中整理出有效的请求信息。请说明同事需要提供什么,再重新识别。'); return
1201
+ }
1202
+ if (new Set(normalized.map((rule) => rule.name)).size !== normalized.length) {
1203
+ reject('请求信息识别有重复项。请修改任务描述并重新识别。'); return
1204
+ }
1205
+ if (normalized.some((rule) => rule.name === 'head_sha' && rule.kind !== 'git_sha')) {
1206
+ reject('head_sha 是 PR 提交版本的保留字段;请在自然语言描述中使用 PR Head SHA。'); return
1207
+ }
1208
+ if (normalized.some((rule) => rule.description && bytes(rule.description) > 100)) {
1209
+ reject('请求信息说明过长。请缩短任务描述并重新识别。'); return
1210
+ }
1211
+ if (normalized.some((rule) => rule.kind === 'choice' && (!rule.choices?.length || rule.choices.length > 32
1212
+ || rule.choices.some((choice) => bytes(choice) > 100)
1213
+ || new Set(rule.choices).size !== rule.choices.length))) {
1214
+ reject('描述中的可选范围不清楚或重复。请修改描述并重新识别。'); return
1215
+ }
1216
+ if (normalized.some((rule) => (rule.min != null && !Number.isInteger(rule.min))
1217
+ || (rule.max != null && !Number.isInteger(rule.max))
1218
+ || (rule.min != null && rule.max != null && rule.min > rule.max)
1219
+ || (rule.kind === 'text' && rule.max != null && (rule.max < 1 || rule.max > 4096))
1220
+ || (rule.kind === 'gitea_pr' && ((rule.min != null && rule.min < 1)
1221
+ || (rule.max != null && rule.max > 1_000_000_000))))) {
1222
+ reject('描述中的请求范围无效。请明确范围或提供完整 PR 链接,再重新识别。'); return
1223
+ }
1224
+ if (normalized.some((rule) => rule.kind === 'gitea_pr' && (!rule.gitea_origin || !rule.repository))) {
1225
+ reject('没能从描述中识别 PR 来源或仓库。请补充完整 PR 链接或仓库名,再重新识别。'); return
1226
+ }
1227
+ if (new Set(normalized.filter((rule) => rule.kind === 'gitea_pr')
1228
+ .map((rule) => normalizeServiceUrl(rule.gitea_origin)).filter(Boolean)).size > 1) {
1229
+ reject('同一任务中的 PR 资源必须来自同一个 Gitea 主机。')
1230
+ return
1231
+ }
1232
+ if (normalized.some((rule) => rule.kind === 'gitea_pr'
1233
+ && selectedGiteaOrigin && normalizeServiceUrl(rule.gitea_origin) !== selectedGiteaOrigin)) {
1234
+ reject(`${translateLocaleText('任务描述中的 Gitea 来源必须与此机器人的连接器主机一致({origin});为保护令牌,ANT 不会向其他主机发送凭据。', { origin: selectedGiteaOrigin })} ${translateLocaleText('请在描述中改用该主机下的 PR 链接并重新分析。')}`)
1235
+ return
1236
+ }
1237
+ const validRepository = (value) => {
1238
+ const parts = value.split('/')
1239
+ return parts.length === 2 && parts.every((part) => part !== '.' && part !== '..'
1240
+ && /^[A-Za-z0-9_.-]{1,100}$/u.test(part))
1241
+ }
1242
+ if (normalized.some((rule) => rule.kind === 'gitea_pr' && !validRepository(rule.repository))) {
1243
+ reject('仓库名无法识别。请在描述中写明“团队名/仓库名”或粘贴完整 PR 链接,再重新识别。'); return
1244
+ }
1245
+ if (!reviewers.length || !reviewers.includes(runner)) {
1246
+ reject('请至少选择一位任务执行 Agent,并设置普通请求的默认执行方。'); return
1247
+ }
1248
+ if (nativeReviewerSelected && !((normalized.length === 1
1249
+ && normalized[0].kind === 'gitea_pr' && normalized[0].required)
1250
+ || (normalized.length === 2 && normalized.some((rule) => rule.kind === 'gitea_pr' && rule.required)
1251
+ && normalized.some((rule) => rule.kind === 'git_sha' && rule.name === 'head_sha' && !rule.required)))) {
1252
+ reject('Codex 和 Claude Code 当前只支持一个必填 Gitea PR 资源连接器;任务行为仍由自然语言描述决定。'); return
1253
+ }
1254
+ const scope = conversationKind === 'group'
1255
+ ? translateLocaleText('群 {group_id}', { group_id: groupId })
1256
+ : translateLocaleText('私聊')
1257
+ const resultDestination = translateLocaleText(conversationKind === 'group'
1258
+ ? '原群(群内可见)' : '发起任务的私聊')
1259
+ const executionDetails = {
1260
+ dsh: translateLocaleText('DSH 使用获准的团队模型处理对话内容和 ANT 已核验后提供的资源。'),
1261
+ codex: translateLocaleText('Codex 当前不能用于协作任务,因为 ANT 无法核验其逐任务文件、Git 和网络权限。'),
1262
+ 'claude-code': translateLocaleText('Claude Code 当前不能用于协作任务,因为 ANT 无法核验其逐任务文件、Git 和网络权限。'),
1263
+ }
1264
+ const executionInfo = reviewers.length > 1
1265
+ ? translateLocaleText('普通请求默认由 {runner} 执行;请求人明确要求多 Agent 分别处理时,会并行启动 {reviewers},分别返回结果。{details}',
1266
+ { runner: reviewerLabel(runner), reviewers: reviewers.map(reviewerLabel).join('、'),
1267
+ details: reviewers.map((item) => executionDetails[item]).join(' ') })
1268
+ : executionDetails[reviewers[0]]
1269
+ const actionDescription = editingCardId
1270
+ ? translateLocaleText('更新“{title}”后,{requesterSummary}可在{scope}按任务描述中的规则发起请求。旧待确认请求将失效,已提交任务继续使用提交时的配置。结果{resultDestination}。到期时间保持为 {expiry}。',
1271
+ { title, requesterSummary, scope, resultDestination, expiry: formatLocaleDate(editingExpiresAt * 1000) })
1272
+ : translateLocaleText('开放“{title}”后,{requesterSummary}可在{scope}按任务描述中的规则发起请求,有效期 {days} 天;结果{resultDestination}。',
1273
+ { title, requesterSummary, scope, resultDestination, days: formatLocaleNumber(days) })
1274
+ if (!confirmLocalized(`${actionDescription}${executionInfo}${translateLocaleText('请确认。')}`)) return
1275
+ setBusy(true)
1276
+ try {
1277
+ const response = await fetch('/api/ant-teams/delegation/cards', {
1278
+ method: editingCardId ? 'PUT' : 'POST', headers: { 'content-type': 'application/json' },
1279
+ body: JSON.stringify({ ...(editingCardId ? { id: editingCardId } : {}),
1280
+ bot_id: selectedBot.bot_id, bot_fingerprint: selectedBot.fingerprint,
1281
+ title, rule_description: ruleDescription.trim(), trigger_phrases: [],
1282
+ intent, examples: ruleExamples,
1283
+ parameters: normalized, task_prompt: taskPrompt, runner, reviewers, workspace: null,
1284
+ sender_scope: senderScope, sender_ids: senderScope === 'allowlist'
1285
+ ? senderIds.split(/[\s,,]+/u).filter(Boolean) : [], conversation_kind: conversationKind,
1286
+ ...(conversationKind === 'group' ? { conversation_id: groupId } : {}),
1287
+ expires_at: editingCardId ? editingExpiresAt : Math.floor(Date.now() / 1000) + Number(days) * 86400 }),
1288
+ })
1289
+ const result = await readLocalJsonResponse(response)
1290
+ if (!response.ok && result.code === 'IM_TASK_RULE_REQUIRED') {
1291
+ throw new Error('当前 ANT 服务端不支持自然语言任务 Harness,请升级 ANT 服务端后再开放任务。')
1292
+ }
1293
+ if (!response.ok && reviewers.includes('claude-code') && result.code === 'INVALID_REQUEST') {
1294
+ throw new Error('当前团队服务端可能尚不支持 Claude Code 审查配置。请管理员升级服务端后刷新重试。')
1295
+ }
1296
+ if (!response.ok) throw new Error(result.message || '能力保存失败。')
1297
+ const savedReviewers = Array.isArray(result.reviewers) && result.reviewers.length
1298
+ ? result.reviewers : [result.runner]
1299
+ if ([...savedReviewers].sort().join('\0') !== [...reviewers].sort().join('\0')) {
1300
+ if (!editingCardId && typeof result.id === 'string') {
1301
+ const cleanup = await fetch('/api/ant-teams/delegation/cards', {
1302
+ method: 'DELETE', headers: { 'content-type': 'application/json' },
1303
+ body: JSON.stringify({ id: result.id }),
1304
+ }).catch(() => null)
1305
+ if (!cleanup?.ok) {
1306
+ await load().catch(() => undefined)
1307
+ throw new Error('团队服务端尚不支持多 Agent 审查配置;旧服务端可能已保存单 Agent 授权,请刷新列表并停止它,再升级 ANT 服务端。')
1308
+ }
1309
+ }
1310
+ throw new Error('当前团队服务端尚不支持多 Agent 审查配置;请管理员升级 ANT 服务端后重试。')
1311
+ }
1312
+ recognizedBaselineRef.current = null
1313
+ recognizedDescriptionRef.current = null
1314
+ autoAnalyzeDescriptionRef.current = null
1315
+ recognitionRequestRef.current += 1
1316
+ setRuleDescription(''); setMissingRequired([]); setSuggestions([]); setRuleExamples([])
1317
+ setTitle(''); setIntent(''); setTaskPrompt(''); setParameters([]); setRunner('dsh'); setReviewers(['dsh'])
1318
+ setParallelAgentsOpen(false)
1319
+ setEditingCardId(null); setEditingExpiresAt(null)
1320
+ await load()
1321
+ setCreateOpen(false)
1322
+ setSubmissionError('')
1323
+ setMessage(editingCardId
1324
+ ? '能力配置已更新。新请求将使用新配置,已提交任务保留原配置。'
1325
+ : '任务已开放。机器人会按已确认的描述判断请求;缺少必要信息时会向请求人追问。')
1326
+ } catch (error) { reject(error.message || translateLocaleText('能力保存失败。')) }
1327
+ finally { setBusy(false) }
1328
+ }
1329
+ const revokeCard = async (card) => {
1330
+ if (!confirmLocalized(`停止开放“${card.title}”?正在处理的任务无法撤销已经发生的读取。`)) return
1331
+ setBusy(true)
1332
+ try {
1333
+ const response = await fetch('/api/ant-teams/delegation/cards', {
1334
+ method: 'DELETE', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ id: card.id }),
1335
+ })
1336
+ if (!response.ok) throw new Error('停止能力失败,请重试。')
1337
+ await load(); setMessage('能力已停止开放。')
1338
+ } catch (error) { setMessage(error.message) }
1339
+ finally { setBusy(false) }
1340
+ }
1341
+ const copyCardToDraft = (card) => {
1342
+ setEditingCardId(null); setEditingExpiresAt(null)
1343
+ setParallelAgentsOpen(false)
1344
+ const copiedDescription = card.rule_description || ''
1345
+ recognizedDescriptionRef.current = copiedDescription.trim() || null
1346
+ autoAnalyzeDescriptionRef.current = null
1347
+ recognitionRequestRef.current += 1
1348
+ setDraftNotice(copiedDescription.trim()
1349
+ ? '已复制到新草稿。复制不保留原有效期;请检查任务描述和请求范围。'
1350
+ : '这项旧任务没有自然语言描述。请补充任务描述,让 AI 生成 Harness 后再开放。')
1351
+ const cardBot = bots.find((bot) => bot.fingerprint === card.bot_fingerprint)
1352
+ const titleChars = Array.from(translateLocaleText('复制:{title}', {
1353
+ title: card.title || translateLocaleText('未命名能力'),
1354
+ }))
1355
+ while (new TextEncoder().encode(titleChars.join('')).length > 100) titleChars.pop()
1356
+ const taskDraft = taskRuleDraftFromCard(card, titleChars.join(''))
1357
+ recognizedBaselineRef.current = taskDraft
1358
+ setBotId(card.bot_id || cardBot?.bot_id || '')
1359
+ setRuleDescription(copiedDescription)
1360
+ setMissingRequired([]); setSuggestions(taskDraft.suggestions); setRuleExamples(taskDraft.examples)
1361
+ setTitle(taskDraft.title)
1362
+ setIntent(taskDraft.intent)
1363
+ setTaskPrompt(taskDraft.task_prompt)
1364
+ setRunner(['dsh', 'codex', 'claude-code'].includes(card.runner) ? card.runner : 'dsh')
1365
+ setReviewers(Array.isArray(card.reviewers) && card.reviewers.length ? card.reviewers : [card.runner || 'dsh'])
1366
+ setParameters(taskDraft.parameters)
1367
+ setConversationKind(card.conversation_kind === 'group' ? 'group' : 'dm')
1368
+ setGroupId(card.conversation_id || '')
1369
+ setSenderScope(card.sender_scope === 'allowlist' ? 'allowlist' : 'any')
1370
+ setSenderIds(Array.isArray(card.sender_ids) ? card.sender_ids.join('\n') : '')
1371
+ setDays(7)
1372
+ setCreateOpen(true)
1373
+ onSelectTab('collaboration')
1374
+ }
1375
+ const cancelTask = async (task) => {
1376
+ if (!confirmLocalized(`取消任务 ${task.task_id}?已经发生的读取不能撤回。`)) return
1377
+ setBusy(true)
1378
+ try {
1379
+ const response = await fetch('/api/ant-teams/delegation/cancel', { method: 'POST',
1380
+ headers: { 'content-type': 'application/json' }, body: JSON.stringify({ task_id: task.task_id }) })
1381
+ const result = await readLocalJsonResponse(response)
1382
+ if (!response.ok || !result.canceled) throw new Error(result.message || '任务已结束或无法取消,请刷新状态。')
1383
+ await load(); setMessage('已请求取消任务。')
1384
+ } catch (error) { setMessage(error.message) }
1385
+ finally { setBusy(false) }
1386
+ }
1387
+ const robotCard = h('section', { style: collaborationCardStyle, 'aria-label': '机器人和设备' },
1388
+ h('div', { style: { display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 8 } },
1389
+ h('strong', null, '机器人和设备'),
1390
+ h('button', { type: 'button', disabled: loading || busy,
1391
+ onClick: () => void load().catch((error) => setMessage(error.message)), style: secondaryButtonStyle },
1392
+ loading ? '读取中…' : '刷新状态')),
1393
+ h('p', { role: 'status', style: mutedTextStyle }, collaborationStatus),
1394
+ bots.length ? h('label', null, '我的机器人', h('select', { id: 'ant-bot-selector', value: botId,
1395
+ onChange: (event) => { setBotId(event.target.value); setGroupId('') }, style: inputStyle },
1396
+ h('option', { value: '' }, '请选择机器人'),
1397
+ ...bots.map((bot) => h('option', { key: bot.bot_id, value: bot.bot_id,
1398
+ disabled: !bot.available || !bot.connected }, rawLocaleText(bot.name),
1399
+ bot.available && bot.connected ? null : '(未连接)')))) : null,
1400
+ connectedBots.length === 0 && !loading && !botLoadError ? h('div', { style: { display: 'flex', gap: 8, alignItems: 'center', flexWrap: 'wrap' } },
1401
+ h('button', { type: 'button', onClick: openImSettings, style: secondaryButtonStyle }, '打开 DSH-IM 设置'),
1402
+ h('span', { style: mutedTextStyle }, '先在 DSH 的插件列表安装并连接飞书机器人。')) : null,
1403
+ selectedBot && !botConnected && connectedBots.length ? h('button', { type: 'button', onClick: openImSettings,
1404
+ style: secondaryButtonStyle }, '检查 DSH-IM 连接') : null,
1405
+ selectedBot && !selectedEnrollmentBound ? h('button', { type: 'button', disabled: busy || !botConnected || enrollmentLoadError,
1406
+ onClick: () => void enrollBot(), style: primaryButtonStyle },
1407
+ selectedEnrollment ? '绑定原协作配置到这台 DSH' : '启用并绑定到这台 DSH') : null)
1408
+ const groupTaskStatusPanel = selectedEnrollmentBound && botConnected ? h('section', {
1409
+ id: 'ant-group-task-status', role: 'region', 'aria-label': '各群聊天与任务状态', tabIndex: -1,
1410
+ style: { ...collaborationCardStyle, gap: 10 } },
1411
+ h('div', { style: { display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 8 } },
1412
+ h('strong', null, '群聊'),
1413
+ h('button', { type: 'button', disabled: busy || loading,
1414
+ onClick: () => void load().catch((error) => setMessage(error.message)), style: secondaryButtonStyle },
1415
+ loading ? '读取中…' : '刷新群列表')),
1416
+ h('p', { style: mutedTextStyle }, groupChatLoadFailed
1417
+ ? '群列表暂不可用,请刷新状态后重试。'
1418
+ : availableGroups.length ? '每个群分别控制普通聊天和任务;名称取自 DSH-IM 已保存目标,括号内为识别码末两位。未匹配名称时显示完整识别码。'
1419
+ : '先在目标群 @机器人,再刷新状态发现群。'),
1420
+ availableGroups.length ? h('div', { id: 'ant-group-card-grid', style: collaborationGridStyle },
1421
+ ...availableGroups.map((group) => {
1422
+ const taskCount = activeCards.filter((card) => card.bot_fingerprint === selectedBot.fingerprint
1423
+ && card.conversation_kind === 'group' && card.conversation_id === group.group_id).length
1424
+ return h('article', { key: group.group_id, style: { ...collaborationCardStyle, padding: 10, gap: 8 } },
1425
+ h('div', { style: { display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 8 } },
1426
+ h('strong', { title: `完整识别码 ${group.group_code}` }, rawLocaleText(groupLabel(group))),
1427
+ h('span', { style: mutedTextStyle }, `已开放任务 ${taskCount} 项`)),
1428
+ h('label', { style: { display: 'flex', alignItems: 'center', gap: 8 } },
1429
+ h('input', { type: 'checkbox', checked: group.chat_enabled,
1430
+ disabled: busy || groupChatLoadFailed,
1431
+ onChange: (event) => void saveGroupChat(event.target.checked, group.group_id),
1432
+ 'aria-label': translateLocaleText('允许群 {group} 普通聊天', { group: groupLabel(group) }) }), '普通聊天'),
1433
+ h('button', { type: 'button', disabled: busy, style: secondaryButtonStyle,
1434
+ onClick: () => { startNewCard({ conversationKind: 'group', groupId: group.group_id }); focusAfterTabChange('collaboration', 'ant-new-task-summary') } },
1435
+ '为此群开放任务'))
1436
+ })) : h('div', { style: infoNoticeStyle },
1437
+ h('strong', null, '还没有发现群'),
1438
+ h('span', { style: mutedTextStyle }, '在目标群 @机器人后刷新列表。'))) : null
1439
+ return h('section', { style: { ...settingsPanelStyle,
1440
+ display: ['collaboration', 'local'].includes(activeTab) ? 'grid' : 'none' },
1441
+ 'aria-label': '群聊协作设置' },
1442
+ message && !(activeTab === 'collaboration' && createOpen
1443
+ && submissionError && message === submissionError)
1444
+ ? h('p', { role: 'status', style: feedbackNoticeStyle }, message) : null,
1445
+ h('div', { id: 'ant-chat-entry', role: 'region', 'aria-label': '聊天入口和机器人状态', tabIndex: -1,
1446
+ style: { display: activeTab === 'collaboration' ? 'grid' : 'none', gap: 12 } },
1447
+ h('div', { style: { display: 'flex', justifyContent: 'space-between', alignItems: 'start', gap: 12, flexWrap: 'wrap' } },
1448
+ h('div', { style: { display: 'grid', gap: 4 } },
1449
+ h('h3', { style: sectionTitleStyle }, '协作总览'),
1450
+ h('p', { style: mutedTextStyle }, '选择机器人,设置聊天入口,再按需要开放任务规则。聊天和任务授权分别控制。')),
1451
+ h('span', { style: { ...mutedTextStyle, padding: '4px 9px', borderRadius: 999,
1452
+ backgroundColor: 'var(--dsw-alias-bg-layer-2)' } }, selectedBot ? selectedBot.name : '尚未选择机器人')),
1453
+ loadFailures.length ? h('p', { role: 'status', style: mutedTextStyle },
1454
+ `部分协作信息暂时无法读取:${loadFailures.map((path) => loadNames[path]).join('、')}。已读取的信息仍显示,请稍后刷新状态。`) : null,
1455
+ h('div', { id: 'ant-collaboration-settings-grid', style: collaborationSettingsGridStyle },
1456
+ robotCard,
1457
+ chatScopePanel,
1458
+ ),
1459
+ setupStepper,
1460
+ groupTaskStatusPanel,
1461
+ selectedEnrollmentBound && botConnected ? h('p', { style: mutedTextStyle },
1462
+ dmChatEnabled
1463
+ ? `自测:私聊“${selectedBot.name}”发送“你能做什么”;发起任务后可问“刚才的任务怎么样了”。`
1464
+ : '私聊当前已关闭;如要恢复,请在上方开启。') : null,
1465
+ ),
1466
+ h('div', { id: 'ant-capability-list', role: 'region', 'aria-label': '已开放任务规则', tabIndex: -1,
1467
+ style: { display: activeTab === 'collaboration' ? 'grid' : 'none', gap: 12 } },
1468
+ h('div', { style: { display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 10, flexWrap: 'wrap' } },
1469
+ h('h4', { style: sectionTitleStyle }, '我的任务规则 · ' +
1470
+ (authorizationLoadError ? translateLocaleText('暂未读取') : activeCards.length)),
1471
+ h('div', { role: 'toolbar', 'aria-label': '任务规则操作', style: { display: 'flex', gap: 8, flexWrap: 'wrap' } },
1472
+ h('button', { type: 'button', onClick: () => { startNewCard(); focusAfterTabChange('collaboration', 'ant-new-task-summary') },
1473
+ style: primaryButtonStyle }, '新建任务规则'))),
1474
+ h('p', { style: mutedTextStyle }, '当前一项能力只能绑定一个范围:私聊,或某一个群。若要给其他群或私聊开放相同任务,目前需分别建立能力卡;它们的请求人和有效期独立。'),
1475
+ h('div', { id: 'ant-capability-cards', style: collaborationGridStyle },
1476
+ ...activeCards.map((card) => {
1477
+ const expiresAt = Number(card.expires_at) * 1000
1478
+ const remainingDays = Math.max(1, Math.ceil((expiresAt - Date.now()) / 86_400_000))
1479
+ const expiry = remainingDays <= 7
1480
+ ? translateLocaleText('{days} 天后到期', { days: formatLocaleNumber(remainingDays) })
1481
+ : translateLocaleText('至 {expiry_date}', { expiry_date: formatLocaleDate(expiresAt, { dateStyle: 'short' }) })
1482
+ const conversation = card.conversation_kind === 'group'
1483
+ ? `${translateLocaleText('群')} ${groupLabel(groups.find((group) => group.bot_fingerprint === card.bot_fingerprint
1484
+ && group.group_id === card.conversation_id)) || card.conversation_id}`
1485
+ : translateLocaleText('私聊')
1486
+ const requester = translateLocaleText(card.sender_scope === 'allowlist' ? '指定成员可请求'
1487
+ : card.conversation_kind === 'group' ? '群成员可请求' : '可私聊者可请求')
1488
+ const blockedExternalExecutor = card.runner !== 'dsh' || card.cross_review_always === true
1489
+ const examplesText = Array.isArray(card.examples) ? card.examples.join('、') : ''
1490
+ const requesterIds = card.sender_scope === 'allowlist' && Array.isArray(card.sender_ids) ? card.sender_ids.join('、') : ''
1491
+ const remainingDaysLabel = remainingDays <= 7 ? 'var(--dsw-alias-state-warning-primary, var(--dsw-alias-label-secondary))'
1492
+ : 'var(--dsw-alias-label-secondary)'
1493
+ return h('article', { key: card.id, style: { ...collaborationCardStyle, padding: 12, gap: 8 } },
1494
+ h('div', { style: { display: 'grid', gap: 6, minWidth: 0 } },
1495
+ h('div', { style: { display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap' } },
1496
+ h('strong', { style: { overflowWrap: 'anywhere' } },
1497
+ card.title ? rawLocaleText(card.title) : '未命名能力'),
1498
+ h('span', { style: { ...mutedTextStyle, padding: '2px 8px', borderRadius: 999,
1499
+ backgroundColor: 'var(--dsw-alias-bg-layer-2)', color: remainingDaysLabel, whiteSpace: 'nowrap' } }, expiry)),
1500
+ h('span', { style: mutedTextStyle }, translateLocaleText(
1501
+ '{reviewers} · {conversation} · {requesters} · 结果回复原{destination}', {
1502
+ reviewers: cardReviewerSummary(card), conversation, requesters: requester,
1503
+ destination: translateLocaleText(card.conversation_kind === 'group' ? '群' : '私聊'),
1504
+ })),
1505
+ blockedExternalExecutor ? h('p', { role: 'status', style: { ...mutedTextStyle,
1506
+ color: 'var(--dsw-alias-state-warning-primary, var(--dsw-alias-label-secondary))' } },
1507
+ '此任务暂不可执行:当前无法核验外部 Agent 的逐任务权限。点击“编辑”,改用 DSH 并移除外部 Agent 后可重新开放。') : null,
1508
+ card.rule_description
1509
+ ? h('span', { style: { ...mutedTextStyle, overflowWrap: 'anywhere' } }, rawLocaleText(card.rule_description))
1510
+ : h('span', { role: 'status', style: { ...mutedTextStyle, color: 'var(--dsw-alias-state-warning-primary, var(--dsw-alias-label-secondary))' } },
1511
+ '旧任务卡没有自然语言描述。请编辑并补充描述,让 AI 生成 Harness 后再开放。'),
1512
+ h('details', null,
1513
+ h('summary', { style: { cursor: 'pointer', color: 'var(--dsw-alias-link)', fontSize: 13 } }, '查看规则说明'),
1514
+ h('div', { style: { display: 'grid', gap: 4, paddingTop: 6 } },
1515
+ card.rule_description ? h('p', { style: { ...mutedTextStyle, overflowWrap: 'anywhere' } }, rawLocaleText(card.rule_description)) : null,
1516
+ requesterIds ? h('p', { style: { ...mutedTextStyle, overflowWrap: 'anywhere' } }, '允许请求的 IM 用户:', rawLocaleText(requesterIds)) : null,
1517
+ examplesText ? h('p', { style: mutedTextStyle }, '请求示例:', rawLocaleText(examplesText)) : null,
1518
+ Array.isArray(card.parameters) && card.parameters.length
1519
+ ? h('p', { style: { ...mutedTextStyle, overflowWrap: 'anywhere' } },
1520
+ `请求时还需提供:${card.parameters.map(parameterSummary).join(';')}`)
1521
+ : h('p', { style: mutedTextStyle }, '无需额外参数,按请求中的内容处理'),
1522
+ card.task_prompt ? h('p', { style: mutedTextStyle }, '处理要求:', rawLocaleText(card.task_prompt)) : null))),
1523
+ h('div', { style: { display: 'flex', gap: 6, flexWrap: 'wrap', justifyContent: 'flex-end', paddingTop: 4,
1524
+ borderTop: '1px solid var(--dsw-alias-border-l2)' } },
1525
+ h('button', { type: 'button', disabled: busy, onClick: () => editCard(card), style: secondaryButtonStyle }, '编辑'),
1526
+ h('button', { type: 'button', disabled: busy, onClick: () => copyCardToDraft(card), style: secondaryButtonStyle }, '复制'),
1527
+ h('button', { type: 'button', disabled: busy, onClick: () => void revokeCard(card), style: secondaryButtonStyle }, '停止')))
1528
+ }),
1529
+ activeCards.length === 0 ? h('div', { style: { ...collaborationCardStyle, gridColumn: '1 / -1', justifyItems: 'start' } },
1530
+ h('p', { style: mutedTextStyle }, authorizationLoadError
1531
+ ? '暂时无法确认已开放的能力。刷新授权状态后再试;列表未核实前请勿重复创建。'
1532
+ : '还没有开放任务。先描述要做什么,再设置请求范围和有效期。'),
1533
+ authorizationLoadError ? h('button', { type: 'button', disabled: loading,
1534
+ onClick: () => void load().catch((error) => setMessage(error.message)), style: secondaryButtonStyle },
1535
+ loading ? '正在刷新…' : '刷新授权状态') : null) : null),
1536
+ ),
1537
+ h('div', { role: 'region', 'aria-label': '最近任务', style: { display: activeTab === 'local' ? 'grid' : 'none', gap: 12 } },
1538
+ h('h4', { style: sectionTitleStyle }, '最近任务'),
1539
+ h('p', { style: mutedTextStyle }, translateLocaleText('本页显示任务失败原因和结果发送状态;完整结果仍回复到原群或私聊。')),
1540
+ ...(tasks.filter((task) => task.task_id).length ? tasks.filter((task) => task.task_id)
1541
+ .map((task) => {
1542
+ const title = task.title ? rawLocaleText(task.title) : task.pr_number
1543
+ ? task.repository
1544
+ ? translateLocaleText('{repository} PR #{pr_number} 差异审查', { repository: task.repository, pr_number: task.pr_number })
1545
+ : translateLocaleText('PR #{pr_number} 差异审查', { pr_number: task.pr_number })
1546
+ : '任务'
1547
+ const status = translateLocaleText(task.outcome === 'canceled' ? '已取消' : task.outcome === 'failed' ? '未完成' : ({
1548
+ pending: '排队中', running: '处理中', reply_pending: '结果待发送', reply_attempted: '回复状态待核对', done: '已回复',
1549
+ }[task.status] || task.status))
1550
+ const createdAt = task.created_at && Number.isFinite(Date.parse(task.created_at))
1551
+ ? formatLocaleDate(task.created_at) : ''
1552
+ const taskStatusLine = translateLocaleText('{status}{time_label} · 任务 {task_id}', {
1553
+ status, time_label: createdAt ? ` · ${createdAt}` : '', task_id: task.task_id,
1554
+ })
1555
+ return h('div', { key: task.task_id, style: { display: 'flex', gap: 12, alignItems: 'center',
1556
+ justifyContent: 'space-between', flexWrap: 'wrap', borderTop: '1px solid var(--dsw-alias-border-l2)', paddingTop: 8 } },
1557
+ h('div', { style: { display: 'grid', gap: 6, flex: '1 1 280px', minWidth: 0, overflowWrap: 'anywhere' } },
1558
+ h('strong', null, title),
1559
+ h('div', { style: mutedTextStyle }, taskStatusLine),
1560
+ task.failure_reason ? h('div', { role: 'alert', style: warningNoticeStyle },
1561
+ h('span', { style: { ...mutedTextStyle, whiteSpace: 'pre-line' } }, translateLocaleText(
1562
+ '任务未完成:{reason}\n处理建议:按错误提示修复配置或请求内容后,在原群或私聊重新发起。',
1563
+ { reason: task.failure_reason }))) : null,
1564
+ task.delivery_error ? h('div', { role: 'alert', style: warningNoticeStyle },
1565
+ h('span', { style: { ...mutedTextStyle, whiteSpace: 'pre-line' } }, translateLocaleText(
1566
+ '结果发送状态未确认:{reason}\n处理建议:先检查原群或私聊是否已收到结果;若未收到,再修复连接问题后重试。',
1567
+ { reason: task.delivery_error }))) : null,
1568
+ task.status === 'reply_attempted' && !task.delivery_error ? h('div', { role: 'status', style: warningNoticeStyle },
1569
+ h('span', { style: mutedTextStyle }, translateLocaleText(
1570
+ 'ANT 尚未确认消息平台是否收到结果。请先检查原群或私聊,再决定是否重新发起。'))) : null),
1571
+ ['card_task', 'legacy_pr_task'].includes(task.kind) && ['pending', 'running'].includes(task.status) ? h('button', { type: 'button', disabled: busy,
1572
+ onClick: () => void cancelTask(task), style: secondaryButtonStyle }, '取消任务') : null)
1573
+ })
1574
+ : [h('p', { key: 'none', style: mutedTextStyle }, loadFailures.includes('status')
1575
+ ? '任务记录暂时无法读取,请刷新状态。' : '暂无任务。')])),
1576
+ h('div', { role: 'region', 'aria-label': '任务规则编辑器', style: { display: activeTab === 'collaboration' ? 'grid' : 'none' } },
1577
+ h('details', { id: 'ant-new-task', open: createOpen,
1578
+ onToggle: (event) => setCreateOpen(event.currentTarget.open),
1579
+ style: { border: '1px solid var(--dsw-alias-border-l2)', borderRadius: 8, padding: 12 } },
1580
+ h('summary', { id: 'ant-new-task-summary', style: { cursor: 'pointer', fontWeight: 600 } }, editingCardId ? '编辑能力配置' : '开放一项能力'),
1581
+ h('div', { style: { display: 'grid', gridTemplateColumns: 'minmax(0, 1fr)',
1582
+ gap: 12, alignItems: 'start', marginTop: 12 } },
1583
+ h('form', { id: 'ant-capability-create-form', onSubmit: createCard, style: { display: 'grid', gap: 9, minWidth: 0 } },
1584
+ editingCardId ? h('p', { role: 'status', style: mutedTextStyle },
1585
+ `保存会生成新的授权版本并停止旧版本;到期时间保持不变:${formatLocaleDate(editingExpiresAt * 1000)}。已提交任务继续使用原配置。`) : null,
1586
+ h('p', { style: mutedTextStyle }, selectedBot
1587
+ ? `当前机器人:${selectedBot.name}${selectedEnrollmentBound ? ' · 已绑定此设备' : ' · 请先绑定到此设备'}`
1588
+ : '请先在上方选择机器人并启用协作。'),
1589
+ draftNotice ? h('p', { role: 'status', style: { ...mutedTextStyle,
1590
+ color: 'var(--dsw-alias-state-warning-primary, var(--dsw-alias-label-secondary))' } }, draftNotice) : null,
1591
+ selectedEnrollmentBound ? h('p', { style: mutedTextStyle },
1592
+ '机器人及其任务能力只在这台 DSH 设备接收和执行;同一账号的其他设备不会继承本机授权。') : null,
1593
+ selectedEnrollment && !selectedEnrollmentBound ? h('p', { style: mutedTextStyle },
1594
+ '这是尚未绑定到设备的机器人。请在要继续使用它的电脑重新启用;原协作配置会保留。若旧设备访问曾被撤销,原任务权限不会恢复,需要重新开放。') : null,
1595
+ selectedBot && conversationKind === 'group' && !selectedBot.history_available ? h('p', { role: 'status', style: mutedTextStyle },
1596
+ '这个机器人当前不能读取平台群历史;群聊只能参考实际送达的消息和本机近期记录。请检查 DSH-IM 权限。') : null,
1597
+ h('div', { style: { display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(min(100%, 320px), 1fr))',
1598
+ gap: 12, alignItems: 'start' } },
1599
+ h('div', { style: { display: 'grid', gap: 9, minWidth: 0 } },
1600
+ h('label', null, '描述规则', h('textarea', { required: true, maxLength: 4000, rows: 4, value: ruleDescription,
1601
+ onChange: (event) => {
1602
+ autoAnalyzeDescriptionRef.current = event.target.value
1603
+ recognitionRequestRef.current += 1
1604
+ setRuleDescription(event.target.value)
1605
+ setRecognitionBusy(false)
1606
+ setRecognitionMessage(event.target.value.trim() ? '你暂停输入后,AI 会自动检查任务是否完整。' : '')
1607
+ },
1608
+ placeholder: '用日常语言说明要完成什么、可处理哪些资料和希望怎样返回。例如:审查来自 https://gitea.example.com/team/shop 的 PR,指出可定位的问题,不修改代码;请求人可指定 Head SHA,未指定时用最新 Head。', style: inputStyle })),
1609
+ h('p', { style: mutedTextStyle }, 'AI 会在输入停顿后分析必需范围、缺失信息和可选条件。执行方、请求人、群范围和有效期由下方通用授权控制。'),
1610
+ h('div', { style: { display: 'flex', gap: 10, alignItems: 'center', flexWrap: 'wrap' } },
1611
+ h('button', { type: 'button', disabled: recognitionBusy || busy || !ruleDescription.trim(),
1612
+ onClick: () => void identifyRule(), style: secondaryButtonStyle }, recognitionBusy ? 'AI 正在分析…' : ruleSummaryReady ? '立即重新分析' : '立即分析'),
1613
+ h('span', { style: mutedTextStyle }, '自动分析和手动分析都会调用当前团队模型;只生成建议和待复核草稿,不会开放任务。')),
1614
+ recognitionMessage ? h('p', { role: 'status', 'aria-live': 'polite', style: feedbackNoticeStyle }, recognitionMessage) : null),
1615
+ h('section', { role: 'region', 'aria-label': 'AI 任务助手', style: { ...panelStyle, padding: 10, gap: 7, minWidth: 0 } },
1616
+ h('div', { style: { display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8 } },
1617
+ h('strong', null, ruleSummaryPending ? 'AI 正在检查当前描述' : title || 'AI 任务助手'),
1618
+ h('span', { style: mutedTextStyle }, ruleSummaryPending ? '描述已更新' : ruleSummaryReady ? '待复核 · 尚未开放' : '填写描述后开始分析')),
1619
+ h('p', { style: { ...mutedTextStyle, overflowWrap: 'anywhere' } }, ruleSummaryPending
1620
+ ? 'AI 正在根据当前描述更新任务理解。上一次分析结果暂不用于授权开放。' : ruleSummaryNarrative),
1621
+ ruleSummaryReady && missingHarnessInputs.length ? h('p', { role: 'status', style: { ...mutedTextStyle,
1622
+ color: 'var(--dsw-alias-state-warning-primary, var(--dsw-alias-label-secondary))' } },
1623
+ `还需要明确:${missingHarnessInputs.join(';')}`) : ruleSummaryReady
1624
+ ? h('p', { role: 'status', style: mutedTextStyle }, 'AI 暂未发现必需信息缺项;请确认任务来源和处理范围符合预期。') : null,
1625
+ ruleSummaryReady && suggestions.length ? h('p', { style: mutedTextStyle }, `可选补充:${suggestions.join(';')}`) : null,
1626
+ ruleSummaryReady && ruleExamples.length ? h('p', { style: mutedTextStyle }, `自然请求示例:${ruleExamples.join(';')}`) : null,
1627
+ h('p', { style: mutedTextStyle }, ruleSummaryReady
1628
+ ? '草稿未开放。检查任务理解、必需范围和建议;有误就改描述,AI 会重新分析。'
1629
+ : ruleSummaryPending ? '分析完成前不能开放任务。' : 'AI 会整理任务理解;草稿不会自动开放。'))),
1630
+ h('section', { style: { ...panelStyle, padding: 10, gap: 9, display: 'grid',
1631
+ gridTemplateColumns: 'repeat(auto-fit, minmax(min(100%, 280px), 1fr))' } },
1632
+ h('strong', { style: { gridColumn: '1 / -1' } }, '通用授权'),
1633
+ h('p', { style: { ...mutedTextStyle, gridColumn: '1 / -1' } },
1634
+ '上方描述规则任务要做什么;这里限定谁能请求、在哪里请求、由谁执行和授权多久。'),
1635
+ h('label', null, '执行方', h('select', { value: runner, onChange: (event) => selectRunner(event.target.value),
1636
+ style: inputStyle },
1637
+ h('option', { value: 'dsh', disabled: !dshAvailable && runner !== 'dsh' }, 'DSH · 当前团队模型'),
1638
+ h('option', { value: 'codex', disabled: runner !== 'codex' }, 'Codex · DSH 子 Agent'),
1639
+ h('option', { value: 'claude-code', disabled: runner !== 'claude-code' }, 'Claude Code · DSH 子 Agent')),
1640
+ h('span', { style: mutedTextStyle }, runner === 'codex'
1641
+ ? 'Codex 暂不可用于协作任务:ANT 无法核验它的逐任务文件、Git 和网络权限。'
1642
+ : runner === 'claude-code' ? 'Claude Code 暂不可用于协作任务:ANT 无法核验它的逐任务文件、Git 和网络权限。'
1643
+ : 'DSH 使用获准团队模型处理对话内容和 ANT 已核验后提供的资源。')),
1644
+ h('details', { id: 'ant-parallel-agents-details', open: parallelAgentsOpen,
1645
+ onToggle: (event) => setParallelAgentsOpen(event.currentTarget.open),
1646
+ style: { gridColumn: '1 / -1', border: '1px solid var(--dsw-alias-border-l2)', borderRadius: 8, padding: 10 } },
1647
+ h('summary', { style: { cursor: 'pointer', fontWeight: 600 } }, parallelAgentsSummary
1648
+ ? `并行执行:${parallelAgentsSummary}` : '多 Agent 并行(可选)'),
1649
+ h('p', { style: mutedTextStyle }, '当前只开放 DSH。外部 Agent 的逐任务文件、Git 和网络权限无法由 ANT 核验;编辑旧任务时可取消其选择并改用 DSH。'),
1650
+ h('div', { style: { display: 'flex', gap: 14, flexWrap: 'wrap' } },
1651
+ h('label', null, h('input', { type: 'checkbox', 'aria-label': '任务 Agent DSH', checked: reviewers.includes('dsh'),
1652
+ disabled: !dshAvailable && !reviewers.includes('dsh'),
1653
+ onChange: (event) => changeReviewer('dsh', event.target.checked) }), ' DSH'),
1654
+ h('label', null, h('input', { type: 'checkbox', 'aria-label': '任务 Agent Codex', checked: reviewers.includes('codex'),
1655
+ disabled: !reviewers.includes('codex'),
1656
+ onChange: (event) => changeReviewer('codex', event.target.checked) }), ' Codex'),
1657
+ h('label', null, h('input', { type: 'checkbox', 'aria-label': '任务 Agent Claude Code', checked: reviewers.includes('claude-code'),
1658
+ disabled: !reviewers.includes('claude-code'),
1659
+ onChange: (event) => changeReviewer('claude-code', event.target.checked) }), ' Claude Code')),
1660
+ null),
1661
+ nativePrUnavailableReason ? h('p', { role: 'status', style: { ...mutedTextStyle, gridColumn: '1 / -1' } },
1662
+ `${nativePrUnavailableReason}。当前仍可使用 DSH 团队模型处理任务。`) : null,
1663
+ h('label', null, '使用场景', h('select', { value: conversationKind,
1664
+ onChange: (event) => { setConversationKind(event.target.value); setGroupId('') }, style: inputStyle },
1665
+ h('option', { value: 'dm' }, '私聊'), h('option', { value: 'group' }, '指定群聊'))),
1666
+ conversationKind === 'group' ? h('div', { style: { display: 'grid', gridTemplateColumns: 'minmax(0, 1fr) auto',
1667
+ gap: 8, alignItems: 'end' } },
1668
+ h('label', null, '群聊', h('select', { required: true, value: groupId,
1669
+ onChange: (event) => setGroupId(event.target.value), style: inputStyle },
1670
+ h('option', { value: '' }, '让群成员先 @ 机器人,再刷新列表'),
1671
+ ...availableGroups.map((group) => h('option', { key: group.group_id, value: group.group_id },
1672
+ rawLocaleText(groupLabel(group)))))),
1673
+ h('button', { type: 'button', disabled: busy,
1674
+ onClick: () => void load().catch((error) => setMessage(error.message)), style: secondaryButtonStyle }, '刷新群列表')) : null,
1675
+ h('label', null, '谁可以请求', h('select', { value: senderScope,
1676
+ onChange: (event) => setSenderScope(event.target.value), style: inputStyle },
1677
+ h('option', { value: 'any' }, conversationKind === 'group' ? '此群任何成员' : '任何能私聊此机器人者'),
1678
+ h('option', { value: 'allowlist' }, '指定 IM 用户 ID'))),
1679
+ senderScope === 'allowlist' ? h('label', null, '可请求成员 ID', h('input', { 'aria-label': '可请求的 IM 用户 ID',
1680
+ required: true, value: senderIds, onChange: (event) => setSenderIds(event.target.value),
1681
+ placeholder: '多个 ID 用逗号分隔', style: inputStyle })) : null,
1682
+ editingCardId ? h('p', { style: { ...mutedTextStyle, alignSelf: 'end' } },
1683
+ `有效期:${formatLocaleDate(editingExpiresAt * 1000)}(编辑时保持不变)`)
1684
+ : h('label', null, '有效期', h('select', { value: days, onChange: (event) => setDays(Number(event.target.value)), style: inputStyle },
1685
+ h('option', { value: 1 }, '1 天'), h('option', { value: 7 }, '7 天'), h('option', { value: 30 }, '30 天'))),
1686
+ (runner === 'codex' || runner === 'claude-code') ? h('p', { style: { ...mutedTextStyle, gridColumn: '1 / -1' } },
1687
+ 'Provider Profile 的本机权限由 DSH 管理;ANT 当前不会用 Codex 或 Claude Code 执行协作任务,也不会把 Gitea 凭据交给它们。') : null),
1688
+ !hasPrParameter ? h('p', { style: mutedTextStyle },
1689
+ 'Codex 和 Claude Code 即使已在 DSH 注册,目前也不用于任何协作任务。') : null),
1690
+ h('aside', { id: 'ant-authorization-review', role: 'region', 'aria-label': '开放前复核', tabIndex: -1,
1691
+ style: { ...settingsPanelStyle, padding: 14, gap: 10, alignSelf: 'stretch' } },
1692
+ h('div', { style: { display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 8 } },
1693
+ h('h4', { style: sectionTitleStyle }, '开放前看一眼'),
1694
+ h('span', { style: { ...mutedTextStyle, padding: '3px 8px', borderRadius: 999,
1695
+ backgroundColor: 'var(--dsw-alias-bg-layer-2)' } }, '草稿 · 未开放')),
1696
+ h('p', { style: mutedTextStyle }, translateLocaleText(
1697
+ '这项任务将在{conversation}开放给{requesters},由{executor}执行;有效期 {expiry},{result_destination}。',
1698
+ {
1699
+ conversation: conversationKind === 'group'
1700
+ ? translateLocaleText('群“{group_name}”',
1701
+ { group_name: selectedGroupSummary || translateLocaleText('尚未选择') })
1702
+ : translateLocaleText('私聊'),
1703
+ requesters: requesterSummary,
1704
+ executor: executorSummary,
1705
+ expiry: editingCardId ? formatLocaleDate(editingExpiresAt * 1000)
1706
+ : `${formatLocaleNumber(days)} ${translateLocaleText('天')}`,
1707
+ result_destination: resultRouteSummary,
1708
+ })),
1709
+ hasPrParameter && !selectedGiteaOrigin && taskPrOrigins.length === 1
1710
+ ? h('p', { role: 'note', style: mutedTextStyle },
1711
+ `首次确认开放后,这台机器人会绑定到 ${taskPrOrigins[0]};后续 PR 任务只允许使用此主机,令牌不会发往其他主机。`)
1712
+ : null,
1713
+ hasPrParameter && selectedGiteaOrigin
1714
+ ? h('p', { role: 'note', style: mutedTextStyle },
1715
+ `这台机器人已绑定 ${selectedGiteaOrigin};任务来源需与此主机一致,令牌不会发往其他主机。`)
1716
+ : null,
1717
+ cardBlockReason ? h('div', { id: 'ant-capability-block-reason', role: 'alert', 'aria-live': 'assertive',
1718
+ style: warningNoticeStyle }, h('p', { style: mutedTextStyle }, cardBlockReason)) : null,
1719
+ submissionError ? h('div', { id: 'ant-capability-submission-error', role: 'alert', 'aria-live': 'assertive', style: warningNoticeStyle },
1720
+ h('p', { style: { ...mutedTextStyle, whiteSpace: 'pre-line' } }, translateLocaleText(
1721
+ '开放失败:{reason}\n处理建议:按错误提示修正配置后重试;若提示版本不兼容,请管理员升级 ANT 插件或服务端。',
1722
+ { reason: submissionError }))) : null,
1723
+ h('button', { type: 'submit', form: 'ant-capability-create-form', disabled: busy || Boolean(cardBlockReason),
1724
+ 'aria-describedby': cardBlockReason ? 'ant-capability-block-reason'
1725
+ : submissionError ? 'ant-capability-submission-error' : undefined,
1726
+ style: { ...primaryButtonStyle, width: '100%' } }, busy ? translateLocaleText('正在处理…')
1727
+ : editingCardId ? '保存能力修改' : '确认并开放能力'))))),
1728
+ h('div', { role: 'region', 'aria-label': '本机处理设置', style: { display: activeTab === 'local' ? 'grid' : 'none', gap: 12 } },
1729
+ showPrSecuritySettings ? h('section', { style: { ...settingsPanelStyle, padding: 14 } },
1730
+ h('strong', null, 'PR 只读凭据(本机)'),
1731
+ h('p', { style: mutedTextStyle }, tokenConfigured
1732
+ ? '令牌由 DSH 本机凭据服务保存。ANT Host 在读取已授权 PR 时会使用它;不会同步到 ANT 服务端或写入审查提示词。'
1733
+ : '读取 Gitea PR 需要只读访问令牌。保存后由 DSH 本机凭据服务管理,ANT Host 只在读取已授权 PR 时使用。'),
1734
+ h('p', { role: 'note', style: mutedTextStyle }, 'DSH 默认将凭据保存在 DSH Home 的私有文件中,环境变量也可作为回退来源。文件权限只隔离其他 OS 用户;同一用户权限下的 Agent 进程可能读取它。ANT 当前只允许无 DSH 工具的任务会话处理对话内容和 Host 核验后提供的资源。Codex 和 Claude Code 子 Agent 暂停用于协作任务,因为 ANT 无法核验其逐任务文件、Git 和网络权限。ANT Gitea 凭据只由 Host Connector 使用,不会放入 Agent 请求。'),
1735
+ h('p', { role: 'note', style: mutedTextStyle }, selectedGiteaOrigin
1736
+ ? `这枚只读令牌仅用于已绑定主机 ${selectedGiteaOrigin};任务来源来自自然语言描述,但必须匹配该主机。`
1737
+ : '首次确认并开放包含 PR 来源的任务时,会将该来源绑定到这台机器人;确认前 ANT 不会把只读令牌发送到任务描述中的地址。'),
1738
+ h('div', { style: { display: 'flex', gap: 8, flexWrap: 'wrap' } },
1739
+ h('input', { 'aria-label': 'Gitea 只读访问令牌', type: 'password', autoComplete: 'new-password', value: giteaToken,
1740
+ onChange: (event) => setGiteaToken(event.target.value),
1741
+ placeholder: tokenConfigured ? '已保存;输入新令牌可替换' : '粘贴 Gitea 只读令牌',
1742
+ style: { ...inputStyle, flex: '1 1 280px' } }),
1743
+ h('button', { type: 'button', disabled: busy || !giteaToken.trim(),
1744
+ onClick: () => void saveGiteaToken(), style: secondaryButtonStyle }, tokenConfigured ? '替换本机令牌' : '保存本机令牌'))) : null,
1745
+ h('details', { style: { border: '1px solid var(--dsw-alias-border-l2)', borderRadius: 8, padding: 12 } },
1746
+ h('summary', { style: { cursor: 'pointer', fontWeight: 600 } }, '本机处理设置'),
1747
+ h('p', { style: mutedTextStyle }, '本机并发上限只影响这台电脑接收的新任务。外部代码执行器已暂停,当前不创建 PR 仓库缓存;缓存上限仅保留用于旧缓存回收,暂不可调整。'),
1748
+ h('div', { style: { display: 'flex', gap: 8, flexWrap: 'wrap', alignItems: 'center' } },
1749
+ h('span', { style: mutedTextStyle }, loadFailures.includes('settings') ? '团队默认值暂未读取。'
1750
+ : `团队默认:先看 ${defaults?.context_messages ?? 10} 条前文、最多翻阅 ${defaults?.history_max_records ?? 100} 条平台记录、同时处理 ${defaults?.max_concurrency ?? 3} 项任务。`),
1751
+ h('button', { type: 'button', onClick: () => void load().catch((error) => setMessage(error.message)), style: secondaryButtonStyle }, '刷新')),
1752
+ loadFailures.includes('local-settings') ? h('p', { role: 'status', style: mutedTextStyle },
1753
+ '本机处理设置暂未读取;请刷新后重试。')
1754
+ : h('form', { onSubmit: saveLocalProcessingSettings, style: { display: 'flex', gap: 12, flexWrap: 'wrap', alignItems: 'end' } },
1755
+ h('label', { style: { display: 'grid', gap: 5, flex: '0 1 280px', maxWidth: '100%' } }, '这台电脑最多同时处理',
1756
+ h('select', { value: localConcurrency == null ? '' : String(localConcurrency),
1757
+ onChange: (event) => setLocalConcurrency(event.target.value), style: { ...inputStyle, width: '100%' } },
1758
+ h('option', { value: '' }, '跟随团队默认'),
1759
+ ...Array.from({ length: 8 }, (_, index) => h('option', { key: index + 1, value: index + 1 }, `${index + 1} 项任务`)))),
1760
+ h('label', { style: { display: 'grid', gap: 5, flex: '0 1 200px', maxWidth: '100%' } },
1761
+ '这台电脑 PR 仓库缓存上限(GiB,暂不可调整)',
1762
+ h('input', { 'aria-label': '这台电脑 PR 仓库缓存上限(GiB)', type: 'number', min: 1, max: 100, step: 1,
1763
+ disabled: true,
1764
+ value: repositoryCacheLimitGib,
1765
+ style: { ...inputStyle, width: 128, maxWidth: '100%', boxSizing: 'border-box' } })),
1766
+ h('button', { disabled: busy, style: secondaryButtonStyle }, '保存本机处理设置'),
1767
+ h('p', { style: { ...mutedTextStyle, flex: '1 1 100%', margin: 0 } },
1768
+ '当前不拉取 PR 仓库快照;刷新授权状态时仍会清理已停用或到期能力的旧缓存。')),
1769
+ ),
1770
+ h('section', { 'aria-label': '执行方状态与权限边界', style: { ...settingsPanelStyle, padding: 14, gap: 8 } },
1771
+ h('strong', null, '执行方状态与权限边界'),
1772
+ h('p', { style: mutedTextStyle }, '这里显示 DSH 本机的执行器状态;Codex 或 Claude Code 已注册,不代表它们获准执行协作任务。'),
1773
+ loadFailures.includes('executors') ? h('p', { role: 'status', style: mutedTextStyle }, '暂时无法读取执行方状态,请刷新后重试。') : null,
1774
+ ...executors.filter((item) => ['dsh', 'codex', 'claude-code'].includes(item.id)).map((item) => h('div', {
1775
+ key: item.id, style: { display: 'grid', gap: 3, paddingTop: 8, borderTop: '1px solid var(--dsw-alias-border-l2)' } },
1776
+ h('strong', null, item.title + ' · ' + (item.id === 'dsh'
1777
+ ? item.available ? '可用' : item.reason || '未就绪'
1778
+ : item.available ? '已注册 · 协作任务暂不可用' : '协作任务暂不可用')),
1779
+ h('span', { style: mutedTextStyle }, item.id === 'codex'
1780
+ ? 'ANT 暂不启动 Codex 子 Agent,因为当前无法核验逐任务文件、Git 和网络权限。'
1781
+ : item.id === 'claude-code'
1782
+ ? 'ANT 暂不启动 Claude Code 子 Agent,因为当前无法核验逐任务文件、Git 和网络权限。'
1783
+ : '处理授权任务提供的内容,不调用本机工具。'))))))
1784
+ }
1785
+
1786
+ function SkillCenterPage({ remote, onBack, onAll, onSkills, onPlugins, openBundle,
1787
+ includePlugins, query, onQueryChange }) {
1788
+ const [skills, setSkills] = useState([])
1789
+ const [loading, setLoading] = useState(false)
1790
+ const [loadError, setLoadError] = useState(false)
1791
+ const [workingId, setWorkingId] = useState('')
1792
+ const [message, setMessage] = useState('')
1793
+ const [detailActionMessage, setDetailActionMessage] = useState(null)
1794
+ const [originalView, setOriginalView] = useState(null)
1795
+ const [selectedSkill, setSelectedSkill] = useState(null)
1796
+ const detailTriggerRef = useRef(null)
1797
+ const restoreDetailFocus = useRef(false)
1798
+ const originalGeneration = useRef(0)
1799
+ const [filter, setFilter] = useState('all')
1800
+ const [scopeFilter, setScopeFilter] = useState('all')
1801
+ const [categoryFilter, setCategoryFilter] = useState('all')
1802
+ const [refreshToken, setRefreshToken] = useState(0)
1803
+ const refreshGeneration = useRef(0)
1804
+ const refresh = async () => {
1805
+ const generation = ++refreshGeneration.current
1806
+ setLoading(true)
1807
+ try {
1808
+ const response = await fetch('/api/ant-teams/skills', { cache: 'no-store' })
1809
+ const result = await readLocalJsonResponse(response)
1810
+ if (!response.ok) throw new Error(response.status === 401
1811
+ ? '请返回 ANT 插件设置,先验证工作邮箱并连接团队。'
1812
+ : result.message || `读取技能失败(${response.status})。`)
1813
+ if (!Array.isArray(result.skills)) throw new Error('企业技能目录格式无效。')
1814
+ if (generation !== refreshGeneration.current) return false
1815
+ setSkills(result.skills)
1816
+ setSelectedSkill((current) => {
1817
+ if (!current) return current
1818
+ const refreshedSkill = result.skills.find((skill) => skill.id === current.id)
1819
+ if (!refreshedSkill) restoreDetailFocus.current = true
1820
+ return refreshedSkill || null
1821
+ })
1822
+ setLoadError(false)
1823
+ setMessage(result.warning || (result.skills.length ? '' : '当前没有可显示的全市场或本企业技能。管理员可能尚未启用,或已隐藏待启用的市场技能;下方仍可查看 DSH 官方技能。'))
1824
+ return true
1825
+ } catch (error) {
1826
+ if (generation !== refreshGeneration.current) return false
1827
+ setSkills([])
1828
+ setLoadError(true)
1829
+ setMessage(error instanceof Error ? error.message : '无法读取企业精选技能。')
1830
+ return false
1831
+ }
1832
+ finally { if (generation === refreshGeneration.current) setLoading(false) }
1833
+ }
1834
+ useEffect(() => { void refresh() }, [])
1835
+ useEffect(() => {
1836
+ if (!selectedSkill && restoreDetailFocus.current) {
1837
+ restoreDetailFocus.current = false
1838
+ detailTriggerRef.current?.focus()
1839
+ }
1840
+ }, [selectedSkill])
1841
+ const closeSkillDetails = () => {
1842
+ restoreDetailFocus.current = true
1843
+ setSelectedSkill(null)
1844
+ }
1845
+ const changeInstall = async (skill, remove = false) => {
1846
+ const action = remove ? '卸载' : skill.local_status === 'update-available' ? '更新' : '安装'
1847
+ const localizedAction = translateLocaleText(action)
1848
+ const reportInDetail = selectedSkill?.id === skill.id
1849
+ const prompt = remove
1850
+ ? skill.conflict_reason === 'other-source'
1851
+ ? '这台 DSH 已安装另一个来源的同名技能。确认卸载本机旧来源?已修改的本地文件不会被删除。'
1852
+ : translateLocaleText('从这台 DSH 卸载 {skill_title}?已修改的本地文件不会被删除。', { skill_title: skill.title })
1853
+ : translateLocaleText('将 {skill_title} {action}到这台 DSH?\n\n外部数据交互:{data_interactions}\n\n本机依赖:{requirements}\n\n技能可能让 DSH 读取文件或执行脚本,仍受 DSH 的工具授权控制。ANT 不会自动安装系统依赖。',
1854
+ { skill_title: skill.title, action: localizedAction,
1855
+ data_interactions: skill.data_interactions?.trim() || translateLocaleText('待管理员补充;使用前请先核实数据去向。'),
1856
+ requirements: skill.requirements })
1857
+ if (!confirmLocalized(prompt)) return
1858
+ setWorkingId(skill.id)
1859
+ const progressMessage = translateLocaleText('正在{action} {skill_title}…',
1860
+ { action: localizedAction, skill_title: skill.title })
1861
+ setMessage(progressMessage)
1862
+ if (reportInDetail) setDetailActionMessage({ skillId: skill.id, text: progressMessage })
1863
+ try {
1864
+ const response = await fetch(`/api/ant-teams/skills/${remove ? 'uninstall' : 'install'}`, {
1865
+ method: 'POST', headers: { 'Content-Type': 'application/json' },
1866
+ body: JSON.stringify(remove ? { dsh_name: skill.dsh_name } : { skill_id: skill.id, scope: skill.scope || 'team' }),
1867
+ })
1868
+ const result = await readLocalJsonResponse(response)
1869
+ if (!response.ok) throw new Error(result.message || `${action}失败(${response.status})。`)
1870
+ const refreshed = await refresh()
1871
+ if (!refreshed) {
1872
+ if (reportInDetail) closeSkillDetails()
1873
+ setMessage(`${skill.title} 的${action}请求已成功提交,但目录状态暂时无法核实。请刷新目录后再操作,避免重复${action}。`)
1874
+ return
1875
+ }
1876
+ const resultMessage = remove ? skill.conflict_reason === 'other-source'
1877
+ ? '本机旧来源已卸载,可以安装所选技能。'
1878
+ : `${skill.title} 已从 ANT 管理的本机目录卸载。`
1879
+ : `${skill.title} 的文件已${action}到 DSH 用户技能目录。DSH 会在后续会话或模型步骤中读取;若不可用,请检查当前预设是否启用了本地技能。`
1880
+ setMessage(resultMessage)
1881
+ if (reportInDetail) setDetailActionMessage({ skillId: skill.id, text: resultMessage })
1882
+ } catch (error) {
1883
+ const errorMessage = error instanceof Error ? error.message : `${action}失败。`
1884
+ setMessage(errorMessage)
1885
+ if (reportInDetail) setDetailActionMessage({ skillId: skill.id, text: errorMessage })
1886
+ }
1887
+ finally { setWorkingId('') }
1888
+ }
1889
+ const openOriginal = async (skill) => {
1890
+ const generation = ++originalGeneration.current
1891
+ setOriginalView({ title: skill.title, loading: true })
1892
+ try {
1893
+ const params = new URLSearchParams({ skill_id: skill.id, scope: skill.scope || 'team' })
1894
+ const response = await fetch(`/api/ant-teams/skills/original?${params}`, { cache: 'no-store' })
1895
+ if (response.status === 404 && !hasChineseIntroduction(skill.description)) {
1896
+ if (generation === originalGeneration.current) setOriginalView({
1897
+ title: skill.title, markdown: skill.description, partial: true,
1898
+ })
1899
+ return
1900
+ }
1901
+ if (!response.ok) {
1902
+ const error = await readLocalJsonResponse(response)
1903
+ throw new Error(error.message || '技能原文暂时无法打开。')
1904
+ }
1905
+ const markdown = await response.text()
1906
+ if (generation === originalGeneration.current) setOriginalView({ title: skill.title, markdown })
1907
+ } catch (error) {
1908
+ if (generation === originalGeneration.current) setOriginalView({
1909
+ title: skill.title, error: error instanceof Error ? error.message : '技能原文暂时无法打开。',
1910
+ })
1911
+ }
1912
+ }
1913
+ const visible = skills.filter((skill) => {
1914
+ const canInstall = skill.scope !== 'market' || skill.team_enabled === true
1915
+ const matchesFilter = filter === 'all'
1916
+ || filter === 'available' && canInstall && ['not-installed', 'update-available'].includes(skill.local_status)
1917
+ || filter === 'installed' && ['installed', 'update-available'].includes(skill.local_status)
1918
+ || filter === 'updates' && canInstall && skill.local_status === 'update-available'
1919
+ const matchesQuery = !query.trim() || `${skill.title} ${skillIntroduction(skill)} ${skill.description} ${skill.dsh_name}`.toLowerCase().includes(query.trim().toLowerCase())
1920
+ return matchesFilter && matchesQuery
1921
+ && (scopeFilter === 'all' || (skill.scope || 'team') === scopeFilter)
1922
+ && (categoryFilter === 'all' || skillCategory(skill) === categoryFilter)
1923
+ })
1924
+ const visibleOfficial = officialOfficeSkills.filter((skill) => {
1925
+ const matchesQuery = !query.trim() || `${skill.title} ${skill.name} ${skill.description} ${skill.prompt}`.toLowerCase().includes(query.trim().toLowerCase())
1926
+ return filter === 'all' && matchesQuery
1927
+ && (scopeFilter === 'all' || scopeFilter === 'official')
1928
+ && (categoryFilter === 'all' || skill.category === categoryFilter)
1929
+ })
1930
+ const statusLabel = { installed: '已放入本机目录', 'update-available': '可更新', 'not-installed': '未安装', conflict: '本机冲突' }
1931
+ if (originalView) return h('section', { 'aria-label': '技能原文', style: {
1932
+ height: '100%', overflowY: 'auto', boxSizing: 'border-box',
1933
+ padding: 'calc(var(--dsh-frame-top-clearance, 0px) + 20px) clamp(16px, 3vw, 36px) 48px',
1934
+ } }, h('div', { style: { maxWidth: 1100, margin: '0 auto', display: 'grid', gap: 16 } },
1935
+ h('button', { type: 'button', onClick: () => { originalGeneration.current += 1; setOriginalView(null) },
1936
+ style: { ...secondaryButtonStyle, width: 'fit-content' } }, includePlugins ? '← 返回企业扩展' : '← 返回技能中心'),
1937
+ h('h1', { style: { margin: 0, fontSize: 26 } }, rawLocaleText(originalView.title), ' · ', '原始技能说明'),
1938
+ h('p', { style: mutedTextStyle }, originalView.partial
1939
+ ? '当前服务端尚未提供完整原文,此处仅显示导入时的英文简介。'
1940
+ : '这里显示发布时保存的 SKILL.md。它供 DSH 使用,与技能中心的中文介绍分别维护;ANT 可能给原技能名加前缀。'),
1941
+ originalView.loading ? h('p', { role: 'status', style: mutedTextStyle }, '正在读取原文…')
1942
+ : originalView.error ? h('p', { role: 'alert', style: mutedTextStyle }, originalView.error)
1943
+ : h('pre', { style: { ...panelStyle, whiteSpace: 'pre-wrap', overflowWrap: 'anywhere', fontFamily: 'monospace', fontSize: 13, lineHeight: 1.6 } }, originalView.markdown)))
1944
+ return h('section', { dir: formatLocaleDirection(), 'aria-label': includePlugins ? '企业扩展' : '技能中心', style: {
1945
+ height: '100%', overflowY: 'auto', boxSizing: 'border-box',
1946
+ padding: 'calc(var(--dsh-frame-top-clearance, 0px) + 20px) clamp(16px, 3vw, 36px) 48px',
1947
+ } }, h('div', { style: { maxWidth: 1440, margin: '0 auto', display: 'grid', gap: 22 } },
1948
+ h('div', { style: { display: 'flex', flexWrap: 'wrap', alignItems: 'center', gap: 8 } },
1949
+ h('nav', { 'aria-label': '企业扩展分类', style: { display: 'flex', gap: 6 } },
1950
+ includePlugins
1951
+ ? h('span', { 'aria-current': 'page', style: { ...categoryButtonStyle, display: 'inline-flex', alignItems: 'center', cursor: 'default', backgroundColor: 'var(--dsw-alias-bg-layer-2)' } }, '总览')
1952
+ : h('button', { type: 'button', onClick: onAll, style: categoryButtonStyle }, '总览'),
1953
+ includePlugins
1954
+ ? h('button', { type: 'button', onClick: onSkills, style: categoryButtonStyle }, '技能')
1955
+ : h('span', { 'aria-current': 'page', style: { ...categoryButtonStyle, display: 'inline-flex', alignItems: 'center', cursor: 'default', backgroundColor: 'var(--dsw-alias-bg-layer-2)' } }, '技能'),
1956
+ h('button', { type: 'button', onClick: onPlugins, style: categoryButtonStyle }, '插件')),
1957
+ h('button', { type: 'button', onClick: onBack, style: { ...categoryButtonStyle, marginLeft: 'auto' } }, 'ANT 设置')),
1958
+ h('div', { style: { display: 'flex', flexWrap: 'wrap', alignItems: 'end', justifyContent: 'space-between', gap: 16 } },
1959
+ h('div', null,
1960
+ h('h1', { style: { margin: 0, fontSize: 28 } }, includePlugins ? '企业扩展' : '技能中心'),
1961
+ h('p', { style: { ...mutedTextStyle, marginTop: 6 } }, includePlugins
1962
+ ? '浏览全市场与本企业审核的技能、插件;选择需要的扩展安装到这台 DSH。'
1963
+ : '浏览全市场精选和本企业技能;安装到这台 DSH 后,由 DSH 原生技能系统发现和使用。')),
1964
+ h('button', { type: 'button', disabled: loading || Boolean(workingId), onClick: () => {
1965
+ void refresh()
1966
+ if (includePlugins) setRefreshToken((value) => value + 1)
1967
+ }, style: secondaryButtonStyle }, loading ? '读取中…' : '刷新目录')),
1968
+ h(ExtensionRequestNotice),
1969
+ selectedSkill ? (() => {
1970
+ const marketPending = selectedSkill.scope === 'market' && selectedSkill.team_enabled !== true
1971
+ const originalEnglish = Boolean(curatedSkillIntroduction(selectedSkill)) || !hasChineseIntroduction(selectedSkill.description)
1972
+ const englishSource = skillEnglishSource(selectedSkill)
1973
+ const sourceRef = selectedSkill.source_ref || ''
1974
+ const versionLabel = /^[a-f0-9]{40,64}$/iu.test(sourceRef) ? sourceRef.slice(0, 12) : sourceRef
1975
+ const sourceLabel = /^https:\/\/github\.com\//u.test(selectedSkill.source_url || '') ? 'GitHub'
1976
+ : /^https:\/\/clawhub\.ai\//u.test(selectedSkill.source_url || '') ? 'ClawHub'
1977
+ : selectedSkill.source_kind === 'upload' ? '管理员上传' : '原作者来源'
1978
+ const canInstall = !marketPending && selectedSkill.local_status !== 'conflict'
1979
+ return h('div', { role: 'presentation', onClick: (event) => {
1980
+ if (event.target === event.currentTarget) closeSkillDetails()
1981
+ }, style: { position: 'fixed', inset: 0, zIndex: 1000, display: 'grid', placeItems: 'center',
1982
+ padding: 20, background: 'rgba(0, 0, 0, 0.58)' } },
1983
+ h('section', { role: 'dialog', 'aria-modal': 'true', 'aria-label': `${selectedSkill.title} 技能详情`,
1984
+ onKeyDown: (event) => {
1985
+ if (event.key === 'Escape') { closeSkillDetails(); return }
1986
+ if (event.key !== 'Tab') return
1987
+ const controls = Array.from(event.currentTarget.querySelectorAll('a[href], button:not([disabled]), [tabindex]:not([tabindex="-1"])'))
1988
+ const first = controls[0]
1989
+ const last = controls[controls.length - 1]
1990
+ if (event.shiftKey && document.activeElement === first) { event.preventDefault(); last?.focus() }
1991
+ else if (!event.shiftKey && document.activeElement === last) { event.preventDefault(); first?.focus() }
1992
+ },
1993
+ style: { width: 'min(720px, 100%)', maxHeight: 'min(88vh, 900px)', overflowY: 'auto',
1994
+ boxSizing: 'border-box', padding: 24, display: 'grid', gap: 18,
1995
+ border: '1px solid var(--dsw-alias-border-l2)', borderRadius: 16,
1996
+ backgroundColor: 'var(--dsw-alias-bg-layer-1)', boxShadow: '0 24px 80px rgba(0,0,0,.35)' } },
1997
+ h('header', { style: { display: 'flex', justifyContent: 'space-between', gap: 16, alignItems: 'start' } },
1998
+ h('div', { style: { display: 'grid', gap: 8 } },
1999
+ h('h2', { style: { margin: 0, fontSize: 24 } }, rawLocaleText(selectedSkill.title)),
2000
+ h('div', { style: { display: 'flex', flexWrap: 'wrap', gap: 8, alignItems: 'center' } },
2001
+ h('span', { style: { ...mutedTextStyle, padding: '3px 9px', borderRadius: 999, backgroundColor: 'var(--dsw-alias-bg-layer-2)' } }, selectedSkill.scope === 'market' ? '全市场精选' : '本企业'),
2002
+ h('span', { style: { ...mutedTextStyle, padding: '3px 9px', borderRadius: 999, backgroundColor: 'var(--dsw-alias-bg-layer-2)' } }, categoryLabel(skillCategory(selectedSkill))),
2003
+ h('span', { style: mutedTextStyle }, marketPending
2004
+ ? selectedSkill.team_connected ? '待企业启用' : '连接企业后查看启用状态'
2005
+ : statusLabel[selectedSkill.local_status] || '状态未知'))),
2006
+ h('button', { type: 'button', autoFocus: true, 'aria-label': '关闭技能详情', onClick: closeSkillDetails,
2007
+ style: { ...secondaryButtonStyle, flex: '0 0 auto' } }, '关闭')),
2008
+ h('section', { style: { display: 'grid', gap: 7 } },
2009
+ h('h3', { style: { margin: 0, fontSize: 15 } }, '这个技能能做什么'),
2010
+ h('p', { style: { ...mutedTextStyle, whiteSpace: 'pre-wrap', overflowWrap: 'anywhere' } },
2011
+ skillIntroductionDisplay(selectedSkill, skillIntroduction(selectedSkill)))),
2012
+ h('section', { style: { display: 'grid', gap: 7, padding: 14, borderRadius: 10,
2013
+ border: '1px solid var(--dsw-alias-border-l2)', backgroundColor: 'var(--dsw-alias-bg-layer-2)' } },
2014
+ h('h3', { style: { margin: 0, fontSize: 15 } }, '外部数据交互'),
2015
+ h('p', { style: { ...mutedTextStyle, whiteSpace: 'pre-wrap', overflowWrap: 'anywhere' } },
2016
+ selectedSkill.data_interactions?.trim()
2017
+ ? rawLocaleText(selectedSkill.data_interactions.trim())
2018
+ : '待管理员补充。使用前请核实这项技能是否调用外部服务,以及会发送哪些数据。')),
2019
+ h('section', { style: { display: 'grid', gap: 7, overflowWrap: 'anywhere' } },
2020
+ h('h3', { style: { margin: 0, fontSize: 15 } }, '来源与使用条件'),
2021
+ h('p', { style: mutedTextStyle }, '来源:',
2022
+ ['GitHub', 'ClawHub'].includes(sourceLabel) ? rawLocaleText(sourceLabel) : sourceLabel,
2023
+ ' · 许可:', rawLocaleText(selectedSkill.license)),
2024
+ h('p', { style: mutedTextStyle }, formatLocaleNumber(selectedSkill.file_count), ' 个文件 · 本机条件:', rawLocaleText(selectedSkill.requirements)),
2025
+ h('p', { style: mutedTextStyle, title: sourceRef }, `固定版本:${versionLabel || '已锁定制品'}`),
2026
+ englishSource ? h('a', { href: englishSource, target: '_blank', rel: 'noopener noreferrer',
2027
+ style: { color: 'var(--dsw-alias-link)', fontSize: 13 } }, originalEnglish ? '查看英文原文 ↗' : '查看原始说明 ↗')
2028
+ : h('button', { type: 'button', onClick: () => void openOriginal(selectedSkill),
2029
+ style: { border: 0, padding: 0, background: 'transparent', cursor: 'pointer',
2030
+ color: 'var(--dsw-alias-link)', fontSize: 13, textAlign: 'left' } },
2031
+ originalEnglish ? '查看英文原文 →' : '查看原始说明 →'),
2032
+ /^https:\/\//u.test(selectedSkill.source_url || '')
2033
+ ? h('a', { href: selectedSkill.source_url, target: '_blank', rel: 'noopener noreferrer',
2034
+ style: { color: 'var(--dsw-alias-link)', fontSize: 13 } }, '查看原始来源 ↗')
2035
+ : h('p', { style: mutedTextStyle }, '来源:管理员上传并审核')),
2036
+ marketPending ? h('p', { role: 'status', style: mutedTextStyle }, selectedSkill.team_connected
2037
+ ? '本企业尚未启用这个固定版本。需要使用时请联系企业管理员。'
2038
+ : '连接企业并验证工作邮箱后,才能查看本企业是否启用并安装这个技能。') : null,
2039
+ selectedSkill.local_status === 'conflict' ? h('p', { role: 'status', style: mutedTextStyle },
2040
+ selectedSkill.conflict_reason === 'other-source'
2041
+ ? '本机已安装另一个来源的同名技能。可卸载本机旧来源后再安装。'
2042
+ : '本机同名技能有未受 ANT 管理的内容、文件已被修改或备份损坏;请联系管理员处理。') : null,
2043
+ detailActionMessage?.skillId === selectedSkill.id
2044
+ ? h('p', { role: 'status', style: feedbackNoticeStyle }, detailActionMessage.text) : null,
2045
+ h('footer', { style: { display: 'flex', flexWrap: 'wrap', justifyContent: 'flex-end', gap: 8,
2046
+ borderTop: '1px solid var(--dsw-alias-border-l2)', paddingTop: 14 } },
2047
+ selectedSkill.local_status === 'conflict' && selectedSkill.conflict_reason === 'other-source'
2048
+ ? h('button', { type: 'button', disabled: Boolean(workingId), onClick: () => void changeInstall(selectedSkill, true),
2049
+ style: secondaryButtonStyle }, '卸载旧来源') : null,
2050
+ ['installed', 'update-available'].includes(selectedSkill.local_status)
2051
+ ? h('button', { type: 'button', disabled: Boolean(workingId), onClick: () => void changeInstall(selectedSkill, true),
2052
+ style: secondaryButtonStyle }, '卸载') : null,
2053
+ canInstall && selectedSkill.local_status !== 'installed' ? h('button', { type: 'button', disabled: Boolean(workingId),
2054
+ onClick: () => void changeInstall(selectedSkill), style: primaryButtonStyle },
2055
+ selectedSkill.local_status === 'update-available' ? '更新技能' : '安装到这台 DSH') : null)))
2056
+ })() : null,
2057
+ h('div', { style: { ...panelStyle, gap: 12 } },
2058
+ h('input', { type: 'search', value: query, onChange: (event) => onQueryChange(event.target.value),
2059
+ placeholder: includePlugins ? '搜索技能或插件名称、用途' : '搜索技能名称或说明',
2060
+ 'aria-label': includePlugins ? '搜索企业扩展' : '搜索企业精选技能', style: inputStyle }),
2061
+ h('div', { style: { display: 'flex', flexWrap: 'wrap', alignItems: 'center', gap: 8 } },
2062
+ ...[['all', '全部'], ['available', '可安装或更新'], ['installed', '已安装'], ['updates', '可更新']].map(([value, label]) =>
2063
+ h('button', { key: value, type: 'button', onClick: () => setFilter(value), 'aria-pressed': filter === value,
2064
+ style: { ...secondaryButtonStyle, minHeight: 34, padding: '6px 12px', backgroundColor: filter === value ? 'var(--dsw-alias-bg-layer-2)' : secondaryButtonStyle.backgroundColor } }, label)),
2065
+ includePlugins ? null : h('span', { style: { ...mutedTextStyle, marginLeft: 'auto' } }, `显示 ${visible.length + visibleOfficial.length} / ${skills.length + officialOfficeSkills.length} 个技能`)),
2066
+ h('div', { style: { display: 'flex', flexWrap: 'wrap', alignItems: 'center', gap: 8 } },
2067
+ h('span', { style: mutedTextStyle }, '来源'),
2068
+ ...[['all', '全部'], ['official', 'DSH 官方'], ['market', '全市场精选'], ['team', '本企业']].map(([value, label]) =>
2069
+ h('button', { key: value, type: 'button', onClick: () => setScopeFilter(value), 'aria-pressed': scopeFilter === value,
2070
+ style: { ...categoryButtonStyle, backgroundColor: scopeFilter === value ? 'var(--dsw-alias-bg-layer-2)' : categoryButtonStyle.backgroundColor } }, label)),
2071
+ h('label', { style: { ...mutedTextStyle, marginLeft: 'auto', display: 'flex', alignItems: 'center', gap: 6 } }, '用途类别',
2072
+ h('select', { value: categoryFilter, onChange: (event) => setCategoryFilter(event.target.value),
2073
+ 'aria-label': '筛选扩展用途类别', style: { ...inputStyle, width: 'auto', minHeight: 34 } },
2074
+ h('option', { value: 'all' }, '全部用途'),
2075
+ ...extensionCategories.map(([category, label]) => h('option', { key: category, value: category }, label)))),
2076
+ )),
2077
+ includePlugins ? h('h2', { style: { margin: 0, fontSize: 20 } }, loading ? '技能 · 读取中…' : `技能 · ${visible.length + visibleOfficial.length}`) : null,
2078
+ message && (!includePlugins || loadError || skills.length || (!loading && !query.trim()))
2079
+ ? h('p', { role: loadError ? 'alert' : 'status', style: feedbackNoticeStyle }, message) : null,
2080
+ visible.length && !includePlugins ? h('h2', { style: { margin: 0, fontSize: 20 } }, '全市场与本企业技能') : null,
2081
+ visible.length ? h('div', { style: { display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(min(100%, 300px), 1fr))', gap: 14 } },
2082
+ ...visible.map((skill) => {
2083
+ const marketPending = skill.scope === 'market' && skill.team_enabled !== true
2084
+ const description = skillIntroduction(skill)
2085
+ const actions = !marketPending && skill.local_status !== 'conflict'
2086
+ ? h('div', { style: { display: 'flex', flexWrap: 'wrap', gap: 8 } },
2087
+ skill.local_status === 'installed' ? null : h('button', { type: 'button', disabled: Boolean(workingId),
2088
+ onClick: () => void changeInstall(skill), style: primaryButtonStyle },
2089
+ skill.local_status === 'update-available' ? '更新技能' : '安装到这台 DSH'),
2090
+ skill.local_status === 'not-installed' ? null : h('button', { type: 'button', disabled: Boolean(workingId),
2091
+ onClick: () => void changeInstall(skill, true), style: secondaryButtonStyle }, '卸载'))
2092
+ : null
2093
+ return h('article', { key: skill.id, style: { ...panelStyle, gap: 12, padding: 16,
2094
+ minHeight: 190, boxSizing: 'border-box', alignContent: 'start' } },
2095
+ h('div', { style: { display: 'flex', justifyContent: 'space-between', alignItems: 'start', gap: 10 } },
2096
+ h('div', { style: { minWidth: 0, display: 'grid', gap: 7 } },
2097
+ h('h2', { style: { margin: 0, fontSize: 18, lineHeight: 1.3, overflowWrap: 'anywhere' } }, rawLocaleText(skill.title)),
2098
+ h('div', { style: { display: 'flex', flexWrap: 'wrap', gap: 6, alignItems: 'center' } },
2099
+ h('span', { style: { ...mutedTextStyle, padding: '2px 7px', borderRadius: 999, backgroundColor: 'var(--dsw-alias-bg-layer-2)', fontSize: 11 } }, skill.scope === 'market' ? '全市场精选' : '本企业'),
2100
+ h('span', { style: { ...mutedTextStyle, fontSize: 12 } }, categoryLabel(skillCategory(skill))))),
2101
+ h('span', { style: { ...mutedTextStyle, flex: '0 0 auto', fontSize: 12 } }, marketPending
2102
+ ? skill.team_connected ? '待启用' : '未连接'
2103
+ : statusLabel[skill.local_status] || '状态未知')),
2104
+ h('p', { style: { ...mutedTextStyle, display: '-webkit-box', WebkitBoxOrient: 'vertical',
2105
+ WebkitLineClamp: 2, overflow: 'hidden', minHeight: 42 } }, skillIntroductionDisplay(skill, description)),
2106
+ h('div', { style: { display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 8, marginTop: 'auto' } },
2107
+ h('button', { type: 'button', onClick: (event) => {
2108
+ detailTriggerRef.current = event?.currentTarget || null
2109
+ setDetailActionMessage(null)
2110
+ setSelectedSkill(skill)
2111
+ },
2112
+ style: { border: 0, padding: 0, background: 'transparent', cursor: 'pointer',
2113
+ color: 'var(--dsw-alias-link)', fontSize: 13 } }, '查看详情 →'),
2114
+ actions))
2115
+ })) : !includePlugins && !loading && (skills.length || officialOfficeSkills.length) && !visibleOfficial.length ? h('p', { style: mutedTextStyle }, '没有符合筛选条件的技能。') : null,
2116
+ visibleOfficial.length ? h('section', { 'aria-label': 'DSH 官方 Office 技能', style: { display: 'grid', gap: 12 } },
2117
+ h('div', null,
2118
+ h('h2', { style: { margin: 0, fontSize: 20 } }, 'DSH 官方 Office'),
2119
+ h('p', { style: { ...mutedTextStyle, marginTop: 4 } }, '这些能力随对应版本的 DSH 提供,无需通过 ANT 安装。在新会话中直接描述任务即可;不计入 ANT 的本机安装筛选。'),
2120
+ h('a', { href: officialOfficeGuide, target: '_blank', rel: 'noopener noreferrer', style: { color: 'var(--dsw-alias-link)', fontSize: 13 } }, '查看中文官方说明 ↗')),
2121
+ h('div', { style: { display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(min(100%, 300px), 1fr))', gap: 14 } },
2122
+ ...visibleOfficial.map((skill) => h('article', { key: skill.name, style: { ...panelStyle, gap: 10 } },
2123
+ h('div', { style: { display: 'flex', flexWrap: 'wrap', justifyContent: 'space-between', alignItems: 'baseline', gap: 8 } },
2124
+ h('h3', { style: { margin: 0, fontSize: 17 } }, skill.title),
2125
+ h('span', { style: { ...mutedTextStyle, padding: '2px 8px', borderRadius: 6,
2126
+ backgroundColor: 'var(--dsw-alias-bg-layer-2)' } }, 'DSH 自带 · 无需在 ANT 安装'),
2127
+ h('span', { style: { ...mutedTextStyle, padding: '2px 7px', borderRadius: 6,
2128
+ backgroundColor: 'var(--dsw-alias-bg-layer-2)' } }, categoryLabel(skill.category))),
2129
+ h('p', { style: mutedTextStyle }, skill.description),
2130
+ h('p', { style: mutedTextStyle }, `在新会话中说:“${skill.prompt}”。也可输入 /${skill.name}。`),
2131
+ h('p', { style: mutedTextStyle }, `DSH ${skill.since} 起提供;如果无法使用,请在 DSH 检查更新。`),
2132
+ h('a', { href: officialOfficeEnglish(skill), target: '_blank', rel: 'noopener noreferrer',
2133
+ style: { color: 'var(--dsw-alias-link)', fontSize: 13, lineHeight: 1.6, padding: '4px 0' } }, '英文原文 ↗'))))) : null,
2134
+ includePlugins ? h(PluginCenterPage, { remote, onBack, onAll, onSkills, openBundle,
2135
+ embedded: true, query, onQueryChange, externalFilter: filter, externalCategoryFilter: categoryFilter,
2136
+ externalScopeFilter: scopeFilter,
2137
+ hasSkillMatches: visible.length + visibleOfficial.length > 0, skillCatalogReady: !loading && !loadError,
2138
+ refreshToken }) : null))
2139
+ }
2140
+
2141
+ function PluginCenterPage({ remote, onBack, onAll, onSkills, openBundle,
2142
+ embedded = false, query, onQueryChange, externalFilter = 'all',
2143
+ externalCategoryFilter = 'all', externalScopeFilter = 'all',
2144
+ hasSkillMatches = false, skillCatalogReady = false, refreshToken }) {
2145
+ const [plugins, setPlugins] = useState([])
2146
+ const [bundles, setBundles] = useState([])
2147
+ const [loading, setLoading] = useState(true)
2148
+ const [loadError, setLoadError] = useState(false)
2149
+ const [workingId, setWorkingId] = useState('')
2150
+ const [uncertainId, setUncertainId] = useState('')
2151
+ const [completedId, setCompletedId] = useState('')
2152
+ const [message, setMessage] = useState('')
2153
+ const [filter, setFilter] = useState('all')
2154
+ const [categoryFilter, setCategoryFilter] = useState('all')
2155
+ const refreshGeneration = useRef(0)
2156
+ const refresh = async () => {
2157
+ const generation = ++refreshGeneration.current
2158
+ setLoading(true)
2159
+ try {
2160
+ const manager = remote?.pluginManager
2161
+ if (typeof manager?.listBundles !== 'function') throw new Error('当前 DSH 未提供插件管理接口。')
2162
+ const [response, listed] = await Promise.all([
2163
+ fetch('/api/ant-teams/plugins', { cache: 'no-store' }), manager.listBundles(),
2164
+ ])
2165
+ const result = await readLocalJsonResponse(response)
2166
+ if (!response.ok) throw new Error(result.message || `读取插件目录失败(${response.status})。`)
2167
+ if (!Array.isArray(result.plugins)) throw new Error('企业插件目录格式无效。')
2168
+ if (!listed.ok) throw new Error(listed.error?.message || '无法读取 DSH 本机插件。')
2169
+ if (generation !== refreshGeneration.current) return
2170
+ setPlugins(result.plugins)
2171
+ setBundles(listed.value)
2172
+ setLoadError(false)
2173
+ setMessage(result.plugins.length ? '' : '团队暂未发布精选插件。')
2174
+ } catch (error) {
2175
+ if (generation !== refreshGeneration.current) return
2176
+ setPlugins([])
2177
+ setBundles([])
2178
+ setLoadError(true)
2179
+ setMessage(error instanceof Error ? error.message : '无法读取企业精选插件。')
2180
+ } finally { if (generation === refreshGeneration.current) setLoading(false) }
2181
+ }
2182
+ useEffect(() => { void refresh() }, [refreshToken])
2183
+ const install = async (plugin) => {
2184
+ const artifactUrl = approvedPluginArtifactUrl(plugin)
2185
+ const installSpec = pluginInstallSpec(plugin)
2186
+ if (!installSpec || workingId || uncertainId === plugin.id || completedId === plugin.id) return
2187
+ const manager = remote?.pluginManager
2188
+ if (typeof manager?.installBundle !== 'function') {
2189
+ setMessage('当前 DSH 未提供插件安装接口,请联系管理员。')
2190
+ return
2191
+ }
2192
+ const local = bundles.find((bundle) => bundle.name === plugin.package_name && bundle.installed)
2193
+ const localAhead = local?.version && newerVersion(local.version, plugin.version)
2194
+ const updatingInstalled = Boolean(local?.version && local.version !== plugin.version)
2195
+ const replacingInstalled = Boolean(local?.version && (updatingInstalled
2196
+ || artifactUrl && local.source !== artifactUrl))
2197
+ const action = localAhead ? '回退到团队版本' : local ? local.version === plugin.version ? '重新安装' : '更新' : '安装'
2198
+ const sourceNotice = artifactUrl
2199
+ ? translateLocaleText('DSH 将安装 ANT 固定的顶层制品。')
2200
+ : translateLocaleText(`DSH 将优先从 npm 官方源以 ${installSpec} 安装此精确版本,并按其配置回退 registry;依赖版本可能因设备不同。`)
2201
+ const updateNotice = translateLocaleText('ANT 不会批准依赖构建脚本;插件自身的更新器或 DSH 原生管理页之后仍可安装其他版本。')
2202
+ const installConfirmation = translateLocaleText(
2203
+ '在这台 DSH {action}团队审核的 {plugin_title} {version}?{source_notice}{update_notice} 插件将在本机运行,完成后需要完全重启 DSH。',
2204
+ { action: translateLocaleText(action), plugin_title: plugin.title, version: plugin.version, source_notice: sourceNotice, update_notice: updateNotice })
2205
+ if (!confirmLocalized(installConfirmation)) return
2206
+ setWorkingId(plugin.id)
2207
+ setMessage(translateLocaleText('正在安装 {plugin_title},请不要退出 DSH…', { plugin_title: plugin.title }))
2208
+ try {
2209
+ const response = await fetch('/api/ant-teams/plugins', { cache: 'no-store' })
2210
+ const catalog = await readLocalJsonResponse(response)
2211
+ const latest = Array.isArray(catalog?.plugins)
2212
+ ? catalog.plugins.find((item) => item.id === plugin.id) : null
2213
+ if (!response.ok || latest?.package_name !== plugin.package_name
2214
+ || latest?.version !== plugin.version || pluginInstallSpec(latest) !== installSpec) {
2215
+ throw new Error('插件审核信息已变化,请刷新目录后重试。')
2216
+ }
2217
+ const requestId = crypto.randomUUID()
2218
+ const requestReference = requestId.slice(0, 8).toUpperCase()
2219
+ const previousSourceIsRegistry = Boolean(local && (!local.source
2220
+ || local.source === plugin.package_name || local.source.startsWith(`${plugin.package_name}@`)))
2221
+ const previousInstallSpec = local
2222
+ ? previousSourceIsRegistry ? `${plugin.package_name}@${local.version}` : local.source || ''
2223
+ : ''
2224
+ const expectedPreviousSource = previousSourceIsRegistry ? previousInstallSpec : local?.source
2225
+ const previousRegistry = previousSourceIsRegistry ? 'https://registry.npmjs.org/' : null
2226
+ const currentBundle = async () => {
2227
+ try {
2228
+ const listed = await manager.listBundles()
2229
+ if (listed.ok && Array.isArray(listed.value)) {
2230
+ return listed.value.find((bundle) => bundle.name === plugin.package_name && bundle.installed) || null
2231
+ }
2232
+ } catch {}
2233
+ return undefined
2234
+ }
2235
+ const isPreviousVersion = (bundle) => bundle?.version === local?.version
2236
+ && (!expectedPreviousSource || bundle.source === expectedPreviousSource)
2237
+ const restorePreviousVersion = async () => {
2238
+ let installed = await currentBundle()
2239
+ if (installed === undefined) return 'unknown'
2240
+ if (isPreviousVersion(installed)) {
2241
+ if (installed.enabled === (local.enabled !== false)) return 'restored'
2242
+ if (typeof manager.setBundleEnabled !== 'function') return 'unknown'
2243
+ try {
2244
+ await manager.setBundleEnabled(plugin.package_name, local.enabled !== false)
2245
+ } catch {}
2246
+ installed = await currentBundle()
2247
+ return isPreviousVersion(installed) && installed.enabled === (local.enabled !== false)
2248
+ ? 'restored' : 'unknown'
2249
+ }
2250
+ if (installed?.installed) {
2251
+ return installed.version === plugin.version
2252
+ && (!artifactUrl || installed.source === artifactUrl) ? 'target' : 'unknown'
2253
+ }
2254
+ if (installed !== null || !previousInstallSpec) return 'unknown'
2255
+ if (previousSourceIsRegistry && !previousRegistry) return 'unknown'
2256
+ const restoreRequestId = crypto.randomUUID()
2257
+ try {
2258
+ const restoreOptions = {
2259
+ enabled: local.enabled !== false, requestId: restoreRequestId,
2260
+ saveExact: true,
2261
+ }
2262
+ if (previousSourceIsRegistry && previousRegistry) restoreOptions.registry = previousRegistry
2263
+ await manager.installBundle(previousInstallSpec, restoreOptions)
2264
+ if (typeof manager.waitForInstall === 'function') {
2265
+ await manager.waitForInstall(restoreRequestId)
2266
+ }
2267
+ } catch {}
2268
+ installed = await currentBundle()
2269
+ return isPreviousVersion(installed) && installed.enabled === (local.enabled !== false)
2270
+ ? 'restored' : 'unknown'
2271
+ }
2272
+ let result
2273
+ let installFailure = null
2274
+ let updateRestore = null
2275
+ let removedForUpdate = false
2276
+ const options = artifactUrl
2277
+ ? { enabled: local ? local.enabled !== false : true, requestId }
2278
+ : { enabled: local ? local.enabled !== false : true, requestId, registry: 'https://registry.npmjs.org/' }
2279
+ if (replacingInstalled && !localAhead && !artifactUrl && local.updatable !== false
2280
+ && typeof manager.updateBundle === 'function') {
2281
+ try {
2282
+ const update = await manager.updateBundle(plugin.package_name, plugin.version, {
2283
+ requestId, registry: 'https://registry.npmjs.org/',
2284
+ })
2285
+ result = { ok: update?.ok === true, value: update?.value?.result, error: update?.error }
2286
+ updateRestore = update?.value?.restore || null
2287
+ } catch (error) { installFailure = error; result = null }
2288
+ } else {
2289
+ if (replacingInstalled && typeof manager.removeBundle !== 'function') {
2290
+ setMessage('当前 DSH 不支持通过 ANT 安全替换已安装插件。请在 DSH 插件管理查看状态,或联系管理员。')
2291
+ return
2292
+ }
2293
+ if (replacingInstalled) {
2294
+ let removed = null
2295
+ let removeFailure = null
2296
+ try { removed = await manager.removeBundle(plugin.package_name) }
2297
+ catch (error) { removeFailure = error }
2298
+ if (!removed?.ok || !['applied', 'restart-required'].includes(removed.value?.application)) {
2299
+ const diagnostic = safeInstallDiagnostic(removed?.value?.error || removed?.error || removeFailure)
2300
+ const recovery = await restorePreviousVersion()
2301
+ if (recovery !== 'restored') setUncertainId(plugin.id)
2302
+ const recoveryNotice = recovery === 'restored'
2303
+ ? translateLocaleText('旧版本号和原启用状态已恢复。{source_notice}', {
2304
+ source_notice: previousSourceIsRegistry
2305
+ ? ` ${translateLocaleText('恢复按团队目录使用 npm 官方源;若此前来自私有源,请联系管理员核对。')}` : '' })
2306
+ : recovery === 'target' ? translateLocaleText(
2307
+ '本机列表显示审核版本 {version} 已安装,请核对后再操作。', { version: plugin.version })
2308
+ : translateLocaleText('无法确认旧版本及启用状态,请先在 DSH 插件管理核对。')
2309
+ setMessage(`无法开始更新 ${plugin.title}:DSH 未能确认旧版本移除完成。${diagnostic
2310
+ ? `DSH 诊断:${diagnostic}。` : ''}${recoveryNotice}`)
2311
+ return
2312
+ }
2313
+ removedForUpdate = true
2314
+ }
2315
+ try { result = await manager.installBundle(installSpec, options) }
2316
+ catch (error) { installFailure = error; result = null }
2317
+ }
2318
+ if (!result?.ok) {
2319
+ if (!installFailure && result?.error) installFailure = result.error
2320
+ let recovered = null
2321
+ let waitFailure = null
2322
+ if (typeof manager.waitForInstall === 'function') {
2323
+ try {
2324
+ const pending = await manager.waitForInstall(requestId)
2325
+ if (pending.ok && pending.value) recovered = { ok: true, value: pending.value }
2326
+ else if (pending?.error) waitFailure = pending.error
2327
+ } catch (error) { waitFailure = error }
2328
+ }
2329
+ if (!recovered) {
2330
+ setUncertainId(plugin.id)
2331
+ let restoreNotice = ''
2332
+ if (removedForUpdate) {
2333
+ const restoreState = await restorePreviousVersion()
2334
+ restoreNotice = restoreState === 'restored'
2335
+ ? translateLocaleText('DSH 已恢复旧版本号 {version}。{source_notice}', {
2336
+ version: local.version,
2337
+ source_notice: previousSourceIsRegistry
2338
+ ? ` ${translateLocaleText('恢复按团队目录使用 npm 官方源;若此前来自私有源,请核对来源。')}` : '' })
2339
+ : restoreState === 'target' ? ` ${translateLocaleText(
2340
+ '本机列表显示审核版本 {version} 已安装,但操作结果未确认。', { version: plugin.version })}`
2341
+ : ` ${translateLocaleText('DSH 未能确认旧版本恢复,请先在插件列表核对。')}`
2342
+ }
2343
+ const details = [installFailure && `installBundle:${safeInstallDiagnostic(installFailure)}`,
2344
+ waitFailure && `waitForInstall:${safeInstallDiagnostic(waitFailure)}`].filter(Boolean)
2345
+ setMessage(`暂时无法确认 ${plugin.title} 的安装结果(请求编号 ${requestReference})。${details.length
2346
+ ? `本机诊断:${details.join(';')}。` : ''}${restoreNotice}请先在 DSH 插件列表核对,勿重复点击安装。`)
2347
+ return
2348
+ }
2349
+ result = recovered
2350
+ }
2351
+ const outcome = result.value
2352
+ if (!outcome || typeof outcome !== 'object') {
2353
+ setUncertainId(plugin.id)
2354
+ setMessage(`DSH 未返回 ${plugin.title} 的安装结果。请先在插件列表核对,勿重复点击安装。`)
2355
+ return
2356
+ }
2357
+ if (outcome.application === 'failed' || outcome.application === 'cancelled') {
2358
+ if (outcome.error?.code === 'ambiguous-install' && local?.version === plugin.version) {
2359
+ setMessage(`DSH 无法确定 ${plugin.title} 本次安装的唯一结果,未确认完成。请先在 DSH 插件列表核对;若已经正常使用同版则无需重复安装,仍需核对来源时请联系管理员。`)
2360
+ return
2361
+ }
2362
+ const diagnostic = safeInstallDiagnostic({ name: outcome.error?.name,
2363
+ code: outcome.error?.code,
2364
+ message: outcome.error?.diagnostic || outcome.error?.message || outcome.packageResult?.output })
2365
+ let restoreNotice = ''
2366
+ if (updateRestore) {
2367
+ restoreNotice = ['applied', 'restart-required'].includes(updateRestore.application)
2368
+ ? ` ${translateLocaleText('DSH 已恢复旧版本 {version}。', { version: local.version })}`
2369
+ : ` ${translateLocaleText('DSH 未能确认旧版本恢复,请先在插件列表核对。')}`
2370
+ } else if (removedForUpdate) {
2371
+ const restoreState = await restorePreviousVersion()
2372
+ restoreNotice = restoreState === 'restored'
2373
+ ? translateLocaleText('DSH 已恢复旧版本号 {version}。{source_notice}', {
2374
+ version: local.version,
2375
+ source_notice: previousSourceIsRegistry
2376
+ ? ` ${translateLocaleText('恢复按团队目录使用 npm 官方源;若此前来自私有源,请核对来源。')}` : '' })
2377
+ : restoreState === 'target' ? ` ${translateLocaleText(
2378
+ '本机列表显示审核版本 {version} 已安装,但结果未确认。', { version: plugin.version })}`
2379
+ : ` ${translateLocaleText('DSH 未能确认旧版本恢复,请先在插件列表核对。')}`
2380
+ }
2381
+ setMessage(`${plugin.title} 安装未完成(请求编号 ${requestReference})。${diagnostic
2382
+ ? `DSH 诊断:${diagnostic}。` : 'DSH 没有返回失败诊断。'}${restoreNotice}请在 DSH 插件管理查看状态或联系管理员。`)
2383
+ return
2384
+ }
2385
+ if (outcome.bundle !== plugin.package_name
2386
+ || !['restart-required', 'applied'].includes(outcome.application)) {
2387
+ setUncertainId(plugin.id)
2388
+ setMessage(`DSH 未确认 ${plugin.title} 已安装。请先在插件列表核对,勿重复点击安装。`)
2389
+ return
2390
+ }
2391
+ let observed = null
2392
+ try {
2393
+ const installed = await manager.listBundles()
2394
+ if (installed.ok && Array.isArray(installed.value)) {
2395
+ observed = installed.value.find((bundle) => bundle.name === plugin.package_name && bundle.installed) || null
2396
+ }
2397
+ } catch {}
2398
+ if ((outcome.version && outcome.version !== plugin.version) || observed?.version !== plugin.version) {
2399
+ setUncertainId(plugin.id)
2400
+ setMessage(`DSH 未确认 ${plugin.title} 的审核版本已安装。请先在插件列表核对,勿重复点击安装。`)
2401
+ return
2402
+ }
2403
+ await refresh()
2404
+ if (artifactUrl && plugin.artifact_sha256) {
2405
+ try { localStorage.setItem(`${PLUGIN_INSTALL_RECORD_PREFIX}${plugin.id}`, plugin.artifact_sha256) } catch {}
2406
+ }
2407
+ setCompletedId(plugin.id)
2408
+ setMessage(`${plugin.title} 已安装。请完全退出并重新启动 DSH 后使用。`)
2409
+ } catch (error) {
2410
+ setMessage(error instanceof Error ? error.message : '插件安装未完成,请稍后重试。')
2411
+ } finally { setWorkingId('') }
2412
+ }
2413
+ const activeFilter = embedded ? externalFilter : filter
2414
+ const activeCategoryFilter = embedded ? externalCategoryFilter : categoryFilter
2415
+ const activeScopeFilter = embedded ? externalScopeFilter : 'team'
2416
+ const currentPluginByPackage = new Map()
2417
+ const publishedPluginPackages = new Set()
2418
+ for (const plugin of plugins) {
2419
+ if (!currentPluginByPackage.has(plugin.package_name)
2420
+ || plugin.status === 'published' && !publishedPluginPackages.has(plugin.package_name)) {
2421
+ currentPluginByPackage.set(plugin.package_name, plugin.id)
2422
+ }
2423
+ if (plugin.status === 'published') publishedPluginPackages.add(plugin.package_name)
2424
+ }
2425
+ if (activeFilter === 'installed') {
2426
+ for (const plugin of plugins) {
2427
+ if (publishedPluginPackages.has(plugin.package_name)) continue
2428
+ const installed = bundles.find((bundle) => bundle.name === plugin.package_name && bundle.installed)
2429
+ if (!installed?.version || installed.version !== plugin.version) continue
2430
+ currentPluginByPackage.set(plugin.package_name, plugin.id)
2431
+ }
2432
+ }
2433
+ const visible = plugins.filter((plugin) => {
2434
+ const isCurrentVersion = currentPluginByPackage.get(plugin.package_name) === plugin.id
2435
+ const installed = bundles.find((bundle) => bundle.name === plugin.package_name && bundle.installed)
2436
+ const artifactUrl = approvedPluginArtifactUrl(plugin)
2437
+ const installSpec = pluginInstallSpec(plugin)
2438
+ const localAhead = installed?.version && newerVersion(installed.version, plugin.version)
2439
+ const matches = !query.trim() || `${plugin.title} ${plugin.description} ${plugin.package_name}`.toLowerCase().includes(query.trim().toLowerCase())
2440
+ return matches && (activeScopeFilter === 'all' || activeScopeFilter === 'team')
2441
+ && (activeCategoryFilter === 'all' || categoryOf(plugin) === activeCategoryFilter)
2442
+ && (activeFilter === 'retired'
2443
+ ? plugin.status !== 'published'
2444
+ : isCurrentVersion && (activeFilter === 'all'
2445
+ || activeFilter === 'installed' && Boolean(installed)
2446
+ || activeFilter === 'available' && plugin.status === 'published' && installSpec && !localAhead && (!installed || (installed.version && installed.version !== plugin.version))
2447
+ || activeFilter === 'updates' && plugin.status === 'published' && installSpec && installed && installed.version && installed.version !== plugin.version && !localAhead)
2448
+ )
2449
+ })
2450
+ const noMatches = embedded
2451
+ ? skillCatalogReady ? '没有找到符合条件的企业扩展。' : '插件中没有符合条件的结果。'
2452
+ : activeFilter === 'available'
2453
+ ? '当前没有可一键安装的插件。可在“目录概览”查看审核目录,或联系企业管理员。'
2454
+ : '没有符合筛选条件的插件。'
2455
+ return h('section', { 'aria-label': '企业精选插件', style: embedded
2456
+ ? { display: 'grid', gap: 16 }
2457
+ : { height: '100%', overflowY: 'auto', boxSizing: 'border-box',
2458
+ padding: 'calc(var(--dsh-frame-top-clearance, 0px) + 20px) clamp(16px, 3vw, 36px) 48px' },
2459
+ }, h('div', { style: embedded ? { display: 'grid', gap: 16 } : { maxWidth: 1440, margin: '0 auto', display: 'grid', gap: 22 } },
2460
+ embedded ? h('h2', { style: { margin: 0, fontSize: 20 } }, loading ? '插件 · 读取中…' : `插件 · ${visible.length}`) : h('div', { style: { display: 'flex', flexWrap: 'wrap', alignItems: 'center', gap: 8 } },
2461
+ h('nav', { 'aria-label': '企业扩展分类', style: { display: 'flex', gap: 6 } },
2462
+ h('button', { type: 'button', onClick: onAll, style: categoryButtonStyle }, '总览'),
2463
+ h('button', { type: 'button', onClick: onSkills, style: categoryButtonStyle }, '技能'),
2464
+ h('span', { 'aria-current': 'page', style: { ...categoryButtonStyle, display: 'inline-flex', alignItems: 'center', cursor: 'default', backgroundColor: 'var(--dsw-alias-bg-layer-2)' } }, '插件')),
2465
+ h('button', { type: 'button', onClick: onBack, style: { ...categoryButtonStyle, marginLeft: 'auto' } }, 'ANT 设置')),
2466
+ embedded ? null : h('div', { style: { display: 'flex', flexWrap: 'wrap', justifyContent: 'space-between', gap: 16 } },
2467
+ h('div', null,
2468
+ h('h1', { style: { margin: 0, fontSize: 28 } }, '企业精选插件'),
2469
+ h('p', { style: { ...mutedTextStyle, marginTop: 6 } }, '这里展示团队审核过的插件版本及本机状态。DSH 0.2.0-rc.2 不会自动更新 Bundle;插件自身的更新器可能绕过此目录安装其他版本。')),
2470
+ h('button', { type: 'button', disabled: loading, onClick: () => void refresh(), style: secondaryButtonStyle }, loading ? '读取中…' : '刷新目录')),
2471
+ !loading && !plugins.length && !loadError ? embedded
2472
+ ? h('p', { role: 'status', style: mutedTextStyle }, '团队暂未发布精选插件。')
2473
+ : h('section', { role: 'status', style: panelStyle },
2474
+ h('h2', { style: { margin: 0, fontSize: 18 } }, '团队暂未发布精选插件'),
2475
+ h('p', { style: mutedTextStyle }, '需要某个插件?请联系企业管理员,说明用途或提供插件地址。审核发布后会显示在这里。')) : null,
2476
+ !loading && loadError ? h('p', { role: 'alert', style: feedbackNoticeStyle }, message) : null,
2477
+ plugins.length && !embedded ? h(ExtensionRequestNotice) : null,
2478
+ plugins.length && !embedded ? h('div', { style: panelStyle },
2479
+ h('input', { type: 'search', value: query, onChange: (event) => onQueryChange(event.target.value), placeholder: '搜索插件名称或用途', 'aria-label': '搜索企业精选插件', style: inputStyle }),
2480
+ h('div', { style: { display: 'flex', flexWrap: 'wrap', gap: 8 } },
2481
+ ...[['all', '目录概览'], ['available', '可安装或升级'], ['installed', '已安装'], ['retired', '已废弃']].map(([value, label]) =>
2482
+ h('button', { key: value, type: 'button', onClick: () => setFilter(value), 'aria-pressed': filter === value,
2483
+ style: { ...secondaryButtonStyle, minHeight: 34, backgroundColor: filter === value ? 'var(--dsw-alias-bg-layer-2)' : secondaryButtonStyle.backgroundColor } }, label)),
2484
+ h('label', { style: { ...mutedTextStyle, marginLeft: 'auto', display: 'flex', alignItems: 'center', gap: 6 } }, '用途类别',
2485
+ h('select', { value: categoryFilter, onChange: (event) => setCategoryFilter(event.target.value),
2486
+ 'aria-label': '筛选插件用途类别', style: { ...inputStyle, width: 'auto', minHeight: 34 } },
2487
+ h('option', { value: 'all' }, '全部用途'),
2488
+ ...extensionCategories.map(([category, label]) => h('option', { key: category, value: category }, label)))))) : null,
2489
+ plugins.length && message ? h('p', { role: 'status', style: feedbackNoticeStyle }, message) : null,
2490
+ visible.length ? h('div', { style: { display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(min(100%, 420px), 1fr))', gap: 16 } },
2491
+ ...visible.map((plugin) => {
2492
+ const local = bundles.find((bundle) => bundle.name === plugin.package_name && bundle.installed)
2493
+ const sameVersion = local?.version === plugin.version
2494
+ const security = plugin.status === 'security_withdrawn'
2495
+ const artifactUrl = approvedPluginArtifactUrl(plugin)
2496
+ const installSpec = pluginInstallSpec(plugin)
2497
+ const localAhead = local?.version && newerVersion(local.version, plugin.version)
2498
+ const sourceKnown = typeof local?.source === 'string'
2499
+ const verifiedLocal = sameVersion && artifactUrl && sourceKnown && local.source === artifactUrl
2500
+ const recordedInstall = sameVersion && !sourceKnown && previouslyInstalledReviewedPlugin(plugin)
2501
+ const status = security ? '已废弃(安全风险)'
2502
+ : plugin.status === 'deprecated' ? local?.version ? `已废弃 · 本机 ${local.version}` : '已废弃' : local?.error ? '加载异常' : localAhead
2503
+ ? '本机版本高于团队目录版本' : sameVersion
2504
+ ? verifiedLocal ? local.enabled ? '本机已装(团队来源,已启用)' : '本机已装(团队来源,未启用)'
2505
+ : sourceKnown ? '本机同版,来源不同' : recordedInstall
2506
+ ? '本机同版,曾由企业扩展安装;当前 DSH 无法复核来源' : '本机同版,当前 DSH 无法核对来源'
2507
+ : installSpec ? local ? local.version ? `可更新 · 本机 ${local.version}` : '本机版本暂无法读取' : artifactUrl ? '可安装' : '可从 npm 安装'
2508
+ : local ? `本机版本 ${local.version || '暂无法读取'}` : '已发布版本暂不可安装'
2509
+ return h('article', { key: plugin.id, style: security
2510
+ ? { ...panelStyle, borderColor: 'var(--dsw-alias-label-danger, #d44)' } : panelStyle },
2511
+ h('div', { style: { display: 'flex', flexWrap: 'wrap', justifyContent: 'space-between', gap: 8 } },
2512
+ h('div', { style: { display: 'flex', alignItems: 'baseline', flexWrap: 'wrap', gap: 8 } },
2513
+ h('h2', { style: { margin: 0, fontSize: 19 } }, rawLocaleText(plugin.title)),
2514
+ embedded ? h('span', { style: mutedTextStyle }, '插件') : null,
2515
+ h('span', { style: { ...mutedTextStyle, padding: '2px 7px', borderRadius: 6,
2516
+ backgroundColor: 'var(--dsw-alias-bg-layer-2)' } }, categoryLabel(categoryOf(plugin)))),
2517
+ h('span', { style: security
2518
+ ? { ...mutedTextStyle, color: 'var(--dsw-alias-label-danger, #d44)', fontWeight: 650 } : mutedTextStyle }, status)),
2519
+ h('p', { style: mutedTextStyle }, rawLocaleText(plugin.description)),
2520
+ h('p', { style: mutedTextStyle }, rawLocaleText(`${plugin.package_name}@${plugin.version}`), ' · 许可:',
2521
+ plugin.license ? rawLocaleText(plugin.license) : '未声明'),
2522
+ h('p', { style: mutedTextStyle }, `来源:${plugin.source_url || '未提供'} · DSH 版本要求:${plugin.peer_range || '包未声明'}`),
2523
+ h('p', { style: mutedTextStyle }, `额外配置:${plugin.requirements || '无'}`),
2524
+ installSpec && !artifactUrl ? h('p', { role: 'note', style: mutedTextStyle },
2525
+ 'ANT 通过 DSH 包管理器安装目录中的精确 npm 版本;实际下载和依赖解析由 DSH 执行。ANT 不批准依赖构建脚本;若 DSH 因此拒绝安装,请按 DSH 提示在原生插件管理页处理。插件自身更新器或 DSH 原生管理也可更新到目录外的版本。') : null,
2526
+ plugin.dependencies && artifactUrl ? h('p', { role: 'note', style: mutedTextStyle },
2527
+ '此插件声明了依赖。ANT 固定插件包本身;DSH 会在本机按当前配置解析依赖,不同设备可能得到不同版本。依赖构建脚本由 DSH 单独请求批准。') : null,
2528
+ plugin.scripts ? h('p', { style: mutedTextStyle }, `包自身的安装脚本:${plugin.scripts}`) : null,
2529
+ plugin.status !== 'published' ? h('p', { role: 'status', style: security
2530
+ ? { ...mutedTextStyle, color: 'var(--dsw-alias-label-danger, #d44)' } : mutedTextStyle },
2531
+ plugin.withdrawal_reason || '团队已停止推荐此版本。') : null,
2532
+ local?.error ? h('p', { role: 'status', style: mutedTextStyle }, local.error.message || String(local.error)) : null,
2533
+ sameVersion && !sourceKnown && artifactUrl ? h('p', { style: mutedTextStyle }, recordedInstall
2534
+ ? '此前曾由企业扩展安装;当前 DSH 无法再次核对来源。正常使用无需重复安装;若后来换过来源,可以重新安装。'
2535
+ : '已装同版且使用正常时无需重复安装;若想改用团队审核包,可自愿安装。') : null,
2536
+ h('div', { style: { display: 'flex', flexWrap: 'wrap', gap: 8 } },
2537
+ installSpec && (!local || (local.version && local.version !== plugin.version && (!localAhead || artifactUrl))
2538
+ || (artifactUrl && sameVersion && !verifiedLocal))
2539
+ ? h('button', { type: 'button', disabled: Boolean(workingId) || uncertainId === plugin.id || completedId === plugin.id,
2540
+ onClick: () => void install(plugin), style: primaryButtonStyle },
2541
+ workingId === plugin.id ? '安装中…' : uncertainId === plugin.id ? '先核对安装结果'
2542
+ : completedId === plugin.id ? '重启 DSH 后生效'
2543
+ : local ? sameVersion || localAhead ? '按团队审核包重新安装' : '更新到审核版本' : '安装到这台 DSH') : null,
2544
+ plugin.status === 'published' && !local && !installSpec
2545
+ ? h('p', { style: mutedTextStyle }, '如需安装,请联系企业管理员安排。') : null,
2546
+ local || uncertainId === plugin.id ? h('button', { type: 'button', onClick: () => openBundle(plugin.package_name), style: secondaryButtonStyle }, '打开 DSH 插件管理') : null,
2547
+ local && !sameVersion && plugin.status === 'published' && !installSpec
2548
+ ? h('p', { style: mutedTextStyle }, '本机版本与团队审核版本不同;请联系企业管理员核对。') : null))
2549
+ })) : !loading && plugins.length && (!embedded || !hasSkillMatches)
2550
+ ? h('p', { style: mutedTextStyle }, noMatches) : null))
2551
+ }
2552
+
2553
+ function ModelSyncFooter({ remote, serviceUrl, bindingReady, activeTab, onServiceUrlChange,
2554
+ onConnectionChange, onUpdateStateChange, onSelectTab }) {
2555
+ const [email, setEmail] = useState('')
2556
+ const [code, setCode] = useState('')
2557
+ const [message, setMessage] = useState('')
2558
+ const [modelMessage, setModelMessage] = useState('')
2559
+ const [busy, setBusy] = useState(false)
2560
+ const [codeRequested, setCodeRequested] = useState(false)
2561
+ const [credentialConfigured, setCredentialConfigured] = useState(null)
2562
+ const [reauthenticate, setReauthenticate] = useState(false)
2563
+ const [needsReconnect, setNeedsReconnect] = useState(false)
2564
+ const [allowLocalCleanup, setAllowLocalCleanup] = useState(false)
2565
+ const [bundleRelease, setBundleRelease] = useState(null)
2566
+ const [bundleUpdate, setBundleUpdate] = useState({ state: 'idle', currentVersion: '', message: '' })
2567
+ const [dshCompatibility, setDshCompatibility] = useState({ state: 'checking', runtime_version: null,
2568
+ required_range: null, validated_baseline: null, message: '正在读取 DSH 客户端版本…' })
2569
+ const dshCompatibilityCheckRevision = useRef(0)
2570
+ const [authorizedModels, setAuthorizedModels] = useState([])
2571
+ const [providerSyncGroups, setProviderSyncGroups] = useState([])
2572
+ const [appliedProviderSyncExclusions, setAppliedProviderSyncExclusions] = useState([])
2573
+ const [providerSyncDraft, setProviderSyncDraft] = useState([])
2574
+ const [imageInputOptOuts, setImageInputOptOuts] = useState(() => ({
2575
+ serviceUrl: normalizeServiceUrl(serviceUrl),
2576
+ modelKeys: readImageInputOptOuts(serviceUrl),
2577
+ }))
2578
+ const [appliedImageInputOptOuts, setAppliedImageInputOptOuts] = useState(() => readImageInputOptOuts(serviceUrl))
2579
+ const [serverDefaultModel, setServerDefaultModel] = useState(null)
2580
+ const [dshDefaultSelection, setDshDefaultSelection] = useState(null)
2581
+ const [defaultModelDraft, setDefaultModelDraft] = useState('')
2582
+ const [defaultModelBusy, setDefaultModelBusy] = useState(false)
2583
+ const [defaultModelMessage, setDefaultModelMessage] = useState('')
2584
+ const [lastModelSync, setLastModelSync] = useState(null)
2585
+ const [serviceCompatibility, setServiceCompatibility] = useState({ state: 'idle', message: '' })
2586
+ const [pinnedServiceUrl, setPinnedServiceUrl] = useState(null)
2587
+
2588
+ useEffect(() => {
2589
+ onUpdateStateChange?.({ ...bundleUpdate, version: bundleRelease?.version || '', dshCompatibility })
2590
+ }, [bundleUpdate, bundleRelease, dshCompatibility, onUpdateStateChange])
2591
+
2592
+ useEffect(() => {
2593
+ const saved = readImageInputOptOuts(serviceUrl)
2594
+ setImageInputOptOuts({ serviceUrl: normalizeServiceUrl(serviceUrl), modelKeys: saved })
2595
+ setAppliedImageInputOptOuts(saved)
2596
+ }, [serviceUrl])
2597
+
2598
+ const inspectDshCompatibility = async (requiredRange = null) => {
2599
+ const revision = ++dshCompatibilityCheckRevision.current
2600
+ try {
2601
+ const response = await fetch('/api/ant-teams/dsh-compatibility', {
2602
+ cache: 'no-store',
2603
+ ...(requiredRange ? { method: 'POST', headers: { 'content-type': 'application/json' },
2604
+ body: JSON.stringify({ required_range: requiredRange }) } : {}),
2605
+ })
2606
+ const result = await readLocalJsonResponse(response)
2607
+ if (!response.ok || !['incompatible', 'range-met', 'untested', 'unknown'].includes(result.state)
2608
+ || typeof result.required_range !== 'string' || typeof result.message !== 'string'
2609
+ || (result.runtime_version !== null && typeof result.runtime_version !== 'string')) {
2610
+ throw new Error('DSH 客户端兼容状态响应无效。')
2611
+ }
2612
+ if (revision === dshCompatibilityCheckRevision.current) setDshCompatibility(result)
2613
+ return result
2614
+ } catch {
2615
+ const result = {
2616
+ state: 'unknown', runtime_version: null,
2617
+ required_range: typeof requiredRange === 'string' ? requiredRange : null, validated_baseline: null,
2618
+ message: '无法读取 DSH 客户端版本;当前不能确认 ANT 与 DSH 兼容。',
2619
+ }
2620
+ if (revision === dshCompatibilityCheckRevision.current) setDshCompatibility(result)
2621
+ return result
2622
+ }
2623
+ }
2624
+
2625
+ const markDshCompatibilityUnknown = (message) => {
2626
+ dshCompatibilityCheckRevision.current += 1
2627
+ const result = { state: 'unknown', runtime_version: null, required_range: null,
2628
+ validated_baseline: null, message }
2629
+ setDshCompatibility(result)
2630
+ return result
2631
+ }
2632
+
2633
+ useEffect(() => {
2634
+ void inspectDshCompatibility()
2635
+ return () => { dshCompatibilityCheckRevision.current += 1 }
2636
+ }, [])
2637
+
2638
+ const connectionErrorMessage = (result, status) => {
2639
+ const message = result?.message || `请求失败(${status})`
2640
+ if (!['LEGACY_DEVICE_REVOKE_REQUIRED', 'ANT_CONNECTION_CLEANUP_REQUIRED'].includes(result?.code)) return message
2641
+ setAllowLocalCleanup(true)
2642
+ const deviceId = savedDeviceId()
2643
+ return deviceId
2644
+ ? `${message} 设备编号:${deviceId}。请把编号提供给原团队管理员。`
2645
+ : `${message} 本机无法确认旧设备编号;请让原团队管理员按成员查看设备清单,勿用新编号猜测。`
2646
+ }
2647
+
2648
+ const inspectServiceCompatibility = async (rawServiceUrl, useSavedConnection = false, isCurrent = () => true) => {
2649
+ const normalized = normalizeServiceUrl(rawServiceUrl)
2650
+ if (!normalized && !useSavedConnection) {
2651
+ if (isCurrent()) setServiceCompatibility({ state: 'idle', message: '' })
2652
+ return null
2653
+ }
2654
+ if (isCurrent()) setServiceCompatibility({ state: 'checking', message: '正在识别 ANT 客户端与服务端版本…' })
2655
+ try {
2656
+ const manager = remote?.pluginManager
2657
+ if (typeof manager?.listBundles !== 'function') throw new Error('当前 DSH 未提供 Bundle 版本读取接口。')
2658
+ const listed = await manager.listBundles()
2659
+ if (!listed.ok) throw new Error(listed.error?.message || '无法读取已安装的 ANT Bundle 版本。')
2660
+ const installed = listed.value.find((bundle) => bundle.name === ANT_BUNDLE_PACKAGE_NAME && bundle.installed)
2661
+ if (typeof installed?.version !== 'string') throw new Error('无法确定当前 ANT Bundle 版本。')
2662
+ const response = await fetch('/api/ant-teams/service-info', {
2663
+ method: 'POST',
2664
+ headers: { 'Content-Type': 'application/json' },
2665
+ body: JSON.stringify({
2666
+ service_url: normalized || '',
2667
+ bundle_version: installed.version,
2668
+ api_protocol_versions: ANT_API_PROTOCOL_VERSIONS,
2669
+ }),
2670
+ })
2671
+ const result = await readLocalJsonResponse(response)
2672
+ if (!response.ok) throw new Error(result.message || `版本检查失败(${response.status})`)
2673
+ const serverProtocols = Array.isArray(result.server_api_protocol_versions) ? result.server_api_protocol_versions : []
2674
+ const sharedProtocols = Array.isArray(result.shared_api_protocol_versions) ? result.shared_api_protocol_versions : []
2675
+ const compatibility = typeof result.compatibility === 'boolean'
2676
+ ? result.compatibility
2677
+ : serverProtocols.length === 0 ? null : sharedProtocols.length > 0
2678
+ const message = compatibility === true
2679
+ ? `服务端 v${result.server_version} · ANT Bundle v${result.bundle_version} · API 协议 v${sharedProtocols.join(', v')}:兼容。`
2680
+ : compatibility === false
2681
+ ? `服务端 v${result.server_version} · ANT Bundle v${result.bundle_version}:没有共同 API 协议(服务端 v${serverProtocols.join(', v')},客户端 v${ANT_API_PROTOCOL_VERSIONS.join(', v')})。请更新 ANT 插件或联系管理员升级服务端。`
2682
+ : `已识别 ANT Bundle v${result.bundle_version} 和服务端 v${result.server_version};服务端未提供协议能力,兼容性未知,仍允许继续。`
2683
+ const state = compatibility === true ? 'compatible' : compatibility === false ? 'incompatible' : 'unknown'
2684
+ const status = { state, message, ...result }
2685
+ if (isCurrent()) setServiceCompatibility(status)
2686
+ return status
2687
+ } catch (error) {
2688
+ const status = {
2689
+ state: 'unknown',
2690
+ message: `无法确认 ANT 版本兼容性,仍允许继续:${error instanceof Error ? error.message : '连接检查失败。'}`,
2691
+ }
2692
+ if (isCurrent()) setServiceCompatibility(status)
2693
+ return status
2694
+ }
2695
+ }
2696
+
2697
+ const requireCompatibleService = async (rawServiceUrl, useSavedConnection = false) => {
2698
+ const status = await inspectServiceCompatibility(rawServiceUrl, useSavedConnection)
2699
+ if (status?.state === 'incompatible') throw new Error(status.message)
2700
+ return status
2701
+ }
2702
+
2703
+ const modelProvider = (model) => {
2704
+ const providerId = typeof model?.provider_id === 'string' ? model.provider_id : ''
2705
+ if (!providerId) return null
2706
+ return model.protocol === 'anthropic'
2707
+ ? 'ant-team-anthropic-' + providerId
2708
+ : 'ant-team-openai-' + providerId + '-' + (model.openai_api_mode === 'responses' ? 'responses' : 'chat-completions')
2709
+ }
2710
+ const oldDefaultRoutes = ['ant-team-openai-responses', 'ant-team-openai-chat-completions',
2711
+ 'ant-team-openai', 'ant-team-anthropic']
2712
+ const isAntModelProviderRoute = (route, profile) => typeof route === 'string'
2713
+ && profile?.apiKeyEnv === 'ANT_MODEL_API_KEY'
2714
+ && (oldDefaultRoutes.includes(route)
2715
+ || route.startsWith('ant-team-openai-') || route.startsWith('ant-team-anthropic-'))
2716
+ const modelSelectionKey = (model) => JSON.stringify({ provider_id: model.provider_id || '', protocol: model.protocol, model_id: model.model_id })
2717
+ const defaultPreferenceKey = (rawServiceUrl) => `${DEFAULT_MODEL_INITIALIZED_KEY}:${normalizeServiceUrl(rawServiceUrl)}:${savedDeviceId() || ''}`
2718
+ const providerSyncPreferenceKey = (rawServiceUrl) => `${PROVIDER_SYNC_EXCLUSIONS_KEY}:${normalizeServiceUrl(rawServiceUrl)}:${savedDeviceId() || ''}`
2719
+ const toggleModelImageInput = (model, enabled) => {
2720
+ if (model.supports_images !== true) return
2721
+ const normalized = normalizeServiceUrl(serviceUrl)
2722
+ setImageInputOptOuts((current) => {
2723
+ const currentValues = current.serviceUrl === normalized
2724
+ ? current.modelKeys : readImageInputOptOuts(normalized)
2725
+ const next = new Set(currentValues)
2726
+ const key = modelSelectionKey(model)
2727
+ if (enabled) next.delete(key)
2728
+ else next.add(key)
2729
+ return { serviceUrl: normalized, modelKeys: [...next] }
2730
+ })
2731
+ }
2732
+ const readDefaultPreference = (rawServiceUrl) => {
2733
+ try { return JSON.parse(localStorage.getItem(defaultPreferenceKey(rawServiceUrl)) || 'null') } catch { return null }
2734
+ }
2735
+ const saveDefaultPreference = (rawServiceUrl, value) => {
2736
+ try { localStorage.setItem(defaultPreferenceKey(rawServiceUrl), JSON.stringify(value)) } catch {}
2737
+ }
2738
+ const modelForProviderSelection = (selection, models) => {
2739
+ if (!selection) return null
2740
+ return models.find((model) => model.model_id === selection.model
2741
+ && modelProvider(model) === selection.provider) || null
2742
+ }
2743
+ const readDshDefaultSelection = async () => {
2744
+ if (typeof remote?.settings?.describe !== 'function') throw new Error('当前 DSH 未提供全局默认模型读取接口。')
2745
+ const response = await remote.settings.describe()
2746
+ if (!response?.ok) throw new Error(response?.error?.message || '无法读取这台 DSH 的全局默认模型。')
2747
+ const value = response.value?.namespaces?.find((entry) => entry.ns === 'agent-default-model')?.value
2748
+ return value && typeof value.provider === 'string' && typeof value.model === 'string'
2749
+ ? { provider: value.provider, model: value.model,
2750
+ ...(typeof value.reasoningEffort === 'string' ? { reasoningEffort: value.reasoningEffort } : {}) } : null
2751
+ }
2752
+ const readDshProviderProfiles = async () => {
2753
+ if (typeof remote?.settings?.describe !== 'function') throw new Error('无法读取 DSH 中的 ANT 提供方列表。')
2754
+ const response = await remote.settings.describe()
2755
+ if (!response?.ok) throw new Error(response?.error?.message || '无法读取 DSH 中的 ANT 提供方列表。')
2756
+ const profiles = response.value?.namespaces?.find((entry) => entry.ns === 'llm-pi-ai')?.value?.providers
2757
+ return profiles && typeof profiles === 'object' ? profiles : {}
2758
+ }
2759
+ const writeDshDefaultModel = async (model) => {
2760
+ const response = await remote.settings.mutate('agent-default-model', [
2761
+ { op: 'set', path: ['provider'], value: modelProvider(model) },
2762
+ { op: 'set', path: ['model'], value: model.model_id },
2763
+ { op: 'unset', path: ['reasoningEffort'] },
2764
+ ], undefined)
2765
+ if (!response?.ok) throw new Error(response?.error?.message || 'DSH 无法保存全局默认模型。')
2766
+ const selection = { provider: modelProvider(model), model: model.model_id }
2767
+ setDshDefaultSelection(selection)
2768
+ setDefaultModelDraft(modelSelectionKey(model))
2769
+ return selection
2770
+ }
2771
+ const applyUserDefaultModel = async (model) => {
2772
+ if (!model || !syncedModels.some((item) => modelSelectionKey(item) === modelSelectionKey(model))) {
2773
+ setDefaultModelMessage('请选择当前已同步到 DSH 的模型。')
2774
+ return
2775
+ }
2776
+ setDefaultModelBusy(true)
2777
+ try {
2778
+ const selection = await writeDshDefaultModel(model)
2779
+ const preference = readDefaultPreference(serviceUrl) || { initialized: true, serverDefault: '' }
2780
+ const isServerDefault = serverDefaultModel && modelSelectionKey(model) === modelSelectionKey(serverDefaultModel)
2781
+ if (isServerDefault) preference.serverDefault = modelSelectionKey(serverDefaultModel)
2782
+ preference.initialized = true
2783
+ saveDefaultPreference(serviceUrl, preference)
2784
+ setDshDefaultSelection(selection)
2785
+ setDefaultModelMessage(`已将 ${model.display_name || model.model_id} 设为 DSH 全局默认模型。`)
2786
+ } catch (error) {
2787
+ setDefaultModelMessage(error instanceof Error ? error.message : '保存本机默认模型失败。')
2788
+ } finally { setDefaultModelBusy(false) }
2789
+ }
2790
+ const applyAuthorizedModels = async (models, rawServiceUrl, rawDefaultModel = null, options = {}) => {
2791
+ const normalized = normalizeServiceUrl(rawServiceUrl)
2792
+ if (!normalized || !Array.isArray(models)) throw new Error('ANT 返回的团队模型目录格式无效。')
2793
+ if (typeof remote?.settings?.mutate !== 'function') throw new Error('当前 DSH 未提供模型设置接口。')
2794
+ const imageOptOuts = imageInputOptOuts.serviceUrl === normalized
2795
+ ? imageInputOptOuts.modelKeys : readImageInputOptOuts(normalized)
2796
+ const imageOptOutSet = new Set(imageOptOuts)
2797
+ const grouped = new Map()
2798
+ for (const model of models) {
2799
+ const protocol = model.protocol
2800
+ if (!['openai', 'anthropic'].includes(protocol)) continue
2801
+ if (typeof model.provider_id !== 'string' || !model.provider_id) {
2802
+ throw new Error('ANT 返回的模型缺少 provider_id;请升级服务端后重试。')
2803
+ }
2804
+ const providerId = model.provider_id
2805
+ const apiMode = protocol === 'openai'
2806
+ ? model.openai_api_mode === 'responses' ? 'responses' : 'chat_completions'
2807
+ : null
2808
+ const key = providerId + '\u0000' + protocol + '\u0000' + (apiMode || '')
2809
+ let provider = grouped.get(key)
2810
+ if (!provider) {
2811
+ const providerName = model.provider_name || (protocol === 'openai'
2812
+ ? 'ANT 团队 · OpenAI' : 'ANT 团队 · Anthropic')
2813
+ provider = {
2814
+ providerId,
2815
+ providerName: protocol === 'openai'
2816
+ ? compactOpenaiProviderName(providerName)
2817
+ : providerName,
2818
+ protocol,
2819
+ apiMode,
2820
+ models: [],
2821
+ }
2822
+ grouped.set(key, provider)
2823
+ }
2824
+ provider.models.push(model)
2825
+ }
2826
+ const providers = [...grouped.values()]
2827
+ const routeForProvider = (provider) => modelProvider({
2828
+ provider_id: provider.providerId,
2829
+ protocol: provider.protocol,
2830
+ openai_api_mode: provider.apiMode,
2831
+ })
2832
+ const routeConfigurations = new Map()
2833
+ const providerGroups = []
2834
+ const dshModelConfig = (model) => {
2835
+ const hasReasoningEfforts = model.reasoning_efforts && Object.keys(model.reasoning_efforts).length > 0
2836
+ const compat = { ...(model.compat || {}) }
2837
+ if (model.protocol === 'anthropic' && hasReasoningEfforts
2838
+ && compat.forceAdaptiveThinking === undefined) {
2839
+ compat.forceAdaptiveThinking = true
2840
+ }
2841
+ return {
2842
+ id: model.model_id,
2843
+ name: model.display_name,
2844
+ ...(Number.isSafeInteger(model.context_window) && model.context_window > 0
2845
+ ? { contextWindow: model.context_window } : {}),
2846
+ ...(Number.isSafeInteger(model.max_tokens) && model.max_tokens > 0
2847
+ ? { maxTokens: model.max_tokens } : {}),
2848
+ ...(model.supports_images === true && !imageOptOutSet.has(modelSelectionKey(model))
2849
+ ? { input: ['text', 'image'] } : {}),
2850
+ ...(hasReasoningEfforts ? { reasoningEfforts: model.reasoning_efforts } : {}),
2851
+ ...(Object.keys(compat).length > 0 ? { compat } : {}),
2852
+ }
2853
+ }
2854
+ for (const provider of providers) {
2855
+ const route = routeForProvider(provider)
2856
+ const api = provider.protocol === 'openai'
2857
+ ? provider.apiMode === 'responses' ? 'openai-responses' : 'openai-completions'
2858
+ : 'anthropic-messages'
2859
+ const baseURL = provider.protocol === 'openai'
2860
+ ? new URL('/model-gateway/openai/providers/' + encodeURIComponent(provider.providerId) + '/v1', normalized).toString()
2861
+ : new URL('/model-gateway/anthropic/providers/' + encodeURIComponent(provider.providerId), normalized).toString()
2862
+ routeConfigurations.set(route, {
2863
+ displayName: provider.providerName,
2864
+ apiKeyEnv: 'ANT_MODEL_API_KEY',
2865
+ api,
2866
+ baseURL,
2867
+ models: provider.models.map(dshModelConfig),
2868
+ })
2869
+ providerGroups.push({
2870
+ key: route,
2871
+ label: provider.providerName + ' · ' + (provider.protocol === 'anthropic'
2872
+ ? 'Anthropic Messages' : provider.apiMode === 'responses' ? 'OpenAI Responses' : 'OpenAI Chat Completions'),
2873
+ routes: [route],
2874
+ modelCount: provider.models.length,
2875
+ })
2876
+ }
2877
+ const ops = []
2878
+ let previousRoutes = []
2879
+ try {
2880
+ const parsed = JSON.parse(localStorage.getItem(PROVIDER_ROUTES_STORAGE_KEY) || '[]')
2881
+ if (Array.isArray(parsed)) previousRoutes = parsed.filter((route) => typeof route === 'string')
2882
+ } catch {}
2883
+ const existingProfiles = await readDshProviderProfiles()
2884
+ const profileRoutes = Object.keys(existingProfiles).filter((route) =>
2885
+ isAntModelProviderRoute(route, existingProfiles[route]))
2886
+ const knownRoutes = new Set([...previousRoutes.filter((route) =>
2887
+ isAntModelProviderRoute(route, existingProfiles[route])), ...profileRoutes])
2888
+ const allGroups = providerGroups
2889
+ let savedExcludedGroups = null
2890
+ try {
2891
+ const saved = JSON.parse(localStorage.getItem(providerSyncPreferenceKey(normalized)) || 'null')
2892
+ if (Array.isArray(saved)) savedExcludedGroups = saved
2893
+ } catch {}
2894
+ let excludedGroups = options.excludedGroups
2895
+ if (!Array.isArray(excludedGroups) && savedExcludedGroups) excludedGroups = savedExcludedGroups
2896
+ if (!Array.isArray(excludedGroups)) excludedGroups = []
2897
+ excludedGroups = [...new Set(excludedGroups.filter((key) => allGroups.some((group) => group.key === key)))]
2898
+ const excludedGroupSet = new Set(excludedGroups)
2899
+ const excluded = new Set(allGroups.filter((group) => excludedGroupSet.has(group.key)).flatMap((group) => group.routes))
2900
+ const routes = [...routeConfigurations.keys()].filter((route) => !excluded.has(route))
2901
+ const syncedModels = models.filter((model) => !excluded.has(modelProvider(model)))
2902
+ if (models.length && !syncedModels.length) throw new Error('请至少保留一个常规模型 provider 同步到本机 DSH。')
2903
+ const staleRoutes = [...knownRoutes].filter((route) => !routes.includes(route))
2904
+ const obsoleteRoutes = staleRoutes.filter((route) => !routeConfigurations.has(route))
2905
+ const excludedRoutes = staleRoutes.filter((route) => routeConfigurations.has(route))
2906
+ const cleanupWarning = obsoleteRoutes.length && excludedRoutes.length
2907
+ ? '升级会移除旧路由和已关闭同步的 provider route。历史会话需手动选择仍同步且已获准的 ANT 模型。DSH 会将选择应用到当前会话并在后台设为本机 Profile 默认;保存成功后影响该 Profile 新会话及 ANT 对话/任务。之后可在 ANT「团队模型」页更改本机默认;重新启用 provider 可恢复标准 route。会话正文保留。仍要应用吗?'
2908
+ : obsoleteRoutes.length
2909
+ ? '升级会移除旧会话路由。继续历史会话需手动选择已获准并同步的 ANT 模型。DSH 会将选择应用到当前会话并在后台设为本机 Profile 默认;保存成功后影响该 Profile 新会话及 ANT 对话/任务。之后可在 ANT「团队模型」页更改本机默认。会话正文保留。仍要应用吗?'
2910
+ : excludedRoutes.length
2911
+ ? '关闭这些 provider 会从本机 DSH 移除对应模型路由,可能影响历史会话。重新勾选并刷新可恢复。仍要应用吗?'
2912
+ : ''
2913
+ if (cleanupWarning && !confirmLocalized(cleanupWarning)) {
2914
+ throw new Error('已取消旧 route 清理;本机 DSH 设置未修改。')
2915
+ }
2916
+ const defaultMatch = rawDefaultModel && models.find((model) =>
2917
+ model.provider_id === rawDefaultModel.provider_id
2918
+ && model.protocol === rawDefaultModel.protocol && model.model_id === rawDefaultModel.model_id)
2919
+ const syncedDefaultMatch = defaultMatch && syncedModels.some((model) => modelSelectionKey(model) === modelSelectionKey(defaultMatch))
2920
+ ? defaultMatch : null
2921
+ const serverDefault = syncedDefaultMatch || null
2922
+ const initialDefault = syncedDefaultMatch || (rawDefaultModel == null ? syncedModels[0] : null)
2923
+ const currentSelection = await readDshDefaultSelection()
2924
+ let selectionChangedForRouteCleanup = null
2925
+ if (isAntModelProviderRoute(currentSelection?.provider, existingProfiles[currentSelection?.provider])
2926
+ && !routes.includes(currentSelection.provider)) {
2927
+ const replacement = serverDefault || syncedModels[0]
2928
+ if (!replacement) throw new Error('请先配置一个获准并同步的 provider,再清理旧默认 route。')
2929
+ await writeDshDefaultModel(replacement)
2930
+ selectionChangedForRouteCleanup = currentSelection
2931
+ }
2932
+ for (const route of knownRoutes) {
2933
+ if (!routes.includes(route)) ops.push({ op: 'unset', path: ['providers', route] })
2934
+ }
2935
+ for (const [route, value] of routeConfigurations) {
2936
+ ops.push({ op: 'set', path: ['providers', route], value })
2937
+ }
2938
+ const restoreDefaultAfterRouteWriteFailure = async (failure) => {
2939
+ if (!selectionChangedForRouteCleanup) return
2940
+ const previous = selectionChangedForRouteCleanup
2941
+ try {
2942
+ const restore = await remote.settings.mutate('agent-default-model', [
2943
+ { op: 'set', path: ['provider'], value: previous.provider },
2944
+ { op: 'set', path: ['model'], value: previous.model },
2945
+ previous.reasoningEffort
2946
+ ? { op: 'set', path: ['reasoningEffort'], value: previous.reasoningEffort }
2947
+ : { op: 'unset', path: ['reasoningEffort'] },
2948
+ ], undefined)
2949
+ if (!restore?.ok) throw new Error(restore?.error?.message || 'DSH 无法恢复全局默认模型。')
2950
+ setDshDefaultSelection(previous)
2951
+ const previousModel = modelForProviderSelection(previous, syncedModels)
2952
+ setDefaultModelDraft(previousModel ? modelSelectionKey(previousModel) : '')
2953
+ } catch (rollbackError) {
2954
+ const rollbackMessage = rollbackError instanceof Error ? rollbackError.message : 'DSH 无法恢复全局默认模型。'
2955
+ throw new Error(`${failure.message || 'DSH 无法更新团队模型设置。'} 本机默认模型也未能恢复:${rollbackMessage}`)
2956
+ }
2957
+ }
2958
+ let settingsWrite
2959
+ try {
2960
+ settingsWrite = await remote.settings.mutate('llm-pi-ai', ops, undefined)
2961
+ } catch (error) {
2962
+ await restoreDefaultAfterRouteWriteFailure(error)
2963
+ throw error
2964
+ }
2965
+ if (!settingsWrite?.ok) {
2966
+ const error = new Error(settingsWrite?.error?.message || 'DSH 无法更新团队模型设置。')
2967
+ await restoreDefaultAfterRouteWriteFailure(error)
2968
+ throw error
2969
+ }
2970
+ saveImageInputOptOuts(normalized, imageOptOuts)
2971
+ setImageInputOptOuts({ serviceUrl: normalized, modelKeys: imageOptOuts })
2972
+ setAppliedImageInputOptOuts(imageOptOuts)
2973
+ try { localStorage.setItem(PROVIDER_ROUTES_STORAGE_KEY, JSON.stringify(routes)) } catch {}
2974
+ try { localStorage.setItem(providerSyncPreferenceKey(normalized), JSON.stringify(excludedGroups)) } catch {}
2975
+ setProviderSyncGroups(allGroups)
2976
+ setAppliedProviderSyncExclusions(excludedGroups)
2977
+ setProviderSyncDraft(excludedGroups)
2978
+ setServerDefaultModel(serverDefault)
2979
+ const preference = readDefaultPreference(normalized)
2980
+ let statusMessage = obsoleteRoutes.length
2981
+ ? '旧兼容 route 已清理;继续旧会话需手动选择已获准并同步的 ANT 模型。DSH 会在后台保存为本机 Profile 默认,成功后影响新会话及 ANT 对话/任务;之后可在 ANT「团队模型」页更改默认。'
2982
+ : ''
2983
+ let selection
2984
+ if (!preference?.initialized && initialDefault) {
2985
+ const previousDefault = await readDshDefaultSelection()
2986
+ selection = await writeDshDefaultModel(initialDefault)
2987
+ saveDefaultPreference(normalized, { initialized: true, serverDefault: modelSelectionKey(serverDefault || initialDefault), previousDefault })
2988
+ statusMessage = serverDefault
2989
+ ? '已按团队默认模型设置 DSH 全局默认。该 Profile 的新会话会使用此模型;你之后可在此更改,刷新不会覆盖选择。'
2990
+ : '当前无法使用团队默认模型;已用首个获准模型初始化 DSH 全局默认。请管理员检查默认设置和成员授权。'
2991
+ } else {
2992
+ selection = await readDshDefaultSelection()
2993
+ const currentAuthorized = modelForProviderSelection(selection, syncedModels)
2994
+ const baseline = syncedModels.find((model) => modelSelectionKey(model) === preference?.serverDefault)
2995
+ const stillUsingBaseline = baseline && currentAuthorized && modelSelectionKey(currentAuthorized) === modelSelectionKey(baseline)
2996
+ if (currentAuthorized && selection?.provider !== modelProvider(currentAuthorized)) {
2997
+ selection = await writeDshDefaultModel(currentAuthorized)
2998
+ }
2999
+ if (serverDefault && stillUsingBaseline && modelSelectionKey(serverDefault) !== preference.serverDefault) {
3000
+ selection = await writeDshDefaultModel(serverDefault)
3001
+ saveDefaultPreference(normalized, { ...preference, initialized: true, serverDefault: modelSelectionKey(serverDefault) })
3002
+ statusMessage = '团队默认模型已更新;你尚未设置个人覆盖,因此已同步到 DSH 全局默认。'
3003
+ } else if (isAntModelProviderRoute(selection?.provider, existingProfiles[selection?.provider])
3004
+ && !currentAuthorized && syncedModels.length) {
3005
+ const fallback = serverDefault || syncedModels[0]
3006
+ selection = await writeDshDefaultModel(fallback)
3007
+ saveDefaultPreference(normalized, { ...preference, initialized: true,
3008
+ serverDefault: modelSelectionKey(serverDefault || fallback) })
3009
+ statusMessage = serverDefault
3010
+ ? '当前默认模型已失去授权,已恢复为团队默认模型。'
3011
+ : '当前默认模型已失去授权,已改用首个获准模型;请管理员设置团队默认模型。'
3012
+ }
3013
+ const effectiveAuthorized = modelForProviderSelection(selection, syncedModels)
3014
+ setDshDefaultSelection(selection)
3015
+ setDefaultModelDraft(effectiveAuthorized ? modelSelectionKey(effectiveAuthorized) : '')
3016
+ if (!serverDefault && !statusMessage) statusMessage = rawDefaultModel
3017
+ ? '团队默认模型当前未同步到这台 DSH;请在下方选择一个已同步模型作为本机默认。'
3018
+ : '团队默认模型尚未设置;请联系管理员设置,或在下方选择本机可用的默认模型。'
3019
+ else if (!statusMessage) statusMessage = effectiveAuthorized
3020
+ ? '已保留你选择的 DSH 全局默认模型。'
3021
+ : '当前 DSH 默认不属于 ANT 获准模型;ANT 对话和任务会使用服务端默认模型。'
3022
+ }
3023
+ setDefaultModelMessage(statusMessage)
3024
+ try { localStorage.setItem(SERVICE_URL_STORAGE_KEY, normalized) } catch {}
3025
+ onServiceUrlChange(normalized)
3026
+ return { count: syncedModels.length, defaultSelection: selection }
3027
+ }
3028
+
3029
+ const requestTeamModelCatalog = async (version = '3') => {
3030
+ const response = await fetch('/api/ant-teams/models', {
3031
+ method: 'POST', headers: { 'x-ant-model-provider-config': version },
3032
+ })
3033
+ return { response, result: await readLocalJsonResponse(response) }
3034
+ }
3035
+ const requestCompatibleTeamModelCatalog = async () => {
3036
+ const current = await requestTeamModelCatalog('3')
3037
+ if (!current.response.ok || current.result.model_provider_config_version === 3) return current
3038
+ return requestTeamModelCatalog('2')
3039
+ }
3040
+
3041
+ const refreshModels = async (applyDraft = false) => {
3042
+ if (!bindingReady) {
3043
+ setMessage('请先等待团队绑定检查完成,再刷新团队模型。')
3044
+ return
3045
+ }
3046
+ setBusy(true)
3047
+ setModelMessage('正在从 ANT 刷新获准模型…')
3048
+ try {
3049
+ await requireCompatibleService(serviceUrl, true)
3050
+ const { response, result } = await requestCompatibleTeamModelCatalog()
3051
+ if (!response.ok) {
3052
+ if (response.status === 401) setNeedsReconnect(true)
3053
+ throw new Error(result.message || `刷新失败(${response.status})`)
3054
+ }
3055
+ if (![2, 3].includes(result.model_provider_config_version)) {
3056
+ throw new Error('服务端不支持 provider-config v2,请先升级 ANT 服务端。')
3057
+ }
3058
+ const sync = await applyAuthorizedModels(result.models, result.service_url, result.default_model,
3059
+ applyDraft ? { excludedGroups: providerSyncDraft } : {})
3060
+ setAuthorizedModels(result.models)
3061
+ setLastModelSync(new Date())
3062
+ setCredentialConfigured(true)
3063
+ setNeedsReconnect(false)
3064
+ setReauthenticate(false)
3065
+ setModelMessage(`模型目录已刷新,共同步 ${sync.count} 个获准模型。`)
3066
+ } catch (error) {
3067
+ setModelMessage(error instanceof Error ? error.message : '刷新模型失败,请稍后重试。')
3068
+ } finally {
3069
+ setBusy(false)
3070
+ }
3071
+ }
3072
+
3073
+ const checkBundleUpdate = async () => {
3074
+ setBundleUpdate({ state: 'checking', currentVersion: '', message: '正在检查 ANT 更新…' })
3075
+ try {
3076
+ const response = await fetch('/api/ant-teams/bundle-release', {
3077
+ cache: 'no-store', headers: {
3078
+ 'x-ant-bundle-capabilities': 'direct-package-install',
3079
+ 'x-ant-bundle-update-mode': 'check-only',
3080
+ },
3081
+ })
3082
+ const release = await readLocalJsonResponse(response)
3083
+ if (!response.ok) throw new Error(release.message || `检查失败(${response.status})`)
3084
+ const legacyInstallSpec = `ant@npm:${ANT_BUNDLE_PACKAGE_NAME}@${release.version}`
3085
+ const directSpec = directInstallSpec(release)
3086
+ const validPackageName = release.package_name === ANT_BUNDLE_PACKAGE_NAME
3087
+ const validVersion = typeof release.version === 'string'
3088
+ && (release.version === '' || /^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)$/u.test(release.version))
3089
+ const validDshRange = release.dsh_engine_range === undefined
3090
+ || (typeof release.dsh_engine_range === 'string' && release.dsh_engine_range.length <= 128
3091
+ && (!release.dsh_engine_range || /^[0-9A-Za-z .+*|,<>=~^\-]+$/u.test(release.dsh_engine_range)))
3092
+ if (release.bundle_name !== 'ant' || !validPackageName || !validVersion || !validDshRange
3093
+ || typeof release.install_spec !== 'string' || typeof release.release_notes !== 'string'
3094
+ || (release.version && release.install_spec !== legacyInstallSpec)
3095
+ || (!release.version && release.install_spec !== '')
3096
+ || (release.direct_install_spec !== undefined && release.direct_install_spec !== directSpec)) {
3097
+ throw new Error('ANT 更新信息字段无效。')
3098
+ }
3099
+ setBundleRelease(release)
3100
+ if (!release.version) {
3101
+ setBundleUpdate({ state: 'none', currentVersion: '', message: '管理员尚未发布 ANT 更新。' })
3102
+ return
3103
+ }
3104
+ const manager = remote?.pluginManager
3105
+ if (typeof manager?.listBundles !== 'function') throw new Error('当前 DSH 版本未提供官方 Bundle 管理器。')
3106
+ const listed = await manager.listBundles()
3107
+ if (!listed.ok) throw new Error(listed.error?.message || '无法读取 DSH 已安装 Bundle。')
3108
+ const installed = listed.value.find((bundle) => bundle.name === release.package_name && bundle.installed)
3109
+ if (!installed || typeof installed.version !== 'string') {
3110
+ const legacy = listed.value.find((bundle) => bundle.name === 'ant' && bundle.installed)
3111
+ if (legacy) {
3112
+ setBundleUpdate({
3113
+ state: 'migration-required', currentVersion: legacy.version || '',
3114
+ message: `当前安装使用旧 alias(${legacy.name})。请在 DSH 插件管理器卸载旧 ANT,再直接安装 ${release.package_name}@${release.version} 并重启 DSH。若管理器无法完成迁移,请参考 ANT 包内的备用迁移说明。`,
3115
+ })
3116
+ return
3117
+ }
3118
+ throw new Error(`当前 DSH 未找到已安装的 ${release.package_name} Bundle。`)
3119
+ }
3120
+ const available = newerVersion(release.version, installed.version)
3121
+ if (release.artifact_status === 'revoked') {
3122
+ setBundleUpdate({ state: 'revoked', currentVersion: installed.version,
3123
+ message: installed.version === release.version
3124
+ ? `当前 ANT ${installed.version} 的安装包已因安全问题停用。请联系企业管理员获取处理方式;ANT 不会自动删除本机副本。`
3125
+ : `发布版本 ${release.version} 的安装包已因安全问题停用,请等待管理员发布修复版本。` })
3126
+ return
3127
+ }
3128
+ let compatibility = null
3129
+ if (available && release.dsh_engine_range) {
3130
+ compatibility = await inspectDshCompatibility(release.dsh_engine_range)
3131
+ if (compatibility.state === 'incompatible') {
3132
+ setBundleUpdate({ state: 'incompatible', currentVersion: installed.version,
3133
+ message: `已暂停更新:${compatibility.message}` })
3134
+ return
3135
+ }
3136
+ if (!['range-met', 'untested'].includes(compatibility.state)) {
3137
+ setBundleUpdate({ state: 'unknown', currentVersion: installed.version,
3138
+ message: `无法确认候选版本与当前 DSH 的兼容性,已暂停更新。${compatibility.message}` })
3139
+ return
3140
+ }
3141
+ } else if (available) {
3142
+ const unknown = markDshCompatibilityUnknown(
3143
+ 'ANT 服务端没有提供这份候选制品的 DSH 兼容范围,已暂停更新。请管理员发布带有 DSH 兼容声明的制品。')
3144
+ setBundleUpdate({ state: 'unknown', currentVersion: installed.version, message: unknown.message })
3145
+ return
3146
+ }
3147
+ const artifactUrl = approvedArtifactUrl(release)
3148
+ setBundleUpdate({
3149
+ state: available ? artifactUrl ? 'available' : 'artifact-missing' : 'current',
3150
+ currentVersion: installed.version,
3151
+ message: available
3152
+ ? artifactUrl
3153
+ ? compatibility?.state === 'untested'
3154
+ ? `发现新版本 ${release.version}。当前 DSH 版本尚未验收,请核对上方兼容提示后再更新。`
3155
+ : `发现新版本 ${release.version},当前 DSH 在兼容范围内。`
3156
+ : `发现新版本 ${release.version},但管理员尚未提供已审核安装包。请联系管理员。`
3157
+ : `当前已是最新发布版本(${installed.version})。`,
3158
+ })
3159
+ } catch (error) {
3160
+ setBundleUpdate({ state: 'failed', currentVersion: '', message: error instanceof Error ? error.message : '检查 ANT 更新失败。' })
3161
+ }
3162
+ }
3163
+
3164
+ const installBundleUpdate = async () => {
3165
+ if (bundleUpdate.state !== 'available') return
3166
+ if (!bundleRelease?.dsh_engine_range) {
3167
+ markDshCompatibilityUnknown('当前 ANT 更新缺少 DSH 兼容范围,已暂停安装。请联系管理员补全发布制品信息。')
3168
+ return
3169
+ }
3170
+ const compatibility = await inspectDshCompatibility(bundleRelease.dsh_engine_range)
3171
+ if (!['range-met', 'untested'].includes(compatibility.state)) return
3172
+ const artifactUrl = approvedArtifactUrl(bundleRelease)
3173
+ if (!artifactUrl) return
3174
+ const manager = remote?.pluginManager
3175
+ if (typeof manager?.installBundle !== 'function') {
3176
+ setBundleUpdate((current) => ({ ...current, state: 'failed', message: '当前 DSH 未提供 Bundle 更新接口。' }))
3177
+ return
3178
+ }
3179
+ setBusy(true)
3180
+ setBundleUpdate((current) => ({ ...current, state: 'installing', message: '正在由 DSH 安装已审核的 ANT 更新…' }))
3181
+ try {
3182
+ const releaseResponse = await fetch('/api/ant-teams/bundle-release', {
3183
+ cache: 'no-store', headers: {
3184
+ 'x-ant-bundle-capabilities': 'direct-package-install',
3185
+ 'x-ant-bundle-update-mode': 'check-only',
3186
+ },
3187
+ })
3188
+ const latest = await readLocalJsonResponse(releaseResponse)
3189
+ if (!releaseResponse.ok || latest.version !== bundleRelease.version
3190
+ || latest.artifact_sha256 !== bundleRelease.artifact_sha256
3191
+ || approvedArtifactUrl(latest) !== artifactUrl) {
3192
+ throw new Error('ANT 更新信息已变化,请重新检查更新。')
3193
+ }
3194
+ const requestId = crypto.randomUUID()
3195
+ let result
3196
+ try {
3197
+ result = await manager.installBundle(artifactUrl, { enabled: true, requestId })
3198
+ } catch {
3199
+ result = null
3200
+ }
3201
+ if (!result?.ok) {
3202
+ let recovered = null
3203
+ if (typeof manager.waitForInstall === 'function') {
3204
+ try {
3205
+ const pending = await manager.waitForInstall(requestId)
3206
+ if (pending.ok && pending.value) recovered = { ok: true, value: pending.value }
3207
+ } catch {}
3208
+ }
3209
+ if (!recovered) {
3210
+ setBundleUpdate((current) => ({ ...current, state: 'unknown',
3211
+ message: 'DSH 连接中断,更新结果暂时无法确认。请先在 DSH 插件列表查看 ANT 版本,勿重复点击更新。' }))
3212
+ return
3213
+ }
3214
+ result = recovered
3215
+ }
3216
+ const outcome = result.value
3217
+ if (outcome.application === 'failed' || outcome.application === 'cancelled') {
3218
+ const reason = outcome.error?.diagnostic || outcome.packageResult?.output || '安装未完成。'
3219
+ if (outcome.error?.code === 'incompatible-version') {
3220
+ const runtimeVersion = typeof outcome.error?.runtimeVersion === 'string'
3221
+ ? outcome.error.runtimeVersion : ''
3222
+ const compatibilityMessage = runtimeVersion
3223
+ ? translateLocaleText('DSH 安装器判定当前客户端 {runtime_version} 与此 ANT 版本不兼容:{reason}',
3224
+ { runtime_version: runtimeVersion, reason })
3225
+ : translateLocaleText('DSH 安装器判定当前客户端与此 ANT 版本不兼容:{reason}', { reason })
3226
+ setDshCompatibility((current) => ({ ...current, state: 'incompatible',
3227
+ runtime_version: runtimeVersion || current.runtime_version,
3228
+ message: compatibilityMessage }))
3229
+ }
3230
+ setBundleUpdate((current) => ({ ...current, state: 'failed', message: `更新失败:${reason}` }))
3231
+ return
3232
+ }
3233
+ if (outcome.bundle !== ANT_BUNDLE_PACKAGE_NAME
3234
+ || !['restart-required', 'applied'].includes(outcome.application)) {
3235
+ throw new Error('DSH 未确认 ANT 安装成功,请联系管理员检查插件状态。')
3236
+ }
3237
+ let observed = null
3238
+ try {
3239
+ const installed = await manager.listBundles()
3240
+ if (installed.ok && Array.isArray(installed.value)) {
3241
+ observed = installed.value.find((bundle) => bundle.name === ANT_BUNDLE_PACKAGE_NAME && bundle.installed) || null
3242
+ }
3243
+ } catch {}
3244
+ if ((outcome.version && outcome.version !== bundleRelease.version) || observed?.version !== bundleRelease.version) {
3245
+ setBundleUpdate((current) => ({ ...current, state: 'unknown',
3246
+ message: 'DSH 未确认新版本已安装。请先在 DSH 插件列表核对 ANT 版本,勿重复点击更新。' }))
3247
+ return
3248
+ }
3249
+ setBundleUpdate({ state: 'done', currentVersion: bundleRelease.version,
3250
+ message: `ANT ${bundleRelease.version} 已安装。请完全退出并重新启动 DSH 后生效。` })
3251
+ } catch (error) {
3252
+ setBundleUpdate((current) => ({ ...current, state: 'failed', message: error instanceof Error ? error.message : '更新未完成。' }))
3253
+ } finally {
3254
+ setBusy(false)
3255
+ }
3256
+ }
3257
+
3258
+ const clearLocalConnection = async () => {
3259
+ if (typeof remote?.settings?.mutate !== 'function') throw new Error('DSH 未提供模型设置接口。')
3260
+ const existingProfiles = await readDshProviderProfiles()
3261
+ const isManagedRoute = (route) => isAntModelProviderRoute(route, existingProfiles[route])
3262
+ const selection = await readDshDefaultSelection()
3263
+ if (isManagedRoute(selection?.provider)) {
3264
+ const previous = readDefaultPreference(serviceUrl)?.previousDefault
3265
+ const restore = previous && typeof previous.provider === 'string' && typeof previous.model === 'string'
3266
+ && !isManagedRoute(previous.provider)
3267
+ const operations = restore
3268
+ ? [
3269
+ { op: 'set', path: ['provider'], value: previous.provider },
3270
+ { op: 'set', path: ['model'], value: previous.model },
3271
+ previous.reasoningEffort
3272
+ ? { op: 'set', path: ['reasoningEffort'], value: previous.reasoningEffort }
3273
+ : { op: 'unset', path: ['reasoningEffort'] },
3274
+ ]
3275
+ : [
3276
+ { op: 'unset', path: ['provider'] },
3277
+ { op: 'unset', path: ['model'] },
3278
+ { op: 'unset', path: ['reasoningEffort'] },
3279
+ ]
3280
+ const reset = await remote.settings.mutate('agent-default-model', [
3281
+ ...operations,
3282
+ ], undefined)
3283
+ if (!reset.ok) throw new Error(reset.error?.message || 'DSH 全局默认模型未能恢复。')
3284
+ }
3285
+ const routes = Object.keys(existingProfiles).filter(isManagedRoute)
3286
+ const settingsResult = await remote.settings.mutate('llm-pi-ai', [...routes].map((route) => ({
3287
+ op: 'unset', path: ['providers', route],
3288
+ })), undefined)
3289
+ if (!settingsResult.ok) throw new Error(settingsResult.error?.message || 'ANT 模型设置未能清除。')
3290
+ try { localStorage.removeItem(PROVIDER_ROUTES_STORAGE_KEY) } catch {}
3291
+ if (typeof remote?.credentials?.unset !== 'function') throw new Error('DSH 未提供凭证删除接口。')
3292
+ const credentialResult = await remote.credentials.unset('ANT_MODEL_API_KEY')
3293
+ if (!credentialResult.ok) throw new Error(credentialResult.error?.message || 'ANT 成员凭证未能清除。')
3294
+ setCredentialConfigured(false)
3295
+ setAuthorizedModels([]); setServerDefaultModel(null); setDshDefaultSelection(null); setDefaultModelDraft('')
3296
+ setProviderSyncGroups([]); setAppliedProviderSyncExclusions([]); setProviderSyncDraft([])
3297
+ try { localStorage.removeItem(`${DEFAULT_MODEL_INITIALIZED_KEY}:${normalizeServiceUrl(serviceUrl)}:${savedDeviceId() || ''}`) } catch {}
3298
+ onConnectionChange?.(null)
3299
+ setNeedsReconnect(false)
3300
+ setReauthenticate(false)
3301
+ setAllowLocalCleanup(false)
3302
+ }
3303
+
3304
+ const disconnect = async () => {
3305
+ setBusy(true)
3306
+ setMessage('正在断开此设备的 ANT 连接…')
3307
+ try {
3308
+ const response = await fetch('/api/ant-teams/disconnect', { method: 'POST' })
3309
+ const result = await readLocalJsonResponse(response)
3310
+ if (!response.ok || result.revoked !== true) {
3311
+ throw new Error(connectionErrorMessage(result, response.status))
3312
+ }
3313
+ } catch (error) {
3314
+ setAllowLocalCleanup(true)
3315
+ setBusy(false)
3316
+ setMessage(`未清除本机凭证和模型设置:${error instanceof Error ? error.message : '请稍后重试。'}`)
3317
+ return
3318
+ }
3319
+ try {
3320
+ await clearLocalConnection()
3321
+ setMessage('此设备的 ANT 凭证已撤销,ANT 模型设置已清除。团队服务地址已保留。')
3322
+ } catch (error) {
3323
+ setAllowLocalCleanup(true)
3324
+ setMessage(`服务端已撤销设备令牌,但本机清理失败:${error instanceof Error ? error.message : '请稍后重试'}。可选择仅清理本机。`)
3325
+ } finally { setBusy(false) }
3326
+ }
3327
+
3328
+ const clearOnlyLocal = async () => {
3329
+ if (!confirmLocalized('仅清理这台 DSH 的 ANT 凭证和模型设置,不保证服务端设备令牌已撤销。请先让原团队管理员确认远端撤销;否则令牌可能仍可被使用。确定继续吗?')) return
3330
+ setBusy(true)
3331
+ try {
3332
+ await clearLocalConnection()
3333
+ setMessage('已仅清理本机 ANT 凭证和模型设置。此操作未确认服务端撤销,请向原团队管理员核对。')
3334
+ } catch (error) {
3335
+ setMessage(`本机清理未完成:${error instanceof Error ? error.message : '请稍后重试。'}`)
3336
+ } finally { setBusy(false) }
3337
+ }
3338
+
3339
+ useEffect(() => {
3340
+ let current = true
3341
+ const describe = remote?.credentials?.describe
3342
+ if (typeof describe !== 'function') {
3343
+ setCredentialConfigured(null)
3344
+ return () => { current = false }
3345
+ }
3346
+ describe.call(remote.credentials, ['ANT_MODEL_API_KEY']).then((result) => {
3347
+ if (!current) return
3348
+ const configured = result.ok ? Boolean(result.value?.ANT_MODEL_API_KEY?.configured) : null
3349
+ setCredentialConfigured(configured)
3350
+ if (configured && bindingReady) {
3351
+ void refreshModels()
3352
+ void checkBundleUpdate()
3353
+ }
3354
+ }).catch(() => { if (current) setCredentialConfigured(null) })
3355
+ return () => { current = false }
3356
+ }, [remote, bindingReady])
3357
+
3358
+ useEffect(() => {
3359
+ let current = true
3360
+ if (credentialConfigured !== true) {
3361
+ setPinnedServiceUrl(null)
3362
+ return () => { current = false }
3363
+ }
3364
+ const readPinnedOrigin = async () => {
3365
+ try {
3366
+ const response = await fetch('/api/ant-teams/connection-origin', { cache: 'no-store' })
3367
+ const result = await readLocalJsonResponse(response)
3368
+ if (current) setPinnedServiceUrl(response.ok ? normalizeServiceUrl(result.service_url) : null)
3369
+ } catch { if (current) setPinnedServiceUrl(null) }
3370
+ }
3371
+ void readPinnedOrigin()
3372
+ return () => { current = false }
3373
+ }, [remote, credentialConfigured])
3374
+
3375
+ useEffect(() => {
3376
+ if (!bindingReady) {
3377
+ setServiceCompatibility({ state: 'idle', message: '' })
3378
+ return
3379
+ }
3380
+ let current = true
3381
+ void inspectServiceCompatibility(serviceUrl, credentialConfigured === true, () => current)
3382
+ return () => { current = false }
3383
+ }, [remote, serviceUrl, credentialConfigured, bindingReady])
3384
+
3385
+ const requestCode = async (event) => {
3386
+ event.preventDefault()
3387
+ if (!bindingReady) {
3388
+ setMessage('请先等待团队绑定检查完成,再验证工作邮箱。')
3389
+ return
3390
+ }
3391
+ const normalized = normalizeServiceUrl(serviceUrl)
3392
+ const normalizedEmail = email.trim()
3393
+ if (!normalized) {
3394
+ setMessage('请先在上方填写并保存团队服务地址。')
3395
+ return
3396
+ }
3397
+ if (!normalizedEmail) {
3398
+ setMessage('请填写工作邮箱。')
3399
+ return
3400
+ }
3401
+ if (credentialConfigured !== false && !savedDeviceId()) {
3402
+ if (credentialConfigured === true) setAllowLocalCleanup(true)
3403
+ setMessage(credentialConfigured === true
3404
+ ? '旧 ANT 凭证仍在,但本机无法确认它绑定的设备编号。请让原团队管理员按成员核查并撤销旧设备,再仅清理本机。'
3405
+ : '尚未确认本机凭证状态,也没有已保存的设备编号。请等待检查完成,或修复 DSH 凭证接口后重试。')
3406
+ return
3407
+ }
3408
+ setBusy(true)
3409
+ setMessage('正在发送邮箱验证码…')
3410
+ try {
3411
+ await requireCompatibleService(normalized)
3412
+ localStorage.setItem(SERVICE_URL_STORAGE_KEY, normalized)
3413
+ const response = await fetch('/api/ant-teams/request-code', {
3414
+ method: 'POST',
3415
+ headers: { 'Content-Type': 'application/json', 'X-Ant-Locale': localeRuntime?.getLocale?.().active || 'en' },
3416
+ body: JSON.stringify({ service_url: normalized, email: normalizedEmail }),
3417
+ })
3418
+ const result = await readLocalJsonResponse(response)
3419
+ if (!response.ok) throw new Error(connectionErrorMessage(result, response.status))
3420
+ setEmail(normalizedEmail)
3421
+ setCodeRequested(true)
3422
+ setMessage(result.message || '如果该邮箱符合团队规则,验证码将发送至邮箱。')
3423
+ } catch (error) {
3424
+ setMessage(error instanceof Error ? error.message : '验证码发送失败,请稍后重试。')
3425
+ } finally {
3426
+ setBusy(false)
3427
+ }
3428
+ }
3429
+
3430
+ const connect = async (event) => {
3431
+ event.preventDefault()
3432
+ if (!bindingReady) {
3433
+ setMessage('请先等待团队绑定检查完成,再连接团队。')
3434
+ return
3435
+ }
3436
+ const normalized = normalizeServiceUrl(serviceUrl)
3437
+ const normalizedEmail = email.trim()
3438
+ const normalizedCode = code.trim()
3439
+ if (!normalized || !normalizedEmail || !/^\d{8}$/u.test(normalizedCode)) {
3440
+ setMessage('请填写有效的服务地址、工作邮箱和 8 位验证码。')
3441
+ return
3442
+ }
3443
+ if (credentialConfigured !== false && !savedDeviceId()) {
3444
+ if (credentialConfigured === true) setAllowLocalCleanup(true)
3445
+ setMessage(credentialConfigured === true
3446
+ ? '旧 ANT 凭证仍在,但本机无法确认旧设备编号。请先联系原团队管理员撤销旧设备,再仅清理本机。'
3447
+ : '尚未确认本机凭证状态,也没有已保存的设备编号。请等待检查完成,或修复 DSH 凭证接口后重试。')
3448
+ return
3449
+ }
3450
+ setBusy(true)
3451
+ setMessage('正在验证邮箱并同步团队模型…')
3452
+ let credentialSaved = false
3453
+ try {
3454
+ await requireCompatibleService(normalized)
3455
+ localStorage.setItem(SERVICE_URL_STORAGE_KEY, normalized)
3456
+ const response = await fetch('/api/ant-teams/connect', {
3457
+ method: 'POST',
3458
+ headers: { 'Content-Type': 'application/json', 'x-ant-model-provider-config': '3' },
3459
+ body: JSON.stringify({
3460
+ service_url: normalized,
3461
+ email: normalizedEmail,
3462
+ code: normalizedCode,
3463
+ device_id: loadDeviceId(),
3464
+ }),
3465
+ })
3466
+ const result = await readLocalJsonResponse(response)
3467
+ if (!response.ok) throw new Error(connectionErrorMessage(result, response.status))
3468
+ if (typeof result.token !== 'string' || !result.token.startsWith('antm_') || !Array.isArray(result.models)) {
3469
+ throw new Error('ANT 返回的连接信息格式无效。')
3470
+ }
3471
+ if (typeof remote?.credentials?.set !== 'function' || typeof remote?.settings?.mutate !== 'function') {
3472
+ throw new Error('当前 DSH 版本未提供安全凭证和模型设置接口。')
3473
+ }
3474
+ const credentialWrite = await remote.credentials.set('ANT_MODEL_API_KEY', result.token)
3475
+ if (!credentialWrite.ok) throw new Error(credentialWrite.error?.message || 'DSH 无法安全保存 ANT 凭证。')
3476
+ credentialSaved = true
3477
+ let modelCatalog = result
3478
+ if (result.model_provider_config_version !== 3) {
3479
+ const fallback = await requestTeamModelCatalog('2')
3480
+ if (!fallback.response.ok) {
3481
+ if (fallback.response.status === 401) setNeedsReconnect(true)
3482
+ throw new Error(fallback.result.message || `刷新失败(${fallback.response.status})`)
3483
+ }
3484
+ modelCatalog = fallback.result
3485
+ }
3486
+ if (![2, 3].includes(modelCatalog.model_provider_config_version)) {
3487
+ throw new Error('服务端不支持 provider-config v2,请先升级 ANT 服务端。')
3488
+ }
3489
+ await applyAuthorizedModels(modelCatalog.models, normalized, modelCatalog.default_model)
3490
+ setAuthorizedModels(modelCatalog.models)
3491
+ setLastModelSync(new Date())
3492
+ setCode('')
3493
+ onServiceUrlChange(normalized)
3494
+ setCodeRequested(false)
3495
+ setCredentialConfigured(true)
3496
+ onConnectionChange?.(normalized)
3497
+ setAllowLocalCleanup(false)
3498
+ setNeedsReconnect(false)
3499
+ setReauthenticate(false)
3500
+ setMessage(`已连接 ${result.email || normalizedEmail},同步 ${modelCatalog.models.length} 个获准模型。它们现已出现在 DSH 模型选择器中。`)
3501
+ } catch (error) {
3502
+ if (credentialSaved) {
3503
+ setCredentialConfigured(true)
3504
+ setCode('')
3505
+ setCodeRequested(false)
3506
+ onConnectionChange?.(normalized)
3507
+ setMessage(`ANT 凭证已保存,但团队模型未能同步:${error instanceof Error ? error.message : '请稍后重试。'} 请点击“刷新团队模型”重试。`)
3508
+ } else {
3509
+ setMessage(error instanceof Error ? error.message : '连接失败,请稍后重试。')
3510
+ }
3511
+ } finally {
3512
+ setBusy(false)
3513
+ }
3514
+ }
3515
+
3516
+ const showConnectForm = credentialConfigured !== true || reauthenticate || needsReconnect
3517
+ const canCheckUpdate = bindingReady && credentialConfigured === true && !needsReconnect
3518
+ const updateGuideUrl = pinnedServiceUrl
3519
+ ? new URL('/ant-update', pinnedServiceUrl).href : null
3520
+ const currentDshDefaultModel = modelForProviderSelection(dshDefaultSelection, authorizedModels, serverDefaultModel)
3521
+ const excludedGroupSet = new Set(providerSyncDraft)
3522
+ const excludedRouteSet = new Set(providerSyncGroups.filter((group) => excludedGroupSet.has(group.key))
3523
+ .flatMap((group) => group.routes))
3524
+ const appliedExcludedGroupSet = new Set(appliedProviderSyncExclusions)
3525
+ const appliedExcludedRouteSet = new Set(providerSyncGroups.filter((group) => appliedExcludedGroupSet.has(group.key))
3526
+ .flatMap((group) => group.routes))
3527
+ const syncedModels = authorizedModels.filter((model) => !appliedExcludedRouteSet.has(modelProvider(model)))
3528
+ const currentImageInputOptOuts = imageInputOptOuts.serviceUrl === normalizeServiceUrl(serviceUrl)
3529
+ ? imageInputOptOuts.modelKeys : readImageInputOptOuts(serviceUrl)
3530
+ const imageInputOptOutSet = new Set(currentImageInputOptOuts)
3531
+ const appliedImageInputOptOutSet = new Set(appliedImageInputOptOuts)
3532
+ const hasPendingImageInputChanges = authorizedModels.some((model) => model.supports_images === true
3533
+ && imageInputOptOutSet.has(modelSelectionKey(model)) !== appliedImageInputOptOutSet.has(modelSelectionKey(model)))
3534
+ const hasPendingSyncChanges = [...new Set([...providerSyncDraft, ...appliedProviderSyncExclusions])]
3535
+ .some((key) => excludedGroupSet.has(key) !== appliedExcludedGroupSet.has(key))
3536
+ const activePrimaryGroupCount = providerSyncGroups.filter((group) => !excludedGroupSet.has(group.key)).length
3537
+ const pendingServerDefaultRemoval = hasPendingSyncChanges && serverDefaultModel
3538
+ ? providerSyncGroups.some((group) => group.routes.includes(modelProvider(serverDefaultModel))
3539
+ && !appliedExcludedGroupSet.has(group.key) && excludedGroupSet.has(group.key))
3540
+ : false
3541
+ const selectedDefaultDraft = syncedModels.find((model) => modelSelectionKey(model) === defaultModelDraft)
3542
+ const toggleProviderSyncGroup = (group, checked) => {
3543
+ setProviderSyncDraft((current) => {
3544
+ const next = new Set(current)
3545
+ if (checked) next.delete(group.key)
3546
+ else next.add(group.key)
3547
+ return [...next]
3548
+ })
3549
+ }
3550
+ const modelRows = authorizedModels.map((model) => {
3551
+ const providerName = model.protocol === 'openai'
3552
+ ? compactOpenaiProviderName(model.provider_name)
3553
+ : model.provider_name
3554
+ const isSynced = !excludedRouteSet.has(modelProvider(model))
3555
+ const imageInputEnabled = model.supports_images === true && !imageInputOptOutSet.has(modelSelectionKey(model))
3556
+ return h('div', { key: `${model.provider_id || ''}:${model.protocol}:${model.model_id}`, role: 'listitem',
3557
+ style: { display: 'grid', gridTemplateColumns: 'minmax(0, 1fr) minmax(120px, auto) minmax(190px, auto)',
3558
+ gap: 12, alignItems: 'center', padding: '10px 2px', borderBottom: '1px solid var(--dsw-alias-border-l2)' } },
3559
+ h('strong', { style: { minWidth: 0, overflowWrap: 'anywhere' } }, rawLocaleText(`${providerName ? `${providerName} · ` : ''}${model.display_name || model.model_id}`)),
3560
+ h('span', { style: { display: 'inline-flex', justifySelf: 'start', padding: '3px 8px', borderRadius: 999,
3561
+ backgroundColor: 'var(--dsw-alias-bg-layer-2)', color: 'var(--dsw-alias-label-secondary)', fontSize: 12 } },
3562
+ model.protocol === 'anthropic' ? 'Anthropic Messages' : `OpenAI · ${model.openai_api_mode === 'responses' ? 'Responses' : 'Chat Completions'}`),
3563
+ h('div', { style: { display: 'grid', justifyItems: 'end', gap: 5 } },
3564
+ h('span', { style: mutedTextStyle }, hasPendingSyncChanges
3565
+ ? isSynced ? '刷新后同步到 DSH' : '刷新后从 DSH 移除'
3566
+ : isSynced ? '已同步到 DSH' : '未同步到 DSH'),
3567
+ model.supports_images === true
3568
+ ? h('label', { style: { display: 'flex', alignItems: 'center', gap: 6, cursor: busy ? 'default' : 'pointer' } },
3569
+ h('input', { type: 'checkbox', 'aria-label': `允许 ${model.display_name || model.model_id} 在本机 DSH 接收图片`,
3570
+ checked: imageInputEnabled, disabled: busy,
3571
+ onChange: (event) => toggleModelImageInput(model, event.target.checked) }),
3572
+ h('span', { style: mutedTextStyle }, imageInputEnabled ? '本机允许图片输入' : '本机已关闭图片输入'))
3573
+ : h('span', { style: mutedTextStyle }, '团队未开放图片输入')))
3574
+ })
3575
+ const connectionPanel = h('section', { style: { ...settingsPanelStyle, display: activeTab === 'connection' ? 'grid' : 'none' } },
3576
+ h('div', null,
3577
+ h('h3', { style: sectionTitleStyle }, 'ANT 团队账号'),
3578
+ h('p', { style: { ...mutedTextStyle, marginTop: 4 } }, '邮箱验证建立这台 DSH 的成员凭证;断开后会清除此设备凭证和同步的模型设置。')),
3579
+ h('span', { role: 'status', style: mutedTextStyle }, credentialConfigured === true && !bindingReady
3580
+ ? '本机有 ANT 凭证,但尚未确认它绑定的团队;请完成上方的绑定检查。'
3581
+ : credentialConfigured === true ? 'DSH 已安全保存此设备的 ANT 团队凭证。'
3582
+ : credentialConfigured === false ? '验证工作邮箱后即可连接团队服务。' : '正在检查 ANT 连接状态…'),
3583
+ h('div', { role: 'note', style: infoNoticeStyle },
3584
+ h('strong', { style: { fontSize: 13, fontWeight: 600 } }, '配置保存范围'),
3585
+ h('p', { style: mutedTextStyle }, '团队模型与能力授权由 ANT 管理;成员凭证、Gitea 令牌、本机缓存和任务记录保存在这台 DSH。')),
3586
+ serviceCompatibility.state !== 'idle' ? h('p', { role: 'status', style: { ...mutedTextStyle,
3587
+ color: serviceCompatibility.state === 'incompatible' ? 'var(--dsw-alias-state-error-primary)' : mutedTextStyle.color } },
3588
+ serviceCompatibility.message) : null,
3589
+ credentialConfigured === true && !showConnectForm ? h('div', { style: { display: 'flex', flexWrap: 'wrap', gap: 8 } },
3590
+ h('button', { type: 'button', disabled: busy || !bindingReady,
3591
+ onClick: () => { setReauthenticate(true); setMessage('') }, style: secondaryButtonStyle }, '重新验证邮箱'),
3592
+ h('button', { type: 'button', disabled: busy,
3593
+ onClick: () => { if (confirmLocalized('断开当前设备与 ANT 的连接?本机 ANT 凭证和模型设置将被清除,团队服务地址会保留。')) void disconnect() },
3594
+ style: secondaryButtonStyle }, '断开当前设备')) : null,
3595
+ showConnectForm ? h('form', { onSubmit: requestCode, style: { display: 'grid', gap: 9, maxWidth: 560 } },
3596
+ h('label', { htmlFor: 'ant-team-model-email', style: { fontSize: 13, fontWeight: 550 } }, '工作邮箱'),
3597
+ h('input', { id: 'ant-team-model-email', type: 'email', autoComplete: 'email', required: true, value: email,
3598
+ onChange: (event) => setEmail(event.target.value), style: inputStyle }),
3599
+ h('button', { type: 'submit', disabled: busy || !bindingReady, style: primaryButtonStyle }, busy ? '发送中…' : '发送验证码')) : null,
3600
+ showConnectForm && codeRequested ? h('form', { onSubmit: connect, style: { display: 'grid', gap: 9, maxWidth: 560 } },
3601
+ h('label', { htmlFor: 'ant-team-model-code', style: { fontSize: 13, fontWeight: 550 } }, '邮箱验证码'),
3602
+ h('input', { id: 'ant-team-model-code', type: 'text', inputMode: 'numeric', autoComplete: 'one-time-code',
3603
+ required: true, maxLength: 8, value: code, placeholder: '8 位验证码',
3604
+ onChange: (event) => setCode(event.target.value.replace(/\D/gu, '').slice(0, 8)), style: inputStyle }),
3605
+ h('button', { type: 'submit', disabled: busy || !bindingReady || code.length !== 8, style: primaryButtonStyle }, busy ? '连接中…' : '验证并连接')) : null,
3606
+ credentialConfigured === true && showConnectForm ? h('button', { type: 'button', disabled: busy,
3607
+ onClick: () => { if (confirmLocalized('断开当前设备与 ANT 的连接?本机 ANT 凭证和模型设置将被清除,团队服务地址会保留。')) void disconnect() },
3608
+ style: secondaryButtonStyle }, '断开当前设备') : null,
3609
+ allowLocalCleanup ? h('section', { style: { ...settingsPanelStyle, padding: 14, gap: 9 } },
3610
+ h('p', { style: mutedTextStyle }, savedDeviceId()
3611
+ ? `已保存的设备编号:${savedDeviceId()}。请交给原团队管理员核对。`
3612
+ : '本机无法确认旧设备编号。请让原团队管理员按成员查看设备清单,勿用新编号猜测。'),
3613
+ h('p', { style: mutedTextStyle }, '仅清理本机不会确认服务端令牌已撤销;请先取得管理员确认。'),
3614
+ h('div', { style: { display: 'flex', flexWrap: 'wrap', gap: 8 } },
3615
+ h('button', { type: 'button', disabled: busy, onClick: () => void clearOnlyLocal(), style: secondaryButtonStyle }, '仅清理本机'),
3616
+ h('button', { type: 'button', disabled: busy || !savedDeviceId(), onClick: async () => {
3617
+ try {
3618
+ const deviceId = savedDeviceId()
3619
+ if (!deviceId) throw new Error('device id unavailable')
3620
+ if (typeof window.navigator?.clipboard?.writeText !== 'function') throw new Error('clipboard unavailable')
3621
+ await window.navigator.clipboard.writeText(deviceId)
3622
+ setMessage('设备编号已复制,请交给原团队管理员。')
3623
+ } catch { setMessage(savedDeviceId() ? `请复制设备编号:${savedDeviceId()}` : '本机无法确认旧设备编号,请联系原团队管理员核查。') }
3624
+ }, style: secondaryButtonStyle }, '复制设备编号'))) : null,
3625
+ message ? h('p', { role: 'status', style: feedbackNoticeStyle }, message) : null)
3626
+
3627
+ const modelPanel = h('section', { style: { ...settingsPanelStyle, display: activeTab === 'models' ? 'grid' : 'none' } },
3628
+ h('div', { style: { display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 12 } },
3629
+ h('div', null,
3630
+ h('h3', { style: sectionTitleStyle }, '团队模型'),
3631
+ h('p', { style: { ...mutedTextStyle, marginTop: 4 } }, '每个获准模型单独列出;刷新后同步到 DSH 模型选择器。'),
3632
+ h('p', { style: { ...mutedTextStyle, marginTop: 4 } }, '图片输入默认继承管理员设置;可为本机关闭单个模型的图片输入,不影响团队其他成员。刷新团队模型后生效。'),
3633
+ h('p', { style: { ...mutedTextStyle, marginTop: 4 } }, '协议与 API 模式按团队模型配置。DSH 的本机设置只影响当前 Profile,不会修改服务器;刷新团队模型会重新同步各模型路由。')),
3634
+ h('span', { style: { flexShrink: 0, padding: '4px 9px', borderRadius: 999,
3635
+ color: credentialConfigured === true && bindingReady ? 'var(--dsw-alias-state-success-primary)' : 'var(--dsw-alias-label-secondary)',
3636
+ backgroundColor: credentialConfigured === true && bindingReady ? 'var(--dsw-alias-state-success-tertiary)' : 'var(--dsw-alias-bg-layer-2)',
3637
+ fontSize: 12,
3638
+ } }, credentialConfigured === true ? bindingReady ? '已连接' : '待核对' : credentialConfigured === false ? '未连接' : '检查中')),
3639
+ h('section', { style: { ...infoNoticeStyle, gap: 8 } },
3640
+ h('div', { style: { display: 'flex', justifyContent: 'space-between', gap: 10, flexWrap: 'wrap', alignItems: 'center' } },
3641
+ h('strong', null, 'ANT 默认模型'),
3642
+ h('span', { style: mutedTextStyle }, serverDefaultModel
3643
+ ? `团队默认:${serverDefaultModel.display_name || serverDefaultModel.model_id}`
3644
+ : '团队默认尚未设置,或当前成员无权使用')),
3645
+ h('p', { style: mutedTextStyle }, '首次同步时,ANT 会用团队默认初始化 DSH 全局默认模型。它会影响该 Profile 的新会话以及 ANT 对话和任务;之后刷新保留你的个人覆盖。'),
3646
+ h('label', { style: { display: 'grid', gap: 5, maxWidth: 720 } }, 'DSH 全局默认模型',
3647
+ h('select', { 'aria-label': 'DSH 全局默认模型', value: defaultModelDraft,
3648
+ disabled: credentialConfigured !== true || !syncedModels.length || defaultModelBusy || busy || hasPendingSyncChanges,
3649
+ onChange: (event) => setDefaultModelDraft(event.target.value), style: inputStyle },
3650
+ h('option', { value: '' }, '选择获准模型'),
3651
+ ...syncedModels.map((model) => {
3652
+ const providerName = model.protocol === 'openai'
3653
+ ? compactOpenaiProviderName(model.provider_name)
3654
+ : model.provider_name
3655
+ const protocolName = model.protocol === 'anthropic' ? 'Anthropic' : `OpenAI ${model.openai_api_mode === 'responses' ? 'Responses' : 'Chat Completions'}`
3656
+ return h('option', { key: modelSelectionKey(model), value: modelSelectionKey(model) },
3657
+ rawLocaleText(`${providerName ? `${providerName} · ` : ''}${model.display_name || model.model_id} · ${protocolName}`))
3658
+ }))),
3659
+ h('div', { style: { display: 'flex', gap: 8, flexWrap: 'wrap', alignItems: 'center' } },
3660
+ h('button', { type: 'button', disabled: defaultModelBusy || !selectedDefaultDraft || hasPendingSyncChanges,
3661
+ onClick: () => void applyUserDefaultModel(selectedDefaultDraft),
3662
+ style: primaryButtonStyle }, defaultModelBusy ? '保存中…' : '保存为 DSH 全局默认'),
3663
+ h('button', { type: 'button', disabled: busy || defaultModelBusy || pendingServerDefaultRemoval || !serverDefaultModel
3664
+ || modelSelectionKey(currentDshDefaultModel || {}) === modelSelectionKey(serverDefaultModel),
3665
+ onClick: () => void applyUserDefaultModel(serverDefaultModel), style: secondaryButtonStyle }, '恢复团队默认'),
3666
+ currentDshDefaultModel ? h('span', { style: mutedTextStyle }, `当前 DSH 默认:${currentDshDefaultModel.display_name || currentDshDefaultModel.model_id}`) : null),
3667
+ pendingServerDefaultRemoval ? h('p', { role: 'status', style: mutedTextStyle },
3668
+ '团队默认 provider 正准备移除;先刷新应用同步范围,或重新勾选该 provider。') : null,
3669
+ defaultModelMessage ? h('p', { role: 'status', style: mutedTextStyle }, defaultModelMessage) : null),
3670
+ providerSyncGroups.length ? h('section', { style: { ...infoNoticeStyle, gap: 8 } },
3671
+ h('strong', null, '同步到本机 DSH 的 provider'),
3672
+ h('p', { style: mutedTextStyle }, '取消勾选并刷新后,该 provider 会从本机 DSH 移除;使用它的历史会话可能需要重新选择模型。'),
3673
+ h('p', { style: mutedTextStyle }, '至少保留一个获准 provider。'),
3674
+ hasPendingSyncChanges ? h('p', { role: 'status', style: mutedTextStyle }, '同步范围尚未应用;点击“刷新团队模型”后生效。') : null,
3675
+ ...providerSyncGroups.map((group) => h('label', { key: group.key,
3676
+ style: { display: 'flex', alignItems: 'center', gap: 9, padding: '5px 0', cursor: busy ? 'default' : 'pointer' } },
3677
+ h('input', { type: 'checkbox', 'aria-label': group.label,
3678
+ checked: !excludedGroupSet.has(group.key), disabled: busy
3679
+ || (!excludedGroupSet.has(group.key) && activePrimaryGroupCount <= 1),
3680
+ onChange: (event) => toggleProviderSyncGroup(group, event.target.checked) }),
3681
+ h('span', null, `${group.label} · ${group.modelCount} 个模型`)))) : null,
3682
+ hasPendingImageInputChanges ? h('p', { role: 'status', style: mutedTextStyle },
3683
+ '本机图片输入偏好尚未同步;点击“刷新团队模型”后生效。') : null,
3684
+ h('div', { role: 'list', 'aria-label': '获准模型', style: { display: 'grid', gap: 0, borderTop: '1px solid var(--dsw-alias-border-l2)' } },
3685
+ modelRows.length ? modelRows : h('div', { style: { display: 'grid', gap: 8, padding: '12px 0' } },
3686
+ h('p', { style: mutedTextStyle }, credentialConfigured === true && modelMessage.startsWith('正在') ? modelMessage
3687
+ : credentialConfigured === true ? '当前没有已获准模型,请刷新或联系团队管理员。'
3688
+ : '连接并验证工作邮箱后,这里会列出逐个获准模型。'),
3689
+ credentialConfigured !== true ? h('button', { type: 'button', onClick: () => onSelectTab('connection'),
3690
+ style: secondaryButtonStyle }, '前往团队连接') : null)),
3691
+ h('div', { style: { display: 'flex', flexWrap: 'wrap', alignItems: 'center', gap: 10 } },
3692
+ h('button', { type: 'button', disabled: busy || defaultModelBusy || !bindingReady || credentialConfigured !== true,
3693
+ onClick: () => void refreshModels(true), style: primaryButtonStyle }, busy ? '刷新中…' : '刷新团队模型'),
3694
+ lastModelSync ? h('span', { style: mutedTextStyle }, `最近同步:${lastModelSync.toLocaleString(formatLocale())}`) : null),
3695
+ modelMessage && !modelMessage.startsWith('正在') ? h('p', { role: 'status', style: mutedTextStyle }, modelMessage) : null)
3696
+
3697
+ const updateStatusLabels = {
3698
+ available: '有新版', 'artifact-missing': '等待发布制品', revoked: '安装包已撤回',
3699
+ 'migration-required': '需要迁移', incompatible: 'DSH 不兼容', unknown: '状态待确认', failed: '检查失败',
3700
+ installing: '正在安装', done: '需重启 DSH', current: '已是最新', checking: '正在检查', none: '尚未发布',
3701
+ }
3702
+ const dshCompatibilityLabels = {
3703
+ checking: '正在检查 DSH', incompatible: 'DSH 不兼容', 'range-met': '在声明范围内',
3704
+ untested: '版本尚未验收', unknown: 'DSH 版本未知',
3705
+ }
3706
+ const updateStatusNeedsDetails = ['artifact-missing', 'revoked', 'migration-required', 'incompatible', 'unknown', 'failed', 'installing', 'done']
3707
+ const updateVersionSummary = bundleUpdate.state === 'available'
3708
+ ? `可更新至 ${bundleRelease?.version || '最新版本'}`
3709
+ : updateStatusNeedsDetails.includes(bundleUpdate.state) ? '' : bundleUpdate.currentVersion && bundleRelease?.version
3710
+ ? bundleUpdate.currentVersion === bundleRelease.version
3711
+ ? `当前版本 ${bundleUpdate.currentVersion} · 已是最新`
3712
+ : `当前版本 ${bundleUpdate.currentVersion} · 最新版本 ${bundleRelease.version}`
3713
+ : bundleUpdate.currentVersion ? `当前版本 ${bundleUpdate.currentVersion}`
3714
+ : bundleRelease?.version ? `最新版本 ${bundleRelease.version}` : ''
3715
+ const showReleaseNotes = canCheckUpdate && bundleRelease?.version && bundleRelease.release_notes
3716
+ && ['current', 'available', 'artifact-missing'].includes(bundleUpdate.state)
3717
+ const dshCompatibilityCard = h('section', { role: 'status', style: {
3718
+ ...feedbackNoticeStyle,
3719
+ color: dshCompatibility.state === 'incompatible' ? 'var(--dsw-alias-state-error-primary)'
3720
+ : dshCompatibility.state === 'range-met' ? 'var(--dsw-alias-state-success-primary)'
3721
+ : 'var(--dsw-alias-state-warning-primary, var(--dsw-alias-label-secondary))',
3722
+ } },
3723
+ h('strong', null, `DSH 客户端兼容性:${dshCompatibilityLabels[dshCompatibility.state] || '状态未知'}`),
3724
+ h('p', { style: mutedTextStyle }, dshCompatibility.message),
3725
+ dshCompatibility.required_range ? h('p', { style: mutedTextStyle },
3726
+ `ANT 要求 ${dshCompatibility.required_range};已记录基线 ${dshCompatibility.validated_baseline || '未知'}。`) : null)
3727
+ const updatePanel = h('section', { style: { ...settingsPanelStyle, display: activeTab === 'updates' ? 'grid' : 'none' } },
3728
+ h('div', { style: { display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 12 } },
3729
+ h('div', null,
3730
+ h('h3', { style: sectionTitleStyle }, '关于 ANT'),
3731
+ h('p', { style: { ...mutedTextStyle, marginTop: 4 } }, '查看版本、更新说明和兼容状态。')),
3732
+ h('span', { style: { ...mutedTextStyle, flexShrink: 0,
3733
+ color: bundleUpdate.state === 'revoked' || serviceCompatibility.state === 'incompatible'
3734
+ || dshCompatibility.state === 'incompatible'
3735
+ ? 'var(--dsw-alias-state-error-primary)' : mutedTextStyle.color } },
3736
+ updateStatusLabels[bundleUpdate.state] || '等待检查')),
3737
+ updateVersionSummary ? h('p', { style: { ...mutedTextStyle, color: 'var(--dsw-alias-label-primary)', fontWeight: 550 } }, updateVersionSummary) : null,
3738
+ dshCompatibilityCard,
3739
+ showReleaseNotes ? h('section', { style: { ...infoNoticeStyle, padding: 12 } },
3740
+ h('strong', { style: { fontSize: 14, lineHeight: 1.4 } }, '本版更新'),
3741
+ h('p', { style: mutedTextStyle }, bundleRelease.release_notes)) : null,
3742
+ ['incompatible', 'unknown'].includes(serviceCompatibility.state) ? h('p', { role: 'status', style: {
3743
+ ...feedbackNoticeStyle,
3744
+ color: serviceCompatibility.state === 'incompatible' ? 'var(--dsw-alias-state-error-primary)'
3745
+ : 'var(--dsw-alias-state-warning-primary, var(--dsw-alias-label-secondary))',
3746
+ } }, `服务端兼容性:${serviceCompatibility.message}`) : null,
3747
+ bundleUpdate.message && updateStatusNeedsDetails.includes(bundleUpdate.state) ? h('p', { role: 'status', style: bundleUpdate.state === 'revoked'
3748
+ ? { ...feedbackNoticeStyle, color: 'var(--dsw-alias-state-error-primary)' } : feedbackNoticeStyle }, bundleUpdate.message) : null,
3749
+ !canCheckUpdate && updateGuideUrl ? h('a', { href: updateGuideUrl, target: '_blank', rel: 'noopener noreferrer',
3750
+ style: { color: 'var(--dsw-alias-link)', fontSize: 13 } }, '打开更新指引 ↗') : null,
3751
+ !canCheckUpdate && !updateGuideUrl ? h('p', { style: mutedTextStyle }, '无法核对原团队地址时,请向企业管理员索取更新指引。') : null,
3752
+ !canCheckUpdate ? h('button', { type: 'button', onClick: () => onSelectTab('connection'), style: secondaryButtonStyle },
3753
+ '前往团队连接') : null,
3754
+ canCheckUpdate && bundleUpdate.state === 'available'
3755
+ ? h('button', { type: 'button', disabled: busy || !bundleRelease?.dsh_engine_range
3756
+ || !['range-met', 'untested'].includes(dshCompatibility.state),
3757
+ onClick: () => void installBundleUpdate(), style: primaryButtonStyle }, busy ? '更新中…' : '更新 ANT') : null,
3758
+ h('button', { type: 'button', disabled: busy || !canCheckUpdate || bundleUpdate.state === 'checking',
3759
+ onClick: () => void checkBundleUpdate(), style: secondaryButtonStyle }, bundleUpdate.state === 'checking' ? '正在检查…' : '检查更新'))
3760
+
3761
+ return h('div', { style: { display: 'grid', gap: 16, width: '100%' } },
3762
+ connectionPanel, modelPanel, updatePanel)
3763
+
3764
+ }
3765
+
3766
+ function EnterpriseExtensionsPanelIcon({ size }) {
3767
+ return h('span', { 'aria-hidden': true, style: {
3768
+ display: 'inline-grid', placeItems: 'center', width: size, height: size,
3769
+ fontSize: size, lineHeight: 1,
3770
+ } }, '✦')
3771
+ }
3772
+
3773
+ function AntSettingsPanelIcon({ size }) {
3774
+ return h('span', { 'aria-hidden': true, style: {
3775
+ display: 'inline-grid', placeItems: 'center', width: size, height: size,
3776
+ color: 'var(--dsw-alias-brand-primary)', fontSize: size * 0.82, fontWeight: 700, lineHeight: 1,
3777
+ } }, 'A')
3778
+ }
3779
+
3780
+ function EnterpriseExtensionsPage({ remote, onBack, openBundle }) {
3781
+ useLocaleRevision()
3782
+ const [tab, setTab] = useState('all')
3783
+ const [query, setQuery] = useState('')
3784
+ const navigation = {
3785
+ onAll: () => setTab('all'), onSkills: () => setTab('skills'),
3786
+ onPlugins: () => setTab('plugins'),
3787
+ }
3788
+ return tab === 'plugins'
3789
+ ? h(PluginCenterPage, { remote, onBack, openBundle, query, onQueryChange: setQuery, ...navigation })
3790
+ : h(SkillCenterPage, { remote, onBack, openBundle, query, onQueryChange: setQuery,
3791
+ includePlugins: tab === 'all', ...navigation })
3792
+ }
3793
+
3794
+ function brandingCacheKey() {
3795
+ const serviceUrl = loadServiceUrl()
3796
+ return serviceUrl ? `${BRANDING_CACHE_PREFIX}${serviceUrl}` : null
3797
+ }
3798
+
3799
+ function readBrandingCache() {
3800
+ const key = brandingCacheKey()
3801
+ if (!key) return null
3802
+ try {
3803
+ const value = JSON.parse(localStorage.getItem(key) || 'null')
3804
+ if (!value || !Number.isSafeInteger(value.revision) || value.revision < 0) return null
3805
+ return value
3806
+ } catch { return null }
3807
+ }
3808
+
3809
+ function normalizeBranding(value) {
3810
+ if (!value || !Number.isSafeInteger(value.revision) || value.revision < 0) return null
3811
+ const fields = ['wordmark', 'badge', 'headline']
3812
+ if (fields.some((field) => value[field] != null && typeof value[field] !== 'string')) return null
3813
+ if (value.logo_data_url != null && (typeof value.logo_data_url !== 'string'
3814
+ || !/^data:image\/(?:png|jpeg|webp);base64,[A-Za-z0-9+/]+=*$/u.test(value.logo_data_url)
3815
+ || value.logo_data_url.length > 512 * 1024)) return null
3816
+ return { revision: value.revision, logo_data_url: value.logo_data_url || null,
3817
+ wordmark: value.wordmark || null, badge: value.badge || null, headline: value.headline || null }
3818
+ }
3819
+
3820
+ function installEnterpriseBranding(ctx) {
3821
+ const slotDisposers = new Map()
3822
+ const slotValues = new Map()
3823
+ const originalHeadlines = new Map()
3824
+ let headlineObserver = null
3825
+ let applied = null
3826
+ let timer = null
3827
+ let retryTimer = null
3828
+ let disposed = false
3829
+ const isHeroHeadlineNode = (node) => {
3830
+ let container = node?.parentElement
3831
+ const compact = (value) => value?.replace(/\s+/gu, '') || ''
3832
+ const aliases = [node?.textContent?.trim(), originalHeadlines.get(node)?.original,
3833
+ originalHeadlines.get(node)?.current, '探索未至之境', 'Into the Unknown'].filter(Boolean).map(compact)
3834
+ for (let depth = 0; container && depth < 6; depth += 1, container = container.parentElement) {
3835
+ if (!container.querySelector) continue
3836
+ const badges = [...container.querySelectorAll('span, small, label')]
3837
+ .filter((element) => ['预览版', 'Preview'].includes(element.textContent?.trim()))
3838
+ const marks = container.querySelectorAll('svg, img')
3839
+ const wholeRow = compact(container.textContent)
3840
+ if (badges.length === 1 && marks.length === 1
3841
+ && aliases.some((title) => ['预览版', 'Preview'].some((badge) =>
3842
+ wholeRow === `${title}${compact(badge)}` || wholeRow === `${compact(badge)}${title}`))) return true
3843
+ }
3844
+ return false
3845
+ }
3846
+ const replaceSlot = (name, value, component) => {
3847
+ if (slotValues.get(name) === value) return
3848
+ slotDisposers.get(name)?.()
3849
+ slotDisposers.delete(name); slotValues.delete(name)
3850
+ if (!value) return
3851
+ const dispose = ctx.slots.inject(name, () => ctx.slots.register({ name, priority: -1 }, component))
3852
+ slotDisposers.set(name, dispose); slotValues.set(name, value)
3853
+ }
3854
+ const replaceHeadlineNode = (node) => {
3855
+ if (node?.nodeType !== Node.TEXT_NODE) return
3856
+ const text = node.textContent?.trim()
3857
+ const prior = originalHeadlines.get(node)
3858
+ const matchesHeadline = text === '探索未至之境' || text === 'Into the Unknown'
3859
+ || text === prior?.original || text === prior?.current
3860
+ if (applied?.headline && text !== applied.headline && matchesHeadline && isHeroHeadlineNode(node)) {
3861
+ originalHeadlines.set(node, { original: prior?.original || text, current: applied.headline })
3862
+ node.textContent = applied.headline
3863
+ } else if (!applied?.headline && prior && text === prior.current) {
3864
+ node.textContent = prior.original
3865
+ originalHeadlines.delete(node)
3866
+ }
3867
+ }
3868
+ const replaceHeadlineSubtree = (root) => {
3869
+ if (!root) return
3870
+ if (root.nodeType === Node.TEXT_NODE) { replaceHeadlineNode(root); return }
3871
+ const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT)
3872
+ let node
3873
+ while ((node = walker.nextNode())) replaceHeadlineNode(node)
3874
+ }
3875
+ const updateHeadline = (records = null) => {
3876
+ if (typeof document === 'undefined' || !document.body) return
3877
+ if (!applied?.headline) {
3878
+ for (const [node, prior] of originalHeadlines) {
3879
+ if (node.textContent?.trim() === prior.current) {
3880
+ node.textContent = prior.original
3881
+ originalHeadlines.delete(node)
3882
+ }
3883
+ }
3884
+ return
3885
+ }
3886
+ if (!records) { replaceHeadlineSubtree(document.body); return }
3887
+ for (const record of records) {
3888
+ if (record.type === 'characterData') replaceHeadlineNode(record.target)
3889
+ else for (const node of record.addedNodes) replaceHeadlineSubtree(node)
3890
+ }
3891
+ for (const node of originalHeadlines.keys()) if (!node.isConnected) originalHeadlines.delete(node)
3892
+ }
3893
+ const apply = (value) => {
3894
+ const branding = normalizeBranding(value)
3895
+ applied = branding ? { ...branding } : null
3896
+ const logo = branding?.logo_data_url || null
3897
+ const nameValue = branding && (branding.wordmark || branding.badge)
3898
+ ? `${branding.wordmark || ''}\u0000${branding.badge || ''}` : null
3899
+ const mark = ({ size = 24, className }) => logo
3900
+ ? h('img', { src: logo, alt: '', className, draggable: false,
3901
+ style: { display: 'block', width: size, height: size, objectFit: 'contain' } }) : null
3902
+ const brandName = () => h('div', { style: { display: 'flex', alignItems: 'center', gap: 6, whiteSpace: 'nowrap' } },
3903
+ h('span', { style: { color: 'var(--dsw-alias-brand-primary)', fontWeight: 650 } }, branding?.wordmark || 'DEEPSEEK'),
3904
+ h('span', { style: { padding: '2px 5px', borderRadius: 4, color: 'var(--dsw-alias-label-primary-inverted)',
3905
+ background: 'var(--dsw-alias-brand-primary)', fontSize: 10, fontWeight: 650, letterSpacing: '.04em' } }, branding?.badge || 'HARNESS'))
3906
+ replaceSlot('sidebar.brand.mark', logo, mark)
3907
+ replaceSlot('conversation.hero.brand.mark', logo, mark)
3908
+ replaceSlot('sidebar.brand.name', nameValue, brandName)
3909
+ if (branding?.headline && !headlineObserver && typeof document !== 'undefined' && document.body) {
3910
+ headlineObserver = new MutationObserver(updateHeadline)
3911
+ headlineObserver.observe(document.body, { childList: true, subtree: true, characterData: true })
3912
+ }
3913
+ updateHeadline()
3914
+ }
3915
+
3916
+ const cleanup = () => {
3917
+ if (disposed) return
3918
+ disposed = true
3919
+ if (timer !== null) clearInterval(timer)
3920
+ if (retryTimer !== null) clearTimeout(retryTimer)
3921
+ headlineObserver?.disconnect()
3922
+ for (const [node, prior] of originalHeadlines) {
3923
+ if (node.textContent?.trim() === prior.current) node.textContent = prior.original
3924
+ }
3925
+ for (const dispose of slotDisposers.values()) dispose?.()
3926
+ }
3927
+
3928
+ try {
3929
+ apply(readBrandingCache())
3930
+ } catch (error) {
3931
+ cleanup()
3932
+ console.warn('ANT branding setup failed; continuing with the default DSH branding.', error)
3933
+ return cleanup
3934
+ }
3935
+
3936
+ let etag = applied?.revision ? `"${applied.revision}"` : null
3937
+ let retryCount = 0
3938
+ const refresh = async () => {
3939
+ if (disposed) return
3940
+ let retryable = true
3941
+ try {
3942
+ if (!loadServiceUrl()) {
3943
+ const originResponse = await fetch('/api/ant-teams/connection-origin', { cache: 'no-store' })
3944
+ if (disposed) return
3945
+ if (!originResponse.ok) return
3946
+ const originInfo = await readLocalJsonResponse(originResponse)
3947
+ if (disposed) return
3948
+ const origin = normalizeServiceUrl(originInfo?.service_url || '')
3949
+ if (!origin) return
3950
+ try { localStorage.setItem(SERVICE_URL_STORAGE_KEY, origin) } catch {}
3951
+ }
3952
+ const response = await fetch(BRANDING_SYNC_PATH, { cache: 'no-store',
3953
+ headers: etag ? { 'if-none-match': etag } : {} })
3954
+ if (disposed) return
3955
+ if (response.status === 304) { retryCount = 0; return }
3956
+ if (!response.ok) {
3957
+ retryable = [404, 426, 502, 503].includes(response.status)
3958
+ throw new Error('branding sync unavailable')
3959
+ }
3960
+ const branding = normalizeBranding(await readLocalJsonResponse(response))
3961
+ if (disposed || !branding) return
3962
+ etag = response.headers.get('etag') || `"${branding.revision}"`
3963
+ const key = brandingCacheKey()
3964
+ if (key) {
3965
+ try { localStorage.setItem(key, JSON.stringify(branding)) } catch {}
3966
+ }
3967
+ apply(branding)
3968
+ retryCount = 0
3969
+ } catch {
3970
+ if (!disposed && retryable && retryCount < 3) {
3971
+ const delay = [3_000, 10_000, 30_000][retryCount]
3972
+ retryCount += 1
3973
+ clearTimeout(retryTimer)
3974
+ retryTimer = setTimeout(() => void refresh(), delay)
3975
+ }
3976
+ }
3977
+ }
3978
+ void refresh()
3979
+ timer = setInterval(() => void refresh(), 5 * 60 * 1000)
3980
+ return cleanup
3981
+ }
3982
+
3983
+ function apply(ctx) {
3984
+ ctx.effect(() => installEnterpriseBranding(ctx), 'ANT enterprise branding synchronization')
3985
+ ctx.effect(() => {
3986
+ const runtime = ctx.locale
3987
+ localeRuntime = runtime
3988
+ localeTranslate = runtime.bind('ant.team')
3989
+ let disposed = false
3990
+ const removers = []
3991
+ void fetch(ANT_LOCALE_MESSAGES_PATH, { cache: 'no-store' }).then(async (response) => {
3992
+ if (!response.ok) throw new Error(`HTTP ${response.status}`)
3993
+ return response.json()
3994
+ }).then((catalogs) => {
3995
+ const catalogMetadata = catalogs?.locales
3996
+ const sourceMessages = catalogs?.messages
3997
+ if (disposed || !catalogMetadata?.en || !catalogMetadata?.zh || !sourceMessages) return
3998
+ localeMetadata = catalogMetadata
3999
+ const messagesFor = (id) => Object.fromEntries(Object.entries(sourceMessages)
4000
+ .map(([source, translations]) => [source, translations[id] ?? translations.en ?? source]))
4001
+ localeMessagePatterns = Object.keys(sourceMessages)
4002
+ .filter((key) => /\{[a-zA-Z][a-zA-Z0-9_]*\}/u.test(key))
4003
+ .sort((a, b) => b.length - a.length)
4004
+ .map(compileLocalePattern)
4005
+ removers.push(runtime.register('ant.team', {
4006
+ en: messagesFor('en'),
4007
+ zh: messagesFor('zh'),
4008
+ }))
4009
+ const registered = new Set(runtime.getLocale().locales.map((item) => item.id.toLowerCase()))
4010
+ for (const id of ANT_LOCALE_IDS) {
4011
+ const catalog = localeMetadata[id]
4012
+ if (!catalog) continue
4013
+ if (!registered.has(id.toLowerCase())) {
4014
+ removers.push(runtime.addLanguage({ id, label: catalog.label, fallback: 'en' }))
4015
+ registered.add(id.toLowerCase())
4016
+ }
4017
+ removers.push(runtime.register('ant.team', id, messagesFor(id)))
4018
+ }
4019
+ }).catch((error) => ctx.logger?.warn?.('ANT locale catalogs unavailable:', error?.message))
4020
+ return () => {
4021
+ disposed = true
4022
+ for (const remove of removers.reverse()) remove()
4023
+ if (localeRuntime === runtime) {
4024
+ localeRuntime = null
4025
+ localeMetadata = {}
4026
+ localeMessagePatterns = []
4027
+ localeTranslate = (key) => key
4028
+ }
4029
+ }
4030
+ }, 'ANT locale catalog registration')
4031
+ const remote = {
4032
+ credentials: ctx.remote.credentials,
4033
+ settings: ctx.remote.settings,
4034
+ pluginManager: ctx.remote.pluginManager,
4035
+ }
4036
+ const openAntSettings = () => ctx.layout.selectPanel(ANT_SETTINGS_PANEL_ID)
4037
+ const renderAntSettings = () => h(TeamServiceConfig, {
4038
+ remote,
4039
+ openInstalledPlugin: (name) => ctx.pluginNavigation.openBundle(name),
4040
+ })
4041
+ const renderAntPanel = () => h('section', { 'aria-label': 'ANT 团队设置', style: {
4042
+ height: '100%', overflowY: 'auto', boxSizing: 'border-box',
4043
+ padding: 'calc(var(--dsh-frame-top-clearance, 0px) + 20px) clamp(16px, 3vw, 36px) 48px',
4044
+ } }, h('div', { style: { maxWidth: 1120, margin: '0 auto' } }, renderAntSettings()))
4045
+ const renderAntSettingsShortcut = ({ close } = {}) => h('section', { style: {
4046
+ display: 'grid', gap: 10, width: '100%', maxWidth: 620,
4047
+ } },
4048
+ h('h2', { style: sectionTitleStyle }, 'ANT 团队设置'),
4049
+ h('p', { style: mutedTextStyle }, '团队连接、模型、协作与本机任务在左侧 ANT 页面中统一管理。'),
4050
+ h('button', { type: 'button', onClick: () => {
4051
+ close?.()
4052
+ openAntSettings()
4053
+ }, style: primaryButtonStyle }, '打开 ANT 设置'))
4054
+ ctx.slots.inject('main', () => ctx.slots.register({ name: 'main', key: ANT_SETTINGS_PANEL_ID }, renderAntPanel))
4055
+ ctx.slots.inject('sidebar.panellist', () => ctx.slots.register({
4056
+ name: 'sidebar.panellist', id: ANT_SETTINGS_PANEL_ID, order: 4, label: 'ANT',
4057
+ }, AntSettingsPanelIcon))
4058
+ ctx.slots.inject('main', () => ctx.slots.register({ name: 'main', key: 'ant-skills' },
4059
+ () => h(EnterpriseExtensionsPage, {
4060
+ remote,
4061
+ onBack: openAntSettings,
4062
+ openBundle: (name) => ctx.pluginNavigation.openBundle(name),
4063
+ })))
4064
+ ctx.slots.inject('sidebar.panellist', () => ctx.slots.register({
4065
+ name: 'sidebar.panellist', id: 'ant-skills', order: 5, label: '企业扩展',
4066
+ }, EnterpriseExtensionsPanelIcon))
4067
+ ctx.slots.inject('settings.section', () => ctx.slots.register({
4068
+ name: 'settings.section', id: ANT_SETTINGS_SECTION_ID, order: 40,
4069
+ label: `ANT (${ANT_BUNDLE_PACKAGE_NAME})`,
4070
+ }, renderAntSettingsShortcut))
4071
+ ctx.slots.inject('plugins.bundle.config', () => ctx.slots.register({
4072
+ name: 'plugins.bundle.config',
4073
+ key: ANT_BUNDLE_PACKAGE_NAME,
4074
+ inject: () => ({ remote }),
4075
+ }, ({ view, remote: injectedRemote }) => view === 'summary'
4076
+ ? h('p', null, 'ANT 团队服务入口。')
4077
+ : h(TeamServiceConfig, {
4078
+ remote: injectedRemote,
4079
+ openInstalledPlugin: (name) => ctx.pluginNavigation.openBundle(name),
4080
+ })))
4081
+ }
4082
+
4083
+ Object.assign(exports, { inject, apply })
4084
+ return module.exports
4085
+ },
4086
+ })