From d4133835a700ea5854f813f7823b2dea6fd49fc1 Mon Sep 17 00:00:00 2001 From: Rory O'Keeffe Date: Wed, 18 Nov 2026 13:47:24 +0000 Subject: [PATCH] perf(inbox): look up channel names with one call tdc inbox asked the server for each inbox channel one at a time, just to show its name. With 24 channels in the inbox, a script running the command every few seconds used up the per-user rate limit for channels/getone, and the user's own apps started getting 429s too. The public-channel check already fetches the workspace's channel list, which has the names. I now keep that list instead of only the public ids, and read the names from it. A channel missing from the list (one the user has left) still gets looked up by itself. Co-Authored-By: Claude Opus 5.5 --- src/commands/inbox.test.ts | 87 ++++++++++++++++++++++++++++++++++---- src/commands/inbox.ts | 16 ++++--- src/lib/public-channels.ts | 17 ++++---- 3 files changed, 98 insertions(+), 22 deletions(-) diff --git a/src/commands/inbox.test.ts b/src/commands/inbox.test.ts index 51c6705..edb202a 100644 --- a/src/commands/inbox.test.ts +++ b/src/commands/inbox.test.ts @@ -24,19 +24,22 @@ vi.mock('../lib/global-args.js', async (importOriginal) => ({ includePrivateChannels: vi.fn().mockReturnValue(true), })) -vi.mock('../lib/public-channels.js', () => ({ - getPublicChannelIds: vi.fn(), -})) - vi.mock('chalk') +import { includePrivateChannels } from '../lib/global-args.js' +import { clearPublicChannelCache } from '../lib/public-channels.js' import { registerInboxCommand } from './inbox.js' const createProgram = () => createTestProgram(registerInboxCommand) +beforeEach(() => { + clearPublicChannelCache() +}) + function mockClient(overrides: { inboxThreads?: unknown[] unreadData?: unknown[] + channels?: unknown[] getChannel?: ReturnType getInbox?: ReturnType getUnread?: ReturnType @@ -45,13 +48,14 @@ function mockClient(overrides: { const getUnread = overrides.getUnread ?? vi.fn().mockResolvedValue({ data: overrides.unreadData ?? [], version: 1 }) + const getChannels = vi.fn().mockResolvedValue(overrides.channels ?? []) const getChannel = overrides.getChannel ?? vi.fn() apiMocks.getCommsClient.mockResolvedValue({ inbox: { getInbox }, threads: { getUnread }, - channels: { getChannel }, + channels: { getChannels, getChannel }, }) - return { getInbox, getUnread, getChannel } + return { getInbox, getUnread, getChannels, getChannel } } describe('inbox --workspace conflict', () => { @@ -134,7 +138,7 @@ describe('inbox --ids-only', () => { it('outputs thread IDs without fetching channel names when no channel filter is set', async () => { vi.clearAllMocks() apiMocks.getCurrentWorkspaceId.mockResolvedValue(1) - const { getChannel } = mockClient({ + const { getChannels, getChannel } = mockClient({ inboxThreads: [ { id: 'thread-1', @@ -157,6 +161,7 @@ describe('inbox --ids-only', () => { await createProgram().parseAsync(['node', 'tdc', 'inbox', '--ids-only']) expect(consoleSpy).toHaveBeenCalledWith('thread-1\nthread-2') + expect(getChannels).not.toHaveBeenCalled() expect(getChannel).not.toHaveBeenCalled() }) }) @@ -176,7 +181,7 @@ describe('inbox empty output (channel filter)', () => { } mockClient({ inboxThreads: [thread], - getChannel: vi.fn().mockResolvedValue({ id: 'CH10', name: 'engineering' }), + channels: [{ id: 'CH10', name: 'engineering', public: true }], }) logSpy = captureConsole('log') }) @@ -190,6 +195,70 @@ describe('inbox empty output (channel filter)', () => { }) }) +describe('inbox channel names', () => { + const threadIn = (channelId: string) => ({ + id: `thread-${channelId}`, + channelId, + title: channelId, + posted: '2026-05-01T00:00:00Z', + url: `https://example.test/thread-${channelId}`, + }) + let logSpy: ReturnType + + beforeEach(() => { + vi.clearAllMocks() + apiMocks.getCurrentWorkspaceId.mockResolvedValue(1) + logSpy = captureConsole('log') + }) + + function channelNamesByThread(): Record { + const output = JSON.parse(logSpy.mock.calls[0]?.[0] as string) as Array<{ + id: string + channelName: unknown + }> + return Object.fromEntries(output.map((t) => [t.id, t.channelName])) + } + + it('reuses the public-channel list for names without per-channel lookups', async () => { + vi.mocked(includePrivateChannels).mockReturnValueOnce(false) + const { getChannels, getChannel } = mockClient({ + inboxThreads: [threadIn('CH1'), threadIn('CH2'), threadIn('CH3')], + channels: [ + { id: 'CH1', name: 'engineering', public: true }, + { id: 'CH2', name: 'design', public: true }, + { id: 'CH3', name: 'secret', public: false }, + ], + }) + + await createProgram().parseAsync(['node', 'tdc', 'inbox', '--json', '--full']) + + expect(channelNamesByThread()).toEqual({ + 'thread-CH1': 'engineering', + 'thread-CH2': 'design', + }) + expect(getChannels).toHaveBeenCalledTimes(1) + expect(getChannel).not.toHaveBeenCalled() + }) + + it('looks up only the channels missing from the list', async () => { + const { getChannels, getChannel } = mockClient({ + inboxThreads: [threadIn('CH1'), threadIn('CH-left')], + channels: [{ id: 'CH1', name: 'engineering', public: true }], + getChannel: vi.fn().mockResolvedValue({ id: 'CH-left', name: 'old-team' }), + }) + + await createProgram().parseAsync(['node', 'tdc', 'inbox', '--json', '--full']) + + expect(channelNamesByThread()).toEqual({ + 'thread-CH1': 'engineering', + 'thread-CH-left': 'old-team', + }) + expect(getChannels).toHaveBeenCalledTimes(1) + expect(getChannel).toHaveBeenCalledTimes(1) + expect(getChannel).toHaveBeenCalledWith('CH-left') + }) +}) + describe('inbox API errors', () => { it('propagates SDK rejections through the Promise.all that replaced batch', async () => { vi.clearAllMocks() @@ -249,7 +318,7 @@ describe('inbox unread mentions', () => { mockClient({ inboxThreads: threads, unreadData, - getChannel: vi.fn().mockResolvedValue({ id: 'CH1', name: 'engineering' }), + channels: [{ id: 'CH1', name: 'engineering', public: true }], }) logSpy = captureConsole('log') }) diff --git a/src/commands/inbox.ts b/src/commands/inbox.ts index 5cdd546..2ff2099 100644 --- a/src/commands/inbox.ts +++ b/src/commands/inbox.ts @@ -9,7 +9,7 @@ import { CliError } from '../lib/errors.js' import { includePrivateChannels, isAccessible } from '../lib/global-args.js' import { toDate, type PaginatedViewOptions } from '../lib/options.js' import { colors, formatJson, formatNdjson } from '../lib/output.js' -import { getPublicChannelIds } from '../lib/public-channels.js' +import { getPublicChannelIds, getJoinedChannels } from '../lib/public-channels.js' import { resolveWorkspaceRef } from '../lib/refs.js' import { fetchUnreadThreads, unreadFlags } from '../lib/threads.js' @@ -80,11 +80,17 @@ async function showInbox(workspaceRef: string | undefined, options: InboxOptions let channelMap = new Map() if (outputMode !== 'ids-only' || options.channel) { - const channelIds = [...new Set(inboxThreads.map((t) => t.channelId))] - const channelEntries = await Promise.all( - channelIds.map(async (id) => [id, await client.channels.getChannel(id)] as const), + const channels = await getJoinedChannels(workspaceId) + channelMap = new Map(channels.map((ch) => [ch.id, ch.name])) + // The list only has channels the user is a member of, but an inbox thread can sit + // in one they've left, so look those up one by one. + const unlistedIds = [...new Set(inboxThreads.map((t) => t.channelId))].filter( + (id) => !channelMap.has(id), ) - channelMap = new Map(channelEntries.map(([id, channel]) => [id, channel.name])) + const unlisted = await Promise.all( + unlistedIds.map(async (id) => [id, await client.channels.getChannel(id)] as const), + ) + for (const [id, channel] of unlisted) channelMap.set(id, channel.name) } if (options.channel) { diff --git a/src/lib/public-channels.ts b/src/lib/public-channels.ts index 9a53f85..84bdb53 100644 --- a/src/lib/public-channels.ts +++ b/src/lib/public-channels.ts @@ -1,26 +1,27 @@ +import type { Channel } from '@todoist/comms-sdk' + import { getCommsClient } from './api.js' import { CliError } from './errors.js' import { includePrivateChannels } from './global-args.js' -// Channel ID to whether it's public, for the channels the user has joined. -const joinedChannelCache = new Map>() +const joinedChannelCache = new Map() const workspacePublicChannelCache = new Map>() -async function getJoinedChannels(workspaceId: number): Promise> { +/** The channels the user has joined, with their names. One request per workspace. */ +export async function getJoinedChannels(workspaceId: number): Promise { const cached = joinedChannelCache.get(workspaceId) if (cached) return cached const client = await getCommsClient() const channels = await client.channels.getChannels({ workspaceId }) - const joined = new Map(channels.map((ch) => [ch.id, ch.public])) - joinedChannelCache.set(workspaceId, joined) - return joined + joinedChannelCache.set(workspaceId, channels) + return channels } /** IDs of the public channels the user has joined. */ export async function getPublicChannelIds(workspaceId: number): Promise> { const joined = await getJoinedChannels(workspaceId) - return new Set([...joined].filter(([, isPublic]) => isPublic).map(([id]) => id)) + return new Set(joined.filter((ch) => ch.public).map((ch) => ch.id)) } // Every public channel in the workspace, joined or not. Much bigger than the joined list (all @@ -44,7 +45,7 @@ export function clearPublicChannelCache(): void { async function isPublicChannel(channelId: string, workspaceId: number): Promise { const joined = await getJoinedChannels(workspaceId) return ( - joined.get(channelId) ?? + joined.find((ch) => ch.id === channelId)?.public ?? // getChannels only returns joined channels, so an unjoined one could still be public. (await getWorkspacePublicChannelIds(workspaceId)).has(channelId) )