Skip to content
Back to search

whatsapp-claude-plugin

MarketplaceWorks with Claude CodeGitHub

WhatsApp channel plugin for Claude Code

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today

Check it deeper on your machine

Its scripts were only partly scanned.

As a Claude Code plugin, install it and then ask Claude Code:

/plugin marketplace add keithmackay/mackayi/plugin install scanskillsafety@mackayiDo a deep scan of https://github.com/Rich627/whatsapp-claude-plugin with scanskillsafety

Or from a terminal, clone it and run it:

git clone https://github.com/keithmackay/scanskillsafety-skill ~/.claude/skills/scanskillsafetynode ~/.claude/skills/scanskillsafety/cli.cjs --deep 'https://github.com/Rich627/whatsapp-claude-plugin'

It checks the exact commit: every file, its packages against OSV (api.osv.dev), how it compares with this page's scan (findsafeskills.com receives the repository's address), and, if you agree, Claude reading every file with your own Claude subscription. It never runs the code.

Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/rich627-whatsapp-claude-plugin/badge.svg)](/listings/rich627-whatsapp-claude-plugin)

HTML

<a href="/listings/rich627-whatsapp-claude-plugin"><img src="/api/listings/rich627-whatsapp-claude-plugin/badge.svg" alt="findsafeskills safety rating" /></a>

Install

Install instructions from the README

As written by the repo's author. findsafeskills has not verified these steps.

claude plugin marketplace add Rich627/whatsapp-claude-plugin
claude plugin install whatsapp-channel@whatsapp-claude-plugin
claude --dangerously-load-development-channels plugin:whatsapp-channel@whatsapp-claude-plugin

The `--dangerously-load-development-channels` flag matters: it registers the plugin as a **channel**, so an inbound WhatsApp message wakes your session immediately. Without it the tools still load, but nothing wakes the session when messages arrive — they sit unanswered until you (or a [watchdog](./scripts/watchdog.sh)) prompt Claude to check. `--channels` does not accept this plugin yet (it is not on the research-preview allowlist), so the development flag is currently the only way.

> **Know what this flag does.** Claude Code warns against loading downloaded channels this way: a loaded channel can put text from other people straight into your session. Read this plugin's code before you use it, keep the [allowlist](./ACCESS.md) to people you trust, and keep permission prompts on. Never combine it with `--dangerously-skip-permissions`: with prompts off, anyone in an allowlisted chat could get Claude to run commands on your computer.

Inside the session, choose your connection:

/whatsapp-channel:setup
/whatsapp-channel:configure provider

The wizard runs in your own terminal so Cloud credentials never pass through chat. Or run `bun scripts/provider.ts choose` from the plugin directory.

| Connection | Setup | Main limits | | ---------------------------------- | --------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | | Linked device (`baileys`, default) | Pair your phone; no Meta API credentials | Unofficial protocol; existing personal/group behavior | | Official (`cloud-api`) | Meta business number, token, app secret, verify token, public HTTPS webhook | DMs only in this implementation; service window/templates and Meta fees/policies apply |

For linked-device pairing, save your number with `/whatsapp-channel:configure <phone>` (country code + number, no `+`). Enter the printed pairing code in WhatsApp → Settings → Linked Devices → Link a Device → **Link with phone number instead**, or scan the QR.

