diff --git a/src/pages/Subscription/index.jsx b/src/pages/Subscription/index.jsx
index 09c98314..92b64304 100644
--- a/src/pages/Subscription/index.jsx
+++ b/src/pages/Subscription/index.jsx
@@ -24,6 +24,7 @@ import {
} from '../../components/console/ConsolePrimitives';
import { ConsolePageActions } from '../../components/console/ConsolePageContainer';
import React, { useCallback, useEffect, useMemo, useState } from 'react';
+import { useEffectEvent } from '../../hooks/common/useEffectEvent';
import { useTranslation } from 'react-i18next';
import { useNavigate } from 'react-router-dom';
import {
@@ -117,7 +118,9 @@ const RemainingTag = ({ endDate, status, t }) => {
let cls = 'text-xs text-gray-500';
if (days <= 3) cls = 'text-xs text-red-500 font-semibold';
else if (days <= 7) cls = 'text-xs text-amber-500 font-medium';
- return
{t('剩余 {{n}} 天', { n: days, count: days })};
+ return (
+
{t('剩余 {{n}} 天', { n: days, count: days })}
+ );
};
const Subscription = () => {
@@ -342,158 +345,152 @@ const Subscription = () => {
}
};
- const columns = useMemo(() => {
- return [
- { title: 'ID', dataIndex: 'id', width: 70 },
- {
- title: t('用户'),
- width: 180,
- render: (_, r) => {
- const display = r.display_name || '';
- const username = r.username || '';
- return (
-
-
- {display || username || `User#${r.user_id}`}
-
-
- #{r.user_id}
- {username ? ` @${username}` : ''}
-
-
- );
- },
- },
- {
- title: t('套餐'),
- width: 180,
- render: (_, r) => (
-
-
- {r.plan_name || r.plan_type}
-
- {r.tier ? (
-
- {r.tier}
-
- ) : null}
-
- ),
- },
- {
- title: t('状态'),
- dataIndex: 'status',
- width: 90,
- render: (s) => (
-
{t(s || '未知')}
- ),
- },
- {
- title: t('起始时间'),
- dataIndex: 'start_date',
- width: 110,
- render: formatDateOnly,
- },
- {
- title: t('到期时间'),
- width: 160,
- render: (_, r) => (
+ const columns = [
+ { title: 'ID', dataIndex: 'id', width: 70 },
+ {
+ title: t('用户'),
+ width: 180,
+ render: (_, r) => {
+ const display = r.display_name || '';
+ const username = r.username || '';
+ return (
- {formatDateOnly(r.end_date)}
-
+
+ {display || username || `User#${r.user_id}`}
+
+
+ #{r.user_id}
+ {username ? ` @${username}` : ''}
+
- ),
+ );
},
- {
- title: t('每日额度'),
- dataIndex: 'daily_quota',
- width: 110,
- render: (v) => renderQuota(v, 2),
- },
- {
- title: t('支付金额'),
- dataIndex: 'price_paid',
- width: 100,
- render: (v) => (v != null ? `¥${Number(v).toFixed(2)}` : '-'),
- },
- {
- title: t('操作'),
- width: 300,
- fixed: 'right',
- render: (_, r) => (
-
+ },
+ {
+ title: t('套餐'),
+ width: 180,
+ render: (_, r) => (
+
+
+ {r.plan_name || r.plan_type}
+
+ {r.tier ? (
+
+ {r.tier}
+
+ ) : null}
+
+ ),
+ },
+ {
+ title: t('状态'),
+ dataIndex: 'status',
+ width: 90,
+ render: (s) => (
+ {t(s || '未知')}
+ ),
+ },
+ {
+ title: t('起始时间'),
+ dataIndex: 'start_date',
+ width: 110,
+ render: formatDateOnly,
+ },
+ {
+ title: t('到期时间'),
+ width: 160,
+ render: (_, r) => (
+
+ {formatDateOnly(r.end_date)}
+
+
+ ),
+ },
+ {
+ title: t('每日额度'),
+ dataIndex: 'daily_quota',
+ width: 110,
+ render: (v) => renderQuota(v, 2),
+ },
+ {
+ title: t('支付金额'),
+ dataIndex: 'price_paid',
+ width: 100,
+ render: (v) => (v != null ? `¥${Number(v).toFixed(2)}` : '-'),
+ },
+ {
+ title: t('操作'),
+ width: 300,
+ fixed: 'right',
+ render: (_, r) => (
+
+
+ {admin && r.status !== 'banned' && (
- {admin && r.status !== 'banned' && (
+ )}
+ {admin && r.status === 'banned' && (
+ }
+ onClick={() => openUnban(r)}
+ >
+ {t('解封')}
+
+ )}
+ {admin && r.status !== 'canceled' && r.status !== 'banned' && (
+ }
+ onClick={() => openExtend(r)}
+ >
+ {t('延长')}
+
+ )}
+ {admin && (
+ }
+ onClick={() => openEdit(r)}
+ >
+ {t('编辑')}
+
+ )}
+ {admin && r.status === 'active' && (
+ doGrant(r)}
+ >
}
- onClick={() => openBan(r)}
+ icon={}
>
- {t('封禁')}
+ {t('补发')}
- )}
- {admin && r.status === 'banned' && (
- }
- onClick={() => openUnban(r)}
- >
- {t('解封')}
-
- )}
- {admin && r.status !== 'canceled' && r.status !== 'banned' && (
- }
- onClick={() => openExtend(r)}
- >
- {t('延长')}
-
- )}
- {admin && (
- }
- onClick={() => openEdit(r)}
- >
- {t('编辑')}
-
- )}
- {admin && r.status === 'active' && (
- doGrant(r)}
- >
- }
- >
- {t('补发')}
-
-
- )}
-
- ),
- },
- ];
- }, [t, admin]);
+
+ )}
+
+ ),
+ },
+ ];
return (
@@ -760,14 +757,15 @@ const CreateMembershipModal = ({
const [reason, setReason] = useState(() => t('管理员手动开通会员'));
const [submitting, setSubmitting] = useState(false);
+ const resetForm = useEffectEvent(() => {
+ setUserId(undefined);
+ setPlanId(undefined);
+ setDays(30);
+ setReason(t('管理员手动开通会员'));
+ });
useEffect(() => {
- if (visible) {
- setUserId(undefined);
- setPlanId(undefined);
- setDays(30);
- setReason(t('管理员手动开通会员'));
- }
- }, [visible]);
+ if (visible) resetForm();
+ }, [visible, resetForm]);
const enabledPlans = useMemo(
() => plans.filter((plan) => plan.is_enabled),
diff --git a/src/pages/Tutorial/components/VideoTutorial.css b/src/pages/Tutorial/components/VideoTutorial.css
index 62f42078..f939c391 100644
--- a/src/pages/Tutorial/components/VideoTutorial.css
+++ b/src/pages/Tutorial/components/VideoTutorial.css
@@ -123,7 +123,11 @@ Video Tutorial Component Styles
.video-retry-btn {
padding: 12px 32px;
- background: linear-gradient(135deg, var(--brand-primary), var(--brand-gradient-via));
+ background: linear-gradient(
+ 135deg,
+ var(--brand-primary),
+ var(--brand-gradient-via)
+ );
border: none;
border-radius: 14px;
color: white;
@@ -157,7 +161,8 @@ Video Tutorial Component Styles
.video-retry-btn:hover {
transform: translateY(-3px) scale(1.02);
- box-shadow: 0 12px 28px color-mix(in srgb, var(--brand-primary) 50%, transparent);
+ box-shadow: 0 12px 28px
+ color-mix(in srgb, var(--brand-primary) 50%, transparent);
}
/* 视频信息 */
@@ -240,7 +245,11 @@ Video Tutorial Component Styles
content: '';
width: 4px;
height: 20px;
- background: linear-gradient(135deg, var(--brand-primary), var(--brand-gradient-via));
+ background: linear-gradient(
+ 135deg,
+ var(--brand-primary),
+ var(--brand-gradient-via)
+ );
border-radius: 2px;
}
@@ -276,7 +285,11 @@ Video Tutorial Component Styles
left: 0;
width: 4px;
height: 100%;
- background: linear-gradient(135deg, var(--brand-primary), var(--brand-gradient-via));
+ background: linear-gradient(
+ 135deg,
+ var(--brand-primary),
+ var(--brand-gradient-via)
+ );
transform: scaleY(0);
transition: transform 0.3s ease;
border-radius: 0 4px 4px 0;
@@ -324,7 +337,11 @@ Video Tutorial Component Styles
right: 8px;
width: 24px;
height: 24px;
- background: linear-gradient(135deg, var(--brand-primary), var(--brand-gradient-via));
+ background: linear-gradient(
+ 135deg,
+ var(--brand-primary),
+ var(--brand-gradient-via)
+ );
border-radius: 50%;
display: flex;
align-items: center;
@@ -396,7 +413,8 @@ Video Tutorial Component Styles
font-size: 11px;
font-weight: 700;
color: white;
- box-shadow: 0 2px 8px color-mix(in srgb, var(--brand-primary) 40%, transparent);
+ box-shadow: 0 2px 8px
+ color-mix(in srgb, var(--brand-primary) 40%, transparent);
}
.video-list-duration {
@@ -461,9 +479,14 @@ Video Tutorial Component Styles
}
.video-tips-card:hover {
- border-color: color-mix(in srgb, var(--brand-primary) 25%, transparent) !important;
+ border-color: color-mix(
+ in srgb,
+ var(--brand-primary) 25%,
+ transparent
+ ) !important;
transform: translateY(-2px);
- box-shadow: 0 8px 24px color-mix(in srgb, var(--brand-primary) 10%, transparent);
+ box-shadow: 0 8px 24px
+ color-mix(in srgb, var(--brand-primary) 10%, transparent);
}
.video-tips-card::before {
@@ -571,7 +594,11 @@ html.dark .video-tutorial-empty {
html.dark .video-player-card {
background: var(--ui-color-bg-1);
- border-color: color-mix(in srgb, var(--brand-primary) 20%, transparent) !important;
+ border-color: color-mix(
+ in srgb,
+ var(--brand-primary) 20%,
+ transparent
+ ) !important;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
}
@@ -634,7 +661,11 @@ html.dark .video-tips-card {
color-mix(in srgb, var(--brand-primary) 10%, transparent),
color-mix(in srgb, var(--brand-gradient-via) 10%, transparent)
) !important;
- border-color: color-mix(in srgb, var(--brand-primary) 25%, transparent) !important;
+ border-color: color-mix(
+ in srgb,
+ var(--brand-primary) 25%,
+ transparent
+ ) !important;
}
html.dark .video-tips-content strong {
diff --git a/src/pages/Tutorial/components/VideoTutorial.jsx b/src/pages/Tutorial/components/VideoTutorial.jsx
index 7b539d10..0c372e7c 100644
--- a/src/pages/Tutorial/components/VideoTutorial.jsx
+++ b/src/pages/Tutorial/components/VideoTutorial.jsx
@@ -17,6 +17,7 @@ along with this program. If not, see .
For commercial licensing, please contact support@quantumnous.com
*/
+import { useEffectEvent } from '../../../hooks/common/useEffectEvent';
import React, { useState, useEffect, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import { Typography, Card, Empty, Spin, Toast } from '@/components/ui';
@@ -35,9 +36,10 @@ const VideoTutorial = () => {
const videoRef = useRef(null);
// 获取视频列表
- useEffect(() => {
+ const onMount = useEffectEvent(() => {
loadVideos();
- }, []);
+ });
+ useEffect(() => onMount(), [onMount]);
const loadVideos = async () => {
setLoading(true);
diff --git a/src/pages/Tutorial/styles.css b/src/pages/Tutorial/styles.css
index 9b467d4e..27c80940 100644
--- a/src/pages/Tutorial/styles.css
+++ b/src/pages/Tutorial/styles.css
@@ -23,7 +23,8 @@ License, or (at your option) any later version.
left: -50%;
width: 200%;
height: 200%;
- background: radial-gradient(
+ background:
+ radial-gradient(
circle at 50% 50%,
color-mix(in srgb, var(--brand-primary) 5%, transparent) 0%,
transparent 50%
@@ -1600,7 +1601,8 @@ html.dark .tutorial-card-animated:hover {
left: -50%;
width: 200%;
height: 200%;
- background: radial-gradient(
+ background:
+ radial-gradient(
circle at 30% 50%,
color-mix(in srgb, var(--brand-primary) 5%, transparent) 0%,
transparent 50%
diff --git a/src/pages/UserCenter/Invoice.jsx b/src/pages/UserCenter/Invoice.jsx
index 9ede9f2d..3ce0a0c1 100644
--- a/src/pages/UserCenter/Invoice.jsx
+++ b/src/pages/UserCenter/Invoice.jsx
@@ -32,13 +32,7 @@ import {
Empty,
Spin,
} from '@/components/ui';
-import {
- Receipt,
- Plus,
- Download,
- Eye,
- X,
-} from 'lucide-react';
+import { Receipt, Plus, Download, Eye, X } from 'lucide-react';
import UserCenterPageHeader from '../../components/common/UserCenterPageHeader';
import { API, showError, showSuccess } from '../../helpers';
import {
diff --git a/src/pages/UserCenter/UserDashboard.jsx b/src/pages/UserCenter/UserDashboard.jsx
index a130cd97..2ebea245 100644
--- a/src/pages/UserCenter/UserDashboard.jsx
+++ b/src/pages/UserCenter/UserDashboard.jsx
@@ -17,6 +17,7 @@ along with this program. If not, see .
For commercial licensing, please contact support@quantumnous.com
*/
+import { useEffectEvent } from '../../hooks/common/useEffectEvent';
import React, { useContext, useEffect, useState } from 'react';
import { Select } from 'antd';
import UserCenterPageHeader from '../../components/common/UserCenterPageHeader';
@@ -124,9 +125,10 @@ const UserDashboard = () => {
};
// ========== Effects ==========
- useEffect(() => {
+ const onMount = useEffectEvent(() => {
initChart();
- }, []);
+ });
+ useEffect(() => onMount(), [onMount]);
// ========== 公告弹窗检查 ==========
useEffect(() => {
diff --git a/src/pages/WeyAiDownload/weyai-download.css b/src/pages/WeyAiDownload/weyai-download.css
index f184ed6a..4f29ff35 100644
--- a/src/pages/WeyAiDownload/weyai-download.css
+++ b/src/pages/WeyAiDownload/weyai-download.css
@@ -19,11 +19,7 @@
transparent
);
--wd-danger: var(--ui-color-danger);
- --wd-danger-tint: color-mix(
- in srgb,
- var(--ui-color-danger) 8%,
- transparent
- );
+ --wd-danger-tint: color-mix(in srgb, var(--ui-color-danger) 8%, transparent);
position: relative;
color: var(--wd-ink);
}
@@ -155,11 +151,8 @@
overflow: hidden;
padding: 20px;
border-color: var(--wd-accent-line);
- background: radial-gradient(
- 120% 160% at 100% 0%,
- var(--wd-tint) 0%,
- transparent 55%
- ),
+ background:
+ radial-gradient(120% 160% at 100% 0%, var(--wd-tint) 0%, transparent 55%),
var(--wd-card);
}
@media (min-width: 640px) {
diff --git a/tailwind.config.js b/tailwind.config.js
index 87220124..dd9d6a73 100644
--- a/tailwind.config.js
+++ b/tailwind.config.js
@@ -59,10 +59,8 @@ export default {
'ui-color-primary-disabled': 'var(--ui-color-primary-disabled)',
'ui-color-primary-light-default':
'var(--ui-color-primary-light-default)',
- 'ui-color-primary-light-hover':
- 'var(--ui-color-primary-light-hover)',
- 'ui-color-primary-light-active':
- 'var(--ui-color-primary-light-active)',
+ 'ui-color-primary-light-hover': 'var(--ui-color-primary-light-hover)',
+ 'ui-color-primary-light-active': 'var(--ui-color-primary-light-active)',
'ui-color-secondary': 'var(--ui-color-secondary)',
'ui-color-secondary-hover': 'var(--ui-color-secondary-hover)',
'ui-color-secondary-active': 'var(--ui-color-secondary-active)',
@@ -78,8 +76,7 @@ export default {
'ui-color-tertiary-active': 'var(--ui-color-tertiary-active)',
'ui-color-tertiary-light-default':
'var(--ui-color-tertiary-light-default)',
- 'ui-color-tertiary-light-hover':
- 'var(--ui-color-tertiary-light-hover)',
+ 'ui-color-tertiary-light-hover': 'var(--ui-color-tertiary-light-hover)',
'ui-color-tertiary-light-active':
'var(--ui-color-tertiary-light-active)',
'ui-color-default': 'var(--ui-color-default)',
@@ -98,27 +95,21 @@ export default {
'ui-color-success-disabled': 'var(--ui-color-success-disabled)',
'ui-color-success-light-default':
'var(--ui-color-success-light-default)',
- 'ui-color-success-light-hover':
- 'var(--ui-color-success-light-hover)',
- 'ui-color-success-light-active':
- 'var(--ui-color-success-light-active)',
+ 'ui-color-success-light-hover': 'var(--ui-color-success-light-hover)',
+ 'ui-color-success-light-active': 'var(--ui-color-success-light-active)',
'ui-color-danger': 'var(--ui-color-danger)',
'ui-color-danger-hover': 'var(--ui-color-danger-hover)',
'ui-color-danger-active': 'var(--ui-color-danger-active)',
- 'ui-color-danger-light-default':
- 'var(--ui-color-danger-light-default)',
+ 'ui-color-danger-light-default': 'var(--ui-color-danger-light-default)',
'ui-color-danger-light-hover': 'var(--ui-color-danger-light-hover)',
- 'ui-color-danger-light-active':
- 'var(--ui-color-danger-light-active)',
+ 'ui-color-danger-light-active': 'var(--ui-color-danger-light-active)',
'ui-color-warning': 'var(--ui-color-warning)',
'ui-color-warning-hover': 'var(--ui-color-warning-hover)',
'ui-color-warning-active': 'var(--ui-color-warning-active)',
'ui-color-warning-light-default':
'var(--ui-color-warning-light-default)',
- 'ui-color-warning-light-hover':
- 'var(--ui-color-warning-light-hover)',
- 'ui-color-warning-light-active':
- 'var(--ui-color-warning-light-active)',
+ 'ui-color-warning-light-hover': 'var(--ui-color-warning-light-hover)',
+ 'ui-color-warning-light-active': 'var(--ui-color-warning-light-active)',
'ui-color-focus-border': 'var(--ui-color-focus-border)',
'ui-color-disabled-text': 'var(--ui-color-disabled-text)',
'ui-color-disabled-border': 'var(--ui-color-disabled-border)',
@@ -168,8 +159,7 @@ export default {
'ui-color-data-19': 'var(--ui-color-data-19)',
},
borderRadius: {
- 'ui-border-radius-extra-small':
- 'var(--ui-border-radius-extra-small)',
+ 'ui-border-radius-extra-small': 'var(--ui-border-radius-extra-small)',
'ui-border-radius-small': 'var(--ui-border-radius-small)',
'ui-border-radius-medium': 'var(--ui-border-radius-medium)',
'ui-border-radius-large': 'var(--ui-border-radius-large)',
diff --git a/test/unit/effect-events.test.js b/test/unit/effect-events.test.js
new file mode 100644
index 00000000..74626a97
--- /dev/null
+++ b/test/unit/effect-events.test.js
@@ -0,0 +1,142 @@
+/*
+Copyright (C) 2025 QuantumNous
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or (at your option) any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see .
+
+For commercial licensing, please contact support@quantumnous.com
+*/
+
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { setImmediate } from 'node:timers/promises';
+import React from 'react';
+import { createHookRuntime } from './helpers/hookRuntime.js';
+import { loadFrontendModule } from './helpers/frontendModule.js';
+
+async function harness() {
+ const runtime = createHookRuntime();
+ const { useEffectEvent } = await loadFrontendModule(
+ new URL('../../src/hooks/common/useEffectEvent.js', import.meta.url),
+ { react: runtime.react },
+ );
+ return { runtime, useEffectEvent };
+}
+
+test('effect events keep identity and only expose the latest committed callback', async () => {
+ const { runtime, useEffectEvent } = await harness();
+ const Component = ({ value }) => useEffectEvent((extra) => value + extra);
+ const first = runtime.render(Component, { value: 1 });
+ runtime.commit();
+ assert.equal(first(2), 3);
+ const updated = runtime.render(Component, { value: 10 });
+ assert.equal(updated, first);
+ assert.equal(
+ first(2),
+ 3,
+ 'An uncommitted render must not leak to external handlers',
+ );
+ runtime.commit();
+ assert.equal(first(2), 12);
+});
+
+test('explicit scope changes run once and cleanup keeps its original resource', async () => {
+ const { runtime, useEffectEvent } = await harness();
+ const calls = [];
+ const cleanups = [];
+ const Component = ({ scope, draft }) => {
+ const onChange = useEffectEvent(() => {
+ calls.push([scope, draft]);
+ return () => cleanups.push(scope);
+ });
+ runtime.react.useEffect(() => onChange(), [onChange, scope]);
+ };
+ runtime.render(Component, { scope: 1, draft: 'a' });
+ runtime.flush();
+ runtime.render(Component, { scope: 1, draft: 'b' });
+ runtime.flush();
+ assert.deepEqual(
+ calls,
+ [[1, 'a']],
+ 'Editing a draft must not reinitialize the form',
+ );
+ runtime.render(Component, { scope: 2, draft: 'b' });
+ runtime.flush();
+ assert.deepEqual(calls, [
+ [1, 'a'],
+ [2, 'b'],
+ ]);
+ assert.deepEqual(cleanups, [1]);
+ runtime.unmount();
+ assert.deepEqual(cleanups, [1, 2]);
+});
+
+test('event callbacks preserve return values, async results, and errors', async () => {
+ const { runtime, useEffectEvent } = await harness();
+ const AsyncComponent = () => useEffectEvent(async (value) => value * 2);
+ const asyncEvent = runtime.render(AsyncComponent);
+ runtime.commit();
+ assert.equal(await asyncEvent(4), 8);
+ const ThrowingComponent = () =>
+ useEffectEvent(() => {
+ throw new Error('expected failure');
+ });
+ runtime.render(ThrowingComponent);
+ runtime.commit();
+ assert.throws(asyncEvent, /expected failure/);
+});
+
+test('settings mount and manual refresh settle without repeated option requests', async () => {
+ const { runtime, useEffectEvent } = await harness();
+ const requests = [];
+ const { default: Settings } = await loadFrontendModule(
+ new URL('../../src/components/settings/ChatsSetting.jsx', import.meta.url),
+ {
+ react: runtime.react,
+ '../../hooks/common/useEffectEvent': { useEffectEvent },
+ '@/components/ui': { Card: 'Card', Spin: 'Spin' },
+ 'react-i18next': { useTranslation: () => ({ t: (key) => key }) },
+ '../../pages/Setting/Chat/SettingsChats': {
+ default: 'SettingsChats',
+ __esModule: true,
+ },
+ '../../helpers': {
+ API: {
+ get: async (url) => {
+ requests.push(url);
+ return {
+ data: { success: true, data: [{ key: 'Chats', value: '[]' }] },
+ };
+ },
+ },
+ showError: assert.fail,
+ toBoolean: (value) => value === 'true',
+ },
+ },
+ );
+ runtime.render(Settings);
+ runtime.flush();
+ await setImmediate();
+ let tree = runtime.flush();
+ assert.deepEqual(requests, ['/api/option/']);
+ const find = (node) =>
+ React.isValidElement(node)
+ ? node.type === 'SettingsChats'
+ ? node
+ : React.Children.toArray(node.props.children).map(find).find(Boolean)
+ : undefined;
+ await find(tree).props.refresh();
+ tree = runtime.flush();
+ assert.deepEqual(requests, ['/api/option/', '/api/option/']);
+ assert.equal(find(tree).props.options.Chats, '[]');
+});
diff --git a/test/unit/fixtures/unpaginated-tables.json b/test/unit/fixtures/unpaginated-tables.json
new file mode 100644
index 00000000..946b261b
--- /dev/null
+++ b/test/unit/fixtures/unpaginated-tables.json
@@ -0,0 +1,16 @@
+{
+ "src/pages/AdminOrganizations/index.jsx": 1,
+ "src/pages/AdminInvoice/index.jsx": 1,
+ "src/components/settings/DataSecuritySetting.jsx": 4,
+ "src/pages/Organization/OrgPrivateSkills.jsx": 2,
+ "src/pages/Organization/OrgSkillAssignments.jsx": 1,
+ "src/pages/Organization/OrgEffectiveness.jsx": 4,
+ "src/pages/Organization/OrgMemberAccounts.jsx": 1,
+ "src/pages/Organization/OrgDeptManage.jsx": 2,
+ "src/pages/Organization/OrgProjectManage.jsx": 1,
+ "src/pages/Organization/OrgProjects.jsx": 2,
+ "src/pages/Organization/OrgBudgets.jsx": 1,
+ "src/pages/Organization/OrgLogs.jsx": 1,
+ "src/pages/Organization/components/OrgTaskRecords.jsx": 1,
+ "src/pages/Organization/datasecurity/OrgDsRules.jsx": 2
+}
diff --git a/test/unit/helpers/frontendModule.js b/test/unit/helpers/frontendModule.js
new file mode 100644
index 00000000..784c95d0
--- /dev/null
+++ b/test/unit/helpers/frontendModule.js
@@ -0,0 +1,45 @@
+/*
+Copyright (C) 2025 QuantumNous
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or (at your option) any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see .
+
+For commercial licensing, please contact support@quantumnous.com
+*/
+
+import assert from 'node:assert/strict';
+import { readFile } from 'node:fs/promises';
+import { transformWithEsbuild } from 'vite';
+
+export async function loadFrontendModule(filename, mocks) {
+ const { code } = await transformWithEsbuild(
+ await readFile(filename, 'utf8'),
+ filename.pathname,
+ {
+ loader: 'jsx',
+ format: 'cjs',
+ jsx: 'transform',
+ define: { 'import.meta.env': '{}' },
+ },
+ );
+ const module = { exports: {} };
+ new Function('require', 'module', 'exports', code)(
+ (name) => {
+ assert.ok(Object.hasOwn(mocks, name), 'Missing test dependency: ' + name);
+ return mocks[name];
+ },
+ module,
+ module.exports,
+ );
+ return module.exports;
+}
diff --git a/test/unit/helpers/hookRuntime.js b/test/unit/helpers/hookRuntime.js
new file mode 100644
index 00000000..7d8eecae
--- /dev/null
+++ b/test/unit/helpers/hookRuntime.js
@@ -0,0 +1,107 @@
+/*
+Copyright (C) 2025 QuantumNous
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or (at your option) any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see .
+
+For commercial licensing, please contact support@quantumnous.com
+*/
+
+import assert from 'node:assert/strict';
+import React from 'react';
+
+// A deterministic controller harness, not a replacement for React's DOM scheduler.
+export function createHookRuntime() {
+ const slots = [];
+ let cursor = 0;
+ let dirty = false;
+ let renderCurrent;
+ let output;
+ let pending = [];
+ const changed = (before, after) =>
+ !before ||
+ !after ||
+ before.length !== after.length ||
+ after.some((v, i) => !Object.is(v, before[i]));
+ const react = {
+ ...React,
+ useState(initial) {
+ const index = cursor++;
+ if (!slots[index]) {
+ const slot = {
+ value: typeof initial === 'function' ? initial() : initial,
+ };
+ slot.set = (next) => {
+ const value = typeof next === 'function' ? next(slot.value) : next;
+ if (!Object.is(value, slot.value)) {
+ slot.value = value;
+ dirty = true;
+ }
+ };
+ slots[index] = slot;
+ }
+ return [slots[index].value, slots[index].set];
+ },
+ useRef(initial) {
+ const index = cursor++;
+ slots[index] ??= { current: initial };
+ return slots[index];
+ },
+ useMemo(factory, dependencies) {
+ const index = cursor++;
+ if (changed(slots[index]?.dependencies, dependencies))
+ slots[index] = { value: factory(), dependencies };
+ return slots[index].value;
+ },
+ useCallback(callback, dependencies) {
+ return react.useMemo(() => callback, dependencies);
+ },
+ useEffect(callback, dependencies) {
+ const index = cursor++;
+ if (changed(slots[index]?.dependencies, dependencies))
+ pending.push({ index, callback, dependencies });
+ },
+ };
+ react.useLayoutEffect = react.useEffect;
+ const runtime = {
+ react,
+ render(component, props = {}) {
+ cursor = 0;
+ pending = [];
+ dirty = false;
+ renderCurrent = () => runtime.render(component, props);
+ output = component(props);
+ return output;
+ },
+ commit() {
+ const effects = pending;
+ pending = [];
+ for (const { index, callback, dependencies } of effects) {
+ slots[index]?.cleanup?.();
+ slots[index] = { dependencies, cleanup: callback() };
+ }
+ },
+ flush() {
+ for (let i = 0; ; i++) {
+ assert.ok(i < 20, 'Effects must settle without a render/request loop');
+ runtime.commit();
+ if (!dirty) return output;
+ renderCurrent();
+ }
+ },
+ unmount() {
+ for (const slot of slots) slot?.cleanup?.();
+ },
+ };
+ return runtime;
+}
diff --git a/test/unit/model-local-pagination.test.js b/test/unit/model-local-pagination.test.js
new file mode 100644
index 00000000..15c39237
--- /dev/null
+++ b/test/unit/model-local-pagination.test.js
@@ -0,0 +1,234 @@
+/*
+Copyright (C) 2025 QuantumNous
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or (at your option) any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see .
+
+For commercial licensing, please contact support@quantumnous.com
+*/
+
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import React from 'react';
+import { renderToStaticMarkup } from 'react-dom/server';
+import { Table as AntTable } from 'antd';
+import { loadFrontendModule } from './helpers/frontendModule.js';
+
+async function fixture(kind) {
+ const calls = [];
+ const models = Array.from(
+ { length: 24 },
+ (_, i) => 'aa-' + String(i + 1).padStart(2, '0'),
+ );
+ const states =
+ kind === 'Missing' ? [5, false, models, 'AA', 2] : [5, {}, 2, 'AA'];
+ let cursor = 0;
+ const react = {
+ ...React,
+ useEffect: () => {},
+ useMemo: (fn) => fn(),
+ useCallback: (fn) => fn,
+ useState: () => {
+ const index = cursor++;
+ return [states[index], (value) => calls.push([index, value])];
+ },
+ };
+ const ui = {
+ ...Object.fromEntries(
+ [
+ 'Modal',
+ 'Table',
+ 'Spin',
+ 'Button',
+ 'Empty',
+ 'Input',
+ 'Checkbox',
+ 'Tag',
+ 'Popover',
+ ].map((name) => [name, name]),
+ ),
+ Typography: { Text: 'Text' },
+ };
+ const file =
+ kind === 'Missing' ? 'MissingModelsModal' : 'UpstreamConflictModal';
+ const { default: Component } = await loadFrontendModule(
+ new URL(
+ '../../src/components/table/models/modals/' + file + '.jsx',
+ import.meta.url,
+ ),
+ {
+ react,
+ '@/components/ui': ui,
+ '../../../../hooks/common/useEffectEvent': {
+ useEffectEvent: (callback) => callback,
+ },
+ '../../../../hooks/common/useIsMobile': { useIsMobile: () => false },
+ '../../../../constants': { MODEL_TABLE_PAGE_SIZE: 10 },
+ '../../../../helpers': {
+ API: {
+ get: () => assert.fail('Local pagination must not send requests'),
+ },
+ showError: assert.fail,
+ hoverOrClickTrigger: () => 'hover',
+ },
+ '../../../common/illustrations': {
+ IllustrationNoResult: 'Illustration',
+ IllustrationNoResultDark: 'Illustration',
+ },
+ '@/components/ui/icons': { IconSearch: 'Search' },
+ 'lucide-react': { MousePointerClick: 'Pointer' },
+ },
+ );
+ const tree = Component({
+ visible: true,
+ t: (key) => key,
+ conflicts: models.map((model_name) => ({ model_name, fields: [] })),
+ });
+ const find = (type, node = tree) =>
+ React.isValidElement(node)
+ ? [
+ ...(node.type === type ? [node] : []),
+ ...React.Children.toArray(node.props.children).flatMap((child) =>
+ find(type, child),
+ ),
+ ]
+ : [];
+ return {
+ calls,
+ models,
+ table: find('Table')[0].props,
+ input: find('Input')[0].props,
+ };
+}
+
+for (const kind of ['Missing', 'Upstream']) {
+ test(
+ kind + ': case-insensitive local filtering uses selected page and size',
+ async () => {
+ const { table, models } = await fixture(kind);
+ assert.deepEqual(
+ Array.from(table.dataSource, (row) => row.model || row.model_name),
+ models.slice(5, 10),
+ );
+ assert.equal(table.pagination.total, 24);
+ assert.equal(table.pagination.pageSize, 5);
+ assert.equal(table.pagination.currentPage, 2);
+ },
+ );
+ test(
+ kind +
+ ': search and size changes reset the current page without network calls',
+ async () => {
+ const { calls, table, input } = await fixture(kind);
+ table.pagination.onPageSizeChange(20);
+ assert.ok(calls.some(([, value]) => value === 1));
+ assert.ok(calls.some(([, value]) => value === 20));
+ calls.length = 0;
+ input.onChange('aa-24');
+ assert.ok(calls.some(([, value]) => value === 'aa-24'));
+ assert.ok(calls.some(([, value]) => value === 1));
+ },
+ );
+}
+
+async function modelTestFixture() {
+ const calls = [];
+ const models = Array.from({ length: 24 }, (_, index) => `aa-${index + 1}`);
+ const { default: Component } = await loadFrontendModule(
+ new URL(
+ '../../src/components/table/channels/modals/ModelTestModal.jsx',
+ import.meta.url,
+ ),
+ {
+ react: {
+ ...React,
+ useState: () => [5, (value) => calls.push(['size', value])],
+ },
+ antd: {
+ ...Object.fromEntries(
+ ['Modal', 'Button', 'Input', 'Table', 'Tag', 'Select'].map((name) => [
+ name,
+ name,
+ ]),
+ ),
+ Typography: { Text: 'Text' },
+ },
+ 'lucide-react': { Search: 'Search' },
+ './model-test-modal.css': {},
+ '../../../../helpers': {},
+ '../../../../constants': { MODEL_TABLE_PAGE_SIZE: 10 },
+ },
+ );
+ const tree = Component({
+ currentTestChannel: { id: 7, name: 'channel', models: models.join(',') },
+ modelSearchKeyword: 'AA',
+ modelTablePage: 2,
+ selectedModelKeys: [],
+ modelTestResults: {},
+ testingModels: new Set(),
+ setModelTablePage: (value) => calls.push(['page', value]),
+ setModelSearchKeyword: (value) => calls.push(['search', value]),
+ t: (key) => key,
+ });
+ const find = (type, node = tree) =>
+ React.isValidElement(node)
+ ? [
+ ...(node.type === type ? [node] : []),
+ ...React.Children.toArray(node.props.children).flatMap((child) =>
+ find(type, child),
+ ),
+ ]
+ : [];
+ return {
+ calls,
+ models,
+ table: find('Table')[0].props,
+ input: find('Input')[0].props,
+ };
+}
+
+test('Model test dialog passes the complete filtered list to native Ant pagination', async () => {
+ const { table, models } = await modelTestFixture();
+ assert.deepEqual(
+ Array.from(table.dataSource, (row) => row.model),
+ models,
+ );
+ assert.equal(table.pagination.total, 24);
+ assert.equal(table.pagination.current, 2);
+ assert.equal(table.pagination.pageSize, 5);
+ const html = renderToStaticMarkup(React.createElement(AntTable, table));
+ assert.deepEqual(
+ Array.from(html.matchAll(/data-row-key="([^"]+)"/g), (match) => match[1]),
+ models.slice(5, 10),
+ 'Ant Table renders only the selected page, with no second manual slice',
+ );
+});
+
+test('Model test dialog preserves page changes and resets after search or size changes', async () => {
+ const { calls, table, input } = await modelTestFixture();
+ table.pagination.onChange(3, 5);
+ assert.deepEqual(calls.splice(0), [
+ ['page', 3],
+ ['size', 5],
+ ]);
+ table.pagination.onChange(3, 20);
+ assert.deepEqual(calls.splice(0), [
+ ['page', 1],
+ ['size', 20],
+ ]);
+ input.onChange({ target: { value: 'aa-24' } });
+ assert.deepEqual(calls, [
+ ['search', 'aa-24'],
+ ['page', 1],
+ ]);
+});
diff --git a/test/unit/pagination.test.js b/test/unit/pagination.test.js
new file mode 100644
index 00000000..8fd3b821
--- /dev/null
+++ b/test/unit/pagination.test.js
@@ -0,0 +1,555 @@
+/*
+Copyright (C) 2025 QuantumNous
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or (at your option) any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see .
+
+For commercial licensing, please contact support@quantumnous.com
+*/
+
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import fs from 'node:fs/promises';
+import { runInNewContext } from 'node:vm';
+import { parse } from '@babel/parser';
+import React from 'react';
+import { renderToStaticMarkup } from 'react-dom/server';
+import * as Ant from 'antd';
+import { transformWithEsbuild } from 'vite';
+import i18next from 'i18next';
+import * as pagination from '../../src/components/ui/pagination.js';
+
+await i18next.init({
+ lng: 'zh',
+ initImmediate: false,
+ resources: { zh: { translation: { '共 {{total}} 条': '共 {{total}} 条' } } },
+});
+const walk = (node, visit) => {
+ if (!node || typeof node !== 'object') return;
+ if (node.type) visit(node);
+ for (const [key, val] of Object.entries(node))
+ if (!['loc', 'start', 'end'].includes(key)) {
+ if (Array.isArray(val)) val.forEach((n) => walk(n, visit));
+ else if (val && typeof val === 'object') walk(val, visit);
+ }
+};
+async function callback(file, name, rootName) {
+ const source = await fs.readFile(file, 'utf8');
+ const ast = parse(source, { sourceType: 'module', plugins: ['jsx'] });
+ let root = ast;
+ if (rootName)
+ walk(ast, (n) => {
+ if (n.type === 'FunctionDeclaration' && n.id?.name === rootName) root = n;
+ });
+ let found;
+ walk(root, (n) => {
+ if (!found && n.type === 'VariableDeclarator' && n.id.name === name)
+ found =
+ n.init?.callee?.name === 'useCallback' ? n.init.arguments[0] : n.init;
+ });
+ assert.ok(found, `${file}: ${name} exists`);
+ return { source: source.slice(found.start, found.end), root, text: source };
+}
+const sentinel = { id: 42, name: 'pagination-fixture' };
+async function exercise(
+ {
+ file,
+ fn,
+ root,
+ args = [],
+ expectedPath,
+ expectedSize = 50,
+ expectedPage = 3,
+ pageKey = 'p',
+ values = {},
+ },
+ failure = false,
+) {
+ const { source, root: ast } = await callback(file, fn, root);
+ const states = {},
+ calls = [],
+ errors = [];
+ const context = {
+ URLSearchParams,
+ Date,
+ Promise,
+ console: { error() {} },
+ page: 3,
+ pageSize: 50,
+ orgId: 77,
+ pageSizeRef: { current: 50 },
+ requestSeq: { current: 0 },
+ seqRef: { current: 0 },
+ orgRef: { current: 77 },
+ fetchSeqRef: { current: 0 },
+ searchKeyword: 'pagination-fixture',
+ appliedKeyword: 'pagination-fixture',
+ appliedOrderId: 42,
+ appliedUserId: 7,
+ statusFilter: '',
+ paymentMethodFilter: '',
+ dateRange: [],
+ appliedMinMoney: undefined,
+ appliedMaxMoney: undefined,
+ levelFilter: '',
+ salesRepFilter: '',
+ alertFilter: '',
+ userIdFilter: '',
+ sortBy: '',
+ sortOrder: '',
+ endDateRange: [],
+ quickFilter: '',
+ planTypes: [],
+ tiers: [],
+ statuses: [],
+ sources: [],
+ getOrgHeaders: (id) => ({ 'X-Org-Id': String(id) }),
+ t: (key) => key,
+ showError: (e) => errors.push(e),
+ getFormValues: () => ({
+ username: '',
+ token_name: '',
+ model_name: '',
+ start_timestamp: '2026-11-02 00:00:00',
+ end_timestamp: '2026-11-07 23:44:54',
+ channel: '',
+ group: '',
+ user_id: '',
+ logType: 0,
+ channel_id: '',
+ mj_id: '',
+ }),
+ isAdminUser: true,
+ listRequestIdRef: { current: 0 },
+ logsRequestIdRef: { current: 0 },
+ appliedExportParamsRef: { current: {} },
+ ...values,
+ API: {
+ get: async (url, options = {}) => {
+ calls.push({ url, options });
+ if (failure) throw new Error('simulated pagination failure');
+ return {
+ data: {
+ success: true,
+ data: {
+ items: [sentinel],
+ list: [sentinel],
+ total: 156,
+ page: expectedPage,
+ page_size: expectedSize,
+ requests: { items: [sentinel], total: 156 },
+ audits: { items: [sentinel], total: 156 },
+ },
+ },
+ };
+ },
+ },
+ };
+ walk(ast, (n) => {
+ if (n.type === 'Identifier' && /^set[A-Z]/.test(n.name))
+ context[n.name] ||= (val) => {
+ states[n.name] = typeof val === 'function' ? val(states[n.name]) : val;
+ };
+ });
+ const run = runInNewContext(`(${source})`, context);
+ await run(...args);
+ assert.ok(calls.length > 0, 'Uses the existing API wrapper');
+ const request = calls.find((c) => c.url.startsWith(expectedPath));
+ assert.ok(request, `${expectedPath} requested`);
+ const u = new URL(request.url, 'http://localhost');
+ const params = {
+ ...Object.fromEntries(u.searchParams),
+ ...request.options.params,
+ };
+ assert.equal(
+ Number(params.page_size),
+ expectedSize,
+ 'Selected page size reaches API',
+ );
+ assert.equal(
+ Number(params[pageKey]),
+ expectedPage,
+ 'Requested page reaches API without changing indexing',
+ );
+ if (failure) {
+ if ('setLoading' in states)
+ assert.equal(states.setLoading, false, 'Failure releases loading');
+ assert.ok(
+ errors.length > 0 || Boolean(states.setError),
+ 'Failure is reported by a message or inline error',
+ );
+ } else if ('setTotal' in states)
+ assert.equal(states.setTotal, 156, 'Response total maps to pagination');
+ return { calls, states, errors };
+}
+
+for (const cfg of [
+ {
+ file: 'src/pages/AdminOrder/index.jsx',
+ fn: 'fetchOrders',
+ expectedPath: '/api/order/search',
+ },
+ {
+ file: 'src/pages/AdminInvoice/index.jsx',
+ fn: 'fetchInvoices',
+ expectedPath: '/api/invoice/list',
+ },
+ {
+ file: 'src/pages/AdminOrganizations/index.jsx',
+ fn: 'fetchOrgs',
+ expectedPath: '/api/admin/organizations',
+ },
+ {
+ file: 'src/pages/Subscription/index.jsx',
+ fn: 'fetchList',
+ expectedPath: '/api/user/membership/manage/subscriptions',
+ pageKey: 'page',
+ },
+ {
+ file: 'src/hooks/org/useOrgMembers.js',
+ fn: 'fetch',
+ root: 'useOrgMembers',
+ args: [3, 50],
+ expectedPath: '/api/org/members',
+ },
+ {
+ file: 'src/hooks/org/useOrgData.js',
+ fn: 'fetch',
+ root: 'useOrgTokens',
+ args: [3, 50],
+ expectedPath: '/api/org/tokens',
+ },
+ {
+ file: 'src/hooks/org/useOrgData.js',
+ fn: 'fetch',
+ root: 'useOrgAuditLogs',
+ args: [3, 50, ''],
+ expectedPath: '/api/org/audit',
+ values: { seqRef: { current: 0 }, orgRef: { current: 77 } },
+ },
+ {
+ file: 'src/hooks/org/useOrgData.js',
+ fn: 'fetch',
+ root: 'useOrgPromptRecords',
+ args: [3, 50, {}],
+ expectedPath: '/api/org/prompt-archive/records',
+ values: { seqRef: { current: 0 } },
+ },
+ {
+ file: 'src/hooks/org/useOrgData.js',
+ fn: 'fetch',
+ root: 'useOrgMemberLogs',
+ args: [3, 50, {}],
+ expectedPath: '/api/org/logs',
+ values: { buildOrgLogFilters: (x) => x },
+ },
+ {
+ file: 'src/pages/Organization/OrgRecharge.jsx',
+ fn: 'fetchHistory',
+ args: [3],
+ expectedPath: '/api/org/topup',
+ values: { historyPageSize: 50, orgHeaders: { 'X-Org-Id': '77' } },
+ },
+ {
+ file: 'src/pages/Organization/OrgDashboard.jsx',
+ fn: 'fetchLogs',
+ args: [3, {}, 50],
+ expectedPath: '/api/org/logs',
+ values: { member: { user_id: 9 }, appliedFilters: {} },
+ },
+ {
+ file: 'src/pages/Organization/datasecurity/OrgDsChanges.jsx',
+ fn: 'fetchChanges',
+ args: [{ reqP: 3, auditP: 2, section: 'requests' }],
+ expectedPath: '/api/org/data-security/changes',
+ pageKey: 'page',
+ values: {
+ reqSizeRef: { current: 50 },
+ auditSizeRef: { current: 20 },
+ headers: {},
+ },
+ },
+ {
+ file: 'src/pages/Organization/datasecurity/OrgDsChanges.jsx',
+ fn: 'fetchChanges',
+ args: [{ reqP: 1, auditP: 3, section: 'audits' }],
+ expectedPath: '/api/org/data-security/changes',
+ pageKey: 'page',
+ values: {
+ reqSizeRef: { current: 20 },
+ auditSizeRef: { current: 50 },
+ headers: {},
+ },
+ },
+ {
+ file: 'src/pages/Setting/Payment/SettingsPaymentGatewayPayPal.jsx',
+ fn: 'refreshFeePolicy',
+ args: [3, true],
+ expectedPath: '/api/option/paypal/fee-policy/audits',
+ values: { isRoot: () => true, feeAuditSizeRef: { current: 50 } },
+ },
+ {
+ file: 'src/pages/Setting/Payment/SettingsPaymentGatewayPayPal.jsx',
+ fn: 'refreshOperations',
+ args: [3],
+ expectedPath: '/api/option/paypal/operations/preflight',
+ values: {
+ isRoot: () => true,
+ operationsSizeRef: { current: 50 },
+ normalizePayPalOperations: (d) => d,
+ },
+ },
+ {
+ file: 'src/hooks/analytics/useRiskControlData.js',
+ fn: 'fetchBanLogs',
+ args: [{ page: 3, pageSize: 50 }],
+ expectedPath: '/api/analytics/risk/ban-logs',
+ pageKey: 'page',
+ values: { banLogStatus: 0, banLogPage: 1, banLogPageSize: 20 },
+ },
+ ...[
+ ['loadAudits', 'audit', '/api/desensitize/config-audit'],
+ ['loadHitLogs', 'hitLog', '/api/desensitize/logs'],
+ ['loadChangeRequests', 'changeReq', '/api/desensitize/change-requests'],
+ ].map(([fn, name, expectedPath]) => ({
+ file: 'src/components/settings/DataSecuritySetting.jsx',
+ fn,
+ args: [3],
+ expectedPath,
+ pageKey: 'page',
+ values: { [`${name}PageSize`]: 50 },
+ })),
+ {
+ file: 'src/pages/Organization/datasecurity/OrgDsHitLogs.jsx',
+ fn: 'fetchLogs',
+ args: [3, false],
+ expectedPath: '/api/org/data-security/logs',
+ pageKey: 'page',
+ values: {
+ logsSeqRef: { current: 0 },
+ lastAttemptedPageRef: { current: 1 },
+ headers: {},
+ },
+ },
+ {
+ file: 'src/hooks/usage-logs/useUsageLogsData.jsx',
+ fn: 'loadLogs',
+ args: [3, 50],
+ expectedPath: '/api/log/',
+ values: { setLogsFormat: () => {} },
+ },
+ {
+ file: 'src/hooks/mj-logs/useMjLogsData.js',
+ fn: 'loadLogs',
+ args: [3, 50],
+ expectedPath: '/api/mj/',
+ values: { syncPageData: () => {} },
+ },
+]) {
+ test(`${cfg.file}: selected page and size use existing request contract`, () =>
+ exercise(cfg));
+ test(`${cfg.file}: network failure exits loading and reports error`, () =>
+ exercise(cfg, true));
+}
+
+test('Resizing emits one size callback and never a stale page request', () => {
+ const calls = [];
+ const events = pagination.centerPaginationEvents({
+ pageSize: 10,
+ onPageSizeChange: (s) => calls.push(['size', s]),
+ onPageChange: (p) => calls.push(['page', p]),
+ onChange: (p, s) => calls.push(['change', p, s]),
+ });
+ events.onChange(3, 50);
+ assert.deepEqual(calls, [['size', 50]]);
+ events.onChange(2, 10);
+ assert.deepEqual(calls.slice(1), [
+ ['page', 2],
+ ['change', 2, 10],
+ ]);
+});
+test('Legacy Ant resize handlers receive page one exactly once', () => {
+ const calls = [];
+ pagination
+ .centerPaginationEvents({
+ pageSize: 10,
+ onShowSizeChange: (p, s) => calls.push([p, s]),
+ onChange: () => calls.push('duplicate'),
+ })
+ .onChange(4, 20);
+ assert.deepEqual(calls, [[1, 20]]);
+});
+test('Desktop and mobile share size options and translated totals; only mobile has jump input', () => {
+ for (const mobile of [false, true]) {
+ const opts = pagination.centerPaginationOptions({}, mobile);
+ assert.equal(opts.size, 'small');
+ assert.equal(opts.showTotal(156), '共 156 条');
+ assert.equal(opts.showQuickJumper, mobile);
+ assert.deepEqual(opts.pageSizeOptions, [10, 20, 50, 100]);
+ }
+});
+
+const uiFile = 'src/components/ui/index.jsx';
+const transformed = await transformWithEsbuild(
+ await fs.readFile(uiFile, 'utf8'),
+ uiFile,
+ { loader: 'jsx', format: 'cjs', target: 'node22', jsx: 'transform' },
+);
+const modules = {
+ './pagination.css': {},
+ '../../hooks/common/useIsMobile': { useIsMobile: () => false },
+ react: React,
+ antd: Ant,
+ './controls': { controlSize: (s) => s },
+ './pagination': pagination,
+ './overlayPolicy': {},
+ './form': {},
+ './chat': {},
+ '../console/ConsoleContext': { useConsolePage: () => null },
+ '../console/ConsolePrimitives': {},
+ '../console/consoleTableAdapter': {},
+};
+const module = { exports: {} };
+runInNewContext(transformed.code, {
+ module,
+ exports: module.exports,
+ window: { matchMedia: () => ({ matches: false }) },
+ require(name) {
+ assert.ok(name in modules, name);
+ return modules[name];
+ },
+});
+const { Table } = module.exports;
+test('Tables with pagination false or omitted never gain a paginator', () => {
+ for (const config of [false, undefined]) {
+ const el = Table({
+ pagination: config,
+ columns: [{ dataIndex: 'id' }],
+ dataSource: [sentinel],
+ });
+ assert.equal(el.props.pagination, false);
+ assert.doesNotMatch(renderToStaticMarkup(el), /ant-pagination/);
+ }
+});
+
+test('Existing unpaginated tables keep pagination disabled after other UI edits', async () => {
+ const expected = JSON.parse(
+ await fs.readFile(
+ new URL('./fixtures/unpaginated-tables.json', import.meta.url),
+ 'utf8',
+ ),
+ );
+ let compared = 0;
+ for (const [file, count] of Object.entries(expected)) {
+ const ast = parse(await fs.readFile(file, 'utf8'), {
+ sourceType: 'module',
+ plugins: ['jsx'],
+ });
+ let actual = 0;
+ walk(ast, (node) => {
+ if (
+ node.type !== 'JSXOpeningElement' ||
+ !/Table$/.test(node.name.name || '')
+ )
+ return;
+ if (
+ node.attributes.some(
+ (attr) =>
+ attr.name?.name === 'pagination' &&
+ attr.value?.expression?.value === false,
+ )
+ )
+ actual++;
+ });
+ assert.equal(actual, count, file + ': unpaginated table count');
+ compared += actual;
+ }
+ assert.ok(compared > 20, 'Covers the original unpaginated tables');
+});
+
+test('Visual model editor keeps frontend filtering and supports size reset', async () => {
+ const file = 'src/pages/Setting/Ratio/ModelSettingsVisualEditor.jsx';
+ const after = await fs.readFile(file, 'utf8');
+ const calls = [];
+ walk(parse(after, { sourceType: 'module', plugins: ['jsx'] }), (node) => {
+ if (node.type === 'CallExpression' && node.callee.object?.name === 'API')
+ calls.push(node);
+ });
+ assert.equal(calls.length, 1, 'Only the existing save request is present');
+ assert.equal(calls[0].callee.property.name, 'put');
+ assert.equal(calls[0].arguments[0].value, '/api/option/');
+ assert.match(after, /\[pageSize, setPageSize\] = useState\(10\)/);
+ assert.match(
+ after,
+ /onPageSizeChange: \(size\) => \{\s*setPageSize\(size\);\s*setCurrentPage\(1\);/,
+ );
+});
+
+test('Multi-key read pagination preserves existing POST action and response fields', async () => {
+ const { source } = await callback(
+ 'src/components/table/channels/modals/MultiKeyManageModal.jsx',
+ 'loadKeyStatus',
+ );
+ const calls = [],
+ states = {};
+ const context = {
+ channel: { id: 7 },
+ currentPage: 3,
+ pageSize: 50,
+ statusFilter: 1,
+ API: {
+ post: async (path, data) => {
+ calls.push({ path, data });
+ return {
+ data: {
+ success: true,
+ data: {
+ keys: [sentinel],
+ total: 156,
+ page: 3,
+ page_size: 50,
+ total_pages: 4,
+ },
+ },
+ };
+ },
+ },
+ setLoading: (x) => {
+ states.loading = x;
+ },
+ setKeyStatusList: (x) => {
+ states.rows = x;
+ },
+ setTotal: (x) => {
+ states.total = x;
+ },
+ setCurrentPage: () => {},
+ setPageSize: () => {},
+ setTotalPages: () => {},
+ setEnabledCount: () => {},
+ setManualDisabledCount: () => {},
+ setAutoDisabledCount: () => {},
+ showError: assert.fail,
+ t: (x) => x,
+ console,
+ };
+ await runInNewContext('(' + source + ')', context)(3, 50, 1);
+ assert.equal(calls.length, 1);
+ assert.equal(calls[0].path, '/api/channel/multi_key/manage');
+ assert.equal(calls[0].data.action, 'get_key_status');
+ assert.equal(calls[0].data.page, 3);
+ assert.equal(calls[0].data.page_size, 50);
+ assert.equal(states.total, 156);
+ assert.equal(states.rows[0], sentinel);
+ assert.equal(states.loading, false);
+});
diff --git a/test/unit/test-discovery.test.js b/test/unit/test-discovery.test.js
new file mode 100644
index 00000000..0293b473
--- /dev/null
+++ b/test/unit/test-discovery.test.js
@@ -0,0 +1,62 @@
+/*
+Copyright (C) 2025 QuantumNous
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or (at your option) any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see .
+
+For commercial licensing, please contact support@quantumnous.com
+*/
+
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { mkdtemp, mkdir, writeFile, rm } from 'node:fs/promises';
+import os from 'node:os';
+import path from 'node:path';
+import { findUnitTests } from '../../scripts/test.mjs';
+
+test('unit discovery includes source and maintained suites and excludes evidence scripts', async () => {
+ const root = await mkdtemp(path.join(os.tmpdir(), 'monkey-unit-discovery-'));
+ try {
+ for (const name of [
+ 'src/nested',
+ 'tests/helpers',
+ 'test/unit',
+ 'report',
+ 'logs',
+ 'e2e',
+ ])
+ await mkdir(path.join(root, name), { recursive: true });
+ for (const name of [
+ 'src/nested/model.test.js',
+ 'tests/legacy.test.js',
+ 'test/unit/new.test.js',
+ 'tests/helpers/loader.js',
+ 'report/prototype-test.mjs',
+ 'report/contracts.test.mjs',
+ 'logs/output.test.js',
+ 'e2e/page.spec.js',
+ ])
+ await writeFile(path.join(root, name), '');
+ const files = await findUnitTests(root);
+ assert.deepEqual(
+ files.map((file) => path.relative(root, file).replaceAll('\\', '/')),
+ [
+ 'src/nested/model.test.js',
+ 'test/unit/new.test.js',
+ 'tests/legacy.test.js',
+ ],
+ );
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+});