dsh-connect-workbuddy 2.3.1 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/client.js CHANGED
@@ -37,6 +37,25 @@ window.__ModuleLoader__.load({
37
37
  * browser half.
38
38
  */
39
39
  const WORKBUDDY_PROBE_PATH = "/plugins/dsh-connect-workbuddy/probe";
40
+ /**
41
+ * Plugin-owned account-pool endpoint: one batch action per call.
42
+ *
43
+ * `?action=checkin` claims the daily reward for every account of a region;
44
+ * `?action=test` probes every account against the region's target model. Both
45
+ * are POST and loopback-only because both cost something real — check-in writes
46
+ * to the user's account, a probe spends credits.
47
+ *
48
+ * Deliberately ONE endpoint rather than two: the two actions share every
49
+ * guard (method, origin, region, pool-enabled) and differ only in the work, so
50
+ * splitting them would duplicate the guards and invite them to drift apart.
51
+ */
52
+ const WORKBUDDY_POOL_PATH = "/plugins/dsh-connect-workbuddy/pool";
53
+ /** Query parameter selecting which pool batch action a request means. */
54
+ const WORKBUDDY_POOL_ACTION_PARAM = "action";
55
+ /** Address one region's pool endpoint with an action. */
56
+ function withWorkBuddyRegionAndAction(path, region, action) {
57
+ return `${withWorkBuddyRegion(path, region)}&${WORKBUDDY_POOL_ACTION_PARAM}=${action}`;
58
+ }
40
59
  /** Query parameter naming the region a card request addresses. */
41
60
  const WORKBUDDY_REGION_PARAM = "region";
42
61
  /** Every region, in card tab order. */
@@ -113,6 +132,33 @@ window.__ModuleLoader__.load({
113
132
  * value is always the `regions` map, i.e. exactly what `settingsScope.set(
114
133
  * 'regions', ...)` needs.
115
134
  */
135
+ /**
136
+ * Build the next `regions` settings value for a MODEL-LIST save.
137
+ *
138
+ * The model save replaces a region slot wholesale, so the merge has to start
139
+ * from the EXISTING slot rather than from a fresh object: the pool's
140
+ * preferences live in that same slot, and a save that omitted them would delete
141
+ * settings the user configured elsewhere in the card. Every writer that owns
142
+ * only part of a slot goes through a helper like this one.
143
+ */
144
+ function nextRegionModels(value, region, models) {
145
+ return nextRegionSlots(regionsMapOf(value), region, {
146
+ ...regionSlotOf(value, region),
147
+ ...models
148
+ });
149
+ }
150
+ /**
151
+ * Build the next `regions` settings value for a POOL-PREFERENCES save.
152
+ *
153
+ * Same reasoning as {@link nextRegionModels}: the pool is one field of a slot
154
+ * that also holds the model list, so the merge starts from the existing slot.
155
+ */
156
+ function nextRegionPool(value, region, pool) {
157
+ return nextRegionSlots(regionsMapOf(value), region, {
158
+ ...regionSlotOf(value, region),
159
+ pool
160
+ });
161
+ }
116
162
  function nextRegionEnabled(value, region, enabled) {
117
163
  return nextRegionSlots(regionsMapOf(value), region, {
118
164
  ...regionSlotOf(value, region),
@@ -371,8 +417,9 @@ window.__ModuleLoader__.load({
371
417
  * @throws {WorkBuddySettingsWriteError} when the catalog does not read back.
372
418
  */
373
419
  async function writeRegionModels(scope, region, payload) {
420
+ const next = nextRegionModels(scope.getSnapshot().value, region, payload)[region];
374
421
  const written = payload.lastCatalog.map((model) => model.id);
375
- await writeField(scope, "regions", region, payload, (readBack) => {
422
+ await writeField(scope, "regions", region, next, (readBack) => {
376
423
  const stored = readBack?.lastCatalog?.map((model) => model.id);
377
424
  return stored !== void 0 && stored.length === written.length && stored.every((id, index) => id === written[index]);
378
425
  });
@@ -409,6 +456,1001 @@ window.__ModuleLoader__.load({
409
456
  return stored !== null && stored !== void 0 && stored["enabled"] === enabled;
410
457
  });
411
458
  }
459
+ /**
460
+ * Write one region's account-pool PREFERENCES, verifying they landed.
461
+ *
462
+ * Routed through {@link writeField} like every other settings write, so it gets
463
+ * the same Host-endpoint-first path and the same landed check. The card treats
464
+ * a resolved write as "the draft is now safe to discard", so a write that
465
+ * silently did nothing would throw away the user's edits while reporting
466
+ * success — unrecoverable, since the draft is the only copy.
467
+ *
468
+ * The COMPLETE region slot is passed in by the caller for the same reason
469
+ * {@link writeRegionEnabled} does it: the pool lives INSIDE the region slot
470
+ * alongside `lastCatalog`/`enabledModelIds`, so writing only the pool field
471
+ * would drop the model list.
472
+ *
473
+ * Deliberately does NOT carry the pool's measured facts. Those are written by
474
+ * the Host to its own file; keeping them out of settings is what stops a save
475
+ * from rolling back a test result the timer had just recorded.
476
+ *
477
+ * @param scope - the bound settings scope for this plugin's namespace.
478
+ * @param region - the region whose pool preferences are written.
479
+ * @param preferences - the four preference fields, as the user set them.
480
+ * @param slot - the region's COMPLETE next slot (caller owns the merge).
481
+ * @throws {WorkBuddySettingsWriteError} when neither writer persists the value.
482
+ */
483
+ async function writePoolPreferences(scope, region, preferences) {
484
+ const next = nextRegionPool(scope.getSnapshot().value, region, preferences)[region];
485
+ await writeField(scope, "regions", region, next, (readBack) => {
486
+ const pool = readBack?.pool;
487
+ if (pool === void 0 || pool === null) return false;
488
+ if (pool["enabled"] !== preferences.enabled || pool["rotateByCredits"] !== preferences.rotateByCredits || pool["autoTestIntervalMinutes"] !== preferences.autoTestIntervalMinutes || pool["targetModelId"] !== preferences.targetModelId) return false;
489
+ const stored = pool["memberAccountIds"];
490
+ if (!Array.isArray(stored) || stored.length !== preferences.memberAccountIds.length) return false;
491
+ const wanted = new Set(preferences.memberAccountIds);
492
+ return stored.every((id) => typeof id === "string" && wanted.has(id));
493
+ });
494
+ }
495
+ //#endregion
496
+ //#region src/account-pool.ts
497
+ /**
498
+ * The checked ids that still resolve to a local sign-in, in the caller's order.
499
+ *
500
+ * This is THE definition of "effective members", and it exists because the same
501
+ * predicate was written five separate times: the status document
502
+ * (`web-status.ts`), the batch route's empty-pool guard, the Host dependency the
503
+ * card reads, `poolMemberAccounts` and the browser helper. Five copies of one
504
+ * rule is this project's single most productive bug shape ("fixed one end,
505
+ * missed the other"), so the rule now has one home and every site delegates to
506
+ * it.
507
+ *
508
+ * ORDER IS THE CALLER'S, and comes from `orderedIds`: the answer preserves the
509
+ * order of THAT argument. Callers pass whichever list's order they want to show
510
+ * — the saved list for the user's own order, the store's roster for the account
511
+ * table's. Neither is silently reshuffled by the filter. (The first parameter was
512
+ * once named `saved`, which read as "this must be the saved list" even though
513
+ * `web-status.ts` legitimately passes the roster for store order; the name was
514
+ * the trap, so it now describes the ROLE instead of the source.)
515
+ *
516
+ * Pure, so it is unit-testable without a store, and it never mutates its input.
517
+ */
518
+ function effectiveMembersOf(orderedIds, listedIds) {
519
+ return orderedIds.filter((id) => listedIds.has(id));
520
+ }
521
+ /**
522
+ * A latest-wins guard for one region's asynchronous work.
523
+ *
524
+ * Exists because `applyRotation` awaits (it fetches credits per member), so two
525
+ * overlapping calls can interleave: a slow call that read "rotation is ON" can
526
+ * resume AFTER a newer call cleared the override for "rotation is OFF" and write
527
+ * the stale account back — leaving the card showing the pool switched off while
528
+ * a rotated account is still billed.
529
+ *
530
+ * `begin()` claims a new generation and returns a probe; the caller must check
531
+ * it after EVERY await and bail when it reports stale. Extracted as a pure
532
+ * factory rather than inlined so the rule is unit-testable: an inlined token is
533
+ * only observable by reproducing a real interleaving, which is slow and easy to
534
+ * get subtly wrong (a harness that never actually overlaps passes either way).
535
+ */
536
+ function createLatestWins() {
537
+ const generations = {};
538
+ return { begin(key) {
539
+ const generation = (generations[key] ?? 0) + 1;
540
+ generations[key] = generation;
541
+ return () => generations[key] !== generation;
542
+ } };
543
+ }
544
+ //#endregion
545
+ //#region src/client/pool-state.ts
546
+ /**
547
+ * Pure decision helpers for the account pool's card section.
548
+ *
549
+ * 参考:`src/account-pool.ts` 的做法——把「判定规则」从组件里抽出来,让规则本身
550
+ * 可被单测直接钉住,而不是只能通过渲染整棵组件树间接观察。
551
+ * 改动:新增本模块,收纳三组此前内联在 `AccountPool.tsx` 里的判定。抽出它们的
552
+ * 直接原因是**独立验证发现 H-1/H-2 两个最高危修复没有任何自动化回归测试**:
553
+ * 内联在组件里就只能靠真实渲染验证,而渲染测试既慢又容易被隔离问题骗过。
554
+ *
555
+ * 本模块不 import React、不碰网络,纯函数、全函数。
556
+ *
557
+ * @module dsh-connect-workbuddy/client/pool-state
558
+ */
559
+ /**
560
+ * Whether rotation currently owns the region's billing choice, and whether the
561
+ * user has drafted turning it off.
562
+ *
563
+ * `locked` reads the COMMITTED preferences, never the draft. The Host decides
564
+ * who is billed from the saved config, so a draft-based lock let one click of
565
+ * "turn off rotation" re-enable the manual dropdown and hide the conflict
566
+ * notice while the Host kept rotating — the user then picked an account, the
567
+ * card showed it as current, and a different account was billed. That is
568
+ * exactly the failure the lock exists to prevent.
569
+ *
570
+ * `unlockPending` is the honest intermediate state: the draft says "stop
571
+ * rotating" but the Host has not been told yet, so the lock still applies and
572
+ * the UI must say so rather than looking broken.
573
+ */
574
+ function rotationLockState(saved, active) {
575
+ const locked = saved.enabled && saved.rotateByCredits;
576
+ return {
577
+ locked,
578
+ unlockPending: locked && !(active.enabled && active.rotateByCredits)
579
+ };
580
+ }
581
+ /**
582
+ * The base a draft edit starts from.
583
+ *
584
+ * Resolved at EDIT time rather than captured when the callback was built. The
585
+ * defect this fixes: the callback's dependency list named individual scalar
586
+ * fields, so a field added later (`memberAccountIds`) was missing from it and
587
+ * the callback kept a STALE base — checking one account then silently dropped
588
+ * another that had been saved in between.
589
+ *
590
+ * `previous` is the draft already in state; it only applies to the region it
591
+ * was made on, because the two pools are independent and one region's unsaved
592
+ * edits must never seed the other's.
593
+ */
594
+ function draftBaseFor(previous, previousRegion, region, saved) {
595
+ return previous !== null && previousRegion === region ? previous : saved;
596
+ }
597
+ /**
598
+ * Membership that resolves to a real local sign-in — what a batch runs on.
599
+ *
600
+ * The HOST computes this and sends it; this helper only chooses which answer to
601
+ * trust. Counting the raw saved list is what let the UI claim "已选 1 / 共 1"
602
+ * and enable both buttons while the batch ran on ZERO accounts and reported
603
+ * success, so:
604
+ *
605
+ * - while the draft is CLEAN, the Host's answer is authoritative (it reflects
606
+ * what would actually run, including sign-ins that have since disappeared);
607
+ * - while the draft is DIRTY, it must be derived from the edited list, since
608
+ * the Host's answer describes the SAVED state and would ignore the edit the
609
+ * user is looking at.
610
+ */
611
+ function effectiveMemberIds(input) {
612
+ if (!input.dirty) return [...input.savedEffective];
613
+ return effectiveMembersOf(input.draftMembers, input.listedIds);
614
+ }
615
+ /**
616
+ * Saved member ids with no matching sign-in.
617
+ *
618
+ * Surfaced rather than silently ignored: the ids remain in the user's saved
619
+ * list (a login can come back), so the card has to explain why the pool behaves
620
+ * as though they were absent.
621
+ */
622
+ function ghostMemberIds(draftMembers, listedIds) {
623
+ return draftMembers.filter((id) => !listedIds.has(id));
624
+ }
625
+ /**
626
+ * How many accounts a batch will really touch, as the log announces it.
627
+ *
628
+ * Mirrors the HOST's own resolution exactly — `effective ?? saved` in the pool
629
+ * route — because the number in the activity log must describe what the Host
630
+ * runs, not what the card happens to display. Two wrong answers are possible and
631
+ * both were live at different times:
632
+ *
633
+ * - counting the raw SAVED list overstates it, so a ghost-only pool logged
634
+ * "checking in 1 account(s)" and was then refused with 409 having touched
635
+ * nothing;
636
+ * - counting the DRAFT-derived set announces unsaved edits the Host will not
637
+ * run (it reads the committed config).
638
+ *
639
+ * `savedEffective` is `undefined` only for a Host too old to send it, where the
640
+ * saved list is the best available answer — the same fallback the route uses.
641
+ */
642
+ function announcedBatchCount(input) {
643
+ return (input.savedEffective ?? input.savedMembers).length;
644
+ }
645
+ const POOL_INTERVAL_MAX = 1440;
646
+ /**
647
+ * Localize a pool route failure from its structured cause.
648
+ *
649
+ * Lives here, not in `AccountPool.tsx`, because the card's module graph pulls
650
+ * DSH's browser packages and there is no jsdom in this project — a rule left
651
+ * inside the component cannot be tested at all. That is not hypothetical: the
652
+ * independent verification deleted this function's `no-live-members` branch AND
653
+ * both locale copies of its copy, and the whole 618-test suite still passed.
654
+ * Extracting it is what lets `tests/pool-state.spec.ts` pin every branch.
655
+ *
656
+ * Returns undefined for an unknown cause so the caller can fall back to the
657
+ * Host's own words — a new cause added upstream must still be visible rather
658
+ * than swallowed into a generic message.
659
+ *
660
+ * `detail` is the Host's raw `error` text, used only where the sentence has a
661
+ * slot for it (`pool-failed`). It is NOT the primary path: echoing English
662
+ * developer prose into a Chinese UI was the defect this function exists to
663
+ * prevent, and only the cases with no structured cause fall back to it.
664
+ */
665
+ function poolErrorText(t, reason, detail) {
666
+ switch (reason) {
667
+ case "pool-disabled": return t("row.poolErrDisabled");
668
+ case "no-members": return t("row.poolErrNoMembers");
669
+ case "no-live-members": return t("row.poolErrNoLiveMembers");
670
+ case "no-free-model": return t("row.poolErrNoFreeModel");
671
+ case "target-model-stale": return t("row.poolErrStaleModel");
672
+ case "pool-unavailable": return t("row.poolErrUnavailable");
673
+ case "pool-failed": return t("row.poolErrFailed", { message: detail ?? "" });
674
+ default: return;
675
+ }
676
+ }
677
+ /**
678
+ * The message to show for a failed pool request, from every signal available.
679
+ *
680
+ * The three-tier rule, in order, and why each tier exists:
681
+ *
682
+ * 1. the STRUCTURED cause, localized — the Host's `error` is an English
683
+ * developer sentence, and echoing it put untranslated prose in a Chinese UI;
684
+ * 2. the Host's raw text, for a cause this build does not know — still more
685
+ * informative than a generic message, and it keeps a new upstream cause
686
+ * visible rather than swallowed;
687
+ * 3. a message keyed on the STATUS — every pool exit that carries no reason
688
+ * (405/403/400 and the generic 500) otherwise reached the user as bare
689
+ * English like `HTTP 405`.
690
+ *
691
+ * Extracted from the card for the same reason as {@link poolErrorText}: a rule
692
+ * inside the browser-only `.tsx` cannot be tested, and the status tier in
693
+ * particular had no guard at all — reverting it to `` `HTTP ${status}` `` left
694
+ * the entire suite green.
695
+ */
696
+ function poolFailureText(t, input) {
697
+ return poolErrorText(t, input.reason, input.error) ?? input.error ?? t("row.poolErrHttp", { status: String(input.status) });
698
+ }
699
+ /**
700
+ * Parse an in-progress interval edit.
701
+ *
702
+ * Returns `undefined` while the text is not yet a plain non-negative integer —
703
+ * empty, `-`, `12e`, `1.5` — so the caller can leave EXACTLY what the user typed
704
+ * on screen instead of rewriting the control from a parsed number.
705
+ *
706
+ * That rewriting was the defect this replaces: the field clamped on every
707
+ * keystroke and wrote the clamped result back into a controlled `value`, so
708
+ * typing `120` produced `520` (each keystroke's clamped `5` was rendered, and the
709
+ * next digit appended to it) and clearing the field immediately snapped it to
710
+ * `5`. The user's original request was "设置一个时间间隔自动测试" — a field that
711
+ * cannot be typed into is that requirement unmet, not a cosmetic wart.
712
+ */
713
+ function parseIntervalInput(raw) {
714
+ const trimmed = raw.trim();
715
+ if (!/^[0-9]+$/.test(trimmed)) return void 0;
716
+ const parsed = Number(trimmed);
717
+ if (!Number.isFinite(parsed)) return void 0;
718
+ return Math.min(POOL_INTERVAL_MAX, Math.max(5, Math.round(parsed)));
719
+ }
720
+ /**
721
+ * One keystroke in the interval field: what to DISPLAY, and what to commit.
722
+ *
723
+ * `text` is ALWAYS the raw keystroke, never a re-serialized number — that
724
+ * distinction is the whole defect. A field whose displayed value is derived from
725
+ * the parsed-and-clamped number cannot be typed into: each keystroke's clamped
726
+ * `5` is rendered, and the next digit appends to it (`120` → `520`).
727
+ *
728
+ * `commit` is the clamped number to fold into the draft, or `undefined` while the
729
+ * text is not yet a plain integer (so the draft is left alone until the entry is
730
+ * meaningful). Splitting the two makes the invariant unit-testable without a DOM,
731
+ * which this project has no way to render.
732
+ */
733
+ function intervalEditOnInput(raw) {
734
+ return {
735
+ text: raw,
736
+ commit: parseIntervalInput(raw)
737
+ };
738
+ }
739
+ /**
740
+ * Pool MEMBERS that can serve right now.
741
+ *
742
+ * Judged over members only. Using the whole account table made the "no usable
743
+ * account" warning unreachable: unchecked rows are listed for the user to opt
744
+ * into and never carry `excludedBy`, so any unchecked sign-in kept the count
745
+ * above zero — exactly when every member was limited and the explanation was
746
+ * most needed.
747
+ */
748
+ function usableMemberIds(accounts, effectiveMembers, draftMembers) {
749
+ const wanted = /* @__PURE__ */ new Set([...effectiveMembers, ...draftMembers]);
750
+ return accounts.filter((account) => wanted.has(account.accountId) && account.excludedBy === void 0).map((account) => account.accountId);
751
+ }
752
+ //#endregion
753
+ //#region src/client/AccountPool.tsx
754
+ /**
755
+ * The account pool's card section.
756
+ *
757
+ * 参考:`WorkBuddyCard.tsx` 的既有写法 —— 草稿态 + dirty 标记 + 「保存/放弃」、
758
+ * 60 秒轮询、`writeField` 验证写入,全部沿用;样式类名继续用
759
+ * `dsm-workbuddy-*` 前缀,好让这一块与卡片其余部分共用同一套外观语言。
760
+ * 改动:把「账号池」这一整块独立成模块。原因是它有三条别的区块没有的规则,
761
+ * 放在卡片里会被淹没:
762
+ *
763
+ * 1. **两项互斥。** 自动轮换开启时,上方卡片原有的手动账号下拉必须停用 ——
764
+ * 否则会出现"下拉显示 A、实际计费 B"。本模块通过 `onRotationChange`
765
+ * 把这个状态交回卡片,由卡片去禁用那个下拉。
766
+ * 2. **两种状态、两套写入。** 四项偏好走草稿 + 保存(保存成功才丢弃草稿);
767
+ * 测试结果与轮换是**运行时事实**,由 Host 自动落盘,绝不经这个保存按钮。
768
+ * 把它们混在一起,一次「保存」就会用旧草稿覆盖刚测出的结果。
769
+ * 3. **免费模型可能不存在。** 国内版静态目录不带倍率,所以「自动挑免费模型」
770
+ * 在国内版首次刷新前会挑到空。此时**不回退到收费模型**,而是如实说明并
771
+ * 停用测试按钮。
772
+ *
773
+ * @module dsh-connect-workbuddy/client/AccountPool
774
+ */
775
+ /** How many activity lines are kept; the oldest are dropped. */
776
+ const LOG_LIMIT = 60;
777
+ /**
778
+ * Activity logs, kept per region OUTSIDE the component.
779
+ *
780
+ * The card unmounts its whole body when collapsed (`WorkBuddyCard.tsx:832`
781
+ * renders it only while `open`), and again whenever a poll briefly leaves the
782
+ * region unsigned-in. Component state therefore lost the entire log on every
783
+ * collapse, and — because the rotation bookkeeping reset with it — wrote a
784
+ * PHANTOM "switched from — to X" record on the next open. Holding both here
785
+ * keeps the history across remounts and across tab switches.
786
+ */
787
+ const logStore = /* @__PURE__ */ new Map();
788
+ const rotationMemory = /* @__PURE__ */ new Map();
789
+ /**
790
+ * Whether two id sets are equal, ignoring order.
791
+ *
792
+ * The membership compare must not depend on click order: re-selecting the same
793
+ * accounts in a different sequence is not an edit, and treating it as one would
794
+ * light up "unsaved changes" for a no-op.
795
+ */
796
+ function sameIds(left, right) {
797
+ if (left.length !== right.length) return false;
798
+ const wanted = new Set(right);
799
+ return left.every((id) => wanted.has(id));
800
+ }
801
+ /** Whether a probe outcome means the model answered. */
802
+ function outcomeOk(outcome) {
803
+ return outcome === "ok";
804
+ }
805
+ /** A short, localizable label for one probe outcome. */
806
+ function outcomeText(t, outcome) {
807
+ switch (outcome) {
808
+ case "ok": return t("row.probeOk");
809
+ case "rate-limited": return t("row.poolExcludedRateLimited");
810
+ case "out-of-credit": return t("row.poolExcludedOutOfCredit");
811
+ case "credential-rejected": return t("row.probeCredentialRejected");
812
+ case "not-found": return t("row.probeNotFound");
813
+ case "unavailable": return t("row.probeUnavailable");
814
+ default: return t("row.probeFailed");
815
+ }
816
+ }
817
+ function formatNumber$1(value) {
818
+ return new Intl.NumberFormat(void 0, { maximumFractionDigits: 0 }).format(value);
819
+ }
820
+ /**
821
+ * `MM/DD, HH:mm` on a 24-hour clock.
822
+ *
823
+ * `hourCycle: 'h23'` is REQUIRED, not decorative: without it `Intl` follows the
824
+ * browser locale's preference, and en-US renders `09/30, 01:23 PM`. A wall-clock
825
+ * glued to "AM/PM" reads as 12-hour no matter what the surrounding UI assumes,
826
+ * and it is the one thing a Chinese user cannot scan past — the card otherwise
827
+ * speaks 24-hour everywhere (see `formatClock`).
828
+ *
829
+ * `h23` rather than `hour12: false`, because the latter maps to `h24` in some
830
+ * engines and would print midnight as `24:00`. `h23` pins 00–23 exactly, which
831
+ * is also the cycle DSH's own timestamps use.
832
+ */
833
+ function formatShort(value) {
834
+ return new Intl.DateTimeFormat(void 0, {
835
+ month: "2-digit",
836
+ day: "2-digit",
837
+ hour: "2-digit",
838
+ minute: "2-digit",
839
+ hourCycle: "h23"
840
+ }).format(new Date(value));
841
+ }
842
+ function formatClock(value) {
843
+ return new Intl.DateTimeFormat(void 0, {
844
+ hour: "2-digit",
845
+ minute: "2-digit",
846
+ second: "2-digit",
847
+ hourCycle: "h23"
848
+ }).format(new Date(value));
849
+ }
850
+ /** A dot colour for one account's state. */
851
+ function stateColor(account) {
852
+ if (account.excludedBy !== void 0) return account.excludedBy === "rate-limited" || account.excludedBy === "unavailable" ? "var(--dsw-alias-state-warn-primary, #f59e0b)" : "var(--dsw-alias-state-error-primary, #ef4444)";
853
+ if (account.probe === void 0) return "var(--dsw-alias-label-dimmed, #9aa0a6)";
854
+ return outcomeOk(account.probe.outcome) ? "var(--dsw-alias-state-success-primary, #22a06b)" : "var(--dsw-alias-state-warn-primary, #f59e0b)";
855
+ }
856
+ /** The exclusion label for one account, or undefined when it is usable. */
857
+ function exclusionText(t, account) {
858
+ switch (account.excludedBy) {
859
+ case "rate-limited": return t("row.poolExcludedRateLimited");
860
+ case "out-of-credit": return t("row.poolExcludedOutOfCredit");
861
+ case "credential-rejected": return t("row.poolExcludedRejected");
862
+ case "not-found": return t("row.probeNotFound");
863
+ case "unavailable": return t("row.probeUnavailable");
864
+ case "failed": return t("row.probeFailed");
865
+ case "unusable": return t("row.poolExcludedUnusable");
866
+ default: return;
867
+ }
868
+ }
869
+ /**
870
+ * The pool section.
871
+ *
872
+ * Renders nothing when the Host reports no pool state at all: an older Host
873
+ * built without this feature should show an unmodified card, not an empty
874
+ * section implying the feature exists.
875
+ */
876
+ function AccountPool(props) {
877
+ const { t, region, pool, settingsScope, siblingBusy, onBusyChange, onSaved, onRefresh, onRotationChange } = props;
878
+ const [draft, setDraft] = (0, react.useState)(null);
879
+ const [saving, setSaving] = (0, react.useState)(false);
880
+ const [saveError, setSaveError] = (0, react.useState)(void 0);
881
+ const [busy, setBusy] = (0, react.useState)(void 0);
882
+ const [actionError, setActionError] = (0, react.useState)(void 0);
883
+ const [log, setLog] = (0, react.useState)(() => logStore.get(region) ?? []);
884
+ (0, react.useEffect)(() => {
885
+ setLog(logStore.get(region) ?? []);
886
+ setIntervalText(void 0);
887
+ }, [region]);
888
+ const [draftRegion, setDraftRegion] = (0, react.useState)(void 0);
889
+ /**
890
+ * The interval field's raw text while it is being typed.
891
+ *
892
+ * `undefined` means "not editing" and the control renders the committed
893
+ * number. Keeping the in-progress string here is what makes the field
894
+ * typeable: clamping on every keystroke and writing the result straight back
895
+ * into the controlled `value` turned `120` into `520` and made an empty field
896
+ * snap to `5`. See `parseIntervalInput`.
897
+ */
898
+ const [intervalText, setIntervalText] = (0, react.useState)(void 0);
899
+ const mounted = (0, react.useRef)(true);
900
+ (0, react.useEffect)(() => {
901
+ mounted.current = true;
902
+ return () => {
903
+ mounted.current = false;
904
+ };
905
+ }, []);
906
+ const saved = {
907
+ enabled: pool?.enabled ?? false,
908
+ rotateByCredits: pool?.rotateByCredits ?? false,
909
+ autoTestIntervalMinutes: pool?.autoTestIntervalMinutes ?? 30,
910
+ targetModelId: pool?.targetModelId || pool?.staleTargetModelId || "",
911
+ memberAccountIds: pool?.memberAccountIds ?? []
912
+ };
913
+ const active = draftRegion === region && draft !== null ? draft : saved;
914
+ const dirty = draftRegion === region && draft !== null && (draft.enabled !== saved.enabled || draft.rotateByCredits !== saved.rotateByCredits || draft.autoTestIntervalMinutes !== saved.autoTestIntervalMinutes || draft.targetModelId !== saved.targetModelId || !sameIds(draft.memberAccountIds, saved.memberAccountIds));
915
+ const current = pool?.accounts.find((account) => account.current);
916
+ /**
917
+ * Membership that actually resolves to a local sign-in — what a batch runs on.
918
+ *
919
+ * The HOST computes this and sends it, so the card cannot drift from the
920
+ * batch's real behaviour. Counting the raw saved list is what let the UI
921
+ * claim "已选 1 / 共 1" and enable both buttons while the batch ran on ZERO
922
+ * accounts and reported success.
923
+ *
924
+ * Derived locally as a FALLBACK for the case where the user has edited the
925
+ * draft (the Host's answer describes the SAVED state) or an older Host omits
926
+ * the field.
927
+ */
928
+ const listedIds = new Set((pool?.accounts ?? []).map((account) => account.accountId));
929
+ const effectiveMembers = effectiveMemberIds({
930
+ savedEffective: pool?.effectiveMemberAccountIds ?? [],
931
+ draftMembers: active.memberAccountIds,
932
+ listedIds,
933
+ dirty
934
+ });
935
+ /** Saved ids with no matching sign-in; surfaced rather than silently ignored. */
936
+ const ghostMembers = ghostMemberIds(active.memberAccountIds, listedIds);
937
+ /**
938
+ * Pool MEMBERS that can serve right now.
939
+ *
940
+ * Judged over members only. Using the whole account table made the "no usable
941
+ * account" warning unreachable: unchecked rows are listed for the user to opt
942
+ * into and never carry `excludedBy`, so any unchecked sign-in kept the count
943
+ * above zero — exactly when every member was limited and the explanation was
944
+ * most needed.
945
+ */
946
+ const usableMemberSet = new Set(usableMemberIds(pool?.accounts ?? [], effectiveMembers, active.memberAccountIds));
947
+ const usable = (pool?.accounts ?? []).filter((account) => usableMemberSet.has(account.accountId));
948
+ /**
949
+ * Whether rotation currently owns this region's choice — read from the
950
+ * COMMITTED preferences, not the draft.
951
+ *
952
+ * The distinction is the whole point. The Host decides who is billed from the
953
+ * saved config, so a draft-based lock let one click of "turn off rotation"
954
+ * re-enable the manual dropdown and hide the conflict notice while the Host
955
+ * kept rotating — the user then picked an account, the card showed it as
956
+ * current, and a different account was billed. That is exactly the failure
957
+ * the lock exists to prevent.
958
+ *
959
+ * Reading the committed value means the dropdown stays disabled until the
960
+ * change is SAVED, which is honest: until then the Host really is still
961
+ * rotating. The conflict notice says so and offers to save.
962
+ */
963
+ const { locked: rotationLocked, unlockPending: rotationUnlockPending } = rotationLockState(saved, active);
964
+ const canEditPool = settingsScope !== void 0;
965
+ (0, react.useEffect)(() => {
966
+ onRotationChange?.(rotationLocked);
967
+ return () => {
968
+ onRotationChange?.(false);
969
+ };
970
+ }, [onRotationChange, rotationLocked]);
971
+ (0, react.useEffect)(() => {
972
+ onBusyChange?.(saving);
973
+ return () => {
974
+ onBusyChange?.(false);
975
+ };
976
+ }, [onBusyChange, saving]);
977
+ const appendLog = (0, react.useCallback)((text, tone) => {
978
+ setLog((previous) => {
979
+ const next = [{
980
+ atMs: Date.now(),
981
+ text,
982
+ tone
983
+ }, ...previous].slice(0, LOG_LIMIT);
984
+ logStore.set(region, next);
985
+ return next;
986
+ });
987
+ }, [region]);
988
+ /**
989
+ * Record a rotation the HOST performed.
990
+ *
991
+ * Rotation can happen on a timer with no card interaction, so the browser
992
+ * cannot infer it — the Host reports which account it moved to and this logs
993
+ * the transition. Without it "every switch is recorded" was a promise the UI
994
+ * had no way to keep.
995
+ */
996
+ /**
997
+ * Record rotation transitions the HOST performed.
998
+ *
999
+ * Rotation can happen on a timer with no card interaction, so the browser
1000
+ * cannot infer it — the Host reports which account it moved to and this logs
1001
+ * the change.
1002
+ *
1003
+ * Three defects are fixed here, all from keeping one `useRef` for a value
1004
+ * that is per-region and long-lived:
1005
+ *
1006
+ * 1. **No phantom first record.** The ref used to start `undefined`, so the
1007
+ * first rotation the card ever SAW was reported as a fresh switch ("from
1008
+ * — to X") even when it had happened long before. The first observation
1009
+ * now PRIMES the ref instead of logging.
1010
+ * 2. **Per-region state.** The card keeps ONE component instance across
1011
+ * tabs and only swaps the `region` prop, so a shared ref explained one
1012
+ * region's rotation with another region's account list — producing
1013
+ * records for switches that never happened. State is keyed by region.
1014
+ * 3. **The stop event is logged.** Rotation ending (`undefined`) used to
1015
+ * return early AND leave the ref set, so "rotation stopped, back to your
1016
+ * own account" never appeared, and rotating to the SAME account again
1017
+ * was silently skipped.
1018
+ */
1019
+ const rotatedTo = pool?.rotatedToAccountId;
1020
+ (0, react.useEffect)(() => {
1021
+ const memory = rotationMemory.get(region) ?? {
1022
+ last: void 0,
1023
+ primed: false
1024
+ };
1025
+ const previous = memory.last;
1026
+ if (!memory.primed) {
1027
+ rotationMemory.set(region, {
1028
+ last: rotatedTo,
1029
+ primed: true
1030
+ });
1031
+ return;
1032
+ }
1033
+ if (rotatedTo === previous) return;
1034
+ if (rotatedTo === void 0) {
1035
+ rotationMemory.set(region, {
1036
+ last: void 0,
1037
+ primed: true
1038
+ });
1039
+ if (previous !== void 0) appendLog(t("row.poolLogRotationStopped", { from: nameOf(previous, pool) || t("row.accountUnnamed") }), "info");
1040
+ return;
1041
+ }
1042
+ rotationMemory.set(region, {
1043
+ last: rotatedTo,
1044
+ primed: true
1045
+ });
1046
+ appendLog(t("row.poolLogRotated", {
1047
+ from: previous === void 0 ? "—" : nameOf(previous, pool) || t("row.accountUnnamed"),
1048
+ to: nameOf(rotatedTo, pool) || t("row.accountUnnamed")
1049
+ }), "info");
1050
+ }, [
1051
+ appendLog,
1052
+ pool,
1053
+ region,
1054
+ rotatedTo,
1055
+ t
1056
+ ]);
1057
+ /**
1058
+ * The latest saved preferences, for callbacks that must not capture a stale
1059
+ * copy.
1060
+ *
1061
+ * `saved` is rebuilt on every render, so putting it in a `useCallback` dep
1062
+ * list would rebuild the callback every render (making the memo pointless),
1063
+ * while listing individual fields by hand is exactly what caused the
1064
+ * data-loss defect this ref fixes: a field added later
1065
+ * (`memberAccountIds`) was missing from the list, so the callback kept a
1066
+ * stale base and checking one account silently dropped another.
1067
+ *
1068
+ * A ref gives both properties at once — a STABLE callback identity and a
1069
+ * base read at call time. It is synced in a LAYOUT effect, which flushes
1070
+ * synchronously after commit and BEFORE the browser paints: a user event
1071
+ * cannot be processed before a frame is painted, so by the time any click
1072
+ * reaches `editDraft` the ref is current. (A plain `useEffect` would leave a
1073
+ * window between paint and its flush; a render-phase write would be unsafe
1074
+ * under concurrent rendering, where a discarded pass could leave the ref
1075
+ * holding values from a tree that never committed.)
1076
+ *
1077
+ * Seeded with the initial value so the very first interaction, before any
1078
+ * effect has run, still reads real preferences.
1079
+ */
1080
+ const savedRef = (0, react.useRef)(saved);
1081
+ (0, react.useLayoutEffect)(() => {
1082
+ savedRef.current = saved;
1083
+ });
1084
+ /** Read by `editDraft` so it can refuse edits mid-save without rebuilding. */
1085
+ const savingRef = (0, react.useRef)(saving);
1086
+ (0, react.useLayoutEffect)(() => {
1087
+ savingRef.current = saving;
1088
+ });
1089
+ const editDraft = (0, react.useCallback)((edit) => {
1090
+ if (savingRef.current) return;
1091
+ setDraftRegion(region);
1092
+ setDraft((previous) => {
1093
+ return edit(draftBaseFor(previous, draftRegion, region, savedRef.current));
1094
+ });
1095
+ }, [draftRegion, region]);
1096
+ const discard = (0, react.useCallback)(() => {
1097
+ setDraft(null);
1098
+ setDraftRegion(void 0);
1099
+ setIntervalText(void 0);
1100
+ setSaveError(void 0);
1101
+ }, []);
1102
+ /** Save the four preferences through the plugin's VERIFIED write path. */
1103
+ const save = (0, react.useCallback)(async () => {
1104
+ if (settingsScope === void 0 || !dirty || draft === null) return;
1105
+ setSaving(true);
1106
+ setSaveError(void 0);
1107
+ let committed = false;
1108
+ try {
1109
+ await writePoolPreferences(settingsScope, region, draft);
1110
+ if (await onSaved?.() === false) {
1111
+ if (mounted.current) setSaveError(t("row.poolSavedStaleRefresh"));
1112
+ return;
1113
+ }
1114
+ committed = true;
1115
+ } catch (error) {
1116
+ if (mounted.current) setSaveError(error instanceof Error ? error.message : t("row.requestFailed"));
1117
+ } finally {
1118
+ if (committed) discard();
1119
+ if (mounted.current) setSaving(false);
1120
+ }
1121
+ }, [
1122
+ dirty,
1123
+ discard,
1124
+ draft,
1125
+ onSaved,
1126
+ region,
1127
+ settingsScope,
1128
+ t
1129
+ ]);
1130
+ /** Check or uncheck one account in this pool. */
1131
+ const toggleMember = (0, react.useCallback)((accountId, next) => {
1132
+ editDraft((current) => {
1133
+ const set = new Set(current.memberAccountIds);
1134
+ if (next) set.add(accountId);
1135
+ else set.delete(accountId);
1136
+ return {
1137
+ ...current,
1138
+ memberAccountIds: [...set]
1139
+ };
1140
+ });
1141
+ }, [editDraft]);
1142
+ /** Check every listed account, or none of them. */
1143
+ const selectAll = (0, react.useCallback)((next) => {
1144
+ editDraft((current) => ({
1145
+ ...current,
1146
+ memberAccountIds: next ? (pool?.accounts ?? []).map((account) => account.accountId) : []
1147
+ }));
1148
+ }, [editDraft, pool]);
1149
+ /**
1150
+ * The interval control's two halves, kept apart so the field is typeable.
1151
+ *
1152
+ * `onIntervalInput` records what the user typed and only folds a VALID value
1153
+ * into the draft; `onIntervalCommit` (blur / Enter) forces the text back to
1154
+ * the committed number, clamping an out-of-range or non-numeric entry exactly
1155
+ * once, after the user is done. Committing on every keystroke is what made
1156
+ * `120` land as `520`.
1157
+ */
1158
+ const onIntervalInput = (0, react.useCallback)((raw) => {
1159
+ const { text, commit } = intervalEditOnInput(raw);
1160
+ setIntervalText(text);
1161
+ if (commit === void 0) return;
1162
+ editDraft((current) => ({
1163
+ ...current,
1164
+ autoTestIntervalMinutes: commit
1165
+ }));
1166
+ }, [editDraft]);
1167
+ const onIntervalCommit = (0, react.useCallback)(() => {
1168
+ setIntervalText(void 0);
1169
+ }, []);
1170
+ /** Run one batch action against the Host. */
1171
+ const runAction = (0, react.useCallback)(async (action) => {
1172
+ setBusy(action);
1173
+ setActionError(void 0);
1174
+ const memberCount = announcedBatchCount({
1175
+ savedEffective: pool?.effectiveMemberAccountIds,
1176
+ savedMembers: pool?.memberAccountIds ?? []
1177
+ });
1178
+ appendLog(action === "checkin" ? t("row.poolLogCheckinStart", { count: memberCount }) : t("row.poolLogTestStart", {
1179
+ count: memberCount,
1180
+ model: pool?.targetModelId ?? ""
1181
+ }), "info");
1182
+ try {
1183
+ const response = await fetch(withWorkBuddyRegionAndAction(WORKBUDDY_POOL_PATH, region, action), {
1184
+ method: "POST",
1185
+ headers: { accept: "application/json" },
1186
+ credentials: "same-origin"
1187
+ });
1188
+ const body = await response.json().catch(() => void 0);
1189
+ if (!response.ok) throw new Error(poolFailureText(t, {
1190
+ status: response.status,
1191
+ reason: body?.reason,
1192
+ error: body?.error
1193
+ }));
1194
+ if (!mounted.current) return;
1195
+ if (action === "checkin") {
1196
+ for (const row of body?.rows ?? []) if (row.status === "claimed") appendLog(t("row.poolLogCheckinClaimed", {
1197
+ accountName: row.accountName === "" ? t("row.accountUnnamed") : row.accountName,
1198
+ credit: String(row.credit ?? 0)
1199
+ }), "ok");
1200
+ else if (row.status === "already") appendLog(t("row.poolLogCheckinAlready", { accountName: row.accountName === "" ? t("row.accountUnnamed") : row.accountName }), "info");
1201
+ else appendLog(t("row.poolLogCheckinFailed", {
1202
+ accountName: row.accountName === "" ? t("row.accountUnnamed") : row.accountName,
1203
+ message: row.message ?? t("row.requestFailed")
1204
+ }), "error");
1205
+ appendLog(t("row.poolLogCheckinDone"), "ok");
1206
+ } else {
1207
+ for (const row of body?.rows ?? []) {
1208
+ const outcome = row?.result?.outcome;
1209
+ if (outcome === void 0) {
1210
+ appendLog(t("row.poolLogTestRowMalformed", { accountName: row?.accountName === "" || row?.accountName === void 0 ? t("row.accountUnnamed") : row.accountName }), "warn");
1211
+ continue;
1212
+ }
1213
+ appendLog(t("row.poolLogTestRow", {
1214
+ accountName: row.accountName === "" ? t("row.accountUnnamed") : row.accountName,
1215
+ outcome: outcomeText(t, outcome)
1216
+ }), outcomeOk(outcome) ? "ok" : "warn");
1217
+ }
1218
+ appendLog(t("row.poolLogTestDone"), "ok");
1219
+ }
1220
+ onRefresh?.();
1221
+ } catch (error) {
1222
+ const message = error instanceof Error ? error.message : t("row.requestFailed");
1223
+ if (mounted.current) {
1224
+ setActionError(message);
1225
+ appendLog(t("row.poolLogBatchFailed", { message }), "error");
1226
+ }
1227
+ } finally {
1228
+ if (mounted.current) setBusy(void 0);
1229
+ }
1230
+ }, [
1231
+ appendLog,
1232
+ onRefresh,
1233
+ pool,
1234
+ region,
1235
+ t
1236
+ ]);
1237
+ if (pool === void 0) return null;
1238
+ /**
1239
+ * Where the target model came from.
1240
+ *
1241
+ * Rendered under the buttons. This was computed and then never used, so the
1242
+ * card never explained its own target — which is the entire reason
1243
+ * `targetModelSource` is sent by the Host.
1244
+ */
1245
+ const targetLabel = pool.targetModelSource === "preferred" ? t("row.poolTargetPreferred", { model: pool.targetModelId ?? "" }) : pool.targetModelSource === "free" ? t("row.poolTargetFree", { model: pool.targetModelId ?? "" }) : pool.targetModelSource === "stale" ? t("row.poolTargetStale", { model: pool.staleTargetModelId ?? "" }) : t("row.poolTargetNone");
1246
+ return (0, react.createElement)("section", { className: "dsm-workbuddy-pool" }, (0, react.createElement)("div", { className: "dsm-workbuddy-pool-head" }, (0, react.createElement)("div", null, (0, react.createElement)("h3", { className: "dsm-workbuddy-pool-title" }, t("row.poolTitle")), (0, react.createElement)("p", { className: "dsm-workbuddy-pool-summary" }, t("row.poolSummary", {
1247
+ count: effectiveMembers.length,
1248
+ model: pool.targetModelId ?? (pool.targetModelSource === "stale" ? t("row.poolTargetStaleShort") : pool.targetModelSource === "none" ? t("row.poolTargetNoneShort") : t("row.poolTargetAuto"))
1249
+ }))), rotationLocked && current !== void 0 ? (0, react.createElement)("span", { className: "dsm-workbuddy-pool-badge" }, t("row.poolRotating")) : null), (0, react.createElement)("div", { className: "dsm-workbuddy-pool-actions" }, (0, react.createElement)("button", {
1250
+ type: "button",
1251
+ className: "dsm-btn dsm-btn-primary",
1252
+ disabled: busy !== void 0 || !active.enabled || effectiveMembers.length === 0,
1253
+ onClick: () => {
1254
+ runAction("checkin");
1255
+ }
1256
+ }, busy === "checkin" ? t("row.poolCheckingIn") : t("row.poolCheckinAll")), (0, react.createElement)("button", {
1257
+ type: "button",
1258
+ className: "dsm-btn dsm-btn-outline",
1259
+ disabled: busy !== void 0 || !active.enabled || effectiveMembers.length === 0 || pool.targetModelSource === "none" || pool.targetModelSource === "stale",
1260
+ title: pool.targetModelSource === "none" ? t("row.poolTargetNone") : pool.targetModelSource === "stale" ? t("row.poolTargetStale", { model: pool.staleTargetModelId ?? "" }) : void 0,
1261
+ onClick: () => {
1262
+ runAction("test");
1263
+ }
1264
+ }, busy === "test" ? t("row.poolTesting") : t("row.poolTestAll")), busy === void 0 ? null : (0, react.createElement)("span", { className: "dsm-workbuddy-pool-hint" }, t("row.poolBusyHint"))), (0, react.createElement)("p", { className: "dsm-workbuddy-pool-note" }, targetLabel), !active.enabled ? (0, react.createElement)("p", { className: "dsm-workbuddy-pool-note" }, t("row.poolEnabledHint")) : null, rotationLocked && usable.length === 0 ? (0, react.createElement)("p", {
1265
+ className: "dsm-workbuddy-pool-warn",
1266
+ role: "status"
1267
+ }, `${t("row.poolNoCandidate")} ${t("row.poolNoCandidateHint")}`) : null, (0, react.createElement)("div", { className: "dsm-workbuddy-pool-members" }, (0, react.createElement)("div", { className: "dsm-workbuddy-pool-members-head" }, (0, react.createElement)("div", null, (0, react.createElement)("h4", { className: "dsm-workbuddy-pool-members-title" }, t("row.poolMembersTitle")), (0, react.createElement)("p", { className: "dsm-workbuddy-pool-note" }, t("row.poolMembersHint"))), (0, react.createElement)("div", { className: "dsm-workbuddy-pool-members-actions" }, (0, react.createElement)("span", { className: "dsm-workbuddy-pool-hint" }, t("row.poolSelectedCount", {
1268
+ count: effectiveMembers.length,
1269
+ total: pool.accounts.length
1270
+ })), (0, react.createElement)("button", {
1271
+ type: "button",
1272
+ className: "dsm-btn dsm-btn-outline dsm-workbuddy-pool-small-btn",
1273
+ disabled: pool.accounts.length === 0 || !canEditPool,
1274
+ onClick: () => selectAll(true)
1275
+ }, t("row.poolSelectAll")), (0, react.createElement)("button", {
1276
+ type: "button",
1277
+ className: "dsm-btn dsm-btn-outline dsm-workbuddy-pool-small-btn",
1278
+ disabled: effectiveMembers.length === 0 || !canEditPool,
1279
+ onClick: () => selectAll(false)
1280
+ }, t("row.poolSelectNone")))), (0, react.createElement)("div", { className: "dsm-workbuddy-pool-table" }, (0, react.createElement)("div", { className: "dsm-workbuddy-pool-row dsm-workbuddy-pool-row-head" }, (0, react.createElement)("span", null, t("row.poolColumnAccount")), (0, react.createElement)("span", null, t("row.poolColumnCredits")), (0, react.createElement)("span", null, t("row.poolColumnProbe")), (0, react.createElement)("span", null, t("row.poolColumnCheckin"))), ...pool.accounts.map((account) => renderAccountRow({
1281
+ t,
1282
+ account,
1283
+ checked: active.memberAccountIds.includes(account.accountId),
1284
+ canEdit: canEditPool,
1285
+ onToggle: (next) => toggleMember(account.accountId, next)
1286
+ }))), effectiveMembers.length === 0 ? (0, react.createElement)("p", {
1287
+ className: "dsm-workbuddy-pool-warn",
1288
+ role: "status"
1289
+ }, `${t("row.poolNoneSelected")} ${t("row.poolNoneSelectedHint")}`) : null, ghostMembers.length === 0 ? null : (0, react.createElement)("p", {
1290
+ className: "dsm-workbuddy-pool-warn",
1291
+ role: "status"
1292
+ }, t("row.poolGhostMembers", { count: ghostMembers.length })), dirty && !sameIds(active.memberAccountIds, saved.memberAccountIds) ? (0, react.createElement)("p", { className: "dsm-workbuddy-pool-dirty" }, t("row.poolUnsavedMembers")) : null), pool.targetModelSource === "none" ? (0, react.createElement)("p", {
1293
+ className: "dsm-workbuddy-pool-warn",
1294
+ role: "status"
1295
+ }, `${t("row.poolTargetNone")} ${t("row.poolTargetNoneHint")}`) : null, pool.targetModelSource === "stale" ? (0, react.createElement)("div", { className: "dsm-workbuddy-pool-conflict" }, (0, react.createElement)("span", { className: "dsm-workbuddy-pool-conflict-main" }, (0, react.createElement)("b", null, t("row.poolTargetStale", { model: pool.staleTargetModelId ?? "" })), (0, react.createElement)("span", null, t("row.poolTargetStaleHint"))), (0, react.createElement)("button", {
1296
+ type: "button",
1297
+ className: "dsm-btn dsm-btn-outline",
1298
+ disabled: !canEditPool,
1299
+ onClick: () => {
1300
+ editDraft((current) => ({
1301
+ ...current,
1302
+ targetModelId: ""
1303
+ }));
1304
+ }
1305
+ }, t("row.poolTargetStaleClear"))) : null, actionError === void 0 ? null : (0, react.createElement)("p", {
1306
+ className: "dsm-workbuddy-pool-error",
1307
+ role: "alert"
1308
+ }, actionError), renderSettings({
1309
+ t,
1310
+ pool,
1311
+ active,
1312
+ dirty,
1313
+ saving,
1314
+ siblingBusy: siblingBusy === true,
1315
+ rotationLocked,
1316
+ rotationUnlockPending,
1317
+ saveError,
1318
+ settingsScope,
1319
+ intervalText,
1320
+ onIntervalInput,
1321
+ onIntervalCommit,
1322
+ onEdit: editDraft,
1323
+ onSave: () => {
1324
+ save();
1325
+ },
1326
+ onDiscard: discard,
1327
+ onUnlock: () => {
1328
+ editDraft((current) => ({
1329
+ ...current,
1330
+ rotateByCredits: false
1331
+ }));
1332
+ },
1333
+ appendLog
1334
+ }), (0, react.createElement)("p", { className: "dsm-workbuddy-pool-note" }, t("row.poolRegionNote")), renderLog({
1335
+ t,
1336
+ log,
1337
+ busy: busy !== void 0,
1338
+ onClear: () => {
1339
+ logStore.set(region, []);
1340
+ setLog([]);
1341
+ }
1342
+ }));
1343
+ }
1344
+ /** An account's display name by id, or undefined when it is not listed. */
1345
+ function nameOf(accountId, pool) {
1346
+ const account = pool?.accounts.find((entry) => entry.accountId === accountId);
1347
+ return account === void 0 ? void 0 : account.accountName;
1348
+ }
1349
+ /** One account's row. */
1350
+ function renderAccountRow(input) {
1351
+ const { t, account, checked, canEdit, onToggle } = input;
1352
+ const name = account.accountName === "" ? t("row.accountUnnamed") : account.accountName;
1353
+ const excluded = exclusionText(t, account);
1354
+ const probe = account.probe;
1355
+ const probeLine = probe === void 0 ? t("row.poolNeverTested") : probe.retryAtMs !== void 0 ? `${outcomeText(t, probe.outcome)} · ${t("row.poolRetryAt", { at: formatShort(probe.retryAtMs) })}` : probe.outcome === "rate-limited" || probe.outcome === "out-of-credit" ? `${outcomeText(t, probe.outcome)} · ${t("row.poolRetryUnknown")}` : outcomeText(t, probe.outcome);
1356
+ return (0, react.createElement)("div", {
1357
+ className: `dsm-workbuddy-pool-row${account.current ? " dsm-workbuddy-pool-row-current" : ""}`,
1358
+ key: account.accountId
1359
+ }, (0, react.createElement)("span", { className: "dsm-workbuddy-pool-account" }, (0, react.createElement)("label", { className: "dsm-workbuddy-pool-check" }, (0, react.createElement)("input", {
1360
+ type: "checkbox",
1361
+ checked,
1362
+ disabled: !canEdit,
1363
+ "aria-label": t("row.poolSelectAria", { accountName: name }),
1364
+ onChange: (event) => onToggle(event.currentTarget.checked)
1365
+ })), (0, react.createElement)("span", {
1366
+ className: "dsm-workbuddy-usage-dot",
1367
+ style: { background: stateColor(account) }
1368
+ }), (0, react.createElement)("span", { className: "dsm-workbuddy-pool-account-name" }, (0, react.createElement)("b", null, name), (0, react.createElement)("span", { className: checked ? "dsm-workbuddy-pool-member" : "dsm-workbuddy-pool-not-member" }, checked ? t("row.poolMember") : t("row.poolNotMember")), excluded === void 0 ? probe === void 0 ? null : (0, react.createElement)("span", null, t("row.poolTestedAt", { at: formatShort(probe.atMs) })) : (0, react.createElement)("span", { className: "dsm-workbuddy-pool-excluded" }, excluded))), (0, react.createElement)("span", { className: "dsm-workbuddy-pool-credits" }, account.credits === void 0 ? (0, react.createElement)("span", null, "—") : (0, react.createElement)("b", null, formatNumber$1(account.credits)), account.expiringSoon !== void 0 && account.expiringSoon > 0 ? (0, react.createElement)("span", { className: "dsm-workbuddy-pool-soon" }, t("row.poolCreditSoon", { count: formatNumber$1(account.expiringSoon) })) : account.nearestExpiryMs === void 0 ? null : (0, react.createElement)("span", { className: "dsm-workbuddy-pool-soon-plain" }, t("row.poolCreditNearest", { at: formatShort(account.nearestExpiryMs) }))), (0, react.createElement)("span", { className: "dsm-workbuddy-pool-probe" }, probeLine), (0, react.createElement)("span", { className: "dsm-workbuddy-pool-checkin" }, account.checkedInToday === void 0 ? (0, react.createElement)("span", {
1369
+ className: "dsm-workbuddy-pool-unknown",
1370
+ title: t("row.poolNeverTested")
1371
+ }, t("row.poolCheckinUnknown")) : account.checkedInToday ? (0, react.createElement)("span", { className: "dsm-workbuddy-pool-checked" }, t("row.poolCheckedIn")) : t("row.poolNotCheckedIn")));
1372
+ }
1373
+ /** The preference editor plus its save/discard actions. */
1374
+ function renderSettings(input) {
1375
+ const { t, pool, active, dirty, saving, siblingBusy, rotationLocked, rotationUnlockPending, saveError, settingsScope, intervalText, onEdit, onSave, onDiscard, onUnlock, onIntervalInput, onIntervalCommit } = input;
1376
+ const canEdit = settingsScope !== void 0;
1377
+ const toggle = (label, hint, checked, onChange, disabled = false) => (0, react.createElement)("div", { className: "dsm-workbuddy-pool-set" }, (0, react.createElement)("span", { className: "dsm-workbuddy-pool-set-copy" }, (0, react.createElement)("b", null, label), (0, react.createElement)("span", null, hint)), (0, react.createElement)("span", { className: "dsm-workbuddy-pool-set-ctl" }, (0, react.createElement)("label", { className: "sw" }, (0, react.createElement)("input", {
1378
+ type: "checkbox",
1379
+ checked,
1380
+ disabled: disabled || !canEdit,
1381
+ onChange: (event) => onChange(event.currentTarget.checked)
1382
+ }), (0, react.createElement)("span", { className: "sw-track" }))));
1383
+ return (0, react.createElement)("div", { className: "dsm-workbuddy-pool-settings-wrap" }, (0, react.createElement)("div", { className: "dsm-workbuddy-pool-head" }, (0, react.createElement)("h3", { className: "dsm-workbuddy-pool-title" }, t("row.poolSettingsTitle")), dirty ? (0, react.createElement)("span", { className: "dsm-workbuddy-pool-dirty" }, t("row.poolDirty")) : null), (0, react.createElement)("p", { className: "dsm-workbuddy-pool-note" }, t("row.poolSettingsHint")), (0, react.createElement)("div", { className: "dsm-workbuddy-pool-settings" }, toggle(t("row.poolEnabled"), t("row.poolEnabledHint"), active.enabled, (next) => onEdit((current) => ({
1384
+ ...current,
1385
+ enabled: next
1386
+ }))), toggle(t("row.poolRotate"), t("row.poolRotateHint"), active.rotateByCredits, (next) => onEdit((current) => ({
1387
+ ...current,
1388
+ rotateByCredits: next
1389
+ })), !active.enabled), (0, react.createElement)("div", { className: "dsm-workbuddy-pool-set" }, (0, react.createElement)("span", { className: "dsm-workbuddy-pool-set-copy" }, (0, react.createElement)("b", null, t("row.poolInterval")), (0, react.createElement)("span", null, t("row.poolIntervalHint"))), (0, react.createElement)("span", { className: "dsm-workbuddy-pool-set-ctl" }, (0, react.createElement)("input", {
1390
+ className: "dsm-workbuddy-pool-num",
1391
+ type: "number",
1392
+ min: 5,
1393
+ max: POOL_INTERVAL_MAX,
1394
+ step: 5,
1395
+ value: intervalText ?? String(active.autoTestIntervalMinutes),
1396
+ disabled: !active.enabled || !canEdit,
1397
+ onChange: (event) => {
1398
+ onIntervalInput(event.currentTarget.value);
1399
+ },
1400
+ onBlur: () => onIntervalCommit(),
1401
+ onKeyDown: (event) => {
1402
+ if (event.key === "Enter") onIntervalCommit();
1403
+ }
1404
+ }), (0, react.createElement)("span", { className: "dsm-workbuddy-pool-hint" }, t("row.poolIntervalUnit")))), (0, react.createElement)("div", { className: "dsm-workbuddy-pool-set" }, (0, react.createElement)("span", { className: "dsm-workbuddy-pool-set-copy" }, (0, react.createElement)("b", null, t("row.poolTargetLabel")), (0, react.createElement)("span", null, t("row.poolTargetHint"))), (0, react.createElement)("span", { className: "dsm-workbuddy-pool-set-ctl" }, (0, react.createElement)("select", {
1405
+ className: "dsm-workbuddy-pool-select",
1406
+ value: active.targetModelId,
1407
+ disabled: !active.enabled || !canEdit,
1408
+ onChange: (event) => {
1409
+ const value = event.currentTarget.value;
1410
+ onEdit((current) => ({
1411
+ ...current,
1412
+ targetModelId: value
1413
+ }));
1414
+ }
1415
+ }, (0, react.createElement)("option", { value: "" }, t("row.poolTargetAutoOption")), active.targetModelId !== "" && !(pool.catalog ?? []).some((m) => m.id === active.targetModelId) ? (0, react.createElement)("option", {
1416
+ value: active.targetModelId,
1417
+ disabled: true
1418
+ }, t("row.poolTargetStaleOption", { model: active.targetModelId })) : null, ...(pool.catalog ?? []).map((model) => (0, react.createElement)("option", {
1419
+ value: model.id,
1420
+ key: model.id
1421
+ }, model.creditMultiplier === void 0 ? model.name : `${model.name} (x${model.creditMultiplier.toFixed(2)})`)))))), (0, react.createElement)("div", { className: "dsm-workbuddy-pool-save-bar" }, (0, react.createElement)("button", {
1422
+ type: "button",
1423
+ className: "dsm-btn dsm-btn-primary",
1424
+ disabled: !dirty || saving || siblingBusy || !canEdit,
1425
+ onClick: onSave
1426
+ }, saving ? t("row.poolSaving") : t("row.poolSaved")), (0, react.createElement)("button", {
1427
+ type: "button",
1428
+ className: "dsm-btn dsm-btn-outline",
1429
+ disabled: !dirty || saving || siblingBusy,
1430
+ onClick: onDiscard
1431
+ }, t("row.poolDiscard")), (0, react.createElement)("span", { className: "dsm-workbuddy-pool-hint" }, dirty ? t("row.poolSaveDirty") : t("row.poolSaveIdle"))), saveError === void 0 ? null : (0, react.createElement)("p", {
1432
+ className: "dsm-workbuddy-pool-error",
1433
+ role: "alert"
1434
+ }, t("row.poolSaveFailed", { message: saveError })), rotationLocked ? (0, react.createElement)("div", { className: "dsm-workbuddy-pool-conflict" }, (0, react.createElement)("span", { className: "dsm-workbuddy-pool-conflict-main" }, (0, react.createElement)("b", null, t("row.poolManualLocked")), (0, react.createElement)("span", null, t("row.poolManualLockedHint"))), rotationUnlockPending ? (0, react.createElement)("span", { className: "dsm-workbuddy-pool-pending" }, t("row.poolUnlockPending")) : null, (0, react.createElement)("button", {
1435
+ type: "button",
1436
+ className: "dsm-btn dsm-btn-outline",
1437
+ disabled: !canEdit || rotationUnlockPending,
1438
+ onClick: onUnlock
1439
+ }, rotationUnlockPending ? t("row.poolUnlockSaved") : t("row.poolManualUnlock"))) : null);
1440
+ }
1441
+ /** The activity log. */
1442
+ function renderLog(input) {
1443
+ const { t, log, busy, onClear } = input;
1444
+ return (0, react.createElement)("div", { className: "dsm-workbuddy-pool-log" }, (0, react.createElement)("div", { className: "dsm-workbuddy-pool-log-head" }, (0, react.createElement)("span", null, t("row.poolLogTitle")), log.length === 0 ? null : (0, react.createElement)("button", {
1445
+ type: "button",
1446
+ className: "dsm-btn dsm-btn-outline dsm-workbuddy-pool-log-clear",
1447
+ disabled: busy === true,
1448
+ onClick: onClear
1449
+ }, t("row.poolLogClear"))), log.length === 0 ? (0, react.createElement)("div", { className: "dsm-workbuddy-pool-log-empty" }, t("row.poolLogEmpty")) : (0, react.createElement)("div", { className: "dsm-workbuddy-pool-log-body" }, ...log.map((entry, index) => (0, react.createElement)("div", {
1450
+ className: "dsm-workbuddy-pool-log-row",
1451
+ key: `${entry.atMs}-${index}`
1452
+ }, (0, react.createElement)("span", { className: "dsm-workbuddy-pool-log-time" }, formatClock(entry.atMs)), (0, react.createElement)("span", { className: `dsm-workbuddy-pool-log-text dsm-workbuddy-pool-log-${entry.tone}` }, entry.text)))));
1453
+ }
412
1454
  //#endregion
413
1455
  //#region src/native-modality.ts
414
1456
  /**
@@ -618,6 +1660,86 @@ window.__ModuleLoader__.load({
618
1660
  .dsm-workbuddy-usage-cheer-star{font-size:12px;line-height:1;display:inline-flex}
619
1661
  .dsm-workbuddy-usage-cheer:hover{color:var(--dsw-alias-label-primary,#e6e6e6)}
620
1662
  .dsm-workbuddy-usage-cheer:focus-visible{outline:2px solid var(--dsw-alias-brand-primary,#5686fe);outline-offset:2px}
1663
+
1664
+ /* ---- Account pool ---- */
1665
+ .dsm-workbuddy-pool{display:flex;flex-direction:column;gap:12px;margin:0;padding:16px 0 4px;border-top:1px solid var(--dsw-alias-border-l2,#36373b)}
1666
+ .dsm-workbuddy-pool-head{display:flex;align-items:flex-start;justify-content:space-between;gap:12px;flex-wrap:wrap}
1667
+ .dsm-workbuddy-pool-title{margin:0;font-size:15px;font-weight:600;color:var(--dsw-alias-label-primary,#e6e6e6)}
1668
+ .dsm-workbuddy-pool-summary{margin:2px 0 0;font-size:12px;line-height:18px;color:var(--dsw-alias-label-tertiary,#999)}
1669
+ .dsm-workbuddy-pool-badge{flex:none;padding:2px 9px;border-radius:999px;font-size:12px;line-height:18px;font-weight:500;color:var(--dsw-alias-brand-primary,#5686fe);background:rgba(86,134,254,.12);border:1px solid rgba(86,134,254,.32)}
1670
+ .dsm-workbuddy-pool-actions{display:flex;gap:8px;flex-wrap:wrap;align-items:center}
1671
+ .dsm-workbuddy-pool-hint{font-size:12px;line-height:18px;color:var(--dsw-alias-label-tertiary,#999)}
1672
+ .dsm-workbuddy-pool-note{margin:0;font-size:12px;line-height:17px;color:var(--dsw-alias-label-tertiary,#999)}
1673
+ .dsm-workbuddy-pool-warn{margin:0;padding:9px 11px;border-radius:9px;font-size:12px;line-height:17px;color:var(--dsw-alias-state-warn-primary,#f59e0b);background:rgba(245,158,11,.09);border:1px solid rgba(245,158,11,.3)}
1674
+ .dsm-workbuddy-pool-error{margin:0;font-size:12px;line-height:17px;color:var(--dsw-alias-state-error-primary,#ef4444);white-space:pre-line}
1675
+ .dsm-workbuddy-pool-table{border:1px solid var(--dsw-alias-border-l2,#3a3d45);border-radius:12px;overflow:hidden;background:var(--dsw-alias-bg-layer-2,#24262c)}
1676
+ .dsm-workbuddy-pool-row{display:grid;grid-template-columns:1.6fr 1fr 1.3fr .9fr;gap:10px;align-items:center;padding:10px 14px;border-top:1px solid var(--dsw-alias-border-l1,#2c2d31);font-size:13px;color:var(--dsw-alias-label-secondary,#c6c9d0)}
1677
+ .dsm-workbuddy-pool-row:first-child{border-top:0}
1678
+ .dsm-workbuddy-pool-row-head{padding:8px 14px;background:var(--dsw-alias-bg-layer-3,#2a2c33);color:var(--dsw-alias-label-tertiary,#999);font-size:11px;font-weight:600;letter-spacing:.02em;text-transform:uppercase}
1679
+ .dsm-workbuddy-pool-row-current{background:rgba(86,134,254,.07)}
1680
+ .dsm-workbuddy-pool-account{display:flex;align-items:center;gap:8px;min-width:0}
1681
+ .dsm-workbuddy-pool-account-name{display:flex;flex-direction:column;gap:1px;min-width:0}
1682
+ .dsm-workbuddy-pool-account-name b{font-weight:500;color:var(--dsw-alias-label-primary,#e6e6e6);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
1683
+ .dsm-workbuddy-pool-account-name span{font-size:11px;line-height:16px;color:var(--dsw-alias-label-tertiary,#999)}
1684
+ .dsm-workbuddy-pool-excluded{color:var(--dsw-alias-state-warn-primary,#f59e0b)}
1685
+ .dsm-workbuddy-pool-credits{display:flex;flex-direction:column;gap:1px;min-width:0;font-variant-numeric:tabular-nums}
1686
+ .dsm-workbuddy-pool-credits b{color:var(--dsw-alias-label-primary,#e6e6e6);font-weight:600}
1687
+ .dsm-workbuddy-pool-soon{font-size:11px;line-height:16px;color:var(--dsw-alias-state-warn-primary,#f59e0b)}
1688
+ .dsm-workbuddy-pool-soon-plain{font-size:11px;line-height:16px;color:var(--dsw-alias-label-tertiary,#999)}
1689
+ .dsm-workbuddy-pool-probe,.dsm-workbuddy-pool-checkin{font-size:12px;line-height:17px;color:var(--dsw-alias-label-tertiary,#999);min-width:0;overflow-wrap:anywhere}
1690
+ .dsm-workbuddy-pool-members{display:flex;flex-direction:column;gap:10px}
1691
+ .dsm-workbuddy-pool-members-head{display:flex;align-items:flex-start;justify-content:space-between;gap:12px;flex-wrap:wrap}
1692
+ .dsm-workbuddy-pool-members-title{margin:0 0 3px;font-size:13px;font-weight:600;color:var(--dsw-alias-label-primary,#e6e6e6)}
1693
+ .dsm-workbuddy-pool-members-actions{display:flex;align-items:center;gap:8px;flex-wrap:wrap}
1694
+ .dsm-workbuddy-pool-small-btn{padding:3px 10px;font-size:12px}
1695
+ .dsm-workbuddy-pool-check{display:inline-flex;align-items:center;flex:none;cursor:pointer}
1696
+ .dsm-workbuddy-pool-check input{margin:0;cursor:pointer;accent-color:var(--dsw-alias-brand-primary,#5686fe)}
1697
+ .dsm-workbuddy-pool-check input:disabled{cursor:default;opacity:.5}
1698
+ .dsm-workbuddy-pool-checked{color:var(--dsw-alias-state-success-primary,#22a06b)}
1699
+ .dsm-workbuddy-pool-unknown{color:var(--dsw-alias-label-dimmed,#9aa0a6)}
1700
+ .dsm-workbuddy-pool-member{color:var(--dsw-alias-brand-primary,#5686fe)}
1701
+ .dsm-workbuddy-pool-not-member{color:var(--dsw-alias-label-dimmed,#9aa0a6)}
1702
+ .dsm-workbuddy-pool-settings-wrap{display:flex;flex-direction:column;gap:10px}
1703
+ .dsm-workbuddy-pool-dirty{font-size:12px;line-height:18px;font-weight:500;color:var(--dsw-alias-state-warn-primary,#f59e0b)}
1704
+ .dsm-workbuddy-pool-settings{display:flex;flex-direction:column;gap:1px;border:1px solid var(--dsw-alias-border-l2,#3a3d45);border-radius:12px;overflow:hidden;background:var(--dsw-alias-bg-layer-2,#24262c)}
1705
+ .dsm-workbuddy-pool-set{display:flex;align-items:flex-start;justify-content:space-between;gap:16px;padding:12px 14px;border-top:1px solid var(--dsw-alias-border-l1,#2c2d31)}
1706
+ .dsm-workbuddy-pool-set:first-child{border-top:0}
1707
+ .dsm-workbuddy-pool-set-copy{display:flex;flex-direction:column;gap:3px;min-width:0;flex:1}
1708
+ .dsm-workbuddy-pool-set-copy b{font-size:13px;font-weight:500;color:var(--dsw-alias-label-primary,#e6e6e6)}
1709
+ .dsm-workbuddy-pool-set-copy span{font-size:12px;line-height:18px;color:var(--dsw-alias-label-tertiary,#999)}
1710
+ .dsm-workbuddy-pool-set-ctl{flex:none;display:flex;align-items:center;gap:8px}
1711
+ .dsm-workbuddy-pool-num{width:74px;padding:6px 10px;border:1px solid var(--dsw-alias-border-l2,#3a3d45);border-radius:8px;background:var(--dsw-alias-bg-layer-3,#2a2c33);color:var(--dsw-alias-label-primary,#e6e6e6);font:inherit;font-size:13px;text-align:center;font-variant-numeric:tabular-nums}
1712
+ .dsm-workbuddy-pool-select{max-width:260px;padding:6px 10px;border:1px solid var(--dsw-alias-border-l2,#3a3d45);border-radius:8px;background:var(--dsw-alias-bg-layer-3,#2a2c33);color:var(--dsw-alias-label-primary,#e6e6e6);font:inherit;font-size:13px;cursor:pointer}
1713
+ .dsm-workbuddy-pool-select:disabled,.dsm-workbuddy-pool-num:disabled{opacity:.5;cursor:default}
1714
+ .dsm-workbuddy-pool-save-bar{display:flex;align-items:center;gap:9px;flex-wrap:wrap}
1715
+ .dsm-workbuddy-pool-conflict{display:flex;align-items:flex-start;justify-content:space-between;gap:12px;flex-wrap:wrap;padding:11px 13px;border-radius:10px;background:rgba(245,158,11,.08);border:1px solid var(--dsw-alias-state-warn-primary,#f59e0b)}
1716
+ .dsm-workbuddy-pool-pending{flex:none;align-self:center;font-size:12px;line-height:17px;color:var(--dsw-alias-state-warn-primary,#f59e0b)}
1717
+ .dsm-workbuddy-pool-conflict-main{display:flex;flex-direction:column;gap:2px;min-width:0;flex:1}
1718
+ .dsm-workbuddy-pool-conflict-main b{font-size:12px;font-weight:600;color:var(--dsw-alias-state-warn-primary,#f59e0b)}
1719
+ .dsm-workbuddy-pool-conflict-main span{font-size:12px;line-height:17px;color:var(--dsw-alias-label-secondary,#c6c9d0)}
1720
+ .dsm-workbuddy-pool-log{border:1px solid var(--dsw-alias-border-l2,#3a3d45);border-radius:12px;overflow:hidden;background:var(--dsw-alias-bg-layer-2,#24262c)}
1721
+ .dsm-workbuddy-pool-log-head{display:flex;align-items:center;justify-content:space-between;padding:9px 14px;background:var(--dsw-alias-bg-layer-3,#2a2c33);border-bottom:1px solid var(--dsw-alias-border-l1,#2c2d31);font-size:12px;font-weight:600;color:var(--dsw-alias-label-secondary,#c6c9d0)}
1722
+ .dsm-workbuddy-pool-log-clear{padding:2px 10px;font-size:12px}
1723
+ .dsm-workbuddy-pool-log-body{max-height:186px;overflow-y:auto}
1724
+ .dsm-workbuddy-pool-log-row{display:flex;gap:10px;padding:7px 14px;border-top:1px solid var(--dsw-alias-border-l1,#2c2d31);font-size:12px;line-height:18px}
1725
+ .dsm-workbuddy-pool-log-row:first-child{border-top:0}
1726
+ .dsm-workbuddy-pool-log-time{flex:none;color:var(--dsw-alias-label-tertiary,#999);font-family:ui-monospace,SFMono-Regular,Menlo,monospace}
1727
+ .dsm-workbuddy-pool-log-text{min-width:0;overflow-wrap:anywhere}
1728
+ .dsm-workbuddy-pool-log-ok{color:var(--dsw-alias-state-success-primary,#22a06b)}
1729
+ .dsm-workbuddy-pool-log-warn{color:var(--dsw-alias-state-warn-primary,#f59e0b)}
1730
+ .dsm-workbuddy-pool-log-error{color:var(--dsw-alias-state-error-primary,#ef4444)}
1731
+ .dsm-workbuddy-pool-log-info{color:var(--dsw-alias-label-secondary,#c6c9d0)}
1732
+ .dsm-workbuddy-pool-log-empty{padding:14px;font-size:12px;color:var(--dsw-alias-label-tertiary,#999)}
1733
+ @media (max-width:760px){.dsm-workbuddy-pool-row{grid-template-columns:1fr 1fr;row-gap:6px}.dsm-workbuddy-pool-select{max-width:180px}}
1734
+ /* Pool switch, namespaced under .dsm-workbuddy-pool so it cannot collide with host styles. */
1735
+ .dsm-workbuddy-pool .sw{position:relative;display:inline-block;width:38px;height:22px;flex:none;cursor:pointer}
1736
+ .dsm-workbuddy-pool .sw input{position:absolute;opacity:0;width:0;height:0}
1737
+ .dsm-workbuddy-pool .sw-track{position:absolute;inset:0;border-radius:999px;background:var(--dsw-alias-border-l2,#3a3d45);transition:background .18s}
1738
+ .dsm-workbuddy-pool .sw-track::after{content:"";position:absolute;top:3px;left:3px;width:16px;height:16px;border-radius:50%;background:#fff;transition:transform .18s;box-shadow:0 1px 3px rgba(0,0,0,.3)}
1739
+ .dsm-workbuddy-pool .sw input:checked+.sw-track{background:var(--dsw-alias-brand-primary,#5686fe)}
1740
+ .dsm-workbuddy-pool .sw input:checked+.sw-track::after{transform:translateX(16px)}
1741
+ .dsm-workbuddy-pool .sw input:disabled+.sw-track{opacity:.4}
1742
+ .dsm-workbuddy-pool .sw input:disabled{cursor:default}
621
1743
  `;
622
1744
  //#endregion
623
1745
  //#region src/client/searched-paths.ts
@@ -866,16 +1988,25 @@ window.__ModuleLoader__.load({
866
1988
  month: "2-digit",
867
1989
  day: "2-digit",
868
1990
  hour: "2-digit",
869
- minute: "2-digit"
1991
+ minute: "2-digit",
1992
+ hourCycle: "h23"
870
1993
  }).format(new Date(value));
871
1994
  }
872
- /** Compact package-date rendering with time, e.g. 08/25 14:44. */
1995
+ /**
1996
+ * Compact package-date rendering with time, e.g. `08/25 14:44`.
1997
+ *
1998
+ * `hourCycle: 'h23'` is what makes that example TRUE. Without it `Intl` defers
1999
+ * to the browser locale, and en-US produced `08/25, 02:44 PM` — 12-hour, with a
2000
+ * comma the template never asked for. `h23` (not `hour12: false`) keeps midnight
2001
+ * at `00:00` instead of `24:00`, and matches DSH's own clock cycle.
2002
+ */
873
2003
  function formatDate(value) {
874
2004
  return new Intl.DateTimeFormat(void 0, {
875
2005
  month: "2-digit",
876
2006
  day: "2-digit",
877
2007
  hour: "2-digit",
878
- minute: "2-digit"
2008
+ minute: "2-digit",
2009
+ hourCycle: "h23"
879
2010
  }).format(new Date(value));
880
2011
  }
881
2012
  function formatCapacity(value, unknown) {
@@ -970,6 +2101,22 @@ window.__ModuleLoader__.load({
970
2101
  /** Save failure surfaced next to the buttons; cleared by the next attempt. */
971
2102
  const [saveError, setSaveError] = (0, react.useState)(void 0);
972
2103
  const [switchingAccount, setSwitchingAccount] = (0, react.useState)(false);
2104
+ /**
2105
+ * Whether the account pool's rotation currently owns this region's choice.
2106
+ *
2107
+ * Reported up by the pool section. While true, the manual account dropdown is
2108
+ * disabled: both would write the same slot, and letting them disagree is how
2109
+ * the card ends up showing one account while another is billed. The pool
2110
+ * shows the reason and an inline way to switch rotation off.
2111
+ */
2112
+ const [poolRotationLocked, setPoolRotationLocked] = (0, react.useState)(false);
2113
+ /**
2114
+ * Whether the account pool's save is in flight. Both sections write into one
2115
+ * region slot and the Host merges per-region, so two concurrent saves can
2116
+ * interleave on a stale base and revert each other while both report success
2117
+ * — the two save buttons are serialized to make that impossible.
2118
+ */
2119
+ const [poolBusy, setPoolBusy] = (0, react.useState)(false);
973
2120
  /** A refused account write (silently unpersisted settings on a locked file). */
974
2121
  const [accountError, setAccountError] = (0, react.useState)(void 0);
975
2122
  const [checkingIn, setCheckingIn] = (0, react.useState)(false);
@@ -998,7 +2145,37 @@ window.__ModuleLoader__.load({
998
2145
  (0, react.useEffect)(() => settingsScope?.subscribe(() => {
999
2146
  setSettingsRevision((value) => value + 1);
1000
2147
  }), [settingsScope]);
2148
+ /**
2149
+ * Per-region latest-wins guard for the usage fetch.
2150
+ *
2151
+ * Two refreshes can overlap — the 60s poll, a save, a batch action, the
2152
+ * account re-scan — and they are plain `fetch`es with no ordering guarantee.
2153
+ * Without a guard the SLOWER response wins, so a snapshot taken before a
2154
+ * check-in could land after one taken after it and overwrite the newer
2155
+ * credits. The guard makes "the last request started" the one that is applied,
2156
+ * whatever order the responses arrive in.
2157
+ *
2158
+ * Keyed by region, not global: the card deliberately fetches BOTH regions at
2159
+ * once (`for (const region of WORKBUDDY_REGIONS)` below), so a single shared
2160
+ * counter would make each of those two calls cancel the other and leave one
2161
+ * tab permanently stale.
2162
+ *
2163
+ * The rule itself is the tested `createLatestWins` factory, not a second
2164
+ * implementation written here.
2165
+ *
2166
+ * `begin()` returns a probe that reports **stale**: `true` once a newer call
2167
+ * has claimed the same region (see `src/account-pool.ts`). So the variable is
2168
+ * named `stale` and the bail-out is `if (stale())` — the same polarity as the
2169
+ * Host's rotation guard in `src/index.ts`. Naming it `fresh` and writing
2170
+ * `if (!fresh())` inverts the poll: every response that is NOT superseded —
2171
+ * i.e. every response in the single-fetch case — gets discarded, and the card
2172
+ * renders its placeholder forever. That defect shipped once; the polarity is
2173
+ * now pinned by a rendered assertion rather than by the spelling of the
2174
+ * identifier.
2175
+ */
2176
+ const usageGuard = (0, react.useRef)(createLatestWins());
1001
2177
  const refreshUsage = (0, react.useCallback)(async (region, signal) => {
2178
+ const stale = usageGuard.current.begin(region);
1002
2179
  try {
1003
2180
  const response = await fetch(withWorkBuddyRegion(WORKBUDDY_USAGE_PATH, region), {
1004
2181
  headers: { accept: "application/json" },
@@ -1008,19 +2185,34 @@ window.__ModuleLoader__.load({
1008
2185
  const value = await response.json().catch(() => void 0);
1009
2186
  if (!response.ok) throw new Error(`HTTP ${response.status}`);
1010
2187
  const usage = value;
2188
+ if (stale()) return void 0;
1011
2189
  if (mounted.current && signal?.aborted !== true) setStatusByRegion((prev) => ({
1012
2190
  ...prev,
1013
2191
  [region]: usage
1014
2192
  }));
1015
2193
  return usage;
1016
2194
  } catch (error) {
1017
- if (mounted.current && signal?.aborted !== true) setStatusByRegion((prev) => ({
1018
- ...prev,
1019
- [region]: {
1020
- status: "error",
1021
- message: error instanceof Error ? error.message : t("row.requestFailed")
1022
- }
1023
- }));
2195
+ if (stale()) return void 0;
2196
+ if (mounted.current && signal?.aborted !== true) {
2197
+ const message = error instanceof Error ? error.message : t("row.requestFailed");
2198
+ setStatusByRegion((prev) => {
2199
+ const previous = prev[region];
2200
+ if (previous !== void 0 && previous.status === "signed-in") return {
2201
+ ...prev,
2202
+ [region]: {
2203
+ ...previous,
2204
+ refreshError: message
2205
+ }
2206
+ };
2207
+ return {
2208
+ ...prev,
2209
+ [region]: {
2210
+ status: "error",
2211
+ message
2212
+ }
2213
+ };
2214
+ });
2215
+ }
1024
2216
  return;
1025
2217
  }
1026
2218
  }, [t]);
@@ -1203,6 +2395,7 @@ window.__ModuleLoader__.load({
1203
2395
  if (mounted.current) setStatusByRegion((prev) => ({
1204
2396
  ...prev,
1205
2397
  [activeRegion]: {
2398
+ ...prev[activeRegion],
1206
2399
  status: "error",
1207
2400
  message: error instanceof Error ? error.message : t("row.requestFailed")
1208
2401
  }
@@ -1454,7 +2647,7 @@ window.__ModuleLoader__.load({
1454
2647
  children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("input", {
1455
2648
  type: "checkbox",
1456
2649
  checked: regionOnState,
1457
- disabled: togglingRegion === region || !canWrite,
2650
+ disabled: togglingRegion === region || !canWrite || saving || poolBusy,
1458
2651
  "aria-label": t("row.tabSwitchAria", { region: region === "cn" ? t("row.tabCn") : t("row.tabGlobal") }),
1459
2652
  onChange: (event) => {
1460
2653
  toggleRegion(region, event.target.checked);
@@ -1518,7 +2711,7 @@ window.__ModuleLoader__.load({
1518
2711
  children: /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("select", {
1519
2712
  className: "dsm-workbuddy-usage-select",
1520
2713
  value: status.accounts.find((account) => account.selected)?.id ?? "",
1521
- disabled: switchingAccount || !canWrite,
2714
+ disabled: switchingAccount || !canWrite || poolRotationLocked,
1522
2715
  onChange: (event) => {
1523
2716
  switchAccount(event.currentTarget.value);
1524
2717
  },
@@ -1640,6 +2833,11 @@ window.__ModuleLoader__.load({
1640
2833
  className: "dsm-workbuddy-usage-error",
1641
2834
  children: t("row.creditsError", { message: status.creditsError })
1642
2835
  }),
2836
+ status.refreshError === void 0 ? null : /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
2837
+ className: "dsm-workbuddy-usage-error",
2838
+ role: "alert",
2839
+ children: t("row.requestFailedHint", { message: status.refreshError })
2840
+ }),
1643
2841
  /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("section", {
1644
2842
  className: "dsm-workbuddy-models",
1645
2843
  "aria-label": t("row.modelsTitle"),
@@ -1801,13 +2999,13 @@ window.__ModuleLoader__.load({
1801
2999
  children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
1802
3000
  type: "button",
1803
3001
  className: "dsm-btn dsm-btn-outline",
1804
- disabled: !dirty || saving,
3002
+ disabled: !dirty || saving || poolBusy || togglingRegion !== void 0,
1805
3003
  onClick: discardModels,
1806
3004
  children: t("row.discard")
1807
3005
  }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
1808
3006
  type: "button",
1809
3007
  className: "dsm-btn dsm-btn-primary",
1810
- disabled: !dirty || saving || activeEnabledIds.size === 0,
3008
+ disabled: !dirty || saving || poolBusy || togglingRegion !== void 0 || activeEnabledIds.size === 0,
1811
3009
  onClick: () => {
1812
3010
  saveModels();
1813
3011
  },
@@ -1817,6 +3015,19 @@ window.__ModuleLoader__.load({
1817
3015
  ]
1818
3016
  })
1819
3017
  ]
3018
+ }),
3019
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)(AccountPool, {
3020
+ t,
3021
+ region: activeRegion,
3022
+ ...status.pool === void 0 ? {} : { pool: status.pool },
3023
+ ...settingsScope === void 0 ? {} : { settingsScope },
3024
+ siblingBusy: saving || togglingRegion !== void 0,
3025
+ onBusyChange: setPoolBusy,
3026
+ onSaved: async () => await refreshUsage(activeRegion) !== void 0,
3027
+ onRefresh: () => {
3028
+ refreshUsage(activeRegion);
3029
+ },
3030
+ onRotationChange: setPoolRotationLocked
1820
3031
  })
1821
3032
  ] }) : null,
1822
3033
  status.status === "signed-out" ? /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
@@ -1883,6 +3094,15 @@ window.__ModuleLoader__.load({
1883
3094
  "row.credentialRejectedRelogin": "No other local sign-in exists to switch to. Sign in again in the WorkBuddy desktop app.",
1884
3095
  "row.credentialRejectedChoose": "Other local sign-ins exist but none of them answered the upstream just now. Try switching to one above; if none works, sign in again in the desktop app.",
1885
3096
  "row.requestFailed": "Request failed",
3097
+ "row.requestFailedHint": "Refresh failed — showing the last loaded data: {message}",
3098
+ "row.poolErrUnavailable": "The account pool is not available in this build (or its batch route is missing). Restart the app; if it persists, the plugin needs reinstalling.",
3099
+ "row.poolErrFailed": "The batch failed on the host side: {message}",
3100
+ "row.poolErrHttp": "The batch was refused (HTTP {status}). Check the plugin is up to date and try again.",
3101
+ "row.poolErrDisabled": "The account pool is switched off for this region. Turn it on and save before running a batch.",
3102
+ "row.poolErrNoMembers": "No account is checked into this pool — the batch had nothing to run. Check at least one account and save.",
3103
+ "row.poolErrNoLiveMembers": "Every account checked into this pool has lost its local sign-in, so the batch had nothing to run. Sign in again in the WorkBuddy desktop app, or save to drop them.",
3104
+ "row.poolErrNoFreeModel": "This region has no zero-multiplier model to test with. Refresh the model catalog, or pick a target model yourself.",
3105
+ "row.poolErrStaleModel": "The target model is no longer offered by this region. Pick another, or switch back to automatic.",
1886
3106
  "row.creditsTotalLabel": "Total remaining credits",
1887
3107
  "row.creditsMonthlyRemain": "Remaining {remain} / {size} · Refreshes {at}",
1888
3108
  "row.checkinClaim": "Check in",
@@ -1938,7 +3158,98 @@ window.__ModuleLoader__.load({
1938
3158
  "row.probeFailed": "✗ Test failed",
1939
3159
  "row.probeFailedStatus": "✗ Test failed (HTTP {status})",
1940
3160
  "row.probeError": "Could not run the test: {message}",
1941
- "row.cheer": "Star on GitHub"
3161
+ "row.cheer": "Star on GitHub",
3162
+ "row.poolTitle": "Account pool",
3163
+ "row.poolSummary": "{count} account(s) in this region · target model {model}",
3164
+ "row.poolNoCandidate": "No account in this pool can be used right now.",
3165
+ "row.poolNoCandidateHint": "Every account is rate-limited, out of credits, rejected, unreachable, or in a state this build cannot use. Re-check the accounts, or sign in again in the desktop app.",
3166
+ "row.poolRotating": "Auto-rotating",
3167
+ "row.poolCheckinAll": "Check in all accounts",
3168
+ "row.poolCheckingIn": "Checking in…",
3169
+ "row.poolTestAll": "Test all accounts",
3170
+ "row.poolTesting": "Testing…",
3171
+ "row.poolBusyHint": "Running one account at a time…",
3172
+ "row.poolTargetAuto": "Auto",
3173
+ "row.poolTargetStaleShort": "target model unavailable",
3174
+ "row.poolTargetNoneShort": "no free model",
3175
+ "row.poolTargetFree": "Auto-picked free model: {model}",
3176
+ "row.poolTargetPreferred": "Your chosen model: {model}",
3177
+ "row.poolTargetNone": "This region has no zero-multiplier model yet.",
3178
+ "row.poolTargetStale": "The target model you saved is no longer offered: {model}",
3179
+ "row.poolTargetStaleHint": "The region's catalog changed and no longer lists this model, so testing is off rather than running against a model the upstream may not accept. Pick another target, or switch back to automatic.",
3180
+ "row.poolTargetStaleClear": "Switch back to automatic",
3181
+ "row.poolTargetStaleOption": "{model} (no longer offered)",
3182
+ "row.poolTargetNoneHint": "The domestic catalog only reveals its multipliers after a model refresh. Rather than quietly spending credits on a paid model, testing stays off until one appears — refresh the models, or pick a target model yourself.",
3183
+ "row.poolColumnAccount": "Account",
3184
+ "row.poolColumnCredits": "Credits",
3185
+ "row.poolColumnProbe": "Target model",
3186
+ "row.poolColumnCheckin": "Check-in",
3187
+ "row.poolNeverTested": "Not tested yet",
3188
+ "row.poolTestedAt": "Tested {at}",
3189
+ "row.poolCheckedIn": "Checked in",
3190
+ "row.poolNotCheckedIn": "Not checked in",
3191
+ "row.poolCheckinUnknown": "—",
3192
+ "row.poolCreditSoon": "{count} expiring within 3 days",
3193
+ "row.poolCreditNearest": "Nearest package expires {at}",
3194
+ "row.poolExcludedRateLimited": "Rate limited",
3195
+ "row.poolExcludedOutOfCredit": "Out of credits",
3196
+ "row.poolExcludedRejected": "Rejected",
3197
+ "row.poolExcludedUnusable": "Unusable",
3198
+ "row.poolRetryAt": "Back after {at}",
3199
+ "row.poolRetryUnknown": "The upstream gave no time for when this frees up",
3200
+ "row.poolSettingsTitle": "Account pool settings",
3201
+ "row.poolSettingsHint": "These four are preferences: they take effect when you save (same as the model list). Test results and rotation are written automatically and are not affected by this button.",
3202
+ "row.poolEnabled": "Enable the account pool",
3203
+ "row.poolEnabledHint": "While off, the plugin behaves exactly as before: it follows the account you selected and never reorders accounts.",
3204
+ "row.poolRotate": "Rotate by credits",
3205
+ "row.poolRotateHint": "Let the plugin pick the billing account by availability, then credits, then expiry (ties fall back to credential freshness and account id). Turning this on disables manual selection until you save; every switch is recorded.",
3206
+ "row.poolInterval": "Automatic test interval",
3207
+ "row.poolIntervalHint": "Minutes between automatic tests of this region's accounts. Runs only while BOTH the pool and this region's provider are enabled; switching either off stops the timer.",
3208
+ "row.poolIntervalUnit": "minutes",
3209
+ "row.poolTargetLabel": "Target test model",
3210
+ "row.poolTargetHint": "Auto (default) picks a zero-multiplier model from this region's catalog, preferring the largest context window. The two regions can pick different models. A manual choice always wins.",
3211
+ "row.poolTargetAutoOption": "Auto — pick a free model",
3212
+ "row.poolSaved": "Save",
3213
+ "row.poolSaving": "Saving…",
3214
+ "row.poolSaveFailed": "Could not save: {message}",
3215
+ "row.poolSavedStaleRefresh": "Saved, but the panel could not re-read it. The value is stored; the next refresh will show it.",
3216
+ "row.poolDiscard": "Discard changes",
3217
+ "row.poolDirty": "● Unsaved changes",
3218
+ "row.poolSaveIdle": "Change any setting above to save it.",
3219
+ "row.poolSaveDirty": "You have unsaved changes — saving writes them to this region.",
3220
+ "row.poolManualLocked": "Manual selection is disabled: this region is rotating automatically",
3221
+ "row.poolManualLockedHint": "The plugin picks the account by availability, then credits, then expiry, so you cannot pin one manually. The dropdown above is disabled to avoid showing one account while another is billed.",
3222
+ "row.poolManualUnlock": "Turn off rotation",
3223
+ "row.poolUnlockPending": "Save to apply — until then the plugin is still rotating.",
3224
+ "row.poolUnlockSaved": "Rotation off — save to unlock",
3225
+ "row.poolLogTitle": "Activity",
3226
+ "row.poolLogClear": "Clear",
3227
+ "row.poolLogEmpty": "Nothing yet. Check-ins, tests, and account switches are recorded here.",
3228
+ "row.poolLogCheckinStart": "Checking in {count} account(s), one at a time",
3229
+ "row.poolLogCheckinClaimed": "{accountName}: checked in (+{credit})",
3230
+ "row.poolLogCheckinAlready": "{accountName}: already checked in today — skipped",
3231
+ "row.poolLogCheckinFailed": "{accountName}: check-in failed — {message}",
3232
+ "row.poolLogCheckinDone": "Check-in finished",
3233
+ "row.poolLogBatchFailed": "Batch failed — nothing ran: {message}",
3234
+ "row.poolLogTestStart": "Testing {count} account(s) against {model}",
3235
+ "row.poolLogTestRow": "{accountName}: {outcome}",
3236
+ "row.poolLogTestDone": "Test finished; the pool was re-ranked",
3237
+ "row.poolLogTestRowMalformed": "{accountName}: the host returned no result for this account",
3238
+ "row.poolLogRotated": "Switched billing from {from} to {to}",
3239
+ "row.poolLogRotationStopped": "Rotation stopped — back to {from}",
3240
+ "row.poolRegionNote": "The domestic and international pools are fully independent: accounts, switches, intervals, and target models never affect each other.",
3241
+ "row.poolMembersTitle": "Accounts in this pool",
3242
+ "row.poolMembersHint": "Only checked accounts are checked in, tested, and used for rotation. Nothing is selected by default — check the ones you want, then save.",
3243
+ "row.poolSelectAll": "Select all",
3244
+ "row.poolSelectNone": "Clear all",
3245
+ "row.poolSelectedCount": "{count} of {total} selected",
3246
+ "row.poolNoneSelected": "No account is checked into this pool.",
3247
+ "row.poolNoneSelectedHint": "Check at least one account above and save. Until then both buttons stay disabled, because a pool with no members has nothing to run on.",
3248
+ "row.poolGhostMembers": "{count} saved account(s) are no longer signed in on this machine, so they are not counted and not used. Save again to drop them.",
3249
+ "row.poolSelectAria": "Include {accountName} in this region's account pool",
3250
+ "row.poolMember": "In pool",
3251
+ "row.poolNotMember": "Not in pool",
3252
+ "row.poolUnsavedMembers": "Selection changed — save to apply"
1942
3253
  };
1943
3254
  const zh = {
1944
3255
  "row.title": "接入使用 WorkBuddy 积分与模型(dsh-connect-workbuddy)",
@@ -1975,6 +3286,15 @@ window.__ModuleLoader__.load({
1975
3286
  "row.credentialRejectedRelogin": "本机没有其他账号可切换。请在 WorkBuddy 桌面端重新登录。",
1976
3287
  "row.credentialRejectedChoose": "本机还有其他账号,但刚才都没能通过上游校验。可以在上方切换一个试试;如果都不行,请在桌面端重新登录。",
1977
3288
  "row.requestFailed": "请求失败",
3289
+ "row.requestFailedHint": "刷新失败——下方为上次加载的数据:{message}",
3290
+ "row.poolErrUnavailable": "本版本没有可用的账号池(或其批量接口缺失)。请重启应用;若仍不行,插件可能需要重新安装。",
3291
+ "row.poolErrFailed": "批量操作在宿主侧失败:{message}",
3292
+ "row.poolErrHttp": "批量操作被拒绝(HTTP {status})。请确认插件是最新版本后重试。",
3293
+ "row.poolErrDisabled": "本区域的账号池是关闭的。请先启用并保存,再执行批量操作。",
3294
+ "row.poolErrNoMembers": "本池没有勾选任何账号,批量操作没有可执行对象。请至少勾选一个账号并保存。",
3295
+ "row.poolErrNoLiveMembers": "本池勾选的账号在本机都已不再登录,批量操作没有可执行对象。请在 WorkBuddy 桌面端重新登录,或保存以移除它们。",
3296
+ "row.poolErrNoFreeModel": "本区域没有可用的免费(倍率为 0)模型。请先刷新模型目录,或自己指定一个目标模型。",
3297
+ "row.poolErrStaleModel": "目标模型已不在本区域目录中。请改选一个,或切回自动。",
1978
3298
  "row.creditsTotalLabel": "总剩余积分",
1979
3299
  "row.creditsMonthlyRemain": "剩余 {remain} / {size} · {at} 刷新",
1980
3300
  "row.checkinClaim": "立即签到",
@@ -2030,7 +3350,98 @@ window.__ModuleLoader__.load({
2030
3350
  "row.probeFailed": "✗ 测试失败",
2031
3351
  "row.probeFailedStatus": "✗ 测试失败(HTTP {status})",
2032
3352
  "row.probeError": "无法执行测试:{message}",
2033
- "row.cheer": "鼓励一下"
3353
+ "row.cheer": "鼓励一下",
3354
+ "row.poolTitle": "账号池",
3355
+ "row.poolSummary": "本区域 {count} 个账号 · 目标模型 {model}",
3356
+ "row.poolNoCandidate": "账号池里目前没有可用的账号。",
3357
+ "row.poolNoCandidateHint": "每个账号要么被限流、要么积分耗尽、要么被上游拒绝、要么连不上上游,或处于本版本无法使用的状态。请重新检测账号,或在桌面端重新登录。",
3358
+ "row.poolRotating": "自动轮换中",
3359
+ "row.poolCheckinAll": "一键签到所有账号",
3360
+ "row.poolCheckingIn": "签到中…",
3361
+ "row.poolTestAll": "一键测试所有账号",
3362
+ "row.poolTesting": "测试中…",
3363
+ "row.poolBusyHint": "正在逐个账号执行…",
3364
+ "row.poolTargetAuto": "自动",
3365
+ "row.poolTargetStaleShort": "目标模型已失效",
3366
+ "row.poolTargetNoneShort": "无免费模型",
3367
+ "row.poolTargetFree": "自动选中的免费模型:{model}",
3368
+ "row.poolTargetPreferred": "你指定的模型:{model}",
3369
+ "row.poolTargetNone": "本区域暂时没有倍率为 0 的免费模型。",
3370
+ "row.poolTargetStale": "你保存的目标模型已不在目录中:{model}",
3371
+ "row.poolTargetStaleHint": "本区域的模型目录已变化,不再包含这个模型,因此测试被停用——而不是拿一个上游可能不接受的模型去跑。请改选一个目标模型,或切回自动。",
3372
+ "row.poolTargetStaleClear": "切回自动",
3373
+ "row.poolTargetStaleOption": "{model}(已下架)",
3374
+ "row.poolTargetNoneHint": "国内版的倍率要等模型目录刷新后才会出现。为了不让你在不知情的情况下花掉积分,插件**不会**自动改用收费模型——请先刷新模型目录,或自己指定一个目标模型。",
3375
+ "row.poolColumnAccount": "账号",
3376
+ "row.poolColumnCredits": "积分",
3377
+ "row.poolColumnProbe": "目标模型",
3378
+ "row.poolColumnCheckin": "签到",
3379
+ "row.poolNeverTested": "尚未测试",
3380
+ "row.poolTestedAt": "测试于 {at}",
3381
+ "row.poolCheckedIn": "已签到",
3382
+ "row.poolNotCheckedIn": "未签到",
3383
+ "row.poolCheckinUnknown": "—",
3384
+ "row.poolCreditSoon": "{count} 积分 3 天内过期",
3385
+ "row.poolCreditNearest": "最近积分包 {at} 过期",
3386
+ "row.poolExcludedRateLimited": "被限流",
3387
+ "row.poolExcludedOutOfCredit": "积分耗尽",
3388
+ "row.poolExcludedRejected": "被拒绝",
3389
+ "row.poolExcludedUnusable": "不可用",
3390
+ "row.poolRetryAt": "{at} 之后可再用",
3391
+ "row.poolRetryUnknown": "上游未给出何时恢复",
3392
+ "row.poolSettingsTitle": "账号池设置",
3393
+ "row.poolSettingsHint": "下面四项是偏好设置:点保存才生效(与「模型管理」一致)。测试结果与轮换记录由插件自动写入,不受这个保存按钮影响。",
3394
+ "row.poolEnabled": "启用账号池",
3395
+ "row.poolEnabledHint": "关闭时插件行为与从前完全一致:跟随你选择的账号,绝不按积分重排。",
3396
+ "row.poolRotate": "按积分自动轮换",
3397
+ "row.poolRotateHint": "允许插件按「可用性 → 积分 → 可用时间」自动选择计费账号(并列时依次比凭据新鲜度与账号 id)。开启后需保存才停用手动选择;每次切换都会留下记录。",
3398
+ "row.poolInterval": "自动测试间隔",
3399
+ "row.poolIntervalHint": "每隔多少分钟自动测试本区域账号。需要「账号池」与本区域的供应商都启用;任一关闭即停止定时器。",
3400
+ "row.poolIntervalUnit": "分钟",
3401
+ "row.poolTargetLabel": "目标测试模型",
3402
+ "row.poolTargetHint": "「自动」(默认)会从本区域目录里挑一个倍率为 0 的免费模型,多个候选取上下文窗口最大的。国内版与国际版可能挑到不同的模型。手动指定优先于自动。",
3403
+ "row.poolTargetAutoOption": "自动 —— 挑一个免费模型",
3404
+ "row.poolSaved": "保存",
3405
+ "row.poolSaving": "保存中…",
3406
+ "row.poolSaveFailed": "保存失败:{message}",
3407
+ "row.poolSavedStaleRefresh": "已保存,但面板未能重新读取。设置已写入;下次刷新后会显示。",
3408
+ "row.poolDiscard": "放弃修改",
3409
+ "row.poolDirty": "● 有未保存的修改",
3410
+ "row.poolSaveIdle": "修改任一设置后即可保存。",
3411
+ "row.poolSaveDirty": "有未保存的修改 —— 保存后写入本区域配置。",
3412
+ "row.poolManualLocked": "手动选择已停用:本区域正在自动轮换",
3413
+ "row.poolManualLockedHint": "插件按「可用性 → 积分 → 可用时间」自动选择账号,因此不能手动指定。上面的下拉已置灰,避免出现\"显示 A 却计费 B\"。",
3414
+ "row.poolManualUnlock": "关闭自动轮换",
3415
+ "row.poolUnlockPending": "保存后生效 —— 在那之前插件仍在轮换。",
3416
+ "row.poolUnlockSaved": "已关闭轮换 —— 保存后解锁",
3417
+ "row.poolLogTitle": "活动记录",
3418
+ "row.poolLogClear": "清空",
3419
+ "row.poolLogEmpty": "尚无活动。签到、测试与账号切换都会记录在这里。",
3420
+ "row.poolLogCheckinStart": "开始签到 {count} 个账号(逐个执行)",
3421
+ "row.poolLogCheckinClaimed": "{accountName}:签到成功 +{credit}",
3422
+ "row.poolLogCheckinAlready": "{accountName}:今日已签到,跳过",
3423
+ "row.poolLogCheckinFailed": "{accountName}:签到失败 —— {message}",
3424
+ "row.poolLogCheckinDone": "签到完成",
3425
+ "row.poolLogBatchFailed": "批量操作失败 —— 没有执行:{message}",
3426
+ "row.poolLogTestStart": "开始测试 {count} 个账号 × {model}",
3427
+ "row.poolLogTestRow": "{accountName}:{outcome}",
3428
+ "row.poolLogTestDone": "测试完成,已重新计算候选账号",
3429
+ "row.poolLogTestRowMalformed": "{accountName}:Host 未返回该账号的结果",
3430
+ "row.poolLogRotated": "计费账号已从 {from} 切换到 {to}",
3431
+ "row.poolLogRotationStopped": "轮换已停止 —— 回到 {from}",
3432
+ "row.poolRegionNote": "国内版与国际版是完全独立的两个账号池:账号、开关、间隔、目标模型互不影响。",
3433
+ "row.poolMembersTitle": "本池包含的账号",
3434
+ "row.poolMembersHint": "只有勾选的账号才会被签到、测试和轮换。默认一个都不勾 —— 请勾选你要的账号,然后保存。",
3435
+ "row.poolSelectAll": "全选",
3436
+ "row.poolSelectNone": "全不选",
3437
+ "row.poolSelectedCount": "已选 {count} / {total}",
3438
+ "row.poolNoneSelected": "这个池里还没有勾选任何账号。",
3439
+ "row.poolNoneSelectedHint": "请在上方勾选至少一个账号并保存。在此之前两个按钮都不可用 —— 空池没有可执行的对象。",
3440
+ "row.poolGhostMembers": "有 {count} 个已保存的账号在本机已不再登录,因此不计入、也不会被使用。再保存一次即可移除它们。",
3441
+ "row.poolSelectAria": "把 {accountName} 加入本区域的账号池",
3442
+ "row.poolMember": "已在池中",
3443
+ "row.poolNotMember": "未入池",
3444
+ "row.poolUnsavedMembers": "勾选已改动 —— 保存后生效"
2034
3445
  };
2035
3446
  //#endregion
2036
3447
  //#region src/client/index.tsx