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

✅ (api-v13): AI 对话测试改用 account_type + account_id,补设备 id 冒充用户的用例

- factory 用 forUser() / forGuest(),查询用 ownedBy(),不再手拼 user:<uid>
- 新增:游客把 device_id 填成某个用户的 uid,看不到、花不了他的积分,也写不进他的会话
- 管理端评价列表不返回自增 id

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

+ 4 - 4
api-v13/tests/Feature/AdminStatsV3Test.php

@@ -126,8 +126,8 @@ it('summarises agent runs', function () {
     $userThread = AgentThread::factory()->forUser($user)->create();
     $guestThread = AgentThread::factory()->create();
     $at = '2026-10-20 10:00:00';
-    AgentRun::factory()->for($userThread, 'thread')->create(['route' => 'term', 'deep' => true, 'latency_ms' => 1000, 'started_at' => $at, 'user_uid' => $user, 'tokens_in' => 100]);
-    AgentRun::factory()->for($userThread, 'thread')->create(['route' => 'passage', 'latency_ms' => 3000, 'started_at' => $at, 'user_uid' => $user]);
+    AgentRun::factory()->for($userThread, 'thread')->create(['route' => 'term', 'deep' => true, 'latency_ms' => 1000, 'started_at' => $at, 'tokens_in' => 100]);
+    AgentRun::factory()->for($userThread, 'thread')->create(['route' => 'passage', 'latency_ms' => 3000, 'started_at' => $at]);
     AgentRun::factory()->for($guestThread, 'thread')->create(['route' => null, 'status' => 'denied', 'latency_ms' => 50, 'started_at' => $at, 'improve' => false]);
     AgentRun::factory()->for($guestThread, 'thread')->create(['route' => 'question', 'status' => 'ok', 'latency_ms' => 99999, 'started_at' => '2026-09-01 00:00:00']);
 
@@ -153,7 +153,7 @@ it('lists tool calls and credit flows', function () {
         ['seq' => 2, 'kind' => 'event', 'name' => 'quota', 'args' => ['result' => 'unchecked']],
     ]);
     DB::table('credit_ledger')->insert([
-        'account' => $thread->account, 'delta' => -10, 'kind' => 'spend', 'bucket' => 'free', 'source' => 'agent_run',
+        'account_type' => $thread->account_type, 'account_id' => $thread->account_id, 'delta' => -10, 'kind' => 'spend', 'bucket' => 'free', 'source' => 'agent_run',
         'ref' => $run->run_id, 'day' => '2026-10-20', 'policy_version' => 1, 'created_at' => now(), 'updated_at' => now(),
     ]);
 
@@ -185,7 +185,7 @@ it('lists runs newest first with filters', function () {
 it('shows the full research process of a run', function () {
     $user = makeStudio('asker-'.Str::random(4));
     $thread = AgentThread::factory()->forUser($user)->create();
-    $run = AgentRun::factory()->for($thread, 'thread')->create(['user_uid' => $user, 'evidence' => '证据全文']);
+    $run = AgentRun::factory()->for($thread, 'thread')->create(['evidence' => '证据全文']);
     $run->steps()->create(['seq' => 0, 'kind' => 'route', 'args' => ['route' => 'term']]);
 
     $this->getJson("/api/v3/admin/agent-runs/{$run->run_id}", authHeader(makeAdmin()))

+ 44 - 17
api-v13/tests/Feature/AgentCreditV3Test.php

@@ -7,6 +7,7 @@ use App\Models\ReadingDaily;
 use App\Models\UserInfo;
 use App\Models\UserOperationDaily;
 use App\Services\AuthService;
+use App\Services\V3\AgentAccount;
 use Illuminate\Foundation\Testing\RefreshDatabase;
 use Illuminate\Support\Str;
 
@@ -43,10 +44,10 @@ function charge(array $body, ?string $userUid = null, array $headers = [])
     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
+function spendFree(AgentAccount $account, int $amount, ?string $ip = null): void
 {
     CreditLedgerEntry::create([
-        'account' => $account, 'delta' => -$amount, 'kind' => 'spend', 'bucket' => 'free',
+        ...$account->columns(), 'delta' => -$amount, 'kind' => 'spend', 'bucket' => 'free',
         'source' => 'agent_run', 'ref' => (string) Str::uuid(), 'day' => now('UTC')->toDateString(),
         'policy_version' => 1, 'client_ip' => $ip,
     ]);
@@ -65,7 +66,7 @@ it('refuses a guest without a client ip but not a signed-in user', function () {
 });
 
 it('refuses to charge for a thread that belongs to another account', function () {
-    $thread = AgentThread::factory()->create(['account' => 'user:'.Str::uuid()]);
+    $thread = AgentThread::factory()->forUser((string) Str::uuid())->create();
 
     charge(['device_id' => (string) Str::uuid(), 'thread_id' => $thread->thread_id])->assertForbidden();
     expect(CreditLedgerEntry::count())->toBe(0);
@@ -73,7 +74,7 @@ it('refuses to charge for a thread that belongs to another account', function ()
 
 it('charges for my own thread, deleted or not, and for a new one', function () {
     $device = (string) Str::uuid();
-    $thread = AgentThread::factory()->create(['account' => 'guest:'.$device, 'user_uid' => null, 'device_id' => $device]);
+    $thread = AgentThread::factory()->forGuest($device)->create();
     $thread->delete();
 
     charge(['device_id' => $device, 'thread_id' => $thread->thread_id])->assertCreated();
@@ -122,7 +123,7 @@ it('is idempotent on run_id', function () {
 
 it('spends daily free first, then earned credits', function () {
     $user = makeStudio('mix-'.Str::random(5));
-    spendFree('user:'.$user, 490);
+    spendFree(AgentAccount::user($user), 490);
     $this->artisan('credits:adjust', ['user' => $user, 'delta' => 50, '--reason' => 'test'])->assertSuccessful();
 
     charge(['deep' => true], $user)
@@ -134,7 +135,7 @@ it('spends daily free first, then earned credits', function () {
 });
 
 it('caps all guests behind one ip', function () {
-    spendFree('guest:'.Str::uuid(), 490, '198.51.100.9');
+    spendFree(AgentAccount::guest((string) Str::uuid()), 490, '198.51.100.9');
 
     charge(['device_id' => (string) Str::uuid(), 'client_ip' => '198.51.100.9'])->assertCreated();
     charge(['device_id' => (string) Str::uuid(), 'client_ip' => '198.51.100.9'])
@@ -144,7 +145,7 @@ it('caps all guests behind one ip', function () {
 });
 
 it('does not apply the ip cap to signed-in users', function () {
-    spendFree('guest:'.Str::uuid(), 500, '198.51.100.9');
+    spendFree(AgentAccount::guest((string) Str::uuid()), 500, '198.51.100.9');
 
     charge(['client_ip' => '198.51.100.9'], makeStudio('ipuser-'.Str::random(5)))->assertCreated();
 });
@@ -206,6 +207,32 @@ it('shows guest quota without earn rules', function () {
         ->assertJsonStructure(['data' => ['resets_at', 'policy_version', 'earned_balance', 'earned_today']]);
 });
 
+it('never mistakes a guest whose device id equals a user uid for that user', function () {
+    // 设备 id 由客户端填,可以故意填成别人的 uid:账号必须按 account_type + account_id 两列认
+    $user = makeStudio('twin-'.Str::random(5));
+    CreditLedgerEntry::create([
+        ...AgentAccount::user($user)->columns(), 'delta' => 200, 'kind' => 'adjust', 'bucket' => 'earned',
+        'source' => 'admin', 'ref' => 'gift', 'day' => now('UTC')->toDateString(), 'policy_version' => 1,
+    ]);
+    $userThread = AgentThread::factory()->forUser($user)->create();
+
+    // 看不到他的积分
+    $this->getJson("/api/v3/agent-quota?device_id={$user}")
+        ->assertOk()
+        ->assertJsonPath('data.account_type', 'guest')
+        ->assertJsonPath('data.earned_balance', 0);
+    // 不能往他的会话里提问
+    charge(['device_id' => $user, 'thread_id' => $userThread->thread_id])->assertForbidden();
+    // 花掉游客自己的赠送额度后就被拒,碰不到他的积分
+    spendFree(AgentAccount::guest($user), 100);
+    charge(['device_id' => $user])->assertStatus(402);
+
+    $this->getJson('/api/v3/agent-quota', authHeader($user))
+        ->assertJsonPath('data.account_type', 'user')
+        ->assertJsonPath('data.earned_balance', 200)
+        ->assertJsonPath('data.free_used', 0);
+});
+
 it('requires a device id for guest quota', function () {
     $this->getJson('/api/v3/agent-quota')->assertUnprocessable()->assertJsonValidationErrors('device_id');
 });
@@ -286,11 +313,11 @@ it('settles yesterday for everyone with the daily command', function () {
 
     $this->artisan('credits:settle-activity')->assertSuccessful();
 
-    expect(CreditLedgerEntry::where('account', 'user:'.$user)->where('source', 'reading')->value('delta'))->toBe(20);
+    expect(CreditLedgerEntry::ownedBy(AgentAccount::user($user))->where('source', 'reading')->value('delta'))->toBe(20);
 
     // 重复执行不重复入账
     $this->artisan('credits:settle-activity')->assertSuccessful();
-    expect(CreditLedgerEntry::where('account', 'user:'.$user)->where('source', 'reading')->count())->toBe(1);
+    expect(CreditLedgerEntry::ownedBy(AgentAccount::user($user))->where('source', 'reading')->count())->toBe(1);
 });
 
 it('backfills every missed day since credits started, however many', function () {
@@ -313,7 +340,7 @@ it('backfills every missed day since credits started, however many', function ()
 
     $this->artisan('credits:settle-activity')->assertSuccessful();
 
-    $earned = CreditLedgerEntry::where('account', 'user:'.$user)->orderBy('day')->get(['source', 'day', 'delta'])
+    $earned = CreditLedgerEntry::ownedBy(AgentAccount::user($user))->orderBy('day')->get(['source', 'day', 'delta'])
         ->map(fn ($e) => [$e->source, $e->day->toDateString(), $e->delta])->all();
     expect($earned)->toBe([
         ['reading', now('UTC')->subDays(40)->toDateString(), 5],
@@ -335,7 +362,7 @@ it('re-settles a day that was settled before it ended and leaves closed days alo
     }
     // 那天中午就结算过(之后又读了),以及那天结束后才结算过(数额以当时为准,不再动)
     $entry = fn ($day, int $delta, $at) => CreditLedgerEntry::create([
-        'account' => 'user:'.$user, 'delta' => $delta, 'kind' => 'earn', 'bucket' => 'earned', 'source' => 'reading',
+        ...AgentAccount::user($user)->columns(), 'delta' => $delta, 'kind' => 'earn', 'bucket' => 'earned', 'source' => 'reading',
         'ref' => $day->toDateString(), 'day' => $day->toDateString(), 'policy_version' => 1,
     ])->forceFill(['updated_at' => $at])->saveQuietly();
     $entry($early, 2, $early->copy()->addHours(12));
@@ -343,7 +370,7 @@ it('re-settles a day that was settled before it ended and leaves closed days alo
 
     $this->artisan('credits:settle-activity')->assertSuccessful();
 
-    $deltas = CreditLedgerEntry::where('account', 'user:'.$user)->pluck('delta', 'ref');
+    $deltas = CreditLedgerEntry::ownedBy(AgentAccount::user($user))->pluck('delta', 'ref');
     expect($deltas[$early->toDateString()])->toBe(20)
         ->and($deltas[$closed->toDateString()])->toBe(7);
 });
@@ -355,7 +382,7 @@ it('does not keep re-settling an early-settled day whose amount was already righ
     ReadingDaily::create(['user_uid' => $user, 'day' => $day->toDateString(), 'seconds' => 120, 'seconds_reported' => 120]);
     // 当天中途结算过,数额恰好已经对了(2 分)
     CreditLedgerEntry::create([
-        'account' => 'user:'.$user, 'delta' => 2, 'kind' => 'earn', 'bucket' => 'earned', 'source' => 'reading',
+        ...AgentAccount::user($user)->columns(), 'delta' => 2, 'kind' => 'earn', 'bucket' => 'earned', 'source' => 'reading',
         'ref' => $day->toDateString(), 'day' => $day->toDateString(), 'policy_version' => 1,
     ])->forceFill(['updated_at' => $day->copy()->addHours(12)])->saveQuietly();
 
@@ -375,13 +402,13 @@ it('re-settles editing on a western client day settled before that local day end
     ]);
     // 次日 01:00 UTC(本地那天还没结束)只结算到 2 分钟
     CreditLedgerEntry::create([
-        'account' => 'user:'.$user, 'delta' => 10, 'kind' => 'earn', 'bucket' => 'earned', 'source' => 'editing',
+        ...AgentAccount::user($user)->columns(), 'delta' => 10, 'kind' => 'earn', 'bucket' => 'earned', 'source' => 'editing',
         'ref' => $day->toDateString(), 'day' => $day->toDateString(), 'policy_version' => 1,
     ])->forceFill(['updated_at' => $day->copy()->addDay()->addHour()])->saveQuietly();
 
     $this->artisan('credits:settle-activity')->assertSuccessful();
 
-    expect(CreditLedgerEntry::where('account', 'user:'.$user)->where('source', 'editing')->value('delta'))->toBe(50);
+    expect(CreditLedgerEntry::ownedBy(AgentAccount::user($user))->where('source', 'editing')->value('delta'))->toBe(50);
 });
 
 /* ------------------------------------------------------------------ 策略与调整 */
@@ -416,9 +443,9 @@ it('applies a manual adjustment only once per ref', function () {
 
 it('tells guests to sign in and users to read when out of credits', function () {
     $device = (string) Str::uuid();
-    spendFree('guest:'.$device, 100);
+    spendFree(AgentAccount::guest($device), 100);
     $user = makeStudio('out-'.Str::random(5));
-    spendFree('user:'.$user, 500);
+    spendFree(AgentAccount::user($user), 500);
 
     $guestDetail = charge(['device_id' => $device], null, ['Accept-Language' => 'zh-Hans'])->assertStatus(402)->json('detail');
     $userDetail = charge([], $user, ['Accept-Language' => 'zh-Hans'])->assertStatus(402)->json('detail');

+ 9 - 7
api-v13/tests/Feature/AgentFeedbackV3Test.php

@@ -43,7 +43,7 @@ it('lets a guest rate an answer and change the rating', function () {
     ])->assertOk()->assertJsonPath('data.comment', '中部有这段');
 
     expect(AgentFeedback::count())->toBe(1)
-        ->and(AgentFeedback::first()->account)->toBe('guest:'.$device);
+        ->and(AgentFeedback::first()->only('account_type', 'account_id'))->toBe(['account_type' => 'guest', 'account_id' => $device]);
 });
 
 it('keeps one rating per user and per guest device', function () {
@@ -121,7 +121,7 @@ it('rejects an unknown signal', function () {
 
 it('turns improve on for the rated run of the same account only', function () {
     $device = (string) Str::uuid();
-    $mine = AgentThread::factory()->create(['account' => 'guest:'.$device, 'user_uid' => null, 'device_id' => $device]);
+    $mine = AgentThread::factory()->forGuest($device)->create();
     $run = AgentRun::factory()->for($mine, 'thread')->create(['assistant_message_id' => 'msg-c1', 'improve' => false]);
     $other = AgentRun::factory()->for(AgentThread::factory(), 'thread')->create(['assistant_message_id' => 'msg-c2', 'improve' => false]);
 
@@ -164,7 +164,9 @@ it('lists feedback with the run summary for admins only', function () {
         ->assertJsonCount(1, 'data')
         ->assertJsonPath('data.0.question', '什么是慈?')
         ->assertJsonPath('data.0.account_type', 'guest')
-        ->assertJsonMissingPath('data.0.account');
+        ->assertJsonMissingPath('data.0.account')
+        // 对外不暴露自增主键
+        ->assertJsonMissingPath('data.0.id');
     $this->getJson('/api/v3/admin/agent-feedback?filter[tag]=missed', $admin)->assertJsonCount(1, 'data');
     $this->getJson('/api/v3/admin/agent-feedback', $admin)->assertJsonPath('meta.total', 2);
 });
@@ -189,11 +191,11 @@ it('exports a digest without identities or opted-out runs', function () {
     $user = (string) Str::uuid();
     $thread = AgentThread::factory()->forUser($user)->create();
     AgentRun::factory()->for($thread, 'thread')->create([
-        'user_uid' => $user, 'assistant_message_id' => 'd1', 'started_at' => '2026-10-20 10:00:00', 'question' => 'Q1',
+        'assistant_message_id' => 'd1', 'started_at' => '2026-10-20 10:00:00', 'question' => 'Q1',
         'plan' => ['lemmas' => ['mettā'], 'keywords' => [['lemma' => 'mettā', 'tags' => 'sutta']]],
     ]);
-    AgentRun::factory()->for($thread, 'thread')->create(['user_uid' => $user, 'started_at' => '2026-10-20 10:00:30', 'question' => 'Q2']);
-    AgentRun::factory()->for($thread, 'thread')->create(['user_uid' => $user, 'started_at' => '2026-10-20 10:05:00', 'question' => 'secret', 'improve' => false]);
+    AgentRun::factory()->for($thread, 'thread')->create(['started_at' => '2026-10-20 10:00:30', 'question' => 'Q2']);
+    AgentRun::factory()->for($thread, 'thread')->create(['started_at' => '2026-10-20 10:05:00', 'question' => 'secret', 'improve' => false]);
     $this->postJson('/api/v3/agent-events', ['message_id' => 'd1', 'kind' => 'copy'], authHeader($user));
 
     $res = $this->getJson('/api/v3/admin/agent-runs/digest?from=2026-10-20&to=2026-10-20', feedbackAdmin())->assertOk();
@@ -201,7 +203,7 @@ it('exports a digest without identities or opted-out runs', function () {
 
     expect(array_column($items, 'question'))->toBe(['Q1', 'Q2'])
         ->and($items[0])->toMatchArray(['lemmas' => ['mettā'], 'keywords' => ['mettā|sutta'], 'events' => ['copy' => 1], 'next_question_after_s' => 30])
-        ->and($items[0])->not->toHaveKeys(['user', 'user_uid', 'device_id', 'client_ip', 'account', 'answer', 'evidence'])
+        ->and($items[0])->not->toHaveKeys(['user', 'user_uid', 'device_id', 'client_ip', 'account_id', 'answer', 'evidence'])
         ->and($res->json('meta.has_more'))->toBeFalse();
 });
 

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

@@ -121,10 +121,10 @@ it('ignores fields other than title on rename', function () {
     $me = (string) Str::uuid();
     $thread = AgentThread::factory()->forUser($me)->create();
 
-    $this->patchJson("/api/v3/me/agent-threads/{$thread->thread_id}", ['account' => 'user:someone-else'], authHeader($me))
+    $this->patchJson("/api/v3/me/agent-threads/{$thread->thread_id}", ['account_type' => 'guest', 'account_id' => (string) Str::uuid()], authHeader($me))
         ->assertOk();
 
-    expect($thread->fresh()->account)->toBe('user:'.$me);
+    expect($thread->fresh()->only('account_type', 'account_id'))->toBe(['account_type' => 'user', 'account_id' => $me]);
 });
 
 it('rejects an empty title', function () {

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

@@ -92,12 +92,12 @@ it('records a guest run with device id and ip', function () {
         ->assertJsonPath('data.account_type', 'guest');
 
     $run = AgentRun::where('run_id', $payload['run_id'])->firstOrFail();
-    expect($run->user_uid)->toBeNull()
-        ->and($run->device_id)->toBe($payload['device_id'])
+    expect($run->account_type)->toBe('guest')
+        ->and($run->account_id)->toBe($payload['device_id'])
         ->and($run->client_ip)->toBe('203.0.113.7')
         ->and($run->plan)->toBe(['lemmas' => ['ariyasacca']])
         ->and($run->steps()->count())->toBe(3)
-        ->and($run->thread->account)->toBe('guest:'.$payload['device_id'])
+        ->and($run->thread->only('account_type', 'account_id'))->toBe(['account_type' => 'guest', 'account_id' => $payload['device_id']])
         ->and($run->thread->title)->toBe('什么是四圣谛?');
 });
 
@@ -126,7 +126,7 @@ it('treats a model token as a guest', function () {
         'Authorization' => 'Bearer '.AuthService::getUserToken($model->uid),
     ])->assertCreated()->assertJsonPath('data.account_type', 'guest');
 
-    expect(AgentRun::where('run_id', $payload['run_id'])->value('user_uid'))->toBeNull();
+    expect(AgentRun::where('run_id', $payload['run_id'])->value('account_type'))->toBe('guest');
 });
 
 /* ------------------------------------------------------------------ 登录用户 */
@@ -140,10 +140,10 @@ it('records a user run without device id or ip', function () {
         ->assertJsonPath('data.account_type', 'user');
 
     $run = AgentRun::where('run_id', $payload['run_id'])->firstOrFail();
-    expect($run->user_uid)->toBe($user)
-        ->and($run->device_id)->toBeNull()
+    expect($run->account_type)->toBe('user')
+        ->and($run->account_id)->toBe($user)
         ->and($run->client_ip)->toBeNull()
-        ->and($run->thread->account)->toBe('user:'.$user);
+        ->and($run->thread->only('account_type', 'account_id'))->toBe(['account_type' => 'user', 'account_id' => $user]);
 });
 
 it('records a run even when the user opted out of improvement', function () {
@@ -164,7 +164,7 @@ it('rejects a thread id that belongs to another account', function () {
         ->assertJsonPath('status', 403);
 
     expect(AgentThread::where('thread_id', $thread)->count())->toBe(1)
-        ->and(AgentThread::where('thread_id', $thread)->value('account'))->toStartWith('guest:');
+        ->and(AgentThread::where('thread_id', $thread)->value('account_type'))->toBe('guest');
 });
 
 it('appends runs to the same thread and advances last_run_at', function () {