fix(whatsapp): make linking reliable and the connect flow clear (#1802)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Johan CutychandClaude Opus 5.5 authored and GitHub committed 2026-12-02 19:47:15 +01:00
1 parent 043146f52f
commit 7539e18342
12 files changed
+1035 -196

No files matched your search

+10 -6
View File
@@ -68,13 +68,13 @@ This setup works without a public callback URL. If your bot already uses a webho
<Steps>
1. Read the account risk and terms. Select **Show QR code**.
2. On the phone whose WhatsApp Nod will use, open **Settings → Linked Devices → Link a Device**. Scan the code in Nod. A code expires after one minute. The setup expires after five minutes.
3. On that phone, open **Message yourself** and write to Nod there.
1. Read how the link works, accept the account risk and terms, and select **Show QR code**.
2. On the phone whose WhatsApp Nod will use, open **Linked devices** (iPhone: **Settings → Linked Devices**; Android: the three-dot menu → **Linked devices**). Tap **Link a device** and scan the code in Nod with WhatsApp. A code expires after one minute. The setup expires after five minutes. WhatsApp may ask you to confirm on the phone and scan again; Nod then shows a new code and says **Scan this new code**. The panel turns green when WhatsApp accepts the link.
3. Scan the next code with your phone camera, not with WhatsApp. It opens **Message yourself**, the chat with your own number. Send Nod a message there. The panel turns green when Nod receives it. You can also open the chat on your computer from the panel.
</Steps>
To keep your own chats apart, link a second number, such as one registered in the WhatsApp Business app. Then select **Write from another phone** in Nod, scan the code with your personal phone, and send the message that opens. The code works for 15 minutes. After that, your personal phone can message the linked number too.
WhatsApp doesn't notify you about messages in **Message yourself**, so Nod's replies there arrive silently. For notifications, link a second number instead, such as one registered in the WhatsApp Business app. In step 3, the panel shows **Nod's number**. If that isn't your own number, select **Pair your phone**, scan the new code with your personal phone's camera, and send the message that opens. The code works for 15 minutes. The panel turns green when your phone is paired, and Nod then replies from the second number. Later, **Write from another phone** pairs another phone the same way.
Nod ignores groups, status updates, other chats and message history. In **Message yourself**, Nod ignores its own replies. Nod remembers a phone you link with a code by the address WhatsApp uses for it, even when WhatsApp hides the number behind a private ID. Your other chats stay outside the Nod conversation.
@@ -147,7 +147,11 @@ For a short reply with one image, video or document, the reply text is its capti
Nod saves the WhatsApp device keys encrypted in its database. The keys stay on the server. They do not enter the model, sandbox, analytics or chat. The QR code is available only in the private setup panel and is not saved in channel settings.
After a restart or network loss, Nod uses the saved link to connect again. The link stays saved however long WhatsApp can't be reached; only a sign-out from your phone, **Disconnect** or **Start again** removes it. Replies that have not started sending wait while WhatsApp is disconnected. A send with an unclear result is not repeated automatically. This prevents duplicate messages; check Nod if a reply does not arrive.
After a restart or network loss, Nod uses the saved link to connect again. The link stays saved however long WhatsApp can't be reached; only a sign-out from your phone, **Disconnect** or **Start again** removes it. Replies that have not started sending wait while WhatsApp is disconnected. A send with an unclear result is not repeated automatically. This prevents duplicate messages; check Nod if a reply does not arrive. When a phone can't read a message from Nod, or Nod can't read one from you, WhatsApp asks for the same message again; this never creates a second message.
Nod checks WhatsApp's current web version each time it connects. If WhatsApp turns down Nod's version (error 405) three times in a row, Nod stops trying and shows **Connection failed**: update Nod, then select **Reconnect**. If Nod couldn't reach `web.whatsapp.com` to check the version, the message says so; check the internet connection or firewall. The saved link stays.
Nod tells WhatsApp it's idle after each reply and when it connects, so it doesn't keep your account marked as online.
Each connected channel shows when your last message from it reached Nod, or that none has yet. If you write and that line doesn't change, Nod isn't receiving your messages: check that you write from the linked account or chat. Nod can read the same line when you ask whether a chat app works.
@@ -192,7 +196,7 @@ When Nod needs you to sign in to a website or enter a code, because no saved log
While Nod works on something you asked for in this chat, including a task it started for you, you see **typing…**.
- **Telegram** adds a quoted progress section when a task's first message or chat's opening message arrives as one short text message. Named steps use your conversation language. Without a named step, a running labeled tool appears as **Using Gmail**, **Using Slack**, or **Using local files**. The same fallback applies to other apps, websites, and MCP servers. Known tools without a label, such as code and commands, appear by their kind of work, such as **Running code**. A web search appears as **Searching** and its first query, or **Searching the web** without one, and a page read as **Reading** and its site. These fallbacks, and the note shown while Nod retries a failed model request, are in English. The section updates quietly in place and disappears when work stops. The answer arrives separately. You can keep typing and sending messages, or reply to the first message to correct the task. Long or split messages, attachments, visual cards, files and private sign-in or payment links keep typing status only.
- **WhatsApp** shows **typing…** while connected. The Meta Cloud API also marks your latest message as read and stops typing after its 24-hour reply window closes. The QR connection has no reply window.
- **WhatsApp** shows **typing…** while connected, except in **Message yourself**, where WhatsApp doesn't show it. The Meta Cloud API also marks your latest message as read and stops typing after its 24-hour reply window closes. The QR connection has no reply window.
- **A message you send while Nod works** gets a 👀 reaction in both apps until Nod reads it, so you know it's queued. Nod leaves its own reaction to that message alone.
Typing stays on through slow steps without extra messages. Work Nod starts on its own, such as a reply your notification rule asks for, shows no typing.
+1 -1
View File
@@ -54,7 +54,7 @@
"@pedrobef/vozz": "0.3.0",
"@sinclair/typebox": "^0.34.41",
"@spelling-creator/spellophone": "0.2.1",
"@whiskeysockets/baileys": "7.0.0-rc14",
"@whiskeysockets/baileys": "7.0.0",
"agent-browser": "0.43.0",
"chat": "^4.45.0",
"dotenv": "^18.0.10",
@@ -1,12 +0,0 @@
diff --git a/lib/Utils/messages-media.js b/lib/Utils/messages-media.js
index 762c204..0878a93 100644
--- a/lib/Utils/messages-media.js
+++ b/lib/Utils/messages-media.js
@@ -298,5 +298,7 @@ export const getHttpStream = async (url, options = {}) => {
const response = await fetch(url.toString(), {
dispatcher: options.dispatcher,
+ signal: options.signal,
+ redirect: options.redirect,
method: 'GET',
headers: options.headers
});
@@ -0,0 +1,145 @@
diff --git a/lib/Socket/messages-recv.js b/lib/Socket/messages-recv.js
index f2003ac00ef223468c432a1bbe0a0eb02c1453b2..338734063a73d9b04fed8ac9ed8a7f99465c4cb8 100644
--- a/lib/Socket/messages-recv.js
+++ b/lib/Socket/messages-recv.js
@@ -359,7 +359,11 @@ export const makeMessagesRecvSocket = (config) => {
}
};
const sendMessageAck = async (node, errorCode) => {
- const stanza = buildAckStanza(node, errorCode, authState.creds.me.id);
+ const meId = authState.creds.me?.id;
+ if (node.tag === 'message' && !meId) {
+ throw new Boom('cannot ack a message before creds.me is set');
+ }
+ const stanza = buildAckStanza(node, errorCode, meId);
logger.debug({ recv: { tag: node.tag, attrs: node.attrs }, sent: stanza.attrs }, 'sent ack');
await sendNode(stanza);
};
diff --git a/lib/Socket/socket.js b/lib/Socket/socket.js
index ae34a8f315a0b9fd101472cc69e59624c6c63861..aef6d6aa0ca20763c314770da40b4bdd540a12c7 100644
--- a/lib/Socket/socket.js
+++ b/lib/Socket/socket.js
@@ -6,7 +6,7 @@ import { proto } from '../../WAProto/index.js';
import { DEF_CALLBACK_PREFIX, DEF_TAG_PREFIX, INITIAL_PREKEY_COUNT, MIN_PREKEY_COUNT, NOISE_WA_HEADER, PROCESSABLE_HISTORY_TYPES, TimeMs, UPLOAD_TIMEOUT } from '../Defaults/index.js';
import { QueryIds, ReachoutTimelockEnforcementType } from '../Types/index.js';
import { DisconnectReason, XWAPaths } from '../Types/index.js';
-import { addTransactionCapability, aesEncryptCTR, bindWaitForConnectionUpdate, buildPairingQRData, bytesToCrockford, configureSuccessfulPairing, Curve, derivePairingCodeKey, generateLoginNode, generateMdTagPrefix, generateRegistrationNode, getCodeFromWSError, getCompanionPlatformId, getErrorCodeFromStreamError, getNextPreKeysNode, makeEventBuffer, makeNoiseHandler, promiseTimeout, signedKeyPair, xmppSignedPreKey } from '../Utils/index.js';
+import { addTransactionCapability, aesEncryptCTR, bindWaitForConnectionUpdate, buildPairingQRData, bytesToCrockford, configureSuccessfulPairing, Curve, derivePairingCodeKey, generateLoginNode, generateMdTagPrefix, generateRegistrationNode, getCodeFromWSError, getCompanionPlatformId, getErrorCodeFromStreamError, getNextPreKeysNode, handleCompanionRegRefresh, makeEventBuffer, makeNoiseHandler, makePairingQRRenderer, promiseTimeout, signedKeyPair, xmppSignedPreKey } from '../Utils/index.js';
import { assertNodeErrorFree, binaryNodeToString, encodeBinaryNode, getAllBinaryNodeChildren, getBinaryNodeChild, getBinaryNodeChildren, isLidUser, jidDecode, jidEncode, S_WHATSAPP_NET } from '../WABinary/index.js';
import { BinaryInfo } from '../WAM/BinaryInfo.js';
import { USyncQuery, USyncUser } from '../WAUSync/index.js';
@@ -691,6 +691,7 @@ export const makeSocket = (config) => {
// the server terminated the connection
ws.on('CB:xmlstreamend', () => void end(new Boom('Connection Terminated by Server', { statusCode: DisconnectReason.connectionClosed })));
// QR gen
+ let refreshPairingQR;
ws.on('CB:iq,type:set,pair-device', async (stanza) => {
const iq = {
tag: 'iq',
@@ -705,25 +706,32 @@ export const makeSocket = (config) => {
const refNodes = getBinaryNodeChildren(pairDeviceNode, 'ref');
const noiseKeyB64 = Buffer.from(creds.noiseKey.public).toString('base64');
const identityKeyB64 = Buffer.from(creds.signedIdentityKey.public).toString('base64');
- const advB64 = creds.advSecretKey;
+ const renderer = makePairingQRRenderer(refNodes.map(refNode => refNode.content.toString('utf-8')), ref => ev.emit('connection.update', {
+ qr: buildPairingQRData(ref, noiseKeyB64, identityKeyB64, creds.advSecretKey, browser)
+ }));
+ refreshPairingQR = () => void renderer.refresh();
let qrMs = qrTimeout || 60000; // time to let a QR live
const genPairQR = () => {
if (!ws.isOpen) {
return;
}
- const refNode = refNodes.shift();
- if (!refNode) {
+ if (!renderer.next()) {
void end(new Boom('QR refs attempts ended', { statusCode: DisconnectReason.timedOut }));
return;
}
- const ref = refNode.content.toString('utf-8');
- const qr = buildPairingQRData(ref, noiseKeyB64, identityKeyB64, advB64, browser);
- ev.emit('connection.update', { qr });
qrTimer = setTimeout(genPairQR, qrMs);
qrMs = qrTimeout || 20000; // shorter subsequent qrs
};
genPairQR();
});
+ ws.on('CB:notification,type:companion_reg_refresh', (node) => {
+ handleCompanionRegRefresh(node, {
+ creds,
+ emitCredsUpdate: update => ev.emit('creds.update', update),
+ refreshQR: () => refreshPairingQR?.(),
+ logger
+ });
+ });
// device paired for the first time
// if device pairs successfully, the server asks to restart the connection
ws.on('CB:iq,,pair-success', async (stanza) => {
diff --git a/lib/Utils/companion-reg-client-utils.js b/lib/Utils/companion-reg-client-utils.js
index f5edebd725cec9a7b62aa5b768826e53bacc810a..9efdd5ef26293fa732dd33926442187f37a0234f 100644
--- a/lib/Utils/companion-reg-client-utils.js
+++ b/lib/Utils/companion-reg-client-utils.js
@@ -1,3 +1,5 @@
+import { randomBytes } from 'crypto';
+import { getBinaryNodeChild } from '../WABinary/index.js';
export var CompanionWebClientType;
(function (CompanionWebClientType) {
CompanionWebClientType[CompanionWebClientType["UNKNOWN"] = 0] = "UNKNOWN";
@@ -32,4 +34,43 @@ export const buildPairingQRData = (ref, noiseKeyB64, identityKeyB64, advB64, bro
return ('https://wa.me/settings/linked_devices#' +
[ref, noiseKeyB64, identityKeyB64, advB64, getCompanionPlatformId(browser)].join(','));
};
+export const makePairingQRRenderer = (refs, render) => {
+ let index = 0;
+ let current;
+ return {
+ next() {
+ const ref = refs[index];
+ if (ref === undefined) {
+ return false;
+ }
+ index += 1;
+ current = ref;
+ render(ref);
+ return true;
+ },
+ refresh() {
+ if (current === undefined) {
+ return false;
+ }
+ render(current);
+ return true;
+ }
+ };
+};
+const COMPANION_REG_REFRESH_CHILDREN = ['companion_reg_refresh', 'pair-device-rotate-qr'];
+export const handleCompanionRegRefresh = (node, { creds, emitCredsUpdate, refreshQR, logger }) => {
+ if (!COMPANION_REG_REFRESH_CHILDREN.some(tag => getBinaryNodeChild(node, tag))) {
+ logger.warn({ node }, 'companion_reg_refresh carries neither expected child; ignoring');
+ return 'ignored_malformed';
+ }
+ if (creds.me) {
+ logger.debug({ id: node.attrs.id }, 'companion_reg_refresh on a registered session; keeping the adv secret');
+ return 'ignored_registered';
+ }
+ creds.advSecretKey = randomBytes(32).toString('base64');
+ emitCredsUpdate({ advSecretKey: creds.advSecretKey });
+ logger.info({ id: node.attrs.id }, 'rotated the adv secret the server asked to retire; re-rendering the pairing QR');
+ refreshQR();
+ return 'rotated';
+};
//# sourceMappingURL=companion-reg-client-utils.js.map
\ No newline at end of file
diff --git a/lib/Utils/messages-media.js b/lib/Utils/messages-media.js
index c4b59e9b25be6e2bb1251a21c273da462cd960c7..47dad254d2ade97aafc44fb61dc009353e0fb623 100644
--- a/lib/Utils/messages-media.js
+++ b/lib/Utils/messages-media.js
@@ -297,6 +297,8 @@ export async function generateThumbnail(file, mediaType, options) {
export const getHttpStream = async (url, options = {}) => {
const response = await fetch(url.toString(), {
dispatcher: options.dispatcher,
+ signal: options.signal,
+ redirect: options.redirect,
method: 'GET',
headers: options.headers
});
+9 -9
View File
@@ -32,9 +32,9 @@ patchedDependencies:
'@earendil-works/pi-coding-agent@1.7.0':
hash: 5919936c043593969893cf5d65cfdb4ee43c5653ea3b3e1eaaa2bb99ebe28406
path: patches/@earendil-works__pi-coding-agent@1.7.0.patch
'@whiskeysockets/baileys@7.0.0-rc14':
hash: 4b39b1d960dd03c09cc725741416fca69f6b7fefefedd5cbe55c31dee50a78aa
path: patches/@whiskeysockets__baileys@7.0.0-rc14.patch
'@whiskeysockets/baileys@7.0.0':
hash: cb1839e7bac5c2ef2628bf4047f4cdb60196ea8c58b66eaf9b30f1adaccf0b50
path: patches/@whiskeysockets__baileys@7.0.0.patch
libsignal@6.0.0:
hash: c85a97bad5f112bb1fb62d6824af84561f086399ac2934b1e450eaad8a535447
path: patches/libsignal@6.0.0.patch
@@ -107,8 +107,8 @@ importers:
specifier: 0.2.1
version: 0.2.1
'@whiskeysockets/baileys':
specifier: 7.0.0-rc14
version: 7.0.0-rc14(patch_hash=4b39b1d960dd03c09cc725741416fca69f6b7fefefedd5cbe55c31dee50a78aa)(sharp@0.35.5(@types/node@24.19.2))
specifier: 7.0.0
version: 7.0.0(patch_hash=cb1839e7bac5c2ef2628bf4047f4cdb60196ea8c58b66eaf9b30f1adaccf0b50)(sharp@0.35.5(@types/node@24.19.2))
agent-browser:
specifier: 0.43.0
version: 0.43.0
@@ -2223,8 +2223,8 @@ packages:
'@wasm-audio-decoders/ogg-vorbis@0.1.20':
resolution: {integrity: sha512-zaQPasU5usRjUDXtXOHYED5tfkR4QMXd+EH3Nrz1+4+M5pCsdD+s9YxJqb0oqnTyRu/KUujOmu5Z/m/NT47vwg==}
'@whiskeysockets/baileys@7.0.0-rc14':
resolution: {integrity: sha512-WK+X8ju8TPGxvWIsP8hrY6JB6FltYuFe+vsqKfjOYX25JObij9qLf2c3ZGdl1Q+vhFwbnT+AZmWAB5pTvzmSiQ==}
'@whiskeysockets/baileys@7.0.0':
resolution: {integrity: sha512-Qk/xNFqThnHhoaJamfIfz68GGDs2xcO34fC6U/+puLR7z+3xQCOBVOI0SPQ+Kck2ulLO2kMyS3Z4ksilss2D0Q==}
engines: {node: '>=20.0.0'}
peerDependencies:
audio-decode: ^2.1.3
@@ -6741,7 +6741,7 @@ snapshots:
'@wasm-audio-decoders/common': 9.0.7
codec-parser: 2.5.0
'@whiskeysockets/baileys@7.0.0-rc14(patch_hash=4b39b1d960dd03c09cc725741416fca69f6b7fefefedd5cbe55c31dee50a78aa)(sharp@0.35.5(@types/node@24.19.2))':
'@whiskeysockets/baileys@7.0.0(patch_hash=cb1839e7bac5c2ef2628bf4047f4cdb60196ea8c58b66eaf9b30f1adaccf0b50)(sharp@0.35.5(@types/node@24.19.2))':
dependencies:
'@cacheable/node-cache': 1.7.6
'@hapi/boom': 9.1.4
@@ -6830,7 +6830,7 @@ snapshots:
async-mutex@0.5.0:
dependencies:
tslib: 2.8.1
tslib: 2.9.1
atomic-sleep@1.0.0: {}
+1 -1
View File
@@ -32,5 +32,5 @@ allowBuilds:
patchedDependencies:
'@earendil-works/pi-ai@1.7.0': patches/@earendil-works__pi-ai@1.7.0.patch
'@earendil-works/pi-coding-agent@1.7.0': patches/@earendil-works__pi-coding-agent@1.7.0.patch
'@whiskeysockets/baileys@7.0.0-rc14': patches/@whiskeysockets__baileys@7.0.0-rc14.patch
'@whiskeysockets/baileys@7.0.0': patches/@whiskeysockets__baileys@7.0.0.patch
libsignal@6.0.0: patches/libsignal@6.0.0.patch
+31 -13
View File
@@ -94,17 +94,17 @@ export function createWhatsAppLinkedTransport(options: {
const revokedLids = new Set<string>();
let state: ChannelLinkStatus = { state: 'connecting' };
const lifetime = new AbortController();
let versionChecked = true;
let refused = 0;
const createSocket =
options.createSocket ??
(async (configuration: Parameters<typeof makeWASocket>[0]) =>
makeWASocket({
...configuration,
version: (
await fetchLatestWaWebVersion({
signal: AbortSignal.any([lifetime.signal, AbortSignal.timeout(10_000)]),
})
).version,
}));
(async (configuration: Parameters<typeof makeWASocket>[0]) => {
const latest = await fetchLatestWaWebVersion({
signal: AbortSignal.any([lifetime.signal, AbortSignal.timeout(10_000)]),
});
versionChecked = latest.isLatest;
return makeWASocket({ ...configuration, version: latest.version });
});
const pairingId = randomUUID();
const sentIds = new Set<string>();
const incoming: InboundMessage[] = [];
@@ -446,9 +446,6 @@ export function createWhatsAppLinkedTransport(options: {
shouldSyncHistoryMessage: () => false,
markOnlineOnConnect: false,
emitOwnEvents: false,
maxMsgRetryCount: 0,
enableAutoSessionRecreation: false,
enableRecentMessageCache: false,
getMessage: async () => undefined,
connectTimeoutMs: 30_000,
defaultQueryTimeoutMs: 30_000,
@@ -485,11 +482,13 @@ export function createWhatsAppLinkedTransport(options: {
current.ev.on('creds.update', (update) => {
if (closed || halted || socket !== current) return;
Object.assign(auth.creds, update);
if (update.advSecretKey && !auth.creds.me) state = { ...state, rescan: true };
void save({ creds: JSON.stringify(auth.creds, BufferJSON.replacer) }).catch(() => {});
});
current.ev.on('messages.upsert', (event) => {
if (closed || halted || socket !== current) return;
if (event.requestId) return drop('resend_ignored', event.messages[0]);
if (event.requestId && event.type !== 'notify')
return drop('resend_ignored', event.messages[0]);
const messages = event.messages.slice(0, Math.max(0, 1000 - queued));
if (messages.length < event.messages.length)
drop('queue_full', event.messages[messages.length]);
@@ -525,6 +524,8 @@ export function createWhatsAppLinkedTransport(options: {
}
clearTimeout(expiry);
attempt = 0;
refused = 0;
quiet(current);
state = {
...state,
state: 'connected',
@@ -538,6 +539,7 @@ export function createWhatsAppLinkedTransport(options: {
linkedAt = Date.now() - 2000;
void save({ 'intake-start': String(linkedAt) }).catch(() => {});
}
state.linkedAt = new Date(linkedAt).toISOString();
}
if (update.connection === 'close') {
channel.available = false;
@@ -571,7 +573,15 @@ export function createWhatsAppLinkedTransport(options: {
'failed',
`${reason} (${code}). Select Reconnect. If it still fails, check Linked Devices in WhatsApp.`,
);
} else if (code === 405 && ++refused >= 3) {
stop(
'failed',
versionChecked
? 'WhatsApp turned down this version of Nod (405). Update Nod, then select Reconnect.'
: 'WhatsApp turned down this version of Nod (405). Nod could not check the current WhatsApp version at web.whatsapp.com. Check the internet connection or firewall, then select Reconnect.',
);
} else {
if (code !== 405) refused = 0;
state.error = `WhatsApp disconnected${Number.isInteger(code) ? ` (${code})` : ''}. Nod is trying to reconnect.`;
channel.error = state.error;
clearTimeout(reconnect);
@@ -678,8 +688,15 @@ export function createWhatsAppLinkedTransport(options: {
});
if (!result?.key.id || result.key.id !== id)
throw new Error('WhatsApp delivery was not confirmed.');
quiet(current, jid);
return id;
}
function quiet(current: Socket, jid?: string) {
void (async () => {
if (jid && !selfChat(jid)) await current.sendPresenceUpdate('paused', jid);
await current.sendPresenceUpdate('unavailable');
})().catch(() => {});
}
const target = (input: { channelId: string; accountId: string; threadId: string }) => {
if (
input.channelId !== 'whatsapp' ||
@@ -856,6 +873,7 @@ export function createWhatsAppLinkedTransport(options: {
},
async presence(input) {
target(input);
if (selfChat(input.threadId)) return;
if (socket && channel.available) await socket.sendPresenceUpdate('composing', input.threadId);
},
async unlink() {
+2
View File
@@ -411,6 +411,8 @@ export interface ChannelLinkStatus {
| 'failed';
qr?: string;
expiresAt?: string;
rescan?: boolean;
linkedAt?: string;
accountHandle?: string;
accountName?: string;
error?: string;
+314 -8
View File
@@ -1,6 +1,279 @@
.whatsapp-setup-status {
.whatsapp-setup {
gap: 14px;
}
.whatsapp-setup strong {
color: var(--foreground);
font-weight: 600;
}
.whatsapp-consent {
padding: 14px;
border-radius: var(--input-radius);
background: var(--muted);
}
.whatsapp-link-steps {
display: grid;
gap: 16px;
gap: 8px;
margin: 0;
padding: 0;
list-style: none;
transition: color 0.3s;
}
.whatsapp-link-steps > li {
display: flex;
gap: 12px;
align-items: flex-start;
}
.whatsapp-link-steps[data-done] {
color: var(--muted-foreground);
}
.whatsapp-step-marker {
display: grid;
flex-shrink: 0;
place-items: center;
width: 22px;
height: 22px;
border-radius: 50%;
background: var(--secondary);
font-size: 12px;
font-weight: 600;
transition:
background-color 0.3s,
color 0.3s;
}
.whatsapp-link-steps[data-done] .whatsapp-step-marker {
background: var(--success-soft);
color: var(--success);
}
.whatsapp-paths {
display: grid;
grid-template-columns: 72px minmax(0, 1fr);
gap: 2px 0;
margin: 4px 0 0;
font-size: var(--text-control);
}
.whatsapp-paths dt {
color: var(--muted-foreground);
}
.whatsapp-paths dd {
margin: 0;
}
.whatsapp-panel {
display: flex;
flex-direction: column;
gap: 10px;
align-items: center;
padding: 16px;
border-radius: 16px;
background: var(--muted);
text-align: center;
transition: background-color 0.3s;
}
.whatsapp-panel[data-done] {
background: var(--success-soft);
}
.whatsapp-panel h3 {
margin: 0;
font-size: 18px;
font-weight: 500;
}
.whatsapp-panel > p:not(.whatsapp-pill) {
margin: 0;
color: var(--success);
font-size: var(--text-control);
}
.whatsapp-viewfinder {
position: relative;
display: grid;
place-items: center;
width: 180px;
height: 180px;
color: #a8a8a8;
transition: color 0.3s;
}
.whatsapp-viewfinder[data-done] {
color: var(--success);
}
.whatsapp-viewfinder > i {
position: absolute;
width: 28px;
height: 28px;
border: 3px solid currentColor;
}
.whatsapp-viewfinder > [data-corner='top-left'] {
top: 0;
left: 0;
border-right: 0;
border-bottom: 0;
border-top-left-radius: 10px;
}
.whatsapp-viewfinder > [data-corner='top-right'] {
top: 0;
right: 0;
border-bottom: 0;
border-left: 0;
border-top-right-radius: 10px;
}
.whatsapp-viewfinder > [data-corner='bottom-left'] {
bottom: 0;
left: 0;
border-top: 0;
border-right: 0;
border-bottom-left-radius: 10px;
}
.whatsapp-viewfinder > [data-corner='bottom-right'] {
right: 0;
bottom: 0;
border-top: 0;
border-left: 0;
border-bottom-right-radius: 10px;
}
.whatsapp-viewfinder-code {
display: grid;
place-items: center;
box-sizing: border-box;
width: 144px;
height: 144px;
padding: 8px;
border-radius: 10px;
background: #fff;
color: #191919;
}
.whatsapp-qr {
width: 100%;
height: auto;
}
.whatsapp-viewfinder-check {
display: grid;
place-items: center;
width: 72px;
height: 72px;
border-radius: 50%;
background: var(--success);
color: #fff;
animation: whatsapp-check 0.3s ease-out;
}
@keyframes whatsapp-check {
from {
opacity: 0;
transform: scale(0.6);
}
}
.whatsapp-pill {
display: inline-flex;
gap: 8px;
align-items: center;
margin: 0;
padding: 6px 12px;
border-radius: var(--radius-full);
background: var(--background);
color: var(--muted-foreground);
font-size: var(--text-control);
}
.whatsapp-panel[data-attention] .whatsapp-viewfinder {
color: var(--primary);
}
.whatsapp-pill[data-attention] {
background: var(--primary);
color: var(--primary-foreground);
font-weight: 500;
}
.whatsapp-panel[data-done] .whatsapp-pill {
color: var(--success);
font-weight: 500;
}
.whatsapp-spinner {
flex-shrink: 0;
animation: spin 1s linear infinite;
}
.whatsapp-hello-steps {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
gap: 8px;
width: 100%;
margin: 0;
padding: 0;
list-style: none;
font-size: var(--text-control);
}
.whatsapp-hello-steps > li {
display: flex;
flex-direction: column;
gap: 4px;
align-items: center;
}
.whatsapp-hello-steps span {
display: grid;
place-items: center;
width: 22px;
height: 22px;
border-radius: 50%;
background: var(--background);
font-size: 13px;
font-weight: 600;
}
.channel-wizard-step > .whatsapp-setup-hint,
.whatsapp-setup-link {
justify-self: center;
text-align: center;
}
.whatsapp-setup-hint a,
.whatsapp-setup-link {
color: var(--foreground);
font-size: var(--text-control);
}
.whatsapp-setup-footer {
display: flex;
gap: 8px;
align-items: center;
padding-top: 16px;
border-top: 1px solid var(--border);
}
.whatsapp-setup-footer > span {
flex-grow: 1;
color: var(--muted-foreground);
font-size: 13px;
line-height: 1.3;
}
.whatsapp-setup-footer strong {
font-weight: 500;
}
.whatsapp-setup-qr {
@@ -21,18 +294,12 @@
height: auto;
}
.channel-wizard-step > .whatsapp-setup-hint {
text-align: center;
}
.whatsapp-connected-identity {
display: grid;
gap: 4px;
padding: 8px 0 16px;
}
.whatsapp-connected-identity strong {
color: var(--foreground);
font-size: var(--text-body);
font-weight: 500;
}
@@ -41,3 +308,42 @@
color: var(--muted-foreground);
font-size: var(--text-control);
}
@media (prefers-reduced-motion: reduce) {
.whatsapp-link-steps,
.whatsapp-step-marker,
.whatsapp-panel,
.whatsapp-viewfinder {
transition: none;
}
.whatsapp-viewfinder-check,
.whatsapp-spinner {
animation: none;
}
}
.whatsapp-number {
display: grid;
gap: 2px;
min-width: 0;
overflow-wrap: anywhere;
color: var(--muted-foreground);
font-size: var(--text-control);
}
.whatsapp-number strong {
font-weight: 500;
}
.whatsapp-number button,
.whatsapp-setup-hint button {
padding: 0;
border: 0;
background: none;
color: var(--foreground);
font: inherit;
font-weight: 500;
text-decoration: underline;
cursor: pointer;
}
+416 -136
View File
@@ -1,9 +1,58 @@
import { useEffect, useRef, useState } from 'react';
import { useEffect, useLayoutEffect, useRef, useState, type ReactNode } from 'react';
import { QRCodeSVG } from 'qrcode.react';
import type { ChannelLinkStatus, ChannelSetupSummary } from '../../shared/contracts';
import { api, errorMessage } from '../lib/api';
import { Check, LoaderCircle } from './icons';
import { Button, Checkbox, Notice } from './ui';
export type WhatsAppSetupStep = 'start' | 'link' | 'linked' | 'hello' | 'done' | 'reconnect';
const linking = { title: 'Connect WhatsApp', description: 'Step 1 of 2 · Link your WhatsApp' };
const linked = {
title: 'WhatsApp is linked',
description: 'Keep Nod running to receive messages.',
};
export const whatsappSetupHeading: Record<
WhatsAppSetupStep,
{ title: string; description: string }
> = {
start: linking,
link: linking,
linked: linking,
hello: { title: 'WhatsApp is linked', description: 'Step 2 of 2 · Say hi to Nod' },
done: linked,
reconnect: { title: 'WhatsApp', description: 'Keep Nod running to receive messages.' },
};
function Viewfinder({ done, children }: { done: boolean; children: ReactNode }) {
return (
<div className="whatsapp-viewfinder" data-done={done || undefined}>
<i data-corner="top-left" aria-hidden="true" />
<i data-corner="top-right" aria-hidden="true" />
<i data-corner="bottom-left" aria-hidden="true" />
<i data-corner="bottom-right" aria-hidden="true" />
<div className="whatsapp-viewfinder-code">
{done ? (
<span className="whatsapp-viewfinder-check">
<Check size={40} aria-hidden="true" />
</span>
) : (
children
)}
</div>
</div>
);
}
function Waiting({ children }: { children: ReactNode }) {
return (
<p className="whatsapp-pill" role="status">
<LoaderCircle className="whatsapp-spinner" size={16} aria-hidden="true" />
{children}
</p>
);
}
export function WhatsAppSetup({
setup,
busy,
@@ -15,6 +64,8 @@ export function WhatsAppSetup({
onDone,
onDisconnect,
onPhone,
onStep,
lastMessageAt,
}: {
setup?: ChannelSetupSummary;
busy: boolean;
@@ -26,16 +77,23 @@ export function WhatsAppSetup({
onDone(): void;
onDisconnect?(): void;
onPhone?(): Promise<string | null>;
onStep?(step: WhatsAppSetupStep): void;
lastMessageAt?: string | null;
}) {
const [policy, setPolicy] = useState(false);
const [phoneUrl, setPhoneUrl] = useState<string | null>(null);
const [link, setLink] = useState<ChannelLinkStatus>();
const [failure, setFailure] = useState('');
const [restarting, setRestarting] = useState(false);
const [stuck, setStuck] = useState(false);
const [justLinked, setJustLinked] = useState(false);
const [pairing, setPairing] = useState(false);
const [sawPairing, setSawPairing] = useState(false);
const currentLink = useRef<ChannelLinkStatus | undefined>(undefined);
const visible = useRef(false);
const restartPending = useRef(false);
const revision = useRef(0);
const sawCode = useRef(false);
const saved = Boolean(setup?.enabled && setup.mode === 'linked');
async function cancel(link?: ChannelLinkStatus) {
if (setup?.managed) return;
@@ -85,6 +143,28 @@ export function WhatsAppSetup({
};
}, [saved]);
const state = link?.state ?? setup?.connectionState ?? 'connecting';
const hasAccount = state === 'connected' || Boolean(link?.accountHandle || setup?.accountHandle);
const canRestart = state === 'failed' || state === 'expired' || state === 'logged_out' || stuck;
useEffect(() => {
setStuck(false);
if (state === 'awaiting_scan') sawCode.current = true;
if (state === 'connected' && sawCode.current) {
sawCode.current = false;
setJustLinked(true);
}
if (state !== 'disconnected') return;
const timer = setTimeout(() => setStuck(true), 20_000);
return () => clearTimeout(timer);
}, [state]);
useEffect(() => {
if (!justLinked) return;
const timer = setTimeout(() => setJustLinked(false), 1500);
return () => clearTimeout(timer);
}, [justLinked]);
useEffect(() => {
const expiresAt = link?.expiresAt;
if (!link?.qr || !expiresAt) return;
@@ -99,6 +179,30 @@ export function WhatsAppSetup({
return () => clearTimeout(timer);
}, [link?.qr, link?.expiresAt]);
const waitingPhone = Boolean(
setup?.pairingExpiresAt && Date.parse(setup.pairingExpiresAt) > Date.now(),
);
useEffect(() => {
if (pairing && waitingPhone) setSawPairing(true);
}, [pairing, waitingPhone]);
const paired = pairing && sawPairing && !setup?.pairingExpiresAt;
const pairingExpired = pairing && sawPairing && !waitingPhone && !paired;
const step: WhatsAppSetupStep = !saved
? 'start'
: justLinked
? 'linked'
: state === 'connected'
? (lastMessageAt &&
(!link?.linkedAt || Date.parse(lastMessageAt) >= Date.parse(link.linkedAt))) ||
paired
? 'done'
: 'hello'
: hasAccount
? 'reconnect'
: 'link';
useLayoutEffect(() => onStep?.(step), [step]);
async function restart() {
const pairingId = currentLink.current?.pairingId;
if (busy || restartPending.current || !pairingId) return;
@@ -127,19 +231,62 @@ export function WhatsAppSetup({
}
}
const state = link?.state ?? setup?.connectionState ?? 'connecting';
const hasAccount = state === 'connected' || Boolean(link?.accountHandle || setup?.accountHandle);
const canRestart = state === 'failed' || state === 'expired' || state === 'logged_out';
const linkedNumber = (link?.accountHandle ?? setup?.accountHandle)?.replace(/^\+/, '');
const accountName = link?.accountName || setup?.accountName || 'your WhatsApp account';
const accountHandle = link?.accountHandle || setup?.accountHandle;
const linkedNumber = accountHandle?.replace(/^\+/, '');
const chatUrl =
linkedNumber && /^\d{7,15}$/.test(linkedNumber) ? `https://wa.me/${linkedNumber}` : undefined;
const waitingPhone = Boolean(
setup?.pairingExpiresAt && Date.parse(setup.pairingExpiresAt) > Date.now(),
async function pairPhone() {
if (!onPhone) return;
setPairing(true);
setSawPairing(false);
setPhoneUrl(await onPhone());
}
const qr = link?.qr && link.expiresAt && Date.parse(link.expiresAt) > Date.now() ? link.qr : '';
const rescan = Boolean(qr && state === 'awaiting_scan' && link?.rescan);
const problem = canRestart
? (link?.error ??
(state === 'expired'
? 'The QR setup expired. Start again to get a new code.'
: state === 'logged_out'
? 'WhatsApp signed out this device. Link the account again.'
: 'WhatsApp could not connect. Check your connection, then try again.'))
: '';
const startAgain = canRestart && (
<Button
type="button"
onClick={() => void restart()}
disabled={busy || restarting || !link?.pairingId}
>
{restarting ? 'Preparing connection…' : 'Start again'}
</Button>
);
const footer = (
<div className="whatsapp-setup-footer">
<span>
{step === 'done' && (
<>
Nod’s number
<br />
<strong>{accountHandle}</strong> · {accountName}
</>
)}
</span>
{onDisconnect && (
<Button type="button" variant="ghost" disabled={busy || restarting} onClick={onDisconnect}>
Disconnect
</Button>
)}
<Button type="button" onClick={onDone}>
Done
</Button>
</div>
);
return (
<div className="channel-wizard-step" data-analytics-private>
<div className="channel-wizard-step whatsapp-setup" data-analytics-private>
{(error || failure) && <Notice>{error || failure}</Notice>}
{!saved ? (
{step === 'start' ? (
<form
onSubmit={(event) => {
event.preventDefault();
@@ -147,14 +294,14 @@ export function WhatsAppSetup({
}}
>
<p>
Scan the code with the phone whose WhatsApp Nod will use. Then write to Nod in{' '}
<strong>Message yourself</strong>.
<strong>How it works.</strong> Nod links to your WhatsApp the way WhatsApp Web does. You
then chat with Nod in <strong>Message yourself</strong>, the chat with your own number.
</p>
<p>
WhatsApp doesn’t officially support this connection, so there’s a small risk of account
restrictions. Nod only messages you. A separate number keeps your own chats safe.
<strong>Good to know.</strong> Your phone won’t notify you when Nod replies there. If
you want notifications, link a second number instead.
</p>
<label className="channel-policy">
<label className="channel-policy whatsapp-consent">
<Checkbox
checked={policy}
required
@@ -162,7 +309,8 @@ export function WhatsAppSetup({
onChange={(event) => setPolicy(event.target.checked)}
/>
<span>
I understand this risk and have checked the{' '}
WhatsApp doesn’t officially support this kind of link, so there’s a small risk your
account gets restricted. I accept this and the{' '}
<a
href="https://www.whatsapp.com/legal/terms-of-service"
target="_blank"
@@ -184,135 +332,267 @@ export function WhatsAppSetup({
</Button>
)}
</form>
) : (
) : step === 'link' || step === 'linked' ? (
<>
<div className="whatsapp-setup-status" role="status" aria-live="polite">
{state === 'connected' ? (
<>
<div className="whatsapp-connected-identity">
<strong>
{link?.accountName || setup?.accountName || 'Your WhatsApp account'}
</strong>
{(link?.accountHandle || setup?.accountHandle) && (
<span>{link?.accountHandle || setup?.accountHandle}</span>
)}
</div>
<p>
{chatUrl ? (
<a
className="channel-external-link"
href={chatUrl}
target="_blank"
rel="noopener noreferrer"
>
Open WhatsApp
</a>
) : (
'Open WhatsApp'
)}
, select <strong>Message yourself</strong>, and send Nod a message.
</p>
{phoneUrl && waitingPhone ? (
<div className="whatsapp-setup-phone">
<div className="whatsapp-setup-qr">
<QRCodeSVG
value={phoneUrl}
size={152}
marginSize={4}
level="M"
title="Open WhatsApp on your other phone"
/>
</div>
<p>
Scan with your other phone and send the message that opens. The code works for
15 minutes.
</p>
</div>
) : (
<>
{setup?.pairedUser && <p>Also from {setup.pairedUser}.</p>}
{onPhone && (
<Button
type="button"
variant="ghost"
size="sm"
disabled={busy}
onClick={async () => setPhoneUrl(await onPhone())}
>
Write from another phone
</Button>
)}
</>
)}
</>
) : state === 'awaiting_scan' ? (
<>
<p>
In WhatsApp, open <strong>Settings → Linked Devices → Link a Device</strong>, then
scan this code.
</p>
{link?.qr && link.expiresAt && Date.parse(link.expiresAt) > Date.now() ? (
<div className="whatsapp-setup-qr">
<QRCodeSVG
value={link.qr}
size={196}
marginSize={4}
level="M"
title="Link WhatsApp to Nod"
/>
</div>
) : (
<p>Waiting for a new QR code…</p>
)}
</>
) : state === 'connecting' || state === 'disconnected' ? (
<p>
{state === 'connecting'
? 'Connecting to WhatsApp…'
: (link?.error ?? 'WhatsApp is disconnected. Nod is trying to connect again.')}
<ol className="whatsapp-link-steps" data-done={step === 'linked' || undefined}>
<li>
<span className="whatsapp-step-marker">
{step === 'linked' ? <Check size={14} aria-hidden="true" /> : 1}
</span>
<span>Open WhatsApp on your phone.</span>
</li>
<li>
<span className="whatsapp-step-marker">
{step === 'linked' ? <Check size={14} aria-hidden="true" /> : 2}
</span>
<div>
Go to <strong>Linked devices</strong>.
<dl className="whatsapp-paths">
<dt>iPhone</dt>
<dd>Settings → Linked Devices</dd>
<dt>Android</dt>
<dd>Three-dot menu → Linked devices</dd>
</dl>
</div>
</li>
<li>
<span className="whatsapp-step-marker">
{step === 'linked' ? <Check size={14} aria-hidden="true" /> : 3}
</span>
<span>
Tap <strong>Link a device</strong> and scan this code.
</span>
</li>
</ol>
<section
className="whatsapp-panel"
data-done={step === 'linked' || undefined}
data-attention={rescan || undefined}
>
<Viewfinder done={step === 'linked'}>
{qr && state === 'awaiting_scan' ? (
<QRCodeSVG
className="whatsapp-qr"
value={qr}
size={128}
marginSize={0}
level="M"
title="Link WhatsApp to Nod"
/>
) : (
<LoaderCircle className="whatsapp-spinner" size={28} aria-hidden="true" />
)}
</Viewfinder>
{step === 'linked' ? (
<p className="whatsapp-pill" role="status">
Linked as {accountName}
</p>
) : problem ? (
<p className="whatsapp-pill" role="status">
{problem}
</p>
) : rescan ? (
<p className="whatsapp-pill" role="status" data-attention>
WhatsApp asked to scan again. Scan this new code.
</p>
) : (
<Notice>
{link?.error ??
(state === 'expired'
? 'The QR setup expired. Start again to get a new code.'
: state === 'logged_out'
? 'WhatsApp signed out this device. Link the account again.'
: 'WhatsApp could not connect. Check your connection, then try again.')}
</Notice>
<Waiting>
{qr && state === 'awaiting_scan'
? 'Waiting for you to scan…'
: sawCode.current
? 'Linking your WhatsApp…'
: 'Connecting to WhatsApp…'}
</Waiting>
)}
</div>
{!hasAccount && link?.pairingId && !canRestart && (
<p className="whatsapp-setup-hint">Closing this window cancels setup.</p>
</section>
{step === 'linked' ? (
<p className="whatsapp-setup-hint">Moving on to step 2…</p>
) : startAgain ? (
<div className="channel-wizard-actions">{startAgain}</div>
) : (
link?.pairingId && (
<p className="whatsapp-setup-hint">Closing this window cancels setup.</p>
)
)}
{(hasAccount || canRestart) && (
<div className="channel-wizard-actions">
{hasAccount && onDisconnect && (
<Button
type="button"
variant="ghost"
disabled={busy || restarting}
onClick={onDisconnect}
>
Disconnect
</Button>
)}
{state === 'connected' && (
<Button type="button" onClick={onDone}>
Done
</Button>
)}
{canRestart && (
<Button
type="button"
onClick={() => void restart()}
disabled={busy || restarting || !link?.pairingId}
>
{restarting ? 'Preparing connection…' : 'Start again'}
</Button>
</>
) : step === 'hello' || step === 'done' ? (
<>
{step === 'hello' && (
<div className="whatsapp-number">
<span>
<strong>Nod’s number:</strong> {accountHandle} · {accountName}
</span>
{onPhone && !pairing && (
<span>
Not your own number?{' '}
<button type="button" disabled={busy} onClick={() => void pairPhone()}>
Pair your phone
</button>
</span>
)}
</div>
)}
<section className="whatsapp-panel" data-done={step === 'done' || undefined}>
<h3>
{step === 'hello'
? pairing
? 'Pair your phone'
: 'Now say hi to Nod'
: paired
? 'Your phone is paired'
: 'Nod got your message'}
</h3>
<Viewfinder done={step === 'done'}>
{(pairing ? phoneUrl : chatUrl) ? (
<QRCodeSVG
className="whatsapp-qr"
value={(pairing ? phoneUrl : chatUrl)!}
size={128}
marginSize={0}
level="H"
title={pairing ? 'Pair your phone with Nod' : 'Open your Nod chat in WhatsApp'}
imageSettings={{ src: '/favicon.svg', height: 32, width: 32, excavate: true }}
/>
) : (
<LoaderCircle className="whatsapp-spinner" size={28} aria-hidden="true" />
)}
</Viewfinder>
{step === 'done' ? (
paired ? (
<p>
Nod replies from <strong>{accountHandle}</strong>, so you get notifications like
any other chat.
</p>
) : (
<p>
You’re all set. Keep chatting with Nod in <strong>Message yourself</strong>.
</p>
)
) : (
<>
<ol className="whatsapp-hello-steps">
<li>
<span>1</span>Scan with camera
</li>
<li>
<span>2</span>
{pairing ? 'Send the code' : 'Open WhatsApp'}
</li>
<li>
<span>3</span>
{pairing ? 'Chat with Nod' : 'Send “hi”'}
</li>
</ol>
{pairingExpired ? (
<p className="whatsapp-pill" role="status">
The code expired
</p>
) : (
<Waiting>
{pairing ? 'Waiting for your phone…' : 'Waiting for your message…'}
</Waiting>
)}
</>
)}
</section>
{step === 'hello' && pairing ? (
<p className="whatsapp-setup-hint">
Scan with the phone you’ll chat from. The code works for 15 minutes.
<br />
{pairingExpired && (
<>
<button type="button" disabled={busy} onClick={() => void pairPhone()}>
Get a new code
</button>
{' · '}
</>
)}
<button type="button" onClick={() => setPairing(false)}>
Using your own number? Go back
</button>
</p>
) : (
chatUrl &&
(step === 'done' ? (
<a className="whatsapp-setup-link" href={chatUrl} target="_blank" rel="noreferrer">
Open WhatsApp on your computer
</a>
) : (
<p className="whatsapp-setup-hint">
You can also say hi in <strong>Message yourself</strong>
<br />
on your phone or{' '}
<a href={chatUrl} target="_blank" rel="noreferrer">
open WhatsApp on your computer
</a>
.
</p>
))
)}
{step === 'done' &&
!paired &&
(phoneUrl && waitingPhone ? (
<div className="whatsapp-setup-phone">
<div className="whatsapp-setup-qr">
<QRCodeSVG
value={phoneUrl}
size={152}
marginSize={4}
level="M"
title="Open WhatsApp on your other phone"
/>
</div>
<p>
Scan with your other phone and send the message that opens. The code works for 15
minutes.
</p>
</div>
) : (
<>
{setup?.pairedUser && <p>Also from {setup.pairedUser}.</p>}
{onPhone && (
<Button
type="button"
variant="ghost"
size="sm"
disabled={busy}
onClick={async () => setPhoneUrl(await onPhone())}
>
Write from another phone
</Button>
)}
</>
))}
{footer}
</>
) : (
<>
<div className="whatsapp-connected-identity">
<strong>{accountName}</strong>
{accountHandle && <span>{accountHandle}</span>}
</div>
{problem ? (
<Notice>{problem}</Notice>
) : (
<Waiting>
{state === 'disconnected'
? (link?.error ?? 'WhatsApp is disconnected. Nod is trying to connect again.')
: 'Connecting to WhatsApp…'}
</Waiting>
)}
<div className="channel-wizard-actions">
{onDisconnect && (
<Button
type="button"
variant="ghost"
disabled={busy || restarting}
onClick={onDisconnect}
>
Disconnect
</Button>
)}
{startAgain}
</div>
</>
)}
</div>
+12 -5
View File
@@ -13,7 +13,11 @@ import {
} from '../components/icons';
import { IntegrationCard } from '../components/integration-card';
import { TelegramLink, TelegramSetup } from '../components/telegram-setup';
import { WhatsAppSetup } from '../components/whatsapp-setup';
import {
WhatsAppSetup,
whatsappSetupHeading,
type WhatsAppSetupStep,
} from '../components/whatsapp-setup';
import type { ChannelProvider, ChannelSetupSummary } from '../../shared/contracts';
import { telegramState, useChannelSettings } from '../hooks/use-channel-settings';
import { channelSetupBody, telegramBotUrl } from '../lib/secondary-pages';
@@ -417,6 +421,7 @@ export function Channels() {
const whatsappCloud = fields.connection === 'cloud';
const [policy, setPolicy] = useState(false);
const [resuming, setResuming] = useState(false);
const [whatsappStep, setWhatsappStep] = useState<WhatsAppSetupStep>('start');
const [removing, setRemoving] = useState<ChannelProvider | null>(null);
const [removeError, setRemoveError] = useState('');
const page = useRef<HTMLDivElement>(null);
@@ -839,12 +844,10 @@ export function Channels() {
<>
<DialogTitle className="channel-wizard-title">
<img src="/logos/whatsapp.svg" alt="" width={24} height={24} />
{selected?.setup?.connectionState === 'connected' ? 'WhatsApp' : 'Connect WhatsApp'}
{whatsappSetupHeading[whatsappStep].title}
</DialogTitle>
<DialogDescription>
{selected?.setup?.connectionState === 'connected'
? 'Keep Nod running to receive messages.'
: 'Link an account with a QR code.'}
{whatsappSetupHeading[whatsappStep].description}
</DialogDescription>
<WhatsAppSetup
setup={channels.find((item) => item.provider.id === 'whatsapp')?.setup}
@@ -863,6 +866,10 @@ export function Channels() {
}}
onDone={close}
onPhone={selected?.setup?.managed ? undefined : () => pairingLink('whatsapp')}
onStep={setWhatsappStep}
lastMessageAt={
channels.find((item) => item.provider.id === 'whatsapp')?.lastMessageAt
}
/>
</>
) : (
+94 -5
View File
@@ -913,7 +913,6 @@ test(
const initial = await transport.pairing!();
assert.ok(initial.pairingId);
assert.equal(sockets[0].config.logger?.level, 'silent');
assert.equal(sockets[0].config.maxMsgRetryCount, 0);
assert.equal(sockets[0].config.shouldSyncHistoryMessage?.({}), false);
sockets[0].events.emit('connection.update', { qr: 'synthetic-qr' });
assert.equal((await transport.pairing!()).qr, 'synthetic-qr');
@@ -925,6 +924,8 @@ test(
assert.equal((await transport.pairing!()).state, 'connecting');
sockets[0].events.emit('connection.update', { connection: 'open' });
assert.equal((await transport.pairing!()).qr, undefined);
const linkedAt = (await transport.pairing!()).linkedAt;
assert.ok(linkedAt && Date.parse(linkedAt) <= Date.now());
assert.equal(await transport.cancelPairing!(initial.pairingId!), false);
assert.equal(await transport.cancelPairing!(initial.pairingId!, true), false);
await sockets[0].config.auth.keys.set({
@@ -993,6 +994,11 @@ test(
requestId: 'history-request',
messages: [envelope('history')],
});
sockets[0].events.emit('messages.upsert', {
type: 'notify',
requestId: 'placeholder-resend',
messages: [envelope('resent-after-decrypt-failure')],
});
await transport.poll!(
async (message) => {
collected.push(message);
@@ -1005,8 +1011,23 @@ test(
assert.deepEqual(
collected.map((message) => message.messageId),
mode === 'other-phone'
? ['owner', 'image', 'quoted', 'lid', 'unmapped-lid', 'ahead-of-local-clock']
: ['owner', 'image', 'quoted', 'lid', 'ahead-of-local-clock'],
? [
'owner',
'image',
'quoted',
'lid',
'unmapped-lid',
'ahead-of-local-clock',
'resent-after-decrypt-failure',
]
: [
'owner',
'image',
'quoted',
'lid',
'ahead-of-local-clock',
'resent-after-decrypt-failure',
],
);
if (mode === 'other-phone') assert.equal(collected[4].threadId, '77777777@lid');
assert.deepEqual(
@@ -1132,7 +1153,11 @@ test(
messageId: 'owner',
status: 'Synthetic live work',
});
assert.deepEqual(presence, [['composing', jid]]);
assert.deepEqual(
presence.filter(([state]) => state === 'composing'),
mode === 'own-number' ? [] : [['composing', jid]],
);
const beforeReply = presence.length;
if (mode === 'own-number') {
await assert.rejects(
transport.post({
@@ -1154,6 +1179,11 @@ test(
replyToText: 'Fixture task question',
attachments: [audioFile('reply.ogg', 'audio/ogg', oggOpus(1))],
});
for (let tick = 0; tick < 3; tick++)
await new Promise((resolve) => setImmediate(resolve));
const afterReply = presence.slice(beforeReply).map(([state]) => state);
assert.ok(afterReply.includes('unavailable'));
assert.equal(afterReply.includes('paused'), mode !== 'own-number');
assert.equal(sent[0].content.text, '*Task complete*');
assert.equal(sent[1].content.ptt, true);
assert.equal(sent[1].content.mimetype, 'audio/ogg; codecs=opus');
@@ -1412,6 +1442,7 @@ test(
Buffer.from([1, 2, 3]),
);
resumed.events.emit('connection.update', { connection: 'open' });
assert.equal((await transport.pairing!()).linkedAt, linkedAt);
const beforeEcho = collected.length;
resumed.events.emit('messages.upsert', {
type: 'notify',
@@ -1628,7 +1659,7 @@ test('Telegram voice, contact and location replies still send when the message t
]);
});
test('WhatsApp keeps a linked device that cannot connect for five minutes', async (t) => {
test('WhatsApp keeps a linked device through outages and stops after repeated 405s', async (t) => {
type Factory = NonNullable<Parameters<typeof createWhatsAppLinkedTransport>[0]['createSocket']>;
t.mock.timers.enable({ apis: ['setTimeout'] });
const settle = async () => {
@@ -1661,6 +1692,13 @@ test('WhatsApp keeps a linked device that cannot connect for five minutes', asyn
};
const unscanned = await start(new Map());
unscanned.events.emit('connection.update', { qr: 'first-code' });
assert.equal((await unscanned.transport.pairing!()).rescan, undefined);
unscanned.events.emit('creds.update', { advSecretKey: 'rotated-secret' });
unscanned.events.emit('connection.update', { qr: 'second-code' });
const rescan = await unscanned.transport.pairing!();
assert.equal(rescan.qr, 'second-code');
assert.equal(rescan.rescan, true);
await fiveMinutes();
assert.equal((await unscanned.transport.pairing!()).state, 'expired');
@@ -1684,6 +1722,57 @@ test('WhatsApp keeps a linked device that cannot connect for five minutes', asyn
await fiveMinutes();
assert.notEqual((await restarted.transport.pairing!()).state, 'expired');
assert.match(saved.get('creds') ?? '', /12025550102/);
for (let attempt = 0; attempt < 2; attempt++) {
restarted.events.emit('connection.update', {
connection: 'close',
lastDisconnect: { error: { output: { statusCode: 405 } } },
});
await fiveMinutes();
}
const refused = await restarted.transport.pairing!();
assert.equal(refused.state, 'failed');
assert.match(refused.error ?? '', /\(405\)\. Update Nod/);
assert.match(saved.get('creds') ?? '', /12025550102/);
});
test('WhatsApp rotates the pairing secret when the server retires it before the scan', async () => {
type Refresh = (
node: { tag: string; attrs: Record<string, string>; content: unknown[] },
context: {
creds: { advSecretKey: string; me?: { id: string } };
emitCredsUpdate(update: unknown): void;
refreshQR(): void;
logger: Record<'debug' | 'info' | 'warn', () => void>;
},
) => string;
const { handleCompanionRegRefresh } = (await import('@whiskeysockets/baileys')) as unknown as {
handleCompanionRegRefresh: Refresh;
};
const creds: { advSecretKey: string; me?: { id: string } } = { advSecretKey: 'retired' };
let refreshed = 0;
const updates: unknown[] = [];
const context = {
creds,
emitCredsUpdate: (update: unknown) => void updates.push(update),
refreshQR: () => refreshed++,
logger: { debug() {}, info() {}, warn() {} },
};
const notification = {
tag: 'notification',
attrs: { id: '1', type: 'companion_reg_refresh', from: '@s.whatsapp.net' },
content: [{ tag: 'companion_reg_refresh', attrs: {} }],
};
assert.equal(handleCompanionRegRefresh(notification, context), 'rotated');
assert.notEqual(creds.advSecretKey, 'retired');
assert.equal(Buffer.from(creds.advSecretKey, 'base64').length, 32);
assert.equal(refreshed, 1);
assert.deepEqual(updates, [{ advSecretKey: creds.advSecretKey }]);
const rotated = creds.advSecretKey;
creds.me = { id: '12025550102:1@s.whatsapp.net' };
assert.equal(handleCompanionRegRefresh(notification, context), 'ignored_registered');
assert.equal(creds.advSecretKey, rotated);
assert.equal(updates.length, 1);
});
test('WhatsApp accepts the linked phone by a confirmed private ID when mapping lookups miss', async (t) => {