AgentCreditV3Test.php 19 KB

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