Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions packages/cli/docs/messages.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ beeper messages export --chat SEL [--before-cursor MSG_ID | --after-cursor MSG
- `--before-cursor` / `--after-cursor` paginate by message ID (the SDK's cursor model).
- `--before` / `--after` in `messages search` and `messages export` filter by ISO timestamp.
- `messages search` rejects an empty query *and* no filter flags with exit code 2 (`usageError`).
- When `messages search` uses `--chat`, the CLI avoids the Desktop API's currently lossy `chatIDs` search path and applies the resolved chat filter client-side over account-scoped search results, preventing silent one-message-per-chat truncation.
- `messages list --sender` filters client-side: `me` (your own messages), `others`, or an exact user ID.
- `messages list --asc` reverses the default newest-first order.
- `messages export` writes one chat to JSON. Use top-level `export` for a full
Expand Down
62 changes: 60 additions & 2 deletions packages/cli/src/commands/messages/search.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,11 +60,12 @@ export default class MessagesSearch extends BeeperCommand {
}
const useSpinner = !flags.json && !flags.ids
const label = args.query ? `Searching messages for "${args.query}"…` : 'Searching messages…'
const load = () => collectMessageSearch(client, params, flags.limit, chatIDs)
const items = useSpinner
? await withSpinner(label, () => collectPage(client.messages.search(params), flags.limit), {
? await withSpinner(label, load, {
done: value => `${value.length} match${value.length === 1 ? '' : 'es'}`,
})
: await collectPage(client.messages.search(params), flags.limit)
: await load()
if (flags.ids) {
printIDs(items)
return
Expand All @@ -79,3 +80,60 @@ export default class MessagesSearch extends BeeperCommand {
})
}
}


async function collectMessageSearch(
client: any,
params: Record<string, unknown> & { accountIDs?: string[]; chatIDs?: string[] },
limit: number,
resolvedChatIDs?: string[],
): Promise<any[]> {
if (!resolvedChatIDs?.length) {
return collectPage(client.messages.search(params), limit)
}

// Desktop currently truncates message search to one result per chat when chatIDs
// is supplied. Search the relevant account(s) instead, then apply the exact chat
// filter client-side so CLI results are not silently incomplete.
const allowedChatIDs = new Set(resolvedChatIDs.map(String))
const accountIDs = new Set<string>()
let canScopeAccounts = true

for (const chatID of resolvedChatIDs) {
try {
const chat = await client.chats.retrieve(chatID)
if (chat?.id) allowedChatIDs.add(String(chat.id))
if (chat?.localChatID) allowedChatIDs.add(String(chat.localChatID))
if (chat?.accountID) accountIDs.add(String(chat.accountID))
const memberChatIDs = chat?.merge?.chatIDs
if (Array.isArray(memberChatIDs) && memberChatIDs.length) {
canScopeAccounts = false
for (const memberChatID of memberChatIDs) allowedChatIDs.add(String(memberChatID))
}
} catch {
// The resolver already identified this chat. Keep the resolved selector in
// the filter even if details cannot be loaded for account narrowing.
canScopeAccounts = false
}
}

const scopedAccountIDs = params.accountIDs?.length
? params.accountIDs
: canScopeAccounts && accountIDs.size
? Array.from(accountIDs)
: undefined

const safeParams = {
...params,
accountIDs: scopedAccountIDs,
chatIDs: undefined,
}

const items: any[] = []
for await (const message of client.messages.search(safeParams)) {
if (!allowedChatIDs.has(String(message?.chatID ?? ''))) continue
items.push(message)
if (items.length >= limit) break
}
return items
}
111 changes: 111 additions & 0 deletions packages/cli/test/messages-chat-search-integrity.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
import { fileURLToPath } from 'node:url'
import { describe, expect, it } from 'bun:test'

const cliRoot = fileURLToPath(new URL('..', import.meta.url))
const chatID = '!target:beeper.com'

describe('messages search chat integrity', () => {
it('avoids the server chatIDs truncation path and filters results client-side', async () => {
const searchQueries: URLSearchParams[] = []
const server = Bun.serve({
port: 0,
hostname: '127.0.0.1',
fetch(request) {
const url = new URL(request.url)
const path = decodeURIComponent(url.pathname)

if (path === `/v1/chats/${chatID}`) {
return Response.json({
id: chatID,
accountID: 'account-1',
network: 'WhatsApp',
participants: { hasMore: false, items: [], total: 0 },
title: 'Target',
type: 'single',
unreadCount: 0,
})
}

if (path === '/v1/messages/search') {
searchQueries.push(url.searchParams)
return Response.json({
items: [
{
id: 'target-1',
accountID: 'account-1',
chatID,
senderID: 'alice',
sortKey: '3',
timestamp: '2026-01-03T00:00:00Z',
text: 'invoice one',
},
{
id: 'other-1',
accountID: 'account-1',
chatID: '!other:beeper.com',
senderID: 'bob',
sortKey: '2',
timestamp: '2026-01-02T00:00:00Z',
text: 'invoice elsewhere',
},
{
id: 'target-2',
accountID: 'account-1',
chatID,
senderID: 'alice',
sortKey: '1',
timestamp: '2026-01-01T00:00:00Z',
text: 'invoice two',
},
],
hasMore: false,
oldestCursor: null,
newestCursor: null,
})
}

return Response.json({ message: 'not found' }, { status: 404 })
},
})

try {
const child = Bun.spawn([
process.execPath,
'./bin/dev.js',
'messages',
'search',
'invoice',
'--chat',
chatID,
'--limit',
'10',
'--base-url',
server.url.origin,
'--json',
], {
cwd: cliRoot,
env: {
...process.env,
BEEPER_ACCESS_TOKEN: 'test-token',
BEEPER_CLI_CONFIG_DIR: '/tmp/beeper-cli-bun-test',
BEEPER_NO_LOGO: '1',
},
stdout: 'pipe',
stderr: 'pipe',
})

expect(await child.exited).toBe(0)
const stdout = await new Response(child.stdout).text()
const envelope = JSON.parse(stdout)
expect(envelope.data.map((item: { id: string }) => item.id)).toEqual(['target-1', 'target-2'])

expect(searchQueries).toHaveLength(1)
const query = searchQueries[0]!
expect(query.has('chatIDs')).toBe(false)
expect(query.getAll('accountIDs')).toContain('account-1')
expect(query.get('query')).toBe('invoice')
} finally {
server.stop(true)
}
}, 20_000)
})