import { describe, expect, it, vi } from 'vitest'; import { DEFAULT_ARK_ENDPOINT, DEFAULT_ARK_MODEL, requestArkCommand, validateArkSuggestion, } from '../src/ai/arkClient.js'; const context = { selected: { serial: 'emulator-5554', state: 'device' }, devices: [{ serial: 'emulator-5554', state: 'device' }], }; describe('Ark 模型命令建议', () => { it('构造兼容 Chat Completions 的请求并解析白名单命令', async () => { const fetchImpl = vi.fn().mockResolvedValue( new Response( JSON.stringify({ output_text: JSON.stringify({ command: '/shell getprop ro.build.version.release', reason: '读取系统属性', confidence: 0.92 }), }), { status: 200, headers: { 'content-type': 'application/json' } }, ), ); const result = await requestArkCommand('查看 Android 版本', context, { apiKey: 'test-key', fetchImpl, }); expect(result.command).toBe('/shell getprop ro.build.version.release'); expect(result.parsed.kind).toBe('adb'); expect(fetchImpl).toHaveBeenCalledWith( DEFAULT_ARK_ENDPOINT, expect.objectContaining({ method: 'POST', headers: expect.objectContaining({ Authorization: 'Bearer test-key' }), }), ); const body = JSON.parse(fetchImpl.mock.calls[0]![1].body); expect(body.model).toBe(DEFAULT_ARK_MODEL); expect(body.stream).toBe(false); expect(body.tools).toEqual([{ type: 'web_search', max_keyword: 3 }]); expect(body.input[1].content[0].text).toContain('查看 Android 版本'); expect(body.input[1].content[0].text).toContain('emulator-5554'); }); it('拒绝低置信度、命令链和非白名单命令', () => { expect(() => validateArkSuggestion({ command: '/shell id', reason: 'x', confidence: 0.59 })).toThrow('置信度'); expect(() => validateArkSuggestion({ command: '/shell id && reboot', reason: 'x', confidence: 0.9 })).toThrow('不安全'); expect(() => validateArkSuggestion({ command: '/reboot', reason: 'x', confidence: 0.9 })).toThrow('白名单'); }); it('兼容模型包裹的 JSON 代码块或前后说明文字', async () => { const fetchImpl = vi.fn().mockResolvedValue( new Response( JSON.stringify({ output: [{ content: [{ text: '建议如下:```json\n{"command":"/shell id","reason":"查询用户","confidence":0.9}\n```' }] }], }), { status: 200 }, ), ); const result = await requestArkCommand('查询用户', context, { apiKey: 'test-key', fetchImpl }); expect(result.command).toBe('/shell id'); }); it('缺少 API key 或服务错误时拒绝请求', async () => { await expect(requestArkCommand('查看设备', context, { apiKey: '' })).rejects.toThrow('ARK_API_KEY'); const fetchImpl = vi.fn().mockResolvedValue(new Response('{}', { status: 401 })); await expect(requestArkCommand('查看设备', context, { apiKey: 'bad', fetchImpl })).rejects.toThrow('鉴权失败'); const notFoundFetch = vi.fn().mockResolvedValue(new Response(JSON.stringify({ code: 'ModelNotFound', message: 'model not found' }), { status: 404 })); await expect(requestArkCommand('查看设备', context, { apiKey: 'bad', fetchImpl: notFoundFetch })).rejects.toThrow('ARK_MODEL'); }); });