diff --git a/.claude/skills/product-owner/SKILL.md b/.claude/skills/product-owner/SKILL.md index 7c262f94e..ccd4010ee 100644 --- a/.claude/skills/product-owner/SKILL.md +++ b/.claude/skills/product-owner/SKILL.md @@ -7,8 +7,9 @@ user-invocable: true # Product Owner -One Claude Desktop session per product line is its Product Owner. The PO -coordinates; the sub-sessions it starts do the investigation and the work. +One session per product line and PO runtime (Claude Desktop, Qwen Code Desktop, +or Antigravity) is its Product Owner. The PO coordinates; the sub-sessions it +starts do the investigation and the work. `AGENTS.md` and the documents it routes to win over this skill. This skill adds the PO role on top of Rate's existing protocol (`AGENTS.md` sections 0, 1 and 5, `Docs/Resources/RELEASE.md`); it does not replace the claim labels, @@ -34,27 +35,33 @@ apply to it: "Starting a sub-session" (its brief), "Review gate", ## Lines and names -Two POs may run on the same repository at once: one in Claude Code and one -in Qwen Code Desktop (DOS/Rate#1673). They keep apart like this: +Multiple POs may run on the same repository at once: in Claude Code, Qwen +Code Desktop, and Antigravity (DOS/Rate#1673, DOS/Rate#1805). They keep apart +like this: -- **PO line label.** `po:claude` or `po:qwen` says which PO dispatched an - issue. A PO dispatches only issues with its own label or none, and adds its - label when it dispatches +- **PO line label.** `po:claude`, `po:qwen`, or `po:antigravity` says which PO + dispatched an issue. A PO dispatches only issues with its own label or none, + and adds its label when it dispatches (`gh issue edit -R DOS/Rate --add-label po:claude`). `board.mjs` adds - the claimant's line label on a claim and refuses an issue of the other line - without `--take-over` (JOY's assignment only). A claimant of a tool that - runs no PO (for example `codex:...`) gets no `po:*` label and is not + the claimant's line label on a claim and refuses an issue of another PO's + line without `--take-over` (JOY's assignment only). A claimant of a tool + that runs no PO (for example `codex:...`) gets no `po:*` label and is not refused by line; such an agent still respects the labels by this rule. - **Separate state.** Each PO keeps its own state and check-in file, named - per tool (`po-state.claude.md`, `po-state.qwen.md`), outside the - repository (in that PO's own notes folder), never committed, and never - writes the other's. -- **One promoter.** Only the Claude Code PO runs `promote.mjs` and the - `verify-live.mjs` check after it. The Qwen PO asks the Claude Code PO (or - JOY, if it cannot reach it) when its merged work needs a promotion. - `promote.mjs` refuses to run when the session's claimant (resolved as - `board.mjs` does) is not `claude:` or cannot be resolved: a guard against - mistakes, not access control. + per tool and per line (`po-state.claude.md`, `po-state.qwen.md`, or + per-line `*-antigravity-po-checkin.md` under `~/.claude/po-state/` for + Antigravity: `dos-rate-core-antigravity-po-checkin.md` for Rate Core and + `dos-rate-services-services-antigravity-po-checkin.md` for Rate Services), + outside the repository (in that PO's own notes or `po-state` folder), never + committed, and never writes another PO's or line's file. +- **Authorized promoters.** Normally the Claude Code PO runs `promote.mjs` and + the `verify-live.mjs` check after it; on Claude Code quota failover or JOY's + assignment, the Antigravity PO runs them instead (DOS/Rate#1849). The Qwen PO + (and the Antigravity PO when neither on quota failover nor assigned by JOY) + asks the active promoting PO (or JOY, if it cannot reach it) when merged work + needs a promotion. `promote.mjs` refuses to run when the session's claimant + (resolved as `board.mjs` does) is not `claude:` or `antigravity:`, or cannot + be resolved: a guard against mistakes, not access control. - The claim lock (see "Claims") keeps their sub-sessions off each other's issues even when two take the same issue at the same moment. @@ -172,7 +179,9 @@ names a role and two sessions can share it: workflow runs on it. - The lock records the **claimant**, `:`. Claude Code sessions get `claude:` automatically (the desktop session id, - the one `SendMessage` uses). Qwen Code sessions pass `--claimant qwen:` on every call. + the one `SendMessage` uses). Qwen Code sessions pass + `--claimant qwen:` and Antigravity sessions pass + `--claimant antigravity:` on every call. `RATE_CLAIMANT` may only be set for one session, never in a shell profile or an environment other sessions (sub-sessions included) inherit; a Claude Code session id always wins over it. `board.mjs` prints @@ -189,7 +198,7 @@ names a role and two sessions can share it: - A lock taken before a merged PR last closed the issue is stale: the merge ended that work. On a reopened issue, a claim (`in-progress` or `in-review`) replaces a stale lock without `--take-over` (and its stale - `agent:*` label; the other PO's `po:*` label still needs `--take-over`), + `agent:*` label; another PO's `po:*` label still needs `--take-over`), and the lock comment names the lock it replaced. A release does not: on an open issue only the holder releases, or the PO with `--force-release`. A close that was not a merge (not planned, by hand) never makes a lock stale. @@ -270,8 +279,10 @@ the next session claims only after that comment. pages over Project #9 (more than 300 items) time out with 504 or return only the first 30 items; look an issue's board item up from the issue as `AGENTS.md` 1 shows, or page Project #9 GraphQL in pages of 50 or fewer. -2. Skip issues labelled with the other PO's line (`po:qwen` for the Claude - Code PO, `po:claude` for the Qwen PO); see "Lines and names". +2. Skip issues labelled with another PO's line (`po:qwen` and + `po:antigravity` for the Claude Code PO, `po:claude` and `po:antigravity` + for the Qwen PO, `po:claude` and `po:qwen` for the Antigravity PO); see + "Lines and names". Order: `incident` first, then `status:ready`, then other open issues. `status:in-progress` and `status:in-review` issues are someone's claim: check whether they are live or orphaned (see "Claims"). @@ -333,8 +344,9 @@ claim. Use `start_session` with a fresh context and its own worktree. Use `initiation: "user_asked"` only when JOY told the PO to dispatch work in the PO chat; otherwise the session is a proposal card JOY has to start. Worktree: -(`/.claude/worktrees/`, `AGENTS.md` 0.5). The brief is the only -context the session gets, so it carries: +(`/.claude/worktrees/` or `/.gemini/worktrees/` by +runtime, `AGENTS.md` 0.5). The brief is the only context the session gets, so +it carries: - **Task**: the issue link, the problem in a few lines, and the acceptance from the issue. @@ -346,7 +358,8 @@ context the session gets, so it carries: ("Starting a sub-session", "Review gate", "Coordinating", "Stop lines"). - **Process**: claim with `node scripts/ops/board.mjs --status in-progress --agent ` before - editing (a Qwen sub-session adds `--claimant qwen:`); + editing (a Qwen sub-session adds `--claimant qwen:`; an + Antigravity sub-session adds `--claimant antigravity:`); English issue, PR and commit text; PR into `dev` with `Closes #` and a `Claimant: ` line; `board.mjs --status in-review --agent ` once the PR is open; the review gate (below); the PO acceptance gate; then @@ -367,9 +380,9 @@ context the session gets, so it carries: or the shared notes folder, not here. - **Reporting**: the wrap-up is a recap only, never a question or buttons for JOY. Decisions, approvals and access needs go to the PO with SendMessage - (`to`: the PO's `local_...` session id). Reports are in Vietnamese with full - diacritics and no em-dashes or en-dashes; the first line says complete, - running or stopped. + (`to`: the PO's `local_...` session id or Antigravity `conversationId`). + Reports are in Vietnamese with full diacritics and no em-dashes or + en-dashes; the first line says complete, running or stopped. ## Review gate @@ -493,7 +506,9 @@ secrets and credentials (GitHub, Vercel, Supabase, `AI_API_KEY`, The normal `dev` -> `main` promotion is not one of these steps: it stays batched as `AGENTS.md` 0.2 and `Docs/Resources/RELEASE.md` say, needs no -per-release question, and is run by the Claude Code PO only (`node scripts/ops/promote.mjs`, +per-release question, and is run by the Claude Code PO (or the Antigravity PO +on quota failover / JOY's assignment, passing +`--claimant antigravity:`: `node scripts/ops/promote.mjs`, then `node scripts/ops/verify-live.mjs --wait 900`) at the first checkpoint: no ready backlog left, 10 or more PRs waiting on `dev`, the oldest unpromoted change older than 24 hours, or the end of a long working session. diff --git a/.github/labels.yml b/.github/labels.yml index fbcc2af20..96cac737d 100644 --- a/.github/labels.yml +++ b/.github/labels.yml @@ -67,12 +67,15 @@ color: 5319e7 description: Task completed and verified -# Product Owner line, AGENTS.md section 6 (DOS/Rate#1673): which PO -# dispatched the issue. A PO dispatches only issues with its own label or -# none; scripts/ops/board.mjs adds the claimant's line on a claim. +# Product Owner line, AGENTS.md section 6 (DOS/Rate#1673, DOS/Rate#1805): +# which PO dispatched the issue. A PO dispatches only issues with its own +# label or none; scripts/ops/board.mjs adds the claimant's line on a claim. - name: po:claude color: 0052cc description: Dispatched by the Claude Code Product Owner - name: po:qwen color: 0052cc description: Dispatched by the Qwen Code Product Owner +- name: po:antigravity + color: 0052cc + description: Dispatched by the Antigravity Product Owner diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md index 3771bc68f..4d5115b5d 100644 --- a/.github/pull_request_template.md +++ b/.github/pull_request_template.md @@ -12,7 +12,7 @@ Claimant: : +claude:local_1234abcd, qwen:5678efgh or antigravity:. --> ## Checklist - [ ] Build passes: `pnpm --filter build` diff --git a/AGENTS.md b/AGENTS.md index a2d9c70a9..09dcecf6d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -18,7 +18,7 @@ Tài liệu này tổng hợp đầy đủ **User-Level Hard Rules (`~/AGENTS.md - Không bao giờ đưa lệnh terminal, shell snippet hay code bảo JOY tự chạy hoặc tự dán. Agent phải tự chạy tất cả. - Không bao giờ bảo JOY tự review code diff hay bấm nút Merge PR ("chờ mày merge"). Agent phải chạy code review (`superpowers:code-reviewer` / subagent fresh-context review), sửa hết lỗi, đợi CI xanh và **tự động merge PR** (`gh pr merge`). - Chỉ hỏi ý kiến JOY cho: quyết định sản phẩm/kiến trúc, thao tác rủi ro cao (xóa dữ liệu, thay đổi prod, tiêu tiền, sửa khác repo `cross-repo writes`), hoặc bước bắt buộc cần người thật (2FA, CAPTCHA, OAuth device code). - - **PR promote `dev` -> `main` (deploy production) cũng do agent tự merge.** JOY không phải coder, không biết merge và không bấm nút Merge cho bất kỳ PR nào, kể cả PR promote. **Promote theo đợt, không hỏi JOY mỗi lần:** agent cứ làm task liên tục, không kết thúc task bằng câu hỏi "deploy lên production nhé?". Agent tự mở và merge PR promote khi gặp một trong các mốc (khi có PO thì chỉ PO Claude Code promote, xem Mục 6): hết backlog; `dev` dồn từ 10 PR chưa promote trở lên; thay đổi cũ nhất chưa promote đã quá 24 giờ; hoặc agent kết thúc một phiên làm việc dài. Chỉ promote khi CI của `dev` head xanh và không có PR nào đang sửa dở một lỗi đã lên production. Merge bằng merge commit (`gh pr merge --merge`, không squash/rebase), rồi tự kiểm tra bản live theo `Docs/Resources/RELEASE.md`. Không bao giờ viết "chờ JOY merge", "JOY duyệt merge" hay "JOY merge bằng merge commit". Vẫn phải hỏi JOY trước những việc ngoài một lần promote thông thường (migration DOS-Me, sửa dữ liệu production, đổi credential). + - **PR promote `dev` -> `main` (deploy production) cũng do agent tự merge.** JOY không phải coder, không biết merge và không bấm nút Merge cho bất kỳ PR nào, kể cả PR promote. **Promote theo đợt, không hỏi JOY mỗi lần:** agent cứ làm task liên tục, không kết thúc task bằng câu hỏi "deploy lên production nhé?". Agent tự mở và merge PR promote khi gặp một trong các mốc (khi có PO thì chỉ PO Claude Code hoặc PO Antigravity khi failover quota / JOY giao mới promote, xem Mục 6): hết backlog; `dev` dồn từ 10 PR chưa promote trở lên; thay đổi cũ nhất chưa promote đã quá 24 giờ; hoặc agent kết thúc một phiên làm việc dài. Chỉ promote khi CI của `dev` head xanh và không có PR nào đang sửa dở một lỗi đã lên production. Merge bằng merge commit (`gh pr merge --merge`, không squash/rebase), rồi tự kiểm tra bản live theo `Docs/Resources/RELEASE.md`. Không bao giờ viết "chờ JOY merge", "JOY duyệt merge" hay "JOY merge bằng merge commit". Vẫn phải hỏi JOY trước những việc ngoài một lần promote thông thường (migration DOS-Me, sửa dữ liệu production, đổi credential). 3. **Ngôn ngữ & Định dạng Giao tiếp:** - **Trả lời trực tiếp JOY (Private / Direct Chat):** Luôn dùng **Tiếng Việt có dấu đầy đủ 100%** trên bề mặt giao tiếp trực tiếp với JOY (chat, câu hỏi `ask_question`, nhãn lựa chọn). Giữ nguyên thuật ngữ kỹ thuật thông dụng bằng tiếng Anh (`API`, `commit`, `branch`, `PR`, `CI`, `build`, `deploy`, `repo`, `merge`, `push`, `workflow`, `token`, `key`, `env`, `prod`, `staging`). @@ -43,9 +43,9 @@ Tài liệu này tổng hợp đầy đủ **User-Level Hard Rules (`~/AGENTS.md - Ngoại lệ duy nhất: **rollback** về một bản production cũ đã build từ Git (`vercel rollback`), vì không build lại. Sau đó sửa tiếp qua PR hotfix. - **Script vận hành có sẵn trong repo (`scripts/ops/`, dùng thay cho lệnh gõ tay):** - `node scripts/ops/merge-when-green.mjs `: chờ commit head xanh rồi merge, ghim theo SHA head. Xanh nghĩa là mọi check run và mọi commit status (Vercel) đều đạt, và các check mà ruleset bắt buộc đã báo kết quả. PR vào `main` luôn dùng merge commit, PR khác mặc định squash. `--ignore ""` chỉ dùng khi một check không bắt buộc đang hỏng có lý do đã ghi trong PR. - - `node scripts/ops/promote.mjs`: mở hoặc dùng lại PR promote `dev` -> `main`, liệt kê các PR được phát hành, merge bằng merge commit khi CI xanh. Script từ chối chạy khi claimant của session (tính như `board.mjs`) không phải `claude:` (#1675, xem Mục 6). + - `node scripts/ops/promote.mjs [--claimant :]`: mở hoặc dùng lại PR promote `dev` -> `main`, liệt kê các PR được phát hành, merge bằng merge commit khi CI xanh. Script từ chối chạy khi claimant của session (tính như `board.mjs`) không thuộc `claude:` hoặc `antigravity:` (#1675, #1849, xem Mục 6). - `node scripts/ops/verify-live.mjs --wait 900`: kiểm tra rate.vn chạy đúng commit của `main` (`/api/health` trả `commit`), database đọc được và các route chính trả 200. Script đọc lại `main` mỗi vòng chờ. Chỉ khi bản live chậm hơn `main`, nó mới in lệnh `vercel promote --scope metados`; nếu bản live đi trước hoặc lệch nhánh so với `main`, nó dặn không làm gì. Không bao giờ redeploy hay promote một deployment build từ commit khác (`promote` không build lại, và bật lại tự gán domain sau một lần `vercel rollback`). - - `node scripts/ops/board.mjs --status in-progress|in-review|ready|backlog|done --agent [--claimant :]`: lấy, giữ hoặc nhả khóa claim `refs/claims/` của session, rồi cập nhật nhãn và Project #9 (xem mục 1). Script từ chối issue đang bị session khác giữ khóa, đang mang nhãn `agent:*` của agent khác hoặc nhãn `po:*` của PO kia; `--take-over` chỉ dùng khi agent đó đã bàn giao hoặc JOY chỉ định, `--adopt` chỉ cho claim cũ (trước khóa) của chính session này. `--force-release --agent PO --reason "..."` gỡ khóa mồ côi (PO). + - `node scripts/ops/board.mjs --status in-progress|in-review|ready|backlog|done --agent [--claimant :]`: lấy, giữ hoặc nhả khóa claim `refs/claims/` của session, rồi cập nhật nhãn và Project #9 (xem mục 1). Script từ chối issue đang bị session khác giữ khóa, đang mang nhãn `agent:*` của agent khác hoặc nhãn `po:*` của PO khác; `--take-over` chỉ dùng khi agent đó đã bàn giao hoặc JOY chỉ định, `--adopt` chỉ cho claim cũ (trước khóa) của chính session này. `--force-release --agent PO --reason "..."` gỡ khóa mồ côi (PO). 7. **Chủ động thực thi liên tục & đề xuất việc tiếp theo (Always-On Proactive Backlog - Skill `proactive-backlog`):** - **Luôn kích hoạt mặc định ở MỌI lượt hội thoại (không chỉ trong `/goal`):** Mọi Agent (Antigravity, Claude Code, Codex) phải luôn tuân theo quy trình khép kín của skill `proactive-backlog` (`~/.gemini/config/skills/proactive-backlog/SKILL.md`, `~/.claude/skills/proactive-backlog/SKILL.md`, `~/.codex/skills/proactive-backlog/SKILL.md`). @@ -88,10 +88,10 @@ gh issue list -R DOS/Rate-Services --state open **Luôn claim bằng `board.mjs`**, một lệnh làm cả khóa claim, nhãn lẫn board (tự thêm issue vào Project #9 nếu chưa có, chỉ giữ một nhãn `status:*`): `node scripts/ops/board.mjs --status in-progress --agent $agentNick`. Các trạng thái khác: `ready`, `in-review`, `done`, `backlog`. Các lệnh `gh` dưới đây chỉ đặt nhãn và board, **không lấy khóa claim**, nên chỉ để tham khảo hoặc sửa board bằng tay. - **Khóa claim nguyên tử theo từng session (#1673):** nickname chỉ là vai trò (`Core`, `Web`), nên hai session cùng nickname vẫn có thể giẫm lên nhau. Vì vậy `board.mjs` với `--status in-progress` hoặc `in-review` lấy khóa `refs/claims/`: một git ref trong repo của issue, GitHub chỉ tạo khi ref đó chưa tồn tại (HTTP 422 nếu đã có), nên hai session claim cùng lúc thì đúng một bên thắng, bên kia bị từ chối kèm tên session đang giữ. Ref này không chạy workflow nào và không vào bản clone thường. **Không tự tạo, sửa hay xóa ref `refs/claims/*` bằng tay.** - - **Claimant** là id của một session, dạng `:`, được ghi trong khóa và trong comment `board.mjs` tự đăng lên issue. Session Claude Code tự có `claude:` (từ `CLAUDE_CODE_HOST_SESSION_ID`, cũng là id để `SendMessage` tới session đó). Qwen Code và công cụ khác truyền `--claimant qwen:` ở mỗi lệnh. Biến môi trường `RATE_CLAIMANT` chỉ được đặt riêng cho một session, **không bao giờ** trong shell profile hay môi trường mà session khác (kể cả session con) thừa kế; id session Claude Code luôn được ưu tiên hơn biến này. Không có claimant thì `board.mjs` từ chối. + - **Claimant** là id của một session, dạng `:`, được ghi trong khóa và trong comment `board.mjs` tự đăng lên issue. Session Claude Code tự có `claude:` (từ `CLAUDE_CODE_HOST_SESSION_ID`, cũng là id để `SendMessage` tới session đó). Qwen Code truyền `--claimant qwen:`, Antigravity truyền `--claimant antigravity:` (và công cụ khác truyền `--claimant :`) ở mỗi lệnh. Biến môi trường `RATE_CLAIMANT` chỉ được đặt riêng cho một session, **không bao giờ** trong shell profile hay môi trường mà session khác (kể cả session con) thừa kế; id session Claude Code luôn được ưu tiên hơn biến này. Không có claimant thì `board.mjs` từ chối. - Claim lại bởi chính session đang giữ khóa thì không đổi gì. `in-review` giữ khóa. `ready`, `backlog` và `done` nhả khóa; chỉ session đang giữ được nhả, trừ khi issue đã đóng (đã merge) thì ai cũng nhả được. - Nhả khóa không xóa ref (#1675): `board.mjs` thay khóa bằng một commit "tombstone" (`release: ...`, `Released-By: `), cũng bằng compare-and-swap, nên một `--take-over` chen vào giữa lúc đọc và lúc nhả không bị xóa mất (lệnh nhả báo lỗi thay vì ghi đè). Tombstone tính là khóa trống: claim sau đó thay nó, check `task-claim` coi như không có khóa. Mỗi issue từng được claim giữ lại một ref. - - Khóa cũ (#1675): khóa được lấy **trước** lần gần nhất một PR đã merge đóng issue là khóa cũ, vì việc nó giữ đã xong khi PR merge. Khi issue được mở lại, claim (`--status in-progress` hoặc `in-review`) thay khóa cũ mà không cần `--take-over` (nhãn `agent:*` đi kèm khóa cũ cũng vậy; nhãn `po:*` của PO kia vẫn cần `--take-over`), và comment khóa ghi rõ khóa cũ bị thay. Nhả khóa thì không: issue đang mở chỉ session giữ khóa được nhả, hoặc PO dùng `--force-release`. Issue đóng mà không do PR merge (not planned, đóng tay) không làm khóa thành khóa cũ. Không có workflow nào tự gỡ khóa khi issue đóng. + - Khóa cũ (#1675): khóa được lấy **trước** lần gần nhất một PR đã merge đóng issue là khóa cũ, vì việc nó giữ đã xong khi PR merge. Khi issue được mở lại, claim (`--status in-progress` hoặc `in-review`) thay khóa cũ mà không cần `--take-over` (nhãn `agent:*` đi kèm khóa cũ cũng vậy; nhãn `po:*` của PO khác vẫn cần `--take-over`), và comment khóa ghi rõ khóa cũ bị thay. Nhả khóa thì không: issue đang mở chỉ session giữ khóa được nhả, hoặc PO dùng `--force-release`. Issue đóng mà không do PR merge (not planned, đóng tay) không làm khóa thành khóa cũ. Không có workflow nào tự gỡ khóa khi issue đóng. - Session vẫn làm tiếp một issue sau khi issue được mở lại thì chạy lại ngay `board.mjs --status in-progress --agent ` để lấy khóa mới; nếu không, khóa của nó là khóa cũ và session khác claim được. - `--take-over` (chỉ khi có comment bàn giao hoặc JOY giao) chuyển khóa sang session mới, và chỉ thành công nếu khóa không đổi kể từ lúc đọc. - Bàn giao: session cũ chạy `board.mjs --status ready` (nhả khóa, `board.mjs` comment "Claim lock ... released"); session mới chỉ claim sau khi thấy comment đó. @@ -234,13 +234,13 @@ Mỗi finding khi review (subagent fresh-context, bot, hoặc người) phải > > Bài học 2026-10-27: session PO của Rate Core chạy nhiều giờ mà không nạp skill, chỉ biết quy tắc qua brief của chính nó, và hỏi JOY quá nhiều. -JOY có thể giao một session Claude Desktop làm **Product Owner (PO)** cho một line: **Rate Core** (issue của `DOS/Rate`) hoặc **Rate Services** (issue của `DOS/Rate-Services`). PO điều phối backlog, mở session con cho từng issue, trả lời câu hỏi của chúng và chỉ mang quyết định thật sự lên JOY. Toàn bộ quy trình nằm trong skill [`.claude/skills/product-owner/SKILL.md`](./.claude/skills/product-owner/SKILL.md); skill dùng lại giao thức claim ở Mục 1 (`agent:`, `status:*`, khóa `refs/claims/` theo claimant, `board.mjs`, check `task-claim`), không thêm giao thức claim thứ hai. +JOY có thể giao một session (Claude Desktop, Qwen Code Desktop, hoặc Antigravity) làm **Product Owner (PO)** cho một line: **Rate Core** (issue của `DOS/Rate`) hoặc **Rate Services** (issue của `DOS/Rate-Services`). PO điều phối backlog, mở session con cho từng issue, trả lời câu hỏi của chúng và chỉ mang quyết định thật sự lên JOY. Toàn bộ quy trình nằm trong skill [`.claude/skills/product-owner/SKILL.md`](./.claude/skills/product-owner/SKILL.md) (và [`docs/product-owner-config.md`](./docs/product-owner-config.md) cho plugin `cc-po`); skill dùng lại giao thức claim ở Mục 1 (`agent:`, `status:*`, khóa `refs/claims/` theo claimant, `board.mjs`, check `task-claim`), không thêm giao thức claim thứ hai. Quy tắc cho chính các PO: -- **Hai PO trên cùng repo (#1673):** JOY có thể chạy hai PO song song, một trong Claude Code và một trong Qwen Code Desktop. Nhãn `po:claude` và `po:qwen` cho biết PO nào điều phối issue. Mỗi PO chỉ giao issue mang nhãn của mình hoặc chưa có nhãn `po:*`, và gắn nhãn của mình khi giao (`gh issue edit -R DOS/Rate --add-label po:claude`). `board.mjs` tự thêm nhãn line theo claimant khi claim, và từ chối issue mang nhãn của PO kia nếu không có `--take-over` (chỉ khi JOY giao). Claimant của công cụ không chạy PO (ví dụ `codex:...`) không được thêm nhãn `po:*` và không bị chặn theo line; agent đó vẫn phải tôn trọng nhãn `po:*` theo quy tắc này. Session con của PO Qwen dùng claimant `qwen:`, của PO Claude Code dùng `claude:`. -- **Trạng thái PO tách riêng:** mỗi PO có file trạng thái và check-in riêng theo công cụ, `po-state.claude.md` hoặc `po-state.qwen.md`, đặt **ngoài repo** (trong thư mục ghi chú của chính PO đó, ví dụ thư mục notes của session PO), không bao giờ commit, và không bao giờ ghi vào file của PO kia. -- **Chỉ một PO promote:** `promote.mjs` (`dev` -> `main`) và `verify-live.mjs` sau đó chỉ do PO Claude Code chạy. PO Qwen cần promote thì nhắn PO Claude Code (qua JOY nếu không nhắn trực tiếp được), không tự chạy. `promote.mjs` từ chối chạy khi claimant của session không phải `claude:` hoặc không xác định được (#1675). Đây là rào chắn chống nhầm, không phải phân quyền: claimant có thể truyền tay bằng `--claimant`. +- **Nhiều PO song song trên cùng repo (#1673, #1805):** JOY có thể chạy các PO song song trên cùng repo trong Claude Code (`po:claude`), Qwen Code Desktop (`po:qwen`), và Antigravity (`po:antigravity`). Nhãn `po:claude`, `po:qwen`, và `po:antigravity` cho biết PO nào điều phối issue. Mỗi PO chỉ giao issue mang nhãn của mình hoặc chưa có nhãn `po:*`, và gắn nhãn của mình khi giao (ví dụ `gh issue edit -R DOS/Rate --add-label po:claude`). `board.mjs` tự thêm nhãn line theo claimant khi claim, và từ chối issue mang nhãn `po:*` của PO khác nếu không có `--take-over` (chỉ khi JOY giao). Claimant của công cụ không chạy PO (ví dụ `codex:...`) không được thêm nhãn `po:*` và không bị chặn theo line; agent đó vẫn phải tôn trọng nhãn `po:*` theo quy tắc này. Session con của PO Claude Code dùng claimant `claude:`, của PO Qwen dùng `qwen:`, của PO Antigravity dùng `antigravity:`. +- **Trạng thái PO tách riêng:** mỗi PO có file trạng thái và check-in riêng theo công cụ và theo line (`po-state.claude.md`, `po-state.qwen.md`, hoặc file `*-antigravity-po-checkin.md` theo từng line trong `~/.claude/po-state/` cho PO Antigravity: `dos-rate-core-antigravity-po-checkin.md` cho Rate Core, `dos-rate-services-services-antigravity-po-checkin.md` cho Rate Services), đặt **ngoài repo** (trong thư mục ghi chú hoặc `po-state` riêng của chính PO đó), không bao giờ commit, và không bao giờ ghi vào file của PO khác hay line khác. +- **Chỉ PO được phép promote:** `promote.mjs` (`dev` -> `main`) và `verify-live.mjs` sau đó do PO Claude Code chạy (hoặc PO Antigravity khi PO Claude hết quota / được JOY giao, truyền `--claimant antigravity:`, #1849). PO Qwen (hoặc PO Antigravity khi chưa failover và chưa được JOY giao) cần promote thì nhắn PO đang giữ quyền promote (qua JOY nếu không nhắn trực tiếp được), không tự chạy. `promote.mjs` từ chối chạy khi claimant của session không phải `claude:` hay `antigravity:`, hoặc không xác định được (#1675, #1849). Đây là rào chắn chống nhầm, không phải phân quyền: claimant có thể truyền qua `--claimant`. Khi một session do PO mở (session con), các quy tắc sau thay đổi so với Mục 0 và Mục 1: @@ -252,5 +252,5 @@ Khi một session do PO mở (session con), các quy tắc sau thay đổi so v - **`merge-when-green.mjs` của chính PO cũng có thể bị từ chối** (bài học 2026-10-27, lý do "Merge Without Review") cho tới khi JOY duyệt đúng PR đó trong chat của PO. Một câu chung như "chủ động lên" không phải là lời duyệt merge. Khi đó, thay cho câu "agent tự merge" của Mục 0.2, PO không thử lại mà **gom mọi PR đã qua cổng chấp nhận nhưng chưa merge được (session con hoặc chính PO bị từ chối) vào MỘT câu hỏi ngắn** gửi JOY ("PR #a, #b, #c: merge?") thay vì hỏi từng PR, rồi tự chạy script cho đúng các PR JOY duyệt. Không bao giờ bảo JOY tự bấm Merge. - **Nhả issue (release) là một lần bàn giao:** session con nhả issue thì comment lý do và chỗ dừng rồi chạy `board.mjs --status ready --agent `; session sau được dùng `--take-over` và dẫn link comment đó. Claim không có bàn giao nhưng trông như bị bỏ rơi (ví dụ sau khi đổi máy) chỉ được lấy lại khi JOY đồng ý (Mục 0.6); khi đó session mới claim với `--take-over` (thay khóa cũ), hoặc nếu chưa có ai nhận thì PO gỡ khóa bằng `--force-release` như Mục 1. - **Done của thay đổi runtime:** issue tự đóng khi PR merge vào `dev`; với thay đổi runtime, PO chuyển sang `done` sau khi promote và `verify-live.mjs` đạt. Thay đổi docs, CI, tooling thì `done` ngay khi merge. -- PR promote `dev` -> `main` vẫn theo đợt như Mục 0.2, do PO Claude Code chạy (xem "Chỉ một PO promote" ở trên), không do session con. +- PR promote `dev` -> `main` vẫn theo đợt như Mục 0.2, do PO Claude Code (hoặc PO Antigravity khi failover quota / JOY giao) chạy (xem "Chỉ PO được phép promote" ở trên), không do session con. - **Rate Services khác Rate Core:** `DOS/Rate-Services` không có nhánh `dev`, không có check `task-claim` và không có `scripts/ops/`; PR vào `main`, và `board.mjs`/`merge-when-green.mjs` chạy từ checkout `DOS/Rate` với `--repo DOS/Rate-Services`. Chi tiết trong skill. diff --git a/apps/extension/src/background/service-worker.ts b/apps/extension/src/background/service-worker.ts index 5e9505ad9..029c94ecb 100644 --- a/apps/extension/src/background/service-worker.ts +++ b/apps/extension/src/background/service-worker.ts @@ -1,8 +1,13 @@ import { RATE_API_V1_ENDPOINTS } from '@repo/shared-data'; +import { + EXTENSION_MARKETPLACES, + isExtensionMarketplaceHost, +} from '@repo/shared-data/rules'; import type { ExtensionLookupData, ExtensionSettings, ExtractedPageProductSignal, + SupportedEcommercePlatform, } from '../types.js'; import { detectEcommercePlatform, @@ -19,6 +24,8 @@ import { ONBOARDING_PAGE_PATH, sanitizeExtensionProductSignal, selectFreshestSessionSignal, + sliceCodePoints, + stripLoneSurrogates, } from '../security-guards.js'; import { LookupCooldown } from '../rate-limit.js'; import { @@ -205,17 +212,219 @@ function normalizeQuickQueryBareMarketplaceUrl( return sanitizeProductUrl(`https://${hostAndPath}`); } -// The latest product lookup per tab (DOS/Rate#1300, #1664). +// The latest product lookup per tab (DOS/Rate#1300, #1664, #1809). let detectRequestCounter = 0; const latestDetectByTab = new Map(); let fullLookupRequestCounter = 0; const latestFullLookupByTab = new Map(); let latestSelectionCounter = 0; +let latestPageSelectionCounter = 0; +let settingsUpdateChain: Promise = Promise.resolve(); let pendingQuickQueryReceipt: { updatedAt: number; apiBaseUrl: string; data: ExtensionLookupData | null; } | null = null; + +interface VerifiedMarketplaceUrl { + marketplace: SupportedEcommercePlatform; + origin: string; +} + +function resolvePositiveIntId(value: unknown): number | undefined { + return typeof value === 'number' && Number.isInteger(value) && value > 0 + ? value + : undefined; +} + +function resolveMarketplaceFromHttpsUrl( + rawUrl: unknown +): VerifiedMarketplaceUrl | null { + if (typeof rawUrl !== 'string') return null; + const trimmed = rawUrl.trim(); + if (!trimmed || trimmed.length > 8192 || /[\s\p{Cc}]/u.test(trimmed)) { + return null; + } + try { + const parsed = new URL(trimmed); + if ( + parsed.protocol !== 'https:' || + parsed.username || + parsed.password || + parsed.port !== '' + ) { + return null; + } + const host = parsed.hostname.toLowerCase(); + if ( + !host || + host.startsWith('.') || + host.endsWith('.') || + host.includes('..') + ) { + return null; + } + for (const marketplace of EXTENSION_MARKETPLACES) { + if (isExtensionMarketplaceHost(marketplace, host)) { + return { marketplace, origin: parsed.origin.toLowerCase() }; + } + } + return null; + } catch { + return null; + } +} + +interface ContentScriptMessageSender { + id?: string; + frameId?: number; + documentLifecycle?: string; + origin?: string; + tab?: unknown; + url?: string; +} + +function validateContentScriptSender( + sender: ContentScriptMessageSender | null | undefined, + options?: { requireSignal?: boolean; rawSignal?: unknown } +): { ok: true } | { ok: false; error: string } { + if (!sender || typeof sender !== 'object' || Array.isArray(sender)) { + return { ok: false, error: 'Invalid message sender' }; + } + const runtimeId = + typeof chrome !== 'undefined' && + typeof chrome.runtime?.id === 'string' && + chrome.runtime.id.length > 0 + ? chrome.runtime.id + : undefined; + if ( + runtimeId && + typeof sender.id === 'string' && + sender.id.length > 0 && + sender.id !== runtimeId + ) { + return { ok: false, error: 'Untrusted extension sender' }; + } + if (typeof sender.frameId === 'number' && sender.frameId !== 0) { + return { + ok: false, + error: 'Subframe content-script messages are not allowed', + }; + } + if ( + typeof sender.documentLifecycle === 'string' && + sender.documentLifecycle !== 'active' + ) { + return { + ok: false, + error: 'Inactive document lifecycle messages are not allowed', + }; + } + if ( + !sender.tab || + typeof sender.tab !== 'object' || + Array.isArray(sender.tab) + ) { + return { + ok: false, + error: 'Content-script messages must originate from a browser tab', + }; + } + const senderTab = sender.tab as { + id?: unknown; + windowId?: unknown; + url?: unknown; + }; + if ( + resolvePositiveIntId(senderTab.id) === undefined && + resolvePositiveIntId(senderTab.windowId) === undefined + ) { + return { + ok: false, + error: 'Content-script sender tab lacks a valid positive identifier', + }; + } + let senderIdentity: VerifiedMarketplaceUrl | null = null; + if (sender.url !== undefined && sender.url !== null) { + senderIdentity = resolveMarketplaceFromHttpsUrl(sender.url); + if (!senderIdentity) { + return { + ok: false, + error: 'Sender URL is not an allowed marketplace origin', + }; + } + } + if (sender.origin !== undefined && sender.origin !== null) { + const originIdentity = resolveMarketplaceFromHttpsUrl(sender.origin); + if ( + !originIdentity || + (senderIdentity !== null && + (originIdentity.marketplace !== senderIdentity.marketplace || + originIdentity.origin !== senderIdentity.origin)) + ) { + return { + ok: false, + error: 'Sender origin is not an allowed marketplace origin', + }; + } + senderIdentity ??= originIdentity; + } + if ( + senderIdentity === null && + senderTab.url !== undefined && + senderTab.url !== null + ) { + senderIdentity = resolveMarketplaceFromHttpsUrl(senderTab.url); + if (!senderIdentity) { + return { + ok: false, + error: 'Sender tab URL is not an allowed marketplace origin', + }; + } + } + if (options?.requireSignal) { + const rawSignal = options.rawSignal; + if ( + !rawSignal || + typeof rawSignal !== 'object' || + Array.isArray(rawSignal) + ) { + return { ok: false, error: 'Invalid product signal' }; + } + const candidate = rawSignal as { + platform?: unknown; + canonicalUrl?: unknown; + }; + const declaredPlatform = + typeof candidate.platform === 'string' + ? candidate.platform.trim().toLowerCase() + : ''; + const canonicalIdentity = resolveMarketplaceFromHttpsUrl( + candidate.canonicalUrl + ); + if ( + !canonicalIdentity || + declaredPlatform !== canonicalIdentity.marketplace + ) { + return { + ok: false, + error: + 'Signal platform and canonicalUrl must match an allowed marketplace', + }; + } + if ( + senderIdentity !== null && + (declaredPlatform !== senderIdentity.marketplace || + canonicalIdentity.origin !== senderIdentity.origin) + ) { + return { + ok: false, + error: 'Sender URL origin or platform does not match product signal', + }; + } + } + return { ok: true }; +} async function maybeSendOptInCrowdSignal( rawSignal: ExtractedPageProductSignal ): Promise { @@ -358,25 +567,181 @@ chrome.runtime.onMessage.addListener((message, sender, sendResponse) => { // CRITICAL MV3 Rule: Call chrome.sidePanel.open synchronously in the first turn // before any await so the user gesture from clicking the Shadow DOM Pill is preserved! if (msgType === 'RATE_OPEN_SIDE_PANEL') { - const tabId = sender.tab?.id; - const windowId = sender.tab?.windowId; - if (tabId) { - void chrome.sidePanel.open({ tabId }); - } else if (windowId) { - void chrome.sidePanel.open({ windowId }); + const senderCheck = validateContentScriptSender(sender); + if (!senderCheck.ok) { + sendResponse({ ok: false, error: senderCheck.error }); + return false; + } + const tabId = resolvePositiveIntId(sender.tab?.id); + const windowId = resolvePositiveIntId(sender.tab?.windowId); + try { + if (tabId) { + void Promise.resolve(chrome.sidePanel.open({ tabId })).catch(() => { + // Ignore rejections when user gesture expired or tab closed + }); + } else if (windowId) { + void Promise.resolve(chrome.sidePanel.open({ windowId })).catch(() => { + // Ignore rejections when user gesture expired or window closed + }); + } + } catch { + // Ignore synchronous errors if sidePanel API is unavailable } sendResponse({ ok: true }); return false; } + if (msgType === 'RATE_PRODUCT_CLEARED') { + const senderCheck = validateContentScriptSender(sender); + if (!senderCheck.ok) { + sendResponse({ ok: false, error: senderCheck.error }); + return false; + } + const clearId = ++detectRequestCounter; + const tabId = resolvePositiveIntId(sender.tab?.id); + const isBackgroundTab = Boolean(sender.tab && sender.tab.active === false); + const clearPageSeq = !isBackgroundTab ? ++latestPageSelectionCounter : null; + const selectionAtClearEntry = latestSelectionCounter; + if (tabId) latestDetectByTab.set(tabId, clearId); + const isLatestClear = () => + tabId + ? latestDetectByTab.get(tabId) === clearId + : clearPageSeq !== null && + latestPageSelectionCounter === clearPageSeq && + latestSelectionCounter === selectionAtClearEntry; + (async () => { + try { + await updateActionBadge(tabId, null, isLatestClear); + if (!isLatestClear()) { + sendResponse({ ok: true, stale: true }); + return; + } + const readKeys = tabId + ? [`tab_${tabId}`, 'tab_latest', 'lookup_tab_latest'] + : ['tab_latest', 'lookup_tab_latest']; + const sessionData = await chrome.storage.session.get(readKeys); + if (!isLatestClear()) { + sendResponse({ ok: true, stale: true }); + return; + } + const tabEntry = tabId + ? (sessionData[`tab_${tabId}`] as + | { + signal?: ExtractedPageProductSignal; + updatedAt?: number; + source?: 'page' | 'quick_query'; + } + | undefined) + : undefined; + const latestEntry = sessionData.tab_latest as + | { + signal?: ExtractedPageProductSignal; + updatedAt?: number; + source?: 'page' | 'quick_query'; + } + | undefined; + const hasNewerQuickQuery = + latestEntry?.source === 'quick_query' && + Boolean(latestEntry.signal) && + (typeof latestEntry.updatedAt !== 'number' || + typeof tabEntry?.updatedAt !== 'number' || + latestEntry.updatedAt >= tabEntry.updatedAt); + const canClearLatestNow = () => + !hasNewerQuickQuery && + latestSelectionCounter === selectionAtClearEntry && + (clearPageSeq !== null + ? latestPageSelectionCounter === clearPageSeq + : Boolean( + tabEntry?.signal && + latestEntry?.signal && + tabEntry.updatedAt !== undefined && + tabEntry.updatedAt === latestEntry.updatedAt && + tabEntry.signal.canonicalUrl === latestEntry.signal.canonicalUrl + )); + + const ownsCurrentLatest = canClearLatestNow(); + if (ownsCurrentLatest) { + pendingQuickQueryReceipt = null; + } + const sessionStorage = chrome.storage + .session as typeof chrome.storage.session & { + remove?: (keys: string | string[]) => Promise; + }; + if (typeof sessionStorage.remove === 'function') { + if ( + ownsCurrentLatest && + sessionData.lookup_tab_latest === undefined + ) { + await sessionStorage.set({ lookup_tab_latest: null }); + if (!isLatestClear()) { + sendResponse({ ok: true, stale: true }); + return; + } + } + const finalKeysToClear: string[] = []; + if (tabId) { + finalKeysToClear.push(`tab_${tabId}`, `lookup_tab_${tabId}`); + } + if (canClearLatestNow()) { + pendingQuickQueryReceipt = null; + finalKeysToClear.push('tab_latest', 'lookup_tab_latest'); + } + if (finalKeysToClear.length > 0) { + await sessionStorage.remove(finalKeysToClear); + } + } else { + if (ownsCurrentLatest && sessionData.lookup_tab_latest === null) { + await sessionStorage.set({ lookup_tab_latest: false }); + if (!isLatestClear()) { + sendResponse({ ok: true, stale: true }); + return; + } + } + const keysToNull: string[] = []; + if (tabId) { + keysToNull.push(`tab_${tabId}`, `lookup_tab_${tabId}`); + } + if (canClearLatestNow()) { + pendingQuickQueryReceipt = null; + keysToNull.push('tab_latest', 'lookup_tab_latest'); + } + if (keysToNull.length > 0) { + await sessionStorage.set( + Object.fromEntries(keysToNull.map((k) => [k, null])) + ); + } + } + sendResponse({ ok: true }); + } catch (err) { + sendResponse({ + ok: false, + error: + err instanceof Error ? err.message : 'Product state clear failed', + }); + } + })(); + return true; + } + if (msgType === 'RATE_PRODUCT_DETECTED') { + const senderCheck = validateContentScriptSender(sender, { + requireSignal: true, + rawSignal: (message as { signal?: unknown }).signal, + }); + if (!senderCheck.ok) { + sendResponse({ ok: false, error: senderCheck.error }); + return false; + } const requestId = ++detectRequestCounter; - const tabId = sender.tab?.id; + const tabId = resolvePositiveIntId(sender.tab?.id); const isBackgroundTab = Boolean(sender.tab && sender.tab.active === false); const latestOwnerSeq = !isBackgroundTab ? ++latestSelectionCounter : null; + const pageOwnerSeq = !isBackgroundTab ? ++latestPageSelectionCounter : null; if (tabId) latestDetectByTab.set(tabId, requestId); const ownsTabLatest = () => - latestOwnerSeq !== null && latestSelectionCounter === latestOwnerSeq; + latestOwnerSeq !== null && + latestSelectionCounter === latestOwnerSeq && + latestPageSelectionCounter === pageOwnerSeq; // Only the tab's latest lookup may set its badge, stored lookup or // panel: an earlier one can answer after a later one (DOS/Rate#1300). const isLatest = () => @@ -497,14 +862,18 @@ chrome.runtime.onMessage.addListener((message, sender, sendResponse) => { } const fullSeq = ++fullLookupRequestCounter; const detectSnapshotAtEntry = new Map(latestDetectByTab); + const selectionAtEntry = latestSelectionCounter; + const pageSelectionAtEntry = latestPageSelectionCounter; (async () => { try { const cleanedVariant = typeof message.selectedVariant === 'string' - ? message.selectedVariant - .replace(/\p{Cc}+/gu, ' ') - .trim() - .slice(0, 200) + ? sliceCodePoints( + stripLoneSurrogates(message.selectedVariant) + .replace(/\p{Cc}+/gu, ' ') + .trim(), + 200 + ) : ''; const overrideVariant = cleanedVariant || null; const [activeTab] = await chrome.tabs.query({ @@ -569,6 +938,11 @@ chrome.runtime.onMessage.addListener((message, sender, sendResponse) => { trackedTabId !== undefined && latestDetectByTab.get(trackedTabId) === detectSeqAtEntry && latestFullLookupByTab.get(trackedTabId) === fullSeq; + const isCurrentFallbackLookup = () => + fullSeq === fullLookupRequestCounter && + latestSelectionCounter === selectionAtEntry && + (isQuickQuerySelected || + latestPageSelectionCounter === pageSelectionAtEntry); const effectiveSignal: ExtractedPageProductSignal = overrideVariant ? { ...baseSignal, selectedVariant: overrideVariant } @@ -591,7 +965,7 @@ chrome.runtime.onMessage.addListener((message, sender, sendResponse) => { }, }); } - } else if (fullSeq === fullLookupRequestCounter) { + } else if (isCurrentFallbackLookup()) { await chrome.storage.session.set({ tab_latest: { signal: effectiveSignal, @@ -609,7 +983,7 @@ chrome.runtime.onMessage.addListener((message, sender, sendResponse) => { latestEntry?.updatedAt === pendingQuickQueryReceipt.updatedAt && settings.apiBaseUrl === pendingQuickQueryReceipt.apiBaseUrl ) { - if (fullSeq !== fullLookupRequestCounter) { + if (!isCurrentFallbackLookup()) { sendResponse({ ok: true, settings, @@ -646,7 +1020,7 @@ chrome.runtime.onMessage.addListener((message, sender, sendResponse) => { } const stale = isActiveTabPageSignal ? !isCurrentTabLookup() - : fullSeq !== fullLookupRequestCounter; + : !isCurrentFallbackLookup(); sendResponse( outcome.ok ? { @@ -692,10 +1066,12 @@ chrome.runtime.onMessage.addListener((message, sender, sendResponse) => { try { const rawQuery = typeof message.query === 'string' - ? message.query - .replace(/\p{Cc}+/gu, ' ') - .trim() - .slice(0, 500) + ? sliceCodePoints( + stripLoneSurrogates(message.query) + .replace(/\p{Cc}+/gu, ' ') + .trim(), + 500 + ) : ''; const settings = await getSettings(); if (!rawQuery) { @@ -821,7 +1197,7 @@ chrome.runtime.onMessage.addListener((message, sender, sendResponse) => { }); return false; } - (async () => { + const runSettingsUpdate = async (): Promise => { try { const nextSettings: Partial = {}; let serverChanged = false; @@ -863,7 +1239,11 @@ chrome.runtime.onMessage.addListener((message, sender, sendResponse) => { error: err instanceof Error ? err.message : 'Settings update failed', }); } - })(); + }; + settingsUpdateChain = settingsUpdateChain.then( + runSettingsUpdate, + runSettingsUpdate + ); return true; } diff --git a/apps/extension/src/content/content-script.ts b/apps/extension/src/content/content-script.ts index e0e033b8e..977e221f6 100644 --- a/apps/extension/src/content/content-script.ts +++ b/apps/extension/src/content/content-script.ts @@ -1,4 +1,7 @@ -import { extractProductSignalFromDom } from '../extractors/ecommerce-detector.js'; +import { + extractProductSignalFromDom, + sanitizeProductUrl, +} from '../extractors/ecommerce-detector.js'; import { buildProductSignalSignature, formatSafeExtensionVnd, @@ -32,21 +35,38 @@ function isValidPillVndPrice(amount: unknown): amount is number { ); } -function formatCurrencyVnd(amount: number | null | undefined): string { - return formatSafeExtensionVnd(amount, t('priceUpdating')); +function formatCurrencyVnd( + amount: number | null | undefined, + locale = t('langCode') +): string { + return formatSafeExtensionVnd(amount, t('priceUpdating'), locale); } /** * Render an isolated Shadow DOM Floating Trust Pill on supported e-commerce pages. * Zero host CSS pollution; clicking opens the Chrome Native Side Panel. */ -function renderShadowTrustPill(lookup: ExtensionLookupData): void { +function renderShadowTrustPill( + lookup: ExtensionLookupData, + expectedGeneration = detectGeneration, + expectedCanonicalUrl?: string +): void { if (!shouldRenderTrustPill(lookup)) { removeTrustPillHost(); return; } requestAnimationFrame(() => { + if (expectedGeneration !== detectGeneration) { + return; + } + if ( + expectedCanonicalUrl && + sanitizeProductUrl(window.location.href) !== expectedCanonicalUrl + ) { + void inspectCurrentPage(); + return; + } let host = document.getElementById(HOST_ID); if (!host) { host = document.createElement('div'); @@ -55,6 +75,7 @@ function renderShadowTrustPill(lookup: ExtensionLookupData): void { } const shadow = host.shadowRoot || host.attachShadow({ mode: 'open' }); + const uiLocale = t('langCode'); const assessment = lookup.priceAssessment; // The verdict in the extension's language (DOS/Rate#1326). const verdict = verdictTexts(assessment); @@ -78,11 +99,17 @@ function renderShadowTrustPill(lookup: ExtensionLookupData): void { const cheaperSummary = hasCheaperOffers && isValidPillVndPrice(assessment.maxSavingsAmount) ? t('pillCheaperAt', [ - formatSafeNumber(assessment.cheaperOfferCount, { min: 1 }), - formatCurrencyVnd(assessment.maxSavingsAmount), + formatSafeNumber( + assessment.cheaperOfferCount, + { min: 1 }, + uiLocale + ), + formatCurrencyVnd(assessment.maxSavingsAmount, uiLocale), ]) : isValidPillVndPrice(assessment.marketMinPrice) - ? t('pillMarketLow', [formatCurrencyVnd(assessment.marketMinPrice)]) + ? t('pillMarketLow', [ + formatCurrencyVnd(assessment.marketMinPrice, uiLocale), + ]) : t('pillPrompt'); const radarSig = lookup.radarSignal; const radarSpreadPct = Number(radarSig?.spreadPct ?? 0); @@ -95,14 +122,22 @@ function renderShadowTrustPill(lookup: ExtensionLookupData): void { cls: 'radar-deal', icon: '🔥', text: t('pillRadarDeal', [ - formatSafeNumber(radarSig.savingsPct, { min: 0, max: 100 }), + formatSafeNumber( + radarSig.savingsPct, + { min: 0, max: 100 }, + uiLocale + ), ]), } : { cls: 'radar-deal', icon: '✅', text: t('pillRadarBelowMedian', [ - formatSafeNumber(radarSig.savingsPct, { min: 0, max: 100 }), + formatSafeNumber( + radarSig.savingsPct, + { min: 0, max: 100 }, + uiLocale + ), ]), } : radarSig.verdict === 'fake_sale_trap' @@ -110,10 +145,14 @@ function renderShadowTrustPill(lookup: ExtensionLookupData): void { cls: 'radar-trap', icon: '🚨', text: t('pillRadarTrap', [ - formatSafeNumber(radarSig.fakeMarkupPct, { - min: 0, - max: 10000, - }), + formatSafeNumber( + radarSig.fakeMarkupPct, + { + min: 0, + max: 10000, + }, + uiLocale + ), ]), } : Number.isFinite(radarSpreadPct) && radarSpreadPct >= 5 @@ -121,7 +160,11 @@ function renderShadowTrustPill(lookup: ExtensionLookupData): void { cls: 'radar-spread', icon: '📊', text: t('pillRadarSpread', [ - formatSafeNumber(radarSig.spreadPct, { min: 0, max: 10000 }), + formatSafeNumber( + radarSig.spreadPct, + { min: 0, max: 10000 }, + uiLocale + ), ]), } : null @@ -130,7 +173,7 @@ function renderShadowTrustPill(lookup: ExtensionLookupData): void { ? `${escapeHtml(radarBadge.text)}` : ''; const ratingText = trustedRating - ? `${formatSafeNumber(trustedRating, { min: 0, max: 5, decimals: 1 })}${authenticRatio == null ? '' : ` ${t('pillAuthentic', [formatSafeNumber(authenticRatio, { min: 0, max: 100 })])}`}` + ? `${formatSafeNumber(trustedRating, { min: 0, max: 5, decimals: 1 }, uiLocale)}${authenticRatio == null ? '' : ` ${t('pillAuthentic', [formatSafeNumber(authenticRatio, { min: 0, max: 100 }, uiLocale)])}`}` : ''; shadow.innerHTML = ` @@ -254,7 +297,7 @@ function renderShadowTrustPill(lookup: ExtensionLookupData): void { const trigger = shadow.getElementById('rate-pill-trigger'); if (trigger) { const openSidePanel = () => { - void chrome.runtime.sendMessage({ type: 'RATE_OPEN_SIDE_PANEL' }); + sendRuntimeMessageFireAndForget({ type: 'RATE_OPEN_SIDE_PANEL' }); }; trigger.addEventListener('click', openSidePanel); trigger.addEventListener('keydown', (event: KeyboardEvent) => { @@ -267,27 +310,79 @@ function renderShadowTrustPill(lookup: ExtensionLookupData): void { }); } +function sendRuntimeMessageFireAndForget( + payload: Record +): void { + try { + void Promise.resolve(chrome.runtime.sendMessage(payload)).catch(() => { + // Ignore messaging rejections during page unload or worker restart + }); + } catch { + // Ignore synchronous messaging errors if extension context was invalidated + } +} + // Lookups sent from this page, so a late answer for an earlier product is -// ignored (DOS/Rate#1300). +// ignored (DOS/Rate#1300, #1809). let detectGeneration = 0; let lastProcessedSignature = ''; +let hasDetectedProduct = false; +let prerenderListenerAttached = false; // After a rate limit the same product is looked up again once the wait is over // (DOS/Rate#1466). const rateLimitRetry = new RateLimitRetry(); +function deferWhilePrerendering(): boolean { + const prerenderingDoc = document as Document & { + prerendering?: boolean; + addEventListener?: ( + type: string, + listener: () => void, + options?: { once?: boolean } + ) => void; + }; + if (prerenderingDoc.prerendering !== true) { + return false; + } + if ( + !prerenderListenerAttached && + typeof prerenderingDoc.addEventListener === 'function' + ) { + prerenderListenerAttached = true; + prerenderingDoc.addEventListener( + 'prerenderingchange', + () => { + prerenderListenerAttached = false; + void inspectCurrentPage(); + }, + { once: true } + ); + } + return true; +} + async function inspectCurrentPage(): Promise { + if (deferWhilePrerendering()) return; requestAnimationFrame(async () => { + if (deferWhilePrerendering()) return; const signal = extractProductSignalFromDom(document, window.location.href); if (!signal) { + ++detectGeneration; + const shouldNotifyCleared = hasDetectedProduct; + hasDetectedProduct = false; lastProcessedSignature = ''; rateLimitRetry.track(''); removeTrustPillHost(); + if (shouldNotifyCleared) { + sendRuntimeMessageFireAndForget({ type: 'RATE_PRODUCT_CLEARED' }); + } return; } const signature = buildProductSignalSignature(signal); if (signature === lastProcessedSignature) return; lastProcessedSignature = signature; + hasDetectedProduct = true; rateLimitRetry.track(signature); // Only the latest page's answer may draw or clear the pill: on a // single-page shop an earlier lookup can answer after a later one. @@ -306,12 +401,22 @@ async function inspectCurrentPage(): Promise { }; if (generation !== detectGeneration || response?.stale === true) return; + if (sanitizeProductUrl(window.location.href) !== signal.canonicalUrl) { + void inspectCurrentPage(); + return; + } + if (response?.ok === false && response.status === undefined) { + lastProcessedSignature = ''; + hasDetectedProduct = false; + removeTrustPillHost(); + return; + } rateLimitRetry.after(signature, response, () => { lastProcessedSignature = ''; void inspectCurrentPage(); }); if (response?.ok && response.data) { - renderShadowTrustPill(response.data); + renderShadowTrustPill(response.data, generation, signal.canonicalUrl); } else { // Nothing matched or the lookup failed: never leave the previous // product's pill on a single-page shop (DOS/Rate#1300). @@ -325,13 +430,39 @@ async function inspectCurrentPage(): Promise { }); } +let debounceTimer: ReturnType | null = null; +function scheduleImmediateInspection(): void { + if (debounceTimer) { + clearTimeout(debounceTimer); + debounceTimer = null; + } + void inspectCurrentPage(); +} + // Initial inspection + lightweight observation for SPA route/variant selection changes void inspectCurrentPage(); -let debounceTimer: ReturnType | null = null; +if (typeof window !== 'undefined') { + if (typeof window.addEventListener === 'function') { + window.addEventListener('popstate', scheduleImmediateInspection); + window.addEventListener('hashchange', scheduleImmediateInspection); + } + const nav = ( + window as Window & { + navigation?: { + addEventListener?: (type: string, listener: () => void) => void; + }; + } + ).navigation; + if (nav && typeof nav.addEventListener === 'function') { + nav.addEventListener('currententrychange', scheduleImmediateInspection); + } +} + const observer = new MutationObserver(() => { if (debounceTimer) clearTimeout(debounceTimer); debounceTimer = setTimeout(() => { + debounceTimer = null; void inspectCurrentPage(); }, 700); }); diff --git a/apps/extension/src/extractors/ecommerce-detector.ts b/apps/extension/src/extractors/ecommerce-detector.ts index 30af4123b..fc06bf6c1 100644 --- a/apps/extension/src/extractors/ecommerce-detector.ts +++ b/apps/extension/src/extractors/ecommerce-detector.ts @@ -3,6 +3,7 @@ import type { ExtractedStockState, SupportedEcommercePlatform, } from '../types.js'; +import { sliceCodePoints, stripLoneSurrogates } from '../surrogate-safe.js'; /** * Strip all tracking query strings (sp_atk, xptdk, utm_*, fbclid, etc.) and hashes. @@ -785,7 +786,7 @@ export function extractRatingFromJsonLd(aggRaw: unknown): { export function cleanExtractedProductTitle(rawTitle: string): string { if (typeof rawTitle !== 'string') return ''; - const withoutPlatformSuffix = rawTitle + const withoutPlatformSuffix = stripLoneSurrogates(rawTitle) .replace(/\p{Cc}+/gu, ' ') .replace( /\s*(?:\||[-–—])\s*(?:Shopee(?:\s*Việt\s*Nam|\s*VN)?|Lazada(?:\s*Việt\s*Nam|\s*VN)?|Tiki(?:\.vn)?|TikTok\s*Shop|CellphoneS(?:\.com\.vn)?|Thế\s*Giới\s*Di\s*Động|Thegioididong(?:\.com)?|TopZone(?:\.vn)?|Điện\s*Máy\s*Xanh|FPT\s*Shop|Fptshop(?:\.com\.vn)?|Hoàng\s*Hà\s*Mobile|HoangHaMobile(?:\.com)?|Di\s*Động\s*Việt|Didongviet(?:\.vn)?|Phong\s*Vũ|Phongvu(?:\.vn)?).*$/i, @@ -795,7 +796,7 @@ export function cleanExtractedProductTitle(rawTitle: string): string { .trim(); if (!withoutPlatformSuffix.includes('|')) { - return withoutPlatformSuffix.slice(0, 500); + return sliceCodePoints(withoutPlatformSuffix, 500); } const pipeSegments = withoutPlatformSuffix @@ -812,7 +813,10 @@ export function cleanExtractedProductTitle(rawTitle: string): string { } } - return keptSegments.join(' ').replace(/\s+/g, ' ').trim().slice(0, 500); + return sliceCodePoints( + keptSegments.join(' ').replace(/\s+/g, ' ').trim(), + 500 + ); } const CONCRETE_WAI_ARIA_ROLES = new Set([ @@ -944,7 +948,7 @@ export function extractSelectedVariantFromDom(doc: Document): string | null { return; } } - const txt = (node.textContent || '') + const txt = stripLoneSurrogates(node.textContent || '') .replace(/\p{Cc}+/gu, ' ') .replace(/\s+/g, ' ') .trim(); @@ -959,7 +963,7 @@ export function extractSelectedVariantFromDom(doc: Document): string | null { } if (pickedLabels.length > 0) { - return pickedLabels.join(' - ').slice(0, 200); + return sliceCodePoints(pickedLabels.join(' - '), 200) || null; } return null; } diff --git a/apps/extension/src/security-guards.ts b/apps/extension/src/security-guards.ts index e1cb1865f..d28bf39ee 100644 --- a/apps/extension/src/security-guards.ts +++ b/apps/extension/src/security-guards.ts @@ -7,6 +7,17 @@ import type { SupportedEcommercePlatform, } from './types.js'; import { t, type MessageKey } from './i18n.js'; +import { + encodeSurrogateSafeUriComponent, + sliceCodePoints, + stripLoneSurrogates, +} from './surrogate-safe.js'; + +export { + encodeSurrogateSafeUriComponent, + sliceCodePoints, + stripLoneSurrogates, +}; export const DEFAULT_API_BASE_URL = 'https://rate.vn'; @@ -351,19 +362,23 @@ export function sanitizeExtensionProductSignal( const trimmedTitle = typeof safeSignal.title === 'string' - ? safeSignal.title - .replace(/\p{Cc}+/gu, ' ') - .replace(/\s+/g, ' ') - .trim() - .slice(0, 500) + ? sliceCodePoints( + stripLoneSurrogates(safeSignal.title) + .replace(/\p{Cc}+/gu, ' ') + .replace(/\s+/g, ' ') + .trim(), + 500 + ) : ''; const trimmedVariant = typeof safeSignal.selectedVariant === 'string' - ? safeSignal.selectedVariant - .replace(/\p{Cc}+/gu, ' ') - .replace(/\s+/g, ' ') - .trim() - .slice(0, 200) || null + ? sliceCodePoints( + stripLoneSurrogates(safeSignal.selectedVariant) + .replace(/\p{Cc}+/gu, ' ') + .replace(/\s+/g, ' ') + .trim(), + 200 + ) || null : null; return { @@ -482,8 +497,7 @@ export function buildExtensionObservationV1( // v1 allows 120 characters; a longer label is cut, not a reason to // drop the observation. variant_label: signal.selectedVariant - ? Array.from(signal.selectedVariant).slice(0, 120).join('').trim() || - null + ? sliceCodePoints(signal.selectedVariant, 120).trim() || null : null, price_vnd: signal.price, list_price_vnd: signal.originalPrice, @@ -530,9 +544,33 @@ export function escapeSafeExternalHref( } } +const CZECH_NBSP = '\u00A0'; + +function isCzechExtensionLocale(locale: unknown): boolean { + if (typeof locale !== 'string') return false; + const primary = locale.trim().slice(0, 32).toLowerCase().split(/[-_]/)[0]; + return primary === 'cs'; +} + +function groupCzechIntegerString(intStr: string): string { + if (!/^-?\d+$/.test(intStr)) return intStr; + const negative = intStr.startsWith('-'); + const digits = negative ? intStr.slice(1) : intStr; + const grouped = digits.replace(/\B(?=(\d{3})+(?!\d))/g, CZECH_NBSP); + return negative ? `-${grouped}` : grouped; +} + +function formatCzechDecimalString(fixedAscii: string): string { + if (!/^-?\d+(?:\.\d+)?$/.test(fixedAscii)) return fixedAscii; + const [intPart = '0', fracPart] = fixedAscii.split('.'); + const groupedInt = groupCzechIntegerString(intPart); + return fracPart !== undefined ? `${groupedInt},${fracPart}` : groupedInt; +} + export function formatSafeExtensionVnd( val: number | null | undefined, - fallbackText = t('notAvailable') + fallbackText = t('notAvailable'), + locale?: string ): string { if ( typeof val !== 'number' || @@ -542,7 +580,14 @@ export function formatSafeExtensionVnd( ) { return fallbackText; } - return `${Math.round(val).toLocaleString('vi-VN')} ₫`; + const rounded = Math.round(val); + if (rounded <= 0) { + return fallbackText; + } + if (isCzechExtensionLocale(locale)) { + return `${groupCzechIntegerString(String(rounded))}${CZECH_NBSP}₫`; + } + return `${rounded.toLocaleString('vi-VN')} ₫`; } export function resolveSafeApiRelativeUrl( @@ -600,9 +645,12 @@ export function formatSafeNumber( max?: number; decimals?: number; fallback?: number; - } = {} + locale?: string; + } = {}, + locale?: string ): string { const safeOpts = options && typeof options === 'object' ? options : {}; + const effectiveLocale = locale ?? safeOpts.locale; const rawFallback = typeof safeOpts.fallback === 'number' ? safeOpts.fallback @@ -635,9 +683,15 @@ export function formatSafeNumber( safeOpts.decimals >= 0 ) { const decimals = Math.min(6, Math.floor(safeOpts.decimals)); - return roundHalfUpDecimal(clamped, decimals).toFixed(decimals); + const fixed = roundHalfUpDecimal(clamped, decimals).toFixed(decimals); + return isCzechExtensionLocale(effectiveLocale) + ? formatCzechDecimalString(fixed) + : fixed; } - return String(roundHalfUpDecimal(clamped, 0)); + const roundedInt = String(roundHalfUpDecimal(clamped, 0)); + return isCzechExtensionLocale(effectiveLocale) + ? formatCzechDecimalString(roundedInt) + : roundedInt; } const ALLOWED_VERDICT_CLASS_SUFFIXES = new Set([ diff --git a/apps/extension/src/sidepanel/panel-view.ts b/apps/extension/src/sidepanel/panel-view.ts index 7884fd7ed..caeecadd0 100644 --- a/apps/extension/src/sidepanel/panel-view.ts +++ b/apps/extension/src/sidepanel/panel-view.ts @@ -20,6 +20,11 @@ import { resolveSafeApiRelativeUrl, } from '../security-guards.js'; import { contentTextHtml, escapeHtml, t, type MessageKey } from '../i18n.js'; +import { + encodeSurrogateSafeUriComponent, + sliceCodePoints, + stripLoneSurrogates, +} from '../surrogate-safe.js'; export { escapeHtml }; @@ -93,7 +98,8 @@ export function renderVariantPickerHtml( lookup: Pick< ExtensionLookupData, 'variantCandidates' | 'detectedStorageGb' | 'selectedVariant' - > & { matchStatus?: ExtensionLookupData['matchStatus'] } + > & { matchStatus?: ExtensionLookupData['matchStatus'] }, + locale = t('langCode') ): string { if (lookup.variantCandidates.length <= 1) return ''; return ` @@ -110,7 +116,7 @@ export function renderVariantPickerHtml( aria-pressed="${active ? 'true' : 'false'}" data-variant="${escapeHtml(v.label)}" > - ${contentTextHtml(v.label)} (${formatSafeExtensionVnd(v.minPrice)}) + ${contentTextHtml(v.label)} (${formatSafeExtensionVnd(v.minPrice, t('notAvailable'), locale)}) `; }) @@ -201,11 +207,14 @@ export function offerMarks(offer: PanelOffer): string[] { } /** A star rating, or null when unknown or zero (DOS/Rate#1301). */ -export function ratingStarText(raw: unknown): string | null { +export function ratingStarText( + raw: unknown, + locale = t('langCode') +): string | null { const rating = normalizeFiveStarRating(raw); return rating == null ? null - : `★ ${formatSafeNumber(rating, { min: 0, max: 5, decimals: 1 })}`; + : `★ ${formatSafeNumber(rating, { min: 0, max: 5, decimals: 1 }, locale)}`; } export function officialBadgeHtml(): string { @@ -214,11 +223,12 @@ export function officialBadgeHtml(): string { function renderOfferRowHtml( off: ExtensionOfferItem, - cheapest: boolean + cheapest: boolean, + locale: string ): string { const marks = offerMarkItems(off); const muted = !isOfferBuyable(off); - const star = ratingStarText(off.rating_star); + const star = ratingStarText(off.rating_star, locale); const meta = [ escapeHtml(String(off.platform ?? '').toUpperCase()), star, @@ -228,7 +238,11 @@ function renderOfferRowHtml( off.merchant.risk_score == null ? t('offerCombinedRiskNoData') : t('offerCombinedRisk', [ - formatSafeNumber(off.merchant.risk_score, { min: 0, max: 100 }), + formatSafeNumber( + off.merchant.risk_score, + { min: 0, max: 100 }, + locale + ), ]) ), ].filter(Boolean); @@ -259,23 +273,26 @@ function renderOfferRowHtml( - ${formatSafeExtensionVnd(off.price_current)} + ${formatSafeExtensionVnd(off.price_current, t('notAvailable'), locale)} `; } /** The store price list card, or '' with no offer (DOS/Rate#1297). */ -export function renderOffersCardHtml(offers: ExtensionOfferItem[]): string { +export function renderOffersCardHtml( + offers: ExtensionOfferItem[], + locale = t('langCode') +): string { if (offers.length === 0) return ''; const ordered = orderOffersForPanel(offers); const cheapestId = cheapestBuyableOfferId(ordered); return `
-
${escapeHtml(t('offersCardTitle', [formatSafeNumber(offers.length, { min: 0 })]))}
+
${escapeHtml(t('offersCardTitle', [formatSafeNumber(offers.length, { min: 0 }, locale)]))}
${ordered .slice(0, 5) - .map((off) => renderOfferRowHtml(off, off.id === cheapestId)) + .map((off) => renderOfferRowHtml(off, off.id === cheapestId, locale)) .join('')}
`; @@ -293,18 +310,22 @@ export function renderReviewCardHtml( | 'rating_score' | 'user_rating_weighted' | 'average_rating' - > | null + > | null, + locale = t('langCode') ): string { if (!reviews) return ''; - const star = ratingStarText(resolveExtensionMasterRating(master)); + const star = ratingStarText(resolveExtensionMasterRating(master), locale); const analysed = Number(reviews.total_analyzed); const hasReviews = Number.isFinite(analysed) && analysed > 0; // The server writes the summary in Vietnamese only. An English or Czech // panel leaves it out rather than machine-translating it or guessing its // language: the genuine share and the count above say the same // (DOS/Rate#1374). + const isViLocale = + typeof locale === 'string' && + locale.trim().slice(0, 32).toLowerCase().split(/[-_]/)[0] === 'vi'; const summary = - hasReviews && reviews.ai_summary && t('langCode') === 'vi' + hasReviews && reviews.ai_summary && isViLocale && t('langCode') === 'vi' ? reviews.ai_summary : null; return ` @@ -319,7 +340,7 @@ export function renderReviewCardHtml(
${escapeHtml(t('reviewAuthenticShare'))}
${ hasReviews - ? `
${escapeHtml(t('reviewAuthenticValue', [formatSafeNumber(reviews.authentic_pct, { min: 0, max: 100 }), formatSafeNumber(analysed, { min: 0 })]))}
` + ? `
${escapeHtml(t('reviewAuthenticValue', [formatSafeNumber(reviews.authentic_pct, { min: 0, max: 100 }, locale), formatSafeNumber(analysed, { min: 0 }, locale)]))}
` : `
${escapeHtml(t('reviewNone'))}
` } @@ -357,10 +378,12 @@ export function renderNotFoundHtml( apiBaseUrl: string, accessory: boolean ): string { - const query = String(signal.title ?? '').trim(); + const query = sliceCodePoints(String(signal.title ?? '').trim(), 500).trim(); const searchUrl = resolveSafeApiRelativeUrl( apiBaseUrl, - query ? `/inspect?q=${encodeURIComponent(query)}` : '/inspect', + query + ? `/inspect?q=${encodeSurrogateSafeUriComponent(query, 500)}` + : '/inspect', '/inspect' ); return ` @@ -402,9 +425,10 @@ const LOOKUP_FAILURE_MESSAGE = { export function renderLookupErrorHtml( kind: LookupFailureKind, productTitle?: string | null, - retryAfterSeconds?: number | null + retryAfterSeconds?: number | null, + locale = t('langCode') ): string { - const title = String(productTitle ?? '').trim(); + const title = stripLoneSurrogates(String(productTitle ?? '')).trim(); // A rate limit says how long to wait when the server said so (DOS/Rate#1466). const wait = kind === 'rate_limited' && @@ -415,7 +439,9 @@ export function renderLookupErrorHtml( : null; const message = wait !== null - ? t('lookupErrorRateLimitedWait', [String(wait)]) + ? t('lookupErrorRateLimitedWait', [ + formatSafeNumber(wait, { min: 1 }, locale), + ]) : t(LOOKUP_FAILURE_MESSAGE[kind]); return `