Skip to content
Merged
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
4 changes: 4 additions & 0 deletions CODEBASE.md
Original file line number Diff line number Diff line change
Expand Up @@ -185,6 +185,10 @@ don't duplicate it here.
`runSearch`, `printSearchResults`). See `docs/comms-search.md`.
- **`threads.ts`** — `fetchUnreadThreads`, `unreadFlags`; **`public-channels.ts`** —
public-channel id cache + `assertChannelIsPublic`.
- **`read-state.ts`** — `runReadStateMutation`, the loop behind every `mark-read` /
`mark-unread` command (bulk refs, `--stdin`, `--yes`, `--dry-run`, `--json`
rows, the per-workspace unread lookup). An entity plugs in through
`ReadStateEntity` (`THREAD_READ_STATE` in `commands/thread/helpers.ts`).
- **`spinner.ts`** — re-exports `LoadingSpinner`, `withSpinner`,
`startEarlySpinner`, `stopEarlySpinner` from cli-core.
- **`completion.ts`** — Commander tree-walker + `parseCompLine`, `getCompletions`,
Expand Down
210 changes: 21 additions & 189 deletions src/commands/thread/helpers.ts
Original file line number Diff line number Diff line change
@@ -1,23 +1,14 @@
import { requireConfirmation } from '@todoist/cli-core'
import type { CommsApi, Thread } from '@todoist/comms-sdk'
import type { Thread } from '@todoist/comms-sdk'
import chalk from 'chalk'
import { getCommsClient, getWorkspaceGroups, getWorkspaceUsers } from '../../lib/api.js'
import { getWorkspaceGroups, getWorkspaceUsers } from '../../lib/api.js'
import { formatRelativeDate } from '../../lib/dates.js'
import { CliError } from '../../lib/errors.js'
import { isAccessible } from '../../lib/global-args.js'
import { readStdinLines } from '../../lib/input.js'
import { renderMarkdown } from '../../lib/markdown.js'
import type { MutationOptions, StdinOptions } from '../../lib/options.js'
import {
colors,
DELETED_COMMENT_TEXT,
deletedBadge,
formatJson,
pinnedBadge,
pluralize,
} from '../../lib/output.js'
import { colors, DELETED_COMMENT_TEXT, deletedBadge, pinnedBadge } from '../../lib/output.js'
import { assertChannelIsPublic } from '../../lib/public-channels.js'
import type { ReadStateEntity } from '../../lib/read-state.js'
import { partitionNotifyIds, resolveThreadId } from '../../lib/refs.js'
import { fetchUnreadThreads } from '../../lib/threads.js'

