Просмотр исходного кода

✅ (api-v13): 测试游客必须带 IP、路由枚举与未知类型、补发漏结算的积分

- AgentCreditV3Test:游客没有客户端 IP 扣费 422、登录用户不受影响;漏跑的读经 / 编辑积分补发、重算、跨时区
- AgentTraceV3Test:未知的步骤类型照收(只限长度)、regenerate 记 replaces_run_id
- AgentRouteEnumTest(新):docblock 里的路由字面量与 AgentRun::ROUTES 一致;未知路由照收并告警;管理端按未知路由筛选 422

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
visuddhinanda 4 дней назад
Родитель
Сommit
4aa0a3b640

+ 12 - 1
api-v13/tests/Feature/AgentCreditV3Test.php

@@ -39,7 +39,8 @@ function chargeHeaders(?string $userUid = null): array
 
 function charge(array $body, ?string $userUid = null, array $headers = [])
 {
-    return test()->postJson('/api/v3/agent-charges', $body + ['run_id' => (string) Str::uuid()], chargeHeaders($userUid) + $headers);
+    // 游客必须带客户端 IP(runtime 写入);没指定就给一个测试用的
+    return test()->postJson('/api/v3/agent-charges', $body + ['run_id' => (string) Str::uuid(), 'client_ip' => '192.0.2.1'], chargeHeaders($userUid) + $headers);
 }
 
 function spendFree(string $account, int $amount, ?string $ip = null): void
@@ -53,6 +54,16 @@ function spendFree(string $account, int $amount, ?string $ip = null): void
 
 /* ------------------------------------------------------------------ 扣费 */
 
+it('refuses a guest without a client ip but not a signed-in user', function () {
+    $this->postJson('/api/v3/agent-charges', ['run_id' => (string) Str::uuid(), 'device_id' => (string) Str::uuid()], chargeHeaders())
+        ->assertUnprocessable()
+        ->assertJsonValidationErrors('client_ip');
+    expect(CreditLedgerEntry::count())->toBe(0);
+
+    $this->postJson('/api/v3/agent-charges', ['run_id' => (string) Str::uuid()], chargeHeaders(makeStudio('noip-'.Str::random(5))))
+        ->assertCreated();
+});
+
 it('refuses to charge for a thread that belongs to another account', function () {
     $thread = AgentThread::factory()->create(['account' => 'user:'.Str::uuid()]);
 

+ 56 - 0
api-v13/tests/Feature/AgentRouteEnumTest.php

@@ -0,0 +1,56 @@
+<?php
+
+use App\Http\Controllers\V3\AdminAgentRunController;
+use App\Http\Resources\V3\AdminAgentFeedbackResource;
+use App\Http\Resources\V3\AdminAgentRunResource;
+use App\Models\AgentRun;
+use App\Models\AgentRunStep;
+use App\Models\UserInfo;
+use Illuminate\Foundation\Testing\RefreshDatabase;
+use Illuminate\Support\Facades\Log;
+use Illuminate\Support\Str;
+
+uses(RefreshDatabase::class);
+
+/**
+ * 研究路径枚举(AgentRun::ROUTES)的唯一来源守卫,以及入库对未知路由 / 步骤类型的宽容。
+ *
+ * OpenAPI 的枚举来自 Resource `@return` 与控制器 `@queryParam … Enum:` 里写的字面量(PHPDoc 引用不了常量),
+ * 这里断言它们与常量一致;backend 的离线测试再拿 OpenAPI 规格核对 routing.py。
+ */
+it('declares the same route enum in every doc the OpenAPI spec is generated from', function () {
+    foreach ([AdminAgentRunResource::class, AdminAgentFeedbackResource::class] as $resource) {
+        $doc = (new ReflectionMethod($resource, 'toArray'))->getDocComment();
+        expect(preg_match("/\\broute: ((?:'[a-z_]+'\\|)+)null/", $doc, $m))->toBe(1, "{$resource} 的 route 没写成字面量联合")
+            ->and(explode('|', str_replace("'", '', rtrim($m[1], '|'))))->toBe(AgentRun::ROUTES);
+    }
+
+    $doc = (new ReflectionMethod(AdminAgentRunController::class, 'index'))->getDocComment();
+    expect(preg_match('/@queryParam filter\[route\].*Enum: ([a-z_,]+)/', $doc, $m))->toBe(1)
+        ->and(explode(',', $m[1]))->toBe(AgentRun::ROUTES);
+});
+
+it('keeps a trace with a route or step kind it does not know yet, and warns', function () {
+    config(['mint.app.agent_service_key' => 'k']);
+    Log::spy();
+    $run = (string) Str::uuid();
+
+    $this->postJson('/api/v3/agent-traces', [
+        'run_id' => $run, 'thread_id' => (string) Str::uuid(), 'device_id' => (string) Str::uuid(),
+        'question' => '新路由', 'status' => 'ok', 'route' => 'compare', 'answer' => '……',
+        'steps' => [['seq' => 0, 'kind' => 'rerank', 'name' => 'x'], ['seq' => 1, 'kind' => 'tool', 'name' => 'wikipali_search']],
+    ], ['X-Agent-Service-Key' => 'k'])->assertCreated();
+
+    expect(AgentRun::where('run_id', $run)->value('route'))->toBe('compare')
+        ->and(AgentRunStep::where('agent_run_id', AgentRun::where('run_id', $run)->value('id'))->orderBy('seq')->pluck('kind')->all())->toBe(['rerank', 'tool']);
+    Log::shouldHaveReceived('warning')->with('agent trace: unknown route', Mockery::on(fn ($c) => $c['route'] === 'compare'))->once();
+    Log::shouldHaveReceived('warning')->with('agent trace: unknown step kinds', Mockery::on(fn ($c) => $c['kinds'] === ['rerank']))->once();
+});
+
+it('rejects an unknown route in the admin filter', function () {
+    $uid = makeStudio('re-'.Str::random(5));
+    UserInfo::where('userid', $uid)->update(['role' => json_encode(['administrator'])]);
+
+    $this->getJson('/api/v3/admin/agent-runs?filter[route]=compare', authHeader($uid))->assertUnprocessable();
+    $this->getJson('/api/v3/admin/agent-runs?filter[route]=term', authHeader($uid))->assertOk();
+});

+ 2 - 2
api-v13/tests/Feature/AgentTraceV3Test.php

@@ -249,9 +249,9 @@ it('rejects an unknown status', function () {
         ->assertJsonValidationErrors('status');
 });
 
-it('rejects an unknown step kind', function () {
+it('rejects a step kind longer than the column (unknown kinds are kept, see AgentRouteEnumTest)', function () {
     $this->postJson('/api/v3/agent-traces', tracePayload([
-        'steps' => [['seq' => 0, 'kind' => 'bogus']],
+        'steps' => [['seq' => 0, 'kind' => str_repeat('k', 17)]],
     ]), agentHeaders())
         ->assertUnprocessable()
         ->assertJsonValidationErrors('steps.0.kind');