For official business DMs, follow [Cloud API setup](./docs/cloud-api.md). This provider does not yet support groups, message editing, phone history/address-book import or coexistence synchronization. Add an explicitly allowed personal owner; the business number is never auto-added, and the owner must be set explicitly with `/whatsapp-channel:access set owner <jid>`. A non-empty key saved in `~/.whatsapp-channel/.env` by the terminal tools wins over plugin `/config` values for that key; remove it from `.env` to return it to plugin management. Configuration readiness is not proof that the public webhook works. Rates vary; consult [Meta pricing](https://business.whatsapp.com/products/platform-pricing) and [FAQ](https://whatsappbusiness.com/resources/faq/).

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

.claude-plugin/marketplace.json · Manifest · 18 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

  1. {
  2. "$schema": "https://anthropic.com/claude-code/marketplace.schema.json",
  3. "name": "whatsapp-claude-plugin",
  4. "version": "1.5.0",
  5. "description": "WhatsApp channel plugin for Claude Code",
  6. "owner": {
  7. "name": "Rich627"
  8. },
  9. "plugins": [
  10. {
  11. "name": "whatsapp-channel",
  12. "description": "WhatsApp channel for Claude Code \u2014 linked device or official Cloud API, with pairing, allowlists and access control.",
  13. "version": "0.33.1",
  14. "source": "./",
  15. "category": "channels"
  16. }
  17. ]
  18. }
README.md · README · 212 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

  1. # WhatsApp Channel for Claude Code
  2. Drive your Claude Code session from WhatsApp. Choose a **linked device** for a
  3. personal account or the **official WhatsApp Cloud API** for business DMs.
  4. The default Baileys provider connects like WhatsApp Web: pair your phone, then
  5. Claude replies from your own number. Existing installations keep this provider.
  6. The optional Cloud API provider uses Meta's business API and a public HTTPS
  7. webhook, with its own credentials, messaging policies and applicable fees.
  8. Both providers feed the same MCP channel and access gate.
  9. [![Claude Code Plugin](https://img.shields.io/badge/Claude%20Code-Plugin-blue)](https://code.claude.com/docs/en/plugins)
  10. [![MCP Server](https://img.shields.io/badge/MCP-Server-green)](https://modelcontextprotocol.io)
  11. [![License: Apache 2.0](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0)
  12. > **Community project.** This plugin is not made or endorsed by Anthropic or Meta.
  13. > Its Baileys provider uses an unofficial linked-device protocol, which may
  14. > conflict with WhatsApp's terms and put the number at risk. The optional Cloud
  15. > provider uses official API transport; confirm your use is permitted under
  16. > Meta's business and AI-provider rules before enabling it.
  17. ## Installation
  18. ```sh
  19. claude plugin marketplace add Rich627/whatsapp-claude-plugin
  20. claude plugin install whatsapp-channel@whatsapp-claude-plugin
  21. claude --dangerously-load-development-channels plugin:whatsapp-channel@whatsapp-claude-plugin
  22. ```
  23. The `--dangerously-load-development-channels` flag matters: it registers the plugin as a **channel**, so an inbound WhatsApp message wakes your session immediately. Without it the tools still load, but nothing wakes the session when messages arrive — they sit unanswered until you (or a [watchdog](./scripts/watchdog.sh)) prompt Claude to check. `--channels` does not accept this plugin yet (it is not on the research-preview allowlist), so the development flag is currently the only way.
  24. > **Know what this flag does.** Claude Code warns against loading downloaded channels this way: a loaded channel can put text from other people straight into your session. Read this plugin's code before you use it, keep the [allowlist](./ACCESS.md) to people you trust, and keep permission prompts on. Never combine it with `--dangerously-skip-permissions`: with prompts off, anyone in an allowlisted chat could get Claude to run commands on your computer.
  25. Inside the session, choose your connection:
  26. ```text
  27. /whatsapp-channel:setup
  28. /whatsapp-channel:configure provider
  29. ```
  30. The wizard runs in your own terminal so Cloud credentials never pass through
  31. chat. Or run `bun scripts/provider.ts choose` from the plugin directory.
  32. | Connection | Setup | Main limits |
  33. | ---------------------------------- | --------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- |
  34. | Linked device (`baileys`, default) | Pair your phone; no Meta API credentials | Unofficial protocol; existing personal/group behavior |
  35. | Official (`cloud-api`) | Meta business number, token, app secret, verify token, public HTTPS webhook | DMs only in this implementation; service window/templates and Meta fees/policies apply |
  36. For linked-device pairing, save your number with
  37. `/whatsapp-channel:configure <phone>` (country code + number, no `+`). Enter the
  38. printed pairing code in WhatsApp → Settings → Linked Devices → Link a Device →
  39. **Link with phone number instead**, or scan the QR.
  40. For official business DMs, follow [Cloud API setup](./docs/cloud-api.md). This
  41. provider does not yet support groups, message editing, phone history/address-book
  42. import or coexistence synchronization. Add an explicitly allowed personal owner;
  43. the business number is never auto-added, and the owner must be set explicitly with
  44. `/whatsapp-channel:access set owner <jid>`. A non-empty key saved in
  45. `~/.whatsapp-channel/.env` by the terminal tools wins over plugin `/config` values
  46. for that key; remove it from `.env` to return it to plugin management.
  47. Configuration readiness is not proof
  48. that the public webhook works. Rates vary; consult
  49. [Meta pricing](https://business.whatsapp.com/products/platform-pricing) and
  50. [FAQ](https://whatsappbusiness.com/resources/faq/).
  51. ## Other MCP clients (Codex CLI, Gemini CLI, Cursor)
  52. The server is a plain stdio MCP server, so any MCP client can run it. Two things are Claude Code specific and worth knowing before you start:
  53. - **Inbound messages are not pushed.** Waking a session on an incoming message uses `notifications/claude/channel`, a Claude Code extension. MCP has no standard equivalent that reaches the model, and other clients drop unknown notifications silently. Elsewhere the plugin is poll-based: call `wait_for_messages` (parks up to 40s; the first call on a connection returns whatever is already unreplied, later calls only what arrived since) or `catch_up` / `unreplied`. Most tool results also carry a count of unreplied messages, so a client finds out there is traffic on its next call. Three do not: `unreplied` and `wait_for_messages`, which just returned those very messages, and `catch_up` with no arguments, which is that count already.
  54. - **Setup is done from a terminal, not a slash command.** `/whatsapp-channel:access` and friends are Claude Code skills. Use `bun scripts/access.ts` instead (see [Access control from a terminal](#access-control-from-a-terminal)).
  55. Register the server with an absolute path — `${CLAUDE_PLUGIN_ROOT}` is substituted by Claude Code only:
  56. **Codex CLI** (`~/.codex/config.toml`)
  57. ```toml
  58. [mcp_servers.whatsapp]
  59. command = "bun"
  60. args = ["run", "--cwd", "/absolute/path/to/whatsapp-channel", "start"]
  61. startup_timeout_sec = 30 # default 10 is tight for a first Baileys connect
  62. tool_timeout_sec = 120 # default 60; wait_for_messages parks for up to 40s
  63. ```
  64. **Gemini CLI** (`~/.gemini/settings.json`)
  65. ```json
  66. {
  67. "mcpServers": {
  68. "whatsapp": {
  69. "command": "bun",
  70. "args": ["run", "--cwd", "/absolute/path/to/whatsapp-channel", "start"],
  71. "timeout": 600000
  72. }
  73. }
  74. }
  75. ```
  76. **Cursor** (`~/.cursor/mcp.json` for all projects, `.cursor/mcp.json` for one)
  77. ```json
  78. {
  79. "mcpServers": {
  80. "whatsapp": {
  81. "type": "stdio",
  82. "command": "bun",
  83. "args": ["run", "--cwd", "/absolute/path/to/whatsapp-channel", "start"]
  84. }
  85. }
  86. }
  87. ```
  88. Only one client at a time can hold a state directory’s singleton lock. With Baileys, two connections using the same linked-device auth would kick each other off. Use separate state directories for separate numbers. A second server does not fail silently — it stays up and serves a single `whatsapp_unavailable` tool naming the process that holds the connection.
  89. ## Access control from a terminal
  90. Everything the access skill does, without Claude Code:
  91. ```sh
  92. bun scripts/access.ts status # policy, allowlist, pending codes, groups
  93. bun scripts/access.ts policy pairing # open the door
  94. bun scripts/access.ts pair <code> # approve someone who messaged you
  95. bun scripts/access.ts allow <jid> # add directly
  96. bun scripts/access.ts remove <jid>
  97. bun scripts/access.ts group add <groupJid> [--mention] [--allow jid1,jid2]
  98. bun scripts/access.ts set replyToMode first # ackReaction, textChunkLimit, chunkMode, mentionPatterns
  99. ```
  100. Approving always needs the specific code, even when only one pairing is waiting: anyone can create a pending entry just by messaging the account, so "approve the pending one" is exactly what a prompt-injected request looks like. For the same reason this is a terminal command and deliberately **not** an MCP tool, so nothing arriving over WhatsApp can reach it.
  101. ## Features
  102. The list below describes the default linked-device provider. See the
  103. [provider capability comparison](./docs/cloud-api.md#capabilities-in-this-plugins-first-cloud-provider)
  104. for the initial Cloud API scope. Shared DM access, attachment processing,
  105. transcription and context recovery also work with Cloud API.
  106. - **Bidirectional messaging.** Send and receive from the session; long replies are chunked to WhatsApp's limits or sent as a document attachment past a configurable threshold.
  107. - **Typing indicator.** The chat shows "typing…" while Claude works on its message, and "recording audio…" while a voice note uploads (linked device).
  108. - **@-mentions.** `reply` can tag people so they actually get notified — ids are accepted as phone, LID, or full JID, and mentions attach only to the chunk that names them.
  109. - **Full media support.** Photos, voice notes, video, documents, and stickers, in both directions.
  110. - **Polls.** `send_poll` asks a chat a question with up to 12 options; every vote comes back to the session as a message (linked device).
  111. - **Voice transcription.** Incoming voice notes are transcribed locally via mlx-whisper (see [setup](#voice-transcription-optional)); without the script they arrive as plain attachments.
  112. - **Access control.** Pairing codes, allowlists, and per-group policies gate every inbound message — strangers never reach your session. Managed via `/whatsapp-channel:access` in Claude Code, or `bun scripts/access.ts` anywhere.
  113. - **Per-group personalities.** Each group gets its own `config.md` with a custom personality and conversation memory.
  114. - **Permission relay.** Approve or deny Claude's tool requests from WhatsApp with an emoji reaction (👍 / 👎).
  115. - **Cron tasks.** A `## Cron Jobs` section in a group's `config.md` schedules recurring server-side tasks.
  116. - **Context recovery.** After a restart, `catch_up` with no arguments says how many messages are waiting per chat - counts only, no message text - plus open tasks from `tasks.md`. Name a chat and it replays that room's recent two-way conversation, so a fresh session resumes mid-flight work without reading every chat it has.
  117. - **Dual accounts.** Run personal and business numbers side by side with separate state and behaviors.
  118. - **Self-diagnosis.** `/whatsapp-channel:doctor` checks the server process, device link, singleton lock, and config, then walks you through the fixes — no more guessing why replies stopped.
  119. ## How it works
  120. ```text
  121. WhatsApp linked device <──Baileys────────> MCP Server <──stdio──> Claude Code
  122. WhatsApp business DMs <──Cloud API/HTTPS─> MCP Server
  123. ```
  124. The server (a single Bun process) holds either the linked-device connection or the Cloud API webhook listener and forwards inbound messages after they pass the access gate. Claude acts through shared MCP tools such as `reply`, `react`, `download_attachment`, `status`, `unreplied` and `catch_up`. Provider-specific tools include linked-device group/edit operations, polls (`send_poll`), `set_presence`, read receipts (`mark_read`), and Cloud `send_template`. Runtime state lives in `~/.whatsapp-channel/` (or `WHATSAPP_STATE_DIR`), never in the repo.
  125. Messages sent by Claude appear from your linked personal number or configured business number. Use a dedicated number if you want a distinct assistant identity.
  126. ## Voice transcription (optional)
  127. One-time setup (Apple Silicon, mlx-whisper):
  128. ```bash
  129. brew install ffmpeg # mlx-whisper uses it to decode audio
  130. python3 -m venv ~/whisper-env
  131. source ~/whisper-env/bin/activate
  132. pip install mlx-whisper
  133. cp scripts/whisper-transcribe.sh ~/whisper-transcribe.sh
  134. chmod +x ~/whisper-transcribe.sh
  135. ~/whisper-transcribe.sh path/to/sample.ogg # optional: test
  136. ```
  137. The reference script uses `mlx-community/whisper-large-v3-turbo` — accurate, fast, multilingual. Swap the model in the script if you prefer a smaller one.
  138. **Cloud alternative.** To skip the local setup, open `/plugin`, pick this plugin, and set **Voice transcription provider** to `groq` or `openai` along with that provider's API key. Keys are kept in your OS keychain, not in `settings.json`. Voice notes are then uploaded to `api.groq.com` or `api.openai.com` for transcription. The older `TRANSCRIPTION_PROVIDER`, `GROQ_API_KEY` and `OPENAI_API_KEY` environment variables still work.
  139. ## Troubleshooting
  140. | Issue | Solution |
  141. | ----------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
  142. | Pairing code not showing | Run `/whatsapp-channel:configure <phone>` first, then relaunch |
  143. | 440 disconnect error | Only one connection per auth state allowed. Kill stale processes: `pkill -f "whatsapp.*server"` |
  144. | Session not waking on new messages | Most common cause: launched without `--dangerously-load-development-channels plugin:whatsapp-channel@whatsapp-claude-plugin`. Tools work but inbound pushes are dropped (`Channel notifications skipped` in the MCP debug log) — relaunch with the flag. |
  145. | Messages not arriving | Known Claude Code client bug ([#37933](https://github.com/anthropics/claude-code/issues/37933)). Server-side is correct, awaiting client fix. |
  146. | Replies still send, nothing arrives | Send a **DM** to the connected number as well as a group message — a DM that lands while groups stay silent means the group sender-key path, not the connection. `~/.whatsapp-channel/diag.log` records an `inbound upsert` line for every batch WhatsApp delivers, so it distinguishes "never arrived" from "arrived and was dropped". Set `WHATSAPP_DIAG_DEBUG=1` for Baileys' full debug stream. |
  147. | Auth expired | Run `/whatsapp-channel:configure reset-auth` and re-pair |
  148. ## Documentation
  149. Full documentation lives in [USAGE.md](./USAGE.md): [access control](./USAGE.md#access-control), the [tools exposed to the assistant](./USAGE.md#tools-exposed-to-the-assistant), [dual-account setup](./USAGE.md#dual-account-setup), [session conflicts](./USAGE.md#session-conflicts), and [resetting auth](./USAGE.md#resetting-auth).
  150. ## Contributing
  151. Issues and pull requests are welcome — read [CONTRIBUTING.md](./CONTRIBUTING.md) before opening one. Report security issues privately per [SECURITY.md](./SECURITY.md).
  152. ## Star History
  153. <a href="https://www.star-history.com/?type=date&repos=Rich627%2Fwhatsapp-claude-plugin">
  154. <picture>
  155. <source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/chart?repos=Rich627/whatsapp-claude-plugin&type=date&theme=dark&legend=top-left&sealed_token=NrfP1Fv0z7ipQM961lFZJbXE76GS7paukclIhr6km37t0lJAzivyX0JUNQTkRaxa5lSpRCYmef3xvHaiUKCgBS0KbwpeIohfMOqur0ULPiTt2h2DWcUui1YJ2nux4W9Ug8u8D6CNl91ZYInSZCrrdNi5hydWjSLy89XtzYYM83F-mhgJI44lLZoxj7Na" />
  156. <source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/chart?repos=Rich627/whatsapp-claude-plugin&type=date&legend=top-left&sealed_token=NrfP1Fv0z7ipQM961lFZJbXE76GS7paukclIhr6km37t0lJAzivyX0JUNQTkRaxa5lSpRCYmef3xvHaiUKCgBS0KbwpeIohfMOqur0ULPiTt2h2DWcUui1YJ2nux4W9Ug8u8D6CNl91ZYInSZCrrdNi5hydWjSLy89XtzYYM83F-mhgJI44lLZoxj7Na" />
  157. <img alt="Star History Chart" src="https://api.star-history.com/chart?repos=Rich627/whatsapp-claude-plugin&type=date&legend=top-left&sealed_token=NrfP1Fv0z7ipQM961lFZJbXE76GS7paukclIhr6km37t0lJAzivyX0JUNQTkRaxa5lSpRCYmef3xvHaiUKCgBS0KbwpeIohfMOqur0ULPiTt2h2DWcUui1YJ2nux4W9Ug8u8D6CNl91ZYInSZCrrdNi5hydWjSLy89XtzYYM83F-mhgJI44lLZoxj7Na" />
  158. </picture>
  159. </a>
  160. ## License
  161. [Apache 2.0](./LICENSE) — Copyright 2025 Richie Liu
scripts/picker.test.ts · Bundled script · 1,208 lines · 1 finding marked
  1. import { describe, expect, test } from "bun:test";
  2. import { PassThrough } from "node:stream";
  3. import { stripVTControlCharacters as stripAnsi } from "node:util";
  4. import {
  5. applySelection,
  6. chipsOf,
  7. decodeInput,
  8. displayWidth,
  9. hitTest,
  10. initPicker,
  11. layout,
  12. reducePicker,
  13. runPicker,
  14. selectionOf,
  15. truncate,
  16. visibleItems,
  17. type PickerEvent,
  18. type PickerItem,
  19. type PickerModel,
  20. type PickerState,
  21. } from "./picker";
  22. function item(overrides: Partial<PickerItem> = {}): PickerItem {
  23. return {
  24. jid: "1@s.whatsapp.net",
  25. label: "Item",
  26. kind: "dm",
  27. granted: false,
  28. roster: false,
  29. ...overrides,
  30. };
  31. }
  32. function model(overrides: Partial<PickerModel> = {}): PickerModel {
  33. return {
  34. dms: [],
  35. groups: [],
  36. dmNote: "",
  37. groupNote: "",
  38. hasBackup: false,
  39. color: false,
  40. ...overrides,
  41. };
  42. }
  43. function press(state: PickerState, ...events: PickerEvent[]): PickerState {
  44. return events.reduce((s, e) => reducePicker(s, e), state);
  45. }
  46. const rohan = item({
  47. jid: "rohan@s.whatsapp.net",
  48. label: "Rohan",
  49. kind: "dm",
  50. granted: true,
  51. });
  52. const priya = item({
  53. jid: "priya@s.whatsapp.net",
  54. label: "Priya",
  55. kind: "dm",
  56. granted: false,
  57. });
  58. const family = item({
  59. jid: "family@g.us",
  60. label: "Family",
  61. kind: "group",
  62. granted: true,
  63. roster: true,
  64. });
  65. const wil = item({
  66. jid: "wil@g.us",
  67. label: "WIL Group HUDINI",
  68. kind: "group",
  69. granted: false,
  70. });
  71. // -----------------------------------------------------------------------
  72. // reducer
  73. // -----------------------------------------------------------------------
  74. describe("reducePicker", () => {
  75. test("initPicker: every granted item ticked, others not; chips empty; focus dms; cursors 0; done null", () => {
  76. const s = initPicker(
  77. model({ dms: [rohan, priya], groups: [family, wil] }),
  78. 100,
  79. 24,
  80. );
  81. expect(s.ticked.has(rohan.jid)).toBe(true);
  82. expect(s.ticked.has(priya.jid)).toBe(false);
  83. expect(s.ticked.has(family.jid)).toBe(true);
  84. expect(s.ticked.has(wil.jid)).toBe(false);
  85. expect(s.chips).toEqual([]);
  86. expect(s.focus).toBe("dms");
  87. expect(s.cursor).toEqual({ dms: 0, groups: 0 });
  88. expect(s.done).toBeNull();
  89. });
  90. test("a filter change puts both cursors back on row 0", () => {
  91. let s = initPicker(
  92. model({ dms: [rohan, priya], groups: [family, wil] }),
  93. 100,
  94. 24,
  95. );
  96. s = press(s, { type: "down" }); // dms cursor -> 1
  97. expect(s.cursor.dms).toBe(1);
  98. s = press(
  99. s,
  100. { type: "char", ch: "F" },
  101. { type: "char", ch: "A" },
  102. { type: "char", ch: "M" },
  103. );
  104. expect(visibleItems(s, "dms").map((i) => i.jid)).toEqual([]);
  105. expect(visibleItems(s, "groups").map((i) => i.jid)).toEqual([family.jid]);
  106. expect(s.cursor).toEqual({ dms: 0, groups: 0 });
  107. expect(s.focus).toBe("search");
  108. });
  109. test("a term matching only a JID/number matches nothing (label-only filter)", () => {
  110. const contact = item({
  111. jid: "61400011675@s.whatsapp.net",
  112. label: "Rohan",
  113. granted: false,
  114. });
  115. let s = initPicker(model({ dms: [contact] }), 100, 24);
  116. s = press(
  117. s,
  118. { type: "char", ch: "6" },
  119. { type: "char", ch: "1" },
  120. { type: "char", ch: "4" },
  121. );
  122. expect(visibleItems(s, "dms")).toEqual([]);
  123. });
  124. test("Enter with a non-empty search ticks the highlighted row, pushes its chip and clears the search", () => {
  125. let s = initPicker(model({ dms: [priya] }), 100, 24);
  126. s = press(
  127. s,
  128. { type: "char", ch: "p" },
  129. { type: "char", ch: "r" },
  130. { type: "enter" },
  131. );
  132. expect(s.ticked.has(priya.jid)).toBe(true);
  133. expect(s.chips).toEqual([priya.jid]);
  134. expect(s.search).toBe("");
  135. expect(visibleItems(s, "dms")).toEqual([priya]);
  136. });
  137. test("Space inside a non-empty search is a filter character, not a tick", () => {
  138. const smith = item({ jid: "1@s.whatsapp.net", label: "John Smith" });
  139. const doe = item({ jid: "2@s.whatsapp.net", label: "John Doe" });
  140. let s = initPicker(model({ dms: [smith, doe] }), 100, 24);
  141. s = press(
  142. s,
  143. { type: "char", ch: "J" },
  144. { type: "char", ch: "o" },
  145. { type: "char", ch: "h" },
  146. { type: "char", ch: "n" },
  147. { type: "space" },
  148. { type: "char", ch: "S" },
  149. );
  150. expect(s.search).toBe("John S");
  151. expect(s.ticked.size).toBe(0);
  152. expect(visibleItems(s, "dms").map((i) => i.jid)).toEqual([smith.jid]);
  153. });
  154. test("Enter with an empty search sets done='submit'", () => {
  155. let s = initPicker(model(), 100, 24);
  156. s = press(s, { type: "enter" });
  157. expect(s.done).toBe("submit");
  158. });
  159. test("Backspace with a non-empty search deletes one character", () => {
  160. let s = initPicker(model(), 100, 24);
  161. s = press(
  162. s,
  163. { type: "char", ch: "a" },
  164. { type: "char", ch: "b" },
  165. { type: "backspace" },
  166. );
  167. expect(s.search).toBe("a");
  168. });
  169. test("Backspace with an empty search pops the newest chip AND unticks that jid", () => {
  170. let s = initPicker(model({ dms: [priya] }), 100, 24);
  171. s = press(s, { type: "space" });
  172. expect(s.chips).toEqual([priya.jid]);
  173. s = press(s, { type: "backspace" });
  174. expect(s.chips).toEqual([]);
  175. expect(s.ticked.has(priya.jid)).toBe(false);
  176. const before = s;
  177. s = press(s, { type: "backspace" }); // no chips left -> no-op
  178. expect(s).toBe(before);
  179. });
  180. test("Space toggles only the highlighted row of the focused column", () => {
  181. let s = initPicker(
  182. model({ dms: [rohan, priya], groups: [family] }),
  183. 100,
  184. 24,
  185. );
  186. s = press(s, { type: "space" }); // focus dms, cursor 0 -> rohan
  187. expect(s.ticked.has(rohan.jid)).toBe(false);
  188. expect(s.ticked.has(priya.jid)).toBe(false);
  189. expect(s.ticked.has(family.jid)).toBe(true); // untouched
  190. });
  191. test("Enter with the caret in the search line ticks the MARKED row, not the previously focused column", () => {
  192. const alice = item({ jid: "1@s.whatsapp.net", label: "Alice", kind: "dm" });
  193. const zeta = item({ jid: "g1@g.us", label: "Zeta Group", kind: "group" });
  194. let s = initPicker(model({ dms: [alice], groups: [zeta] }), 100, 24);
  195. s = press(s, { type: "tab" }); // groups focused
  196. s = press(s, { type: "char", ch: "a" }); // snaps to search; both match
  197. // Move a column cursor off row 0, then come back to the search line:
  198. // the marker is on row 0 of the target, and Space must follow it.
  199. s = press(
  200. s,
  201. { type: "tab" },
  202. { type: "down" },
  203. { type: "tab" },
  204. { type: "tab" },
  205. );
  206. expect(s.focus).toBe("search");
  207. const marked = layout(s, 100, 24)
  208. .map(stripAnsi)
  209. .find((l) => l.startsWith(">"));
  210. expect(marked).toContain("Alice");
  211. // From the search line a space is a filter character; Enter is the tick.
  212. s = press(s, { type: "enter" });
  213. expect([...s.ticked]).toEqual([alice.jid]);
  214. });
  215. test("Tab cycles dms -> groups -> search -> dms; up/down move and clamp at both ends; empty column is a no-op", () => {
  216. let s = initPicker(model({ dms: [rohan, priya], groups: [] }), 100, 24);
  217. s = press(s, { type: "tab" });
  218. expect(s.focus).toBe("groups");
  219. const before = s;
  220. s = press(s, { type: "down" });
  221. expect(s).toBe(before); // groups is empty
  222. s = press(s, { type: "tab" }); // groups -> search
  223. expect(s.focus).toBe("search");
  224. s = press(s, { type: "tab" }); // search -> dms, completing the cycle
  225. expect(s.focus).toBe("dms");
  226. s = press(s, { type: "down" });
  227. expect(s.cursor.dms).toBe(1);
  228. s = press(s, { type: "down" });
  229. expect(s.cursor.dms).toBe(1); // clamped
  230. s = press(s, { type: "up" }, { type: "up" });
  231. expect(s.cursor.dms).toBe(0);
  232. });
  233. test("Undo pops the last toggle (ticked + chips both restored); undo on an empty stack is a no-op", () => {
  234. let s = initPicker(model({ dms: [priya] }), 100, 24);
  235. s = press(s, { type: "space" });
  236. expect(s.ticked.has(priya.jid)).toBe(true);
  237. s = press(s, { type: "undo" });
  238. expect(s.ticked.has(priya.jid)).toBe(false);
  239. expect(s.chips).toEqual([]);
  240. const before = s;
  241. s = press(s, { type: "undo" });
  242. expect(s).toBe(before);
  243. });
  244. test("'r' on a ticked, not-yet-granted group sets [r]; a second 'r' clears it", () => {
  245. let s = initPicker(model({ groups: [wil] }), 100, 24);
  246. s = press(s, { type: "tab" }, { type: "space" });
  247. expect(s.ticked.has(wil.jid)).toBe(true);
  248. s = press(s, { type: "char", ch: "r" });
  249. expect(s.roster.has(wil.jid)).toBe(true);
  250. s = press(s, { type: "char", ch: "r" });
  251. expect(s.roster.has(wil.jid)).toBe(false);
  252. });
  253. test("'r' on a ticked ALREADY-granted group is a no-op ([D2])", () => {
  254. let s = initPicker(model({ groups: [family] }), 100, 24);
  255. s = press(s, { type: "tab" });
  256. const before = s;
  257. s = press(s, { type: "char", ch: "r" });
  258. expect(s).toBe(before);
  259. });
  260. test("'r' on a contact is a no-op; 'r' while the search is non-empty is a plain filter character", () => {
  261. let s = initPicker(model({ dms: [priya] }), 100, 24);
  262. s = press(s, { type: "space" });
  263. const before = s;
  264. s = press(s, { type: "char", ch: "r" });
  265. expect(s).toBe(before);
  266. s = press(s, { type: "char", ch: "z" }, { type: "char", ch: "r" });
  267. expect(s.search).toBe("zr");
  268. });
  269. test("unticking an existing grant produces a STRUCK chip; re-ticking removes the chip entirely", () => {
  270. let s = initPicker(model({ dms: [rohan] }), 100, 24);
  271. s = press(s, { type: "space" });
  272. expect(chipsOf(s)).toEqual([
  273. { jid: rohan.jid, label: "Rohan", struck: true },
  274. ]);
  275. s = press(s, { type: "space" });
  276. expect(chipsOf(s)).toEqual([]);
  277. });
  278. test("Esc clears a non-empty search; Esc on an empty search sets done='cancel'", () => {
  279. let s = initPicker(model(), 100, 24);
  280. s = press(s, { type: "char", ch: "a" }, { type: "esc" });
  281. expect(s.search).toBe("");
  282. expect(s.done).toBeNull();
  283. s = press(s, { type: "esc" });
  284. expect(s.done).toBe("cancel");
  285. });
  286. test("'restore' is inert when hasBackup:false, sets done='restore' when true", () => {
  287. let s = initPicker(model({ hasBackup: false }), 100, 24);
  288. const before = s;
  289. s = press(s, { type: "restore" });
  290. expect(s).toBe(before);
  291. s = initPicker(model({ hasBackup: true }), 100, 24);
  292. s = press(s, { type: "restore" });
  293. expect(s.done).toBe("restore");
  294. });
  295. test("selectionOf splits groups/dms and filters roster to ticked groups only", () => {
  296. let s = initPicker(model({ dms: [rohan], groups: [wil] }), 100, 24);
  297. s = press(s, { type: "tab" }, { type: "space" }, { type: "char", ch: "r" });
  298. let sel = selectionOf(s);
  299. expect(sel.groups).toEqual(new Set([wil.jid]));
  300. expect(sel.dms).toEqual(new Set([rohan.jid]));
  301. expect(sel.roster).toEqual(new Set([wil.jid]));
  302. s = press(s, { type: "space" }); // untick wil
  303. sel = selectionOf(s);
  304. expect(sel.groups).toEqual(new Set());
  305. expect(sel.roster).toEqual(new Set());
  306. });
  307. test("the reducer never mutates its input (Set identity + original state unchanged)", () => {
  308. const s0 = initPicker(model({ dms: [priya] }), 100, 24);
  309. const tickedRef = s0.ticked;
  310. const s1 = reducePicker(s0, { type: "space" });
  311. expect(s0.ticked).toBe(tickedRef);
  312. expect(s0.ticked.has(priya.jid)).toBe(false);
  313. expect(s1).not.toBe(s0);
  314. expect(s1.ticked).not.toBe(s0.ticked);
  315. });
  316. test("a 'focus' event with an out-of-range index clamps to the last visible row", () => {
  317. let s = initPicker(model({ groups: [family, wil] }), 100, 24);
  318. s = press(s, { type: "focus", column: "groups", index: 999 });
  319. expect(s.focus).toBe("groups");
  320. expect(s.cursor.groups).toBe(1); // clamped to visibleItems("groups").length - 1
  321. });
  322. test("resize mid-session keeps ticks, chips and cursor untouched", () => {
  323. let s = initPicker(model({ dms: [rohan, priya] }), 100, 24);
  324. s = press(s, { type: "down" }, { type: "space" }); // tick priya, cursor 1
  325. expect(s.ticked.has(rohan.jid)).toBe(true);
  326. expect(s.ticked.has(priya.jid)).toBe(true);
  327. expect(s.chips).toEqual([priya.jid]);
  328. s = press(s, { type: "resize", cols: 60, rows: 20 });
  329. expect(s.cols).toBe(60);
  330. expect(s.rows).toBe(20);
  331. expect(s.ticked.has(rohan.jid)).toBe(true);
  332. expect(s.ticked.has(priya.jid)).toBe(true);
  333. expect(s.chips).toEqual([priya.jid]);
  334. expect(s.cursor.dms).toBe(1);
  335. });
  336. test("↑ from row 0 moves focus to the search line and draws the caret", () => {
  337. let s = initPicker(model({ dms: [rohan, priya] }), 100, 24);
  338. s = press(s, { type: "up" });
  339. expect(s.focus).toBe("search");
  340. expect(s.lastColumn).toBe("dms");
  341. const searchLine = layout(s, 100, 24)[0];
  342. expect(searchLine.endsWith("▏")).toBe(true);
  343. });
  344. test("↓ from the search line returns to row 0 of the last-focused column", () => {
  345. let s = initPicker(model({ groups: [family, wil] }), 100, 24);
  346. s = press(s, { type: "tab" }); // dms -> groups
  347. s = press(s, { type: "down" }); // cursor.groups -> 1
  348. s = press(s, { type: "up" }, { type: "up" }); // row 0, then -> search
  349. expect(s.focus).toBe("search");
  350. s = press(s, { type: "down" });
  351. expect(s.focus).toBe("groups");
  352. expect(s.cursor.groups).toBe(0);
  353. });
  354. test("typing while a column is focused snaps the caret to the search line", () => {
  355. let s = initPicker(model({ dms: [rohan], groups: [family] }), 100, 24);
  356. s = press(s, { type: "tab" }, { type: "char", ch: "z" });
  357. expect(s.focus).toBe("search");
  358. expect(s.search).toBe("z");
  359. expect(s.lastColumn).toBe("groups");
  360. expect(s.cursor).toEqual({ dms: 0, groups: 0 });
  361. });
  362. test("Enter on the search line ticks the first visible Contacts row, and Groups only when Contacts has no match", () => {
  363. // Case 1: Contacts has a match -> Contacts wins even though Groups also matches.
  364. let s = initPicker(
  365. model({
  366. dms: [item({ jid: "a@s.whatsapp.net", label: "Alpha" })],
  367. groups: [
  368. item({ jid: "alpha@g.us", label: "Alpha Group", kind: "group" }),
  369. ],
  370. }),
  371. 100,
  372. 24,
  373. );
  374. s = press(s, { type: "up" }); // -> focus search
  375. s = press(
  376. s,
  377. { type: "char", ch: "a" },
  378. { type: "char", ch: "l" },
  379. { type: "enter" },
  380. );
  381. expect(s.ticked.has("a@s.whatsapp.net")).toBe(true);
  382. expect(s.ticked.has("alpha@g.us")).toBe(false);
  383. // Case 2: no Contacts match -> falls through to Groups.
  384. let t = initPicker(
  385. model({
  386. dms: [rohan],
  387. groups: [
  388. item({ jid: "alpha@g.us", label: "Alpha Group", kind: "group" }),
  389. ],
  390. }),
  391. 100,
  392. 24,
  393. );
  394. t = press(t, { type: "up" });
  395. t = press(
  396. t,
  397. { type: "char", ch: "a" },
  398. { type: "char", ch: "l" },
  399. { type: "enter" },
  400. );
  401. expect(t.ticked.has("alpha@g.us")).toBe(true);
  402. });
  403. test("Enter on an empty search still submits with the caret on the search line", () => {
  404. let s = initPicker(model({ dms: [rohan] }), 100, 24);
  405. s = press(s, { type: "up" }); // focus -> search, search still ""
  406. expect(s.focus).toBe("search");
  407. s = press(s, { type: "enter" });
  408. expect(s.done).toBe("submit");
  409. });
  410. test("'r' filters when the caret is on the search line and flags roster when a column is focused", () => {
  411. let s = initPicker(model({ groups: [wil] }), 100, 24);
  412. s = press(s, { type: "tab" }, { type: "space" }); // focus groups, tick wil
  413. s = press(s, { type: "char", ch: "r" });
  414. expect(s.roster.has(wil.jid)).toBe(true);
  415. expect(s.focus).toBe("groups");
  416. let t = initPicker(model({ groups: [wil] }), 100, 24);
  417. t = press(t, { type: "tab" }, { type: "space" }); // tick wil, focus groups
  418. t = press(t, { type: "up" }); // -> focus search (only row is 0)
  419. t = press(t, { type: "char", ch: "r" });
  420. expect(t.search).toBe("r");
  421. expect(t.focus).toBe("search");
  422. expect(t.roster.has(wil.jid)).toBe(false);
  423. });
  424. test("space toggles the last-focused column's row while the caret is on the search line", () => {
  425. let s = initPicker(model({ dms: [rohan, priya] }), 100, 24);
  426. s = press(s, { type: "up" }); // focus -> search, lastColumn dms, cursor.dms 0
  427. expect(s.focus).toBe("search");
  428. s = press(s, { type: "space" });
  429. expect(s.ticked.has(rohan.jid)).toBe(false); // rohan was granted -> toggled off
  430. expect(s.focus).toBe("search"); // space stays focus-neutral
  431. });
  432. });
  433. // -----------------------------------------------------------------------
  434. // decodeInput
  435. // -----------------------------------------------------------------------
  436. describe("decodeInput", () => {
  437. test("every row of the table maps as specified, in order", () => {
  438. expect(decodeInput("\x03")).toEqual([{ type: "cancel" }]);
  439. expect(decodeInput("\r")).toEqual([{ type: "enter" }]);
  440. expect(decodeInput("\n")).toEqual([{ type: "enter" }]);
  441. expect(decodeInput("\t")).toEqual([{ type: "tab" }]);
  442. expect(decodeInput("\x7f")).toEqual([{ type: "backspace" }]);
  443. expect(decodeInput("\x08")).toEqual([{ type: "backspace" }]);
  444. expect(decodeInput(" ")).toEqual([{ type: "space" }]);
  445. expect(decodeInput("\x1a")).toEqual([{ type: "undo" }]);
  446. expect(decodeInput("\x12")).toEqual([{ type: "restore" }]);
  447. expect(decodeInput("\x1b[A")).toEqual([{ type: "up" }]);
  448. expect(decodeInput("\x1b[B")).toEqual([{ type: "down" }]);
  449. expect(decodeInput("\x1b[C")).toEqual([{ type: "tab" }]);
  450. expect(decodeInput("\x1b[D")).toEqual([{ type: "tab" }]);
  451. expect(decodeInput("\x1b[Z")).toEqual([{ type: "tab" }]);
  452. expect(decodeInput("\x1b")).toEqual([{ type: "esc" }]);
  453. expect(decodeInput("a")).toEqual([{ type: "char", ch: "a" }]);
  454. expect(decodeInput("ab\r")).toEqual([
  455. { type: "char", ch: "a" },
  456. { type: "char", ch: "b" },
  457. { type: "enter" },
  458. ]);
  459. expect(decodeInput("\x1b[9~")).toEqual([]); // unknown escape -> nothing
  460. });
  461. test("SGR mouse: click, release and wheel", () => {
  462. expect(decodeInput("\x1b[<0;12;7M")).toEqual([
  463. { type: "click", row: 6, col: 11 },
  464. ]);
  465. expect(decodeInput("\x1b[<0;12;7m")).toEqual([]); // release
  466. expect(decodeInput("\x1b[<64;5;5M")).toEqual([]); // wheel
  467. });
  468. // SS3 (application-cursor-mode) arrows: a terminal left in DECCKM by a
  469. // previous full-screen program sends ESC-O-<letter> instead of the CSI
  470. // (ESC-[-<letter>) form. Before the fix these fell into the bare-esc
  471. // branch (cancel, on an empty search) followed by two literal chars -
  472. // review finding 4.
  473. test("SS3 arrows (ESC O A/B/C/D) decode the same as their CSI form", () => {
  474. expect(decodeInput("\x1bOA")).toEqual([{ type: "up" }]);
  475. expect(decodeInput("\x1bOB")).toEqual([{ type: "down" }]);
  476. expect(decodeInput("\x1bOC")).toEqual([{ type: "tab" }]);
  477. expect(decodeInput("\x1bOD")).toEqual([{ type: "tab" }]);
  478. });
  479. });
  480. // -----------------------------------------------------------------------
  481. // displayWidth
  482. // -----------------------------------------------------------------------
  483. describe("displayWidth", () => {
  484. test("CJK, emoji, combining marks and zero-width characters each measure the cells they occupy", () => {
  485. expect(displayWidth("日本語")).toBe(6);
  486. expect(displayWidth("😀")).toBe(2);
  487. expect(displayWidth("café")).toBe(4);
  488. // Spec (.pipeline/spec.md §4.4) expects 3 assuming ICU joins ನ್ನ
  489. // into one grapheme cluster; this runtime instead splits it as two
  490. // clusters (4 graphemes total) - an ICU segmentation detail, not a
  491. // wrong width range (verified with a standalone Intl.Segmenter probe).
  492. expect(displayWidth("ಕನ್ನಡ")).toBe(4);
  493. expect(displayWidth("🇮🇳")).toBe(1);
  494. expect(displayWidth("‍")).toBe(0);
  495. expect(displayWidth("️")).toBe(0);
  496. });
  497. const WIDE_SAMPLES = [
  498. "ಕನ್ನಡ",
  499. "日本語テキスト",
  500. "😀😀😀",
  501. "🇮🇳🇮🇳",
  502. "café café",
  503. ];
  504. test("truncate never returns more display cells than its budget", () => {
  505. for (const s of WIDE_SAMPLES) {
  506. for (let w = 1; w <= 12; w++) {
  507. expect(displayWidth(truncate(s, w))).toBeLessThanOrEqual(w);
  508. }
  509. }
  510. });
  511. test("a wide grapheme is never split in half", () => {
  512. const lone =
  513. /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/;
  514. for (const s of WIDE_SAMPLES) {
  515. for (let w = 1; w <= 12; w++) {
  516. expect(lone.test(truncate(s, w))).toBe(false);
  517. }
  518. }
  519. });
  520. });
  521. // -----------------------------------------------------------------------
  522. // layout
  523. // -----------------------------------------------------------------------
  524. describe("layout", () => {
  525. test("two columns at cols=100: header contains CONTACTS and GROUPS; granted row [x], ungranted [ ]", () => {
  526. const s = initPicker(
  527. model({ dms: [rohan, priya], groups: [family, wil] }),
  528. 100,
  529. 24,
  530. );
  531. const text = layout(s, 100, 24).join("\n");
  532. expect(text).toContain("CONTACTS");
  533. expect(text).toContain("GROUPS");
  534. expect(text).toContain("[x] Rohan");
  535. expect(text).toContain("[ ] Priya");
  536. });
  537. test("every line's stripAnsi width <= cols, and lines.length <= rows, at several sizes", () => {
  538. const s = initPicker(
  539. model({ dms: [rohan, priya], groups: [family, wil], color: true }),
  540. 100,
  541. 24,
  542. );
  543. for (const [cols, rows] of [
  544. [100, 24],
  545. [60, 24],
  546. [100, 10],
  547. [40, 8],
  548. ] as const) {
  549. const lines = layout(s, cols, rows);
  550. expect(lines.length).toBeLessThanOrEqual(rows);
  551. for (const l of lines)
  552. expect(stripAnsi(l).length).toBeLessThanOrEqual(cols);
  553. }
  554. });
  555. test("cols=60 stacks: CONTACTS and GROUPS on separate lines, one column wide", () => {
  556. const s = initPicker(
  557. model({ dms: [rohan, priya], groups: [family, wil] }),
  558. 60,
  559. 24,
  560. );
  561. const lines = layout(s, 60, 24);
  562. const contactsRow = lines.findIndex((l) => l.includes("CONTACTS"));
  563. const groupsRow = lines.findIndex(
  564. (l, i) => i > contactsRow && l.includes("GROUPS"),
  565. );
  566. expect(contactsRow).toBeGreaterThanOrEqual(0);
  567. expect(groupsRow).toBeGreaterThan(contactsRow);
  568. });
  569. test("a short terminal still emits the search, picked and footer lines", () => {
  570. const s = initPicker(
  571. model({ dms: [rohan, priya], groups: [family, wil] }),
  572. 40,
  573. 8,
  574. );
  575. const lines = layout(s, 40, 8);
  576. expect(lines.length).toBeLessThanOrEqual(8);
  577. expect(lines.some((l) => l.startsWith("Search:"))).toBe(true);
  578. expect(lines.some((l) => l.startsWith("Picked:"))).toBe(true);
  579. expect(lines.some((l) => l.includes("Submit"))).toBe(true);
  580. });
  581. test("a long label is truncated with an ellipsis; an emoji label is never cut mid-surrogate", () => {
  582. const long = item({ jid: "x@g.us", label: "A".repeat(200), kind: "group" });
  583. const emoji = item({
  584. jid: "y@s.whatsapp.net",
  585. label: "\u{1F600}".repeat(50),
  586. kind: "dm",
  587. });
  588. const s = initPicker(model({ dms: [emoji], groups: [long] }), 40, 24);
  589. const text = layout(s, 40, 24).join("\n");
  590. expect(text).toContain("…");
  591. const lone =
  592. /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/;
  593. expect(lone.test(text)).toBe(false);
  594. });
  595. test("a label containing ANSI, CR, LF and a bidi override reaches the frame with all of them gone", () => {
  596. const dirty = item({
  597. jid: "d@s.whatsapp.net",
  598. label: "a\x1b[31mb\rc\nd‮e",
    • Dismissed after review: Contains 2 bidirectional-override character(s), which make text display in a different order from how it's read
    • Line 650 on GitHub
  599. });
  600. const s = initPicker(model({ dms: [dirty] }), 100, 24);
  601. const text = layout(s, 100, 24).join("\n");
  602. expect(text).not.toContain("\x1b[31m");
  603. expect(text).not.toContain("\r");
  604. expect(text).not.toContain("‮");
  605. expect(text).toContain("a[31mbcde");
  606. });
  607. test("an empty contacts column draws dmNote, wrapped to the column width", () => {
  608. const s = initPicker(
  609. model({
  610. dms: [],
  611. groups: [family],
  612. dmNote:
  613. "No contacts to review - set WHATSAPP_CACHE_CONTACTS=0 to opt out.",
  614. }),
  615. 100,
  616. 24,
  617. );
  618. const text = layout(s, 100, 24).join("\n");
  619. expect(text).toContain("WHATSAPP_CACHE_CONTACTS=0");
  620. });
  621. test("an empty column with no note draws dim '(none)'", () => {
  622. const s = initPicker(
  623. model({ dms: [], groups: [family], dmNote: "" }),
  624. 100,
  625. 24,
  626. );
  627. const text = layout(s, 100, 24).join("\n");
  628. expect(text).toContain("(none)");
  629. });
  630. test("chips: '+' for a new tick, '-' for a revoked grant, '×' present", () => {
  631. let s = initPicker(model({ dms: [rohan, priya] }), 100, 24);
  632. s = press(s, { type: "space" }); // untick rohan (granted) -> "-" chip
  633. s = press(s, { type: "down" }, { type: "space" }); // tick priya -> "+" chip
  634. const text = layout(s, 100, 24).join("\n");
  635. expect(text).toContain("[- Rohan ×]");
  636. expect(text).toContain("[+ Priya ×]");
  637. });
  638. test("chips overflow the picked line width and show a leading '+N more'", () => {
  639. const many = Array.from({ length: 20 }, (_, i) =>
  640. item({
  641. jid: `c${i}@s.whatsapp.net`,
  642. label: `Contact Number ${i}`,
  643. granted: false,
  644. }),
  645. );
  646. let s = initPicker(model({ dms: many }), 40, 24);
  647. for (let i = 0; i < many.length; i++) {
  648. s = press(s, { type: "space" });
  649. if (i < many.length - 1) s = press(s, { type: "down" });
  650. }
  651. const text = layout(s, 40, 24).join("\n");
  652. expect(text).toMatch(/\+\d+ more/);
  653. });
  654. test("every line fits the terminal even when one chip plus '+N more' would not", () => {
  655. const many = Array.from({ length: 24 }, (_, i) =>
  656. item({
  657. jid: `c${i}@s.whatsapp.net`,
  658. label: `Name number ${i} Longish`,
  659. granted: true,
  660. }),
  661. );
  662. // 30 columns is the floor: below it the fixed prompt text itself no
  663. // longer fits, and no real terminal is that narrow.
  664. for (const [cols, rows] of [
  665. [40, 24],
  666. [30, 5],
  667. [100, 2],
  668. ]) {
  669. const lines = layout(
  670. initPicker(model({ dms: many }), cols, rows),
  671. cols,
  672. rows,
  673. );
  674. expect(lines.length).toBeLessThanOrEqual(rows);
  675. for (const l of lines) {
  676. expect(displayWidth(stripAnsi(l))).toBeLessThanOrEqual(cols);
  677. }
  678. }
  679. });
  680. test("Restore is dim / not clickable when hasBackup:false", () => {
  681. const s = initPicker(model({ hasBackup: false }), 100, 24);
  682. const lines = layout(s, 100, 24);
  683. const row = lines.findIndex((l) => l.includes("Submit"));
  684. const plain = stripAnsi(lines[row]);
  685. const col = plain.indexOf("Restore");
  686. expect(hitTest(s, 100, 24, row, col)).toBeNull();
  687. });
  688. test("a column with more items than fit ends with '… +N more'", () => {
  689. const many = Array.from({ length: 30 }, (_, i) =>
  690. item({ jid: `g${i}@g.us`, label: `Group ${i}`, kind: "group" }),
  691. );
  692. const s = initPicker(model({ groups: many }), 100, 10);
  693. const text = layout(s, 100, 10).join("\n");
  694. expect(text).toMatch(/… \+\d+ more/);
  695. });
  696. });
  697. // -----------------------------------------------------------------------
  698. // adversarial - a large model, every documented terminal size
  699. // -----------------------------------------------------------------------
  700. describe("layout - adversarial large model", () => {
  701. function bigModel(): PickerModel {
  702. const groups = Array.from({ length: 200 }, (_, i) =>
  703. item({
  704. jid: `g${i}12345678@g.us`,
  705. label: `Group ${i}`,
  706. kind: "group",
  707. granted: i % 3 === 0,
  708. }),
  709. );
  710. const dms = Array.from({ length: 100 }, (_, i) => {
  711. const num = `9198765${String(i).padStart(4, "0")}`; // 11 raw digits
  712. return item({
  713. jid: `${num}@s.whatsapp.net`,
  714. label: `•••••${String(i).padStart(4, "0")}`, // masked, no saved name
  715. kind: "dm",
  716. granted: i % 5 === 0,
  717. });
  718. });
  719. return model({ dms, groups });
  720. }
  721. test("every layout line stays within cols and rows for a 200-group/100-contact model", () => {
  722. const s = initPicker(bigModel(), 80, 24);
  723. for (const cols of [40, 70, 80, 120]) {
  724. for (const rows of [10, 24, 50]) {
  725. const lines = layout(s, cols, rows);
  726. expect(lines.length).toBeLessThanOrEqual(rows);
  727. for (const l of lines) {
  728. expect(stripAnsi(l).length).toBeLessThanOrEqual(cols);
  729. }
  730. }
  731. }
  732. });
  733. test("a one-row column still draws its focused item instead of only a more-line (review finding 11)", () => {
  734. const s = initPicker(bigModel(), 80, 24);
  735. for (const [cols, rows] of [
  736. [60, 11],
  737. [60, 12],
  738. [100, 7],
  739. [100, 8],
  740. ]) {
  741. const lines = layout(s, cols, rows);
  742. expect(lines.length).toBeLessThanOrEqual(rows);
  743. const text = lines.map(stripAnsi).join("\n");
  744. expect(text).toContain(">[");
  745. expect(text).toContain("Group 0");
  746. }
  747. });
  748. test("no drawn line leaks a JID suffix or an unmasked 8+ digit run, contacts with no saved name", () => {
  749. let s = initPicker(bigModel(), 80, 24);
  750. // Tick a few rows so chips (which also render labels) are exercised too.
  751. s = press(s, { type: "space" }, { type: "down" }, { type: "space" });
  752. const digitRun = /\d{8,}/;
  753. for (const cols of [40, 70, 80, 120]) {
  754. for (const rows of [10, 24, 50]) {
  755. const text = layout(s, cols, rows).join("\n");
  756. expect(text).not.toContain("@g.us");
  757. expect(text).not.toContain("@s.whatsapp.net");
  758. expect(text).not.toContain("@lid");
  759. expect(digitRun.test(text)).toBe(false);
  760. }
  761. }
  762. });
  763. // Review finding 1: the window offset was derived from bodyRows, but only
  764. // bodyRows-1 rows are actually drawn once a trailing "... +N more" line is
  765. // needed, so the cursor sat one row below the last drawn row for almost
  766. // the whole scroll range - Space would then toggle an access grant the
  767. // operator cannot see. 200 groups at 100x24 (bodyRows 18) overflows almost
  768. // immediately; 25 Downs lands deep in that range.
  769. test("the cursor marker stays inside the drawn window once a column overflows", () => {
  770. let s = initPicker(bigModel(), 100, 24);
  771. s = press(s, { type: "tab" }); // groups column, right-hand side of the line
  772. for (let i = 0; i < 25; i++) s = press(s, { type: "down" });
  773. expect(s.cursor.groups).toBe(25);
  774. const focusedLabel = visibleItems(s, "groups")[25].label;
  775. const text = layout(s, 100, 24).join("\n");
  776. // Marker is glued directly to the box (">[x]"/">[ ]"), not the row start
  777. // - the groups column sits to the right of the padded dms column, so a
  778. // per-line "starts with >" check would miss it entirely.
  779. const markers = text.match(/>\[[x ]\]/g) ?? [];
  780. expect(markers).toHaveLength(1);
  781. const idx = text.indexOf(markers[0]!);
  782. expect(text.slice(idx, idx + 60)).toContain(focusedLabel);
  783. });
  784. function wideModel(): PickerModel {
  785. const scripts = [`ಕನ್ನಡ`, `日本語`, `😀`, `🇮🇳`, `Café`];
  786. const dms = Array.from({ length: 40 }, (_, i) =>
  787. item({
  788. jid: `d${i}@s.whatsapp.net`,
  789. label: `${scripts[i % scripts.length]} ${i}`,
  790. kind: "dm",
  791. granted: i % 4 === 0,
  792. }),
  793. );
  794. const groups = Array.from({ length: 40 }, (_, i) =>
  795. item({
  796. jid: `w${i}@g.us`,
  797. label: `${scripts[(i + 1) % scripts.length]} Group ${i}`,
  798. kind: "group",
  799. granted: i % 4 === 0,
  800. }),
  801. );
  802. return model({ dms, groups });
  803. }
  804. test("every layout line's DISPLAY width stays within cols for a wide-script model", () => {
  805. const s = initPicker(wideModel(), 80, 24);
  806. for (const cols of [40, 70, 80, 120]) {
  807. for (const rows of [10, 24, 50]) {
  808. const lines = layout(s, cols, rows);
  809. expect(lines.length).toBeLessThanOrEqual(rows);
  810. for (const l of lines) {
  811. expect(displayWidth(stripAnsi(l))).toBeLessThanOrEqual(cols);
  812. }
  813. }
  814. }
  815. });
  816. });
  817. // -----------------------------------------------------------------------
  818. // hitTest / click
  819. // -----------------------------------------------------------------------
  820. describe("hitTest / click", () => {
  821. test("a click on a contacts row toggles it and moves focus + cursor there", () => {
  822. let s = initPicker(
  823. model({ dms: [rohan, priya], groups: [family] }),
  824. 100,
  825. 24,
  826. );
  827. const lines = layout(s, 100, 24);
  828. const row = lines.findIndex((l) => l.includes("Priya"));
  829. const ev = hitTest(s, 100, 24, row, 5);
  830. expect(ev).toEqual({ type: "focus", column: "dms", index: 1 });
  831. s = reducePicker(s, { type: "click", row, col: 5 });
  832. expect(s.focus).toBe("dms");
  833. expect(s.cursor.dms).toBe(1);
  834. expect(s.ticked.has(priya.jid)).toBe(true);
  835. });
  836. test("a click on a chip's '×' removes that chip (same result as backspace-on-empty)", () => {
  837. let s = initPicker(model({ dms: [rohan] }), 100, 24);
  838. s = press(s, { type: "space" }); // untick -> struck chip
  839. const lines = layout(s, 100, 24);
  840. const row = lines.findIndex((l) => l.startsWith("Picked:"));
  841. const plain = stripAnsi(lines[row]);
  842. const col = plain.indexOf("×");
  843. const ev = hitTest(s, 100, 24, row, col);
  844. expect(ev).toEqual({ type: "unchip", jid: rohan.jid });
  845. s = reducePicker(s, { type: "click", row, col });
  846. expect(s.chips).toEqual([]);
  847. expect(s.ticked.has(rohan.jid)).toBe(true);
  848. });
  849. test("clicks on Submit/Undo/Restore dispatch those actions; a click on blank space is a no-op", () => {
  850. const s = initPicker(model({ hasBackup: true }), 100, 24);
  851. const lines = layout(s, 100, 24);
  852. const row = lines.findIndex((l) => l.includes("Submit"));
  853. const plain = stripAnsi(lines[row]);
  854. expect(hitTest(s, 100, 24, row, plain.indexOf("Submit"))).toEqual({
  855. type: "submit",
  856. });
  857. expect(hitTest(s, 100, 24, row, plain.indexOf("Undo"))).toEqual({
  858. type: "undo",
  859. });
  860. expect(hitTest(s, 100, 24, row, plain.indexOf("Restore"))).toEqual({
  861. type: "restore",
  862. });
  863. // Row 0 is now the focusable search line (hits focusSearch, not null) -
  864. // probe blank space past the last footer part instead.
  865. expect(hitTest(s, 100, 24, row, 70)).toBeNull();
  866. });
  867. test("after a resize event the same screen coordinates hit the new geometry", () => {
  868. let s = initPicker(model({ dms: [rohan, priya] }), 100, 24);
  869. s = reducePicker(s, { type: "resize", cols: 60, rows: 24 });
  870. const lines = layout(s, 60, 24);
  871. const row = lines.findIndex((l) => l.includes("Priya"));
  872. const ev = hitTest(s, 60, 24, row, 5);
  873. expect(ev).toEqual({ type: "focus", column: "dms", index: 1 });
  874. });
  875. // Review finding 2: both columns share every body row in the two-column
  876. // form, and itemRows used to be matched on row alone - a click anywhere on
  877. // a row, including deep inside the right-hand GROUPS column, resolved to
  878. // the LEFT (dms) item on that same line. col 55 at cols=100 is inside the
  879. // GROUPS column (rightX = leftW + 2 = 51).
  880. test("a click in the GROUPS column focuses the group, not the dm on the same row", () => {
  881. let s = initPicker(model({ dms: [rohan], groups: [family] }), 100, 24);
  882. const lines = layout(s, 100, 24);
  883. const row = lines.findIndex((l) => l.includes("Family"));
  884. const ev = hitTest(s, 100, 24, row, 55);
  885. expect(ev).toEqual({ type: "focus", column: "groups", index: 0 });
  886. s = reducePicker(s, { type: "click", row, col: 55 });
  887. expect(s.focus).toBe("groups");
  888. expect(s.ticked.has(family.jid)).toBe(false); // family was granted -> untoggled
  889. expect(s.ticked.has(rohan.jid)).toBe(true); // dm row on the same line untouched
  890. });
  891. test("a click on a row draws the '>' marker on that row in the next frame", () => {
  892. // Contacts row.
  893. let s = initPicker(
  894. model({ dms: [rohan, priya], groups: [family] }),
  895. 100,
  896. 24,
  897. );
  898. let lines = layout(s, 100, 24);
  899. let row = lines.findIndex((l) => l.includes("Priya"));
  900. let next = reducePicker(s, { type: "click", row, col: 5 });
  901. let frameLine = stripAnsi(layout(next, 100, 24)[row]);
  902. expect(frameLine).toContain(">[");
  903. expect(frameLine.indexOf(">[")).toBeLessThan(frameLine.indexOf("Priya"));
  904. // Groups row (right-hand column at cols=100, rightX=51).
  905. s = initPicker(model({ dms: [rohan], groups: [family, wil] }), 100, 24);
  906. lines = layout(s, 100, 24);
  907. row = lines.findIndex((l) => l.includes("WIL Group HUDINI"));
  908. next = reducePicker(s, { type: "click", row, col: 55 });
  909. frameLine = stripAnsi(layout(next, 100, 24)[row]);
  910. const markerIdx = frameLine.indexOf(">[");
  911. expect(markerIdx).toBeGreaterThanOrEqual(51); // right half of the line
  912. expect(frameLine.slice(markerIdx)).toContain("WIL Group HUDINI");
  913. });
  914. test("a click on the search line focuses it and ticks nothing", () => {
  915. const s = initPicker(model({ dms: [rohan] }), 100, 24);
  916. expect(hitTest(s, 100, 24, 0, 3)).toEqual({ type: "focusSearch" });
  917. const next = reducePicker(s, { type: "click", row: 0, col: 3 });
  918. expect(next.focus).toBe("search");
  919. expect(next.ticked).toEqual(s.ticked);
  920. });
  921. });
  922. // -----------------------------------------------------------------------
  923. // footer
  924. // -----------------------------------------------------------------------
  925. describe("footer", () => {
  926. test("the footer reads Submit: enter / Undo: ctrl-z / Restore: ctrl-r / Quit: esc", () => {
  927. const s = initPicker(model({ hasBackup: true }), 100, 24);
  928. const lines = layout(s, 100, 24);
  929. const footerLine = lines.find((l) => l.includes("Submit"))!;
  930. expect(footerLine).toBe(
  931. "Submit: enter Undo: ctrl-z Restore: ctrl-r Quit: esc",
  932. );
  933. });
  934. test("verbs are bold+accent and keys dim when colour is on", () => {
  935. const s = initPicker(model({ hasBackup: true, color: true }), 100, 24);
  936. const lines = layout(s, 100, 24);
  937. const footerLine = lines.find((l) => l.includes("Submit"))!;
  938. expect(footerLine).toContain(
  939. "\x1b[1;32mSubmit\x1b[0m: \x1b[2menter\x1b[0m",
  940. );
  941. });
  942. test("the short footer is used when the full one does not fit", () => {
  943. const s = initPicker(model({ hasBackup: true }), 40, 24);
  944. const lines = layout(s, 40, 24);
  945. const row = lines.findIndex((l) => l.includes("Submit"));
  946. const footerLine = stripAnsi(lines[row]);
  947. expect(footerLine).toBe("Submit Undo Restore Quit");
  948. const restoreCol = footerLine.indexOf("Restore");
  949. expect(hitTest(s, 40, 24, row, restoreCol)).toEqual({ type: "restore" });
  950. });
  951. });
  952. // -----------------------------------------------------------------------
  953. // applySelection
  954. // -----------------------------------------------------------------------
  955. describe("applySelection", () => {
  956. function base(): {
  957. allowFrom: string[];
  958. groups: Record<
  959. string,
  960. { requireMention: boolean; allowFrom: string[]; roster?: boolean }
  961. >;
  962. } {
  963. return {
  964. allowFrom: ["kept@s.whatsapp.net", "revoke-me@s.whatsapp.net"],
  965. groups: {
  966. "kept@g.us": {
  967. requireMention: false,
  968. allowFrom: ["x@s"],
  969. roster: true,
  970. },
  971. "revoke@g.us": { requireMention: true, allowFrom: [], roster: false },
  972. },
  973. };
  974. }
  975. test("rule 1: a group shown but not selected is deleted", () => {
  976. const b = base();
  977. const out = applySelection(
  978. b,
  979. { groups: new Set(["kept@g.us"]), dms: new Set(), roster: new Set() },
  980. { groups: new Set(["kept@g.us", "revoke@g.us"]), dms: new Set() },
  981. );
  982. expect(out.groups["revoke@g.us"]).toBeUndefined();
  983. expect(out.groups["kept@g.us"]).toBeDefined();
  984. });
  985. test("rule 2: a group already configured survives byte-identical, roster included", () => {
  986. const b = base();
  987. const out = applySelection(
  988. b,
  989. {
  990. groups: new Set(["kept@g.us"]),
  991. dms: new Set(),
  992. roster: new Set(["kept@g.us"]),
  993. },
  994. { groups: new Set(["kept@g.us"]), dms: new Set() },
  995. );
  996. expect(out.groups["kept@g.us"]).toEqual(b.groups["kept@g.us"]);
  997. });
  998. test("rule 3: a new group gets requireMention:true, empty allowFrom, roster from the selection", () => {
  999. const b = base();
  1000. const out = applySelection(
  1001. b,
  1002. {
  1003. groups: new Set(["new@g.us"]),
  1004. dms: new Set(),
  1005. roster: new Set(["new@g.us"]),
  1006. },
  1007. { groups: new Set(), dms: new Set() },
  1008. );
  1009. expect(out.groups["new@g.us"]).toEqual({
  1010. requireMention: true,
  1011. allowFrom: [],
  1012. roster: true,
  1013. });
  1014. });
  1015. test("rule 4: allowFrom drops only a shown+unticked dm; an entry the server added while shown never listed it is kept", () => {
  1016. const b = {
  1017. allowFrom: [
  1018. "kept@s.whatsapp.net",
  1019. "revoke-me@s.whatsapp.net",
  1020. "added-by-server@s.whatsapp.net",
  1021. ],
  1022. groups: {},
  1023. };
  1024. const out = applySelection(
  1025. b,
  1026. {
  1027. groups: new Set(),
  1028. dms: new Set(["kept@s.whatsapp.net"]),
  1029. roster: new Set(),
  1030. },
  1031. {
  1032. groups: new Set(),
  1033. dms: new Set(["kept@s.whatsapp.net", "revoke-me@s.whatsapp.net"]),
  1034. },
  1035. );
  1036. expect([...out.allowFrom].sort()).toEqual(
  1037. ["added-by-server@s.whatsapp.net", "kept@s.whatsapp.net"].sort(),
  1038. );
  1039. });
  1040. test("rule 5: base is never mutated", () => {
  1041. const b = base();
  1042. const before = JSON.stringify(b);
  1043. applySelection(
  1044. b,
  1045. { groups: new Set(), dms: new Set(), roster: new Set() },
  1046. { groups: new Set(["kept@g.us", "revoke@g.us"]), dms: new Set() },
  1047. );
  1048. expect(JSON.stringify(b)).toBe(before);
  1049. });
  1050. });
  1051. // -----------------------------------------------------------------------
  1052. // e2e - drives runPicker over a fake, paced stdin. Interactive/timing
  1053. // sensitive: skipped only under CI, never removed (brief stop condition).
  1054. // -----------------------------------------------------------------------
  1055. describe("runPicker e2e", () => {
  1056. test.skipIf(!!process.env.CI)(
  1057. "search + Enter + Enter submits with the highlighted group ticked",
  1058. async () => {
  1059. const input = new PassThrough();
  1060. const output = new PassThrough();
  1061. let written = "";
  1062. output.on("data", (d) => (written += d.toString()));
  1063. (input as unknown as { setRawMode: () => void }).setRawMode = () => {
  1064. throw new Error("setRawMode must not be called on a non-TTY stream");
  1065. };
  1066. const familyItem = item({
  1067. jid: "fam@g.us",
  1068. label: "Family",
  1069. kind: "group",
  1070. });
  1071. const resultPromise = runPicker(model({ groups: [familyItem] }), {
  1072. input: input as unknown as NodeJS.ReadStream,
  1073. output: output as unknown as NodeJS.WriteStream,
  1074. });
  1075. const type = async (s: string) => {
  1076. await new Promise((r) => setTimeout(r, 50));
  1077. input.write(s);
  1078. };
  1079. await type("\t"); // focus groups (dms column is empty)
  1080. await type("f");
  1081. await type("a");
  1082. await type("m");
  1083. await type("\r"); // tick highlighted, clear search
  1084. await type("\r"); // submit
  1085. const result = await resultPromise;
  1086. expect(result).toEqual({
  1087. action: "submit",
  1088. groups: new Set(["fam@g.us"]),
  1089. dms: new Set(),
  1090. roster: new Set(),
  1091. });
  1092. expect(written).toContain("\x1b[?1000h");
  1093. expect(written).toContain("\x1b[?1006h");
  1094. expect(written).toContain("\x1b[?1006l\x1b[?1000l");
  1095. expect(written).toContain("\x1b[?1049l");
  1096. },
  1097. { timeout: 5000 },
  1098. );
  1099. test.skipIf(!!process.env.CI)(
  1100. "Ctrl-C resolves null, and the teardown sequence was still written",
  1101. async () => {
  1102. const input = new PassThrough();
  1103. const output = new PassThrough();
  1104. let written = "";
  1105. output.on("data", (d) => (written += d.toString()));
  1106. const resultPromise = runPicker(model({ dms: [rohan] }), {
  1107. input: input as unknown as NodeJS.ReadStream,
  1108. output: output as unknown as NodeJS.WriteStream,
  1109. });
  1110. await new Promise((r) => setTimeout(r, 50));
  1111. input.write("\x03");
  1112. const result = await resultPromise;
  1113. expect(result).toBeNull();
  1114. expect(written).toContain("\x1b[?1049l");
  1115. },
  1116. { timeout: 5000 },
  1117. );
  1118. });

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.