// Team comments from shared dbt docs, in Claude's context and in /comments. // // The open threads of the project's shared docs are fetched when the session starts (or when the first // model is read, for a project below the session folder) and, in an interactive session, every // `commentsPollSeconds`. When Claude reads or edits a model that has open threads, one context block // names each thread's line and text, so it sees the review before it changes the model; what other // people wrote is quoted as data. Replying and resolving are buttons the person presses in the // /comments pane; the plugin gives Claude no way to post (the person's own approved Bash call is outside it). import { atom, read, update } from 'claude-code' import type { Args, EngineInterface, EventResult, On, RenderElement, ToolCallResult } from 'claude-code' import type { CommentsState, CommentsThread } from '../../types' import { later, runTool } from '../altimate-cli' import { openTracked } from '../usage' import type { BashCall, ContextLines, EditedFile, FileCall } from '../tool-chain' import type { BandUi, FeatureContext } from './index' const COMMAND = 'comments' const PANE = 'altimate-comments' const PANE_TITLE = 'Team comments' const TOOL = 'docs_share_comments' // A call the CLI starts and waits on, so a stalled backend is cut off well before a poll's period. const LIST_TIMEOUT_MS = 45_000 const POST_TIMEOUT_MS = 45_000 const DEFAULT_POLL_SECONDS = 900 // What one context block carries at most, so a busy review never floods Claude's context. const MAX_THREADS_IN_CONTEXT = 8 const MAX_MESSAGE_CHARS = 600 const MAX_MESSAGES_PER_THREAD = 6 const MAX_FIELD_CHARS = 120 const MAX_BLOCK_CHARS = 6000 // The first read of a model waits this long for a load still in flight, so Claude sees the review before it edits. // The shared phase (tool-chain.ts) gives up at PHASE_TIMEOUT_MS and drops every feature's context, so this // stays well inside it, with room for the folder walk before. export const FIRST_READ_WAIT_MS = 3_000 // Files a docs thread can sit on: models, seeds, snapshots, their YAML and docs blocks. const MODEL_FILE = /\.(sql|ya?ml|py|md|csv)$/i const PARTIAL_NOTE = 'Not every open thread is listed: the service sent only part of the shares, or the list was cut for size.' const UNCONFIRMED_NOTE = 'An earlier post is not confirmed yet: press Refresh first.' const LOCKED_NOTE = ' The thread stays locked until the list shows the post or a few minutes have passed (the list can lag): press Refresh later.' const NOT_OPEN_NOTE = 'That thread is no longer open (it was resolved, or the list was behind): nothing was sent. The list is read again.' const ALREADY_RESOLVED_NOTE = 'Already resolved: the list was behind. It is hidden now.' const REFUSALS = new Set(['read_only', 'missing_text', 'missing_ids', 'unknown_thread', 'incomplete_list']) const MIN_POLL_SECONDS = 30 const MAX_POLL_SECONDS = 86_400 const NEEDS_NEWER_CLI = 'Team comments need a newer altimate-code (this one has no docs_share_comments tool): npm i -g @altimateai/altimate-code' const INITIAL: CommentsState = { root: null, project: null, threads: [], loadedAt: null, loading: false, needs: null, error: null, partial: null, note: null, drafts: {}, posting: null } const state = atom({ plugin: 'altimate-code', key: 'comments' } as const, null, { shape: 'comments-1' }) async function get($: EngineInterface): Promise { return (await read($, state)) ?? INITIAL } async function change($: EngineInterface, fn: (current: CommentsState) => CommentsState) { return update($, state, current => fn(current ?? INITIAL)) } let pollSeconds = DEFAULT_POLL_SECONDS let inContext = true let poll: { cancel: () => void } | null = null let interactive = true // One load at a time, and one posting at a time: set before the first await, so two presses in a row can't both start. let loadRun: Promise | null = null let loadAgain = false let posting = false // A load that began in an earlier session must not write into this one. let generation = 0 // Counts the posts that changed the shared docs: a list requested before one is out of date once it is done. let writes = 0 // The first-read wait is spent once per session. let firstWaitSpent = false // The project whose first load is scheduled but not started. let pendingFor: string | null = null // The thread of a post that may have landed: it stays busy until a list asked for after the post has been read. let uncertain: { key: string; action: unknown; text: string; root: string | null; at: number; before: Set } | null = null // The service lists from a cache that can be five minutes behind a post: a list does not show a post until // then, so a resolved thread stays hidden and an unchecked post stays locked until its effect is seen or that long has passed. const LIST_LAG_MS = 330_000 const resolvedAt = new Map() // Folders already searched for a dbt project in vain. const searched = new Set() // Folders known to hold no project of their own, each with the loaded project it was looked at from. const within = new Set() /** The `commentsPollSeconds` (never under 30 s) and `commentsInContext` settings. */ export function readOptions(options: Record): { pollSeconds: number; inContext: boolean } { const seconds = options.commentsPollSeconds return { pollSeconds: typeof seconds === 'number' && seconds > 0 ? Math.min(MAX_POLL_SECONDS, Math.max(MIN_POLL_SECONDS, seconds)) : DEFAULT_POLL_SECONDS, inContext: options.commentsInContext !== false, } } /** Adds this feature's own hooks. */ export function register(on: On, context: FeatureContext) { const settings = readOptions(context.options as Record) pollSeconds = settings.pollSeconds inContext = settings.inContext on('command.run', { command: COMMAND }, async $ => { try { await openCommentsPane($) // Running the command again is how a missing tool is looked for again, after an update. await change($, current => ({ ...current, needs: null, note: null })) later($, () => open($)) return { text: 'Team comments opened in the side pane.' } } catch (error) { return { text: `Could not open team comments: ${String(error)}` } } }) on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => { const ui = $.ui.resolve(e) const { Box, Button, Text } = ui // The mobile app draws no field yet: there a thread is shown, not answered. const Input = 'Input' in ui ? ui.Input : null const current = await get($) if (current.needs) { return ( {current.needs} ) } const groups = groupByModel(current.threads) return ( Team comments{current.project ? ` · ${current.project}` : ''} {current.loading ? 'Loading…' : current.threads.length === 0 ? 'No open threads.' : `${current.threads.length} open thread${current.threads.length === 1 ? '' : 's'}`} {current.root === null && No dbt project found yet.} {current.error && {current.error}} {current.partial && {current.partial}} {current.note && {current.note}} {groups.map(group => ( {group.label} {group.threads.map(thread => { const key = `${thread.shareId}:${thread.groupId}` const busy = current.posting === key const draft = current.drafts[key] ?? '' return ( {' '} {thread.column ? `column ${thread.column}` : thread.field ?? 'model'} {thread.range ? ` · line ${thread.range.start.line + 1}` : ''} {thread.highlight ? ` · “${clip(thread.highlight, 60)}”` : ''} {thread.messages.map(message => ( {' '} {message.author}: {clip(message.text, MAX_MESSAGE_CHARS)} ))} {busy ? ( {' '}Posting… ) : ( {Input === null ? null : ( { void change($, now => ({ ...now, drafts: { ...now.drafts, [key]: value } })) }} onSubmit={(value: string) => later($, () => reply($, thread, value))} /> )} {Input !== null &&