@ai-wendao/ant 0.4.1 → 0.4.4

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 CHANGED
@@ -160,6 +160,7 @@ window.__ModuleLoader__.load({
160
160
  const inject = ['slots', 'layout', 'pluginNavigation', 'remote', 'remote.credentials', 'remote.settings', 'remote.pluginManager']
161
161
 
162
162
  async function readLocalJsonResponse(response) {
163
+ if (response.status === 204) return null
163
164
  const contentType = response.headers?.get?.('content-type') || ''
164
165
  const isJson = /^(?:application|text)\/(?:[a-z0-9!#$&^_.+-]+\+)?json(?:\s*;|$)/iu.test(contentType.trim())
165
166
  if (contentType && !isJson) {
@@ -240,7 +241,6 @@ window.__ModuleLoader__.load({
240
241
  const [message, setMessage] = useState('')
241
242
  const [pluginAlerts, setPluginAlerts] = useState([])
242
243
  const [delegationRevision, setDelegationRevision] = useState(0)
243
- const [legacyOpen, setLegacyOpen] = useState(false)
244
244
  useEffect(() => {
245
245
  let disposed = false
246
246
  const revision = bindingRevision.current
@@ -315,6 +315,7 @@ window.__ModuleLoader__.load({
315
315
  const onConnectionChange = (url) => {
316
316
  bindingRevision.current += 1
317
317
  setBinding({ state: 'ready', url: url || null })
318
+ setDelegationRevision((value) => value + 1)
318
319
  if (url) {
319
320
  setServiceUrl(url)
320
321
  setDraft(url)
@@ -356,34 +357,30 @@ window.__ModuleLoader__.load({
356
357
  h(ModelSyncFooter, { remote, serviceUrl, bindingReady: binding.state === 'ready',
357
358
  onServiceUrlChange: setServiceUrl, onConnectionChange }),
358
359
  h(DelegationCards, { remote, revision: delegationRevision,
359
- openImSettings: () => openInstalledPlugin('@xmanrui/dsh-im'),
360
- openPrReview: () => { setLegacyOpen(true)
361
- window.document?.getElementById('ant-pr-review-settings')?.scrollIntoView({ behavior: 'smooth', block: 'start' }) },
362
- onGrantChanged: () => setDelegationRevision((value) => value + 1) }),
363
- h(DelegationSettings, { remote, revision: delegationRevision, open: legacyOpen, onOpenChange: setLegacyOpen,
364
- onChanged: () => setDelegationRevision((value) => value + 1) }))
360
+ openImSettings: () => openInstalledPlugin('@xmanrui/dsh-im') }))
365
361
  }
366
362
 
367
- function DelegationCards({ remote, revision, openImSettings, openPrReview, onGrantChanged }) {
363
+ function DelegationCards({ remote, revision, openImSettings }) {
368
364
  const [bots, setBots] = useState([])
369
365
  const [enrolled, setEnrolled] = useState([])
370
366
  const [groups, setGroups] = useState([])
371
367
  const [cards, setCards] = useState([])
372
- const [grants, setGrants] = useState([])
373
368
  const [tasks, setTasks] = useState([])
374
369
  const [executors, setExecutors] = useState([])
375
370
  const [defaults, setDefaults] = useState(null)
376
371
  const [localConcurrency, setLocalConcurrency] = useState(null)
377
- const [prReviewExecutor, setPrReviewExecutor] = useState('dsh')
372
+ const [repositoryCacheLimitGib, setRepositoryCacheLimitGib] = useState(10)
378
373
  const [botId, setBotId] = useState('')
379
374
  const [trustedOrigin, setTrustedOrigin] = useState('')
380
375
  const [bindingCode, setBindingCode] = useState('')
381
376
  const [conversationKind, setConversationKind] = useState('dm')
382
377
  const [groupId, setGroupId] = useState('')
378
+ const [chatGroupId, setChatGroupId] = useState('')
383
379
  const [title, setTitle] = useState('')
384
380
  const [intent, setIntent] = useState('')
385
381
  const [examples, setExamples] = useState('')
386
382
  const [taskPrompt, setTaskPrompt] = useState('')
383
+ const [runner, setRunner] = useState('dsh')
387
384
  const [parameters, setParameters] = useState([])
388
385
  const [giteaToken, setGiteaToken] = useState('')
389
386
  const [tokenConfigured, setTokenConfigured] = useState(false)
@@ -393,26 +390,40 @@ window.__ModuleLoader__.load({
393
390
  const [busy, setBusy] = useState(false)
394
391
  const [loading, setLoading] = useState(true)
395
392
  const [botLoadError, setBotLoadError] = useState(false)
393
+ const [loadFailures, setLoadFailures] = useState([])
396
394
  const [createOpen, setCreateOpen] = useState(false)
397
395
  const [message, setMessage] = useState('')
398
396
  const load = async () => {
399
397
  setLoading(true)
398
+ setMessage('')
400
399
  try {
401
- const paths = ['bots', 'enrolled-bots', 'groups', 'cards', 'settings', 'executors', 'local-settings', 'status', 'grants']
402
- const responses = await Promise.all(paths.map((path) => fetch(`/api/ant-teams/delegation/${path}`, { cache: 'no-store' })))
403
- const data = await Promise.all(responses.map(readLocalJsonResponse))
404
- if (!responses[3].ok) throw new Error(data[3]?.message || '暂时无法读取任务卡。')
405
- setBots(responses[0].ok ? data[0].bots || [] : [])
406
- setBotLoadError(!responses[0].ok)
407
- setEnrolled(responses[1].ok && Array.isArray(data[1]) ? data[1] : [])
408
- setGroups(responses[2].ok && Array.isArray(data[2]) ? data[2] : [])
409
- setCards(Array.isArray(data[3]) ? data[3] : [])
410
- setDefaults(responses[4].ok ? data[4] : null)
411
- setExecutors(responses[5].ok && Array.isArray(data[5]) ? data[5] : [])
412
- setLocalConcurrency(responses[6].ok ? data[6].max_concurrency : null)
413
- setPrReviewExecutor(responses[6].ok ? data[6].pr_review_executor || 'dsh' : 'dsh')
414
- setTasks(responses[7].ok && Array.isArray(data[7].items) ? data[7].items : [])
415
- setGrants(responses[8].ok && Array.isArray(data[8]) ? data[8] : [])
400
+ const paths = ['bots', 'enrolled-bots', 'groups', 'cards', 'settings', 'executors', 'local-settings', 'status']
401
+ const responses = await Promise.all(paths.map((path) =>
402
+ fetch(`/api/ant-teams/delegation/${path}`, { cache: 'no-store',
403
+ ...(path === 'enrolled-bots' ? { headers: { 'x-ant-include-unbound': 'true' } } : {}) })
404
+ .catch(() => null)))
405
+ const data = await Promise.all(responses.map((response) => response
406
+ ? readLocalJsonResponse(response).catch(() => null) : null))
407
+ const valid = [
408
+ (value) => Array.isArray(value?.bots),
409
+ Array.isArray, Array.isArray, Array.isArray,
410
+ (value) => value && typeof value === 'object' && !Array.isArray(value),
411
+ Array.isArray,
412
+ (value) => value && typeof value === 'object' && !Array.isArray(value),
413
+ (value) => Array.isArray(value?.items),
414
+ ]
415
+ const readable = responses.map((response, index) => Boolean(response?.ok && valid[index](data[index])))
416
+ setLoadFailures(paths.filter((path, index) => !readable[index]))
417
+ setBots(readable[0] ? data[0].bots : [])
418
+ setBotLoadError(!readable[0])
419
+ setEnrolled(readable[1] ? data[1] : [])
420
+ setGroups(readable[2] ? data[2] : [])
421
+ setCards(readable[3] ? data[3] : [])
422
+ setDefaults(readable[4] ? data[4] : null)
423
+ setExecutors(readable[5] ? data[5] : [])
424
+ setLocalConcurrency(readable[6] ? data[6].max_concurrency : null)
425
+ setRepositoryCacheLimitGib(readable[6] ? data[6].repository_cache_limit_gib ?? 10 : 10)
426
+ setTasks(readable[7] ? data[7].items : [])
416
427
  let credential = null
417
428
  try { credential = await remote?.credentials?.describe?.(['ANT_GITEA_API_TOKEN']) } catch {}
418
429
  setTokenConfigured(Boolean(credential?.ok && credential.value?.ANT_GITEA_API_TOKEN?.configured))
@@ -422,19 +433,63 @@ window.__ModuleLoader__.load({
422
433
  const selectedBot = bots.find((bot) => bot.bot_id === botId)
423
434
  const botConnected = Boolean(selectedBot?.available && selectedBot?.connected)
424
435
  const selectedEnrollment = enrolled.find((bot) => bot.bot_fingerprint === selectedBot?.fingerprint)
436
+ const selectedEnrollmentBound = selectedEnrollment?.device_bound_to_current === true
425
437
  const availableGroups = groups.filter((group) => group.bot_fingerprint === selectedBot?.fingerprint)
438
+ const selectedChatGroup = availableGroups.find((group) => group.group_id === chatGroupId)
426
439
  const activeCards = cards.filter((card) => !card.revoked_at && card.expires_at * 1000 > Date.now())
427
- const activeGrants = grants.filter((grant) => !grant.revoked_at && grant.expires_at * 1000 > Date.now())
440
+ const selectedGroupHasTasks = Boolean(selectedBot && chatGroupId && (
441
+ activeCards.some((card) => card.bot_fingerprint === selectedBot.fingerprint
442
+ && card.conversation_kind === 'group' && card.conversation_id === chatGroupId)))
428
443
  const connectedBots = bots.filter((bot) => bot.available && bot.connected)
429
- const enrolledCount = enrolled.filter((item) => connectedBots.some((bot) => bot.fingerprint === item.bot_fingerprint)).length
444
+ const authorizationLoadError = loadFailures.includes('cards')
445
+ const enrollmentLoadError = loadFailures.includes('enrolled-bots')
446
+ const enrolledCount = enrolled.filter((item) => item.device_bound_to_current
447
+ && connectedBots.some((bot) => bot.fingerprint === item.bot_fingerprint)).length
430
448
  const selectedTaskCount = activeCards.filter((card) => card.bot_fingerprint === selectedBot?.fingerprint).length
431
- + activeGrants.filter((grant) => grant.bot_fingerprint === selectedBot?.fingerprint).length
432
- const cardBlockReason = !botConnected || !selectedEnrollment ? '先在上方连接并启用机器人。'
433
- : conversationKind === 'group' && !groupId ? '请先在“更多设置”中选择目标群;若列表为空,让群成员先 @机器人,再刷新群列表。'
434
- : senderScope === 'allowlist' && !senderIds.trim() ? '请在“更多设置”中填写可请求的成员 ID。'
435
- : parameters.some((rule) => rule.kind === 'gitea_pr') && !tokenConfigured ? '请先在“更多设置”中保存本机 Gitea 只读令牌。'
449
+ const selectedRunnerNeedsPr = ['codex', 'claude-code'].includes(runner)
450
+ const codexAvailable = executors.some((item) => item.id === 'codex-readonly' && item.available)
451
+ const claudeCodeAvailable = executors.some((item) => item.id === 'claude-code' && item.available)
452
+ const nativePrUnavailableReason = executors.find((item) => item.reason)?.reason || null
453
+ const requesterSummary = senderScope === 'allowlist'
454
+ ? `仅指定成员:${senderIds.trim() || '尚未填写成员 ID'}`
455
+ : conversationKind === 'group' ? `群 ${groupId || '尚未选择'} 的所有成员` : '任何能私聊此机器人的人'
456
+ const resultRouteSummary = conversationKind === 'group' ? '回复到原群(群内可见)' : '回复到发起任务的私聊'
457
+ const cardBlockReason = enrollmentLoadError ? '暂时无法核对机器人是否已启用协作,请刷新状态后再试。'
458
+ : !botConnected || !selectedEnrollmentBound ? '先在上方把机器人绑定到这台 DSH。'
459
+ : conversationKind === 'group' && loadFailures.includes('groups') ? '暂时无法核对目标群,请刷新状态后再试。'
460
+ : conversationKind === 'group' && !groupId ? '请在“参数与授权范围”中选择目标群;若列表为空,让群成员先 @机器人,再刷新群列表。'
461
+ : senderScope === 'allowlist' && !senderIds.trim() ? '请在“参数与授权范围”中填写可请求成员的 IM ID。'
462
+ : parameters.some((rule) => rule.kind === 'gitea_pr') && !tokenConfigured ? '请先在“参数与授权范围”中保存本机 Gitea 只读令牌。'
463
+ : parameters.some((rule) => rule.kind === 'gitea_pr') && !selectedEnrollment?.gitea_origin
464
+ ? '请先登记这个机器人的可信 Gitea 地址。'
465
+ : parameters.some((rule) => rule.kind === 'gitea_pr')
466
+ && normalizeServiceUrl(trustedOrigin) !== selectedEnrollment?.gitea_origin
467
+ ? '请先保存机器人级可信 Gitea 地址;PR 参数将自动使用这个地址。'
468
+ : selectedRunnerNeedsPr && (parameters.length !== 1 || parameters[0].kind !== 'gitea_pr')
469
+ ? 'Codex 和 Claude Code 目前只支持单个 Gitea PR 审查任务。'
470
+ : selectedRunnerNeedsPr && !parameters[0].required
471
+ ? '本机代码审查的 Gitea PR 编号必须设为必填。'
472
+ : runner === 'codex' && !codexAvailable
473
+ ? '这台 DSH 尚未找到可用的 Codex CLI,请先安装或检查 DSH 的 PATH。'
474
+ : runner === 'claude-code' && !claudeCodeAvailable
475
+ ? '这台 DSH 尚未注册 Claude Code 子代理,请先在 DSH 中安装并启用它。'
436
476
  : ''
477
+ const loadNames = { bots: '机器人', 'enrolled-bots': '协作启用状态', groups: '群聊列表',
478
+ cards: '任务授权', settings: '团队默认值', executors: '本机执行器',
479
+ 'local-settings': '本机设置', status: '最近任务' }
437
480
  const updateParameter = (index, patch) => setParameters((current) => current.map((rule, i) => i === index ? { ...rule, ...patch } : rule))
481
+ const preparePrExample = () => {
482
+ setTitle('审查 Gitea PR 差异')
483
+ setIntent('同事希望查看指定 Gitea PR 的代码差异并获得审查意见。')
484
+ setExamples('请帮我审查 123 号 PR\n看看刚才提到的 PR 有什么风险')
485
+ setTaskPrompt('结合已核验 PR 的完整代码快照和差异,给出可定位的问题;没有足够上下文时说明局限,不修改代码。')
486
+ setParameters([{ name: 'pr_number', kind: 'gitea_pr', required: true,
487
+ description: '要审查的 PR 编号', min: '1', max: '', choices: '',
488
+ gitea_origin: selectedEnrollment?.gitea_origin || trustedOrigin || '', repository: '' }])
489
+ setRunner(codexAvailable ? 'codex' : claudeCodeAvailable ? 'claude-code' : 'dsh')
490
+ setCreateOpen(true)
491
+ window.document?.getElementById('ant-new-task')?.scrollIntoView({ behavior: 'smooth', block: 'start' })
492
+ }
438
493
  const saveGiteaToken = async () => {
439
494
  if (!giteaToken.trim()) return
440
495
  setBusy(true)
@@ -448,24 +503,32 @@ window.__ModuleLoader__.load({
448
503
  }
449
504
  const enrollBot = async () => {
450
505
  if (!selectedBot) return
506
+ const requestedOrigin = trustedOrigin
507
+ const origin = requestedOrigin?.trim() ? normalizeServiceUrl(requestedOrigin) : ''
508
+ if (requestedOrigin?.trim() && !origin) {
509
+ setMessage('请填写有效的 HTTPS Gitea 地址后再启用协作。')
510
+ return
511
+ }
451
512
  setBusy(true)
452
513
  try {
453
514
  const response = await fetch('/api/ant-teams/delegation/enrolled-bots', {
454
515
  method: 'POST', headers: { 'content-type': 'application/json' },
455
- body: JSON.stringify({ bot_id: selectedBot.bot_id, bot_fingerprint: selectedBot.fingerprint }),
516
+ body: JSON.stringify({ bot_id: selectedBot.bot_id, bot_fingerprint: selectedBot.fingerprint,
517
+ gitea_origin: origin }),
456
518
  })
457
519
  const result = await readLocalJsonResponse(response)
458
520
  if (!response.ok) throw new Error(result.message || '协作机器人启用失败。')
459
521
  await load()
460
- setMessage('协作机器人已启用。你可以创建任务卡;私聊时也能正常聊天。')
522
+ if (origin) setTrustedOrigin(origin)
523
+ setMessage('协作机器人已启用。你可以开放能力;私聊时也能正常聊天。')
461
524
  } catch (error) { setMessage(error.message) }
462
525
  finally { setBusy(false) }
463
526
  }
464
527
  const saveTrustedOrigin = async () => {
465
- if (!selectedBot || !selectedEnrollment) return
528
+ if (!selectedBot || !selectedEnrollmentBound) return
466
529
  const origin = normalizeServiceUrl(trustedOrigin)
467
530
  if (!origin) { setMessage('请填写有效的 HTTPS Gitea 地址。'); return }
468
- if (!window.confirm(`将这个机器人的可信 Gitea 地址设为 ${origin}?不匹配的旧版 PR 授权会被撤销,已有任务卡的 PR 参数也需重新核对。`)) return
531
+ if (!window.confirm(`将这个机器人的可信 Gitea 地址设为 ${origin}?已开放能力中的 PR 参数需要重新核对。`)) return
469
532
  setBusy(true)
470
533
  try {
471
534
  const response = await fetch('/api/ant-teams/delegation/enrolled-bots', {
@@ -480,7 +543,7 @@ window.__ModuleLoader__.load({
480
543
  finally { setBusy(false) }
481
544
  }
482
545
  const issueBindingCode = async () => {
483
- if (!selectedBot || !selectedEnrollment) return
546
+ if (!selectedBot || !selectedEnrollmentBound) return
484
547
  setBusy(true)
485
548
  try {
486
549
  const response = await fetch('/api/ant-teams/delegation/owner-challenge', {
@@ -494,53 +557,62 @@ window.__ModuleLoader__.load({
494
557
  } catch (error) { setMessage(error.message) }
495
558
  finally { setBusy(false) }
496
559
  }
497
- const saveConcurrency = async (event) => {
498
- event.preventDefault()
560
+ const saveGroupChat = async () => {
561
+ if (!selectedBot || !selectedEnrollmentBound || !chatGroupId.trim()) return
562
+ const enabled = !selectedChatGroup?.chat_enabled
563
+ if (!enabled && selectedGroupHasTasks) {
564
+ setMessage('这个群还有开放能力。请先停止这些能力,再关闭群聊。')
565
+ return
566
+ }
567
+ if (!window.confirm(enabled
568
+ ? selectedGroupHasTasks
569
+ ? '这个群当前因任务授权可以聊天。要在任务到期后仍允许普通聊天吗?聊天会使用团队模型额度。'
570
+ : '允许这个群与机器人自然聊天?群成员仍不能执行未开放的能力,聊天会使用团队模型额度。'
571
+ : '关闭这个群的普通聊天?已有能力不会自动撤销。')) return
499
572
  setBusy(true)
500
573
  try {
501
- const response = await fetch('/api/ant-teams/delegation/local-settings', {
574
+ const response = await fetch('/api/ant-teams/delegation/groups', {
502
575
  method: 'PUT', headers: { 'content-type': 'application/json' },
503
- body: JSON.stringify({ max_concurrency: localConcurrency === '' ? null : Number(localConcurrency) }),
576
+ body: JSON.stringify({ bot_id: selectedBot.bot_id,
577
+ bot_fingerprint: selectedBot.fingerprint, group_id: chatGroupId.trim(), enabled }),
504
578
  })
505
- const result = await readLocalJsonResponse(response)
506
- if (!response.ok) throw new Error(result.message || '并发设置保存失败。')
507
- setLocalConcurrency(result.max_concurrency)
508
- setMessage('本机并发设置已保存,稍后会应用于新任务。')
579
+ if (!response.ok) {
580
+ const result = await readLocalJsonResponse(response)
581
+ throw new Error(result.message || '群聊设置保存失败。')
582
+ }
583
+ await load()
584
+ setMessage(enabled ? '这个群现在可以与机器人聊天;可执行能力仍需逐项开放。' : '已关闭这个群的普通聊天。')
509
585
  } catch (error) { setMessage(error.message) }
510
586
  finally { setBusy(false) }
511
587
  }
512
- const savePrReviewExecutor = async (event) => {
588
+ const saveLocalProcessingSettings = async (event) => {
513
589
  event.preventDefault()
514
- if (prReviewExecutor !== 'dsh') {
515
- if (!executors.some((item) => item.id === prReviewExecutor && item.available)) {
516
- setMessage('所选执行器尚未在这台 DSH 启用。'); return
517
- }
518
- if (!window.confirm(`启用 ${prReviewExecutor} 的指定 PR 差异审查试用?这会应用于本机所有现有的指定 PR 授权。同事只能请求已授权的 PR,ANT 会固定审查内容和临时目录;但执行器仍沿用你本机的权限,可能读取或修改其他本机文件。结果会回复原私聊或群。`)) return
519
- }
520
590
  setBusy(true)
521
591
  try {
522
592
  const response = await fetch('/api/ant-teams/delegation/local-settings', {
523
593
  method: 'PUT', headers: { 'content-type': 'application/json' },
524
- body: JSON.stringify({ pr_review_executor: prReviewExecutor,
525
- accept_native_permissions: prReviewExecutor !== 'dsh' }),
594
+ body: JSON.stringify({
595
+ max_concurrency: localConcurrency === '' ? null : Number(localConcurrency),
596
+ repository_cache_limit_gib: Number(repositoryCacheLimitGib),
597
+ }),
526
598
  })
527
599
  const result = await readLocalJsonResponse(response)
528
- if (!response.ok) throw new Error(result.message || '审查执行方保存失败。')
529
- setPrReviewExecutor(result.pr_review_executor)
530
- setMessage(result.pr_review_executor === 'dsh' ? '已关闭本机执行器试用;新请求继续由受限 DSH 审查。'
531
- : `已启用 ${result.pr_review_executor} 的指定 PR 差异审查试用;请先用你自己的机器人验证。`)
600
+ if (!response.ok) throw new Error(result.message || '本机处理设置保存失败。')
601
+ setLocalConcurrency(result.max_concurrency)
602
+ setRepositoryCacheLimitGib(result.repository_cache_limit_gib)
603
+ setMessage('本机并发与仓库缓存设置已保存。')
532
604
  } catch (error) { setMessage(error.message) }
533
605
  finally { setBusy(false) }
534
606
  }
535
607
  const createCard = async (event) => {
536
608
  event.preventDefault()
537
- if (!selectedBot || !botConnected || !selectedEnrollment) { setMessage('请先连接并启用选中的协作机器人。'); return }
609
+ if (!selectedBot || !botConnected || !selectedEnrollmentBound) { setMessage('请先在这台 DSH 绑定选中的协作机器人。'); return }
538
610
  if (!title.trim() || !intent.trim() || !taskPrompt.trim()) {
539
- setMessage('请填写任务名称、什么请求属于这项任务,以及处理要求。'); return
611
+ setMessage('请填写能力名称、适用请求说明和处理要求。'); return
540
612
  }
541
613
  const bytes = (value) => new TextEncoder().encode(value).length
542
614
  if (bytes(title.trim()) > 100 || bytes(intent.trim()) > 1000 || bytes(taskPrompt.trim()) > 4000) {
543
- setMessage('任务名称、请求说明或处理要求过长,请缩短后再提交。'); return
615
+ setMessage('能力名称、请求说明或处理要求过长,请缩短后再提交。'); return
544
616
  }
545
617
  const exampleLines = examples.split('\n').map((item) => item.trim()).filter(Boolean)
546
618
  if (exampleLines.length > 8 || exampleLines.some((item) => bytes(item) > 500)) {
@@ -551,7 +623,7 @@ window.__ModuleLoader__.load({
551
623
  required: rule.required, min: rule.min === '' ? null : Number(rule.min),
552
624
  max: rule.max === '' ? null : Number(rule.max),
553
625
  choices: rule.kind === 'choice' ? rule.choices.split(/[,,\n]/u).map((item) => item.trim()).filter(Boolean) : null,
554
- gitea_origin: rule.kind === 'gitea_pr' ? normalizeServiceUrl(rule.gitea_origin) : null,
626
+ gitea_origin: rule.kind === 'gitea_pr' ? selectedEnrollment?.gitea_origin || null : null,
555
627
  repository: rule.kind === 'gitea_pr' ? rule.repository.trim().toLowerCase() : null }))
556
628
  if (normalized.some((rule) => !/^[A-Za-z][A-Za-z0-9_]{0,31}$/u.test(rule.name))) {
557
629
  setMessage('参数键请用英文字母开头,只能包含英文字母、数字和下划线;给同事看的中文问题可填在“参数说明”。'); return
@@ -586,50 +658,57 @@ window.__ModuleLoader__.load({
586
658
  if (normalized.some((rule) => rule.kind === 'gitea_pr' && !validRepository(rule.repository))) {
587
659
  setMessage('Gitea 仓库请填写“团队名/仓库名”,不要包含空格或多余路径。'); return
588
660
  }
661
+ if (['codex', 'claude-code'].includes(runner) && (normalized.length !== 1
662
+ || normalized[0].kind !== 'gitea_pr' || !normalized[0].required)) {
663
+ setMessage('Codex 和 Claude Code 目前需要一个必填的 Gitea PR 编号参数。'); return
664
+ }
665
+ if (runner === 'codex' && !codexAvailable) {
666
+ setMessage('这台 DSH 尚未找到可用的 Codex CLI。'); return
667
+ }
668
+ if (runner === 'claude-code' && !claudeCodeAvailable) {
669
+ setMessage('这台 DSH 尚未注册 Claude Code 子代理。'); return
670
+ }
589
671
  const scope = conversationKind === 'group' ? `群 ${groupId}` : '私聊'
590
- if (!window.confirm(`开启“${title}”后,${scope}中符合条件的人可请机器人执行这个仅用文字处理的任务。${conversationKind === 'group' ? '结果会公开回复原群。' : '结果回复请求人。'}请确认。`)) return
672
+ const resultDestination = conversationKind === 'group' ? '原群(群内可见)' : '发起任务的私聊'
673
+ const executionInfo = runner === 'codex'
674
+ ? 'ANT 会使用这台电脑已登录的 Codex,在已核验 PR Head 的临时完整代码快照中固定只读权限;会传入所有者要求、请求人原话和 PR 差异,不传 Gitea 令牌。'
675
+ : runner === 'claude-code'
676
+ ? 'ANT 会调用这台 DSH 已注册的 Claude Code 子代理,在已核验 PR Head 的临时完整代码快照中审查;会传入所有者要求、请求人原话和 PR 差异,不传 Gitea 令牌。它沿用 DSH 中 Claude Code 的本机权限设置;请确认该设置适合由获准成员请求审查。'
677
+ : '这项任务仅由受限 DSH 处理已提供的文字。'
678
+ if (!window.confirm(`开放“${title}”后,${requesterSummary}可在${scope}请求,有效期 ${days} 天;结果${resultDestination}。${executionInfo}请确认。`)) return
591
679
  setBusy(true)
592
680
  try {
593
681
  const response = await fetch('/api/ant-teams/delegation/cards', {
594
682
  method: 'POST', headers: { 'content-type': 'application/json' },
595
683
  body: JSON.stringify({ bot_id: selectedBot.bot_id, bot_fingerprint: selectedBot.fingerprint,
596
684
  title, intent, examples: exampleLines,
597
- parameters: normalized, task_prompt: taskPrompt, runner: 'dsh', workspace: null,
685
+ parameters: normalized, task_prompt: taskPrompt, runner, workspace: null,
598
686
  sender_scope: senderScope, sender_ids: senderScope === 'allowlist'
599
687
  ? senderIds.split(/[\s,,]+/u).filter(Boolean) : [], conversation_kind: conversationKind,
600
688
  ...(conversationKind === 'group' ? { conversation_id: groupId } : {}),
601
689
  expires_at: Math.floor(Date.now() / 1000) + Number(days) * 86400 }),
602
690
  })
603
691
  const result = await readLocalJsonResponse(response)
604
- if (!response.ok) throw new Error(result.message || '任务卡保存失败。')
605
- setTitle(''); setIntent(''); setExamples(''); setTaskPrompt(''); setParameters([])
692
+ if (!response.ok && runner === 'claude-code' && result.code === 'INVALID_REQUEST') {
693
+ throw new Error('当前团队服务端可能尚不支持 Claude Code 执行方。请管理员升级服务端后刷新重试。')
694
+ }
695
+ if (!response.ok) throw new Error(result.message || '能力保存失败。')
696
+ setTitle(''); setIntent(''); setExamples(''); setTaskPrompt(''); setParameters([]); setRunner('dsh')
606
697
  await load()
607
698
  setCreateOpen(false)
608
- setMessage('任务卡已启用。同事可自然地提出这类请求;参数不完整时机器人会追问。')
699
+ setMessage('能力已开放。同事可自然地提出这类请求;参数不完整时机器人会追问。')
609
700
  } catch (error) { setMessage(error.message) }
610
701
  finally { setBusy(false) }
611
702
  }
612
703
  const revokeCard = async (card) => {
613
- if (!window.confirm(`停止“${card.title}”的新请求?正在处理的任务无法撤销已经发生的读取。`)) return
704
+ if (!window.confirm(`停止开放“${card.title}”?正在处理的任务无法撤销已经发生的读取。`)) return
614
705
  setBusy(true)
615
706
  try {
616
707
  const response = await fetch('/api/ant-teams/delegation/cards', {
617
708
  method: 'DELETE', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ id: card.id }),
618
709
  })
619
- if (!response.ok) throw new Error('停止任务卡失败,请重试。')
620
- await load(); setMessage('任务卡已停止。')
621
- } catch (error) { setMessage(error.message) }
622
- finally { setBusy(false) }
623
- }
624
- const revokeGrant = async (grant) => {
625
- if (!window.confirm(`停止 ${grant.repository} PR #${grant.pr_number} 的新审查请求?正在处理的任务不会因此撤销。`)) return
626
- setBusy(true)
627
- try {
628
- const response = await fetch('/api/ant-teams/delegation/grants', {
629
- method: 'DELETE', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ id: grant.id }),
630
- })
631
- if (!response.ok) throw new Error('停止 PR 授权失败,请重试。')
632
- await load(); onGrantChanged?.(); setMessage('已停止这项 PR 授权;其他聊天和任务不受影响。')
710
+ if (!response.ok) throw new Error('停止能力失败,请重试。')
711
+ await load(); setMessage('能力已停止开放。')
633
712
  } catch (error) { setMessage(error.message) }
634
713
  finally { setBusy(false) }
635
714
  }
@@ -645,24 +724,32 @@ window.__ModuleLoader__.load({
645
724
  } catch (error) { setMessage(error.message) }
646
725
  finally { setBusy(false) }
647
726
  }
648
- return h('section', { style: panelStyle, 'aria-label': '协作机器人和可执行任务' },
649
- h('h3', { style: { margin: 0, fontSize: 16 } }, '协作机器人与任务'),
650
- h('p', { style: mutedTextStyle }, '同事可以像平常一样聊天。只有你开放的任务才会经过参数与权限检查;群里的任务结果公开回复原群。新建任务卡目前使用无本机工具的 DSH 文字处理。'),
651
- h('p', { style: mutedTextStyle }, '机器人用模型判断一句话是否属于某项任务,话题判断可能有误;请求人、群、参数类型和数值范围由 ANT 再次校验。敏感内容请缩小授权范围。'),
727
+ return h('section', { style: panelStyle, 'aria-label': '协作机器人与开放能力' },
728
+ h('h3', { style: { margin: 0, fontSize: 16 } }, '协作机器人'),
729
+ h('p', { style: mutedTextStyle }, '同事可以像平常一样和机器人聊天。DSH 负责理解与回答;只有准备执行你开放的能力时,ANT 才核对请求人、群、参数和权限。群里的任务结果会回复原群。'),
730
+ h('p', { role: 'status', style: mutedTextStyle }, '每项能力都单独设定执行方和请求范围。普通对话不会自动获得读取电脑、调用工具或访问其他群的权限。'),
731
+ loadFailures.length ? h('p', { role: 'status', style: mutedTextStyle },
732
+ `部分协作信息暂时无法读取:${loadFailures.map((path) => loadNames[path]).join('、')}。已读取的信息仍显示,请稍后刷新状态。`) : null,
652
733
  h('div', { style: { border: '1px solid var(--dsw-alias-border-l2)', borderRadius: 8, padding: 12,
653
734
  display: 'grid', gap: 8 } },
654
- h('strong', null, '开始使用'),
735
+ h('strong', null, '机器人和聊天范围'),
655
736
  h('span', { role: 'status', style: mutedTextStyle }, loading ? '正在读取机器人与任务状态…'
656
737
  : botLoadError ? '暂时无法读取机器人状态。请刷新后再试。'
657
738
  : connectedBots.length === 0 ? '尚未发现已连接的机器人。请先在 DSH-IM 中连接飞书机器人。'
658
739
  : selectedBot && !botConnected ? `“${selectedBot.name}”当前离线;请先在 DSH-IM 恢复连接。`
659
- : selectedBot && !selectedEnrollment ? `“${selectedBot.name}”已连接;请先启用协作。启用后,它仍能正常聊天。`
740
+ : enrollmentLoadError ? selectedBot
741
+ ? `“${selectedBot.name}”已连接;暂时无法确认协作是否已启用,请刷新状态。`
742
+ : '机器人已连接;协作启用状态暂未读取,请刷新状态。'
743
+ : selectedBot && !selectedEnrollmentBound ? selectedEnrollment
744
+ ? `“${selectedBot.name}”已连接;原协作配置尚未绑定到这台 DSH,请在本机重新启用。若原设备令牌曾被撤销,旧任务权限已关闭,绑定后需重新开放。`
745
+ : `“${selectedBot.name}”已连接;请先启用本机协作。启用后,它仍能正常聊天。`
660
746
  : enrolledCount === 0 ? '机器人已连接;请选择并启用协作。启用后,它仍能正常聊天。'
661
- : !selectedBot ? '已有协作机器人;请选择一台,查看它的任务并私聊自测。'
662
- : selectedTaskCount === 0 ? `“${selectedBot.name}”已启用协作;下一步开放一项任务。你也可以先私聊自测普通聊天。`
663
- : `“${selectedBot.name}”已启用协作 · ${selectedTaskCount} 项有效授权。可以私聊自测。`),
747
+ : !selectedBot ? '已有协作机器人;请选择一台,查看已开放的能力并私聊自测。'
748
+ : authorizationLoadError ? `“${selectedBot.name}”已启用协作;已开放任务暂未读取,请刷新状态。普通聊天仍可自测。`
749
+ : selectedTaskCount === 0 ? `“${selectedBot.name}”已启用协作;下一步开放一项能力。你也可以先私聊自测普通聊天。`
750
+ : `“${selectedBot.name}”已启用协作 · ${selectedTaskCount} 项能力已开放。可以私聊自测。`),
664
751
  bots.length ? h('label', null, '我的机器人', h('select', { value: botId,
665
- onChange: (event) => { setBotId(event.target.value); setGroupId(''); setBindingCode('');
752
+ onChange: (event) => { setBotId(event.target.value); setGroupId(''); setChatGroupId(''); setBindingCode('');
666
753
  setTrustedOrigin(enrolled.find((bot) => bot.bot_id === event.target.value)?.gitea_origin || '') }, style: inputStyle },
667
754
  h('option', { value: '' }, '请选择机器人'),
668
755
  ...bots.map((bot) => h('option', { key: bot.bot_id, value: bot.bot_id,
@@ -673,31 +760,44 @@ window.__ModuleLoader__.load({
673
760
  '若尚未安装 DSH-IM,请先到 DSH 的插件列表安装并连接机器人。') : null,
674
761
  selectedBot && !botConnected && connectedBots.length ? h('button', { type: 'button', onClick: openImSettings,
675
762
  style: secondaryButtonStyle }, '检查 DSH-IM 连接') : null,
676
- selectedBot && !selectedEnrollment ? h('button', { type: 'button', disabled: busy || !botConnected,
677
- onClick: () => void enrollBot(), style: secondaryButtonStyle }, '启用这个协作机器人') : null,
678
- selectedEnrollment && botConnected ? h('p', { style: mutedTextStyle },
679
- `自测:私聊“${selectedBot.name}”发送“你能做什么”;发起任务后可问“刚才的任务怎么样了”。群聊请先在目标群 @机器人,并在下方任务设置中启用该群。`) : null,
763
+ selectedBot && !selectedEnrollmentBound ? h('button', { type: 'button', disabled: busy || !botConnected || enrollmentLoadError,
764
+ onClick: () => void enrollBot(), style: secondaryButtonStyle },
765
+ selectedEnrollment ? '绑定原协作配置到这台 DSH' : '启用并绑定到这台 DSH') : null,
766
+ selectedEnrollmentBound && botConnected ? h('p', { style: mutedTextStyle },
767
+ `自测:私聊“${selectedBot.name}”发送“你能做什么”;发起任务后可问“刚才的任务怎么样了”。群聊请先在目标群 @机器人,再开放能力时选择该群。`) : null,
768
+ selectedEnrollmentBound && botConnected ? h('div', { style: { display: 'grid', gap: 8 } },
769
+ h('strong', null, '允许聊天的群'),
770
+ h('span', { style: mutedTextStyle }, '群成员可以正常聊天;是否能让机器人办事,由每项能力单独决定。若机器人尚未发现群,可以直接填群 ID。'),
771
+ h('select', { 'aria-label': '已记录的群', value: availableGroups.some((group) => group.group_id === chatGroupId) ? chatGroupId : '',
772
+ onChange: (event) => setChatGroupId(event.target.value), style: inputStyle },
773
+ h('option', { value: '' }, '从已记录的群中选择'),
774
+ ...availableGroups.map((group) => h('option', { key: group.group_id, value: group.group_id },
775
+ `${group.group_code} · ${group.chat_enabled ? '已允许聊天' : '未允许聊天'}`))),
776
+ h('input', { 'aria-label': '群 ID', value: chatGroupId, maxLength: 256,
777
+ onChange: (event) => setChatGroupId(event.target.value.trim()),
778
+ placeholder: '也可以手动填写群 ID', style: inputStyle }),
779
+ h('button', { type: 'button', disabled: busy || !chatGroupId.trim()
780
+ || (selectedChatGroup?.chat_enabled && selectedGroupHasTasks),
781
+ onClick: () => void saveGroupChat(), style: secondaryButtonStyle },
782
+ selectedChatGroup?.chat_enabled ? '关闭此群聊天'
783
+ : selectedGroupHasTasks ? '能力到期后仍允许聊天' : '允许此群聊天'),
784
+ selectedChatGroup?.chat_enabled && selectedGroupHasTasks ? h('span', { style: mutedTextStyle },
785
+ '本群还有开放能力;关闭聊天前请先停止这些能力。') : null) : null,
680
786
  h('div', { style: { display: 'flex', gap: 8, flexWrap: 'wrap' } },
681
787
  h('button', { type: 'button', onClick: () => { setCreateOpen(true)
682
788
  window.document?.getElementById('ant-new-task')?.scrollIntoView({ behavior: 'smooth', block: 'start' }) },
683
- style: primaryButtonStyle }, '开放文字任务'),
684
- h('button', { type: 'button', onClick: openPrReview, style: secondaryButtonStyle }, '开放指定 PR 审查'),
789
+ style: primaryButtonStyle }, '开放新能力'),
790
+ h('button', { type: 'button', onClick: preparePrExample, style: secondaryButtonStyle }, '使用 PR 差异审查示例'),
685
791
  h('button', { type: 'button', onClick: () => void load().catch((error) => setMessage(error.message)),
686
792
  style: secondaryButtonStyle }, '刷新状态'))),
687
- h('h4', { style: { marginBottom: 0 } }, `我开放的任务 · ${activeCards.length + activeGrants.length}`),
793
+ h('h4', { style: { marginBottom: 0 } }, `我开放的能力 · ${authorizationLoadError ? '暂未读取' : activeCards.length}`),
688
794
  ...activeCards.map((card) => h('div', { key: card.id, style: { display: 'flex', gap: 12,
689
795
  alignItems: 'center', justifyContent: 'space-between', flexWrap: 'wrap', borderTop: '1px solid var(--dsw-alias-border-l2)', paddingTop: 8 } },
690
- h('span', { style: { flex: '1 1 280px', minWidth: 0, overflowWrap: 'anywhere' } }, `${card.title} · ${bots.find((bot) => bot.fingerprint === card.bot_fingerprint)?.name || '机器人'} · ${card.conversation_kind === 'group' ? `群 ${groups.find((group) => group.group_id === card.conversation_id)?.group_code || card.conversation_id}` : '私聊'} · ${card.sender_scope === 'allowlist' ? '仅指定成员可请求' : card.conversation_kind === 'group' ? '群成员可请求' : '可私聊者可请求'} · 结果回复原${card.conversation_kind === 'group' ? '群' : '私聊'} · DSH 文字处理 · ${new Date(card.expires_at * 1000).toLocaleString('zh-CN')} 到期`),
796
+ h('span', { style: { flex: '1 1 280px', minWidth: 0, overflowWrap: 'anywhere' } }, `${card.title} · ${bots.find((bot) => bot.fingerprint === card.bot_fingerprint)?.name || '机器人'} · ${card.conversation_kind === 'group' ? `群 ${groups.find((group) => group.group_id === card.conversation_id)?.group_code || card.conversation_id}` : '私聊'} · ${card.sender_scope === 'allowlist' ? '仅指定成员可请求' : card.conversation_kind === 'group' ? '群成员可请求' : '可私聊者可请求'} · 结果回复原${card.conversation_kind === 'group' ? '群' : '私聊'} · ${card.runner === 'codex' ? 'Codex 只读 PR 完整快照审查' : card.runner === 'claude-code' ? 'Claude Code PR 完整快照审查试用' : 'DSH 文字处理'} · ${new Date(card.expires_at * 1000).toLocaleString('zh-CN')} 到期`),
691
797
  h('button', { type: 'button', disabled: busy, onClick: () => void revokeCard(card), style: secondaryButtonStyle }, '停止'))),
692
- ...activeGrants.map((grant) => h('div', { key: grant.id, style: { display: 'flex', gap: 12,
693
- alignItems: 'center', justifyContent: 'space-between', flexWrap: 'wrap', borderTop: '1px solid var(--dsw-alias-border-l2)', paddingTop: 8 } },
694
- h('span', { style: { flex: '1 1 280px', minWidth: 0, overflowWrap: 'anywhere' } }, `指定 PR 差异审查 · ${grant.repository} #${grant.pr_number} · ${bots.find((bot) => bot.fingerprint === grant.bot_fingerprint)?.name || '机器人'} · ${grant.sender_scope === 'allowlist' ? '仅指定成员可请求' : grant.conversation_kind === 'group' ? '群成员可请求' : '可私聊者可请求'} · 结果回复原${grant.conversation_kind === 'group' ? '群' : '私聊'} · ${prReviewExecutor === 'dsh' ? 'DSH' : prReviewExecutor + ' 本机试用'} · ${new Date(grant.expires_at * 1000).toLocaleString('zh-CN')} 到期`),
695
- h('div', { style: { display: 'flex', gap: 8, flexWrap: 'wrap' } },
696
- h('button', { type: 'button', onClick: openPrReview, style: secondaryButtonStyle }, '查看设置'),
697
- h('button', { type: 'button', disabled: busy, onClick: () => void revokeGrant(grant),
698
- style: secondaryButtonStyle }, '停止')))),
699
- activeCards.length + activeGrants.length === 0 ? h('p', { style: mutedTextStyle },
700
- '还没有开放任务。先选机器人,再用上方按钮创建文字任务或指定 PR 审查。') : null,
798
+ activeCards.length === 0 ? h('p', { style: mutedTextStyle },
799
+ authorizationLoadError ? '暂时无法确认已开放的能力,请刷新状态后再试。'
800
+ : '还没有开放能力。先选机器人,再开放一项能力;PR 审查只是可选示例。') : null,
701
801
  h('h4', { style: { marginBottom: 0 } }, '最近任务'),
702
802
  ...(tasks.filter((task) => task.task_id).length ? tasks.filter((task) => task.task_id)
703
803
  .map((task) => h('div', { key: task.task_id, style: { display: 'flex', gap: 12, alignItems: 'center',
@@ -707,28 +807,49 @@ window.__ModuleLoader__.load({
707
807
  }[task.status] || task.status)}`),
708
808
  ['card_task', 'legacy_pr_task'].includes(task.kind) && ['pending', 'running'].includes(task.status) ? h('button', { type: 'button', disabled: busy,
709
809
  onClick: () => void cancelTask(task), style: secondaryButtonStyle }, '取消任务') : null))
710
- : [h('p', { key: 'none', style: mutedTextStyle }, '暂无任务。')]),
810
+ : [h('p', { key: 'none', style: mutedTextStyle }, loadFailures.includes('status')
811
+ ? '任务记录暂时无法读取,请刷新状态。' : '暂无任务。')]),
711
812
  h('details', { id: 'ant-new-task', open: createOpen,
712
813
  onToggle: (event) => setCreateOpen(event.currentTarget.open),
713
814
  style: { border: '1px solid var(--dsw-alias-border-l2)', borderRadius: 8, padding: 12 } },
714
- h('summary', { style: { cursor: 'pointer', fontWeight: 600 } }, '新建文字任务'),
815
+ h('summary', { style: { cursor: 'pointer', fontWeight: 600 } }, '开放一项能力'),
715
816
  h('form', { onSubmit: createCard, style: { display: 'grid', gap: 9, maxWidth: 760 } },
716
817
  h('p', { style: mutedTextStyle }, selectedBot
717
- ? `当前机器人:${selectedBot.name}${selectedEnrollment ? ' · 协作已启用' : ' · 请先在上方启用协作'}`
818
+ ? `当前机器人:${selectedBot.name}${selectedEnrollmentBound ? ' · 已绑定此设备' : ' · 请先绑定到此设备'}`
718
819
  : '请先在上方选择机器人并启用协作。'),
719
- selectedEnrollment ? h('p', { style: mutedTextStyle }, '此机器人已由 ANT 接收协作消息;普通聊天由受限 DSH 对话处理。') : null,
820
+ selectedEnrollmentBound ? h('p', { style: mutedTextStyle },
821
+ '机器人及其任务能力只在这台 DSH 设备接收和执行;同一账号的其他设备不会继承本机授权。') : null,
822
+ selectedEnrollment && !selectedEnrollmentBound ? h('p', { style: mutedTextStyle },
823
+ '这是尚未绑定到设备的机器人。请在要继续使用它的电脑重新启用;Gitea 地址和配置记录会保留。若旧设备访问曾被撤销,原任务权限不会恢复,需要重新开放。') : null,
720
824
  selectedBot && conversationKind === 'group' && !selectedBot.history_available ? h('p', { role: 'status', style: mutedTextStyle },
721
825
  '这个机器人当前不能读取平台群历史;群聊只能参考实际送达的消息和本机近期记录。请检查 DSH-IM 权限。') : null,
722
- h('label', null, '任务名称', h('input', { required: true, maxLength: 100, value: title,
826
+ h('label', null, '能力名称', h('input', { required: true, maxLength: 100, value: title,
723
827
  onChange: (event) => setTitle(event.target.value), placeholder: '例如:总结项目进度', style: inputStyle })),
724
- h('label', null, '什么请求属于这项任务', h('textarea', { required: true, maxLength: 1000, rows: 2, value: intent,
828
+ h('label', null, '什么请求属于这项能力', h('textarea', { required: true, maxLength: 1000, rows: 2, value: intent,
725
829
  onChange: (event) => setIntent(event.target.value), placeholder: '例如:把群里讨论的本周进展整理成摘要', style: inputStyle })),
726
830
  h('label', null, '同事可能怎么说(每行一句,可选)', h('textarea', { rows: 2, value: examples,
727
831
  onChange: (event) => setExamples(event.target.value), placeholder: '帮我总结一下刚才的讨论', style: inputStyle })),
728
832
  h('label', null, '处理要求', h('textarea', { required: true, maxLength: 4000, rows: 3, value: taskPrompt,
729
833
  onChange: (event) => setTaskPrompt(event.target.value), placeholder: '只使用当前会话可见的内容,列出结论和待办', style: inputStyle })),
834
+ h('label', null, '执行方', h('select', { value: runner,
835
+ onChange: (event) => setRunner(event.target.value), style: inputStyle },
836
+ h('option', { value: 'dsh' }, 'DSH · 已提供文字'),
837
+ h('option', { value: 'codex',
838
+ disabled: !codexAvailable }, 'Codex · 单个 Gitea PR 完整快照,只读'),
839
+ h('option', { value: 'claude-code', disabled: !claudeCodeAvailable },
840
+ 'Claude Code · 单个 Gitea PR 完整快照试用'))),
841
+ nativePrUnavailableReason ? h('p', { role: 'status', style: mutedTextStyle },
842
+ `${nativePrUnavailableReason},已禁用 Codex/Claude Code 完整快照选项;可选择 DSH 差异审查。`) : null,
843
+ runner === 'codex' ? h('p', { role: 'status', style: mutedTextStyle },
844
+ 'Codex 使用这台电脑的登录账号及其用量;ANT 为每项能力维护仓库缓存,每次审查创建固定到 PR Head 的临时代码快照。Codex 只能只读查看该快照;不会收到 Gitea 令牌。Git LFS 实际文件不会下载。') : null,
845
+ runner === 'claude-code' ? h('p', { role: 'status', style: mutedTextStyle },
846
+ 'Claude Code 通过 DSH 已注册的子代理运行,可查看本次 PR 的临时代码快照。ANT 不会传 Gitea 令牌;Claude Code 沿用 DSH 提供方的本机权限,不具备 Codex 路径相同的固定只读隔离。Git LFS 实际文件不会下载。') : null,
847
+ selectedRunnerNeedsPr ? h('p', { role: 'status', style: mutedTextStyle },
848
+ '本机 PR 执行方需要 Gitea granular token 的只读权限 read:repository 和 read:user;read:user 仅用于这台 DSH 获取 Git HTTPS 登录名。') : null,
849
+ h('p', { role: 'status', style: mutedTextStyle },
850
+ `开放后:${requesterSummary}可请求 · 有效期 ${days} 天 · ${resultRouteSummary}`),
730
851
  h('details', { style: { border: '1px solid var(--dsw-alias-border-l2)', borderRadius: 8, padding: 10 } },
731
- h('summary', { style: { cursor: 'pointer' } }, '更多设置:参数、群聊与请求人'),
852
+ h('summary', { style: { cursor: 'pointer' } }, '参数与授权范围'),
732
853
  h('div', null, h('strong', null, '需要从请求中确认的参数'),
733
854
  h('p', { style: mutedTextStyle }, '可不添加参数。参数键使用英文,给同事看的中文问题填在参数说明;需要指定 PR 时选“Gitea PR 编号”,系统会核对它是否存在。自由文本留在本机,服务端只核对长度和摘要。')),
734
855
  ...parameters.map((rule, index) => h('div', { key: index, style: { display: 'flex', flexWrap: 'wrap', gap: 8,
@@ -750,8 +871,8 @@ window.__ModuleLoader__.load({
750
871
  onChange: (event) => updateParameter(index, { max: event.target.value }), placeholder: '最大值', style: { ...inputStyle, width: 120 } }) : null,
751
872
  rule.kind === 'choice' ? h('input', { 'aria-label': '可选值', value: rule.choices,
752
873
  onChange: (event) => updateParameter(index, { choices: event.target.value }), placeholder: '用逗号分隔选项', style: { ...inputStyle, flex: '1 1 250px' } }) : null,
753
- rule.kind === 'gitea_pr' ? h('input', { 'aria-label': '可信 Gitea 地址', type: 'url', value: rule.gitea_origin,
754
- onChange: (event) => updateParameter(index, { gitea_origin: event.target.value }), placeholder: 'https://git.example.com', style: { ...inputStyle, flex: '1 1 220px' } }) : null,
874
+ rule.kind === 'gitea_pr' ? h('span', { style: mutedTextStyle },
875
+ `使用机器人的可信 Gitea 地址:${selectedEnrollment?.gitea_origin || trustedOrigin || '请在下方登记一次'}`) : null,
755
876
  rule.kind === 'gitea_pr' ? h('input', { 'aria-label': 'Gitea 仓库', value: rule.repository,
756
877
  onChange: (event) => updateParameter(index, { repository: event.target.value }), placeholder: '团队/仓库', style: { ...inputStyle, flex: '1 1 180px' } }) : null,
757
878
  h('button', { type: 'button', style: secondaryButtonStyle,
@@ -759,12 +880,13 @@ window.__ModuleLoader__.load({
759
880
  h('button', { type: 'button', disabled: parameters.length >= 12, style: secondaryButtonStyle,
760
881
  onClick: () => setParameters((current) => [...current, { name: '', kind: 'text', required: true,
761
882
  description: '', min: '', max: '', choices: '', gitea_origin: '', repository: '' }]) }, '添加参数'),
762
- parameters.some((rule) => rule.kind === 'gitea_pr') && selectedEnrollment ? h('div', { style: { display: 'flex', gap: 8, flexWrap: 'wrap' } },
883
+ parameters.some((rule) => rule.kind === 'gitea_pr') ? h('div', { style: { display: 'flex', gap: 8, flexWrap: 'wrap' } },
763
884
  h('input', { 'aria-label': '这个机器人的可信 Gitea 地址', type: 'url', value: trustedOrigin,
764
885
  onChange: (event) => setTrustedOrigin(event.target.value), placeholder: '可信 Gitea 地址',
765
886
  style: { ...inputStyle, flex: '1 1 260px' } }),
766
- h('button', { type: 'button', disabled: busy || !trustedOrigin.trim(),
767
- onClick: () => void saveTrustedOrigin(), style: secondaryButtonStyle }, '保存可信地址')) : null,
887
+ h('button', { type: 'button', disabled: busy || !trustedOrigin.trim() || !selectedBot,
888
+ onClick: () => void (selectedEnrollmentBound ? saveTrustedOrigin() : enrollBot()), style: secondaryButtonStyle },
889
+ selectedEnrollmentBound ? '保存可信地址' : '绑定到这台 DSH 并保存地址')) : null,
768
890
  parameters.some((rule) => rule.kind === 'gitea_pr') ? h('div', { style: { display: 'flex', gap: 8, flexWrap: 'wrap' } },
769
891
  h('input', { 'aria-label': '只读 Gitea 访问令牌', type: 'password', autoComplete: 'off', value: giteaToken,
770
892
  onChange: (event) => setGiteaToken(event.target.value), placeholder: tokenConfigured ? '本机已保存 Gitea 令牌' : '先保存只读 Gitea 令牌',
@@ -772,7 +894,7 @@ window.__ModuleLoader__.load({
772
894
  h('button', { type: 'button', disabled: busy || !giteaToken.trim(),
773
895
  onClick: () => void saveGiteaToken(), style: secondaryButtonStyle }, '保存令牌')) : null,
774
896
  parameters.some((rule) => rule.kind === 'gitea_pr') ? h('p', { style: mutedTextStyle },
775
- '执行时会用这台 DSH 保存的只读令牌向你登记的可信 Gitea 地址读取 PR;标题和差异会交给当前团队模型处理。') : null,
897
+ '令牌只保存在这台 DSH,用于读取 PR,不会提交到 ANT 服务端或交给执行方。') : null,
776
898
  h('label', null, '使用场景', h('select', { value: conversationKind,
777
899
  onChange: (event) => { setConversationKind(event.target.value); setGroupId('') }, style: inputStyle },
778
900
  h('option', { value: 'dm' }, '私聊'), h('option', { value: 'group' }, '指定群聊'))),
@@ -783,7 +905,7 @@ window.__ModuleLoader__.load({
783
905
  `识别码 ${group.group_code} · ${group.group_id}`)))) : null,
784
906
  conversationKind === 'group' ? h('button', { type: 'button', disabled: busy,
785
907
  onClick: () => void load().catch((error) => setMessage(error.message)), style: secondaryButtonStyle }, '刷新群列表') : null,
786
- conversationKind === 'group' && selectedEnrollment ? h('div', { style: { display: 'flex', gap: 8, alignItems: 'center', flexWrap: 'wrap' } },
908
+ conversationKind === 'group' && selectedEnrollmentBound ? h('div', { style: { display: 'flex', gap: 8, alignItems: 'center', flexWrap: 'wrap' } },
787
909
  h('span', { style: mutedTextStyle }, selectedEnrollment.owner_bound ? '已绑定你的飞书身份,可在群内批准任务' : '群内批准前需绑定你的飞书身份'),
788
910
  h('button', { type: 'button', disabled: busy, onClick: () => void issueBindingCode(), style: secondaryButtonStyle },
789
911
  selectedEnrollment.owner_bound ? '重新获取绑定码' : '获取身份绑定码')) : null,
@@ -799,312 +921,29 @@ window.__ModuleLoader__.load({
799
921
  h('option', { value: 1 }, '1 天'), h('option', { value: 7 }, '7 天'), h('option', { value: 30 }, '30 天')))),
800
922
  cardBlockReason ? h('p', { role: 'status', style: mutedTextStyle }, cardBlockReason) : null,
801
923
  h('button', { disabled: busy || Boolean(cardBlockReason),
802
- style: primaryButtonStyle }, '开启这项任务'))),
924
+ style: primaryButtonStyle }, '保存并开放能力'))),
803
925
  h('details', { style: { border: '1px solid var(--dsw-alias-border-l2)', borderRadius: 8, padding: 12 } },
804
- h('summary', { style: { cursor: 'pointer', fontWeight: 600 } }, '本机与指定 PR 审查设置'),
805
- h('p', { style: mutedTextStyle }, '本机并发影响新任务;下方的 Codex/Claude Code 试用仅影响“指定 PR 差异审查授权”,不影响文字任务。'),
926
+ h('summary', { style: { cursor: 'pointer', fontWeight: 600 } }, '本机处理设置'),
927
+ h('p', { style: mutedTextStyle }, '本机并发上限只影响这台电脑接收的新任务;PR 仓库缓存上限按这台 DSH 的长期仓库缓存总量计算,不包括任务临时工作目录。'),
806
928
  h('div', { style: { display: 'flex', gap: 8, flexWrap: 'wrap', alignItems: 'center' } },
807
- h('span', { style: mutedTextStyle }, `团队默认:先看 ${defaults?.context_messages ?? 10} 条前文、最多翻阅 ${defaults?.history_max_records ?? 100} 条平台记录、同时处理 ${defaults?.max_concurrency ?? 3} 项任务。`),
929
+ h('span', { style: mutedTextStyle }, loadFailures.includes('settings') ? '团队默认值暂未读取。'
930
+ : `团队默认:先看 ${defaults?.context_messages ?? 10} 条前文、最多翻阅 ${defaults?.history_max_records ?? 100} 条平台记录、同时处理 ${defaults?.max_concurrency ?? 3} 项任务。`),
808
931
  h('button', { type: 'button', onClick: () => void load().catch((error) => setMessage(error.message)), style: secondaryButtonStyle }, '刷新')),
809
- h('form', { onSubmit: saveConcurrency, style: { display: 'flex', gap: 8, flexWrap: 'wrap', alignItems: 'end' } },
932
+ loadFailures.includes('local-settings') ? h('p', { role: 'status', style: mutedTextStyle },
933
+ '本机处理设置暂未读取;请刷新后重试。')
934
+ : h('form', { onSubmit: saveLocalProcessingSettings, style: { display: 'flex', gap: 8, flexWrap: 'wrap', alignItems: 'end' } },
810
935
  h('label', null, '这台电脑最多同时处理',
811
936
  h('select', { value: localConcurrency == null ? '' : String(localConcurrency),
812
937
  onChange: (event) => setLocalConcurrency(event.target.value), style: inputStyle },
813
938
  h('option', { value: '' }, '跟随团队默认'),
814
939
  ...Array.from({ length: 8 }, (_, index) => h('option', { key: index + 1, value: index + 1 }, `${index + 1} 项任务`)))),
815
- h('button', { disabled: busy, style: secondaryButtonStyle }, '保存本机并发')),
816
- h('p', { style: mutedTextStyle }, `DSH 官方执行器:${executors.map((item) => `${item.title}${item.available ? '已接入 DSH' : '本机未启用'}`).join('、') || '暂未读取到'}。通用任务卡仍只使用受限 DSH;Codex/Claude Code 仅可在下方为已授权的指定 PR 审查手动开启试用。`),
817
- h('form', { id: 'ant-pr-review-executor-form', onSubmit: savePrReviewExecutor,
818
- style: { display: 'flex', gap: 8, flexWrap: 'wrap', alignItems: 'end' } },
819
- h('label', null, '指定 PR 差异审查使用',
820
- h('select', { id: 'ant-pr-review-executor', value: prReviewExecutor,
821
- onChange: (event) => setPrReviewExecutor(event.target.value), style: inputStyle },
822
- h('option', { value: 'dsh' }, 'DSH 受限文字审查(默认)'),
823
- ...[['codex', 'Codex'], ['claude-code', 'Claude Code']].map(([id, title]) => {
824
- const available = executors.some((item) => item.id === id && item.available)
825
- return h('option', { key: id, value: id, disabled: !available },
826
- `${title}${available ? ' · 本机权限试用' : ' · 未启用或未读取到'}`)
827
- }))),
828
- h('button', { disabled: busy, style: secondaryButtonStyle }, '保存审查执行方')),
829
- prReviewExecutor !== 'dsh' ? h('p', { role: 'status', style: mutedTextStyle },
830
- '选择本机执行器试用后,它沿用你在 Codex/Claude Code 中已有的权限;ANT 固定 PR 和启动参数,但不能保证执行器只读。') : null),
831
- message ? h('p', { role: 'status', style: mutedTextStyle }, message) : null)
832
- }
833
-
834
- function DelegationSettings({ remote, revision, onChanged, open, onOpenChange }) {
835
- const [bots, setBots] = useState([])
836
- const [enrolledBots, setEnrolledBots] = useState([])
837
- const [groups, setGroups] = useState([])
838
- const [grants, setGrants] = useState([])
839
- const [tasks, setTasks] = useState([])
840
- const [teamReady, setTeamReady] = useState(false)
841
- const [botId, setBotId] = useState('')
842
- const [conversationKind, setConversationKind] = useState('dm')
843
- const [groupId, setGroupId] = useState('')
844
- const [bindingCode, setBindingCode] = useState('')
845
- const [groupReady, setGroupReady] = useState(false)
846
- const [groupError, setGroupError] = useState('')
847
- const [origin, setOrigin] = useState('')
848
- const [repository, setRepository] = useState('')
849
- const [prNumber, setPrNumber] = useState('')
850
- const [senderScope, setSenderScope] = useState('any')
851
- const [senderIds, setSenderIds] = useState('')
852
- const [days, setDays] = useState(7)
853
- const [token, setToken] = useState('')
854
- const [tokenReady, setTokenReady] = useState(false)
855
- const [busy, setBusy] = useState(false)
856
- const [message, setMessage] = useState('')
857
- const refresh = async () => {
858
- const [botResponse, grantResponse, credential, statusResponse, enrolledResponse, groupResponse] = await Promise.all([
859
- fetch('/api/ant-teams/delegation/bots', { cache: 'no-store' }),
860
- fetch('/api/ant-teams/delegation/grants', { cache: 'no-store' }),
861
- remote?.credentials?.describe?.(['ANT_GITEA_API_TOKEN']),
862
- fetch('/api/ant-teams/delegation/status', { cache: 'no-store' }),
863
- fetch('/api/ant-teams/delegation/enrolled-bots', { cache: 'no-store' }),
864
- fetch('/api/ant-teams/delegation/groups', { cache: 'no-store' }),
865
- ])
866
- const botData = await readLocalJsonResponse(botResponse)
867
- const grantData = await readLocalJsonResponse(grantResponse)
868
- const statusData = await readLocalJsonResponse(statusResponse)
869
- const enrolledData = await readLocalJsonResponse(enrolledResponse)
870
- const groupData = await readLocalJsonResponse(groupResponse)
871
- if (!grantResponse.ok) { setTeamReady(false); throw new Error(grantData.message || '请先连接 ANT 团队。') }
872
- setTeamReady(true)
873
- setBots(botResponse.ok && Array.isArray(botData.bots) ? botData.bots : [])
874
- setGroupReady(enrolledResponse.ok && groupResponse.ok)
875
- setGroupError(enrolledResponse.ok && groupResponse.ok ? ''
876
- : enrolledResponse.status === 426 || groupResponse.status === 426
877
- ? '团队服务端版本不支持旧版 PR 群聊设置,请联系管理员升级。'
878
- : enrolledData?.message || groupData?.message || '暂时无法读取群聊设置,请稍后刷新。')
879
- setEnrolledBots(enrolledResponse.ok && Array.isArray(enrolledData) ? enrolledData : [])
880
- setGroups(groupResponse.ok && Array.isArray(groupData) ? groupData : [])
881
- setGrants(Array.isArray(grantData) ? grantData : [])
882
- setTasks(statusResponse.ok && Array.isArray(statusData.items) ? statusData.items : [])
883
- setTokenReady(Boolean(credential?.ok && credential.value?.ANT_GITEA_API_TOKEN?.configured))
884
- if (!botResponse.ok) setMessage(botData.message || '请先配置 DSH-IM 飞书机器人。')
885
- else if (!statusResponse.ok) setMessage(statusData.message || '本机任务记录暂时无法读取。')
886
- }
887
- useEffect(() => { void refresh().catch((error) => { setTeamReady(false); setMessage(error.message) }) }, [remote, revision])
888
- const saveToken = async (event) => {
889
- event.preventDefault()
890
- if (!token.trim()) return
891
- setBusy(true)
892
- try {
893
- const result = await remote.credentials.set('ANT_GITEA_API_TOKEN', token.trim())
894
- if (!result?.ok) throw new Error('DSH 无法安全保存 Gitea 访问令牌。')
895
- setToken('')
896
- setTokenReady(true)
897
- setMessage('Gitea 访问令牌已保存在这台 DSH。')
898
- } catch (error) { setMessage(error.message) }
899
- finally { setBusy(false) }
900
- }
901
- const create = async (event) => {
902
- event.preventDefault()
903
- const bot = bots.find((item) => item.bot_id === botId && item.available && item.connected)
904
- if (!teamReady || !bot || !tokenReady) { setMessage('请先连接 ANT 团队,选择可用的专用飞书机器人,并保存 Gitea 访问令牌。'); return }
905
- if (!groupReady || !selectedEnrolled) {
906
- setMessage('请先为这个专用机器人启用协作收件,并固定可信 Gitea 地址。')
907
- return
908
- }
909
- if (conversationKind === 'group' && !groups.some((item) => item.bot_fingerprint === bot.fingerprint && item.group_id === groupId)) {
910
- setMessage('请先让群成员在目标群 @ 机器人一次,然后选择待启用群。')
911
- return
912
- }
913
- if (normalizeServiceUrl(origin) !== selectedEnrollment.gitea_origin) {
914
- setMessage('当前地址与机器人已登记的可信 Gitea 地址不同。请先点击“更新可信地址”,或恢复原地址。')
915
- return
916
- }
917
- const trustedOrigin = selectedEnrollment.gitea_origin
918
- if (!window.confirm(conversationKind === 'group'
919
- ? `确认允许所选群的成员请求 ${trustedOrigin} 上 ${repository} PR #${prNumber} 的差异审查?执行方按上方本机设置运行,结果将公开回复原群/原话题,直到你撤销或授权到期。目前没有每日请求次数上限。`
920
- : `开启后,此飞书机器人由 ANT 接收消息并继续处理普通聊天;只有你授权的 PR 才能被请求审查。Gitea 令牌会发送到 ${origin},请核对地址。目前没有每日请求次数上限。请确认这是专用协作机器人。`)) return
921
- setBusy(true)
922
- try {
923
- const response = await fetch('/api/ant-teams/delegation/grants', {
924
- method: 'POST', headers: { 'content-type': 'application/json' },
925
- body: JSON.stringify({ bot_id: bot.bot_id, bot_fingerprint: bot.fingerprint,
926
- gitea_origin: trustedOrigin, repository, pr_number: Number(prNumber), sender_scope: senderScope,
927
- sender_ids: senderScope === 'allowlist' ? senderIds.split(/[\s,,]+/u).filter(Boolean) : [],
928
- conversation_kind: conversationKind,
929
- ...(conversationKind === 'group' ? { conversation_id: groupId } : {}),
930
- expires_at: Math.floor(Date.now() / 1000) + Number(days) * 86400 }),
931
- })
932
- const result = await readLocalJsonResponse(response)
933
- if (!response.ok) throw new Error(result.message || '委托授权未能创建。')
934
- setPrNumber('')
935
- setMessage(conversationKind === 'group'
936
- ? '本群已启用。在群里 @机器人发送“审查 PR 编号”可试一次;结果会公开回复原群/原话题。'
937
- : '委托已保存;机器人连接后可私聊发送“审查 PR 编号”试一次,以核对 Gitea 令牌和实际回复。')
938
- await refresh()
939
- onChanged?.()
940
- } catch (error) { setMessage(error.message) }
941
- finally { setBusy(false) }
942
- }
943
- const enrollBot = async () => {
944
- const bot = bots.find((item) => item.bot_id === botId && item.available && item.connected)
945
- if (!bot || !groupReady) { setMessage('请先选择可用机器人,并确认团队服务端已支持群聊委托。'); return }
946
- const trustedOrigin = normalizeServiceUrl(origin)
947
- if (!trustedOrigin) { setMessage('请先填写有效的 Gitea 服务地址(HTTPS,或本机测试地址)。'); return }
948
- if (!window.confirm('启用后,ANT 会接收这个机器人的消息并继续处理普通聊天;DSH-IM 原有会话桥不再单独回复。只有你开放的任务才可执行。更换机器人账号或可信 Gitea 地址时,不匹配的旧授权会撤销。')) return
949
- setBusy(true)
950
- try {
951
- const response = await fetch('/api/ant-teams/delegation/enrolled-bots', {
952
- method: 'POST', headers: { 'content-type': 'application/json' },
953
- body: JSON.stringify({ bot_id: bot.bot_id, bot_fingerprint: bot.fingerprint,
954
- gitea_origin: trustedOrigin }),
955
- })
956
- if (!response.ok) {
957
- const result = await readLocalJsonResponse(response)
958
- throw new Error(result.message || '无法启用机器人。')
959
- }
960
- setOrigin(trustedOrigin)
961
- setMessage('协作机器人已启用,私聊可以正常对话。要开放任务,请先创建授权;要在群里使用,请让群成员先 @它一次。')
962
- await refresh()
963
- onChanged?.()
964
- } catch (error) { setMessage(error.message) }
965
- finally { setBusy(false) }
966
- }
967
- const stopBot = async () => {
968
- const bot = enrolledBots.find((item) => item.bot_id === botId)
969
- if (!bot || !window.confirm('停止 ANT 接收这个机器人的协作消息,并撤销全部委托授权?ANT 处理的普通聊天也会停止;如需恢复 DSH-IM 原有聊天,还要在 DSH-IM 中切回普通模式。')) return
970
- setBusy(true)
971
- try {
972
- const response = await fetch('/api/ant-teams/delegation/enrolled-bots', {
973
- method: 'DELETE', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ bot_id: bot.bot_id }),
974
- })
975
- if (!response.ok) throw new Error('停止机器人失败,请重试。')
976
- setMessage('ANT 已停止接收这个机器人的消息并撤销任务授权。若要恢复 DSH-IM 原有聊天,请到 DSH-IM 切回普通模式。')
977
- setBindingCode('')
978
- await refresh()
979
- onChanged?.()
980
- } catch (error) { setMessage(error.message) }
981
- finally { setBusy(false) }
982
- }
983
- const issueBindingCode = async () => {
984
- const bot = bots.find((item) => item.bot_id === botId && item.available && item.connected)
985
- if (!bot || !enrolledBots.some((item) => item.bot_fingerprint === bot.fingerprint)) return
986
- setBusy(true)
987
- try {
988
- const response = await fetch('/api/ant-teams/delegation/owner-challenge', {
989
- method: 'POST', headers: { 'content-type': 'application/json' },
990
- body: JSON.stringify({ bot_id: bot.bot_id, bot_fingerprint: bot.fingerprint }),
991
- })
992
- const result = await readLocalJsonResponse(response)
993
- if (!response.ok) throw new Error(result.message || '无法生成绑定码。')
994
- setBindingCode(result.code)
995
- setMessage('绑定码 5 分钟有效。私聊发送后,点击下方“刷新状态”查看绑定结果。')
996
- } catch (error) { setMessage(error.message) }
997
- finally { setBusy(false) }
998
- }
999
- const revoke = async (grant) => {
1000
- if (!window.confirm(`停止授权 ${grant.repository} 的 PR #${grant.pr_number}?`)) return
1001
- setBusy(true)
1002
- try {
1003
- const response = await fetch('/api/ant-teams/delegation/grants', {
1004
- method: 'DELETE', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ id: grant.id }),
1005
- })
1006
- if (!response.ok) throw new Error('停止授权失败,请重试。')
1007
- setMessage('已停止这项 PR 授权;机器人其他聊天和任务不受影响。')
1008
- await refresh()
1009
- onChanged?.()
1010
- } catch (error) { setMessage(error.message) }
1011
- finally { setBusy(false) }
1012
- }
1013
- const active = grants.filter((grant) => !grant.revoked_at && grant.expires_at * 1000 > Date.now())
1014
- const selectedBot = bots.find((bot) => bot.bot_id === botId)
1015
- const selectedEnrollment = enrolledBots.find((item) => item.bot_fingerprint === selectedBot?.fingerprint)
1016
- const selectedEnrolled = Boolean(selectedEnrollment)
1017
- const botGroups = groups.filter((item) => item.bot_fingerprint === selectedBot?.fingerprint)
1018
- return h('details', { id: 'ant-pr-review-settings', open,
1019
- onToggle: (event) => onOpenChange?.(event.currentTarget.open),
1020
- style: panelStyle, 'aria-label': '指定 PR 差异审查授权' },
1021
- h('summary', { style: { cursor: 'pointer', fontWeight: 600 } }, '指定 PR 差异审查授权'),
1022
- h('p', { style: mutedTextStyle }, '为指定仓库和 PR 编号开放审查。已有授权继续有效;文字任务请在上方创建。'),
1023
- h('p', { style: mutedTextStyle }, '这里管理谁能请求指定 PR;执行方在上方“本机与审查设置”选择。PR 标题和差异会交给所选执行方;ANT 不会主动传入 Gitea 令牌,但本机执行器仍沿用它已有的文件权限。'),
1024
- h('form', { onSubmit: saveToken, style: { display: 'flex', flexWrap: 'wrap', gap: 8 } },
1025
- h('label', { style: { width: '100%', fontSize: 13 } }, `Gitea 访问令牌(仅保存在本机 DSH)${tokenReady ? ' · 已配置' : ''}`),
1026
- h('input', { type: 'password', autoComplete: 'off', value: token, onChange: (event) => setToken(event.target.value),
1027
- placeholder: '只读访问令牌', style: { ...inputStyle, flex: '1 1 260px' } }),
1028
- h('button', { type: 'submit', disabled: busy || !token.trim(), style: secondaryButtonStyle }, '保存令牌')),
1029
- h('form', { onSubmit: create, style: { display: 'grid', gap: 9, maxWidth: 640 } },
1030
- h('label', { htmlFor: 'ant-delegation-bot' }, '专用飞书机器人'),
1031
- h('select', { id: 'ant-delegation-bot', required: true, value: botId,
1032
- onChange: (event) => { setBotId(event.target.value); setGroupId(''); setBindingCode('');
1033
- setOrigin(enrolledBots.find((item) => item.bot_id === event.target.value)?.gitea_origin || '') }, style: inputStyle },
1034
- h('option', { value: '' }, '选择已连接的机器人'),
1035
- ...bots.filter((bot) => bot.available && bot.connected).map((bot) => h('option', { key: bot.bot_id, value: bot.bot_id }, bot.name))),
1036
- h('label', { htmlFor: 'ant-delegation-origin' }, '可信 Gitea 服务地址'),
1037
- h('input', { id: 'ant-delegation-origin', type: 'url', required: true, value: origin,
1038
- onChange: (event) => setOrigin(event.target.value), placeholder: 'https://git.example.com', style: inputStyle }),
1039
- groupReady ? h('div', { style: { display: 'flex', flexWrap: 'wrap', gap: 8, alignItems: 'center' } },
1040
- h('span', { style: mutedTextStyle }, selectedEnrolled
1041
- ? `${selectedEnrollment.owner_bound ? '飞书身份已绑定,可在群内批准' : '协作收件已启用,群内批准需先绑定身份'} · 可信 Gitea:${selectedEnrollment.gitea_origin}`
1042
- : '协作机器人尚未启用'),
1043
- !selectedEnrolled ? h('button', { type: 'button', disabled: busy || !botId,
1044
- onClick: () => void enrollBot(), style: secondaryButtonStyle }, '启用协作机器人') : null,
1045
- selectedEnrolled ? h('button', { type: 'button', disabled: busy,
1046
- onClick: () => void enrollBot(), style: secondaryButtonStyle }, '更新可信地址') : null,
1047
- selectedEnrolled ? h('button', { type: 'button', disabled: busy,
1048
- onClick: () => void issueBindingCode(), style: secondaryButtonStyle },
1049
- selectedEnrollment.owner_bound ? '重新绑定飞书身份' : '绑定我的飞书身份') : null,
1050
- selectedEnrolled ? h('button', { type: 'button', disabled: busy,
1051
- onClick: () => void stopBot(), style: secondaryButtonStyle }, '停止接收并撤销授权') : null) :
1052
- h('p', { style: mutedTextStyle }, groupError),
1053
- bindingCode && selectedEnrolled ? h('p', { role: 'status', style: mutedTextStyle },
1054
- `请你本人私聊这个机器人发送“绑定身份 ${bindingCode}”;5 分钟内有效,不要把码发在群里。绑定后可在群里 @它发送“在本群启用 <完整 PR 链接> 审查”,再按提示确认。`) : null,
1055
- h('label', { htmlFor: 'ant-delegation-kind' }, '授权给谁使用'),
1056
- h('select', { id: 'ant-delegation-kind', value: conversationKind,
1057
- onChange: (event) => { setConversationKind(event.target.value); setGroupId('') }, style: inputStyle },
1058
- h('option', { value: 'dm' }, '私聊这个机器人'),
1059
- groupReady ? h('option', { value: 'group' }, '仅所选飞书群') : null),
1060
- conversationKind === 'group' ? h('p', { style: mutedTextStyle },
1061
- '让群成员先在目标群 @机器人一次,然后刷新列表。向群成员核对机器人回复的识别码;启用后,该群成员都能看到审查结果。') : null,
1062
- conversationKind === 'group' ? h('div', { style: { display: 'flex', gap: 8 } },
1063
- h('select', { 'aria-label': '待启用群', required: true, value: groupId,
1064
- onChange: (event) => setGroupId(event.target.value), style: { ...inputStyle, flex: 1 } },
1065
- h('option', { value: '' }, '选择待启用群'),
1066
- ...botGroups.map((group) => h('option', { key: group.group_id, value: group.group_id },
1067
- `识别码 ${group.group_code} · ${new Date(group.last_seen_at * 1000).toLocaleString('zh-CN')} · ${group.group_id}${group.active_grants ? ' · 已有授权' : ' · 待启用'}`))),
1068
- h('button', { type: 'button', disabled: busy, onClick: () => void refresh().catch((error) => setMessage(error.message)),
1069
- style: secondaryButtonStyle }, '刷新群列表')) : null,
1070
- h('label', { htmlFor: 'ant-delegation-repository' }, '仓库'),
1071
- h('input', { id: 'ant-delegation-repository', required: true, value: repository,
1072
- onChange: (event) => setRepository(event.target.value), placeholder: '团队名/仓库名', style: inputStyle }),
1073
- h('label', { htmlFor: 'ant-delegation-pr' }, '允许审查的 PR 编号'),
1074
- h('input', { id: 'ant-delegation-pr', type: 'number', min: 1, required: true, value: prNumber,
1075
- onChange: (event) => setPrNumber(event.target.value), style: inputStyle }),
1076
- h('label', { htmlFor: 'ant-delegation-audience' }, '谁可以请求'),
1077
- h('select', { id: 'ant-delegation-audience', value: senderScope,
1078
- onChange: (event) => setSenderScope(event.target.value), style: inputStyle },
1079
- h('option', { value: 'any' }, conversationKind === 'group' ? '所选群的所有成员' : '任何能私聊这个专用机器人的人'),
1080
- h('option', { value: 'allowlist' }, '仅指定飞书用户 ID')),
1081
- senderScope === 'allowlist' ? h('input', { 'aria-label': '飞书用户 ID', required: true, value: senderIds,
1082
- onChange: (event) => setSenderIds(event.target.value), placeholder: '多个 ID 用逗号分隔', style: inputStyle }) : null,
1083
- h('label', { htmlFor: 'ant-delegation-days' }, '有效期'),
1084
- h('select', { id: 'ant-delegation-days', value: days, onChange: (event) => setDays(Number(event.target.value)), style: inputStyle },
1085
- h('option', { value: 1 }, '1 天'), h('option', { value: 7 }, '7 天'), h('option', { value: 30 }, '30 天')),
1086
- conversationKind === 'group' ? h('p', { style: mutedTextStyle },
1087
- '请确认该 PR 的标题、差异和审查结果可以向整个群公开;“指定发送者”只限制谁能发起,不会把结果改成私聊。目前没有每日请求次数上限。')
1088
- : senderScope === 'any' ? h('p', { style: mutedTextStyle },
1089
- 'PR 审查结果会回复给发信人;请确认该 PR 可以向这些人披露。') : null,
1090
- h('button', { type: 'submit', disabled: busy || !teamReady || !tokenReady || !selectedEnrolled ||
1091
- (conversationKind === 'group' && !groupId), style: primaryButtonStyle }, '开启这项委托')),
1092
- h('h4', { style: { marginBottom: 0 } }, `当前有效授权 · ${active.length}`),
1093
- ...active.map((grant) => h('div', { key: grant.id, style: { display: 'flex', justifyContent: 'space-between', gap: 12,
1094
- alignItems: 'center', borderTop: '1px solid var(--dsw-alias-border-l2)', paddingTop: 10 } },
1095
- h('span', null, `${grant.repository} · PR #${grant.pr_number} · ${grant.conversation_kind === 'group'
1096
- ? `群 ${grant.conversation_id}(${grant.sender_scope === 'any' ? '全群' : '指定发送者'})`
1097
- : (grant.sender_scope === 'any' ? '任何私聊者' : '指定发送者')} · ${new Date(grant.expires_at * 1000).toLocaleString('zh-CN')} 到期`),
1098
- h('button', { type: 'button', disabled: busy, onClick: () => void revoke(grant), style: secondaryButtonStyle }, '停止授权'))),
1099
- h('div', { style: { display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 8 } },
1100
- h('h4', { style: { margin: 0 } }, '最近任务'),
1101
- h('button', { type: 'button', disabled: busy, onClick: () => void refresh().catch((error) => { setTeamReady(false); setMessage(error.message) }),
1102
- style: secondaryButtonStyle }, '刷新状态')),
1103
- ...(tasks.length ? tasks.map((task, index) => h('p', { key: `${task.created_at}-${index}`, style: mutedTextStyle },
1104
- `${task.created_at ? new Date(task.created_at).toLocaleString('zh-CN') + ' · ' : ''}${task.repository || '请求'}${task.pr_number ? ` · PR #${task.pr_number}` : ''} · ${task.outcome === 'canceled' ? '已取消' : task.outcome === 'failed' ? '未完成' : ({
1105
- pending: '排队中', running: '处理中', reply_pending: '待回复', reply_attempted: '回复状态待核对,请查看飞书原会话',
1106
- done: '已回复',
1107
- }[task.status] || task.status)}`)) : [h('p', { style: mutedTextStyle }, '暂无任务记录。')]),
940
+ h('label', null, '这台电脑 PR 仓库缓存上限(GiB)',
941
+ h('input', { type: 'number', min: 1, max: 100, step: 1, required: true,
942
+ value: repositoryCacheLimitGib,
943
+ onChange: (event) => setRepositoryCacheLimitGib(event.target.value), style: inputStyle }),
944
+ h('span', { style: mutedTextStyle }, '默认 10 GiB,范围 1–100 GiB,按长期仓库文件逻辑大小计算(不含临时工作区和文件系统分配开销)。日常不会淘汰仍启用能力的缓存;停用或到期能力会在刷新时回收。单次拉取若实际越界,为恢复预算会清理这项能力的仓库缓存(旧 PR 可重新下载)。')),
945
+ h('button', { disabled: busy, style: secondaryButtonStyle }, '保存本机处理设置')),
946
+ h('p', { style: mutedTextStyle }, `本机可用执行方:${executors.map((item) => `${item.title}${item.available ? '(可用)' : `(${item.reason || '未启用或未找到'})`}`).join('、') || '暂未读取到'}。可用选项会出现在对应能力的执行方设置中。`)),
1108
947
  message ? h('p', { role: 'status', style: mutedTextStyle }, message) : null)
1109
948
  }
1110
949