From 7a06428a531b1eabe3e62f7e845a244409dd1c3c Mon Sep 17 00:00:00 2001 From: Harish Kumar Date: Fri, 13 Nov 2026 17:01:21 +0530 Subject: [PATCH 01/29] feat: team comments from shared dbt docs in Claude's context and a /comments pane Co-Authored-By: Claude Sonnet 5.5 --- plugins/altimate-code/hooks/comments.test.tsx | 149 +++++++ .../altimate-code/hooks/features/comments.tsx | 369 +++++++++++++++++- plugins/altimate-code/types/index.d.ts | 34 +- 3 files changed, 533 insertions(+), 19 deletions(-) create mode 100644 plugins/altimate-code/hooks/comments.test.tsx diff --git a/plugins/altimate-code/hooks/comments.test.tsx b/plugins/altimate-code/hooks/comments.test.tsx new file mode 100644 index 00000000..b1258a7f --- /dev/null +++ b/plugins/altimate-code/hooks/comments.test.tsx @@ -0,0 +1,149 @@ +import { expect, mock, test } from 'claude-code/testing' + +import { contextBlock, groupByModel, placeThread, projectName, relativePath, threadsOnFile, toThread } from './features/comments' + +const ROOT = '/repo' +const FILE = `${ROOT}/models/orders.sql` +const SQL = 'select\n id,\n sum(amount) as revenue\nfrom payments\ngroup by 1\n' + +const RAW = { + share_id: 7, + share_name: 'Finance review', + group_id: 11, + file_path: 'models/orders.sql', + highlight: 'sum(amount)', + range: { start: { line: 0, character: 0 }, end: { line: 0, character: 4 } }, + messages: [ + { id: 100, author: 'Ada Lovelace', text: 'Is this net of refunds?' }, + { id: 101, author: 'Grace Hopper', text: 'No, gross.' }, + ], +} + +const PANE = { + plugin: 'altimate-code', + component: 'Pane', + requestId: 'altimate-comments', + props: { title: 'Team comments', isFocused: false, bodyColumns: 80, placement: 'dock', scroll: { offset: 0, bodyRows: 30 }, view: {} }, +} as const + +/** A dbt project at /repo whose CLI answers docs_share_comments from `threads`; each tool call is recorded. */ +async function start($: any, on: any, options: { threads?: unknown[]; noTool?: boolean; failPost?: boolean } = {}) { + const clock = mock.clock(on) + const cli: { args: Record; write: boolean }[] = [] + on('command.register', () => ({ value: { command: 'comments' } })) + on('turn.start', (_: unknown, e: { turnId: string }) => ({ turnId: e.turnId })) + on('session.end', () => ({ sessionId: 'test' })) + on('turn.complete', (_: unknown, e: { answer: string }) => ({ text: e.answer })) + on('session.start', (_: unknown, e: { cwd: string }) => ({ cwd: e.cwd })) + on('session.root', () => ({ value: ROOT })) + on('ui.open', () => ({ value: {} })) + on('ui.toast', () => ({ value: undefined })) + on('ui.log', () => ({ value: undefined })) + on('fs.exists', (_: unknown, e: { path: string }) => ({ value: e.path === `${ROOT}/dbt_project.yml` })) + on('fs.stat', () => ({ value: { kind: 'file', size: 10, mtimeMs: 1, isLink: false } })) + on('fs.read', (_: unknown, e: { path: string }) => { + if (e.path === `${ROOT}/dbt_project.yml`) return { value: "name: 'jaffle_shop'\nversion: '1.0'\n" } + if (e.path === FILE) return { value: SQL } + throw new Error('ENOENT') + }) + on('process.run', (_: unknown, e: { argv: readonly string[] }) => { + const [, command, , tool] = e.argv + if (command !== 'tool') return { value: { exitCode: 1, stdout: '', stderr: 'not this test' } } + if (options.noTool) return { value: { exitCode: 1, stdout: JSON.stringify({ status: 'error', output: 'Unknown tool: docs_share_comments', metadata: {} }), stderr: '' } } + const args = JSON.parse(String(e.argv[e.argv.indexOf('--args') + 1] ?? '{}')) + cli.push({ args: { tool, ...args }, write: e.argv.includes('--allow-write') }) + if (args.action === 'list') { + return { value: { exitCode: 0, stdout: JSON.stringify({ status: 'ok', output: '', metadata: { success: true, threads: options.threads ?? [RAW] } }), stderr: '' } } + } + if (options.failPost) return { value: { exitCode: 0, stdout: JSON.stringify({ status: 'ok', output: 'posting needs write permission', metadata: { success: false } }), stderr: '' } } + return { value: { exitCode: 0, stdout: JSON.stringify({ status: 'ok', output: 'done', metadata: { success: true } }), stderr: '' } } + }) + on('tool.call', () => ({ result: { ok: true } })) + await $.session.start({ cwd: ROOT, surface: 'terminal', isInteractive: true }) + await clock.settle() + return { clock, cli } +} + +test('a thread is placed on the line holding its highlighted text, else on its stored range', () => { + const thread = toThread(RAW)! + // The model was edited since the comment: the stored range (line 1) is stale, the highlight is on line 3. + expect(placeThread(thread, SQL)).toBe(3) + expect(placeThread(thread, 'select 1')).toBe(1) + expect(placeThread({ ...thread, highlight: undefined, range: undefined }, SQL)).toBeNull() +}) + +test('threads are matched to a file by project-relative path and grouped by model', () => { + const a = toThread(RAW)! + const b = toThread({ ...RAW, group_id: 12, file_path: 'models/customers.sql' })! + expect(relativePath(ROOT, FILE)).toBe('models/orders.sql') + expect(threadsOnFile([a, b], ROOT, FILE)).toEqual([a]) + expect(groupByModel([a, b]).map(g => g.label)).toEqual(['models/customers.sql', 'models/orders.sql']) + expect(toThread({ group_id: 1 })).toBeNull() + expect(projectName("name: 'jaffle_shop'\n")).toBe('jaffle_shop') +}) + +test('the context block names each thread line, target and message, and caps a long review', () => { + const thread = toThread(RAW)! + const block = contextBlock('models/orders.sql', [thread], SQL) + expect(block).toContain('Open team comments on models/orders.sql') + expect(block).toContain('line 3, model, on “sum(amount)”') + expect(block).toContain('Ada Lovelace: Is this net of refunds?') + const many = Array.from({ length: 10 }, (_, i) => ({ ...thread, groupId: i })) + expect(contextBlock('models/orders.sql', many, SQL)).toContain('and 2 more open threads') +}) + +test('reading a model with open threads adds the thread lines to Claude’s context', async ($, on) => { + const { clock, cli } = await start($, on) + expect(cli).toEqual([{ args: { tool: 'docs_share_comments', action: 'list', project: 'jaffle_shop' }, write: false }]) + const result: any = await $.tool.call({ tool: 'Read', file_path: FILE }) + await clock.settle() + expect(result.context?.[0]).toContain('line 3, model, on “sum(amount)”') + expect(result.context?.[0]).toContain('Grace Hopper: No, gross.') + + // A model with no threads adds nothing. + const other: any = await $.tool.call({ tool: 'Read', file_path: `${ROOT}/models/customers.sql` }) + expect(other.context ?? []).toEqual([]) +}) + +test('the list is fetched again every commentsPollSeconds', async ($, on) => { + const { clock, cli } = await start($, on) + await clock.advance(900_000) + await clock.settle() + expect(cli.filter(c => c.args.action === 'list').length).toBeGreaterThanOrEqual(2) +}) + +test('the pane shows threads by model; Reply and Resolve go through the CLI with write permission', async ($, on) => { + const { clock, cli } = await start($, on) + const ui = await $.ui.mount({ ...PANE, surface: 'terminal' }) + await clock.settle() + expect(await ui.find({ type: 'Text', text: 'models/orders.sql' })).toBeDefined() + expect(await ui.find({ type: 'Text', text: /Is this net of refunds\?/ })).toBeDefined() + + await ui.press({ key: '7:11-resolve' }) + await clock.settle() + const resolved = cli.find(c => c.args.action === 'resolve') + expect(resolved).toEqual({ args: { tool: 'docs_share_comments', share_id: 7, group_id: 11, action: 'resolve' }, write: true }) + await ui.unmount() +}) + +test('a CLI without the tool shows one line naming the version needed, and no error loop', async ($, on) => { + const { clock, cli } = await start($, on, { noTool: true }) + const ui = await $.ui.mount({ ...PANE, surface: 'terminal' }) + await clock.settle() + expect(await ui.find({ type: 'Text', text: /newer altimate-code than 0\.12\.10/ })).toBeDefined() + await clock.advance(900_000) + await clock.settle() + expect(cli).toEqual([]) + await ui.unmount() +}) + +test('a refused post keeps the threads and shows why', async ($, on) => { + const { clock } = await start($, on, { failPost: true }) + const ui = await $.ui.mount({ ...PANE, surface: 'terminal' }) + await clock.settle() + await ui.press({ key: '7:11-resolve' }) + await clock.settle() + expect(await ui.find({ type: 'Text', text: /posting needs write permission/ })).toBeDefined() + expect(await ui.find({ type: 'Text', text: /Is this net of refunds\?/ })).toBeDefined() + await ui.unmount() +}) diff --git a/plugins/altimate-code/hooks/features/comments.tsx b/plugins/altimate-code/hooks/features/comments.tsx index f94411ed..382a6b65 100644 --- a/plugins/altimate-code/hooks/features/comments.tsx +++ b/plugins/altimate-code/hooks/features/comments.tsx @@ -1,49 +1,382 @@ // Team comments from shared dbt docs, in Claude's context and in /comments. // -// The plugin calls each function below at its moment, in the order features/index.ts fixes; one with -// nothing to do stays a no-op. This feature's own hooks (its commands and panes, each under a matcher -// no other part uses) go in `register`. The events the whole plugin shares (session start and end, -// turns, Bash and file tool calls, the band) come through the other functions, since a plugin hooks -// each of those once. The status-line part is set with `setStatusPart($, 'comments', text)`. +// The open threads of the project's shared docs are fetched when the session starts and 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. Replying and +// resolving are buttons the person presses in the /comments pane; Claude never posts. +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 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 NEEDS_NEWER_CLI = 'Team comments need a newer altimate-code than 0.12.10 (it has no docs_share_comments tool): npm install -g altimate-code@latest' + +const INITIAL: CommentsState = { root: null, project: null, threads: [], loadedAt: null, loading: false, needs: null, note: null, drafts: {}, posting: null } + +const state = atom({ plugin: 'altimate-code', key: 'comments' } as const, null as CommentsState | null) + +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 + /** Adds this feature's own hooks. */ -export function register(on: On, context: FeatureContext) {} +export function register(on: On, context: FeatureContext) { + const options = context.options as Record + pollSeconds = typeof options.commentsPollSeconds === 'number' && options.commentsPollSeconds >= 30 ? options.commentsPollSeconds : DEFAULT_POLL_SECONDS + inContext = options.commentsInContext !== false + + on('command.run', { command: COMMAND }, async $ => { + try { + await $.ui.open({ id: PANE, title: PANE_TITLE, focus: true, closeOnEscape: true }) + // Running the command again is how a missing tool is looked for again, after an update. + await change($, current => ({ ...current, needs: null })) + later($, () => load($)) + 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($) -/** After the session started: the place to register commands. */ -export async function sessionStart($: EngineInterface, e: Args<'session.start'>) {} + 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.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 &&