whatsapp-claude-plugin
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.
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
Markdown
[](/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)
- {
- "$schema": "https://anthropic.com/claude-code/marketplace.schema.json",
- "name": "whatsapp-claude-plugin",
- "version": "1.5.0",
- "description": "WhatsApp channel plugin for Claude Code",
- "owner": {
- "name": "Rich627"
- },
- "plugins": [
- {
- "name": "whatsapp-channel",
- "description": "WhatsApp channel for Claude Code \u2014 linked device or official Cloud API, with pairing, allowlists and access control.",
- "version": "0.33.1",
- "source": "./",
- "category": "channels"
- }
- ]
- }
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)
- # WhatsApp Channel for Claude Code
- Drive your Claude Code session from WhatsApp. Choose a **linked device** for a
- personal account or the **official WhatsApp Cloud API** for business DMs.
- The default Baileys provider connects like WhatsApp Web: pair your phone, then
- Claude replies from your own number. Existing installations keep this provider.
- The optional Cloud API provider uses Meta's business API and a public HTTPS
- webhook, with its own credentials, messaging policies and applicable fees.
- Both providers feed the same MCP channel and access gate.
- [](https://code.claude.com/docs/en/plugins)
- [](https://modelcontextprotocol.io)
- [](https://opensource.org/licenses/Apache-2.0)
- > **Community project.** This plugin is not made or endorsed by Anthropic or Meta.
- > Its Baileys provider uses an unofficial linked-device protocol, which may
- > conflict with WhatsApp's terms and put the number at risk. The optional Cloud
- > provider uses official API transport; confirm your use is permitted under
- > Meta's business and AI-provider rules before enabling it.
- ## Installation
- ```sh
- 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:
- ```text
- /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/).
- ## Other MCP clients (Codex CLI, Gemini CLI, Cursor)
- 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:
- - **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.
- - **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)).
- Register the server with an absolute path — `${CLAUDE_PLUGIN_ROOT}` is substituted by Claude Code only:
- **Codex CLI** (`~/.codex/config.toml`)
- ```toml
- [mcp_servers.whatsapp]
- command = "bun"
- args = ["run", "--cwd", "/absolute/path/to/whatsapp-channel", "start"]
- startup_timeout_sec = 30 # default 10 is tight for a first Baileys connect
- tool_timeout_sec = 120 # default 60; wait_for_messages parks for up to 40s
- ```
- **Gemini CLI** (`~/.gemini/settings.json`)
- ```json
- {
- "mcpServers": {
- "whatsapp": {
- "command": "bun",
- "args": ["run", "--cwd", "/absolute/path/to/whatsapp-channel", "start"],
- "timeout": 600000
- }
- }
- }
- ```
- **Cursor** (`~/.cursor/mcp.json` for all projects, `.cursor/mcp.json` for one)
- ```json
- {
- "mcpServers": {
- "whatsapp": {
- "type": "stdio",
- "command": "bun",
- "args": ["run", "--cwd", "/absolute/path/to/whatsapp-channel", "start"]
- }
- }
- }
- ```
- 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.
- ## Access control from a terminal
- Everything the access skill does, without Claude Code:
- ```sh
- bun scripts/access.ts status # policy, allowlist, pending codes, groups
- bun scripts/access.ts policy pairing # open the door
- bun scripts/access.ts pair <code> # approve someone who messaged you
- bun scripts/access.ts allow <jid> # add directly
- bun scripts/access.ts remove <jid>
- bun scripts/access.ts group add <groupJid> [--mention] [--allow jid1,jid2]
- bun scripts/access.ts set replyToMode first # ackReaction, textChunkLimit, chunkMode, mentionPatterns
- ```
- 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.
- ## Features
- The list below describes the default linked-device provider. See the
- [provider capability comparison](./docs/cloud-api.md#capabilities-in-this-plugins-first-cloud-provider)
- for the initial Cloud API scope. Shared DM access, attachment processing,
- transcription and context recovery also work with Cloud API.
- - **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.
- - **Typing indicator.** The chat shows "typing…" while Claude works on its message, and "recording audio…" while a voice note uploads (linked device).
- - **@-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.
- - **Full media support.** Photos, voice notes, video, documents, and stickers, in both directions.
- - **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).
- - **Voice transcription.** Incoming voice notes are transcribed locally via mlx-whisper (see [setup](#voice-transcription-optional)); without the script they arrive as plain attachments.
- - **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.
- - **Per-group personalities.** Each group gets its own `config.md` with a custom personality and conversation memory.
- - **Permission relay.** Approve or deny Claude's tool requests from WhatsApp with an emoji reaction (👍 / 👎).
- - **Cron tasks.** A `## Cron Jobs` section in a group's `config.md` schedules recurring server-side tasks.
- - **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.
- - **Dual accounts.** Run personal and business numbers side by side with separate state and behaviors.
- - **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.
- ## How it works
- ```text
- WhatsApp linked device <──Baileys────────> MCP Server <──stdio──> Claude Code
- WhatsApp business DMs <──Cloud API/HTTPS─> MCP Server
- ```
- 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.
- 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.
- ## Voice transcription (optional)
- One-time setup (Apple Silicon, mlx-whisper):
- ```bash
- brew install ffmpeg # mlx-whisper uses it to decode audio
- python3 -m venv ~/whisper-env
- source ~/whisper-env/bin/activate
- pip install mlx-whisper
- cp scripts/whisper-transcribe.sh ~/whisper-transcribe.sh
- chmod +x ~/whisper-transcribe.sh
- ~/whisper-transcribe.sh path/to/sample.ogg # optional: test
- ```
- 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.
- **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.
- ## Troubleshooting
- | Issue | Solution |
- | ----------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
- | Pairing code not showing | Run `/whatsapp-channel:configure <phone>` first, then relaunch |
- | 440 disconnect error | Only one connection per auth state allowed. Kill stale processes: `pkill -f "whatsapp.*server"` |
- | 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. |
- | Messages not arriving | Known Claude Code client bug ([#37933](https://github.com/anthropics/claude-code/issues/37933)). Server-side is correct, awaiting client fix. |
- | 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. |
- | Auth expired | Run `/whatsapp-channel:configure reset-auth` and re-pair |
- ## Documentation
- 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).
- ## Contributing
- Issues and pull requests are welcome — read [CONTRIBUTING.md](./CONTRIBUTING.md) before opening one. Report security issues privately per [SECURITY.md](./SECURITY.md).
- ## Star History
- <a href="https://www.star-history.com/?type=date&repos=Rich627%2Fwhatsapp-claude-plugin">
- <picture>
- <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" />
- <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" />
- <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" />
- </picture>
- </a>
- ## License
- [Apache 2.0](./LICENSE) — Copyright 2025 Richie Liu
scripts/picker.test.ts · Bundled script · 1,208 lines · 1 finding marked
- import { describe, expect, test } from "bun:test";
- import { PassThrough } from "node:stream";
- import { stripVTControlCharacters as stripAnsi } from "node:util";
- import {
- applySelection,
- chipsOf,
- decodeInput,
- displayWidth,
- hitTest,
- initPicker,
- layout,
- reducePicker,
- runPicker,
- selectionOf,
- truncate,
- visibleItems,
- type PickerEvent,
- type PickerItem,
- type PickerModel,
- type PickerState,
- } from "./picker";
- function item(overrides: Partial<PickerItem> = {}): PickerItem {
- return {
- jid: "1@s.whatsapp.net",
- label: "Item",
- kind: "dm",
- granted: false,
- roster: false,
- ...overrides,
- };
- }
- function model(overrides: Partial<PickerModel> = {}): PickerModel {
- return {
- dms: [],
- groups: [],
- dmNote: "",
- groupNote: "",
- hasBackup: false,
- color: false,
- ...overrides,
- };
- }
- function press(state: PickerState, ...events: PickerEvent[]): PickerState {
- return events.reduce((s, e) => reducePicker(s, e), state);
- }
- const rohan = item({
- jid: "rohan@s.whatsapp.net",
- label: "Rohan",
- kind: "dm",
- granted: true,
- });
- const priya = item({
- jid: "priya@s.whatsapp.net",
- label: "Priya",
- kind: "dm",
- granted: false,
- });
- const family = item({
- jid: "family@g.us",
- label: "Family",
- kind: "group",
- granted: true,
- roster: true,
- });
- const wil = item({
- jid: "wil@g.us",
- label: "WIL Group HUDINI",
- kind: "group",
- granted: false,
- });
- // -----------------------------------------------------------------------
- // reducer
- // -----------------------------------------------------------------------
- describe("reducePicker", () => {
- test("initPicker: every granted item ticked, others not; chips empty; focus dms; cursors 0; done null", () => {
- const s = initPicker(
- model({ dms: [rohan, priya], groups: [family, wil] }),
- 100,
- 24,
- );
- expect(s.ticked.has(rohan.jid)).toBe(true);
- expect(s.ticked.has(priya.jid)).toBe(false);
- expect(s.ticked.has(family.jid)).toBe(true);
- expect(s.ticked.has(wil.jid)).toBe(false);
- expect(s.chips).toEqual([]);
- expect(s.focus).toBe("dms");
- expect(s.cursor).toEqual({ dms: 0, groups: 0 });
- expect(s.done).toBeNull();
- });
- test("a filter change puts both cursors back on row 0", () => {
- let s = initPicker(
- model({ dms: [rohan, priya], groups: [family, wil] }),
- 100,
- 24,
- );
- s = press(s, { type: "down" }); // dms cursor -> 1
- expect(s.cursor.dms).toBe(1);
- s = press(
- s,
- { type: "char", ch: "F" },
- { type: "char", ch: "A" },
- { type: "char", ch: "M" },
- );
- expect(visibleItems(s, "dms").map((i) => i.jid)).toEqual([]);
- expect(visibleItems(s, "groups").map((i) => i.jid)).toEqual([family.jid]);
- expect(s.cursor).toEqual({ dms: 0, groups: 0 });
- expect(s.focus).toBe("search");
- });
- test("a term matching only a JID/number matches nothing (label-only filter)", () => {
- const contact = item({
- jid: "61400011675@s.whatsapp.net",
- label: "Rohan",
- granted: false,
- });
- let s = initPicker(model({ dms: [contact] }), 100, 24);
- s = press(
- s,
- { type: "char", ch: "6" },
- { type: "char", ch: "1" },
- { type: "char", ch: "4" },
- );
- expect(visibleItems(s, "dms")).toEqual([]);
- });
- test("Enter with a non-empty search ticks the highlighted row, pushes its chip and clears the search", () => {
- let s = initPicker(model({ dms: [priya] }), 100, 24);
- s = press(
- s,
- { type: "char", ch: "p" },
- { type: "char", ch: "r" },
- { type: "enter" },
- );
- expect(s.ticked.has(priya.jid)).toBe(true);
- expect(s.chips).toEqual([priya.jid]);
- expect(s.search).toBe("");
- expect(visibleItems(s, "dms")).toEqual([priya]);
- });
- test("Space inside a non-empty search is a filter character, not a tick", () => {
- const smith = item({ jid: "1@s.whatsapp.net", label: "John Smith" });
- const doe = item({ jid: "2@s.whatsapp.net", label: "John Doe" });
- let s = initPicker(model({ dms: [smith, doe] }), 100, 24);
- s = press(
- s,
- { type: "char", ch: "J" },
- { type: "char", ch: "o" },
- { type: "char", ch: "h" },
- { type: "char", ch: "n" },
- { type: "space" },
- { type: "char", ch: "S" },
- );
- expect(s.search).toBe("John S");
- expect(s.ticked.size).toBe(0);
- expect(visibleItems(s, "dms").map((i) => i.jid)).toEqual([smith.jid]);
- });
- test("Enter with an empty search sets done='submit'", () => {
- let s = initPicker(model(), 100, 24);
- s = press(s, { type: "enter" });
- expect(s.done).toBe("submit");
- });
- test("Backspace with a non-empty search deletes one character", () => {
- let s = initPicker(model(), 100, 24);
- s = press(
- s,
- { type: "char", ch: "a" },
- { type: "char", ch: "b" },
- { type: "backspace" },
- );
- expect(s.search).toBe("a");
- });
- test("Backspace with an empty search pops the newest chip AND unticks that jid", () => {
- let s = initPicker(model({ dms: [priya] }), 100, 24);
- s = press(s, { type: "space" });
- expect(s.chips).toEqual([priya.jid]);
- s = press(s, { type: "backspace" });
- expect(s.chips).toEqual([]);
- expect(s.ticked.has(priya.jid)).toBe(false);
- const before = s;
- s = press(s, { type: "backspace" }); // no chips left -> no-op
- expect(s).toBe(before);
- });
- test("Space toggles only the highlighted row of the focused column", () => {
- let s = initPicker(
- model({ dms: [rohan, priya], groups: [family] }),
- 100,
- 24,
- );
- s = press(s, { type: "space" }); // focus dms, cursor 0 -> rohan
- expect(s.ticked.has(rohan.jid)).toBe(false);
- expect(s.ticked.has(priya.jid)).toBe(false);
- expect(s.ticked.has(family.jid)).toBe(true); // untouched
- });
- test("Enter with the caret in the search line ticks the MARKED row, not the previously focused column", () => {
- const alice = item({ jid: "1@s.whatsapp.net", label: "Alice", kind: "dm" });
- const zeta = item({ jid: "g1@g.us", label: "Zeta Group", kind: "group" });
- let s = initPicker(model({ dms: [alice], groups: [zeta] }), 100, 24);
- s = press(s, { type: "tab" }); // groups focused
- s = press(s, { type: "char", ch: "a" }); // snaps to search; both match
- // Move a column cursor off row 0, then come back to the search line:
- // the marker is on row 0 of the target, and Space must follow it.
- s = press(
- s,
- { type: "tab" },
- { type: "down" },
- { type: "tab" },
- { type: "tab" },
- );
- expect(s.focus).toBe("search");
- const marked = layout(s, 100, 24)
- .map(stripAnsi)
- .find((l) => l.startsWith(">"));
- expect(marked).toContain("Alice");
- // From the search line a space is a filter character; Enter is the tick.
- s = press(s, { type: "enter" });
- expect([...s.ticked]).toEqual([alice.jid]);
- });
- test("Tab cycles dms -> groups -> search -> dms; up/down move and clamp at both ends; empty column is a no-op", () => {
- let s = initPicker(model({ dms: [rohan, priya], groups: [] }), 100, 24);
- s = press(s, { type: "tab" });
- expect(s.focus).toBe("groups");
- const before = s;
- s = press(s, { type: "down" });
- expect(s).toBe(before); // groups is empty
- s = press(s, { type: "tab" }); // groups -> search
- expect(s.focus).toBe("search");
- s = press(s, { type: "tab" }); // search -> dms, completing the cycle
- expect(s.focus).toBe("dms");
- s = press(s, { type: "down" });
- expect(s.cursor.dms).toBe(1);
- s = press(s, { type: "down" });
- expect(s.cursor.dms).toBe(1); // clamped
- s = press(s, { type: "up" }, { type: "up" });
- expect(s.cursor.dms).toBe(0);
- });
- test("Undo pops the last toggle (ticked + chips both restored); undo on an empty stack is a no-op", () => {
- let s = initPicker(model({ dms: [priya] }), 100, 24);
- s = press(s, { type: "space" });
- expect(s.ticked.has(priya.jid)).toBe(true);
- s = press(s, { type: "undo" });
- expect(s.ticked.has(priya.jid)).toBe(false);
- expect(s.chips).toEqual([]);
- const before = s;
- s = press(s, { type: "undo" });
- expect(s).toBe(before);
- });
- test("'r' on a ticked, not-yet-granted group sets [r]; a second 'r' clears it", () => {
- let s = initPicker(model({ groups: [wil] }), 100, 24);
- s = press(s, { type: "tab" }, { type: "space" });
- expect(s.ticked.has(wil.jid)).toBe(true);
- s = press(s, { type: "char", ch: "r" });
- expect(s.roster.has(wil.jid)).toBe(true);
- s = press(s, { type: "char", ch: "r" });
- expect(s.roster.has(wil.jid)).toBe(false);
- });
- test("'r' on a ticked ALREADY-granted group is a no-op ([D2])", () => {
- let s = initPicker(model({ groups: [family] }), 100, 24);
- s = press(s, { type: "tab" });
- const before = s;
- s = press(s, { type: "char", ch: "r" });
- expect(s).toBe(before);
- });
- test("'r' on a contact is a no-op; 'r' while the search is non-empty is a plain filter character", () => {
- let s = initPicker(model({ dms: [priya] }), 100, 24);
- s = press(s, { type: "space" });
- const before = s;
- s = press(s, { type: "char", ch: "r" });
- expect(s).toBe(before);
- s = press(s, { type: "char", ch: "z" }, { type: "char", ch: "r" });
- expect(s.search).toBe("zr");
- });
- test("unticking an existing grant produces a STRUCK chip; re-ticking removes the chip entirely", () => {
- let s = initPicker(model({ dms: [rohan] }), 100, 24);
- s = press(s, { type: "space" });
- expect(chipsOf(s)).toEqual([
- { jid: rohan.jid, label: "Rohan", struck: true },
- ]);
- s = press(s, { type: "space" });
- expect(chipsOf(s)).toEqual([]);
- });
- test("Esc clears a non-empty search; Esc on an empty search sets done='cancel'", () => {
- let s = initPicker(model(), 100, 24);
- s = press(s, { type: "char", ch: "a" }, { type: "esc" });
- expect(s.search).toBe("");
- expect(s.done).toBeNull();
- s = press(s, { type: "esc" });
- expect(s.done).toBe("cancel");
- });
- test("'restore' is inert when hasBackup:false, sets done='restore' when true", () => {
- let s = initPicker(model({ hasBackup: false }), 100, 24);
- const before = s;
- s = press(s, { type: "restore" });
- expect(s).toBe(before);
- s = initPicker(model({ hasBackup: true }), 100, 24);
- s = press(s, { type: "restore" });
- expect(s.done).toBe("restore");
- });
- test("selectionOf splits groups/dms and filters roster to ticked groups only", () => {
- let s = initPicker(model({ dms: [rohan], groups: [wil] }), 100, 24);
- s = press(s, { type: "tab" }, { type: "space" }, { type: "char", ch: "r" });
- let sel = selectionOf(s);
- expect(sel.groups).toEqual(new Set([wil.jid]));
- expect(sel.dms).toEqual(new Set([rohan.jid]));
- expect(sel.roster).toEqual(new Set([wil.jid]));
- s = press(s, { type: "space" }); // untick wil
- sel = selectionOf(s);
- expect(sel.groups).toEqual(new Set());
- expect(sel.roster).toEqual(new Set());
- });
- test("the reducer never mutates its input (Set identity + original state unchanged)", () => {
- const s0 = initPicker(model({ dms: [priya] }), 100, 24);
- const tickedRef = s0.ticked;
- const s1 = reducePicker(s0, { type: "space" });
- expect(s0.ticked).toBe(tickedRef);
- expect(s0.ticked.has(priya.jid)).toBe(false);
- expect(s1).not.toBe(s0);
- expect(s1.ticked).not.toBe(s0.ticked);
- });
- test("a 'focus' event with an out-of-range index clamps to the last visible row", () => {
- let s = initPicker(model({ groups: [family, wil] }), 100, 24);
- s = press(s, { type: "focus", column: "groups", index: 999 });
- expect(s.focus).toBe("groups");
- expect(s.cursor.groups).toBe(1); // clamped to visibleItems("groups").length - 1
- });
- test("resize mid-session keeps ticks, chips and cursor untouched", () => {
- let s = initPicker(model({ dms: [rohan, priya] }), 100, 24);
- s = press(s, { type: "down" }, { type: "space" }); // tick priya, cursor 1
- expect(s.ticked.has(rohan.jid)).toBe(true);
- expect(s.ticked.has(priya.jid)).toBe(true);
- expect(s.chips).toEqual([priya.jid]);
- s = press(s, { type: "resize", cols: 60, rows: 20 });
- expect(s.cols).toBe(60);
- expect(s.rows).toBe(20);
- expect(s.ticked.has(rohan.jid)).toBe(true);
- expect(s.ticked.has(priya.jid)).toBe(true);
- expect(s.chips).toEqual([priya.jid]);
- expect(s.cursor.dms).toBe(1);
- });
- test("↑ from row 0 moves focus to the search line and draws the caret", () => {
- let s = initPicker(model({ dms: [rohan, priya] }), 100, 24);
- s = press(s, { type: "up" });
- expect(s.focus).toBe("search");
- expect(s.lastColumn).toBe("dms");
- const searchLine = layout(s, 100, 24)[0];
- expect(searchLine.endsWith("▏")).toBe(true);
- });
- test("↓ from the search line returns to row 0 of the last-focused column", () => {
- let s = initPicker(model({ groups: [family, wil] }), 100, 24);
- s = press(s, { type: "tab" }); // dms -> groups
- s = press(s, { type: "down" }); // cursor.groups -> 1
- s = press(s, { type: "up" }, { type: "up" }); // row 0, then -> search
- expect(s.focus).toBe("search");
- s = press(s, { type: "down" });
- expect(s.focus).toBe("groups");
- expect(s.cursor.groups).toBe(0);
- });
- test("typing while a column is focused snaps the caret to the search line", () => {
- let s = initPicker(model({ dms: [rohan], groups: [family] }), 100, 24);
- s = press(s, { type: "tab" }, { type: "char", ch: "z" });
- expect(s.focus).toBe("search");
- expect(s.search).toBe("z");
- expect(s.lastColumn).toBe("groups");
- expect(s.cursor).toEqual({ dms: 0, groups: 0 });
- });
- test("Enter on the search line ticks the first visible Contacts row, and Groups only when Contacts has no match", () => {
- // Case 1: Contacts has a match -> Contacts wins even though Groups also matches.
- let s = initPicker(
- model({
- dms: [item({ jid: "a@s.whatsapp.net", label: "Alpha" })],
- groups: [
- item({ jid: "alpha@g.us", label: "Alpha Group", kind: "group" }),
- ],
- }),
- 100,
- 24,
- );
- s = press(s, { type: "up" }); // -> focus search
- s = press(
- s,
- { type: "char", ch: "a" },
- { type: "char", ch: "l" },
- { type: "enter" },
- );
- expect(s.ticked.has("a@s.whatsapp.net")).toBe(true);
- expect(s.ticked.has("alpha@g.us")).toBe(false);
- // Case 2: no Contacts match -> falls through to Groups.
- let t = initPicker(
- model({
- dms: [rohan],
- groups: [
- item({ jid: "alpha@g.us", label: "Alpha Group", kind: "group" }),
- ],
- }),
- 100,
- 24,
- );
- t = press(t, { type: "up" });
- t = press(
- t,
- { type: "char", ch: "a" },
- { type: "char", ch: "l" },
- { type: "enter" },
- );
- expect(t.ticked.has("alpha@g.us")).toBe(true);
- });
- test("Enter on an empty search still submits with the caret on the search line", () => {
- let s = initPicker(model({ dms: [rohan] }), 100, 24);
- s = press(s, { type: "up" }); // focus -> search, search still ""
- expect(s.focus).toBe("search");
- s = press(s, { type: "enter" });
- expect(s.done).toBe("submit");
- });
- test("'r' filters when the caret is on the search line and flags roster when a column is focused", () => {
- let s = initPicker(model({ groups: [wil] }), 100, 24);
- s = press(s, { type: "tab" }, { type: "space" }); // focus groups, tick wil
- s = press(s, { type: "char", ch: "r" });
- expect(s.roster.has(wil.jid)).toBe(true);
- expect(s.focus).toBe("groups");
- let t = initPicker(model({ groups: [wil] }), 100, 24);
- t = press(t, { type: "tab" }, { type: "space" }); // tick wil, focus groups
- t = press(t, { type: "up" }); // -> focus search (only row is 0)
- t = press(t, { type: "char", ch: "r" });
- expect(t.search).toBe("r");
- expect(t.focus).toBe("search");
- expect(t.roster.has(wil.jid)).toBe(false);
- });
- test("space toggles the last-focused column's row while the caret is on the search line", () => {
- let s = initPicker(model({ dms: [rohan, priya] }), 100, 24);
- s = press(s, { type: "up" }); // focus -> search, lastColumn dms, cursor.dms 0
- expect(s.focus).toBe("search");
- s = press(s, { type: "space" });
- expect(s.ticked.has(rohan.jid)).toBe(false); // rohan was granted -> toggled off
- expect(s.focus).toBe("search"); // space stays focus-neutral
- });
- });
- // -----------------------------------------------------------------------
- // decodeInput
- // -----------------------------------------------------------------------
- describe("decodeInput", () => {
- test("every row of the table maps as specified, in order", () => {
- expect(decodeInput("\x03")).toEqual([{ type: "cancel" }]);
- expect(decodeInput("\r")).toEqual([{ type: "enter" }]);
- expect(decodeInput("\n")).toEqual([{ type: "enter" }]);
- expect(decodeInput("\t")).toEqual([{ type: "tab" }]);
- expect(decodeInput("\x7f")).toEqual([{ type: "backspace" }]);
- expect(decodeInput("\x08")).toEqual([{ type: "backspace" }]);
- expect(decodeInput(" ")).toEqual([{ type: "space" }]);
- expect(decodeInput("\x1a")).toEqual([{ type: "undo" }]);
- expect(decodeInput("\x12")).toEqual([{ type: "restore" }]);
- expect(decodeInput("\x1b[A")).toEqual([{ type: "up" }]);
- expect(decodeInput("\x1b[B")).toEqual([{ type: "down" }]);
- expect(decodeInput("\x1b[C")).toEqual([{ type: "tab" }]);
- expect(decodeInput("\x1b[D")).toEqual([{ type: "tab" }]);
- expect(decodeInput("\x1b[Z")).toEqual([{ type: "tab" }]);
- expect(decodeInput("\x1b")).toEqual([{ type: "esc" }]);
- expect(decodeInput("a")).toEqual([{ type: "char", ch: "a" }]);
- expect(decodeInput("ab\r")).toEqual([
- { type: "char", ch: "a" },
- { type: "char", ch: "b" },
- { type: "enter" },
- ]);
- expect(decodeInput("\x1b[9~")).toEqual([]); // unknown escape -> nothing
- });
- test("SGR mouse: click, release and wheel", () => {
- expect(decodeInput("\x1b[<0;12;7M")).toEqual([
- { type: "click", row: 6, col: 11 },
- ]);
- expect(decodeInput("\x1b[<0;12;7m")).toEqual([]); // release
- expect(decodeInput("\x1b[<64;5;5M")).toEqual([]); // wheel
- });
- // SS3 (application-cursor-mode) arrows: a terminal left in DECCKM by a
- // previous full-screen program sends ESC-O-<letter> instead of the CSI
- // (ESC-[-<letter>) form. Before the fix these fell into the bare-esc
- // branch (cancel, on an empty search) followed by two literal chars -
- // review finding 4.
- test("SS3 arrows (ESC O A/B/C/D) decode the same as their CSI form", () => {
- expect(decodeInput("\x1bOA")).toEqual([{ type: "up" }]);
- expect(decodeInput("\x1bOB")).toEqual([{ type: "down" }]);
- expect(decodeInput("\x1bOC")).toEqual([{ type: "tab" }]);
- expect(decodeInput("\x1bOD")).toEqual([{ type: "tab" }]);
- });
- });
- // -----------------------------------------------------------------------
- // displayWidth
- // -----------------------------------------------------------------------
- describe("displayWidth", () => {
- test("CJK, emoji, combining marks and zero-width characters each measure the cells they occupy", () => {
- expect(displayWidth("日本語")).toBe(6);
- expect(displayWidth("😀")).toBe(2);
- expect(displayWidth("café")).toBe(4);
- // Spec (.pipeline/spec.md §4.4) expects 3 assuming ICU joins ನ್ನ
- // into one grapheme cluster; this runtime instead splits it as two
- // clusters (4 graphemes total) - an ICU segmentation detail, not a
- // wrong width range (verified with a standalone Intl.Segmenter probe).
- expect(displayWidth("ಕನ್ನಡ")).toBe(4);
- expect(displayWidth("🇮🇳")).toBe(1);
- expect(displayWidth("")).toBe(0);
- expect(displayWidth("️")).toBe(0);
- });
- const WIDE_SAMPLES = [
- "ಕನ್ನಡ",
- "日本語テキスト",
- "😀😀😀",
- "🇮🇳🇮🇳",
- "café café",
- ];
- test("truncate never returns more display cells than its budget", () => {
- for (const s of WIDE_SAMPLES) {
- for (let w = 1; w <= 12; w++) {
- expect(displayWidth(truncate(s, w))).toBeLessThanOrEqual(w);
- }
- }
- });
- test("a wide grapheme is never split in half", () => {
- const lone =
- /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/;
- for (const s of WIDE_SAMPLES) {
- for (let w = 1; w <= 12; w++) {
- expect(lone.test(truncate(s, w))).toBe(false);
- }
- }
- });
- });
- // -----------------------------------------------------------------------
- // layout
- // -----------------------------------------------------------------------
- describe("layout", () => {
- test("two columns at cols=100: header contains CONTACTS and GROUPS; granted row [x], ungranted [ ]", () => {
- const s = initPicker(
- model({ dms: [rohan, priya], groups: [family, wil] }),
- 100,
- 24,
- );
- const text = layout(s, 100, 24).join("\n");
- expect(text).toContain("CONTACTS");
- expect(text).toContain("GROUPS");
- expect(text).toContain("[x] Rohan");
- expect(text).toContain("[ ] Priya");
- });
- test("every line's stripAnsi width <= cols, and lines.length <= rows, at several sizes", () => {
- const s = initPicker(
- model({ dms: [rohan, priya], groups: [family, wil], color: true }),
- 100,
- 24,
- );
- for (const [cols, rows] of [
- [100, 24],
- [60, 24],
- [100, 10],
- [40, 8],
- ] as const) {
- const lines = layout(s, cols, rows);
- expect(lines.length).toBeLessThanOrEqual(rows);
- for (const l of lines)
- expect(stripAnsi(l).length).toBeLessThanOrEqual(cols);
- }
- });
- test("cols=60 stacks: CONTACTS and GROUPS on separate lines, one column wide", () => {
- const s = initPicker(
- model({ dms: [rohan, priya], groups: [family, wil] }),
- 60,
- 24,
- );
- const lines = layout(s, 60, 24);
- const contactsRow = lines.findIndex((l) => l.includes("CONTACTS"));
- const groupsRow = lines.findIndex(
- (l, i) => i > contactsRow && l.includes("GROUPS"),
- );
- expect(contactsRow).toBeGreaterThanOrEqual(0);
- expect(groupsRow).toBeGreaterThan(contactsRow);
- });
- test("a short terminal still emits the search, picked and footer lines", () => {
- const s = initPicker(
- model({ dms: [rohan, priya], groups: [family, wil] }),
- 40,
- 8,
- );
- const lines = layout(s, 40, 8);
- expect(lines.length).toBeLessThanOrEqual(8);
- expect(lines.some((l) => l.startsWith("Search:"))).toBe(true);
- expect(lines.some((l) => l.startsWith("Picked:"))).toBe(true);
- expect(lines.some((l) => l.includes("Submit"))).toBe(true);
- });
- test("a long label is truncated with an ellipsis; an emoji label is never cut mid-surrogate", () => {
- const long = item({ jid: "x@g.us", label: "A".repeat(200), kind: "group" });
- const emoji = item({
- jid: "y@s.whatsapp.net",
- label: "\u{1F600}".repeat(50),
- kind: "dm",
- });
- const s = initPicker(model({ dms: [emoji], groups: [long] }), 40, 24);
- const text = layout(s, 40, 24).join("\n");
- expect(text).toContain("…");
- const lone =
- /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/;
- expect(lone.test(text)).toBe(false);
- });
- test("a label containing ANSI, CR, LF and a bidi override reaches the frame with all of them gone", () => {
- const dirty = item({
- jid: "d@s.whatsapp.net",
- label: "a\x1b[31mb\rc\nde",
- 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
- });
- const s = initPicker(model({ dms: [dirty] }), 100, 24);
- const text = layout(s, 100, 24).join("\n");
- expect(text).not.toContain("\x1b[31m");
- expect(text).not.toContain("\r");
- expect(text).not.toContain("");
- expect(text).toContain("a[31mbcde");
- });
- test("an empty contacts column draws dmNote, wrapped to the column width", () => {
- const s = initPicker(
- model({
- dms: [],
- groups: [family],
- dmNote:
- "No contacts to review - set WHATSAPP_CACHE_CONTACTS=0 to opt out.",
- }),
- 100,
- 24,
- );
- const text = layout(s, 100, 24).join("\n");
- expect(text).toContain("WHATSAPP_CACHE_CONTACTS=0");
- });
- test("an empty column with no note draws dim '(none)'", () => {
- const s = initPicker(
- model({ dms: [], groups: [family], dmNote: "" }),
- 100,
- 24,
- );
- const text = layout(s, 100, 24).join("\n");
- expect(text).toContain("(none)");
- });
- test("chips: '+' for a new tick, '-' for a revoked grant, '×' present", () => {
- let s = initPicker(model({ dms: [rohan, priya] }), 100, 24);
- s = press(s, { type: "space" }); // untick rohan (granted) -> "-" chip
- s = press(s, { type: "down" }, { type: "space" }); // tick priya -> "+" chip
- const text = layout(s, 100, 24).join("\n");
- expect(text).toContain("[- Rohan ×]");
- expect(text).toContain("[+ Priya ×]");
- });
- test("chips overflow the picked line width and show a leading '+N more'", () => {
- const many = Array.from({ length: 20 }, (_, i) =>
- item({
- jid: `c${i}@s.whatsapp.net`,
- label: `Contact Number ${i}`,
- granted: false,
- }),
- );
- let s = initPicker(model({ dms: many }), 40, 24);
- for (let i = 0; i < many.length; i++) {
- s = press(s, { type: "space" });
- if (i < many.length - 1) s = press(s, { type: "down" });
- }
- const text = layout(s, 40, 24).join("\n");
- expect(text).toMatch(/\+\d+ more/);
- });
- test("every line fits the terminal even when one chip plus '+N more' would not", () => {
- const many = Array.from({ length: 24 }, (_, i) =>
- item({
- jid: `c${i}@s.whatsapp.net`,
- label: `Name number ${i} Longish`,
- granted: true,
- }),
- );
- // 30 columns is the floor: below it the fixed prompt text itself no
- // longer fits, and no real terminal is that narrow.
- for (const [cols, rows] of [
- [40, 24],
- [30, 5],
- [100, 2],
- ]) {
- const lines = layout(
- initPicker(model({ dms: many }), cols, rows),
- cols,
- rows,
- );
- expect(lines.length).toBeLessThanOrEqual(rows);
- for (const l of lines) {
- expect(displayWidth(stripAnsi(l))).toBeLessThanOrEqual(cols);
- }
- }
- });
- test("Restore is dim / not clickable when hasBackup:false", () => {
- const s = initPicker(model({ hasBackup: false }), 100, 24);
- const lines = layout(s, 100, 24);
- const row = lines.findIndex((l) => l.includes("Submit"));
- const plain = stripAnsi(lines[row]);
- const col = plain.indexOf("Restore");
- expect(hitTest(s, 100, 24, row, col)).toBeNull();
- });
- test("a column with more items than fit ends with '… +N more'", () => {
- const many = Array.from({ length: 30 }, (_, i) =>
- item({ jid: `g${i}@g.us`, label: `Group ${i}`, kind: "group" }),
- );
- const s = initPicker(model({ groups: many }), 100, 10);
- const text = layout(s, 100, 10).join("\n");
- expect(text).toMatch(/… \+\d+ more/);
- });
- });
- // -----------------------------------------------------------------------
- // adversarial - a large model, every documented terminal size
- // -----------------------------------------------------------------------
- describe("layout - adversarial large model", () => {
- function bigModel(): PickerModel {
- const groups = Array.from({ length: 200 }, (_, i) =>
- item({
- jid: `g${i}12345678@g.us`,
- label: `Group ${i}`,
- kind: "group",
- granted: i % 3 === 0,
- }),
- );
- const dms = Array.from({ length: 100 }, (_, i) => {
- const num = `9198765${String(i).padStart(4, "0")}`; // 11 raw digits
- return item({
- jid: `${num}@s.whatsapp.net`,
- label: `•••••${String(i).padStart(4, "0")}`, // masked, no saved name
- kind: "dm",
- granted: i % 5 === 0,
- });
- });
- return model({ dms, groups });
- }
- test("every layout line stays within cols and rows for a 200-group/100-contact model", () => {
- const s = initPicker(bigModel(), 80, 24);
- for (const cols of [40, 70, 80, 120]) {
- for (const rows of [10, 24, 50]) {
- const lines = layout(s, cols, rows);
- expect(lines.length).toBeLessThanOrEqual(rows);
- for (const l of lines) {
- expect(stripAnsi(l).length).toBeLessThanOrEqual(cols);
- }
- }
- }
- });
- test("a one-row column still draws its focused item instead of only a more-line (review finding 11)", () => {
- const s = initPicker(bigModel(), 80, 24);
- for (const [cols, rows] of [
- [60, 11],
- [60, 12],
- [100, 7],
- [100, 8],
- ]) {
- const lines = layout(s, cols, rows);
- expect(lines.length).toBeLessThanOrEqual(rows);
- const text = lines.map(stripAnsi).join("\n");
- expect(text).toContain(">[");
- expect(text).toContain("Group 0");
- }
- });
- test("no drawn line leaks a JID suffix or an unmasked 8+ digit run, contacts with no saved name", () => {
- let s = initPicker(bigModel(), 80, 24);
- // Tick a few rows so chips (which also render labels) are exercised too.
- s = press(s, { type: "space" }, { type: "down" }, { type: "space" });
- const digitRun = /\d{8,}/;
- for (const cols of [40, 70, 80, 120]) {
- for (const rows of [10, 24, 50]) {
- const text = layout(s, cols, rows).join("\n");
- expect(text).not.toContain("@g.us");
- expect(text).not.toContain("@s.whatsapp.net");
- expect(text).not.toContain("@lid");
- expect(digitRun.test(text)).toBe(false);
- }
- }
- });
- // Review finding 1: the window offset was derived from bodyRows, but only
- // bodyRows-1 rows are actually drawn once a trailing "... +N more" line is
- // needed, so the cursor sat one row below the last drawn row for almost
- // the whole scroll range - Space would then toggle an access grant the
- // operator cannot see. 200 groups at 100x24 (bodyRows 18) overflows almost
- // immediately; 25 Downs lands deep in that range.
- test("the cursor marker stays inside the drawn window once a column overflows", () => {
- let s = initPicker(bigModel(), 100, 24);
- s = press(s, { type: "tab" }); // groups column, right-hand side of the line
- for (let i = 0; i < 25; i++) s = press(s, { type: "down" });
- expect(s.cursor.groups).toBe(25);
- const focusedLabel = visibleItems(s, "groups")[25].label;
- const text = layout(s, 100, 24).join("\n");
- // Marker is glued directly to the box (">[x]"/">[ ]"), not the row start
- // - the groups column sits to the right of the padded dms column, so a
- // per-line "starts with >" check would miss it entirely.
- const markers = text.match(/>\[[x ]\]/g) ?? [];
- expect(markers).toHaveLength(1);
- const idx = text.indexOf(markers[0]!);
- expect(text.slice(idx, idx + 60)).toContain(focusedLabel);
- });
- function wideModel(): PickerModel {
- const scripts = [`ಕನ್ನಡ`, `日本語`, `😀`, `🇮🇳`, `Café`];
- const dms = Array.from({ length: 40 }, (_, i) =>
- item({
- jid: `d${i}@s.whatsapp.net`,
- label: `${scripts[i % scripts.length]} ${i}`,
- kind: "dm",
- granted: i % 4 === 0,
- }),
- );
- const groups = Array.from({ length: 40 }, (_, i) =>
- item({
- jid: `w${i}@g.us`,
- label: `${scripts[(i + 1) % scripts.length]} Group ${i}`,
- kind: "group",
- granted: i % 4 === 0,
- }),
- );
- return model({ dms, groups });
- }
- test("every layout line's DISPLAY width stays within cols for a wide-script model", () => {
- const s = initPicker(wideModel(), 80, 24);
- for (const cols of [40, 70, 80, 120]) {
- for (const rows of [10, 24, 50]) {
- const lines = layout(s, cols, rows);
- expect(lines.length).toBeLessThanOrEqual(rows);
- for (const l of lines) {
- expect(displayWidth(stripAnsi(l))).toBeLessThanOrEqual(cols);
- }
- }
- }
- });
- });
- // -----------------------------------------------------------------------
- // hitTest / click
- // -----------------------------------------------------------------------
- describe("hitTest / click", () => {
- test("a click on a contacts row toggles it and moves focus + cursor there", () => {
- let s = initPicker(
- model({ dms: [rohan, priya], groups: [family] }),
- 100,
- 24,
- );
- const lines = layout(s, 100, 24);
- const row = lines.findIndex((l) => l.includes("Priya"));
- const ev = hitTest(s, 100, 24, row, 5);
- expect(ev).toEqual({ type: "focus", column: "dms", index: 1 });
- s = reducePicker(s, { type: "click", row, col: 5 });
- expect(s.focus).toBe("dms");
- expect(s.cursor.dms).toBe(1);
- expect(s.ticked.has(priya.jid)).toBe(true);
- });
- test("a click on a chip's '×' removes that chip (same result as backspace-on-empty)", () => {
- let s = initPicker(model({ dms: [rohan] }), 100, 24);
- s = press(s, { type: "space" }); // untick -> struck chip
- const lines = layout(s, 100, 24);
- const row = lines.findIndex((l) => l.startsWith("Picked:"));
- const plain = stripAnsi(lines[row]);
- const col = plain.indexOf("×");
- const ev = hitTest(s, 100, 24, row, col);
- expect(ev).toEqual({ type: "unchip", jid: rohan.jid });
- s = reducePicker(s, { type: "click", row, col });
- expect(s.chips).toEqual([]);
- expect(s.ticked.has(rohan.jid)).toBe(true);
- });
- test("clicks on Submit/Undo/Restore dispatch those actions; a click on blank space is a no-op", () => {
- const s = initPicker(model({ hasBackup: true }), 100, 24);
- const lines = layout(s, 100, 24);
- const row = lines.findIndex((l) => l.includes("Submit"));
- const plain = stripAnsi(lines[row]);
- expect(hitTest(s, 100, 24, row, plain.indexOf("Submit"))).toEqual({
- type: "submit",
- });
- expect(hitTest(s, 100, 24, row, plain.indexOf("Undo"))).toEqual({
- type: "undo",
- });
- expect(hitTest(s, 100, 24, row, plain.indexOf("Restore"))).toEqual({
- type: "restore",
- });
- // Row 0 is now the focusable search line (hits focusSearch, not null) -
- // probe blank space past the last footer part instead.
- expect(hitTest(s, 100, 24, row, 70)).toBeNull();
- });
- test("after a resize event the same screen coordinates hit the new geometry", () => {
- let s = initPicker(model({ dms: [rohan, priya] }), 100, 24);
- s = reducePicker(s, { type: "resize", cols: 60, rows: 24 });
- const lines = layout(s, 60, 24);
- const row = lines.findIndex((l) => l.includes("Priya"));
- const ev = hitTest(s, 60, 24, row, 5);
- expect(ev).toEqual({ type: "focus", column: "dms", index: 1 });
- });
- // Review finding 2: both columns share every body row in the two-column
- // form, and itemRows used to be matched on row alone - a click anywhere on
- // a row, including deep inside the right-hand GROUPS column, resolved to
- // the LEFT (dms) item on that same line. col 55 at cols=100 is inside the
- // GROUPS column (rightX = leftW + 2 = 51).
- test("a click in the GROUPS column focuses the group, not the dm on the same row", () => {
- let s = initPicker(model({ dms: [rohan], groups: [family] }), 100, 24);
- const lines = layout(s, 100, 24);
- const row = lines.findIndex((l) => l.includes("Family"));
- const ev = hitTest(s, 100, 24, row, 55);
- expect(ev).toEqual({ type: "focus", column: "groups", index: 0 });
- s = reducePicker(s, { type: "click", row, col: 55 });
- expect(s.focus).toBe("groups");
- expect(s.ticked.has(family.jid)).toBe(false); // family was granted -> untoggled
- expect(s.ticked.has(rohan.jid)).toBe(true); // dm row on the same line untouched
- });
- test("a click on a row draws the '>' marker on that row in the next frame", () => {
- // Contacts row.
- let s = initPicker(
- model({ dms: [rohan, priya], groups: [family] }),
- 100,
- 24,
- );
- let lines = layout(s, 100, 24);
- let row = lines.findIndex((l) => l.includes("Priya"));
- let next = reducePicker(s, { type: "click", row, col: 5 });
- let frameLine = stripAnsi(layout(next, 100, 24)[row]);
- expect(frameLine).toContain(">[");
- expect(frameLine.indexOf(">[")).toBeLessThan(frameLine.indexOf("Priya"));
- // Groups row (right-hand column at cols=100, rightX=51).
- s = initPicker(model({ dms: [rohan], groups: [family, wil] }), 100, 24);
- lines = layout(s, 100, 24);
- row = lines.findIndex((l) => l.includes("WIL Group HUDINI"));
- next = reducePicker(s, { type: "click", row, col: 55 });
- frameLine = stripAnsi(layout(next, 100, 24)[row]);
- const markerIdx = frameLine.indexOf(">[");
- expect(markerIdx).toBeGreaterThanOrEqual(51); // right half of the line
- expect(frameLine.slice(markerIdx)).toContain("WIL Group HUDINI");
- });
- test("a click on the search line focuses it and ticks nothing", () => {
- const s = initPicker(model({ dms: [rohan] }), 100, 24);
- expect(hitTest(s, 100, 24, 0, 3)).toEqual({ type: "focusSearch" });
- const next = reducePicker(s, { type: "click", row: 0, col: 3 });
- expect(next.focus).toBe("search");
- expect(next.ticked).toEqual(s.ticked);
- });
- });
- // -----------------------------------------------------------------------
- // footer
- // -----------------------------------------------------------------------
- describe("footer", () => {
- test("the footer reads Submit: enter / Undo: ctrl-z / Restore: ctrl-r / Quit: esc", () => {
- const s = initPicker(model({ hasBackup: true }), 100, 24);
- const lines = layout(s, 100, 24);
- const footerLine = lines.find((l) => l.includes("Submit"))!;
- expect(footerLine).toBe(
- "Submit: enter Undo: ctrl-z Restore: ctrl-r Quit: esc",
- );
- });
- test("verbs are bold+accent and keys dim when colour is on", () => {
- const s = initPicker(model({ hasBackup: true, color: true }), 100, 24);
- const lines = layout(s, 100, 24);
- const footerLine = lines.find((l) => l.includes("Submit"))!;
- expect(footerLine).toContain(
- "\x1b[1;32mSubmit\x1b[0m: \x1b[2menter\x1b[0m",
- );
- });
- test("the short footer is used when the full one does not fit", () => {
- const s = initPicker(model({ hasBackup: true }), 40, 24);
- const lines = layout(s, 40, 24);
- const row = lines.findIndex((l) => l.includes("Submit"));
- const footerLine = stripAnsi(lines[row]);
- expect(footerLine).toBe("Submit Undo Restore Quit");
- const restoreCol = footerLine.indexOf("Restore");
- expect(hitTest(s, 40, 24, row, restoreCol)).toEqual({ type: "restore" });
- });
- });
- // -----------------------------------------------------------------------
- // applySelection
- // -----------------------------------------------------------------------
- describe("applySelection", () => {
- function base(): {
- allowFrom: string[];
- groups: Record<
- string,
- { requireMention: boolean; allowFrom: string[]; roster?: boolean }
- >;
- } {
- return {
- allowFrom: ["kept@s.whatsapp.net", "revoke-me@s.whatsapp.net"],
- groups: {
- "kept@g.us": {
- requireMention: false,
- allowFrom: ["x@s"],
- roster: true,
- },
- "revoke@g.us": { requireMention: true, allowFrom: [], roster: false },
- },
- };
- }
- test("rule 1: a group shown but not selected is deleted", () => {
- const b = base();
- const out = applySelection(
- b,
- { groups: new Set(["kept@g.us"]), dms: new Set(), roster: new Set() },
- { groups: new Set(["kept@g.us", "revoke@g.us"]), dms: new Set() },
- );
- expect(out.groups["revoke@g.us"]).toBeUndefined();
- expect(out.groups["kept@g.us"]).toBeDefined();
- });
- test("rule 2: a group already configured survives byte-identical, roster included", () => {
- const b = base();
- const out = applySelection(
- b,
- {
- groups: new Set(["kept@g.us"]),
- dms: new Set(),
- roster: new Set(["kept@g.us"]),
- },
- { groups: new Set(["kept@g.us"]), dms: new Set() },
- );
- expect(out.groups["kept@g.us"]).toEqual(b.groups["kept@g.us"]);
- });
- test("rule 3: a new group gets requireMention:true, empty allowFrom, roster from the selection", () => {
- const b = base();
- const out = applySelection(
- b,
- {
- groups: new Set(["new@g.us"]),
- dms: new Set(),
- roster: new Set(["new@g.us"]),
- },
- { groups: new Set(), dms: new Set() },
- );
- expect(out.groups["new@g.us"]).toEqual({
- requireMention: true,
- allowFrom: [],
- roster: true,
- });
- });
- test("rule 4: allowFrom drops only a shown+unticked dm; an entry the server added while shown never listed it is kept", () => {
- const b = {
- allowFrom: [
- "kept@s.whatsapp.net",
- "revoke-me@s.whatsapp.net",
- "added-by-server@s.whatsapp.net",
- ],
- groups: {},
- };
- const out = applySelection(
- b,
- {
- groups: new Set(),
- dms: new Set(["kept@s.whatsapp.net"]),
- roster: new Set(),
- },
- {
- groups: new Set(),
- dms: new Set(["kept@s.whatsapp.net", "revoke-me@s.whatsapp.net"]),
- },
- );
- expect([...out.allowFrom].sort()).toEqual(
- ["added-by-server@s.whatsapp.net", "kept@s.whatsapp.net"].sort(),
- );
- });
- test("rule 5: base is never mutated", () => {
- const b = base();
- const before = JSON.stringify(b);
- applySelection(
- b,
- { groups: new Set(), dms: new Set(), roster: new Set() },
- { groups: new Set(["kept@g.us", "revoke@g.us"]), dms: new Set() },
- );
- expect(JSON.stringify(b)).toBe(before);
- });
- });
- // -----------------------------------------------------------------------
- // e2e - drives runPicker over a fake, paced stdin. Interactive/timing
- // sensitive: skipped only under CI, never removed (brief stop condition).
- // -----------------------------------------------------------------------
- describe("runPicker e2e", () => {
- test.skipIf(!!process.env.CI)(
- "search + Enter + Enter submits with the highlighted group ticked",
- async () => {
- const input = new PassThrough();
- const output = new PassThrough();
- let written = "";
- output.on("data", (d) => (written += d.toString()));
- (input as unknown as { setRawMode: () => void }).setRawMode = () => {
- throw new Error("setRawMode must not be called on a non-TTY stream");
- };
- const familyItem = item({
- jid: "fam@g.us",
- label: "Family",
- kind: "group",
- });
- const resultPromise = runPicker(model({ groups: [familyItem] }), {
- input: input as unknown as NodeJS.ReadStream,
- output: output as unknown as NodeJS.WriteStream,
- });
- const type = async (s: string) => {
- await new Promise((r) => setTimeout(r, 50));
- input.write(s);
- };
- await type("\t"); // focus groups (dms column is empty)
- await type("f");
- await type("a");
- await type("m");
- await type("\r"); // tick highlighted, clear search
- await type("\r"); // submit
- const result = await resultPromise;
- expect(result).toEqual({
- action: "submit",
- groups: new Set(["fam@g.us"]),
- dms: new Set(),
- roster: new Set(),
- });
- expect(written).toContain("\x1b[?1000h");
- expect(written).toContain("\x1b[?1006h");
- expect(written).toContain("\x1b[?1006l\x1b[?1000l");
- expect(written).toContain("\x1b[?1049l");
- },
- { timeout: 5000 },
- );
- test.skipIf(!!process.env.CI)(
- "Ctrl-C resolves null, and the teardown sequence was still written",
- async () => {
- const input = new PassThrough();
- const output = new PassThrough();
- let written = "";
- output.on("data", (d) => (written += d.toString()));
- const resultPromise = runPicker(model({ dms: [rohan] }), {
- input: input as unknown as NodeJS.ReadStream,
- output: output as unknown as NodeJS.WriteStream,
- });
- await new Promise((r) => setTimeout(r, 50));
- input.write("\x03");
- const result = await resultPromise;
- expect(result).toBeNull();
- expect(written).toContain("\x1b[?1049l");
- },
- { timeout: 5000 },
- );
- });
Ratings and comments
Sign in to rate this skill.
Sign inFree to use. If it’s helped, pass it on.