Skip to content
Draft
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
87 changes: 78 additions & 9 deletions src/commands/inbox.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<typeof vi.fn>
getInbox?: ReturnType<typeof vi.fn>
getUnread?: ReturnType<typeof vi.fn>
Expand All @@ -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', () => {
Expand Down Expand Up @@ -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',
Expand All @@ -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()
})
})
Expand All @@ -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')
})
Expand All @@ -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<typeof vi.spyOn>

beforeEach(() => {
vi.clearAllMocks()
apiMocks.getCurrentWorkspaceId.mockResolvedValue(1)
logSpy = captureConsole('log')
})

function channelNamesByThread(): Record<string, unknown> {
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()
Expand Down Expand Up @@ -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')
})
Expand Down
16 changes: 11 additions & 5 deletions src/commands/inbox.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'

Expand Down Expand Up @@ -80,11 +80,17 @@ async function showInbox(workspaceRef: string | undefined, options: InboxOptions

let channelMap = new Map<string, string>()
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) {
Expand Down
17 changes: 9 additions & 8 deletions src/lib/public-channels.ts
Original file line number Diff line number Diff line change
@@ -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<number, Map<string, boolean>>()
const joinedChannelCache = new Map<number, Channel[]>()
const workspacePublicChannelCache = new Map<number, Set<string>>()

async function getJoinedChannels(workspaceId: number): Promise<Map<string, boolean>> {
/** The channels the user has joined, with their names. One request per workspace. */
export async function getJoinedChannels(workspaceId: number): Promise<Channel[]> {
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<Set<string>> {
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
Expand All @@ -44,7 +45,7 @@ export function clearPublicChannelCache(): void {
async function isPublicChannel(channelId: string, workspaceId: number): Promise<boolean> {
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)
)
Expand Down
Loading