feat(agents): 完善恢复费用与云资源交互

This commit is contained in:
2026-09-10 22:29:24 +08:00
parent f8f39f39de
commit 303f26294e
24 changed files with 1170 additions and 127 deletions

View File

@@ -3,18 +3,26 @@ import { afterEach, beforeEach, expect, it, vi } from 'vitest';
import { CloudChat } from '@/pages/CloudAgents/CloudChat';
import { CloudAccessPanel } from '@/pages/CloudAgents/CloudAccess';
import { CloudSchedules } from '@/pages/CloudAgents/CloudSchedules';
import { CloudBudgetEditor, CloudCosts } from '@/pages/CloudAgents/CloudCosts';
import { EMPTY_CLOUD_CONFIGURATION } from '../../shared/cloud-agents';
const api = vi.hoisted(() => ({ call: vi.fn(), events: vi.fn(), upload: vi.fn(), download: vi.fn() }));
const api = vi.hoisted(() => ({ call: vi.fn(), events: vi.fn(), upload: vi.fn(), download: vi.fn(), remember: vi.fn(), recovery: vi.fn() }));
vi.mock('@/lib/cloud-agents-api', () => ({ cloudAgentsApi: api }));
class Stream extends EventTarget { close = vi.fn(); onopen = null; onerror = null; }
const stream = new Stream();
const slug = 'ml-' + 'a'.repeat(32);
const budget = { agent_slug: slug, request_limit_points: null, daily_limit_points: null, daily_committed_points: '0.00', timezone: 'Asia/Shanghai', unit: '词元点数', resets_at: '2026-09-11T00:00:00+08:00' };
const scheduleContext = { version: 2, enabled: true, configuration: { ...EMPTY_CLOUD_CONFIGURATION, model: 'model-a' }, result_destination: '任务历史对话与活动', payer: 'creator' };
const run = { agent_run_id: 'run-1', request_id: 'request-1', thread_id: 'thread-1', agent_slug: slug, status: 'running', version: '2', output: '' };
const history = { thread_id: 'thread-1', messages: [], run, next_offset: null };
beforeEach(() => {
vi.resetAllMocks();
api.remember.mockResolvedValue({ saved: true });
api.recovery.mockResolvedValue({ recent: null, pending: [] });
api.events.mockResolvedValue(stream);
api.call.mockImplementation(async (operation: string) => {
if (operation === 'budget') return budget;
if (operation === 'scheduleContext') return scheduleContext;
if (operation === 'threads') return { threads: [], next_offset: null };
if (operation === 'history') return history;
if (operation === 'attachments') return { attachments: [] };
@@ -25,6 +33,98 @@ beforeEach(() => {
});
afterEach(cleanup);
it('recovers a server queue and cancels it after remount without resubmitting messages', async () => {
const base = api.call.getMockImplementation()!;
let cancelled = false;
api.call.mockImplementation(async (operation, input) => {
if (operation === 'threads') return { threads: [{ thread_id: 'thread-1', client_thread_id: 'client', mode: 'published' }], next_offset: null };
if (operation === 'history') return { ...history, run: { ...run, status: 'completed' }, queued_requests: cancelled ? [] : [{ request_id: 'queued-request', thread_id: 'thread-1', run_id: null, status: 'queued', version: '1' }] };
if (operation === 'request') return { request_id: 'queued-request', thread_id: 'thread-1', run_id: null, status: 'queued', version: '1' };
if (operation === 'cancelRequest') { cancelled = true; return { status: 'cancelled' }; }
return base(operation, input);
});
render(<CloudChat slug={slug} />);
fireEvent.click(await screen.findByRole('button', { name: '取消排队' }));
await waitFor(() => expect(screen.queryByRole('button', { name: '取消排队' })).not.toBeInTheDocument());
expect(api.call).toHaveBeenCalledWith('cancelRequest', { request_id: 'queued-request' });
expect(api.call.mock.calls.some(call => call[0] === 'submit')).toBe(false);
});
it('returns to the last selected thread on remount and requires restoring an archived conversation before sending', async () => {
const base = api.call.getMockImplementation()!;
const threads = ['newest', 'older'].map(id => ({ thread_id: id, client_thread_id: id, agent_slug: slug, mode: 'published' as const, title: id, status: 'idle', updated_at: '', run_id: null, unread: false }));
let recent = { slug, mode: 'published' as const, thread_id: 'older' };
api.recovery.mockImplementation(async () => ({ recent, pending: [] }));
api.remember.mockImplementation(async value => { recent = value; return { saved: true }; });
api.call.mockImplementation(async (operation, input) => {
if (operation === 'threads') return { threads, next_offset: null };
if (operation === 'history') return { thread_id: input.thread_id, messages: [], run: null, next_offset: null };
if (operation === 'archiveThread') return { thread_id: input.thread_id, archived: false };
return base(operation, input);
});
const first = render(<CloudChat slug={slug} />);
await waitFor(() => expect(screen.getByLabelText('历史对话')).toHaveValue('older'));
fireEvent.change(screen.getByLabelText('历史对话'), { target: { value: 'newest' } });
await waitFor(() => expect(recent.thread_id).toBe('newest'));
first.unmount();
const second = render(<CloudChat slug={slug} />);
await waitFor(() => expect(screen.getByLabelText('历史对话')).toHaveValue('newest'));
second.unmount();
recent = { ...recent, thread_id: 'older' };
const beforeArchive = api.call.getMockImplementation()!;
api.call.mockImplementation(async (operation, input) => operation === 'threads'
? { threads: input.archived ? [{ ...threads[1], archived: true }] : [threads[0]], next_offset: null }
: beforeArchive(operation, input));
render(<CloudChat slug={slug} />);
const restore = await screen.findByRole('button', { name: '恢复对话' });
expect(screen.getByLabelText('消息')).toBeDisabled();
fireEvent.click(restore);
await waitFor(() => expect(screen.getByLabelText('消息')).toBeEnabled());
expect(api.call).toHaveBeenCalledWith('archiveThread', { thread_id: 'older', archived: false });
expect(api.call.mock.calls.some(call => call[0] === 'submit')).toBe(false);
});
it('keeps proposed schedules disabled until the creator enables and reviews them', async () => {
const base = api.call.getMockImplementation()!;
api.call.mockImplementation(async (operation, input) => {
if (operation === 'schedules') return { jobs: [] };
if (operation === 'createSchedule') return { id: 'job', ...input };
return base(operation, input);
});
render(<CloudSchedules slug={slug} onOpen={() => undefined} proposal={{ id: 'proposal-1', name: '周末选题', prompt: '整理五个方向', cron_expression: '30 10 * * 6', timezone: 'Asia/Shanghai' }} />);
expect(screen.getByLabelText('任务名称')).toHaveValue('周末选题');
expect(screen.getByLabelText('执行时间')).toHaveValue('10:30');
expect(screen.getByLabelText('星期')).toHaveValue('6');
expect(screen.getByLabelText('保存后启用')).not.toBeChecked();
expect(api.call.mock.calls.some(call => call[0] === 'createSchedule')).toBe(false);
await screen.findByText('启用前确认');
fireEvent.change(screen.getByLabelText('执行时间'), { target: { value: '08:45' } });
fireEvent.click(screen.getByLabelText('保存后启用'));
fireEvent.click(screen.getByRole('button', { name: '保存并启用' }));
await waitFor(() => expect(api.call).toHaveBeenCalledWith('createSchedule', expect.objectContaining({ cron_expression: '45 8 * * 6', enabled: true })));
});
it('saves independent Agent ceilings and pages cost results under the active source filter', async () => {
api.call.mockImplementation(async (operation, input) => {
if (operation === 'budget') return budget;
if (operation === 'saveBudget') return { ...budget, ...input };
if (operation === 'costs') return { items: [], next_offset: input.offset ? null : 50, summary: { count: 75, settled_points: '12.30', pending_points: '4.50' }, unit: '词元点数' };
throw new Error(operation);
});
render(<><CloudBudgetEditor slug={slug} /><CloudCosts slug={slug} applications={[]} /></>);
const request = await screen.findByLabelText('每次任务上限(词元点数)');
await waitFor(() => expect(request).toBeEnabled());
fireEvent.change(request, { target: { value: '20.50' } });
fireEvent.change(screen.getByLabelText('每日上限(词元点数)'), { target: { value: '100' } });
fireEvent.click(screen.getByRole('button', { name: '保存费用上限' }));
await waitFor(() => expect(api.call).toHaveBeenCalledWith('saveBudget', { slug, request_limit_points: '20.50', daily_limit_points: '100' }));
fireEvent.change(screen.getByLabelText('费用来源'), { target: { value: 'api' } });
await waitFor(() => expect(screen.getByRole('button', { name: '加载更多费用' })).toBeEnabled());
fireEvent.click(screen.getByRole('button', { name: '加载更多费用' }));
await waitFor(() => expect(api.call).toHaveBeenCalledWith('costs', expect.objectContaining({ slug, source: 'api', offset: 50 })));
expect(screen.getByText(/共 75 次模型调用/)).toHaveTextContent('12.30');
});
it('retries the same request after a lost response and renders batched native SSE', async () => {
let attempts = 0;
const base = api.call.getMockImplementation()!;
@@ -78,6 +178,7 @@ it('keeps publication and access controls usable when cost history is unavailabl
api.call.mockImplementation(async (operation) => {
if (operation === 'access') return { published_version: 1, enabled: true, share_url: 'niancode://agents/' + slug, versions: [], grants: [], applications: [] };
if (operation === 'costs') throw new Error('费用暂不可用');
if (operation === 'budget') return budget;
throw new Error(operation);
});
render(<CloudAccessPanel slug={slug} revision={2} onPublished={() => undefined} />);
@@ -86,10 +187,28 @@ it('keeps publication and access controls usable when cost history is unavailabl
expect(await screen.findByRole('alert')).toHaveTextContent('费用暂不可用');
});
it('saves a manually created schedule disabled unless the creator selects enable', async () => {
const base = api.call.getMockImplementation()!;
api.call.mockImplementation(async (operation, input) => {
if (operation === 'schedules') return { jobs: [] };
if (operation === 'createSchedule') return { id: 'job', ...input };
return base(operation, input);
});
render(<CloudSchedules slug={slug} onOpen={() => undefined} />);
fireEvent.click(await screen.findByRole('button', { name: '添加任务' }));
expect(screen.getByLabelText('保存后启用')).not.toBeChecked();
fireEvent.change(screen.getByLabelText('任务名称'), { target: { value: '早间选题' } });
fireEvent.change(screen.getByLabelText('目标与要求'), { target: { value: '给出三个选题' } });
fireEvent.click(screen.getByRole('button', { name: '保存为停用任务' }));
await waitFor(() => expect(api.call).toHaveBeenCalledWith('createSchedule', expect.objectContaining({ enabled: false })));
});
it('an uncertain schedule save retries the same operation and explicit enabled state', async () => {
let attempt = 0;
api.call.mockImplementation(async (operation) => {
if (operation === 'schedules') return { jobs: [] };
if (operation === 'budget') return budget;
if (operation === 'scheduleContext') return scheduleContext;
if (operation === 'createSchedule') { if (++attempt === 1) throw new Error('超时'); return { id: 'job' }; }
throw new Error(operation);
});
@@ -97,6 +216,9 @@ it('an uncertain schedule save retries the same operation and explicit enabled s
fireEvent.click(await screen.findByRole('button', { name: '添加任务' }));
fireEvent.change(screen.getByLabelText('任务名称'), { target: { value: '早间选题' } });
fireEvent.change(screen.getByLabelText('目标与要求'), { target: { value: '给出三个选题' } });
expect(screen.getByLabelText('保存后启用')).not.toBeChecked();
fireEvent.click(screen.getByLabelText('保存后启用'));
await waitFor(() => expect(screen.getByRole('button', { name: '保存并启用' })).toBeEnabled());
fireEvent.click(screen.getByRole('button', { name: '保存并启用' }));
fireEvent.click(await screen.findByRole('button', { name: '重试保存' }));
await screen.findByRole('button', { name: '添加任务' });