export function printSeparator(label: string): void {
const totalWidth = 60
Expand Down Expand Up @@ -97,183 +88,24 @@ export function formatNotifyLabel(items: NamedEntity[]): string {
return items.map((i) => `${i.name} (${i.id})`).join(', ')
}

// Shared by `mark-read` and `mark-unread`: the bulk-ref loop, the per-workspace
// unread lookup, confirmation, and output. Each verb supplies a per-thread plan.

export type ReadStateTextStatus = 'changed' | 'preview' | 'unchanged'

export type ThreadReadState = {
thread: Thread
/**
* Object index of the last comment the user has read, or `null` when the
* thread is fully read (absent from the workspace's unread list). `-1`
* means nothing has been read, including the thread body.
*/
lastReadObjIndex: number | null
}

export type ReadStatePlan<Status> = {
/** Appended to messages, e.g. `' from comment X'`; empty for the whole thread. */
scope: string
isUnchanged(state: ThreadReadState): boolean
/** JSON row; `outcome` is `'unchanged'` when nothing needs to move. */
status(state: ThreadReadState, outcome: 'planned' | 'unchanged'): Status
/** Performs the mutation and returns the thread's new `lastReadObjIndex`. */
apply(client: CommsApi, state: ThreadReadState): Promise<number | null>
}

export type ReadStateMutation<Status> = {
verb: 'read' | 'unread'
/** Runs on the full ref list (positional plus `--stdin`) before anything is loaded. */
validateRefs?(rawRefs: string[]): void
/**
* Builds the per-thread plan. Runs before the unread lookup so an invalid
* option (a bad `--from` ref) fails without a workspace-wide request.
*/
plan(client: CommsApi, threadId: string): Promise<ReadStatePlan<Status>>
}

export async function runThreadReadStateMutation<Status extends { id: string }>(
refs: string[],
options: MutationOptions & StdinOptions,
mutation: ReadStateMutation<Status>,
): Promise<void> {
const rawRefs = await collectThreadRefs(refs, options)
if (rawRefs.length === 0) {
throw new CliError(
'INVALID_REF',
'No thread references provided. Pass refs as arguments, or pipe them in with --stdin.',
)
}
mutation.validateRefs?.(rawRefs)

// One thread runs without --yes; a bulk run needs it. The dry-run and
// preview output stays per thread, so only the guard is shared.
const needsConfirmation = rawRefs.length > 1 && !options.yes && !options.dryRun
if (needsConfirmation) {
requireConfirmation(options, { command: `tdc thread mark-${mutation.verb}` })
}

const client = await getCommsClient()
const unreadCache = new Map<number, Map<string, number>>()
const jsonStatuses: Status[] = []
const textStatuses: ReadStateTextStatus[] = []

for (const rawRef of rawRefs) {
const threadId = resolveThreadId(rawRef)
const plan = await mutation.plan(client, threadId)
const state = await loadThreadReadState(client, unreadCache, threadId)
const label = threadLabel(state.thread)

if (plan.isUnchanged(state)) {
jsonStatuses.push(plan.status(state, 'unchanged'))
textStatuses.push('unchanged')
if (!options.json) {
console.log(`Thread ${label} is already ${mutation.verb}${plan.scope}.`)
}
continue
}

if (needsConfirmation || options.dryRun) {
jsonStatuses.push(plan.status(state, 'planned'))
textStatuses.push('preview')
if (!options.json) {
const prefix = options.dryRun ? 'Dry run: would' : 'Would'
console.log(`${prefix} mark ${mutation.verb} thread ${label}${plan.scope}.`)
}
continue
}

const lastReadObjIndex = await plan.apply(client, state)
const unreadByThread = unreadCache.get(state.thread.workspaceId)
if (lastReadObjIndex === null) {
unreadByThread?.delete(threadId)
} else {
unreadByThread?.set(threadId, lastReadObjIndex)
}

jsonStatuses.push(plan.status(state, 'planned'))
textStatuses.push('changed')
if (!options.json) {
console.log(`Thread ${label} marked ${mutation.verb}${plan.scope}.`)
}
}

if (options.json) {
console.log(
formatJson(
options.dryRun
? jsonStatuses.map((status) => ({ ...status, dryRun: true }))
: jsonStatuses,
),
)
return
}

if (rawRefs.length > 1) {
printReadStateSummary(textStatuses)
}

if (needsConfirmation) {
console.log('Use --yes to confirm.')
}
}

async function collectThreadRefs(refs: string[], options: StdinOptions): Promise<string[]> {
const inlineRefs = refs.map((ref) => ref.trim()).filter(Boolean)
if (!options.stdin) return inlineRefs
return [...inlineRefs, ...(await readStdinLines())]
}

/**
* Loads a thread and its unread position. `unreadCache` maps a workspace id to
* its unread threads (`threadId` -> last read `objIndex`) so bulk runs fetch
* the unread list once per workspace.
*/
async function loadThreadReadState(
client: CommsApi,
unreadCache: Map<number, Map<string, number>>,
threadId: string,
): Promise<ThreadReadState> {
const thread = await client.threads.getThread(threadId)
await assertChannelIsPublic(thread.channelId, thread.workspaceId)

let unreadByThread = unreadCache.get(thread.workspaceId)
if (!unreadByThread) {
const unread = await client.threads.getUnread(thread.workspaceId)
unreadByThread = new Map(
unread.data.map((unreadThread) => [unreadThread.threadId, unreadThread.objIndex]),
)
unreadCache.set(thread.workspaceId, unreadByThread)
}

return { thread, lastReadObjIndex: unreadByThread.get(thread.id) ?? null }
/** Threads for the shared `mark-read` / `mark-unread` runner in `src/lib/read-state.ts`. */
export const THREAD_READ_STATE: ReadStateEntity<Thread> = {
noun: 'thread',
command: 'thread',
resolveId: resolveThreadId,
load: async (client, threadId) => {
const thread = await client.threads.getThread(threadId)
await assertChannelIsPublic(thread.channelId, thread.workspaceId)
return thread
},
workspaceId: (thread) => thread.workspaceId,
loadUnread: async (client, workspaceId) => {
const unread = await fetchUnreadThreads(client, workspaceId)
return new Map([...unread].map(([threadId, { objIndex }]) => [threadId, objIndex]))
},
label: threadLabel,
}

export function threadLabel(thread: Pick<Thread, 'id' | 'title'>): string {
return `${thread.title} (${thread.id})`
}

function printReadStateSummary(statuses: ReadStateTextStatus[]): void {
const summary = [
summarizeStatus(statuses, 'changed'),
summarizeStatus(statuses, 'unchanged'),
summarizeStatus(statuses, 'preview'),
].filter(Boolean)

console.log('')
console.log(`Summary: ${summary.join(', ')}`)
}

function summarizeStatus(
statuses: ReadStateTextStatus[],
status: ReadStateTextStatus,
): string | null {
const count = statuses.filter((value) => value === status).length
if (count === 0) {
return null
}

const noun = status === 'preview' ? pluralize(count, 'preview') : pluralize(count, 'thread')
return status === 'preview' ? `${count} ${noun}` : `${count} ${status} ${noun}`
}
9 changes: 5 additions & 4 deletions src/commands/thread/read.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import type { Thread } from '@todoist/comms-sdk'
import type { MutationOptions, StdinOptions } from '../../lib/options.js'
import { runThreadReadStateMutation } from './helpers.js'
import { runReadStateMutation } from '../../lib/read-state.js'
import { THREAD_READ_STATE } from './helpers.js'

export type MarkThreadReadOptions = MutationOptions & StdinOptions

Expand All @@ -13,16 +14,16 @@ export async function markThreadRead(
refs: string[],
options: MarkThreadReadOptions,
): Promise<void> {
await runThreadReadStateMutation<MarkReadStatus>(refs, options, {
await runReadStateMutation<Thread, MarkReadStatus>(THREAD_READ_STATE, refs, options, {
verb: 'read',
plan: async (_client, threadId) => ({
scope: '',
isUnchanged: (state) => state.lastReadObjIndex === null,
isUnchanged: (state) => state.unreadObjIndex === null,
status: () => ({ id: threadId, isRead: true }),
apply: async (client, state) => {
await client.threads.markRead({
id: threadId,
objIndex: getLatestObjIndex(state.thread),
objIndex: getLatestObjIndex(state.item),
})
return null
},
Expand Down
11 changes: 6 additions & 5 deletions src/commands/thread/unread.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import type { CommsApi } from '@todoist/comms-sdk'
import type { CommsApi, Thread } from '@todoist/comms-sdk'
import { CliError } from '../../lib/errors.js'
import type { MutationOptions, StdinOptions } from '../../lib/options.js'
import { runReadStateMutation } from '../../lib/read-state.js'
import { resolveCommentId } from '../../lib/refs.js'
import { runThreadReadStateMutation } from './helpers.js'
import { THREAD_READ_STATE } from './helpers.js'

export type MarkThreadUnreadOptions = MutationOptions & StdinOptions & { from?: string }

Expand All @@ -22,7 +23,7 @@ export async function markThreadUnread(
): Promise<void> {
const from = options.from

await runThreadReadStateMutation<MarkUnreadStatus>(refs, options, {
await runReadStateMutation<Thread, MarkUnreadStatus>(THREAD_READ_STATE, refs, options, {
verb: 'unread',
validateRefs: (rawRefs) => {
if (from !== undefined && rawRefs.length > 1) {
Expand All @@ -41,12 +42,12 @@ export async function markThreadUnread(
scope: from === undefined ? '' : ` from comment ${from}`,
// Already unread at or before the target: nothing to move.
isUnchanged: (state) =>
state.lastReadObjIndex !== null && state.lastReadObjIndex <= target,
state.unreadObjIndex !== null && state.unreadObjIndex <= target,
status: (state, outcome) => ({
id: threadId,
isRead: false,
lastReadObjIndex:
outcome === 'unchanged' ? (state.lastReadObjIndex ?? target) : target,
outcome === 'unchanged' ? (state.unreadObjIndex ?? target) : target,
}),
apply: async (client) => {
await client.threads.markUnread({ id: threadId, objIndex: target })
Expand Down
Loading