From a2f85b3d985044fd79dfaeef0ff273d5dc4d6534 Mon Sep 17 00:00:00 2001 From: zhaoying Date: Mon, 20 Apr 2026 10:16:31 +0800 Subject: [PATCH 01/16] fix(web): update quotas key --- web/src/components/SiderMenu/SubscriptionDetailModal.tsx | 2 +- web/src/components/SiderMenu/index.tsx | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/web/src/components/SiderMenu/SubscriptionDetailModal.tsx b/web/src/components/SiderMenu/SubscriptionDetailModal.tsx index ae084fcd..fbb5030c 100644 --- a/web/src/components/SiderMenu/SubscriptionDetailModal.tsx +++ b/web/src/components/SiderMenu/SubscriptionDetailModal.tsx @@ -82,7 +82,7 @@ const SubscriptionDetailModal = forwardRef((_props, {/* Features */} {billingUnits.map(({ key, unit, icon }) => { - const value = detail?.quota[key as keyof Subscription['quota']]; + const value = detail?.quotas[key as keyof Subscription['quotas']]; if (value === undefined || value === null) return null; return ( {['workspace_quota', 'skill_quota', 'app_quota', 'model_quota'].map(key => (
-
{subscription.quota?.[key as keyof typeof subscription.quota]}
+
{subscription.quotas?.[key as keyof typeof subscription.quotas]}
{t(`index.${key}`)}
))} From 4a39fd5f464165299e1b88472ddb6ca194e4f3ed Mon Sep 17 00:00:00 2001 From: zhaoying Date: Mon, 20 Apr 2026 14:31:31 +0800 Subject: [PATCH 02/16] fix(web) if-else port y calculate update --- .../Workflow/components/CheckList/index.tsx | 8 +- .../components/Nodes/ConditionNode.tsx | 32 ++-- .../components/Properties/CaseList/index.tsx | 35 ++-- web/src/views/Workflow/constant.ts | 4 +- web/src/views/Workflow/utils.ts | 160 +++++------------- 5 files changed, 102 insertions(+), 137 deletions(-) diff --git a/web/src/views/Workflow/components/CheckList/index.tsx b/web/src/views/Workflow/components/CheckList/index.tsx index 4afdb863..b2598999 100644 --- a/web/src/views/Workflow/components/CheckList/index.tsx +++ b/web/src/views/Workflow/components/CheckList/index.tsx @@ -1,3 +1,9 @@ +/* + * @Author: ZhaoYing + * @Date: 2026-04-09 18:58:21 + * @Last Modified by: ZhaoYing + * @Last Modified time: 2026-04-20 10:39:17 + */ import { useState, useCallback, useEffect, useRef, type FC } from 'react' import { Popover, Flex } from 'antd' import { WarningFilled } from '@ant-design/icons' @@ -49,7 +55,7 @@ const specialValidators: Record boolean> = { if (expr?.sub_variable_condition?.conditions?.length > 0) return expr.sub_variable_condition?.conditions.every(isSubExprSet) if (!expr.left) return false if (['not_empty', 'empty'].includes(expr.operator)) return true - return !!expr.left && (!!expr.right || typeof expr.right === 'boolean' || typeof expr.right === 'number') + return !!expr.left && (expr?.sub_variable_condition || !!expr.right || typeof expr.right === 'boolean' || typeof expr.right === 'number') } return val.some(c => !c?.expressions?.length || c.expressions.some((expr: any) => !isExprSet(expr))) }, diff --git a/web/src/views/Workflow/components/Nodes/ConditionNode.tsx b/web/src/views/Workflow/components/Nodes/ConditionNode.tsx index 9cd1309e..1bd6559f 100644 --- a/web/src/views/Workflow/components/Nodes/ConditionNode.tsx +++ b/web/src/views/Workflow/components/Nodes/ConditionNode.tsx @@ -9,7 +9,7 @@ import { useVariableList } from '../Properties/hooks/useVariableList' import { isSubExprSet } from '../../utils' import { fileSubFieldOperators } from '../Properties/CaseList' -const caculateIsSet = (item: any, type: string) => { +const calculateIsSet = (item: any, type: string) => { switch (type) { case 'categories': return typeof item?.class_name === 'string' && item?.class_name !== '' @@ -79,7 +79,7 @@ const ConditionNode: ReactShapeConfig['component'] = ({ node }) => {
{t('workflow.config.question-classifier.class_name')} {index + 1} - {caculateIsSet(item, 'categories') ? t(`workflow.config.${data.type}.set`) : t(`workflow.config.${data.type}.unset`)} + {calculateIsSet(item, 'categories') ? t(`workflow.config.${data.type}.set`) : t(`workflow.config.${data.type}.unset`)}
))} @@ -89,17 +89,24 @@ const ConditionNode: ReactShapeConfig['component'] = ({ node }) => { {data.config?.cases?.defaultValue.map((item: any, index: number) => (
0 ? '' : 'rb:mb-1'}> - 0 ? "space-between" : 'end'} className="rb:mb-1"> - {item.expressions.length > 0 && CASE{index + 1}} + 0 ? "space-between" : 'end'} className="rb:mb-1! rb:leading-4"> + {item.expressions.length > 0 && CASE{index + 1}} {index === 0 ? 'IF' : `ELIF`} {item.expressions.length > 0 && {item.expressions.map((expression: any, eIndex: number) => (
- {item.expressions.length > 1 && eIndex > 0 &&
{item.logical_operator?.toLocaleUpperCase()}
} - + {item.expressions.length > 1 && eIndex > 0 && +
{item.logical_operator?.toLocaleUpperCase()}
+ } + 0, + 'rb:py-1!': !expression.sub_variable_condition?.conditions || !expression.sub_variable_condition?.conditions?.length + })} + > - {caculateIsSet(expression, 'cases') + {calculateIsSet(expression, 'cases') ? <> {labelRender(expression.left)} {getLocaleField(expression.operator, typeof expression.right)} @@ -109,11 +116,16 @@ const ConditionNode: ReactShapeConfig['component'] = ({ node }) => { } {expression.sub_variable_condition?.conditions?.length > 0 && expression.sub_variable_condition?.conditions.every(isSubExprSet) - ?
+ ?
{expression.sub_variable_condition?.conditions.map((sub: any, sIndex: number) => (
{expression.sub_variable_condition?.conditions.length > 1 && sIndex > 0 &&
{expression.sub_variable_condition?.logical_operator?.toLocaleUpperCase()}
} - + {sub.key} {getSubLocaleField(sub.operator, sub.key)} @@ -129,7 +141,7 @@ const ConditionNode: ReactShapeConfig['component'] = ({ node }) => { ))}
: expression.sub_variable_condition?.conditions?.length > 0 - ? + ? {t(`workflow.config.${data.type}.unset`)} : null diff --git a/web/src/views/Workflow/components/Properties/CaseList/index.tsx b/web/src/views/Workflow/components/Properties/CaseList/index.tsx index 2fd24628..a9da1457 100644 --- a/web/src/views/Workflow/components/Properties/CaseList/index.tsx +++ b/web/src/views/Workflow/components/Properties/CaseList/index.tsx @@ -2,7 +2,7 @@ * @Author: ZhaoYing * @Date: 2026-02-09 18:24:53 * @Last Modified by: ZhaoYing - * @Last Modified time: 2026-04-17 20:47:49 + * @Last Modified time: 2026-04-20 10:46:05 */ import { useEffect, useMemo, type FC } from 'react' import clsx from 'clsx' @@ -39,7 +39,7 @@ interface Expression { sub_variable_condition?: SubVariableCondition; } -interface CaseItem { +export interface CaseItem { logical_operator: 'and' | 'or'; expressions: Expression[]; } @@ -274,7 +274,9 @@ const ArrayFileSubConditions: FC = ({ conditionFiel className="rb:w-full!" suffix="Byte" size="small" - onChange={(value) => { form.setFieldValue([name, caseIndex, 'expressions', conditionIndex, 'right'], value); }} + onChange={(value) => { + form.setFieldValue([name, caseIndex, 'expressions', conditionIndex, 'sub_variable_condition', 'conditions', subIndex, 'value'], value); + }} /> } @@ -483,13 +485,24 @@ const CaseList: FC = ({ form.setFieldValue([name, index, 'logical_operator'], currentValue === 'and' ? 'or' : 'and'); }; - const handleLeftFieldChange = (caseIndex: number, conditionIndex: number, newValue: string) => { - form.setFieldValue([name, caseIndex, 'expressions', conditionIndex], { - left: newValue, - operator: undefined, - right: undefined, - input_type: 'constant' - }); + const handleLeftFieldChange = (caseIndex: number, conditionIndex: number, newValue: string, option?: Suggestion | undefined) => { + if (option?.dataType === 'array[file]') { + form.setFieldValue([name, caseIndex, 'expressions', conditionIndex], { + left: newValue, + operator: undefined, + sub_variable_condition: { + conditions: [], + logical_operator: 'and' + } + }); + } else { + form.setFieldValue([name, caseIndex, 'expressions', conditionIndex], { + left: newValue, + operator: undefined, + right: undefined, + input_type: 'constant' + }); + } }; const handleAddCase = (addCaseFunc: Function) => { @@ -590,7 +603,7 @@ const CaseList: FC = ({ options={options} size="small" allowClear={false} - onChange={(val) => handleLeftFieldChange(caseIndex, conditionIndex, val as string)} + onChange={(val, option) => handleLeftFieldChange(caseIndex, conditionIndex, val as string, option as unknown as Suggestion)} variant="borderless" className="rb:w-36!" /> diff --git a/web/src/views/Workflow/constant.ts b/web/src/views/Workflow/constant.ts index cae20180..c11eb4c0 100644 --- a/web/src/views/Workflow/constant.ts +++ b/web/src/views/Workflow/constant.ts @@ -2,7 +2,7 @@ * @Author: ZhaoYing * @Date: 2026-02-03 15:06:18 * @Last Modified by: ZhaoYing - * @Last Modified time: 2026-04-16 17:52:30 + * @Last Modified time: 2026-04-20 11:39:40 */ import LoopNode from './components/Nodes/LoopNode'; import NormalNode from './components/Nodes/NormalNode'; @@ -734,7 +734,7 @@ export const portTextAttrs = { fontSize: 12, fill: '#5B6167' } /** * Port position arguments */ -export const portItemArgsY = 26.5; +export const portItemArgsY = 27.5; export const portArgs = { x: nodeWidth, y: portItemArgsY } const defaultPortGroup = { diff --git a/web/src/views/Workflow/utils.ts b/web/src/views/Workflow/utils.ts index bd81b6eb..74dfca2c 100644 --- a/web/src/views/Workflow/utils.ts +++ b/web/src/views/Workflow/utils.ts @@ -2,136 +2,70 @@ * @Author: ZhaoYing * @Date: 2026-03-24 15:07:49 * @Last Modified by: ZhaoYing - * @Last Modified time: 2026-04-17 20:40:47 + * @Last Modified time: 2026-04-20 14:20:34 */ -import { portItemArgsY, conditionNodePortItemArgsY, conditionNodeHeight } from './constant' +import { conditionNodePortItemArgsY, conditionNodeHeight } from './constant' -/** - * Calculate the total height of a condition (if-else) node based on its cases. - * - * The height is composed of: - * - `conditionNodeHeight`: the base height of the node (header + padding). - * - `(cases.length - 1) * 26`: vertical spacing added for each additional case - * beyond the first (each case separator row is 26px). - * - `exprCount * 20`: each individual expression row occupies 20px. - * - `hasMultiExprCount * 3`: a small extra padding (3px per expression) is added - * for cases that contain more than one expression, to account for the logical - * operator indicator (AND/OR) between expressions. - * - * @param cases - Array of case objects, each containing an `expressions` array. - * @returns The total pixel height for the condition node. - */ export const isSubExprSet = (sub: any) => { if (!sub?.key) return false; if (['not_empty', 'empty'].includes(sub?.operator)) return true; return !!sub.value || typeof sub.value === 'boolean' || typeof sub.value === 'number'; }; - -const getEffectiveExprCount = (expr: any): number => { - const subs = expr?.sub_variable_condition?.conditions; - if (subs?.length && subs.every(isSubExprSet)) return 1 + subs.length; - if (subs?.length > 0) { - return 2 - } - return 1; +/** + * Calculate the total height of a condition (if-else) node based on its cases. + * Uses the same per-expression height logic as getConditionNodeCasePortY. + */ +export const calcConditionNodeTotalHeight = (cases: any[]) => { + const casesHeight = cases.reduce((acc: number, c: any) => { + const exprs = c?.expressions ?? []; + const n = exprs.length; + const exprsHeight = n === 0 ? 0 : exprs.reduce((s: number, e: any) => s + calcExpressionHeight(e), 0) + 2 * (n - 1); + return acc + 20 + exprsHeight; + }, 0); + return conditionNodeHeight + casesHeight + (cases.length - 1) * 4 - 27.5; }; -export const calcConditionNodeTotalHeight = (cases: any[]) => { - // Total number of effective expression rows (sub_variable_condition expand height when all set) - const exprCount = cases.reduce((acc: number, c: any) => - acc + (c?.expressions?.reduce((s: number, e: any) => s + getEffectiveExprCount(e), 0) || 0), 0); - // Sum of effective expression counts only for cases that have more than one expression - const hasMultiExprCount = cases.reduce((acc: number, c: any) => { - if (!c?.expressions?.length || c.expressions.length <= 1) return acc; - const effectiveCount = c.expressions.reduce((s: number, e: any) => s + getEffectiveExprCount(e), 0); - return acc + effectiveCount; - }, 0); - - return conditionNodeHeight + (cases.length - 1) * 26 + exprCount * 20 + hasMultiExprCount * 3; +/** + * Height of a single expression block in ConditionNode (px). + * + * expression outer Flex padding: + * - has sub conditions (length > 0): pt-1 (4px top only) + * - no sub conditions: py-1 (4px top + 4px bottom) + * expression main row: leading-4 = 16px + * sub_variable_condition block (mt-1 = 4px gap): + * - all isSet, m subs: sub[0] = leading-3.5(14) + pb-1(4) = 18px; + * sub[k>0] = py-1(8) + leading-3.5(14) = 22px + * total = 18 + 22*(m-1) + * - exists but not all isSet: pb-1(4) + leading-4(16) = 20px + */ +const calcExpressionHeight = (expression: any): number => { + const subs = expression?.sub_variable_condition?.conditions; + if (!subs?.length) return 24; // py-1(8) + leading-4(16) + const subBlockHeight = subs.every(isSubExprSet) + ? 18 + 22 * (subs.length - 1) + : 20; + return 4 + 16 + 4 + subBlockHeight - 2; // pt-1 + main row + mt-1 + sub block (-2 rendering correction) }; /** * Calculate the Y-coordinate of the right-side output port for a specific case - * in a condition (if-else) node. + * in a condition (if-else) node, aligned with the IF/ELIF label in ConditionNode. * - * The port position is determined by iterating through all preceding cases - * (index 0 to caseIndex - 1) and accumulating their visual heights. Several - * pixel-level corrections are applied to align ports with the rendered UI: - * - * 1. **Base offset**: starts at `conditionNodePortItemArgsY`, which is the Y - * position of the first case port relative to the node top. - * - * 2. **Per-case accumulation**: for each preceding case with `n` expressions, - * add `portItemArgsY * (n + 1)` — this accounts for `n` expression rows - * plus one case header/separator row. - * - * 3. **Single-expression correction**: cases with exactly 1 expression render - * slightly shorter than the generic formula predicts. Subtract - * `singleExprCount * 7 + 2` to compensate for the reduced row height when - * no logical operator row is shown. - * - * 4. **Multi-expression correction**: cases with 2+ expressions have a compact - * logical operator row. Subtract `multiExprCount * 9` to offset the - * over-estimated spacing. - * - * 5. **Extra expression correction**: for cases with more than 2 expressions, - * each additional expression beyond the second introduces a minor spacing - * discrepancy. Subtract `(extraExprs + 1) * 2` to fine-tune alignment. - * - * @param cases - Array of case objects, each containing an `expressions` array. - * @param caseIndex - The zero-based index of the target case whose port Y is needed. - * @returns The Y-coordinate (in pixels) for the output port of the given case. + * Layout (from node top): + * - 12px padding-top + 24px header + 12px mt-3 = 48px to cases area + * - Each IF/ELIF label row: leading-4 (16px), center at +8px → first port Y = 56.5 + * - Each case: IF/ELIF row (leading-4=16) + mb-1(4) + expressions (gap={2}=2px between) + * - Gap between cases (Flex gap={4}): 4px */ export const getConditionNodeCasePortY = (cases: any[], caseIndex: number) => { - let y = conditionNodePortItemArgsY; - let singleExprCount = 0; - let multiExprCount = 0; - let extraExprs = 0; - let portItemArgsYNum = 0; - + let y = conditionNodePortItemArgsY; // 56.5, center of first IF label for (let i = 0; i < caseIndex; i++) { - const notHasSub = cases[i]?.expressions?.filter((e: any) => !e?.sub_variable_condition?.conditions || e?.sub_variable_condition?.conditions.length <1).length - const n = cases[i]?.expressions?.length || 0; - let casePortItemArgsYNum = n + 1; - // Add extra y for expressions with all sub_variable_condition set - cases[i]?.expressions?.forEach((expr: any) => { - const subs = expr?.sub_variable_condition?.conditions; - if (subs?.length && subs.every(isSubExprSet)) { - casePortItemArgsYNum += subs.length; - } else if (subs?.length) { - casePortItemArgsYNum += 1 - } - }); - portItemArgsYNum += casePortItemArgsYNum; - if (n === 1 && !cases[i]?.expressions?.some((e: any) => e?.sub_variable_condition?.conditions?.length > 0)) { - singleExprCount++ - } else if (n >= 2 || cases[i]?.expressions?.some((e: any) => e?.sub_variable_condition?.conditions?.length > 0)) { - multiExprCount++; - cases[i]?.expressions?.forEach((e: any) => { - const subs = e?.sub_variable_condition?.conditions; - if (subs?.length && subs.every(isSubExprSet) && subs.length > 1) { - extraExprs += subs.length + 2; - } - }); - - console.log('extraExprs notHasSub', notHasSub) - if (notHasSub > 3) { - extraExprs += n - 2 + notHasSub/4; - } else { - extraExprs += n - 2 + notHasSub/4 - } - } + const exprs = cases[i]?.expressions ?? []; + const n = exprs.length; + // IF/ELIF row (16) + mb-1 (4) = 20px base; expressions: sum of heights + 2px gap between + const exprsHeight = n === 0 ? 0 : exprs.reduce((acc: number, e: any) => acc + calcExpressionHeight(e), 0) + 2 * (n - 1); + y += 20 + exprsHeight + 4; // case height + Flex gap between cases } - - console.log('singleExprCount', singleExprCount, 'multiExprCount', multiExprCount, 'extraExprs', extraExprs) - y += portItemArgsY * portItemArgsYNum - // Correction for single-expression cases (slightly shorter rendered height) - if (singleExprCount > 0) y -= singleExprCount * 7 + 2; - // Correction for multi-expression cases (compact logical operator row) - y -= multiExprCount * 9; - // Correction for cases with more than 2 expressions (minor spacing drift) - if (extraExprs > 0) y -= (extraExprs + 1) * 2; - return y; -}; +}; \ No newline at end of file From 559b4bef6b362cd6bdfa82efa60e48d0a11145ba Mon Sep 17 00:00:00 2001 From: zhaoying Date: Mon, 20 Apr 2026 14:47:16 +0800 Subject: [PATCH 03/16] fix(web): add tool_id required check list --- web/src/i18n/en.ts | 1 + web/src/i18n/zh.ts | 1 + .../Workflow/components/Properties/ToolConfig/index.tsx | 5 +++++ web/src/views/Workflow/constant.ts | 5 +++-- 4 files changed, 10 insertions(+), 2 deletions(-) diff --git a/web/src/i18n/en.ts b/web/src/i18n/en.ts index dfc42973..9470e2e9 100644 --- a/web/src/i18n/en.ts +++ b/web/src/i18n/en.ts @@ -2564,6 +2564,7 @@ Memory Bear: After the rebellion, regional warlordism intensified for several re 'jinja-render.template': 'Template', 'document-extractor.file_selector': 'File variable', 'list-operator.input_list': 'Input list', + 'tool.tool_id': 'Tool', }, checkListHasErrors: 'Please resolve all issues in the checklist before publishing', variableSelect: { diff --git a/web/src/i18n/zh.ts b/web/src/i18n/zh.ts index ae0181c9..8a134a06 100644 --- a/web/src/i18n/zh.ts +++ b/web/src/i18n/zh.ts @@ -2528,6 +2528,7 @@ export const zh = { 'jinja-render.template': '模板', 'document-extractor.file_selector': '文件变量', 'list-operator.input_list': '输入变量', + 'tool.tool_id': '工具', }, checkListHasErrors: '发布前确认检查清单中所有问题均已解决', variableSelect: { diff --git a/web/src/views/Workflow/components/Properties/ToolConfig/index.tsx b/web/src/views/Workflow/components/Properties/ToolConfig/index.tsx index ce30ee8f..d38265da 100644 --- a/web/src/views/Workflow/components/Properties/ToolConfig/index.tsx +++ b/web/src/views/Workflow/components/Properties/ToolConfig/index.tsx @@ -147,6 +147,11 @@ const ToolConfig: FC<{ options: Suggestion[]; }> = ({ }; const handleChange: CascaderProps - : log.type === 'search_result' && log.raw_results && typeof log.raw_results !== 'string' + : log.type === 'search_result' && log.result ? -
{log.query}
- {(log.raw_results.reranked_results as AnyObject)?.communities?.length > 0 && <> -
{t('memoryConversation.communities')}
-
    - {((log.raw_results.reranked_results as AnyObject)?.communities as { content: string }[]).map((item, index: number) => ( -
  • {item.content}
  • - ))} -
- } - {(log.raw_results.reranked_results as AnyObject)?.summaries?.length > 0 && <> -
{t('memoryConversation.summaries')}
-
    - {((log.raw_results.reranked_results as AnyObject)?.summaries as { content: string }[]).map((item, index: number) => ( -
  • {item.content}
  • - ))} -
- } +
: log.type === 'retrieval_summary' && log.summary ? From 10a655772fa35ba8e722e53dd4594b73c1bad358 Mon Sep 17 00:00:00 2001 From: zhaoying Date: Mon, 20 Apr 2026 17:04:00 +0800 Subject: [PATCH 08/16] fix(web): jump list --- .../ApplicationManagement/components/UploadModal.tsx | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/web/src/views/ApplicationManagement/components/UploadModal.tsx b/web/src/views/ApplicationManagement/components/UploadModal.tsx index 4211e72b..623b1b59 100644 --- a/web/src/views/ApplicationManagement/components/UploadModal.tsx +++ b/web/src/views/ApplicationManagement/components/UploadModal.tsx @@ -2,7 +2,7 @@ * @Author: ZhaoYing * @Date: 2026-02-28 14:08:14 * @Last Modified by: ZhaoYing - * @Last Modified time: 2026-04-13 18:17:32 + * @Last Modified time: 2026-04-20 16:52:32 */ /** * UploadModal Component @@ -16,6 +16,7 @@ import { forwardRef, useImperativeHandle, useState, useMemo } from 'react'; import { Form, Steps, Flex, Alert, Button, Result, message } from 'antd'; import { useTranslation } from 'react-i18next'; +import { useNavigate } from 'react-router-dom'; import type { Application, UploadModalRef } from '../types' import RbModal from '@/components/RbModal' @@ -51,6 +52,7 @@ const UploadModal = forwardRef(({ id }, ref) => { const { t } = useTranslation(); + const navigate = useNavigate(); // State management const [visible, setVisible] = useState(false); // Modal visibility @@ -146,6 +148,10 @@ const UploadModal = forwardRef(({ window.open(`/#/application/config/${appId}`, '_blank'); } break; + case 'list': + if (id) { + navigate('/application') + } } }, 100) }; From b03300c804a8f60a5020468399b763bc041a77fb Mon Sep 17 00:00:00 2001 From: wwq Date: Mon, 20 Apr 2026 17:18:05 +0800 Subject: [PATCH 09/16] refactor(rate_limit): refactor API Key rate limiting and remove tenant-level QPS check - Streamline rate limit check flow by removing redundant tenant-level QPS checks. - Restrict checks to API Key QPS and plan degradation protection only. - Update constant naming and error message handling for consistency. --- api/app/core/api_key_auth.py | 3 +- api/app/core/quota_stub.py | 4 +- api/app/services/api_key_service.py | 83 ++++++----------------------- 3 files changed, 18 insertions(+), 72 deletions(-) diff --git a/api/app/core/api_key_auth.py b/api/app/core/api_key_auth.py index b7cacd21..1ded6f81 100644 --- a/api/app/core/api_key_auth.py +++ b/api/app/core/api_key_auth.py @@ -108,8 +108,7 @@ def require_api_key( # 根据错误消息判断限流类型 if "Daily" in error_msg: code = BizCode.API_KEY_DAILY_LIMIT_EXCEEDED - elif "QPS" in error_msg or "ops rate limit" in error_msg: - # "QPS limit exceeded" 和 "API ops rate limit exceeded" 同属 QPS 类 + elif "QPS" in error_msg: code = BizCode.API_KEY_QPS_LIMIT_EXCEEDED else: code = BizCode.API_KEY_QUOTA_EXCEEDED diff --git a/api/app/core/quota_stub.py b/api/app/core/quota_stub.py index 4a8f7cee..248d0875 100644 --- a/api/app/core/quota_stub.py +++ b/api/app/core/quota_stub.py @@ -18,7 +18,7 @@ from app.core.quota_manager import ( get_quota_usage, _check_quota, QuotaUsageRepository, - TENANT_QPS_REDIS_KEY, + API_KEY_QPS_REDIS_KEY, ) __all__ = [ @@ -34,5 +34,5 @@ __all__ = [ "get_quota_usage", "_check_quota", "QuotaUsageRepository", - "TENANT_QPS_REDIS_KEY", + "API_KEY_QPS_REDIS_KEY", ] diff --git a/api/app/services/api_key_service.py b/api/app/services/api_key_service.py index 4fe9d8b5..d710d4ee 100644 --- a/api/app/services/api_key_service.py +++ b/api/app/services/api_key_service.py @@ -282,42 +282,6 @@ class RateLimiterService: def __init__(self): self.redis = aio_redis - async def check_tenant_rate_limit(self, window_id: uuid.UUID, limit: int) -> Tuple[bool, dict]: - """ - 按 window_id(api_key_id)做 1 秒滑动窗口限速。 - 限制值来自套餐配额 api_ops_rate_limit,每个 API Key 独立受此上限约束。 - 只有请求被允许时才计入窗口,超限请求不污染计数。 - """ - now = time.time() - window_start = now - 1 # 1 秒窗口 - key = f"rate_limit:tenant_qps:{window_id}" - - async with self.redis.pipeline() as pipe: - pipe.zremrangebyscore(key, 0, window_start) - pipe.zcard(key) - results = await pipe.execute() - - current = results[1] - - if current >= limit: - return False, { - "limit": limit, - "remaining": 0, - "reset": int(now) + 1, - } - - member = f"{now}:{uuid.uuid4().hex}" - async with self.redis.pipeline() as pipe: - pipe.zadd(key, {member: now}) - pipe.expire(key, 2) - await pipe.execute() - - return True, { - "limit": limit, - "remaining": max(0, limit - current - 1), - "reset": int(now) + 1, - } - async def check_qps(self, api_key_id: uuid.UUID, limit: int) -> Tuple[bool, dict]: """ 检查 API Key 自身 QPS 限制(1 秒滑动窗口)。 @@ -337,6 +301,7 @@ class RateLimiterService: if current >= limit: return False, { "limit": limit, + "current": current, "remaining": 0, "reset": int(now) + 1, } @@ -349,6 +314,7 @@ class RateLimiterService: return True, { "limit": limit, + "current": current + 1, "remaining": max(0, limit - current - 1), "reset": int(now) + 1, } @@ -398,14 +364,9 @@ class RateLimiterService: ) -> Tuple[bool, str, dict]: """ 检查所有限制,按以下顺序: - 1. API Key 自身 QPS(每个 key 独立,不超过其配置的 rate_limit) - 2. 租户套餐 api_ops_rate_limit(每个 key 独立受套餐限额约束) + 1. API Key 自身 QPS(rate_limit 在创建时已保证不超过套餐 api_ops_rate_limit) + 2. 套餐降级保护:若套餐已降级导致 rate_limit > 套餐上限,用套餐上限二次卡控 3. API Key 日调用量 - - 设计语义: - - 租户下 N 个 API Key 可以并发调用,互不影响 - - 每个 API Key 独立受自身 rate_limit 约束 - - 每个 API Key 独立受租户套餐 api_ops_rate_limit 约束(per-key 限额) """ # 1. 检查 API Key 自身 QPS qps_ok, qps_info = await self.check_qps( @@ -419,24 +380,20 @@ class RateLimiterService: "X-RateLimit-Reset": str(qps_info["reset"]) } - # 2. 检查租户套餐 api_ops_rate_limit(运行时流量控制) - # 每个 API Key 的速率都不能超过租户套餐上限,无论 key 自身配置多少 - tenant_info = None + # 2. 套餐降级保护 + # 套餐降级后已有 api_key 的 rate_limit 可能高于新套餐上限 + # 复用第1关已计好的 current,不重复写 Redis if db is not None: try: from app.models.workspace_model import Workspace from app.core.quota_manager import get_api_ops_rate_limit - # 从 Redis 缓存取 tenant_limit,避免每次请求都查数据库 - # TTL 60 秒,套餐变更后最多 1 分钟生效 - # 用 workspace_id 作为滑动窗口维度(一个 workspace 只属于一个 tenant,语义等价) cache_key = f"tenant_api_ops_limit:{api_key.workspace_id}" cached = await self.redis.get(cache_key) if cached is not None: try: tenant_limit = int(cached) if cached != "0" else None except (ValueError, TypeError): - # 缓存数据损坏,回源查数据库 cached = None tenant_limit = None @@ -448,19 +405,14 @@ class RateLimiterService: else: tenant_limit = None - if tenant_limit: - # 用 api_key.id 作为滑动窗口 key,每个 API Key 独立受 api_ops_rate_limit 约束 - tenant_ok, tenant_info = await self.check_tenant_rate_limit( - api_key.id, tenant_limit - ) - if not tenant_ok: - return False, "API ops rate limit exceeded", { - "X-RateLimit-Limit-QPS": str(tenant_limit), - "X-RateLimit-Remaining-QPS": str(tenant_info["remaining"]), - "X-RateLimit-Reset": str(tenant_info["reset"]), - } + if tenant_limit and qps_info["current"] > tenant_limit: + return False, "QPS limit exceeded", { + "X-RateLimit-Limit-QPS": str(tenant_limit), + "X-RateLimit-Remaining-QPS": "0", + "X-RateLimit-Reset": str(qps_info["reset"]), + } except Exception as e: - logger.warning(f"租户 api_ops_rate_limit 运行时检查失败,跳过: {e}") + logger.warning(f"套餐降级保护检查失败,跳过: {e}") # 3. 检查日调用量 daily_ok, daily_info = await self.check_daily_requests( @@ -474,18 +426,13 @@ class RateLimiterService: "X-RateLimit-Reset": str(daily_info["reset"]) } - headers = { + return True, "", { "X-RateLimit-Limit-QPS": str(qps_info["limit"]), "X-RateLimit-Remaining-QPS": str(qps_info["remaining"]), "X-RateLimit-Limit-Day": str(daily_info["limit"]), "X-RateLimit-Remaining-Day": str(daily_info["remaining"]), "X-RateLimit-Reset": str(daily_info["reset"]), } - # 如果租户限速信息存在,补充到响应头 - if tenant_info: - headers["X-RateLimit-Limit-Tenant-QPS"] = str(tenant_info["limit"]) - headers["X-RateLimit-Remaining-Tenant-QPS"] = str(tenant_info["remaining"]) - return True, "", headers class ApiKeyAuthService: From 08b5c7bc8a09ac36fc20427cf795ece38dcdd99d Mon Sep 17 00:00:00 2001 From: wwq Date: Mon, 20 Apr 2026 17:46:05 +0800 Subject: [PATCH 10/16] =?UTF-8?q?perf(=E9=99=90=E6=B5=81=E6=9C=8D=E5=8A=A1?= =?UTF-8?q?):=20=E4=BC=98=E5=8C=96Redis=E6=9F=A5=E8=AF=A2=E4=BB=A5?= =?UTF-8?q?=E5=87=8F=E5=B0=91=E5=91=BD=E4=BB=A4=E6=95=B0=E9=87=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 使用zcount替代zremrangebyscore和zcard组合查询,减少一次Redis操作 --- api/app/services/api_key_service.py | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/api/app/services/api_key_service.py b/api/app/services/api_key_service.py index d710d4ee..c1bbbdc8 100644 --- a/api/app/services/api_key_service.py +++ b/api/app/services/api_key_service.py @@ -292,11 +292,10 @@ class RateLimiterService: key = f"rate_limit:qps:{api_key_id}" async with self.redis.pipeline() as pipe: - pipe.zremrangebyscore(key, 0, window_start) - pipe.zcard(key) + pipe.zcount(key, window_start, "+inf") results = await pipe.execute() - current = results[1] + current = results[0] if current >= limit: return False, { From 3227c25b07a805caab6d8c4c5fc71ddd7278e33c Mon Sep 17 00:00:00 2001 From: wwq Date: Mon, 20 Apr 2026 18:10:28 +0800 Subject: [PATCH 11/16] fix(quota): fix tenant ID retrieval and QPS counting logic - Fix issue where tenant ID lookup from shared records failed to query the workspace correctly. - Switch QPS counting from sliding window to simple counter to improve performance and simplify logic. - Remove unnecessary `time` module import. --- api/app/core/quota_manager.py | 9 ++-- api/app/services/api_key_service.py | 79 +++++++++++------------------ 2 files changed, 34 insertions(+), 54 deletions(-) diff --git a/api/app/core/quota_manager.py b/api/app/core/quota_manager.py index 28130dee..bf04059e 100644 --- a/api/app/core/quota_manager.py +++ b/api/app/core/quota_manager.py @@ -6,7 +6,6 @@ 2. 降级到 default_free_plan.py 配置文件(社区版兜底) """ import asyncio -import time from functools import wraps from typing import Optional, Callable, Dict, Any from uuid import UUID @@ -68,7 +67,9 @@ def _get_tenant_id_from_kwargs(db: Session, kwargs: dict): if share_record: app = db.query(App).filter(App.id == share_record.app_id, App.is_active.is_(True)).first() if app: - return app.workspace.tenant_id + workspace = db.query(Workspace).filter(Workspace.id == app.workspace_id).first() + if workspace: + return workspace.tenant_id return None @@ -597,7 +598,6 @@ async def get_quota_usage(db: Session, tenant_id: UUID) -> dict: from app.aioRedis import aio_redis as _aio_redis from app.models.api_key_model import ApiKey from app.models.workspace_model import Workspace - _now = time.time() # api_ops_rate_limit 限的是每个 api_key 每秒最高限额 # 展示当前最接近触发限流的 key 的 QPS(取最大值) api_key_ids = db.query(ApiKey.id).join( @@ -608,7 +608,8 @@ async def get_quota_usage(db: Session, tenant_id: UUID) -> dict: ).all() for (key_id,) in api_key_ids: _rk = API_KEY_QPS_REDIS_KEY.format(api_key_id=key_id) - count = int(await _aio_redis.zcount(_rk, _now - 1, "+inf") or 0) + val = await _aio_redis.get(_rk) + count = int(val) if val else 0 if count > api_ops_current: api_ops_current = count except Exception as e: diff --git a/api/app/services/api_key_service.py b/api/app/services/api_key_service.py index c1bbbdc8..e67d623e 100644 --- a/api/app/services/api_key_service.py +++ b/api/app/services/api_key_service.py @@ -283,39 +283,27 @@ class RateLimiterService: self.redis = aio_redis async def check_qps(self, api_key_id: uuid.UUID, limit: int) -> Tuple[bool, dict]: + """检查QPS限制 + + Returns: + (is_allowed, rate_limit_info) """ - 检查 API Key 自身 QPS 限制(1 秒滑动窗口)。 - 只有请求被允许时才计入窗口,超限请求不污染计数。 - """ - now = time.time() - window_start = now - 1 key = f"rate_limit:qps:{api_key_id}" async with self.redis.pipeline() as pipe: - pipe.zcount(key, window_start, "+inf") + pipe.incr(key) + pipe.expire(key, 1, nx=True) # 1 秒过期 results = await pipe.execute() current = results[0] + remaining = max(0, limit - current) + reset_time = int(time.time()) + 1 - if current >= limit: - return False, { - "limit": limit, - "current": current, - "remaining": 0, - "reset": int(now) + 1, - } - - member = f"{now}:{uuid.uuid4().hex}" - async with self.redis.pipeline() as pipe: - pipe.zadd(key, {member: now}) - pipe.expire(key, 2) - await pipe.execute() - - return True, { + return current <= limit, { "limit": limit, - "current": current + 1, - "remaining": max(0, limit - current - 1), - "reset": int(now) + 1, + "current": current, + "remaining": remaining, + "reset": reset_time, } async def check_daily_requests( @@ -363,25 +351,11 @@ class RateLimiterService: ) -> Tuple[bool, str, dict]: """ 检查所有限制,按以下顺序: - 1. API Key 自身 QPS(rate_limit 在创建时已保证不超过套餐 api_ops_rate_limit) - 2. 套餐降级保护:若套餐已降级导致 rate_limit > 套餐上限,用套餐上限二次卡控 - 3. API Key 日调用量 + 1. API Key QPS:取 api_key.rate_limit 与套餐 api_ops_rate_limit 的最小值作为限额 + 2. API Key 日调用量 """ - # 1. 检查 API Key 自身 QPS - qps_ok, qps_info = await self.check_qps( - api_key.id, - api_key.rate_limit - ) - if not qps_ok: - return False, "QPS limit exceeded", { - "X-RateLimit-Limit-QPS": str(qps_info["limit"]), - "X-RateLimit-Remaining-QPS": str(qps_info["remaining"]), - "X-RateLimit-Reset": str(qps_info["reset"]) - } - - # 2. 套餐降级保护 - # 套餐降级后已有 api_key 的 rate_limit 可能高于新套餐上限 - # 复用第1关已计好的 current,不重复写 Redis + # 1. 取套餐限额与 api_key 自身限额的最小值 + effective_limit = api_key.rate_limit if db is not None: try: from app.models.workspace_model import Workspace @@ -404,16 +378,21 @@ class RateLimiterService: else: tenant_limit = None - if tenant_limit and qps_info["current"] > tenant_limit: - return False, "QPS limit exceeded", { - "X-RateLimit-Limit-QPS": str(tenant_limit), - "X-RateLimit-Remaining-QPS": "0", - "X-RateLimit-Reset": str(qps_info["reset"]), - } + if tenant_limit: + effective_limit = min(api_key.rate_limit, tenant_limit) except Exception as e: - logger.warning(f"套餐降级保护检查失败,跳过: {e}") + logger.warning(f"获取套餐限额失败,使用 api_key 自身限额: {e}") - # 3. 检查日调用量 + # 用最终有效限额做 QPS 检查 + qps_ok, qps_info = await self.check_qps(api_key.id, effective_limit) + if not qps_ok: + return False, "QPS limit exceeded", { + "X-RateLimit-Limit-QPS": str(qps_info["limit"]), + "X-RateLimit-Remaining-QPS": str(qps_info["remaining"]), + "X-RateLimit-Reset": str(qps_info["reset"]) + } + + # 2. 检查日调用量 daily_ok, daily_info = await self.check_daily_requests( api_key.id, api_key.daily_request_limit From d59990d3260652a88d55773b47ae2e26e8a713cf Mon Sep 17 00:00:00 2001 From: wwq Date: Mon, 20 Apr 2026 18:25:39 +0800 Subject: [PATCH 12/16] fix(rate_limit): differentiate between tenant plan and API Key QPS limit errors - Add logic to detect tenant plan QPS limits and return a specific error message when triggered. - Simplify boolean check in model activation quota validation. --- api/app/core/api_key_auth.py | 2 ++ api/app/core/quota_manager.py | 4 ++-- api/app/services/api_key_service.py | 7 ++++++- 3 files changed, 10 insertions(+), 3 deletions(-) diff --git a/api/app/core/api_key_auth.py b/api/app/core/api_key_auth.py index 1ded6f81..05bca945 100644 --- a/api/app/core/api_key_auth.py +++ b/api/app/core/api_key_auth.py @@ -108,6 +108,8 @@ def require_api_key( # 根据错误消息判断限流类型 if "Daily" in error_msg: code = BizCode.API_KEY_DAILY_LIMIT_EXCEEDED + elif "Tenant" in error_msg: + code = BizCode.API_KEY_QPS_LIMIT_EXCEEDED # 租户套餐速率超限,同属 QPS 类 elif "QPS" in error_msg: code = BizCode.API_KEY_QPS_LIMIT_EXCEEDED else: diff --git a/api/app/core/quota_manager.py b/api/app/core/quota_manager.py index bf04059e..534e1940 100644 --- a/api/app/core/quota_manager.py +++ b/api/app/core/quota_manager.py @@ -488,7 +488,7 @@ def check_model_activation_quota(func: Callable) -> Callable: logger.warning("模型激活配额检查失败:缺少 model_id 或 model_data 参数") return await func(*args, **kwargs) - if model_data.is_active is True: + if model_data.is_active: try: from app.services.model_service import ModelConfigService @@ -522,7 +522,7 @@ def check_model_activation_quota(func: Callable) -> Callable: logger.warning("模型激活配额检查失败:缺少 model_id 或 model_data 参数") return func(*args, **kwargs) - if model_data.is_active is True: + if model_data.is_active: try: from app.services.model_service import ModelConfigService diff --git a/api/app/services/api_key_service.py b/api/app/services/api_key_service.py index e67d623e..5595e93f 100644 --- a/api/app/services/api_key_service.py +++ b/api/app/services/api_key_service.py @@ -386,7 +386,12 @@ class RateLimiterService: # 用最终有效限额做 QPS 检查 qps_ok, qps_info = await self.check_qps(api_key.id, effective_limit) if not qps_ok: - return False, "QPS limit exceeded", { + # 判断是套餐限额触发还是 api_key 自身限额触发 + if tenant_limit and effective_limit == tenant_limit and api_key.rate_limit > tenant_limit: + error_msg = "Tenant QPS limit exceeded" + else: + error_msg = "QPS limit exceeded" + return False, error_msg, { "X-RateLimit-Limit-QPS": str(qps_info["limit"]), "X-RateLimit-Remaining-QPS": str(qps_info["remaining"]), "X-RateLimit-Reset": str(qps_info["reset"]) From 94d2d975ee21ac2c3dc2fe8932a0b58a357e6809 Mon Sep 17 00:00:00 2001 From: lanceyq <1982376970@qq.com> Date: Mon, 20 Apr 2026 18:26:20 +0800 Subject: [PATCH 13/16] fix(memory): use end_user.workspace_id instead of app.workspace_id in log message Corrected variable reference in get_end_user_connected_config log statement. The previous code referenced app.workspace_id which could be incorrect or undefined in this context. --- api/app/services/memory_agent_service.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/api/app/services/memory_agent_service.py b/api/app/services/memory_agent_service.py index b12bb48a..335a0f8b 100644 --- a/api/app/services/memory_agent_service.py +++ b/api/app/services/memory_agent_service.py @@ -1280,7 +1280,7 @@ def get_end_user_connected_config(end_user_id: str, db: Session) -> Dict[str, An } logger.info( - f"Successfully retrieved connected config: memory_config_id={memory_config_id}, workspace_id={app.workspace_id}") + f"Successfully retrieved connected config: memory_config_id={memory_config_id}, workspace_id={end_user.workspace_id}") return result From 817aa78d0394d062e10423e0910acd063f3b524d Mon Sep 17 00:00:00 2001 From: wwq Date: Mon, 20 Apr 2026 18:34:18 +0800 Subject: [PATCH 14/16] fix(rate_limit): differentiate between tenant plan and API Key QPS limit errors - Add logic to detect tenant plan QPS limits and return a specific error message when triggered. - Simplify boolean check in model activation quota validation. --- api/app/services/api_key_service.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/api/app/services/api_key_service.py b/api/app/services/api_key_service.py index 5595e93f..53aad5ce 100644 --- a/api/app/services/api_key_service.py +++ b/api/app/services/api_key_service.py @@ -388,7 +388,7 @@ class RateLimiterService: if not qps_ok: # 判断是套餐限额触发还是 api_key 自身限额触发 if tenant_limit and effective_limit == tenant_limit and api_key.rate_limit > tenant_limit: - error_msg = "Tenant QPS limit exceeded" + error_msg = "Tenant limit exceeded" else: error_msg = "QPS limit exceeded" return False, error_msg, { From 2c2ed0ebf3703481a7bdd8a0d975ff60c988c7a0 Mon Sep 17 00:00:00 2001 From: zhaoying Date: Mon, 20 Apr 2026 18:39:59 +0800 Subject: [PATCH 15/16] fix(web): check list add vision_input --- web/src/components/ModelSelect/index.tsx | 4 ++-- web/src/i18n/en.ts | 1 + web/src/i18n/zh.ts | 1 + .../views/Workflow/components/CheckList/index.tsx | 12 ++++++++++++ 4 files changed, 16 insertions(+), 2 deletions(-) diff --git a/web/src/components/ModelSelect/index.tsx b/web/src/components/ModelSelect/index.tsx index 85977376..4c59c87b 100644 --- a/web/src/components/ModelSelect/index.tsx +++ b/web/src/components/ModelSelect/index.tsx @@ -2,7 +2,7 @@ * @Author: ZhaoYing * @Date: 2026-03-07 16:49:59 * @Last Modified by: ZhaoYing - * @Last Modified time: 2026-04-17 10:11:54 + * @Last Modified time: 2026-04-20 18:14:34 */ import { type FC, useEffect, useState } from 'react'; import { Select, Flex, Space } from 'antd'; @@ -56,7 +56,7 @@ const ModelSelect: FC = ({ params, placeholder, fontClassName, useEffect(() => { if (updateOptions) updateOptions([...options, ...initialData]); - }, [options, initialData]) + }, [JSON.stringify(options), JSON.stringify(initialData)]) return (