Skip to content

YC (S26) | Open Computer History | Continuously record your company computer work, map your workflows, help you find work worth automating, and power your agents' context

Add WhatsApp chat history, contacts sync, and improved API descriptions

Louis Beaumontaaf0311693fa
diff --git a/crates/screenpipe-connect/src/whatsapp/gateway.mjs b/crates/screenpipe-connect/src/whatsapp/gateway.mjs
index d7bfa0d83..371705c7d 100644
--- a/crates/screenpipe-connect/src/whatsapp/gateway.mjs
+++ b/crates/screenpipe-connect/src/whatsapp/gateway.mjs
@@ -12,8 +12,10 @@
// { "type": "http", "port": 3035 }
//
// HTTP API (Pi curls this directly):
-// POST /send { "to": "+33612345678", "text": "hello" }
-// GET /contacts returns [{ "id": "33612345678", "name": "John", "phone": "+33612345678" }, ...]
+// POST /send { "to": "+33612345678", "text": "hello" }
+// GET /contacts returns [{ "id": "...", "name": "John", "phone": "+33612345678" }, ...]
+// GET /messages?jid=<jid>&limit=50 returns recent messages for a chat
+// GET /chats returns list of recent chats
// GET /status
import makeWASocket, { useMultiFileAuthState, DisconnectReason, fetchLatestBaileysVersion } from "@whiskeysockets/baileys";
@@ -22,12 +24,20 @@ import { join } from "path";
import { homedir } from "os";
import { mkdirSync } from "fs";
import { createServer } from "http";
+import { URL } from "url";
const SESSION_DIR = process.env.WHATSAPP_SESSION_DIR || join(homedir(), ".screenpipe", "whatsapp-session");
const HTTP_PORT = parseInt(process.env.WHATSAPP_HTTP_PORT || "3035", 10);
mkdirSync(SESSION_DIR, { recursive: true });
let sock = null;
+// In-memory contact store — populated from contacts.update events
+const contactStore = {};
+// In-memory message store — keeps last N messages per chat
+const MAX_MESSAGES_PER_CHAT = 200;
+const messageStore = {};
+// Chat metadata
+const chatStore = {};
function emit(obj) {
process.stdout.write(JSON.stringify(obj) + "\n");
@@ -38,11 +48,27 @@ function toJid(phone) {
return cleaned.includes("@") ? cleaned : `${cleaned}@s.whatsapp.net`;
}
+function parseUrl(req) {
+ try {
+ return new URL(req.url, `http://${req.headers.host || "localhost"}`);
+ } catch {
+ return new URL(`http://localhost${req.url}`);
+ }
+}
+
+function contactName(jid) {
+ const c = contactStore[jid];
+ if (c) return c.name || c.notify || c.verifiedName || null;
+ return null;
+}
+
// HTTP server — Pi curls this directly
const server = createServer(async (req, res) => {
res.setHeader("Content-Type", "application/json");
+ const url = parseUrl(req);
+ const pathname = url.pathname;
- if (req.method === "POST" && req.url === "/send") {
+ if (req.method === "POST" && pathname === "/send") {
let body = "";
for await (const chunk of req) body += chunk;
try {
@@ -65,17 +91,14 @@ const server = createServer(async (req, res) => {
}
}
- if (req.method === "GET" && req.url === "/contacts") {
+ if (req.method === "GET" && pathname === "/contacts") {
if (!sock) {
res.writeHead(503);
return res.end(JSON.stringify({ error: "whatsapp not connected" }));
}
try {
const contacts = [];
- const store = sock.store?.contacts || {};
- // sock.store may not be available; use the contacts from the socket directly
- const contactMap = sock.contacts || store;
- for (const [jid, contact] of Object.entries(contactMap)) {
+ for (const [jid, contact] of Object.entries(contactStore)) {
if (!jid.endsWith("@s.whatsapp.net")) continue;
const phone = "+" + jid.split("@")[0];
contacts.push({
@@ -84,6 +107,8 @@ const server = createServer(async (req, res) => {
phone,
});
}
+ // Sort by name
+ contacts.sort((a, b) => a.name.localeCompare(b.name));
res.writeHead(200);
return res.end(JSON.stringify(contacts));
} catch (err) {
@@ -92,13 +117,76 @@ const server = createServer(async (req, res) => {
}
}
- if (req.method === "GET" && req.url === "/status") {
+ if (req.method === "GET" && pathname === "/chats") {
+ if (!sock) {
+ res.writeHead(503);
+ return res.end(JSON.stringify({ error: "whatsapp not connected" }));
+ }
+ try {
+ const chats = [];
+ for (const [jid, meta] of Object.entries(chatStore)) {
+ const msgs = messageStore[jid] || [];
+ const lastMsg = msgs[msgs.length - 1];
+ chats.push({
+ id: jid,
+ name: contactName(jid) || jid.split("@")[0],
+ lastMessage: lastMsg ? {
+ text: lastMsg.text || null,
+ timestamp: lastMsg.timestamp,
+ fromMe: lastMsg.fromMe,
+ } : null,
+ messageCount: msgs.length,
+ updatedAt: meta.updatedAt || (lastMsg?.timestamp) || null,
+ });
+ }
+ // Sort by most recent activity
+ chats.sort((a, b) => (b.updatedAt || 0) - (a.updatedAt || 0));
+ res.writeHead(200);
+ return res.end(JSON.stringify(chats));
+ } catch (err) {
+ res.writeHead(500);
+ return res.end(JSON.stringify({ error: err.message || String(err) }));
+ }
+ }
+
+ if (req.method === "GET" && pathname === "/messages") {
+ if (!sock) {
+ res.writeHead(503);
+ return res.end(JSON.stringify({ error: "whatsapp not connected" }));
+ }
+ const jid = url.searchParams.get("jid");
+ const phone = url.searchParams.get("phone");
+ const limit = parseInt(url.searchParams.get("limit") || "50", 10);
+
+ const targetJid = jid || (phone ? toJid(phone) : null);
+ if (!targetJid) {
+ res.writeHead(400);
+ return res.end(JSON.stringify({ error: "provide 'jid' or 'phone' query param" }));
+ }
+
+ try {
+ const msgs = (messageStore[targetJid] || []).slice(-limit);
+ res.writeHead(200);
+ return res.end(JSON.stringify({
+ jid: targetJid,
+ name: contactName(targetJid) || targetJid.split("@")[0],
+ messages: msgs,
+ }));
+ } catch (err) {
+ res.writeHead(500);
+ return res.end(JSON.stringify({ error: err.message || String(err) }));
+ }
+ }
+
+ if (req.method === "GET" && pathname === "/status") {
const me = sock?.user;
res.writeHead(200);
return res.end(JSON.stringify({
connected: !!me,
name: me?.name || null,
phone: me?.id?.split(":")[0] || null,
+ contactCount: Object.keys(contactStore).length,
+ chatCount: Object.keys(chatStore).length,
}));
}
@@ -110,6 +198,18 @@ server.listen(HTTP_PORT, "127.0.0.1", () => {
emit({ type: "http", port: HTTP_PORT });
});
+function storeMessage(jid, msg) {
+ if (!messageStore[jid]) messageStore[jid] = [];
+ messageStore[jid].push(msg);
+ // Trim to max
+ if (messageStore[jid].length > MAX_MESSAGES_PER_CHAT) {
+ messageStore[jid] = messageStore[jid].slice(-MAX_MESSAGES_PER_CHAT);
+ }
+ // Update chat metadata
+ if (!chatStore[jid]) chatStore[jid] = {};
+ chatStore[jid].updatedAt = msg.timestamp || Date.now();
+}
+
async function start() {
const { state, saveCreds } = await useMultiFileAuthState(SESSION_DIR);
const { version } = await fetchLatestBaileysVersion();
@@ -123,6 +223,57 @@ async function start() {
sock.ev.on("creds.update", saveCreds);
+ // Sync contacts into our in-memory store
+ sock.ev.on("contacts.update", (updates) => {
+ for (const contact of updates) {
+ if (contact.id) {
+ contactStore[contact.id] = { ...contactStore[contact.id], ...contact };
+ }
+ }
+ });
+
+ sock.ev.on("contacts.upsert", (contacts) => {
+ for (const contact of contacts) {
+ if (contact.id) {
+ contactStore[contact.id] = { ...contactStore[contact.id], ...contact };
+ }
+ }
+ });
+
+ // Track incoming/outgoing messages
+ sock.ev.on("messages.upsert", ({ messages: msgs, type }) => {
+ for (const msg of msgs) {
+ if (!msg.message) continue; // skip protocol messages
+ const jid = msg.key.remoteJid;
+ if (!jid || jid === "status@broadcast") continue;
+
+ const text =
+ msg.message.conversation ||
+ msg.message.extendedTextMessage?.text ||
+ msg.message.imageMessage?.caption ||
+ msg.message.videoMessage?.caption ||
+ null;
+
+ const mediaType =
+ msg.message.imageMessage ? "image" :
+ msg.message.videoMessage ? "video" :
+ msg.message.audioMessage ? "audio" :
+ msg.message.documentMessage ? "document" :
+ msg.message.stickerMessage ? "sticker" :
+ null;
+
+ storeMessage(jid, {
+ id: msg.key.id,
+ fromMe: !!msg.key.fromMe,
+ from: msg.key.fromMe ? "me" : (contactName(jid) || jid.split("@")[0]),
+ text,
+ mediaType,
+ timestamp: msg.messageTimestamp ? Number(msg.messageTimestamp) : Math.floor(Date.now() / 1000),
+ pushName: msg.pushName || null,
+ });
+ }
+ });
+
sock.ev.on("connection.update", (update) => {
const { connection, lastDisconnect, qr } = update;
diff --git a/crates/screenpipe-engine/src/cli/connection.rs b/crates/screenpipe-engine/src/cli/connection.rs
index 862028845..c27311f0c 100644
--- a/crates/screenpipe-engine/src/cli/connection.rs
+++ b/crates/screenpipe-engine/src/cli/connection.rs
@@ -31,7 +31,7 @@ pub async fn handle_connection_command(command: &ConnectionCommand) -> anyhow::R
.await
.is_ok();
let wa_desc = if wa_connected {
- "WhatsApp messaging. First GET http://localhost:3035/contacts to resolve names to phone numbers, then POST http://localhost:3035/send with {\"to\":\"+PHONE\",\"text\":\"MSG\"}".to_string()
+ "WhatsApp messaging gateway. Endpoints at http://localhost:3035: GET /contacts (list contacts), GET /chats (recent chats), GET /messages?phone=+PHONE&limit=50 (read messages), POST /send {\"to\":\"+PHONE\",\"text\":\"MSG\"} (send message), GET /status.".to_string()
} else if has_session {
"WhatsApp has a saved session but the gateway is not running. It should auto-reconnect on server restart.".to_string()
} else {
@@ -87,7 +87,7 @@ pub async fn handle_connection_command(command: &ConnectionCommand) -> anyhow::R
json!({
"id": "whatsapp",
"connected": true,
- "description": "WhatsApp messaging. First GET http://localhost:3035/contacts to resolve names to phone numbers, then POST http://localhost:3035/send with {\"to\":\"+PHONE\",\"text\":\"MSG\"}"
+ "description": "WhatsApp messaging gateway. Endpoints at http://localhost:3035: GET /contacts (list contacts), GET /chats (recent chats), GET /messages?phone=+PHONE&limit=50 (read messages), POST /send {\"to\":\"+PHONE\",\"text\":\"MSG\"} (send message), GET /status."
})
} else if has_session {
json!({
diff --git a/crates/screenpipe-engine/src/connections_api.rs b/crates/screenpipe-engine/src/connections_api.rs
index f84c1cd3d..781c92c36 100644
--- a/crates/screenpipe-engine/src/connections_api.rs
+++ b/crates/screenpipe-engine/src/connections_api.rs
@@ -56,7 +56,13 @@ async fn list_connections(State(state): State<ConnectionsState>) -> Json<Value>
);
let wa_desc = if let Some(port) = wa_port {
format!(
- "WhatsApp messaging. First GET http://localhost:{}/contacts to resolve names to phone numbers, then POST http://localhost:{}/send with {{\"to\":\"+PHONE\",\"text\":\"MSG\"}}",
+ "WhatsApp messaging gateway on port {}. Endpoints: \
+ GET /contacts — list saved contacts (may be empty, ask user for phone number if needed). \
+ GET /chats — list recent chats with last message. \
+ GET /messages?phone=+PHONE&limit=50 — read recent messages from a chat. \
+ POST /send {{\"to\":\"+PHONE\",\"text\":\"MSG\"}} — send a message. \
+ GET /status — connection info. \
+ All endpoints are at http://localhost:{}.",
port, port
)
} else {