feat(neovim): make a pivi tool call as legible as the work it did
d40c346f5269628f7f8f7809790b847b0f1a562b
Oliver Krylow <o.krylow@isp-insoft.de> ·
SSH signature · not checked
- Parent 1: 50d905fcddb4
bugabingas dorkfiles
d40c346f5269628f7f8f7809790b847b0f1a562b
Oliver Krylow <o.krylow@isp-insoft.de> ·
SSH signature · not checked
+1219 / −54 text lines
+12 / −1 text lines
20. **Never force a parse per streamed delta.** Markdown rendering is `vim.treesitter.start` and stays redraw-driven; a forced parse per delta measured roughly five hundred times slower.21. **Contract tests guard assumptions,** not features. They skip unless `pi` is on `PATH` and opt-in is set. When Pi changes behavior, they fail before users do.21. **Never invent an outcome.** `bugabinga.pivi.tool` derives everything from what a tool reported in its result details, and a tool that reported nothing gets no outcome, no language, and no change. Pi reports a change on every `edit`, progress on `bash`, and truncation only at a limit; `write` reports nothing at all. Every interpretation needs a spec for the reporting tool and a spec for the silent one.22. **Entry shape changes without the buffer changing.** Re-anchoring an entry moves its bounds while touching no character, so anything cached per buffer must key on `entry.version` as well as `b:changedtick`. A fold cache keyed on the tick alone silently goes stale the moment an entry is rewritten.23. **Contract tests guard assumptions,** not features. They skip unless `pi` is on `PATH` and opt-in is set. When Pi changes behavior, they fail before users do.| Transcript keys | buffer-local only, plus a `<Plug>` mapping; Neovim already ships `]m` and `[m` globally, so assert on mapping descriptions rather than on the absence of a key || Folds | one fold per entry through `foldexpr`; appended text does not recompute folds until a redraw, so `apply` runs `zX` first and then drives folds from recorded intent || Tool outcome | end-of-line virtual text on the entry's opening line, and repeated in the fold line so a collapsed entry stays useful || Reported change | written as the tool formatted it and highlighted with `DiffAdd`/`DiffDelete` per line; `bugabinga.pivi.diff` rebuilds the prior content from the change itself and states when the file has moved on || Streaming output | rewrite only the entry tail, skip per-line decoration while it runs, and never run `fold.apply` mid-stream || Output language | parsed as a standalone string and applied as highlight extmarks, never as a fence, so transcript text stays what the tool produced |+18 / −0 text lines
local comparison = require 'bugabinga.pivi.diff'subcommands.diff = function() local bufnr = vim.api.nvim_get_current_buf() if vim.bo[bufnr].filetype ~= transcript.filetype then notify( 'move the cursor into a transcript first', vim.log.levels.WARN ) return end local changed, _, faithful = comparison.open( bufnr ) if not changed then notify( 'this entry reports no change to compare', vim.log.levels.WARN ) return end if faithful == false then notify( 'the file has moved on since this change', vim.log.levels.WARN ) endendnew file mode 100644+136 / −0 text lines
local entry = require 'bugabinga.pivi.entry'local navigate = require 'bugabinga.pivi.navigate'local tool = require 'bugabinga.pivi.tool'local state = { window = nil, buffer = nil, }--- Reads a reported change back into the lines it added and removed.--- The tool numbers every changed line, so the change can be undone on the--- content it produced.local parse = function( change ) local removed, added = {}, {} for _, line in ipairs( vim.split( change or '', '\n', { plain = true, } ) ) do local mark = line:sub( 1, 1 ) local number, text = line:sub( 2 ):match '^%s*(%d+) (.*)$' if number then local record = { line = tonumber( number ), text = text, } if mark == '+' then table.insert( added, record ) elseif mark == '-' then table.insert( removed, record ) end end end return removed, addedend--- The content that existed before a change, rebuilt from the change itself.--- @return string[] lines--- @return boolean faithful whether the content still matches what was changedlocal before = function( current, change ) local removed, added = parse( change ) local lines = vim.deepcopy( current ) local faithful = true for _, record in ipairs( added ) do if lines[record.line] ~= record.text then faithful = false end end local descending = vim.deepcopy( added ) table.sort( descending, function( left, right ) return left.line > right.line end ) for _, record in ipairs( descending ) do if lines[record.line] ~= nil then table.remove( lines, record.line ) end end local ascending = vim.deepcopy( removed ) table.sort( ascending, function( left, right ) return left.line < right.line end ) for _, record in ipairs( ascending ) do table.insert( lines, math.min( record.line, #lines + 1 ), record.text ) end return lines, faithfulendlocal close = function() if state.window and vim.api.nvim_win_is_valid( state.window ) then pcall( vim.api.nvim_win_call, state.window, function() vim.cmd 'diffoff' end ) pcall( vim.api.nvim_win_close, state.window, true ) end if state.buffer and vim.api.nvim_buf_is_valid( state.buffer ) then pcall( vim.api.nvim_buf_delete, state.buffer, { force = true, } ) end state.window, state.buffer = nil, nilend--- Opens a completed change as an editor comparison.--- The change is compared against the content the tool produced, so ordinary--- diff motions and diff folds apply.--- @return number? changed the window showing the file--- @return number? original the window showing the content before the change--- @return boolean? faithful whether the file still matches what was changedlocal open = function( bufnr, line_number ) local item = entry.at( bufnr, line_number or vim.api.nvim_win_get_cursor( 0 )[1] ) if not item or item.kind ~= 'tool' then return nil end local change = tool.diff( item.meta ) local location = navigate.location_of( item ) if not change or not location then return nil end local working = vim.api.nvim_get_current_win() local changed = navigate.locate( bufnr, item.first ) if not changed then return nil end close() local target = vim.api.nvim_win_get_buf( changed ) local current = vim.api.nvim_buf_get_lines( target, 0, -1, false ) local original, faithful = before( current, change ) state.buffer = vim.api.nvim_create_buf( false, true ) vim.bo[state.buffer].buftype = 'nofile' vim.bo[state.buffer].bufhidden = 'wipe' vim.bo[state.buffer].swapfile = false vim.api.nvim_buf_set_lines( state.buffer, 0, -1, false, original ) vim.bo[state.buffer].modifiable = false vim.bo[state.buffer].filetype = vim.bo[target].filetype local label = 'pivi://' .. vim.fs.basename( location.path ) .. '/before' if not faithful then label = label .. ' (the file has moved on)' end pcall( vim.api.nvim_buf_set_name, state.buffer, label ) local opened = pcall( vim.api.nvim_win_call, changed, function() vim.cmd 'diffthis' vim.cmd 'leftabove vsplit' vim.api.nvim_win_set_buf( 0, state.buffer ) vim.cmd 'diffthis' state.window = vim.api.nvim_get_current_win() end ) if not opened then close() return nil end if vim.api.nvim_win_is_valid( working ) then vim.api.nvim_set_current_win( working ) end return changed, state.window, faithfulendlocal bind = function( bufnr ) local action = function() open( bufnr ) end vim.keymap.set( 'n', 'gD', action, { buffer = bufnr, desc = 'pivi compare the change of the entry', } ) vim.keymap.set( 'n', '<Plug>(pivi-compare-change)', action, { buffer = bufnr, desc = 'pivi compare the change of the entry', } )endrequire( 'bugabinga.pivi.transcript' ).on_buffer( bind )return { parse = parse, before = before, open = open, close = close, bind = bind,}+31 / −0 text lines
local versions = {}--- Bumped whenever the entries of a buffer change shape.--- Buffer text alone is not enough to know that: re-anchoring an entry moves--- its bounds without touching a single character.local version = function( bufnr ) return versions[bufnr] or 0endlocal touch = function( bufnr ) versions[bufnr] = version( bufnr ) + 1end touch( bufnr ) touch( bufnr )--- Replaces everything an entry shows below its opening line.--- A tool that reports progress rewrites its own tail, so the entry keeps its--- identity and its bounds while its content changes.local rewrite = function( bufnr, id, text ) if not id or not vim.api.nvim_buf_is_valid( bufnr ) then return end if not of_buffer( bufnr )[id] then return end local first = start_row( bufnr, id ) if not first then return end transcript.replace( bufnr, first + 1, content_row( bufnr, first ) + 1, text ) extend( bufnr, id )end versions[bufnr] = nil version = version, rewrite = rewrite,+15 / −2 text lines
local tool = require 'bugabinga.pivi.tool' local shape = entry.version( bufnr ) if cached and cached.tick == tick then return cached.rows end if cached and cached.tick == tick and cached.shape == shape then return cached.rows end levels[bufnr] = { tick = tick, rows = rows, } levels[bufnr] = { tick = tick, shape = shape, rows = rows, }+4 / −0 text lines
+7 / −2 text lines
+73 / −3 text lines
local tool = require 'bugabinga.pivi.tool'--- Presents a tool's output in the language it came from.--- The output is parsed as a standalone string and the result is applied as--- decoration, so the transcript text stays exactly what the tool produced.local speak = function( bufnr, item, lang ) if item.last <= item.first then return false end local text = table.concat( vim.api.nvim_buf_get_lines( bufnr, item.first, item.last, false ), '\n' ) if text == '' then return false end local parsed, parser = pcall( vim.treesitter.get_string_parser, text, lang ) if not parsed or not parser then return false end local trees = parser:parse( true ) if not trees or not trees[1] then return false end local query = vim.treesitter.query.get( lang, 'highlights' ) if not query then return false end local offset = item.first for id, node in query:iter_captures( trees[1]:root(), text ) do local first_row, first_column, last_row, last_column = node:range() pcall( vim.api.nvim_buf_set_extmark, bufnr, namespace(), offset + first_row, first_column, { end_row = offset + last_row, end_col = last_column, hl_group = '@' .. query.captures[id] .. '.' .. lang, priority = 90, } ) end return trueendlocal decorate = function( bufnr, id ) -- What a tool reported about its own work, beside what it acted on. if item.kind == 'tool' then local ended = tool.outcome( item.meta ) if ended then pcall( vim.api.nvim_buf_set_extmark, bufnr, namespace(), item.first - 1, 0, { virt_text = { { ' ' .. ended, item.meta.failed and 'ErrorMsg' or 'Comment', }, }, virt_text_pos = 'eol', right_gravity = false, priority = 60, } ) end end for row = item.first - 1, item.last - 1 do -- A reported change reads as a change: added and removed lines stay distinct -- from the dimmed body around them. local change = item.kind == 'tool' and tool.diff( item.meta ) ~= nil -- While a tool still reports progress its body is rewritten repeatedly, so -- only its opening line is decorated until it finishes. local final_row = options and options.head_only and item.first - 1 or item.last - 1 for row = item.first - 1, final_row do speak = speak,+18 / −45 text lines
local tool = require 'bugabinga.pivi.tool'local relative = function( self, path ) if type( path ) ~= 'string' or path == '' then return nil end local root = self.cwd and vim.fs.normalize( self.cwd ) or nil local full = vim.fs.normalize( path ) if root and full:sub( 1, #root + 1 ) == root .. '/' then return full:sub( #root + 2 ) end return vim.fs.basename( full )end--- Describes a tool call the way a reader wants to scan it.local describe_tool = function( self, name, arguments ) local subject = type( arguments ) == 'table' and ( arguments.path or arguments.file_path or arguments.filePath or arguments.command or arguments.pattern or arguments.tag or arguments.title ) or nil if type( subject ) ~= 'string' or subject == '' then return tostring( name ) end if subject:find( '[/\\]' ) then subject = relative( self, subject ) or subject end subject = subject:gsub( '%s+', ' ' ) if #subject > 60 then subject = subject:sub( 1, 59 ) .. '…' end return tostring( name ) .. ' ' .. subjectend--- The text a tool produced, as the tool produced it.local result_text = function( result ) if type( result ) ~= 'table' then return nil end local pieces = {} for _, block in ipairs( result.content or {} ) do if block.type == 'text' and type( block.text ) == 'string' then table.insert( pieces, block.text ) end end local joined = vim.trim( table.concat( pieces, '\n' ) ) if joined == '' then return nil end return joinedend self.streamed = nil entry.line( bufnr, self.entry, describe_tool( self, event.toolName, event.args ) ) entry.line( bufnr, self.entry, tool.headline( entry.meta( bufnr, self.entry ) ) ) elseif event.type == 'tool_execution_update' then -- Output arrives while the tool still runs, so the entry shows it now -- rather than only once the tool ends. if self.entry_kind == 'tool' and event.partialResult then entry.annotate( bufnr, self.entry, { result = event.partialResult, } ) local shown = tool.body( entry.meta( bufnr, self.entry ) ) local joined = table.concat( shown, '\n' ) if joined ~= self.streamed then self.streamed = joined entry.rewrite( bufnr, self.entry, shown ) render.decorate( bufnr, self.entry, { head_only = true, } ) end end entry.annotate( bufnr, self.entry, { result = event.result, failed = event.isError == true, } )+8 / −1 text lines
- Markdown is rendered rather than shown as markup, and fenced code is presented in its own language.- Tool output lands inside its tool entry and arrives collapsed; the conversation itself stays open.- A tool entry states what it acted on and, once finished, how it ended: an edit shows how many lines it added and removed, a truncated result says so, a failure says so.- A completed edit shows its change, with added and removed lines distinct, and `:Pi diff` or `gD` opens it as a real editor comparison.- Going to an edit lands on its first changed line; going from a truncated result reaches the file its full output was spilled to.- Output of a running tool appears as it arrives, and output that came from a known language is presented in it.- Nothing here is invented: a tool that reports nothing about its own work simply names its subject.| `gD` | compare a completed change as a real editor diff |These keys are buffer-local, and `<Plug>(pivi-toggle-entry)`, `<Plug>(pivi-next-entry)`, `<Plug>(pivi-previous-entry)`, `<Plug>(pivi-next-tool)`, `<Plug>(pivi-previous-tool)`, `<Plug>(pivi-goto-location)` and `<Plug>(pivi-inspect-entry)` exist alongside them.These keys are buffer-local, and `<Plug>(pivi-toggle-entry)`, `<Plug>(pivi-next-entry)`, `<Plug>(pivi-previous-entry)`, `<Plug>(pivi-next-tool)`, `<Plug>(pivi-previous-tool)`, `<Plug>(pivi-goto-location)`, `<Plug>(pivi-inspect-entry)` and `<Plug>(pivi-compare-change)` exist alongside them.| `:Pi diff` | compare the change of the entry under the cursor |new file mode 100644+203 / −0 text lines
local MAX_SUBJECT = 60--- What a tool reports about its own work.--- Everything here is derived from that report; a tool that reports nothing--- gets no outcome rather than an invented one.local details_of = function( meta ) local result = meta and meta.result if type( result ) ~= 'table' then return nil end if type( result.details ) ~= 'table' then return nil end return result.detailsendlocal relative = function( path, cwd ) if type( path ) ~= 'string' or path == '' then return nil end local root = cwd and vim.fs.normalize( cwd ) or nil local full = vim.fs.normalize( path ) if root and full:sub( 1, #root + 1 ) == root .. '/' then return full:sub( #root + 2 ) end return vim.fs.basename( full )end--- What the tool acted on, short enough to scan.local subject = function( meta ) local args = meta and type( meta.args ) == 'table' and meta.args or {} local found = args.path or args.file_path or args.filePath or args.command or args.pattern or args.tag or args.title if type( found ) ~= 'string' or found == '' then return nil end if found:find( '[/\\]' ) then found = relative( found, meta.cwd ) or found end found = found:gsub( '%s+', ' ' ) if #found > MAX_SUBJECT then found = found:sub( 1, MAX_SUBJECT - 1 ) .. '\u{2026}' end return foundendlocal counts = function( diff ) local added, removed = 0, 0 for _, line in ipairs( vim.split( diff or '', '\n', { plain = true, } ) ) do local mark = line:sub( 1, 1 ) if mark == '+' then added = added + 1 elseif mark == '-' then removed = removed + 1 end end return added, removedendlocal LIMITS = { { field = 'matchLimitReached', label = 'match limit', }, { field = 'resultLimitReached', label = 'result limit', }, { field = 'entryLimitReached', label = 'entry limit', },}--- How the tool ended, or nothing when it reported nothing.local outcome = function( meta ) if not meta then return nil end local details = details_of( meta ) local parts = {} if details and type( details.diff ) == 'string' then local added, removed = counts( details.diff ) table.insert( parts, ( '+%d -%d' ):format( added, removed ) ) end if details and type( details.truncation ) == 'table' and details.truncation.truncated then table.insert( parts, 'truncated' ) end for _, limit in ipairs( LIMITS ) do if details and details[limit.field] then table.insert( parts, limit.label ) end end if meta.failed then table.insert( parts, 'failed' ) end if #parts == 0 then return nil end return table.concat( parts, ' ' )end--- The change a completed edit reported, as the tool formatted it.local diff = function( meta ) local details = details_of( meta ) if not details or type( details.diff ) ~= 'string' then return nil end local text = details.diff:gsub( '\n+$', '' ) if text == '' then return nil end return textend--- The line a reported change starts at, when the tool reported one.local first_changed_line = function( meta ) local details = details_of( meta ) local line = details and details.firstChangedLine if type( line ) ~= 'number' or line < 1 then return nil end return math.floor( line )end--- How one line of a reported change should read.local diff_highlight = function( text ) local mark = ( text or '' ):sub( 1, 1 ) if mark == '+' then return 'DiffAdd' end if mark == '-' then return 'DiffDelete' end return nilend--- The text a tool produced, as the tool produced it.local produced = function( meta ) local result = meta and meta.result if type( result ) ~= 'table' then return nil end local pieces = {} for _, block in ipairs( result.content or {} ) do if block.type == 'text' and type( block.text ) == 'string' then table.insert( pieces, block.text ) end end local joined = vim.trim( table.concat( pieces, '\n' ) ) if joined == '' then return nil end return joinedend--- What a tool entry shows below its headline.--- A reported change reads better than a sentence about it, so an edit shows--- its change and every other tool shows what it produced.local body = function( meta ) local change = diff( meta ) if change then return vim.split( change, '\n', { plain = true, } ) end local output = produced( meta ) if output then return vim.split( output, '\n', { plain = true, } ) end if meta and meta.failed then return { 'failed', } end return {}end--- Tools whose output is the content of the file they name.local CONTENT_TOOLS = { read = true, }--- The language a tool's output came from, when that is known.--- Only a tool that returns file content can claim one; anything else would--- be a guess dressed up as syntax.local language = function( meta ) if not meta or not CONTENT_TOOLS[meta.tool] then return nil end if diff( meta ) then return nil end local args = type( meta.args ) == 'table' and meta.args or {} local path = args.path or args.file_path or args.filePath if type( path ) ~= 'string' or path == '' then return nil end local filetype = vim.filetype.match { filename = path, } if not filetype then return nil end local resolved = vim.treesitter.language.get_lang( filetype ) if not resolved then return nil end if not pcall( vim.treesitter.language.add, resolved ) then return nil end return resolvedend--- Whether a tool kept less than it produced.local truncated = function( meta ) local details = details_of( meta ) local truncation = details and details.truncation return type( truncation ) == 'table' and truncation.truncated == trueend--- Where everything a tool produced still lives, when it reported that.local full_output = function( meta ) local details = details_of( meta ) local path = details and details.fullOutputPath if type( path ) ~= 'string' or path == '' then return nil end return pathend--- The line a tool entry opens with: the tool and what it acted on.local headline = function( meta ) local name = tostring( meta and meta.tool or 'tool' ) local acted_on = subject( meta ) if not acted_on then return name end return name .. ' ' .. acted_onend--- Tool, subject and outcome in one line, for a collapsed entry.local summary = function( meta ) local ended = outcome( meta ) if not ended then return headline( meta ) end return headline( meta ) .. ' ' .. endedendreturn { max_subject = MAX_SUBJECT, details = details_of, relative = relative, subject = subject, counts = counts, diff = diff, first_changed_line = first_changed_line, diff_highlight = diff_highlight, produced = produced, body = body, language = language, outcome = outcome, truncated = truncated, full_output = full_output, headline = headline, summary = summary,}+11 / −0 text lines
--- Replaces a range of rows, leaving everything around it alone.--- Rows are zero based and the end row is exclusive, as in the buffer API.local replace = function( bufnr, first, last, text ) if not vim.api.nvim_buf_is_valid( bufnr ) then return end writable( bufnr, function() vim.api.nvim_buf_set_lines( bufnr, first, last, false, text ) end ) follow_windows( bufnr )end replace = replace,new file mode 100644+168 / −0 text lines
---@diagnostic disable: duplicate-set-field, need-check-nil, param-type-mismatch, assign-type-mismatch, redundant-parameterlocal diff = require 'bugabinga.pivi.diff'local entry = require 'bugabinga.pivi.entry'local follow = require 'bugabinga.pivi.follow'local transcript = require 'bugabinga.pivi.transcript'local fake = dofile 'tests/helpers/pivi_fake.lua'local temp_file = function( lines ) local path = vim.fs.normalize( vim.fn.tempname() .. '.lua' ) vim.fn.writefile( lines, path ) return pathend-- A change as the edit tool formats it: every changed line carries its number.local CHANGE = table.concat( { ' 1 one', '-2 two', '+2 TWO', ' 3 three',}, '\n' )local recorded = function( bufnr, path, change ) local id = entry.open( bufnr, 'tool', { tool = 'edit', args = { path = path, }, result = { details = { diff = change, firstChangedLine = 2, }, }, } ) entry.line( bufnr, id, 'edit ' .. vim.fs.basename( path ) ) for _, line in ipairs( vim.split( change, '\n', { plain = true, } ) ) do entry.line( bufnr, id, line ) end entry.close( bufnr, id ) return idenddescribe( 'pivi diff', function() local bufnr, win before_each( function() bufnr = transcript.ensure 'comparing' transcript.clear( bufnr ) win = transcript.show( bufnr ) vim.api.nvim_set_current_win( win ) end ) after_each( function() diff.close() follow.reset() transcript.forget_all() fake.close_extra_windows() vim.cmd 'silent! %bwipeout!' end ) describe( 'reading a reported change', function() it( 'separates what was added from what was removed', function() local removed, added = diff.parse( CHANGE ) assert.same( { { line = 2, text = 'two', }, }, removed ) assert.same( { { line = 2, text = 'TWO', }, }, added ) end ) it( 'ignores context lines', function() local removed, added = diff.parse ' 1 untouched' assert.same( {}, removed ) assert.same( {}, added ) end ) it( 'rebuilds the content that existed before the change', function() local original, faithful = diff.before( { 'one', 'TWO', 'three', }, CHANGE ) assert.same( { 'one', 'two', 'three', }, original ) assert.is_true( faithful ) end ) it( 'rebuilds a change that only added lines', function() local original = diff.before( { 'one', 'two', }, '+2 two' ) assert.same( { 'one', }, original ) end ) it( 'rebuilds a change that only removed lines', function() local original = diff.before( { 'one', }, '-2 two' ) assert.same( { 'one', 'two', }, original ) end ) it( 'says so when the content no longer matches the change', function() local _, faithful = diff.before( { 'one', 'something else', 'three', }, CHANGE ) assert.is_false( faithful ) end ) end ) describe( 'comparing', function() it( 'opens the change as an editor comparison', function() local path = temp_file { 'one', 'TWO', 'three', } local id = recorded( bufnr, path, CHANGE ) local first = select( 1, entry.range( bufnr, id ) ) local changed, original, faithful = diff.open( bufnr, first ) assert.is_number( changed ) assert.is_number( original ) assert.is_true( faithful ) assert.is_true( vim.wo[changed].diff ) assert.is_true( vim.wo[original].diff ) assert.same( { 'one', 'two', 'three', }, vim.api.nvim_buf_get_lines( vim.api.nvim_win_get_buf( original ), 0, -1, false ) ) end ) it( 'keeps the working window and leaves the transcript untouched', function() local path = temp_file { 'one', 'TWO', 'three', } local id = recorded( bufnr, path, CHANGE ) local first = select( 1, entry.range( bufnr, id ) ) local before_text = transcript.lines( bufnr ) diff.open( bufnr, first ) assert.equal( win, vim.api.nvim_get_current_win() ) assert.same( before_text, transcript.lines( bufnr ) ) end ) it( 'states that the file has moved on', function() local path = temp_file { 'one', 'something else', 'three', } local id = recorded( bufnr, path, CHANGE ) local first = select( 1, entry.range( bufnr, id ) ) local _, original, faithful = diff.open( bufnr, first ) assert.is_false( faithful ) assert.is_true( vim.api.nvim_buf_get_name( vim.api.nvim_win_get_buf( original ) ):find( 'moved on', 1, true ) ~= nil ) end ) it( 'compares nothing for an entry that reports no change', function() local id = entry.open( bufnr, 'tool', { tool = 'read', args = { path = temp_file { 'one', }, }, } ) entry.line( bufnr, id, 'read a.lua' ) entry.close( bufnr, id ) assert.is_nil( diff.open( bufnr, select( 1, entry.range( bufnr, id ) ) ) ) end ) it( 'compares nothing outside a tool entry', function() local id = entry.open( bufnr, 'answer' ) entry.line( bufnr, id, 'just words' ) entry.close( bufnr, id ) assert.is_nil( diff.open( bufnr, select( 1, entry.range( bufnr, id ) ) ) ) end ) it( 'can be left again', function() local path = temp_file { 'one', 'TWO', 'three', } local id = recorded( bufnr, path, CHANGE ) local _, original = diff.open( bufnr, select( 1, entry.range( bufnr, id ) ) ) diff.close() assert.is_false( vim.api.nvim_win_is_valid( original ) ) assert.equal( win, vim.api.nvim_get_current_win() ) end ) it( 'binds comparison in its own buffers only', function() local bound = {} for _, mapping in ipairs( vim.api.nvim_buf_get_keymap( bufnr, 'n' ) ) do bound[mapping.lhs] = mapping.desc or '' end assert.is_string( bound.gD ) assert.is_true( bound.gD:find( 'pivi', 1, true ) ~= nil ) end ) end )end )+76 / −0 text lines
it( 'reaches the first changed line of an edit', function() local located = navigate.location_of { kind = 'tool', meta = { tool = 'edit', args = { path = 'a.lua', }, result = { details = { diff = '-7 old\n+7 new', firstChangedLine = 7, }, }, }, } assert.equal( 7, located.line ) end ) it( 'prefers the reported change over an argument line', function() local located = navigate.location_of { kind = 'tool', meta = { tool = 'edit', args = { path = 'a.lua', line = 1, }, result = { details = { firstChangedLine = 12, }, }, }, } assert.equal( 12, located.line ) end ) it( 'keeps the argument line when no change was reported', function() local located = navigate.location_of { kind = 'tool', meta = { tool = 'read', args = { path = 'a.lua', line = 4, }, }, } assert.equal( 4, located.line ) end ) it( 'lands on an edit at the line it changed', function() local path = temp_file { 'one', 'two', 'three', 'four', 'five', } block( bufnr, 'tool', { tool = 'edit', args = { path = path, }, result = { details = { diff = '-4 four\n+4 FOUR', firstChangedLine = 4, }, }, }, { 'edit', '-4 four', '+4 FOUR', } ) local listed = entry.list( bufnr ) local target = navigate.locate( bufnr, listed[#listed].first ) assert.is_number( target ) assert.equal( 4, vim.api.nvim_win_get_cursor( target )[1] ) end ) it( 'reaches the full output of a truncated result', function() local located = navigate.location_of { kind = 'tool', meta = { tool = 'bash', args = { command = 'ls -R', }, result = { details = { truncation = { truncated = true, }, fullOutputPath = '/tmp/pi-bash-abc.log', }, }, }, } assert.equal( '/tmp/pi-bash-abc.log', located.path ) end ) it( 'prefers what a tool acted on over where its output spilled', function() local located = navigate.location_of { kind = 'tool', meta = { tool = 'read', args = { path = '/work/a.lua', }, result = { details = { fullOutputPath = '/tmp/spill.log', }, }, }, } assert.equal( '/work/a.lua', located.path ) end )+87 / −0 text lines
local tool = require 'bugabinga.pivi.tool' it( 'shows a reported change with added and removed lines distinguished', function() local id = entry.open( bufnr, 'tool', { tool = 'edit', args = { path = 'a.lua', }, result = { details = { diff = ' 1 keep\n-2 old\n+2 new\n', }, }, } ) for _, text in ipairs { 'edit a.lua', ' 1 keep', '-2 old', '+2 new', } do entry.line( bufnr, id, text ) end entry.close( bufnr, id ) local before = transcript.lines( bufnr ) render.decorate( bufnr, id ) local groups = {} for _, mark in ipairs( render.marks( bufnr ) ) do local details = mark[4] or {} if details.line_hl_group then groups[mark[2] + 1] = details.line_hl_group end end local first = select( 1, entry.range( bufnr, id ) ) assert.equal( 'Comment', groups[first] ) assert.equal( 'Comment', groups[first + 1] ) assert.equal( 'DiffDelete', groups[first + 2] ) assert.equal( 'DiffAdd', groups[first + 3] ) -- The change is decoration over reported text, so the text is untouched. assert.same( before, transcript.lines( bufnr ) ) end ) it( 'leaves a tool that reported no change entirely dimmed', function() local id = entry.open( bufnr, 'tool', { tool = 'read', args = { path = 'a.lua', }, } ) for _, text in ipairs { 'read a.lua', '+ not a diff', } do entry.line( bufnr, id, text ) end entry.close( bufnr, id ) render.decorate( bufnr, id ) for _, mark in ipairs( render.marks( bufnr ) ) do assert.is_not.equal( 'DiffAdd', ( mark[4] or {} ).line_hl_group ) end end ) it( 'presents tool output in the language it came from', function() local id = entry.open( bufnr, 'tool', { tool = 'read', args = { path = '/work/greet.lua', }, cwd = '/work', result = { content = { { type = 'text', text = 'local value = 1', }, }, }, } ) entry.line( bufnr, id, 'read greet.lua' ) entry.line( bufnr, id, 'local value = 1' ) entry.close( bufnr, id ) local before = transcript.lines( bufnr ) render.decorate( bufnr, id ) local groups = {} for _, mark in ipairs( render.marks( bufnr ) ) do local group = ( mark[4] or {} ).hl_group if group then groups[group] = true end end assert.is_true( groups['@keyword.lua'] or groups['@variable.lua'] or false, 'no lua highlight was applied: ' .. vim.inspect( vim.tbl_keys( groups ) ) ) assert.same( before, transcript.lines( bufnr ) ) end ) it( 'leaves output alone when no language can be claimed', function() for _, meta in ipairs { { tool = 'bash', args = { command = 'ls', }, }, { tool = 'read', args = { path = '/work/notes.unknownext', }, }, { tool = 'read', args = {}, }, { tool = 'edit', args = { path = '/work/a.lua', }, result = { details = { diff = '+1 x', }, }, }, } do assert.is_nil( tool.language( meta ) ) end assert.equal( 'lua', tool.language { tool = 'read', args = { path = '/work/a.lua', }, result = { content = {}, }, } ) end )+158 / −0 text lines
it( 'states how a tool ended beside what it acted on', function() local channel = fake.new() local current = create( channel ) local win = transcript.show( current.buffer ) channel.frame { type = 'tool_execution_start', toolCallId = 'c1', toolName = 'edit', args = { path = 'greet.lua', }, } channel.frame { type = 'tool_execution_end', toolCallId = 'c1', toolName = 'edit', isError = false, result = { content = { { type = 'text', text = 'Successfully replaced 1 block(s) in greet.lua.', }, }, details = { diff = ' 1 keep\n-2 old\n+2 new\n', firstChangedLine = 2, }, }, } channel.flush() local item = entry.list( current.buffer )[1] local lines = transcript.lines( current.buffer ) -- The outcome is decoration, never buffer text. assert.equal( 'edit greet.lua', lines[item.first] ) local outcomes = {} for _, mark in ipairs( render.marks( current.buffer ) ) do local virt = ( mark[4] or {} ).virt_text if virt then table.insert( outcomes, virt[1][1] ) end end assert.is_true( vim.iter( outcomes ):any( function( text ) return text:find( '+1 -1', 1, true ) ~= nil end ) ) -- And it survives collapsing. local collapsed = vim.api.nvim_win_call( win, function() vim.v.foldstart = item.first vim.v.foldend = item.last return fold.text() end ) assert.is_true( collapsed:find( 'greet.lua', 1, true ) ~= nil ) assert.is_true( collapsed:find( '+1 -1', 1, true ) ~= nil ) end ) it( 'shows the output of a running tool as it arrives', function() local channel = fake.new() local current = create( channel ) channel.frame { type = 'tool_execution_start', toolCallId = 'c1', toolName = 'bash', args = { command = 'count', }, } channel.flush() local opened = entry.list( current.buffer )[1] assert.equal( opened.first, opened.last ) channel.frame { type = 'tool_execution_update', toolCallId = 'c1', toolName = 'bash', partialResult = { content = { { type = 'text', text = 'one', }, }, }, } channel.flush() local growing = entry.list( current.buffer )[1] assert.is_true( vim.list_contains( transcript.lines( current.buffer ), 'one' ) ) assert.equal( opened.first, growing.first ) assert.equal( growing.first + 1, growing.last ) channel.frame { type = 'tool_execution_update', toolCallId = 'c1', toolName = 'bash', partialResult = { content = { { type = 'text', text = 'one\ntwo\nthree', }, }, }, } channel.flush() local grown = entry.list( current.buffer )[1] local lines = transcript.lines( current.buffer ) -- The tail was rewritten rather than appended twice. assert.equal( opened.first, grown.first ) assert.equal( grown.first + 3, grown.last ) assert.same( { 'bash count', 'one', 'two', 'three', }, vim.list_slice( lines, grown.first, grown.last ) ) channel.frame { type = 'tool_execution_end', toolCallId = 'c1', toolName = 'bash', isError = false, result = { content = { { type = 'text', text = 'one\ntwo\nthree\ndone', }, }, }, } channel.flush() local finished = entry.list( current.buffer )[1] assert.same( { 'bash count', 'one', 'two', 'three', 'done', }, vim.list_slice( transcript.lines( current.buffer ), finished.first, finished.last ) ) end ) it( 'keeps later entries intact while a tool streams', function() local channel = fake.new() local current = create( channel ) current.submit( 'do it', { capture = false, } ) channel.frame { type = 'tool_execution_start', toolCallId = 'c1', toolName = 'bash', args = { command = 'go', }, } for _, text in ipairs { 'a', 'a\nb', 'a\nb\nc', } do channel.frame { type = 'tool_execution_update', toolCallId = 'c1', toolName = 'bash', partialResult = { content = { { type = 'text', text = text, }, }, }, } end channel.flush() local listed = entry.list( current.buffer ) local prompt = listed[1] assert.equal( 'prompt', prompt.kind ) assert.equal( 'do it', transcript.lines( current.buffer )[prompt.first] ) assert.is_true( listed[2].first > prompt.last ) end ) it( 'says nothing about a tool that reported nothing', function() local channel = fake.new() local current = create( channel ) channel.frame { type = 'tool_execution_start', toolCallId = 'c1', toolName = 'write', args = { path = 'new.lua', }, } channel.frame { type = 'tool_execution_end', toolCallId = 'c1', toolName = 'write', isError = false, result = { content = { { type = 'text', text = 'wrote new.lua', }, }, }, } channel.flush() local item = entry.list( current.buffer )[1] assert.is_nil( require( 'bugabinga.pivi.tool' ).outcome( item.meta ) ) assert.equal( 'write new.lua', transcript.lines( current.buffer )[item.first] ) end )new file mode 100644+194 / −0 text lines
---@diagnostic disable: duplicate-set-field, need-check-nil, param-type-mismatch, assign-type-mismatch, redundant-parameterlocal tool = require 'bugabinga.pivi.tool'-- Shapes recorded from the installed Pi implementation: edit always reports a-- change, bash reports truncation and a full output path, the search tools-- report the limit they hit, and write reports nothing.local EDIT_DIFF = table.concat( { ' 1 local function greet(name)', '-2 return name', '+2 return "hello " .. name', '+3 -- added', ' 4 end',}, '\n' )describe( 'pivi tool', function() describe( 'subject', function() it( 'names a path relative to the session directory', function() assert.equal( 'lua/deep/file.lua', tool.subject { tool = 'edit', args = { path = '/work/lua/deep/file.lua', }, cwd = '/work', } ) end ) it( 'falls back to the basename of a foreign path', function() assert.equal( 'file.lua', tool.subject { tool = 'read', args = { path = '/elsewhere/file.lua', }, cwd = '/work', } ) end ) it( 'names a command, a pattern, a tag or a title', function() assert.equal( 'ls -la', tool.subject { args = { command = 'ls -la', }, } ) assert.equal( 'needle', tool.subject { args = { pattern = 'needle', }, } ) assert.equal( 'quickfix', tool.subject { args = { tag = 'quickfix', }, } ) assert.equal( 'review', tool.subject { args = { title = 'review', }, } ) end ) it( 'collapses whitespace and bounds the length', function() local long = tool.subject { args = { command = string.rep( 'x', 200 ), }, } assert.is_true( #long <= tool.max_subject + 2 ) assert.equal( 'a b c', tool.subject { args = { command = 'a b\tc', }, } ) end ) it( 'names nothing when the arguments name nothing', function() assert.is_nil( tool.subject { tool = 'nvim_state', args = {}, } ) assert.is_nil( tool.subject( nil ) ) end ) end ) describe( 'outcome', function() it( 'counts what an edit added and removed', function() assert.equal( '+2 -1', tool.outcome { tool = 'edit', result = { details = { diff = EDIT_DIFF, }, }, } ) end ) it( 'reports a truncated result', function() assert.equal( 'truncated', tool.outcome { tool = 'bash', result = { details = { truncation = { truncated = true, }, fullOutputPath = '/tmp/out.log', }, }, } ) end ) it( 'reports the limit a search tool hit', function() assert.equal( 'match limit', tool.outcome { tool = 'grep', result = { details = { matchLimitReached = 100, }, }, } ) assert.equal( 'result limit', tool.outcome { tool = 'find', result = { details = { resultLimitReached = 100, }, }, } ) assert.equal( 'entry limit', tool.outcome { tool = 'ls', result = { details = { entryLimitReached = 500, }, }, } ) end ) it( 'reports a failure whatever the tool reported', function() assert.equal( 'failed', tool.outcome { tool = 'bash', failed = true, } ) assert.equal( 'truncated failed', tool.outcome { tool = 'bash', failed = true, result = { details = { truncation = { truncated = true, }, }, }, } ) end ) it( 'reports nothing for a tool that reported nothing', function() assert.is_nil( tool.outcome { tool = 'write', result = { content = {}, }, } ) assert.is_nil( tool.outcome { tool = 'read', result = { content = {}, details = nil, }, } ) assert.is_nil( tool.outcome( nil ) ) end ) it( 'ignores a truncation that did not happen', function() assert.is_nil( tool.outcome { tool = 'read', result = { details = { truncation = { truncated = false, }, }, }, } ) end ) end ) describe( 'the change an edit reported', function() it( 'keeps the change as the tool formatted it', function() local change = tool.diff { tool = 'edit', result = { details = { diff = EDIT_DIFF .. '\n\n', }, }, } assert.equal( EDIT_DIFF, change ) end ) it( 'reports no change when none was reported', function() assert.is_nil( tool.diff { tool = 'write', result = { content = {}, }, } ) assert.is_nil( tool.diff { tool = 'edit', result = { details = { diff = '', }, }, } ) end ) it( 'distinguishes added from removed lines', function() assert.equal( 'DiffAdd', tool.diff_highlight '+2 return "hello"' ) assert.equal( 'DiffDelete', tool.diff_highlight '-2 return name' ) assert.is_nil( tool.diff_highlight ' 1 local function greet(name)' ) assert.is_nil( tool.diff_highlight( nil ) ) end ) it( 'shows the change rather than a sentence about it', function() local shown = tool.body { tool = 'edit', result = { content = { { type = 'text', text = 'Successfully replaced 1 block(s) in a.lua.', }, }, details = { diff = EDIT_DIFF, }, }, } assert.same( vim.split( EDIT_DIFF, '\n', { plain = true, } ), shown ) end ) it( 'shows what a tool produced when it reported no change', function() assert.same( { 'alpha', 'beta', }, tool.body { tool = 'read', result = { content = { { type = 'text', text = 'alpha\nbeta\n', }, }, }, } ) end ) it( 'shows a failure when a tool produced nothing at all', function() assert.same( { 'failed', }, tool.body { tool = 'bash', failed = true, result = { content = {}, }, } ) assert.same( {}, tool.body { tool = 'write', result = { content = {}, }, } ) end ) end ) describe( 'truncation', function() it( 'knows a result was kept only in part', function() assert.is_true( tool.truncated { tool = 'bash', result = { details = { truncation = { truncated = true, }, }, }, } ) assert.is_false( tool.truncated { tool = 'bash', result = { details = { truncation = { truncated = false, }, }, }, } ) assert.is_false( tool.truncated { tool = 'write', result = { content = {}, }, } ) end ) it( 'knows where the full output still lives', function() assert.equal( '/tmp/pi-bash-abc.log', tool.full_output { tool = 'bash', result = { details = { truncation = { truncated = true, }, fullOutputPath = '/tmp/pi-bash-abc.log', }, }, } ) assert.is_nil( tool.full_output { tool = 'read', result = { details = { truncation = {}, }, }, } ) end ) end ) describe( 'lines', function() it( 'opens an entry with the tool and what it acted on', function() assert.equal( 'edit a.lua', tool.headline { tool = 'edit', args = { path = 'a.lua', }, } ) assert.equal( 'nvim_state', tool.headline { tool = 'nvim_state', args = {}, } ) end ) it( 'states subject and outcome together for a collapsed entry', function() local collapsed = tool.summary { tool = 'edit', args = { path = 'a.lua', }, result = { details = { diff = EDIT_DIFF, }, }, } assert.is_true( collapsed:find( 'edit', 1, true ) ~= nil ) assert.is_true( collapsed:find( 'a.lua', 1, true ) ~= nil ) assert.is_true( collapsed:find( '+2 -1', 1, true ) ~= nil ) end ) it( 'degrades to the subject alone when nothing was reported', function() assert.equal( 'write a.lua', tool.summary { tool = 'write', args = { path = 'a.lua', }, } ) end ) end )end )