AgentCreditV3Test.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429
  1. <?php
  2. use App\Models\AgentThread;
  3. use App\Models\AiModel;
  4. use App\Models\CreditLedgerEntry;
  5. use App\Models\ReadingDaily;
  6. use App\Models\UserInfo;
  7. use App\Models\UserOperationDaily;
  8. use App\Services\AuthService;
  9. use Illuminate\Foundation\Testing\RefreshDatabase;
  10. use Illuminate\Support\Str;
  11. uses(RefreshDatabase::class);
  12. /**
  13. * v3 AI 对话额度与积分(策略在 config mint.credits.policy):
  14. *
  15. * POST /api/v3/agent-charges 提问扣费(服务间,X-Agent-Service-Key)
  16. * GET /api/v3/agent-quota 额度概况(可选登录,游客带 device_id)
  17. * POST /api/v3/me/reading-time 读经时长上报(登录)
  18. * GET /api/v3/credit-policy 当前积分策略(公开)
  19. * artisan credits:settle-activity / credits:adjust
  20. *
  21. * v1:游客每日 100、登录 500;普通 10、深度 30;读经 1/分钟每日上限 100;编辑 5/分钟不设上限;
  22. * 游客同 IP 每日 500。
  23. *
  24. * 这里断言的是形状而非契约(spectator 尚未安装,见 v3-resource skill 第 3 步)。
  25. */
  26. beforeEach(function () {
  27. config(['mint.app.agent_service_key' => 'test-agent-key']);
  28. });
  29. function chargeHeaders(?string $userUid = null): array
  30. {
  31. $headers = ['X-Agent-Service-Key' => 'test-agent-key'];
  32. return $userUid ? $headers + authHeader($userUid) : $headers;
  33. }
  34. function charge(array $body, ?string $userUid = null, array $headers = [])
  35. {
  36. // 游客必须带客户端 IP(runtime 写入);没指定就给一个测试用的
  37. return test()->postJson('/api/v3/agent-charges', $body + ['run_id' => (string) Str::uuid(), 'client_ip' => '192.0.2.1'], chargeHeaders($userUid) + $headers);
  38. }
  39. function spendFree(string $account, int $amount, ?string $ip = null): void
  40. {
  41. CreditLedgerEntry::create([
  42. 'account' => $account, 'delta' => -$amount, 'kind' => 'spend', 'bucket' => 'free',
  43. 'source' => 'agent_run', 'ref' => (string) Str::uuid(), 'day' => now('UTC')->toDateString(),
  44. 'policy_version' => 1, 'client_ip' => $ip,
  45. ]);
  46. }
  47. /* ------------------------------------------------------------------ 扣费 */
  48. it('refuses a guest without a client ip but not a signed-in user', function () {
  49. $this->postJson('/api/v3/agent-charges', ['run_id' => (string) Str::uuid(), 'device_id' => (string) Str::uuid()], chargeHeaders())
  50. ->assertUnprocessable()
  51. ->assertJsonValidationErrors('client_ip');
  52. expect(CreditLedgerEntry::count())->toBe(0);
  53. $this->postJson('/api/v3/agent-charges', ['run_id' => (string) Str::uuid()], chargeHeaders(makeStudio('noip-'.Str::random(5))))
  54. ->assertCreated();
  55. });
  56. it('refuses to charge for a thread that belongs to another account', function () {
  57. $thread = AgentThread::factory()->create(['account' => 'user:'.Str::uuid()]);
  58. charge(['device_id' => (string) Str::uuid(), 'thread_id' => $thread->thread_id])->assertForbidden();
  59. expect(CreditLedgerEntry::count())->toBe(0);
  60. });
  61. it('charges for my own thread, deleted or not, and for a new one', function () {
  62. $device = (string) Str::uuid();
  63. $thread = AgentThread::factory()->create(['account' => 'guest:'.$device, 'user_uid' => null, 'device_id' => $device]);
  64. $thread->delete();
  65. charge(['device_id' => $device, 'thread_id' => $thread->thread_id])->assertCreated();
  66. charge(['device_id' => $device, 'thread_id' => (string) Str::uuid()])->assertCreated();
  67. });
  68. it('requires the service key to charge', function () {
  69. $this->postJson('/api/v3/agent-charges', ['run_id' => (string) Str::uuid(), 'device_id' => (string) Str::uuid()])
  70. ->assertUnauthorized();
  71. });
  72. it('gives a guest ten normal questions a day', function () {
  73. $device = (string) Str::uuid();
  74. foreach (range(1, 10) as $i) {
  75. charge(['device_id' => $device])->assertCreated()->assertJsonPath('data.free_remaining', 100 - 10 * $i);
  76. }
  77. charge(['device_id' => $device])
  78. ->assertStatus(402)
  79. ->assertJsonPath('type', fn ($type) => str_ends_with($type, 'quota-exceeded'))
  80. ->assertJsonPath('reason', 'insufficient')
  81. ->assertJsonPath('cost', 10)
  82. ->assertJsonPath('free_remaining', 0);
  83. });
  84. it('charges a deep question thirty credits', function () {
  85. $user = makeStudio('deep-'.Str::random(5));
  86. charge(['deep' => true], $user)
  87. ->assertCreated()
  88. ->assertJsonPath('data.cost', 30)
  89. ->assertJsonPath('data.charged_free', 30)
  90. ->assertJsonPath('data.free_remaining', 470);
  91. });
  92. it('is idempotent on run_id', function () {
  93. $device = (string) Str::uuid();
  94. $run = (string) Str::uuid();
  95. charge(['device_id' => $device, 'run_id' => $run])->assertCreated();
  96. charge(['device_id' => $device, 'run_id' => $run])->assertOk()->assertJsonPath('data.cost', 10);
  97. expect(CreditLedgerEntry::where('ref', $run)->count())->toBe(1);
  98. });
  99. it('spends daily free first, then earned credits', function () {
  100. $user = makeStudio('mix-'.Str::random(5));
  101. spendFree('user:'.$user, 490);
  102. $this->artisan('credits:adjust', ['user' => $user, 'delta' => 50, '--reason' => 'test'])->assertSuccessful();
  103. charge(['deep' => true], $user)
  104. ->assertCreated()
  105. ->assertJsonPath('data.charged_free', 10)
  106. ->assertJsonPath('data.charged_earned', 20)
  107. ->assertJsonPath('data.free_remaining', 0)
  108. ->assertJsonPath('data.earned_balance', 30);
  109. });
  110. it('caps all guests behind one ip', function () {
  111. spendFree('guest:'.Str::uuid(), 490, '198.51.100.9');
  112. charge(['device_id' => (string) Str::uuid(), 'client_ip' => '198.51.100.9'])->assertCreated();
  113. charge(['device_id' => (string) Str::uuid(), 'client_ip' => '198.51.100.9'])
  114. ->assertStatus(402)
  115. ->assertJsonPath('reason', 'ip_cap');
  116. charge(['device_id' => (string) Str::uuid(), 'client_ip' => '198.51.100.10'])->assertCreated();
  117. });
  118. it('does not apply the ip cap to signed-in users', function () {
  119. spendFree('guest:'.Str::uuid(), 500, '198.51.100.9');
  120. charge(['client_ip' => '198.51.100.9'], makeStudio('ipuser-'.Str::random(5)))->assertCreated();
  121. });
  122. it('treats a model token as a guest when charging', function () {
  123. $human = makeStudio('owner-'.Str::random(5));
  124. $model = AiModel::factory()->ownedBy($human)->create();
  125. $this->postJson('/api/v3/agent-charges', ['run_id' => (string) Str::uuid()], [
  126. 'X-Agent-Service-Key' => 'test-agent-key',
  127. 'Authorization' => 'Bearer '.AuthService::getUserToken($model->uid),
  128. ])->assertUnprocessable()->assertJsonValidationErrors('device_id');
  129. });
  130. /* ------------------------------------------------------------------ 退款 */
  131. it('refunds the charge when the run failed without an answer', function () {
  132. $device = (string) Str::uuid();
  133. $run = (string) Str::uuid();
  134. charge(['device_id' => $device, 'run_id' => $run])->assertCreated();
  135. $this->postJson('/api/v3/agent-traces', [
  136. 'run_id' => $run, 'thread_id' => (string) Str::uuid(), 'device_id' => $device,
  137. 'question' => 'q', 'status' => 'error', 'error' => 'boom',
  138. ], chargeHeaders())->assertCreated();
  139. $this->getJson("/api/v3/agent-quota?device_id={$device}")->assertOk()->assertJsonPath('data.free_remaining', 100);
  140. // 补发同一条研究过程不会退两次
  141. $this->postJson('/api/v3/agent-traces', [
  142. 'run_id' => $run, 'thread_id' => (string) Str::uuid(), 'device_id' => $device,
  143. 'question' => 'q', 'status' => 'error',
  144. ], chargeHeaders())->assertOk();
  145. expect(CreditLedgerEntry::where('ref', $run)->where('kind', 'refund')->count())->toBe(1);
  146. });
  147. it('keeps the charge when the user cancelled', function () {
  148. $device = (string) Str::uuid();
  149. $run = (string) Str::uuid();
  150. charge(['device_id' => $device, 'run_id' => $run])->assertCreated();
  151. $this->postJson('/api/v3/agent-traces', [
  152. 'run_id' => $run, 'thread_id' => (string) Str::uuid(), 'device_id' => $device,
  153. 'question' => 'q', 'status' => 'cancelled',
  154. ], chargeHeaders())->assertCreated();
  155. $this->getJson("/api/v3/agent-quota?device_id={$device}")->assertJsonPath('data.free_remaining', 90);
  156. });
  157. /* ------------------------------------------------------------------ 额度概况 */
  158. it('shows guest quota without earn rules', function () {
  159. $this->getJson('/api/v3/agent-quota?device_id='.Str::uuid())
  160. ->assertOk()
  161. ->assertJsonPath('data.account_type', 'guest')
  162. ->assertJsonPath('data.daily_free', 100)
  163. ->assertJsonPath('data.cost.deep', 30)
  164. ->assertJsonPath('data.earn', [])
  165. ->assertJsonStructure(['data' => ['resets_at', 'policy_version', 'earned_balance', 'earned_today']]);
  166. });
  167. it('requires a device id for guest quota', function () {
  168. $this->getJson('/api/v3/agent-quota')->assertUnprocessable()->assertJsonValidationErrors('device_id');
  169. });
  170. it('shows user quota with earn rules', function () {
  171. $this->getJson('/api/v3/agent-quota', authHeader(makeStudio('q-'.Str::random(5))))
  172. ->assertOk()
  173. ->assertJsonPath('data.account_type', 'user')
  174. ->assertJsonPath('data.daily_free', 500)
  175. ->assertJsonPath('data.earn.reading.daily_cap', 100)
  176. ->assertJsonPath('data.earn.editing.credits_per_minute', 5);
  177. });
  178. /* ------------------------------------------------------------------ 读经时长 */
  179. it('turns reading time into credits', function () {
  180. $user = makeStudio('reader-'.Str::random(5));
  181. $this->postJson('/api/v3/me/reading-time', ['seconds' => 300], authHeader($user))
  182. ->assertOk()
  183. ->assertJsonPath('data.seconds', 300);
  184. $this->getJson('/api/v3/agent-quota', authHeader($user))
  185. ->assertJsonPath('data.earned_today.reading', 5)
  186. ->assertJsonPath('data.earned_balance', 5);
  187. });
  188. it('clamps reading reports to wall-clock time', function () {
  189. $user = makeStudio('clamp-'.Str::random(5));
  190. $this->postJson('/api/v3/me/reading-time', ['seconds' => 600], authHeader($user))->assertOk();
  191. $this->travel(60)->seconds();
  192. $this->postJson('/api/v3/me/reading-time', ['seconds' => 600], authHeader($user))
  193. ->assertOk()
  194. ->assertJsonPath('data.seconds', 690);
  195. });
  196. it('caps reading credits at one hundred a day', function () {
  197. $user = makeStudio('cap-'.Str::random(5));
  198. ReadingDaily::create(['user_uid' => $user, 'day' => now('UTC')->toDateString(), 'seconds' => 20000, 'seconds_reported' => 20000]);
  199. $this->getJson('/api/v3/agent-quota', authHeader($user))->assertJsonPath('data.earned_today.reading', 100);
  200. });
  201. it('rejects reading reports too far in the past', function () {
  202. $this->postJson('/api/v3/me/reading-time', [
  203. 'seconds' => 60, 'day' => now('UTC')->subDays(3)->toDateString(),
  204. ], authHeader(makeStudio('old-'.Str::random(5))))->assertUnprocessable()->assertJsonValidationErrors('day');
  205. });
  206. it('requires login to report reading time', function () {
  207. $this->postJson('/api/v3/me/reading-time', ['seconds' => 60])->assertUnauthorized();
  208. });
  209. it('rejects an oversized reading report', function () {
  210. $this->postJson('/api/v3/me/reading-time', ['seconds' => 5000], authHeader(makeStudio('big-'.Str::random(5))))
  211. ->assertUnprocessable();
  212. });
  213. /* ------------------------------------------------------------------ 编辑时长 */
  214. it('turns editing time into credits without a cap', function () {
  215. $user = makeStudio('editor-'.Str::random(5));
  216. $sn = UserInfo::where('userid', $user)->value('id');
  217. // UTC+8 的客户端:本地今天零点 = UTC 今天零点 − 8 小时
  218. $localMidnight = now('UTC')->startOfDay()->getTimestampMs() - 8 * 3600 * 1000;
  219. UserOperationDaily::forceCreate([
  220. 'id' => app('snowflake')->id(), 'user_id' => $sn, 'date_int' => $localMidnight,
  221. 'duration' => 600 * 60 * 1000, 'hit' => 10,
  222. ]);
  223. $this->getJson('/api/v3/agent-quota', authHeader($user))->assertJsonPath('data.earned_today.editing', 3000);
  224. });
  225. it('settles yesterday for everyone with the daily command', function () {
  226. $user = makeStudio('nightly-'.Str::random(5));
  227. ReadingDaily::create(['user_uid' => $user, 'day' => now('UTC')->subDay()->toDateString(), 'seconds' => 1200, 'seconds_reported' => 1200]);
  228. $this->artisan('credits:settle-activity')->assertSuccessful();
  229. expect(CreditLedgerEntry::where('account', 'user:'.$user)->where('source', 'reading')->value('delta'))->toBe(20);
  230. // 重复执行不重复入账
  231. $this->artisan('credits:settle-activity')->assertSuccessful();
  232. expect(CreditLedgerEntry::where('account', 'user:'.$user)->where('source', 'reading')->count())->toBe(1);
  233. });
  234. it('backfills every missed day since credits started, however many', function () {
  235. config(['mint.credits.earn_since' => now('UTC')->subDays(60)->toDateString()]);
  236. $user = makeStudio('missed-'.Str::random(5));
  237. $sn = UserInfo::where('userid', $user)->value('id');
  238. foreach ([10, 40] as $ago) {
  239. ReadingDaily::create(['user_uid' => $user, 'day' => now('UTC')->subDays($ago)->toDateString(), 'seconds' => 300, 'seconds_reported' => 300]);
  240. }
  241. // UTC+8 客户端 25 天前的本地日:编辑 3 分钟
  242. UserOperationDaily::forceCreate([
  243. 'id' => app('snowflake')->id(), 'user_id' => $sn,
  244. 'date_int' => now('UTC')->subDays(25)->startOfDay()->getTimestampMs() - 8 * 3600 * 1000,
  245. 'duration' => 3 * 60 * 1000, 'hit' => 3,
  246. ]);
  247. // 上线日之前的不补
  248. ReadingDaily::create(['user_uid' => $user, 'day' => now('UTC')->subDays(70)->toDateString(), 'seconds' => 600, 'seconds_reported' => 600]);
  249. // 不足 1 分钟的不给积分,也不算漏
  250. ReadingDaily::create(['user_uid' => $user, 'day' => now('UTC')->subDays(5)->toDateString(), 'seconds' => 30, 'seconds_reported' => 30]);
  251. $this->artisan('credits:settle-activity')->assertSuccessful();
  252. $earned = CreditLedgerEntry::where('account', 'user:'.$user)->orderBy('day')->get(['source', 'day', 'delta'])
  253. ->map(fn ($e) => [$e->source, $e->day->toDateString(), $e->delta])->all();
  254. expect($earned)->toBe([
  255. ['reading', now('UTC')->subDays(40)->toDateString(), 5],
  256. ['editing', now('UTC')->subDays(25)->toDateString(), 15],
  257. ['reading', now('UTC')->subDays(10)->toDateString(), 5],
  258. ]);
  259. // 再跑一次:都已结清,什么都不动
  260. $this->artisan('credits:settle-activity')->expectsOutputToContain('补结算了 0 位用户')->assertSuccessful();
  261. });
  262. it('re-settles a day that was settled before it ended and leaves closed days alone', function () {
  263. config(['mint.credits.earn_since' => now('UTC')->subDays(30)->toDateString()]);
  264. $user = makeStudio('early-'.Str::random(5));
  265. $early = now('UTC')->subDays(3)->startOfDay();
  266. $closed = now('UTC')->subDays(4)->startOfDay();
  267. foreach ([$early, $closed] as $day) {
  268. ReadingDaily::create(['user_uid' => $user, 'day' => $day->toDateString(), 'seconds' => 1200, 'seconds_reported' => 1200]);
  269. }
  270. // 那天中午就结算过(之后又读了),以及那天结束后才结算过(数额以当时为准,不再动)
  271. $entry = fn ($day, int $delta, $at) => CreditLedgerEntry::create([
  272. 'account' => 'user:'.$user, 'delta' => $delta, 'kind' => 'earn', 'bucket' => 'earned', 'source' => 'reading',
  273. 'ref' => $day->toDateString(), 'day' => $day->toDateString(), 'policy_version' => 1,
  274. ])->forceFill(['updated_at' => $at])->saveQuietly();
  275. $entry($early, 2, $early->copy()->addHours(12));
  276. $entry($closed, 7, $closed->copy()->addDay()->addHour());
  277. $this->artisan('credits:settle-activity')->assertSuccessful();
  278. $deltas = CreditLedgerEntry::where('account', 'user:'.$user)->pluck('delta', 'ref');
  279. expect($deltas[$early->toDateString()])->toBe(20)
  280. ->and($deltas[$closed->toDateString()])->toBe(7);
  281. });
  282. it('does not keep re-settling an early-settled day whose amount was already right', function () {
  283. config(['mint.credits.earn_since' => now('UTC')->subDays(30)->toDateString()]);
  284. $user = makeStudio('same-'.Str::random(5));
  285. $day = now('UTC')->subDays(3)->startOfDay();
  286. ReadingDaily::create(['user_uid' => $user, 'day' => $day->toDateString(), 'seconds' => 120, 'seconds_reported' => 120]);
  287. // 当天中途结算过,数额恰好已经对了(2 分)
  288. CreditLedgerEntry::create([
  289. 'account' => 'user:'.$user, 'delta' => 2, 'kind' => 'earn', 'bucket' => 'earned', 'source' => 'reading',
  290. 'ref' => $day->toDateString(), 'day' => $day->toDateString(), 'policy_version' => 1,
  291. ])->forceFill(['updated_at' => $day->copy()->addHours(12)])->saveQuietly();
  292. $this->artisan('credits:settle-activity')->expectsOutputToContain('补结算了 1 位用户')->assertSuccessful();
  293. $this->artisan('credits:settle-activity')->expectsOutputToContain('补结算了 0 位用户')->assertSuccessful();
  294. });
  295. it('re-settles editing on a western client day settled before that local day ended', function () {
  296. config(['mint.credits.earn_since' => now('UTC')->subDays(30)->toDateString()]);
  297. $user = makeStudio('west-'.Str::random(5));
  298. $sn = UserInfo::where('userid', $user)->value('id');
  299. $day = now('UTC')->subDays(3)->startOfDay();
  300. // UTC−8 客户端:本地那天零点 = UTC 当天 08:00,一直到 UTC 次日 08:00
  301. UserOperationDaily::forceCreate([
  302. 'id' => app('snowflake')->id(), 'user_id' => $sn, 'date_int' => $day->getTimestampMs() + 8 * 3600 * 1000,
  303. 'duration' => 10 * 60 * 1000, 'hit' => 10,
  304. ]);
  305. // 次日 01:00 UTC(本地那天还没结束)只结算到 2 分钟
  306. CreditLedgerEntry::create([
  307. 'account' => 'user:'.$user, 'delta' => 10, 'kind' => 'earn', 'bucket' => 'earned', 'source' => 'editing',
  308. 'ref' => $day->toDateString(), 'day' => $day->toDateString(), 'policy_version' => 1,
  309. ])->forceFill(['updated_at' => $day->copy()->addDay()->addHour()])->saveQuietly();
  310. $this->artisan('credits:settle-activity')->assertSuccessful();
  311. expect(CreditLedgerEntry::where('account', 'user:'.$user)->where('source', 'editing')->value('delta'))->toBe(50);
  312. });
  313. /* ------------------------------------------------------------------ 策略与调整 */
  314. it('shows the current credit policy to anyone', function () {
  315. $this->getJson('/api/v3/credit-policy')
  316. ->assertOk()
  317. ->assertJsonPath('data.version', config('mint.credits.policy.version'))
  318. ->assertJsonPath('data.day_timezone', 'UTC')
  319. ->assertJsonPath('data.daily_free.guest', 100)
  320. ->assertJsonPath('data.cost.deep', 30)
  321. ->assertJsonPath('data.earn.editing.daily_cap', null);
  322. });
  323. it('charges by the policy in config and records its version', function () {
  324. config(['mint.credits.policy.version' => 20261201, 'mint.credits.policy.cost.normal' => 5]);
  325. charge(['device_id' => (string) Str::uuid()])->assertCreated()
  326. ->assertJsonPath('data.cost', 5)
  327. ->assertJsonPath('data.policy_version', 20261201);
  328. expect(CreditLedgerEntry::value('policy_version'))->toBe(20261201);
  329. });
  330. it('applies a manual adjustment only once per ref', function () {
  331. $user = makeStudio('adj-'.Str::random(5));
  332. $this->artisan('credits:adjust', ['user' => $user, 'delta' => 100, '--ref' => 'gift-1'])->assertSuccessful();
  333. $this->artisan('credits:adjust', ['user' => $user, 'delta' => 100, '--ref' => 'gift-1'])->assertSuccessful();
  334. $this->getJson('/api/v3/agent-quota', authHeader($user))->assertJsonPath('data.earned_balance', 100);
  335. });
  336. it('tells guests to sign in and users to read when out of credits', function () {
  337. $device = (string) Str::uuid();
  338. spendFree('guest:'.$device, 100);
  339. $user = makeStudio('out-'.Str::random(5));
  340. spendFree('user:'.$user, 500);
  341. $guestDetail = charge(['device_id' => $device], null, ['Accept-Language' => 'zh-Hans'])->assertStatus(402)->json('detail');
  342. $userDetail = charge([], $user, ['Accept-Language' => 'zh-Hans'])->assertStatus(402)->json('detail');
  343. expect($guestDetail)->toContain('登录')
  344. ->and($userDetail)->toContain('读经')
  345. ->and($guestDetail)->not->toBe('messages.agent_quota_insufficient_guest');
  346. });