JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.
Python
fix(cron): disable Xiaoyi push target without api_id
NickFuryXXX4e9b98d19f84
diff --git a/jiuwenswarm/channels/web/frontend/package.json b/jiuwenswarm/channels/web/frontend/package.jsonindex 3434cd10b9..8364420bd3 100644--- a/jiuwenswarm/channels/web/frontend/package.json+++ b/jiuwenswarm/channels/web/frontend/package.json@@ -12,6 +12,7 @@"test:openai-account-model-state": "tsc src/components/ConfigPanel/openaiAccountModelState.ts --target ES2020 --module ES2020 --moduleResolution Bundler --rootDir src --outDir node_modules/.cache/openai-account-model-state --skipLibCheck && node --test tests/openaiAccountModelState.test.mjs","test:tool-result-lifecycle": "tsc src/stores/toolResultLifecycle.ts --target ES2020 --module ES2020 --moduleResolution Bundler --rootDir src --outDir node_modules/.cache/tool-result-lifecycle --skipLibCheck --noEmitOnError && node --test tests/toolResultLifecycle.test.mjs","test:create-conversation-session": "tsc src/multi-session/state/createConversationSession.ts --target ES2020 --module ES2020 --moduleResolution Bundler --rootDir src --outDir node_modules/.cache/create-conversation-session --skipLibCheck --noEmitOnError && node --test tests/createConversationSession.test.mjs",+ "test:xiaoyi-cron-target": "tsc src/components/CronPanel/xiaoyiCronTarget.ts --target ES2020 --module ES2020 --moduleResolution Bundler --rootDir src --outDir node_modules/.cache/xiaoyi-cron-target --skipLibCheck --noEmitOnError && node --test tests/xiaoyiCronTarget.test.mjs","lint": "eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 0","preview": "vite preview"},diff --git a/jiuwenswarm/channels/web/frontend/src/components/ChannelsPanel/index.tsx b/jiuwenswarm/channels/web/frontend/src/components/ChannelsPanel/index.tsxindex a590a50e9d..c0e7576ec3 100644--- a/jiuwenswarm/channels/web/frontend/src/components/ChannelsPanel/index.tsx+++ b/jiuwenswarm/channels/web/frontend/src/components/ChannelsPanel/index.tsx@@ -1,6 +1,6 @@import { useCallback, useEffect, useMemo, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';-import { ChevronRight, Plus, Trash2 } from 'lucide-react';+import { ChevronRight, Plus, Trash2, X } from 'lucide-react';import i18n from '../../i18n';import { webRequest } from '../../services/webClient';import { AvatarPermEditor } from './AvatarPermEditor';@@ -957,6 +957,7 @@ export function ChannelsPanel({ isConnected }: ChannelsPanelProps) {const [xiaoyiSaving, setXiaoyiSaving] = useState(false);const [xiaoyiSaveError, setXiaoyiSaveError] = useState<string | null>(null);const [xiaoyiSuccess, setXiaoyiSuccess] = useState<string | null>(null);+ const [xiaoyiApiIdHintDismissed, setXiaoyiApiIdHintDismissed] = useState(false);const [dingtalkConfig, setDingtalkConfig] = useState<DingTalkConfig>(DEFAULT_DINGTALK_CONF);const [dingtalkDraft, setDingtalkDraft] = useState<DingTalkDraft>(draftFromDingtalkConfig(DEFAULT_DINGTALK_CONF));const [dingtalkVisibleFields, setDingtalkVisibleFields] = useState<Record<string, boolean>>({});@@ -1473,6 +1474,10 @@ export function ChannelsPanel({ isConnected }: ChannelsPanelProps) {setXiaoyiDraft((prev) => ({ ...prev, [key]: value }));setXiaoyiSaveError(null);setXiaoyiSuccess(null);+ // 填入 api_id 后重置关闭状态,清空时警告横幅可再次出现+ if (key === 'api_id' && String(value ?? '').trim()) {+ setXiaoyiApiIdHintDismissed(false);+ }};const handleCancelXiaoyiConfig = () => {@@ -2066,15 +2071,36 @@ export function ChannelsPanel({ isConnected }: ChannelsPanelProps) {</div>);- const renderXiaoyiConfigEditor = () => (- <table className="w-full text-sm">- <tbody>- {(['enabled', 'enable_streaming', 'ak', 'sk', 'agent_id', 'api_id'] as const).map((field) =>- renderXiaoyiField(xiaoyiDraft, field),- )}- </tbody>- </table>- );+ const renderXiaoyiConfigEditor = () => {+ // 仅在启用且未填 api_id 时显示警告横幅;填入后直接消失,不切换成灰色说明条+ const showApiIdHint =+ xiaoyiDraft.enabled && !xiaoyiDraft.api_id.trim() && !xiaoyiApiIdHintDismissed;+ return (+ <>+ {showApiIdHint ? (+ <div className="mb-3 flex items-start gap-2 rounded-md border border-warn/30 bg-warn-subtle px-3 py-2 text-xs text-warn">+ <p className="min-w-0 flex-1">{t('channels.placeholders.xiaoyiApiIdRequiredForCron')}</p>+ <button+ type="button"+ onClick={() => setXiaoyiApiIdHintDismissed(true)}+ className="inline-flex h-5 w-5 shrink-0 items-center justify-center rounded text-current/70 hover:bg-secondary hover:text-current"+ aria-label={t('common.close')}+ title={t('common.close')}+ >+ <X className="h-3.5 w-3.5" />+ </button>+ </div>+ ) : null}+ <table className="w-full text-sm">+ <tbody>+ {(['enabled', 'enable_streaming', 'ak', 'sk', 'agent_id', 'api_id'] as const).map((field) =>+ renderXiaoyiField(xiaoyiDraft, field),+ )}+ </tbody>+ </table>+ </>+ );+ };const configErrorNotice = useMemo(() => {return Array.from(new Set(diff --git a/jiuwenswarm/channels/web/frontend/src/components/CronPanel/index.tsx b/jiuwenswarm/channels/web/frontend/src/components/CronPanel/index.tsxindex 16be0843de..d06f146cda 100644--- a/jiuwenswarm/channels/web/frontend/src/components/CronPanel/index.tsx+++ b/jiuwenswarm/channels/web/frontend/src/components/CronPanel/index.tsx@@ -15,6 +15,7 @@ import ConfirmDialog from './ConfirmDialog';import CronTaskDrawer, { jobToForm, templateToForm, isDefaultLikeProject, type CronTaskFormValue } from './CronTaskDrawer';import { useClickOutside } from './useClickOutside';import SimpleSelect from './SimpleSelect';+import { hasXiaoyiPushApiId, isCronTargetOptionDisabled } from './xiaoyiCronTarget';import emptyIllustration from '../../assets/cron-empty.svg';// 任务列表分页:每页条数可选项(默认 20),纯前端本地分页——后端 cron.job.list 目前@@ -228,6 +229,8 @@ export default function CronPanel({ sessionId, onCreateViaChat, onSelectSessionconst [jobs, setJobs] = useState<CronTaskUI[]>([]);const [projects, setProjects] = useState<ProjectInfo[]>([]);const [enabledChannels, setEnabledChannels] = useState<Set<string>>(new Set());+ // 小艺推送依赖 api_id;频道已注册但未配 api_id 时仍应置灰(Issue #2497)+ const [xiaoyiPushReady, setXiaoyiPushReady] = useState(false);const [loading, setLoading] = useState(true);const [error, setError] = useState<string | null>(null);const [success, setSuccess] = useState<string | null>(null);@@ -337,7 +340,7 @@ export default function CronPanel({ sessionId, onCreateViaChat, onSelectSession}}, []);- // 沿用旧 CronPanel 的做法:按已启用的推送频道决定"推送频道"下拉里哪些选项可选+ // 按已启用频道决定推送下拉可选项;小艺额外要求 api_id 已配置(Issue #2497)const loadChannels = useCallback(async () => {try {const payload = await webRequest<{ channels?: unknown[] }>('channel.get');@@ -354,12 +357,26 @@ export default function CronPanel({ sessionId, onCreateViaChat, onSelectSessionsetEnabledChannels(enabled);} catch {// 忽略错误,保持空集合(下拉里全部选项禁用,用户仍可看到但选不了,不阻塞其他功能)+ setEnabledChannels(new Set());+ }++ try {+ const xiaoyiPayload = await webRequest<{ config?: unknown }>('channel.xiaoyi.get_conf');+ setXiaoyiPushReady(hasXiaoyiPushApiId(xiaoyiPayload?.config));+ } catch {+ // 拉不到小艺配置时保守置为不可用,避免无 api_id 仍可选+ setXiaoyiPushReady(false);}}, []);const targetOptions = useMemo(- () => SELECTABLE_TARGET_KEYS.map((id) => ({ value: id, label: t(`cron.targets.${id}`), disabled: !enabledChannels.has(id) })),- [enabledChannels, t],+ () =>+ SELECTABLE_TARGET_KEYS.map((id) => ({+ value: id,+ label: t(`cron.targets.${id}`),+ disabled: isCronTargetOptionDisabled(id, enabledChannels, xiaoyiPushReady),+ })),+ [enabledChannels, t, xiaoyiPushReady],);useEffect(() => {@@ -641,6 +658,8 @@ export default function CronPanel({ sessionId, onCreateViaChat, onSelectSession// 抽屉打开瞬间主动重拉一次项目列表:CronPanel 的 projects 只在挂载时拉取一次,// 停留页面期间新建的项目不会自动同步进来(bug003),这里保证每次打开抽屉都是最新数据void loadProjects();+ // 同步刷新推送频道可用性(含小艺 api_id),避免刚改完频道配置仍用旧置灰状态+ void loadChannels();setDrawer({ mode: 'template', initial: templateToForm(tpl, t(tpl.titleKey), t(tpl.descriptionKey)) });}@@ -730,6 +749,7 @@ export default function CronPanel({ sessionId, onCreateViaChat, onSelectSessionsetCreateMenuOpen(false);// 同 openTemplateDrawer:打开抽屉瞬间重拉一次项目列表,避免拿到挂载时的旧快照void loadProjects();+ void loadChannels();setDrawer({ mode: 'create' });}}className="block w-full px-3 py-2 text-left text-sm font-semibold text-text hover:bg-bg-hover"@@ -864,8 +884,9 @@ export default function CronPanel({ sessionId, onCreateViaChat, onSelectSession<img src={emptyIllustration} alt="" className="h-20 w-20" /><buttononClick={() => {- // 同上:打开抽屉瞬间重拉一次项目列表+ // 同上:打开抽屉瞬间重拉一次项目列表与频道可用性void loadProjects();+ void loadChannels();setDrawer({ mode: 'create' });}}className="btn !px-4 !py-2"@@ -973,7 +994,10 @@ export default function CronPanel({ sessionId, onCreateViaChat, onSelectSession</button>)}<button- onClick={() => setDrawer({ mode: 'edit', initial: jobToForm(job), jobId: job.id })}+ onClick={() => {+ void loadChannels();+ setDrawer({ mode: 'edit', initial: jobToForm(job), jobId: job.id });+ }}className="text-sm text-cron-action-link hover:opacity-80">{t('cron.table.edit')}diff --git a/jiuwenswarm/channels/web/frontend/src/components/CronPanel/xiaoyiCronTarget.ts b/jiuwenswarm/channels/web/frontend/src/components/CronPanel/xiaoyiCronTarget.tsnew file mode 100644index 0000000000..0f963109ac--- /dev/null+++ b/jiuwenswarm/channels/web/frontend/src/components/CronPanel/xiaoyiCronTarget.ts@@ -0,0 +1,54 @@+/**+ * Xiaoyi cron push-target readiness helpers.+ *+ * Cron UI previously treated a registered `xiaoyi` channel as selectable.+ * Push delivery still requires a non-empty `api_id`, so the target must stay+ * disabled until that field is configured.+ */++/** True when Xiaoyi conf has at least one enabled app (or flat conf) with non-empty api_id. */+export function hasXiaoyiPushApiId(config: unknown): boolean {+ if (!config || typeof config !== 'object') {+ return false;+ }+ const conf = config as Record<string, unknown>;+ const apps = conf.apps;+ if (Array.isArray(apps)) {+ return apps.some((app) => {+ if (!app || typeof app !== 'object') {+ return false;+ }+ const item = app as Record<string, unknown>;+ if (item.enabled === false) {+ return false;+ }+ return String(item.api_id ?? '').trim().length > 0;+ });+ }+ if (conf.enabled === false) {+ return false;+ }+ return String(conf.api_id ?? '').trim().length > 0;+}++/**+ * Whether a cron push-channel option should be disabled.+ * Xiaoyi additionally requires push api_id readiness.+ */+export function isCronTargetOptionDisabled(+ channelId: string,+ enabledChannels: Iterable<string>,+ xiaoyiPushReady: boolean,+): boolean {+ const enabled = enabledChannels instanceof Set ? enabledChannels : new Set(enabledChannels);+ const id = String(channelId || '')+ .trim()+ .toLowerCase();+ if (!id || !enabled.has(id)) {+ return true;+ }+ if (id === 'xiaoyi') {+ return !xiaoyiPushReady;+ }+ return false;+}diff --git a/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json b/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.jsonindex cfc6ffdf5d..60e81e59b5 100644--- a/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json+++ b/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json@@ -629,6 +629,8 @@"whatsappJids": "One WhatsApp JID per line (comma-separated is also supported)","wecomDefaultChatId": "userid or chatid (group)","wecomDefaultChatIdHint": "Target for heartbeat/scheduled push. Leave empty to use last chatid",+ "xiaoyiApiIdHint": "Scheduled task push to Xiaoyi requires api_id. Without it, Xiaoyi cannot be selected as a cron push channel.",+ "xiaoyiApiIdRequiredForCron": "api_id is not configured: Xiaoyi cannot be selected as a cron push channel.","discordGuildId": "Enter the Discord server ID (direct message still works without this)","discordChannelId": "Enter the Discord server's channel ID (direct message still works without this)","slackBotToken": "Enter the xoxb bot token",diff --git a/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json b/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.jsonindex be6638c74a..f48bde7488 100644--- a/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json+++ b/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json@@ -629,6 +629,8 @@"whatsappJids": "每行一个 WhatsApp JID(也支持逗号分隔)","wecomDefaultChatId": "userid 或 chatid(群聊)","wecomDefaultChatIdHint": "心跳/定时推送目标。不填则自动使用最近一次聊天的 chatid",+ "xiaoyiApiIdHint": "定时任务推送到小艺需要配置 api_id;未配置时无法在定时任务中选择小艺作为推送渠道。",+ "xiaoyiApiIdRequiredForCron": "未配置 api_id:定时任务中无法选择小艺作为推送渠道。","discordGuildId": "请填入Discord的服务器ID(留空则仅接收私信)","discordChannelId": "请填入Discord服务器的频道ID(留空则仅接收私信)","slackBotToken": "请输入 xoxb Bot Token",diff --git a/jiuwenswarm/channels/web/frontend/tests/xiaoyiCronTarget.test.mjs b/jiuwenswarm/channels/web/frontend/tests/xiaoyiCronTarget.test.mjsnew file mode 100644index 0000000000..2b16b69c65--- /dev/null+++ b/jiuwenswarm/channels/web/frontend/tests/xiaoyiCronTarget.test.mjs@@ -0,0 +1,67 @@+import assert from "node:assert/strict";+import test from "node:test";++import {+ hasXiaoyiPushApiId,+ isCronTargetOptionDisabled,+} from "../node_modules/.cache/xiaoyi-cron-target/components/CronPanel/xiaoyiCronTarget.js";++test("hasXiaoyiPushApiId is false for empty/missing conf", () => {+ assert.equal(hasXiaoyiPushApiId(undefined), false);+ assert.equal(hasXiaoyiPushApiId(null), false);+ assert.equal(hasXiaoyiPushApiId({}), false);+ assert.equal(hasXiaoyiPushApiId({ apps: [] }), false);+});++test("hasXiaoyiPushApiId accepts flat conf with non-empty api_id", () => {+ assert.equal(hasXiaoyiPushApiId({ api_id: "webhook-1" }), true);+ assert.equal(hasXiaoyiPushApiId({ api_id: " " }), false);+ assert.equal(hasXiaoyiPushApiId({ api_id: "webhook-1", enabled: false }), false);+});++test("hasXiaoyiPushApiId requires enabled app with non-empty api_id", () => {+ assert.equal(+ hasXiaoyiPushApiId({+ apps: [{ enabled: true, api_id: "" }],+ }),+ false,+ );+ assert.equal(+ hasXiaoyiPushApiId({+ apps: [{ enabled: true, api_id: " webhook43 " }],+ }),+ true,+ );+ assert.equal(+ hasXiaoyiPushApiId({+ apps: [+ { enabled: false, api_id: "disabled-has-id" },+ { enabled: true, api_id: "" },+ ],+ }),+ false,+ );+ assert.equal(+ hasXiaoyiPushApiId({+ apps: [+ { enabled: false, api_id: "disabled-has-id" },+ { enabled: true, api_id: "ready" },+ ],+ }),+ true,+ );+});++test("isCronTargetOptionDisabled keeps non-xiaoyi channels on enabled-only rule", () => {+ const enabled = new Set(["web", "xiaoyi", "feishu"]);+ assert.equal(isCronTargetOptionDisabled("web", enabled, false), false);+ assert.equal(isCronTargetOptionDisabled("feishu", enabled, true), false);+ assert.equal(isCronTargetOptionDisabled("dingtalk", enabled, true), true);+});++test("isCronTargetOptionDisabled greys out xiaoyi without api_id even when registered", () => {+ const enabled = new Set(["web", "xiaoyi"]);+ assert.equal(isCronTargetOptionDisabled("xiaoyi", enabled, false), true);+ assert.equal(isCronTargetOptionDisabled("xiaoyi", enabled, true), false);+ assert.equal(isCronTargetOptionDisabled("xiaoyi", new Set(["web"]), true), true);+});