From e41a9da6624956954ff0893066b2e29fcbfa62bb Mon Sep 17 00:00:00 2001 From: tomeyer97 <107920881+tomeyer97@users.noreply.github.com> Date: Thu, 26 Nov 2026 22:40:40 +0100 Subject: [PATCH] Threads and anchors: stale lines visible in the editor, a clear move, applied suggestions recorded, links that read well aloud Stale notes tint their lines and mark the ruler, and the banner shows the old and new line as a wrapped word diff. Move Note finishes from the status bar (no toast). Applying a suggestion is recorded on the message and cannot run twice. Answers link root files (package.json:3). Thread command links use short keys instead of percent-encoded JSON, and concern actions move from the comment body to thread actions. --- src/core/linkifyAnswer.ts | 13 +++- src/notes/decorations.ts | 39 ++++++---- src/notes/move.ts | 31 ++++---- src/notes/suggestion.ts | 21 +++++- src/platform/commands.ts | 51 +++++++++++++ src/threads/banner.ts | 96 +++++++++++++++++++++-- src/threads/comments.ts | 17 +++-- src/threads/context.ts | 8 +- src/threads/index.ts | 18 ++++- src/threads/rows.ts | 9 ++- src/threads/rows/check.ts | 36 ++++----- src/threads/text.ts | 22 +++++- test/answerLinks.test.ts | 14 +++- test/commands.test.ts | 20 ++++- test/integration/check/answers.ts | 10 ++- test/integration/check/askAndFix.ts | 6 +- test/integration/check/support.ts | 6 +- test/integration/main/context.ts | 10 +++ test/integration/main/journeyTour.ts | 4 +- test/integration/main/notesReview.ts | 10 +-- test/integration/main/requests.ts | 4 +- test/integration/main/threads.ts | 109 +++++++++++++++++++++++++++ test/integration/suite.ts | 3 + test/threadText.test.ts | 22 +++++- 24 files changed, 478 insertions(+), 101 deletions(-) create mode 100644 test/integration/main/threads.ts diff --git a/src/core/linkifyAnswer.ts b/src/core/linkifyAnswer.ts index c77c52c..2f4ac23 100644 --- a/src/core/linkifyAnswer.ts +++ b/src/core/linkifyAnswer.ts @@ -18,15 +18,20 @@ const TARGET = /^(.*?)(?:#L(\d+)(?:-L?\d+)?|:(\d+)(?:-\d+)?)?$/ const REF_START = String.raw`(? | undefined const theme = (id: string) => new vscode.ThemeColor(id) -/** The left bar and the scrollbar mark of a note (one marker per note: never a tint over its lines). */ -const BARS = { +/** The left bar and the scrollbar mark of a note; a stale note's lines are tinted too (amber: the code changed under + * it), so it shows in the editor, not only in its thread. */ +export const BARS = { openBar: { style: 'solid', color: 'codeNotes.noteBorder', ruler: 'codeNotes.noteRuler' }, - staleBar: { style: 'dashed', color: 'editorWarning.foreground', ruler: 'editorWarning.foreground' }, + staleBar: { style: 'dashed', color: 'editorWarning.foreground', ruler: 'editorWarning.foreground', background: 'codeNotes.staleBackground' }, } -function bar(b: (typeof BARS)[keyof typeof BARS]): vscode.TextEditorDecorationType { +function bar(b: { style: string; color: string; ruler: string; background?: string }): vscode.TextEditorDecorationType { return vscode.window.createTextEditorDecorationType({ isWholeLine: true, borderWidth: '0 0 0 2px', borderStyle: b.style, borderColor: theme(b.color), overviewRulerColor: theme(b.ruler), overviewRulerLane: vscode.OverviewRulerLane.Right, + ...(b.background ? { backgroundColor: theme(b.background) } : {}), }) } @@ -67,18 +70,24 @@ function exactRange(doc: vscode.TextDocument, n: Note): vscode.Range | undefined /** The notes marked in an editor: open or unread, not in a hidden session. */ const marked = (n: Note) => (n.data.status === 'open' || unread(n) > 0) && !hiddenInEditor(n) -/** Every visible editor's note marks (and the step card's), as the notes are now. None on the code a podcast is - * telling while it plays (they come back on pause). */ +/** An editor's note marks, by kind, as the notes are now. None on the code a podcast is telling while it plays. */ +export function marksOf(editor: vscode.TextEditor): Record { + const shown = cfg().get('highlight', true) && !notesPorts().layout.narrates(editor) + const list = shown ? lineNotesFor(editor.document.uri).filter(marked) : [] + return { + openBar: list.filter((n) => !n.data.stale).map(linesOf), + staleBar: list.filter((n) => n.data.stale).map(linesOf), + unread: list.filter((n) => unread(n) > 0).map(linesOf), + exact: list.map((n) => exactRange(editor.document, n)).filter((r): r is vscode.Range => !!r), + } +} + +/** Every visible editor's note marks (and the step card's), as the notes are now (they come back on a pause). */ export function refreshDecorations(): void { if (!deco) return - const on = cfg().get('highlight', true) for (const editor of vscode.window.visibleTextEditors) { - const shown = on && !notesPorts().layout.narrates(editor) - const list = shown ? lineNotesFor(editor.document.uri).filter(marked) : [] - setDecorations(editor, deco.openBar, list.filter((n) => !n.data.stale).map(linesOf)) - setDecorations(editor, deco.staleBar, list.filter((n) => n.data.stale).map(linesOf)) - setDecorations(editor, deco.unread, list.filter((n) => unread(n) > 0).map(linesOf)) - setDecorations(editor, deco.exact, list.map((n) => exactRange(editor.document, n)).filter((r): r is vscode.Range => !!r)) + const marks = marksOf(editor) + for (const kind of Object.keys(marks) as Kind[]) setDecorations(editor, deco[kind], marks[kind]) } notesPorts().layout.refreshCard() } diff --git a/src/notes/move.ts b/src/notes/move.ts index 5e30d68..c861f9e 100644 --- a/src/notes/move.ts +++ b/src/notes/move.ts @@ -1,5 +1,5 @@ -// Moving a note to other code: the selection now, or select it and click Move Here. Keep Here: a stale note takes -// the code at its lines. +// Moving a note to other code: the selection now, or select it and press Enter (or click "Move note here" in the +// status bar). Keep Here: a stale note takes the code at its lines. import * as vscode from 'vscode' import { store } from './ports' @@ -23,8 +23,9 @@ import { hint } from './hint' const MOVING_CTX = 'codeNotes.moving' /** - * A move waiting for the person to select the code: which note, its status bar item (click: Move Here) and the - * context key. Idle, or moving one note; start, complete or cancel go from one to the other. + * A move waiting for the person to select the code: which note, its status bar item (click or Enter: move it) and the + * context key. Idle, or moving one note; start, complete or cancel go from one to the other. No notification: one + * hides as soon as the editor takes the focus to select the code. */ class MoveMode implements vscode.Disposable { private readonly item = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Left, 51) @@ -36,18 +37,16 @@ class MoveMode implements vscode.Disposable { this.item.backgroundColor = new vscode.ThemeColor('statusBarItem.warningBackground') } - /** Waits for the code: the item, the context key and a message with Move Here. */ - async start(n: Note): Promise { + /** Waits for the code: the status bar item and the context key (Enter and Esc read it). */ + start(n: Note): void { this.wait(n) - this.item.text = `$(move) Move "${noteTitle(n, 30)}" to the selection` - this.item.tooltip = 'Select the code, then click here. Esc cancels.' + this.item.text = '$(move) Move note here' + this.item.tooltip = `Select the code for "${noteTitle(n, 60)}", then press Enter or click here. Esc cancels.` this.item.show() - const question = `Move note "${noteTitle(n)}": select the code it belongs to, then click Move Here.` - const pick = await vscode.window.showInformationMessage(question, 'Move Here', 'Cancel') - if (pick === 'Move Here') await this.complete() - else if (pick === 'Cancel') this.cancel() } + get moving(): boolean { return this.pending !== undefined } + /** The note waiting is `n`. */ private wait(n: Note): void { this.pending = n.data.id @@ -96,7 +95,7 @@ const moveMode = () => (mode ??= new MoveMode()) /** The move mode, made when the notes start (its status bar item goes with them). */ export function createMoveMode(): vscode.Disposable { return moveMode() } -export const startMove = (n: Note) => moveMode().start(n) +export const startMove = async (n: Note) => moveMode().start(n) export const cancelMove = () => moveMode().cancel() export const completeMove = () => moveMode().complete() @@ -111,8 +110,10 @@ export const acceptCode = async (arg?: CommandArg) => { notesChanged({ kind: 'placed', ids: [n.data.id] }) } -/** codeNotes.moveToSelection: a selection elsewhere: the note moves there now (with Undo); otherwise it asks for one. */ -export const moveToSelection = (arg?: CommandArg) => { +/** codeNotes.moveToSelection: a selection elsewhere: the note moves there now (with Undo); otherwise it asks for one. + * No note given while a move waits (Enter): that move goes to the selection. */ +export const moveToSelection = async (arg?: CommandArg) => { + if (arg === undefined && moveMode().moving) return moveMode().complete() const [n] = notesFrom(arg) if (!n) return const e = vscode.window.activeTextEditor diff --git a/src/notes/suggestion.ts b/src/notes/suggestion.ts index d23f548..ec363a4 100644 --- a/src/notes/suggestion.ts +++ b/src/notes/suggestion.ts @@ -1,7 +1,7 @@ -// An agent's ```suggestion block applied to the note's lines (the editor's Undo takes it back). +// An agent's ```suggestion block applied to the note's lines (the editor's Undo takes it back), recorded on its message. import * as vscode from 'vscode' -import { notesPorts } from './ports' +import { notesPorts, store } from './ports' import { byId } from './visible' import { showError } from '../platform/run' import { anchorAt, docUri, neverAnchored, placement } from './location' @@ -9,11 +9,13 @@ import { notesChanged } from './model' import { Note } from './store' import { rangeLabel } from '../core/text' import { suggestionOf } from '../threads/comments' +import { appliedOf, withApplied } from '../threads/text' import { docLines } from '../platform/documents' import { fireAndForget } from '../platform/run' import { alternateAnchor } from './alternateAnchor' import { placeAt } from './place' import { hint } from './hint' +import { me } from './identity' /** How long "Applied … Save to keep" stays in the status bar. */ const APPLIED_MS = 5000 @@ -36,17 +38,28 @@ function cannotApply(n: Note): string | undefined { /** Apply on an agent's ```suggestion block: replaces the note's lines; the editor's Undo takes it back. */ export async function applySuggestion(id: string, mi: number, k: number): Promise { const n = byId(id) - const text = n ? suggestionOf(n.data.messages[mi]?.body ?? '', k) : undefined - if (!n || text === undefined) { hint('That suggestion is gone'); return false } + const m = n?.data.messages[mi] + const text = m ? suggestionOf(m.body, k) : undefined + if (!n || !m || text === undefined) { hint('That suggestion is gone'); return false } + // Applied once: a second click would put it in again over the code it already is. + const done = appliedOf(m.extra, k) + if (done) { hint(`Already applied by ${done.by}`); return false } const why = cannotApply(n) if (why) { fireAndForget(showError(why), 'suggestion: showError'); return false } const doc = await vscode.workspace.openTextDocument(docUri(n)) const start = n.data.range.start - 1, end = Math.min(n.data.range.end - 1, doc.lineCount - 1) // A note whose anchor was lost (an agent rewrote the file from an older copy): take it now, so Undo has the old code. if (neverAnchored(n.data.anchor)) n.data.anchor = await anchorAt(docLines(doc), start, end, n.folder) + // Recorded before the edit: saved then, the note file still has the lines on disk (the new ones are saved with the code). + const extra = m.extra + m.extra = withApplied(extra, { suggestion: k, by: me(), at: new Date().toISOString() }) + await store().save(n) const edit = new vscode.WorkspaceEdit() edit.replace(doc.uri, new vscode.Range(start, 0, end, doc.lineAt(end).text.length), text) if (!(await vscode.workspace.applyEdit(edit))) { + m.extra = extra + await store().save(n) + notesChanged({ kind: 'placed', ids: [n.data.id] }) fireAndForget(showError('the suggestion could not be applied.'), 'suggestion: showError') return false } diff --git a/src/platform/commands.ts b/src/platform/commands.ts index 49a2940..42b9688 100644 --- a/src/platform/commands.ts +++ b/src/platform/commands.ts @@ -101,6 +101,14 @@ export const HiddenCmd = { openNoteId: 'codeNotes.openNoteId', openStepLink: 'codeNotes.openStepLink', podcastFollow: 'codeNotes.podcastFollow', + /** A thread's links run through this one with a short key (shortLinks below). */ + link: 'codeNotes.link', + /** A check concern's actions on its thread (menus on the thread, not links in the text). */ + concernFix: 'codeNotes.concernFix', + concernTodo: 'codeNotes.concernTodo', + concernFlag: 'codeNotes.concernFlag', + concernFixed: 'codeNotes.concernFixed', + concernDismiss: 'codeNotes.concernDismiss', notesFocus: 'codeNotes.notes.focus', journeysFocus: 'codeNotes.journeys.focus', checkFocus: 'codeNotes.check.focus', @@ -130,3 +138,46 @@ export const cmdLink = (label: string, command: string, ...args: unknown[]) => ` /** The same with a tooltip (`title`). */ export const titledCmdLink = (label: string, title: string, command: string, ...args: unknown[]) => `[${label}](${commandUri(command, ...args)} "${title}")` + +/** A link's command and arguments, by its short key (keys live as long as the window: threads are drawn anew). */ +const linkCalls = new Map() +const linkKeys = new Map() +/** Keys are random, so text an agent wrote can't guess one made for another thread. */ +const KEY_SPACE = 900_000 + +/** The short key of a link that runs `command` with `args` (the same link keeps its key, so a redraw is a no-op). */ +export function linkKey(command: string, args: unknown[]): number { + const sig = JSON.stringify([command, args]) + let key = linkKeys.get(sig) + if (key !== undefined) return key + do key = 100_000 + Math.floor(Math.random() * KEY_SPACE) + while (linkCalls.has(key)) + linkKeys.set(sig, key) + linkCalls.set(key, { command, args }) + return key +} + +/** What the link with this key runs. */ +export const linkCall = (key: unknown) => (typeof key === 'number' ? linkCalls.get(key) : undefined) + +/** A link target `command:?` in Markdown (its title after a space). */ +const COMMAND_TARGET = /\]\(command:([\w.-]+)(?:\?([^\s)]+))?/g + +/** + * Markdown whose links to `allowed` commands run through HiddenCmd.link with a short key: screen readers read a + * comment's Markdown as is, and a JSON argument in a link is hundreds of percent-encoded characters. + */ +export function shortLinks(markdown: string, allowed: readonly string[]): string { + return markdown.replace(COMMAND_TARGET, (m, command: string, query?: string) => { + // Without arguments it is short already. + if (!query || !allowed.includes(command)) return m + let args: unknown + try { args = JSON.parse(decodeURIComponent(query)) } catch { return m } + return `](command:${HiddenCmd.link}?${linkKey(command, Array.isArray(args) ? args : [args])}` + }) +} + +/** What a clicked link runs: a short link's command and arguments, any other as it is. */ +export function clickedLink(command: string, args: unknown[]): { command: string; args: unknown[] } { + return (command === HiddenCmd.link && linkCall(args[0])) || { command, args } +} diff --git a/src/threads/banner.ts b/src/threads/banner.ts index da353bf..79077d1 100644 --- a/src/threads/banner.ts +++ b/src/threads/banner.ts @@ -2,7 +2,7 @@ // lines were and the buttons (Keep here, Move). No vscode here: unit-tested in test/threadText.test.ts. import { Cmd } from '../platform/commands' import { THREAD_LIMITS } from './limits' -import { codeBlock } from './text' +import { verbatimText } from './text' import type { Links } from './links' /** The first lines, then "… n more". */ @@ -11,12 +11,92 @@ function shortLines(lines: readonly string[]): string[] { return lines.length > max ? [...lines.slice(0, max), `… ${lines.length - max} more`] : [...lines] } -/** The note's old code, shortened. */ -export const oldCodeBlock = (lines: readonly string[]) => codeBlock(shortLines(lines)) +/** Words, runs of spaces and single punctuation: what a changed word is made of. */ +const TOKEN = /\s+|[\w$]+|[^\w\s]/g +/** Lines longer than this many tokens (each × the other's) are shown without the changed words picked out. */ +const MAX_WORD_CELLS = 40_000 -/** Only the lines that changed, as a diff (a one-word change is visible, a 15-line note is not repeated). */ -export function diffBlock(del: readonly string[], ins: readonly string[]): string { - return codeBlock([...shortLines(del).map((l) => `- ${l.trim()}`), ...shortLines(ins).map((l) => `+ ${l.trim()}`)], 'diff') +const isSpace = (token: string) => /^\s/.test(token) + +/** The longest common subsequence table of two word lists: table[i][j] is the length for oldWords[i..] and newWords[j..]. */ +function lcsTable(oldWords: string[], newWords: string[]): number[][] { + const table: number[][] = Array.from({ length: oldWords.length + 1 }, () => new Array(newWords.length + 1).fill(0)) + for (let i = oldWords.length - 1; i >= 0; i--) { + for (let j = newWords.length - 1; j >= 0; j--) { + table[i][j] = oldWords[i] === newWords[j] ? table[i + 1][j + 1] + 1 : Math.max(table[i + 1][j], table[i][j + 1]) + } + } + return table +} + +/** For each word of both lists: true when it is not part of their longest common subsequence (it changed). */ +function unmatchedWords(oldWords: string[], newWords: string[], table: number[][]): { oldChanged: boolean[]; newChanged: boolean[] } { + const oldChanged = oldWords.map(() => true), newChanged = newWords.map(() => true) + let i = 0, j = 0 + while (i < oldWords.length && j < newWords.length) { + if (oldWords[i] === newWords[j]) { + oldChanged[i++] = false + newChanged[j++] = false + } else if (table[i + 1][j] >= table[i][j + 1]) i++ + else j++ + } + return { oldChanged, newChanged } +} + +/** For each token of the old and the new line: changed. Spaces are left out of the match (a shared space would pull + * the words apart); wrappedLine decides theirs. Lines too long to compare: nothing picked out. */ +function changedTokens(oldTokens: string[], newTokens: string[]): { oldChanged: boolean[]; newChanged: boolean[] } { + const wordIndexes = (tokens: string[]) => tokens.flatMap((t, k) => (isSpace(t) ? [] : [k])) + const oldAt = wordIndexes(oldTokens), newAt = wordIndexes(newTokens) + const oldChanged = oldTokens.map(() => false), newChanged = newTokens.map(() => false) + if (oldAt.length * newAt.length > MAX_WORD_CELLS) return { oldChanged, newChanged } + const oldWords = oldAt.map((k) => oldTokens[k]), newWords = newAt.map((k) => newTokens[k]) + const words = unmatchedWords(oldWords, newWords, lcsTable(oldWords, newWords)) + words.oldChanged.forEach((changed, w) => { oldChanged[oldAt[w]] = changed }) + words.newChanged.forEach((changed, w) => { newChanged[newAt[w]] = changed }) + return { oldChanged, newChanged } +} + +/** A line of code as Markdown that wraps (a code block scrolls sideways): escaped text, the changed words as code. */ +function wrappedLine(mark: string, tokens: string[], changed: boolean[]): string { + // A space between two changed words is part of the change (one code span, not two). + const inChange = changed.map((c, k) => (isSpace(tokens[k]) ? k > 0 && k < tokens.length - 1 && changed[k - 1] && changed[k + 1] : c)) + let out = '' + for (let start = 0; start < tokens.length;) { + let end = start + while (end < tokens.length && inChange[end] === inChange[start]) end++ + const text = tokens.slice(start, end).join('') + out += inChange[start] && !text.includes('`') ? `\`${text}\`` : verbatimText(text) + start = end + } + return `${mark} ${out}` +} + +const tokensOf = (line: string) => line.trim().match(TOKEN) ?? [] +const plainLine = (mark: string, line: string) => (line.startsWith('… ') ? line : `${mark} ${verbatimText(line.trim())}`) +/** "−" is not Markdown; a "+" starting a line would be a list item. */ +const DEL = '−', INS = '\\+' + +/** The note's old code, shortened, one line under the other (wrapped). */ +export const oldLines = (lines: readonly string[]) => shortLines(lines).map((l) => plainLine(DEL, l)).join(' \n') + +/** + * Only the lines that changed: − what was there, + what is there now, the changed words picked out (a one-word change + * is visible, a 15-line note is not repeated). Lines wrap: a long line is never cut at the panel's edge. + */ +export function diffLines(del: readonly string[], ins: readonly string[]): string { + const linesBefore = shortLines(del), linesNow = shortLines(ins) + // Line k of the old code is compared word by word with line k of the new; the lines past the pairs are shown whole. + const pairs = Math.min(del.length, ins.length, THREAD_LIMITS.bannerLines) + const oldOut = linesBefore.map((line, k) => (k < pairs ? '' : plainLine(DEL, line))) + const newOut = linesNow.map((line, k) => (k < pairs ? '' : plainLine(INS, line))) + for (let k = 0; k < pairs; k++) { + const oldTokens = tokensOf(linesBefore[k]), newTokens = tokensOf(linesNow[k]) + const changed = changedTokens(oldTokens, newTokens) + oldOut[k] = wrappedLine(DEL, oldTokens, changed.oldChanged) + newOut[k] = wrappedLine(INS, newTokens, changed.newChanged) + } + return [...oldOut, ...newOut].join(' \n') } export interface StaleFacts { @@ -28,14 +108,14 @@ export interface StaleFacts { missing: boolean /** The file is shorter than the note's lines: its length now. */ pastEnd?: number - /** What the lines were (a code or diff block), or '' when there is nothing to show. */ + /** What the lines were (oldLines or diffLines), or '' when there is nothing to show. */ was: string /** The branch the note was written on, when it is not this one. */ branch?: string } const gone = (f: StaleFacts) => `**\`${f.file}\` no longer exists.**` -/** A code block starts on its own line. */ +/** Its own paragraph. */ const wasPart = (f: StaleFacts) => (f.was ? `\n\n${f.was}` : '') const move = (f: StaleFacts, links: Links) => links.to('Move', Cmd.moveToSelection, f.id) diff --git a/src/threads/comments.ts b/src/threads/comments.ts index b651e8d..4aaf83e 100644 --- a/src/threads/comments.ts +++ b/src/threads/comments.ts @@ -15,11 +15,11 @@ import { isAgent, mine } from '../notes/identity' import { docUri, placement } from '../notes/location' import { seenCount, visitFrom } from '../notes/seen' import type { Note } from '../notes/store' -import { diffBlock, oldCodeBlock, staleText } from './banner' +import { diffLines, oldLines, staleText } from './banner' import { COMMENT_CONTEXT } from './context' import { Links } from './links' import { linkedMarkdown, shownKey, systemRow, type MessageShape, type ThreadContributions, type ThreadRow } from './rows' -import { messageText, verbatimText } from './text' +import { appliedOf, appliedText, messageText, verbatimText } from './text' import { hiddenReplies, timeline, type TimelineEntry } from './timeline' export { suggestionOf } from './text' @@ -73,9 +73,9 @@ function wasText(n: Note): string { const a = n.data.anchor.text if (!a.trim()) return '' const doc = openDoc(docUri(n)) - if (!doc || placement.pastEnd(n.data.id) !== undefined) return oldCodeBlock(a.split('\n')) + if (!doc || placement.pastEnd(n.data.id) !== undefined) return oldLines(a.split('\n')) const ch = lineDiff(a.split('\n'), docLines(doc).slice(n.data.range.start - 1, n.data.range.end)) - return ch.del.length || ch.ins.length ? diffBlock(ch.del, ch.ins) : '' + return ch.del.length || ch.ins.length ? diffLines(ch.del, ch.ins) : '' } function staleBanner(n: Note): ThreadRow[] { @@ -117,8 +117,13 @@ function messageMarkdown(n: Note, i: number, shapes: MessageShape[]): vscode.Mar } const codeLinks = shapes.flatMap((s) => s.codeLinks ?? []) const key = checkLinkKey(n.data.id, i) - const apply = isAgent(n.data.messages[i]) && !n.data.target - ? (k: number) => links.titled('Apply suggestion', `Replace ${rangeLabel(n)} with this · Ctrl+Z undoes`, Cmd.applySuggestion, n.data.id, i, k) + const m = n.data.messages[i] + const applied = (k: number) => appliedOf(m.extra, k) + const apply = isAgent(m) && !n.data.target + ? (k: number) => { + const a = applied(k) + return a ? appliedText(a) : links.titled('Apply suggestion', `Replace ${rangeLabel(n)} with this · Ctrl+Z undoes`, Cmd.applySuggestion, n.data.id, i, k) + } : undefined const md = linkedMarkdown(messageText({ body: text, suffix, apply, codeLinks, diff --git a/src/threads/context.ts b/src/threads/context.ts index 3666464..cca8a12 100644 --- a/src/threads/context.ts +++ b/src/threads/context.ts @@ -2,7 +2,7 @@ // /stale/`, `comment == message`); test/threadContext.test.ts checks every word the menus use is one of these. No // vscode here. -/** A note thread's words: "note;open;stale;asking;check" (the ones that apply). */ +/** A note thread's words: "note;open;stale;asking;check;concern" (the ones that apply). */ export const THREAD_WORD = { note: 'note', open: 'open', @@ -12,6 +12,12 @@ export const THREAD_WORD = { asking: 'asking', /** A question of the understanding check. */ check: 'check', + /** The check's grader found a concern about the code (its actions are the thread's menu). */ + concern: 'concern', + /** …a TODO is added for it already. */ + todo: 'todo', + /** …it is flagged for the reviewer. */ + flagged: 'flagged', } as const export type ThreadWord = (typeof THREAD_WORD)[keyof typeof THREAD_WORD] diff --git a/src/threads/index.ts b/src/threads/index.ts index b11f920..2ad932c 100644 --- a/src/threads/index.ts +++ b/src/threads/index.ts @@ -1,8 +1,9 @@ // The notes' comment threads: one per note drawn in the editor, its comments, links and buttons. import * as vscode from 'vscode' -import { Cmd } from '../platform/commands' +import { Cmd, HiddenCmd, linkCall } from '../platform/commands' import type { WorkspaceEvents } from '../platform/events' import { registerCommands } from '../platform/registerCommands' +import type { ConcernAction } from '../check/concernState' import type { NotesApi } from '../notes/model' import { ThreadsPorts, check, journeys, tour, useThreadsPorts } from './ports' import { ThreadContributions, type ThreadContribution } from './rows' @@ -35,9 +36,24 @@ export function activateThreads(context: vscode.ExtensionContext, ports: Threads const view = new ThreadView(ports.controller, settleGate(), contributions) useThreadView(view) context.subscriptions.push(view, { dispose: () => { useThreadView(undefined); disposeSettleGate() } }) + /** A concern's action from the thread's menu (VS Code passes the thread, or the reply box with its thread). */ + const concern = (action: ConcernAction) => (arg?: vscode.CommentThread | vscode.CommentReply) => { + const thread = arg && 'thread' in arg ? arg.thread : arg + const n = thread && view.noteOf(thread) + return n ? vscode.commands.executeCommand(Cmd.checkConcern, n.data.id, action) : undefined + } registerCommands(context, { [Cmd.expandThread]: (id: string) => view.expand(id), [Cmd.collapseThread]: (id: string) => view.collapse(id), + [HiddenCmd.link]: (key: unknown) => { + const call = linkCall(key) + return call ? vscode.commands.executeCommand(call.command, ...call.args) : undefined + }, + [HiddenCmd.concernFix]: concern('fix'), + [HiddenCmd.concernTodo]: concern('todo'), + [HiddenCmd.concernFlag]: concern('flag'), + [HiddenCmd.concernFixed]: concern('fixed'), + [HiddenCmd.concernDismiss]: concern('dismiss'), }) return { has: (id) => view.has(id), diff --git a/src/threads/rows.ts b/src/threads/rows.ts index 838ac29..78171ac 100644 --- a/src/threads/rows.ts +++ b/src/threads/rows.ts @@ -1,7 +1,7 @@ // What a feature adds to a note's thread (Claude answering, the check's grading, a step question's link back), and // the rows themselves: comments.ts renders a thread from these without knowing the features. import * as vscode from 'vscode' -import { SYSTEM_COMMANDS } from '../platform/commands' +import { HiddenCmd, shortLinks, SYSTEM_COMMANDS } from '../platform/commands' import type { Note } from '../notes/store' import { COMMENT_CONTEXT, type ThreadWord } from './context' import { Links } from './links' @@ -79,11 +79,12 @@ export class ThreadContributions { } } -/** Markdown that may run what `links` says (nothing to run: untrusted). */ +/** Markdown that may run what `links` says (nothing to run: untrusted). Links with arguments get a short key: a + * comment's Markdown is what a screen reader reads. */ export function linkedMarkdown(text: string, links: Links): vscode.MarkdownString { - const md = new vscode.MarkdownString(text) const commands = links.commands - if (commands.length) md.isTrusted = { enabledCommands: commands } + const md = new vscode.MarkdownString(commands.length ? shortLinks(text, commands) : text) + if (commands.length) md.isTrusted = { enabledCommands: [...commands, HiddenCmd.link] } return md } diff --git a/src/threads/rows/check.ts b/src/threads/rows/check.ts index 7ff137f..85d4f6c 100644 --- a/src/threads/rows/check.ts +++ b/src/threads/rows/check.ts @@ -6,28 +6,27 @@ import { Cmd, HiddenCmd } from '../../platform/commands' import { isAgent } from '../../notes/identity' import type { Note } from '../../notes/store' import type { TourApi } from '../../tour/api' -import { THREAD_WORD } from '../context' +import { THREAD_WORD, type ThreadWord } from '../context' import type { Links } from '../links' import type { ThreadsCheck } from '../ports' import { systemRow, type ThreadContribution, type ThreadRow } from '../rows' type Concern = NonNullable -/** A concern the grader found: Suggest a fix, Add TODO, Flag for reviewer; quiet: Mark fixed once it is flagged (it - * leaves the merge request), Dismiss with a reason when it is wrong. */ -function concernRow(id: string, c: Concern): ThreadRow { - const text = (l: Links) => { - const act = (label: string, action: string) => l.to(label, Cmd.checkConcern, id, action) - const acts = [ - act('Suggest a fix', 'fix'), - c.todo ? `TODO added at ${c.todo}` : act('Add TODO', 'todo'), - act(c.flagged ? (c.by ? `Flagged by ${c.by} ✓` : 'Flagged ✓') : 'Flag for reviewer', 'flag'), - ...(c.flagged ? [act('Mark fixed', 'fixed')] : []), - act('Dismiss', 'dismiss'), - ] - return `⚠ ${c.text}\n\n${acts.join(' · ')}` - } - return { comment: systemRow(text, c.suspect ? 'Understanding check' : 'Found while grading') } +/** A concern the grader found, and what was done about it. Its actions (Suggest a fix, Add TODO, Flag for reviewer, + * Mark fixed, Dismiss) are the thread's menu: links here were read aloud as their command URIs. */ +function concernRow(c: Concern): ThreadRow { + const done = [ + c.todo ? `TODO added at ${c.todo}` : '', + c.flagged ? (c.by ? `Flagged by ${c.by} ✓` : 'Flagged ✓') : '', + ].filter(Boolean).join(' · ') + return { comment: systemRow(`⚠ ${c.text}${done ? `\n\n${done}` : ''}`, c.suspect ? 'Understanding check' : 'Found while grading') } +} + +/** The words the concern's menu items look for. */ +export function concernWords(c: Concern | undefined): ThreadWord[] { + if (!c) return [] + return [THREAD_WORD.concern, ...(c.todo ? [THREAD_WORD.todo] : []), ...(c.flagged ? [THREAD_WORD.flagged] : [])] } /** An open question whose code a journey of the repository walks: one link to that step. */ @@ -44,7 +43,7 @@ function statusRows(n: Note, chk: ThreadsCheck, tour: Pick `⚠ ${s.error} ${l.to('Try again', Cmd.gradeCheck, id)}`, 'Code Notes') }] : []), ] @@ -58,7 +57,8 @@ export function checkRows(check: () => ThreadsCheck | undefined, tour: () => Pic if (!chk) return undefined const s = chk.threadStatus(n) const isCheck = chk.isCheck(n) - return { pinned: chk.pinned(n), working: !!s?.checking, failed: !!s?.error, words: isCheck ? [THREAD_WORD.check] : [], neverResolved: isCheck } + const words = [...(isCheck ? [THREAD_WORD.check] : []), ...concernWords(s?.concern)] + return { pinned: chk.pinned(n), working: !!s?.checking, failed: !!s?.error, words, neverResolved: isCheck } }, message: (n, index) => { const chk = check() diff --git a/src/threads/text.ts b/src/threads/text.ts index e693c04..f3a45f0 100644 --- a/src/threads/text.ts +++ b/src/threads/text.ts @@ -4,7 +4,7 @@ import type { StepLink } from '../core/format/journeyModel' import { linkify } from '../core/linkifyAnswer' import { linkPhrases, PH, PH_RE } from '../core/codeLinkText' -import { escapeTags } from '../core/escape' +import { escapeMarkdown, escapeTags } from '../core/escape' /** A piece of a message between its ``` fences; suggestion blocks are numbered in order (`k`) for Apply. */ export type Segment = @@ -34,6 +34,26 @@ export function suggestionOf(body: string, k: number): string | undefined { return undefined } +/** A suggestion applied: which block of the message (`suggestion`), by whom, when. Kept in the note file as the + * message's `applied` list, so a reader of the thread later sees it was taken. */ +export interface Applied { suggestion: number; by: string; at: string } + +/** Who applied suggestion `k` of a message (its `extra.applied`), if anyone did. */ +export function appliedOf(extra: Record | undefined, k: number): Applied | undefined { + const list = extra?.applied + if (!Array.isArray(list)) return undefined + return list.find((a): a is Applied => !!a && typeof a === 'object' && a.suggestion === k && typeof a.by === 'string') +} + +/** The message's extra fields with suggestion `k` marked applied by `by` (the other fields as they were). */ +export function withApplied(extra: Record | undefined, a: Applied): Record { + const list = Array.isArray(extra?.applied) ? extra.applied : [] + return { ...extra, applied: [...list, a] } +} + +/** What stands under an applied suggestion instead of Apply. */ +export const appliedText = (a: Applied) => `_Applied ✓ by ${escapeMarkdown(a.by)}_` + /** A code link of the check: a phrase of the message and the lines it shows. */ export type CodeLinkRef = StepLink diff --git a/test/answerLinks.test.ts b/test/answerLinks.test.ts index fff074c..95f7527 100644 --- a/test/answerLinks.test.ts +++ b/test/answerLinks.test.ts @@ -15,6 +15,8 @@ test('references in answers are links, inside parentheses and lists, never with assert.equal(L('[x](src/x.ts#L4)'), '[x](cmd:src/x.ts:4)') assert.equal(L('lines src/a.ts:12-20.'), 'lines [src/a.ts:12-20](cmd:src/a.ts:12).') assert.equal(L('outside /home/me/other/b.ts:2'), 'outside ~/other/b.ts:2', 'outside the repo: no link, no home path') + assert.equal(L('See package.json:3.'), 'See [package.json:3](cmd:package.json:3).', 'a root file, as the agents\' README says') + assert.equal(L('e.g:3'), 'e.g:3', 'two single letters are not a file') assert.equal(L('[docs](https://example.com/a/b.md:3)'), '[docs](https://example.com/a/b.md:3)') assert.equal(L('![shot](img/a.png)'), '[image: shot](img/a.png)') }) @@ -55,8 +57,11 @@ test('the reference patterns, case by case: the bare reference assembled, and wh const P = ANSWER_LINK_PATTERNS // The bare reference as a reader would have to assemble it: not after a word, "/", "~", ".", "-" or a kept link; // an optional backtick; the path (folders, then a file name); its line. + // A path is folders then a file name, or a file at the root (not two single letters, not a host name). assert.equal(P.BARE_REF.source, - String.raw`(? [...s.matchAll(new RegExp(re.source, 'g'))].map((m) => [...m]) const table: [RegExp, string, (string | undefined)[][]][] = [ [P.IMAGE, 'see ![chart](img/a.png "t")', [['![chart](img/a.png "t")', 'chart', 'img/a.png']]], @@ -66,7 +71,12 @@ test('the reference patterns, case by case: the bare reference assembled, and wh [P.TARGET, 'src/a.ts#L12-L20', [['src/a.ts#L12-L20', 'src/a.ts', '12', undefined]]], [P.BARE_REF, 'at src/a.ts:12-20.', [['src/a.ts:12-20', 'src/a.ts', '12', undefined]]], [P.BARE_REF, '(`src/a.ts#L4`)', [['`src/a.ts#L4`', 'src/a.ts', undefined, '4']]], - [P.BARE_REF, 'a.ts:3 ~/x/b.ts:2 lib/src/c.ts:1', [['lib/src/c.ts:1', 'lib/src/c.ts', '1', undefined]]], + [P.BARE_REF, 'a.ts:3 ~/x/b.ts:2 lib/src/c.ts:1', [['a.ts:3', 'a.ts', '3', undefined], ['lib/src/c.ts:1', 'lib/src/c.ts', '1', undefined]]], + [P.BARE_REF, 'See package.json:3 and docs/agent-protocol.md#L5.', [ + ['package.json:3', 'package.json', '3', undefined], ['docs/agent-protocol.md#L5', 'docs/agent-protocol.md', undefined, '5']]], + [P.BARE_REF, '`README.md#L2`, vite.config.ts:9, main.c:4', [ + ['`README.md#L2`', 'README.md', undefined, '2'], ['vite.config.ts:9', 'vite.config.ts', '9', undefined], ['main.c:4', 'main.c', '4', undefined]]], + [P.BARE_REF, 'e.g:3 i.e:4 example.com:443 api.example.org:80 Makefile:2 package.json 1.5:3', []], ] for (const [re, text, want] of table) assert.deepEqual(all(re, text), want, `${text}`) }) diff --git a/test/commands.test.ts b/test/commands.test.ts index 78e795b..c1237f4 100644 --- a/test/commands.test.ts +++ b/test/commands.test.ts @@ -2,7 +2,7 @@ import { test } from 'node:test' import assert from 'node:assert/strict' import * as fs from 'fs' import * as path from 'path' -import { BANNER_COMMANDS, Cmd, commandUri, HiddenCmd, MESSAGE_COMMANDS, SYSTEM_COMMANDS } from '../src/platform/commands' +import { BANNER_COMMANDS, clickedLink, Cmd, cmdLink, commandUri, HiddenCmd, linkCall, linkKey, MESSAGE_COMMANDS, shortLinks, SYSTEM_COMMANDS } from '../src/platform/commands' const ROOT = path.join(__dirname, '../..') const pkg = JSON.parse(fs.readFileSync(path.join(ROOT, 'package.json'), 'utf8')) @@ -47,3 +47,21 @@ test('commandUri: the arguments as JSON in the query', () => { assert.equal(commandUri(Cmd.openAt), 'command:codeNotes.openAt') assert.equal(commandUri(Cmd.openAt, 'a b', 2), `command:codeNotes.openAt?${encodeURIComponent('["a b",2]')}`) }) + +test('shortLinks: a link with arguments runs through a short key (no percent-encoded JSON for a screen reader to read)', () => { + const folder = 'file:///work/shop' + const md = `See ${cmdLink('redeemGiftCard', Cmd.openAt, folder, 'api/giftcards.js', 1)} · ${cmdLink('Next', HiddenCmd.nextCheckQuestion)}` + const short = shortLinks(md, [Cmd.openAt, HiddenCmd.nextCheckQuestion]) + const m = /^See \[redeemGiftCard\]\(command:codeNotes\.link\?(\d{6})\) · \[Next\]\(command:codeNotes\.nextCheckQuestion\)$/.exec(short) + assert.ok(m, short) + assert.deepEqual(linkCall(Number(m[1])), { command: Cmd.openAt, args: [folder, 'api/giftcards.js', 1] }) + assert.deepEqual(clickedLink(HiddenCmd.link, [Number(m[1])]), { command: Cmd.openAt, args: [folder, 'api/giftcards.js', 1] }) + assert.equal(shortLinks(md, [Cmd.openAt, HiddenCmd.nextCheckQuestion]), short, 'the same link keeps its key (a redraw is a no-op)') + assert.doesNotMatch(short, /%/) + // A command the text may not run is left as it is (the short key would let it run). + assert.equal(shortLinks(md, []), md) + // A link to another note gets another key. + assert.notEqual(linkKey(Cmd.openAt, [folder, 'b.js', 1]), Number(m[1])) + assert.equal(linkCall(1), undefined) + assert.equal(linkCall('123456'), undefined, 'only a number is a key') +}) diff --git a/test/integration/check/answers.ts b/test/integration/check/answers.ts index b491ef3..6ede649 100644 --- a/test/integration/check/answers.ts +++ b/test/integration/check/answers.ts @@ -221,15 +221,21 @@ export const answersTests = [ await until('D opens q3', () => codeEditor()?.document.uri.fsPath === limitsPath && noteById(noteOf('q3').id)?.threadExpanded) await answer('q3', 'GOOD CONCERN: they are in memory, so a restart forgets them.') await until('q3 passed with a concern', () => view()?.rows[2].flag === 'concern') - await vscode.commands.executeCommand('codeNotes.checkConcern', noteOf('q3').id, 'flag') + // The concern's actions are the thread's menu: its words say which apply; a menu item gets the reply box's thread. + const words = () => String(api.thread(noteOf('q3').id)?.contextValue).split(';') + await until('the concern\'s menu', () => words().includes('concern') && !words().includes('flagged') && !words().includes('todo')) + await vscode.commands.executeCommand('codeNotes.concernFlag', { thread: api.thread(noteOf('q3').id), text: '' }) await until('flagged in the file', () => readCheck().questions[2].concern?.flagged === true) await until('flagged on the row', () => view().rows[2].flag === 'flagged for review') // Add TODO next to the flag: one short line in the code, said in the thread; the flag stays. - await vscode.commands.executeCommand('codeNotes.checkConcern', noteOf('q3').id, 'todo') + await until('Flag for reviewer leaves the menu', () => words().includes('flagged')) + await vscode.commands.executeCommand('codeNotes.concernTodo', api.thread(noteOf('q3').id)) const todo = await until('a TODO in the code', () => { const ls = fs.readFileSync(limitsPath, 'utf8').split('\n'); const i = ls.findIndex((l) => l.includes('TODO')); return i >= 0 && ls.slice(i, i + 2) }) // The whole concern (wrapped, nothing cut), at the line's indentation. assert.ok(todo.every((l) => l.length <= 100) && todo.map((l) => l.replace(/^\/\/( TODO:)?\s+/, '')).join(' ').includes('a restart lets everyone order again.'), `the whole concern: ${todo.join(' / ')}`) await until('said in the thread', () => threadComments(noteOf('q3').id).some((c) => /TODO added at limits\.js:1\b/.test(commentBody(c)))) assert.equal(readCheck().questions[2].concern?.flagged, true, 'Add TODO keeps the flag') + await until('Add TODO leaves the menu', () => words().includes('todo')) + assert.ok(threadComments(noteOf('q3').id).every((c) => !/%5B|%22/.test(commentBody(c))), 'no percent-encoded JSON in the thread') }), ] diff --git a/test/integration/check/askAndFix.ts b/test/integration/check/askAndFix.ts index 1d968da..0a04dba 100644 --- a/test/integration/check/askAndFix.ts +++ b/test/integration/check/askAndFix.ts @@ -48,8 +48,10 @@ export const askAndFixTests = [ }), test('a concern dismissed with a reason (Dismiss, beside Mark fixed): kept in the file, gone from the thread, the row and the merge request', async () => { - const actions = threadComments(noteOf('q3').id).flatMap(linksOf).filter((l) => l.command === 'codeNotes.checkConcern').map((l) => `${l.label}:${l.args[1]}`) - assert.deepEqual(actions.slice(-2), ['Mark fixed:fixed', 'Dismiss:dismiss'], `the quiet actions, Dismiss beside Mark fixed: ${actions}`) + // The concern's actions are the thread's menu (named buttons), not links in its text: Mark fixed once flagged, Dismiss. + const words = String(api.thread(noteOf('q3').id)?.contextValue).split(';') + assert.ok(['concern', 'flagged'].every((w) => words.includes(w)), `the menu's words: ${words}`) + assert.deepEqual(threadComments(noteOf('q3').id).flatMap(linksOf).filter((l) => l.command === 'codeNotes.checkConcern'), [], 'no action links in the text') await vscode.commands.executeCommand('codeNotes.checkConcern', noteOf('q3').id, 'dismiss', 'A restart is fine: counts are per hour anyway.') await until('dismissed', () => readCheck().questions[2].concern?.dismissed?.reason === 'A restart is fine: counts are per hour anyway.' && readCheck().questions[2].concern.flagged === false && !view().rows[2].flag) await until('gone from the thread', () => !threadComments(noteOf('q3').id).some((c) => /Found while grading/.test(String((c.author as any)?.name)))) diff --git a/test/integration/check/support.ts b/test/integration/check/support.ts index cc7dd37..ea837cb 100644 --- a/test/integration/check/support.ts +++ b/test/integration/check/support.ts @@ -7,19 +7,21 @@ import * as path from 'path' import assert from 'assert' import { cdp, checkFrame, ui } from '../devtools' import { api, checkFile, readCheck } from './context' +import { clickedLink } from '../../../src/platform/commands' /* eslint-disable @typescript-eslint/no-explicit-any */ /** A command link in a comment's markdown: its text (markup taken out), the command and its arguments. */ export type CommandLink = { label: string; command: string; args: unknown[] } -/** The command links in a comment's markdown, as VS Code runs them when clicked. */ +/** The command links in a comment's markdown, as VS Code runs them when clicked (a short link as its own command). */ export function commandLinks(markdown: string): CommandLink[] { return [...markdown.matchAll(/\[([^\]]*)\]\(command:([\w.]+)(?:\?([^ )]+))?[^)]*\)/g)].map((m) => { let args: unknown = [] try { if (m[3]) args = JSON.parse(decodeURIComponent(m[3])) } catch { assert.fail(`the arguments of the ${m[2]} link do not parse: ${m[3]}`) } const label = m[1].replace(/<[^>]*>/g, '').replace(/\\(.)/g, '$1').trim() - return { label, command: m[2], args: Array.isArray(args) ? args : [args] } + // A thread's short link (codeNotes.link?) runs the command it stands for. + return { label, ...clickedLink(m[2], Array.isArray(args) ? args : [args]) } }) } diff --git a/test/integration/main/context.ts b/test/integration/main/context.ts index 47e485f..e5e8d4a 100644 --- a/test/integration/main/context.ts +++ b/test/integration/main/context.ts @@ -5,6 +5,7 @@ import * as vscode from 'vscode' import * as fs from 'fs' import * as path from 'path' import type { TestApi } from '../../../src/testApi' +import { clickedLink } from '../../../src/platform/commands' import type { SuiteContext } from '../helpers' import { waiter } from '../helpers' @@ -71,6 +72,15 @@ export const setting = (key: string, value: unknown) => vscode.workspace.getConf /** A thread's first comment as markdown. */ export const bodyOf = (c: vscode.Comment) => (c.body as vscode.MarkdownString).value +/** The command links in Markdown as a click runs them: label, command and arguments (a thread's short link + * `codeNotes.link?` as the command it stands for). */ +export function commandLinksIn(markdown: string): { label: string; command: string; args: unknown[] }[] { + return [...markdown.matchAll(/\[([^\]]*)\]\(command:([\w.]+)(?:\?([^ )]+))?/g)].map((m) => { + const args = m[3] ? JSON.parse(decodeURIComponent(m[3])) : [] + return { label: m[1], ...clickedLink(m[2], Array.isArray(args) ? args : [args]) } + }) +} + export const closeAllEditors = () => vscode.commands.executeCommand('workbench.action.closeAllEditors') /** Is a text tab whose path matches `re` open in any group? */ diff --git a/test/integration/main/journeyTour.ts b/test/integration/main/journeyTour.ts index 823499f..04dd1c4 100644 --- a/test/integration/main/journeyTour.ts +++ b/test/integration/main/journeyTour.ts @@ -9,7 +9,7 @@ import assert from 'assert' import { appendMessage, now, quiet, settle, test, windowShot } from '../helpers' import { shotsInBothThemes } from './themeShots' import { journey, step, writeLines } from '../fixtures' -import { at, bodyOf, codeLenses, ctx, journeysDir, journeysTree, lenses, notesTree, setting, snap, tabOpen, tour, until, wsPath } from './context' +import { at, bodyOf, codeLenses, commandLinksIn, ctx, journeysDir, journeysTree, lenses, notesTree, setting, snap, tabOpen, tour, until, wsPath } from './context' import { demoPath, demoStep, demoSteps, writeDemo } from './shared' /* eslint-disable @typescript-eslint/no-explicit-any */ @@ -349,7 +349,7 @@ export const journeyTourTests = [ test('End keeps a resumable place; Next resumes; the sidebar marks the running tour', async () => { // Not walking: the step question links back to its step, with the journey's name. - await until('the back-link', () => /\[↩ Step 3 · Demo\]\(command:codeNotes\.openStepLink/.test(bodyOf(ctx.api.thread(stepQuestion()!.id)!.comments[0]))) + await until('the back-link', () => commandLinksIn(bodyOf(ctx.api.thread(stepQuestion()!.id)!.comments[0])).some((l) => l.label === '↩ Step 3 · Demo' && l.command === 'codeNotes.openStepLink')) assert.ok(tabOpen(/flow\.ts$/), 'End keeps the code you were reading') assert.ok(journeysTree().some((l: string) => /journey:Demo · step 3\/4$/.test(l)), `the sidebar row: its title and, after End, where it was left:\n${journeysTree().join('\n')}`) await vscode.commands.executeCommand('codeNotes.notes.focus') diff --git a/test/integration/main/notesReview.ts b/test/integration/main/notesReview.ts index f070917..bf624a0 100644 --- a/test/integration/main/notesReview.ts +++ b/test/integration/main/notesReview.ts @@ -7,7 +7,7 @@ import * as fs from 'fs' import assert from 'assert' import { appendMessage, now, quiet, readJson, settle, sleep, test } from '../helpers' import { agentNote, writeNote } from '../fixtures' -import { at, bodyOf, tour, closeAllEditors, ctx, journeysTree, noteById, notePath, notesTree, snap, until, wsPath } from './context' +import { at, bodyOf, commandLinksIn, tour, closeAllEditors, ctx, journeysTree, noteById, notePath, notesTree, snap, until, wsPath } from './context' import { UNREAD_FINDING } from './shared' /* eslint-disable @typescript-eslint/no-explicit-any */ @@ -41,13 +41,7 @@ function rowsOf(lines: string[]): Row[] { const notesRows = () => rowsOf(notesTree()) /** The command links in a comment's markdown, as VS Code runs them when clicked: the command and its arguments. */ -function commandLinks(markdown: string): { command: string; args: unknown[] }[] { - return [...markdown.matchAll(/\(command:([\w.]+)(?:\?([^ )]+))?/g)].map((m) => { - let args: unknown = [] - try { if (m[2]) args = JSON.parse(decodeURIComponent(m[2])) } catch { assert.fail(`the arguments of the ${m[1]} link do not parse: ${m[2]}`) } - return { command: m[1], args: Array.isArray(args) ? args : [args] } - }) -} +const commandLinks = (markdown: string) => commandLinksIn(markdown) export const notesReviewTests = [ test('R resolves the note at the cursor (recorded in "events") and opens the next unread note', async () => { diff --git a/test/integration/main/requests.ts b/test/integration/main/requests.ts index 8d3ef87..e032fc5 100644 --- a/test/integration/main/requests.ts +++ b/test/integration/main/requests.ts @@ -10,7 +10,7 @@ import * as path from 'path' import assert from 'assert' import { EXT_ID, claudeRuns, fakeCalls, flag, quiet, readJson, test, untilEqual } from '../helpers' import { readResult, requestFile, writeRequest } from '../fixtures' -import { closeAllEditors, ctx, noteById, setting, snap, until } from './context' +import { closeAllEditors, commandLinksIn, ctx, noteById, setting, snap, until } from './context' import { repoJourneysDir, savingJourney } from './shared' /* eslint-disable @typescript-eslint/no-explicit-any */ @@ -171,7 +171,7 @@ export const requestsTests = [ await untilEqual('its thread open, titled by the question', () => [!!noteById(asked.id)?.threadExpanded, noteById(asked.id)?.threadLabel], [true, 'Where is the note written?']) await until('Claude answered in it', () => noteById(asked.id)?.messages.at(-1)?.author === 'Claude', 10000) // The answer as the thread shows it (once re-rendered): its reference is a link. - await until('the answer\'s reference is a link', () => ctx.api.thread(asked.id)?.comments.some((c: vscode.Comment) => c.author.name === 'Claude' && /\[`src\/renamed\.ts:3`\]\(command:codeNotes\.openAt\?/.test((c.body as vscode.MarkdownString).value))) + await until('the answer\'s reference is a link', () => ctx.api.thread(asked.id)?.comments.some((c: vscode.Comment) => c.author.name === 'Claude' && commandLinksIn((c.body as vscode.MarkdownString).value).some((l) => l.label === '`src/renamed.ts:3`' && l.command === 'codeNotes.openAt'))) fs.unlinkSync(asked.path) }), diff --git a/test/integration/main/threads.ts b/test/integration/main/threads.ts new file mode 100644 index 0000000..17647a7 --- /dev/null +++ b/test/integration/main/threads.ts @@ -0,0 +1,109 @@ +// Threads and anchors: an applied suggestion is recorded on its message and can't be applied twice, thread links are +// short (a screen reader reads a comment's Markdown as is), a stale note is tinted in the editor and its banner shows +// the old and the new line as text that wraps, and a move waits in the status bar (no notification) for Enter. +// Source: src/notes/suggestion.ts, src/platform/commands.ts (shortLinks), src/threads/, src/notes/decorations.ts, +// src/notes/move.ts. +import * as vscode from 'vscode' +import * as fs from 'fs' +import assert from 'assert' +import { appendMessage, now, quiet, readJson, test } from '../helpers' +import { agentNote, writeLines, writeNote } from '../fixtures' +import { cdp, ui } from '../devtools' +import { BARS, marksOf } from '../../../src/notes/decorations' +import { HiddenCmd } from '../../../src/platform/commands' +import { commandLinksIn, ctx, noteById, notePath, snap, until, wsPath } from './context' + +/* eslint-disable @typescript-eslint/no-explicit-any */ +const noteId = (tag: string) => `20261126-100000-${tag}` +const bodyOf = (c: vscode.Comment) => (typeof c.body === 'string' ? c.body : c.body.value) +const bodies = (id: string): string[] => (ctx.api.thread(id)?.comments ?? []).map(bodyOf) + +/** The command links of a thread's comments, as a click runs them (a short link's own command and arguments). */ +const links = (id: string) => bodies(id).flatMap(commandLinksIn) + +/** The link a click on `[label](command:…)` runs, as VS Code runs it. */ +const click = (l: { command: string; args: unknown[] }) => vscode.commands.executeCommand(l.command, ...l.args) + +/** A file of the test's own, and a note by the person on line `line`, read, anchored on disk, with its thread. */ +async function noteOn(tag: string, lines: string[], line: number, body = 'Why this?'): Promise<{ id: string; file: string; rel: string }> { + const rel = `src/threads-${tag}.ts` + writeLines(wsPath(rel), lines) + const id = noteId(tag) + writeNote(ctx.notesDir, id, { file: rel, range: { start: line, end: line }, status: 'open', messages: [{ author: snap().me, role: 'human', body }] }) + await until(`${id} anchored on disk`, () => readJson(notePath(id)).anchor?.text === lines[line - 1]) + await vscode.window.showTextDocument(vscode.Uri.file(wsPath(rel))) + await until(`${id}'s thread`, () => ctx.api.thread(id)) + return { id, file: wsPath(rel), rel } +} + +export const threadsTests = [ + test('Apply suggestion: recorded on the message in the note file, the link reads Applied ✓, a second Apply does nothing', async () => { + const n = await noteOn('apply', ['export const a = 1', 'export const b = 2'], 2, 'Make b 3?') + appendMessage(notePath(n.id), { author: 'claude', role: 'agent', body: 'Yes:\n\n```suggestion\nexport const b = 3\n```', at: now() }) + const apply = await until('the Apply link', () => links(n.id).find((l) => l.command === 'codeNotes.applySuggestion')) + await click(apply) + const doc = await vscode.workspace.openTextDocument(n.file) + await until('applied', () => doc.lineAt(1).text === 'export const b = 3') + const applied = readJson(notePath(n.id)).messages[1].applied + assert.equal(applied?.length, 1, `the note file records it: ${JSON.stringify(readJson(notePath(n.id)).messages[1])}`) + assert.deepEqual({ suggestion: applied[0].suggestion, by: applied[0].by }, { suggestion: 0, by: snap().me }) + await until('the link reads Applied ✓', () => bodies(n.id).some((b) => b.includes('Applied ✓')) && !links(n.id).some((l) => l.command === 'codeNotes.applySuggestion')) + // Clicked again (a link drawn before): nothing changes. + assert.equal(await ctx.api.applySuggestion(n.id, 1, 0), false) + await quiet(500, 'a second copy of the suggestion') + assert.equal(doc.getText(), 'export const a = 1\nexport const b = 3\n') + assert.equal(readJson(notePath(n.id)).messages[1].applied.length, 1) + await doc.save() + }), + + test('thread links hold no percent-encoded JSON; a short link runs its command (a root file:line opens it)', async () => { + writeLines(wsPath('tool.json'), ['{', ' "a": 1,', ' "b": 2', '}']) + const n = await noteOn('links', ['export const c = 1'], 1) + appendMessage(notePath(n.id), { author: 'claude', role: 'agent', body: 'See tool.json:3 and src/app.ts:2.', at: now() }) + const open = await until('the answer\'s links', () => { + const l = links(n.id).filter((x) => x.command === 'codeNotes.openAt') + return l.length === 2 ? l : undefined + }) + for (const b of bodies(n.id)) assert.doesNotMatch(b, /%5B|%22|%7B/, `no percent-encoded JSON in a comment: ${b}`) + assert.ok(bodies(n.id).some((b) => /\[tool\.json:3\]\(command:codeNotes\.link\?\d{6}\)/.test(b)), bodies(n.id).join('\n')) + await click(open[0]) + await until('tool.json open at line 3', () => vscode.window.activeTextEditor?.document.uri.fsPath === wsPath('tool.json') + && vscode.window.activeTextEditor.selection.active.line === 2) + const all = await vscode.commands.getCommands(true) + for (const c of [HiddenCmd.link, HiddenCmd.concernFix, HiddenCmd.concernTodo, HiddenCmd.concernFlag, HiddenCmd.concernFixed, HiddenCmd.concernDismiss]) { + assert.ok(all.includes(c), `${c} is registered (the concern's actions on its thread)`) + } + }), + + test('a stale note: its lines tinted and marked in the ruler; the banner shows the old and the new line, wrapped', async () => { + const was = '// The error the person must see is shown as an error (a toast), not a log line.' + const n = await noteOn('stale', ['export function run() {', was, '}'], 2) + fs.writeFileSync(n.file, ['export function run() {', '// The failure the user has to notice is surfaced (a toast), not a log line.', '}', ''].join('\n')) + await until('stale', () => noteById(n.id)?.stale === true) + const editor = await vscode.window.showTextDocument(vscode.Uri.file(n.file)) + await until('the stale tint on line 2', () => marksOf(editor).staleBar.some((r) => r.start.line === 1)) + assert.deepEqual(marksOf(editor).openBar.filter((r) => r.start.line === 1), [], 'not marked as an open note') + assert.equal(BARS.staleBar.background, 'codeNotes.staleBackground') + assert.equal(BARS.staleBar.ruler, 'editorWarning.foreground') + const banner = await until('the banner with − old / + new', () => bodies(n.id).find((b) => b.includes('The code changed since this note') && b.includes('\\+ '))) + assert.ok(!banner.includes('```'), `no code block (it scrolls sideways): ${banner}`) + assert.match(banner, /− \/\/ The `error` the `person must see` is `shown as an error`/) + assert.match(banner, /\\\+ \/\/ The `failure` the `user has to notice` is `surfaced`/) + }), + + test('Move: the status bar item waits for the selection, no notification; Enter (moveToSelection without a note) moves it', async () => { + const n = await noteOn('move', ['const one = 1', 'const two = 2', 'const three = 3', 'const four = 4'], 1) + const editor = await vscode.window.showTextDocument(vscode.Uri.file(n.file)) + editor.selection = new vscode.Selection(0, 0, 0, 0) + await vscode.commands.executeCommand('codeNotes.moveToSelection', n.id) + if (cdp) { + const page = await ui() + await until('Move note here in the status bar', async () => (await page.locator('.statusbar-item', { hasText: 'Move note here' }).count()) > 0) + assert.equal(await page.locator('.notification-toast', { hasText: /Move/ }).count(), 0, 'no notification') + } + editor.selection = new vscode.Selection(2, 0, 3, 14) + await vscode.commands.executeCommand('codeNotes.moveToSelection') // Enter's binding passes no note + await until('moved to lines 3-4', () => noteById(n.id)?.range?.start === 3 && noteById(n.id).range.end === 4) + assert.equal(readJson(notePath(n.id)).range.start, 3) + }), +] diff --git a/test/integration/suite.ts b/test/integration/suite.ts index 069af03..effd105 100644 --- a/test/integration/suite.ts +++ b/test/integration/suite.ts @@ -19,6 +19,7 @@ import { journeyMarksTests } from './main/journeyMarks' import { roundTripsTests } from './main/roundTrips' import { podcastTests } from './main/podcast' import { listenEditorTests } from './main/listenEditor' +import { threadsTests } from './main/threads' /** * The fake claude CLI, wired up for a chapter that runs after the notes chapter. The notes chapter wires it up @@ -55,6 +56,8 @@ export const chapters: Chapter[] = [ covers: 'a journey\'s podcast: the walk follows the audio, seeks, the audio while hidden podcast/' }, { name: 'listenEditor', file: 'main/listenEditor.ts', tests: listenEditorTests, ...fakeClaude, covers: 'the editor while a podcast plays: the card, the marks, what goes quiet tour/card.ts, podcast/marks.ts' }, + { name: 'threads', file: 'main/threads.ts', tests: threadsTests, ...fakeClaude, + covers: 'applied suggestions, short thread links, the stale tint and banner, Move with Enter notes/suggestion.ts, threads/, notes/move.ts' }, ] /** The entry point run.ts starts VS Code with (extensionTestsPath). */ diff --git a/test/threadText.test.ts b/test/threadText.test.ts index cf6f730..dfd8ba4 100644 --- a/test/threadText.test.ts +++ b/test/threadText.test.ts @@ -1,7 +1,7 @@ import { test } from 'node:test' import assert from 'node:assert/strict' import { aboutStepLine, codeBlock, messageText, segments, suggestionOf, verbatimText } from '../src/threads/text' -import { diffBlock, oldCodeBlock, staleText, type StaleFacts } from '../src/threads/banner' +import { diffLines, oldLines, staleText, type StaleFacts } from '../src/threads/banner' import { Links } from '../src/threads/links' import { BANNER_COMMANDS, Cmd, MESSAGE_COMMANDS } from '../src/platform/commands' @@ -53,11 +53,27 @@ test('the stale banner: gone, shorter, changed (with the branch), and only the l assert.equal(staleText({ ...f, missing: true, was: '```\nx\n```' }, l()), `**\`src/a.ts\` no longer exists.**\n\n\`\`\`\nx\n\`\`\`\n\n${move}`) assert.equal(staleText({ ...f, pastEnd: 7 }, l()), `**The code changed since this note** (the file has 7 lines now).\n\n${move}`) assert.equal(staleText({ ...f, branch: 'dev' }, l()), `**The code changed since this note** (written on \`dev\`).\n\n${keep} · ${move}`) - assert.equal(oldCodeBlock(['1', '2', '3', '4', '5']), '```\n1\n2\n3\n… 2 more\n```') - assert.equal(diffBlock([' a'], [' b']), '```diff\n- a\n+ b\n```') + assert.equal(oldLines(['1', '2', '3', '4', '5']), '− 1 \n− 2 \n− 3 \n… 2 more') + assert.equal(diffLines([' a'], [' b']), '− `a` \n\\+ `b`') assert.equal(codeBlock(['x'], 'ts'), '```ts\nx\n```') }) +test('the stale banner shows the old and the new line as text that wraps, the changed words as code', () => { + const was = '// The error the person must see is shown as an error (a toast), not a log line.' + const now = '// The failure the user has to notice is surfaced (a toast), not a log line.' + assert.equal(diffLines([` ${was}`], [` ${now}`]), + '− // The `error` the `person must see` is `shown as an error` \\(a toast\\), not a log line. \n' + + '\\+ // The `failure` the `user has to notice` is `surfaced` \\(a toast\\), not a log line.') + // No code block (it scrolls sideways at the panel's width); Markdown in the code is text. + assert.ok(!diffLines([was], [now]).includes('```')) + assert.equal(diffLines(['a * b'], ['a * c']), '− a \\* `b` \n\\+ a \\* `c`') + assert.equal(diffLines(['x = `a`'], ['x = `b`']), '− x = \\``a`\\` \n\\+ x = \\``b`\\`', 'backticks in the code: escaped') + assert.equal(diffLines(['a'], ['`b`']), '− `a` \n\\+ \\`b\\`', 'a change with a backtick in it: escaped text') + assert.equal(diffLines(['gone'], []), '− gone', 'a line without a partner is shown whole') + const f: StaleFacts = { id: 'n1', file: 'src/a.ts', wholeFile: false, missing: false, was: diffLines(['a'], ['b']) } + assert.match(staleText(f, new Links(BANNER_COMMANDS)), /^\*\*The code changed since this note\*\*\.\n\n− `a` \n\\\+ `b`\n\n\[Keep here\]/) +}) + test('links: the text may run every command it links to, after the ones it is allowed anyway', () => { const l = new Links(MESSAGE_COMMANDS) assert.deepEqual(l.commands, [...MESSAGE_COMMANDS])