Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 9 additions & 4 deletions src/core/linkifyAnswer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,15 +18,20 @@ const TARGET = /^(.*?)(?:#L(\d+)(?:-L?\d+)?|:(\d+)(?:-\d+)?)?$/
const REF_START = String.raw`(?<![\w/~.\-\u0000])`
/** A reference's line: `:12`, `:12-20` (the first group) or `#L12` (the second). */
const REF_LINE = String.raw`(?::(\d+)(?:-\d+)?|#L(\d+))`
/**
* A file at the repository's root (`package.json`), only with a line after it: not two single letters (`e.g:3`) and
* not a host name (`example.com:443`). Step text needs a folder; answers follow the agents' README ("path:line").
*/
const ROOT_FILE = String.raw`(?![a-zA-Z]\.[a-zA-Z](?![\w.]))[\w-][\w.-]*\.(?!(?:com|org|net)\b)[a-zA-Z]{1,6}`
/**
* A bare reference, also right after "(" or in a list, optionally in backticks: `src/a.ts:12`, `src/a.ts:12-20`,
* `src/a.ts#L12` (path, line, line). Never inside a longer word or path, nor after `~/` (outside the repo: left as text).
* The path is journeyModel's PATH, as in step text (REF_IN_TEXT); what may come before it and the line forms differ.
* `src/a.ts#L12`, `package.json:3` (path, line, line). Never inside a longer word or path, nor after `~/` (outside the
* repo: left as text). The path is journeyModel's PATH, as in step text (REF_IN_TEXT), or a root file.
*/
const BARE_REF = new RegExp(`${REF_START}\`?(${PATH})${REF_LINE}\`?`, 'g')
const BARE_REF = new RegExp(`${REF_START}\`?(${PATH}|${ROOT_FILE})${REF_LINE}\`?`, 'g')

/** The patterns, for test/answerLinks.test.ts's table (what each one matches, and the bare reference assembled). */
export const ANSWER_LINK_PATTERNS = { IMAGE, MD_LINK, NOT_A_FILE, TARGET, BARE_REF } as const
export const ANSWER_LINK_PATTERNS = { IMAGE, MD_LINK, NOT_A_FILE, TARGET, ROOT_FILE, BARE_REF } as const

/**
* One piece of answer text (outside ``` fences) with its file references as links. `link(text, file, line)` makes
Expand Down
39 changes: 24 additions & 15 deletions src/notes/decorations.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
// How notes mark their lines in the editor: a bar for open and stale notes, the exact text a note is about, unread
// in the scrollbar. (src/platform/decorations.ts sends each editor's decorations; the step card draws its own: tour/card.ts.)
// How notes mark their lines in the editor: a bar for open notes, a bar and a tint for stale ones, the exact text a
// note is about, unread in the scrollbar. (src/platform/decorations.ts sends each editor's decorations; the step card
// draws its own: tour/card.ts.)

import * as vscode from 'vscode'
import { cfg } from '../platform/settings'
Expand All @@ -18,16 +19,18 @@ let deco: Record<Kind, vscode.TextEditorDecorationType> | 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) } : {}),
})
}

Expand Down Expand Up @@ -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<Kind, vscode.Range[]> {
const shown = cfg().get<boolean>('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<boolean>('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()
}
Expand Down
31 changes: 16 additions & 15 deletions src/notes/move.ts
Original file line number Diff line number Diff line change
@@ -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'
Expand All @@ -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)
Expand All @@ -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<void> {
/** 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
Expand Down Expand Up @@ -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()

Expand All @@ -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
Expand Down
21 changes: 17 additions & 4 deletions src/notes/suggestion.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,21 @@
// 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'
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
Expand All @@ -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<boolean> {
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
}
Expand Down
51 changes: 51 additions & 0 deletions src/platform/commands.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand Down Expand Up @@ -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<number, { command: string; args: unknown[] }>()
const linkKeys = new Map<string, number>()
/** 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:<id>?<query>` 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 }
}
Loading
Loading