From 2fd489432b5c0b7e691341910307307f828738dc Mon Sep 17 00:00:00 2001 From: tomeyer97 <107920881+tomeyer97@users.noreply.github.com> Date: Wed, 25 Nov 2026 13:32:35 +0100 Subject: [PATCH 01/17] The whole integration suite green on the refactored branch: a code link is one call into the window again Slice: 35 Zeroshot-Run: 01a2122f-c149-77b1-8506-8a764e1ecc60 --- src/journeys/codeGroup.ts | 32 +++++++++++++++++++++++++++++++- src/tour/walk.ts | 12 +++++++++--- 2 files changed, 40 insertions(+), 4 deletions(-) diff --git a/src/journeys/codeGroup.ts b/src/journeys/codeGroup.ts index d247cd6..d3273b3 100644 --- a/src/journeys/codeGroup.ts +++ b/src/journeys/codeGroup.ts @@ -1,6 +1,7 @@ import * as vscode from 'vscode' import { ownSelection } from '../codeLinks/claudeChatLinks' import { shownOutside } from './codeColumn' +import { openDoc } from '../platform/documents' // A step's code in the editor group beside the panel (the code group): where a file a step names is now, and showing // it there. Used by code links (codeLinks.ts), the beat's line (beats.ts), value hints (valueHints.ts) and the podcast. @@ -54,10 +55,39 @@ export class CodeGroup { ...(col ? { viewColumn: col } : {}), ...(o.selection ? { selection: o.selection } : {}), } - return target instanceof vscode.Uri ? vscode.window.showTextDocument(target, options) : vscode.window.showTextDocument(target, options) + return target instanceof vscode.Uri ? showUri(target, options) : vscode.window.showTextDocument(target, options) } } +/** How long to wait for the window to report the editor `vscode.open` made, before showing it the usual way. */ +const OPENED_EDITOR_WAIT_MS = 1000 + +/** + * Shows `uri` in one call into the window. showTextDocument with a file the extension host has not opened yet first + * opens it (a round trip), then shows it (another); `vscode.open` does both in the window, and the editor and its + * document reach the extension host with the window's own update. + */ +async function showUri(uri: vscode.Uri, options: vscode.TextDocumentShowOptions): Promise { + if (openDoc(uri)) return vscode.window.showTextDocument(uri, options) + await vscode.commands.executeCommand('vscode.open', uri, options) + return (await openedEditor(uri, options.viewColumn)) ?? vscode.window.showTextDocument(uri, options) +} + +/** The visible editor showing `uri` (in `column` when given), now or once the window reports it; undefined: not seen. */ +function openedEditor(uri: vscode.Uri, column: vscode.ViewColumn | undefined): Promise { + const find = () => { + const eds = vscode.window.visibleTextEditors.filter((e) => e.document.uri.toString() === uri.toString()) + return eds.find((e) => column === undefined || e.viewColumn === column) ?? eds[0] + } + const now = find() + if (now) return Promise.resolve(now) + return new Promise((resolve) => { + const done = (ed: vscode.TextEditor | undefined) => { clearTimeout(t); sub.dispose(); resolve(ed) } + const sub = vscode.window.onDidChangeVisibleTextEditors(() => { const ed = find(); if (ed) done(ed) }) + const t = setTimeout(() => done(undefined), OPENED_EDITOR_WAIT_MS) + }) +} + /** Shows a document in the code group whose column is `column()` (CodeGroup.show). */ export function showInCodeGroup( target: vscode.TextDocument | vscode.Uri, column: () => vscode.ViewColumn | undefined, o: ShowOptions, diff --git a/src/tour/walk.ts b/src/tour/walk.ts index 95a6d0d..09fe278 100644 --- a/src/tour/walk.ts +++ b/src/tour/walk.ts @@ -326,10 +326,14 @@ export class Walk { * stack size exceeded"; the card or thread then stays collapsed). See SETTLE_MS. */ columnFor(uri: vscode.Uri): vscode.ViewColumn | undefined { + return this.shownOutsideMap(uri)?.viewColumn ?? this.claimCodeColumn() + } + + /** The visible editor showing `uri`, outside the map's group. */ + private shownOutsideMap(uri: vscode.Uri): vscode.TextEditor | undefined { const mapCol = mapPanel().viewColumn - const showing = vscode.window.visibleTextEditors.find((e) => + return vscode.window.visibleTextEditors.find((e) => e.document.uri.toString() === uri.toString() && e.viewColumn !== undefined && e.viewColumn !== mapCol) - return showing?.viewColumn ?? this.claimCodeColumn() } showMap(lj: LoadedJourney, preserveFocus = false): void { @@ -433,7 +437,9 @@ export class Walk { const column = this.columnFor(uri) ownSelection(OWN_MOVE_MS) // the file's caret and the step's: not a chat link const shown = { preview: true, preserveFocus: opts.focus === false, ...(column ? { viewColumn: column } : {}) } - const editor = await vscode.window.showTextDocument(uri, shown) + // Already on screen and the keyboard stays where it is: nothing to show. Its column may be about to change (a + // group closing renumbers those after it), and a show by an old number would open a new group. + const editor = (opts.focus === false ? this.shownOutsideMap(uri) : undefined) ?? await vscode.window.showTextDocument(uri, shown) if (this.superseded(token, lj, n)) return undefined if (editor.viewColumn) { tour.doc = { uri, column: editor.viewColumn } From 64c5d06dd8cf6145bde254202315f86c080552f3 Mon Sep 17 00:00:00 2001 From: tomeyer97 <107920881+tomeyer97@users.noreply.github.com> Date: Wed, 25 Nov 2026 23:14:14 +0100 Subject: [PATCH 02/17] The integration suite passes on GitHub's slower runners: no races in opening journeys, walking steps and branch switches Slice: 36 Zeroshot-Run: 01a2148a-0894-7f21-92fe-4bf2ce1bda44 --- src/check/controller.ts | 9 +++++++ src/check/state.ts | 4 +++ src/journeys/mapPanel.ts | 16 +++++++++++ src/tour/commands.ts | 14 +++++++--- src/tour/walk.ts | 5 ++-- test/checkState.test.ts | 14 ++++++++++ test/integration/check/answers.ts | 10 ++++--- test/integration/check/start.ts | 4 +-- test/integration/devtools.ts | 9 +++++++ test/integration/main/context.ts | 40 ++++++++++++++++++++++++++-- test/integration/main/journeyTour.ts | 5 +++- test/integration/main/notes.ts | 4 +-- test/integration/suite.ts | 5 ++-- 13 files changed, 121 insertions(+), 18 deletions(-) diff --git a/src/check/controller.ts b/src/check/controller.ts index eec296f..ef38bbd 100644 --- a/src/check/controller.ts +++ b/src/check/controller.ts @@ -95,6 +95,8 @@ export class CheckController implements CheckQuery, vscode.Disposable { /** Refreshes done in full and skipped as unchanged (integration test). */ private counts = { full: 0, same: 0 } private timer: NodeJS.Timeout | undefined + /** The state offBranch read when the notes last followed it (CheckState.offBranchKey). */ + private hidesShown = '' /** A refreshSoon meanwhile asked for a full refresh (not gated). */ private soonForce = false /** Run once the current refresh has published (a check put back from the cache opens its first question). */ @@ -274,6 +276,13 @@ export class CheckController implements CheckQuery, vscode.Disposable { /** What the window shows follows: the status bar, the threads, the context key, the tour, the view, the journeys list. */ private async publish(): Promise { const st = this.state.st + // Another branch's notes hidden (or back): the notes' threads and lists follow. The branch watcher's own pass may + // have run before this refresh read the branch, and hidden nothing. + const hides = this.state.offBranchKey + if (hides !== this.hidesShown) { + this.hidesShown = hides + this.host.refresh() + } if (!this.writer.writing) this.status.show(this.statusLook()) if (st?.check) await this.threads.sync(st.check) // While there is a check, an empty Code Notes view steps aside: the Check view gets its room (package.json). diff --git a/src/check/state.ts b/src/check/state.ts index e8221b7..9ee3052 100644 --- a/src/check/state.ts +++ b/src/check/state.ts @@ -99,6 +99,10 @@ export class CheckState { const f = linkOf(n)?.file ?? checkExtra(n).checkFile return !!f && !!this.st && (f !== this.st.file || !this.st.exists) } + /** What offBranch reads of the state, as one string: when it changes, other notes are hidden. */ + get offBranchKey(): string { + return this.st ? `${this.st.file}\0${this.st.exists}` : '' + } } /** What every part of the check gets: the state, the understanding CLI, the log, and the ways to show a change. */ diff --git a/src/journeys/mapPanel.ts b/src/journeys/mapPanel.ts index 93f6a3e..1c6bdde 100644 --- a/src/journeys/mapPanel.ts +++ b/src/journeys/mapPanel.ts @@ -26,6 +26,8 @@ export interface PanelPodcast { } export const MAP_VIEW = 'codeNotes.journey' +/** How long opening a journey waits for the window to place a new panel (it says within a moment). */ +const PLACED_WAIT_MS = 3000 /** * The group a new map opens in: the whole group when there is nothing to read beside it (`alone`); else the one it @@ -269,6 +271,20 @@ export class MapPanel implements vscode.Disposable { if (this.panel) this.channel.send(m) } + /** + * Resolves once the window has said which group the panel is in. A panel made beside the editor or in the active + * group has no column in the extension host until then, and code shown meanwhile could not keep off its group. + */ + placed(): Promise { + const p = this.panel + if (!p || p.viewColumn !== undefined) return Promise.resolve() + return new Promise((resolve) => { + const done = () => { clearTimeout(t); subs.forEach((x) => x.dispose()); resolve() } + const subs = [p.onDidChangeViewState(() => { if (p.viewColumn !== undefined) done() }), p.onDidDispose(done)] + const t = setTimeout(done, PLACED_WAIT_MS) + }) + } + close(): void { this.panel?.dispose() } /** The keyboard back in the panel. */ takeFocus(): void { this.panel?.reveal(this.panel.viewColumn, false) } diff --git a/src/tour/commands.ts b/src/tour/commands.ts index 5835799..656428f 100644 --- a/src/tour/commands.ts +++ b/src/tour/commands.ts @@ -86,13 +86,18 @@ function isHere(lj: LoadedJourney): boolean { */ async function openMapIfRoom(lj: LoadedJourney): Promise { const room = !!mapPanel().journey || (await panelFits()) - await openMap(lj, room) + // A step opens next and takes the keyboard: the map doesn't take it first (a slow window gave it the map after). + await openMap(lj, room, true) if (!room) cardOnly() return room } -/** Shows a journey's map (`show`: false when there is no room for it). Another journey's tour ends first, keeping its place. */ -export async function openMap(lj: LoadedJourney, show = true): Promise { +/** + * Shows a journey's map (`show`: false when there is no room for it; `preserveFocus`: the keyboard stays where it is). + * Another journey's tour ends first, keeping its place. Resolves once the map's group is known, so code shown next + * goes beside it. + */ +export async function openMap(lj: LoadedJourney, show = true, preserveFocus = false): Promise { // Another journey's map is only a look: the running tour goes on until Start there, or End. await markJourneysSeen(lj) if (showIntro()) await stored().set(STATE.journeyOpened, true) @@ -100,8 +105,9 @@ export async function openMap(lj: LoadedJourney, show = true): Promise { // for Resume); its status item and code marker go with it. if (lj.key !== tourState().key && walk().touring()) await walk().end() if (lj.key !== tourState().key) walk().browse(lj) - if (show) walk().showMap(lj) + if (show) walk().showMap(lj, preserveFocus) walk().updateTour() + if (show) await mapPanel().placed() } /** Finish on the last step (walk.finish). */ diff --git a/src/tour/walk.ts b/src/tour/walk.ts index 09fe278..28322a2 100644 --- a/src/tour/walk.ts +++ b/src/tour/walk.ts @@ -483,8 +483,9 @@ export class Walk { private async revealStep(lj: LoadedJourney, n: number, editor: vscode.TextEditor, uri: vscode.Uri): Promise { const { tour, card } = this // The editor just opened on this file: the card is made once it has settled (see editorSettling). - const settle = editorSettling(uri) - if (settle) { + // Until it has: a timer may fire a moment before the clock says the wait is over, and the card then came after + // the step's command had resolved. + for (let settle = editorSettling(uri); settle > 0; settle = editorSettling(uri)) { await new Promise((r) => setTimeout(r, settle)) if (!tour.isAt(lj, n)) return } diff --git a/test/checkState.test.ts b/test/checkState.test.ts index 3077889..2a8043a 100644 --- a/test/checkState.test.ts +++ b/test/checkState.test.ts @@ -82,6 +82,20 @@ test('another branch\'s check thread, or a note made from one, is off the branch assert.deepEqual(s.branchOf(note({ check: { file: 'understanding/feat.json', q: 'q1' } })), { checkFile: 'understanding/feat.json' }) }) +test('offBranchKey changes exactly when offBranch can answer otherwise: another check file, or its file gone', () => { + const s = new CheckState(folder, records()) + const keys = [s.offBranchKey] + s.read(status({}), undefined) + keys.push(s.offBranchKey) + s.read(status({ branch: 'feat', head: 'other commit' } as Partial), undefined) + assert.equal(s.offBranchKey, keys[1], 'the same check file: nothing hidden changes') + s.read(status({ branch: 'main', file: 'understanding/main.json', exists: false }), undefined) + keys.push(s.offBranchKey) + s.read(status({ exists: false }), undefined) + keys.push(s.offBranchKey) + assert.equal(new Set(keys).size, keys.length, `each a key of its own: ${JSON.stringify(keys)}`) +}) + test('a branch left: nothing selected, nothing said', () => { const s = new CheckState(folder, records()) s.select('q1') diff --git a/test/integration/check/answers.ts b/test/integration/check/answers.ts index 29fea56..b491ef3 100644 --- a/test/integration/check/answers.ts +++ b/test/integration/check/answers.ts @@ -6,8 +6,8 @@ import * as vscode from 'vscode' import * as fs from 'fs' import * as path from 'path' import assert from 'assert' -import { quiet, settle, test, untilEqual } from '../helpers' -import { boxFocused, checkFrame, focusedElement, pageShot, ui } from '../devtools' +import { quiet, settle, test, untilAll, untilEqual } from '../helpers' +import { boxFocused, checkFrame, checkViewFocus, focusedElement, pageShot, ui } from '../devtools' import { CHECK_WAIT_MS, api, answer, codeEditor, commentBody, devtools, inLines, lastBody, left, limitsEditor, limitsPath, noteById, noteOf, readCheck, threadComments, typeAnswer, until, view, ws } from './context' import { linksOf, withoutDevtools } from './support' @@ -166,7 +166,11 @@ export const answersTests = [ await vscode.commands.executeCommand('codeNotes.next') await until('on q3', () => view().answer?.id === 'q3') await vscode.commands.executeCommand('codeNotes.previous') - await until('back on q2 with its draft', async () => view().answer?.id === 'q2' && /my answer goes here/.test(view().answer!.draft) && (await boxFocused()) === 'q2') + await untilAll('back on q2 with its draft', { + 'q2 in the view': () => view().answer?.id === 'q2', + 'its draft': () => /my answer goes here/.test(view().answer?.draft ?? ''), + 'the keyboard in its box': async () => { const b = await boxFocused(); if (b !== 'q2') console.log('focus back on q2:', b, await focusedElement(), '|', await checkViewFocus()); return b === 'q2' }, + }, CHECK_WAIT_MS) // Esc: back to the code. await (await ui()).keyboard.press('Escape') await until('Esc: the editor has the keyboard', async () => (await boxFocused()) === '' && (await (await ui()).evaluate(() => !!(globalThis as any).document.activeElement?.closest?.('.monaco-editor')))) diff --git a/test/integration/check/start.ts b/test/integration/check/start.ts index db3490e..f642665 100644 --- a/test/integration/check/start.ts +++ b/test/integration/check/start.ts @@ -5,7 +5,7 @@ import * as fs from 'fs' import * as path from 'path' import assert from 'assert' import { settle, test } from '../helpers' -import { boxFocused, checkFrame, focusedElement, pageShot, ui } from '../devtools' +import { boxFocused, checkFrame, checkViewFocus, focusedElement, pageShot, ui } from '../devtools' import { api, checkFile, checkNotes, chk, devtools, git, inLines, left, limitsPath, noteById, noteOf, readCheck, until, view, ws } from './context' import { setFakeScenario } from './fakeGrader' import { clickInCheckView, withWindowSize } from './support' @@ -63,7 +63,7 @@ export const startTests = [ test('the keyboard is in q1\'s answer box on open, not in the code; a draft is kept in the workspace; VS Code\'s shortcuts work from the box', async () => { // Typing in the code would edit limits.js. const page = await ui() - await until('focus in the answer box, not the code', async () => { const b = await boxFocused(); if (b !== 'q1') console.log('focus at start:', b, await focusedElement()); return b === 'q1' }) + await until('focus in the answer box, not the code', async () => { const b = await boxFocused(); if (b !== 'q1') console.log('focus at start:', b, await focusedElement(), '|', await checkViewFocus()); return b === 'q1' }) await page.keyboard.type('typed') assert.equal(fs.readFileSync(limitsPath, 'utf8').includes('typed'), false) assert.ok(!vscode.window.activeTextEditor?.document.isDirty, 'the code is untouched') diff --git a/test/integration/devtools.ts b/test/integration/devtools.ts index a4e6716..a8019f7 100644 --- a/test/integration/devtools.ts +++ b/test/integration/devtools.ts @@ -55,6 +55,15 @@ export function checkFrame(): Promise { return webviewFrame('script[src*="/pages/check.js"]', 'the Check view frame') } +/** Where the keyboard is inside the Check view's page (for a failing wait's log): whether the page has it, and the + * element that has it there. */ +export async function checkViewFocus(): Promise { + return (await checkFrame()).evaluate(() => { + const d = (globalThis as any).document, a = d.activeElement + return `page focused: ${d.hasFocus()}, active: ${a ? `${a.tagName}.${[...a.classList].join('.')}${a.closest?.('.answer') ? ` in ${a.closest('.answer').dataset.id}` : ''}` : 'none'}` + }) +} + /** Which answer box in the Check view has the keyboard: its question id, '' for none. */ export async function boxFocused(): Promise { return (await checkFrame()).evaluate(() => { const d = (globalThis as any).document; const a = d.activeElement; return d.hasFocus() && a?.classList?.contains('box') ? a.closest('.answer').dataset.id : '' }) diff --git a/test/integration/main/context.ts b/test/integration/main/context.ts index 62c1610..47e485f 100644 --- a/test/integration/main/context.ts +++ b/test/integration/main/context.ts @@ -2,6 +2,7 @@ // and short ways to read its state. Every test file of the main suite imports these; suite.ts fills `ctx` once, from // `createSuiteContext` (helpers.ts), before any test runs. import * as vscode from 'vscode' +import * as fs from 'fs' import * as path from 'path' import type { TestApi } from '../../../src/testApi' import type { SuiteContext } from '../helpers' @@ -28,8 +29,18 @@ export const ctx = { get notesDir(): string { return ready().notesDir }, } -/** The main suite's wait (6 s by default): on a timeout it prints the tour's state (most waits are on it). */ -export const until = waiter({ dump: () => { try { const s = suite?.api.snapshot(); return s && { journeys: s.journeys.map((j: { id: string }) => j.id), tour: s.tour && { ...s.tour, story: undefined } } } catch { return undefined } } }) +/** The editor groups as "column: tab, tab" (* the active tab, ! the active group): where the code and the map are. */ +const groupsNow = () => vscode.window.tabGroups.all.map((g) => + `${g.isActive ? '!' : ''}${g.viewColumn}: ${g.tabs.map((t) => `${t.isActive ? '*' : ''}${t.label}`).join(', ')}`) + +/** The main suite's wait (6 s by default): on a timeout it prints the tour's state (most waits are on it), where the + * active editor is and the editor groups. */ +export const until = waiter({ dump: () => { + try { + const s = suite?.api.snapshot() + return s && { at: suite ? at() : '', groups: groupsNow(), journeys: s.journeys.map((j: { id: string; steps: number }) => `${j.id} (${j.steps} steps)`), tour: s.tour && { ...s.tour, story: undefined } } + } catch { return undefined } +} }) /** Everything the extension shows, as data (notes, journeys, the tour, counts). */ export const snap = () => ctx.api.snapshot() @@ -91,3 +102,28 @@ export async function useFakeClaude(): Promise { process.env.FAKE_CLAUDE_LOG = log await setting('claude.path', FAKE_CLAUDE) } + +/** + * The notes folder there and watched by the window, as the notes chapter leaves it: a chapter run alone starts from + * it. A folder made together with its parent (mkdir -p .code-notes/journeys) can be missed by the window's file + * watcher for good (it watches a new folder once it has seen it, and the inner one came first); then no change in it + * is ever reported. A probe file in it is written until the watcher reports it. + */ +export async function notesFolderWatched(): Promise { + if (fs.existsSync(ctx.notesDir)) return + fs.mkdirSync(ctx.notesDir) + const probe = path.join(ctx.notesDir, '.watched') + const w = vscode.workspace.createFileSystemWatcher(new vscode.RelativePattern(ctx.folder, path.relative(ctx.ws, probe))) + let seen = false + w.onDidCreate(() => { seen = true }) + w.onDidChange(() => { seen = true }) + try { + await until('the notes folder watched by the window', () => { + if (!seen) fs.writeFileSync(probe, String(Date.now())) + return seen + }) + } finally { + w.dispose() + fs.rmSync(probe, { force: true }) + } +} diff --git a/test/integration/main/journeyTour.ts b/test/integration/main/journeyTour.ts index bdeb1ec..823499f 100644 --- a/test/integration/main/journeyTour.ts +++ b/test/integration/main/journeyTour.ts @@ -118,7 +118,10 @@ export const journeyTourTests = [ await settle(500, 'the panel group taking its size') const settled = await editorLayout() if (settled.groups.length === 2) { - const panelShare = settled.groups[1].size / (settled.groups[0].size + settled.groups[1].size) + // The panel's own group: beside the code, or the first one when nothing was open (this chapter run alone). + const panel = settled.groups[(tour().mapColumn ?? 0) - 1] + assert.ok(panel, `the map's group in the layout: ${JSON.stringify(settled)}`) + const panelShare = panel.size / (settled.groups[0].size + settled.groups[1].size) assert.ok(panelShare <= 0.41, `the panel takes ${JSON.stringify(settled)}`) } const card1 = tour().card! diff --git a/test/integration/main/notes.ts b/test/integration/main/notes.ts index 3b80b1d..e407bb4 100644 --- a/test/integration/main/notes.ts +++ b/test/integration/main/notes.ts @@ -75,8 +75,8 @@ export const notesTests = [ test('replies unread whatever their timestamps; a missing "at" is not invented', async () => { // Stamped EARLIER than anything (clock skew): still unread. appendMessage(firstNotePath(), { author: 'claude', role: 'agent', body: 'It is read once in `main`.', at: '2001-01-01T00:00:00Z' }) - await until('past-dated reply unread', () => first()?.unread === 1) - assert.equal(snap().badge, 1) + // The badge follows the notes' change event, a moment after the store has the reply. + await until('past-dated reply unread, the badge says 1', () => first()?.unread === 1 && snap().badge === 1) appendMessage(firstNotePath(), { author: 'claude', role: 'agent', body: 'And no timestamp on this one.' }) await until('second reply unread', () => first()?.unread === 2) await vscode.commands.executeCommand('codeNotes.refresh') diff --git a/test/integration/suite.ts b/test/integration/suite.ts index 06b9e24..069af03 100644 --- a/test/integration/suite.ts +++ b/test/integration/suite.ts @@ -5,7 +5,7 @@ // test/.test.ts, src//.ts in test/.test.ts (src/journeys/steps.ts: // journeySteps.test.ts, src/tour/stepText.ts: tourStepText.test.ts). import { Chapter, createSuiteContext, runChapters } from './helpers' -import { setMainContext, useFakeClaude } from './main/context' +import { notesFolderWatched, setMainContext, useFakeClaude } from './main/context' import { notesTests } from './main/notes' import { journeyTourTests } from './main/journeyTour' import { keysAndMapTests } from './main/keysAndMap' @@ -30,7 +30,8 @@ const fakeClaude = { setup: useFakeClaude } export const chapters: Chapter[] = [ { name: 'notes', file: 'main/notes.ts', tests: notesTests, covers: 'notes from the first one to the trash notes/, threads/, store.ts, anchor.ts, ask/, claude.ts' }, - { name: 'journeyTour', file: 'main/journeyTour.ts', tests: journeyTourTests, ...fakeClaude, + { name: 'journeyTour', file: 'main/journeyTour.ts', tests: journeyTourTests, + setup: async () => { await notesFolderWatched(); await useFakeClaude() }, covers: 'walking a journey, step cards, lenses journeys/, journeyModel.ts, tour/' }, { name: 'keysAndMap', file: 'main/keysAndMap.ts', tests: keysAndMapTests, ...fakeClaude, covers: 'chord keys, the tutorial, the whole map package.json keybindings, tutorialSpot.ts' }, From fb0969f5778dc80340a4839f13480882fa6b1df6 Mon Sep 17 00:00:00 2001 From: tomeyer97 <107920881+tomeyer97@users.noreply.github.com> Date: Thu, 26 Nov 2026 15:03:35 +0100 Subject: [PATCH 03/17] The check CLI: no check on the default branch, its own files never count as the change, init works from a copied CLI, plain words Slice: S14 Zeroshot-Run: 01a21815-2f80-79c1-bd32-d2b059c15e9b --- cli/understanding.mjs | 75 ++++++++++++------- cli/understanding/changeFiles.ts | 7 +- cli/understanding/constants.ts | 3 +- cli/understanding/index.ts | 2 +- cli/understanding/init.ts | 46 +++++++----- cli/understanding/main.ts | 21 ++++-- cli/understanding/mrComment.ts | 6 +- cli/understanding/phases.ts | 21 ++++-- cli/understanding/size.ts | 3 + cli/understanding/skillFiles.ts | 6 ++ cli/understanding/state.ts | 11 ++- .../understanding-check/scripts/questions.mjs | 4 +- test/cli/golden-skill-copy.test.mjs | 32 ++++++++ test/cli/understanding-init.test.mjs | 57 +++++++++++++- test/cli/understanding-mr-comment.test.mjs | 6 +- test/cli/understanding-status.test.mjs | 32 +++++++- test/goldens/check/helpers.json | 16 ++-- test/goldens/check/refunds.commands.json | 2 +- test/goldens/check/states.json | 40 +++++----- 19 files changed, 283 insertions(+), 107 deletions(-) create mode 100644 cli/understanding/skillFiles.ts create mode 100644 test/cli/golden-skill-copy.test.mjs diff --git a/cli/understanding.mjs b/cli/understanding.mjs index 94c758d..0e104ef 100755 --- a/cli/understanding.mjs +++ b/cli/understanding.mjs @@ -53,7 +53,7 @@ var MAX_TOUR_STEPS = 20; var TOUR_LINE = "A guided tour of this change: open it in VS Code with Code Notes (Check view)"; var REPO_URL = "https://github.com/tomeyer97/code-notes"; var DOCS_URL = `${REPO_URL}/blob/main/docs/understanding-check.md`; -var CI_URL = `${REPO_URL}#in-ci`; +var CI_URL = `${DOCS_URL}#in-ci`; var SKILL_URL = `${REPO_URL}/tree/main/skills/understanding-check`; var SKILL_DIR = ".claude/skills/understanding-check"; var SELF = ""; @@ -197,7 +197,7 @@ function globRe(glob) { return new RegExp(`${g.includes("/") ? "^" : "(^|/)"}${re}$`); } var isDoc = (file) => /\.(md|mdx|markdown|rst|adoc|txt)$/i.test(file) || /(^|\/)docs?\//i.test(file); -var own = (file) => file.startsWith(`${DIR}/`) || file.startsWith(".code-notes/") || file === ".gitattributes" || file === ".ignore" || file.startsWith(`${SKILL_DIR}/`); +var own = (file) => file.startsWith(`${DIR}/`) || file.startsWith(".code-notes/") || file === ".gitattributes" || file === ".ignore" || file.startsWith(`${SKILL_DIR}/`) || /(^|\/)understanding\.mjs$/.test(file); function counted(file, exempt = []) { return !own(file) && !exempt.some((g) => globRe(g).test(file)); } @@ -1041,6 +1041,7 @@ function questionsFor(lines, cfg = DEFAULTS) { const { min = 1, max = 5 } = cfg.questions ?? {}; return Math.max(1, Math.min(max, Math.max(min, n))); } +var topUpQuestions = (lines) => lines < 80 ? 1 : 2; function changeKind(st) { return st?.docsOnly ? "docs" : st && st.added === 0 && st.removed > 0 ? "removal" : "code"; } @@ -1288,12 +1289,16 @@ var PHASE = { } }, drift: { - words: (state) => ({ - tone: "warn", - bar: `Needs top-up: +${state.grew} lines`, - title: `Needs top-up: +${state.grew} lines`, - line: state.commitFirst ? "Commit, then add 1–2 questions about the new lines." : "Add 1–2 questions about the new lines." - }), + // New work, not a fault: the status bar counts the questions; the line count is in the title (the tooltip). + words: (state) => { + const n = questionsText(topUpQuestions(state.grew ?? 0)); + return { + tone: "todo", + bar: `Understanding: +${n}`, + title: `Your change grew by ${state.grew} code lines`, + line: `${state.commitFirst ? "Commit, then add" : "Add"} ${n} about the new lines.` + }; + }, ci: { log: (w) => `Your change grew by ${w.drift.lines} code lines since the check${w.drift.approx ? " (compared by size: the branch was rewritten)" : ""}. Run "Check my understanding" again: it adds 1–2 questions about the new part only. Then commit and push.`, comment: (w) => `**Understanding check: needs a top-up.** The change grew by ${w.drift.lines} code lines since the questions; 1–2 questions about the new part are missing.` @@ -1336,6 +1341,7 @@ var PHASE = { } } }; +var questionsText = (n) => `${n} question${n === 1 ? "" : "s"}`; var roomText = (drift, maxDrift) => drift.lines ? ` ${drift.lines} code line${drift.lines === 1 ? "" : "s"} since the check (top-up at ${maxDrift}).` : ""; function nothingLine(state, st) { if (st.stackedOn) return `Covered by ${st.stackedOn}'s check.`; @@ -1463,7 +1469,7 @@ function checkState(st, cfg = DEFAULTS) { function noFileState(st, cfg) { if (st.stashed) return { phase: "stashed", stash: st.stashed }; const renamed = !!st.change?.renamed?.length; - if (st.small || !st.changed && !renamed) return { phase: "nothing", changed: st.changed ?? 0, exemptOnly: !!st.change?.exemptOnly }; + if (st.small || st.onBase || !st.changed && !renamed) return { phase: "nothing", changed: st.changed ?? 0, exemptOnly: !!st.change?.exemptOnly }; const kind = changeKind(st.change); return { phase: "none", @@ -1871,6 +1877,14 @@ import path10 from "node:path"; // cli/understanding/init.ts import fs7 from "node:fs"; import path9 from "node:path"; + +// cli/understanding/skillFiles.ts +var SKILL_FILES = { + "SKILL.md": '---\nname: understanding-check\ndescription: >-\n An UNDERSTANDING CHECK for the current branch: 1-5 short questions (by the change\'s size) about the author\'s own\n change (how a part behaves, why it is built this way, how it fails, an edge case), each anchored on the changed\n lines it is about, written to understanding/.json with the bundled script. The author answers them next to\n the code (Code Notes in VS Code), or right here in the chat, one at a time, graded with the same rules. Use when\n asked to "check my understanding" (/understanding-check), write understanding-check questions, or top up a check\n after the change grew.\n---\n\n# Understanding check: writing the questions\n\n**Goal.** The author is about to merge a change, often written with an AI agent. Ask the few questions a sharp\nsenior colleague would ask in review to find out whether the author really owns this code. Answering takes about\n5 minutes in total, 1-3 sentences each. It must feel like help, not an exam: a good question makes the author look\nat something they would otherwise have skipped.\n\nWrite only through `scripts/questions.mjs` (never write the JSON by hand); read every line it prints and fix each\n`PROBLEM`. Run it by its full path, one command per call: no shell variables, no `&&` or pipes.\n\n## Procedure\n\n1. `questions.mjs start` (or `start --top-up` when asked to top up an existing check). It prints the change with the\n new file\'s line numbers and how many questions to write (1 for a small change, up to 5 for a big one; write that\n many). `NOTHING` or `UNCOMMITTED`: write nothing, reply with that one line. `REMOVED ONLY`: the change only removes\n code; write ONE evidence question (`--evidence --kind change`) from the `EVIDENCE` the script prints (a search of\n the repository for the removed names): "Nothing calls `refundReport` any more (search: 0 hits) — right?", for the\n author to confirm or correct in one sentence. Check the hits with Grep first and keep the numbers true; put it on\n the lines where code was removed or on code that used it (any file). `RENAMED ONLY`: one question about what the move changes, `--whole-file`. `DOCS ONLY`: one question about what a reader now sees or\n understands differently; never why a word was chosen.\n2. Read the diff. Open the changed files (Read) where the diff alone doesn\'t show what the code does, and the code\n that calls the changed functions. Find the places that matter most: where the behaviour is decided, where it can\n fail, what is new.\n3. Pick the questions (rules below), then add each one:\n `questions.mjs add --kind failure --file api/orders.js --lines 12-18 --text "…?"`\n Use `--whole-file` (no lines) only for a question about the design of a whole file.\n When the answer depends on code the change did NOT touch (the loop that retries a failing handler, the\n constraint that rejects a duplicate, the caller that ignores an error), add it: `--also worker/queue.js:84-96`\n (up to 3, comma-separated). It is shown beside the question, so the author knows where to look.\n Name code in the question by what it is ("the catch block in `tick()`", "the INSERT"), never by line number, and\n link those words to their lines: `--links "the catch block in tick()@worker/queue.js:88-96"` (up to 3,\n `;`-separated; the phrase exactly as in the text). The author clicks the phrase to see the code. A phrase linked\n to an `--also` range is all the pointer that range needs.\n When the honest answer to a question is "this is a bug" (the code really does lose data, double-charge, race,\n skip a check), still ask it neutrally and add `--suspect`: once they have answered, the author is offered a fix. Only\n when you read the code and are confident; never as a trick.\n4. `questions.mjs finish`. It writes `understanding/.json`. Reply with one line per question, nothing more.\n\n## What makes a good question\n\n- **About this change, answerable from it.** It names the function, value or case it is about, so it makes sense\n on its own next to its lines. The answer is in the code (and its obvious callers), not in someone\'s head.\n- **Answerable in 1-3 sentences.** One question, one point, under ~140 characters. "…, and could the customer …?"\n is two questions, and "what happens to the row, the counters and the job?" is three: keep the one that matters.\n- **About code, never comments.** Ask about what the code does, not what a comment claims ("finance audits this\n monthly" is not a requirement). Lines that hold only comments or blank lines can\'t carry a question.\n- **Mixed kinds** (from 3 questions on): at least one `failure` or `edge`, and one `why` when the change makes a design choice (it\n almost always does: a limit, an order of operations, where something is stored, what is retried):\n - `failure`: "What happens to the order when the payment client times out after the order was stored?"\n - `edge`: "What does `applyDiscount` return when the same code is applied twice to one cart?"\n - `why`: "Why does the worker re-read the order before charging instead of using the job\'s copy?"\n - `how`: "How does a settled order stop a second charge for the same job?" (behaviour, not a line-by-line read)\n - `change`: "Which callers of `insertOrder` get a different result after this change?"\n- **Anchored on the lines that answer it** (`--lines`): the decision, the check, the catch, not the whole function.\n At most ~15 lines when you can.\n- **At most one computed value.** "What does `rule59` return for a 200-cent item at qty 61?" is a calculator drill\n unless it says why it matters: ask it once at most, and say what is at stake ("… is that a valid price?"). Prefer why,\n failure and edge questions.\n- **Riskiest first.** Before anything clever, ask about what can hurt most: who may call a new endpoint or run a new\n action (an auth gate, a token that may be unset), money moving, data leaving (a field now returned to a client),\n data lost. When the change has such a surface, one question is about it, and it comes first.\n- **Prefer what the author is most likely to have skipped**: error paths, retries, ordering between two writes,\n what is shared between requests, limits, what happens with empty or duplicate input, a default that changed.\n\n## Never\n\n- Trivia or reading aloud: "What does line 12 do?", "What is the name of …?", "Which file defines …?".\n- Questions whose answer is in a comment right next to the lines, or in the question itself.\n- Yes/no questions, opinion questions ("Is this a good design?"), or questions about code the change didn\'t touch.\n- Hints of the answer in the question. Answers are never stored: the grader judges each answer against the code.\n\n## The tour (when asked to write it)\n\nAfter the questions, the author can walk a short **journey of the change** and click their way to each answer\ninstead of reading the code cold. Write it only when the request asks for the tour.\n\n1. `questions.mjs tour` (`tour --top-up` when topping up). It prints the questions, the changed lines and the exact\n `journey.py` path and `--dir` to use (always that `--dir`; the slug is `tour`).\n2. Write the journey with `journey.py` (the code-journey skill\'s script; `journey.py help ` gives its rules):\n - **As many steps as the change needs** (`tour` prints the range: 2-3 for a few lines, documentation or a removal,\n up to 6-10 for a big change) through the changed code AND the unchanged code it depends on (the caller, the table, the retry loop), in\n the order a request or the data actually flows. Every step is about the change or what it relies on: no step\n that only says something stayed the same. A top-up adds 1-4 steps after the last one, about the new part\n only; never change the earlier steps.\n - **A change that only removes code** (`REMOVAL`): steps on code that is still there: where the removed code used\n to be called (or that nothing calls it: the search), and why removing it is safe. One that mostly removes code:\n what was removed, what used it before, and the few lines that changed besides. Not a tour of the code around it.\n - **Documentation** (`DOCS`): steps on the existing code the edited text describes, never on the text. When it\n describes no code, write no tour: `questions.mjs tour-finish --none`, and you are done.\n - `new tour "" "" --dir … < summary`: the question one developer would ask about this\n change ("What happens when a shopper asks for a refund?"), a short title that names the change ("Refunds by\n staff", "Dropping refundReport"), a 2-sentence summary.\n - A small map: 1-3 `system` boxes (reuse the names of the repo\'s journeys in `journeys/` when there are some), a\n `function` box per function a step is in (`range` prints its lines), and an `edge` for each hop between them.\n - Each `step`: a title that is one fact (≤ 70 chars), a lead of one plain sentence (≤ 25 words), lines that make\n the title true (≤ 15). Details and refs only where they save a click.\n - **Each question\'s answer must be visible by its step**: a step up to it shows the question\'s lines (or the code\n it depends on). Order the steps so the questions come along the way, not all at the end.\n - **Show the way to an answer, never the answer**: the steps state what the code does, one fact each; the author\n puts two facts together to answer. A title or lead that says what a question asks for ("so a failed refund is\n not listed", "so a restart loses the job") gives it away: cut that clause.\n - Then 1-3 `link`s per step (a phrase of the lead to the lines doing it). No `value`, no `scene`.\n - `check <repo> tour quiet --dir …`: fix every PROBLEM and WARNING it prints, except its step count (6-14 is for a\n journey of the repository; `tour` prints the tour\'s own).\n3. `questions.mjs tour-finish --steps q1=3,q2=5,…`: for each question, the step after which its answer can be seen.\n Reply with the step titles, one per line.\n\n## Top-up\n\n`start --top-up` lists the NEW LINES of the branch\'s own change since the questions were written (code merged in\nfrom the target branch is never among them). Add 1-2 questions about those lines only (the earlier questions and\nanswers stay), then `finish`.\n\n## Without VS Code: answering in the chat\n\nWhen the person asks you directly (`/understanding-check`, "check my understanding") and no prompt told you exactly\nwhich script commands to run, do the whole check here in the chat. It is help, not an exam: be the friendly senior\ncolleague. `S` below is this skill\'s `scripts/questions.mjs`; `S cli …` runs the check\'s CLI (the repository\'s copy,\ne.g. `tools/understanding.mjs`, or the one beside this script), so the file ends up exactly as VS Code writes it.\n\n1. `S cli status`. No check yet: write the questions (Procedure above; no tour). A check that needs a top-up: top up.\n `No check needed`: say so in one line and stop.\n2. `S cli next` prints the question to answer next (its id, where it is, the text). Ask it in the chat, ONE question\n at a time, with where to look (file and lines). Then wait for the answer. Never hint at the answer before they try.\n3. Grade their answer with the same rules as everywhere: `S cli grade --question q1 --answer \'<their words>\' --prompt`\n prints the grader\'s instructions for it. Follow them (read the code they name) and write the JSON reply they ask\n for. Then record it: `S cli grade --question q1 --answer \'<their words>\' --reply \'<the JSON>\'`. Quote both with\n single quotes (a `\'` inside becomes `\'\\\'\'`); never change their words.\n4. Tell them what the recorded line says, in your own short words: "Right" and why; "Not quite" with the hint (they\n try once more); after a second miss, the explanation, and offer to let them say it back in one sentence (optional:\n record it the same way, it counts as passed). A `Concern:` is about the code: tell them, and when they want a\n reviewer to see it, `S cli flag --question q1`.\n5. Repeat from 2 until `S cli next` (or the recorded line) says done. Then offer to commit: `S cli commit` commits the\n check file only (the repository\'s first check also adds the `.gitattributes` line that folds check files in diffs)\n and pushes. Say what it printed in one line.\n', + "scripts/questions.mjs": "#!/usr/bin/env node\n// Writes the questions of an understanding check, one validated question at a time (SKILL.md says how to use it).\n// questions.mjs start [--base <ref>] [--branch <name> --head <sha>] [--top-up] [--replace] the change, with new-file\n// line numbers; starts a draft. --branch/--head: the branch and commit the check is for, whatever is\n// checked out by the time each command runs (the person may switch meanwhile)\n// questions.mjs add --kind <kind> --file <path> (--lines A-B | --whole-file) --text \"<question>\" [--also <path>:A-B,…] [--suspect]\n// [--links \"<phrase>@<path>:A-B;…\"] phrases of the text that become links to those lines\n// questions.mjs list | remove <qN> | finish\n// questions.mjs tour [--top-up] then journey.py (its path and --dir are printed) writes the tour\n// questions.mjs tour-finish --steps q1=3,q2=5,… checks the tour and puts it, and each question's step, in the file\n// questions.mjs tour-finish --none documentation that describes no code: no tour\n// questions.mjs cli <command> … the CLI found below (next, grade, flag, commit, status, …):\n// answering in a chat without VS Code\n// The draft lives in the git folder (never committed); `finish` writes understanding/<branch>.json; the tour is\n// written with the code-journey skill's journey.py into a staging folder there, then embedded as `journey`.\n// It uses understanding.mjs (the CLI): UNDERSTANDING_CLI, else the copy that ships beside this skill, else the one the\n// repository has (e.g. tools/understanding.mjs, the copy its CI runs).\nimport fs from 'node:fs'\nimport path from 'node:path'\nimport { execFileSync } from 'node:child_process'\nimport { fileURLToPath, pathToFileURL } from 'node:url'\n\nconst here = path.dirname(fileURLToPath(import.meta.url))\nconst inRepo = () => { try { const top = execFileSync('git', ['rev-parse', '--show-toplevel'], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim(); const f = execFileSync('git', ['ls-files', '--', ':(glob)**/understanding.mjs'], { cwd: top, encoding: 'utf8' }).split('\\n').find(Boolean); return f && path.join(top, f) } catch { return undefined } }\nconst cliPath = [process.env.UNDERSTANDING_CLI, path.join(here, 'understanding.mjs'), path.join(here, '../../../cli/understanding.mjs')].find((p) => p && fs.existsSync(p)) ?? inRepo()\nif (!cliPath) { console.log('PROBLEM: understanding.mjs not found (set UNDERSTANDING_CLI to its path)'); process.exit(2) }\nconst U = await import(pathToFileURL(cliPath).href)\n\n// The CLI itself, for answering in a chat (SKILL.md, \"Without VS Code\"): one path to know.\nif (process.argv[2] === 'cli') {\n const code = await U.main(process.argv.slice(3))\n // A long output (the grader's instructions) is written out before the exit.\n await new Promise((resolve) => process.stdout.write('', resolve))\n process.exit(code)\n}\n\nconst cwd = process.cwd()\nconst repo = U.repoRoot(cwd) ?? cwd\nconst draftPath = process.env.UNDERSTANDING_DRAFT || path.join(path.resolve(repo, execFileSync('git', ['rev-parse', '--git-dir'], { cwd: repo, encoding: 'utf8' }).trim()), 'understanding-draft.json')\nconst cfg = U.loadConfig(repo)\nconst o = U.parseArgs(process.argv.slice(2))\nconst cmd = o._[0]\nconst say = (s) => console.log(s)\nconst fail = (s) => { say(`PROBLEM: ${s}`); process.exit(1) }\nconst loadDraft = () => { try { return JSON.parse(fs.readFileSync(draftPath, 'utf8')) } catch { fail('no draft: run `questions.mjs start` first') } }\nconst saveDraft = (d) => fs.writeFileSync(draftPath, JSON.stringify(d, null, 2) + '\\n')\nconst MAX_DIFF_LINES = 1500\nconst gitDir = () => path.resolve(repo, execFileSync('git', ['rev-parse', '--git-dir'], { cwd: repo, encoding: 'utf8' }).trim())\n/** Where journey.py writes the tour (slug TOUR) before tour-finish embeds it. */\nconst stageDir = () => process.env.UNDERSTANDING_TOUR_DIR || path.join(gitDir(), 'understanding-tour')\nconst TOUR = 'tour'\n/** The code-journey skill's journey.py: JOURNEY_PY, the repository's copy, else the one shipped beside this skill. */\nconst journeyPy = () => [process.env.JOURNEY_PY, path.join(repo, '.claude/skills/code-journey/scripts/journey.py'), path.join(here, '../../code-journey/scripts/journey.py')].find((p) => p && fs.existsSync(p))\n/** Steps a top-up adds to a tour (a new tour: U.tourSize, by the change's kind and size). */\nconst TOPUP_STEPS = [1, 4]\nconst sizeOf = (check) => (check.diffStat ? U.linesOf(check.diffStat) : Infinity)\nconst fmtRange = (rs) => rs.map(([a, b]) => (a === b ? a : `${a}-${b}`)).join(', ')\nconst qLine = (q) => `${q.id} (${q.kind}) ${q.file}${q.target ? '' : `:${q.start}-${q.end}`}${q.also?.length ? ` (also ${q.also.map((x) => `${x.file}:${x.start}-${x.end}`).join(', ')})` : ''}${q.step ? ` · step ${q.step}` : ''}: ${q.text}`\n\n/**\n * Where `branch`'s check file is: in the working tree while it is checked out, else in the git-ignored cache the\n * extension puts back in place when the branch returns (so a branch switch never writes into another branch).\n */\nfunction checkPath(branch) {\n if (U.currentBranch(repo) === branch) return path.join(repo, U.fileFor(branch))\n const cache = path.join(repo, U.cachedFor(branch))\n fs.mkdirSync(path.dirname(cache), { recursive: true })\n const ignore = path.join(repo, '.code-notes/.cache/.gitignore')\n if (!fs.existsSync(ignore)) fs.writeFileSync(ignore, '*\\n')\n return cache\n}\n/** A file's lines at the draft's commit (the working tree may be another branch by now). */\nfunction linesAt(head, file) {\n try { return U.git(repo, ['show', `${head}:${file}`]).split('\\n') } catch { return undefined }\n}\n\n/** How many questions a change gets (U.questionsForChange: one for docs or a removal); a top-up U.topUpQuestions (an older CLI copy: its rule). */\nfunction wanted(st, lines, topUp) {\n return topUp ? (U.topUpQuestions?.(lines) ?? (lines < 80 ? 1 : 2)) : U.questionsForChange(st, cfg)\n}\n\nif (cmd === 'start') {\n const branch = typeof o.branch === 'string' ? o.branch : U.currentBranch(repo)\n const head = U.git(repo, ['rev-parse', typeof o.head === 'string' ? `${o.head}^{commit}` : 'HEAD']).trim()\n const rel = U.fileFor(branch)\n const at = checkPath(branch)\n // Its check: here, in the cache, else as committed on that branch.\n const committed = () => { try { return JSON.parse(U.git(repo, ['show', `${head}:${rel}`])) } catch { return undefined } }\n const existing = fs.existsSync(at) ? U.readCheck(at) : U.currentBranch(repo) === branch ? undefined : committed()\n const topUp = !!o['top-up']\n if (topUp && !existing) fail(`--top-up: ${rel} doesn't exist yet; run start without it`)\n if (!topUp && existing && !o.replace) fail(`${rel} exists already. Use --top-up to add questions about what changed since, or --replace to start over (its answers are lost)`)\n const baseRef = typeof o.base === 'string' ? o.base : U.defaultBase(repo)\n const mb = baseRef && U.mergeBase(repo, baseRef, head)\n if (!mb) fail('no base to compare with: pass --base <branch or commit>')\n // Stacked on a branch whose check is committed here: only what came after that check's code.\n const stack = U.stackBase(repo, mb, head, rel)\n const base = stack?.base ?? mb\n if (stack) say(`STACKED: on ${stack.branch}, whose check covers its own code; this change starts after it.`)\n // Committed code only: the questions record the commit they were written for (uncommitted lines would count as drift).\n // Code lines only: blank and comment-only lines don't count, nor the config's exempt files.\n // Always the branch's OWN change (from today's merge base): code that came in from the target branch is never asked.\n let files = U.numstat(repo, base, head)\n // Uncommitted lines: only those of this branch's working tree (another branch may be checked out by now).\n const loose = U.currentBranch(repo) === branch ? U.linesOf(U.codeStat(repo, head, undefined, cfg.exempt)) : 0\n const st = U.codeStat(repo, base, head, cfg.exempt)\n let lines = U.linesOf(st), ranges\n if (topUp) {\n // Only what the branch's own change gained since the questions (freshLines); else, when the questions' commits are\n // gone, what changed since the questions' commit, or the whole change.\n const fresh = U.freshLines(repo, existing, base, head, cfg.exempt)\n ?? (U.hasCommit(repo, existing.head) ? U.codeLines(repo, existing.head, head, cfg.exempt) : U.codeLines(repo, base, head, cfg.exempt))\n lines = fresh.length\n ranges = U.rangesOf(fresh)\n files = files.filter((f) => ranges.has(f.file))\n }\n if (!topUp && !lines && loose && U.currentBranch(repo) === branch) { say(`UNCOMMITTED: this change is not committed yet (${loose} code lines). Ask the person to commit it first. Write nothing.`); process.exit(0) }\n const renamedOnly = !topUp && !lines && st.renamed?.length > 0\n if ((!lines && !renamedOnly) || (topUp && !ranges.size)) { say(`NOTHING: no code lines changed${topUp ? ' since the questions were written' : ''} (only comments, blank lines or exempt files). Write nothing.`); process.exit(0) }\n const diff = U.diffText(repo, base, head, files, cfg.exempt)\n ranges ??= U.changedRanges(diff, { codeOnly: true })\n // Removed code is part of the change: a question may sit where code was removed, and when the change only removes\n // code, also where the removed code was used (any file).\n for (const [f, rs] of U.removalPoints(diff)) ranges.set(f, [...(ranges.get(f) ?? []), ...rs])\n // A moved file: a question about the move itself (--whole-file), never about the content it kept.\n if (renamedOnly) for (const r of st.renamed) if (!ranges.has(r.to)) ranges.set(r.to, [])\n const removedOnly = !topUp && U.changeKind(st) === 'removal'\n // Only documentation changed: one question about what a reader now sees or understands differently.\n const docsOnly = !topUp && U.changeKind(st) === 'docs'\n const want = wanted(st, lines, topUp)\n const stat = (x) => ({ files: x.files, added: x.added, removed: x.removed })\n const fmt = (rs) => rs.map(([a, b]) => (a === b ? a : `${a}-${b}`)).join(', ')\n saveDraft({ branch, base, head, mode: topUp ? 'top-up' : 'new', want, diffStat: stat(st), ranges: Object.fromEntries(ranges), ...(removedOnly ? { removedOnly } : {}), ...(docsOnly ? { docsOnly } : {}), questions: [] })\n say(topUp ? `TOP-UP: branch ${branch} · ${lines} new code lines since the questions were written` : `CHANGE: branch ${branch} · ${st.files} files · ${lines} code lines (+${st.added} −${st.removed})`)\n if (loose) say(`NOTE: ${loose} uncommitted code lines are not included.`)\n if (docsOnly) say('DOCS ONLY: only documentation changed. Write ONE question about what a reader now sees, can do or understands differently (never why a word was chosen, never about unchanged text). \"It is just wording\" is a full answer.')\n if (renamedOnly) say(`RENAMED ONLY: ${st.renamed.map((r) => `${r.from} → ${r.to}`).join(', ')}, 0 lines changed. Ask only what the move changes (how a tool, an import or a convention treats the new name or place), with --whole-file; never about the content it kept.`)\n if (removedOnly) {\n // The evidence: where the removed names still appear (a search of the repository at the change's commit).\n const found = U.searchNames(repo, head, U.removedNames(U.codeLines(repo, base, head, cfg.exempt)))\n say(`REMOVED ONLY: this change only removes code. Write ONE evidence question (--evidence --kind change): what a search found about the removed code, for the author to confirm or correct in one sentence. Put it on the lines where code was removed (${[...ranges].map(([f, rs]) => `${f}:${fmt(rs)}`).join(' · ') || 'none left: the files are gone'}), or on code that used what was removed (any file).`)\n if (found.length) say(`EVIDENCE (search at ${head.slice(0, 7)}): ${found.map(U.evidenceText).join(' · ')}`)\n const none = found.find((e) => !e.hits.length), some = found.find((e) => e.hits.length)\n say(` e.g. ${none ? `\"Nothing calls ${none.name} any more (search: 0 hits) — right?\"` : some ? `\"${some.name} is still named in ${some.hits[0].file} (search: ${some.hits.length} hit${some.hits.length === 1 ? '' : 's'}) — what happens there now?\"` : '\"Nothing used what this removes (search: 0 hits) — right?\"'} Check the hits yourself (Grep) before you write it; keep the numbers true.`)\n }\n if (topUp) say(`NEW LINES (ask only about these): ${[...ranges].map(([f, rs]) => `${f}:${fmt(rs)}`).join(' · ')}`)\n say(`WRITE: ${want} question${want === 1 ? '' : 's'}${topUp ? ' about these new lines only' : ''}, about code lines (never comments or blank lines), then \\`finish\\`. Files: ${files.filter((f) => U.counted(f.file, cfg.exempt)).map((f) => `${f.file} (+${f.added} −${f.removed})`).join(', ')}`)\n const numbered = U.numberDiff(diff).split('\\n')\n say('')\n say(numbered.slice(0, MAX_DIFF_LINES).join('\\n'))\n if (numbered.length > MAX_DIFF_LINES) say(`\\n… the diff goes on (${numbered.length - MAX_DIFF_LINES} more lines): read the remaining files with Read; line numbers are the files' own.`)\n process.exit(0)\n}\n\nif (cmd === 'add') {\n const d = loadDraft()\n const kind = String(o.kind ?? '')\n const file = String(o.file ?? '').replace(/^\\.\\//, '')\n const text = String(o.text ?? '').replace(/\\s+/g, ' ').trim()\n if (!U.KINDS.includes(kind)) fail(`--kind must be one of ${U.KINDS.join(', ')}`)\n if (!file) fail('--file is missing')\n // The file as committed in the change (whatever is checked out now).\n const lines = linesAt(d.head, file)\n if (!lines) fail(`${file} doesn't exist`)\n // A removal-only change: also the code that used what was removed (anywhere).\n const ranges = d.ranges[file] ?? (d.removedOnly ? [] : undefined)\n if (!ranges) fail(`${file} is not part of this ${d.mode === 'top-up' ? 'new change' : 'change'}: ask about the changed files (${Object.keys(d.ranges).join(', ')})`)\n if (text.length < 25) fail('--text is too short: ask a real question about this change')\n if (text.length > U.MAX_TEXT) fail(`--text is ${text.length} characters: at most ${U.MAX_TEXT}. One question, plainly`)\n if (!text.endsWith('?')) fail('--text must be one question, ending with \"?\"')\n if ((text.match(/\\?/g) ?? []).length > 1) fail('--text asks more than one question: ask one')\n if (/(,?\\s+(and|or)( also| then)?|;|\\s+as well as)\\s+(how|what|why|when|where|which|who|whose|does|do|did|is|are|was|were|can|could|would|should|will|has|have|if)\\b/i.test(text)) fail('--text asks two things (\"…, and could …\"): keep the one that matters')\n // \"what happens to X, Y and Z\": three things to cover is three questions.\n if (/,\\s+(?!(?:what|how|why|when|where|which|who|does|do|is|are|can|could|would|should|will|if|so|but|or)\\b)[^,?]{1,60},?\\s+(and|or)\\s+[^?]+\\?$/i.test(text)) fail('--text asks about a list of things (\"X, Y and Z\"): ask about the one that matters')\n // \"What does f(x) return for 200 at qty 61?\": one computed value per check at most.\n const computed = (t) => /^(what|which)\\b[^?]*\\b(return|returns|price|cost|total|result|value)\\b[^?]*\\d/i.test(t) || /^(what|which)\\b[^?]*\\d[^?]*\\breturns?\\b/i.test(t)\n if (computed(text) && d.questions.some((x) => computed(x.text))) fail('a second \"what does it return for <numbers>\" question: one is enough; ask why, or what can go wrong, instead')\n if (/\\bline\\s+\\d+/i.test(text)) fail('--text names a line number: name the function, value or case instead (the question is shown on its lines)')\n if (/^(what does|what is)\\b/i.test(text) && kind === 'how' && text.length < 60) say('WARNING: \"what does X do\" questions are trivia; ask how it behaves in a case, or why')\n const q = { id: '', kind, text, file }\n if (o['whole-file']) q.target = 'file'\n else {\n const m = /^(\\d+)(?:-(\\d+))?$/.exec(String(o.lines ?? ''))\n if (!m) fail('--lines A-B (or --whole-file for a question about the design of the whole file)')\n q.start = Number(m[1]); q.end = Number(m[2] ?? m[1])\n if (q.end < q.start) fail('--lines: the end is before the start')\n if (q.end > lines.length) fail(`--lines: ${file} has ${lines.length} lines`)\n if (q.end - q.start > 40) fail('--lines: more than 40 lines; point at the lines that matter (the question shows on them)')\n const cs = {}\n if (!lines.slice(q.start - 1, q.end).map((l) => U.isCode(l, file, cs)).some(Boolean)) fail(`--lines ${q.start}-${q.end} hold only comments or blank lines: ask about code`)\n const near = (d.removedOnly && !d.ranges[file]) || ranges.some(([a, b]) => q.start <= b + 5 && q.end >= a - 5)\n if (!near) fail(`--lines ${q.start}-${q.end} are not near a changed code line of ${file} (changed: ${ranges.map(([a, b]) => (a === b ? a : `${a}-${b}`)).join(', ')})`)\n q.anchor = U.compactOf(lines, q.start, q.end)\n }\n // The honest answer is \"this is a bug\": once answered, the author is offered a fix, a TODO or a flag.\n if (o.suspect) q.suspect = true\n // A removal: the author confirms or corrects what a search found (the grader passes a true one-sentence answer).\n if (o.evidence) { if (!d.removedOnly) fail('--evidence is for a change that only removes code'); q.evidence = true }\n // Unchanged code the answer depends on (a caller, a retry loop, a constraint): shown beside the question.\n if (typeof o.also === 'string' && o.also.trim()) {\n q.also = []\n for (const part of o.also.split(',').map((x) => x.trim()).filter(Boolean)) {\n const m = /^(.+):(\\d+)(?:-(\\d+))?$/.exec(part)\n if (!m) fail(`--also ${part}: write it as path:A-B`)\n const f = m[1].replace(/^\\.\\//, ''), a = Number(m[2]), b = Number(m[3] ?? m[2])\n const fl = path.isAbsolute(f) || f.split(/[\\\\/]/).includes('..') ? undefined : linesAt(d.head, f)\n if (!fl) fail(`--also: ${f} doesn't exist`)\n if (b < a || b > fl.length) fail(`--also ${part}: ${f} has ${fl.length} lines`)\n if (b - a > 40) fail(`--also ${part}: more than 40 lines; point at the lines that matter`)\n if (f === q.file && q.start && a <= q.end && q.start <= b) fail(`--also ${part}: overlaps the question's own lines`)\n q.also.push({ file: f, start: a, end: b, anchor: U.compactOf(fl, a, b) })\n }\n if (q.also.length > 3) fail('--also: at most 3 places')\n }\n // Code links: words of the question shown as a clickable phrase that lights those lines (never line numbers).\n if (typeof o.links === 'string' && o.links.trim()) {\n const raw = []\n for (const part of o.links.split(';').map((x) => x.trim()).filter(Boolean)) {\n const m = /^(.+)@([^@]+):(\\d+)(?:-(\\d+))?$/.exec(part)\n if (!m) fail(`--links ${part}: write it as \"phrase@path:A-B\"`)\n const phrase = m[1].trim()\n if (!text.includes(phrase)) fail(`--links: \"${phrase}\" is not in the question's text (exactly as written)`)\n raw.push({ phrase, file: m[2].replace(/^\\.\\//, ''), start: Number(m[3]), end: Number(m[4] ?? m[3]) })\n }\n if (raw.length > 3) fail('--links: at most 3')\n const ok = U.codeLinksIn(repo, raw, (f) => { const l = linesAt(d.head, f); if (!l) throw new Error(f); return l })\n const bad = raw.filter((l) => !ok.some((x) => x.phrase === l.phrase))\n if (bad.length) fail(`--links: ${bad.map((l) => `${l.file}:${l.start}-${l.end}`).join(', ')} is not a range of a file in the repository`)\n q.links = ok\n }\n if (d.questions.some((x) => x.file === q.file && x.start && q.start && x.start <= q.end && q.start <= x.end)) say('WARNING: another question is on overlapping lines: make sure it asks something different')\n d.questions.push(q)\n saveDraft(d)\n say(`added #${d.questions.length} (${kind}) ${file}${q.target ? '' : `:${q.start}-${q.end}`}${q.also ? ` (also ${q.also.map((x) => `${x.file}:${x.start}-${x.end}`).join(', ')})` : ''}${q.links ? ` · ${q.links.length} link${q.links.length === 1 ? '' : 's'}` : ''} · ${d.questions.length} of ${d.want}`)\n if (!q.target) say(` ${lines[q.start - 1].trim().slice(0, 100)}${q.end > q.start ? `\\n … ${lines[q.end - 1].trim().slice(0, 100)}` : ''}`)\n process.exit(0)\n}\n\nif (cmd === 'list') {\n const d = loadDraft()\n d.questions.forEach((q, i) => say(`#${i + 1} ${q.kind} ${q.file}${q.target ? '' : `:${q.start}-${q.end}`}: ${q.text}`))\n say(`${d.questions.length} of ${d.want}`)\n process.exit(0)\n}\n\nif (cmd === 'remove') {\n const d = loadDraft()\n const i = Number(String(o._[1] ?? '').replace(/^#/, '')) - 1\n if (!(i >= 0 && i < d.questions.length)) fail('remove <number> (as `list` shows it)')\n d.questions.splice(i, 1)\n saveDraft(d)\n say(`removed; ${d.questions.length} of ${d.want}`)\n process.exit(0)\n}\n\nif (cmd === 'finish') {\n const d = loadDraft()\n const n = d.questions.length\n // The count follows the change's size: exactly `want` for a small change (1 or 2), 3 up to the config's max above.\n const [lo, hi] = d.mode === 'top-up' ? [1, 2] : d.want < 3 ? [d.want, d.want] : [Math.min(3, d.want), Math.max(d.want, cfg.questions.max)]\n if (n < lo || n > hi) fail(`${n} question${n === 1 ? '' : 's'}: write ${lo === hi ? lo : `${lo}-${hi}`} for this change${lo === hi ? '' : ` (${d.want} suggested)`}`)\n const kinds = new Set(d.questions.map((q) => q.kind))\n if (d.mode !== 'top-up' && n >= 3 && kinds.size < 2) fail('all questions are of one kind: mix them (how, why, failure, edge, change)')\n if (d.mode !== 'top-up' && n >= 3 && ![...kinds].some((k) => ['why', 'failure', 'edge'].includes(k))) fail('ask at least one why, failure or edge question')\n if (d.removedOnly && !d.questions.some((q) => q.evidence)) fail('this change only removes code: its question is an evidence question (add it with --evidence; see EVIDENCE)')\n const rel = U.fileFor(d.branch)\n // Its branch was switched away from meanwhile: into the cache, never into the branch checked out now.\n const abs = checkPath(d.branch)\n const model = process.env.UNDERSTANDING_MODEL_LABEL || process.env.UNDERSTANDING_MODEL || undefined\n let check\n if (d.mode === 'top-up') {\n check = fs.existsSync(abs) ? U.readCheck(abs) : JSON.parse(U.git(repo, ['show', `${d.head}:${rel}`]))\n let k = Math.max(0, ...check.questions.map((q) => Number(q.id.slice(1)) || 0))\n const round = Math.max(1, ...check.questions.map((q) => q.round ?? 1)) + 1\n for (const q of d.questions) check.questions.push({ ...q, id: `q${++k}`, round })\n check.base = d.base\n check.head = d.head\n check.diffStat = d.diffStat\n check.updatedAt = new Date().toISOString()\n } else {\n const who = U.gitIdentity(repo)\n check = { version: 1, branch: d.branch, base: d.base, head: d.head, diffStat: d.diffStat, ...(who ? { answeredBy: who } : {}), ...(model ? { model } : {}), createdAt: new Date().toISOString(),\n questions: d.questions.map((q, i) => ({ ...q, id: `q${i + 1}`, ...(d.docsOnly ? { docs: true } : {}) })) }\n }\n // Its files are checked in the working tree only while its branch is checked out (they were read at its commit).\n const errs = U.validateCheck(check, U.currentBranch(repo) === d.branch ? { repo } : {})\n if (errs.length) fail(`the file would not be valid: ${errs.join('; ')}`)\n U.writeCheck(abs, U.stamp(check, cfg))\n fs.rmSync(draftPath, { force: true })\n say(`WROTE ${path.relative(repo, abs) === rel ? rel : `${rel} (kept for ${d.branch}: it is not checked out)`}: ${check.questions.length} questions${d.mode === 'top-up' ? ` (${n} new)` : ''}. Done: reply with one line per new question.`)\n process.exit(0)\n}\n\nif (cmd === 'tour') {\n const branch = typeof o.branch === 'string' ? o.branch : U.currentBranch(repo)\n const rel = U.fileFor(branch)\n const abs = checkPath(branch)\n if (!fs.existsSync(abs)) fail(`${rel} doesn't exist: write the questions first (start, add, finish)`)\n const check = U.readCheck(abs)\n const J = journeyPy()\n if (!J) fail('journey.py (the code-journey skill) was not found: set JOURNEY_PY to its path')\n const stage = stageDir()\n fs.rmSync(stage, { recursive: true, force: true })\n fs.mkdirSync(stage, { recursive: true })\n const topUp = !!o['top-up'] && !!check.journey\n // The branch it is for: tour-finish writes there even after a branch switch.\n fs.writeFileSync(path.join(stage, 'meta.json'), JSON.stringify({ branch }) + '\\n')\n if (topUp) fs.writeFileSync(path.join(stage, `${TOUR}.json`), JSON.stringify({ ...check.journey, id: TOUR }, null, 2) + '\\n')\n // What the tour must show: the change's lines (a top-up: only what is new since the tour), by file.\n const base = check.base && U.hasCommit(repo, check.base) ? check.base : U.mergeBase(repo, U.defaultBase(repo) ?? 'HEAD', check.head)\n let ranges\n if (topUp) {\n const known = new Set(check.journey.steps.map((s) => s.file))\n const fresh = check.journey.commit && U.hasCommit(repo, check.journey.commit) ? U.codeLines(repo, check.journey.commit, check.head, cfg.exempt) : []\n ranges = U.rangesOf(fresh)\n if (!ranges.size) for (const q of check.questions.filter((x) => !x.step)) if (!known.has(q.file)) ranges.set(q.file, [[q.start ?? 1, q.end ?? 1]])\n } else ranges = base ? U.changedRanges(U.diffText(repo, base, check.head, U.numstat(repo, base, check.head), cfg.exempt), { codeOnly: true }) : new Map()\n const want = topUp ? check.questions.filter((q) => !q.step) : check.questions\n const kind = U.checkKind(check)\n const [lo, hi] = topUp ? TOPUP_STEPS : U.tourSize(kind, sizeOf(check))\n const n0 = topUp ? check.journey.steps.length : 0\n const st = check.diffStat\n // A removal: where the removed code was used; never steps on code that is gone.\n if (!topUp && kind === 'removal' && base) for (const [f, rs] of U.removalPoints(U.diffText(repo, base, check.head, U.numstat(repo, base, check.head), cfg.exempt))) ranges.set(f, [...(ranges.get(f) ?? []), ...rs])\n say(topUp ? `TOUR TOP-UP: the tour of ${branch} has ${n0} steps; add ${lo}-${hi} after step ${n0}, through the new part only` : `TOUR: a journey of this change (${branch}, ${st ? `+${st.added} −${st.removed} ${kind === 'docs' ? 'lines' : 'code lines'}` : 'its size unknown'}): ${lo}-${hi} steps${kind === 'code' ? ' through the changed code and the unchanged code it depends on, in the order a request or the data flows' : ''}. Its title names the change (\"Dropping refundReport\", \"Bumping the version\"), not the area`)\n if (!topUp && kind === 'docs') say(`DOCS: the change edits documentation. Steps on the EXISTING code the edited text describes (what a reader can now find or do there), never on the text itself. When the text describes no code, write no tour: run questions.mjs tour-finish --none`)\n else if (!topUp && kind === 'removal') say('REMOVAL: this change only removes code. Steps on code that is still there: where the removed code used to be called (or show that nothing calls it: the search), and why removing it is safe (what takes its place, what never reached it); nothing else')\n // A change that mostly removes code: the tour shows what went and why that is safe, not the code around it.\n else if (!topUp && st && st.removed > 2 * st.added) say('REMOVAL: this change mostly removes code. Steps: what was removed (on the lines where it was), what used it before (or that nothing does now: say how you checked), and the one or two lines that changed besides; nothing else')\n else if (!topUp && sizeOf(check) < 10) say('SMALL: a few lines changed. Steps around the changed lines: what calls them and what they change; nothing else')\n // journey.py check wants 6-14 steps for a journey of the repository; a tour has its own count.\n const steps = `(its \"N steps (want 6-14 …)\" line doesn't apply: this tour has ${n0 + lo}-${n0 + hi})`\n say(`JOURNEY: ${J} <command> <repo> ${TOUR} … --dir ${stage} (repo: ${repo}; always --dir; slug ${TOUR})`)\n if (topUp) { say('STEPS SO FAR (keep them as they are):'); check.journey.steps.forEach((s, i) => say(` ${i + 1}. ${s.title} (${s.file}:${s.range.start}-${s.range.end})`)) }\n say(`QUESTIONS ${topUp ? 'that need a step' : '(each needs the step after which its answer is visible)'}:`)\n for (const q of want) say(` ${qLine(q)}`)\n if (ranges.size) say(`CHANGED: ${[...ranges].map(([f, rs]) => `${f}:${fmtRange(rs)}`).join(' · ')}`)\n say(`THEN: ${J} check <repo> ${TOUR} quiet --dir ${stage}; fix every PROBLEM ${steps}; then questions.mjs tour-finish --steps ${want.map((q) => `${q.id}=<n>`).join(',')}`)\n process.exit(0)\n}\n\nif (cmd === 'tour-finish') {\n let meta = {}\n try { meta = JSON.parse(fs.readFileSync(path.join(stageDir(), 'meta.json'), 'utf8')) } catch { /* none: this branch */ }\n const branch = meta.branch || U.currentBranch(repo)\n const rel = U.fileFor(branch)\n // Its branch was switched away from meanwhile: the extension keeps its check in .code-notes/.cache/checks.\n const abs = [path.join(repo, rel), path.join(repo, '.code-notes/.cache/checks', `${U.slugOf(branch)}.json`)].find((f) => fs.existsSync(f))\n if (!abs) fail(`${rel} doesn't exist`)\n // Documentation that describes no code: no tour, on purpose (the check says so; nothing offers to write one).\n if (o.none) {\n const check = U.readCheck(abs)\n if (U.checkKind(check) !== 'docs' || check.journey) fail('--none is only for a change to documentation that describes no code')\n check.noTour = true\n U.writeCheck(abs, check)\n fs.rmSync(stageDir(), { recursive: true, force: true })\n say(`WROTE ${rel}: no tour (the edited text describes no code). Done: reply \"No tour: the text describes no code.\"`)\n process.exit(0)\n }\n const staged = path.join(stageDir(), `${TOUR}.json`)\n let j\n try { j = JSON.parse(fs.readFileSync(staged, 'utf8')) } catch { fail(`no tour in ${stageDir()}: run \\`questions.mjs tour\\`, then journey.py new … ${TOUR} --dir …`) }\n const J = journeyPy()\n if (J) {\n let out = '', code = 0\n try { out = execFileSync('python3', [J, 'check', repo, TOUR, 'quiet', '--dir', stageDir()], { cwd: repo, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }) } catch (e) { code = e.status ?? 1; out = `${e.stdout ?? ''}${e.stderr ?? ''}` }\n // The count is checked below, by the change's size: journey.py's own count (6-14, for a journey of the repository)\n // doesn't apply to a tour. Any other problem does.\n const problems = out.split('\\n').filter((l) => /^PROBLEM:/.test(l) && !/^PROBLEM: \\d+ steps \\(want \\d+-\\d+/.test(l))\n if (code && (problems.length || !/^PROBLEM:/m.test(out))) { say(out.trim()); fail('journey.py check found problems: fix them, then tour-finish again') }\n }\n // The file as it is now: answers given while the tour was written are kept.\n const check = U.readCheck(abs)\n const before = check.journey\n const n0 = before ? before.steps.length : 0\n const steps = Array.isArray(j.steps) ? j.steps : []\n const added = steps.length - n0\n if (before) {\n // A top-up only appends: the steps the questions already point at stay where they are.\n const same = before.steps.every((s, i) => steps[i] && steps[i].id === s.id && steps[i].title === s.title && steps[i].file === s.file)\n if (!same) fail(`the first ${n0} steps changed: a top-up only adds steps after step ${n0} (journey.py restore, or rmstep the new ones and add them again)`)\n if (added < TOPUP_STEPS[0] || added > TOPUP_STEPS[1]) fail(`${added} new steps: add ${TOPUP_STEPS[0]}-${TOPUP_STEPS[1]} after step ${n0}`)\n } else { const [lo, hi] = U.tourSize(U.checkKind(check), sizeOf(check)); if (steps.length < lo || steps.length > hi) fail(`${steps.length} steps: a tour of this change has ${lo}-${hi} (its size)`) }\n // No animations in a check's tour (time and cost): dropped if any.\n for (const s of steps) delete s.scene\n const given = new Map()\n for (const part of String(o.steps ?? '').split(',').map((x) => x.trim()).filter(Boolean)) {\n const m = /^(q\\d+)\\s*=\\s*(\\d+)$/.exec(part)\n if (!m) fail(`--steps ${part}: write it as q1=3`)\n if (!check.questions.some((q) => q.id === m[1])) fail(`--steps: there is no question ${m[1]}`)\n given.set(m[1], Number(m[2]))\n }\n const problems = []\n for (const q of check.questions) {\n const n = given.get(q.id) ?? q.step\n if (!n) { problems.push(`${q.id} has no step: --steps ${q.id}=<n>`); continue }\n if (n < 1 || n > steps.length) { problems.push(`${q.id}=${n}: the tour has ${steps.length} steps`); continue }\n if (before && given.has(q.id) && q.step && q.step !== n) { problems.push(`${q.id} is at step ${q.step} already: keep it`); continue }\n // Its answer must be visible by then: a step up to n shows the question's file (or the code it also depends on).\n // Documentation and a removal: the tour shows the code the text describes, or where the removed code was used.\n const files = new Set([q.file, ...(q.also ?? []).map((x) => x.file)])\n if (!q.docs && !q.evidence && !steps.slice(0, n).some((s) => files.has(s.file))) problems.push(`${q.id}=${n}: no step up to ${n} is in ${[...files].join(' or ')}; give a later step, or add a step there`)\n q.step = n\n }\n if (problems.length) fail(problems.join('; '))\n const model = process.env.UNDERSTANDING_MODEL_LABEL || process.env.UNDERSTANDING_MODEL || undefined\n delete check.noTour\n check.journey = { ...j, id: TOUR, commit: check.head, ...(before?.createdAt ? { createdAt: before.createdAt, updatedAt: new Date().toISOString() } : { createdAt: new Date().toISOString() }), ...(model ? { model } : {}) }\n // Its files are checked in the working tree only while its branch is checked out (they were read at its commit).\n const errs = U.validateCheck(check, U.currentBranch(repo) === branch ? { repo } : {})\n if (errs.length) fail(`the file would not be valid: ${errs.join('; ')}`)\n U.writeCheck(abs, U.stamp(check, cfg))\n fs.rmSync(stageDir(), { recursive: true, force: true })\n say(`WROTE the tour into ${rel}: ${steps.length} steps${before ? ` (${added} new)` : ''}; ${check.questions.map((q) => `${q.id} after step ${q.step}`).join(', ')}. Done: reply with the step titles, one per line.`)\n process.exit(0)\n}\n\nsay(`questions.mjs start [--base <ref>] [--top-up] [--replace] | add --kind <${U.KINDS.join('|')}> --file <path> (--lines A-B | --whole-file) --text \"<question>\" [--also <path>:A-B,…] [--suspect] [--evidence] | list | remove <n> | finish | tour [--top-up] | tour-finish (--steps q1=<n>,… | --none) | cli <command> …`)\nprocess.exit(cmd ? 2 : 0)\n" +}; + +// cli/understanding/init.ts var INIT_LINES = { // The settings stay in sight: a merge request that changes them shows the change. ".gitattributes": [`${DIR}/*.json gitlab-generated linguist-generated`, `${DIR}/config.json -gitlab-generated -linguist-generated`], @@ -1911,19 +1925,24 @@ var foldDiffs = (repo) => initRepo(repo, { only: ".gitattributes" }); var FOLD_TEXT = "also folds check files in diffs (.gitattributes)"; function skillSource(cli = SELF) { const here = path9.dirname(cli); - const dir = [path9.join(here, "../skills/understanding-check"), path9.join(here, "..")].find((d) => fs7.existsSync(path9.join(d, "SKILL.md")) && fs7.existsSync(path9.join(d, "scripts/questions.mjs"))); - return dir ? { dir, cli } : void 0; + const names = Object.keys(SKILL_FILES); + const dir = cli ? [path9.join(here, "../skills/understanding-check"), path9.join(here, "..")].find((d) => names.every((f) => fs7.existsSync(path9.join(d, f)))) : void 0; + const files = dir ? Object.fromEntries(names.map((f) => [f, fs7.readFileSync(path9.join(dir, f), "utf8")])) : SKILL_FILES; + return { files, cli }; } var hasSkill = (repo) => fs7.existsSync(path9.join(repo, SKILL_DIR, "SKILL.md")); -var committedCli = (repo) => (gitOk(repo, ["ls-files", "--", ":(glob)**/understanding.mjs"]) ?? "").split("\n").find((f) => f && !f.startsWith(`${SKILL_DIR}/`)); +function repoCli(repo, cli) { + const committed = (gitOk(repo, ["ls-files", "--", ":(glob)**/understanding.mjs"]) ?? "").split("\n").find((f) => f && !f.startsWith(`${SKILL_DIR}/`)); + if (committed || !cli) return committed; + const rel = path9.relative(fs7.realpathSync(repo), fs7.realpathSync(cli)).split(path9.sep).join("/"); + return !rel.startsWith("..") && !path9.isAbsolute(rel) && !rel.startsWith(`${SKILL_DIR}/`) ? rel : void 0; +} function installSkill(repo, from = skillSource()) { - if (!from) return void 0; - const want = [["SKILL.md", path9.join(from.dir, "SKILL.md")], ["scripts/questions.mjs", path9.join(from.dir, "scripts/questions.mjs")]]; - if (!committedCli(repo)) want.push(["scripts/understanding.mjs", from.cli]); + const want = Object.entries(from.files).map(([rel, text]) => [rel, Buffer.from(text)]); + if (from.cli && !repoCli(repo, from.cli)) want.push(["scripts/understanding.mjs", fs7.readFileSync(from.cli)]); const out = []; - for (const [rel, from2] of want) { + for (const [rel, text] of want) { const to = path9.join(repo, SKILL_DIR, rel); - const text = fs7.readFileSync(from2); let have; try { have = fs7.readFileSync(to); @@ -2205,7 +2224,7 @@ function answersSection(check, sum, link) { const title = `**${questionText(q.text)}** · ${refText(q, link)}${q.suspect ? " · may be a bug" : ""}`; if (s === STATE.restated) { const a = as.findLast((x) => x.verdict === STATE.restated); - all.push("", `${title}${byText(a, check)} · restated after an explanation`, ...answer(a)); + all.push("", `${title}${byText(a, check)}`, ...answer(a)); } else if (s === STATE.explained) { all.push("", `${title} · explained`); } else { @@ -3001,13 +3020,12 @@ function initCommand({ repo, print }) { const changed = initRepo(repo); const skill = installSkill(repo); const files = [...new Set(changed.map((l) => l.split(":")[0]))]; - const skillLine = skill?.length ? [`the skill (${SKILL_DIR}: ${skill.map((f) => path12.basename(f)).join(", ")})`] : []; - print(changed.length || skill?.length ? `Added: ${[...changed, ...skillLine].join("; ")}.` : "Already set up."); - if (files.length || skill?.length) { - print(`Commit them: git add ${[...files, ...skill?.length ? [SKILL_DIR] : []].join(" ")} && git commit -m "Add understanding check setup"`); + const skillLine = skill.length ? [`the skill (${SKILL_DIR}: ${skill.map((f) => path12.basename(f)).join(", ")})`] : []; + print(changed.length || skill.length ? `Added: ${[...changed, ...skillLine].join("; ")}.` : "Already set up."); + if (files.length || skill.length) { + print(`Commit them: git add ${[...files, ...skill.length ? [SKILL_DIR] : []].join(" ")} && git commit -m "Add understanding check setup"`); } - if (skill?.length || skill && hasSkill(repo)) print("Without VS Code: type /understanding-check in Claude Code."); - else if (!skill) print(withoutVsCode(hasSkill(repo))); + print(withoutVsCode(hasSkill(repo))); print(`CI recipe: ${CI_URL}`); return 0; } @@ -3120,7 +3138,7 @@ function nextCommand({ repo, env, print }) { const c = branch.check; const q = nextQuestion(c); if (!q) { - print(progressLine(c, loadConfig(repo), repo, env)); + print(grownLine(repo, env) ?? progressLine(c, loadConfig(repo), repo, env)); return 0; } const i = c.questions.indexOf(q); @@ -3175,6 +3193,12 @@ function branchCheck(repo, env, print) { return void 0; } } +function grownLine(repo, env) { + const s = localStatus(repo, { env }); + if (s.state.phase !== "drift") return void 0; + const w = stateWords(s.state, s); + return `${w.title} · ${w.line}`; +} function gradeLine(q, a) { const hint = a.hint ? ` Hint: ${a.hint}` : ""; @@ -3353,6 +3377,7 @@ export { summarize, syncConcerns, threadBody, + topUpQuestions, tourProblems, tourSize, tourText, diff --git a/cli/understanding/changeFiles.ts b/cli/understanding/changeFiles.ts index 8a16a6f..c94939a 100644 --- a/cli/understanding/changeFiles.ts +++ b/cli/understanding/changeFiles.ts @@ -17,8 +17,11 @@ export function globRe(glob: string): RegExp { /** Documentation files: a change made only of these gets one question about what a reader sees differently. */ export const isDoc = (file: string): boolean => /\.(md|mdx|markdown|rst|adoc|txt)$/i.test(file) || /(^|\/)docs?\//i.test(file) -/** Files that never count: the check itself, Code Notes' notes, and what `init` writes for them (its lines, the skill). */ -export const own = (file: string): boolean => file.startsWith(`${DIR}/`) || file.startsWith('.code-notes/') || file === '.gitattributes' || file === '.ignore' || file.startsWith(`${SKILL_DIR}/`) +/** + * Files that never count: the check itself, Code Notes' notes, what `init` writes for them (its lines, the skill) and + * a committed copy of this CLI (tools/understanding.mjs: the docs suggest one for CI). + */ +export const own = (file: string): boolean => file.startsWith(`${DIR}/`) || file.startsWith('.code-notes/') || file === '.gitattributes' || file === '.ignore' || file.startsWith(`${SKILL_DIR}/`) || /(^|\/)understanding\.mjs$/.test(file) /** Whether a changed file counts: not the check itself, not one of the config's `exempt` globs (none by default). */ export function counted(file: string, exempt: string[] = []): boolean { return !own(file) && !exempt.some((g) => globRe(g).test(file)) diff --git a/cli/understanding/constants.ts b/cli/understanding/constants.ts index b52721f..144a716 100644 --- a/cli/understanding/constants.ts +++ b/cli/understanding/constants.ts @@ -51,7 +51,8 @@ export const TOUR_LINE = 'A guided tour of this change: open it in VS Code with /** The project's repository: the docs, the CI recipes and the skill, for people who only have this file. */ const REPO_URL = 'https://github.com/tomeyer97/code-notes' export const DOCS_URL = `${REPO_URL}/blob/main/docs/understanding-check.md` -export const CI_URL = `${REPO_URL}#in-ci` +/** The CI recipes: the docs' "In CI" section (the README has none). */ +export const CI_URL = `${DOCS_URL}#in-ci` /** The skill that writes the questions (and, in Claude Code without VS Code, asks them in the chat). */ export const SKILL_URL = `${REPO_URL}/tree/main/skills/understanding-check` diff --git a/cli/understanding/index.ts b/cli/understanding/index.ts index 2b8173f..fe5c725 100644 --- a/cli/understanding/index.ts +++ b/cli/understanding/index.ts @@ -13,7 +13,7 @@ export { ciBranch, currentBranch, DEFAULT_BRANCHES, defaultBase, git, gitRun, ha export { counted, globRe, isDoc, own } from './changeFiles' export { commentStyle, isCode } from './comments' export { changedRanges, codeLines, codeStat, diffText, freshLines, hunksOf, linesOf, nearestChanged, newCodeLines, numberDiff, numstat, oldLineOf, rangesOf, removalPoints, stat } from './diff' -export { changeKind, checkKind, evidenceText, minutesFor, questionsFor, questionsForChange, removedNames, searchNames, sizeText, sizeWords, tourSize } from './size' +export { changeKind, checkKind, evidenceText, minutesFor, questionsFor, questionsForChange, removedNames, searchNames, sizeText, sizeWords, topUpQuestions, tourSize } from './size' export { addAttempt, attemptHash, CACHE, cachedFor, conflictOf, conflictSides, fileFor, flagConcern, gitIdentity, loadConfig, pruneAttempts, readCheck, slugOf, unknownSettings, writeCheck } from './checkFile' export { hashProblems, tourProblems, validateCheck } from './validate' export { checkState, driftOf, isDone, isPassed, localStatus, needed, nextQuestion, refreshInputs, ruleText, stamp, stateOf, stateWords, summarize } from './state' diff --git a/cli/understanding/init.ts b/cli/understanding/init.ts index 7895282..ab015d75 100644 --- a/cli/understanding/init.ts +++ b/cli/understanding/init.ts @@ -3,6 +3,7 @@ import fs from 'node:fs' import path from 'node:path' import { DIR, SELF, SKILL_DIR } from './constants' import { gitOk } from './git' +import { SKILL_FILES } from './skillFiles' /** * What `init` makes sure of: the check files collapsed in merge request diffs (GitLab reads `gitlab-generated`, GitHub @@ -65,38 +66,45 @@ export const foldDiffs = (repo: string): string[] => initRepo(repo, { only: '.gi export const FOLD_TEXT = 'also folds check files in diffs (.gitattributes)' -/** What installSkill copies: the skill's folder (SKILL.md, scripts/questions.mjs) and this CLI file. */ -export interface SkillSource { dir: string; cli: string } +/** What installSkill writes: the skill's files (`files`: path in the skill → text) and this CLI file (`cli`). */ +export interface SkillSource { files: Readonly<Record<string, string>>; cli: string } /** - * Where this copy of the CLI finds the skill to install: beside it, as it ships. The built cli/understanding.mjs (in - * the extension and in its repository) has it at ../skills/understanding-check; the skill's own copy - * (<skill>/scripts/understanding.mjs) is inside it. A copy elsewhere (a CI download) has none: undefined. + * The skill to install: the one beside this copy of the CLI, as it ships (the built cli/understanding.mjs has it at + * ../skills/understanding-check; the skill's own copy, <skill>/scripts/understanding.mjs, is inside it), else the copy + * this file carries (SKILL_FILES: a CLI copied elsewhere, e.g. tools/understanding.mjs, still installs it). */ -export function skillSource(cli: string = SELF): SkillSource | undefined { +export function skillSource(cli: string = SELF): SkillSource { const here = path.dirname(cli) - const dir = [path.join(here, '../skills/understanding-check'), path.join(here, '..')].find((d) => fs.existsSync(path.join(d, 'SKILL.md')) && fs.existsSync(path.join(d, 'scripts/questions.mjs'))) - return dir ? { dir, cli } : undefined + const names = Object.keys(SKILL_FILES) + const dir = cli ? [path.join(here, '../skills/understanding-check'), path.join(here, '..')].find((d) => names.every((f) => fs.existsSync(path.join(d, f)))) : undefined + const files = dir ? Object.fromEntries(names.map((f) => [f, fs.readFileSync(path.join(dir, f), 'utf8')])) : SKILL_FILES + return { files, cli } } /** The repository has the skill (`init` put it there). */ export const hasSkill = (repo: string): boolean => fs.existsSync(path.join(repo, SKILL_DIR, 'SKILL.md')) -/** The CLI the repository has committed already (e.g. tools/understanding.mjs), outside the skill's folder. */ -const committedCli = (repo: string): string | undefined => (gitOk(repo, ['ls-files', '--', ':(glob)**/understanding.mjs']) ?? '').split('\n').find((f) => f && !f.startsWith(`${SKILL_DIR}/`)) +/** + * The repository's own copy of the CLI outside the skill's folder (e.g. tools/understanding.mjs): committed, or this + * very file when it runs from inside the repository (copied in, not committed yet). + */ +function repoCli(repo: string, cli: string): string | undefined { + const committed = (gitOk(repo, ['ls-files', '--', ':(glob)**/understanding.mjs']) ?? '').split('\n').find((f) => f && !f.startsWith(`${SKILL_DIR}/`)) + if (committed || !cli) return committed + const rel = path.relative(fs.realpathSync(repo), fs.realpathSync(cli)).split(path.sep).join('/') + return !rel.startsWith('..') && !path.isAbsolute(rel) && !rel.startsWith(`${SKILL_DIR}/`) ? rel : undefined +} /** * Puts the skill in the repository (SKILL_DIR: SKILL.md and its script), so anyone running Claude Code there can type - * /understanding-check, and the CLI beside it unless the repository has a copy committed already (the script finds - * that one). `from`: what to copy (skillSource: what ships beside this file). Written when missing or different; - * returns the files written, or undefined when there is no skill to copy. + * /understanding-check, and the CLI beside it unless the repository has a copy of its own (the script finds that + * one). `from`: what to write (skillSource). Written when missing or different; returns the files written. */ -export function installSkill(repo: string, from: SkillSource | undefined = skillSource()): string[] | undefined { - if (!from) return undefined - const want: [string, string][] = [['SKILL.md', path.join(from.dir, 'SKILL.md')], ['scripts/questions.mjs', path.join(from.dir, 'scripts/questions.mjs')]] - if (!committedCli(repo)) want.push(['scripts/understanding.mjs', from.cli]) +export function installSkill(repo: string, from: SkillSource = skillSource()): string[] { + const want: [string, Buffer][] = Object.entries(from.files).map(([rel, text]) => [rel, Buffer.from(text)]) + if (from.cli && !repoCli(repo, from.cli)) want.push(['scripts/understanding.mjs', fs.readFileSync(from.cli)]) const out: string[] = [] - for (const [rel, from] of want) { + for (const [rel, text] of want) { const to = path.join(repo, SKILL_DIR, rel) - const text = fs.readFileSync(from) let have: Buffer | undefined try { have = fs.readFileSync(to) } catch { /* new */ } if (have && have.equals(text)) continue diff --git a/cli/understanding/main.ts b/cli/understanding/main.ts index b93a47f..3541f63 100644 --- a/cli/understanding/main.ts +++ b/cli/understanding/main.ts @@ -135,13 +135,12 @@ function initCommand({ repo, print }: CommandArgs): number { const changed = initRepo(repo) const skill = installSkill(repo) const files = [...new Set(changed.map((l) => l.split(':')[0]))] - const skillLine = skill?.length ? [`the skill (${SKILL_DIR}: ${skill.map((f) => path.basename(f)).join(', ')})`] : [] - print(changed.length || skill?.length ? `Added: ${[...changed, ...skillLine].join('; ')}.` : 'Already set up.') - if (files.length || skill?.length) { - print(`Commit them: git add ${[...files, ...(skill?.length ? [SKILL_DIR] : [])].join(' ')} && git commit -m "Add understanding check setup"`) + const skillLine = skill.length ? [`the skill (${SKILL_DIR}: ${skill.map((f) => path.basename(f)).join(', ')})`] : [] + print(changed.length || skill.length ? `Added: ${[...changed, ...skillLine].join('; ')}.` : 'Already set up.') + if (files.length || skill.length) { + print(`Commit them: git add ${[...files, ...(skill.length ? [SKILL_DIR] : [])].join(' ')} && git commit -m "Add understanding check setup"`) } - if (skill?.length || (skill && hasSkill(repo))) print('Without VS Code: type /understanding-check in Claude Code.') - else if (!skill) print(withoutVsCode(hasSkill(repo))) + print(withoutVsCode(hasSkill(repo))) // The CI job goes in the last stage with needs: [] (in .pre, a missing check would skip lint and tests). print(`CI recipe: ${CI_URL}`) return 0 @@ -229,7 +228,7 @@ function nextCommand({ repo, env, print }: CommandArgs): number { if (!branch) return 1 const c = branch.check const q = nextQuestion(c) - if (!q) { print(progressLine(c, loadConfig(repo), repo, env)); return 0 } + if (!q) { print(grownLine(repo, env) ?? progressLine(c, loadConfig(repo), repo, env)); return 0 } const i = c.questions.indexOf(q) const tries = (q.attempts ?? []).filter((a: Attempt) => a.verdict).length const where = q.target === 'file' ? q.file : `${q.file}:${q.start}-${q.end}` @@ -279,6 +278,14 @@ function branchCheck(repo: string, env: NodeJS.ProcessEnv, print: Print): { file } } +/** Every question done but the change grew past the check (status's drift): its words, the same as `status`. */ +function grownLine(repo: string, env: NodeJS.ProcessEnv): string | undefined { + const s = localStatus(repo, { env }) + if (s.state.phase !== 'drift') return undefined + const w = stateWords(s.state, s) + return `${w.title} · ${w.line}` +} + /** One grade in a line: "✓ q1 pass: Right: …", with the hint and a concern when there are. */ function gradeLine(q: Question, a: Attempt): string { const hint = a.hint ? `\n Hint: ${a.hint}` : '' diff --git a/cli/understanding/mrComment.ts b/cli/understanding/mrComment.ts index 2ff626a..d5154fc 100644 --- a/cli/understanding/mrComment.ts +++ b/cli/understanding/mrComment.ts @@ -227,8 +227,8 @@ function itemLine(it: ReviewItem, url: string | undefined, { check, link, change } /** - * "All answers", collapsed: each question once, with the answer that counts (a pass's, or a restatement's, marked); - * an explained one only says so (its point is in "Worth discussing"). + * "All answers", collapsed: each question once, with the answer that counts (a pass's or a restatement's; how many + * tries it took is never said); an explained one only says so (its point is in "Worth discussing"). */ function answersSection(check: Check, sum: Summary, link: (q: Spot) => string | undefined): string[] { const all: string[] = [] @@ -238,7 +238,7 @@ function answersSection(check: Check, sum: Summary, link: (q: Spot) => string | const title = `**${questionText(q.text)}** · ${refText(q, link)}${q.suspect ? ' · may be a bug' : ''}` if (s === STATE.restated) { const a = as.findLast((x) => x.verdict === STATE.restated) - all.push('', `${title}${byText(a, check)} · restated after an explanation`, ...answer(a)) + all.push('', `${title}${byText(a, check)}`, ...answer(a)) } else if (s === STATE.explained) { all.push('', `${title} · explained`) } else { diff --git a/cli/understanding/phases.ts b/cli/understanding/phases.ts index 22581a3..47be34a 100644 --- a/cli/understanding/phases.ts +++ b/cli/understanding/phases.ts @@ -1,7 +1,7 @@ // The check's phases (checkState's one word) and what every surface says in each: the status bar, the Check view and // `status` (`words`), and for the phases CI reports from a check file, the CI log and the merge request comment (`ci`). // One entry per phase, so adding a phase means filling in its entry here; the types make the table exhaustive. -import { minutesFor, sizeText } from './size' +import { minutesFor, sizeText, topUpQuestions } from './size' import type { BranchStatus, CheckPosition, Drift, Phase, Summary, Words } from './types' /** Every phase, in the order a branch usually goes through them. */ @@ -61,12 +61,16 @@ export const PHASE: { [P in Phase]: PhaseEntry<P> } = { }), }, drift: { - words: (state) => ({ - tone: 'warn', - bar: `Needs top-up: +${state.grew} lines`, - title: `Needs top-up: +${state.grew} lines`, - line: state.commitFirst ? 'Commit, then add 1–2 questions about the new lines.' : 'Add 1–2 questions about the new lines.', - }), + // New work, not a fault: the status bar counts the questions; the line count is in the title (the tooltip). + words: (state) => { + const n = questionsText(topUpQuestions(state.grew ?? 0)) + return { + tone: 'todo', + bar: `Understanding: +${n}`, + title: `Your change grew by ${state.grew} code lines`, + line: `${state.commitFirst ? 'Commit, then add' : 'Add'} ${n} about the new lines.`, + } + }, ci: { log: (w) => `Your change grew by ${w.drift.lines} code lines since the check${w.drift.approx ? ' (compared by size: the branch was rewritten)' : ''}. Run "Check my understanding" again: it adds 1–2 questions about the new part only. Then commit and push.`, comment: (w) => `**Understanding check: needs a top-up.** The change grew by ${w.drift.lines} code lines since the questions; 1–2 questions about the new part are missing.`, @@ -110,6 +114,9 @@ export const PHASE: { [P in Phase]: PhaseEntry<P> } = { }, } +/** "1 question", "2 questions". */ +const questionsText = (n: number): string => `${n} question${n === 1 ? '' : 's'}` + /** How much room is left before a top-up is needed (the CI log's "done" line). */ export const roomText = (drift: Drift, maxDrift: number): string => (drift.lines ? ` ${drift.lines} code line${drift.lines === 1 ? '' : 's'} since the check (top-up at ${maxDrift}).` : '') diff --git a/cli/understanding/size.ts b/cli/understanding/size.ts index c459f18..a382833 100644 --- a/cli/understanding/size.ts +++ b/cli/understanding/size.ts @@ -22,6 +22,9 @@ export function questionsFor(lines: number, cfg: Config = DEFAULTS): number { return Math.max(1, Math.min(max, Math.max(min, n))) } +/** How many questions a top-up adds for `lines` new code lines: 1, or 2 when the change grew a lot. */ +export const topUpQuestions = (lines: number): number => (lines < 80 ? 1 : 2) + /** * What kind of change it is, for its size rules: `docs` (only documentation), `removal` (only removes code), else * `code`. `st`: codeStat's shape (`docsOnly`, `added`, `removed`). diff --git a/cli/understanding/skillFiles.ts b/cli/understanding/skillFiles.ts new file mode 100644 index 0000000..b097b3c --- /dev/null +++ b/cli/understanding/skillFiles.ts @@ -0,0 +1,6 @@ +// Generated from skills/understanding-check by test/cli/golden-skill-copy.test.mjs (UPDATE_GOLDENS=1 npm run +// test:goldens): edit the skill, not this file. What `init` installs when no skill ships beside the CLI. +export const SKILL_FILES: Readonly<Record<string, string>> = { + "SKILL.md": "---\nname: understanding-check\ndescription: >-\n An UNDERSTANDING CHECK for the current branch: 1-5 short questions (by the change's size) about the author's own\n change (how a part behaves, why it is built this way, how it fails, an edge case), each anchored on the changed\n lines it is about, written to understanding/<branch>.json with the bundled script. The author answers them next to\n the code (Code Notes in VS Code), or right here in the chat, one at a time, graded with the same rules. Use when\n asked to \"check my understanding\" (/understanding-check), write understanding-check questions, or top up a check\n after the change grew.\n---\n\n# Understanding check: writing the questions\n\n**Goal.** The author is about to merge a change, often written with an AI agent. Ask the few questions a sharp\nsenior colleague would ask in review to find out whether the author really owns this code. Answering takes about\n5 minutes in total, 1-3 sentences each. It must feel like help, not an exam: a good question makes the author look\nat something they would otherwise have skipped.\n\nWrite only through `scripts/questions.mjs` (never write the JSON by hand); read every line it prints and fix each\n`PROBLEM`. Run it by its full path, one command per call: no shell variables, no `&&` or pipes.\n\n## Procedure\n\n1. `questions.mjs start` (or `start --top-up` when asked to top up an existing check). It prints the change with the\n new file's line numbers and how many questions to write (1 for a small change, up to 5 for a big one; write that\n many). `NOTHING` or `UNCOMMITTED`: write nothing, reply with that one line. `REMOVED ONLY`: the change only removes\n code; write ONE evidence question (`--evidence --kind change`) from the `EVIDENCE` the script prints (a search of\n the repository for the removed names): \"Nothing calls `refundReport` any more (search: 0 hits) — right?\", for the\n author to confirm or correct in one sentence. Check the hits with Grep first and keep the numbers true; put it on\n the lines where code was removed or on code that used it (any file). `RENAMED ONLY`: one question about what the move changes, `--whole-file`. `DOCS ONLY`: one question about what a reader now sees or\n understands differently; never why a word was chosen.\n2. Read the diff. Open the changed files (Read) where the diff alone doesn't show what the code does, and the code\n that calls the changed functions. Find the places that matter most: where the behaviour is decided, where it can\n fail, what is new.\n3. Pick the questions (rules below), then add each one:\n `questions.mjs add --kind failure --file api/orders.js --lines 12-18 --text \"…?\"`\n Use `--whole-file` (no lines) only for a question about the design of a whole file.\n When the answer depends on code the change did NOT touch (the loop that retries a failing handler, the\n constraint that rejects a duplicate, the caller that ignores an error), add it: `--also worker/queue.js:84-96`\n (up to 3, comma-separated). It is shown beside the question, so the author knows where to look.\n Name code in the question by what it is (\"the catch block in `tick()`\", \"the INSERT\"), never by line number, and\n link those words to their lines: `--links \"the catch block in tick()@worker/queue.js:88-96\"` (up to 3,\n `;`-separated; the phrase exactly as in the text). The author clicks the phrase to see the code. A phrase linked\n to an `--also` range is all the pointer that range needs.\n When the honest answer to a question is \"this is a bug\" (the code really does lose data, double-charge, race,\n skip a check), still ask it neutrally and add `--suspect`: once they have answered, the author is offered a fix. Only\n when you read the code and are confident; never as a trick.\n4. `questions.mjs finish`. It writes `understanding/<branch>.json`. Reply with one line per question, nothing more.\n\n## What makes a good question\n\n- **About this change, answerable from it.** It names the function, value or case it is about, so it makes sense\n on its own next to its lines. The answer is in the code (and its obvious callers), not in someone's head.\n- **Answerable in 1-3 sentences.** One question, one point, under ~140 characters. \"…, and could the customer …?\"\n is two questions, and \"what happens to the row, the counters and the job?\" is three: keep the one that matters.\n- **About code, never comments.** Ask about what the code does, not what a comment claims (\"finance audits this\n monthly\" is not a requirement). Lines that hold only comments or blank lines can't carry a question.\n- **Mixed kinds** (from 3 questions on): at least one `failure` or `edge`, and one `why` when the change makes a design choice (it\n almost always does: a limit, an order of operations, where something is stored, what is retried):\n - `failure`: \"What happens to the order when the payment client times out after the order was stored?\"\n - `edge`: \"What does `applyDiscount` return when the same code is applied twice to one cart?\"\n - `why`: \"Why does the worker re-read the order before charging instead of using the job's copy?\"\n - `how`: \"How does a settled order stop a second charge for the same job?\" (behaviour, not a line-by-line read)\n - `change`: \"Which callers of `insertOrder` get a different result after this change?\"\n- **Anchored on the lines that answer it** (`--lines`): the decision, the check, the catch, not the whole function.\n At most ~15 lines when you can.\n- **At most one computed value.** \"What does `rule59` return for a 200-cent item at qty 61?\" is a calculator drill\n unless it says why it matters: ask it once at most, and say what is at stake (\"… is that a valid price?\"). Prefer why,\n failure and edge questions.\n- **Riskiest first.** Before anything clever, ask about what can hurt most: who may call a new endpoint or run a new\n action (an auth gate, a token that may be unset), money moving, data leaving (a field now returned to a client),\n data lost. When the change has such a surface, one question is about it, and it comes first.\n- **Prefer what the author is most likely to have skipped**: error paths, retries, ordering between two writes,\n what is shared between requests, limits, what happens with empty or duplicate input, a default that changed.\n\n## Never\n\n- Trivia or reading aloud: \"What does line 12 do?\", \"What is the name of …?\", \"Which file defines …?\".\n- Questions whose answer is in a comment right next to the lines, or in the question itself.\n- Yes/no questions, opinion questions (\"Is this a good design?\"), or questions about code the change didn't touch.\n- Hints of the answer in the question. Answers are never stored: the grader judges each answer against the code.\n\n## The tour (when asked to write it)\n\nAfter the questions, the author can walk a short **journey of the change** and click their way to each answer\ninstead of reading the code cold. Write it only when the request asks for the tour.\n\n1. `questions.mjs tour` (`tour --top-up` when topping up). It prints the questions, the changed lines and the exact\n `journey.py` path and `--dir` to use (always that `--dir`; the slug is `tour`).\n2. Write the journey with `journey.py` (the code-journey skill's script; `journey.py help <command>` gives its rules):\n - **As many steps as the change needs** (`tour` prints the range: 2-3 for a few lines, documentation or a removal,\n up to 6-10 for a big change) through the changed code AND the unchanged code it depends on (the caller, the table, the retry loop), in\n the order a request or the data actually flows. Every step is about the change or what it relies on: no step\n that only says something stayed the same. A top-up adds 1-4 steps after the last one, about the new part\n only; never change the earlier steps.\n - **A change that only removes code** (`REMOVAL`): steps on code that is still there: where the removed code used\n to be called (or that nothing calls it: the search), and why removing it is safe. One that mostly removes code:\n what was removed, what used it before, and the few lines that changed besides. Not a tour of the code around it.\n - **Documentation** (`DOCS`): steps on the existing code the edited text describes, never on the text. When it\n describes no code, write no tour: `questions.mjs tour-finish --none`, and you are done.\n - `new <repo> tour \"<question>\" \"<title>\" --dir … < summary`: the question one developer would ask about this\n change (\"What happens when a shopper asks for a refund?\"), a short title that names the change (\"Refunds by\n staff\", \"Dropping refundReport\"), a 2-sentence summary.\n - A small map: 1-3 `system` boxes (reuse the names of the repo's journeys in `journeys/` when there are some), a\n `function` box per function a step is in (`range` prints its lines), and an `edge` for each hop between them.\n - Each `step`: a title that is one fact (≤ 70 chars), a lead of one plain sentence (≤ 25 words), lines that make\n the title true (≤ 15). Details and refs only where they save a click.\n - **Each question's answer must be visible by its step**: a step up to it shows the question's lines (or the code\n it depends on). Order the steps so the questions come along the way, not all at the end.\n - **Show the way to an answer, never the answer**: the steps state what the code does, one fact each; the author\n puts two facts together to answer. A title or lead that says what a question asks for (\"so a failed refund is\n not listed\", \"so a restart loses the job\") gives it away: cut that clause.\n - Then 1-3 `link`s per step (a phrase of the lead to the lines doing it). No `value`, no `scene`.\n - `check <repo> tour quiet --dir …`: fix every PROBLEM and WARNING it prints, except its step count (6-14 is for a\n journey of the repository; `tour` prints the tour's own).\n3. `questions.mjs tour-finish --steps q1=3,q2=5,…`: for each question, the step after which its answer can be seen.\n Reply with the step titles, one per line.\n\n## Top-up\n\n`start --top-up` lists the NEW LINES of the branch's own change since the questions were written (code merged in\nfrom the target branch is never among them). Add 1-2 questions about those lines only (the earlier questions and\nanswers stay), then `finish`.\n\n## Without VS Code: answering in the chat\n\nWhen the person asks you directly (`/understanding-check`, \"check my understanding\") and no prompt told you exactly\nwhich script commands to run, do the whole check here in the chat. It is help, not an exam: be the friendly senior\ncolleague. `S` below is this skill's `scripts/questions.mjs`; `S cli …` runs the check's CLI (the repository's copy,\ne.g. `tools/understanding.mjs`, or the one beside this script), so the file ends up exactly as VS Code writes it.\n\n1. `S cli status`. No check yet: write the questions (Procedure above; no tour). A check that needs a top-up: top up.\n `No check needed`: say so in one line and stop.\n2. `S cli next` prints the question to answer next (its id, where it is, the text). Ask it in the chat, ONE question\n at a time, with where to look (file and lines). Then wait for the answer. Never hint at the answer before they try.\n3. Grade their answer with the same rules as everywhere: `S cli grade --question q1 --answer '<their words>' --prompt`\n prints the grader's instructions for it. Follow them (read the code they name) and write the JSON reply they ask\n for. Then record it: `S cli grade --question q1 --answer '<their words>' --reply '<the JSON>'`. Quote both with\n single quotes (a `'` inside becomes `'\\''`); never change their words.\n4. Tell them what the recorded line says, in your own short words: \"Right\" and why; \"Not quite\" with the hint (they\n try once more); after a second miss, the explanation, and offer to let them say it back in one sentence (optional:\n record it the same way, it counts as passed). A `Concern:` is about the code: tell them, and when they want a\n reviewer to see it, `S cli flag --question q1`.\n5. Repeat from 2 until `S cli next` (or the recorded line) says done. Then offer to commit: `S cli commit` commits the\n check file only (the repository's first check also adds the `.gitattributes` line that folds check files in diffs)\n and pushes. Say what it printed in one line.\n", + "scripts/questions.mjs": "#!/usr/bin/env node\n// Writes the questions of an understanding check, one validated question at a time (SKILL.md says how to use it).\n// questions.mjs start [--base <ref>] [--branch <name> --head <sha>] [--top-up] [--replace] the change, with new-file\n// line numbers; starts a draft. --branch/--head: the branch and commit the check is for, whatever is\n// checked out by the time each command runs (the person may switch meanwhile)\n// questions.mjs add --kind <kind> --file <path> (--lines A-B | --whole-file) --text \"<question>\" [--also <path>:A-B,…] [--suspect]\n// [--links \"<phrase>@<path>:A-B;…\"] phrases of the text that become links to those lines\n// questions.mjs list | remove <qN> | finish\n// questions.mjs tour [--top-up] then journey.py (its path and --dir are printed) writes the tour\n// questions.mjs tour-finish --steps q1=3,q2=5,… checks the tour and puts it, and each question's step, in the file\n// questions.mjs tour-finish --none documentation that describes no code: no tour\n// questions.mjs cli <command> … the CLI found below (next, grade, flag, commit, status, …):\n// answering in a chat without VS Code\n// The draft lives in the git folder (never committed); `finish` writes understanding/<branch>.json; the tour is\n// written with the code-journey skill's journey.py into a staging folder there, then embedded as `journey`.\n// It uses understanding.mjs (the CLI): UNDERSTANDING_CLI, else the copy that ships beside this skill, else the one the\n// repository has (e.g. tools/understanding.mjs, the copy its CI runs).\nimport fs from 'node:fs'\nimport path from 'node:path'\nimport { execFileSync } from 'node:child_process'\nimport { fileURLToPath, pathToFileURL } from 'node:url'\n\nconst here = path.dirname(fileURLToPath(import.meta.url))\nconst inRepo = () => { try { const top = execFileSync('git', ['rev-parse', '--show-toplevel'], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim(); const f = execFileSync('git', ['ls-files', '--', ':(glob)**/understanding.mjs'], { cwd: top, encoding: 'utf8' }).split('\\n').find(Boolean); return f && path.join(top, f) } catch { return undefined } }\nconst cliPath = [process.env.UNDERSTANDING_CLI, path.join(here, 'understanding.mjs'), path.join(here, '../../../cli/understanding.mjs')].find((p) => p && fs.existsSync(p)) ?? inRepo()\nif (!cliPath) { console.log('PROBLEM: understanding.mjs not found (set UNDERSTANDING_CLI to its path)'); process.exit(2) }\nconst U = await import(pathToFileURL(cliPath).href)\n\n// The CLI itself, for answering in a chat (SKILL.md, \"Without VS Code\"): one path to know.\nif (process.argv[2] === 'cli') {\n const code = await U.main(process.argv.slice(3))\n // A long output (the grader's instructions) is written out before the exit.\n await new Promise((resolve) => process.stdout.write('', resolve))\n process.exit(code)\n}\n\nconst cwd = process.cwd()\nconst repo = U.repoRoot(cwd) ?? cwd\nconst draftPath = process.env.UNDERSTANDING_DRAFT || path.join(path.resolve(repo, execFileSync('git', ['rev-parse', '--git-dir'], { cwd: repo, encoding: 'utf8' }).trim()), 'understanding-draft.json')\nconst cfg = U.loadConfig(repo)\nconst o = U.parseArgs(process.argv.slice(2))\nconst cmd = o._[0]\nconst say = (s) => console.log(s)\nconst fail = (s) => { say(`PROBLEM: ${s}`); process.exit(1) }\nconst loadDraft = () => { try { return JSON.parse(fs.readFileSync(draftPath, 'utf8')) } catch { fail('no draft: run `questions.mjs start` first') } }\nconst saveDraft = (d) => fs.writeFileSync(draftPath, JSON.stringify(d, null, 2) + '\\n')\nconst MAX_DIFF_LINES = 1500\nconst gitDir = () => path.resolve(repo, execFileSync('git', ['rev-parse', '--git-dir'], { cwd: repo, encoding: 'utf8' }).trim())\n/** Where journey.py writes the tour (slug TOUR) before tour-finish embeds it. */\nconst stageDir = () => process.env.UNDERSTANDING_TOUR_DIR || path.join(gitDir(), 'understanding-tour')\nconst TOUR = 'tour'\n/** The code-journey skill's journey.py: JOURNEY_PY, the repository's copy, else the one shipped beside this skill. */\nconst journeyPy = () => [process.env.JOURNEY_PY, path.join(repo, '.claude/skills/code-journey/scripts/journey.py'), path.join(here, '../../code-journey/scripts/journey.py')].find((p) => p && fs.existsSync(p))\n/** Steps a top-up adds to a tour (a new tour: U.tourSize, by the change's kind and size). */\nconst TOPUP_STEPS = [1, 4]\nconst sizeOf = (check) => (check.diffStat ? U.linesOf(check.diffStat) : Infinity)\nconst fmtRange = (rs) => rs.map(([a, b]) => (a === b ? a : `${a}-${b}`)).join(', ')\nconst qLine = (q) => `${q.id} (${q.kind}) ${q.file}${q.target ? '' : `:${q.start}-${q.end}`}${q.also?.length ? ` (also ${q.also.map((x) => `${x.file}:${x.start}-${x.end}`).join(', ')})` : ''}${q.step ? ` · step ${q.step}` : ''}: ${q.text}`\n\n/**\n * Where `branch`'s check file is: in the working tree while it is checked out, else in the git-ignored cache the\n * extension puts back in place when the branch returns (so a branch switch never writes into another branch).\n */\nfunction checkPath(branch) {\n if (U.currentBranch(repo) === branch) return path.join(repo, U.fileFor(branch))\n const cache = path.join(repo, U.cachedFor(branch))\n fs.mkdirSync(path.dirname(cache), { recursive: true })\n const ignore = path.join(repo, '.code-notes/.cache/.gitignore')\n if (!fs.existsSync(ignore)) fs.writeFileSync(ignore, '*\\n')\n return cache\n}\n/** A file's lines at the draft's commit (the working tree may be another branch by now). */\nfunction linesAt(head, file) {\n try { return U.git(repo, ['show', `${head}:${file}`]).split('\\n') } catch { return undefined }\n}\n\n/** How many questions a change gets (U.questionsForChange: one for docs or a removal); a top-up U.topUpQuestions (an older CLI copy: its rule). */\nfunction wanted(st, lines, topUp) {\n return topUp ? (U.topUpQuestions?.(lines) ?? (lines < 80 ? 1 : 2)) : U.questionsForChange(st, cfg)\n}\n\nif (cmd === 'start') {\n const branch = typeof o.branch === 'string' ? o.branch : U.currentBranch(repo)\n const head = U.git(repo, ['rev-parse', typeof o.head === 'string' ? `${o.head}^{commit}` : 'HEAD']).trim()\n const rel = U.fileFor(branch)\n const at = checkPath(branch)\n // Its check: here, in the cache, else as committed on that branch.\n const committed = () => { try { return JSON.parse(U.git(repo, ['show', `${head}:${rel}`])) } catch { return undefined } }\n const existing = fs.existsSync(at) ? U.readCheck(at) : U.currentBranch(repo) === branch ? undefined : committed()\n const topUp = !!o['top-up']\n if (topUp && !existing) fail(`--top-up: ${rel} doesn't exist yet; run start without it`)\n if (!topUp && existing && !o.replace) fail(`${rel} exists already. Use --top-up to add questions about what changed since, or --replace to start over (its answers are lost)`)\n const baseRef = typeof o.base === 'string' ? o.base : U.defaultBase(repo)\n const mb = baseRef && U.mergeBase(repo, baseRef, head)\n if (!mb) fail('no base to compare with: pass --base <branch or commit>')\n // Stacked on a branch whose check is committed here: only what came after that check's code.\n const stack = U.stackBase(repo, mb, head, rel)\n const base = stack?.base ?? mb\n if (stack) say(`STACKED: on ${stack.branch}, whose check covers its own code; this change starts after it.`)\n // Committed code only: the questions record the commit they were written for (uncommitted lines would count as drift).\n // Code lines only: blank and comment-only lines don't count, nor the config's exempt files.\n // Always the branch's OWN change (from today's merge base): code that came in from the target branch is never asked.\n let files = U.numstat(repo, base, head)\n // Uncommitted lines: only those of this branch's working tree (another branch may be checked out by now).\n const loose = U.currentBranch(repo) === branch ? U.linesOf(U.codeStat(repo, head, undefined, cfg.exempt)) : 0\n const st = U.codeStat(repo, base, head, cfg.exempt)\n let lines = U.linesOf(st), ranges\n if (topUp) {\n // Only what the branch's own change gained since the questions (freshLines); else, when the questions' commits are\n // gone, what changed since the questions' commit, or the whole change.\n const fresh = U.freshLines(repo, existing, base, head, cfg.exempt)\n ?? (U.hasCommit(repo, existing.head) ? U.codeLines(repo, existing.head, head, cfg.exempt) : U.codeLines(repo, base, head, cfg.exempt))\n lines = fresh.length\n ranges = U.rangesOf(fresh)\n files = files.filter((f) => ranges.has(f.file))\n }\n if (!topUp && !lines && loose && U.currentBranch(repo) === branch) { say(`UNCOMMITTED: this change is not committed yet (${loose} code lines). Ask the person to commit it first. Write nothing.`); process.exit(0) }\n const renamedOnly = !topUp && !lines && st.renamed?.length > 0\n if ((!lines && !renamedOnly) || (topUp && !ranges.size)) { say(`NOTHING: no code lines changed${topUp ? ' since the questions were written' : ''} (only comments, blank lines or exempt files). Write nothing.`); process.exit(0) }\n const diff = U.diffText(repo, base, head, files, cfg.exempt)\n ranges ??= U.changedRanges(diff, { codeOnly: true })\n // Removed code is part of the change: a question may sit where code was removed, and when the change only removes\n // code, also where the removed code was used (any file).\n for (const [f, rs] of U.removalPoints(diff)) ranges.set(f, [...(ranges.get(f) ?? []), ...rs])\n // A moved file: a question about the move itself (--whole-file), never about the content it kept.\n if (renamedOnly) for (const r of st.renamed) if (!ranges.has(r.to)) ranges.set(r.to, [])\n const removedOnly = !topUp && U.changeKind(st) === 'removal'\n // Only documentation changed: one question about what a reader now sees or understands differently.\n const docsOnly = !topUp && U.changeKind(st) === 'docs'\n const want = wanted(st, lines, topUp)\n const stat = (x) => ({ files: x.files, added: x.added, removed: x.removed })\n const fmt = (rs) => rs.map(([a, b]) => (a === b ? a : `${a}-${b}`)).join(', ')\n saveDraft({ branch, base, head, mode: topUp ? 'top-up' : 'new', want, diffStat: stat(st), ranges: Object.fromEntries(ranges), ...(removedOnly ? { removedOnly } : {}), ...(docsOnly ? { docsOnly } : {}), questions: [] })\n say(topUp ? `TOP-UP: branch ${branch} · ${lines} new code lines since the questions were written` : `CHANGE: branch ${branch} · ${st.files} files · ${lines} code lines (+${st.added} −${st.removed})`)\n if (loose) say(`NOTE: ${loose} uncommitted code lines are not included.`)\n if (docsOnly) say('DOCS ONLY: only documentation changed. Write ONE question about what a reader now sees, can do or understands differently (never why a word was chosen, never about unchanged text). \"It is just wording\" is a full answer.')\n if (renamedOnly) say(`RENAMED ONLY: ${st.renamed.map((r) => `${r.from} → ${r.to}`).join(', ')}, 0 lines changed. Ask only what the move changes (how a tool, an import or a convention treats the new name or place), with --whole-file; never about the content it kept.`)\n if (removedOnly) {\n // The evidence: where the removed names still appear (a search of the repository at the change's commit).\n const found = U.searchNames(repo, head, U.removedNames(U.codeLines(repo, base, head, cfg.exempt)))\n say(`REMOVED ONLY: this change only removes code. Write ONE evidence question (--evidence --kind change): what a search found about the removed code, for the author to confirm or correct in one sentence. Put it on the lines where code was removed (${[...ranges].map(([f, rs]) => `${f}:${fmt(rs)}`).join(' · ') || 'none left: the files are gone'}), or on code that used what was removed (any file).`)\n if (found.length) say(`EVIDENCE (search at ${head.slice(0, 7)}): ${found.map(U.evidenceText).join(' · ')}`)\n const none = found.find((e) => !e.hits.length), some = found.find((e) => e.hits.length)\n say(` e.g. ${none ? `\"Nothing calls ${none.name} any more (search: 0 hits) — right?\"` : some ? `\"${some.name} is still named in ${some.hits[0].file} (search: ${some.hits.length} hit${some.hits.length === 1 ? '' : 's'}) — what happens there now?\"` : '\"Nothing used what this removes (search: 0 hits) — right?\"'} Check the hits yourself (Grep) before you write it; keep the numbers true.`)\n }\n if (topUp) say(`NEW LINES (ask only about these): ${[...ranges].map(([f, rs]) => `${f}:${fmt(rs)}`).join(' · ')}`)\n say(`WRITE: ${want} question${want === 1 ? '' : 's'}${topUp ? ' about these new lines only' : ''}, about code lines (never comments or blank lines), then \\`finish\\`. Files: ${files.filter((f) => U.counted(f.file, cfg.exempt)).map((f) => `${f.file} (+${f.added} −${f.removed})`).join(', ')}`)\n const numbered = U.numberDiff(diff).split('\\n')\n say('')\n say(numbered.slice(0, MAX_DIFF_LINES).join('\\n'))\n if (numbered.length > MAX_DIFF_LINES) say(`\\n… the diff goes on (${numbered.length - MAX_DIFF_LINES} more lines): read the remaining files with Read; line numbers are the files' own.`)\n process.exit(0)\n}\n\nif (cmd === 'add') {\n const d = loadDraft()\n const kind = String(o.kind ?? '')\n const file = String(o.file ?? '').replace(/^\\.\\//, '')\n const text = String(o.text ?? '').replace(/\\s+/g, ' ').trim()\n if (!U.KINDS.includes(kind)) fail(`--kind must be one of ${U.KINDS.join(', ')}`)\n if (!file) fail('--file is missing')\n // The file as committed in the change (whatever is checked out now).\n const lines = linesAt(d.head, file)\n if (!lines) fail(`${file} doesn't exist`)\n // A removal-only change: also the code that used what was removed (anywhere).\n const ranges = d.ranges[file] ?? (d.removedOnly ? [] : undefined)\n if (!ranges) fail(`${file} is not part of this ${d.mode === 'top-up' ? 'new change' : 'change'}: ask about the changed files (${Object.keys(d.ranges).join(', ')})`)\n if (text.length < 25) fail('--text is too short: ask a real question about this change')\n if (text.length > U.MAX_TEXT) fail(`--text is ${text.length} characters: at most ${U.MAX_TEXT}. One question, plainly`)\n if (!text.endsWith('?')) fail('--text must be one question, ending with \"?\"')\n if ((text.match(/\\?/g) ?? []).length > 1) fail('--text asks more than one question: ask one')\n if (/(,?\\s+(and|or)( also| then)?|;|\\s+as well as)\\s+(how|what|why|when|where|which|who|whose|does|do|did|is|are|was|were|can|could|would|should|will|has|have|if)\\b/i.test(text)) fail('--text asks two things (\"…, and could …\"): keep the one that matters')\n // \"what happens to X, Y and Z\": three things to cover is three questions.\n if (/,\\s+(?!(?:what|how|why|when|where|which|who|does|do|is|are|can|could|would|should|will|if|so|but|or)\\b)[^,?]{1,60},?\\s+(and|or)\\s+[^?]+\\?$/i.test(text)) fail('--text asks about a list of things (\"X, Y and Z\"): ask about the one that matters')\n // \"What does f(x) return for 200 at qty 61?\": one computed value per check at most.\n const computed = (t) => /^(what|which)\\b[^?]*\\b(return|returns|price|cost|total|result|value)\\b[^?]*\\d/i.test(t) || /^(what|which)\\b[^?]*\\d[^?]*\\breturns?\\b/i.test(t)\n if (computed(text) && d.questions.some((x) => computed(x.text))) fail('a second \"what does it return for <numbers>\" question: one is enough; ask why, or what can go wrong, instead')\n if (/\\bline\\s+\\d+/i.test(text)) fail('--text names a line number: name the function, value or case instead (the question is shown on its lines)')\n if (/^(what does|what is)\\b/i.test(text) && kind === 'how' && text.length < 60) say('WARNING: \"what does X do\" questions are trivia; ask how it behaves in a case, or why')\n const q = { id: '', kind, text, file }\n if (o['whole-file']) q.target = 'file'\n else {\n const m = /^(\\d+)(?:-(\\d+))?$/.exec(String(o.lines ?? ''))\n if (!m) fail('--lines A-B (or --whole-file for a question about the design of the whole file)')\n q.start = Number(m[1]); q.end = Number(m[2] ?? m[1])\n if (q.end < q.start) fail('--lines: the end is before the start')\n if (q.end > lines.length) fail(`--lines: ${file} has ${lines.length} lines`)\n if (q.end - q.start > 40) fail('--lines: more than 40 lines; point at the lines that matter (the question shows on them)')\n const cs = {}\n if (!lines.slice(q.start - 1, q.end).map((l) => U.isCode(l, file, cs)).some(Boolean)) fail(`--lines ${q.start}-${q.end} hold only comments or blank lines: ask about code`)\n const near = (d.removedOnly && !d.ranges[file]) || ranges.some(([a, b]) => q.start <= b + 5 && q.end >= a - 5)\n if (!near) fail(`--lines ${q.start}-${q.end} are not near a changed code line of ${file} (changed: ${ranges.map(([a, b]) => (a === b ? a : `${a}-${b}`)).join(', ')})`)\n q.anchor = U.compactOf(lines, q.start, q.end)\n }\n // The honest answer is \"this is a bug\": once answered, the author is offered a fix, a TODO or a flag.\n if (o.suspect) q.suspect = true\n // A removal: the author confirms or corrects what a search found (the grader passes a true one-sentence answer).\n if (o.evidence) { if (!d.removedOnly) fail('--evidence is for a change that only removes code'); q.evidence = true }\n // Unchanged code the answer depends on (a caller, a retry loop, a constraint): shown beside the question.\n if (typeof o.also === 'string' && o.also.trim()) {\n q.also = []\n for (const part of o.also.split(',').map((x) => x.trim()).filter(Boolean)) {\n const m = /^(.+):(\\d+)(?:-(\\d+))?$/.exec(part)\n if (!m) fail(`--also ${part}: write it as path:A-B`)\n const f = m[1].replace(/^\\.\\//, ''), a = Number(m[2]), b = Number(m[3] ?? m[2])\n const fl = path.isAbsolute(f) || f.split(/[\\\\/]/).includes('..') ? undefined : linesAt(d.head, f)\n if (!fl) fail(`--also: ${f} doesn't exist`)\n if (b < a || b > fl.length) fail(`--also ${part}: ${f} has ${fl.length} lines`)\n if (b - a > 40) fail(`--also ${part}: more than 40 lines; point at the lines that matter`)\n if (f === q.file && q.start && a <= q.end && q.start <= b) fail(`--also ${part}: overlaps the question's own lines`)\n q.also.push({ file: f, start: a, end: b, anchor: U.compactOf(fl, a, b) })\n }\n if (q.also.length > 3) fail('--also: at most 3 places')\n }\n // Code links: words of the question shown as a clickable phrase that lights those lines (never line numbers).\n if (typeof o.links === 'string' && o.links.trim()) {\n const raw = []\n for (const part of o.links.split(';').map((x) => x.trim()).filter(Boolean)) {\n const m = /^(.+)@([^@]+):(\\d+)(?:-(\\d+))?$/.exec(part)\n if (!m) fail(`--links ${part}: write it as \"phrase@path:A-B\"`)\n const phrase = m[1].trim()\n if (!text.includes(phrase)) fail(`--links: \"${phrase}\" is not in the question's text (exactly as written)`)\n raw.push({ phrase, file: m[2].replace(/^\\.\\//, ''), start: Number(m[3]), end: Number(m[4] ?? m[3]) })\n }\n if (raw.length > 3) fail('--links: at most 3')\n const ok = U.codeLinksIn(repo, raw, (f) => { const l = linesAt(d.head, f); if (!l) throw new Error(f); return l })\n const bad = raw.filter((l) => !ok.some((x) => x.phrase === l.phrase))\n if (bad.length) fail(`--links: ${bad.map((l) => `${l.file}:${l.start}-${l.end}`).join(', ')} is not a range of a file in the repository`)\n q.links = ok\n }\n if (d.questions.some((x) => x.file === q.file && x.start && q.start && x.start <= q.end && q.start <= x.end)) say('WARNING: another question is on overlapping lines: make sure it asks something different')\n d.questions.push(q)\n saveDraft(d)\n say(`added #${d.questions.length} (${kind}) ${file}${q.target ? '' : `:${q.start}-${q.end}`}${q.also ? ` (also ${q.also.map((x) => `${x.file}:${x.start}-${x.end}`).join(', ')})` : ''}${q.links ? ` · ${q.links.length} link${q.links.length === 1 ? '' : 's'}` : ''} · ${d.questions.length} of ${d.want}`)\n if (!q.target) say(` ${lines[q.start - 1].trim().slice(0, 100)}${q.end > q.start ? `\\n … ${lines[q.end - 1].trim().slice(0, 100)}` : ''}`)\n process.exit(0)\n}\n\nif (cmd === 'list') {\n const d = loadDraft()\n d.questions.forEach((q, i) => say(`#${i + 1} ${q.kind} ${q.file}${q.target ? '' : `:${q.start}-${q.end}`}: ${q.text}`))\n say(`${d.questions.length} of ${d.want}`)\n process.exit(0)\n}\n\nif (cmd === 'remove') {\n const d = loadDraft()\n const i = Number(String(o._[1] ?? '').replace(/^#/, '')) - 1\n if (!(i >= 0 && i < d.questions.length)) fail('remove <number> (as `list` shows it)')\n d.questions.splice(i, 1)\n saveDraft(d)\n say(`removed; ${d.questions.length} of ${d.want}`)\n process.exit(0)\n}\n\nif (cmd === 'finish') {\n const d = loadDraft()\n const n = d.questions.length\n // The count follows the change's size: exactly `want` for a small change (1 or 2), 3 up to the config's max above.\n const [lo, hi] = d.mode === 'top-up' ? [1, 2] : d.want < 3 ? [d.want, d.want] : [Math.min(3, d.want), Math.max(d.want, cfg.questions.max)]\n if (n < lo || n > hi) fail(`${n} question${n === 1 ? '' : 's'}: write ${lo === hi ? lo : `${lo}-${hi}`} for this change${lo === hi ? '' : ` (${d.want} suggested)`}`)\n const kinds = new Set(d.questions.map((q) => q.kind))\n if (d.mode !== 'top-up' && n >= 3 && kinds.size < 2) fail('all questions are of one kind: mix them (how, why, failure, edge, change)')\n if (d.mode !== 'top-up' && n >= 3 && ![...kinds].some((k) => ['why', 'failure', 'edge'].includes(k))) fail('ask at least one why, failure or edge question')\n if (d.removedOnly && !d.questions.some((q) => q.evidence)) fail('this change only removes code: its question is an evidence question (add it with --evidence; see EVIDENCE)')\n const rel = U.fileFor(d.branch)\n // Its branch was switched away from meanwhile: into the cache, never into the branch checked out now.\n const abs = checkPath(d.branch)\n const model = process.env.UNDERSTANDING_MODEL_LABEL || process.env.UNDERSTANDING_MODEL || undefined\n let check\n if (d.mode === 'top-up') {\n check = fs.existsSync(abs) ? U.readCheck(abs) : JSON.parse(U.git(repo, ['show', `${d.head}:${rel}`]))\n let k = Math.max(0, ...check.questions.map((q) => Number(q.id.slice(1)) || 0))\n const round = Math.max(1, ...check.questions.map((q) => q.round ?? 1)) + 1\n for (const q of d.questions) check.questions.push({ ...q, id: `q${++k}`, round })\n check.base = d.base\n check.head = d.head\n check.diffStat = d.diffStat\n check.updatedAt = new Date().toISOString()\n } else {\n const who = U.gitIdentity(repo)\n check = { version: 1, branch: d.branch, base: d.base, head: d.head, diffStat: d.diffStat, ...(who ? { answeredBy: who } : {}), ...(model ? { model } : {}), createdAt: new Date().toISOString(),\n questions: d.questions.map((q, i) => ({ ...q, id: `q${i + 1}`, ...(d.docsOnly ? { docs: true } : {}) })) }\n }\n // Its files are checked in the working tree only while its branch is checked out (they were read at its commit).\n const errs = U.validateCheck(check, U.currentBranch(repo) === d.branch ? { repo } : {})\n if (errs.length) fail(`the file would not be valid: ${errs.join('; ')}`)\n U.writeCheck(abs, U.stamp(check, cfg))\n fs.rmSync(draftPath, { force: true })\n say(`WROTE ${path.relative(repo, abs) === rel ? rel : `${rel} (kept for ${d.branch}: it is not checked out)`}: ${check.questions.length} questions${d.mode === 'top-up' ? ` (${n} new)` : ''}. Done: reply with one line per new question.`)\n process.exit(0)\n}\n\nif (cmd === 'tour') {\n const branch = typeof o.branch === 'string' ? o.branch : U.currentBranch(repo)\n const rel = U.fileFor(branch)\n const abs = checkPath(branch)\n if (!fs.existsSync(abs)) fail(`${rel} doesn't exist: write the questions first (start, add, finish)`)\n const check = U.readCheck(abs)\n const J = journeyPy()\n if (!J) fail('journey.py (the code-journey skill) was not found: set JOURNEY_PY to its path')\n const stage = stageDir()\n fs.rmSync(stage, { recursive: true, force: true })\n fs.mkdirSync(stage, { recursive: true })\n const topUp = !!o['top-up'] && !!check.journey\n // The branch it is for: tour-finish writes there even after a branch switch.\n fs.writeFileSync(path.join(stage, 'meta.json'), JSON.stringify({ branch }) + '\\n')\n if (topUp) fs.writeFileSync(path.join(stage, `${TOUR}.json`), JSON.stringify({ ...check.journey, id: TOUR }, null, 2) + '\\n')\n // What the tour must show: the change's lines (a top-up: only what is new since the tour), by file.\n const base = check.base && U.hasCommit(repo, check.base) ? check.base : U.mergeBase(repo, U.defaultBase(repo) ?? 'HEAD', check.head)\n let ranges\n if (topUp) {\n const known = new Set(check.journey.steps.map((s) => s.file))\n const fresh = check.journey.commit && U.hasCommit(repo, check.journey.commit) ? U.codeLines(repo, check.journey.commit, check.head, cfg.exempt) : []\n ranges = U.rangesOf(fresh)\n if (!ranges.size) for (const q of check.questions.filter((x) => !x.step)) if (!known.has(q.file)) ranges.set(q.file, [[q.start ?? 1, q.end ?? 1]])\n } else ranges = base ? U.changedRanges(U.diffText(repo, base, check.head, U.numstat(repo, base, check.head), cfg.exempt), { codeOnly: true }) : new Map()\n const want = topUp ? check.questions.filter((q) => !q.step) : check.questions\n const kind = U.checkKind(check)\n const [lo, hi] = topUp ? TOPUP_STEPS : U.tourSize(kind, sizeOf(check))\n const n0 = topUp ? check.journey.steps.length : 0\n const st = check.diffStat\n // A removal: where the removed code was used; never steps on code that is gone.\n if (!topUp && kind === 'removal' && base) for (const [f, rs] of U.removalPoints(U.diffText(repo, base, check.head, U.numstat(repo, base, check.head), cfg.exempt))) ranges.set(f, [...(ranges.get(f) ?? []), ...rs])\n say(topUp ? `TOUR TOP-UP: the tour of ${branch} has ${n0} steps; add ${lo}-${hi} after step ${n0}, through the new part only` : `TOUR: a journey of this change (${branch}, ${st ? `+${st.added} −${st.removed} ${kind === 'docs' ? 'lines' : 'code lines'}` : 'its size unknown'}): ${lo}-${hi} steps${kind === 'code' ? ' through the changed code and the unchanged code it depends on, in the order a request or the data flows' : ''}. Its title names the change (\"Dropping refundReport\", \"Bumping the version\"), not the area`)\n if (!topUp && kind === 'docs') say(`DOCS: the change edits documentation. Steps on the EXISTING code the edited text describes (what a reader can now find or do there), never on the text itself. When the text describes no code, write no tour: run questions.mjs tour-finish --none`)\n else if (!topUp && kind === 'removal') say('REMOVAL: this change only removes code. Steps on code that is still there: where the removed code used to be called (or show that nothing calls it: the search), and why removing it is safe (what takes its place, what never reached it); nothing else')\n // A change that mostly removes code: the tour shows what went and why that is safe, not the code around it.\n else if (!topUp && st && st.removed > 2 * st.added) say('REMOVAL: this change mostly removes code. Steps: what was removed (on the lines where it was), what used it before (or that nothing does now: say how you checked), and the one or two lines that changed besides; nothing else')\n else if (!topUp && sizeOf(check) < 10) say('SMALL: a few lines changed. Steps around the changed lines: what calls them and what they change; nothing else')\n // journey.py check wants 6-14 steps for a journey of the repository; a tour has its own count.\n const steps = `(its \"N steps (want 6-14 …)\" line doesn't apply: this tour has ${n0 + lo}-${n0 + hi})`\n say(`JOURNEY: ${J} <command> <repo> ${TOUR} … --dir ${stage} (repo: ${repo}; always --dir; slug ${TOUR})`)\n if (topUp) { say('STEPS SO FAR (keep them as they are):'); check.journey.steps.forEach((s, i) => say(` ${i + 1}. ${s.title} (${s.file}:${s.range.start}-${s.range.end})`)) }\n say(`QUESTIONS ${topUp ? 'that need a step' : '(each needs the step after which its answer is visible)'}:`)\n for (const q of want) say(` ${qLine(q)}`)\n if (ranges.size) say(`CHANGED: ${[...ranges].map(([f, rs]) => `${f}:${fmtRange(rs)}`).join(' · ')}`)\n say(`THEN: ${J} check <repo> ${TOUR} quiet --dir ${stage}; fix every PROBLEM ${steps}; then questions.mjs tour-finish --steps ${want.map((q) => `${q.id}=<n>`).join(',')}`)\n process.exit(0)\n}\n\nif (cmd === 'tour-finish') {\n let meta = {}\n try { meta = JSON.parse(fs.readFileSync(path.join(stageDir(), 'meta.json'), 'utf8')) } catch { /* none: this branch */ }\n const branch = meta.branch || U.currentBranch(repo)\n const rel = U.fileFor(branch)\n // Its branch was switched away from meanwhile: the extension keeps its check in .code-notes/.cache/checks.\n const abs = [path.join(repo, rel), path.join(repo, '.code-notes/.cache/checks', `${U.slugOf(branch)}.json`)].find((f) => fs.existsSync(f))\n if (!abs) fail(`${rel} doesn't exist`)\n // Documentation that describes no code: no tour, on purpose (the check says so; nothing offers to write one).\n if (o.none) {\n const check = U.readCheck(abs)\n if (U.checkKind(check) !== 'docs' || check.journey) fail('--none is only for a change to documentation that describes no code')\n check.noTour = true\n U.writeCheck(abs, check)\n fs.rmSync(stageDir(), { recursive: true, force: true })\n say(`WROTE ${rel}: no tour (the edited text describes no code). Done: reply \"No tour: the text describes no code.\"`)\n process.exit(0)\n }\n const staged = path.join(stageDir(), `${TOUR}.json`)\n let j\n try { j = JSON.parse(fs.readFileSync(staged, 'utf8')) } catch { fail(`no tour in ${stageDir()}: run \\`questions.mjs tour\\`, then journey.py new … ${TOUR} --dir …`) }\n const J = journeyPy()\n if (J) {\n let out = '', code = 0\n try { out = execFileSync('python3', [J, 'check', repo, TOUR, 'quiet', '--dir', stageDir()], { cwd: repo, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }) } catch (e) { code = e.status ?? 1; out = `${e.stdout ?? ''}${e.stderr ?? ''}` }\n // The count is checked below, by the change's size: journey.py's own count (6-14, for a journey of the repository)\n // doesn't apply to a tour. Any other problem does.\n const problems = out.split('\\n').filter((l) => /^PROBLEM:/.test(l) && !/^PROBLEM: \\d+ steps \\(want \\d+-\\d+/.test(l))\n if (code && (problems.length || !/^PROBLEM:/m.test(out))) { say(out.trim()); fail('journey.py check found problems: fix them, then tour-finish again') }\n }\n // The file as it is now: answers given while the tour was written are kept.\n const check = U.readCheck(abs)\n const before = check.journey\n const n0 = before ? before.steps.length : 0\n const steps = Array.isArray(j.steps) ? j.steps : []\n const added = steps.length - n0\n if (before) {\n // A top-up only appends: the steps the questions already point at stay where they are.\n const same = before.steps.every((s, i) => steps[i] && steps[i].id === s.id && steps[i].title === s.title && steps[i].file === s.file)\n if (!same) fail(`the first ${n0} steps changed: a top-up only adds steps after step ${n0} (journey.py restore, or rmstep the new ones and add them again)`)\n if (added < TOPUP_STEPS[0] || added > TOPUP_STEPS[1]) fail(`${added} new steps: add ${TOPUP_STEPS[0]}-${TOPUP_STEPS[1]} after step ${n0}`)\n } else { const [lo, hi] = U.tourSize(U.checkKind(check), sizeOf(check)); if (steps.length < lo || steps.length > hi) fail(`${steps.length} steps: a tour of this change has ${lo}-${hi} (its size)`) }\n // No animations in a check's tour (time and cost): dropped if any.\n for (const s of steps) delete s.scene\n const given = new Map()\n for (const part of String(o.steps ?? '').split(',').map((x) => x.trim()).filter(Boolean)) {\n const m = /^(q\\d+)\\s*=\\s*(\\d+)$/.exec(part)\n if (!m) fail(`--steps ${part}: write it as q1=3`)\n if (!check.questions.some((q) => q.id === m[1])) fail(`--steps: there is no question ${m[1]}`)\n given.set(m[1], Number(m[2]))\n }\n const problems = []\n for (const q of check.questions) {\n const n = given.get(q.id) ?? q.step\n if (!n) { problems.push(`${q.id} has no step: --steps ${q.id}=<n>`); continue }\n if (n < 1 || n > steps.length) { problems.push(`${q.id}=${n}: the tour has ${steps.length} steps`); continue }\n if (before && given.has(q.id) && q.step && q.step !== n) { problems.push(`${q.id} is at step ${q.step} already: keep it`); continue }\n // Its answer must be visible by then: a step up to n shows the question's file (or the code it also depends on).\n // Documentation and a removal: the tour shows the code the text describes, or where the removed code was used.\n const files = new Set([q.file, ...(q.also ?? []).map((x) => x.file)])\n if (!q.docs && !q.evidence && !steps.slice(0, n).some((s) => files.has(s.file))) problems.push(`${q.id}=${n}: no step up to ${n} is in ${[...files].join(' or ')}; give a later step, or add a step there`)\n q.step = n\n }\n if (problems.length) fail(problems.join('; '))\n const model = process.env.UNDERSTANDING_MODEL_LABEL || process.env.UNDERSTANDING_MODEL || undefined\n delete check.noTour\n check.journey = { ...j, id: TOUR, commit: check.head, ...(before?.createdAt ? { createdAt: before.createdAt, updatedAt: new Date().toISOString() } : { createdAt: new Date().toISOString() }), ...(model ? { model } : {}) }\n // Its files are checked in the working tree only while its branch is checked out (they were read at its commit).\n const errs = U.validateCheck(check, U.currentBranch(repo) === branch ? { repo } : {})\n if (errs.length) fail(`the file would not be valid: ${errs.join('; ')}`)\n U.writeCheck(abs, U.stamp(check, cfg))\n fs.rmSync(stageDir(), { recursive: true, force: true })\n say(`WROTE the tour into ${rel}: ${steps.length} steps${before ? ` (${added} new)` : ''}; ${check.questions.map((q) => `${q.id} after step ${q.step}`).join(', ')}. Done: reply with the step titles, one per line.`)\n process.exit(0)\n}\n\nsay(`questions.mjs start [--base <ref>] [--top-up] [--replace] | add --kind <${U.KINDS.join('|')}> --file <path> (--lines A-B | --whole-file) --text \"<question>\" [--also <path>:A-B,…] [--suspect] [--evidence] | list | remove <n> | finish | tour [--top-up] | tour-finish (--steps q1=<n>,… | --none) | cli <command> …`)\nprocess.exit(cmd ? 2 : 0)\n", +} diff --git a/cli/understanding/state.ts b/cli/understanding/state.ts index 8445707..e8f0287 100644 --- a/cli/understanding/state.ts +++ b/cli/understanding/state.ts @@ -24,6 +24,8 @@ export interface StateFacts { stashed?: string /** The caller judged the change too small to check (no check needed). */ small?: boolean + /** On the default branch: an edit there is no change to check (no nudge to commit, no background run). */ + onBase?: boolean changed?: number change?: CodeStat errors?: string[] @@ -167,7 +169,7 @@ function readOrExplain(repo: string, rel: string): ReadResult { /** * Where the check stands, in one word: what the status bar, the Check view, `status` and CI all show. - * nothing no check needed (`exemptOnly`: only exempt files changed) + * nothing no check needed (`exemptOnly`: only exempt files changed; the default branch without a check file) * none no check yet (`changed` lines) * invalid the file can't be read or is not valid (`why`) * drift the change grew past maxDrift by `grew` lines (`commitFirst`: only uncommitted lines put it over) @@ -189,11 +191,14 @@ export function checkState(st: StateFacts | undefined, cfg: Config = DEFAULTS): return { ...base, phase: s.done < s.total ? 'answering' : s.met ? 'done' : 'short' } } -/** No check file in the tree: in a stash, no check needed (nothing changed), or none yet (with its size). */ +/** + * No check file in the tree: in a stash, no check needed (nothing changed, or the default branch: a scratch edit + * there is not a change to check), or none yet (with its size). + */ function noFileState(st: StateFacts, cfg: Config): CheckPosition { if (st.stashed) return { phase: 'stashed', stash: st.stashed } const renamed = !!st.change?.renamed?.length - if (st.small || (!st.changed && !renamed)) return { phase: 'nothing', changed: st.changed ?? 0, exemptOnly: !!st.change?.exemptOnly } + if (st.small || st.onBase || (!st.changed && !renamed)) return { phase: 'nothing', changed: st.changed ?? 0, exemptOnly: !!st.change?.exemptOnly } const kind = changeKind(st.change) return { phase: 'none', diff --git a/skills/understanding-check/scripts/questions.mjs b/skills/understanding-check/scripts/questions.mjs index b3fb936..321f8f6 100755 --- a/skills/understanding-check/scripts/questions.mjs +++ b/skills/understanding-check/scripts/questions.mjs @@ -74,9 +74,9 @@ function linesAt(head, file) { try { return U.git(repo, ['show', `${head}:${file}`]).split('\n') } catch { return undefined } } -/** How many questions a change gets (U.questionsForChange: one for docs or a removal); a top-up 1, or 2 when it grew a lot. */ +/** How many questions a change gets (U.questionsForChange: one for docs or a removal); a top-up U.topUpQuestions (an older CLI copy: its rule). */ function wanted(st, lines, topUp) { - return topUp ? (lines < 80 ? 1 : 2) : U.questionsForChange(st, cfg) + return topUp ? (U.topUpQuestions?.(lines) ?? (lines < 80 ? 1 : 2)) : U.questionsForChange(st, cfg) } if (cmd === 'start') { diff --git a/test/cli/golden-skill-copy.test.mjs b/test/cli/golden-skill-copy.test.mjs new file mode 100644 index 0000000..8aa279c --- /dev/null +++ b/test/cli/golden-skill-copy.test.mjs @@ -0,0 +1,32 @@ +// The skill's copy inside the CLI (cli/understanding/skillFiles.ts): `init` installs it from a CLI copied away from +// skills/understanding-check (tools/understanding.mjs). Generated from the skill: UPDATE_GOLDENS=1 npm run +// test:goldens writes it, then npm run build bundles it. +import { test } from 'node:test' +import assert from 'node:assert/strict' +import fs from 'node:fs' +import path from 'node:path' +import { root } from './helpers/repos.mjs' + +const SKILL = path.join(root, 'skills/understanding-check') +const COPY = path.join(root, 'cli/understanding/skillFiles.ts') +/** The files `init` installs, relative to the skill's folder. */ +const FILES = ['SKILL.md', 'scripts/questions.mjs'] + +/** skillFiles.ts as the skill's files make it. */ +function generated() { + const entries = FILES.map((f) => ` ${JSON.stringify(f)}: ${JSON.stringify(fs.readFileSync(path.join(SKILL, f), 'utf8'))},`) + return [ + '// Generated from skills/understanding-check by test/cli/golden-skill-copy.test.mjs (UPDATE_GOLDENS=1 npm run', + '// test:goldens): edit the skill, not this file. What `init` installs when no skill ships beside the CLI.', + 'export const SKILL_FILES: Readonly<Record<string, string>> = {', + ...entries, + '}', + '', + ].join('\n') +} + +test('the CLI carries the skill as it is (cli/understanding/skillFiles.ts)', () => { + const want = generated() + if (process.env.UPDATE_GOLDENS) fs.writeFileSync(COPY, want) + assert.equal(fs.readFileSync(COPY, 'utf8'), want, 'the skill changed: UPDATE_GOLDENS=1 npm run test:goldens, then npm run build') +}) diff --git a/test/cli/understanding-init.test.mjs b/test/cli/understanding-init.test.mjs index 43cea3b..c2e0f31 100644 --- a/test/cli/understanding-init.test.mjs +++ b/test/cli/understanding-init.test.mjs @@ -1,11 +1,11 @@ // `understanding init` and the setup it writes: .gitattributes and .ignore lines, the skill (with the CLI beside it) -// in .claude/skills; what is missing, said by ci as a tip. +// in .claude/skills, also from a copied CLI; what is missing, said by ci as a tip; the setup never counts as the change. import { test } from 'node:test' import assert from 'node:assert/strict' import fs from 'node:fs' import path from 'node:path' -import { initRepo, installSkill, localStatus, main, own, setupMissing } from '../../cli/understanding.mjs' -import { commitAll, gitIn, ID, repo, root, sh, verdicts } from './helpers/repos.mjs' +import { CI_URL, initRepo, installSkill, localStatus, main, own, setupMissing, stateWords } from '../../cli/understanding.mjs' +import { checkedRepo, commitAll, gitIn, grow, ID, repo, root, sh, verdicts } from './helpers/repos.mjs' import { answerAll, ci, EXIT, run, writeQuestions } from './helpers/cli.mjs' const ATTRIBUTES = ['.gitattributes: understanding/*.json gitlab-generated linguist-generated', '.gitattributes: understanding/config.json -gitlab-generated -linguist-generated'] @@ -17,7 +17,8 @@ test('init: .gitattributes and .ignore, the skill; what to commit and the CI rec const r = await run(d, ['init']) assert.equal(r.out.split('\n')[0], 'Added: .gitattributes: understanding/*.json gitlab-generated linguist-generated; .gitattributes: understanding/config.json -gitlab-generated -linguist-generated; .ignore: understanding/; the skill (.claude/skills/understanding-check: SKILL.md, questions.mjs, understanding.mjs).') assert.equal(r.out.split('\n')[1], 'Commit them: git add .gitattributes .ignore .claude/skills/understanding-check && git commit -m "Add understanding check setup"') - assert.match(r.out, /CI recipe: https:\/\/github\.com\/.*#in-ci/) + // The docs' section: the README has no "In CI". + assert.match(r.out, /^CI recipe: https:\/\/github\.com\/[^ ]*\/docs\/understanding-check\.md#in-ci$/m) // The settings file is not collapsed: a change to them stays in sight. assert.equal(read(d, '.gitattributes'), '*.png binary\nunderstanding/*.json gitlab-generated linguist-generated\nunderstanding/config.json -gitlab-generated -linguist-generated\n') assert.equal(read(d, '.ignore'), 'understanding/\n') @@ -98,3 +99,51 @@ test('init in a repository that commits its own copy of the CLI (tools/understan assert.match(installedScript(e, 'start', '--base', 'main'), /^CHANGE: branch feat\/x/m) assert.match((await run(e, ['init'])).out, /^Already set up\./) }) + +test('the CI link goes to a section that exists: docs/understanding-check.md "## In CI"', () => { + const [, file, anchor] = CI_URL.match(/\/blob\/main\/(.+)#(.+)$/) + const headings = read(root, file).split('\n').filter((l) => /^#+ /.test(l)).map((l) => l.replace(/^#+ /, '').toLowerCase().replace(/[^a-z0-9 -]/g, '').replace(/ /g, '-')) + assert.ok(headings.includes(anchor), `${file} has no heading for #${anchor}`) +}) + +/** `d` with the CLI copied into tools/, as the docs suggest (the extension's bundle, nothing beside it). */ +const copyCli = (d) => { + fs.mkdirSync(path.join(d, 'tools')) + fs.copyFileSync(path.join(root, 'cli/understanding.mjs'), path.join(d, 'tools/understanding.mjs')) + return path.join(d, 'tools/understanding.mjs') +} + +test('init from a copied CLI (tools/understanding.mjs, not committed yet): installs the skill it carries, no second CLI copy', () => { + const d = repo() + const cli = copyCli(d) + const out = sh(d, 'node', [cli, 'init']) + const skill = path.join(d, '.claude/skills/understanding-check') + assert.equal(read(skill, 'SKILL.md'), read(root, 'skills/understanding-check/SKILL.md')) + assert.equal(read(skill, 'scripts/questions.mjs'), read(root, 'skills/understanding-check/scripts/questions.mjs')) + assert.ok(!fs.existsSync(path.join(skill, 'scripts/understanding.mjs')), 'the repository has its own copy') + assert.match(out, /^Added: .*; the skill \(\.claude\/skills\/understanding-check: SKILL\.md, questions\.mjs\)\.$/m) + assert.match(out, /^Without VS Code: type \/understanding-check in Claude Code\.$/m) + assert.doesNotMatch(out, /add the understanding-check skill/) + assert.match(out, /#in-ci$/m) +}) + +test('a committed CLI copy and the setup never count as the change: status and next agree the check is done', async () => { + const { d } = checkedRepo() + const cli = copyCli(d) + sh(d, 'node', [cli, 'init']) + commitAll(d, 'understanding check setup') + const st = localStatus(d) + assert.equal(own('tools/understanding.mjs'), true) + assert.equal(st.state.phase, 'done') + assert.equal(st.drift.lines, 0) + assert.match((await run(d, ['status'])).out, /· 0 lines since the check$/m) + assert.match((await run(d, ['next'])).out, /^✓ Done: 3 of 3 passed/) +}) + +test('next says a grown check like status does, not Done', async () => { + const { d } = checkedRepo() + grow(d, 45) + const words = stateWords(localStatus(d).state) + assert.equal((await run(d, ['next'])).out, `${words.title} · ${words.line}`) + assert.match((await run(d, ['status'])).out, /^Your change grew by 45 code lines · Add 1 question about the new lines\./) +}) diff --git a/test/cli/understanding-mr-comment.test.mjs b/test/cli/understanding-mr-comment.test.mjs index fe92915..2fdf716 100644 --- a/test/cli/understanding-mr-comment.test.mjs +++ b/test/cli/understanding-mr-comment.test.mjs @@ -114,7 +114,7 @@ test('answers, notes and concerns are literal text in the MR comment: no heading assert.doesNotMatch(body, /<img|<\/blockquote>|^#/m) }) -test('threads go on the nearest changed line of their hunk, one per question; the comment shows restatements and cuts long answers', () => { +test('threads go on the nearest changed line of their hunk, one per question; the comment shows a restatement as the answer, no history, and cuts long answers', () => { const diff = dedent` diff --git a/w.js b/w.js --- a/w.js @@ -149,7 +149,9 @@ test('threads go on the nearest changed line of their hunk, one per question; th const items = reviewItems(check, sum, { qa: true }) assert.deepEqual(items.map((it) => [it.id, !!it.flagged, !!it.d]), [['q1', true, true]], 'concern and "Worth discussing" of one question: one item') const body = commentBody(check, sum, 'head', undefined, { qa: true }) - assert.match(body, /\*\*What happens when sendMail throws\?\*\* · `w\.js:58-60` · restated after an explanation\n> It retries, then gives up with a log line\./) + // The restatement is shown as the answer; how many tries it took is not (the reviewer sees answers, not a record). + assert.match(body, /\*\*What happens when sendMail throws\?\*\* · `w\.js:58-60`\n> It retries, then gives up with a log line\./) + assert.doesNotMatch(body, /restated|after an explanation/) assert.doesNotMatch(body, /Check: |Worth discussing/) const quoted = body.split('\n').find((l) => l.startsWith('> word')) assert.ok(quoted.length < 345 && quoted.endsWith('… (full answer in the check file)'), quoted) diff --git a/test/cli/understanding-status.test.mjs b/test/cli/understanding-status.test.mjs index e2bc312..95036a8 100644 --- a/test/cli/understanding-status.test.mjs +++ b/test/cli/understanding-status.test.mjs @@ -6,7 +6,7 @@ import fs from 'node:fs' import os from 'node:os' import path from 'node:path' import { checkState, conflictOf, hashProblems, isDefaultBranch, localStatus, readCheck, stateWords, validateCheck, writeCheck } from '../../cli/understanding.mjs' -import { commitAll, gitIn, grow, ID, repo, root, sh, smallRepo, stashUntracked, verdicts } from './helpers/repos.mjs' +import { bareRemote, commitAll, gitIn, grow, ID, repo, root, sh, smallRepo, stashUntracked, verdicts } from './helpers/repos.mjs' import { answerAll, ci, EXIT, gitlabEnv, grade, run, SCRIPT, writeQuestions } from './helpers/cli.mjs' test('status: what to do next, locally', async () => { @@ -41,7 +41,8 @@ test('checkState: one word for where the check stands', () => { // Uncommitted lines past the limit: a top-up is due once they are committed. grow(d, 45, { commit: false, name: 'w' }) assert.deepEqual(checkState(localStatus(d)), { phase: 'drift', commitFirst: true, passed: 2, done: 3, total: 3, needed: 2, maxDrift: 40, grew: 45 }) - assert.equal(stateWords(localStatus(d).state).bar, 'Needs top-up: +45 lines') + // New work, not a fault: neutral, counted in questions; the lines are in the title (the status bar's tooltip). + assert.deepEqual(stateWords(localStatus(d).state), { tone: 'todo', bar: 'Understanding: +1 question', title: 'Your change grew by 45 code lines', line: 'Commit, then add 1 question about the new lines.', rule: 'Answer all 3 · 2 must pass' }) commitAll(d, 'more') assert.equal(checkState(localStatus(d)).commitFirst, false) }) @@ -53,6 +54,33 @@ test('the default branch: one line, no check here', () => { assert.deepEqual(stateWords(st.state, st), { tone: 'ok', bar: '', title: 'main: no check here', line: '', rule: '' }) }) +test('the default branch with a scratch edit or a staged rename: no check here, no nudge to commit or start', async () => { + const d = repo() + gitIn(d, 'checkout', '-q', 'main') + // Cloned: main is compared with origin/main, so an edit on main is a change of its own. + gitIn(d, 'remote', 'add', 'origin', bareRemote()) + gitIn(d, 'push', '-q', 'origin', 'main') + gitIn(d, 'remote', 'set-head', 'origin', 'main') + const quiet = async () => { + const st = localStatus(d) + assert.equal(st.state.phase, 'nothing') + assert.deepEqual(stateWords(st.state, st), { tone: 'ok', bar: '', title: 'main: no check here', line: '', rule: '' }) + const r = await run(d, ['status']) + assert.equal(r.out.split('\n')[0], 'main: no check here') + assert.doesNotMatch(r.out, /Check my understanding|Without VS Code|Commit/) + } + // Five lines deleted while walking a journey, not committed. + fs.writeFileSync(path.join(d, 'src/app.js'), 'export function main() {\n') + assert.ok(localStatus(d).changed > 0) + await quiet() + gitIn(d, 'checkout', '-q', '--', 'src/app.js') + gitIn(d, 'mv', 'src/app.js', 'src/main.js') + await quiet() + // Committed on main too: still no check there. + commitAll(d, 'rename') + await quiet() +}) + test('the default branch is one rule: origin/HEAD when known, else main/master, plus the branch compared with', () => { const d = repo() const onBase = (branch, base) => { diff --git a/test/goldens/check/helpers.json b/test/goldens/check/helpers.json index 933595f..3542c65 100644 --- a/test/goldens/check/helpers.json +++ b/test/goldens/check/helpers.json @@ -256,10 +256,10 @@ "done": 3 }, { - "tone": "warn", - "bar": "Needs top-up: +60 lines", - "title": "Needs top-up: +60 lines", - "line": "Add 1–2 questions about the new lines.", + "tone": "todo", + "bar": "Understanding: +1 question", + "title": "Your change grew by 60 code lines", + "line": "Add 1 question about the new lines.", "rule": "Answer all 3 · 2 must pass" } ], @@ -271,10 +271,10 @@ "commitFirst": true }, { - "tone": "warn", - "bar": "Needs top-up: +60 lines", - "title": "Needs top-up: +60 lines", - "line": "Commit, then add 1–2 questions about the new lines.", + "tone": "todo", + "bar": "Understanding: +1 question", + "title": "Your change grew by 60 code lines", + "line": "Commit, then add 1 question about the new lines.", "rule": "" } ], diff --git a/test/goldens/check/refunds.commands.json b/test/goldens/check/refunds.commands.json index 7a3bd2a..ec90521 100644 --- a/test/goldens/check/refunds.commands.json +++ b/test/goldens/check/refunds.commands.json @@ -383,7 +383,7 @@ " · q6 edge: What does the refund handler answer for an order that was never paid a…", " tip: run \"node understanding.mjs init\" once and commit .gitattributes and .ignore: check files then collapse in diffs." ], - "comment": "<!-- understanding-check -->\n**⚠ This merge request changes the understanding check's settings: questions {\"min\"\\:1,\"max\"\\:5} → {\"min\"\\:1,\"max\"\\:6}** (from the merge on; this merge request follows the current settings)\n\n**✓ Understanding check done** · 6 questions\n\n- ⚠ OPS\\_EMAIL is never set in the worker chart\\: the alerts go nowhere. · `worker/alerts.js:5-12`\n- 💬 **Worth discussing: idempotency** · `api/refunds.js:11-13` · The lookup runs before the lock, so both miss it; the second insert then fails on the UNIQUE key.\n- 💬 **Worth discussing: Why is the order row locked before the remaining refundable amount is checked?** · `api/refunds.js:18-20` · Right.\n- 💬 **Worth discussing: What does the refund handler answer for an order that was never paid at all?** · `api/refunds.js` · It answers 404\\\\\\: the order lookup finds nothing paid.\n\n<details><summary>All answers</summary>\n\n**If sendMail throws in refundNotice after the mail server already accepted the message, what happens to the job?** · `worker/notify.js:33-39`\n> tick() catches it and retries the job, so the mail may go out twice.\n\n**What happens when two refund requests with the same Idempotency-Key for one order arrive at the same time?** · `api/refunds.js:11-13` · restated after an explanation\n> Both miss the lookup; the unique key makes the second one fail.\n\n**Why is the order row locked before the remaining refundable amount is checked?** · `api/refunds.js:18-20`\n> So two refunds for one order run one after the other.\n\n**Where do the low-stock alerts end up once this runs in production?** · `worker/alerts.js:5-12`\n> They are emailed to OPS\\_EMAIL.\n\n**Why does every refunded unit go back into product stock, even when staff refund without a return?** · `api/restock.js:3-6`\n> Restock is called for every unit.\n\n**What does the refund handler answer for an order that was never paid at all?** · `api/refunds.js` · explained\n\n</details>", + "comment": "<!-- understanding-check -->\n**⚠ This merge request changes the understanding check's settings: questions {\"min\"\\:1,\"max\"\\:5} → {\"min\"\\:1,\"max\"\\:6}** (from the merge on; this merge request follows the current settings)\n\n**✓ Understanding check done** · 6 questions\n\n- ⚠ OPS\\_EMAIL is never set in the worker chart\\: the alerts go nowhere. · `worker/alerts.js:5-12`\n- 💬 **Worth discussing: idempotency** · `api/refunds.js:11-13` · The lookup runs before the lock, so both miss it; the second insert then fails on the UNIQUE key.\n- 💬 **Worth discussing: Why is the order row locked before the remaining refundable amount is checked?** · `api/refunds.js:18-20` · Right.\n- 💬 **Worth discussing: What does the refund handler answer for an order that was never paid at all?** · `api/refunds.js` · It answers 404\\\\\\: the order lookup finds nothing paid.\n\n<details><summary>All answers</summary>\n\n**If sendMail throws in refundNotice after the mail server already accepted the message, what happens to the job?** · `worker/notify.js:33-39`\n> tick() catches it and retries the job, so the mail may go out twice.\n\n**What happens when two refund requests with the same Idempotency-Key for one order arrive at the same time?** · `api/refunds.js:11-13`\n> Both miss the lookup; the unique key makes the second one fail.\n\n**Why is the order row locked before the remaining refundable amount is checked?** · `api/refunds.js:18-20`\n> So two refunds for one order run one after the other.\n\n**Where do the low-stock alerts end up once this runs in production?** · `worker/alerts.js:5-12`\n> They are emailed to OPS\\_EMAIL.\n\n**Why does every refunded unit go back into product stock, even when staff refund without a return?** · `api/restock.js:3-6`\n> Restock is called for every unit.\n\n**What does the refund handler answer for an order that was never paid at all?** · `api/refunds.js` · explained\n\n</details>", "mode": "required" }, "ci.advisory-other-branch": { diff --git a/test/goldens/check/states.json b/test/goldens/check/states.json index bf64938..21cf5b1 100644 --- a/test/goldens/check/states.json +++ b/test/goldens/check/states.json @@ -353,21 +353,21 @@ "phase": "drift", "commitFirst": true }, - "next": "Commit, then add 1–2 questions about the new lines." + "next": "Commit, then add 1 question about the new lines." }, "words": { - "tone": "warn", - "bar": "Needs top-up: +60 lines", - "title": "Needs top-up: +60 lines", - "line": "Commit, then add 1–2 questions about the new lines.", + "tone": "todo", + "bar": "Understanding: +1 question", + "title": "Your change grew by 60 code lines", + "line": "Commit, then add 1 question about the new lines.", "rule": "Answer all 3 · 2 must pass" }, "view": { "branch": "feat/x", "file": "understanding/feat-x.json", - "tone": "warn", - "title": "Needs top-up: +60 lines", - "line": "Commit, then add 1–2 questions about the new lines.", + "tone": "todo", + "title": "Your change grew by 60 code lines", + "line": "Commit, then add 1 question about the new lines.", "rows": [ { "id": "q1", @@ -406,8 +406,8 @@ } }, "bar": { - "text": "$(warning) Needs top-up: +60 lines", - "tip": "Needs top-up: +60 lines · Commit, then add 1–2 questions about the new lines.", + "text": "$(checklist) Understanding: +1 question", + "tip": "Your change grew by 60 code lines · Commit, then add 1 question about the new lines.", "warn": true }, "run": "scm" @@ -558,21 +558,21 @@ "phase": "drift", "commitFirst": false }, - "next": "Add 1–2 questions about the new lines." + "next": "Add 1 question about the new lines." }, "words": { - "tone": "warn", - "bar": "Needs top-up: +60 lines", - "title": "Needs top-up: +60 lines", - "line": "Add 1–2 questions about the new lines.", + "tone": "todo", + "bar": "Understanding: +1 question", + "title": "Your change grew by 60 code lines", + "line": "Add 1 question about the new lines.", "rule": "Answer all 3 · 2 must pass" }, "view": { "branch": "feat/x", "file": "understanding/feat-x.json", - "tone": "warn", - "title": "Needs top-up: +60 lines", - "line": "Add 1–2 questions about the new lines.", + "tone": "todo", + "title": "Your change grew by 60 code lines", + "line": "Add 1 question about the new lines.", "rows": [ { "id": "q1", @@ -611,8 +611,8 @@ } }, "bar": { - "text": "$(warning) Needs top-up: +60 lines", - "tip": "Needs top-up: +60 lines · Add 1–2 questions about the new lines.", + "text": "$(checklist) Understanding: +1 question", + "tip": "Your change grew by 60 code lines · Add 1 question about the new lines.", "warn": true }, "run": "topUp" From 955c7f47ad01338ff8e9485626edbe90bd5f47ca Mon Sep 17 00:00:00 2001 From: tomeyer97 <107920881+tomeyer97@users.noreply.github.com> Date: Thu, 26 Nov 2026 15:22:06 +0100 Subject: [PATCH 04/17] Saving a note never loses anyone's words: agent fields kept, replies kept when the file is mid-write, Undo never overwrites Slice: S04 Zeroshot-Run: 01a21811-3b88-7fb0-a36f-f45692ab826b --- src/core/format/noteModel.ts | 87 ++++++++++++--- src/core/format/schema/note.schema.json | 2 +- src/notes/brokenAt.ts | 37 ++++++- src/notes/reply.ts | 24 +++-- src/notes/store.ts | 77 +++++++++++--- test/golden-notes.test.ts | 33 ++++++ test/goldens/notes/merge.json | 122 +++++++++++++++++++++ test/goldens/notes/nested-extras.json | 86 +++++++++++++++ test/goldens/notes/notes.crafted.json | 19 +++- test/integration/main/notesStore.ts | 91 ++++++++++++++++ test/noteBrokenAt.test.ts | 40 +++++++ test/noteModel.test.ts | 42 ++++++++ test/noteStore.test.ts | 135 ++++++++++++++++++++++++ 13 files changed, 754 insertions(+), 41 deletions(-) create mode 100644 test/goldens/notes/nested-extras.json create mode 100644 test/integration/main/notesStore.ts create mode 100644 test/noteBrokenAt.test.ts create mode 100644 test/noteStore.test.ts diff --git a/src/core/format/noteModel.ts b/src/core/format/noteModel.ts index 7fecf90..d6f22d0 100644 --- a/src/core/format/noteModel.ts +++ b/src/core/format/noteModel.ts @@ -3,16 +3,24 @@ // Reading and writing the files themselves, and the README written for agents beside them, is notes/store.ts. import type { FullAnchor } from '../anchors/kinds' import { isAbsolutePath, slashPath } from '../paths' -import { opt, optString } from './read' +import { isObj, opt, optString } from './read' import { accepted, parseJson, Parsed, refused } from './result' import { VERSIONS } from './versions' export type Role = 'human' | 'agent' -export interface Message { author: string; body: string; at?: string; role?: Role } +export interface Message { + author: string; body: string; at?: string; role?: Role + /** Fields of the message this version doesn't know (an agent's attachments, ids): written back as they were. */ + extra?: Record<string, unknown> +} export const SEVERITIES = ['high', 'medium', 'low', 'nit'] as const export type Severity = typeof SEVERITIES[number] /** A status change: who resolved or reopened the note, and when (shown as a grey line in the thread). */ -export interface NoteEvent { type: 'resolved' | 'reopened'; by: string; role?: Role; at: string } +export interface NoteEvent { + type: 'resolved' | 'reopened'; by: string; role?: Role; at: string + /** Fields of the event this version doesn't know: written back as they were. */ + extra?: Record<string, unknown> +} /** A note's anchor: the full text it was written on (core/anchors/anchor.ts follows it), and where it was written. */ export interface NoteAnchor extends FullAnchor { commit?: string; branch?: string } @@ -43,18 +51,27 @@ export interface NoteData { events?: NoteEvent[] /** A note on a whole file or folder: no lines (range is 1-1 in memory and not written). */ target?: 'file' | 'folder' + /** Fields of the file's range and anchor this version doesn't know: written back inside them, after a move too. */ + rangeExtra?: Record<string, unknown> + anchorExtra?: Record<string, unknown> + /** Events this version can't read (another type, or malformed), each with its place among the file's events: + * written back where they were. */ + otherEvents?: OtherEvent[] /** Fields of the file this version doesn't know (a newer extension or an agent wrote them): written back as they were. */ extra?: Record<string, unknown> } +/** An event kept as it was in the file, `index` its place in the file's "events". */ +export interface OtherEvent { index: number; event: unknown } + /** * Every field of a note file this version knows: what `merge` does with it when the file changed on disk while we * changed the note (`ours`: ours if we changed it, else theirs; `theirs`: never changed here after it is made; * `append`: both sides' new entries), whether it is left out of the file when it is unset (`optional`), and whether it - * is about lines (`lines`: not written for a note on a whole file or folder). Checked against NoteData: a field added - * there must be added here. + * is about lines (`lines`: not written for a note on a whole file or folder), and whether it is written inside another + * field rather than as one of its own (`inside`). Checked against NoteData: a field added there must be added here. */ -type FieldRule = { merge: 'ours' | 'theirs' | 'append'; optional?: true; lines?: true } +type FieldRule = { merge: 'ours' | 'theirs' | 'append'; optional?: true; lines?: true; inside?: true } const NOTE_FIELDS = { id: { merge: 'theirs' }, file: { merge: 'ours' }, @@ -70,13 +87,17 @@ const NOTE_FIELDS = { severity: { merge: 'ours', optional: true }, events: { merge: 'append' }, target: { merge: 'ours', optional: true }, + // Never changed here: theirs. + rangeExtra: { merge: 'ours', optional: true, lines: true, inside: true }, + anchorExtra: { merge: 'ours', optional: true, lines: true, inside: true }, + otherEvents: { merge: 'ours', optional: true, inside: true }, } as const satisfies Record<Exclude<keyof NoteData, 'extra'>, FieldRule> type Field = keyof typeof NOTE_FIELDS const fieldsWhere = (rule: (r: FieldRule) => boolean) => (Object.keys(NOTE_FIELDS) as Field[]).filter((k) => rule(NOTE_FIELDS[k])) /** Fields this version knows: everything else in a note file is kept as is when the extension rewrites it. */ -const KNOWN = new Set<string>([...FILE_FIELDS, ...Object.keys(NOTE_FIELDS)]) +const KNOWN = new Set<string>([...FILE_FIELDS, ...fieldsWhere((r) => r.inside !== true)]) const OURS_IF_CHANGED = fieldsWhere((r) => r.merge === 'ours') /** Left out of the file when unset (after a merge too). */ const OPTIONAL = fieldsWhere((r) => r.optional === true) @@ -133,10 +154,25 @@ export function titleOf(raw: string): string | undefined { try { const b = JSON.parse(raw)?.messages?.[0]?.body; return typeof b === 'string' && b.trim() ? b : undefined } catch { return undefined } } -/** A note's file: its version first, then its fields in order, then the fields this version doesn't know. */ +/** A message or event as written: its fields, then the ones this version doesn't know. */ +const flat = <T extends { extra?: Record<string, unknown> }>({ extra, ...known }: T) => ({ ...known, ...extra }) + +/** The file's events: the ones this version reads, with the others put back where they were. */ +function eventsOf(known: NoteEvent[], others: OtherEvent[]): unknown[] { + const out: unknown[] = known.map(flat) + for (const o of [...others].sort((a, b) => a.index - b.index)) out.splice(Math.min(o.index, out.length), 0, o.event) + return out +} + +/** A note's file: its version first, then its fields in order, then the fields this version doesn't know (nested + * ones inside the object they came in). */ export function serialize(d: NoteData): string { - const { extra, ...rest } = d + const { extra, rangeExtra, anchorExtra, otherEvents, ...rest } = d const out: Record<string, unknown> = { version: VERSIONS.note, ...rest } + out.messages = d.messages.map(flat) + if (rangeExtra) out.range = { ...d.range, ...rangeExtra } + if (anchorExtra) out.anchor = { ...d.anchor, ...anchorExtra } + if (d.events?.length || otherEvents?.length) out.events = eventsOf(d.events ?? [], otherEvents ?? []) // A file or folder note has no lines: no range or anchor in its file. if (d.target) for (const k of LINE_FIELDS) delete out[k] return JSON.stringify({ ...out, ...extra }, null, 2) + '\n' @@ -174,6 +210,16 @@ function noteProblem(v: any): string | undefined { const readRole = (r: unknown) => opt(r === 'human' || r === 'agent', 'role', r as Role) +/** The keys of `v` (an object) other than `known`; empty when it is not an object. */ +const unknownKeys = (v: unknown, known: readonly string[]): Record<string, unknown> => + (isObj(v) ? Object.fromEntries(Object.entries(v).filter(([k]) => !known.includes(k))) : {}) +const MESSAGE_KEYS = ['author', 'role', 'body', 'at'] +const EVENT_KEYS = ['type', 'by', 'role', 'at'] +const RANGE_KEYS = ['start', 'end'] +const ANCHOR_KEYS = ['text', 'before', 'after', 'commit', 'branch'] +/** `{ [k]: extra }` when it has something in it. */ +const optExtra = <K extends string>(k: K, extra: Record<string, unknown>) => opt(Object.keys(extra).length, k, extra) + function readNoteAnchor(a: any): NoteAnchor { return { text: String(a?.text ?? ''), before: String(a?.before ?? ''), after: String(a?.after ?? ''), @@ -189,12 +235,21 @@ function readSelection(s: any): Pick<NoteData, 'selection'> { } /** A missing "at" stays missing: unread state does not depend on it, and inventing one would be a lie. */ -const readMessage = (m: any): Message => ({ author: String(m.author ?? 'unknown'), ...readRole(m.role), body: m.body, ...optString('at', m.at) }) +const readMessage = (m: any): Message => ({ + author: String(m.author ?? 'unknown'), ...readRole(m.role), body: m.body, ...optString('at', m.at), + ...optExtra('extra', unknownKeys(m, MESSAGE_KEYS)), +}) + +const isEvent = (e: any) => isObj(e) && (e.type === 'resolved' || e.type === 'reopened') && typeof e.at === 'string' -function readEvents(v: unknown): NoteEvent[] { - return (Array.isArray(v) ? v : []) - .filter((e: any) => e && (e.type === 'resolved' || e.type === 'reopened') && typeof e.at === 'string') - .map((e: any) => ({ type: e.type, by: String(e.by ?? 'unknown'), ...readRole(e.role), at: e.at })) +/** The events this version reads, and the others (kept as they are, with their place). */ +function readEvents(v: unknown): { events: NoteEvent[]; others: OtherEvent[] } { + const all: unknown[] = Array.isArray(v) ? v : [] + const events = all.filter(isEvent).map((e: any): NoteEvent => ({ + type: e.type, by: String(e.by ?? 'unknown'), ...readRole(e.role), at: e.at, ...optExtra('extra', unknownKeys(e, EVENT_KEYS)), + })) + const others = all.flatMap((event, index) => (isEvent(event) ? [] : [{ index, event }])) + return { events, others } } /** Checks a note file's content; returns the note or why it is not one. `id` is the file's name. */ @@ -210,7 +265,7 @@ export function parseNote(raw: string, id: string): Parsed<NoteData> { // An unknown severity ("critical") is not an error: it is kept in the file but shown as none. const severity = SEVERITIES.includes(v.severity) ? v.severity as Severity : undefined const extra = Object.fromEntries(Object.entries(v).filter(([k]) => !KNOWN.has(k) || (k === 'severity' && !severity))) - const events = readEvents(v.events) + const { events, others } = readEvents(v.events) const session = typeof v.session === 'string' ? v.session.trim() : '' return accepted({ id, @@ -227,6 +282,8 @@ export function parseNote(raw: string, id: string): Parsed<NoteData> { ...opt(severity, 'severity', severity!), ...opt(events.length, 'events', events), ...opt(target, 'target', target!), + ...(target ? {} : { ...optExtra('rangeExtra', unknownKeys(v.range, RANGE_KEYS)), ...optExtra('anchorExtra', unknownKeys(v.anchor, ANCHOR_KEYS)) }), + ...opt(others.length, 'otherEvents', others), ...opt(Object.keys(extra).length, 'extra', extra), }) } diff --git a/src/core/format/schema/note.schema.json b/src/core/format/schema/note.schema.json index c325c4d..5d54801 100644 --- a/src/core/format/schema/note.schema.json +++ b/src/core/format/schema/note.schema.json @@ -3,7 +3,7 @@ "$id": "note.schema.json", "title": "Code note", "description": "A note on the code: one file .code-notes/<id>.json, a comment thread on some lines, a whole file or a folder (media/notes-README.template.md).", - "$comment": "From src/core/format/noteModel.ts noteProblem and parseNote. Required: file, messages (at least one, each with a body), and range unless target is set. Unknown fields are allowed: the extension keeps them and writes them back. Lenient fallbacks of the reader not described here: a selection with non-number columns, an unknown role, a malformed event (each dropped when read). severity is any string: the extension knows high, medium, low and nit, and keeps any other value (\"critical\") in the file without an error, showing it as none. Not expressible here: range.end >= range.start; range and anchor are ignored when target is set.", + "$comment": "From src/core/format/noteModel.ts noteProblem and parseNote. Required: file, messages (at least one, each with a body), and range unless target is set. Unknown fields are allowed, at the top and inside range, anchor, messages and events: the extension keeps them and writes them back. An event of another type, or malformed, is kept in the file as it is but not shown. Lenient fallbacks of the reader not described here: a selection with non-number columns, an unknown role (dropped when read). severity is any string: the extension knows high, medium, low and nit, and keeps any other value (\"critical\") in the file without an error, showing it as none. Not expressible here: range.end >= range.start; range and anchor are ignored when target is set.", "type": "object", "properties": { "version": { "description": "The note format version: 1 (a file without it is version 1).", "const": 1 }, diff --git a/src/notes/brokenAt.ts b/src/notes/brokenAt.ts index 24149ae..d31fbcb 100644 --- a/src/notes/brokenAt.ts +++ b/src/notes/brokenAt.ts @@ -16,11 +16,42 @@ const FIELDS: [string, (v: Record<string, any>) => boolean][] = [ ['messages', (v) => Array.isArray(v.messages) && v.messages.length > 0 && v.messages.every((m: any) => typeof m?.body === 'string')], ] -/** Where in `text` (a note file) the cursor goes to fix it: the end when it is not JSON, a wrong field's name, or the - * top (0) when no field is to blame. */ +/** Where the parser stops in `text` (its error says "at position N", or that the text ended too soon); undefined: it + * parses, or its error names no place ("Unexpected token 'x'"). */ +function stopsAt(text: string): number | undefined { + try { JSON.parse(text); return undefined } catch (e) { + const m = (e as Error).message + const at = /\bposition (\d+)/.exec(m) + if (at) return Math.min(Number(at[1]), text.length) + return /end of JSON input/.test(m) ? text.length : undefined + } +} + +/** Whether `text` is wrong before its end (not only cut off). */ +const wrongBeforeEnd = (text: string) => { + try { JSON.parse(text); return false } catch { return (stopsAt(text) ?? -1) < text.length } +} + +/** Where the parser stopped in `text`, which is not JSON: as its error says, else the shortest start of the text that + * is already wrong ends there. Cut off: the end. */ +function syntaxErrorAt(text: string): number { + const named = stopsAt(text) + if (named !== undefined) return named + let ok = 0 + let wrong = text.length + while (wrong - ok > 1) { + const mid = (ok + wrong) >> 1 + if (wrongBeforeEnd(text.slice(0, mid))) wrong = mid + else ok = mid + } + return wrong - 1 +} + +/** Where in `text` (a note file) the cursor goes to fix it: where the parser stopped when it is not JSON, a wrong + * field's name, or the top (0) when no field is to blame. */ export function brokenOffset(text: string): number { const json = parseJson(text) - if (!json.ok) return text.length + if (!json.ok) return syntaxErrorAt(text) const v = json.value if (!v || typeof v !== 'object' || Array.isArray(v)) return 0 const field = FIELDS.find(([, ok]) => !ok(v as Record<string, any>))?.[0] diff --git a/src/notes/reply.ts b/src/notes/reply.ts index 4815617..6a5d441 100644 --- a/src/notes/reply.ts +++ b/src/notes/reply.ts @@ -20,7 +20,10 @@ import { withRollback } from './rollback' const replying = new OncePerSubmit<string>() /** Adds your message; on a failed save (an error toast is shown) the note is left as it was. */ -export const addReply = async (n: Note, text: string, status?: 'open' | 'resolved'): Promise<boolean> => { +export const addReply = async (n: Note, text: string, status?: 'open' | 'resolved'): Promise<boolean> => (await sendReply(n, text, status)) === 'saved' + +/** addReply, saying whether it was not saved because the same reply is being saved already ('busy'). */ +async function sendReply(n: Note, text: string, status?: 'open' | 'resolved'): Promise<'saved' | 'failed' | 'busy'> { const saved = await replying.run(`${n.data.id}\0${text}\0${status ?? ''}`, () => withRollback(n, ['messages', 'status', 'events'], async () => { if (text) n.data.messages.push({ author: me(), role: 'human', body: text, at: now() }) const next = status ?? (n.data.status === 'resolved' && text ? 'open' : n.data.status) @@ -30,20 +33,27 @@ export const addReply = async (n: Note, text: string, status?: 'open' | 'resolve syncThread(n) return store().save(n) })) - if (saved === undefined) return false + if (saved === undefined) return 'busy' if (!saved) { notesChanged({ kind: 'saved', ids: [n.data.id] }) - return false + return 'failed' } fireAndForget(markRead([n]), 'mark read') - return true + return 'saved' } +/** VS Code clears a thread's box when its command returns, and leaves it as it is when the command fails: a reply + * that was not saved (the error is shown) stays there to send again. Cancelled: VS Code shows nothing more. */ +const keepInBox = (): never => { throw new vscode.CancellationError() } + /** codeNotes.reply (and replyReopen): Ctrl+Enter in a thread's box. */ export const replyTo = async (r: vscode.CommentReply) => { const n = noteOfThread(r.thread) if (!n || !r.text.trim()) return - if ((await addReply(n, r.text.trim())) && askAlways()) await askClaude(n) + const sent = await sendReply(n, r.text.trim()) + if (sent === 'failed') keepInBox() + // Not awaited: the box is cleared once the reply is saved, not when Claude has answered. + if (sent === 'saved' && askAlways()) fireAndForget(askClaude(n), 'ask Claude after a reply') } /** Answer and close in one step (the usual end of a thread): the reply, then the same resolve as the Resolve button. */ @@ -52,6 +62,8 @@ export const replyAndResolve = async (reply: vscode.CommentReply) => { if (!n) return // The reply keeps the status as it is (a resolved thread is not reopened by it): resolving is resolve's. const text = reply.text.trim() - if (text && !(await addReply(n, text, n.data.status))) return + const sent = text ? await sendReply(n, text, n.data.status) : 'saved' + if (sent === 'failed') keepInBox() + if (sent !== 'saved') return await resolve([n]) } diff --git a/src/notes/store.ts b/src/notes/store.ts index 296380a..448af99 100644 --- a/src/notes/store.ts +++ b/src/notes/store.ts @@ -7,6 +7,7 @@ import { fileName, jsonFilesIn, jsonName, readText, watchJsonFiles } from '../pl import { NoteData, merge, parseNote, serialize, titleOf } from '../core/format/noteModel' import { SaveFailures } from '../platform/saveFailures' import { exists, notFound, statOf } from '../platform/exists' +import { sleep } from './timing' import { report } from '../platform/run' import { folderName, notesDir, setUpFolder, trashUri, writeReadme } from './notesFolder' import { fitTarget, isRangelessFileNote } from './model/target' @@ -46,6 +47,8 @@ type FileRead = { note?: Note; before?: NoteData } * the old content or the new one, never a half-written file (the flaky "note history" test read a truncated file). */ let tmpSeq = 0 +/** How often a save looks again at a note file being written. */ +const WRITING_POLL_MS = 100 const encoder = new TextEncoder() export async function writeAtomic(uri: vscode.Uri, text: string): Promise<void> { // One temp file per write: two saves of a note at once must not rename each other's file away. @@ -78,6 +81,8 @@ export class Store implements vscode.Disposable { private watchers: vscode.Disposable[] = [] /** Saves that failed, said once each and together. */ private readonly saveFailures: SaveFailures + /** How long a save waits for a note file that can't be read (an agent half-way through writing it) to parse again. */ + writingWaitMs = 3000 constructor(private log: vscode.LogOutputChannel, private person: () => string) { this.saveFailures = new SaveFailures(log, folderName) @@ -232,11 +237,9 @@ export class Store implements vscode.Disposable { let merged = false if (n.raw !== undefined) { // Undefined: deleted, write ours. - const disk = await readText(n.uri) - if (disk !== undefined && disk !== n.raw) { - const read = parseNote(disk, n.data.id) - if (!read.ok) { this.log.appendLine(`${n.uri.fsPath}: not saved, the file is being written (${read.why})`); return false } - const theirs = read.value + const theirs = await this.changedOnDisk(n) + if (theirs === false) return false + if (theirs) { n.data = merge(n.base ?? theirs, n.data, theirs) this.log.appendLine(`${n.uri.fsPath}: merged a change made on disk`) merged = true @@ -260,6 +263,26 @@ export class Store implements vscode.Disposable { return true } + /** + * The note as its file has it now, when that changed since we read it (undefined: unchanged or gone). A file that + * can't be read is waited for (an agent writing it in two steps); false when it stays so: our change can't be + * merged, and overwriting would lose theirs. Said, not only logged: the caller's change is not saved. + */ + private async changedOnDisk(n: Note): Promise<NoteData | undefined | false> { + const until = Date.now() + this.writingWaitMs + for (;;) { + const disk = await readText(n.uri) + if (disk === undefined || disk === n.raw) return undefined + const read = parseNote(disk, n.data.id) + if (read.ok) return read.value + if (Date.now() >= until) { + this.saveFailures.report(n.uri, new Error(`the file can't be read (${read.why}); fix it or try again`)) + return false + } + await sleep(WRITING_POLL_MS) + } + } + /** Moves the note's file to <folder>/.trash/ (restore brings it back). */ async trash(n: Note): Promise<void> { this.forget(n.uri) @@ -269,21 +292,45 @@ export class Store implements vscode.Disposable { this.changed.fire({ kind: 'removed', ids: [n.data.id] }) } - /** Brings a trashed note back: its file from the trash, else (not there, or a file is in its place) written again - * from memory. */ + /** + * Brings a trashed note back: its file from the trash, else (not there) written again from memory. A note written + * under its id since (an agent's) is never overwritten: this one comes back under a new id beside it. + */ async restore(n: Note): Promise<void> { - if (!(await this.fromTrash(n))) await this.save({ ...n, raw: undefined }) - this.put(n) + const trashed = trashUri(n.folder, n.uri) + const back = (await exists(n.uri)) ? 'taken' : await this.fromTrash(n, trashed) + if (back === 'done') this.put(n) + else { + if (back === 'taken' || (await exists(n.uri))) await this.renameFree(n) + n.raw = undefined + // The trash copy is this note: gone once it is back. + if (await this.save(n)) await wfs.remove(trashed).catch((e) => { if (!notFound(e)) report(e, { what: `removing ${trashed.fsPath}` }) }) + } this.changed.fire({ kind: 'removed', ids: [n.data.id] }) } - /** The note's file renamed back from the trash; false when that can't be done. */ - private async fromTrash(n: Note): Promise<boolean> { - try { await wfs.rename(trashUri(n.folder, n.uri), n.uri, { overwrite: false }); return true } catch (e) { - const expected = notFound(e) || (e instanceof vscode.FileSystemError && e.code === 'FileExists') - if (!expected) report(e, { what: `restoring ${n.uri.fsPath} from the trash` }) - return false + /** The note's file renamed back from the trash: done, or why not (no trash copy, a file in its place, failed). */ + private async fromTrash(n: Note, trashed: vscode.Uri): Promise<'done' | 'gone' | 'taken' | 'failed'> { + try { await wfs.rename(trashed, n.uri, { overwrite: false }); return 'done' } catch (e) { + if (notFound(e)) return 'gone' + if (e instanceof vscode.FileSystemError && e.code === 'FileExists') return 'taken' + report(e, { what: `restoring ${n.uri.fsPath} from the trash` }) + return 'failed' + } + } + + /** Gives the note a new id (`<id>-restored`, `-restored-2`, …) whose file is free. */ + private async renameFree(n: Note): Promise<void> { + const was = n.uri + for (let k = 1; ; k++) { + const id = `${n.data.id}-restored${k > 1 ? `-${k}` : ''}` + const uri = vscode.Uri.joinPath(n.uri, '..', `${id}.json`) + if (await exists(uri)) continue + n.data.id = id + n.uri = uri + break } + this.log.warn(`${was.fsPath}: a note was written under its id since it was deleted; it stays, and the deleted one is back as ${n.data.id}`) } /** The README for agents, naming the person. */ diff --git a/test/golden-notes.test.ts b/test/golden-notes.test.ts index f2f4029..94d43a6 100644 --- a/test/golden-notes.test.ts +++ b/test/golden-notes.test.ts @@ -71,6 +71,32 @@ test('golden: crafted notes read and written back; files that are not notes, and expectGolden(AREA, 'notes.invalid', BAD_NOTES.map(([name, raw]) => ({ name, why: parsedOrWhy(raw, 'x'), title: titleOf(raw) ?? null }))) }) +/** A note as an agent or a newer version may write it: fields this version doesn't know inside a message, the range + * and the anchor, and events of other types (one malformed). */ +const withNestedExtras = note({ + range: { start: 3, end: 5, rangeExtra: 'r' }, + anchor: { text: 'a', before: '', after: '', anchorExtra: 'a', hash: { algo: 'x', v: 1 } }, + messages: [msg({ msgExtra: 'keep-me', attachments: ['a.png'] }), msg({ author: 'Claude', role: 'agent', body: 'Seen.', at: '2026-11-17T10:05:00Z', tool: { name: 'Read' } })], + events: [{ type: 'assigned', by: 'bot', at: '2026-11-17T10:01:00Z' }, { type: 'resolved', by: 'ann', at: '2026-11-17T10:02:00Z', why: 'fixed' }, { type: 'reopened' }], + custom: true, +}) + +test('golden: fields this version doesn\'t know, nested too, written back after a resolve, a reply and a move', () => { + const read = () => parsedOrWhy(JSON.stringify(withNestedExtras), 'n1') as NoteData + const resolved = read() + resolved.status = 'resolved' + resolved.events = [...resolved.events!, { type: 'resolved', by: 'ann', role: 'human', at: '2026-11-17T12:00:00Z' }] + const replied = read() + replied.messages.push({ author: 'ann', role: 'human', body: 'Thanks.', at: '2026-11-17T12:00:00Z' }) + const moved = read() + moved.range = { start: 8, end: 10 } + moved.anchor = captureAnchor(['x', 'y', 'z'], 1, 1) + expectGolden(AREA, 'nested-extras', { + parsed: read(), + written: Object.fromEntries(([['resolved', resolved], ['replied', replied], ['moved', moved]] as const).map(([k, d]) => [k, serialize(d)])), + }) +}) + test('golden: the three-way merge of a note changed on disk and in memory', () => { const base = parsedOrWhy(JSON.stringify(note({ events: [{ type: 'resolved', by: 'ann', at: 't1' }] })), 'n') as NoteData const with_ = (o: Partial<NoteData>): NoteData => ({ ...base, ...o }) @@ -85,6 +111,13 @@ test('golden: the three-way merge of a note changed on disk and in memory', () = ['we cleared the severity they set', with_({ severity: undefined }), with_({ severity: 'high', target: undefined })], ['they removed the events', base, with_({ events: undefined })], ['they changed the id and createdAt (theirs kept)', with_({ id: 'ours', createdAt: 'a' }), with_({ id: 'theirs', createdAt: 'b' })], + ['they added fields this version doesn\'t know, nested too, while we resolved', with_({ status: 'resolved' }), with_({ + messages: [{ ...base.messages[0], extra: { attachments: ['a.png'] } }, { ...m2, extra: { tool: 'Read' } }], + rangeExtra: { r: 1 }, anchorExtra: { a: 1 }, otherEvents: [{ index: 0, event: { type: 'assigned', at: 't0' } }], + })], + ['both have fields this version doesn\'t know in their new messages; we moved, they kept the range\'s', with_({ + range: { start: 9, end: 9 }, messages: [...base.messages, { ...m3, extra: { ours: 1 } }], rangeExtra: { r: 1 }, + }), with_({ messages: [...base.messages, { ...m2, extra: { theirs: 1 } }], rangeExtra: { r: 1 } })], ] expectGolden(AREA, 'merge', cases.map(([name, ours, theirs]) => { const m = merge(base, ours, theirs); return { name, merged: m, written: serialize(m) } })) }) diff --git a/test/goldens/notes/merge.json b/test/goldens/notes/merge.json index 252262d..6e72e28 100644 --- a/test/goldens/notes/merge.json +++ b/test/goldens/notes/merge.json @@ -308,5 +308,127 @@ "claudeSession": "[undefined]" }, "written": "{\n \"version\": 1,\n \"id\": \"theirs\",\n \"file\": \"api/orders.js\",\n \"range\": {\n \"start\": 3,\n \"end\": 5\n },\n \"anchor\": {\n \"text\": \"\",\n \"before\": \"\",\n \"after\": \"\"\n },\n \"status\": \"open\",\n \"stale\": false,\n \"messages\": [\n {\n \"author\": \"ann\",\n \"role\": \"human\",\n \"body\": \"Why is this retried?\",\n \"at\": \"2026-11-17T10:00:00Z\"\n }\n ],\n \"events\": [\n {\n \"type\": \"resolved\",\n \"by\": \"ann\",\n \"at\": \"t1\"\n }\n ],\n \"createdAt\": \"b\"\n}\n" + }, + { + "name": "they added fields this version doesn't know, nested too, while we resolved", + "merged": { + "id": "n", + "file": "api/orders.js", + "range": { + "start": 3, + "end": 5 + }, + "anchor": { + "text": "", + "before": "", + "after": "" + }, + "status": "resolved", + "stale": false, + "messages": [ + { + "author": "ann", + "role": "human", + "body": "Why is this retried?", + "at": "2026-11-17T10:00:00Z", + "extra": { + "attachments": [ + "a.png" + ] + } + }, + { + "author": "Claude", + "role": "agent", + "body": "An answer.", + "at": "t2", + "extra": { + "tool": "Read" + } + } + ], + "events": [ + { + "type": "resolved", + "by": "ann", + "at": "t1" + } + ], + "rangeExtra": { + "r": 1 + }, + "anchorExtra": { + "a": 1 + }, + "otherEvents": [ + { + "index": 0, + "event": { + "type": "assigned", + "at": "t0" + } + } + ], + "session": "[undefined]", + "claudeSession": "[undefined]" + }, + "written": "{\n \"version\": 1,\n \"id\": \"n\",\n \"file\": \"api/orders.js\",\n \"range\": {\n \"start\": 3,\n \"end\": 5,\n \"r\": 1\n },\n \"anchor\": {\n \"text\": \"\",\n \"before\": \"\",\n \"after\": \"\",\n \"a\": 1\n },\n \"status\": \"resolved\",\n \"stale\": false,\n \"messages\": [\n {\n \"author\": \"ann\",\n \"role\": \"human\",\n \"body\": \"Why is this retried?\",\n \"at\": \"2026-11-17T10:00:00Z\",\n \"attachments\": [\n \"a.png\"\n ]\n },\n {\n \"author\": \"Claude\",\n \"role\": \"agent\",\n \"body\": \"An answer.\",\n \"at\": \"t2\",\n \"tool\": \"Read\"\n }\n ],\n \"events\": [\n {\n \"type\": \"assigned\",\n \"at\": \"t0\"\n },\n {\n \"type\": \"resolved\",\n \"by\": \"ann\",\n \"at\": \"t1\"\n }\n ]\n}\n" + }, + { + "name": "both have fields this version doesn't know in their new messages; we moved, they kept the range's", + "merged": { + "id": "n", + "file": "api/orders.js", + "range": { + "start": 9, + "end": 9 + }, + "anchor": { + "text": "", + "before": "", + "after": "" + }, + "status": "open", + "stale": false, + "messages": [ + { + "author": "ann", + "role": "human", + "body": "Why is this retried?", + "at": "2026-11-17T10:00:00Z" + }, + { + "author": "Claude", + "role": "agent", + "body": "An answer.", + "at": "t2", + "extra": { + "theirs": 1 + } + }, + { + "author": "ann", + "role": "human", + "body": "Thanks.", + "at": "t3", + "extra": { + "ours": 1 + } + } + ], + "events": [ + { + "type": "resolved", + "by": "ann", + "at": "t1" + } + ], + "rangeExtra": { + "r": 1 + }, + "session": "[undefined]", + "claudeSession": "[undefined]" + }, + "written": "{\n \"version\": 1,\n \"id\": \"n\",\n \"file\": \"api/orders.js\",\n \"range\": {\n \"start\": 9,\n \"end\": 9,\n \"r\": 1\n },\n \"anchor\": {\n \"text\": \"\",\n \"before\": \"\",\n \"after\": \"\"\n },\n \"status\": \"open\",\n \"stale\": false,\n \"messages\": [\n {\n \"author\": \"ann\",\n \"role\": \"human\",\n \"body\": \"Why is this retried?\",\n \"at\": \"2026-11-17T10:00:00Z\"\n },\n {\n \"author\": \"Claude\",\n \"role\": \"agent\",\n \"body\": \"An answer.\",\n \"at\": \"t2\",\n \"theirs\": 1\n },\n {\n \"author\": \"ann\",\n \"role\": \"human\",\n \"body\": \"Thanks.\",\n \"at\": \"t3\",\n \"ours\": 1\n }\n ],\n \"events\": [\n {\n \"type\": \"resolved\",\n \"by\": \"ann\",\n \"at\": \"t1\"\n }\n ]\n}\n" } ] diff --git a/test/goldens/notes/nested-extras.json b/test/goldens/notes/nested-extras.json new file mode 100644 index 0000000..a665815 --- /dev/null +++ b/test/goldens/notes/nested-extras.json @@ -0,0 +1,86 @@ +{ + "parsed": { + "id": "n1", + "file": "api/orders.js", + "range": { + "start": 3, + "end": 5 + }, + "anchor": { + "text": "a", + "before": "", + "after": "" + }, + "status": "open", + "stale": false, + "messages": [ + { + "author": "ann", + "role": "human", + "body": "Why is this retried?", + "at": "2026-11-17T10:00:00Z", + "extra": { + "msgExtra": "keep-me", + "attachments": [ + "a.png" + ] + } + }, + { + "author": "Claude", + "role": "agent", + "body": "Seen.", + "at": "2026-11-17T10:05:00Z", + "extra": { + "tool": { + "name": "Read" + } + } + } + ], + "events": [ + { + "type": "resolved", + "by": "ann", + "at": "2026-11-17T10:02:00Z", + "extra": { + "why": "fixed" + } + } + ], + "rangeExtra": { + "rangeExtra": "r" + }, + "anchorExtra": { + "anchorExtra": "a", + "hash": { + "algo": "x", + "v": 1 + } + }, + "otherEvents": [ + { + "index": 0, + "event": { + "type": "assigned", + "by": "bot", + "at": "2026-11-17T10:01:00Z" + } + }, + { + "index": 2, + "event": { + "type": "reopened" + } + } + ], + "extra": { + "custom": true + } + }, + "written": { + "resolved": "{\n \"version\": 1,\n \"id\": \"n1\",\n \"file\": \"api/orders.js\",\n \"range\": {\n \"start\": 3,\n \"end\": 5,\n \"rangeExtra\": \"r\"\n },\n \"anchor\": {\n \"text\": \"a\",\n \"before\": \"\",\n \"after\": \"\",\n \"anchorExtra\": \"a\",\n \"hash\": {\n \"algo\": \"x\",\n \"v\": 1\n }\n },\n \"status\": \"resolved\",\n \"stale\": false,\n \"messages\": [\n {\n \"author\": \"ann\",\n \"role\": \"human\",\n \"body\": \"Why is this retried?\",\n \"at\": \"2026-11-17T10:00:00Z\",\n \"msgExtra\": \"keep-me\",\n \"attachments\": [\n \"a.png\"\n ]\n },\n {\n \"author\": \"Claude\",\n \"role\": \"agent\",\n \"body\": \"Seen.\",\n \"at\": \"2026-11-17T10:05:00Z\",\n \"tool\": {\n \"name\": \"Read\"\n }\n }\n ],\n \"events\": [\n {\n \"type\": \"assigned\",\n \"by\": \"bot\",\n \"at\": \"2026-11-17T10:01:00Z\"\n },\n {\n \"type\": \"resolved\",\n \"by\": \"ann\",\n \"at\": \"2026-11-17T10:02:00Z\",\n \"why\": \"fixed\"\n },\n {\n \"type\": \"reopened\"\n },\n {\n \"type\": \"resolved\",\n \"by\": \"ann\",\n \"role\": \"human\",\n \"at\": \"2026-11-17T12:00:00Z\"\n }\n ],\n \"custom\": true\n}\n", + "replied": "{\n \"version\": 1,\n \"id\": \"n1\",\n \"file\": \"api/orders.js\",\n \"range\": {\n \"start\": 3,\n \"end\": 5,\n \"rangeExtra\": \"r\"\n },\n \"anchor\": {\n \"text\": \"a\",\n \"before\": \"\",\n \"after\": \"\",\n \"anchorExtra\": \"a\",\n \"hash\": {\n \"algo\": \"x\",\n \"v\": 1\n }\n },\n \"status\": \"open\",\n \"stale\": false,\n \"messages\": [\n {\n \"author\": \"ann\",\n \"role\": \"human\",\n \"body\": \"Why is this retried?\",\n \"at\": \"2026-11-17T10:00:00Z\",\n \"msgExtra\": \"keep-me\",\n \"attachments\": [\n \"a.png\"\n ]\n },\n {\n \"author\": \"Claude\",\n \"role\": \"agent\",\n \"body\": \"Seen.\",\n \"at\": \"2026-11-17T10:05:00Z\",\n \"tool\": {\n \"name\": \"Read\"\n }\n },\n {\n \"author\": \"ann\",\n \"role\": \"human\",\n \"body\": \"Thanks.\",\n \"at\": \"2026-11-17T12:00:00Z\"\n }\n ],\n \"events\": [\n {\n \"type\": \"assigned\",\n \"by\": \"bot\",\n \"at\": \"2026-11-17T10:01:00Z\"\n },\n {\n \"type\": \"resolved\",\n \"by\": \"ann\",\n \"at\": \"2026-11-17T10:02:00Z\",\n \"why\": \"fixed\"\n },\n {\n \"type\": \"reopened\"\n }\n ],\n \"custom\": true\n}\n", + "moved": "{\n \"version\": 1,\n \"id\": \"n1\",\n \"file\": \"api/orders.js\",\n \"range\": {\n \"start\": 8,\n \"end\": 10,\n \"rangeExtra\": \"r\"\n },\n \"anchor\": {\n \"text\": \"y\",\n \"before\": \"x\",\n \"after\": \"z\",\n \"anchorExtra\": \"a\",\n \"hash\": {\n \"algo\": \"x\",\n \"v\": 1\n }\n },\n \"status\": \"open\",\n \"stale\": false,\n \"messages\": [\n {\n \"author\": \"ann\",\n \"role\": \"human\",\n \"body\": \"Why is this retried?\",\n \"at\": \"2026-11-17T10:00:00Z\",\n \"msgExtra\": \"keep-me\",\n \"attachments\": [\n \"a.png\"\n ]\n },\n {\n \"author\": \"Claude\",\n \"role\": \"agent\",\n \"body\": \"Seen.\",\n \"at\": \"2026-11-17T10:05:00Z\",\n \"tool\": {\n \"name\": \"Read\"\n }\n }\n ],\n \"events\": [\n {\n \"type\": \"assigned\",\n \"by\": \"bot\",\n \"at\": \"2026-11-17T10:01:00Z\"\n },\n {\n \"type\": \"resolved\",\n \"by\": \"ann\",\n \"at\": \"2026-11-17T10:02:00Z\",\n \"why\": \"fixed\"\n },\n {\n \"type\": \"reopened\"\n }\n ],\n \"custom\": true\n}\n" + } +} diff --git a/test/goldens/notes/notes.crafted.json b/test/goldens/notes/notes.crafted.json index e1ce5ea..35948b8 100644 --- a/test/goldens/notes/notes.crafted.json +++ b/test/goldens/notes/notes.crafted.json @@ -74,9 +74,26 @@ "role": "human", "at": "2026-11-17T11:00:00Z" } + ], + "otherEvents": [ + { + "index": 1, + "event": { + "type": "deleted", + "by": "x", + "at": "y" + } + }, + { + "index": 2, + "event": { + "type": "reopened", + "at": 3 + } + } ] }, - "written": "{\n \"version\": 1,\n \"id\": \"n1\",\n \"file\": \"api/orders.js\",\n \"range\": {\n \"start\": 3,\n \"end\": 5\n },\n \"anchor\": {\n \"text\": \"a\",\n \"before\": \"b\",\n \"after\": \"c\",\n \"commit\": \"abc1234\",\n \"branch\": \"feat/x\"\n },\n \"session\": \"Review · api\",\n \"claudeSession\": \"sess-1\",\n \"selection\": {\n \"text\": \"total\",\n \"startCol\": 8,\n \"endCol\": 13\n },\n \"status\": \"resolved\",\n \"stale\": true,\n \"createdAt\": \"2026-11-17T09:00:00Z\",\n \"messages\": [\n {\n \"author\": \"ann\",\n \"role\": \"human\",\n \"body\": \"Why is this retried?\",\n \"at\": \"2026-11-17T10:00:00Z\"\n },\n {\n \"author\": \"Claude\",\n \"role\": \"agent\",\n \"body\": \"Because the queue is at-least-once.\",\n \"at\": \"2026-11-17T10:05:00Z\"\n }\n ],\n \"severity\": \"medium\",\n \"events\": [\n {\n \"type\": \"resolved\",\n \"by\": \"ann\",\n \"role\": \"human\",\n \"at\": \"2026-11-17T11:00:00Z\"\n }\n ]\n}\n" + "written": "{\n \"version\": 1,\n \"id\": \"n1\",\n \"file\": \"api/orders.js\",\n \"range\": {\n \"start\": 3,\n \"end\": 5\n },\n \"anchor\": {\n \"text\": \"a\",\n \"before\": \"b\",\n \"after\": \"c\",\n \"commit\": \"abc1234\",\n \"branch\": \"feat/x\"\n },\n \"session\": \"Review · api\",\n \"claudeSession\": \"sess-1\",\n \"selection\": {\n \"text\": \"total\",\n \"startCol\": 8,\n \"endCol\": 13\n },\n \"status\": \"resolved\",\n \"stale\": true,\n \"createdAt\": \"2026-11-17T09:00:00Z\",\n \"messages\": [\n {\n \"author\": \"ann\",\n \"role\": \"human\",\n \"body\": \"Why is this retried?\",\n \"at\": \"2026-11-17T10:00:00Z\"\n },\n {\n \"author\": \"Claude\",\n \"role\": \"agent\",\n \"body\": \"Because the queue is at-least-once.\",\n \"at\": \"2026-11-17T10:05:00Z\"\n }\n ],\n \"severity\": \"medium\",\n \"events\": [\n {\n \"type\": \"resolved\",\n \"by\": \"ann\",\n \"role\": \"human\",\n \"at\": \"2026-11-17T11:00:00Z\"\n },\n {\n \"type\": \"deleted\",\n \"by\": \"x\",\n \"at\": \"y\"\n },\n {\n \"type\": \"reopened\",\n \"at\": 3\n }\n ]\n}\n" }, { "name": "unknown fields kept, in place", diff --git a/test/integration/main/notesStore.ts b/test/integration/main/notesStore.ts new file mode 100644 index 0000000..e1340ee --- /dev/null +++ b/test/integration/main/notesStore.ts @@ -0,0 +1,91 @@ +// Saving a note never loses anyone's words: a reply sent while an agent is half-way through writing the note's file +// (saved once the file is whole, else the box keeps the text and an error says why), Undo of a delete when an agent +// has written a note under the same id since (both kept), and a reply with Claude: Mode "always" (the box is cleared +// once the reply is saved, not when Claude has answered). +// Source: src/notes/store.ts (save, restore), src/notes/reply.ts. VS Code clears a thread's box when the reply command +// returns and keeps the text when it fails: the command's promise is what these tests watch. +import * as vscode from 'vscode' +import * as fs from 'fs' +import * as path from 'path' +import assert from 'assert' +import { readJson, test } from '../helpers' +import { agentNote, writeNote } from '../fixtures' +import { cdp, ui } from '../devtools' +import { ctx, noteById, notePath, setting, until } from './context' + +/* eslint-disable @typescript-eslint/no-explicit-any */ +/** A note id in the note-ID format; only `tag` matters (a unique name). */ +const noteId = (tag: string) => `20261126-090000-${tag}` + +/** An agent's note on src/app.ts line 1, read by the window and with its thread; its id and file. */ +async function agentsNote(tag: string, body: string): Promise<{ id: string; file: string; text: string }> { + const id = noteId(tag) + const file = writeNote(ctx.notesDir, id, agentNote('src/app.ts', 1, body)) + await until(`${id} read, with its thread`, () => noteById(id) && ctx.api.thread(id)) + return { id, file, text: fs.readFileSync(file, 'utf8') } +} + +const reply = (id: string, text: string) => vscode.commands.executeCommand('codeNotes.reply', { thread: ctx.api.thread(id), text }) +const bodies = (file: string): string[] => readJson(file).messages.map((m: any) => m.body) + +export const notesStoreTests = [ + test('a reply sent while an agent is half-way through writing the note file is saved once the file is whole', async () => { + const n = await agentsNote('half', 'Half-written target') + fs.writeFileSync(n.file, n.text.slice(0, 60)) + const sent = reply(n.id, 'typed while the file was half-written') + // The agent finishes its write, with a reply of its own. + setTimeout(() => appendWhole(n.file, n.text, 'the agent\'s reply'), 500) + await sent + assert.deepEqual(bodies(n.file), ['Half-written target', 'the agent\'s reply', 'typed while the file was half-written']) + }), + + test('a reply to a note file that stays unreadable: the command fails (the box keeps the text), an error says why, the file is untouched', async () => { + const n = await agentsNote('broken', 'Broken target') + const broken = n.text.slice(0, 60) + fs.writeFileSync(n.file, broken) + const failed = await Promise.resolve(reply(n.id, 'typed while the file was broken')).then(() => undefined, (e: Error) => e) + assert.equal(failed?.name, 'Canceled', 'the reply command fails quietly: VS Code leaves the text in the box') + assert.equal(fs.readFileSync(n.file, 'utf8'), broken, 'not overwritten') + assert.ok(!noteById(n.id).messages.some((m: any) => m.body === 'typed while the file was broken'), 'not shown as sent') + if (cdp) await until('the error toast', async () => (await (await ui()).locator('.notification-toast', { hasText: /couldn't save .*can't be read/ }).count()) > 0) + fs.writeFileSync(n.file, n.text) + }), + + test('Undo of a delete when an agent has written a note under the same id since: both notes kept, the trash empty', async () => { + const n = await agentsNote('undo', 'The note deleted') + await vscode.commands.executeCommand('codeNotes.delete', n.id) + await until('in the trash', () => !fs.existsSync(n.file) && !noteById(n.id)) + writeNote(ctx.notesDir, n.id, agentNote('src/app.ts', 1, 'The agent\'s new note, same id')) + await until('the agent\'s note read', () => noteById(n.id)?.messages[0].body === 'The agent\'s new note, same id') + await vscode.commands.executeCommand('codeNotes.undo') + const restored = `${n.id}-restored` + await until('the deleted note back under a new id', () => noteById(restored)?.messages[0].body === 'The note deleted') + assert.equal(readJson(n.file).messages[0].body, 'The agent\'s new note, same id', 'the agent\'s note is not overwritten') + assert.equal(readJson(notePath(restored)).messages[0].body, 'The note deleted') + assert.ok(!fs.existsSync(path.join(ctx.notesDir, '.trash', `${n.id}.json`)), 'no stale copy in the trash') + }), + + test('Claude: Mode "always": the reply command returns once the reply is saved, while Claude still answers; one human message', async () => { + const n = await agentsNote('always', 'Always mode target') + await setting('claude.mode', 'always') + try { + const t0 = Date.now() + await reply(n.id, 'a slow question') + assert.ok(Date.now() - t0 < 2000, `returned after ${Date.now() - t0} ms: the box is cleared then`) + await until('Claude asked', () => noteById(n.id)?.asking) + assert.equal(bodies(n.file).filter((b) => b === 'a slow question').length, 1) + } finally { + await vscode.commands.executeCommand('codeNotes.cancelClaude', n.id) + await setting('claude.mode', undefined) + await until('Claude stopped', () => !noteById(n.id)?.asking) + } + assert.equal(noteById(n.id).messages.filter((m: any) => m.body === 'a slow question').length, 1) + }), +] + +/** The note file written whole again, with `body` appended as an agent's message (the end of the agent's write). */ +function appendWhole(file: string, text: string, body: string): void { + const v = JSON.parse(text) + v.messages.push({ author: 'claude', role: 'agent', body, at: new Date().toISOString() }) + fs.writeFileSync(file, JSON.stringify(v, null, 2)) +} diff --git a/test/noteBrokenAt.test.ts b/test/noteBrokenAt.test.ts new file mode 100644 index 0000000..76509ee --- /dev/null +++ b/test/noteBrokenAt.test.ts @@ -0,0 +1,40 @@ +// Where "Open Note File at the Problem" puts the cursor in a note file that is not JSON (src/notes/brokenAt.ts): where +// the parser stopped, not the end of the file. (The fields it points at in a file that is JSON: noteCommands.test.ts.) +import { test } from 'node:test' +import assert from 'node:assert/strict' +import { brokenOffset } from '../src/notes/brokenAt' + +/** The 1-based line and column of `offset` in `text`, as the editor shows them. */ +function lineCol(text: string, offset: number): [number, number] { + const before = text.slice(0, offset).split('\n') + return [before.length, before[before.length - 1].length + 1] +} + +const note = { + version: 1, id: 'n1', file: 'src/notes/store.ts', range: { start: 120, end: 121 }, + anchor: { text: 'a', before: 'b', after: 'c', commit: 'abc1234', branch: 'main' }, session: 'Review', status: 'open', + createdAt: '2026-11-26T09:00:00.000Z', + messages: [ + { author: 'ann', role: 'human', body: 'Why?', at: '2026-11-26T09:00:00.000Z' }, + { author: 'Claude', role: 'agent', body: 'Because.', at: '2026-11-26T09:01:00.000Z' }, + ], +} + +test('brokenOffset: a file that is not JSON puts the cursor where the parser stopped (line 23, column 14), not at the end', () => { + // As `sed 's/"body"/"body" BROKEN,/'` leaves it. + const text = JSON.stringify(note, null, 2).replace(/"body"/g, '"body" BROKEN,') + assert.deepEqual(lineCol(text, brokenOffset(text)), [23, 14]) + assert.ok(brokenOffset(text) < text.length - 100, 'not at the end') +}) + +test('brokenOffset: where the parser stopped, also when its message names no place; cut off: the end', () => { + const cases: [string, string][] = [ + ['{\n "file": "a.ts",,\n}', '2:18'], + ['{\n "file" "a.ts"\n}', '2:10'], + // "Unexpected token 'x'": no position in the message. + ['{\n "messages": [\n { "body": x }\n ]\n}', '3:15'], + ['{\n "status": open\n}', '2:13'], + ] + for (const [text, want] of cases) assert.equal(lineCol(text, brokenOffset(text)).join(':'), want, text) + for (const cut of ['{ "file": "a.ts", "messages": [', '{ "file": "a.t', '{ "file": tr']) assert.equal(brokenOffset(cut), cut.length, cut) +}) diff --git a/test/noteModel.test.ts b/test/noteModel.test.ts index 04341a1..24e579a 100644 --- a/test/noteModel.test.ts +++ b/test/noteModel.test.ts @@ -96,6 +96,48 @@ test('merge: messages and events append; other fields are ours if we changed the assert.ok(!('target' in m) && !('events' in merge(base, base, base)), 'no empty optional fields') }) +test('parseNote and serialize: fields this version doesn\'t know inside messages, events, range and anchor, and events of other types, are written back', () => { + const file = { + file: 'src/a.ts', range: { start: 3, end: 5, rangeExtra: 'r' }, anchor: { text: 'x', anchorExtra: 'a' }, status: 'open', + messages: [{ author: 'ann', role: 'human', body: 'Why?', msgExtra: 'keep-me', attachments: ['a.png'] }], + events: [{ type: 'assigned', by: 'bot', at: 't0' }, { type: 'resolved', by: 'ann', at: 't1', why: 'fixed' }, 'odd'], + } + const d = noteOf(JSON.stringify(file)) + assert.deepEqual(d.messages[0].extra, { msgExtra: 'keep-me', attachments: ['a.png'] }) + assert.deepEqual(d.events, [{ type: 'resolved', by: 'ann', at: 't1', extra: { why: 'fixed' } }], 'the events this version reads') + assert.deepEqual(d.otherEvents, [{ index: 0, event: file.events[0] }, { index: 2, event: 'odd' }]) + // Resolved, replied to and moved: nothing of theirs is lost. + d.status = 'resolved' + d.events!.push({ type: 'resolved', by: 'me', at: 't2' }) + d.messages.push({ author: 'me', body: 'Done.' }) + d.range = { start: 7, end: 9 } + d.anchor = { text: 'y', before: '', after: '' } + const back = JSON.parse(serialize(d)) + assert.deepEqual(back.messages[0], file.messages[0]) + assert.deepEqual(back.range, { start: 7, end: 9, rangeExtra: 'r' }) + assert.deepEqual(back.anchor, { text: 'y', before: '', after: '', anchorExtra: 'a' }) + assert.deepEqual(back.events, [...file.events, { type: 'resolved', by: 'me', at: 't2' }]) + assert.ok(!('otherEvents' in back) && !('rangeExtra' in back) && !('extra' in back.messages[0]), 'nothing of memory\'s own in the file') + assert.equal(serialize(noteOf(serialize(d))), serialize(d), 'read and written again: the same') + // A file or folder note has no range or anchor: none of theirs either. + assert.deepEqual(Object.keys(JSON.parse(serialize(noteOf(JSON.stringify({ ...file, target: 'file' }))))).filter((k) => k === 'range' || k === 'anchor'), []) +}) + +test('merge: fields this version doesn\'t know, nested ones too, are kept from both sides', () => { + const base = parsed() + const ours = { ...structuredClone(base), status: 'resolved' as const, messages: [...base.messages, { author: 'me', body: 'mine', extra: { ours: 1 } }] } + const theirs = { + ...structuredClone(base), messages: [{ ...base.messages[0], extra: { attachments: ['a.png'] } }, { author: 'agent', body: 'theirs', extra: { tool: 'Read' } }], + rangeExtra: { r: 1 }, anchorExtra: { a: 1 }, otherEvents: [{ index: 0, event: { type: 'assigned', at: 't0' } }], extra: { custom: true }, + } + const m = merge(base, ours, theirs) + assert.equal(m.status, 'resolved') + assert.deepEqual(m.messages.map((x) => x.extra), [{ attachments: ['a.png'] }, { tool: 'Read' }, { ours: 1 }]) + assert.deepEqual([m.rangeExtra, m.anchorExtra, m.otherEvents, m.extra], [theirs.rangeExtra, theirs.anchorExtra, theirs.otherEvents, theirs.extra]) + const gone = merge(theirs, theirs, { ...structuredClone(base), status: 'open' }) + assert.ok(!('rangeExtra' in gone) && !('otherEvents' in gone), 'removed on disk: removed (no empty fields)') +}) + test('merge: a message on both sides is not doubled', () => { const base = parsed() const reply = { author: 'agent', body: 'same', at: 't' } diff --git a/test/noteStore.test.ts b/test/noteStore.test.ts new file mode 100644 index 0000000..521951e --- /dev/null +++ b/test/noteStore.test.ts @@ -0,0 +1,135 @@ +// The notes store (src/notes/store.ts) on a real folder, outside VS Code (its API faked): a save never loses what an +// agent wrote (a file being written is waited for, else the save fails and says so), and Undo of a delete never +// overwrites a note written under the same id since. +import { test } from 'node:test' +import assert from 'node:assert/strict' +import * as fs from 'fs' +import * as os from 'os' +import * as path from 'path' +import { pathToFileURL } from 'node:url' +import type * as vscodeTypes from 'vscode' +import { vscode } from './journey-podcast/fakeVscode' + +/** A file URI as VS Code's: joinPath resolves `..`. */ +class Uri { + readonly scheme = 'file' + constructor(readonly path: string) {} + static file(p: string): Uri { return new Uri(p) } + static joinPath(u: Uri, ...parts: string[]): Uri { return new Uri(path.posix.join(u.path, ...parts)) } + get fsPath(): string { return this.path } + toString(): string { return pathToFileURL(this.path).href } +} +class FileSystemError extends Error { + constructor(readonly code: string, u: Uri) { super(`${code}: ${u.path}`) } + static FileNotFound = (u: Uri) => new FileSystemError('FileNotFound', u) + static FileExists = (u: Uri) => new FileSystemError('FileExists', u) + static FileIsADirectory = (u: Uri) => new FileSystemError('FileIsADirectory', u) + static FileNotADirectory = (u: Uri) => new FileSystemError('FileNotADirectory', u) + static NoPermissions = (u: Uri) => new FileSystemError('NoPermissions', u) +} +Object.assign(vscode, { Uri, FileSystemError, FileType: { Unknown: 0, File: 1, Directory: 2, SymbolicLink: 64 } }) + +type Store = import('../src/notes/store').Store +type Note = import('../src/notes/store').Note +const loaded = import('../src/notes/store') + +const said: string[] = [] +const log = { + appendLine: (m: string) => said.push(m), info: (m: string) => said.push(m), warn: (m: string) => said.push(`warn ${m}`), + error: (m: string) => said.push(`error ${m}`), debug: () => undefined, +} as unknown as vscodeTypes.LogOutputChannel + +/** A workspace folder with src/a.ts and an empty notes folder; its store, and a note file's content. */ +async function setUp() { + const ws = fs.mkdtempSync(path.join(os.tmpdir(), 'cn-store-')) + fs.mkdirSync(path.join(ws, 'src')) + fs.writeFileSync(path.join(ws, 'src/a.ts'), 'a\nb\nc\n') + const dir = path.join(ws, '.code-notes') + fs.mkdirSync(dir) + const folder = { uri: Uri.file(ws), name: 'ws', index: 0 } as unknown as vscodeTypes.WorkspaceFolder + const store: Store = new (await loaded).Store(log, () => 'Ann') + store.writingWaitMs = 600 + const file = (id: string) => path.join(dir, `${id}.json`) + const json = (body: string, o: object = {}) => JSON.stringify({ file: 'src/a.ts', range: { start: 1, end: 1 }, status: 'open', messages: [{ author: 'claude', role: 'agent', body }], ...o }, null, 2) + /** The note `id` as the store reads it from its file (the file written first). */ + const read = async (id: string, text = json(`note ${id}`)): Promise<Note> => { + fs.writeFileSync(file(id), text) + const uri = Uri.file(file(id)) as unknown as vscodeTypes.Uri + const raw = fs.readFileSync(file(id), 'utf8') + const { parseNote } = await import('../src/core/format/noteModel') + const r = parseNote(raw, id) + assert.ok(r.ok) + return { data: r.value, folder, uri, raw, base: structuredClone(r.value) } + } + const onDisk = (id: string) => JSON.parse(fs.readFileSync(file(id), 'utf8')) + return { ws, dir, store, file, json, read, onDisk, cleanUp: () => { store.dispose(); fs.rmSync(ws, { recursive: true, force: true }) } } +} + +test('save: a note file half-written by an agent is waited for; their change and ours are both saved', async () => { + const s = await setUp() + try { + const n = await s.read('n1') + const agent = s.json('note n1', { messages: [{ author: 'claude', role: 'agent', body: 'note n1' }, { author: 'claude', role: 'agent', body: 'theirs' }] }) + fs.writeFileSync(s.file('n1'), agent.slice(0, 40)) // the agent half-way + setTimeout(() => fs.writeFileSync(s.file('n1'), agent), 200) + n.data.messages.push({ author: 'Ann', role: 'human', body: 'mine' }) + assert.equal(await s.store.save(n), true) + assert.deepEqual(s.onDisk('n1').messages.map((m: { body: string }) => m.body), ['note n1', 'theirs', 'mine']) + } finally { s.cleanUp() } +}) + +test('save: a note file that stays unreadable is not overwritten; the save fails and says so', async () => { + const s = await setUp() + try { + const n = await s.read('n1') + fs.writeFileSync(s.file('n1'), '{ "file": "src/a.ts", "messa') + n.data.messages.push({ author: 'Ann', role: 'human', body: 'mine' }) + said.length = 0 + assert.equal(await s.store.save(n), false) + assert.equal(fs.readFileSync(s.file('n1'), 'utf8'), '{ "file": "src/a.ts", "messa', 'the file is left as it is') + assert.ok(said.some((l) => l.startsWith('error') && l.includes("couldn't save") && l.includes("can't be read")), said.join('\n')) + } finally { s.cleanUp() } +}) + +test('restore: a note written under the same id since the delete stays; the deleted one comes back under a new id, the trash is empty', async () => { + const s = await setUp() + try { + const n = await s.read('same-1', s.json('the deleted note')) + await s.store.trash(n) + assert.ok(fs.existsSync(path.join(s.dir, '.trash/same-1.json')) && !fs.existsSync(s.file('same-1'))) + fs.writeFileSync(s.file('same-1'), s.json('the agent\'s new note')) + said.length = 0 + await s.store.restore(n) + assert.equal(s.onDisk('same-1').messages[0].body, 'the agent\'s new note', 'the agent\'s note is not overwritten') + assert.equal(n.data.id, 'same-1-restored') + assert.equal(s.onDisk('same-1-restored').messages[0].body, 'the deleted note') + assert.equal(s.store.get('same-1-restored'), n) + assert.deepEqual(fs.readdirSync(path.join(s.dir, '.trash')), [], 'no stale copy in the trash') + assert.ok(said.some((l) => l.startsWith('warn') && l.includes('same-1-restored')), said.join('\n')) + // Again, with that name taken too. + const m = await s.read('same-2', s.json('deleted two')) + await s.store.trash(m) + fs.writeFileSync(s.file('same-2'), s.json('agent two')) + fs.writeFileSync(s.file('same-2-restored'), s.json('agent two again')) + await s.store.restore(m) + assert.deepEqual([s.onDisk('same-2'), s.onDisk('same-2-restored'), s.onDisk('same-2-restored-2')].map((x) => x.messages[0].body), ['agent two', 'agent two again', 'deleted two']) + } finally { s.cleanUp() } +}) + +test('restore: with its id free, the note\'s own file comes back from the trash as it was', async () => { + const s = await setUp() + try { + const n = await s.read('back-1', s.json('back', { custom: 1 })) + const before = fs.readFileSync(s.file('back-1'), 'utf8') + await s.store.trash(n) + await s.store.restore(n) + assert.equal(fs.readFileSync(s.file('back-1'), 'utf8'), before) + assert.equal(n.data.id, 'back-1') + assert.deepEqual(fs.readdirSync(path.join(s.dir, '.trash')), []) + // Its trash copy gone meanwhile: written again from memory. + await s.store.trash(n) + fs.rmSync(path.join(s.dir, '.trash/back-1.json')) + await s.store.restore(n) + assert.equal(s.onDisk('back-1').custom, 1) + } finally { s.cleanUp() } +}) From cbf51895aa9470c6be19bf6b5694fd905bb61674 Mon Sep 17 00:00:00 2001 From: tomeyer97 <107920881+tomeyer97@users.noreply.github.com> Date: Thu, 26 Nov 2026 15:23:02 +0100 Subject: [PATCH 05/17] Adding a note: the box keeps the keyboard, file and folder notes ask for their text, and the new note stays in view Slice: S03 Zeroshot-Run: 01a21811-3b88-7701-bce9-f306b4b8b8c2 --- src/core/text.ts | 6 +- src/notes/commentRanges.ts | 58 ++++++++---- src/notes/create.ts | 81 ++++++++++++++-- src/notes/index.ts | 15 ++- test/integration/main/notesAdd.ts | 152 ++++++++++++++++++++++++++++++ test/integration/suite.ts | 3 + test/notesCreate.test.ts | 18 ++++ 7 files changed, 302 insertions(+), 31 deletions(-) create mode 100644 test/integration/main/notesAdd.ts create mode 100644 test/notesCreate.test.ts diff --git a/src/core/text.ts b/src/core/text.ts index 79f15bf..3e09186 100644 --- a/src/core/text.ts +++ b/src/core/text.ts @@ -13,8 +13,10 @@ const oneSpaced = (s: string) => s.replace(/\s+/g, ' ').trim() /** At most `max` characters: a longer text ends in "…". */ const cut = (t: string, max: number) => (t.length > max ? `${t.slice(0, max - 1)}…` : t) -/** One line of a markdown message (its first with text), as plain text. */ -export function plain(s: string, max = 80): string { +/** One line of a markdown message (its first with text), as plain text. Anything but a string (a note file written + * by hand or by an old bug) is no text. */ +export function plain(s: unknown, max = 80): string { + if (typeof s !== 'string') return '' const line = s.split('\n').find((x) => x.trim()) ?? '' return cut(oneSpaced(markdownAsText(line)), max) } diff --git a/src/notes/commentRanges.ts b/src/notes/commentRanges.ts index 2179470..c50fc0c 100644 --- a/src/notes/commentRanges.ts +++ b/src/notes/commentRanges.ts @@ -1,13 +1,13 @@ -// When VS Code may open a comment box: no commenting range on any line (no "+" bar in the gutter), except for a moment -// while Add Note opens one. +// When VS Code may open a comment box: no commenting range on any line (no "+" bar in the gutter), except in the file +// where Add Note is opening one, until that box is done with. import * as vscode from 'vscode' import { controller } from './ports' import { inNotesFolder } from './notesFolder' import { Poll, sleep, waitUntil } from './timing' -/** Commenting ranges: none, except until this time (a note box being opened). */ -let addingUntil = 0 +/** The file (uri) whose lines are commentable while Add Note's box is open there; undefined: none. */ +let addingIn: string | undefined /** When VS Code last asked for a file's commenting ranges: an editor that has just opened asks before it draws its threads. */ export const rangesAskedAt = new Map<string, number>() @@ -15,34 +15,60 @@ export const rangesAskedAt = new Map<string, number>() export const rangeProvider: vscode.CommentingRangeProvider = { provideCommentingRanges: (doc) => { rangesAskedAt.set(doc.uri.toString(), Date.now()) - const adding = Date.now() < addingUntil && vscode.workspace.getWorkspaceFolder(doc.uri) && doc.lineCount && !inNotesFolder(doc.uri) + const adding = doc.uri.toString() === addingIn && vscode.workspace.getWorkspaceFolder(doc.uri) && doc.lineCount && !inNotesFolder(doc.uri) return adding ? [new vscode.Range(0, 0, doc.lineCount - 1, 0)] : [] }, } -/** How long the whole file is commentable for a note box to open. */ -const ADDING_MS = 1500 -/** The provider is set again a little after that, so VS Code asks again and the ranges are gone. */ -const ADDING_OFF_AFTER_MS = 50 /** At least this long before the box is asked for: the comment widgets settle. */ const SETTLE_MS = 120 /** The window asks for the file's ranges again within a round trip: looked for often (it is usually quick), for at * most a second (a slow remote link). */ const RANGES_ASKED: Poll = { tries: 100, everyMs: 10 } -let rangesOff: NodeJS.Timeout | undefined +/** The scheme of a comment box's input editor. */ +export const COMMENT_INPUT = 'comment' -/** The whole file commentable for a moment; resolves once the window has the ranges and a box may be opened. */ -export async function allowComments(ms = ADDING_MS): Promise<void> { - addingUntil = Date.now() + ms +/** What ends the ranges once the person is back in the code. */ +let watching: vscode.Disposable | undefined + +/** The active file commentable; resolves once the window has the ranges and a box may be opened. They stay until + * endComments: never on a timer, as VS Code redraws every comment widget of the file when the ranges change and the + * open box loses the keyboard. */ +export async function allowComments(): Promise<void> { + const u = vscode.window.activeTextEditor?.document.uri.toString() + watching?.dispose() + watching = undefined + addingIn = u controller().commentingRangeProvider = rangeProvider const t0 = Date.now() - clearTimeout(rangesOff) - rangesOff = setTimeout(() => { controller().commentingRangeProvider = rangeProvider }, ms + ADDING_OFF_AFTER_MS) // At least SETTLE_MS, and until the window has asked for the file's ranges again: over a slow link that round trip // takes longer, and the box would not open. - const u = vscode.window.activeTextEditor?.document.uri.toString() if (u) await waitUntil(() => (rangesAskedAt.get(u) ?? 0) >= t0, RANGES_ASKED) const left = SETTLE_MS - (Date.now() - t0) if (left > 0) await sleep(left) } + +/** The box is open: the ranges end when the person is back in the code (a click or a key in an editor, another + * file), as the box's own close (trash icon) tells the extension nothing. */ +export function endCommentsWhenBack(): void { + watching?.dispose() + const back = vscode.TextEditorSelectionChangeKind + // The box's own input is a text editor too (scheme 'comment'): typing in it is not being back in the code. + const code = (e: vscode.TextEditor | undefined): e is vscode.TextEditor => !!e && e.document.uri.scheme !== COMMENT_INPUT + watching = vscode.Disposable.from( + vscode.window.onDidChangeTextEditorSelection((e) => { + if (code(e.textEditor) && (e.kind === back.Keyboard || e.kind === back.Mouse)) endComments() + }), + vscode.window.onDidChangeActiveTextEditor((e) => { if (code(e) && e.document.uri.toString() !== addingIn) endComments() }), + ) +} + +/** No commenting ranges again (a note saved from the box, the box closed, the person back in the code). */ +export function endComments(): void { + watching?.dispose() + watching = undefined + if (addingIn === undefined) return + addingIn = undefined + controller().commentingRangeProvider = rangeProvider +} diff --git a/src/notes/create.ts b/src/notes/create.ts index 83f2b3f..8d36a83 100644 --- a/src/notes/create.ts +++ b/src/notes/create.ts @@ -5,7 +5,6 @@ import { store } from './ports' import { Loc } from '../core/anchors/anchor' import { chordKey } from '../platform/chordKey' import { log, now } from '../platform/host' -import { showError } from '../platform/run' import { askClaude } from '../ask/run' import { askAlways, askOnQuestion } from '../ask/settings' import { me } from './identity' @@ -17,12 +16,13 @@ import { alternateAnchor } from './alternateAnchor' import { relPath } from '../platform/documents' import { diskLines } from '../platform/documents' import { wfs } from '../platform/workspaceFs' -import { allowComments } from './commentRanges' +import { allowComments, COMMENT_INPUT, endComments, endCommentsWhenBack } from './commentRanges' import { reveal } from './reveal' -import { fireAndForget } from '../platform/run' +import { openThread } from './threadView' import { linesAt } from './place' import { hint } from './hint' import { OncePerSubmit } from './submit' +import { Poll, waitUntil } from './timing' /** The note box's words. */ export const NOTE_OPTIONS: vscode.CommentOptions = { prompt: 'Reply', placeHolder: 'Note or reply…' } @@ -62,7 +62,9 @@ async function newNote(folder: vscode.WorkspaceFolder, body: string, place: () = } const OWN_FILES = "No notes on Code Notes' own files" -const SAVE_INSIDE = 'save the file inside the open folder to add notes to it.' +/** A file not saved inside the open folder: no mistake, a limit (an offer to save it, not an error). */ +const SAVE_INSIDE = 'Save the file inside the open folder to add notes to it.' +export const SAVE_AS = 'Save As…' /** Why no note can go on `uri` (undefined: one can): it is one of Code Notes' own files (the notes, their README), * or not saved inside the open folder. */ @@ -72,19 +74,32 @@ function canAnnotate(uri: vscode.Uri, untitled = false): string | undefined { return undefined } -/** Says why no note was made (canAnnotate): an error for a file outside the folder, else a short hint. */ +/** Says why no note was made on one of Code Notes' own files: a short hint. */ function refuse(why: string): undefined { - if (why === SAVE_INSIDE) fireAndForget(showError(why), 'create: showError') - else hint(why) + hint(why) return undefined } +/** A file not saved inside the folder (untitled, or outside): Save As…, then `then` on the saved file's editor, with + * the same selection, once it is inside the folder (saved outside again: the same offer). */ +async function saveFirst<T>(doc: vscode.TextDocument, selection: vscode.Selection | undefined, then: (e: vscode.TextEditor) => Promise<T>): Promise<T | undefined> { + const pick = await vscode.window.showInformationMessage(SAVE_INSIDE, SAVE_AS) + if (pick !== SAVE_AS) return undefined + const saved = await vscode.workspace.saveAs(doc.uri) + if (!saved) return undefined + const e = await vscode.window.showTextDocument(saved, selection ? { selection } : {}) + if (canAnnotate(e.document.uri, e.document.isUntitled)) return saveFirst(e.document, selection, then) + return then(e) +} + const created = new vscode.EventEmitter<Note>() /** A note was made and saved by the person (its first message is theirs). */ export const onDidCreateNote = created.event export async function createNote(doc: vscode.TextDocument, loc: Loc, body: string, selection?: NoteData['selection'], extra?: Record<string, unknown>): Promise<Note | undefined> { const why = canAnnotate(doc.uri) + // The note is kept until the file is saved: then it goes on the saved file's same lines. + if (why === SAVE_INSIDE) return saveFirst(doc, undefined, (e) => createNote(e.document, loc, body, selection, extra)) if (why) return refuse(why) const folder = vscode.workspace.getWorkspaceFolder(doc.uri)! const n = await newNote(folder, body, async () => ({ ...(await linesAt(doc, loc, folder)), ...(selection ? { selection } : {}) }), extra) @@ -123,6 +138,8 @@ type Origin = /** What follows the making of a note, by where it came from (one place for these rules). */ async function afterCreate(n: Note, origin: Origin): Promise<void> { if (origin === 'path') await reveal(n) + // The note just posted stays in view, with its Ask Claude, instead of folding at once. + if (origin === 'box') openThread(n) if (origin === 'question' ? askOnQuestion() : askAlways()) await askClaude(n) } @@ -138,17 +155,23 @@ export async function addNote(): Promise<void> { const editor = vscode.window.activeTextEditor if (!editor) return noEditor() const why = canAnnotate(editor.document.uri, editor.document.isUntitled) + // Saved: the box opens on the same lines. + if (why === SAVE_INSIDE) { await saveFirst(editor.document, editor.selection, () => addNote()); return } if (why) return refuse(why) await allowComments() try { await vscode.commands.executeCommand('workbench.action.addComment') } catch (e) { + endComments() log().warn(`the comment box did not open (${e}): the one-line box instead`) await addQuickNote() return } + endCommentsWhenBack() // On a big block the box is off screen: bring the last line (and the box below it) into view. const end = selectedLines(editor).end + openBox = boxKey(editor.document.uri, end) + await restoreDraft(openBox) const showBox = () => { const vis = editor.visibleRanges[0] const roomBelow = vis ? vis.end.line - end : 0 @@ -167,7 +190,7 @@ async function noEditor(): Promise<void> { } /** A note on a whole file or folder: from the explorer, the editor tab, or the palette (the active file). */ -export async function addPathNote(uri?: vscode.Uri, text?: string): Promise<Note | undefined> { +export async function addPathNote(uri?: vscode.Uri, text?: unknown): Promise<Note | undefined> { uri = uri instanceof vscode.Uri ? uri : vscode.window.activeTextEditor?.document.uri const folder = uri && vscode.workspace.getWorkspaceFolder(uri) if (!uri || !folder) { hint('Pick a file or folder in the Explorer first'); return undefined } @@ -184,7 +207,9 @@ export async function addPathNote(uri?: vscode.Uri, text?: string): Promise<Note return undefined } const title = `Note on ${isDir ? 'folder' : 'file'} ${file}${isDir ? '/' : ''}` - const body = text ?? (await vscode.window.showInputBox({ title, placeHolder: 'Your note or question', ignoreFocusOut: true }))?.trim() + // A menu passes its own argument here (the editor tab's {groupId, editorIndex}, the Explorer's selected uris): only + // a string is the note's text. + const body = typeof text === 'string' ? text.trim() : (await vscode.window.showInputBox({ title, placeHolder: 'Your note or question', ignoreFocusOut: true }))?.trim() if (!body) return undefined // No lines: range 1-1, no anchor (neither is written to the file). const noLines = { range: { start: 1, end: 1 }, anchor: { text: '', before: '', after: '' } } @@ -225,12 +250,14 @@ const creating = new OncePerSubmit<vscode.CommentThread>() export const noteFromNewThread = async (reply: vscode.CommentReply): Promise<Note | undefined> => { const t = reply.thread + endComments() return creating.run(t, async () => { const body = reply.text.trim() if (!body) { t.dispose(); hint('Empty note: not saved'); return undefined } // no empty shell const doc = await vscode.workspace.openTextDocument(t.uri) const r = t.range ?? new vscode.Range(0, 0, 0, 0) t.dispose() + drafts.delete(boxKey(doc.uri, rangeLines(doc, r).end)) return createNote(doc, rangeLines(doc, r), body, partialSelection(doc, r)) }) } @@ -246,3 +273,39 @@ export const createFromThread = async (reply: vscode.CommentReply) => { const n = await noteFromNewThread(reply) if (n) await afterCreate(n, 'box') } + +/** Drafts of closed note boxes, by file and line: VS Code deletes an empty box it folds, text and all. */ +const drafts = new Map<string, string>() +/** Where Add Note last opened its box. */ +let openBox: string | undefined +const boxKey = (uri: vscode.Uri, line: number) => `${uri.toString()}#${line}` + +/** A box's input is a text editor of its own (scheme 'comment') once it has the keyboard: up to a second. */ +const BOX_INPUT: Poll = { tries: 20, everyMs: 50 } +const boxInput = () => { + const e = vscode.window.activeTextEditor + return e?.document.uri.scheme === COMMENT_INPUT ? e : undefined +} + +/** The draft of a box closed on these lines, back in the box just opened there. */ +async function restoreDraft(key: string): Promise<void> { + const text = drafts.get(key) + if (text === undefined || !(await waitUntil(() => !!boxInput(), BOX_INPUT))) return + const input = boxInput()! + if (input.document.getText()) return + if (await input.edit((b) => b.insert(new vscode.Position(0, 0), text))) drafts.delete(key) +} + +/** Esc in a new note box: closed, its draft kept in memory (Add Note on those lines puts it back). The box is emptied + * first, so VS Code folds it without asking to discard the text. */ +export async function closeNoteBox(): Promise<void> { + const input = boxInput() + if (input) { + const text = input.document.getText() + if (openBox && text.trim()) drafts.set(openBox, text) + const all = new vscode.Range(0, 0, input.document.lineCount, 0) + if (text) await input.edit((b) => b.delete(all)) + } + await vscode.commands.executeCommand('workbench.action.hideComment') + endComments() +} diff --git a/src/notes/index.ts b/src/notes/index.ts index 9106328..4d99915 100644 --- a/src/notes/index.ts +++ b/src/notes/index.ts @@ -14,7 +14,7 @@ import { openBroken, restoreBroken } from './broken' import { followNotesOnDisk } from './changedOnDisk' import { rangeProvider } from './commentRanges' import { followContextKeys } from './contextKeys' -import { addNote, addPathNote, addQuickNote, askFromThread, createFromThread, NOTE_OPTIONS, onDidCreateNote } from './create' +import { addNote, addPathNote, addQuickNote, askFromThread, closeNoteBox, createFromThread, NOTE_OPTIONS, onDidCreateNote } from './create' import { followCursor } from './cursor' import { createDecorations, followNotes as decorationsFollow } from './decorations' import { findNote } from './find' @@ -43,6 +43,9 @@ export type { NotesFeaturePorts } from './ports' /** A file in the notes folder (the store watches it: no note or step is on it). */ export { inNotesFolder } from './notesFolder' +/** Closes a new note box, keeping its draft (create.ts closeNoteBox). */ +export const CLOSE_NOTE_BOX = 'codeNotes.closeNoteBox' + /** The id VS Code knows the notes' comment threads by. */ const CONTROLLER_ID = 'codeNotes' @@ -80,8 +83,8 @@ export async function activateNotes(context: vscode.ExtensionContext, ports: Not readHidden: () => stored().get(STATE.hiddenSessions), writeHidden: (names) => stored().set(STATE.hiddenSessions, names), }) - // No commenting-range bar on every line (–): the whole file is commentable only while Add Note opens its - // box (Ctrl+' C, the command); VS Code asks again when the provider is set. + // No commenting-range bar on every line (–): a file is commentable only from Add Note (Ctrl+' C, the command) + // until its box is done with (commentRanges.ts); VS Code asks again when the provider is set. controller.commentingRangeProvider = rangeProvider controller.options = NOTE_OPTIONS fireAndForget(setCtx(NOTES_CTX.showResolved, false), 'notes: setCtx codeNotes.showResolved') @@ -93,12 +96,16 @@ export async function activateNotes(context: vscode.ExtensionContext, ports: Not // A note you made is read (its first message is yours): stored in the background (a round trip to the window). onDidCreateNote((n) => fireAndForget(setSeen([[n.data.id, 1]]), 'seen')), takeLinks((link) => stepLink(ports.layout, link)), + // Esc in a new note box (the key is the manifest's); not in the command table yet, so registered here. + vscode.commands.registerCommand(CLOSE_NOTE_BOX, async () => { + try { await closeNoteBox() } finally { drafting.fire(false) } + }), ) registerCommands(context, { // Adding, replying, asking from a thread. A note being written pauses what plays (its code stays put under it). [Cmd.add]: chord(() => { drafting.fire(true); return addNote() }), [Cmd.addQuick]: addQuickNote, - [Cmd.addPathNote]: (uri?: vscode.Uri, text?: string) => addPathNote(uri, text), + [Cmd.addPathNote]: (uri?: vscode.Uri, text?: unknown) => addPathNote(uri, text), [Cmd.askFromThread]: askFromThread, [Cmd.createFromThread]: async (...a: Parameters<typeof createFromThread>) => { try { return await createFromThread(...a) } finally { drafting.fire(false) } diff --git a/test/integration/main/notesAdd.ts b/test/integration/main/notesAdd.ts new file mode 100644 index 0000000..d5ec5f2 --- /dev/null +++ b/test/integration/main/notesAdd.ts @@ -0,0 +1,152 @@ +// Adding a note: the box keeps the keyboard (chord and palette), a saved note stays open, Esc closes the box and keeps +// its draft, file and folder notes ask for their text, an untitled file offers Save As…. +// Source: src/notes/create.ts, src/notes/commentRanges.ts. +import * as vscode from 'vscode' +import * as fs from 'fs' +import assert from 'assert' +import { settle, test } from '../helpers' +import { cdp, ui } from '../devtools' +import { closeAllEditors, ctx, snap, until, wsPath } from './context' + +/* eslint-disable @typescript-eslint/no-explicit-any */ +/** Tests that type for real in the workbench page; skipped without the DevTools connection. */ +const devtools = { when: () => cdp, whenNot: 'no DevTools' } + +/** The file these tests add notes to (written by the first test). */ +const ADDING = () => wsPath('src', 'adding.ts') +const LINES = Array.from({ length: 40 }, (_, i) => `export const line${i + 1} = ${i + 1}`).join('\n') + '\n' + +/** Not wired to a key here: the manifest's Esc runs it (src/notes/index.ts). */ +const CLOSE_NOTE_BOX = 'codeNotes.closeNoteBox' + +// VS Code's own DOM (read off VS Code 1.147): the comment box is a .review-widget, its input in a .comment-form. +/** The keyboard is in a comment box's input. */ +const boxFocused = async () => (await ui()).evaluate(() => !!(globalThis as any).document.activeElement?.closest?.('.review-widget .comment-form')) +/** What the comment box that has the keyboard holds ('' for none). */ +const boxText = async () => (await ui()).evaluate(() => { + const form = (globalThis as any).document.activeElement?.closest?.('.review-widget .comment-form') + return (form?.querySelector('.view-lines')?.textContent ?? '').replace(/ /g, ' ') +}) +/** Where the keyboard is and which comment boxes are drawn (for a failing wait's message). */ +const whereNow = async () => (await ui()).evaluate(() => { + const d = (globalThis as any).document, a = d.activeElement + const forms = [...d.querySelectorAll('.review-widget .comment-form')].map((f: any) => `${f.offsetParent ? 'shown' : 'hidden'}:${f.className}`) + return `focus: ${a?.tagName}.${String(a?.className).slice(0, 80)} in review-widget: ${!!a?.closest?.('.review-widget')}; widgets: ${d.querySelectorAll('.review-widget').length}; forms: ${forms.join(' | ')}` +}) +/** Waits for the keyboard in a comment box's input; says where it is instead on a timeout. */ +async function untilBoxFocused(): Promise<void> { + try { await until('the keyboard in the note box', () => boxFocused()) } catch (e) { throw new Error(`${(e as Error).message} (${await whereNow()})`, { cause: e }) } +} +/** Any comment box input on screen holds `text`. */ +const boxShows = async (text: string) => (await ui()).evaluate((t) => + [...(globalThis as any).document.querySelectorAll('.review-widget .comment-form .view-lines')].some((v: any) => (v.textContent ?? '').replace(/ /g, ' ').includes(t)), text) + +async function openAdding(line: number, selectTo?: number): Promise<vscode.TextEditor> { + if (!fs.existsSync(ADDING())) fs.writeFileSync(ADDING(), LINES) + const editor = await vscode.window.showTextDocument(vscode.Uri.file(ADDING())) + editor.selection = new vscode.Selection(line, 0, selectTo ?? line, selectTo === undefined ? 0 : 10) + return editor +} + +/** Types into the box that has the keyboard after `ms` (as a person would), and checks it landed there. */ +async function typeLater(editor: vscode.TextEditor, text: string, ms: number): Promise<void> { + const page = await ui() + await untilBoxFocused() + await settle(ms, 'a person reads the box before typing') + assert.ok(await boxFocused(), 'the box still has the keyboard') + await page.keyboard.type(text) + await until(`"${text}" in the box`, async () => (await boxText()).includes(text)) + assert.ok(!editor.document.isDirty, 'nothing typed into the code') +} + +const noteWith = (body: string) => snap().notes.find((n: any) => n.messages[0].body === body) + +export const notesAddTests = [ + test('Ctrl+\' C: the box keeps the keyboard; typed text lands in it; the saved note stays open', async () => { + const editor = await openAdding(4) + const page = await ui() + await page.keyboard.press("Control+'") + await page.keyboard.press('c') + await typeLater(editor, 'zz', 2000) + await settle(3000, 'five seconds after the chord') + assert.ok(await boxFocused(), 'the box has the keyboard five seconds on') + await page.keyboard.press('Control+Enter') + const n = await until('the note saved', () => noteWith('zz')) + await until('its thread open with the posted note', () => ctx.api.thread(n.id)?.collapsibleState === vscode.CommentThreadCollapsibleState.Expanded) + }, devtools), + + test('Add Note from the palette on a selection: typing goes into the box, not over the selected code', async () => { + const editor = await openAdding(10, 12) + await vscode.commands.executeCommand('codeNotes.add') + await typeLater(editor, 'zz2', 2000) + await (await ui()).keyboard.press('Control+Enter') + await until('the note saved', () => noteWith('zz2')) + assert.ok(!editor.document.isDirty, 'the selected code is untouched') + }, devtools), + + test('Esc on an empty new note box closes it, with VS Code\'s default settings and no question asked', async () => { + const editor = await openAdding(30) + await vscode.commands.executeCommand('codeNotes.add') + await untilBoxFocused() + await vscode.commands.executeCommand(CLOSE_NOTE_BOX) + await until('the box closed', async () => !(await boxFocused())) + assert.equal(await (await ui()).locator('.monaco-dialog-box').count(), 0, 'no "discard?" dialog') + assert.ok(!editor.document.isDirty) + }, devtools), + + test('closing a new note box with a draft asks nothing and keeps it: Add Note on that line puts it back', async () => { + // VS Code's default settings: folding a box that holds text would ask to discard it. + const editor = await openAdding(20) + await vscode.commands.executeCommand('codeNotes.add') + await typeLater(editor, 'draft kept', 500) + await vscode.commands.executeCommand(CLOSE_NOTE_BOX) + await until('the box closed', async () => !(await boxShows('draft kept'))) + assert.equal(await (await ui()).locator('.monaco-dialog-box').count(), 0, 'no "discard?" dialog') + editor.selection = new vscode.Selection(20, 0, 20, 0) + await vscode.commands.executeCommand('codeNotes.add') + await until('the draft back in the box', async () => (await boxText()).includes('draft kept')) + assert.ok(!noteWith('draft kept'), 'a closed box saves nothing') + await (await ui()).keyboard.press('Control+Enter') + await until('the draft saved as the note', () => noteWith('draft kept')) + assert.ok(!editor.document.isDirty) + await closeAllEditors() + }, devtools), + + test('Add Code Note… from an editor tab or the Explorer asks for the text; Esc saves nothing', async () => { + await openAdding(0) + const file = vscode.Uri.file(ADDING()) + const folder = vscode.Uri.file(wsPath('src')) + const noteFiles = () => (fs.existsSync(ctx.notesDir) ? fs.readdirSync(ctx.notesDir).length : 0) + const before = noteFiles() + // What VS Code passes from an editor tab's menu, then from the Explorer's (the selected uris). + for (const [uri, arg] of [[file, { groupId: 0, editorIndex: 1 }], [folder, [folder]]] as const) { + const done = vscode.commands.executeCommand('codeNotes.addPathNote', uri, arg) + await settle(500, 'the input box opens') + if (cdp) assert.ok(await (await ui()).locator('.quick-input-widget').isVisible(), 'the input box is shown') + await vscode.commands.executeCommand('workbench.action.closeQuickOpen') + assert.equal(await done, undefined, 'no note') + } + assert.equal(noteFiles(), before, 'no note file written') + if (!cdp) return + const done = vscode.commands.executeCommand<any>('codeNotes.addPathNote', file, { groupId: 0, editorIndex: 1 }) + await until('the input box', () => ui().then((p) => p.locator('.quick-input-widget').isVisible())) + await (await ui()).keyboard.type('Is this file needed?') + await (await ui()).keyboard.press('Enter') + const n = await done + assert.equal(n?.data.messages[0].body, 'Is this file needed?', 'the typed text is the note') + }), + + test('Add Note on an untitled file offers Save As…, not an error', async () => { + const doc = await vscode.workspace.openTextDocument({ content: 'one\ntwo\n' }) + const editor = await vscode.window.showTextDocument(doc) + editor.selection = new vscode.Selection(0, 0, 1, 3) + void vscode.commands.executeCommand('codeNotes.add') + const page = await ui() + const toast = page.locator('.notification-toast', { hasText: /save the file inside the open folder/i }).first() + await until('the message', () => toast.isVisible()) + assert.ok(await toast.locator('.monaco-button', { hasText: 'Save As…' }).isVisible(), 'a Save As… button') + assert.ok(!(await toast.locator('.codicon-error').count()), 'not an error') + await vscode.commands.executeCommand('notifications.clearAll') + await vscode.commands.executeCommand('workbench.action.revertAndCloseActiveEditor') + }, devtools), +] diff --git a/test/integration/suite.ts b/test/integration/suite.ts index 069af03..4250463 100644 --- a/test/integration/suite.ts +++ b/test/integration/suite.ts @@ -11,6 +11,7 @@ import { journeyTourTests } from './main/journeyTour' import { keysAndMapTests } from './main/keysAndMap' import { journeyFilesTests } from './main/journeyFiles' import { notesReviewTests } from './main/notesReview' +import { notesAddTests } from './main/notesAdd' import { writeJourneyTests } from './main/writeJourney' import { repoJourneysTests } from './main/repoJourneys' import { requestsTests } from './main/requests' @@ -39,6 +40,8 @@ export const chapters: Chapter[] = [ covers: 'a journey\'s files changing under it journeys/, gitRenames.ts, anchor.ts, compact.ts' }, { name: 'notesReview', file: 'main/notesReview.ts', tests: notesReviewTests, ...fakeClaude, covers: 'findings: R, severity, history, suggestions, file and folder notes notes/, sidebar/, noteModel.ts' }, + { name: 'notesAdd', file: 'main/notesAdd.ts', tests: notesAddTests, ...fakeClaude, + covers: 'adding a note: the box keeps the keyboard, Esc, file and folder notes, untitled files notes/create.ts, notes/commentRanges.ts' }, { name: 'writeJourney', file: 'main/writeJourney.ts', tests: writeJourneyTests, ...fakeClaude, covers: 'the agent writes a journey write/, writing.ts, claude.ts' }, { name: 'repoJourneys', file: 'main/repoJourneys.ts', tests: repoJourneysTests, ...fakeClaude, diff --git a/test/notesCreate.test.ts b/test/notesCreate.test.ts new file mode 100644 index 0000000..100bfbd --- /dev/null +++ b/test/notesCreate.test.ts @@ -0,0 +1,18 @@ +// Adding a note: what the lists and toasts make of a note whose first message is not text (a menu's argument once +// saved as the body, a note file written by hand). The commands themselves: test/integration/main/notesAdd.ts. +import test from 'node:test' +import assert from 'node:assert/strict' +import { describeNotes, noteTitle, plain } from '../src/core/text' + +const note = (body: unknown) => ({ data: { messages: [{ author: 'a', role: 'human' as const, body: body as string, at: '' }], range: { start: 1, end: 1 } } }) + +test('plain: anything but a string is no text', () => { + for (const body of [{ groupId: 0, editorIndex: 1 }, [{ path: '/src' }], 42, null, undefined]) assert.equal(plain(body), '') + assert.equal(plain(' \n**Why** this?\nmore'), 'Why this?', 'a string as before') +}) + +test('noteTitle and describeNotes: a non-string first message names no note, and throws nothing', () => { + assert.equal(noteTitle(note({ groupId: 0, editorIndex: 1 })), '') + assert.equal(describeNotes([note(['a'])]), '""') + assert.equal(noteTitle(note('Is this file still used?')), 'Is this file still used?') +}) From fd9f91b1f1da081c894170e5bd410926f6d61d08 Mon Sep 17 00:00:00 2001 From: tomeyer97 <107920881+tomeyer97@users.noreply.github.com> Date: Thu, 26 Nov 2026 16:50:05 +0100 Subject: [PATCH 06/17] The journey walk keeps 80 columns of code, survives binary files and folder changes, and the panel leaves its list when a journey opens Slice: S09 Zeroshot-Run: 01a2182b-588d-7521-a94f-7eb2f2b4e5fa --- src/journeys/mapPanel.ts | 10 ++- src/journeys/panel/codeRoom.ts | 25 ++++++ src/journeys/panel/features/author.ts | 6 +- src/journeys/panel/layout.ts | 50 +++++++++-- src/tour/commands.ts | 7 +- src/tour/tutorial.ts | 15 ++-- src/tour/walk.ts | 73 ++++++++++++++--- test/integration/main/journeyTour.ts | 114 +++++++++++++++++++++++++- test/layout.test.ts | 17 ++++ 9 files changed, 284 insertions(+), 33 deletions(-) create mode 100644 src/journeys/panel/codeRoom.ts diff --git a/src/journeys/mapPanel.ts b/src/journeys/mapPanel.ts index 1c6bdde..419ca5e 100644 --- a/src/journeys/mapPanel.ts +++ b/src/journeys/mapPanel.ts @@ -108,7 +108,7 @@ export class MapPanel implements vscode.Disposable { /** What the integration tests read of the panel: what it shows and where, as the page reported it. */ snapshot() { const { story, rendered, focus } = this.probe - return { story, map: this.journey?.j.id, mapTitle: this.tabTitle, mapBoxes: rendered, mapFocus: focus, mapColumn: this.viewColumn } + return { story, map: this.journey?.j.id, mapKey: this.journey?.key, mapTitle: this.tabTitle, mapBoxes: rendered, mapFocus: focus, mapColumn: this.viewColumn } } /** The tab's title (for the integration test). */ get tabTitle(): string | undefined { return this.panel?.title } @@ -296,6 +296,14 @@ export class MapPanel implements vscode.Disposable { this.send({ type: 'deleted', file: fileName(this.shown.uri) }) } + /** The journey shown is now read from another file (key `was` before): the panel shows it from there. */ + follow(was: string, lj: LoadedJourney): void { + if (!this.panel || this.shown?.key !== was) return + this.shown = lj + this.panel.title = this.title() + this.post(true) + } + /** The journey file changed (or another one is shown): send it all again; otherwise only the tour position. */ update(lj?: LoadedJourney): void { if (!this.panel || !this.shown) return diff --git a/src/journeys/panel/codeRoom.ts b/src/journeys/panel/codeRoom.ts new file mode 100644 index 0000000..f940e1c --- /dev/null +++ b/src/journeys/panel/codeRoom.ts @@ -0,0 +1,25 @@ +// What a step change does to the journey panel when the code beside it has under 80 columns (pure: unit-tested in +// test/layout.test.ts). The README promises the walk never leaves the code that narrow: the panel shrinks to the share +// that leaves the code its columns, or, with no such share, the walk goes on with the step card alone. + +/** Keep the layout, set the panel to this share of the editor area, or close the panel (the step card alone). */ +export type CodeRoomMove = 'keep' | 'cardOnly' | { share: number } + +export interface CodeRoomInput { + /** The code group's width (px). */ + codePx: number + /** What 80 columns of code need (px: core/panelWidth codeWidth). */ + needPx: number + /** The panel's share that leaves the code its columns (core/panelWidth panelShare; 0: none does). */ + share: number + /** The reader chose this layout (asked for the map's room): it is theirs to keep. */ + readerChose: boolean +} + +/** A pixel or two under is rounding, not a squeezed editor. */ +const SLACK_PX = 2 + +export function codeRoomMove(i: CodeRoomInput): CodeRoomMove { + if (i.readerChose || i.codePx + SLACK_PX >= i.needPx) return 'keep' + return i.share > 0 ? { share: i.share } : 'cardOnly' +} diff --git a/src/journeys/panel/features/author.ts b/src/journeys/panel/features/author.ts index f438a28..57e894d 100644 --- a/src/journeys/panel/features/author.ts +++ b/src/journeys/panel/features/author.ts @@ -54,7 +54,11 @@ function showRuleBreaks(lj: LoadedJourney): void { /** A journey file that can't be read: back to its last good version. */ function restoreLastGood(lj: LoadedJourney): void { const raw = journeys().lastGood.get(lj.key) - if (!raw) return + // Nothing to write back: said, not a click that does nothing. + if (!raw) { + vscode.window.setStatusBarMessage(`$(info) No earlier version of ${lj.j.title} to restore`, 4000) + return + } const restored = () => vscode.window.setStatusBarMessage(`$(check) Restored ${lj.j.title}`, 4000) const failed = (e: unknown) => { log().warn(`journey ${lj.j.id}: restoring its last good version failed: ${e}`) diff --git a/src/journeys/panel/layout.ts b/src/journeys/panel/layout.ts index 2e4aaf5..7c5de81 100644 --- a/src/journeys/panel/layout.ts +++ b/src/journeys/panel/layout.ts @@ -6,8 +6,9 @@ import * as vscode from 'vscode' import type { StateStore } from '../../platform/state' import { STATE } from '../../platform/state' import { OWN_MOVE_MS } from '../../platform/timings' +import { codeRoomMove } from './codeRoom' import { - EditorLayout, expandedOnFocus, groupWidths, grownSince, isFlatRow, layoutOfWidths, listeningShare, panelShare, withRoomForMap, + codeWidth, EditorLayout, expandedOnFocus, groupWidths, grownSince, isFlatRow, layoutOfWidths, listeningShare, panelShare, withRoomForMap, } from '../../core/panelWidth' /** A layout change VS Code reports this soon after the panel set one is the panel's own (the same settling time as @@ -45,6 +46,9 @@ export class PanelLayout { private setAt = 0 /** The groups' widths (px) as last seen settled (side by side only). */ private known: number[] | undefined + /** The reader asked for the map's room (Ctrl+' V) while the panel is open: a step change keeps that layout, even + * with the code under 80 columns. A drag is not told from a window resize, so it doesn't count. */ + private readerChose = false private readonly now: () => number constructor(private readonly d: PanelLayoutDeps) { @@ -94,12 +98,15 @@ export class PanelLayout { return { ...read, panel } } + /** The editor's font size and minimap (what 80 columns of code need). */ + private editorLook(): { fontSize: number; minimap: boolean } { + const ed = vscode.workspace.getConfiguration('editor') + return { fontSize: ed.get<number>('fontSize') ?? 14, minimap: ed.get<boolean>('minimap.enabled') ?? true } + } + /** The panel's share of an editor area `total` px wide (0: no room beside 80 columns of code). */ private shareFor(total: number): number { - const ed = vscode.workspace.getConfiguration('editor') - const fontSize = ed.get<number>('fontSize') ?? 14 - const minimap = ed.get<boolean>('minimap.enabled') ?? true - return panelShare(total, { fontSize, minimap, remembered: this.d.stored.get(STATE.panelShare) }) + return panelShare(total, { ...this.editorLook(), remembered: this.d.stored.get(STATE.panelShare) }) } /** Room for the panel beside the code (80 columns of it), in the editor area as it is now. */ @@ -113,9 +120,9 @@ export class PanelLayout { /** * A walk beside the code: the panel at the reader's width (else 35 %, at most 40 %), never squeezing the code below * 80 columns. A panel that is open is never closed from here (a reload, a row clicked again): too little room keeps - * the layout as it is; only opening a journey decides "the step card only" (cardOnly). The layout never changes on - * its own mid-walk. While an episode is on, the panel is as wide as its animation and player need (listeningShare) - * and the code gets the rest; it is not remembered as the reader's width. + * the layout as it is; only opening a journey decides "the step card only" (cardOnly), and a step change that finds + * the code under 80 columns (keepCodeRoom). While an episode is on, the panel is as wide as its animation and + * player need (listeningShare) and the code gets the rest; it is not remembered as the reader's width. */ async codeGetsMoreRoom(): Promise<void> { const s = await this.sideBySide() @@ -127,6 +134,31 @@ export class PanelLayout { await this.setLayout({ orientation: 0, groups: s.layout.groups.map((_, i) => ({ size: i === s.panel ? share : 1 - share })) }) } + /** + * A step opened with the panel beside it: the code keeps its 80 columns. Squeezed under them (a panel opened by + * Ctrl+' V or left open while the window narrowed), the panel shrinks to leave them, or closes: the step card alone. + * The map's room asked for while the panel is open stays, and so does the listening width. + */ + async keepCodeRoom(): Promise<void> { + if (!this.d.isOpen()) { this.readerChose = false; return } + if (this.d.episodeOn()) return + const s = await this.sideBySide() + if (!s) return + const look = this.editorLook() + const move = codeRoomMove({ + codePx: s.layout.groups[1 - s.panel].size ?? 0, + needPx: codeWidth(80, look.fontSize, look.minimap), + share: this.shareFor(s.total), + readerChose: this.readerChose, + }) + if (move === 'keep') return + if (move === 'cardOnly') { this.cardOnly(); return } + // Already at that share: VS Code's own rounding of the groups, not a squeeze. + if (Math.abs((s.layout.groups[s.panel].size ?? 0) / s.total - move.share) < SHARE_TOLERANCE) return + this.d.log.info('journey panel: the code was under 80 columns; the panel made narrower') + await this.setLayout({ orientation: 0, groups: s.layout.groups.map((_, i) => ({ size: i === s.panel ? move.share : 1 - move.share })) }) + } + /** The layout as it is now is the one to keep (the reader dragged, groups opened or closed, the extension set it). */ async noteLayout(): Promise<void> { this.known = await this.flatWidths() @@ -194,6 +226,7 @@ export class PanelLayout { const mapCol = this.d.viewColumn() const now = await this.flatWidths() if (mapCol === undefined || !now) return + this.readerChose = true const i = mapCol - 1 // Revealing the panel may just have had VS Code expand it (focused at its minimum): the widths before that count. const sizes = grownSince(this.known, now, i) ? [...this.known] : now @@ -205,6 +238,7 @@ export class PanelLayout { /** The walk goes on with the step card in the editor; the panel (if open) closes. Said once per walk. */ cardOnly(): void { + this.readerChose = false if (this.d.isOpen()) this.d.close() this.d.log.info('journey panel: no room beside 80 columns of code; the step card only') vscode.window.setStatusBarMessage(`$(info) Narrow window: the step card only (${this.d.chordKey()} V: the map)`, 6000) diff --git a/src/tour/commands.ts b/src/tour/commands.ts index 656428f..12c1df0 100644 --- a/src/tour/commands.ts +++ b/src/tour/commands.ts @@ -81,10 +81,11 @@ function isHere(lj: LoadedJourney): boolean { /** * The journey's map, when there is room for it beside 80 columns of code; else the step card only. Decided before - * anything opens (the panel never squeezes the code, not even for a moment), and only then: a panel that is open - * stays (it shows this journey now), whatever its width. Returns whether the panel is shown. + * anything opens (the panel never squeezes the code, not even for a moment). A panel that is open stays (it shows + * this journey now); the step opened next gives the code its room (walk.ts keepCodeRoom). Returns whether the panel + * is shown. */ -async function openMapIfRoom(lj: LoadedJourney): Promise<boolean> { +export async function openMapIfRoom(lj: LoadedJourney): Promise<boolean> { const room = !!mapPanel().journey || (await panelFits()) // A step opens next and takes the keyboard: the map doesn't take it first (a slow window gave it the map after). await openMap(lj, room, true) diff --git a/src/tour/tutorial.ts b/src/tour/tutorial.ts index 3547131..ce0df6f 100644 --- a/src/tour/tutorial.ts +++ b/src/tour/tutorial.ts @@ -7,7 +7,8 @@ import { stored } from '../platform/host' import { portsSlot } from '../platform/ports' import type { FromMap as MapMessage } from '../protocol/map' import { atOf, fileOf, LoadedJourney } from '../journeys/steps' -import { openMap } from './commands' +import { openMapIfRoom } from './commands' +import { panelLayout } from './panelLayout' import { pickJourney } from './pick' import { fireAndForget } from '../platform/run' import { STATE } from '../platform/state' @@ -41,12 +42,16 @@ export class Tutorial implements vscode.Disposable { dispose(): void { this.changed.dispose() } - /** Code Notes: Journey Tutorial: the map (the tour's, the last one, or picked) with the tutorial from card 1. */ + /** Code Notes: Journey Tutorial: the map (the tour's, the last one, or picked) with the tutorial from card 1. With + * no room for the panel beside 80 columns of code: the step card alone, as any walk (the status bar says so). */ async start(): Promise<void> { - const lj = this.p.walk.tourJourney() ?? this.p.journeys.byPos(stored().get(STATE.mapJourney)) ?? (await pickJourney()) + const { walk, journeys, mapPanel } = this.p + const lj = walk.tourJourney() ?? journeys.byPos(stored().get(STATE.mapJourney)) ?? (await pickJourney()) if (!lj) return - await openMap(lj) - this.p.mapPanel.send({ type: 'tutorial' }) + // A panel already open may squeeze the code: it gets its room first (or the panel goes). + if (await openMapIfRoom(lj)) await panelLayout().keepCodeRoom() + if (mapPanel.journey) mapPanel.send({ type: 'tutorial' }) + else await walk.goToStep(lj, walk.startStep(lj)) } /** A message from the map's tutorial: a card shown (and what it points at in the editor), skipped or done. */ diff --git a/src/tour/walk.ts b/src/tour/walk.ts index 28322a2..a04a9fa 100644 --- a/src/tour/walk.ts +++ b/src/tour/walk.ts @@ -5,7 +5,7 @@ // the map beside it, the step's row in the list, the beat cleared and the notes folded under the card. import * as vscode from 'vscode' import { beats, codeLinks, isCheckLink, journeys, mapPanel } from './ports' -import { now, stored } from '../platform/host' +import { log, now, stored } from '../platform/host' import { ownSelection } from '../codeLinks/claudeChatLinks' import { atOf, fileOf, LoadedJourney, posKey, stepOf } from '../journeys/steps' import { revealJourneyRow } from '../sidebar/journeyRows' @@ -14,7 +14,7 @@ import { refreshDecorations } from '../notes/decorations' import { wfs } from '../platform/workspaceFs' import type { StepCard } from './card' import { openCheckpoint, stopBy } from './checkTour' -import { panelFits } from './panelLayout' +import { panelFits, panelLayout } from './panelLayout' import { pickJourney } from './pick' import type { ShownAt, TourProbe, TourState } from './state' import type { Narration, WalkController } from './api' @@ -52,6 +52,11 @@ export class Walk { private readonly restored = new vscode.EventEmitter<LoadedJourney>() /** The open step's opening: cancelled when another step starts opening. */ private opening: vscode.CancellationTokenSource | undefined + /** The walked (or browsed) journey's folder and id (posKey): found again when its key changes (Journeys: Folder + * set to a folder with the same journey). */ + private walkedPos: string | undefined + /** Steps whose file VS Code can't show as text (a binary file), by journey key and step id: out of date. */ + private readonly unopenable = new Set<string>() /** The walk moved, or the journeys changed under it (updateTour): what shows the walk follows. */ readonly onDidChange = this.changed.event /** The same moment, as the podcast follows a reader's move (TourApi.onDidMove). */ @@ -104,7 +109,10 @@ export class Walk { } /** A journey's map is open with no step shown (no walk running). */ - browse(lj: LoadedJourney): void { this.tour.browse(lj.key) } + browse(lj: LoadedJourney): void { + this.tour.browse(lj.key) + this.walkedPos = posKey(lj) + } /** More / Less on the step card (`open`: which; none: the other), the card drawn again for the step walked. */ showDetails(open?: boolean): void { @@ -131,6 +139,7 @@ export class Walk { /** The journey file changed during a tour: stay on the same step (by id); if it was removed, its neighbour. */ followStep(): void { const { tour } = this + this.followMovedJourney() const lj = this.tourJourney() if (!lj || !tour.step) return const n = numberOf(lj, tour.stepId) @@ -205,10 +214,25 @@ export class Walk { this.updateTour() } - /** Step number -> 'stale' (its code can't be found), for the map. */ + /** + * The journey's file left the list but the same journey (folder and id) is listed from another file (Journeys: + * Folder changed): the walk and the panel follow it there, not "deleted". + */ + private followMovedJourney(): void { + const { tour } = this + if (!tour.key || journeys().list.has(tour.key)) return + const again = journeys().byPos(this.walkedPos) + if (!again) return + log().info(`journey ${again.j.id}: now read from ${again.uri.path}; the walk follows it`) + const was = tour.key + tour.key = again.key + mapPanel().follow(was, again) + } + + /** Step number -> 'stale' (its code can't be found, or its file can't be shown as text), for the map. */ stepMarks(lj: LoadedJourney): Record<number, string> { const out: Record<number, string> = {} - lj.at.forEach((a, i) => { if (a.stale) out[i + 1] = 'stale' }) + lj.at.forEach((a, i) => { if (a.stale || this.unopenable.has(stepKey(lj, i + 1))) out[i + 1] = 'stale' }) return out } @@ -218,6 +242,7 @@ export class Walk { */ updateTour(): void { const { tour } = this + this.followMovedJourney() const lj = this.tourJourney() this.dropStaleLinkBack() if (tour.key && !lj) fireAndForget(this.end('deleted'), 'walk: end deleted') @@ -377,7 +402,10 @@ export class Walk { return } const editor = await this.openStepFile(lj, n, uri, opts, token) - if (editor) await this.revealStep(lj, n, editor, uri) + if (!editor) return + await this.revealStep(lj, n, editor, uri) + // Beside an open panel the code keeps its 80 columns (the panel narrower, or the step card alone). + if (mapPanel().journey && this.tour.isAt(lj, n)) await panelLayout().keepCodeRoom() } /** The tour is on step n now (another journey's walk ended first), stored, its map and lists follow. False: superseded. */ @@ -399,6 +427,7 @@ export class Walk { } if (tour.step === 0 || tour.key !== lj.key || tour.step !== n) tour.detailsOpen = false tour.key = lj.key + this.walkedPos = posKey(lj) tour.step = n tour.finishedKey = undefined tour.stepId = stepOf(lj, n).id @@ -428,18 +457,24 @@ export class Walk { if (this.superseded(token, lj, n)) return undefined this.markShown(lj, n, file, gone) // Its code was deleted: no code under the card pretending to be it; the card shows what it was. - if (gone || atOf(lj, n).removed) { - card.show(lj, n) - this.showMap(lj, true) - revealJourneyRow(lj) - return undefined - } + if (gone || atOf(lj, n).removed) return this.noCodeToShow(lj, n) const column = this.columnFor(uri) ownSelection(OWN_MOVE_MS) // the file's caret and the step's: not a chat link const shown = { preview: true, preserveFocus: opts.focus === false, ...(column ? { viewColumn: column } : {}) } // Already on screen and the keyboard stays where it is: nothing to show. Its column may be about to change (a // group closing renumbers those after it), and a show by an old number would open a new group. - const editor = (opts.focus === false ? this.shownOutsideMap(uri) : undefined) ?? await vscode.window.showTextDocument(uri, shown) + let editor: vscode.TextEditor + try { + editor = (opts.focus === false ? this.shownOutsideMap(uri) : undefined) ?? await vscode.window.showTextDocument(uri, shown) + } catch (e) { + // VS Code can't show it as text (a binary file): no code to sit on, as for a file that is gone. + log().info(`journey ${lj.j.id} step ${n}: ${file} can't be shown (${e instanceof Error ? e.message : String(e)})`) + if (this.superseded(token, lj, n)) return undefined + this.unopenable.add(stepKey(lj, n)) + this.markShown(lj, n, file, true) + return this.noCodeToShow(lj, n) + } + this.unopenable.delete(stepKey(lj, n)) if (this.superseded(token, lj, n)) return undefined if (editor.viewColumn) { tour.doc = { uri, column: editor.viewColumn } @@ -452,6 +487,15 @@ export class Walk { return editor } + /** Step n has no code to show (its file is gone or can't be shown as text, or its code was deleted): its card is + * in the map, which marks the step out of date. */ + private noCodeToShow(lj: LoadedJourney, n: number): undefined { + this.card.show(lj, n) + this.showMap(lj, true) + revealJourneyRow(lj) + return undefined + } + /** * Step n of `lj` is what the editor shows for the walk now (from `file`; `gone`: that file doesn't exist): where (to * see later that the agent moved it), a notice about another step goes, and no reference is open under it. @@ -570,3 +614,6 @@ export class Walk { await this.goToStep(lj, this.resumeAt(lj) || 1) } } + +/** A step of a journey, by its id (a number moves when steps are inserted). */ +const stepKey = (lj: LoadedJourney, n: number) => `${lj.key}#${stepOf(lj, n)?.id ?? n}` diff --git a/test/integration/main/journeyTour.ts b/test/integration/main/journeyTour.ts index 823499f..451c8b6 100644 --- a/test/integration/main/journeyTour.ts +++ b/test/integration/main/journeyTour.ts @@ -8,8 +8,9 @@ import * as path from 'path' 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 { journey, step, writeJourney, writeLines } from '../fixtures' +import { cdp, codeColumns, ui } from '../devtools' +import { at, bodyOf, closeAllEditors, codeLenses, 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 */ @@ -74,6 +75,38 @@ function writeTopJourney(): string { const stepLenses = async (u: vscode.Uri) => (await lenses(u)).filter((x) => x.includes('◇')) const flowUri = () => vscode.Uri.file(wsPath('src', 'flow.ts')) +/** Runs `fn` with the workbench `width` px wide at zoom 0 (the DevTools window emulation); size and zoom come back. */ +async function withWindowWidth<T>(width: number, fn: (page: import('playwright').Page) => Promise<T>): Promise<T> { + const page = await ui() + const session = await page.context().newCDPSession(page) + const win = () => vscode.workspace.getConfiguration('window') + const zoom = win().inspect<number>('zoomLevel')?.globalValue + await win().update('zoomLevel', 0, vscode.ConfigurationTarget.Global) + await session.send('Emulation.setDeviceMetricsOverride', { width, height: 900, deviceScaleFactor: 1, mobile: false }) + try { return await fn(page) } finally { + await session.send('Emulation.clearDeviceMetricsOverride') + await win().update('zoomLevel', zoom, vscode.ConfigurationTarget.Global) + await session.detach() + } +} + +/** Next, or Previous on the last step: another step of the demo journey, its card shown. */ +async function anotherStep(): Promise<void> { + const n = tour().step + await vscode.commands.executeCommand(n < 3 ? 'codeNotes.nextStep' : 'codeNotes.previousStep') + await until(`a step after ${n}, its card shown`, () => tour().touring && tour().step !== n && !!tour().card, 10000) +} + +/** The demo's steps with one on a binary file (src/sound.mp3) in the middle. */ +const withBinaryStep = () => journey('binary', [ + demoStep('x-a', 'a calls b', 'fa', 'src/flow.ts', 2), + step('src/sound.mp3', 1, 3, { id: 'x-mp3', title: 'A sound', node: 'fb' }), + demoStep('x-c', 'Then c', 'fc', 'src/flow2.ts', 2), +], { title: 'Binary' }) + +/** The demo's steps as the journey "moving", in a folder of the repository (`steps`: from the second on). */ +const moving = (title: string, from = 0) => journey('moving', demoSteps.slice(from).map((x) => ({ ...x, id: `m-${x.id}` })), { title }) + export const journeyTourTests = [ test('v2 journeys load (v1 and broken files skipped); steps are not notes; the group lists titles, new ones marked', async () => { writeLines(wsPath('src', 'flow.ts'), ['export function a() {', ' return b()', '}', '', 'export function b() {', ' return 2', '}']) @@ -362,4 +395,81 @@ export const journeyTourTests = [ writeDemo() await until('back to 3 steps', () => snap().journeys[0]?.steps === 3) }), + + test('a step on a binary file: its card in the map, out of date; Next and a click on it throw nothing, the last card goes', async () => { + // NUL bytes on lines 1-3 and after: binary to VS Code, yet the step's lines are there (not "removed"). + fs.writeFileSync(wsPath('src', 'sound.mp3'), Buffer.from([0x49, 0x44, 0x33, 0, 0x0a, 0, 0, 0x0a, 0, 0, 0x0a, ...new Array<number>(64).fill(0)])) + const file = writeJourney(journeysDir(), withBinaryStep()) + try { + await until('the journey listed', () => snap().journeys.some((x: any) => x.id === 'binary'), 8000) + await vscode.commands.executeCommand('codeNotes.startJourney', 'binary') + await until('step 1, its card above the code', () => tour().journey === 'binary' && tour().step === 1 && tour().card?.title === 'a calls b', 10000) + // VS Code refuses to show the file as text: the command resolves all the same. + await vscode.commands.executeCommand('codeNotes.nextStep') + const inMap = () => tour().step === 2 && !tour().card && tour().panelCard?.title === 'A sound' && tour().panelCard?.stale && tour().map === 'binary' + await until('step 2: no card left on step 1\'s code; its card in the map, out of date', inMap, 10000) + // The step clicked on the map, from step 3. + await vscode.commands.executeCommand('codeNotes.nextStep') + await until('step 3', () => tour().step === 3 && tour().card?.title === 'Then c', 10000) + ctx.api.mapMessage({ type: 'step', n: 2 }) + await until('step 2 again from the map', inMap, 10000) + } finally { + await vscode.commands.executeCommand('codeNotes.endJourney') + fs.rmSync(file, { force: true }) + fs.rmSync(wsPath('src', 'sound.mp3'), { force: true }) + } + await until('the journey gone', () => !snap().journeys.some((x: any) => x.id === 'binary')) + }), + + test('Journeys: Folder changed mid-walk: the walk and the panel follow the same journey in the new folder, never "deleted"', async () => { + const first = writeJourney(wsPath('journeys'), moving('Moving')) + const alt = writeJourney(wsPath('alt-journeys'), moving('Moving (alt)', 1)) + try { + await until('the journey listed', () => snap().journeys.some((x: any) => x.id === 'moving'), 8000) + await vscode.commands.executeCommand('codeNotes.startJourney', 'moving') + await until('walking it at step 1', () => tour().map === 'moving' && tour().journey === 'moving' && tour().step === 1, 10000) + await vscode.commands.executeCommand('codeNotes.nextStep') + await until('step 2', () => tour().step === 2 && tour().card?.title === 'b returns', 10000) + const keyBefore = tour().mapKey + await setting('journeys.folder', 'alt-journeys') + await until('the panel shows the journey from the new folder', () => /\/alt-journeys\/moving\.json$/.test(tour().mapKey ?? '') && tour().mapTitle === 'Moving (alt)', 10000) + assert.notEqual(tour().mapKey, keyBefore) + // The same step (by id), numbered as the new file has it; the walk never ended. + assert.ok(tour().touring && tour().journey === 'moving' && tour().step === 1 && tour().card?.title === 'b returns', `still walking it: ${JSON.stringify({ step: tour().step, card: tour().card?.title })}`) + } finally { + await setting('journeys.folder', undefined) + await vscode.commands.executeCommand('codeNotes.endJourney') + fs.rmSync(first, { force: true }) + fs.rmSync(path.dirname(alt), { recursive: true, force: true }) + } + await until('the journey gone', () => !snap().journeys.some((x: any) => x.id === 'moving')) + }), + + test('a 1440 px window with the sidebar: the code keeps 80 columns, on a step beside the panel and from the tutorial', async () => { + await vscode.commands.executeCommand('codeNotes.openJourney', 'demo') + await until('walking the demo beside its map', () => tour().map === 'demo' && tour().touring && !!tour().card, 10000) + const cols = await withWindowWidth(1440, async (page) => { + const keeps80 = async (what: string) => { + await settle(600, 'the code laid out at 1440 px before its columns are counted') + const c = await codeColumns(page) + assert.ok(c.length && Math.min(...c) >= 80, `${what}: the code keeps 80 columns (${tour().map ? 'beside the panel' : 'the step card alone'}): ${c}`) + return Math.min(...c) + } + // The panel opened in a wider window: the next step gives the code its room. + await anotherStep() + await keeps80('a step with the panel open') + await vscode.commands.executeCommand('codeNotes.endJourney') + await closeAllEditors() + await until('no map', () => tour().map === undefined) + await vscode.commands.executeCommand('codeNotes.tutorial') + await until('the tutorial: its map, or the step card alone', () => tour().map === 'demo' || (tour().touring && !!tour().card), 10000) + if (!tour().touring) await vscode.commands.executeCommand('codeNotes.nextStep') + await until('a step shown', () => tour().touring && !!tour().card, 10000) + await keeps80('the tutorial') + await anotherStep() + return keeps80('the step after it') + }) + await vscode.commands.executeCommand('codeNotes.endJourney') + return `${cols} columns` + }, { when: () => cdp, whenNot: 'no DevTools' }), ] diff --git a/test/layout.test.ts b/test/layout.test.ts index fce12f5..e989d76 100644 --- a/test/layout.test.ts +++ b/test/layout.test.ts @@ -4,6 +4,7 @@ import { codeWidth, DEFAULT_SHARE, expandedOnFocus, GROUP_MIN_PX, grownSince, isFlatRow, layoutOfWidths, LISTENING_MAX_PX, LISTENING_MIN_PX, LISTENING_SHARE, listeningShare, MAP_ROOM_PX, MAX_SHARE, MEASURED_EDITOR, panelShare, widestOther, withRoomForMap, } from '../src/core/panelWidth' +import { codeRoomMove } from '../src/journeys/panel/codeRoom' // What is measured (MEASURED_EDITOR, in src) against what the width model computes from it. @@ -34,6 +35,22 @@ test('the panel: 35 % by default, never squeezing the code under 80 columns', () assert.ok(panelShare(1090, { fontSize: 14, minimap: false }) > 0) }) +test('a step beside an open panel: the code keeps 80 columns (the panel narrower, else the step card alone)', () => { + const needPx = codeWidth(80, 14) + const move = (total: number, panelPx: number, readerChose = false) => + codeRoomMove({ codePx: total - panelPx, needPx, share: panelShare(total, { fontSize: 14 }), readerChose }) + // A 1440 px window with the sidebar (~1090 px of editors), the panel at 40 %: no room for both, the card alone. + assert.equal(move(1090, 436), 'cardOnly') + // A wider window, the panel squeezing the code: the panel gets the share that leaves the code its columns. + const wider = move(1300, 600) + assert.ok(typeof wider === 'object' && 1300 * (1 - wider.share) >= needPx - 1, JSON.stringify(wider)) + // The code has its columns (a pixel short is rounding): nothing changes. + assert.equal(move(1600, 1600 - needPx), 'keep') + assert.equal(move(1600, 1600 - needPx + 1), 'keep') + // The reader asked for the map's room: theirs to keep. + assert.equal(move(1090, 436, true), 'keep') +}) + test('the reader\'s width is kept (also above 40 %), within the code\'s 80 columns', () => { assert.equal(panelShare(2000, { fontSize: 14, remembered: 0.5 }), 0.5) assert.equal(panelShare(2000, { fontSize: 14, remembered: 0.25 }), 0.25) From 65867d45f93ee0781283254dcf215931d0dd53ac Mon Sep 17 00:00:00 2001 From: tomeyer97 <107920881+tomeyer97@users.noreply.github.com> Date: Thu, 26 Nov 2026 16:50:05 +0100 Subject: [PATCH 07/17] The Notes view: one row shape, sessions read as a severity list, honest counts, session commands that finish the job and never block Slice: S07 Zeroshot-Run: 01a2183d-225c-7f53-b86e-b62996991096 --- src/notes/model/query.ts | 12 +++- src/notes/sessions.ts | 20 +++++-- src/sidebar/noteGroups.ts | 47 +++++++-------- src/sidebar/noteNodes.ts | 11 ++-- src/sidebar/notesRows.ts | 25 ++++---- src/sidebar/rowText.ts | 20 ++++++- test/integration/main/notes.ts | 10 ++++ test/integration/main/notesReview.ts | 62 +++++++++++++++++--- test/notesModel.test.ts | 19 ++++++ test/notesRows.test.ts | 86 +++++++++++++++++++++------- 10 files changed, 231 insertions(+), 81 deletions(-) diff --git a/src/notes/model/query.ts b/src/notes/model/query.ts index b6e62ff..b065615 100644 --- a/src/notes/model/query.ts +++ b/src/notes/model/query.ts @@ -42,6 +42,8 @@ export class NotesQuery { filter: Filter = 'all' showResolved = false groupMode: GroupMode = 'file' + /** Its thread is open in the editor: hiding its session leaves it (closing it would drop a reply being typed). */ + keepInEditor: (id: string) => boolean = () => false constructor(private readonly facts: NoteFacts) {} @@ -54,7 +56,8 @@ export class NotesQuery { if (this.facts.isCheck(n)) return false const open = n.data.status === 'open' switch (f) { - case 'unread': return this.facts.unread(n) > 0 || this.facts.revealed() === n.data.id + // Hidden resolved notes stay hidden here too (an unread resolve still shows under All). + case 'unread': return (open || this.showResolved) && (this.facts.unread(n) > 0 || this.facts.revealed() === n.data.id) case 'stale': return !!n.data.stale && (open || this.showResolved) default: return open || this.showResolved || this.facts.unread(n) > 0 } @@ -65,8 +68,11 @@ export class NotesQuery { isHidden(n: Note): boolean { return this.facts.hiddenSessions().has(sessionOf(n)) } - /** A note whose session is hidden is not drawn in the editor (unless it was just opened from the list). */ - hiddenInEditor(n: Note): boolean { return this.facts.revealed() !== n.data.id && this.isHidden(n) } + /** A note whose session is hidden is not drawn in the editor (unless it was just opened from the list, or its + * thread is open). */ + hiddenInEditor(n: Note): boolean { + return this.facts.revealed() !== n.data.id && this.isHidden(n) && !this.keepInEditor(n.data.id) + } /** Grouped by session: when there are sessions and the person chose it. */ bySessions(): boolean { return this.groupMode === 'session' && this.facts.notes().some((x) => x.data.session) } diff --git a/src/notes/sessions.ts b/src/notes/sessions.ts index be1fa40..e252cf9 100644 --- a/src/notes/sessions.ts +++ b/src/notes/sessions.ts @@ -9,17 +9,24 @@ import { hint } from './hint' import { isRow, SessionRow } from './model/rows' import { folderName } from './notesFolder' import { resolve, trash } from './status' +import { markRead, unread } from './seen' +import { threads } from '../threads/sync' -/** Hides or shows sessions; `only` shows these and hides every other one. */ +/** The note's thread is open in the editor. Folding or removing it would make VS Code ask (modal) whether to drop + * a reply being typed, and hold every later command until answered. */ +const threadOpen = (id: string) => threads.get(id)?.collapsibleState === vscode.CommentThreadCollapsibleState.Expanded + +/** Hides or shows sessions; `only` shows these and hides every other one. An open thread stays (see threadOpen). */ export async function setSessionHidden(names: string[], hidden: boolean, only = false): Promise<void> { const model = notesModel() + model.query.keepInEditor = threadOpen const h = only ? new Set(visibleNotes().map(sessionOf).filter((x) => !names.includes(x))) : new Set(model.hiddenSessions()) if (!only) for (const name of names) hidden ? h.add(name) : h.delete(name) await model.setHiddenSessions(h, () => { - // The note just opened from the list is folded when its session is hidden now. + // The note just opened from the list, folded, is no longer shown when its session is hidden now. const id = revealedId() const r = id ? byId(id) : undefined - if (!r || !h.has(sessionOf(r))) return + if (!r || !h.has(sessionOf(r)) || threadOpen(r.data.id)) return forgetRevealed(r.data.id) foldThread(r.data.id) }) @@ -53,8 +60,13 @@ export const showOnlySession = withSession((session) => setSessionHidden([sessio export const showAllSessions = () => notesModel().setHiddenSessions([]) export const resolveSession = withSession(async (session) => { - const open = visibleNotes().filter((n) => sessionOf(n) === session && n.data.status === 'open') + const notes = visibleNotes().filter((n) => sessionOf(n) === session) + const open = notes.filter((n) => n.data.status === 'open') await resolve(open, session ? ` in "${session}"` : '') + // Cancelled (or not saved): nothing else. Done: the ones resolved by others are read too, or they stay listed as new. + if (open.some((n) => n.data.status === 'open')) return + const resolvedUnread = notes.filter((n) => n.data.status === 'resolved' && unread(n) > 0) + if (resolvedUnread.length) await markRead(resolvedUnread) // "Show only" this session, and it is done: show the others again. const h = notesModel().hiddenSessions() const rest = new Set(visibleNotes().filter((n) => n.data.status === 'open').map(sessionOf)) diff --git a/src/sidebar/noteGroups.ts b/src/sidebar/noteGroups.ts index 4d7f45c..5e88cf2 100644 --- a/src/sidebar/noteGroups.ts +++ b/src/sidebar/noteGroups.ts @@ -15,21 +15,25 @@ export const sevRank = (n: Note) => SEV_RANK[n.data.severity ?? 'medium'] export const rowOrder = (a: Note, b: Note) => sevRank(a) - sevRank(b) || (a.data.target ? 0 : 1) - (b.data.target ? 0 : 1) || order(a, b) +/** The order of notes in a session (a review, read as one list): severity, then by file, then as under a file row. */ +export const sessionOrder = (a: Note, b: Note) => + sevRank(a) - sevRank(b) || a.data.file.localeCompare(b.data.file) || rowOrder(a, b) + /** What a session's row counts: its notes listed, those with unread replies, and resolved ones out of all of its notes. */ export interface SessionCounts { unread: number; resolved: number; total: number } -/** What a file row counts: its stale notes and its unread messages. */ -export interface FileCounts { stale: number; newMessages: number } +/** What a file row counts: its stale notes and its notes with something unread. */ +export interface FileCounts { stale: number; unread: number } /** What a row shows that depends on the other rows. */ export interface RowFacts { - /** The note is a row of its own (no file row above it): the row names its file. */ + /** No file row above the note's row (in a session, or in the Journeys view): the row names its file. */ alone(n: Note): boolean session(name: string): SessionCounts file(key: string): FileCounts } const NO_SESSION: SessionCounts = { unread: 0, resolved: 0, total: 0 } -const NO_FILE: FileCounts = { stale: 0, newMessages: 0 } +const NO_FILE: FileCounts = { stale: 0, unread: 0 } /** What the layout is made from (the notes model's answers, read once). */ export interface LayoutInput { @@ -43,31 +47,27 @@ export interface LayoutInput { unread(n: Note): number } -/** The key of the file row a note falls in, under `scope`. */ -const fileKeyOf = (n: Note, scope: string | undefined) => sessionFileKey(scope, n.folder.uri, n.data.file) - export class NotesLayout implements RowFacts { - /** The top rows: note files that can't be used, the sessions (when grouped by session), then the notes by file. */ + /** The top rows: note files that can't be used, the sessions (when grouped by session), then the files. */ readonly roots: NoteNode[] private readonly kids = new Map<string, NoteNode[]>() private readonly parents = new Map<string, NoteNode>() private readonly sessions = new Map<string, SessionCounts>() private readonly files = new Map<string, FileCounts>() - /** How many listed notes fall in each file row's key. */ - private readonly perFile = new Map<string, number>() + /** The notes listed under a file row (by id). */ + private readonly inFile = new Set<string>() constructor(private readonly input: LayoutInput) { const grouped = input.listed.filter((n) => input.scopeOf(n) !== undefined) const loose = input.listed.filter((n) => input.scopeOf(n) === undefined) - this.roots = [...input.broken, ...this.sessionRows(grouped), ...this.fileRows(loose, undefined)] + this.roots = [...input.broken, ...this.sessionRows(grouped), ...this.fileRows(loose)] } children(node: NoteNode): NoteNode[] { return this.kids.get(keyOf(node)) ?? [] } parent(node: NoteNode): NoteNode | undefined { return this.parents.get(keyOf(node)) } - /** At most one listed note in its file (itself, or one other when it is not listed: a step's question). */ - alone(n: Note): boolean { return (this.perFile.get(fileKeyOf(n, this.input.scopeOf(n))) ?? 0) <= 1 } + alone(n: Note): boolean { return !this.inFile.has(n.data.id) } session(name: string): SessionCounts { return this.sessions.get(name) ?? NO_SESSION } @@ -93,32 +93,29 @@ export class NotesLayout implements RowFacts { resolved: all.filter((n) => n.data.status === 'resolved').length, total: all.length, }) - this.under(node, this.fileRows(list, name)) + // A review reads as one list, most severe first: no file rows inside a session. + this.under(node, [...list].sort(sessionOrder).map(noteNode)) return node }).sort((x, y) => hasNew(x.notes) - hasNew(y.notes) || latest(y.notes).localeCompare(latest(x.notes))) } - /** Notes grouped by file (or folder); a file with one note is that note's row. */ - private fileRows(list: Note[], session: string | undefined): NoteNode[] { + /** Notes grouped by file (or folder), by path; a file with one note is a file row too (one shape to scan). */ + private fileRows(list: Note[]): NoteNode[] { const groups = new Map<string, FileNode>() for (const n of list) { - const key = fileKeyOf(n, session) - if (!groups.has(key)) groups.set(key, fileNode(n, session, [])) + const key = sessionFileKey(undefined, n.folder.uri, n.data.file) + if (!groups.has(key)) groups.set(key, fileNode(n, [])) groups.get(key)!.notes.push(n) - this.perFile.set(key, (this.perFile.get(key) ?? 0) + 1) + this.inFile.add(n.data.id) } // A stable order: the list must not jump while an agent writes; unread shows as dots. - // In a session (a review): the most severe findings first, then by file. - const worst = (g: FileNode) => (session !== undefined ? Math.min(...g.notes.map(sevRank)) : 0) - return [...groups.values()] - .sort((a, b) => worst(a) - worst(b) || a.file.localeCompare(b.file)) - .map((g) => (g.notes.length === 1 ? noteNode(g.notes[0]) : this.fileRow(g))) + return [...groups.values()].sort((a, b) => a.file.localeCompare(b.file)).map((g) => this.fileRow(g)) } private fileRow(g: FileNode): FileNode { this.files.set(g.key, { stale: g.notes.filter((n) => n.data.stale).length, - newMessages: g.notes.reduce((a, n) => a + this.input.unread(n), 0), + unread: g.notes.filter((n) => this.input.unread(n) > 0).length, }) this.under(g, [...g.notes].sort(rowOrder).map(noteNode)) return g diff --git a/src/sidebar/noteNodes.ts b/src/sidebar/noteNodes.ts index c41df2f..8453841 100644 --- a/src/sidebar/noteNodes.ts +++ b/src/sidebar/noteNodes.ts @@ -7,8 +7,8 @@ import { NodeCache } from './nodeCache' /** A session's group (a review), and the notes listed in it. */ export type SessionNode = { kind: 'session'; name: string; notes: Note[] } -/** The notes of one file (or folder) under a session (`session`) or at the top. */ -export type FileNode = { kind: 'file'; key: string; folder: vscode.WorkspaceFolder; file: string; notes: Note[]; session?: string; isFolder?: boolean } +/** The notes of one file (or folder), at the top (a session lists its notes without file rows). */ +export type FileNode = { kind: 'file'; key: string; folder: vscode.WorkspaceFolder; file: string; notes: Note[]; isFolder?: boolean } export type NoteRowNode = { kind: 'note'; note: Note } /** A note file that can't be used: its title and its last good version, when known. */ export type BrokenNode = { kind: 'broken'; uri: string; why: string; title?: string; known?: Note } @@ -34,11 +34,10 @@ export const noteNode = (note: Note) => kept<NoteRowNode>({ kind: 'note', note } export const sessionNode = (name: string, notes: Note[]) => kept<SessionNode>({ kind: 'session', name, notes }) -/** The file row of note `n` under `session` (or at the top), holding `notes`. */ -export function fileNode(n: Note, session: string | undefined, notes: Note[]): FileNode { +/** The file row of note `n`, holding `notes`. */ +export function fileNode(n: Note, notes: Note[]): FileNode { return kept<FileNode>({ - kind: 'file', key: sessionFileKey(session, n.folder.uri, n.data.file), folder: n.folder, file: n.data.file, notes, - ...(session !== undefined ? { session } : {}), + kind: 'file', key: sessionFileKey(undefined, n.folder.uri, n.data.file), folder: n.folder, file: n.data.file, notes, ...(n.data.target === 'folder' ? { isFolder: true } : {}), }) } diff --git a/src/sidebar/notesRows.ts b/src/sidebar/notesRows.ts index b370b5e..44645ee 100644 --- a/src/sidebar/notesRows.ts +++ b/src/sidebar/notesRows.ts @@ -4,8 +4,8 @@ import * as vscode from 'vscode' import { journeys } from './ports' import { askErrors, asking } from '../ask/run' -import { mine } from '../notes/identity' -import { unread } from '../notes/seen' +import { evMine, mine } from '../notes/identity' +import { seenCount, unread } from '../notes/seen' import { Note } from '../notes/store' import { ago, isolate, plain, plural, rangeLabel } from '../core/text' import { placement } from '../notes/location' @@ -17,7 +17,7 @@ import { Cmd } from '../platform/commands' import { BrokenNode, FileNode, NoteNode, NoteRowNode, SessionNode } from './noteNodes' import { FileCounts, RowFacts, SessionCounts } from './noteGroups' import { rowContext } from './rowContext' -import { shortDir, whereLabel } from './rowText' +import { groupCounts, resolvedLabel, shortDir, unreadMessages, whereLabel } from './rowText' export const SEV_ICON: Record<Severity, [string, string]> = { high: ['flame', 'charts.red'], medium: ['triangle-up', 'charts.orange'], low: ['triangle-down', 'charts.blue'], nit: ['dash', 'descriptionForeground'], @@ -41,8 +41,7 @@ function sessionItem(node: SessionNode, c: SessionCounts): vscode.TreeItem { const item = new vscode.TreeItem(node.name || 'Notes', fold) item.id = `session:${node.name}` item.description = description([ - `${node.notes.length}`, - c.unread ? `${c.unread} new` : '', + ...groupCounts(node.notes.length, c.unread), c.resolved ? `${c.resolved}/${c.total} resolved` : '', hidden ? 'hidden' : '', ]) @@ -73,8 +72,7 @@ function fileItem(node: FileNode, c: FileCounts): vscode.TreeItem { const item = new vscode.TreeItem(baseName(node.file), vscode.TreeItemCollapsibleState.Expanded) item.id = `file:${node.key}` item.description = description([ - `${node.notes.length}`, - c.newMessages ? `${c.newMessages} new` : '', + ...groupCounts(node.notes.length, c.unread), c.stale ? `${c.stale} stale` : '', shortDir(node.file), ]) @@ -88,8 +86,10 @@ function fileItem(node: FileNode, c: FileCounts): vscode.TreeItem { /** What a note's row shows besides its text. */ interface NoteFlags { - /** Replies not seen yet. */ + /** Messages and others' resolves not seen yet. */ unread: number + /** Messages not seen yet (a resolve is not one: the row says who resolved it). */ + newMessages: number /** Its file (or folder) is not found. */ gone: boolean /** No file row above it: the row names the file. */ @@ -99,7 +99,8 @@ interface NoteFlags { function noteItem(node: NoteRowNode, alone: boolean): vscode.TreeItem { const n = node.note const d = n.data - const flags: NoteFlags = { unread: unread(n), gone: placement.missing(d.id), alone } + const newMessages = unreadMessages(n, seenCount(n), mine) + const flags: NoteFlags = { unread: unread(n), newMessages, gone: placement.missing(d.id), alone } const item = new vscode.TreeItem({ label: noteLabel(n, flags) }) item.id = `note:${d.id}` item.description = noteDescription(n, flags) @@ -127,12 +128,12 @@ function noteDescription(n: Note, f: NoteFlags): string { const d = n.data const replies = d.messages.length - 1 return description([ - f.unread ? `${f.unread} new` : '', + f.newMessages ? `${f.newMessages} new` : '', claudeState(d.id), f.gone ? 'file not found' : d.stale ? 'stale' : '', - d.status === 'resolved' ? 'resolved' : '', + d.status === 'resolved' ? resolvedLabel(n, evMine) : '', whereLabel(n, f.alone), - !f.unread && replies > 0 ? plural(replies, 'reply', 'replies') : '', + !f.newMessages && replies > 0 ? plural(replies, 'reply', 'replies') : '', ]) } diff --git a/src/sidebar/rowText.ts b/src/sidebar/rowText.ts index af69a06..5f43afa 100644 --- a/src/sidebar/rowText.ts +++ b/src/sidebar/rowText.ts @@ -1,10 +1,24 @@ // Short texts of the Code Notes rows that follow rules worth testing. No vscode here. import type { Note } from '../notes/store' +import type { Message, NoteEvent } from '../core/format/noteModel' import { baseName } from '../core/paths' -import { rangeLabel } from '../core/text' +import { plural, rangeLabel } from '../core/text' -/** Where a note's row says it is. Under a file row its lines (`L12`); alone, the row names the file: `app.ts:12`, a - * whole-file note `app.ts`, a folder note `src/`. */ +/** A group row's counts, each with its noun: `2 notes`, `1 new` (notes with something unread). */ +export const groupCounts = (notes: number, unread: number): string[] => [plural(notes, 'note'), unread ? `${unread} new` : ''] + +/** Messages after the `seen` first ones, not the person's own: a note row's "n new" (a resolve is not a message). */ +export const unreadMessages = (n: Note, seen: number, mine: (m: Message) => boolean): number => + n.data.messages.slice(seen).filter((m) => !mine(m)).length + +/** A resolved note's state: "resolved by X" when someone else resolved it last, else "resolved". */ +export function resolvedLabel(n: Note, mine: (e: NoteEvent) => boolean): string { + const ev = [...(n.data.events ?? [])].reverse().find((e) => e.type === 'resolved') + return ev && !mine(ev) ? `resolved by ${ev.by}` : 'resolved' +} + +/** Where a note's row says it is. Under a file row its lines (`L12`); elsewhere (in a session, in the Journeys view) + * the row names the file: `app.ts:12`, a whole-file note `app.ts`, a folder note `src/`. */ export function whereLabel(n: Note, alone: boolean): string { if (!alone) return rangeLabel(n) const base = baseName(n.data.file) diff --git a/test/integration/main/notes.ts b/test/integration/main/notes.ts index e407bb4..7904b71 100644 --- a/test/integration/main/notes.ts +++ b/test/integration/main/notes.ts @@ -229,6 +229,16 @@ export const notesTests = [ await until('all shown', () => bySession('Visual review')?.hasThread && bySession('Classic review')?.hasThread) }), + test('Show Only This Session leaves an open thread open (folding it would drop a reply being typed)', async () => { + const classic = needs(bySession('Classic review'), 'sessions: hide, show only, show all') + await vscode.commands.executeCommand('codeNotes.reveal', { thread: await until('thread', () => ctx.api.thread(classic.id)) }) + await until('its thread open', () => bySession('Classic review')?.threadExpanded) + await vscode.commands.executeCommand('codeNotes.showOnlySession', { kind: 'session', name: 'Visual review', notes: [] }) + await quiet(600, 'the open thread folded or removed') + assert.ok(bySession('Classic review')?.hasThread && bySession('Classic review')?.threadExpanded, 'the open thread is left as it was') + await vscode.commands.executeCommand('codeNotes.showAllSessions') + }), + test('invalid ranges, statuses and empty notes are reported as unreadable', async () => { // Reported, not shown as normal notes. const brokenBefore = snap().broken diff --git a/test/integration/main/notesReview.ts b/test/integration/main/notesReview.ts index f070917..ede9863 100644 --- a/test/integration/main/notesReview.ts +++ b/test/integration/main/notesReview.ts @@ -81,8 +81,8 @@ export const notesReviewTests = [ await until('grouped by session', () => snap().groupBy === 'session' && notesTree().some((l: string) => l.startsWith('session:Review'))) const rows = notesRows() const session = rows.findIndex((r) => r.kind === 'session' && r.label.startsWith('Review')) - // Under the session, the notes under its file row (session > file > note). - const kids = rows.slice(session + 1, session + 7).filter((r) => r.kind === 'note' && r.depth === 2) + // Under the session, its notes as one list (no file rows inside a session). + const kids = rows.slice(session + 1, session + 5).filter((r) => r.kind === 'note' && r.depth === 1) const shown = kids.map((r) => r.text).join(' | ') assert.deepEqual(kids.map((r) => r.label), ['high finding', 'none finding', 'critical finding', 'low finding'], `severity order: ${shown}`) assert.deepEqual(kids.map((r) => r.icon), ['flame', 'circle-filled', kids[2]?.icon, 'triangle-down'], `icons (no severity, unread: the blue dot): ${shown}`) @@ -95,18 +95,64 @@ export const notesReviewTests = [ assert.equal(readJson(notePath(CRITICAL)).events.length, 1) }), - test('Group by File / Session toggles; single-note files are one row', async () => { - // File puts every non-journey note under its file; a file with one note is one row (file:line). + test('two review sessions of 9 findings: 2 + 18 rows, each a flat list, most severe first, "file:line"', async () => { + // The same 3 files in both sessions: no file rows repeated per session. + const sevs = ['low', 'high', 'nit', 'medium', 'high', 'low', 'medium', 'nit', 'high'] + const files = ['src/flow.ts', 'src/flow2.ts', 'src/renamed.ts'] + const written: string[] = [] + for (const s of ['Perf A', 'Perf B']) { + sevs.forEach((severity, i) => written.push(writeNote(ctx.notesDir, noteId(`2005${s.endsWith('A') ? 0 : 1}${i}`, `prf${s.at(-1)!.toLowerCase()}${i}`), + agentNote(files[i % 3], 1 + Math.floor(i / 3), `${s} finding ${i}`, { session: s, severity })))) + } + await until('both reviews listed', () => notesRows().filter((r) => /^Perf [AB] finding/.test(r.label)).length === 18) + const rows = notesRows() + const all = rows.map((r) => r.text).join('\n') + for (const name of ['Perf A', 'Perf B']) { + const at = rows.findIndex((r) => r.kind === 'session' && r.label === name) + assert.ok(at >= 0 && rows[at].depth === 0, `a session row for ${name}:\n${all}`) + assert.match(rows[at].description, /^9 notes · 9 new\b/, `the session's counts say what they count:\n${all}`) + const kids = rows.slice(at + 1, at + 10) + assert.ok(kids.every((r) => r.kind === 'note' && r.depth === 1), `9 note rows right under the session:\n${all}`) + assert.deepEqual(kids.map((r) => r.icon), ['flame', 'flame', 'flame', 'triangle-up', 'triangle-up', 'triangle-down', 'triangle-down', 'dash', 'dash'], `most severe first:\n${all}`) + assert.ok(kids.every((r) => /\b(flow|flow2|renamed)\.ts:\d+\b/.test(r.description)), `each row names its file and line:\n${all}`) + } + for (const p of written) fs.unlinkSync(p) + await until('reviews gone', () => !notesRows().some((r) => r.kind === 'session' && /^Perf [AB]$/.test(r.label))) + }), + + test('Resolve Session: the notes others resolved are read too, so the session leaves the list', async () => { + writeNote(ctx.notesDir, noteId('200600', 'dno1'), agentNote('src/flow.ts', 2, 'Done open finding', { session: 'Done review' })) + await until('loaded', () => notesRows().some((r) => r.label === 'Done open finding')) + await vscode.commands.executeCommand('codeNotes.markAllRead') // one read open note: Resolve Session asks nothing + await until('read', () => snap().notes.every((x: any) => x.unread === 0)) + const byAgent = { status: 'resolved', events: [{ type: 'resolved', by: 'claude', role: 'agent', at: now() }] } + writeNote(ctx.notesDir, noteId('200601', 'dnr1'), agentNote('src/flow.ts', 3, 'Done by agent 1', { session: 'Done review', ...byAgent })) + writeNote(ctx.notesDir, noteId('200602', 'dnr2'), agentNote('src/flow2.ts', 1, 'Done by agent 2', { session: 'Done review', ...byAgent })) + await until('the agent\'s resolved notes listed as new', () => notesRows().filter((r) => /^Done by agent/.test(r.label) && /^1 new · resolved by claude\b/.test(r.description)).length === 2) + void vscode.commands.executeCommand('codeNotes.resolveSession', { kind: 'session', name: 'Done review', notes: [] }) // an Undo toast: not awaited + await until('no row of the session left', () => !notesRows().some((r) => /^Done (open finding|by agent)|^Done review$/.test(r.label))) + assert.ok(snap().notes.filter((x: any) => x.session === 'Done review').every((x: any) => x.unread === 0 && x.status === 'resolved'), 'none counts as new') + }), + + test('Group by File: every file is a file row, also with one note; files by path', async () => { + const lone = writeNote(ctx.notesDir, noteId('200700', 'lon1'), agentNote('src/flow2.ts', 2, 'Lone note')) await vscode.commands.executeCommand('codeNotes.groupByFile') - await until('grouped by file', () => snap().groupBy === 'file') + await until('grouped by file, the lone note listed', () => snap().groupBy === 'file' && notesRows().some((r) => r.label === 'Lone note')) const rows = notesRows() const all = rows.map((r) => r.text).join('\n') const top = rows.filter((r) => r.depth === 0) assert.ok(!rows.some((r) => r.kind === 'session' && r.label.startsWith('Review')), 'no Review session in file mode') assert.ok(!rows.some((r) => r.kind === 'journeys') && rowsOf(journeysTree()).some((r) => r.kind === 'jgroup' && r.label.startsWith('All')), 'journeys stay in their own view') - assert.ok(top.some((r) => r.kind === 'file' && r.label.startsWith('flow.ts')), `flow.ts row:\n${all}`) - const solo = top.find((r) => r.kind === 'note' && /renamed\.ts:\d+/.test(r.description)) ?? top.find((r) => r.kind === 'note' && /\.ts:\d+/.test(r.text)) - assert.ok(solo, `a single-note file is one row with file:line:\n${all}`) + assert.ok(top.every((r) => r.kind === 'file' || r.kind === 'broken'), `only file rows at the top:\n${all}`) + assert.ok(rows.filter((r) => r.kind === 'note').every((r) => r.depth === 1 && !/\.ts:\d+/.test(r.description)), `every note under its file row, by its lines:\n${all}`) + const files = top.filter((r) => r.kind === 'file') + const flow = files.find((r) => r.label === 'flow.ts'), renamed = files.find((r) => r.label === 'renamed.ts') + assert.ok(flow && /^\d+ notes?\b/.test(flow.description), `flow.ts row with its count:\n${all}`) + assert.ok(renamed && files.indexOf(flow!) < files.indexOf(renamed), `files by path (src/flow.ts before src/renamed.ts):\n${all}`) + const at = rows.findIndex((r) => r.kind === 'file' && r.label === 'flow2.ts') + assert.ok(at >= 0 && rows[at].description.startsWith('1 note · 1 new') && rows[at + 1]?.label === 'Lone note' && rows[at + 1].description === '1 new · L2', `a one-note file is a file row of one:\n${all}`) + fs.unlinkSync(lone) + await until('lone note gone', () => !notesRows().some((r) => r.label === 'Lone note')) }), test('an agent\'s resolve on disk is recorded and unread; resolve/reopen lines in the thread', async () => { diff --git a/test/notesModel.test.ts b/test/notesModel.test.ts index c0c9a76..2e4b15b 100644 --- a/test/notesModel.test.ts +++ b/test/notesModel.test.ts @@ -46,6 +46,25 @@ test('query: the filter lists open notes, resolved ones when shown or unread, st assert.equal(q.count('all'), 4) }) +test('query: Unread with resolved notes hidden lists no resolved note (an unread resolve stays under All)', () => { + const open = note('o'), done = note('r', { status: 'resolved' }) + const q = new NotesQuery(facts([open, done], { unread: () => 1, revealed: () => 'r' })) + assert.equal(q.listedUnder(done, 'unread'), false) + assert.equal(q.listedUnder(open, 'unread'), true) + assert.equal(q.listedUnder(done, 'all'), true) + assert.equal(q.count('unread'), 1) + q.showResolved = true + assert.equal(q.listedUnder(done, 'unread'), true) +}) + +test('query: an open thread is never hidden in the editor with its session', () => { + const a = note('a', { session: 'Review' }) + const q = new NotesQuery(facts([a], { hiddenSessions: () => new Set(['Review']) })) + assert.equal(q.hiddenInEditor(a), true) + q.keepInEditor = (id) => id === 'a' + assert.equal(q.hiddenInEditor(a), false) +}) + test('query: a check question is never listed; the note just opened is listed as unread', () => { const a = note('a'), b = note('b') const opened: { id?: string } = {} diff --git a/test/notesRows.test.ts b/test/notesRows.test.ts index d8d21e5..7e76b48 100644 --- a/test/notesRows.test.ts +++ b/test/notesRows.test.ts @@ -10,7 +10,7 @@ import { NodeCache } from '../src/sidebar/nodeCache' import { BrokenNode, keyOf, NoteNode, noteNode } from '../src/sidebar/noteNodes' import { LayoutInput, NotesLayout, rowOrder } from '../src/sidebar/noteGroups' import { NOTE_FLAGS, rowContext, ROW_WORDS } from '../src/sidebar/rowContext' -import { shortDir, whereLabel } from '../src/sidebar/rowText' +import { groupCounts, resolvedLabel, shortDir, unreadMessages, whereLabel } from '../src/sidebar/rowText' const folder = { uri: { toString: () => 'file:///w' } } as unknown as Note['folder'] @@ -51,50 +51,96 @@ test('node cache: one object per key, its fields replaced; rows not asked for du assert.notEqual(cache.get('gone', { kind: 'y' }), undefined) }) -test('layout: a file with one note is that note\'s row; a file row holds the others, in the sidebar\'s order', () => { +test('layout: every file is a file row, one note or several, by path; notes in the sidebar\'s order', () => { const solo = note('solo', { file: 'src/b.ts' }) const low = note('low', { severity: 'low', range: { start: 2, end: 2 } }) const high = note('high', { severity: 'high', range: { start: 9, end: 9 } }) const whole = note('whole', { target: 'file' }) - const l = layout([solo, low, high, whole]) - assert.deepEqual(shape(l), [['file:|file:///w|src/a.ts', ['note:high', 'note:whole', 'note:low']], 'note:solo']) - const fileRow = l.roots[0] + const first = note('first', { file: 'docs/z.md' }) + const l = layout([solo, low, high, whole, first]) + assert.deepEqual(shape(l), [ + ['file:|file:///w|docs/z.md', ['note:first']], + ['file:|file:///w|src/a.ts', ['note:high', 'note:whole', 'note:low']], + ['file:|file:///w|src/b.ts', ['note:solo']], + ]) + const fileRow = l.roots[1] assert.equal(l.parent(noteNode(low)), fileRow, 'the parent recorded while the rows were made') assert.equal(l.parent(fileRow), undefined) - assert.equal(l.parent(noteNode(solo)), undefined) - assert.ok(l.alone(solo) && !l.alone(low)) + assert.equal(l.parent(noteNode(solo)), l.roots[2], 'a one-note file is a group of one') + assert.ok(!l.alone(solo) && !l.alone(low), 'under a file row: the row says its lines') assert.deepEqual([low, high, whole].sort(rowOrder).map((n) => n.data.id), ['high', 'whole', 'low']) }) -test('layout: by session, sessions with unread notes first then the newest, each with its counts', () => { - const a1 = note('a1', { session: 'A', createdAt: '2026-01-01' }) - const a2 = note('a2', { session: 'A', createdAt: '2026-01-02', status: 'resolved' }) +test('layout: by session, sessions with unread notes first then the newest, each a flat list, most severe first', () => { + const a1 = note('a1', { session: 'A', createdAt: '2026-01-01', severity: 'low' }) + const a2 = note('a2', { session: 'A', createdAt: '2026-01-02', status: 'resolved', file: 'src/b.ts', severity: 'high' }) + const a3 = note('a3', { session: 'A', createdAt: '2026-01-02', file: 'src/a.ts', range: { start: 7, end: 7 }, severity: 'high' }) const b1 = note('b1', { session: 'B', createdAt: '2026-01-03' }) const loose = note('loose', { file: 'src/c.ts' }) - const filteredOut = note('a3', { session: 'A', status: 'resolved', file: 'src/z.ts' }) + const filteredOut = note('a4', { session: 'A', status: 'resolved', file: 'src/z.ts' }) const broken: BrokenNode = { kind: 'broken', uri: 'file:///w/.code-notes/x.json', why: 'bad JSON' } - const l = layout([a1, a2, b1, loose], { - visible: [a1, a2, b1, loose, filteredOut], broken: [broken], + const l = layout([a1, a2, a3, b1, loose], { + visible: [a1, a2, a3, b1, loose, filteredOut], broken: [broken], scopeOf: (n) => n.data.session, unread: (n) => (n === a1 ? 2 : 0), }) assert.deepEqual(shape(l), [ 'broken:file:///w/.code-notes/x.json', - ['session:A', [['file:A|file:///w|src/a.ts', ['note:a1', 'note:a2']]]], + ['session:A', ['note:a3', 'note:a2', 'note:a1']], ['session:B', ['note:b1']], - 'note:loose', + ['file:|file:///w|src/c.ts', ['note:loose']], ]) - assert.deepEqual(l.session('A'), { unread: 1, resolved: 2, total: 3 }, 'resolved out of all of the session\'s notes') - assert.deepEqual(l.file('A|file:///w|src/a.ts'), { stale: 0, newMessages: 2 }) + assert.deepEqual(l.session('A'), { unread: 1, resolved: 2, total: 4 }, 'resolved out of all of the session\'s notes') + assert.ok(l.alone(a1) && l.alone(b1), 'in a session the row names its file') const session = l.roots[1] assert.equal(l.parent(noteNode(b1)), l.roots[2]) - assert.equal(l.parent(l.children(session)[0]), session) + assert.equal(l.parent(noteNode(a2)), session) +}) + +test('layout: two sessions of 9 findings on the same files: 2 + 18 rows, each session most severe first', () => { + const sevs = ['low', 'high', 'nit', 'medium', 'high', 'low', 'medium', 'nit', 'high'] as const + const files = ['src/store.ts', 'src/run.ts', 'src/text.ts'] + const review = (s: string) => sevs.map((severity, i) => note(`${s}${i}`, { session: s, severity, file: files[i % 3], range: { start: i + 1, end: i + 1 } })) + const notes = [...review('P'), ...review('Q')] + const l = layout(notes, { scopeOf: (n) => n.data.session }) + const rows = l.roots.flatMap((r) => [r, ...l.children(r)]) + assert.equal(rows.length, 20) + assert.deepEqual(l.roots.map((r) => r.kind), ['session', 'session']) + for (const s of l.roots) { + const kids = l.children(s).map((r) => (r.kind === 'note' ? r.note.data.severity : r.kind)) + assert.deepEqual(kids, ['high', 'high', 'high', 'medium', 'medium', 'low', 'low', 'nit', 'nit']) + assert.ok(l.children(s).every((r) => r.kind === 'note' && l.alone(r.note))) + } }) -test('layout: a note not listed (a step\'s question) is alone unless two listed notes share its file', () => { +test('layout: a file row counts its notes with something unread and its stale ones', () => { + const a = note('a'), b = note('b', { range: { start: 4, end: 4 }, stale: true }) + const l = layout([a, b], { unread: (n) => (n === a ? 3 : 0) }) + assert.deepEqual(l.file('|file:///w|src/a.ts'), { stale: 1, unread: 1 }) +}) + +test('layout: a note not listed (a step\'s question) has no file row above it: its row names its file', () => { const q = note('q') assert.ok(layout([note('x')]).alone(q)) - assert.ok(!layout([note('x'), note('y')]).alone(q)) + assert.ok(layout([note('x'), note('y')]).alone(q)) +}) + +test('row counts: a group says what it counts; "new" is unread messages; a resolve by someone else says who', () => { + const me = (m: { author: string }) => m.author === 'me' + assert.deepEqual(groupCounts(2, 1), ['2 notes', '1 new']) + assert.deepEqual(groupCounts(1, 0), ['1 note', '']) + // An agent's one-message note, resolved by the agent: one new (the message), not two (message + resolve). + const perf = note('perf', { + status: 'resolved', messages: [{ author: 'review-bot', role: 'agent', body: 'Perf finding 8' }], + events: [{ type: 'resolved', by: 'review-bot', role: 'agent', at: '2026-01-01T00:00:00Z' }], + }) + assert.equal(unreadMessages(perf, 0, me), 1) + assert.equal(unreadMessages(perf, 1, me), 0) + assert.equal(resolvedLabel(perf, (e) => e.by === 'me'), 'resolved by review-bot') + assert.equal(resolvedLabel(perf, (e) => e.by === 'review-bot'), 'resolved') + assert.equal(resolvedLabel(note('r', { status: 'resolved' }), () => false), 'resolved', 'no history: just resolved') + const mine = note('m', { messages: [{ author: 'me', role: 'human', body: 'q' }, { author: 'bot', role: 'agent', body: 'a' }] }) + assert.equal(unreadMessages(mine, 0, me), 1, 'your own message is never new') }) test('where a note row says it is: lines under a file row, else the file, the whole file or the folder', () => { From cf24d97ddbc9ad9094e063e46e1ed8ad14c33645 Mon Sep 17 00:00:00 2001 From: tomeyer97 <107920881+tomeyer97@users.noreply.github.com> Date: Thu, 26 Nov 2026 16:50:06 +0100 Subject: [PATCH 08/17] Ask Claude: a labelled button, never an empty paid run, Stop keeps what was written and stops for real Slice: S05 Zeroshot-Run: 01a2183c-4603-7910-a041-c719b6631848 --- src/ask/index.ts | 4 +- src/ask/prompts.ts | 37 +++++++-- src/ask/queue.ts | 6 +- src/ask/run.ts | 65 ++++++++++++--- src/ask/settle.ts | 21 +++++ src/platform/agent/claude.ts | 2 +- src/platform/agent/claudeCli.ts | 15 +++- src/platform/agent/runner.ts | 18 +++- src/platform/agent/stream.ts | 11 +++ test/claude.test.ts | 61 ++++++++++++++ test/integration/main/ask.ts | 141 ++++++++++++++++++++++++++++++++ 11 files changed, 353 insertions(+), 28 deletions(-) create mode 100644 src/ask/settle.ts create mode 100644 test/integration/main/ask.ts diff --git a/src/ask/index.ts b/src/ask/index.ts index 5d127a6..eed3303 100644 --- a/src/ask/index.ts +++ b/src/ask/index.ts @@ -7,6 +7,7 @@ import { askClaudeCommand, cancelClaudeCommand } from './commands' import { AskPorts, useAskPorts } from './ports' import { announceAskChanges, askStatusItem, createAskQueue } from './run' import { watchClaudeCli } from './settings' +import { agentRunner } from '../platform/agent/runner' export interface AskFeature { /** The status item follows the notes' changes. */ @@ -16,7 +17,8 @@ export interface AskFeature { export function activateAsk(context: vscode.ExtensionContext, ports: AskPorts): AskFeature { useAskPorts(ports) const queue = createAskQueue() - context.subscriptions.push(queue, announceAskChanges(queue)) + // The runner goes with the window: the runs it started stop then (runner.ts dispose). + context.subscriptions.push(queue, announceAskChanges(queue), agentRunner()) // No claude CLI: no Ask Claude anywhere; the setting's description says how to get it. watchClaudeCli(context) registerCommands(context, { diff --git a/src/ask/prompts.ts b/src/ask/prompts.ts index c33491d..2aba662 100644 --- a/src/ask/prompts.ts +++ b/src/ask/prompts.ts @@ -9,11 +9,32 @@ import { UPDATE_ASK } from '../tour/texts' /** The author of Claude's answers in a thread. */ export const CLAUDE_AUTHOR = 'Claude' +/** What ends an answer stopped part-way: the text Claude had written is kept, marked. */ +export const STOPPED_MARK = '_(stopped)_' + +/** An answer Claude was stopped in (its `stopped` field): kept for the person, never sent back as said. */ +export const isStopped = (m: Message) => m.extra?.stopped === true + +/** + * One of Claude's own, whole answers: an agent's message by Claude (the check's questions and other agents' messages + * are agent messages too, and are part of what Claude has not seen). + */ +export const isClaudeAnswer = (m: Message) => m.role === 'agent' && m.author === CLAUDE_AUTHOR && !isStopped(m) + +/** The messages said since Claude's last whole answer (all of them before one), the stopped ones left out. */ +function saidSince(n: Note): { lastAnswer: number; fresh: Message[] } { + const lastAnswer = n.data.messages.map(isClaudeAnswer).lastIndexOf(true) + return { lastAnswer, fresh: n.data.messages.slice(lastAnswer + 1).filter((m) => !isStopped(m)) } +} + /** - * One of Claude's own answers: an agent's message by Claude (the check's questions and other agents' messages are - * agent messages too, and are part of what Claude has not seen). + * Nothing for Claude to answer: its last answer is the newest thing said. Asking then would send an empty turn (a + * paid run that can only say it got nothing); the person replies to ask more. */ -export const isClaudeAnswer = (m: Message) => m.role === 'agent' && m.author === CLAUDE_AUTHOR +export const nothingToAnswer = (n: Note): boolean => saidSince(n).fresh.length === 0 + +/** What is said when Ask has nothing to answer. */ +export const REPLY_TO_ASK_MORE = 'Reply to ask more' /** A prompt written as one sentence or clause per line, read as one paragraph. */ export const lines = (...parts: string[]) => parts.join(' ') @@ -62,9 +83,9 @@ function placeOf(n: Note): string { } /** A follow-up (Claude answered before, in session `claudeSession`): only what was said since its last answer. */ -function followUpPrompt(n: Note, lastAnswer: number): string { +function followUpPrompt(n: Note, said: Message[]): string { const d = n.data - const fresh = d.messages.slice(lastAnswer + 1).map((m) => `${m.author}: ${m.body}`).join('\n\n') + const fresh = said.map((m) => `${m.author}: ${m.body}`).join('\n\n') const changed = d.stale ? ', and the code there changed' : '' return `Follow-up on the same note (now on ${placeOf(n)}${changed}):\n\n${fresh}\n\nAnswer it. ${RULES}` } @@ -81,7 +102,7 @@ function firstPrompt(n: Note, code: string[] | undefined, me: string): string { d.selection ? `It is about this exact text: \`${d.selection.text}\`` : '', d.stale && d.anchor.text ? `Originally:\n${fenced(d.anchor.text)}` : '', 'The conversation so far:', - d.messages.map(said).join('\n\n'), + d.messages.filter((m) => !isStopped(m)).map(said).join('\n\n'), `Answer ${me}'s latest message. ${RULES}`, ] return parts.filter(Boolean).join('\n\n') @@ -89,6 +110,6 @@ function firstPrompt(n: Note, code: string[] | undefined, me: string): string { /** The prompt for a note (`me`: the person's name): a follow-up in Claude's session, else the first one. */ export function claudePrompt(n: Note, code: string[] | undefined, me: string): string { - const lastAnswer = n.data.messages.map(isClaudeAnswer).lastIndexOf(true) - return n.data.claudeSession && lastAnswer >= 0 ? followUpPrompt(n, lastAnswer) : firstPrompt(n, code, me) + const { lastAnswer, fresh } = saidSince(n) + return n.data.claudeSession && lastAnswer >= 0 ? followUpPrompt(n, fresh) : firstPrompt(n, code, me) } diff --git a/src/ask/queue.ts b/src/ask/queue.ts index d0e68d8..f062cba 100644 --- a/src/ask/queue.ts +++ b/src/ask/queue.ts @@ -97,7 +97,11 @@ export class AskQueue implements vscode.Disposable { return true } - dispose(): void { this.changed.dispose() } + /** The window closes: nothing waiting starts any more. */ + dispose(): void { + this.waiting.length = 0 + this.changed.dispose() + } private forget(id: string): boolean { if (!this.failures.delete(id)) return false diff --git a/src/ask/run.ts b/src/ask/run.ts index 451081a..20e4d46 100644 --- a/src/ask/run.ts +++ b/src/ask/run.ts @@ -16,10 +16,11 @@ import { NotesApi, notesChanged, selection, whileTyping } from '../notes/model' import { markRead } from '../notes/seen' import { Note } from '../notes/store' import { plural } from '../core/text' -import { syncThread } from '../threads/sync' +import { syncThread, threads } from '../threads/sync' import { askHandlerOf, askHints } from './handlers' -import { CLAUDE_AUTHOR, claudePrompt, stepAskHint } from './prompts' +import { CLAUDE_AUTHOR, claudePrompt, nothingToAnswer, REPLY_TO_ASK_MORE, stepAskHint, STOPPED_MARK } from './prompts' import { AskQueue, AskRun } from './queue' +import { RunEnds } from './settle' import { skillAccess } from './skills' import { fireAndForget } from '../platform/run' import { STATE } from '../platform/state' @@ -29,6 +30,10 @@ import { HiddenCmd } from '../platform/commands' const MAX_ASKS = 3 let queue: AskQueue | undefined +const ends = new RunEnds() + +/** How long the "Reply to ask more" hint stays in the status bar. */ +const HINT_MS = 5000 /** The queue, kept over a reload through the workspace state (ask/index.ts makes it). */ export function createAskQueue(): AskQueue { @@ -81,9 +86,16 @@ export async function askClaude(n: Note, text?: string): Promise<void> { const handler = askHandlerOf(n) if (handler) return handler.ask(n, text) const q = queue! - if (q.busy(n.data.id)) return + const id = n.data.id + if (q.busy(id)) return + // Claude's answer is the newest thing said: asking now would send it nothing (a paid run that can only say so). + if (nothingToAnswer(n)) { + vscode.window.setStatusBarMessage(REPLY_TO_ASK_MORE, HINT_MS) + return + } + if (ends.tooSoon(id, n.data.messages.length)) { log().info(`note ${id}: Ask right after the run ended: ignored`); return } if (!agentRunner().allowed('answer notes')) return - if (q.add(n.data.id)) await runAsk(n.data.id) + if (q.add(id)) await runAsk(id) } /** The next note in the queue, if any, is answered (on its own: not part of the run that just ended). */ @@ -114,6 +126,8 @@ async function runAsk(id: string): Promise<void> { await answer(id) } finally { queue!.finish(id) + // A failure's Try again is meant at once; only an answer or a stop settles. + if (queue!.state(id) !== 'failed') ends.ended(id, byId(id)?.data.messages.length ?? 0) runNext() } } @@ -139,7 +153,7 @@ async function answer(id: string): Promise<void> { const res = await run.done // The answer is shown without the "answering" row. q.finish(id) - await recordAnswer(id, entry, res) + await recordAnswer(id, entry, { ...res, model: model || res.model }) } /** Claude started on the note with its prompt, skills and model; its progress goes into the thread. */ @@ -166,10 +180,16 @@ async function startAsk(n: Note, cli: string, model: string | undefined, entry: return run } -/** The answer as the newest message of the note, saved; on a failed save the note is left as it was. */ -async function saveAnswer(n: Note, res: AskResult): Promise<boolean> { +/** + * The answer as the newest message of the note, with the model and the seconds it took (shown beside the author), + * saved; a stopped one ends with STOPPED_MARK. On a failed save the note is left as it was. + */ +async function saveAnswer(n: Note, res: AskResult, took: number): Promise<boolean> { const before = { messages: n.data.messages.length, session: n.data.claudeSession } - n.data.messages.push({ author: CLAUDE_AUTHOR, role: 'agent', body: res.text.trim(), at: now() }) + const stopped = !!res.cancelled + const body = stopped ? `${res.text.trim()}\n\n${STOPPED_MARK}` : res.text.trim() + const extra = { ...(res.model ? { model: res.model } : {}), took, ...(stopped ? { stopped: true } : {}) } + n.data.messages.push({ author: CLAUDE_AUTHOR, role: 'agent', body, at: now(), extra }) if (res.sessionId) n.data.claudeSession = res.sessionId if (await notesStore().save(n)) return true n.data.messages.length = before.messages @@ -177,25 +197,44 @@ async function saveAnswer(n: Note, res: AskResult): Promise<boolean> { return false } -/** What the run ended with: cancelled (logged), a failure (kept for the thread), or the answer (saved to the note). */ +/** + * What the run ended with: stopped (what was written so far kept, marked), cancelled otherwise (logged: the window + * closing), a failure (kept for the thread), or the answer (saved to the note). + */ async function recordAnswer(id: string, entry: AskRun, res: AskResult): Promise<void> { const answered = byId(id) - if (res.cancelled) { log().info(`note ${id}: Claude cancelled`); return } + const secs = Math.round((Date.now() - entry.started) / 1000) + if (res.cancelled) { + log().info(`note ${id}: Claude stopped after ${secs}s`) + if (!entry.cancelled || !res.text.trim() || !answered) return + if (!(await saveAnswer(answered, res, secs))) { log().error(`note ${id}: Claude's stopped answer could not be saved`); return } + // The person stopped it while reading it: not new to them. + await markRead([answered]) + return + } if (res.error || !res.text.trim()) { log().error(`note ${id}: Ask Claude failed: ${res.error ?? 'no answer'}`) queue!.fail(id, res.error ?? 'Claude returned no answer.') return } if (!answered) return - if (!(await saveAnswer(answered, res))) { + if (!(await saveAnswer(answered, res, secs))) { log().error(`note ${id}: Claude's answer could not be saved`) queue!.fail(id, "Claude's answer could not be saved.") return } - const secs = Math.round((Date.now() - entry.started) / 1000) log().info(`note ${id}: Claude answered in ${secs}s${res.costUsd ? `, $${res.costUsd.toFixed(3)}` : ''}`) - // The person is looking at this note: the answer counts as read, with its "new" label for the visit. + // Opened from the list: read, with its "new" label for the visit. Streamed into the open thread the person is + // reading (a reply sent from it): read. if (selection().revealed === id) await markRead([answered], answered) + else if (threadInView(answered)) await markRead([answered]) +} + +/** The note's thread is open in an editor on screen. */ +function threadInView(n: Note): boolean { + if (threads.get(n.data.id)?.collapsibleState !== vscode.CommentThreadCollapsibleState.Expanded) return false + const uri = docUri(n).toString() + return vscode.window.visibleTextEditors.some((e) => e.document.uri.toString() === uri) } /** Cancel: stops Claude on the note, takes it out of the queue, or dismisses its failure. */ diff --git a/src/ask/settle.ts b/src/ask/settle.ts new file mode 100644 index 0000000..407fcc8 --- /dev/null +++ b/src/ask/settle.ts @@ -0,0 +1,21 @@ +// When each note's last Claude run ended. An Ask right after it, with nothing said since, is a click meant for Stop +// (the title's Ask and Stop swap under the pointer when an answer lands), not a new question. No vscode API here +// (unit-tested in test/claude.test.ts). + +/** How long after a run ends an Ask with nothing new is ignored. */ +export const SETTLE_MS = 1000 + +export class RunEnds { + private readonly ends = new Map<string, { at: number; messages: number }>() + + constructor(private readonly clock: () => number = Date.now) {} + + /** Note `id`'s run is over (answered, stopped or failed); the note has `messages` messages now. */ + ended(id: string, messages: number): void { this.ends.set(id, { at: this.clock(), messages }) } + + /** An Ask on note `id` (now with `messages` messages) that lands within SETTLE_MS of its run ending, nothing said since. */ + tooSoon(id: string, messages: number): boolean { + const e = this.ends.get(id) + return !!e && e.messages === messages && this.clock() - e.at < SETTLE_MS + } +} diff --git a/src/platform/agent/claude.ts b/src/platform/agent/claude.ts index a877e92..0906ec8 100644 --- a/src/platform/agent/claude.ts +++ b/src/platform/agent/claude.ts @@ -62,7 +62,7 @@ export function claudeArgs(o: AgentRunOptions): string[] { /** The four ways a run ends. */ const outcome = { /** Cancel was pressed: what was written so far, and the session (a follow-up can go on with it). */ - cancelled: (s: FoldState): AskResult => ({ text: s.text, cancelled: true, sessionId: s.result?.sessionId }), + cancelled: (s: FoldState): AskResult => ({ text: s.text, cancelled: true, sessionId: s.result?.sessionId, model: s.model }), /** Claude Code said it was done (with its answer, or its error). */ finished: (s: FoldState & { result: AskResult }): AskResult => s.result, /** The process ended without a result: its exit code and the last lines it printed on stderr. */ diff --git a/src/platform/agent/claudeCli.ts b/src/platform/agent/claudeCli.ts index b65b0d6..ee209a8 100644 --- a/src/platform/agent/claudeCli.ts +++ b/src/platform/agent/claudeCli.ts @@ -87,7 +87,14 @@ export class ClaudeCliFinder { private found?: { key: string; cli?: string } private searching?: { key: string; search: Promise<string | undefined> } - constructor(private readonly search = findClaude) {} + /** + * `onSkipped`: the setting names no program, so `used` (another install, or none) runs instead; said once per + * search, so a typo never quietly runs (and bills) a different install. + */ + constructor( + private readonly search = findClaude, + private readonly onSkipped?: (setting: string, used: string | undefined) => void, + ) {} /** The CLI for `setting`: the answer found before, else a search (one at a time per setting and PATH). */ find(setting: string | undefined): Promise<string | undefined> { @@ -95,7 +102,11 @@ export class ClaudeCliFinder { if (this.found?.key === key) return Promise.resolve(this.found.cli) if (this.searching?.key === key) return this.searching.search const search = this.search(setting).then((cli) => { - if (this.searching?.search === search) { this.found = { key, cli }; this.searching = undefined } + if (this.searching?.search === search) { + this.found = { key, cli } + this.searching = undefined + if (setting && cli !== setting) this.onSkipped?.(setting, cli) + } return cli }) this.searching = { key, search } diff --git a/src/platform/agent/runner.ts b/src/platform/agent/runner.ts index e0d63e3..7b051b3 100644 --- a/src/platform/agent/runner.ts +++ b/src/platform/agent/runner.ts @@ -69,7 +69,7 @@ const MODEL_SETTING: Record<AgentPurpose, string | undefined> = { export class AgentRunner implements vscode.Disposable { readonly inProgress = new InProgress() - private readonly finder = new ClaudeCliFinder() + private readonly finder = new ClaudeCliFinder(undefined, skippedPath) /** Agents run tools in the repository (a skill's own scripts among them): only in a trusted folder. */ trusted(): boolean { return vscode.workspace.isTrusted } @@ -118,8 +118,22 @@ export class AgentRunner implements vscode.Disposable { return agentRun } - dispose(): void { this.inProgress.dispose() } + /** + * The window closes or reloads: note and journey runs stop with it (else a Claude that writes nothing outlives the + * window, still billed). The check's writer keeps running: a reloaded window finds it again by its pid. + */ + dispose(): void { + for (const r of this.inProgress.list()) if (r.purpose !== 'check') r.cancel() + this.inProgress.dispose() + } +} + +/** Claude: Path names no program: said in the log and the status bar, naming it (the newest install runs instead). */ +function skippedPath(setting: string, used: string | undefined): void { + log().warn(`Claude: Path ${setting} is not a program; ${used ? `running ${used} instead` : 'no other claude found'}`) + vscode.window.setStatusBarMessage(`$(warning) Claude: Path ${setting} is not a program`, SKIPPED_HINT_MS) } +const SKIPPED_HINT_MS = 15000 const cliSetting = () => cfg().get<string>('claude.path') || undefined diff --git a/src/platform/agent/stream.ts b/src/platform/agent/stream.ts index 6fb0027..35d412e 100644 --- a/src/platform/agent/stream.ts +++ b/src/platform/agent/stream.ts @@ -13,6 +13,8 @@ export interface AskResult { text: string sessionId?: string costUsd?: number + /** The model that answered, as Claude Code named it at the start. */ + model?: string error?: string errorKind?: AskErrorKind cancelled?: boolean @@ -26,6 +28,8 @@ export type AskErrorKind = 'no-cli' /** The events of a stream-json line that a run reads; every other line is `undefined`. */ export type StreamEvent = + /** The session starts, with the model it runs. */ + | { kind: 'init'; model?: string } /** A new assistant message starts (a paragraph break in the text so far). */ | { kind: 'message-start' } /** More of the answer's text. */ @@ -75,6 +79,8 @@ export function readLine(line: string): StreamEvent | undefined { return isObject(e.event) ? streamEvent(e.event) : undefined case 'assistant': return assistantEvent(e.message) + case 'system': + return e.subtype === 'init' ? { kind: 'init', model: str(e.model) } : undefined case 'result': return { kind: 'result', @@ -109,6 +115,7 @@ export interface FoldState { text: string activity?: string tool?: ToolCall + model?: string result?: AskResult } @@ -116,6 +123,9 @@ export interface FoldState { export function foldEvent(state: FoldState, line: string): boolean { const ev = readLine(line) switch (ev?.kind) { + case 'init': + state.model = ev.model + return false case 'message-start': if (!state.text || state.text.endsWith('\n\n')) return false state.text += '\n\n' @@ -136,6 +146,7 @@ export function foldEvent(state: FoldState, line: string): boolean { text: ev.text ?? state.text, sessionId: ev.sessionId, costUsd: ev.costUsd, + ...(state.model ? { model: state.model } : {}), ...(ev.isError ? { error: ev.text ?? 'Claude reported an error' } : {}), } return true diff --git a/test/claude.test.ts b/test/claude.test.ts index 631a17b..bc56caa 100644 --- a/test/claude.test.ts +++ b/test/claude.test.ts @@ -6,6 +6,10 @@ import * as path from 'path' import { Ask, claudeArgs, foldEvent, MODEL_ALIASES, modelProblem } from '../src/platform/agent/claude' import { FoldState, lastTwoSegments, readLine } from '../src/platform/agent/stream' import { ClaudeCliFinder, findClaude } from '../src/platform/agent/claudeCli' +import { CLAUDE_AUTHOR, claudePrompt, isClaudeAnswer, nothingToAnswer, STOPPED_MARK } from '../src/ask/prompts' +import { RunEnds, SETTLE_MS } from '../src/ask/settle' +import type { Message, NoteData } from '../src/core/format/noteModel' +import type { Note } from '../src/notes/store' const FAKE_CLAUDE = path.join(__dirname, '../../test/fixtures/fake-claude.js') @@ -134,3 +138,60 @@ test('the found CLI is remembered: one search, then known without waiting', asyn assert.equal(searches, 1, 'known() and find() shared the search') assert.equal(finder.known(FAKE_CLAUDE), FAKE_CLAUDE, 'a setting that is a program is known at once') }) + +test('the model that answered is read from the stream\'s start', () => { + const state: FoldState = { text: '' } + assert.equal(foldEvent(state, '{"type":"system","subtype":"init","model":"claude-opus-5-5"}'), false, 'nothing shown') + foldEvent(state, '{"type":"result","result":"done","is_error":false}') + assert.equal(state.result?.model, 'claude-opus-5-5') +}) + +test('Claude: Path that is not a program: said once, naming it; the newest install still runs', async () => { + const [newer] = installs(['2.1.10']) + const home = fs.mkdtempSync(path.join(os.tmpdir(), 'home-')) + const where = { pathVar: newer, home, places: [] } + const skipped: [string, string | undefined][] = [] + const finder = new ClaudeCliFinder((s) => findClaude(s, where), (s, used) => skipped.push([s, used])) + assert.equal(await finder.find('/nonexistent/claude'), path.join(newer, 'claude')) + assert.equal(await finder.find('/nonexistent/claude'), path.join(newer, 'claude')) + finder.known('/nonexistent/claude') + assert.deepEqual(skipped, [['/nonexistent/claude', path.join(newer, 'claude')]], 'once, with the program run instead') + await finder.find(path.join(newer, 'claude')) + await finder.find(undefined) + assert.equal(skipped.length, 1, 'a setting that runs, or none: nothing to say') +}) + +test('an Ask right after a run ends, with nothing said since, is ignored for a second', () => { + let now = 1000 + const ends = new RunEnds(() => now) + assert.equal(ends.tooSoon('n', 3), false, 'no run yet') + ends.ended('n', 3) + now += SETTLE_MS - 1 + assert.equal(ends.tooSoon('n', 3), true, 'the click meant for Stop') + assert.equal(ends.tooSoon('n', 4), false, 'a reply since: a new question') + assert.equal(ends.tooSoon('other', 3), false, 'another note') + now += 1 + assert.equal(ends.tooSoon('n', 3), false, 'a second later: a real Ask') +}) + +/** A note as prompts.ts reads it. */ +const noteOf = (messages: Message[], claudeSession?: string): Note => ({ + data: { id: 'n1', file: 'src/a.ts', range: { start: 1, end: 1 }, status: 'open', anchor: { text: 'x' }, messages, claudeSession } as NoteData, +} as unknown as Note) + +test('Ask on a note Claude answered last: nothing to answer (never an empty run); a stopped answer is asked again', () => { + const q: Message = { author: 'Pat', role: 'human', body: 'Why twice?' } + const a: Message = { author: CLAUDE_AUTHOR, role: 'agent', body: 'Once.' } + const stopped: Message = { author: CLAUDE_AUTHOR, role: 'agent', body: `It is read in\n\n${STOPPED_MARK}`, extra: { stopped: true } } + assert.equal(nothingToAnswer(noteOf([q])), false, 'a question') + assert.equal(nothingToAnswer(noteOf([q, a], 's1')), true, "Claude's answer is the newest") + assert.equal(nothingToAnswer(noteOf([q, a, { ...q, body: 'And here?' }], 's1')), false, 'a reply since') + assert.equal(nothingToAnswer(noteOf([q, { author: 'Reviewer', role: 'agent', body: 'See b.ts' }])), false, "another agent's message") + assert.equal(nothingToAnswer(noteOf([q, a, { ...q, body: 'More?' }, stopped], 's1')), false, 'stopped: still awaits its answer') + assert.equal(isClaudeAnswer(stopped), false) + // The stopped text is the person's, not part of what Claude is asked. + const again = claudePrompt(noteOf([q, a, { ...q, body: 'More?' }, stopped], 's1'), undefined, 'Pat') + assert.match(again, /^Follow-up on the same note .*\n\nPat: More\?\n\nAnswer it\./) + assert.ok(!again.includes(STOPPED_MARK)) + assert.ok(!claudePrompt(noteOf([q, stopped]), ['x'], 'Pat').includes(STOPPED_MARK)) +}) diff --git a/test/integration/main/ask.ts b/test/integration/main/ask.ts new file mode 100644 index 0000000..56d7509 --- /dev/null +++ b/test/integration/main/ask.ts @@ -0,0 +1,141 @@ +// Asking Claude about a note: the labelled Ask Claude button beside Reply (the command given the thread's reply box), +// never an empty run on a note Claude answered last, an answer that says its model and seconds, an answer read in +// the open thread that is not new, Stop keeping what was written, and runs stopped with the window. +// Source: src/ask/commands.ts, src/ask/run.ts, src/ask/prompts.ts, src/platform/agent/runner.ts. +import * as vscode from 'vscode' +import * as fs from 'fs' +import * as os from 'os' +import * as path from 'path' +import assert from 'assert' +import { AgentRunner } from '../../../src/platform/agent/runner' +import { claudeRuns, flag, now, quiet, readJson, test } from '../helpers' +import { fixturePath, writeNote } from '../fixtures' +import { bodyOf, ctx, noteById, setting, snap, until, useFakeClaude, wsPath } from './context' + +/* eslint-disable @typescript-eslint/no-explicit-any */ +/** A note id in the note-ID format; only `tag` matters (a unique name). */ +const noteId = (tag: string) => `20261126-100000-${tag}` + +/** A note with the person's question on src/app.ts line 2, read by the window with its thread. */ +async function question(tag: string, body: string): Promise<{ id: string; file: string }> { + const id = noteId(tag) + const file = writeNote(ctx.notesDir, id, { + file: 'src/app.ts', range: { start: 2, end: 2 }, status: 'open', messages: [{ author: snap().me, role: 'human', body, at: now() }], + }) + await until(`${id} read, with its thread`, () => noteById(id) && ctx.api.thread(id)) + return { id, file } +} + +/** The thread's reply box as VS Code hands it to a button beside Reply. */ +const replyBox = (id: string, text = '') => ({ thread: ctx.api.thread(id), text }) +const lastSaved = (file: string): any => readJson(file).messages.at(-1) + +/** A stand-in for `claude` in a folder of its own: a node script (`body`, after the stream helpers) or a shell one. */ +function standIn(name: string, script: string): string { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'claude-stand-in-')) + const p = path.join(dir, name) + fs.writeFileSync(p, script, { mode: 0o755 }) + return p +} + +/** Writes its first words, then keeps thinking (never ends on its own). */ +const firstWordsThenThinking = () => standIn('claude', [ + '#!/usr/bin/env node', + `const s = require(${JSON.stringify(fixturePath('streamJson.js'))})`, + 's.init()', + "s.textDelta('The envelope has six fields. ')", + 'setInterval(() => {}, 1000)', +].join('\n')) + +/** Writes nothing and keeps running (a Claude still thinking). */ +const silent = () => standIn('claude', '#!/bin/sh\nexec sleep 600\n') + +const alive = (pid: number) => { try { process.kill(pid, 0); return true } catch { return false } } + +export const askTests = [ + test('the Ask Claude button beside Reply asks about that thread\'s note; the answer says its model and seconds', async () => { + await useFakeClaude() + await setting('claude.model', 'sonnet') + try { + const n = await question('button', 'Why is the token read here?') + const before = claudeRuns().length + await vscode.commands.executeCommand('codeNotes.askClaude', replyBox(n.id)) + const answer = await until('answered', () => lastSaved(n.file)?.author === 'Claude' && lastSaved(n.file), 10000) + const run = claudeRuns().slice(before) + assert.equal(run.length, 1, 'one run') + assert.match(flag(run[0], '-p') ?? '', /Why is the token read here\?/, 'about that note') + assert.equal(answer.model, 'sonnet') + assert.equal(typeof answer.took, 'number') + assert.equal(noteById(n.id).messages.at(-1).extra?.model, 'sonnet', 'kept on the message the thread shows') + } finally { + await setting('claude.model', undefined) + } + }), + + test('Ask Claude on a note Claude answered last starts no run', async () => { + await useFakeClaude() + const n = await question('answered', 'Where is it written?') + await vscode.commands.executeCommand('codeNotes.askClaude', n.id) + await until('answered', () => noteById(n.id)?.messages.at(-1)?.author === 'Claude' && !noteById(n.id).asking, 10000) + await quiet(1200, 'past the second after an answer') + const runs = claudeRuns().length + const messages = readJson(n.file).messages.length + await vscode.commands.executeCommand('codeNotes.askClaude', n.id) + await vscode.commands.executeCommand('codeNotes.askClaude', replyBox(n.id)) + await quiet(1500, 'a run started') + assert.equal(claudeRuns().length, runs, 'no process spawned') + assert.equal(readJson(n.file).messages.length, messages, 'nothing added') + assert.ok(!noteById(n.id).asking) + }), + + test('an answer to a reply sent from the note\'s open thread is not new', async () => { + await useFakeClaude() + const n = await question('thread', 'First question') + await vscode.window.showTextDocument(vscode.Uri.file(wsPath('src', 'app.ts'))) + const thread = await until('thread', () => ctx.api.thread(n.id)) + thread.collapsibleState = vscode.CommentThreadCollapsibleState.Expanded + await vscode.commands.executeCommand('codeNotes.askClaude', replyBox(n.id, 'And where is it used?')) + await until('answered', () => lastSaved(n.file)?.author === 'Claude', 10000) + await until('read', () => noteById(n.id)?.unread === 0) + }), + + test('Stop after Claude wrote its first words keeps them, marked stopped; Ask asks again', async () => { + const n = await question('stopped', 'Explain every field of the request envelope') + await setting('claude.path', firstWordsThenThinking()) + try { + void vscode.commands.executeCommand('codeNotes.askClaude', n.id) + await until('first words streamed', () => ctx.api.thread(n.id)?.comments.some((c) => bodyOf(c).includes('six fields')), 10000) + await vscode.commands.executeCommand('codeNotes.cancelClaude', n.id) + const saved = await until('kept, marked', () => lastSaved(n.file)?.stopped && lastSaved(n.file), 10000) + assert.equal(saved.author, 'Claude') + assert.match(saved.body, /^The envelope has six fields\.\s+_\(stopped\)_$/) + await until('not new to the person who stopped it', () => noteById(n.id)?.unread === 0) + } finally { + await useFakeClaude() + } + // The note still awaits its answer: Ask runs (once the second after the stop is over). + await quiet(1200, 'past the second after the stop') + const before = claudeRuns().length + await vscode.commands.executeCommand('codeNotes.askClaude', n.id) + await until('asked again', () => lastSaved(n.file)?.author === 'Claude' && !lastSaved(n.file).stopped, 10000) + assert.equal(claudeRuns().length, before + 1) + }), + + test('the window closing stops note and journey runs (no orphan); the check\'s writer keeps running', async () => { + const runner = new AgentRunner() + const hang = silent() + const o = { cwd: ctx.ws, prompt: 'p' } + const note = runner.start(hang, { key: 'note:x', purpose: 'note', label: 'x' }, o) + const journey = runner.start(hang, { key: 'journey:x', purpose: 'journey', label: 'x' }, o) + const check = runner.start(hang, { key: 'check:x', purpose: 'check', label: 'x' }, o) + const pids = [note.pid, journey.pid, check.pid] as number[] + try { + await until('running', () => pids.every((p) => p && alive(p))) + runner.dispose() + await until('note and journey runs gone', () => !alive(pids[0]) && !alive(pids[1])) + assert.ok(alive(pids[2]), 'the check writer is tracked by its pid: it goes on') + } finally { + check.cancel() + } + }), +] From a8e96ffb89ade01f87f6707308eb0c49f3e54cdc Mon Sep 17 00:00:00 2001 From: tomeyer97 <107920881+tomeyer97@users.noreply.github.com> Date: Thu, 26 Nov 2026 20:37:16 +0100 Subject: [PATCH 09/17] Writing journeys: say when there is nothing to refresh, refuse vague questions, put Claude's question in front, keep script errors out of the way Slice: S11 Zeroshot-Run: 01a21943-55d4-7060-b099-df89ed8d3417 --- media/clarify.js | 2 + src/write/clarify.ts | 17 +++- src/write/journeyAnswer.ts | 29 ++++-- src/write/questions.ts | 34 +++++++ src/write/refreshJourney.ts | 39 +++++--- src/write/requests.ts | 8 +- src/write/staging.ts | 9 +- src/write/told.ts | 32 +++++++ src/write/writeJourney.ts | 10 +- test/integration/main/writeJourney.ts | 131 ++++++++++++++++++++++++-- test/writing.test.ts | 51 +++++++++- 11 files changed, 323 insertions(+), 39 deletions(-) create mode 100644 src/write/questions.ts create mode 100644 src/write/told.ts diff --git a/media/clarify.js b/media/clarify.js index 0c8b45b..58098ca 100644 --- a/media/clarify.js +++ b/media/clarify.js @@ -22,3 +22,5 @@ answer.addEventListener('keydown', (e) => { } }) answer.focus() +// Brought forward by the notification's Answer: straight into the box. +window.addEventListener('focus', () => answer.focus()) diff --git a/src/write/clarify.ts b/src/write/clarify.ts index 88fe971..bdda52b 100644 --- a/src/write/clarify.ts +++ b/src/write/clarify.ts @@ -10,6 +10,8 @@ import { WebviewChannel } from '../webview/channel' import { escapeHtml } from '../core/escape' import { writeJourney } from './writeJourney' import { fireAndForget } from '../platform/run' +import { shortQ } from '../core/text' +import { notify } from './told' /** The question Claude asked, and the session its answer resumes. */ interface Asked { question: string; session: string; text: string; model?: string } @@ -29,7 +31,7 @@ class ClarifyPanel implements Asked { this.text = a.text this.model = a.model this.panel = vscode.window.createWebviewPanel('codeNotes.claudeAsks', 'Claude asks', - { viewColumn: vscode.ViewColumn.Active, preserveFocus: false }, { enableScripts: true, retainContextWhenHidden: true }) + { viewColumn: vscode.ViewColumn.Active, preserveFocus: true }, { enableScripts: true, retainContextWhenHidden: true }) const media = (f: string) => vscode.Uri.joinPath(extUri(), 'media', f) // Claude's text is rendered Markdown: its images (https:, data:) and style attributes are let in. this.panel.webview.html = webviewPage(this.panel.webview, { @@ -50,6 +52,9 @@ class ClarifyPanel implements Asked { }) } + /** The page in front, with the reply box focused. */ + reveal(): void { this.panel.reveal(undefined, false) } + dispose(): void { this.panel.dispose() } } @@ -62,9 +67,17 @@ export async function showClarify(question: string, session: string, text: strin let body: string try { body = await vscode.commands.executeCommand<string>('markdown.api.render', text) } catch { body = '' } if (!body) body = `<pre>${escapeHtml(text)}</pre>` - clarify = new ClarifyPanel({ question, session, text, model }, body) + const c = new ClarifyPanel({ question, session, text, model }, body) + clarify = c + // The job's progress has ended: the question must reach you wherever you are working (the page alone opens unnoticed). + const said = notify(asksLine(question, text), 'Answer').then((b) => { if (b && clarify === c) c.reveal() }) + fireAndForget(said, 'clarify: notify') } +/** The notification: Claude's question in one line (Markdown marks dropped). */ +export const asksLine = (question: string, text: string) => + `Claude asks about “${shortQ(question, 40)}”: ${shortQ(text.replace(/[*_`#>]/g, ''), 120)}` + /** Your answer to Claude's question: the same session goes on and writes the journey. */ export async function answerClarify(reply: string): Promise<LoadedJourney | undefined> { const c = clarify diff --git a/src/write/journeyAnswer.ts b/src/write/journeyAnswer.ts index e9573fb..037d5d3 100644 --- a/src/write/journeyAnswer.ts +++ b/src/write/journeyAnswer.ts @@ -13,6 +13,8 @@ import { STATE } from '../platform/state' import { chooseJourney, confirmWrite, matchJourneys } from './rank' import { writeJourney } from './writeJourney' import { journeyModel, modelLabel } from './claudeRun' +import { notify } from './told' +import { shortQ } from '../core/text' /** What answering a request did. */ export type Outcome = @@ -91,7 +93,9 @@ export async function answerQuestion(q: string, model: string | undefined, via: } const bad = modelProblem(journeyModel(model)) if (bad) { - fireAndForget(showError(bad), 'requests: showError') + // A script's mistake goes back to the script (its result) and the log, not to the person at the editor. + if (via === 'file') log().warn(`explain: ${bad}`) + else fireAndForget(showError(bad), 'requests: showError') return { kind: 'error', message: bad } } return confirmAndWrite(q, model, report) @@ -106,15 +110,26 @@ function currentOrLastJourney(): LoadedJourney | undefined { ?? all[0] } -/** The journey panel with its Journeys list in front, over currentOrLastJourney. */ -export async function showJourneysHome(): Promise<void> { +/** What the Journeys list says over it: the question no journey answers, and asking it here. */ +export interface Unanswered { question: string; ask: () => Promise<void> } + +/** The one line for a question no journey answers. */ +export const notAnsweredLine = (q: string) => `No journey answers “${shortQ(q)}”` +const WRITE_ONE = 'Write One…' + +/** The journey panel with its Journeys list in front, over currentOrLastJourney; `unanswered`: one line says so. */ +export async function showJourneysHome(unanswered?: Unanswered): Promise<void> { // The walk goes on: ending it right before a new card made VS Code's comment widgets loop ("Maximum call stack size // exceeded"). Choosing a journey switches as usual. const lj = currentOrLastJourney() - if (!lj) { + if (lj) { + mapPanel().showHome(lj) + fireAndForget(stored().set(STATE.mapJourney, posKey(lj)), 'requests: store mapJourney') + } + if (unanswered) { + const said = notify(notAnsweredLine(unanswered.question), WRITE_ONE).then((b) => { if (b) return unanswered.ask() }) + fireAndForget(said, 'requests: notify') + } else if (!lj) { fireAndForget(vscode.window.showInformationMessage('Code Notes: no journeys in this workspace yet.'), 'requests: window.showInformationMessage') - return } - mapPanel().showHome(lj) - fireAndForget(stored().set(STATE.mapJourney, posKey(lj)), 'requests: store mapJourney') } diff --git a/src/write/questions.ts b/src/write/questions.ts new file mode 100644 index 0000000..9c75ceb --- /dev/null +++ b/src/write/questions.ts @@ -0,0 +1,34 @@ +// What a question and journey.py's check say, read without VS Code (unit-tested in test/writing.test.ts). + +/** Fewer words than this is too vague to write a journey for. */ +const MIN_WORDS = 3 + +/** Why `q` is too vague to send to Claude, or undefined when it is not (the question box's validation). */ +export function vagueQuestion(q: string): string | undefined { + const words = q.trim().split(/\s+/).filter(Boolean).length + return words && words < MIN_WORDS ? 'Ask how something works, e.g. How does a note get saved?' : undefined +} + +/** The question a job is listed by once you answered Claude's question about it. */ +export const clarified = (question: string, reply: string) => `${question.trim()}: ${reply.trim().replace(/\s+/g, ' ')}` + +/** journey.py check's PROBLEM lines, numbers masked (a moved line is not a new problem). */ +export function problemsIn(out: string): Set<string> { + return new Set(out.split('\n').filter((l) => l.startsWith('PROBLEM')).map((l) => l.replace(/\d+/g, '#'))) +} + +/** A PROBLEM line saying something points at code that is no longer there (a link, a value, a beat, the step). */ +const CODE_GONE = /no longer (reads|exists)|its code changed/ + +/** journey.py check's PROBLEM lines saying the steps `steps` (1-based) point at code that is gone, as printed. Their + * other rule breaks (a title's wording, …) are the journey's own, older than the refresh. */ +export function stepProblems(out: string, steps: readonly number[]): string[] { + return out.split('\n').filter((l) => { + const m = /^PROBLEM: step (\d+)[: ]/.exec(l) + return !!m && steps.includes(Number(m[1])) && CODE_GONE.test(l) + }) +} + +/** The steps of `lines` (stepProblems' lines), in order, once each. */ +export const stepsOf = (lines: readonly string[]) => + [...new Set(lines.map((l) => Number(/^PROBLEM: step (\d+)/.exec(l)?.[1])))].sort((a, b) => a - b) diff --git a/src/write/refreshJourney.ts b/src/write/refreshJourney.ts index 23c9c44..a9dc13d 100644 --- a/src/write/refreshJourney.ts +++ b/src/write/refreshJourney.ts @@ -16,6 +16,8 @@ import { journeyJob, journeyPy, JourneyRunReady, prepareJourneyRun, reportNotRea import { isRefreshing } from './journeyJobs' import { refreshPrompt, refreshTask } from './prompts' import { beforeCopies } from './beforeCopies' +import { problemsIn, stepProblems, stepsOf } from './questions' +import { notify, sayInStatusBar, warn } from './told' /** Journeys being refreshed (by key): their Refresh says so. */ export const refreshing: Pick<ReadonlySet<string>, 'has'> = { has: isRefreshing } @@ -32,11 +34,11 @@ export async function refreshJourney(arg?: unknown): Promise<LoadedJourney | und if (!lj) return undefined const stale = staleSteps(lj) if (!stale.length) { - vscode.window.setStatusBarMessage('$(check) Every step matches the code', 3000) + sayInStatusBar('$(check) Every step matches the code') return undefined } if (isRefreshing(lj.key)) { - vscode.window.setStatusBarMessage('$(sync~spin) Already refreshing this journey', 3000) + sayInStatusBar('$(sync~spin) Already refreshing this journey') return undefined } const slug = path.basename(lj.uri.fsPath, '.json') @@ -59,7 +61,7 @@ export async function refreshJourney(arg?: unknown): Promise<LoadedJourney | und const prompt = refreshPrompt(skill, staging.stage, task, ready.bundled) const res = await runJourneySkill(job, `Refreshing: ${shortQ(lj.j.title)}`, ready, { prompt }) try { - const outcome = await applyRefresh(lj, { ...ready, slug, before, was, res }) + const outcome = await applyRefresh(lj, { ...ready, slug, before, was, res, stale }) return said(lj, outcome, { slug, stage: staging.stage, took: Date.now() - job.started }) } finally { refreshJourneyList() @@ -78,9 +80,11 @@ function journeyKeyOf(arg: unknown): string | undefined { /** Which stale journey to refresh: the one in front (the walk, the panel's) preselected, else none (Enter never * refreshes a journey by chance). Undefined: none is stale (said), or Esc. */ async function pickStaleJourney(): Promise<LoadedJourney | undefined> { - const stale = journeys().all().filter((x) => staleCount(x)) + const all = journeys().all() + const stale = all.filter((x) => staleCount(x)) if (!stale.length) { - vscode.window.setStatusBarMessage('$(check) Every journey matches the code', 3000) + // No journeys at all is not "all fresh". + sayInStatusBar(all.length ? '$(check) Every journey matches the code' : NO_JOURNEYS, all.length ? 3000 : 6000) return undefined } const near = tour().tourJourney() ?? mapPanel().journey @@ -94,12 +98,11 @@ async function pickStaleJourney(): Promise<LoadedJourney | undefined> { return p && journeys().list.get(p.key) } -/** journey.py check's PROBLEM lines, numbers masked (a moved line is not a new problem). */ -function problemsIn(out: string): Set<string> { - return new Set(out.split('\n').filter((l) => l.startsWith('PROBLEM')).map((l) => l.replace(/\d+/g, '#'))) -} +/** Refresh Journey in a folder with no journeys. */ +export const NO_JOURNEYS = 'No journeys in this folder yet. Find or Write a Journey… to write one.' -interface RefreshRun extends JourneyRunReady { slug: string; before: string; was: Set<string>; res: AskResult } +/** `stale`: the steps Claude was asked to rewrite (1-based). */ +interface RefreshRun extends JourneyRunReady { slug: string; before: string; was: Set<string>; res: AskResult; stale: number[] } /** How a refresh ended. The refreshed copy stays in the staging folder when it broke a rule or the file changed. */ type Outcome = @@ -108,7 +111,8 @@ type Outcome = | { kind: 'broke-a-rule' } | { kind: 'unchanged'; reply: string } | { kind: 'edited-meanwhile' } - | { kind: 'refreshed'; done?: LoadedJourney; diff: vscode.Uri } + /** `failing`: check's lines saying the rewritten steps still point at code that is gone (said, never hidden). */ + | { kind: 'refreshed'; done?: LoadedJourney; diff: vscode.Uri; failing: string[] } /** * After Claude's run: the refreshed copy replaces the journey file when its check adds no problem and the file was @@ -137,13 +141,13 @@ async function applyRefresh(lj: LoadedJourney, r: RefreshRun): Promise<Outcome> const diff = beforeCopies.keep(staging.id, `${slug}.before.json`, before) await fs.promises.writeFile(lj.uri.fsPath, after) staging.cleanup() - return { kind: 'refreshed', done: await journeys().reload(lj.uri), diff } + return { kind: 'refreshed', done: await journeys().reload(lj.uri), diff, failing: stepProblems(chk.out, r.stale) } } /** Each outcome said: an error, a notice, or nothing (cancelled). The journey after it. */ function said(lj: LoadedJourney, o: Outcome, run: { slug: string; stage: string; took: number }): LoadedJourney | undefined { const title = lj.j.title - const info = (text: string, ...items: string[]) => vscode.window.showInformationMessage(text, ...items) + const info = notify const shownBy = 'refreshJourney: window.showInformationMessage' switch (o.kind) { case 'cancelled': @@ -168,8 +172,13 @@ function said(lj: LoadedJourney, o: Outcome, run: { slug: string; stage: string; const left = o.done ? staleCount(o.done) : 0 log().info(`journey ${run.slug}: refreshed in ${clock(run.took)}${left ? `; ${left} step(s) still out of date` : ''}`) const stillStale = left ? ` · ${plural(left, 'step')} still out of date` : '' - const shown = info(`Refreshed “${title}”${stillStale}`, 'Show changes').then((b) => { - if (!b) return + const failing = stepsOf(o.failing) + if (failing.length) log().warn(`journey ${run.slug}: the refreshed step(s) still fail journey.py check:\n${o.failing.join('\n')}`) + const shown = (failing.length + ? warn(`Refreshed “${title}” · ${failing.length > 1 ? 'steps' : 'step'} ${failing.join(', ')} still ${failing.length > 1 ? 'fail' : 'fails'} its check`, 'Show changes', 'Show Output') + : info(`Refreshed “${title}”${stillStale}`, 'Show changes')).then((b) => { + if (b === 'Show Output') log().show(true) + if (b !== 'Show changes') return const diff = vscode.commands.executeCommand('vscode.diff', o.diff, lj.uri, `${title}: before ↔ refreshed`) fireAndForget(diff, 'refreshJourney: command vscode.diff') }) diff --git a/src/write/requests.ts b/src/write/requests.ts index 43228d4..fb41b43 100644 --- a/src/write/requests.ts +++ b/src/write/requests.ts @@ -11,6 +11,7 @@ import { readEnvelope, readRequest, REQUEST_FILE, RequestResult, RESULT_FILE, resultText, ScriptRequest, Via, } from '../platform/agent/protocol' import { answerQuestion, Outcome, showJourneysHome } from './journeyAnswer' +import { vagueQuestion } from './questions' /** The same request again within this long (an old script sends a link and a file) is handled once. */ const DUPLICATE_MS = 30_000 @@ -130,7 +131,9 @@ async function handleRequest(req: ScriptRequest, via: Via, replyTo?: ReplyTo): P if (answered && answered.kind !== 'not-answered') { report(answered); return } // Overview: the panel's Journeys list (one marked "Start here"), not a picker; the sidebar is left as it was. report({ kind: 'overview' }) - await showJourneysHome() + // A link's question no journey answers is said, with a way to ask it here (the person asks it; the link never does). + const ask = () => handleRequest({ action: 'ask', question: q }, 'command') + await showJourneysHome(answered?.kind === 'not-answered' ? { question: q, ask } : undefined) } /** vscode://<publisher>.code-notes/explain?action=…&q=…[&repo=<path>] (old scripts): `model` is ignored. */ @@ -168,7 +171,8 @@ async function consumeRequest(folder: vscode.WorkspaceFolder): Promise<void> { * written for it. */ export const askQuestion = async () => { - const box = { prompt: 'Ask a question about the code', placeHolder: 'How does … work?', ignoreFocusOut: true } + // A word or two would cost minutes of Claude for a guess: asked again before anything starts. + const box = { prompt: 'Ask a question about the code', placeHolder: 'How does … work?', ignoreFocusOut: true, validateInput: vagueQuestion } const q = (await vscode.window.showInputBox(box))?.trim() if (!q) return // The same path as a request with a question (matching, a pick of close matches, trust, model check, the confirm). diff --git a/src/write/staging.ts b/src/write/staging.ts index 97b6f4e..e004182 100644 --- a/src/write/staging.ts +++ b/src/write/staging.ts @@ -18,13 +18,18 @@ const remove = (dir: string) => { try { fs.rmSync(dir, { recursive: true, force: true }) } catch (e) { report(e, { what: `remove staging folder ${dir}` }) } } -/** A new staging folder in `notesFolder` (relative to `repo`). */ +/** `dir` removed when it is empty: another run's folder in it keeps it. */ +const removeIfEmpty = (dir: string) => { + try { fs.rmdirSync(dir) } catch { /* not empty, or gone already */ } +} + +/** A new staging folder in `notesFolder` (relative to `repo`); its cleanup leaves no empty `.writing` behind. */ export function stagingFolder(repo: string, notesFolder: string): Staging { const id = `${Date.now().toString(36)}${Math.random().toString(36).slice(2, 6)}` const stage = `${notesFolder}/${STAGING}/${id}` const dir = path.join(repo, stage) fs.mkdirSync(dir, { recursive: true }) - return { id, stage, dir, cleanup: () => remove(dir) } + return { id, stage, dir, cleanup: () => { remove(dir); removeIfEmpty(path.dirname(dir)) } } } /** The staging folders under `root` (`<repo>/<notes folder>/.writing`) older than STAGING_MAX_AGE_MS, removed. */ diff --git a/src/write/told.ts b/src/write/told.ts new file mode 100644 index 0000000..0f7a49f --- /dev/null +++ b/src/write/told.ts @@ -0,0 +1,32 @@ +// What writing journeys tells the person outside its own pages (a status bar line, a notification), the newest kept +// for the integration tests to read. +import * as vscode from 'vscode' + +/** How many lines `told` keeps (the newest). */ +const KEPT = 50 + +/** What was said, oldest first. */ +export const told: string[] = [] + +function keep(text: string): void { + told.push(text) + if (told.length > KEPT) told.splice(0, told.length - KEPT) +} + +/** A status bar line for `ms`. */ +export function sayInStatusBar(text: string, ms = 3000): void { + keep(text) + vscode.window.setStatusBarMessage(text, ms) +} + +/** A notification; resolves to the button clicked. */ +export function notify(text: string, ...items: string[]): Thenable<string | undefined> { + keep(text) + return vscode.window.showInformationMessage(text, ...items) +} + +/** A warning notification; resolves to the button clicked. */ +export function warn(text: string, ...items: string[]): Thenable<string | undefined> { + keep(text) + return vscode.window.showWarningMessage(text, ...items) +} diff --git a/src/write/writeJourney.ts b/src/write/writeJourney.ts index f58d7f0..d52a590 100644 --- a/src/write/writeJourney.ts +++ b/src/write/writeJourney.ts @@ -18,6 +18,7 @@ import { elapsed as clock, minutes } from '../core/clock' import { showClarify } from './clarify' import { journeyJob, journeyPy, JourneyRunReady, prepareJourneyRun, reportNotReady, runJourneySkill } from './claudeRun' import { answeredBy, journeyPrompt, journeyRules } from './prompts' +import { clarified } from './questions' interface WriteOptions { model?: string; resume?: { session: string; reply: string } } @@ -41,10 +42,11 @@ export async function writeJourney(question: string, o: WriteOptions = {}): Prom const prompt = o.resume ? `${o.resume.reply}\n\n${journeyRules(ready.skill, ready.staging.stage, jf)}` : journeyPrompt(question, ready.skill, ready.staging.stage, jf, ready.bundled) - const job = journeyJob(ready, 'write', question) - const answered = o.resume ? ' (with your answer to its question)' : '' - log().info(`journey: Claude (${job.model}) is writing one for "${question}"${answered}`) - const res = await runJourneySkill(job, `Writing: ${shortQ(question)}`, ready, { + // Listed by the question as your answer made it, so the job you answered is the one you see going on. + const asked = o.resume ? clarified(question, o.resume.reply) : question + const job = journeyJob(ready, 'write', asked) + log().info(`journey: Claude (${job.model}) is writing one for "${asked}"`) + const res = await runJourneySkill(job, `Writing: ${shortQ(asked)}`, ready, { prompt, resume: o.resume?.session, cache: true, }) const took = Date.now() - job.started diff --git a/test/integration/main/writeJourney.ts b/test/integration/main/writeJourney.ts index 3427f91..6d0a417 100644 --- a/test/integration/main/writeJourney.ts +++ b/test/integration/main/writeJourney.ts @@ -1,14 +1,23 @@ // "Ask the agent to write a journey" when nothing matches: the fake claude CLI (test/fixtures/fake-claude.js) plays // the code-journey skill's journey.py; the journey is staged, checked, moved into journeys/, and its map opens. -// Source: src/write/ (claudeRun.ts, writeJourney.ts, staging.ts); what Claude may run is unit-tested in -// test/writing.test.ts (runOptions.ts through claude.ts's claudeArgs), so here it is enough that the CLI was called. +// Claude's question before writing is a notification; a refresh says what its check still finds on the refreshed +// step; a link no journey answers says so; a script's bad request is not shown to the person. +// Source: src/write/ (claudeRun.ts, writeJourney.ts, staging.ts, clarify.ts, refreshJourney.ts, journeyAnswer.ts); +// what Claude may run is unit-tested in test/writing.test.ts (runOptions.ts through claude.ts's claudeArgs), so here +// it is enough that the CLI was called. +import * as vscode from 'vscode' import * as fs from 'fs' import * as path from 'path' import assert from 'assert' -import { fakeCalls, flag, readJson, test } from '../helpers' -import { writeSkillStandIn } from '../fixtures' +import { EXT_ID, fakeCalls, flag, quiet, readJson, readJsonOr, test } from '../helpers' +import { journey, readResult, step, writeJourney, writeLines, writeRequest, writeSkillStandIn } from '../fixtures' import { STAGING } from '../../../src/write/staging' -import { ctx, snap, until, wsPath } from './context' +import { told } from '../../../src/write/told' +import { NO_JOURNEYS } from '../../../src/write/refreshJourney' +import { notAnsweredLine } from '../../../src/write/journeyAnswer' +import { asksLine } from '../../../src/write/clarify' +import { ctx, journeyById, journeysDir, setting, snap, until, wsPath } from './context' +import { repoJourneysDir } from './shared' /** The journey file `name` in a staging folder of the notes folder (`.writing/<id>/<name>`), once there is one. */ function stagedFile(notesDir: string, name: string): string | undefined { @@ -17,8 +26,79 @@ function stagedFile(notesDir: string, name: string): string | undefined { return fs.readdirSync(root).map((id) => path.join(root, id, name)).find((f) => fs.existsSync(f)) } +/** No staging root left, or an empty one (the run's own folder is gone either way). */ +const noStaging = (notesDir: string) => { + const root = path.join(notesDir, STAGING) + return !fs.existsSync(root) || !fs.readdirSync(root).length +} + +/** What writing journeys says from now on: take it before, read it after. */ +function newTold(): () => string[] { + const n = told.length + return () => told.slice(n) +} + +/** The journey folders moved aside (and the list read again) until `restore`. */ +async function journeysAside(): Promise<{ restore: () => Promise<void> }> { + const dirs = [journeysDir(), repoJourneysDir()].filter((d) => fs.existsSync(d)) + dirs.forEach((d) => fs.renameSync(d, `${d}.aside`)) + await ctx.api.reloadJourneys() + await until('no journeys', () => !snap().journeys.length) + return { + restore: async () => { + dirs.forEach((d) => fs.renameSync(`${d}.aside`, d)) + await ctx.api.reloadJourneys() + }, + } +} + +/** The person's error messages while `fn` runs (the window's own, watched). */ +async function errorsShownDuring(fn: () => Promise<void>): Promise<string[]> { + const win = vscode.window as { showErrorMessage: (...a: any[]) => Thenable<unknown> } + const shown = win.showErrorMessage + const errors: string[] = [] + win.showErrorMessage = (text: string, ...rest: any[]) => { errors.push(text); return shown.call(vscode.window, text, ...rest) } + try { await fn() } finally { win.showErrorMessage = shown } + return errors +} + /* eslint-disable @typescript-eslint/no-explicit-any */ export const writeJourneyTests = [ + // Before the repository's stand-in skill is written (below): a refresh runs the extension's own journey.py. + test('Refresh Journey with no journeys says there are none, not that every journey matches', async () => { + await vscode.commands.executeCommand('codeNotes.endJourney') + const aside = await journeysAside() + try { + const said = newTold() + await vscode.commands.executeCommand('codeNotes.refreshJourney') + assert.deepEqual(said(), [NO_JOURNEYS]) + } finally { await aside.restore() } + }), + + test('a refresh whose rewritten step still points at code that is gone says so; no staging folder is left', async () => { + const file = wsPath('src', 'rf.ts') + const was = ' return gateway.charge(order.total, order.currency)' + writeLines(file, ['// rf', 'export function charge(order) {', was, '}']) + // Its link reads line 3 as it was: the refresh re-anchors the step (fake-claude's restep) but leaves the link. + const link = { phrase: 'charges', file: 'src/rf.ts', start: 3, end: 3, text: was } + const p = writeJourney(journeysDir(), journey('rf', [step('src/rf.ts', 2, 3, { + id: 'r1', title: 'Charged', node: 'c', lead: 'It charges the card.', links: [link], + anchor: { text: ['export function charge(order) {', was].join('\n'), before: '// rf', after: '}' }, + })], { title: 'Rf', nodes: [{ id: 'c', kind: 'function', label: 'charge' }] })) + const rf = () => journeyById('rf')?.at[0] + await until('rf loaded, fresh', () => !!rf() && !rf().stale) + writeLines(file, ['// rf', 'export function charge(order) {', ' return gateway.pay(order.total, "EUR")', '}']) + await until('rf stale', () => rf()?.stale, 8000) + const said = newTold() + await vscode.commands.executeCommand('codeNotes.refreshJourney', vscode.Uri.file(p).toString()) + await until('the refreshed copy replaced the journey', () => readJsonOr(p)?.steps[0].anchor?.v === 3, 20000) + await until('said', () => said().length) + assert.deepEqual(said(), ['Refreshed “Rf” · step 1 still fails its check'], 'said, not shown as fresh') + assert.ok(!fs.existsSync(path.join(ctx.notesDir, STAGING)), 'no empty staging folder left') + fs.unlinkSync(p) + await until('rf gone', () => !journeyById('rf')) + }), + test('"Ask the agent to write a journey": claude with the code-journey skill writes it, its map opens', async () => { // The repository's own copy of the skill is used (a teammate has none in their home folder). const repoSkill = writeSkillStandIn(ctx.ws) @@ -34,7 +114,7 @@ export const writeJourneyTests = [ assert.equal(ctx.api.writing().length, 0, 'no row once written') const writtenFile = wsPath('journeys', 'written.json') assert.equal(readJson(writtenFile).model, 'Claude Code default', 'the model is stamped') - assert.ok(!fs.readdirSync(path.join(ctx.notesDir, STAGING)).length, 'the staging folder is cleaned up') + assert.ok(!fs.existsSync(path.join(ctx.notesDir, STAGING)), 'the staging folder is cleaned up, its root too') await until('its map is open', () => snap().tour.map === 'written') const cli = fakeCalls()[callsBefore] assert.ok(cli, 'the claude CLI was called') @@ -46,4 +126,43 @@ export const writeJourneyTests = [ fs.unlinkSync(writtenFile) await until('written gone', () => !snap().journeys.some((x: any) => x.id === 'written')) }), + + test('Claude\'s question is a notification with Answer; the job goes on under the question as you answered it', async () => { + const said = newTold() + assert.equal(await ctx.api.writeJourney('Something unclear about things'), undefined, 'no journey yet') + const asked = await until('Claude\'s question', () => ctx.api.clarify()) + assert.deepEqual(said(), [asksLine('Something unclear about things', asked.text)]) + assert.match(said()[0], /^Claude asks about “Something unclear about things”: Which part do you mean: saving or loading\?$/) + const resumed = ctx.api.answerClarify('The saving part') + await until('listed under the answered question', () => /^Writing: Something unclear about things: The saving part · \d:\d\d$/.test(ctx.api.writing()[0]?.label ?? '')) + assert.equal(await resumed, 'written') + fs.unlinkSync(wsPath('journeys', 'written.json')) + await until('written gone', () => !snap().journeys.some((x: any) => x.id === 'written')) + }), + + test('a link no journey answers: the Journeys list and one line naming the question; it starts nothing', async () => { + const q = 'How are sprockets teleported?' + const said = newTold() + const runs = fakeCalls().length + await vscode.env.openExternal(vscode.Uri.parse(`${vscode.env.uriScheme}://${EXT_ID}/explain?action=ask&q=${encodeURIComponent(q)}&repo=${encodeURIComponent(ctx.ws)}`)) + await until('the line', () => said().includes(notAnsweredLine(q)), 8000) + assert.equal(notAnsweredLine(q), 'No journey answers “How are sprockets teleported?”') + await until('the Journeys list', () => snap().tour.mapTitle === 'Journeys') + await quiet(500, 'a Claude run after the link') + assert.equal(fakeCalls().length, runs, 'no Claude run') + }), + + test('a request file\'s unknown model goes to its result and the log, not to the person', async () => { + const errors = await errorsShownDuring(async () => { + writeRequest(ctx.notesDir, { action: 'ask', question: 'How are doohickeys frobnicated?', model: 'gpt-9', id: 'req-gpt9' }) + await until('result: error', () => readResult(ctx.notesDir)?.id === 'req-gpt9' && readResult(ctx.notesDir).outcome === 'error', 8000) + assert.match(readResult(ctx.notesDir).message, /Unknown model 'gpt-9'/) + // The person's own run with that model is still told (the watch works). + await setting('journeys.model', 'gpt-9') + try { assert.equal(await ctx.api.writeJourney('How are doohickeys frobnicated?'), undefined) } finally { await setting('journeys.model', undefined) } + }) + assert.equal(errors.length, 1, `only the person's own run: ${JSON.stringify(errors)}`) + assert.match(errors[0], /Unknown model 'gpt-9'/) + assert.ok(noStaging(ctx.notesDir)) + }), ] diff --git a/test/writing.test.ts b/test/writing.test.ts index 44587d9..33b2abd 100644 --- a/test/writing.test.ts +++ b/test/writing.test.ts @@ -1,11 +1,15 @@ // Writing a journey with Claude, the parts without VS Code: the clock (core/clock.ts), the plain phase read from // journey.py's command lines (write/journeyPhases.ts), what Claude may run (write/runOptions.ts through claudeArgs), // the line of its reply that names a journey that already answers (write/prompts.ts), and the message when the -// skill is nowhere (platform/skillDir.ts). +// skill is nowhere (platform/skillDir.ts); a question too vague to write for, the job's name once Claude's question is +// answered and the check's problems on refreshed steps (write/questions.ts); no empty staging root (write/staging.ts). import { test } from 'node:test' import assert from 'node:assert/strict' import * as fs from 'fs' +import * as os from 'os' import * as path from 'path' +import { clarified, problemsIn, stepProblems, stepsOf, vagueQuestion } from '../src/write/questions' +import { STAGING, stagingFolder } from '../src/write/staging' import { elapsed as clock, minutes } from '../src/core/clock' import { NO_PHASE, PHASES, phaseOf } from '../src/write/journeyPhases' import { answeredBy } from '../src/write/prompts' @@ -68,3 +72,48 @@ test('missingSkill: names the places the lookup tried, in its order', () => { "the code-journey skill isn't in this repository (.claude/skills/code-journey), in ~/.claude/skills or in the extension") assert.equal(missingSkill('s', { bundled: '/ext/skills' }), "the s skill isn't in ~/.claude/skills or in the extension") }) + +test('a question under three words is asked again, with an example; a real one passes', () => { + const again = 'Ask how something works, e.g. How does a note get saved?' + assert.equal(vagueQuestion('stuff'), again) + assert.equal(vagueQuestion(' saving notes '), again) + assert.equal(vagueQuestion('How does saving work?'), undefined) + assert.equal(vagueQuestion('loadNote parses what?'), undefined) + assert.equal(vagueQuestion(''), undefined, 'an empty box is Esc, not a mistake') +}) + +test('the job answered: listed by the question with your answer', () => { + assert.equal(clarified('stuff', ' The saving\npart '), 'stuff: The saving part') +}) + +test('a refresh: new problems masked by number; code gone under the refreshed steps found even when it was before', () => { + const out = [ + 'PROBLEM: box validate: its code changed', + 'PROBLEM: step 2 scene: beat 2 ("x"): api/validate.js:22 no longer reads "const product = CATALOG[item.sku]"', + 'PROBLEM: step 2: link "total": api/validate.js:27 no longer reads "total += product.price"', + 'PROBLEM: step 12: link "a": a.js:1 no longer reads "a"', + 'PROBLEM: step 2: title "Saved" is a name, not a fact: say what happens', + 'WARNING: step 2: no code links', + 'ok: 3 steps, 4 problems', + ].join('\n') + assert.ok(problemsIn(out).has('PROBLEM: step # scene: beat # ("x"): api/validate.js:# no longer reads "const product = CATALOG[item.sku]"')) + assert.equal(problemsIn(out).size, 5) + const failing = stepProblems(out, [2]) + assert.equal(failing.length, 2, 'step 2\'s code gone only (not step 12, the box, its title\'s wording or a warning)') + assert.deepEqual(stepsOf(failing), [2]) + assert.deepEqual(stepsOf(stepProblems(out, [12, 2])), [2, 12]) + assert.deepEqual(stepProblems(out, [1]), []) +}) + +test('a staging folder\'s cleanup leaves no empty staging root; another run\'s folder keeps it', () => { + const repo = fs.mkdtempSync(path.join(os.tmpdir(), 'staging-')) + const root = path.join(repo, '.code-notes', STAGING) + const a = stagingFolder(repo, '.code-notes') + const b = stagingFolder(repo, '.code-notes') + a.cleanup() + assert.deepEqual(fs.readdirSync(root), [b.id]) + b.cleanup() + assert.ok(!fs.existsSync(root), 'no empty .writing left') + assert.ok(fs.existsSync(path.join(repo, '.code-notes')), 'the notes folder stays') + fs.rmSync(repo, { recursive: true }) +}) From 9780a349dbac9d6af502dc038e35f56c140965a6 Mon Sep 17 00:00:00 2001 From: tomeyer97 <107920881+tomeyer97@users.noreply.github.com> Date: Thu, 26 Nov 2026 20:45:45 +0100 Subject: [PATCH 10/17] The check in the editor: hidden on the default branch, background runs only where the check is used, no fake 'Reopened', readable warnings Slice: S13 Zeroshot-Run: 01a21943-559c-72c2-8a49-36857965bf2d --- media/check.css | 8 +-- media/check.js | 8 ++- media/checkAnswer.css | 3 +- media/checkAnswer.js | 11 +++- src/check/README.md | 2 +- src/check/background.ts | 49 ++++++----------- src/check/backgroundRule.ts | 69 ++++++++++++++++++++++++ src/check/constants.ts | 2 + src/check/controller.ts | 16 ++++-- src/check/wiring.ts | 3 +- test/check-panel/shoot.mjs | 37 ++++++++++++- test/checkBackground.test.ts | 69 ++++++++++++++++++++++++ test/goldens/check-model/view-names.json | 1 + test/integration/check/answers.ts | 3 ++ test/integration/check/branches.ts | 3 ++ 15 files changed, 235 insertions(+), 49 deletions(-) create mode 100644 src/check/backgroundRule.ts create mode 100644 test/checkBackground.test.ts diff --git a/media/check.css b/media/check.css index 558408a..4d34700 100644 --- a/media/check.css +++ b/media/check.css @@ -5,7 +5,9 @@ body { font-family: var(--vscode-font-family); font-size: var(--vscode-font-size .check header p { margin: 0; overflow-wrap: anywhere; } .check .title { font-weight: 600; } .check .tone-ok .title { color: var(--ok); } -.check .tone-warn .title { color: var(--warn); } +/* Warnings: text in the foreground, only a ⚠ in the warning colour (amber text is ≈3:1 on light themes). */ +.check .tone-warn .title::before, .check > header .failed::before { content: '⚠ ' / ''; color: var(--warn); } +.check .warn-mark { color: var(--warn); } .check .line, .check .who, .check .notice, .check .muted, .check .busy { color: var(--muted); } .check .who { font-style: italic; } .check .busy { margin: 0 0 6px; font-style: italic; } @@ -21,7 +23,7 @@ body { font-family: var(--vscode-font-family); font-size: var(--vscode-font-size .check .text { overflow-wrap: anywhere; display: -webkit-box; -webkit-line-clamp: 3; -webkit-box-orient: vertical; overflow: hidden; } .check .row.pass .text, .check .row.explained .text, .check .row.restated .text { color: var(--muted); } .check .meta { font-size: 0.9em; color: var(--muted); overflow-wrap: anywhere; } -.check .flag { font-size: 0.9em; color: var(--warn); } +.check .flag { font-size: 0.9em; } .check footer { margin: 0 0 8px; } .check .commits { margin: 0 0 4px; color: var(--muted); overflow-wrap: anywhere; } .check .also { display: flex; gap: 6px; align-items: center; margin: 0 0 6px; overflow-wrap: anywhere; } @@ -34,7 +36,7 @@ body { font-family: var(--vscode-font-family); font-size: var(--vscode-font-size .check .tour { display: block; margin: 0 0 6px; max-width: 100%; overflow-wrap: anywhere; } .check .setup { margin: 2px 0 0; color: var(--muted); overflow-wrap: anywhere; } .check .mr { margin: 2px 0 0; overflow-wrap: anywhere; } -.check .failed { margin: 2px 0 0; color: var(--warn); overflow-wrap: anywhere; } +.check .failed { margin: 2px 0 0; overflow-wrap: anywhere; } .check .failed .link { display: inline; } .check .failed .waive { color: var(--muted); } .check .text code { font-family: var(--vscode-editor-font-family, monospace); font-size: 0.95em; } diff --git a/media/check.js b/media/check.js index a017f90..b2c51e1 100644 --- a/media/check.js +++ b/media/check.js @@ -7,7 +7,7 @@ import { watched, WATCHED, overflowing } from './report.js' import { codeSpans, plainText } from './codeSpans.js' import { runTestMessage } from './map/testHooks.js' import { QSTATE } from '../src/protocol/check' -import { answerBoxes } from './checkAnswer.js' +import { answerBoxes, warned } from './checkAnswer.js' /** @typedef {import('../src/protocol/check').ToCheck} ToCheck */ /** @typedef {import('../src/protocol/check').FromCheck} FromCheck */ @@ -163,7 +163,11 @@ function row(r, answer) { const text = watched(el('span', 'text')) text.append(...codeSpans(r.text)) body.append(text, watched(el('span', 'meta', metaLine(r)))) - if (r.flag) body.append(watched(el('span', 'flag', `⚠ ${r.flag}`))) + if (r.flag) { + const flag = watched(el('span', 'flag')) + flag.append(...warned(r.flag)) + body.append(flag) + } b.append(icon, body) li.append(b) if (answer && answer.id === r.id) li.append(answers.box(answer, r)) diff --git a/media/checkAnswer.css b/media/checkAnswer.css index 46970c7..7da83ee 100644 --- a/media/checkAnswer.css +++ b/media/checkAnswer.css @@ -16,7 +16,6 @@ /* "Next question ›": a `.link` (common.css). */ .check .answer .next { margin-top: 4px; } .check .answer .concern p { margin: 4px 0 0; overflow-wrap: anywhere; } -.check .answer .concern p:first-child { color: var(--warn); } .check .answer .concern .link { display: inline; } .check .answer .concern .applied { color: var(--muted); } -.check .answer .failed { margin: 4px 0 0; color: var(--warn); overflow-wrap: anywhere; } +.check .answer .failed { margin: 4px 0 0; overflow-wrap: anywhere; } diff --git a/media/checkAnswer.js b/media/checkAnswer.js index 7bf3b65..961151e 100644 --- a/media/checkAnswer.js +++ b/media/checkAnswer.js @@ -42,6 +42,11 @@ function focusBox(w, caret) { return true } +/** ⚠ then `text`: only the glyph takes the warning colour (amber text is too faint to read on light themes). */ +export function warned(text) { + return [el('span', 'warn-mark', '⚠'), ` ${text}`] +} + /** * The answer boxes of one page, posting with `post`. What they keep between renders lives here: what was typed, the * draft's timer, and the question whose answer was just sent. @@ -128,7 +133,9 @@ export function answerBoxes(post) { * code: said; it goes with Commit & push. */ function concernBlock(a) { const c = el('div', 'concern') - c.append(el('p', null, `⚠ ${a.concern.text}`)) + const said = el('p') + said.append(...warned(a.concern.text)) + c.append(said) const acts = el('p', 'acts') const act = (label, action) => button('link', label, () => post({ type: 'concern', id: a.id, action })) if (a.concern.applied) { @@ -174,7 +181,7 @@ export function answerBoxes(post) { // Couldn't grade it (the answer is kept): why, and Try again. else if (a.error) { const p = watched(el('p', 'failed')) - p.append(`⚠ ${a.error} `, button('link', 'Try again', () => post({ type: 'regrade', id: a.id }))) + p.append(...warned(`${a.error} `), button('link', 'Try again', () => post({ type: 'regrade', id: a.id }))) w.append(p) } else if (a.grade) w.append(gradeBlock(a, w)) if (a.concern) w.append(concernBlock(a)) diff --git a/src/check/README.md b/src/check/README.md index 7e722fd..47aca8e 100644 --- a/src/check/README.md +++ b/src/check/README.md @@ -25,7 +25,7 @@ the threads are a view of it, kept in sync both ways. Where the check stands com | concern.ts | concerns about the code (fix, TODO, flag, dismiss; the TODO's text in todoComment.ts, its edit in editor.ts) | | push.ts | Commit & push (its git calls in pushGit.ts) | | park.ts | a check moved aside while another branch is checked out | -| background.ts | questions written after a push (pushSeen.ts says when one happened) | +| background.ts | questions written after a push, in a repository that uses the check (backgroundRule.ts decides; pushSeen.ts says when one happened) | | invalidFile.ts | a check file that can't be read | | view.ts | the Check view's webview | | statusItem.ts | the status bar item | diff --git a/src/check/background.ts b/src/check/background.ts index c21b0c5..f09c58e 100644 --- a/src/check/background.ts +++ b/src/check/background.ts @@ -1,16 +1,17 @@ // Background questions: when a branch is pushed (it has an upstream and nothing left to push, after it had something -// or no upstream), has code changes and no check, and is not a default branch, its questions are written quietly. One -// run at a time; never twice for the same commit. Setting codeNotes.understanding.background (SETTINGS.background). +// or no upstream), has code changes and no check, is not a default branch, and the repository uses the check, its +// questions are written quietly (backgroundRule.ts decides). One run at a time; never twice for the same commit. +// Setting codeNotes.understanding.background (SETTINGS.background). import * as vscode from 'vscode' import * as path from 'path' -import { BG_COMMITS_KEPT, REFRESH_SOON_MS, SETTINGS } from './constants' +import { REFRESH_SOON_MS, SETTINGS } from './constants' +import { BackgroundWrites } from './backgroundRule' import type { CheckHost } from './host' import { PushWatch } from './pushSeen' import type { CheckCore } from './state' import type { Writer } from './writer' import { fireAndForget } from '../platform/run' import { cfg } from '../platform/settings' -import { STATE, type StateStore } from '../platform/state' /** The parts of VS Code's git extension API used here. */ export interface GitRepo { @@ -19,33 +20,29 @@ export interface GitRepo { } export interface GitApi { repositories: GitRepo[]; onDidOpenRepository: vscode.Event<GitRepo> } -/** What background questions need: the state, a refresh, the log, the workspace memory and the writer. */ +/** What background questions need: the state, a refresh, the log, the workspace memory, the git reads and the writer. */ export interface BackgroundPorts extends Pick<CheckCore, 'state' | 'refresh' | 'log'> { host: Pick<CheckHost, 'stored'> refreshSoon(ms: number, force: boolean): void + /** The repository uses the check (backgroundRule.ts usesCheck). */ + usesCheck(refs: string[]): Promise<boolean> writer: Pick<Writer, 'writing' | 'write'> } -/** The commits whose background questions were written (the last BG_COMMITS_KEPT), in the workspace's memory. */ -export class BackgroundRuns { - constructor(private stored: Pick<StateStore, 'get' | 'set'>) {} - has(commit: string): boolean { return this.stored.get(STATE.checkBackgroundHeads).includes(commit) } - async add(commit: string): Promise<void> { - const done = this.stored.get(STATE.checkBackgroundHeads) - await this.stored.set(STATE.checkBackgroundHeads, [...done.slice(-BG_COMMITS_KEPT), commit]) - } -} - /** How many lines of what the push watcher saw are kept for the integration test (also in the log, at debug). */ const TRACE_KEPT = 10 export class BackgroundQuestions implements vscode.Disposable { private seen: string[] = [] private subs: vscode.Disposable[] = [] - private readonly runs: BackgroundRuns + private readonly writes: BackgroundWrites constructor(private ports: BackgroundPorts) { - this.runs = new BackgroundRuns(ports.host.stored) + this.writes = new BackgroundWrites({ + state: ports.state, refresh: ports.refresh, stored: ports.host.stored, writer: ports.writer, usesCheck: ports.usesCheck, + // Its default (on) is package.json's. + enabled: () => cfg().get<boolean>(SETTINGS.background) !== false, + }) } /** What the push watcher saw last (read by the integration test through the controller's snapshot). */ @@ -89,23 +86,7 @@ export class BackgroundQuestions implements vscode.Disposable { const look = watch.look(h) if (!look) return this.saw(look.line) - if (look.pushedNow) fireAndForget(this.pushed(look.branch, h?.commit), 'background: pushed') - } - - /** `branch` was just pushed at `commit`: its questions, if it needs some (see the top of this file). */ - private async pushed(branch: string, commit: string | undefined): Promise<void> { - const ports = this.ports - // Its default (on) is package.json's. - const on = cfg().get<boolean>(SETTINGS.background) !== false - if (!on || ports.writer.writing || !commit) return - if (this.runs.has(commit)) return - await ports.refresh() - const st = ports.state.st - if (!st || st.branch !== branch || st.state.phase !== 'none') return - // A default branch (the CLI's isDefaultBranch: origin's HEAD, else main or master; or the branch compared with). - if (st.onBase) return - await this.runs.add(commit) - await ports.writer.write(false, { background: true }) + if (look.pushedNow) fireAndForget(this.writes.pushed(look.branch, h?.commit), 'background: pushed') } dispose(): void { for (const s of this.subs) s.dispose() } diff --git a/src/check/backgroundRule.ts b/src/check/backgroundRule.ts new file mode 100644 index 0000000..25786ff --- /dev/null +++ b/src/check/backgroundRule.ts @@ -0,0 +1,69 @@ +// Whether a push writes questions in the background, and the commits it already did it for. No vscode at run time +// (background.ts watches the pushes): unit-tested (test/checkBackground.test.ts). +import * as fs from 'fs' +import * as path from 'path' +import { BG_COMMITS_KEPT } from './constants' +import type { CheckCore } from './state' +import type { Writer } from './writer' +import { DIR } from '../../cli/understanding/constants' +import { gitRaw } from '../platform/git' +import { STATE, type StateStore } from '../platform/state' + +/** + * The repository uses the check: its settings (understanding/config.json) are there, or a check file is committed at + * one of `refs`. Questions are written in the background only then. + */ +export async function usesCheck(repo: string, refs: string[]): Promise<boolean> { + if (fs.existsSync(path.join(repo, DIR, 'config.json'))) return true + for (const ref of refs) { + const out = await gitRaw(repo, ['ls-tree', '--name-only', ref, '--', `${DIR}/`]) + if (out?.split('\n').some((f) => f.endsWith('.json'))) return true + } + return false +} + +/** The commits whose background questions were written (the last BG_COMMITS_KEPT), in the workspace's memory. */ +export class BackgroundRuns { + constructor(private stored: Pick<StateStore, 'get' | 'set'>) {} + has(commit: string): boolean { return this.stored.get(STATE.checkBackgroundHeads).includes(commit) } + async add(commit: string): Promise<void> { + const done = this.stored.get(STATE.checkBackgroundHeads) + await this.stored.set(STATE.checkBackgroundHeads, [...done.slice(-BG_COMMITS_KEPT), commit]) + } +} + +/** What the rule reads: the state after a refresh, the setting, whether the repository uses the check, the writer. */ +export interface PushedPorts extends Pick<CheckCore, 'state' | 'refresh'> { + stored: Pick<StateStore, 'get' | 'set'> + /** codeNotes.understanding.background. */ + enabled(): boolean + /** The repository uses the check: understanding/config.json, or a check file committed at one of `refs`. */ + usesCheck(refs: string[]): Promise<boolean> + writer: Pick<Writer, 'writing' | 'write'> +} + +export class BackgroundWrites { + private readonly runs: BackgroundRuns + constructor(private ports: PushedPorts) { + this.runs = new BackgroundRuns(ports.stored) + } + + /** + * `branch` was just pushed at `commit`: its questions are written when it has a change, no check, is not a default + * branch, and the repository uses the check (a paid run nobody asked for otherwise). Once per commit. True: started. + */ + async pushed(branch: string, commit: string | undefined): Promise<boolean> { + const ports = this.ports + if (!ports.enabled() || ports.writer.writing || !commit) return false + if (this.runs.has(commit)) return false + await ports.refresh() + const st = ports.state.st + if (!st || st.branch !== branch || st.state.phase !== 'none') return false + // A default branch (the CLI's isDefaultBranch: origin's HEAD, else main or master; or the branch compared with). + if (st.onBase) return false + if (!(await ports.usesCheck(['HEAD', ...(st.baseRef ? [st.baseRef] : [])]))) return false + await this.runs.add(commit) + await ports.writer.write(false, { background: true }) + return true + } +} diff --git a/src/check/constants.ts b/src/check/constants.ts index 02af35e..bed2a69 100644 --- a/src/check/constants.ts +++ b/src/check/constants.ts @@ -14,6 +14,8 @@ export const VIEW_ID = 'codeNotes.check' export const STATUS_ITEM_ID = 'codeNotes.understanding' /** The context key that is true while there is a check (package.json: an empty Code Notes view steps aside). */ export const CHECK_OPEN_CONTEXT = 'codeNotes.checkOpen' +/** The context key that is true on a default branch with no check file (package.json: the Check view is hidden there). */ +export const CHECK_ON_BASE_CONTEXT = 'codeNotes.checkOnBase' /** Where the view's Install sends someone without Claude Code. */ export const INSTALL_URL = 'https://claude.com/claude-code' diff --git a/src/check/controller.ts b/src/check/controller.ts index ef38bbd..380209b 100644 --- a/src/check/controller.ts +++ b/src/check/controller.ts @@ -13,10 +13,11 @@ import { gradeFailure } from './failures' import { Coalesced } from '../core/serial' import { plural } from '../core/text' import { BackgroundQuestions } from './background' +import { usesCheck } from './backgroundRule' import { CliThread } from './cliThread' import { Concerns } from './concern' import { - CHECK_OPEN_CONTEXT, FIX_REFRESH_MS, INSTALL_URL, REFRESH_SOON_MS, REPO_FILES, REVEAL_RETRY_MS, SETTINGS, settingId, SKILL, VIEW_ID, + CHECK_ON_BASE_CONTEXT, CHECK_OPEN_CONTEXT, FIX_REFRESH_MS, INSTALL_URL, REFRESH_SOON_MS, REPO_FILES, REVEAL_RETRY_MS, SETTINGS, settingId, SKILL, VIEW_ID, } from './constants' import { Grader } from './grading' import type { CheckHost } from './host' @@ -33,6 +34,7 @@ import type { FromCheck, ToCheck } from '../protocol/check' import { Writer } from './writer' import { baseName } from '../core/paths' import { fireAndForget } from '../platform/run' +import { setCtx } from '../platform/context' import { HiddenCmd } from '../platform/commands' import { checkLinkKey } from '../platform/keys' import { type CheckCore, CheckState, serialScoped } from './state' @@ -109,6 +111,8 @@ export class CheckController implements CheckQuery, vscode.Disposable { /** The codeNotes.checkOpen context as last set. */ private checkOpen: boolean | undefined + /** The codeNotes.checkOnBase context as last set. */ + private onBase = false /** An opened question's reveal retries (REVEAL_RETRY_MS). */ private revealTimers: NodeJS.Timeout[] = [] private subs: vscode.Disposable[] = [] @@ -141,7 +145,10 @@ export class CheckController implements CheckQuery, vscode.Disposable { park: (branch) => this.parking.park(branch), }) this.concerns = new Concerns({ ...core, host, push: this.push }) - this.background = new BackgroundQuestions({ ...core, host, refreshSoon: (ms, force) => this.refreshSoon(ms, force), writer: this.writer }) + this.background = new BackgroundQuestions({ + ...core, host, refreshSoon: (ms, force) => this.refreshSoon(ms, force), writer: this.writer, + usesCheck: (refs) => (this.state.repo ? usesCheck(this.state.repo, refs) : Promise.resolve(false)), + }) this.invalid = new InvalidFile(core) this.view = new CheckViewProvider(host.extUri, host.log, (m) => this.onView(m)) this.subs.push(vscode.window.registerWebviewViewProvider(VIEW_ID, this.view, { webviewOptions: { retainContextWhenHidden: true } })) @@ -287,6 +294,9 @@ export class CheckController implements CheckQuery, vscode.Disposable { if (st?.check) await this.threads.sync(st.check) // While there is a check, an empty Code Notes view steps aside: the Check view gets its room (package.json). this.setCheckOpen(!!st?.check) + // On a default branch with no check file there is nothing to check: the Check view is hidden (package.json). + this.onBase = !!st?.onBase && !st.exists + fireAndForget(setCtx(CHECK_ON_BASE_CONTEXT, this.onBase), 'controller: checkOnBase') // A file that can't be read (a bad edit, a conflict) keeps the tour shown as it was until it reads again. if (st?.state.phase !== 'invalid') await this.host.tourChanged(st?.check, this.state.abs, st?.branch) this.post() @@ -622,7 +632,7 @@ export class CheckController implements CheckQuery, vscode.Disposable { snapshot() { const st = this.state.st, item = this.status.state() return { - itemLabel: item.label, tourBusy: !!this.writer.touring, bg: this.background.trace, + itemLabel: item.label, tourBusy: !!this.writer.touring, bg: this.background.trace, onBase: this.onBase, status: st && { ...st, check: undefined }, words: this.state.words, item: item.text, itemWarn: item.warn, view: this.current(), panel: this.view.state(), grading: [...this.grader.grading.keys()], errors: [...this.grader.errors.values()].map((e) => e.message), refreshes: { ...this.counts }, diff --git a/src/check/wiring.ts b/src/check/wiring.ts index 0351cdd..022c786 100644 --- a/src/check/wiring.ts +++ b/src/check/wiring.ts @@ -36,7 +36,8 @@ export function checkHost(extUri: vscode.Uri, { store, tour }: CheckPorts): Chec allowed: (what) => agentRunner().allowed(what), model: checkModel, changed: noteChanged, - addReply: (n, text) => addReply(n, text), + // The thread's status as it is: the check resolves and opens its threads itself (no "Reopened" by the person). + addReply: (n, text) => addReply(n, text, n.data.status), reveal: (n, col, keep) => reveal(n, col ?? tour.codeColumn(), keep), refresh: () => notesChanged({ kind: 'activity' }), codeColumn: () => tour.codeColumn(), diff --git a/test/check-panel/shoot.mjs b/test/check-panel/shoot.mjs index 36f63e3..a91c97f 100644 --- a/test/check-panel/shoot.mjs +++ b/test/check-panel/shoot.mjs @@ -164,9 +164,44 @@ async function oddIdRedraw(page, view, fail) { await page.waitForTimeout(50) } +/** Warnings (a flag, a concern, a failure, a warning title) are read in the text colour: ≥ 4.5:1 on what is behind + * them; only their ⚠ is in the warning colour. */ +async function warningContrast(page, view, fail) { + const low = await page.evaluate(() => { + const rgb = (c) => (c.match(/[\d.]+/g) || []).map(Number) + const lum = ([r, g, b]) => { + const f = (v) => { v /= 255; return v <= 0.03928 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4 } + return 0.2126 * f(r) + 0.7152 * f(g) + 0.0722 * f(b) + } + const behind = (e) => { + for (let x = e; x; x = x.parentElement) { + const c = rgb(getComputedStyle(x).backgroundColor) + if (c.length >= 3 && (c[3] ?? 1) > 0) return c + } + return [255, 255, 255] + } + const ratio = (a, b) => { const [hi, lo] = [lum(a), lum(b)].sort((x, y) => y - x); return (hi + 0.05) / (lo + 0.05) } + const out = [] + for (const e of document.querySelectorAll('.flag, .answer .concern p:first-child, .failed, .tone-warn .title')) { + const r = ratio(rgb(getComputedStyle(e).color), behind(e)) + if (r < 4.5) out.push(`"${e.textContent.slice(0, 30)}" ${r.toFixed(1)}:1`) + } + for (const e of document.querySelectorAll('.flag, .answer .concern p:first-child')) { + if (!e.querySelector('.warn-mark')) out.push(`"${e.textContent.slice(0, 30)}" has no ⚠ mark`) + } + // One ⚠ per warning: in its text, or drawn before it by the CSS. + for (const e of document.querySelectorAll('.flag, .answer .concern p:first-child, .failed, .tone-warn .title')) { + const marks = (e.textContent.match(/⚠/g) || []).length + (getComputedStyle(e, '::before').content.includes('⚠') ? 1 : 0) + if (marks !== 1) out.push(`"${e.textContent.slice(0, 30)}" has ${marks} ⚠`) + } + return out + }) + if (low.length) fail(`warnings hard to read: ${low.join('; ')}`) +} + /** In the order they run on each drawn view; what the page posted is forgotten before each, so a check passes only on * what its own actions posted. */ -const CHECKS = [arrowDown, rowClick, answerBox, concernAction, nextQuestion, alsoTick, tourLink, mergeRequest, notFoundLinks, gradeRetry, mainButton, clampedQuestions, oddIdRedraw] +const CHECKS = [arrowDown, rowClick, answerBox, concernAction, nextQuestion, alsoTick, tourLink, mergeRequest, notFoundLinks, gradeRetry, mainButton, clampedQuestions, warningContrast, oddIdRedraw] // ---------- main ---------- diff --git a/test/checkBackground.test.ts b/test/checkBackground.test.ts new file mode 100644 index 0000000..ae6fb1c --- /dev/null +++ b/test/checkBackground.test.ts @@ -0,0 +1,69 @@ +// Questions written in the background after a push: only in a repository that uses the check +// (src/check/backgroundRule.ts). +import { test } from 'node:test' +import assert from 'node:assert/strict' +import * as fs from 'fs' +import { BackgroundWrites, type PushedPorts, usesCheck } from '../src/check/backgroundRule' +import type { CheckState } from '../src/check/state' +import type { BranchStatus } from '../src/check/types' +import { gitRepo } from './helpers/gitRepo' + +/** A branch with a change and no check, pushed; `usesCheck`: what the repository says. */ +function fakeRepo(o: { usesCheck: boolean; st?: Partial<BranchStatus>; enabled?: boolean }) { + const st = { branch: 'feat/x', file: 'understanding/feat-x.json', changed: 12, exists: false, baseRef: 'origin/main', state: { phase: 'none' }, ...o.st } as BranchStatus + const stored = new Map<string, unknown>() + const writes: unknown[] = [] + const asked: string[][] = [] + const ports: PushedPorts = { + state: { st } as CheckState, + refresh: async () => undefined, + stored: { get: (k) => (stored.get(k.key) ?? k.fallback) as never, set: async (k, v) => { stored.set(k.key, v) } }, + enabled: () => o.enabled ?? true, + usesCheck: async (refs) => { asked.push(refs); return o.usesCheck }, + writer: { writing: undefined, write: async (...a: unknown[]) => { writes.push(a) } } as unknown as PushedPorts['writer'], + } + return { bg: new BackgroundWrites(ports), writes, asked } +} + +test('a push in a repository that does not use the check starts no background run', async () => { + const r = fakeRepo({ usesCheck: false }) + assert.equal(await r.bg.pushed('feat/x', 'c1'), false) + assert.equal(r.writes.length, 0) + assert.deepEqual(r.asked, [['HEAD', 'origin/main']], 'asked about HEAD and the branch compared with') +}) + +test('a push in a repository that uses the check writes its questions, once per commit', async () => { + const r = fakeRepo({ usesCheck: true }) + assert.equal(await r.bg.pushed('feat/x', 'c1'), true) + assert.equal(await r.bg.pushed('feat/x', 'c1'), false, 'the same commit again: no second run') + assert.deepEqual(r.writes, [[false, { background: true }]]) +}) + +test('no run on a default branch, with the setting off, or when the branch has a check', async () => { + for (const r of [ + fakeRepo({ usesCheck: true, st: { onBase: true } }), + fakeRepo({ usesCheck: true, enabled: false }), + fakeRepo({ usesCheck: true, st: { exists: true, state: { phase: 'answering' } as BranchStatus['state'] } }), + ]) { + assert.equal(await r.bg.pushed('feat/x', 'c1'), false) + assert.equal(r.writes.length, 0) + } +}) + +test('usesCheck: understanding/config.json, or a check file committed at a ref; nothing else', async () => { + const repo = gitRepo({ prefix: 'uses-check-' }) + try { + assert.equal(await usesCheck(repo.dir, ['HEAD', 'main']), false, 'a repository without the check') + assert.equal(await usesCheck(repo.dir, ['no-such-ref']), false, 'a ref that does not exist') + repo.write({ 'understanding/config.json': '{}' }) + assert.equal(await usesCheck(repo.dir, []), true, 'its settings, even uncommitted') + fs.rmSync(`${repo.dir}/understanding`, { recursive: true }) + repo.git('checkout', '-q', '-b', 'feat/a') + repo.commit('check', { 'understanding/feat-a.json': '{}' }) + repo.git('checkout', '-q', 'main') + assert.equal(await usesCheck(repo.dir, ['HEAD']), false, 'not committed on main') + assert.equal(await usesCheck(repo.dir, ['HEAD', 'feat/a']), true, 'committed at feat/a') + } finally { + fs.rmSync(repo.dir, { recursive: true, force: true }) + } +}) diff --git a/test/goldens/check-model/view-names.json b/test/goldens/check-model/view-names.json index d3b2420..40f97e8 100644 --- a/test/goldens/check-model/view-names.json +++ b/test/goldens/check-model/view-names.json @@ -66,6 +66,7 @@ "VIEW_ID": "codeNotes.check", "STATUS_ITEM_ID": "codeNotes.understanding", "CHECK_OPEN_CONTEXT": "codeNotes.checkOpen", + "CHECK_ON_BASE_CONTEXT": "codeNotes.checkOnBase", "INSTALL_URL": "https://claude.com/claude-code", "SETTINGS": { "model": "understanding.model", diff --git a/test/integration/check/answers.ts b/test/integration/check/answers.ts index b491ef3..cd6e350 100644 --- a/test/integration/check/answers.ts +++ b/test/integration/check/answers.ts @@ -212,6 +212,9 @@ export const answersTests = [ assert.ok(noteOf('q2').messages.some((m: any) => /^It retries with backoff/.test(m.body)), 'the explanation stays after saying it back') assert.deepEqual(readCheck().questions[1].attempts.map((a: any) => a.verdict), ['retry', 'explained', 'restated']) assert.equal(view().rows[1].word, 'in your words') + // Saying it back changed no thread status: no "Reopened" row by the person in the question's thread. + assert.ok(!(noteOf('q2').events ?? []).some((e: any) => e.type === 'reopened'), 'no reopened event') + assert.ok(!threadComments(noteOf('q2').id).some((c) => commentBody(c) === '_Reopened_'), 'no "Reopened" row in the thread') await pageShot('check-2-restated') }), diff --git a/test/integration/check/branches.ts b/test/integration/check/branches.ts index 5d31ad0..ec0fbe1 100644 --- a/test/integration/check/branches.ts +++ b/test/integration/check/branches.ts @@ -49,8 +49,11 @@ export const branchesTests = [ // Notes made from the check (Ask Claude on a question, Suggest a fix) belong to the branch too: hidden, never "file not found". await until('notes from the check hidden on main', () => !notesFromCheck().length && !api.thread(left.askedNote.id) && !api.thread(left.fixNote.id)) assert.equal(left.askedNote.extra?.checkFile, 'understanding/feat-limits.json') + // The default branch with no check file: codeNotes.checkOnBase hides the Check view (package.json). + await until('codeNotes.checkOnBase on main', () => chk().onBase === true) } finally { backTo('feat/limits') } await until('back on the branch', () => checkNotes().length === 3 && notesFromCheck().every((n) => !n.missing)) + assert.equal(chk().onBase, false, 'a feature branch shows the Check view') }), test('a branch switch while questions are written: they are written for the branch and commit they were started on, kept in .code-notes/.cache (git-ignored), nothing touches the branch checked out, and they are put in place on return', async () => { From 57691dda4aa84ef1c228c4155a90e1a6ad48e2e7 Mon Sep 17 00:00:00 2001 From: tomeyer97 <107920881+tomeyer97@users.noreply.github.com> Date: Thu, 26 Nov 2026 20:47:46 +0100 Subject: [PATCH 11/17] Listen: speed remembered, damaged audio in Problems, one player at a time Slice: S12 Zeroshot-Run: 01a21944-3e8b-7562-8023-24e07db18a46 --- media/listen.js | 9 +- media/podcast/players.js | 9 +- src/podcast/audioHost.ts | 25 ++++- src/podcast/library.ts | 26 +++-- src/podcast/listenView.ts | 10 +- src/podcast/player.ts | 23 ++-- src/podcast/statusItem.ts | 28 +++-- src/podcast/testing.ts | 3 + test/integration/main/podcast/brokenFiles.ts | 25 +++++ test/integration/main/podcast/camera.ts | 2 +- test/integration/main/podcast/playback.ts | 66 +++++++++--- test/journey-podcast/fakeVscode.ts | 18 +++- test/journey-podcast/pages.mjs | 9 +- test/journey-podcast/shoot.mjs | 15 ++- test/podcastOnePlayer.test.ts | 107 +++++++++++++++++++ 15 files changed, 319 insertions(+), 56 deletions(-) create mode 100644 test/podcastOnePlayer.test.ts diff --git a/media/listen.js b/media/listen.js index c23b0e5..426af51 100644 --- a/media/listen.js +++ b/media/listen.js @@ -1,10 +1,11 @@ // The Listen view (src/podcast/listenView.ts): where a journey's audio plays; the page's script, bundled as // out/pages/listen.js. VS Code keeps the view alive while hidden, so the episode goes on when the journey panel -// closes. It is there only while a journey is listened to: nothing to say before one is loaded. It shows the journey, -// the part being talked about, and the player (journey-podcast.js), which starts as the audio's host. +// closes. It is there only while a journey is listened to and the journey panel does not have its audio: nothing to +// say before one is loaded. It shows the journey, the part being talked about, and the player (journey-podcast.js), +// which starts as the audio's host. // -// One player on screen: while the journey panel shows this episode, the panel's player is the one to use, and this -// view is one line (the journey, ⏸ / ▶ and the time). +// One player on screen: while the journey panel shows this episode (the audio playing here), the panel's player is +// the one to use, and this view is one line (the journey, ⏸ / ▶ and the time). // // Its messages both ways are src/protocol/listen.ts (ToListen, FromListen). import { el, connect, onMessages } from './common.js' diff --git a/media/podcast/players.js b/media/podcast/players.js index 3c40ef5..83af738 100644 --- a/media/podcast/players.js +++ b/media/podcast/players.js @@ -283,7 +283,13 @@ export class HostPlayer { this.ctx.draw() } toggle() { if (this.state().playing) this.pause(); else this.play() } + /** The speed, said at once (as the muting is): the extension keeps it, also when it is set before the audio loads. */ setRate(r) { + this.speed(r) + this.ctx.draw() + this.report(false) + } + speed(r) { this.audio.playbackRate = r this.audio.defaultPlaybackRate = r } @@ -330,7 +336,8 @@ export class HostPlayer { * episode before. */ start(ep, cue) { Object.assign(this, freshHostState(cue.at, cue.play, cue.until)) - this.setRate(knownRate(cue.rate)) + // Not said here: until it loads, the audio is still the episode before's. + this.speed(knownRate(cue.rate)) this.audio.muted = !!cue.muted this.load(ep) } diff --git a/src/podcast/audioHost.ts b/src/podcast/audioHost.ts index a7d16c1..29cd350 100644 --- a/src/podcast/audioHost.ts +++ b/src/podcast/audioHost.ts @@ -11,6 +11,9 @@ // // listen --(Listen view locked, panel unlocked and showing the journey)--> panel // panel --(the panel closes, or shows another journey)--> listen +// +// One player at a time: while the panel has the audio the Listen view is not there (statusItem.ts), and VS Code drops +// its page then; the audio going back makes it again (paused where it was: a new page needs a click to play). import * as vscode from 'vscode' import type { FromListen } from '../protocol/listen' import type { FromPlayer, PodcastAsk, PodcastEpisode, PodcastHostState, PodcastUnavailable, ToPlayer } from '../protocol/podcast' @@ -47,6 +50,8 @@ export interface AudioHostClient { end(lj: LoadedJourney, action: 'walk' | 'next'): Promise<void> /** The Listen view went with the audio in it. */ lost(): void + /** The audio moved to the other player. */ + moved(): void } export class AudioHost implements vscode.Disposable { @@ -86,6 +91,8 @@ export class AudioHost implements vscode.Disposable { alive(): boolean { return this.where === 'panel' ? !!this.hostKey && this.ports.mapPanel().journey?.key === this.hostKey : this.listen.alive } + /** The journey panel has the audio (its player is the one on screen; the Listen view goes). */ + get panelHosts(): boolean { return this.where === 'panel' && this.alive() } /** The host has journey `key`'s episode and takes commands. */ has(key: string): boolean { return this.hostKey === key && this.alive() } @@ -142,13 +149,25 @@ export class AudioHost implements vscode.Disposable { this.listen.send({ type: 'podcast', episode: this.client.episodeFor(lj, (u) => this.listen.toUri(u)) }) this.send({ type: 'podcastRole', role: 'host', ...cue }) this.log().info(`podcast ${lj.j.id}: the audio plays in the ${to === 'panel' ? 'journey panel' : 'Listen view'}${cue.play ? '' : ' (paused)'}`) + this.client.moved() + } + + /** The panel's audio back to the Listen view: at once when the view is there, else once it is made again (the + * panel stops being the host now: it may be showing another journey already). */ + private backToListen(lj: LoadedJourney, cue: Cue): void { + if (this.listen.alive) { this.moveTo('listen', lj, cue); return } + if (this.ports.mapPanel().journey) this.ports.mapPanel().send({ type: 'podcastRole', role: 'remote' }) + this.where = 'listen' + this.forget() + this.client.moved() + fireAndForget(this.load(lj, cue).then((ok) => { if (!ok) this.client.lost() }), 'podcast: load the host') } /** The panel is about to show `lj`: playing another journey's audio, that audio goes to the Listen view first. */ panelShows(lj: LoadedJourney): void { if (this.where === 'panel' && this.hostKey && this.hostKey !== lj.key) { const was = this.journey(this.hostKey) - if (was) this.moveTo('listen', was, { at: this.client.nowOf(was), play: this.client.playing() }) + if (was) this.backToListen(was, { at: this.client.nowOf(was), play: this.client.playing() }) else this.where = 'listen' } this.listen.send({ type: 'panel', key: lj.key }) @@ -160,8 +179,8 @@ export class AudioHost implements vscode.Disposable { this.unlocked.panel = false if (this.where !== 'panel') return const lj = this.journey(this.hostKey) - this.where = 'listen' - if (lj) this.moveTo('listen', lj, { at: this.client.nowOf(lj), play: this.client.playing() }) + if (lj) this.backToListen(lj, { at: this.client.nowOf(lj), play: this.client.playing() }) + else this.where = 'listen' } /** diff --git a/src/podcast/library.ts b/src/podcast/library.ts index 7914541..c8c506a 100644 --- a/src/podcast/library.ts +++ b/src/podcast/library.ts @@ -36,8 +36,9 @@ export class PodcastLibrary { private broken = new Map<string, Broken>() /** The audio's real length as the host loaded it, by audioKey. */ private audioLen = new Map<string, number>() - /** An audio file the host failed to play, by audioKey: what to say (it looks cut off or damaged). */ - private audioFault = new Map<string, string>() + /** An audio file the host failed to play, by audioKey: what to say (it looks cut off or damaged), and the media + * pipeline's own words (the output has them). */ + private audioFault = new Map<string, { text: string; detail: string }>() constructor(private readonly journeys: () => Journeys, private readonly log: () => vscode.LogOutputChannel) {} @@ -55,7 +56,7 @@ export class PodcastLibrary { */ async scan(keepsLast: (key: string, last: Loaded) => boolean): Promise<Scanned> { const reads = await this.readAll() - podcastReports.report(reads.map((r) => r.read)) + podcastReports.report(reads.map((r) => this.withFault(r.read))) const next = new Map<string, Loaded>() const broken = new Map<string, Broken>() for (const { lj, read } of reads) { @@ -91,8 +92,16 @@ export class PodcastLibrary { return { file: r.file, reason: r.v.problems.find((p) => p.level === 'error')?.message ?? 'it has errors' } } + /** `r` as the Problems view and the output tell it: with its audio's failure to play, on "audio". */ + private withFault(r: PodcastRead): PodcastRead { + const fault = r.audio && this.audioFault.get(audioKey(r.audio, r.audioSize)) + if (!fault) return r + const problem: PodcastProblem = { level: 'warning', code: 'audio', message: `${fault.text} (${fault.detail})`, path: ['audio'] } + return { ...r, v: { ...r.v, problems: [...r.v.problems, problem] } } + } + private loaded(r: PodcastRead, episode: Episode, audio: vscode.Uri): Loaded { - const notice = this.audioFault.get(audioKey(audio, r.audioSize)) ?? playNotice(r.v.problems) + const notice = this.audioFault.get(audioKey(audio, r.audioSize))?.text ?? playNotice(r.v.problems) return { file: r.file, audio, audioSize: r.audioSize, episode, problems: r.v.problems, notice, sig: `${r.raw.length}:${r.audioSize}:${JSON.stringify(episode.segments.map((s) => [s.start, s.step, s.beat]))}`, @@ -116,11 +125,12 @@ export class PodcastLibrary { return true } - /** `pod`'s audio can't be decoded: `text` says so, on journey `key`'s podcast. True when it is new. */ - fault(key: string, pod: Loaded, text: string): boolean { + /** `pod`'s audio can't be decoded: `text` says so, on journey `key`'s podcast (`detail`: the media pipeline's + * words). True when it is new. */ + fault(key: string, pod: Loaded, text: string, detail: string): boolean { const audio = audioKey(pod.audio, pod.audioSize) - if (this.audioFault.get(audio) === text) return false - this.audioFault.set(audio, text) + if (this.audioFault.get(audio)?.text === text) return false + this.audioFault.set(audio, { text, detail }) this.playable.set(key, { ...pod, notice: text }) return true } diff --git a/src/podcast/listenView.ts b/src/podcast/listenView.ts index a4867a0..6721999 100644 --- a/src/podcast/listenView.ts +++ b/src/podcast/listenView.ts @@ -2,8 +2,10 @@ // (media/listen.js, with media/journey-podcast.js as the host; the panel's remote while the panel plays it: // audioHost.ts). VS Code keeps it alive while hidden (retainContextWhenHidden), so the episode goes on when the journey // panel closes, is behind another tab, or the side bar is closed; the panel's player is mostly a remote of this one -// (audioHost.ts relays). The view is there only while a journey is listened to (`codeNotes.listening`, statusItem.ts); it is -// made only once it has been shown: `ensure()` brings it in and shows it once, then gives the keyboard back. +// (audioHost.ts relays). The view is there only while a journey is listened to and the panel does not have its audio +// (`codeNotes.listening`, statusItem.ts): VS Code drops a view's page when its `when` turns false, so it goes only +// while the audio is elsewhere. It is made only once it has been shown: `ensure()` brings it in and shows it once, +// then gives the keyboard back. // // Why there and not in the bottom panel: the ▶ people press first is on a Journeys row, right above it, so the view is // usually already on screen (no panel pops up over the code), and it is small enough to stay open. @@ -18,8 +20,10 @@ import { setCtx } from '../platform/context' import { fireAndForget } from '../platform/run' export const LISTEN_VIEW = 'codeNotes.listen' -/** The context key that brings the view in (package.json: the view's and the transport commands' `when`). */ +/** The context key that brings the view in (package.json: the view's `when`). */ export const LISTENING_CTX = 'codeNotes.listening' +/** A journey is listened to, wherever its audio is (for the transport commands' `when`). */ +export const LISTEN_SESSION_CTX = 'codeNotes.listenSession' /** The command VS Code makes for the view: it shows the view (and makes it, the first time). */ const LISTEN_FOCUS = 'codeNotes.listen.focus' /** How long a new view's page has to say it is ready (ms). */ diff --git a/src/podcast/player.ts b/src/podcast/player.ts index 285a843..e3745b6 100644 --- a/src/podcast/player.ts +++ b/src/podcast/player.ts @@ -167,6 +167,7 @@ export class Podcasts implements vscode.Disposable { open: () => this.openSessionMap(), end: (lj, action) => this.onEnd(lj, action), lost: () => this.hostLost(), + moved: () => this.renderItem(), } } @@ -410,10 +411,11 @@ export class Podcasts implements vscode.Disposable { this.marks.show(lj, pod, t, false, this.session.playing, this.session.rate) } - /** The audio's state: the muting remembered; the episode's end said on the row and the status item. */ + /** The audio's state: the speed and the muting remembered (a speed set before the audio is loaded is said only + * here); the episode's end said on the row and the status item. */ private onState(m: PodcastHostState): void { if (!this.host.relayState(m)) return - if (typeof m.muted === 'boolean') this.store.muted = m.muted + this.remember(m) if (m.ended !== this.session.ended) { this.session.ended = !!m.ended this.renderItem() @@ -421,6 +423,12 @@ export class Podcasts implements vscode.Disposable { } } + /** The speed and the muting a player says or asks for, kept for every journey and the next window. */ + private remember(m: { rate?: number; muted?: boolean }): void { + if (typeof m.rate === 'number' && m.rate > 0) this.store.rate = m.rate + if (typeof m.muted === 'boolean') this.store.muted = m.muted + } + /** The host loaded the audio of journey `of` (else the one shown): its real length, checked against the file (a * cut-off audio, a wrong "duration"). */ private onAudioMeta(shown: LoadedJourney, duration: number, of?: string): void { @@ -450,14 +458,15 @@ export class Podcasts implements vscode.Disposable { } /** The media pipeline's own words ("PIPELINE_ERROR_READ: FFmpegDemuxer …") mean nothing to an author: the file and - * what it most likely is. */ + * what it most likely is, in the panel, on the row, and (the next scan reports it) in the Problems view on the + * podcast's "audio" and in the output, with the pipeline's words. */ private audioDamaged(lj: LoadedJourney, pod: Loaded, message: string): void { const name = vscode.workspace.asRelativePath(pod.audio, false) const text = `The audio ${name} (${fileSize(pod.audioSize)}) can't be played at ${clock(this.store.posOf(lj))}: the file looks cut off or damaged` - log().warn(`podcast ${pod.file.fsPath}: ${text} (${message})`) - if (!this.library.fault(lj.key, pod, text)) return + if (!this.library.fault(lj.key, pod, text, message)) return this.mapPanel.sendPodcast() this.ports.refreshJourneyList() + fireAndForget(this.scan(), 'podcast: scan') } /** The Listen view went with the audio in it: its place is kept. */ @@ -489,6 +498,8 @@ export class Podcasts implements vscode.Disposable { if (!this.library.has(key)) return const loaded = this.host.has(key) const { action } = m + // The reader's choice, also when no audio is loaded to take it. + if (action === 'rate' || action === 'mute') this.remember(m) if (action === 'play' || action === 'toggle') { // A ▶ in the panel while only the panel's audio may play: play() moves it there. if (loaded && this.session.is(key) && !(this.host.in === 'listen' && this.host.panelPlays(key))) { @@ -706,7 +717,7 @@ export class Podcasts implements vscode.Disposable { /** The status item drawn for the session as it is. */ private renderItem(): void { - this.statusItem.render({ journey: this.listening(), playing: this.session.playing, ended: this.session.ended, t: this.sessionTime, panelOnScreen: this.mapPanel.visible }) + this.statusItem.render({ journey: this.listening(), playing: this.session.playing, ended: this.session.ended, t: this.sessionTime, panelOnScreen: this.mapPanel.visible, panelHosts: this.host.panelHosts }) } dispose(): void { for (const d of this.subs) d.dispose() } diff --git a/src/podcast/statusItem.ts b/src/podcast/statusItem.ts index d2aa0ab..5473d5a 100644 --- a/src/podcast/statusItem.ts +++ b/src/podcast/statusItem.ts @@ -1,6 +1,7 @@ -// The Listen status item: while a journey is listened to and its panel (the player) is not on screen, "Listening · -// 6:58" or "Paused · 6:58", click: the journey's map. Gone once the episode ended. The walk's own item steps aside -// while a journey is listened to (one item), and the Listen view is there only then (`codeNotes.listening`). +// The Listen status item: while a journey is listened to and its panel (the player) is not on screen, "Listening: +// <journey> · 6:58" or "Paused: <journey> · 6:58", click: the journey's map. Gone once the episode ended. The walk's +// own item steps aside while a journey is listened to (one item). The Listen view is there only while a journey is +// listened to and the panel does not have its audio (`codeNotes.listening`): one player at a time. import * as vscode from 'vscode' import { clock } from '../core/format/podcast/model' import type { LoadedJourney } from '../journeys/steps' @@ -8,13 +9,16 @@ import { chordKey } from '../platform/chordKey' import { Cmd } from '../platform/commands' import { setCtx } from '../platform/context' import { fireAndForget } from '../platform/run' -import { LISTENING_CTX } from './listenView' +import { LISTEN_SESSION_CTX, LISTENING_CTX } from './listenView' /** The Listen view goes this long (ms) after the last journey stopped being listened to (another may start). */ const LISTENING_OFF_MS = 3000 -/** What the item shows. */ -export interface ItemState { journey: LoadedJourney | undefined; playing: boolean; ended: boolean; t: number; panelOnScreen: boolean } +/** A journey's title on the item: this long at most. */ +const TITLE_MAX = 32 + +/** What the item shows. `panelHosts`: the journey panel has the audio (its player is the one; the Listen view goes). */ +export interface ItemState { journey: LoadedJourney | undefined; playing: boolean; ended: boolean; t: number; panelOnScreen: boolean; panelHosts: boolean } export class ListenStatusItem implements vscode.Disposable { private readonly item = vscode.window.createStatusBarItem('codeNotes.listen', vscode.StatusBarAlignment.Left, 49.25) @@ -39,11 +43,14 @@ export class ListenStatusItem implements vscode.Disposable { /** Draws the item (no side effects beyond it); a change of whether a journey is listened to is passed on first. */ render(s: ItemState): void { if (!!s.journey !== this.listening) this.sessionChanged(!!s.journey) + // The view goes at once when the panel takes the audio (VS Code drops a hidden view's page: never the audio's). + if (s.journey) fireAndForget(setCtx(LISTENING_CTX, !s.panelHosts), 'podcast: setCtx LISTENING_CTX') const lj = s.journey this.on = !!lj && !(s.ended && !s.playing) && !s.panelOnScreen if (!lj) { this.item.hide(); return } const state = s.playing ? 'Listening' : 'Paused' - this.item.text = `${state} · ${clock(s.t)}` + const title = lj.j.title.length > TITLE_MAX ? `${lj.j.title.slice(0, TITLE_MAX - 1)}…` : lj.j.title + this.item.text = `${state}: ${title} · ${clock(s.t)}` this.item.tooltip = `${s.playing ? 'Pause' : 'Play'} (${chordKey()} Space) · click: the map` this.item.accessibilityInformation = { label: `${state}: ${lj.j.title}, ${clock(s.t)}. Opens the journey's map.` } if (this.on) this.item.show() @@ -57,7 +64,7 @@ export class ListenStatusItem implements vscode.Disposable { if (on) { clearTimeout(this.listeningOff) this.listeningOff = undefined - fireAndForget(setCtx(LISTENING_CTX, true), 'podcast: setCtx LISTENING_CTX') + fireAndForget(setCtx(LISTEN_SESSION_CTX, true), 'podcast: setCtx LISTEN_SESSION_CTX') } else this.viewOffLater() this.listeningChanged() } @@ -72,8 +79,9 @@ export class ListenStatusItem implements vscode.Disposable { this.listeningOff = setTimeout(() => { this.listeningOff = undefined if (this.listening) return - if (this.idle()) fireAndForget(setCtx(LISTENING_CTX, false), 'podcast: setCtx LISTENING_CTX') - else this.viewOffLater() + if (!this.idle()) { this.viewOffLater(); return } + fireAndForget(setCtx(LISTENING_CTX, false), 'podcast: setCtx LISTENING_CTX') + fireAndForget(setCtx(LISTEN_SESSION_CTX, false), 'podcast: setCtx LISTEN_SESSION_CTX') }, LISTENING_OFF_MS) } diff --git a/src/podcast/testing.ts b/src/podcast/testing.ts index df6d3e0..15e6b31 100644 --- a/src/podcast/testing.ts +++ b/src/podcast/testing.ts @@ -43,6 +43,9 @@ function snapshot(p: Podcasts, ports: Pick<PodcastPorts, 'journeys' | 'mapPanel' unlocked: host.unlocks, hostAlive: host.alive(), hostVisible: host.listen.visible, + panelHosts: host.panelHosts, + rate: p.store.rate, + muted: p.store.muted, ended: session.ended, error: seen.error, moves: seen.moves, diff --git a/test/integration/main/podcast/brokenFiles.ts b/test/integration/main/podcast/brokenFiles.ts index c660c3a..799dc43 100644 --- a/test/integration/main/podcast/brokenFiles.ts +++ b/test/integration/main/podcast/brokenFiles.ts @@ -129,4 +129,29 @@ export const brokenFileTests = [ fs.writeFileSync(podFile(), good) await podUntil('back to the fixture\'s one warning', () => pod().notices.pod === '1 problem' && problems().length === 1, MOVE_MS) }, { consoleClean: true }), + + // An audio that can't be decoded (text named .mp3) is said in the panel, and in the Problems view on the podcast's + // "audio", as every other problem of a podcast is. + podTest('broken file › an audio that can\'t be decoded is in the Problems view', async () => { + writePodJourney() + await podUntil('its podcast is found', () => pod().journeys.includes('pod'), LOAD_MS) + const good = fs.readFileSync(podFile(), 'utf8') + const damaged = path.join(journeysDir(), 'pod-damaged.mp3') + fs.writeFileSync(damaged, 'not audio\n'.repeat(800)) + fs.writeFileSync(podFile(), JSON.stringify({ ...JSON.parse(good), audio: 'pod-damaged.mp3' }, null, 2)) + const isDamaged = (d: vscode.Diagnostic) => /pod-damaged\.mp3 .*looks cut off or damaged/.test(d.message) + try { + await podUntil('the podcast reads the other audio', () => pod().journeys.includes('pod') && !problems().some(isDamaged), MOVE_MS) + await vscode.commands.executeCommand('codeNotes.playPodcast', 'pod') + await podUntil('the panel says the audio looks damaged', () => /pod-damaged\.mp3 .*looks cut off or damaged/.test(pod().notices.pod ?? ''), LOAD_MS) + await podUntil('and the Problems view', () => problems().some(isDamaged), MOVE_MS) + const d = problems().find(isDamaged)! + assert.equal(d.range.start.line, lineOf(podFile(), '"audio"'), 'on the podcast\'s "audio"') + assert.equal(d.severity, vscode.DiagnosticSeverity.Warning, 'a warning') + } finally { + fs.writeFileSync(podFile(), good) + fs.rmSync(damaged, { force: true }) + } + await podUntil('back to the fixture\'s one warning', () => problems().length === 1 && !problems().some(isDamaged), MOVE_MS) + }), ] diff --git a/test/integration/main/podcast/camera.ts b/test/integration/main/podcast/camera.ts index 270c62e..2aa6f53 100644 --- a/test/integration/main/podcast/camera.ts +++ b/test/integration/main/podcast/camera.ts @@ -227,7 +227,7 @@ export const cameraTests = [ await podUntil('a wait', () => pod().camera.waiting === 'read', MOVE_MS) const a = await podUntil('the audio holds', async () => { const x = await listenAudio(); return x.paused && x }, QUICK_MS) assert.equal(a.note, '', 'no line under the player') - assert.match(pod().item, /^Listening · /, `the status item: ${pod().item}`) + assert.match(pod().item, /^Listening: .+ · /, `the status item: ${pod().item}`) assert.equal(tour().card?.body ?? '', '', 'the step card stays its header line') assert.equal(await playButtonOn(await frameOf('listen')), 'true', 'the Listen view shows ⏸') assert.equal(await playButtonOn(await frameOf('journey')), 'true', 'the panel shows ⏸') diff --git a/test/integration/main/podcast/playback.ts b/test/integration/main/podcast/playback.ts index 813735c..ec947ef 100644 --- a/test/integration/main/podcast/playback.ts +++ b/test/integration/main/podcast/playback.ts @@ -18,9 +18,10 @@ const isPanelTab = (input: unknown) => input instanceof vscode.TabInputWebview & export const playbackTests = [ // VS Code lets a webview's audio play only after a click or a key in that webview (a click in the workbench or in // another webview does not count). Nothing has been clicked yet in this window, so this test runs first: the - // unlock it makes lasts for the window. ▶ from a command plays in the panel after Space there; the panel closed, - // the audio waits in the Listen view; a new panel plays after one real click on its ▶; one click in the Listen view - // unlocks it too. No webview runs a test script before its click (`quiet`). + // unlock it makes lasts for the window. ▶ from a command plays in the panel after Space there, and the Listen view + // goes (one player); the panel closed, the audio waits in the Listen view, back with the journey; a new panel plays + // after one real click on its ▶; one click in the Listen view unlocks it too. No webview runs a test script before + // its click (`quiet`). podTest('podcast › ▶ plays wherever it is pressed', async () => { writeAutoJourney() await podUntil('the podcast is found', () => pod().journeys.includes('podauto'), LOAD_MS) @@ -48,6 +49,7 @@ export const playbackTests = [ await audioMoves(pf, 'played in the panel') assert.equal(await pf.evaluate(() => { const e = (globalThis as any).document.querySelector('.pod-err'); return e.hidden ? '' : e.textContent }), '', 'no hint or error line') assert.ok(pod().unlocked.panel && !pod().unlocked.listen, `the panel unlocked, the Listen view not: ${JSON.stringify(pod().unlocked)}`) + await podUntil('the panel has the audio: the Listen view is not there (codeNotes.listening off)', () => pod().panelHosts && !pod().hostAlive && !pod().hostVisible, QUICK_MS) // 2. Closing the panel: the audio goes to the Listen view, which may not play yet: it waits there, paused, where // it was (the one start that still needs a click: the status item or ▶ opens the panel again). @@ -55,8 +57,8 @@ export const playbackTests = [ await closePanel() await podUntil('back in the Listen view, paused there', () => pod().hostIn === 'listen' && !pod().playing && pod().hostAlive, MOVE_MS) assert.ok(Math.abs(pod().t - tClose) < 2, `kept its place: ${tClose} → ${pod().t}`) - assert.ok(pod().listening && pod().itemShown, 'paused with the panel closed: the Listen view and the status item') - assert.match(pod().item, /^Paused · 0:\d\d$/, `the status item: ${pod().item}`) + assert.ok(pod().listening && pod().itemShown && pod().hostVisible, 'paused with the panel closed: the Listen view back, and the status item') + assert.match(pod().item, /^Paused: Pod auto · 0:\d\d$/, `the status item names the journey: ${pod().item}`) const paused = ctx.api.journeyRow('podauto')! assert.match(paused.description ?? '', /^♪ 0:40/, 'the row: its length') assert.doesNotMatch(paused.description ?? '', /Paused|Listening|step/, `the row says no more while paused: ${paused.description}`) @@ -70,6 +72,7 @@ export const playbackTests = [ const pf2 = await frameOf('journey', { quiet: true }) await realClick(pf2, '.pod-b.play') await podUntil('the click on the panel\'s ▶: playing in the panel', () => pod().playing && pod().hostIn === 'panel', MOVE_MS) + await podUntil('the Listen view went: the panel\'s player is the one', () => !pod().hostAlive && !pod().hostVisible, QUICK_MS) await audioMoves(pf2, 'the panel\'s ▶') assert.ok(Math.abs(pod().t - tClose) < 4, `on from where it was: ${tClose} → ${pod().t}`) @@ -79,15 +82,21 @@ export const playbackTests = [ await podUntil('a command plays at once', () => pod().playing, 4000) await audioMoves(pf2, 'started by a command') - // 5. One click in the Listen view (its ▶, a remote now: it pauses) unlocks it for the window: the panel closing - // then hands it the audio, and later starts play there with no click. - await realClick(await frameOf('listen'), '.pod-b.play') - await podUntil('the Listen view\'s ▶ paused it; the Listen view unlocked', () => !pod().playing && pod().unlocked.listen, MOVE_MS) + // 5. The panel closed again: the Listen view back with the audio, paused. One click on its ▶ plays there and + // unlocks it for the window: a start from a command then plays there at once, and the panel opening for it + // leaves the audio there (the view stays: the audio is in it). + await pause() await closePanel() - await podUntil('the audio back in the Listen view', () => pod().hostIn === 'listen' && pod().hostAlive, MOVE_MS) + await podUntil('the audio back in the Listen view', () => pod().hostIn === 'listen' && pod().hostAlive && pod().hostVisible, MOVE_MS) + const lf = await frameOf('listen', { quiet: true }) + await realClick(lf, '.pod-b.play') + await podUntil('the Listen view\'s ▶ plays there; the Listen view unlocked', () => pod().playing && pod().hostIn === 'listen' && pod().unlocked.listen, MOVE_MS) + assert.equal(await lf.evaluate(() => (globalThis as any).document.querySelector('.ls-title')?.textContent), 'Pod auto', 'the view names the journey') + await pause() await vscode.commands.executeCommand('codeNotes.playPodcast', 'podauto') - await podUntil('a command plays in the Listen view at once', () => pod().playing && pod().hostIn === 'listen', 6000) + await podUntil('a command plays in the Listen view at once', () => pod().playing && pod().hostIn === 'listen' && pod().mapVisible, 6000) await audioMoves(await frameOf('listen'), 'in the Listen view') + assert.ok(pod().hostVisible && !pod().panelHosts, 'the audio stays in the Listen view') await pause() }), @@ -101,7 +110,7 @@ export const playbackTests = [ await podUntil('the Listen view has its audio', () => pod().hostAlive && pod().hostKey !== undefined, LOAD_MS) await podUntil('playing, the time moving', () => pod().playing && pod().t > 0.6, LOAD_MS) assert.equal(tour().step, 0, 'the intro: no step open') - assert.match(pod().item, /^Listening · 0:0\d$/, `the status item's text: ${pod().item}`) + assert.match(pod().item, /^Listening: .+ · 0:0\d$/, `the status item's text: ${pod().item}`) assert.ok(!pod().itemShown, 'no status item while the panel (the player) is on screen') const row = ctx.api.journeyRow('pod')! assert.match(row.description ?? '', /^♪ 0:40/, 'the row: its length') @@ -115,7 +124,7 @@ export const playbackTests = [ await pause() await noChangeFor(500, 'the walk ending on a pause') assert.equal(tour().step, 1, 'pausing the podcast does not end the walk') - assert.match(pod().item, /^Paused · 0:0\d$/, `paused: ${pod().item}`) + assert.match(pod().item, /^Paused: .+ · 0:0\d$/, `paused: ${pod().item}`) assert.ok(!pod().itemShown && !tour().statusShown, 'paused, the panel on screen: no status item at all') await shots('listen-panel-open-paused', true) }), @@ -305,7 +314,7 @@ export const playbackTests = [ await podUntil('the panel closed', () => !pod().mapVisible && tour().map === undefined, QUICK_MS) const t0 = pod().t await podUntil(`still playing without the panel (from ${t0})`, () => pod().playing && pod().t > t0 + 0.8, QUICK_MS) - assert.ok(pod().itemShown && /^Listening · \d:\d\d$/.test(pod().item), `the status item, the panel closed: ${pod().item}`) + assert.ok(pod().itemShown && /^Listening: .+ · \d:\d\d$/.test(pod().item), `the status item, the panel closed: ${pod().item}`) await shots('listen-panel-closed-playing') assert.equal((await listenAudio()).paused, false, 'the audio itself plays on') // The status item's click: the map again, its player showing the audio's time and that it plays. @@ -322,6 +331,35 @@ export const playbackTests = [ await podUntil('paused from the panel', () => !pod().playing, QUICK_MS) }), + // The speed is kept for every journey and the next window (the global state a reload reads): set in the panel while + // paused, and in another journey's panel. + podTest('podcast › the speed is remembered', async () => { + await listenTo('podbeat', writeBeatJourney) + const f = await frameOf('journey') + const speedTo = async (r: number) => { + for (let i = 0; i < 5 && pod().rate !== r; i++) { + await f.click('.pod-rate') + await noChangeFor(300, 'the speed said') + } + await podUntil(`${r}× kept`, () => pod().rate === r, QUICK_MS) + } + try { + await speedTo(1.25) + assert.ok(!pod().playing, 'set while paused') + await play() + await podUntil('playing at 1.25×', async () => (await f.evaluate(() => (globalThis as any).document.querySelector('.pod-rate')?.textContent)) === '1.25×', QUICK_MS) + await pause() + // Another journey's panel: the speed asked there is kept too (also before its audio is loaded). + writePodJourney() + await podUntil('pod read', () => pod().journeys.includes('pod'), LOAD_MS) + await vscode.commands.executeCommand('codeNotes.startJourney', 'pod') + await podUntil('the panel shows pod', () => tour().map === 'pod' && pod().mapVisible, MOVE_MS) + await speedTo(1.5) + } finally { + await speedTo(1) + } + }), + // A journey panel closed while VS Code restores it after a reload: nothing throws (it threw "Webview is disposed" // and failed the activation), the map and the place are kept. podTest('podcast › a restored panel closed at once', async () => { diff --git a/test/journey-podcast/fakeVscode.ts b/test/journey-podcast/fakeVscode.ts index 18110b4..6f49a9a 100644 --- a/test/journey-podcast/fakeVscode.ts +++ b/test/journey-podcast/fakeVscode.ts @@ -37,8 +37,24 @@ export const commands = { }, } +/** A status bar item: what it shows, and whether it is shown. */ +export class StatusBarItem { + text = '' + tooltip: unknown = '' + name = '' + command: unknown + accessibilityInformation: unknown + shown = false + show(): void { this.shown = true } + hide(): void { this.shown = false } + dispose(): void { this.shown = false } +} + +export const StatusBarAlignment = { Left: 1, Right: 2 } + export const window = { registerWebviewViewProvider: () => new Disposable(), + createStatusBarItem: () => new StatusBarItem(), } export const workspace = { @@ -49,7 +65,7 @@ export const workspace = { export class ThemeColor { constructor(readonly id: string) {} } export class ThemeIcon { constructor(readonly id: string) {} } -const api = { Uri, Disposable, EventEmitter, commands, window, workspace, ThemeColor, ThemeIcon } +const api = { Uri, Disposable, EventEmitter, commands, window, workspace, ThemeColor, ThemeIcon, StatusBarAlignment } /** `require('vscode')` gets this module from now on. */ function install(): typeof api { diff --git a/test/journey-podcast/pages.mjs b/test/journey-podcast/pages.mjs index 3437139..9a7e338 100644 --- a/test/journey-podcast/pages.mjs +++ b/test/journey-podcast/pages.mjs @@ -46,14 +46,14 @@ export const tour = (current) => ({ current, marks: {}, resume: 0, legendHidden: /** * The extension's part. `fixture`: the journey, the model's episode (`ep`) and the episode as the pages get it. * `st` keeps what happened: the views the walk was put on (`applied`), the host's reports (`times`, `seeks`, - * `lastT`, `playing`), its log lines (`told`), the end's buttons (`ends`), the remotes' asks (`asks`). + * `lastT`, `playing`), the speeds they said (`rates`), its log lines (`told`), the end's buttons (`ends`), the remotes' asks (`asks`). */ export class Extension { constructor(fixture, episode, toListen, toMap) { this.fixture = fixture this.episode = episode this.toMap = toMap - this.st = { cur: 0, want: undefined, applied: [], seeks: 0, times: 0, lastT: 0, playing: false, told: [], ends: [], asks: [] } + this.st = { cur: 0, want: undefined, applied: [], seeks: 0, times: 0, lastT: 0, playing: false, told: [], ends: [], asks: [], rates: [] } this.lj = { key: episode.key, j: { id: episode.key, title: episode.journey } } /** The journey the panel shows (undefined: closed). */ this.panelJourney = undefined @@ -80,8 +80,8 @@ export class Extension { nowOf: () => st.lastT, listening: () => (this.host.key ? this.lj : undefined), playing: () => st.playing, - time: (_lj, m) => this.followTime(m), - state: (m) => { this.host.relayState(m) }, + time: (_lj, m) => { st.rates.push(m.rate); this.followTime(m) }, + state: (m) => { st.rates.push(m.rate); this.host.relayState(m) }, error: (_lj, message) => { st.told.push(message) }, meta: () => {}, ask: async (_lj, m) => this.ask(m), @@ -89,6 +89,7 @@ export class Extension { open: async () => {}, end: async (_lj, action) => { st.ends.push(action) }, lost: () => {}, + moved: () => {}, } } diff --git a/test/journey-podcast/shoot.mjs b/test/journey-podcast/shoot.mjs index 37de39c..228096d 100644 --- a/test/journey-podcast/shoot.mjs +++ b/test/journey-podcast/shoot.mjs @@ -13,7 +13,8 @@ // moves the walk once; the hover tip; the keys; a step clicked moves the audio; ▶ on a storyline row plays that step // and stops at its end; the transcript; the speed; a step the podcast skips; the end; the panel's player going and // coming back; the audio moving to the panel and back; the caption, the speaker when the voice changes; Media -// Session; a fetch that fails; an audio that can't play; a cut-off audio. No console errors from either page. +// Session; a fetch that fails; an audio that can't play; a cut-off audio; the speed said to the extension. No +// console errors from either page. // // Usage (after `npm run build`): node test/journey-podcast/shoot.mjs [screenshot-dir] // One scenario or group: node --test-name-pattern="drag" test/journey-podcast/shoot.mjs. WIDTHS=340,700: the layout @@ -524,6 +525,18 @@ describe('edges', () => { assert.match(await statusLine(P.map), /Can't play/, 'the panel says why') }) + // The speed is the reader's for every journey and the next window: the host says each change at once, paused, and + // before its audio is there (the extension keeps the speed it says). + scenario('a speed set while paused is said to the extension', { width: 700 }, async (P) => { + await playerOf(P.map).rate.click() + await eventually('the panel\'s 1.25× is said by the host', () => P.st.rates.includes(1.25)) + assert.ok((await audioOf(P.listen)).paused, 'still paused') + }) + scenario('a speed set before the audio is there is said to the extension', { width: 700, srcPath: 'missing/', loaded: false }, async (P) => { + P.ext.command('rate', { rate: 1.5 }) + await eventually('1.5× said by the host with no audio loaded', () => P.st.rates.includes(1.5)) + }) + // A truncated mp3 whose header still says its full length can't be told apart in the player: the validator's length // checks cover that. Here the episode says 80 s and the audio is 40 s. scenario('a cut-off audio: the part it can\'t reach greyed, the tip there says so', { width: 700, more: { duration: 80 } }, async (P) => { diff --git a/test/podcastOnePlayer.test.ts b/test/podcastOnePlayer.test.ts new file mode 100644 index 0000000..509ea36 --- /dev/null +++ b/test/podcastOnePlayer.test.ts @@ -0,0 +1,107 @@ +import { test } from 'node:test' +import assert from 'node:assert/strict' +import type * as vscodeTypes from 'vscode' +import { fakeWebviewView, StatusBarItem, vscode } from './journey-podcast/fakeVscode' +import { AudioHost, AudioHostClient } from '../src/podcast/audioHost' +import { ListenStatusItem } from '../src/podcast/statusItem' +import type { LoadedJourney } from '../src/journeys/steps' + +// One player at a time (src/podcast/audioHost.ts, statusItem.ts) on a fake VS Code: the Listen view is there only +// while the journey panel does not have the audio, and VS Code drops its page when it goes. The audio going back +// (the panel closed, or showing another journey) makes the view again and loads the episode there, where it was. + +const log = { warn: () => undefined, error: () => undefined, info: () => undefined, debug: () => undefined } as unknown as vscodeTypes.LogOutputChannel +const lj = { key: 'k1', j: { id: 'order', title: 'Order and payment' } } as unknown as LoadedJourney +const other = { key: 'k2', j: { id: 'other', title: 'Other' } } as unknown as LoadedJourney + +function setup() { + const toListen: { type: string; [k: string]: unknown }[] = [] + const toPanel: { type: string; [k: string]: unknown }[] = [] + const said = { lost: 0, moved: 0 } + const panel: { journey: LoadedJourney | undefined } = { journey: lj } + const ports = { + journeys: () => ({ list: new Map([[lj.key, lj], [other.key, other]]) }), + mapPanel: () => ({ journey: panel.journey, send: (m: { type: string }) => { toPanel.push(m) } }), + tour: () => ({ showMap: () => undefined }), + } + const client = { + episodeFor: (x: LoadedJourney) => ({ key: x.key, title: x.j.title, journey: x.j.title, src: 'a.mp3', duration: 40, at: 0 }), + posOf: () => 0, + nowOf: () => 12, + listening: () => lj, + playing: () => true, + lost: () => { said.lost++ }, + moved: () => { said.moved++ }, + } as unknown as AudioHostClient + const host = new AudioHost(vscode.Uri.file('/ext') as unknown as vscodeTypes.Uri, () => log, ports as never, client) + // Each focus of the view makes a new page, which says it is ready. + const pages: ReturnType<typeof fakeWebviewView>[] = [] + vscode.commands.ran = [] + vscode.commands.handlers = { + 'codeNotes.listen.focus': () => { + const page = fakeWebviewView((m) => { toListen.push(m as { type: string }) }, 'file:') + pages.push(page) + host.listen.resolveWebviewView(page.view as unknown as vscodeTypes.WebviewView) + page.fromPage({ type: 'ready' }) + }, + } + return { host, toListen, toPanel, said, panel, pages } +} + +const settle = () => new Promise<void>((r) => setImmediate(r)) + +/** The audio in the panel, and the Listen view gone with it (its `when` off). */ +async function inPanel() { + const s = setup() + assert.equal(await s.host.listen.ensure(), true) + s.host.moveTo('panel', lj, { at: 3, play: true }) + assert.equal(s.host.panelHosts, true) + s.pages[0].dispose() + assert.equal(s.said.lost, 0, 'the view going with the panel playing loses nothing') + s.toListen.length = 0 + s.toPanel.length = 0 + return s +} + +test('the panel closed after the Listen view went: the view made again, the audio there where it was, playing on', async () => { + const s = await inPanel() + s.panel.journey = undefined + s.host.panelClosed() + assert.equal(s.host.in, 'listen') + assert.equal(s.host.panelHosts, false) + for (let i = 0; i < 5; i++) await settle() + assert.equal(s.pages.length, 2, 'a new Listen page') + const ep = s.toListen.find((m) => m.type === 'podcast')?.episode as { key: string; at: number; play?: boolean } + assert.deepEqual([ep?.key, ep?.at, ep?.play], ['k1', 12, true], 'its episode, where the audio was, asked to play') + assert.equal(s.host.key, 'k1') + assert.equal(s.host.has('k1'), true) + assert.equal(s.said.lost, 0) +}) + +test('the panel showing another journey: it stops being the host at once; the audio goes to a new Listen view', async () => { + const s = await inPanel() + s.panel.journey = other + s.host.panelShows(other) + assert.deepEqual(s.toPanel.find((m) => m.type === 'podcastRole'), { type: 'podcastRole', role: 'remote' }, 'the panel a remote before its new episode') + for (let i = 0; i < 5; i++) await settle() + const ep = s.toListen.find((m) => m.type === 'podcast')?.episode as { key: string; at: number } + assert.deepEqual([ep?.key, ep?.at], ['k1', 12]) + assert.equal(s.host.in, 'listen') +}) + +test('the status item: the Listen view off while the panel has the audio, on otherwise; it names the journey', () => { + const ctx: [string, unknown][] = [] + vscode.commands.handlers = { setContext: (k, v) => { ctx.push([k as string, v]) } } + const item = new ListenStatusItem(() => true, () => undefined) + const shown = (item as unknown as { item: StatusBarItem }).item + const base = { journey: lj, playing: false, ended: false, t: 39, panelOnScreen: true } + item.render({ ...base, panelHosts: true }) + assert.deepEqual(ctx.filter(([k]) => k === 'codeNotes.listening').at(-1), ['codeNotes.listening', false]) + assert.deepEqual(ctx.filter(([k]) => k === 'codeNotes.listenSession').at(-1), ['codeNotes.listenSession', true], 'the transport commands stay') + assert.equal(shown.shown, false, 'no item while the panel is on screen') + item.render({ ...base, panelOnScreen: false, panelHosts: false }) + assert.deepEqual(ctx.filter(([k]) => k === 'codeNotes.listening').at(-1), ['codeNotes.listening', true]) + assert.equal(shown.text, 'Paused: Order and payment · 0:39') + assert.equal(shown.shown, true) + item.dispose() +}) From 71c960ea563789176c85cc665544fc6b1a85784f Mon Sep 17 00:00:00 2001 From: tomeyer97 <107920881+tomeyer97@users.noreply.github.com> Date: Thu, 26 Nov 2026 20:49:01 +0100 Subject: [PATCH 12/17] The map opens readable: no overlapping labels, nothing cut at the edge, no second copy of the code Slice: S10 Zeroshot-Run: 01a21944-3ed2-7413-b426-52a928110c1d --- media/journey-farnames.js | 15 +++++++----- media/journey-graph.js | 33 +++++++++++++++++++-------- media/journey-scene.js | 14 ++++++++---- media/map/animation.js | 4 +++- test/journey-map/layoutChecks.js | 37 ++++++++++++++++++++++++++++++ test/journey-map/shoot.mjs | 39 +++++++++++++++++++++++++++++--- test/journey-scene/check.mjs | 34 +++++++++++++++++++++++++++- 7 files changed, 152 insertions(+), 24 deletions(-) diff --git a/media/journey-farnames.js b/media/journey-farnames.js index d18dc34..52a5850 100644 --- a/media/journey-farnames.js +++ b/media/journey-farnames.js @@ -1,6 +1,6 @@ // The map's names when zoomed out (journey-graph.js `farNames`): a block of leaves, a system or a lone box gets its // name (and its step numbers) at a size you can read, in screen space, where it overlaps nothing placed before it. -// Exports measure(names) and place(items, taken, ring). +// Exports measure(names) and place(items, taken, ring, bounds). import { overlapArea, edgesOf } from './common.js' /** A chip's padding, both sides together (px). */ @@ -197,17 +197,20 @@ function blockCandidates(variants, blockRect, isCurrentBlock) { /** * Places the far names `items` where each overlaps nothing in `taken` (screen rectangles { x, y, w, h }; each name - * placed is added to it) nor the current step's `ring` (its screen rectangle, if shown). In rank order (0 first), - * bigger boxes first (`size`: the box's area); a name with no free place is hidden. The current step's own names - * (rank 0) go over the ring rather than nowhere. + * placed is added to it) nor the current step's `ring` (its screen rectangle, if shown), wholly inside `bounds` (the + * drawing, when given: a name its edge cuts reads as another word). In rank order (0 first), bigger boxes first (`size`: the + * box's area); a name with no free place is hidden. The current step's own names (rank 0) go over the ring rather + * than nowhere. * @param {{ name: MeasuredName, blockRect: { x: number, y: number, w: number, h: number }, isCurrentBlock: boolean, * rank: number, size: number }[]} items * @param {{ x: number, y: number, w: number, h: number }[]} taken * @param {{ x: number, y: number, w: number, h: number } | undefined} ring + * @param {{ x: number, y: number, w: number, h: number }} [bounds] none: anywhere */ -function place(items, taken, ring) { +function place(items, taken, ring, bounds) { const clashes = (r, q) => overlapArea(edgesOf(r), edgesOf(q)) > 0 - const free = (r, { allowRing = false } = {}) => !taken.some((q) => clashes(r, q)) && (allowRing || !ring || !clashes(r, ring)) + const inside = (r) => !bounds || r.x >= bounds.x && r.y >= bounds.y && r.x + r.w <= bounds.x + bounds.w && r.y + r.h <= bounds.y + bounds.h + const free = (r, { allowRing = false } = {}) => inside(r) && !taken.some((q) => clashes(r, q)) && (allowRing || !ring || !clashes(r, ring)) const rectOf = (c) => ({ x: c.x, y: c.y, w: c.variant.w, h: c.variant.h }) items.sort((a, b) => a.rank - b.rank || b.size - a.size) for (const { name, blockRect, isCurrentBlock, rank } of items) { diff --git a/media/journey-graph.js b/media/journey-graph.js index bd5501b..cc83425 100644 --- a/media/journey-graph.js +++ b/media/journey-graph.js @@ -73,6 +73,8 @@ export function JourneyGraph(host) { /** Far out: the names, at a size you can read, over the boxes (screen space, not scaled). */ const names = el('div', 'gnames') names.setAttribute('aria-hidden', 'true') + // Hidden until a far view has placed them: unplaced, every name sits at the top left, over the others. + names.hidden = true stage.append(names) const ctl = el('div', 'gctl') const btn = (cls, text, title, fn) => { @@ -109,6 +111,10 @@ export function JourneyGraph(host) { let anim = 0 /** The step the map last followed (-1: none yet): a new one moves it (also back from wherever it was dragged). */ let followed = -1 + /** The view was placed on the layout drawn (until then it is no view at all: the tutorial does not stop that). */ + let viewPlaced = false + /** The view is the whole map the journey opened on (kept over size changes until the walk or the reader moves). */ + let openFit = false /** The view's size when the map last followed or was resized ({ w, h }; undefined: not yet). */ let lastSize let legendHidden = true @@ -172,6 +178,7 @@ export function JourneyGraph(host) { drawn.farNames = d.farNames drawn.measured = undefined drawn.ring = d.ring + viewPlaced = false mark() host.rendered(shown.journey.nodes.length) } @@ -206,7 +213,8 @@ export function JourneyGraph(host) { if (!p) return [] return [{ name, blockRect: onScreen(p), isCurrentBlock: name.id === holder, rank: farRank(name.id, name.kind, node, holder), size: p.w * p.h }] }) - FarNames.place(items, taken, ring) + const { w, h } = port() + FarNames.place(items, taken, ring, { x: 0, y: 0, w, h }) } /** The ring around box `p` (world px; none: hidden), on screen through `onScreen`; returns its rectangle. */ @@ -236,6 +244,7 @@ export function JourneyGraph(host) { // ---------- the view ---------- function apply() { + viewPlaced = true world.style.transform = `translate(${view.x}px, ${view.y}px) scale(${view.zoom})` const far = view.zoom < FAR viewport.classList.toggle('far', far) @@ -268,25 +277,31 @@ export function JourneyGraph(host) { } anim = requestAnimationFrame(tick) } - function zoomBy(f) { const p = port(); moveView(zoomedAt(view, f, p.w / 2, p.h / 2), true) } + function zoomBy(f) { openFit = false; const p = port(); moveView(zoomedAt(view, f, p.w / 2, p.h / 2), true) } function fit(animate) { const { layout } = shown if (layout) moveView(showing({ x: 0, y: 0, w: layout.w, h: layout.h }, port(), FIT_MAX_ZOOM), animate) } function fitBox(id) { const p = shown.layout && shown.layout.abs.get(id) - if (p) moveView(showing(p, port(), SHOW_MAX_ZOOM), true) + if (p) { openFit = false; moveView(showing(p, port(), SHOW_MAX_ZOOM), true) } } - /** The current step's box and its neighbourhood in view (graph/view.js following); no step: the whole map. */ + /** + * The current step's box and its neighbourhood in view (graph/view.js following). A journey opens on the whole map + * (a step's neighbourhood would cut the boxes at the view's edge) and keeps it over size changes until the walk or + * the reader moves it. The tutorial keeps the view still, once it has one. + */ function follow(animate) { const { layout, journey } = shown - if (!layout || !journey || host.isTutorialUp()) return + if (!layout || !journey || (host.isTutorialUp() && viewPlaced)) return const node = currentNode() + const stepMoved = followed !== shown.current + openFit = followed === -1 || (openFit && !stepMoved) followed = shown.current const p = node && layout.abs.get(node) host.view(p ? node : '') - if (!p) return fit(animate) + if (!p || openFit) return fit(animate) moveView(following(p, neighbours(node), port()), animate) } @@ -315,10 +330,10 @@ export function JourneyGraph(host) { hasLayout: () => !!shown.layout, isTutorialUp: () => host.isTutorialUp(), clamped: (x, y) => clamped(x, y, view.zoom), - jumpTo: (x, y) => { view.x = x; view.y = y; apply() }, - panTo: (x, y) => moveView({ x, y, zoom: view.zoom }, true), + jumpTo: (x, y) => { openFit = false; view.x = x; view.y = y; apply() }, + panTo: (x, y) => { openFit = false; moveView({ x, y, zoom: view.zoom }, true) }, stopAnimation: () => cancelAnimationFrame(anim), - zoomAt: (f, sx, sy) => moveView(zoomedAt(view, f, sx, sy), false), + zoomAt: (f, sx, sy) => { openFit = false; moveView(zoomedAt(view, f, sx, sy), false) }, zoomBy, fit: () => fit(true), }) diff --git a/media/journey-scene.js b/media/journey-scene.js index 9e2fe95..94e2d30 100644 --- a/media/journey-scene.js +++ b/media/journey-scene.js @@ -531,7 +531,8 @@ function playerEl() { cap.setAttribute('aria-live', 'polite') // No example under the caption (less clutter): a beat's example is at its code line, in the editor. // The beat's line with a few lines around it (the eyes stay on the animation): filled by `code()` once the - // extension has found the line; shown only where there is room (the stylesheet). + // extension has found the line; shown only where there is room (the stylesheet), and never while the step's code + // is open beside the panel (two copies of the same lines). const codeEl = el('div', 'scn-code') codeEl.hidden = true root.append(bar, view, cap, codeEl) @@ -568,6 +569,8 @@ function create(opts) { hasNext: false, /** @type {{ w: number, h: number } | undefined} the view's size when last laid out */ size: undefined, + /** the step's code is open beside the player: no lines of it under the caption */ + codeBeside: false, } /** The scene shown; only called once there is one. */ const shown = () => /** @type {Scene} */ (p.scene) @@ -738,14 +741,17 @@ function create(opts) { el: root, get beat() { return p.beat }, /** The current beat's line and the lines around it: { file, line, from, lines } (numbers 1-based), or nothing. */ - code(c) { showCode(codeEl, c) }, + code(c) { showCode(codeEl, p.codeBeside ? undefined : c) }, get count() { return p.scene ? p.scene.beats.length : 0 }, /** Shows a scene; the same key again keeps the beat (a re-render), another starts at `o.beat` (or its first). * o: { file: the step's file (a beat in another file names it), next: there is a next step, beat, still: shown - * without its flight }. - * @param {Scene} s @param {string} k @param {{ file?: string, next?: boolean, beat?: number, still?: boolean }} [o] */ + * without its flight, codeBeside: the step's code is open beside the player (no lines under the caption) }. + * @param {Scene} s @param {string} k + * @param {{ file?: string, next?: boolean, beat?: number, still?: boolean, codeBeside?: boolean }} [o] */ show(s, k, o) { o = o || {} + p.codeBeside = !!o.codeBeside + if (p.codeBeside) showCode(codeEl, undefined) const same = k === p.key && !!p.scene p.stepFile = o.file || '' const had = p.hasNext diff --git a/media/map/animation.js b/media/map/animation.js index e4ab76e..ebf52cc 100644 --- a/media/map/animation.js +++ b/media/map/animation.js @@ -55,7 +55,9 @@ export function makeAnimation(ctx, { isHome }) { scene.layout() const still = !!anim.stillAt[k] delete anim.stillAt[k] - scene.show(sceneOf(state, cur), k, { file: j.steps[cur - 1].file, next: cur < j.steps.length, beat: anim.beatAt[k] || 0, still }) + // The step's card in the panel means its code is not open beside it (gone or deleted): only then its lines here. + const codeBeside = !state.walk.tour.card + scene.show(sceneOf(state, cur), k, { file: j.steps[cur - 1].file, next: cur < j.steps.length, beat: anim.beatAt[k] || 0, still, codeBeside }) // The podcast moved it: the keyboard stays where it was (Space keeps pausing). if ((fresh || anim.focusScene) && anim.movedBy !== 'podcast') scene.focus() anim.focusScene = false diff --git a/test/journey-map/layoutChecks.js b/test/journey-map/layoutChecks.js index 23623f7..26d78d5 100644 --- a/test/journey-map/layoutChecks.js +++ b/test/journey-map/layoutChecks.js @@ -233,6 +233,41 @@ return out } + // ---------- what a journey opens on ---------- + + /** The text the map shows now, near or far: frames' titles, box names and numbers, arrow labels, far names and + * their numbers; each as { what, r } (what it says, where). Hidden ones are left out. */ + function mapTexts(map) { + const shown = (e) => { + for (let x = e; x && x !== map; x = x.parentElement) { + const s = getComputedStyle(x) + if (s.display === 'none' || s.visibility === 'hidden' || x.hidden) return false + } + return e.getClientRects().length > 0 + } + return [...map.querySelectorAll('.gtitle, .glbl, .gnums, .glabel, .gname .gnt, .gfnums')] + .filter(shown) + .map((e) => ({ what: `${e.className.split(' ')[0]} "${e.textContent.replace(/\s+/g, ' ').trim()}"`, r: rect(e) })) + } + + /** As a journey opens: no two texts of the map over each other (names, chip rows, titles, labels), and no text or + * box cut by the drawing's edge (each wholly inside it or wholly out of it). */ + function openViewProblems() { + const map = document.querySelector('.gmap') + if (!map || !map.querySelector('.gworld')) return ['no map'] + const out = [] + const texts = mapTexts(map) + for (let i = 0; i < texts.length; i++) { + for (let k = i + 1; k < texts.length; k++) if (overlap(texts[i].r, texts[k].r, 0.5)) out.push(`${texts[i].what} and ${texts[k].what} overlap`) + } + const st = rect(map.querySelector('.gstage')) + const cut = (r) => r.right > st.left + 0.5 && r.left < st.right - 0.5 && r.bottom > st.top + 0.5 && r.top < st.bottom - 0.5 && + (r.left < st.left - 0.5 || r.right > st.right + 0.5 || r.top < st.top - 0.5 || r.bottom > st.bottom + 0.5) + for (const t of texts) if (cut(t.r)) out.push(`${t.what} cut by the map's edge`) + for (const b of map.querySelectorAll('.gbox.leaf')) if (cut(rect(b))) out.push(`box ${b.dataset.id} cut by the map's edge`) + return out + } + /** Every layout rule on what is shown now; `wantCurrent`: a step is being walked (its box must be ringed). */ const H = (window.__harness = window.__harness || {}) H.mapLayoutProblems = (wantCurrent) => { @@ -251,6 +286,8 @@ } /** Map text contrast (dark themes). */ H.mapTextContrast = mapTextContrast + /** As a journey opens: its texts apart and none cut by the edge. */ + H.openViewProblems = openViewProblems /** Fit and the far view: the map centred; far out, names apart, clear of the buttons, cut well, readable (`dark`); * walking (step `cur`), the current step ringed and its number lit. */ H.farViewProblems = (dark, cur) => { diff --git a/test/journey-map/shoot.mjs b/test/journey-map/shoot.mjs index b42f30d..000f89d 100644 --- a/test/journey-map/shoot.mjs +++ b/test/journey-map/shoot.mjs @@ -2,7 +2,8 @@ // and asserts what a person would notice. The map is the whole journey at once (journey-graph.js): no boxes // overlapping or sticking out of their container, no box text cut, arrow labels on their lines and never over a box // or each other, the current step's box ringed and in view (it follows the step), step numbers walk, boxes open code, -// drag pans without clicking, Ctrl+wheel zooms, Fit shows it all with whole names; the home list; the storyline, +// drag pans without clicking, Ctrl+wheel zooms, Fit shows it all with whole names; a journey opens on the whole map +// (no text over another, nothing cut at its edge, the tutorial up or not); the home list; the storyline, // step card, problems, deleted and the tutorial as before; every bundled sample journey (and, optionally, every journey // in a folder you name) at every step; no console errors. Exits 1 on any failure. // @@ -74,6 +75,8 @@ const journey = journeyFile(path.join(SAMPLES, 'v2-full.json')) const handoff = journeyFile(path.join(FIXTURES, 'handoff.json')) /** A generated journey's shape: a system of modules and functions, two top-level external boxes it calls. */ const GENERATED = path.join(FIXTURES, 'billing-plan-change.json') +/** The example repository's journey (four systems, a store in each, ten steps). */ +const SHOP = path.join(ROOT, 'examples/shop/journeys/place-order.json') // The bundled samples, then the journeys of the folder named on the command line. const extra = JOURNEYS ? jsonIn(JOURNEYS) : [] const real = [...jsonIn(SAMPLES), ...extra] @@ -247,7 +250,9 @@ async function dragThenNextStep(p) { /** Clicks: a step number walks there; a function box opens its code; a module zooms to it; a drag clicks nothing. */ async function clicks(p) { - await p.open(journey, { current: 9, prov: PROV }) + // Walked to step 9 (a journey opens on the whole map, where narrow panels show no box numbers). + await p.open(journey, { prov: PROV }) + await p.tour({ current: 9, prov: PROV }) await p.clickPosts('.gnum[data-n="9"]', { type: FROM.step, n: 9 }, 'a step number') const at = journey.nodes.find((n) => n.id === 'chargestatus').at await p.clickPosts('.gbox.leaf[data-id="chargestatus"] .glbl', { type: FROM.openPath, path: `${at.file}:${at.start}-${at.end}` }, 'a function box opens its code') @@ -615,6 +620,34 @@ async function samples(p) { } } +/** + * A journey opens readable: on step 1, with and without the tutorial started before its map is laid out, at the + * panel's width and in a 1440 × 900 window, no two texts of the map overlap (names, chip rows, titles, labels) and + * the drawing's edge cuts no text and no box (layoutChecks.js openViewProblems). + */ +async function opensReadable(p) { + let fresh = true + for (const f of [SHOP, GENERATED, path.join(SAMPLES, 'v2-full.json')]) { + const name = path.basename(f, '.json') + const j = journeyFile(f) + for (const width of [p.width, 1440]) for (const tutorial of [false, true]) { + // A fresh page each time (the page before checked for errors first). + if (!fresh) { await p.errorsSeen(); await p.reset() } + fresh = false + if (width !== p.width) await p.page.setViewportSize({ width, height: 900 }) + if (tutorial) { + // The tutorial's first card is up before the map is laid out (ELK is async), as from the Tutorial command. + await p.send(p.toMap.journey(j, { current: 1, tutorial: true })) + await p.send({ type: 'tutorial' }) + await p.page.waitForFunction((r) => window.__harness.posted.some((m) => m.type === r), FROM.rendered, { timeout: 15000 }) + await p.settle() + } else await p.open(j, { current: 1 }) + for (const x of await p.page.evaluate(() => window.__harness.openViewProblems())) p.problem(`${name} opened at ${width} px${tutorial ? ' under the tutorial' : ''}: ${x}`) + if (name === 'place-order') await p.shot(`13-open-${width}${tutorial ? '-tutorial' : ''}`) + } + } +} + /** In the page: a top-level external box sits next to what calls it, not in a far corner. */ function externalsFarFromCallers(J) { const out = [] @@ -683,7 +716,7 @@ function stylesheetsAsInThePanel(fail) { const CHECKS = { header, mapPlacement, storylineFocus, walking, splitter, dragThenNextStep, clicks, zoom, legend, stepAnimates, endAndResume, stepCard, longStoryline, problems, tutorial, handoffRecord, home, finished, anotherOpensAtTop, samples, - resize, + resize, opensReadable, } const unknown = ONLY.filter((n) => !Object.hasOwn(CHECKS, n) && n !== 'firstOpen') if (unknown.length) { console.error(`no check ${unknown.join(', ')} (checks: ${[...Object.keys(CHECKS), 'firstOpen'].join(', ')})`); process.exit(2) } diff --git a/test/journey-scene/check.mjs b/test/journey-scene/check.mjs index f62be84..c24d4cf 100644 --- a/test/journey-scene/check.mjs +++ b/test/journey-scene/check.mjs @@ -4,7 +4,8 @@ // box (or text no check covers: selectors.mjs), anything sticking out of an actor box, any visible text in the scene // smaller than 11 px on screen (font-size × the world's scale), the scene column narrower than 400 px, the keyboard // focus leaving the scene, a last beat without "Next step ›" (but on the last step), anything moving with reduced -// motion, or a scene whose names are Object.prototype's keys not drawing like any other. +// motion, a scene whose names are Object.prototype's keys not drawing like any other, or the beat's lines shown +// under the caption while the step's code is open beside the panel. // node test/journey-scene/check.mjs <journey.json> [<dir for screenshots>] // Needs Playwright with Chromium (test/harness/page.mjs launchChromium: PLAYWRIGHT, CHROME). The panel's harness // (test/journey-map/harness.html) loads out/vendor/elk.bundled.js and the page's bundle, out/pages/map.js: run @@ -279,9 +280,40 @@ async function checkPrototypeKeyNames() { await page.close() } +/** The step card as the extension sends it when the step's code is gone (src/protocol/map.ts PanelCard). */ +const PANEL_CARD = { n: 1, title: 'Step', lead: 'Its code was deleted.', refs: '', stale: false, staleText: '', open: true, paths: [] } + +/** The beat's lines under the caption only when the step's code is not open beside the panel: hidden while it is + * (the editor shows and lights them), shown when the step's card lives in the panel (its code is gone). */ +async function checkCodeExcerpt() { + const n = animated[0] + const { page, errors } = await openJourney({ w: 1300, theme: 'dark' }, journey, n) + const send = (m) => page.evaluate((x) => window.postMessage(x, '*'), m) + const code = { file: journey.steps[n - 1].file || 'src/a.js', line: 3, from: 1, lines: ['const a = 1', 'const b = 2', 'check(a, b)', 'done()'] } + const excerpt = async () => { + await send({ type: 'code', n, i: 0, code }) + await page.evaluate(() => new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(() => r())))) + return page.evaluate(() => { const c = document.querySelector('.scn-code'); return !!c && !c.hidden && c.getClientRects().length > 0 }) + } + const problems = [] + try { + await startAnimation(page, n) + await still(page, 1, journey.steps[n - 1].scene.beats.length) + if (await excerpt()) problems.push('the beat\'s lines are shown while the step\'s code is open beside the panel') + await send({ type: 'tour', ...tour({ current: n, card: { ...PANEL_CARD, n } }) }) + await page.waitForSelector('.scn', { timeout: 5000 }) + if (!(await excerpt())) problems.push('the beat\'s lines are not shown when the step\'s card is in the panel (no code beside it)') + } catch (e) { problems.push(`didn't run: ${e.message.split('\n')[0]}`) } + problems.push(...errors) + if (problems.length) fail('code excerpt', problems) + else console.log('code excerpt ok') + await page.close() +} + const browser = await launchChromium() for (const pass of PASSES) await checkPass(pass) await checkPrototypeKeyNames() +await checkCodeExcerpt() await browser.close() console.log(`smallest text: ${smallest.px.toFixed(1)} px (${smallest.cls} "${smallest.text}", ${smallest.at})`) console.log(failures.length ? `FAILED (${failures.length})` : 'ok') From b4fb1949760fd6f96e61551f993b3b7c6a5b33d2 Mon Sep 17 00:00:00 2001 From: tomeyer97 <107920881+tomeyer97@users.noreply.github.com> Date: Thu, 26 Nov 2026 20:53:00 +0100 Subject: [PATCH 13/17] The Journeys view: one row per journey in small repos, plain descriptions, one verb per state, writing jobs visible Slice: S08 Zeroshot-Run: 01a21944-24e5-7481-b90c-eac528f3eaea --- media/home/text.js | 9 +- media/journey-home.js | 9 +- src/core/list/journeyList.ts | 24 +++- src/sidebar/journeyRowText.ts | 30 +++-- src/sidebar/journeyRows.ts | 34 +++++- src/sidebar/journeysTree.ts | 46 ++++++-- src/sidebar/nodes.ts | 3 + src/sidebar/rowItems.ts | 3 +- test/golden-list.test.ts | 17 ++- test/goldens/journey/list.chip-area.json | 2 +- test/goldens/journey/list.chip-stale.json | 1 + test/goldens/journey/list.default.json | 3 +- test/goldens/journey/list.groups.json | 104 ++++++++++++++++++ test/goldens/journey/list.here-all.json | 1 + test/goldens/journey/list.here.json | 3 +- test/goldens/journey/list.kind-check.json | 10 +- test/goldens/journey/list.name.json | 3 +- test/goldens/journey/list.newest.json | 3 +- test/goldens/journey/list.search-any.json | 1 + .../goldens/journey/list.search-fallback.json | 1 + test/goldens/journey/list.search-none.json | 10 +- .../journey/list.search-retry-newest.json | 1 + test/goldens/journey/list.search-retry.json | 1 + test/goldens/journey/list.walked.json | 3 +- test/journey-list/shoot.mjs | 41 ++++++- test/journey-map/shoot.mjs | 10 +- test/journeyHome.test.ts | 14 ++- test/journeyList.test.ts | 36 +++++- test/journeyRowText.test.ts | 28 +++-- 29 files changed, 362 insertions(+), 89 deletions(-) create mode 100644 test/goldens/journey/list.groups.json diff --git a/media/home/text.js b/media/home/text.js index eaa8ebf..d6136c2 100644 --- a/media/home/text.js +++ b/media/home/text.js @@ -22,11 +22,12 @@ export function staleTip(r) { return `${r.stale} step${r.stale === 1 ? '' : 's'} changed since it was written` } -/** The preview's button: back to where the walk is, on from where it was left, or from the start. */ +/** Whether a journey is in progress: being walked, or left past step 1. */ +export const inProgress = (r) => !!r.walking || r.resume > 1 + +/** The preview's button, one verb per state: on from where the walk is or was left ("Resume · 3/10"), else Walk. */ export function walkLabel(r) { - if (r.walking) return `Back to step ${r.resume}` - if (r.resume > 1) return `Resume at ${r.resume}` - return 'Walk' + return inProgress(r) ? `Resume · ${r.resume}/${r.steps}` : 'Walk' } /** diff --git a/media/journey-home.js b/media/journey-home.js index e1119b3..32aadbd 100644 --- a/media/journey-home.js +++ b/media/journey-home.js @@ -4,7 +4,7 @@ // draw it. Styles in journey-home.css; its words in home/text.js. journey-map.js makes it and draws it in place of the // journey while it is in front; what it posts is typed by src/protocol/map.ts FromMap. import { el, button, baseName, runKey, itemAt, rovingKeys } from './common.js' -import { SORTS, staleTip, walkLabel, podcastBadge, escapeRegExp } from './home/text.js' +import { SORTS, staleTip, walkLabel, inProgress, podcastBadge, escapeRegExp } from './home/text.js' /** * What the home needs of the page (journey-map.js): its root element (emptied and drawn again on every render), @@ -252,9 +252,10 @@ export function JourneyHome(host) { b.setAttribute('aria-selected', String(k === sel)) const t = el('span', 'jtop') t.append(marked(r.title, r.hits)) - if (r.start) t.append(el('span', 'jstart', 'Start here')) + // "Start here" is for a journey not begun yet: one in progress says where it is instead. + if (r.start && !inProgress(r)) t.append(el('span', 'jstart', 'Start here')) if (r.isNew) t.append(el('span', 'jnew', 'new')) - if (r.walking || r.resume > 1) { + if (inProgress(r)) { const where = r.walking ? `Walking: step ${r.resume} of ${r.steps}` : `Left at step ${r.resume} of ${r.steps}` t.append(badge('jat', `${r.resume}/${r.steps}`, where)) } @@ -312,7 +313,7 @@ export function JourneyHome(host) { return p } - /** Walk (or Resume, Back to step n); Refresh when steps are stale. */ + /** Walk, or Resume · n/N; Refresh when steps are stale. */ function previewActions(r, hasStale) { const acts = el('div', 'pacts') const go = button('walkb', walkLabel(r), () => host.walk(r.key)) diff --git a/src/core/list/journeyList.ts b/src/core/list/journeyList.ts index be89aa0..35d72c4 100644 --- a/src/core/list/journeyList.ts +++ b/src/core/list/journeyList.ts @@ -18,6 +18,8 @@ export const SORTS: { id: Sort; label: string }[] = [ ] /** "In this file" lists this many, then "Show all". */ export const HERE_CAP = 5 +/** The sidebar lists fewer journeys than this in one flat list (no areas): grouping only helps a long list. */ +export const FLAT_UNDER = 8 /** What the extension knows about one entry. */ export interface ListItem { @@ -81,8 +83,11 @@ export interface ListModel { fallback?: { note: string; missing: string[] } /** The panel's sections (a search: one, "results", best first). */ sections: Section[] - /** The sidebar's groups: In this file · Continue · All (by area, or flat). */ + /** The sidebar's groups: In this file · Continue · All (the rest: by area, or flat). */ groups: Group[] + /** The sidebar draws All's rows as its top rows, no heading: fewer than FLAT_UNDER journeys and All is the only + * group (a lone Continue or In this file keeps its heading: it says why the row is there). */ + flat: boolean /** Rows shown after filtering (search, kind, area). */ count: number total: number @@ -265,8 +270,10 @@ function panelSections(p: ListRows, area: string, results?: ListRow[]): Section[ return out.filter((s) => s.keys.length) } -/** The sidebar's groups: In this file (but the walk's journey) and Continue when they have rows, then All (by area, or flat). */ -function sidebarGroups(p: ListRows): Group[] { +/** The sidebar's groups: In this file (but the walk's journey) and Continue when they have rows, then All: the rest, + * by area or flat (flat while the workspace has fewer than FLAT_UNDER journeys, `total`); each journey once in + * Continue or All. */ +function sidebarGroups(p: ListRows, total: number): Group[] { const out: Group[] = [] // The journey being walked (or listened to) is in Continue: not again in "In this file", which would come and go as // the walk changes files. @@ -275,8 +282,11 @@ function sidebarGroups(p: ListRows): Group[] { const hereAll = p.inFileRows.filter((r) => !walking.has(r.key)) if (hereAll.length) out.push(part('here', 'In this file', hereShown, hereAll.length - hereShown.length)) if (p.continueRows.length) out.push(part('continue', 'Continue', p.continueRows)) - if (p.sort === 'area') out.push({ id: 'all', label: 'All', keys: [], children: areaParts(p.sorted) }) - else out.push(part('all', 'All', p.sorted)) + const continued = new Set(keys(p.continueRows)) + const rest = p.sorted.filter((r) => !continued.has(r.key)) + if (!rest.length) return out + if (p.sort === 'area' && total >= FLAT_UNDER) out.push({ id: 'all', label: 'All', keys: [], children: areaParts(rest) }) + else out.push(part('all', 'All', rest)) return out } @@ -307,6 +317,7 @@ export function buildList(items: ListItem[], o: ListOptions = {}): ListModel { const searchSort = o.searchSort ?? (sort === 'area' ? 'best' : sort) const best = (x: ListRow, y: ListRow) => (hits.get(y.key)!.score - hits.get(x.key)!.score) || ORDER[sort](x, y) const results = query ? [...shown].sort(searchSort === 'best' ? best : ORDER[searchSort]) : undefined + const groups = sidebarGroups(list, all.length) return { rows, query, sort, searchSort, kind, area, ...(all.some((r) => r.here) ? { file: o.activeFile } : {}), @@ -315,7 +326,8 @@ export function buildList(items: ListItem[], o: ListOptions = {}): ListModel { staleCount: all.filter((r) => r.stale > 0).length, ...(fallback ? { fallback } : {}), sections: panelSections(list, area, results), - groups: sidebarGroups(list), + groups, + flat: all.length < FLAT_UNDER && groups.length === 1 && groups[0].id === 'all' && !groups[0].children, count: shown.length, total: all.length, } diff --git a/src/sidebar/journeyRowText.ts b/src/sidebar/journeyRowText.ts index 66b3ebb..50a9fc1 100644 --- a/src/sidebar/journeyRowText.ts +++ b/src/sidebar/journeyRowText.ts @@ -3,6 +3,7 @@ import type { ListRow } from '../core/list/journeyList' import { plural } from '../core/text' +import { ClaudeRun, runProgress } from '../core/agentRun' import { clock } from '../core/format/podcast/model' import type { PodcastStatus } from '../tour/api' @@ -24,7 +25,7 @@ export interface JourneyRowState { stale: boolean unreadable: boolean isNew: boolean - /** Its row in the list model the Journeys view drew: area, age, "3 of 7 steps here" (none before a drawing). */ + /** Its row in the list model the Journeys view drew: "3 of 7 steps here" (none before a drawing). */ row?: ListRow } @@ -32,24 +33,22 @@ const replies = (n: number) => plural(n, 'reply', 'replies') const unreadReplies = (n: number) => plural(n, 'unread reply', 'unread replies') /** - * State only, muted and short: where it was left (step 3/14; while walking the icon says so and the card and status - * bar have the position), else its area and age (journeyList.ts; under its area's group the area is not said again); - * Refreshing… or ⚠ Stale; new replies; unreadable; new. No step count, no question count (the questions are the rows - * below). In this file (`here`): how much of it is here ("3 of 7 steps here"), unless it is being walked or was left. + * Muted and short: where it was left (step 3/14; while walking the icon says so and the card and status bar have the + * position), else how long it is (10 steps); its podcast's length; Refreshing… or ⚠ Stale; new replies; unreadable; + * new. No age (the tooltip says when it was written), no question count (the questions are the rows below). In this + * file (`here`): how much of it is here ("3 of 7 steps here"), unless it is being walked or was left. */ export function journeyDescription(s: JourneyRowState, group: string | undefined): string | undefined { const { row } = s const pod = podcastText(s.pod) if (group === 'here' && row && !(row.walking || row.resume > 1)) { - return [pod, row.hereText, row.stale ? '⚠ Stale' : ''].filter(Boolean).join(' · ') + return [row.hereText, pod, row.stale ? '⚠ Stale' : ''].filter(Boolean).join(' · ') } - const groupArea = group?.startsWith('area:') ? group.slice(5) : '' - const areaAndAge = row ? [groupArea && row.area === groupArea ? '' : row.area, row.age].filter(Boolean).join(' · ') : '' // Listened to: no step (the player has where it is). - const where = s.pod?.session ? '' : s.left ? `step ${s.left}/${s.steps}` : areaAndAge + const where = s.pod?.session ? '' : s.left ? `step ${s.left}/${s.steps}` : plural(s.steps, 'step') return [ - pod, where, + pod, s.refreshing ? 'Refreshing…' : s.stale ? '⚠ Stale' : '', s.newReplies ? replies(s.newReplies) : '', s.unreadable ? '⚠ unreadable' : '', @@ -81,3 +80,14 @@ export function journeyLabel(title: string, s: JourneyRowState): string { const listen = s.pod?.state === 'ok' ? `podcast ${clock(s.pod.duration ?? 0)}` : '' return [title, where, listen, s.newReplies ? unreadReplies(s.newReplies) : '', s.isNew ? 'new' : ''].filter(Boolean).join(', ') } + +/** A journey Claude is writing now, as its row says it: "Writing: <question>", then "1:20 · reading store.ts". */ +export function writingRowText(job: { question: string; model: string } & ClaudeRun, now: number): { label: string; description: string; tooltip: string; a11y: string } { + const q = job.question.replace(/\s+/g, ' ').trim() + return { + label: `Writing: ${q}`, + description: runProgress(job, now), + tooltip: `${q}\nClaude (${job.model}) is writing a journey for this question.`, + a11y: `Writing a journey: ${q}, ${runProgress(job, now)}`, + } +} diff --git a/src/sidebar/journeyRows.ts b/src/sidebar/journeyRows.ts index 7737c60..e40255d 100644 --- a/src/sidebar/journeyRows.ts +++ b/src/sidebar/journeyRows.ts @@ -24,7 +24,8 @@ import { fileName } from '../platform/jsonFolder' import { STATE } from '../platform/state' import { cmdLink, Cmd } from '../platform/commands' import { trustedMarkdown } from '../platform/commandLinks' -import { journeyDescription, journeyLabel, JourneyRowState, journeyTooltip, nestsQuestions, podcastContext } from './journeyRowText' +import { journeyDescription, journeyLabel, JourneyRowState, journeyTooltip, nestsQuestions, podcastContext, writingRowText } from './journeyRowText' +import { journeyJobs } from '../write/journeyJobs' /** Every journey's row, then the journey files that can't be read. */ export const journeyRows = (): Node[] => [...journeys().all().map(journeyNode), ...badJourneyNodes()] @@ -103,7 +104,7 @@ export function journeyRowState(lj: LoadedJourney, questions: Note[], model: Lis /** * A journey's row. The short title is the row; the question is the tooltip. The description is state only. * `group`: the Journeys view's group it is listed in (its id says which; only All and the areas nest its questions). - * `model`: the list model the view drew (the row's area, age and "here" text). + * `model`: the list model the view drew (the row's "here" text). */ export function journeyItem(lj: LoadedJourney, group?: string, model: ListModel | undefined = journeysTree.drawnModel()): vscode.TreeItem { const q = questionsNode(lj) @@ -156,6 +157,35 @@ export function badJourneyItem(node: Extract<Node, { kind: 'badJourney' }>): vsc return item } +/** A journey Claude is writing now: a row at the top of the Journeys view while it runs (its notification can be + * closed). A journey being refreshed is not one: its own row says Refreshing…. */ +export type WritingNode = Extract<Node, { kind: 'writing' }> + +/** The writing rows last drawn, by job id: one object per row, so a row's own redraw (its clock) finds it. */ +let writing = new Map<string, WritingNode>() + +/** The writing rows now (the view's top rows): the ones drawn before kept, the ended ones dropped. */ +export function writingNodes(): WritingNode[] { + const jobs = journeyJobs().filter((job) => job.kind === 'write') + writing = new Map(jobs.map((job) => [job.id, writing.get(job.id) ?? { kind: 'writing' as const, job }])) + return [...writing.values()] +} + +/** The writing rows the view was given last (their clocks redraw them alone). */ +export const drawnWritingNodes = (): WritingNode[] => [...writing.values()] + +export function writingItem(node: WritingNode, now = Date.now()): vscode.TreeItem { + const t = writingRowText(node.job, now) + const item = new vscode.TreeItem(isolate(t.label)) + item.id = `writing:${node.job.id}` + item.description = t.description + item.tooltip = t.tooltip + item.iconPath = new vscode.ThemeIcon('loading~spin') + item.accessibilityInformation = { label: t.a11y } + item.contextValue = 'journeyWriting' + return item +} + /** A row's texts: journeyRowText.ts; revealing rows in the Journeys view: journeysTree.ts. */ export { JourneyRowState, nestsQuestions } from './journeyRowText' export { revealHereGroup, revealJourneyRow } from './journeysTree' diff --git a/src/sidebar/journeysTree.ts b/src/sidebar/journeysTree.ts index 92f46e6..d9955d0 100644 --- a/src/sidebar/journeysTree.ts +++ b/src/sidebar/journeysTree.ts @@ -1,15 +1,16 @@ -// The Journeys view: the journey lists by group (In this file, Continue, All by area), sorting them, and revealing -// rows in it. Its rows are drawn by rowItems.ts (a journey's: journeyRows.ts); its model is listModel.ts; searching -// is journeySearch.ts. +// The Journeys view: the journeys Claude is writing, the journey lists by group (In this file, Continue, All by area; +// a few journeys: one flat list), sorting them, and revealing rows in it. Its rows are drawn by rowItems.ts (a +// journey's: journeyRows.ts); its model is listModel.ts; searching is journeySearch.ts. import * as vscode from 'vscode' import { journeys, tour } from './ports' import { stored } from '../platform/host' import { Group, ListModel, SORTS } from '../core/list/journeyList' +import { agentRunner } from '../platform/agent/runner' import type { Journeys } from '../journeys/journeys' import type { LoadedJourney } from '../journeys/steps' import { badJourneyNodes, jgroupNode, jmoreNode, journeyRowNode, Node } from './nodes' -import { journeyQuestionRows, questionRows } from './journeyRows' +import { drawnWritingNodes, journeyQuestionRows, questionRows, writingNodes } from './journeyRows' import { nestsQuestions } from './journeyRowText' import { activeRel as activeFile, capHere, followCursor, listModel, listSort, onDidChangeListState, showAllHere, sortChanged, useDrawnModel } from './listModel' import { itemOf } from './rowItems' @@ -20,6 +21,8 @@ import { STATE } from '../platform/state' * editor's "In this file" once the editor stayed (the cursor's follow, listModel.ts, redraws before it). */ const REVEAL_WALK_MS = 300 const REVEAL_EDITOR_MS = 700 +/** While Claude writes a journey, its row's clock is drawn again this often. */ +const WRITING_TICK_MS = 1000 class JourneysTree implements vscode.TreeDataProvider<Node> { /** Each row's parent, set while the rows are made and read back by getParent (rows are one object each: nodes.ts). */ @@ -64,12 +67,13 @@ class JourneysTree implements vscode.TreeDataProvider<Node> { return all.children?.find((c) => c.keys.includes(key))?.id } - private rowsOf(g: Group, parent: Node): Node[] { + /** Group `g`'s rows; `parent`: its row (none: they are the view's top rows). */ + private rowsOf(g: Group, parent?: Node): Node[] { const rows: Node[] = g.keys.map((k) => journeyRowNode(journeys().list.get(k)!, g.id)) .filter((n) => n.kind !== 'journey' || !!n.lj) // "Show all": the rest of a capped group (In this file). if (g.more) rows.push(jmoreNode(g)) - for (const r of rows) this.parents.set(r, parent) + if (parent) for (const r of rows) this.parents.set(r, parent) return rows } @@ -77,10 +81,13 @@ class JourneysTree implements vscode.TreeDataProvider<Node> { if (!node) { const m = this.drawn = listModel() this.parents.clear() + const writing = writingNodes() const bad = badJourneyNodes() - if (!m.total) return bad - return [...m.groups.map(jgroupNode), ...bad] + if (!m.total) return [...writing, ...bad] + // A few journeys, none in progress or here: one row each, no "All" above them (journeyList.ts `flat`). + return [...writing, ...(m.flat ? this.rowsOf(m.groups[0]) : m.groups.map(jgroupNode)), ...bad] } + if (node.kind === 'writing') return [] if (node.kind === 'jgroup') { if (!node.g.children) return this.rowsOf(node.g, node) const groups = node.g.children.map(jgroupNode) @@ -121,7 +128,12 @@ export async function sortJourneys(): Promise<void> { /** The Journeys view; its "In this file" follows the editor (capped again), ranked by the cursor's function, and in view. */ export function createJourneysView(context: vscode.ExtensionContext): void { - const view = vscode.window.createTreeView('codeNotes.journeys', { treeDataProvider: journeysTree.sync.provider(journeysTree), showCollapseAll: true }) + // The provider's changes: the whole tree's (ViewSync's redraws), or only the writing rows' clocks (followWriting). + const changed = new vscode.EventEmitter<Node | Node[] | undefined>() + const synced = journeysTree.sync.provider(journeysTree) + const redraws = synced.onDidChangeTreeData!((e) => changed.fire(e as Node | Node[] | undefined)) + const provider: vscode.TreeDataProvider<Node> = { ...synced, onDidChangeTreeData: changed.event } + const view = vscode.window.createTreeView('codeNotes.journeys', { treeDataProvider: provider, showCollapseAll: true }) journeysTree.attach(view) const editorChanged = vscode.window.onDidChangeActiveTextEditor(() => { capHere() @@ -135,7 +147,21 @@ export function createJourneysView(context: vscode.ExtensionContext): void { journeysTree.refresh() if (e.editorChanged) revealHereGroup() }) - context.subscriptions.push(view, editorChanged, selectionChanged, listChanged, ...journeysTree.sync.watch(view)) + context.subscriptions.push(view, editorChanged, selectionChanged, listChanged, ...journeysTree.sync.watch(view), changed, redraws, + followWriting(view, (rows) => changed.fire(rows))) +} + +/** The journeys Claude is writing: their rows come and go with the runs (the whole tree drawn again), and their clocks + * tick while the view shows (only those rows drawn again, by `redrawRows`). */ +function followWriting(view: vscode.TreeView<Node>, redrawRows: (rows: Node[]) => void): vscode.Disposable { + let tick: NodeJS.Timeout | undefined + const runs = agentRunner().inProgress.onDidChange((r) => { + if (r.purpose !== 'journey') return + journeysTree.refresh() + clearInterval(tick) + tick = writingNodes().length ? setInterval(() => { if (view.visible) redrawRows(drawnWritingNodes()) }, WRITING_TICK_MS) : undefined + }) + return vscode.Disposable.from(runs, { dispose: () => clearInterval(tick) }) } /** "Show all" under "In this file". */ diff --git a/src/sidebar/nodes.ts b/src/sidebar/nodes.ts index 844820a..f353cbe 100644 --- a/src/sidebar/nodes.ts +++ b/src/sidebar/nodes.ts @@ -7,6 +7,7 @@ import { Group } from '../core/list/journeyList' import { LoadedJourney } from '../journeys/steps' import { Note } from '../notes/store' import { NodeCache } from './nodeCache' +import type { JourneyJob } from '../write/journeyJobs' import { noteNodes, NoteNode } from './noteNodes' export type { NoteNode } from './noteNodes' @@ -20,6 +21,8 @@ export type JourneyNode = | { kind: 'badJourney'; uri: vscode.Uri; why: string } | { kind: 'intro' } | { kind: 'questions'; lj: LoadedJourney; notes: Note[] } + /** A journey Claude is writing now (journeyRows.ts writingItem). */ + | { kind: 'writing'; job: JourneyJob } /** A row of either view (the Journeys view also lists note rows: the questions asked from a step). */ export type Node = NoteNode | JourneyNode diff --git a/src/sidebar/rowItems.ts b/src/sidebar/rowItems.ts index 196fcd3..7eab7a7 100644 --- a/src/sidebar/rowItems.ts +++ b/src/sidebar/rowItems.ts @@ -3,7 +3,7 @@ import * as vscode from 'vscode' import { tour } from './ports' -import { badJourneyItem, journeyItem, questionsItem, showIntro } from './journeyRows' +import { badJourneyItem, journeyItem, questionsItem, showIntro, writingItem } from './journeyRows' import { listState } from './listModel' import { JourneyNode, Node } from './nodes' import { notesRowItem } from './notesRows' @@ -20,6 +20,7 @@ export function itemOf(node: Node): vscode.TreeItem { case 'questions': return questionsItem(node) case 'jgroup': return jgroupItem(node) case 'jmore': return jmoreItem(node) + case 'writing': return writingItem(node) default: return notesRowItem(node, notesRowFacts()) } } diff --git a/test/golden-list.test.ts b/test/golden-list.test.ts index e163b47..93d3436 100644 --- a/test/golden-list.test.ts +++ b/test/golden-list.test.ts @@ -5,7 +5,7 @@ import { test } from 'node:test' import { expectGolden } from './golden' import { FIXTURES, parsed } from './goldenJourneys' import { matchScore, queryWords, scoreJourney, tellingWords } from '../src/core/list/match' -import { ageOf, areaOf, buildList, seeAlso, stamp } from '../src/core/list/journeyList' +import { FLAT_UNDER, ageOf, areaOf, buildList, seeAlso, stamp } from '../src/core/list/journeyList' import { NOW, items } from './fixtures/journeyList' const AREA = 'journey' @@ -59,6 +59,21 @@ test('golden: the Journeys list model (35 journeys): sorts, searches, chips, the } }) +test('golden: the Journeys view\'s groups for a few journeys and for more, and a walked journey', () => { + const plain = items().map((it) => ({ ...it, resume: 0, walkedAt: undefined })) + const groups = (l: typeof plain) => { + const m = buildList(l, { now: NOW }) + return { flat: m.flat, groups: m.groups } + } + expectGolden(AREA, 'list.groups', { + one: groups(plain.slice(0, 1)), + few: groups(plain.slice(0, FLAT_UNDER - 1)), + nine: groups(plain.slice(0, 9)), + oneWalked: groups([{ ...plain[0], resume: 1, walking: true }]), + nineOneWalked: groups([{ ...plain[0], resume: 1, walking: true }, ...plain.slice(1, 9)]), + }) +}) + test('golden: list helpers: area, age, stamp, see also', () => { const list = items() const day = 86_400_000 diff --git a/test/goldens/journey/list.chip-area.json b/test/goldens/journey/list.chip-area.json index 875ed4e..d050999 100644 --- a/test/goldens/journey/list.chip-area.json +++ b/test/goldens/journey/list.chip-area.json @@ -79,12 +79,12 @@ "k12", "k15", "k17", - "k13", "k18", "k16" ] } ], + "flat": false, "count": 8, "total": 35, "hits": {} diff --git a/test/goldens/journey/list.chip-stale.json b/test/goldens/journey/list.chip-stale.json index b4f1b69..7fc32e3 100644 --- a/test/goldens/journey/list.chip-stale.json +++ b/test/goldens/journey/list.chip-stale.json @@ -87,6 +87,7 @@ ] } ], + "flat": false, "count": 3, "total": 35, "hits": {} diff --git a/test/goldens/journey/list.default.json b/test/goldens/journey/list.default.json index 2f3af79..18d8d86 100644 --- a/test/goldens/journey/list.default.json +++ b/test/goldens/journey/list.default.json @@ -2633,7 +2633,6 @@ "k23", "k20", "k19", - "k26", "k21", "k27", "k22", @@ -2650,7 +2649,6 @@ "k12", "k15", "k17", - "k13", "k18", "k16" ] @@ -2658,6 +2656,7 @@ ] } ], + "flat": false, "count": 35, "total": 35 } diff --git a/test/goldens/journey/list.groups.json b/test/goldens/journey/list.groups.json new file mode 100644 index 0000000..483c8fc --- /dev/null +++ b/test/goldens/journey/list.groups.json @@ -0,0 +1,104 @@ +{ + "one": { + "flat": true, + "groups": [ + { + "id": "all", + "label": "All", + "keys": [ + "k1" + ] + } + ] + }, + "few": { + "flat": true, + "groups": [ + { + "id": "all", + "label": "All", + "keys": [ + "k3", + "k2", + "k1", + "k7", + "k4", + "k5", + "k6" + ] + } + ] + }, + "nine": { + "flat": false, + "groups": [ + { + "id": "all", + "label": "All", + "keys": [], + "children": [ + { + "id": "area:api", + "label": "api", + "keys": [ + "k3", + "k2", + "k9", + "k1", + "k7", + "k4", + "k8", + "k5", + "k6" + ] + } + ] + } + ] + }, + "oneWalked": { + "flat": false, + "groups": [ + { + "id": "continue", + "label": "Continue", + "keys": [ + "k1" + ] + } + ] + }, + "nineOneWalked": { + "flat": false, + "groups": [ + { + "id": "continue", + "label": "Continue", + "keys": [ + "k1" + ] + }, + { + "id": "all", + "label": "All", + "keys": [], + "children": [ + { + "id": "area:api", + "label": "api", + "keys": [ + "k3", + "k2", + "k9", + "k7", + "k4", + "k8", + "k5", + "k6" + ] + } + ] + } + ] + } +} diff --git a/test/goldens/journey/list.here-all.json b/test/goldens/journey/list.here-all.json index eb4cbaa..da19f9c 100644 --- a/test/goldens/journey/list.here-all.json +++ b/test/goldens/journey/list.here-all.json @@ -2572,6 +2572,7 @@ ] } ], + "flat": false, "count": 7, "total": 35 } diff --git a/test/goldens/journey/list.here.json b/test/goldens/journey/list.here.json index 5a34676..cfb22bd 100644 --- a/test/goldens/journey/list.here.json +++ b/test/goldens/journey/list.here.json @@ -2653,7 +2653,6 @@ "k23", "k20", "k19", - "k26", "k21", "k27", "k22", @@ -2670,7 +2669,6 @@ "k12", "k15", "k17", - "k13", "k18", "k16" ] @@ -2678,6 +2676,7 @@ ] } ], + "flat": false, "count": 35, "total": 35 } diff --git a/test/goldens/journey/list.kind-check.json b/test/goldens/journey/list.kind-check.json index 3b507c7..1867e09 100644 --- a/test/goldens/journey/list.kind-check.json +++ b/test/goldens/journey/list.kind-check.json @@ -35,14 +35,8 @@ ], "staleCount": 3, "sections": [], - "groups": [ - { - "id": "all", - "label": "All", - "keys": [], - "children": [] - } - ], + "groups": [], + "flat": false, "count": 0, "total": 35, "hits": {} diff --git a/test/goldens/journey/list.name.json b/test/goldens/journey/list.name.json index 367324c..732fc77 100644 --- a/test/goldens/journey/list.name.json +++ b/test/goldens/journey/list.name.json @@ -116,7 +116,6 @@ "k9", "k34", "k15", - "k26", "k33", "k21", "k27", @@ -127,7 +126,6 @@ "k29", "k10", "k17", - "k13", "k18", "k24", "k4", @@ -140,6 +138,7 @@ ] } ], + "flat": false, "count": 35, "total": 35, "hits": {} diff --git a/test/goldens/journey/list.newest.json b/test/goldens/journey/list.newest.json index 7347994..df0f581 100644 --- a/test/goldens/journey/list.newest.json +++ b/test/goldens/journey/list.newest.json @@ -2577,7 +2577,6 @@ "k10", "k11", "k12", - "k13", "k14", "k15", "k16", @@ -2590,7 +2589,6 @@ "k23", "k24", "k25", - "k26", "k27", "k28", "k29", @@ -2603,6 +2601,7 @@ ] } ], + "flat": false, "count": 35, "total": 35 } diff --git a/test/goldens/journey/list.search-any.json b/test/goldens/journey/list.search-any.json index 0f4c881..b992296 100644 --- a/test/goldens/journey/list.search-any.json +++ b/test/goldens/journey/list.search-any.json @@ -79,6 +79,7 @@ ] } ], + "flat": false, "count": 3, "total": 35, "hits": { diff --git a/test/goldens/journey/list.search-fallback.json b/test/goldens/journey/list.search-fallback.json index 5dc55e8..a173f2e 100644 --- a/test/goldens/journey/list.search-fallback.json +++ b/test/goldens/journey/list.search-fallback.json @@ -67,6 +67,7 @@ ] } ], + "flat": false, "count": 2, "total": 35, "hits": { diff --git a/test/goldens/journey/list.search-none.json b/test/goldens/journey/list.search-none.json index 7420b53..a3d7e0e 100644 --- a/test/goldens/journey/list.search-none.json +++ b/test/goldens/journey/list.search-none.json @@ -41,14 +41,8 @@ "keys": [] } ], - "groups": [ - { - "id": "all", - "label": "All", - "keys": [], - "children": [] - } - ], + "groups": [], + "flat": false, "count": 0, "total": 35, "hits": {} diff --git a/test/goldens/journey/list.search-retry-newest.json b/test/goldens/journey/list.search-retry-newest.json index 39df736..1476a06 100644 --- a/test/goldens/journey/list.search-retry-newest.json +++ b/test/goldens/journey/list.search-retry-newest.json @@ -54,6 +54,7 @@ ] } ], + "flat": false, "count": 2, "total": 35, "hits": { diff --git a/test/goldens/journey/list.search-retry.json b/test/goldens/journey/list.search-retry.json index 1b9b355..12994a6 100644 --- a/test/goldens/journey/list.search-retry.json +++ b/test/goldens/journey/list.search-retry.json @@ -2528,6 +2528,7 @@ ] } ], + "flat": false, "count": 2, "total": 35 } diff --git a/test/goldens/journey/list.walked.json b/test/goldens/journey/list.walked.json index 74cdf7d..a686adf 100644 --- a/test/goldens/journey/list.walked.json +++ b/test/goldens/journey/list.walked.json @@ -102,8 +102,6 @@ "id": "all", "label": "All", "keys": [ - "k13", - "k26", "k23", "k3", "k28", @@ -140,6 +138,7 @@ ] } ], + "flat": false, "count": 35, "total": 35, "hits": {} diff --git a/test/journey-list/shoot.mjs b/test/journey-list/shoot.mjs index 1f32fd7..510f0d0 100644 --- a/test/journey-list/shoot.mjs +++ b/test/journey-list/shoot.mjs @@ -4,7 +4,7 @@ // Checks), "In <file>" capped with "Show n more", a row click selects and previews (stale steps marked, Refresh), // the keyboard (↓ from the search into the rows, a visible focus ring, the focused row in view, chips one Tab stop // with ← →), Enter walks, Esc clears then goes back, "‹ Journeys" from a walk selects that journey, the heading is the -// short title. The extension's part (the model) is out/src/core/list/journeyList.js, run here. +// short title, a card says one verb per state (Resume · n/N or Walk; "Start here" only on one not begun). The extension's part (the model) is out/src/core/list/journeyList.js, run here. // The scenarios run in order on one page per width and theme: each starts where the one before left the home. // Usage (after `npm run build`): node test/journey-list/shoot.mjs [screenshot-dir] (PLAYWRIGHT=…, CHROME=… as in journey-map) import fs from 'node:fs' @@ -41,7 +41,8 @@ function fakeExtension(page, errors) { const posted = () => page.evaluate(() => window.__harness.posted) let state = { query: '', kind: 'all', area: '', sort: 'area' } let hereAll = false - const model = () => buildList(items(), { activeFile: ACTIVE, now: NOW, hereAll, ...state }) + let source = items + const model = () => buildList(source(), { activeFile: ACTIVE, now: NOW, hereAll, ...state }) const staleOf = (key) => (model().rows[key].staleSteps || []).map((n) => ({ n, when: 'a1b2c3d · 3 d ago' })) const answer = { list: async (m) => { @@ -59,7 +60,10 @@ function fakeExtension(page, errors) { seen = ps.length } const settle = async () => { for (let i = 0; i < 4; i++) { await page.waitForTimeout(140); await pump() } } - return { send, posted, settle, model } + /** The journeys listed from now on (the next list the page asks for, or `show`). */ + const use = (f) => { source = f } + const show = () => send({ type: 'tour', ...tour(model()) }) + return { send, posted, settle, model, use, show } } /** What the home shows: sections, rows, the selection and the keyboard, the chips, the preview. */ @@ -254,7 +258,36 @@ async function backFromWalk({ page, ext, fail, shot }) { await shot('home-back') } -const SCENARIOS = [opening, search, sortWhileSearching, fallback, escClears, keyboard, tabOrder, clickAndEnter, staleChip, showMore, escBack, backFromWalk] +/** + * A card per state, one verb each: a "Start here" journey being walked at step 1 says "1/N" and its button "Resume · + * 1/N", no "Start here"; one not begun says "Start here" and its button "Walk". + */ +async function cardStates({ page, ext, fail, shot }) { + const walked = 'k1', fresh = 'k2' + ext.use(() => items().map((it) => it.key === walked ? { ...it, start: true, resume: 1, walking: true } + : it.key === fresh ? { ...it, start: true, resume: 0, walkedAt: undefined } : it)) + await ext.show() + await ext.settle() + const card = async (key) => { + await page.click(`.jrow[data-key="${key}"]`) + await ext.settle() + return page.evaluate((k) => ({ + top: document.querySelector(`.jrow[data-key="${k}"] .jtop`)?.textContent, + start: !!document.querySelector(`.jrow[data-key="${k}"] .jstart`), + go: document.querySelector('.walkb')?.textContent, + }), key) + } + const n = (key) => ext.model().rows[key].steps + const w = await card(walked) + if (w.start || !w.top?.endsWith(`1/${n(walked)}`) || w.go !== `Resume · 1/${n(walked)}`) fail(`a journey in progress: ${JSON.stringify(w)}`) + await shot('home-resume') + const f = await card(fresh) + if (!f.start || f.go !== 'Walk') fail(`a journey not begun: ${JSON.stringify(f)}`) + for (const b of await overflows(page)) fail(`card states: ${b}`) + ext.use(items) +} + +const SCENARIOS = [opening, search, sortWhileSearching, fallback, escClears, keyboard, tabOrder, clickAndEnter, staleChip, showMore, escBack, backFromWalk, cardStates] // ---------- the run ---------- diff --git a/test/journey-map/shoot.mjs b/test/journey-map/shoot.mjs index 000f89d..04a56cf 100644 --- a/test/journey-map/shoot.mjs +++ b/test/journey-map/shoot.mjs @@ -81,7 +81,7 @@ const SHOP = path.join(ROOT, 'examples/shop/journeys/place-order.json') const extra = JOURNEYS ? jsonIn(JOURNEYS) : [] const real = [...jsonIn(SAMPLES), ...extra] /** The home's journeys: those of the folder named, else fixtures/home.json; the first is "here", the second left at - * step 4 and marked "Start here". */ + * step 4 and marked "Start here" (a journey in progress shows where it is instead). */ const list = extra.length ? extra.map((f, i) => ({ key: `k-${path.basename(f)}`, title: path.basename(f, '.json'), question: JSON.parse(fs.readFileSync(f, 'utf8')).question, @@ -534,8 +534,8 @@ async function handoffRecord(p) { async function home(p) { await p.open(journey, { current: 2 }) await p.clickPosts('.homeb', { type: FROM.home, on: true }, '‹ Journeys') - // Each row the title (+ "Start here" on one), where it was left right after it, the question under it (the list - // model, journeyList.ts; its own checks are in test/journey-list/shoot.mjs). A click selects; Enter walks. + // Each row the title (no "Start here" on one in progress), where it was left right after it, the question under it + // (the list model, journeyList.ts; its own checks are in test/journey-list/shoot.mjs). A click selects; Enter walks. const h = await p.page.evaluate(() => ({ rows: [...document.querySelectorAll('.jrow .jtop')].map((r) => r.textContent), qs: [...document.querySelectorAll('.jrow .jq')].map((r) => r.textContent), @@ -544,8 +544,8 @@ async function home(p) { map: !!document.querySelector('.hbody > .hlist .gmap'), h: document.querySelector('.home h1')?.textContent, })) - if (h.rows.length !== list.length || h.map || !h.rows.includes(`${list[1].title}Start here4/13`) || h.h !== 'Journeys') p.problem(`home ${JSON.stringify(h)}`) - if (h.start.join() !== list[1].title) p.problem(`"Start here" on ${JSON.stringify(h.start)}, want only ${list[1].title}`) + if (h.rows.length !== list.length || h.map || !h.rows.includes(`${list[1].title}4/13`) || h.h !== 'Journeys') p.problem(`home ${JSON.stringify(h)}`) + if (h.start.length) p.problem(`"Start here" on ${JSON.stringify(h.start)}, a journey in progress (it says where it is)`) if (h.qs.length !== list.length || !h.qs.includes(list[1].question)) p.problem(`home questions ${JSON.stringify(h.qs)}`) if (h.gap < 0 || h.gap > 20) p.problem(`home "n/N" is ${h.gap}px from its title (want right after it)`) await p.check('home', { current: false }) diff --git a/test/journeyHome.test.ts b/test/journeyHome.test.ts index 7a8520b..b79886d 100644 --- a/test/journeyHome.test.ts +++ b/test/journeyHome.test.ts @@ -6,7 +6,8 @@ import { SORTS as LIST_SORTS } from '../src/core/list/journeyList' interface HomeText { SORTS: [string, string][] staleTip(r: { stale: number; staleSteps?: number[] }): string - walkLabel(r: { walking?: boolean; resume: number }): string + walkLabel(r: { walking?: boolean; resume: number; steps: number }): string + inProgress(r: { walking?: boolean; resume: number }): boolean podcastBadge(p: { duration: number; playing: boolean; at?: number }): { text: string; tip: string } escapeRegExp(s: string): string } @@ -25,10 +26,13 @@ test('a stale row says which steps changed', () => { assert.equal(H.staleTip({ stale: 1 }), '1 step changed since it was written') }) -test('the preview\'s Walk button says where the walk goes', () => { - assert.equal(H.walkLabel({ walking: true, resume: 3 }), 'Back to step 3') - assert.equal(H.walkLabel({ resume: 4 }), 'Resume at 4') - assert.equal(H.walkLabel({ resume: 1 }), 'Walk') +test('the preview\'s button: one verb per state, Resume with where, or Walk', () => { + assert.equal(H.walkLabel({ walking: true, resume: 1, steps: 10 }), 'Resume · 1/10') + assert.equal(H.walkLabel({ walking: true, resume: 3, steps: 10 }), 'Resume · 3/10') + assert.equal(H.walkLabel({ resume: 4, steps: 13 }), 'Resume · 4/13') + assert.equal(H.walkLabel({ resume: 1, steps: 10 }), 'Walk') + assert.equal(H.walkLabel({ resume: 0, steps: 10 }), 'Walk') + assert.deepEqual([{ walking: true, resume: 1 }, { resume: 2 }, { resume: 1 }, { resume: 0 }].map(H.inProgress), [true, true, false, false]) }) test('a row\'s podcast mark: its length, listening, or paused where', () => { diff --git a/test/journeyList.test.ts b/test/journeyList.test.ts index 062eb70..3cacc76 100644 --- a/test/journeyList.test.ts +++ b/test/journeyList.test.ts @@ -1,6 +1,6 @@ import { test } from 'node:test' import assert from 'node:assert/strict' -import { HERE_CAP, ListItem, ageOf, areaOf, buildList, matchedStep, seeAlso } from '../src/core/list/journeyList' +import { FLAT_UNDER, HERE_CAP, ListItem, ageOf, areaOf, buildList, matchedStep, seeAlso } from '../src/core/list/journeyList' import { NAMED, NOW, STORE, items } from './fixtures/journeyList' // The word-level rules the list's search uses (queryWords, stem, matchScore: src/core/list/match.ts) are tested in match.test.ts. @@ -94,8 +94,10 @@ test('sections: Continue, In <file>, New, then by area; the sidebar\'s groups fr assert.deepEqual(m.groups.map((g) => g.id), ['here', 'continue', 'all']) assert.deepEqual(m.groups[2].children!.map((c) => c.label), ['api', 'config', 'payments', 'web', 'worker']) assert.equal(m.rows[NAMED.newest].meta, 'api · 5 steps · 3 d') - // One count everywhere: the panel's total is the sidebar's All. - assert.equal(m.total, m.groups[2].children!.reduce((a, c) => a + c.keys.length, 0)) + // One count everywhere: each journey once in the sidebar's Continue or All, as in the panel. + const listed = [...m.groups[1].keys, ...m.groups[2].children!.flatMap((c) => c.keys)] + assert.equal(new Set(listed).size, listed.length, 'a journey in Continue is not in All again') + assert.equal(m.total, listed.length) // Sorted by date: one flat "Newest" section after the personal ones; the sidebar's All is flat too. const n = buildList(items(), { sort: 'newest', now: NOW }) assert.equal(n.sections.at(-1)!.label, 'Newest') @@ -164,3 +166,31 @@ test('a search result says which step matched', () => { assert.equal(matchedStep(m.rows[NAMED.retries]), 'The worker retries a failed charge with the same key') assert.equal(matchedStep(m.rows[NAMED.newest]), '', 'nothing matched') }) + +test('the sidebar: under FLAT_UNDER journeys one flat All, no areas; from FLAT_UNDER on, All by area', () => { + const few = items().slice(0, FLAT_UNDER - 1).map((it) => ({ ...it, resume: 0, walkedAt: undefined })) + const f = buildList(few, { now: NOW }) + assert.deepEqual(f.groups.map((g) => [g.id, g.label, g.keys.length, g.children]), [['all', 'All', FLAT_UNDER - 1, undefined]]) + assert.equal(f.flat, true, 'its rows are the view\'s top rows, no "All" heading') + assert.equal(buildList(few.slice(0, 1), { now: NOW }).flat, true, 'one journey: one row') + // A step in the active file: "In this file" has a heading, so All keeps its own. + assert.equal(buildList(few, { activeFile: STORE, now: NOW }).flat, false) + const many = items().slice(0, FLAT_UNDER).map((it) => ({ ...it, resume: 0, walkedAt: undefined })) + const g = buildList(many, { now: NOW }) + assert.equal(g.groups.length, 1) + assert.equal(g.flat, false) + assert.equal(buildList(many, { sort: 'name', now: NOW }).flat, false, 'flat All from FLAT_UNDER on keeps its heading') + assert.ok(g.groups[0].children!.length > 0, 'by area') + assert.ok(g.groups[0].children!.every((c) => c.id.startsWith('area:') && c.label !== 'All'), 'no area group named All') +}) + +test('the sidebar: a walked journey is listed once, in Continue; All keeps the rest, or is left out when empty', () => { + const one = { ...items()[0], resume: 1, walking: true } + const m = buildList([one], { now: NOW }) + assert.deepEqual(m.groups.map((g) => [g.id, g.keys]), [['continue', [one.key]]]) + assert.equal(m.flat, false, 'a lone Continue keeps its heading') + const two = buildList([one, { ...items()[1], resume: 0, walkedAt: undefined }], { now: NOW }) + assert.deepEqual(two.groups.map((g) => [g.id, g.keys]), [['continue', [one.key]], ['all', [items()[1].key]]]) + // Opened and closed at step 1: not Continue, a plain row again. + assert.deepEqual(buildList([{ ...one, walking: false }], { now: NOW }).groups.map((g) => g.id), ['all']) +}) diff --git a/test/journeyRowText.test.ts b/test/journeyRowText.test.ts index 9de0000..11c9d95 100644 --- a/test/journeyRowText.test.ts +++ b/test/journeyRowText.test.ts @@ -1,7 +1,7 @@ import { test } from 'node:test' import assert from 'node:assert/strict' import { buildList } from '../src/core/list/journeyList' -import { journeyDescription, journeyLabel, JourneyRowState, journeyTooltip, nestsQuestions, podcastContext } from '../src/sidebar/journeyRowText' +import { journeyDescription, journeyLabel, JourneyRowState, journeyTooltip, nestsQuestions, podcastContext, writingRowText } from '../src/sidebar/journeyRowText' import { NAMED, NOW, STORE, items } from './fixtures/journeyList' // A journey's row in the Journeys view: its texts made from one state (src/sidebar/journeyRowText.ts). @@ -13,9 +13,11 @@ const plain: JourneyRowState = { } const tip = { question: 'How do orders work?', summary: 'The path.', provenance: '', staleLine: '' } -test('a plain row: its area and age; under its area only the age', () => { - assert.equal(journeyDescription(plain, 'all'), 'api · 3 d') - assert.equal(journeyDescription(plain, 'area:api'), '3 d') +test('a plain row: how many steps, in words; no area, no age (the tooltip says when it was written)', () => { + assert.equal(journeyDescription(plain, 'all'), '5 steps') + assert.equal(journeyDescription(plain, 'area:api'), '5 steps') + assert.equal(journeyDescription(plain, undefined), '5 steps') + assert.equal(journeyDescription({ ...plain, steps: 1 }, 'all'), '1 step') assert.equal(journeyLabel('How orders work', plain), 'How orders work') assert.equal(journeyTooltip(plain, tip), 'How do orders work?\nThe path.') }) @@ -31,8 +33,8 @@ test('walking and left: the description and the label say the same step, each in test('refreshing before stale; replies, unreadable and new after', () => { const s = { ...plain, refreshing: true, stale: true, newReplies: 2, unreadable: true, isNew: true } - assert.equal(journeyDescription(s, 'all'), 'api · 3 d · Refreshing… · 2 replies · ⚠ unreadable · new') - assert.equal(journeyDescription({ ...s, refreshing: false }, 'all'), 'api · 3 d · ⚠ Stale · 2 replies · ⚠ unreadable · new') + assert.equal(journeyDescription(s, 'all'), '5 steps · Refreshing… · 2 replies · ⚠ unreadable · new') + assert.equal(journeyDescription({ ...s, refreshing: false }, 'all'), '5 steps · ⚠ Stale · 2 replies · ⚠ unreadable · new') assert.equal(journeyLabel('T', s), 'T, 2 unread replies, new') assert.equal(journeyTooltip({ ...plain, newReplies: 1 }, tip), 'How do orders work?\nThe path.\n1 unread reply from Claude') }) @@ -40,11 +42,14 @@ test('refreshing before stale; replies, unreadable and new after', () => { test('in "In this file": how much of it is here', () => { const here = { ...plain, row: model.rows[NAMED.twoInStore[0]] } assert.equal(journeyDescription(here, 'here'), '2 of 7 steps here') + assert.equal(journeyDescription({ ...here, pod: { state: 'ok', duration: 40 } }, 'here'), '2 of 7 steps here · ♪ 0:40') }) test('a podcast: its length on the row and in the label; one that cannot play says why, and offers no ▶', () => { const ok = { ...plain, pod: { state: 'ok' as const, duration: 125 } } - assert.match(journeyDescription(ok, 'all')!, /^♪ 2:05 · api · 3 d$/) + assert.equal(journeyDescription(ok, 'all'), '5 steps · ♪ 2:05') + assert.equal(journeyDescription({ ...ok, steps: 10, pod: { state: 'ok', duration: 40 } }, 'all'), '10 steps · ♪ 0:40') + assert.equal(journeyDescription({ ...ok, left: 2 }, 'continue'), 'step 2/5 · ♪ 2:05') assert.equal(journeyLabel('T', ok), 'T, podcast 2:05') assert.equal(journeyDescription({ ...ok, left: 2, pod: { ...ok.pod, session: true } }, 'all'), '♪ 2:05', 'listened to: no step') assert.equal(podcastContext(ok.pod), ';podcast') @@ -58,3 +63,12 @@ test('a podcast: its length on the row and in the label; one that cannot play sa test('questions nest under All, its areas and a row of no group only', () => { assert.deepEqual([undefined, 'all', 'area:api', 'here', 'continue'].map(nestsQuestions), [true, true, true, false, false]) }) + +test('a journey being written: its question, then the clock and what Claude is doing', () => { + const job = { question: 'How is a note\n saved to disk?', model: 'sonnet', started: NOW - 80_000, phase: 'reading store.ts' } + const t = writingRowText(job, NOW) + assert.equal(t.label, 'Writing: How is a note saved to disk?') + assert.equal(t.description, '1:20 · reading store.ts') + assert.equal(t.tooltip, 'How is a note saved to disk?\nClaude (sonnet) is writing a journey for this question.') + assert.match(writingRowText({ ...job, started: NOW }, NOW).description, /^0:00 · /) +}) From 8606b8ba6eb5add88e7aab976e90b196c85b1d52 Mon Sep 17 00:00:00 2001 From: tomeyer97 <107920881+tomeyer97@users.noreply.github.com> Date: Thu, 26 Nov 2026 22:46:46 +0100 Subject: [PATCH 14/17] Threads and anchors: stale lines visible in the editor, a clear move, applied suggestions recorded, links that read well aloud Slice: S06 Zeroshot-Run: 01a219c3-993c-77a1-a353-38da6ec92c0a --- 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`(?<![\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 diff --git a/src/notes/decorations.ts b/src/notes/decorations.ts index d9cfba1..798fddc 100644 --- a/src/notes/decorations.ts +++ b/src/notes/decorations.ts @@ -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' @@ -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) } : {}), }) } @@ -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() } 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<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 @@ -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<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 } 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<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 } +} 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<ThreadStatus['concern']> -/** 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<TourApi, 'seeAlsoLink const s = chk.threadStatus(n) return [ ...(s?.checking ? [{ comment: systemRow('_Checking your answer…_', 'Understanding check', 'checking…') }] : []), - ...(s?.concern ? [concernRow(id, s.concern)] : []), + ...(s?.concern ? [concernRow(s.concern)] : []), ...seeAlsoRow(n, chk, tour), ...(s?.error ? [{ comment: systemRow((l) => `⚠ ${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<string, unknown> | 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<string, unknown> | undefined, a: Applied): Record<string, unknown> { + 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`(?<![\w/~.\-\u0000])` + '`?((?:[\\w.-]+\\/)+[\\w.-]+\\.[a-zA-Z]{1,6})' + String.raw`(?::(\d+)(?:-\d+)?|#L(\d+))` + '`?') + String.raw`(?<![\w/~.\-\u0000])` + '`?((?:[\\w.-]+\\/)+[\\w.-]+\\.[a-zA-Z]{1,6}|' + P.ROOT_FILE + ')' + + String.raw`(?::(\d+)(?:-\d+)?|#L(\d+))` + '`?') + assert.equal(P.ROOT_FILE, String.raw`(?![a-zA-Z]\.[a-zA-Z](?![\w.]))[\w-][\w.-]*\.(?!(?:com|org|net)\b)[a-zA-Z]{1,6}`) const all = (re: RegExp, s: string) => [...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 cd6e350..27431c8 100644 --- a/test/integration/check/answers.ts +++ b/test/integration/check/answers.ts @@ -224,15 +224,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?<key>) 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?<key>` 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 451c8b6..5df8189 100644 --- a/test/integration/main/journeyTour.ts +++ b/test/integration/main/journeyTour.ts @@ -10,7 +10,7 @@ import { appendMessage, now, quiet, settle, test, windowShot } from '../helpers' import { shotsInBothThemes } from './themeShots' import { journey, step, writeJourney, writeLines } from '../fixtures' import { cdp, codeColumns, ui } from '../devtools' -import { at, bodyOf, closeAllEditors, codeLenses, ctx, journeysDir, journeysTree, lenses, notesTree, setting, snap, tabOpen, tour, until, wsPath } from './context' +import { at, bodyOf, closeAllEditors, commandLinksIn, codeLenses, 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 */ @@ -382,7 +382,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 ede9863..25702e2 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 4250463..28c1d8e 100644 --- a/test/integration/suite.ts +++ b/test/integration/suite.ts @@ -20,6 +20,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 @@ -58,6 +59,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]) From 5d7f13fd074302a4b2fa7b6103a6bbfe8c2b6d9f Mon Sep 17 00:00:00 2001 From: tomeyer97 <107920881+tomeyer97@users.noreply.github.com> Date: Thu, 26 Nov 2026 23:17:51 +0100 Subject: [PATCH 15/17] The manifest says what the extension does: welcome texts, palette, menus and keys for the other slices, settings wording Slice: S01 Zeroshot-Run: 01a219d3-6242-7a82-a871-2655f6ebbd5d --- package.json | 210 ++++++++++++++++++++++--------- scripts/keymap.mjs | 4 + src/notes/index.ts | 11 +- src/platform/commands.ts | 24 ++-- src/threads/index.ts | 8 +- test/integration/main/threads.ts | 4 +- test/keybindings.test.ts | 18 ++- test/manifest.test.ts | 150 +++++++++++++++++++++- 8 files changed, 340 insertions(+), 89 deletions(-) diff --git a/package.json b/package.json index dbe23e9..03819db 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "code-notes", "displayName": "Code Notes", - "description": "Notes on code that your coding agent answers in threads, and Code Journeys: guided, animated walks through how a codebase works.", + "description": "Understand code you did not write: notes your coding agent answers, journeys through how it works, and an understanding check before you merge.", "version": "0.26.0", "publisher": "tomeyer97", "license": "MIT", @@ -51,7 +51,10 @@ "skills/understanding-check/SKILL.md", "skills/understanding-check/scripts/questions.mjs", "cli/understanding.mjs", + "docs/agent-protocol.md", + "docs/journey-format.md", "docs/podcast-format.md", + "docs/understanding-check.md", "README.md", "CHANGELOG.md", "LICENSE" @@ -81,7 +84,8 @@ { "type": "webview", "id": "codeNotes.check", - "name": "Check" + "name": "Check", + "when": "!codeNotes.checkOnBase" }, { "id": "codeNotes.journeys", @@ -99,6 +103,10 @@ { "view": "codeNotes.notes", "contents": "Select code and press Ctrl+' C to leave a note.\n[Add a Note](command:codeNotes.add)" + }, + { + "view": "codeNotes.journeys", + "contents": "Ask how something works; Claude writes a walk through the code.\n[Ask a Question About the Code…](command:codeNotes.askQuestion)" } ], "commands": [ @@ -108,11 +116,6 @@ "category": "Code Notes", "icon": "$(comment)" }, - { - "command": "codeNotes.addQuick", - "title": "Add One-Line Note", - "category": "Code Notes" - }, { "command": "codeNotes.reply", "title": "Reply", @@ -120,7 +123,7 @@ }, { "command": "codeNotes.createFromThread", - "title": "Add Note", + "title": "Save Note", "category": "Code Notes" }, { @@ -247,11 +250,6 @@ "category": "Code Notes", "icon": "$(copy)" }, - { - "command": "codeNotes.replyResolve", - "title": "Reply & Resolve", - "category": "Code Notes" - }, { "command": "codeNotes.hideSession", "title": "Hide Session in Editor", @@ -266,7 +264,7 @@ }, { "command": "codeNotes.showOnlySession", - "title": "Show Only This Session", + "title": "Show Only This Session in Editor", "category": "Code Notes", "icon": "$(target)" }, @@ -353,7 +351,7 @@ }, { "command": "codeNotes.askQuestion", - "title": "Ask a Question About the Code…", + "title": "Find or Write a Journey…", "category": "Code Notes" }, { @@ -515,6 +513,26 @@ "title": "Act on a Concern Found During the Check", "category": "Code Notes" }, + { + "command": "codeNotes.concernFix", + "title": "Suggest a Fix", + "category": "Code Notes" + }, + { + "command": "codeNotes.concernTodo", + "title": "Add TODO", + "category": "Code Notes" + }, + { + "command": "codeNotes.concernFlag", + "title": "Flag for Reviewer", + "category": "Code Notes" + }, + { + "command": "codeNotes.concernDismiss", + "title": "Dismiss Concern", + "category": "Code Notes" + }, { "command": "codeNotes.pickJourneyStep", "title": "Pick a Journey Step Here", @@ -885,6 +903,16 @@ "command": "codeNotes.cancelMove", "key": "escape", "when": "codeNotes.moving && editorTextFocus && !suggestWidgetVisible && !findWidgetVisible" + }, + { + "command": "codeNotes.moveToSelection", + "key": "enter", + "when": "codeNotes.moving && editorTextFocus && !suggestWidgetVisible" + }, + { + "command": "codeNotes.closeNoteBox", + "key": "escape", + "when": "commentEditorFocused && commentController == codeNotes && commentThreadIsEmpty" } ], "menus": { @@ -919,18 +947,43 @@ "command": "codeNotes.answerCheck", "group": "inline@1", "when": "commentController == codeNotes && !commentThreadIsEmpty && commentThread =~ /check/" + }, + { + "command": "codeNotes.askClaude", + "when": "commentController == codeNotes && config.codeNotes.claude.mode != 'off' && commentThread =~ /open/ && !(commentThread =~ /check/) && !(commentThread =~ /asking/) && codeNotes.claudeFound", + "group": "inline@2" + }, + { + "command": "codeNotes.concernFix", + "when": "commentController == codeNotes && commentThread =~ /concern/", + "group": "inline@3" + }, + { + "command": "codeNotes.concernTodo", + "when": "commentController == codeNotes && commentThread =~ /concern/ && !(commentThread =~ /todo/)", + "group": "inline@4" + }, + { + "command": "codeNotes.concernFlag", + "when": "commentController == codeNotes && commentThread =~ /concern/", + "group": "inline@5" + }, + { + "command": "codeNotes.concernDismiss", + "when": "commentController == codeNotes && commentThread =~ /concern/", + "group": "inline@6" } ], "comments/commentThread/title": [ { "command": "codeNotes.cancelClaude", - "group": "navigation@0", + "group": "navigation@1", "when": "commentController == codeNotes && commentThread =~ /asking/" }, { "command": "codeNotes.askClaude", "group": "navigation@0", - "when": "commentController == codeNotes && config.codeNotes.claude.mode != 'off' && (commentThread =~ /open/ || commentThread =~ /check/) && !(commentThread =~ /asking/) && codeNotes.claudeFound" + "when": "commentController == codeNotes && config.codeNotes.claude.mode != 'off' && commentThread =~ /check/ && !(commentThread =~ /asking/) && codeNotes.claudeFound" }, { "command": "codeNotes.resolve", @@ -1018,6 +1071,16 @@ "command": "codeNotes.sortJourneys", "when": "view == codeNotes.journeys", "group": "navigation@2" + }, + { + "command": "codeNotes.refresh", + "when": "view == codeNotes.notes", + "group": "3_reload@1" + }, + { + "command": "codeNotes.tutorial", + "when": "view == codeNotes.journeys && codeNotes.hasJourneys", + "group": "1_help@1" } ], "view/item/context": [ @@ -1198,11 +1261,11 @@ }, { "command": "codeNotes.showResolved", - "when": "false" + "when": "codeNotes.hasNotes && !codeNotes.showResolved" }, { "command": "codeNotes.hideResolved", - "when": "false" + "when": "codeNotes.showResolved" }, { "command": "codeNotes.resolve", @@ -1232,10 +1295,6 @@ "command": "codeNotes.copyNotePrompt", "when": "codeNotes.cursorOnNote" }, - { - "command": "codeNotes.replyResolve", - "when": "false" - }, { "command": "codeNotes.openAt", "when": "false" @@ -1282,7 +1341,7 @@ }, { "command": "codeNotes.showAllSessions", - "when": "false" + "when": "codeNotes.hasHiddenSessions" }, { "command": "codeNotes.applySuggestion", @@ -1290,11 +1349,11 @@ }, { "command": "codeNotes.groupByFile", - "when": "false" + "when": "codeNotes.groupBy == 'session'" }, { "command": "codeNotes.groupBySession", - "when": "false" + "when": "codeNotes.groupBy == 'file' && codeNotes.hasSessions" }, { "command": "codeNotes.openJourney", @@ -1340,10 +1399,6 @@ "command": "codeNotes.tutorial", "when": "codeNotes.hasJourneys" }, - { - "command": "codeNotes.addQuick", - "when": "false" - }, { "command": "codeNotes.addPathNote", "when": "false" @@ -1370,27 +1425,27 @@ }, { "command": "codeNotes.markAllRead", - "when": "false" + "when": "codeNotes.hasNotes" }, { "command": "codeNotes.resolveAll", - "when": "false" + "when": "codeNotes.hasNotes" }, { "command": "codeNotes.deleteResolved", - "when": "false" + "when": "codeNotes.hasNotes" }, { "command": "codeNotes.nextUnread", - "when": "false" + "when": "codeNotes.hasNotes" }, { "command": "codeNotes.previousUnread", - "when": "false" + "when": "codeNotes.hasNotes" }, { "command": "codeNotes.filter", - "when": "false" + "when": "codeNotes.hasNotes" }, { "command": "codeNotes.find", @@ -1398,7 +1453,7 @@ }, { "command": "codeNotes.copyAgentPrompt", - "when": "false" + "when": "codeNotes.hasNotes" }, { "command": "codeNotes.resolveNext", @@ -1412,10 +1467,6 @@ "command": "codeNotes.askFromThread", "when": "false" }, - { - "command": "codeNotes.refresh", - "when": "false" - }, { "command": "codeNotes.toggleAuthorMode", "when": "config.codeNotes.journeys.authorMode" @@ -1439,6 +1490,38 @@ { "command": "codeNotes.journeysHereAll", "when": "false" + }, + { + "command": "codeNotes.refreshJourney", + "when": "codeNotes.hasJourneys" + }, + { + "command": "codeNotes.playPodcast", + "when": "codeNotes.hasJourneys" + }, + { + "command": "codeNotes.sortJourneys", + "when": "codeNotes.hasJourneys" + }, + { + "command": "codeNotes.toggleAnimation", + "when": "codeNotes.hasJourneys" + }, + { + "command": "codeNotes.concernFix", + "when": "false" + }, + { + "command": "codeNotes.concernTodo", + "when": "false" + }, + { + "command": "codeNotes.concernFlag", + "when": "false" + }, + { + "command": "codeNotes.concernDismiss", + "when": "false" } ], "explorer/context": [ @@ -1476,7 +1559,7 @@ "codeNotes.highlight": { "type": "boolean", "default": true, - "description": "Tint lines that have an open note." + "description": "Show a bar beside lines with an open note." }, "codeNotes.showResolvedInEditor": { "type": "boolean", @@ -1490,18 +1573,29 @@ "always", "off" ], + "enumItemLabels": [ + "When I ask", + "Every note", + "Never" + ], "default": "button", "enumDescriptions": [ "An \"Ask Claude\" button on the note box, threads and the list.", "Every new note and reply goes to Claude right away.", "No Claude." ], - "description": "Answer notes with Claude Code (the newest `claude` CLI found, your existing login). Claude can read the code but not change it (and can use the skills in Code Notes › Claude: Skills). Ask Claude shows only when the `claude` CLI is found (install Claude Code, or set Code Notes › Claude: Path)." + "description": "Claude Code answers notes. It can read code, never change it." }, "codeNotes.claude.model": { "type": "string", "default": "", - "description": "Model for answers (e.g. \"sonnet\" for cheaper, faster answers). Empty: Claude Code's default." + "examples": [ + "sonnet", + "opus", + "haiku", + "fable" + ], + "description": "Model for answers: sonnet, opus, haiku, fable or a model id. Empty: Claude Code's default." }, "codeNotes.claude.path": { "type": "string", @@ -1551,17 +1645,29 @@ "codeNotes.journeys.model": { "type": "string", "default": "", - "description": "Model Claude Code uses to write a journey from the journey picker (\"Ask the agent to write a journey…\"). Empty: Code Notes › Claude: Model, else Claude Code's default." + "examples": [ + "sonnet", + "opus", + "haiku", + "fable" + ], + "markdownDescription": "Model that writes journeys: sonnet, opus, haiku, fable or an id. Empty: `#codeNotes.claude.model#`." }, "codeNotes.understanding.background": { "type": "boolean", "default": true, - "markdownDescription": "Write a branch's understanding-check questions in the background when it is pushed without a check; the status bar says when they are ready." + "markdownDescription": "Writes the questions with Claude when a branch is pushed, in repositories that use the check." }, "codeNotes.understanding.model": { "type": "string", "default": "", - "markdownDescription": "The model that writes and grades the understanding-check questions (`sonnet`, `opus`, a `claude-*` id). Empty: **Code Notes › Claude: Model**, else Claude Code's default." + "examples": [ + "sonnet", + "opus", + "haiku", + "fable" + ], + "markdownDescription": "Model for the check: sonnet, opus, haiku, fable or an id. Empty: `#codeNotes.claude.model#`." } } }, @@ -1586,15 +1692,6 @@ "highContrastLight": "#00a39040" } }, - { - "id": "codeNotes.noteBackground", - "description": "Background of lines with an open note.", - "defaults": { - "dark": "#a371f726", - "light": "#8250df12", - "highContrast": "#a371f726" - } - }, { "id": "codeNotes.noteBorder", "description": "Left bar of lines with an open note.", @@ -1643,7 +1740,6 @@ ], "configurationDefaults": { "comments.openView": "never", - "comments.maxHeight": false, "editor.smoothScrolling": true } }, diff --git a/scripts/keymap.mjs b/scripts/keymap.mjs index 2483b56..c281076 100644 --- a/scripts/keymap.mjs +++ b/scripts/keymap.mjs @@ -28,6 +28,10 @@ export const PREFIXES = [{ key: 'ctrl+[IntlBackslash]', arg: '<' }, { key: "ctrl /** Bindings outside the chord scheme. */ export const OTHERS = [ { command: 'codeNotes.cancelMove', key: 'escape', when: 'codeNotes.moving && editorTextFocus && !suggestWidgetVisible && !findWidgetVisible' }, + // Moving a note: Enter puts it on the selected lines (the status bar item says so). + { command: 'codeNotes.moveToSelection', key: 'enter', when: 'codeNotes.moving && editorTextFocus && !suggestWidgetVisible' }, + // Esc in an empty new note box closes it and keeps the draft. + { command: 'codeNotes.closeNoteBox', key: 'escape', when: 'commentEditorFocused && commentController == codeNotes && commentThreadIsEmpty' }, ] /** diff --git a/src/notes/index.ts b/src/notes/index.ts index 4d99915..20c6e5c 100644 --- a/src/notes/index.ts +++ b/src/notes/index.ts @@ -43,9 +43,6 @@ export type { NotesFeaturePorts } from './ports' /** A file in the notes folder (the store watches it: no note or step is on it). */ export { inNotesFolder } from './notesFolder' -/** Closes a new note box, keeping its draft (create.ts closeNoteBox). */ -export const CLOSE_NOTE_BOX = 'codeNotes.closeNoteBox' - /** The id VS Code knows the notes' comment threads by. */ const CONTROLLER_ID = 'codeNotes' @@ -96,15 +93,15 @@ export async function activateNotes(context: vscode.ExtensionContext, ports: Not // A note you made is read (its first message is yours): stored in the background (a round trip to the window). onDidCreateNote((n) => fireAndForget(setSeen([[n.data.id, 1]]), 'seen')), takeLinks((link) => stepLink(ports.layout, link)), - // Esc in a new note box (the key is the manifest's); not in the command table yet, so registered here. - vscode.commands.registerCommand(CLOSE_NOTE_BOX, async () => { + // Esc in a new note box (the key is the manifest's): closes it, keeping its draft (create.ts closeNoteBox). + vscode.commands.registerCommand(HiddenCmd.closeNoteBox, async () => { try { await closeNoteBox() } finally { drafting.fire(false) } }), ) registerCommands(context, { // Adding, replying, asking from a thread. A note being written pauses what plays (its code stays put under it). [Cmd.add]: chord(() => { drafting.fire(true); return addNote() }), - [Cmd.addQuick]: addQuickNote, + [HiddenCmd.addQuick]: addQuickNote, [Cmd.addPathNote]: (uri?: vscode.Uri, text?: unknown) => addPathNote(uri, text), [Cmd.askFromThread]: askFromThread, [Cmd.createFromThread]: async (...a: Parameters<typeof createFromThread>) => { @@ -112,7 +109,7 @@ export async function activateNotes(context: vscode.ExtensionContext, ports: Not }, [Cmd.reply]: replyTo, [Cmd.replyReopen]: replyTo, // the same, labelled for resolved threads - [Cmd.replyResolve]: replyAndResolve, + [HiddenCmd.replyResolve]: replyAndResolve, [Cmd.applySuggestion]: (id: string, mi: number, k: number) => applySuggestion(id, mi, k), // Resolving, deleting, moving, reading. [Cmd.resolve]: async (arg?: CommandArg, many?: readonly CommandArg[]) => resolve(await pickNotes(arg, many)), diff --git a/src/platform/commands.ts b/src/platform/commands.ts index 42b9688..078fedd 100644 --- a/src/platform/commands.ts +++ b/src/platform/commands.ts @@ -6,9 +6,8 @@ /** The contributed commands (package.json), by name; the comment is the title the palette shows. */ export const Cmd = { add: 'codeNotes.add', // Add Note - addQuick: 'codeNotes.addQuick', // Add One-Line Note reply: 'codeNotes.reply', // Reply - createFromThread: 'codeNotes.createFromThread', // Add Note + createFromThread: 'codeNotes.createFromThread', // Save Note reveal: 'codeNotes.reveal', // Open Thread resolve: 'codeNotes.resolve', // Resolve reopen: 'codeNotes.reopen', // Reopen @@ -31,10 +30,9 @@ export const Cmd = { find: 'codeNotes.find', // Find Note… refresh: 'codeNotes.refresh', // Reload Notes copyAgentPrompt: 'codeNotes.copyAgentPrompt', // Copy Prompt for Agent - replyResolve: 'codeNotes.replyResolve', // Reply & Resolve hideSession: 'codeNotes.hideSession', // Hide Session in Editor showSession: 'codeNotes.showSession', // Show Session in Editor - showOnlySession: 'codeNotes.showOnlySession', // Show Only This Session + showOnlySession: 'codeNotes.showOnlySession', // Show Only This Session in Editor showAllSessions: 'codeNotes.showAllSessions', // Show All Sessions resolveSession: 'codeNotes.resolveSession', // Resolve Session… deleteSession: 'codeNotes.deleteSession', // Delete Session… @@ -50,7 +48,7 @@ export const Cmd = { restoreBroken: 'codeNotes.restoreBroken', // Restore Last Good Version collapseThread: 'codeNotes.collapseThread', // Show Fewer Replies openJourney: 'codeNotes.openJourney', // Open Journey… - askQuestion: 'codeNotes.askQuestion', // Ask a Question About the Code… + askQuestion: 'codeNotes.askQuestion', // Find or Write a Journey… startJourney: 'codeNotes.startJourney', // Start Journey nextStep: 'codeNotes.nextStep', // Next Step previousStep: 'codeNotes.previousStep', // Previous Step @@ -81,6 +79,11 @@ export const Cmd = { answerCheck: 'codeNotes.answerCheck', // Answer gradeCheck: 'codeNotes.gradeCheck', // Grade the Answer Again checkConcern: 'codeNotes.checkConcern', // Act on a Concern Found During the Check + // A check concern's actions, buttons on its thread. + concernFix: 'codeNotes.concernFix', // Suggest a Fix + concernTodo: 'codeNotes.concernTodo', // Add TODO + concernFlag: 'codeNotes.concernFlag', // Flag for Reviewer + concernDismiss: 'codeNotes.concernDismiss', // Dismiss Concern pickJourneyStep: 'codeNotes.pickJourneyStep', // Pick a Journey Step Here searchJourneys: 'codeNotes.searchJourneys', // Search Journeys sortJourneys: 'codeNotes.sortJourneys', // Sort Journeys @@ -103,12 +106,13 @@ export const HiddenCmd = { 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', + /** A concern marked fixed (the commit that fixes it does this; no button). */ concernFixed: 'codeNotes.concernFixed', - concernDismiss: 'codeNotes.concernDismiss', + /** Not contributed (no menu or key runs them); still registered for keybindings people wrote themselves. */ + addQuick: 'codeNotes.addQuick', + replyResolve: 'codeNotes.replyResolve', + /** Esc in a new note box (the manifest's key). */ + closeNoteBox: 'codeNotes.closeNoteBox', notesFocus: 'codeNotes.notes.focus', journeysFocus: 'codeNotes.journeys.focus', checkFocus: 'codeNotes.check.focus', diff --git a/src/threads/index.ts b/src/threads/index.ts index 2ad932c..95e42e2 100644 --- a/src/threads/index.ts +++ b/src/threads/index.ts @@ -49,11 +49,11 @@ export function activateThreads(context: vscode.ExtensionContext, ports: Threads 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'), + [Cmd.concernFix]: concern('fix'), + [Cmd.concernTodo]: concern('todo'), + [Cmd.concernFlag]: concern('flag'), [HiddenCmd.concernFixed]: concern('fixed'), - [HiddenCmd.concernDismiss]: concern('dismiss'), + [Cmd.concernDismiss]: concern('dismiss'), }) return { has: (id) => view.has(id), diff --git a/test/integration/main/threads.ts b/test/integration/main/threads.ts index 17647a7..68c66bb 100644 --- a/test/integration/main/threads.ts +++ b/test/integration/main/threads.ts @@ -10,7 +10,7 @@ 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 { Cmd, HiddenCmd } from '../../../src/platform/commands' import { commandLinksIn, ctx, noteById, notePath, snap, until, wsPath } from './context' /* eslint-disable @typescript-eslint/no-explicit-any */ @@ -70,7 +70,7 @@ export const threadsTests = [ 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]) { + for (const c of [HiddenCmd.link, Cmd.concernFix, Cmd.concernTodo, Cmd.concernFlag, HiddenCmd.concernFixed, Cmd.concernDismiss]) { assert.ok(all.includes(c), `${c} is registered (the concern's actions on its thread)`) } }), diff --git a/test/keybindings.test.ts b/test/keybindings.test.ts index 13e77fa..8838623 100644 --- a/test/keybindings.test.ts +++ b/test/keybindings.test.ts @@ -40,12 +40,23 @@ test('one chord scheme on two prefixes: Ctrl+< by scan code (ISO key) and Ctrl+\ } } } - assert.equal(keys.length, PREFIXES.length * Object.keys(CHORDS).length * 2 + 1 /* escape */, 'nothing else but escape') + assert.equal(keys.length, PREFIXES.length * Object.keys(CHORDS).length * 2 + 3, 'nothing else but Esc and Enter (below)') // VS Code shows the last binding of a command: the plain chord, "Ctrl+' D". for (const command of Object.values(CHORDS)) assert.equal(keys.filter((k) => k.command === command).pop()!.key.replace(/^\S+ /, ''), Object.keys(CHORDS).find((k) => CHORDS[k] === command)) assert.ok(keys.some((k) => k.key === 'escape' && k.command === 'codeNotes.cancelMove')) }) +test('outside the chords: Esc and Enter only where they belong to Code Notes', () => { + const others = keys.filter((k) => !k.args) + assert.deepEqual(others, [ + { command: 'codeNotes.cancelMove', key: 'escape', when: 'codeNotes.moving && editorTextFocus && !suggestWidgetVisible && !findWidgetVisible' }, + // Moving a note: Enter puts it on the selection (the status bar item's action). + { command: 'codeNotes.moveToSelection', key: 'enter', when: 'codeNotes.moving && editorTextFocus && !suggestWidgetVisible' }, + // Esc in an empty new note box of ours closes it (the draft is kept); other comment boxes keep their Esc. + { command: 'codeNotes.closeNoteBox', key: 'escape', when: 'commentEditorFocused && commentController == codeNotes && commentThreadIsEmpty' }, + ]) +}) + test('the chord table is the scheme as documented: letters for notes and journeys, arrows and space for listening', async () => { assert.deepEqual((await keymap()).CHORDS, { c: 'codeNotes.add', @@ -63,7 +74,8 @@ test('the chord table is the scheme as documented: letters for notes and journey }) }) -test('every bound command is contributed', () => { +test('every bound command is contributed, except closing the note box (a key, not a verb for the palette)', () => { const cmds = new Set(pkg.contributes.commands.map((c: { command: string }) => c.command)) - for (const k of keys) assert.ok(cmds.has(k.command), k.command) + for (const k of keys.filter((x) => x.command !== 'codeNotes.closeNoteBox')) assert.ok(cmds.has(k.command), k.command) + assert.ok(!cmds.has('codeNotes.closeNoteBox')) }) diff --git a/test/manifest.test.ts b/test/manifest.test.ts index 1f7a1b1..610403d 100644 --- a/test/manifest.test.ts +++ b/test/manifest.test.ts @@ -1,9 +1,11 @@ // What package.json contributes, checked where it can drift by hand: command titles in one style, every command either -// in the palette on purpose or hidden from it, and every setting that picks what runs listed for Restricted Mode. +// in the palette on purpose or hidden from it, and every setting that picks what runs listed for Restricted Mode. Then +// what it promises a user: the description, the empty views' welcome text, the menus and the settings' wording. import { test } from 'node:test' import assert from 'node:assert/strict' import * as fs from 'fs' import * as path from 'path' +import { HiddenCmd } from '../src/platform/commands' type Command = { command: string; title: string } const pkg = JSON.parse(fs.readFileSync(path.join(__dirname, '../../package.json'), 'utf8')) @@ -28,12 +30,9 @@ test('command titles are in Title Case', () => { const IN_PALETTE = [ 'codeNotes.add', 'codeNotes.askQuestion', - 'codeNotes.toggleAnimation', - 'codeNotes.playPodcast', 'codeNotes.checkUnderstanding', 'codeNotes.searchJourneys', - 'codeNotes.sortJourneys', - 'codeNotes.refreshJourney', + 'codeNotes.refresh', ] test('every command is either shown in the palette on purpose or has a commandPalette rule', () => { @@ -58,7 +57,7 @@ test('every setting that picks what runs, its model or its skills is ignored fro * no code writes `stepAsk`, nor `check` on a row, today. */ const CONTEXT_WORDS: Record<string, string[]> = { - commentThread: ['asking', 'check', 'open', 'resolved', 'stepAsk'], + commentThread: ['asking', 'check', 'concern', 'open', 'resolved', 'stepAsk', 'todo'], viewItem: ['asking', 'broken', 'check', 'hidden', 'journey', 'known', 'named', 'note', 'open', 'podcast', 'replied', 'resolved', 'session', 'shown', 'stale', 'unread'], } @@ -72,3 +71,142 @@ test('the menus look for known context words only', () => { } for (const key of Object.keys(CONTEXT_WORDS)) assert.deepEqual([...found[key]].sort(), CONTEXT_WORDS[key], key) }) + +type Menu = { command: string; when?: string; group?: string } +const c = pkg.contributes +const menus: Record<string, Menu[]> = c.menus +const settings: Record<string, { description?: string; markdownDescription?: string; enum?: string[]; enumItemLabels?: string[]; examples?: string[] }> = c.configuration.properties +const titleOf = (id: string) => commands.find((x) => x.command === id)?.title +const menu = (where: string, command: string) => menus[where].filter((m) => m.command === command) +const describe = (key: string) => settings[key].description ?? settings[key].markdownDescription ?? '' + +test('the description names notes, journeys and the merge-request check in one line', () => { + assert.doesNotMatch(pkg.description, /\n/) + for (const word of [/\bnotes\b/, /\bjourneys\b/, /\bcheck\b/, /\bmerge\b/]) assert.match(pkg.description, word) +}) + +test('an empty Journeys view: one line and a button that writes a journey', () => { + const welcome = c.viewsWelcome.filter((w: { view: string }) => w.view === 'codeNotes.journeys') + assert.equal(welcome.length, 1) + const lines: string[] = welcome[0].contents.split('\n') + assert.equal(lines.length, 2) + assert.doesNotMatch(lines[0], /\[/, 'the first line is text') + assert.equal(lines[1], '[Ask a Question About the Code…](command:codeNotes.askQuestion)') +}) + +test('with journeys, the Journeys view\'s … menu offers the tutorial', () => { + assert.deepEqual(menu('view/title', 'codeNotes.tutorial'), [ + { command: 'codeNotes.tutorial', when: 'view == codeNotes.journeys && codeNotes.hasJourneys', group: '1_help@1' }, + ]) +}) + +test('no walkthrough: the empty views carry the first-run text', () => { + assert.equal(c.walkthroughs, undefined) +}) + +test('no two contributed commands share a title; the unreachable one-line note and Reply & Resolve are gone', () => { + const titles = commands.map((x) => x.title) + assert.deepEqual(titles.filter((t, i) => titles.indexOf(t) !== i), []) + for (const id of ['codeNotes.addQuick', 'codeNotes.replyResolve']) { + assert.equal(titleOf(id), undefined, id) + for (const items of Object.values(menus)) assert.ok(!items.some((m) => m.command === id), id) + } + assert.equal(titleOf('codeNotes.createFromThread'), 'Save Note') +}) + +test('every command the code registers is contributed, or internal by name here', () => { + const internal = [ + 'codeNotes.askStepUpdate', 'codeNotes.claudeLinkBack', 'codeNotes.codeLink', 'codeNotes.codeLinkBack', + 'codeNotes.nextCheckQuestion', 'codeNotes.openNoteId', 'codeNotes.openStepLink', 'codeNotes.podcastFollow', + 'codeNotes.link', 'codeNotes.concernFixed', 'codeNotes.addQuick', 'codeNotes.replyResolve', 'codeNotes.closeNoteBox', + 'codeNotes.notes.focus', 'codeNotes.journeys.focus', 'codeNotes.check.focus', + ] + assert.deepEqual(Object.values(HiddenCmd).sort(), [...internal].sort()) + const contributed = new Set(commands.map((x) => x.command)) + for (const id of internal) assert.ok(!contributed.has(id), `${id} is internal`) +}) + +test('the inbox actions that need no row are in the palette; Reload Notes is in the Notes view\'s … menu too', () => { + const ids = ['markAllRead', 'resolveAll', 'deleteResolved', 'filter', 'refresh', 'copyAgentPrompt', 'nextUnread', + 'previousUnread', 'groupByFile', 'groupBySession', 'showResolved', 'hideResolved', 'showAllSessions'] + for (const id of ids.map((x) => `codeNotes.${x}`)) { + assert.ok(titleOf(id), id) + assert.ok(menu('commandPalette', id).every((m) => m.when !== 'false'), `${id} in the palette`) + } + assert.deepEqual(menu('view/title', 'codeNotes.refresh'), [{ command: 'codeNotes.refresh', when: 'view == codeNotes.notes', group: '3_reload@1' }]) + assert.equal(titleOf('codeNotes.refresh'), 'Reload Notes') +}) + +test('journey commands are in the palette only where there are journeys', () => { + for (const id of ['refreshJourney', 'playPodcast', 'sortJourneys', 'toggleAnimation']) { + assert.deepEqual(menu('commandPalette', `codeNotes.${id}`).map((m) => m.when), ['codeNotes.hasJourneys'], id) + } +}) + +test('titles say what they do', () => { + assert.equal(titleOf('codeNotes.showOnlySession'), 'Show Only This Session in Editor') + assert.equal(titleOf('codeNotes.askQuestion'), 'Find or Write a Journey…') + assert.equal(titleOf('codeNotes.askClaude'), 'Ask Claude') +}) + +test('the note bar: the setting says bar, and no unused background colour', () => { + assert.equal(describe('codeNotes.highlight'), 'Show a bar beside lines with an open note.') + assert.ok(!c.colors.some((x: { id: string }) => x.id === 'codeNotes.noteBackground')) +}) + +test('VS Code\'s comment height cap is left alone', () => { + assert.ok(!('comments.maxHeight' in c.configurationDefaults)) +}) + +test('model settings: one-line descriptions, the four models as suggestions; Claude: Mode reads as behaviour', () => { + for (const key of ['codeNotes.claude.model', 'codeNotes.journeys.model', 'codeNotes.understanding.model']) { + assert.deepEqual(settings[key].examples, ['sonnet', 'opus', 'haiku', 'fable'], key) + assert.equal(settings[key].enum, undefined, `${key} still takes any model id`) + assert.ok(describe(key).length <= 100, `${key}: ${describe(key)}`) + } + const mode = settings['codeNotes.claude.mode'] + assert.deepEqual(mode.enum, ['button', 'always', 'off'], 'stored values unchanged') + assert.deepEqual(mode.enumItemLabels, ['When I ask', 'Every note', 'Never']) + assert.ok(describe('codeNotes.claude.mode').length <= 100) +}) + +test('background questions: the description says where they run', () => { + assert.equal(describe('codeNotes.understanding.background'), 'Writes the questions with Claude when a branch is pushed, in repositories that use the check.') +}) + +test('Ask Claude is a labelled button beside Reply on open notes; Stop has its own title slot', () => { + const ask = menu('comments/commentThread/context', 'codeNotes.askClaude') + assert.equal(ask.length, 1) + assert.equal(ask[0].group, 'inline@2') + for (const part of ['commentController == codeNotes', "config.codeNotes.claude.mode != 'off'", 'codeNotes.claudeFound', 'commentThread =~ /open/', '!(commentThread =~ /check/)']) { + assert.ok(ask[0].when!.includes(part), part) + } + const title = menus['comments/commentThread/title'] + const stop = title.find((m) => m.command === 'codeNotes.cancelClaude')! + assert.equal(stop.group, 'navigation@1') + assert.ok(!title.some((m) => m.command !== stop.command && m.group === stop.group), 'nothing else in Stop\'s slot') +}) + +test('a check concern\'s actions are named buttons on its thread', () => { + const want = { concernFix: 'Suggest a Fix', concernTodo: 'Add TODO', concernFlag: 'Flag for Reviewer', concernDismiss: 'Dismiss Concern' } + for (const [name, title] of Object.entries(want)) { + const id = `codeNotes.${name}` + assert.equal(titleOf(id), title) + const m = menu('comments/commentThread/context', id) + assert.equal(m.length, 1, id) + assert.match(m[0].when!, /commentThread =~ \/concern\//) + assert.match(m[0].group!, /^inline@/) + assert.deepEqual(menu('commandPalette', id).map((x) => x.when), ['false'], `${id} needs a thread`) + } +}) + +test('the Check view is hidden on the default branch without a check', () => { + assert.equal(c.views.codeNotes.find((v: { id: string }) => v.id === 'codeNotes.check').when, '!codeNotes.checkOnBase') +}) + +test('the docs the README links ship in the package', () => { + for (const doc of ['docs/journey-format.md', 'docs/understanding-check.md', 'docs/agent-protocol.md']) { + assert.ok(pkg.files.includes(doc), doc) + assert.ok(fs.existsSync(path.join(__dirname, '../..', doc)), doc) + } +}) From 44862f9236dcefbd5295d1a537e9c8ef387177dd Mon Sep 17 00:00:00 2001 From: tomeyer97 <107920881+tomeyer97@users.noreply.github.com> Date: Thu, 26 Nov 2026 23:38:20 +0100 Subject: [PATCH 16/17] The README and docs match the code: no promises it doesn't keep, a GitLab recipe that runs, one skip rule Slice: S02 Zeroshot-Run: 01a219ef-d097-78b1-9ac4-0653db666971 --- CHANGELOG.md | 12 +++++++- CONTRIBUTING.md | 15 ++++++++++ README.md | 33 +++++++------------- docs/understanding-check.md | 27 +++++++++-------- test/docs.test.ts | 60 +++++++++++++++++++++++++++++++++++++ 5 files changed, 110 insertions(+), 37 deletions(-) create mode 100644 CONTRIBUTING.md diff --git a/CHANGELOG.md b/CHANGELOG.md index 7aa7496..58e91fd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,15 @@ # Changelog +## Unreleased + +### Fixed + +- **Docs match the extension.** The GitLab recipe for the understanding check uses the `test` stage, so it also runs + as a project's only job (GitLab creates no pipeline with only `.post` jobs). Skipping the check is described as it + works: the label plus an approval by someone else. The README lists the two VS Code defaults the extension changes + and how to undo them, no longer mentions a gutter `+` or a status bar bell, and ships the docs it links; + development moved to CONTRIBUTING.md. + ## 0.26.0 ### Added @@ -39,7 +49,7 @@ (after a second miss) the explanation, naming the code as clickable links. The **Check** view in the sidebar lists the questions; the status bar says where the check stands; **Commit & push** finishes it. Answers are saved in `understanding/<branch>.json` for a merge request check that needs no model (`cli/understanding.mjs ci`, GitLab and - GitHub recipes in the README). The bundled `understanding-check` skill writes the questions. + GitHub recipes in [docs/understanding-check.md](docs/understanding-check.md)). The bundled `understanding-check` skill writes the questions. - **Finding journeys:** journeys have their own **Journeys** view: In this file, Continue, Checks, then All by area, with search and sort. The panel's Journeys list gets a search field, chips, the same sections and a preview of the selected journey (its map, small, and its steps); a click selects, Enter or **Walk** starts it. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..ee31b4b --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,15 @@ +# Contributing + +```sh +npm ci +npm run build # the extension, the CLI bundle and the pages (scripts/build.mjs) +npm run lint # ESLint, and the layers of src/ and their import cycles (scripts/check-layers.mjs) +npm test # unit tests, golden tests included (test/README.md) +npm run test:goldens # only the golden tests; UPDATE_GOLDENS=1 rewrites them +npm run test:integration # the extension in a real VS Code (needs a display, or xvfb) +npm run package # code-notes-<version>.vsix +``` + +Open the folder in VS Code and press F5 ("Code Notes (dev)") for a window that reloads itself when the code changes. + +Releases: see [CHANGELOG.md](CHANGELOG.md). Pushing a tag `v<version>` publishes that version. diff --git a/README.md b/README.md index b764800..ca463b9 100644 --- a/README.md +++ b/README.md @@ -13,11 +13,9 @@ Three things for understanding code you did not write, in VS Code: ## Notes -- **Add one:** select code, press **Ctrl+'** then **C**, type, Ctrl+Enter. Or use the gutter `+`, or right-click → - **Add Note**. A note can also be on a whole file or folder (right-click it in the Explorer). +- **Add one:** select code, press **Ctrl+'** then **C**, type, Ctrl+Enter. Or right-click → **Add Note**. A note can also be on a whole file or folder (right-click it in the Explorer). - **Threads:** each note is a comment thread on its lines. Reply in the thread. -- **Answers from an agent** arrive as unread: a dot in the sidebar, a badge on the Code Notes icon, a bell in the - status bar. With the [Claude Code](https://claude.com/claude-code) CLI installed, **Ask Claude** on a note answers +- **Answers from an agent** arrive as unread: a dot in the sidebar and a badge on the Code Notes icon. With the [Claude Code](https://claude.com/claude-code) CLI installed, **Ask Claude** on a note answers it right there; any other agent can answer by editing the note files (see [Storage](#storage)). - **Resolve:** ✓ on the thread or the list row; tick several and resolve them together. Resolved notes are hidden. - **Suggestions:** an agent's ` ```suggestion ` block gets **Apply suggestion**, which replaces the note's lines. @@ -108,9 +106,14 @@ too. ## Settings -The extension turns on smooth editor scrolling by default, so the editor glides between a journey's steps. Set -`editor.smoothScrolling` to `false` to switch that off. All other settings are under **Code Notes** in the Settings -editor, named by what they are about: +The extension changes two VS Code defaults; a value in your own settings wins: + +| Default | Why | To undo | +|---|---|---| +| `comments.openView`: `never` | the Comments panel doesn't pop up for every note (this applies to other comment extensions too) | `"comments.openView": "firstFile"` | +| `editor.smoothScrolling`: `true` | the editor glides between a journey's steps | `"editor.smoothScrolling": false` | + +All other settings are under **Code Notes** in the Settings editor, named by what they are about: | Prefix | About | |---|---| @@ -124,22 +127,6 @@ editor, named by what they are about: The settings that choose what runs (the CLI, the models, the skills) are taken only from your user settings in a workspace you have not trusted. -## Development - -```sh -npm ci -npm run build # the extension, the CLI bundle and the pages (scripts/build.mjs) -npm run lint # ESLint, and the layers of src/ and their import cycles (scripts/check-layers.mjs) -npm test # unit tests, golden tests included (test/README.md) -npm run test:goldens # only the golden tests; UPDATE_GOLDENS=1 rewrites them -npm run test:integration # the extension in a real VS Code (needs a display, or xvfb) -npm run package # code-notes-<version>.vsix -``` - -Open the folder in VS Code and press F5 ("Code Notes (dev)") for a window that reloads itself when the code changes. - -Releases: see [CHANGELOG.md](CHANGELOG.md). Pushing a tag `v<version>` publishes that version. - ## License [MIT](LICENSE) diff --git a/docs/understanding-check.md b/docs/understanding-check.md index eb5ebc4..c64be93 100644 --- a/docs/understanding-check.md +++ b/docs/understanding-check.md @@ -16,7 +16,7 @@ branch's change and ask a few questions about it (1 for a small change, document it is built this way, how it fails. The first question opens as a thread on its lines; the list is the **Check** view in the Code Notes sidebar. Answer in 1-3 sentences and press Ctrl+Enter: Claude checks the answer against the code and replies in the thread, naming the code it means as links you can click. A miss gets a hint and a second try; a second -miss gets the explanation, which you may say back in one sentence (a right one counts as passed). Ctrl+' D goes to +miss gets the explanation, which you may say back in one sentence (a right one counts as passed). **Next question ›** goes to the next open question. You can also answer in the Check view: the selected question has a box there (Ctrl+Enter sends, Esc goes back to the code). @@ -43,8 +43,8 @@ make you look, not to police. never count go in `exempt` (none by default). - **The change grew** by more than 40 code lines since the questions: run the command again; it adds 1-2 questions about the new part only. Merging the target branch in doesn't count. -- **Skip it:** label the merge request `skip-understanding`. Any approval by someone other than the author waives the - check (re-run the job after the approval; on GitHub the review re-runs it). +- **Skip it:** add the label `skip-understanding` and get an approval from someone other than the author, then re-run + the job (on GitHub the review re-runs it). - **Settings** for a repository (a merge request is judged by its target branch's): `understanding/config.json`, e.g. `{ "exempt": ["docs/**", "*.md", "package-lock.json"], "passRatio": 0.6, "maxDrift": 40, "skipLabel": "skip-understanding", "mrComment": true }`. @@ -80,7 +80,8 @@ The command line, [cli/understanding.mjs](../cli/understanding.mjs) (Node 18+, n (e.g. a bad merge of the file) — not a security measure. 6. **The answers help the reviewer.** Once the check is done, CI posts the questions and answers on the merge request (never while it is in progress: no grading in public). -7. **Good faith over enforcement.** Least friction wins: an approval waives the check, every message is one short line. +7. **Good faith over enforcement.** Least friction wins: the skip label and an approval waive the check, + every message is one short line. ## Flow @@ -114,7 +115,7 @@ The command line, [cli/understanding.mjs](../cli/understanding.mjs) (Node 18+, n **Next question ›** appears. An unsent answer is kept per question in the workspace's state (never in the file). The list is the **Check** view in the Code Notes sidebar (the only list of them: the Code Notes tree doesn't repeat them, and steps aside while a check is open and there are no other notes): where the check stands, - one row per question, one button (Start, Add questions, Commit & push). Ctrl+' D / A walk the open questions; + one row per question, one button (Start, Add questions, Commit & push). Ctrl+' D / A walk the open questions (the tour's steps while it is walked); journey lenses step aside in the function of an open question (the rest of the file keeps them); another branch's check threads (and notes made from them) are hidden. Threads follow the file on disk: a changed question gets a new thread, a removed one loses it, and an answer is stored only for the question text it was shown with. @@ -128,7 +129,7 @@ The command line, [cli/understanding.mjs](../cli/understanding.mjs) (Node 18+, n the smallest change: one sentence and a suggestion block with Apply; Undo takes it back), **Add TODO** (the whole concern, wrapped at 100 characters, above the line it names at its indentation, or inside the block a "} catch {" line opens; the thread says where it went), **Flag for reviewer** (independent of the TODO). After a grade the editor stays on the question and the - reply box is empty; **Next question ›** under the grade (or Ctrl+' D) moves on. + reply box is empty; **Next question ›** under the grade moves on (Ctrl+' D follows the tour while one is walked). "Ask Claude" on a check question asks what you want to know and answers in a separate note; Claude is told never to write the check's answer. 5. When the rule is met the status bar says `✓ Understanding` and the view offers **Commit & push** right under @@ -442,8 +443,8 @@ ask a reviewer to approve, then re-run this job." The size is honest: "3 questio ## Skipping No size limit: every change with code lines needs the check (only exempt files or comment-only changes pass by -themselves). To skip one: add the label `skip-understanding`; any approval by someone other than the author waives the -check (GitLab approvals API; GitHub reviews API). The feature relies on good faith, so no reason is asked; the job and the +themselves). To skip one: add the label `skip-understanding` and get an approval from someone other than the author +(GitLab approvals API; GitHub reviews API); neither alone skips. The feature relies on good faith, so no reason is asked; the job and the comment record "waived (approved by @bob)". GitLab doesn't re-run the job on an approval: the message says to re-run it (GitHub's recipe re-runs on the review). @@ -459,8 +460,8 @@ label. ```yaml understanding: image: node:22 - stage: .post # the last stage, so a missing check never skips lint or tests - needs: [] # but it starts at once: a failing test never skips it either + stage: test # if you list stages:, use your last one (not .post: see below) + needs: [] # it starts at once: a failing test never skips it rules: - if: $CI_PIPELINE_SOURCE == "merge_request_event" variables: @@ -508,9 +509,9 @@ comment work as usual, but a failure doesn't block: on GitLab the job exits 3 an To review the script once and keep it, commit a copy (e.g. `tools/understanding.mjs`) and run that instead. -GitLab: a job on `merge_request_event` that runs on its own (`stage: .post`, `needs: []`) with plain `node` (no LLM CLI, no model key); `GITLAB_TOKEN` (project token, -`api` scope) for labels/approvals/comment; `allow_failure: { exit_codes: [3] }`. The last stage, because GitLab skips every later stage after a failed job: in `.pre`, -a missing check would skip lint and tests. `needs: []` starts it at once anyway, so a failing test never skips it either. +GitLab: a job on `merge_request_event` that runs on its own (`needs: []`) with plain `node` (no LLM CLI, no model key); `GITLAB_TOKEN` (project token, +`api` scope) for labels/approvals/comment; `allow_failure: { exit_codes: [3] }`. In the last stage, because GitLab skips every later stage after a failed job, +but not in `.pre`/`.post`: GitLab creates no pipeline whose only jobs are there, so as a project's only job it would never run. GitHub Actions: same CLI, `GITHUB_TOKEN`. **Advisory mode** (`"mode": "advisory"`, or `UNDERSTANDING_MODE=advisory`, which overrides the file): start advisory for diff --git a/test/docs.test.ts b/test/docs.test.ts index 0d75bca..3a392fd 100644 --- a/test/docs.test.ts +++ b/test/docs.test.ts @@ -29,3 +29,63 @@ test('the recipes pin each action to the commit this repository\'s CI uses', () assert.equal(ref, ours.get(action), `${action}: the commit this repository's CI uses`) } }) + +const readme = read('README.md') +const pkg = JSON.parse(read('package.json')) + +test('the README lists every VS Code default the extension changes, with how to undo it', () => { + for (const key of Object.keys(pkg.contributes.configurationDefaults)) { + const row = readme.split('\n').find((l) => l.startsWith(`| \`${key}\``)) + assert.ok(row, `${key}: a row in the README's Settings`) + assert.ok(row.split('|').at(-2)!.includes(`"${key}"`), `${key}: how to undo it`) + } +}) + +test('every docs/ file the README links ships in the package', () => { + const links = [...readme.matchAll(/\]\((docs\/[^)#\s]+)/g)].map((m) => m[1]).filter((l) => !l.startsWith('docs/images/')) + assert.ok(links.length >= 2, 'the README links docs') + for (const l of links) assert.ok(pkg.files.includes(l), l) +}) + +test('the README is for users: no Development section, no gutter +, no status bar bell', () => { + assert.doesNotMatch(readme, /^## Development/m) + assert.doesNotMatch(readme, /gutter `?\+/) + assert.doesNotMatch(readme, /\bbell\b/) +}) + +test('skipping is one rule: the label and an approval, never an approval alone', () => { + for (const text of [readme, doc]) { + assert.doesNotMatch(text, /any approval[^.]*waives/i) + assert.doesNotMatch(text, /approval waives the check/i) + } + const rule = /add the label `skip-understanding` and get an approval from someone other than the author/g + assert.equal([...doc.matchAll(rule)].length, 2, 'Using it and Skipping say the same') +}) + +/** The fenced yaml block that follows `heading` (a line starting with it). */ +function yamlAfter(heading: string): string { + const at = doc.split('\n').findIndex((l) => l.startsWith(heading)) + assert.ok(at >= 0, heading) + const m = /```yaml\n([\s\S]*?)```/.exec(doc.split('\n').slice(at).join('\n')) + assert.ok(m, `a yaml block after ${heading}`) + return m[1] +} + +test('the GitLab recipe is valid YAML in a regular stage, so it runs as a project\'s only job', () => { + const yaml = yamlAfter('GitLab (`.gitlab-ci.yml`)') + // A small structural check (no YAML parser among the dependencies): two-space indents, no tabs, every line a + // `key:` or a `- item` under a key. + const lines = yaml.split('\n').filter((l) => l.trim() && !l.trim().startsWith('#')) + for (const l of lines) { + assert.doesNotMatch(l, /\t/, l) + assert.equal((l.length - l.trimStart().length) % 2, 0, l) + assert.match(l.trim(), /^(- .+|[\w$.-]+:( .*)?)$/, l) + } + assert.match(lines[0], /^understanding:$/) + const stage = /^ {2}stage: (\S+)/m.exec(yaml)?.[1] + assert.ok(stage, 'the job names its stage') + // GitLab creates no pipeline whose only jobs are in .pre/.post. + assert.ok(!['.pre', '.post'].includes(stage), stage) + assert.match(yaml, /^ {2}needs: \[\]/m) + assert.match(yaml, /merge_request_event/) +}) From d20029acea0146d02c42efd11c1278475f49f799 Mon Sep 17 00:00:00 2001 From: tomeyer97 <107920881+tomeyer97@users.noreply.github.com> Date: Fri, 27 Nov 2026 04:42:22 +0100 Subject: [PATCH 17/17] The whole integration suite green after the fixes: tests follow the decided behaviour, regressions fixed in the code The integration suite had not run since the fix slices; it failed early on the Journeys view's new flat list. Tests now assert the intended new behaviour as precisely as before; two regressions are fixed in the code (step questions nested under Continue, a guarded layout check when opening a step). --- src/journeys/panel/layout.ts | 8 +++++--- src/podcast/testing.ts | 2 ++ src/sidebar/journeyRowText.ts | 6 +++--- src/tour/walk.ts | 7 +++++-- test/integration/check/branches.ts | 11 ++++++----- test/integration/main/journeyFiles.ts | 2 +- test/integration/main/journeyTour.ts | 24 ++++++++++++++--------- test/integration/main/notesReview.ts | 6 +++++- test/integration/main/podcast/playback.ts | 11 +++++++---- test/integration/main/roundTrips.ts | 10 +++++++++- test/journeyRowText.test.ts | 4 ++-- 11 files changed, 60 insertions(+), 31 deletions(-) diff --git a/src/journeys/panel/layout.ts b/src/journeys/panel/layout.ts index 7c5de81..a5ad17b 100644 --- a/src/journeys/panel/layout.ts +++ b/src/journeys/panel/layout.ts @@ -137,13 +137,15 @@ export class PanelLayout { /** * A step opened with the panel beside it: the code keeps its 80 columns. Squeezed under them (a panel opened by * Ctrl+' V or left open while the window narrowed), the panel shrinks to leave them, or closes: the step card alone. - * The map's room asked for while the panel is open stays, and so does the listening width. + * The map's room asked for while the panel is open stays, and so does the listening width. Nothing is changed once + * `current` says the step is no longer the one shown. */ - async keepCodeRoom(): Promise<void> { + async keepCodeRoom(current: () => boolean = () => true): Promise<void> { if (!this.d.isOpen()) { this.readerChose = false; return } if (this.d.episodeOn()) return const s = await this.sideBySide() - if (!s) return + // `current`: the step is still the one shown (the layout read is a round trip; another journey may be open now). + if (!s || !current()) return const look = this.editorLook() const move = codeRoomMove({ codePx: s.layout.groups[1 - s.panel].size ?? 0, diff --git a/src/podcast/testing.ts b/src/podcast/testing.ts index 15e6b31..b6c1184 100644 --- a/src/podcast/testing.ts +++ b/src/podcast/testing.ts @@ -42,6 +42,8 @@ function snapshot(p: Podcasts, ports: Pick<PodcastPorts, 'journeys' | 'mapPanel' hostIn: host.in, unlocked: host.unlocks, hostAlive: host.alive(), + /** The Listen view's page (hostAlive is the player that has the audio, which may be the panel). */ + listenAlive: host.listen.alive, hostVisible: host.listen.visible, panelHosts: host.panelHosts, rate: p.store.rate, diff --git a/src/sidebar/journeyRowText.ts b/src/sidebar/journeyRowText.ts index 50a9fc1..7d0baa0 100644 --- a/src/sidebar/journeyRowText.ts +++ b/src/sidebar/journeyRowText.ts @@ -7,9 +7,9 @@ import { ClaudeRun, runProgress } from '../core/agentRun' import { clock } from '../core/format/podcast/model' import type { PodcastStatus } from '../tour/api' -/** The groups under which a journey's row lists its step questions: All and its areas, and a row of no group (the - * Code Notes view's). A row is listed once there. */ -export const nestsQuestions = (group: string | undefined) => !group || group === 'all' || group.startsWith('area:') +/** The groups under which a journey's row lists its step questions: Continue, All and its areas, and a row of no group + * (the Code Notes view's). A journey is listed once there (a walked one only in Continue); "In this file" repeats it. */ +export const nestsQuestions = (group: string | undefined) => !group || group === 'all' || group === 'continue' || group.startsWith('area:') /** What a journey's row says, worked out once: its description, tooltip, screen-reader label, icon and menus are all * made from it. */ diff --git a/src/tour/walk.ts b/src/tour/walk.ts index a04a9fa..3030805 100644 --- a/src/tour/walk.ts +++ b/src/tour/walk.ts @@ -404,8 +404,11 @@ export class Walk { const editor = await this.openStepFile(lj, n, uri, opts, token) if (!editor) return await this.revealStep(lj, n, editor, uri) - // Beside an open panel the code keeps its 80 columns (the panel narrower, or the step card alone). - if (mapPanel().journey && this.tour.isAt(lj, n)) await panelLayout().keepCodeRoom() + // Beside an open panel the code keeps its 80 columns (the panel narrower, or the step card alone). The trade-off, + // on purpose: one waited layout read per step (a round trip to the window, counted apart in the round-trip test). + // Not waited for, it races the layout a journey sets as it opens and can close the panel it just opened. + const shown = () => this.tour.isAt(lj, n) && mapPanel().journey?.key === lj.key + if (shown()) await panelLayout().keepCodeRoom(shown) } /** The tour is on step n now (another journey's walk ended first), stored, its map and lists follow. False: superseded. */ diff --git a/test/integration/check/branches.ts b/test/integration/check/branches.ts index ec0fbe1..c0a898e 100644 --- a/test/integration/check/branches.ts +++ b/test/integration/check/branches.ts @@ -1,4 +1,4 @@ -// Drift and branches: uncommitted lines asking for a top-up, another branch hiding the check's threads, a branch switch +// Drift and branches: uncommitted lines asking for one more question, another branch hiding the check's threads, a branch switch // while questions are written, another git user. Each test puts the branch, the files and the git config back in // `finally`, so a failure here doesn't leave the next tests on another branch. import * as vscode from 'vscode' @@ -25,15 +25,16 @@ function backTo(branch: string): void { } export const branchesTests = [ - test('drift from uncommitted lines: amber "Needs top-up: +46 lines" in the status bar and the view (Commit… first)', async () => { + test('drift from uncommitted lines: "Understanding: +1 question" in the status bar (amber), the line count in the view (Commit… first)', async () => { const saved = fs.readFileSync(limitsPath, 'utf8') try { - // 45 new lines (uncommitted) → amber "Needs top-up" before any push. + // 45 new lines (uncommitted) → one more question asked for before any push; how much it grew is in the view. fs.appendFileSync(limitsPath, Array.from({ length: 45 }, (_, i) => `export const MORE_${i} = ${i}`).join('\n') + '\n') await vscode.commands.executeCommand('workbench.action.files.revert').then(undefined, () => undefined) void api.checkRefresh() - await until('needs top-up', () => /^\$\(warning\) Needs top-up: \+4\d lines$/.test(chk().item)) - await untilEqual('the warning in the status bar and the view', () => [chk().itemWarn, view().tone, view().action?.id], [true, 'warn', 'scm'], CHECK_WAIT_MS) + await until('one more question asked for', () => chk().item === '$(checklist) Understanding: +1 question') + await untilEqual('amber in the status bar; the view says how much it grew and offers Commit… first', () => [chk().itemWarn, view().tone, /^Your change grew by 4\d code lines$/.test(view().title ?? ''), view().line, view().action?.id], + [true, 'todo', true, 'Commit, then add 1 question about the new lines.', 'scm'], CHECK_WAIT_MS) await pageShot('check-4-drift') } finally { fs.writeFileSync(limitsPath, saved) diff --git a/test/integration/main/journeyFiles.ts b/test/integration/main/journeyFiles.ts index 695d318..d6a4b6a 100644 --- a/test/integration/main/journeyFiles.ts +++ b/test/integration/main/journeyFiles.ts @@ -146,7 +146,7 @@ export const journeyFilesTests = withAfter([ await vscode.commands.executeCommand('codeNotes.refreshJourney', vscode.Uri.file(diskPath).toString()) await until('refreshed: the file rewritten, the step fresh', () => JSON.parse(fs.readFileSync(diskPath, 'utf8')).steps[0].anchor?.v === 3 && !diskStep().stale, 20000) assert.equal(snap().notes.length, notesBeforeRefresh, 'Refresh writes no note in the reader\'s name') - assert.ok(!fs.readdirSync(path.join(ctx.notesDir, '.writing')).length, 'the staging folder is cleaned up') + assert.ok(!fs.existsSync(path.join(ctx.notesDir, '.writing')), 'the staging folder is cleaned up, no empty .writing left') fs.unlinkSync(diskPath) await until('disk gone', () => !snap().journeys.some((x: any) => x.id === 'disk')) }), diff --git a/test/integration/main/journeyTour.ts b/test/integration/main/journeyTour.ts index 5df8189..a0ae3a3 100644 --- a/test/integration/main/journeyTour.ts +++ b/test/integration/main/journeyTour.ts @@ -108,7 +108,7 @@ const withBinaryStep = () => journey('binary', [ const moving = (title: string, from = 0) => journey('moving', demoSteps.slice(from).map((x) => ({ ...x, id: `m-${x.id}` })), { title }) export const journeyTourTests = [ - test('v2 journeys load (v1 and broken files skipped); steps are not notes; the group lists titles, new ones marked', async () => { + test('v2 journeys load (v1 and broken files skipped); steps are not notes; the view lists titles, new ones marked', async () => { writeLines(wsPath('src', 'flow.ts'), ['export function a() {', ' return b()', '}', '', 'export function b() {', ' return 2', '}']) writeLines(wsPath('src', 'flow2.ts'), ['// two', 'export const c = 3']) writeLines(wsPath('lib', 'mail', 'address.go'), Array.from({ length: 60 }, (_, i) => `// line ${i + 1}`)) @@ -127,14 +127,13 @@ export const journeyTourTests = [ assert.equal(snap().notes.length, notesBefore, 'steps are not notes') assert.equal(snap().broken, brokenBefore, 'journey files are not read as notes') assert.equal(snap().badge, badgeBefore, 'steps never count as unread') - // 0.24: journeys have their own view (Journeys), grouped by area; the Notes view lists notes only. + // Journeys have their own view (Journeys); the Notes view lists notes only. Fewer than 8 journeys: one flat list, + // a row each (no area or "All" group above it), its length and "new" in the description. const rows = journeysTree() assert.ok(!notesTree().some((l) => /^journeys:|journey:/.test(l)), 'no journeys in the Notes view') - const demoRow = rows.findIndex((l) => /journey:Demo · new$/.test(l)) - assert.ok(demoRow > 0 && /^\s+jgroup:src · 1$/.test(rows[demoRow - 1]), `Demo under its area (not said again), "new":\n${rows.join('\n')}`) - assert.ok(rows.some((l) => /^jgroup:All · 1$/.test(l)), `an "All" group:\n${rows.join('\n')}`) - // Files that never were valid journeys: one dimmed row each, after the groups. - assert.deepEqual(rows.slice(-2), ['badJourney: · ⚠ half-written.json', 'badJourney: · ⚠ old-v1.json'], `never-valid files are dimmed rows:\n${rows.join('\n')}`) + assert.ok(!rows.some((l) => /jgroup:/.test(l)), `a few journeys are not grouped:\n${rows.join('\n')}`) + // Files that never were valid journeys: one dimmed row each, after the journeys. + assert.deepEqual(rows, ['journey:Demo · 3 steps · new', 'badJourney: · ⚠ half-written.json', 'badJourney: · ⚠ old-v1.json'], `Demo a top row, "3 steps · new"; never-valid files are dimmed rows after it:\n${rows.join('\n')}`) }), test('Open Journey: the map and step 1\'s code, the panel at most 40 %; a read-only step card above the lines, details folded', async () => { @@ -300,8 +299,15 @@ export const journeyTourTests = [ assert.equal(question.session, undefined, 'a normal private note') assert.equal(question.unread, 0) const rows = journeysTree() - const row = rows.findIndex((l) => /^ {6}note:Step 2 · Why does b return 2\?/.test(l)) - assert.ok(row > 0 && /^ {4}journey:Demo\b/.test(rows[row - 1]) && !/question/.test(rows[row - 1]), `listed right under its journey, with its step; no count on the row:\n${rows.join('\n')}`) + // The walked journey is listed once, in Continue: its questions under it there. + const row = rows.findIndex((l) => /^ {4}note:Step 2 · Why does b return 2\?/.test(l)) + assert.ok(row > 1, `the question listed:\n${rows.join('\n')}`) + // Right under its journey (the walked one, in Continue), with its step; no question count on the journey's row. + assert.deepEqual(rows.slice(row - 2, row + 1).map((l) => l.replace(/ \[[^\]]*\]$/, '')), [ + 'jgroup:Continue · 1', + ' journey:Demo · step 2/3', + ' note:Step 2 · Why does b return 2? · flow.ts:8', + ], `listed right under its journey, with its step; no count on the row:\n${rows.join('\n')}`) assert.ok(!rows.some((l) => /^note:Why does b return 2/.test(l)), 'not a loose row too') const askedThread = await until('the asked note\'s thread', () => ctx.api.thread(question.id)) assert.ok(!/openStepLink|About the step/.test(bodyOf(askedThread.comments[0])), 'on that very step: no back-link') diff --git a/test/integration/main/notesReview.ts b/test/integration/main/notesReview.ts index 25702e2..398d50c 100644 --- a/test/integration/main/notesReview.ts +++ b/test/integration/main/notesReview.ts @@ -267,6 +267,10 @@ export const notesReviewTests = [ await vscode.commands.executeCommand('type', { text: 'Typed into the box' }) await vscode.commands.executeCommand('editor.action.submitComment') await until('Add Note saved a note', () => snap().notes.length === notesBefore + 1 && snap().notes.some((x: any) => x.messages[0].body === 'Typed into the box'), 8000) - assert.equal(vscode.workspace.getConfiguration('comments').get('maxHeight'), false, 'More grows the card: no nested scroll') + // Of VS Code's comment defaults the extension changes only openView (no Comments panel on every note); + // comments.maxHeight stays VS Code's own, for every comment extension. + const comments = vscode.workspace.getConfiguration('comments') + assert.equal(comments.inspect('maxHeight')?.defaultValue, true, 'comments.maxHeight left at VS Code\'s default') + assert.equal(comments.get('openView'), 'never', 'no Comments panel popping up on every note') }), ] diff --git a/test/integration/main/podcast/playback.ts b/test/integration/main/podcast/playback.ts index ec947ef..fb45f4b 100644 --- a/test/integration/main/podcast/playback.ts +++ b/test/integration/main/podcast/playback.ts @@ -31,7 +31,7 @@ export const playbackTests = [ // Nothing listened to: no Listen view (nor its focus command), no transport in the palette, a plain row. assert.ok(!pod().listening && !pod().hostAlive, 'no Listen view before a journey is listened to') const idle = ctx.api.journeyRow('podauto')! - assert.match(idle.description ?? '', /^♪ 0:40( · |$)/, `the row: its length: ${idle.description}`) + assert.match(idle.description ?? '', /^1 step · ♪ 0:40( · |$)/, `the row: its steps, then its podcast's length: ${idle.description}`) assert.match(idle.contextValue!, /;podcast$/, 'its ▶ Listen') assert.doesNotMatch(String(idle.tooltip), /podcast|Listen/i, 'no podcast line in the tooltip') await shots('listen-idle', true) @@ -49,7 +49,7 @@ export const playbackTests = [ await audioMoves(pf, 'played in the panel') assert.equal(await pf.evaluate(() => { const e = (globalThis as any).document.querySelector('.pod-err'); return e.hidden ? '' : e.textContent }), '', 'no hint or error line') assert.ok(pod().unlocked.panel && !pod().unlocked.listen, `the panel unlocked, the Listen view not: ${JSON.stringify(pod().unlocked)}`) - await podUntil('the panel has the audio: the Listen view is not there (codeNotes.listening off)', () => pod().panelHosts && !pod().hostAlive && !pod().hostVisible, QUICK_MS) + await podUntil('the panel has the audio: the Listen view is not there (codeNotes.listening off)', () => pod().panelHosts && !pod().listenAlive && !pod().hostVisible, QUICK_MS) // 2. Closing the panel: the audio goes to the Listen view, which may not play yet: it waits there, paused, where // it was (the one start that still needs a click: the status item or ▶ opens the panel again). @@ -72,7 +72,7 @@ export const playbackTests = [ const pf2 = await frameOf('journey', { quiet: true }) await realClick(pf2, '.pod-b.play') await podUntil('the click on the panel\'s ▶: playing in the panel', () => pod().playing && pod().hostIn === 'panel', MOVE_MS) - await podUntil('the Listen view went: the panel\'s player is the one', () => !pod().hostAlive && !pod().hostVisible, QUICK_MS) + await podUntil('the Listen view went: the panel\'s player is the one', () => pod().panelHosts && !pod().listenAlive && !pod().hostVisible, QUICK_MS) await audioMoves(pf2, 'the panel\'s ▶') assert.ok(Math.abs(pod().t - tClose) < 4, `on from where it was: ${tClose} → ${pod().t}`) @@ -88,7 +88,8 @@ export const playbackTests = [ await pause() await closePanel() await podUntil('the audio back in the Listen view', () => pod().hostIn === 'listen' && pod().hostAlive && pod().hostVisible, MOVE_MS) - const lf = await frameOf('listen', { quiet: true }) + // Found by its player (not `quiet`): the side bar has other webviews (the Check view). + const lf = await frameOf('listen') await realClick(lf, '.pod-b.play') await podUntil('the Listen view\'s ▶ plays there; the Listen view unlocked', () => pod().playing && pod().hostIn === 'listen' && pod().unlocked.listen, MOVE_MS) assert.equal(await lf.evaluate(() => (globalThis as any).document.querySelector('.ls-title')?.textContent), 'Pod auto', 'the view names the journey') @@ -336,6 +337,8 @@ export const playbackTests = [ podTest('podcast › the speed is remembered', async () => { await listenTo('podbeat', writeBeatJourney) const f = await frameOf('journey') + // The speed button is at the panel's bottom right, under VS Code's own toasts ("extensions are disabled"). + await vscode.commands.executeCommand('notifications.clearAll') const speedTo = async (r: number) => { for (let i = 0; i < 5 && pod().rate !== r; i++) { await f.click('.pod-rate') diff --git a/test/integration/main/roundTrips.ts b/test/integration/main/roundTrips.ts index d718771..e18e704 100644 --- a/test/integration/main/roundTrips.ts +++ b/test/integration/main/roundTrips.ts @@ -23,6 +23,11 @@ const activeUri = () => vscode.window.activeTextEditor?.document.uri.toString() /** What each action may call at most besides storing its place (stored in the background, not waited for). */ const MOST: Record<string, number> = { next: 1, previous: 1, link: 1, back: 1, same: 0, chatBack: 1 } +/** Opening a step (Next, Previous, Back to the step) waits for one more round trip, on purpose: an editor layout read + * after the step is shown, so the code beside the journey panel keeps its 80 columns. Counted apart from MOST. */ +const LAYOUT_PROBE = 'command vscode.getEditorLayout' +const STEP_ACTIONS = new Set(['next', 'previous', 'back']) + /** The code link that goes into another file than the card's, and the one into the card's own file. */ const TO_OTHER_FILE = 1, TO_CARD_FILE = 0 @@ -164,8 +169,11 @@ export const roundTripsTests = [ await chatLinks(c, r) fs.rmSync(tripsPath) for (const [k, n] of Object.entries(MOST)) { - const waited = r[k].calls.filter((x) => !x.startsWith('store ')) + // The step's layout read is waited for too; it is held to its own limit below, not to MOST. + const waited = r[k].calls.filter((x) => !x.startsWith('store ') && !(STEP_ACTIONS.has(k) && x === LAYOUT_PROBE)) assert.ok(waited.length <= n, `${k}: ${waited.length} calls into the window (at most ${n}): ${waited.join(', ')}`) + const probes = r[k].calls.filter((x) => x === LAYOUT_PROBE).length + assert.ok(probes <= (STEP_ACTIONS.has(k) ? 1 : 0), `${k}: ${probes} waited layout reads (opening a step: at most one, after the step is shown; other actions: none)`) } } finally { c.dispose() } }), diff --git a/test/journeyRowText.test.ts b/test/journeyRowText.test.ts index 11c9d95..e6c3935 100644 --- a/test/journeyRowText.test.ts +++ b/test/journeyRowText.test.ts @@ -60,8 +60,8 @@ test('a podcast: its length on the row and in the label; one that cannot play sa assert.equal(podcastContext(undefined), '') }) -test('questions nest under All, its areas and a row of no group only', () => { - assert.deepEqual([undefined, 'all', 'area:api', 'here', 'continue'].map(nestsQuestions), [true, true, true, false, false]) +test('questions nest under Continue, All, its areas and a row of no group; not under In this file', () => { + assert.deepEqual([undefined, 'all', 'area:api', 'here', 'continue'].map(nestsQuestions), [true, true, true, false, true]) }) test('a journey being written: its question, then the clock and what Claude is doing', () => {