From 3744e22dde6c7e8921d7f259a2636c6f483977c1 Mon Sep 17 00:00:00 2001 From: tomeyer97 <107920881+tomeyer97@users.noreply.github.com> Date: Fri, 27 Nov 2026 12:14:23 +0100 Subject: [PATCH 01/12] Notes and journeys: no deleted note written back, no empty list while journeys reload A save that only records where a note's code is no longer re-creates a note file deleted on disk (an anchor adopted ~600 ms after an agent wrote the note raced its delete, so the note stayed listed). Reading the journeys again keeps the list until each file is read, so Open Journey during a settings reload finds the journey. --- src/journeys/repository.ts | 30 ++++++++++++++++++------- src/notes/followEdits.ts | 2 +- src/notes/index.ts | 2 +- src/notes/location.ts | 2 +- src/notes/moves.ts | 6 ++--- src/notes/store.ts | 32 +++++++++++++++++++-------- test/integration/main/notesReview.ts | 28 ++++++++++++++++++++++- test/integration/main/repoJourneys.ts | 28 +++++++++++++++++++++++ 8 files changed, 106 insertions(+), 24 deletions(-) diff --git a/src/journeys/repository.ts b/src/journeys/repository.ts index 5b93264..0625799 100644 --- a/src/journeys/repository.ts +++ b/src/journeys/repository.ts @@ -66,18 +66,28 @@ export class JourneyRepository implements vscode.Disposable { return true } - /** Reads every journey file again (all at once), and watches their folders. */ + /** + * Reads every journey file again (all at once), and watches their folders. Each file is read as if for the first + * time, but the list keeps what it had until then: a journey is never missing from it (or from Open Journey) while + * the files are read, only the files no longer found leave it before. + */ async load(): Promise { - this.files.clear() - this.broken.clear() this.watchAll() const found = (await Promise.all(this.journeyFiles())).flatMap(({ folder, uris }) => uris.map((uri) => ({ folder, uri }))) - const oldFormat = await Promise.all(found.map(({ folder, uri }) => this.read(folder, uri))) + this.forgetAllBut(new Set(found.map(({ uri }) => uri.toString()))) + const oldFormat = await Promise.all(found.map(({ folder, uri }) => this.read(folder, uri, { fresh: true }))) this.keepOrder(found.map(({ uri }) => uri.toString())) this.logOldFormat(oldFormat.filter((name): name is string => !!name)) this.ports.changed() } + /** Forgets the listed and the unreadable journey files whose URI is not in `keys` (not found any more). */ + private forgetAllBut(keys: ReadonlySet): void { + for (const map of [this.files, this.broken]) { + for (const k of [...map.keys()]) if (!keys.has(k)) map.delete(k) + } + } + /** The listed journeys in the order of `keys` (as found, not as their reads ended); any others after them. */ private keepOrder(keys: string[]): void { const first = keys.flatMap((k) => this.files.get(k) ?? []) @@ -184,8 +194,9 @@ export class JourneyRepository implements vscode.Disposable { return this.files.get(uri.toString()) } - /** Reads one journey file; returns its name when it is in the old format (logged by the caller, once). */ - private async read(folder: vscode.WorkspaceFolder, uri: vscode.Uri): Promise { + /** Reads one journey file; returns its name when it is in the old format (logged by the caller, once). `fresh`: as + * if it was never read (a load): what was listed for it is replaced, not carried over or kept as its last good. */ + private async read(folder: vscode.WorkspaceFolder, uri: vscode.Uri, o: { fresh?: boolean } = {}): Promise { // A journey's podcast (src/podcast/) is next to it, not a journey; a change to it still fires onDidChange. if (isPodcastFile(uri.path)) return undefined const key = uri.toString() @@ -197,12 +208,15 @@ export class JourneyRepository implements vscode.Disposable { } const name = jsonName(uri) const parsed = parseJourney(raw, name) - if (!parsed.ok) return this.unreadable(folder, uri, name, parsed.why) + if (!parsed.ok) { + if (o.fresh) this.files.delete(key) + return this.unreadable(folder, uri, name, parsed.why) + } const j = parsed.value this.broken.delete(key) this.deletedText.delete(key) if (this.hiddenByTwin(folder, uri, j.id)) return undefined - const prev = this.files.get(key) + const prev = o.fresh ? undefined : this.files.get(key) const lj: LoadedJourney = { key, folder, uri, j, at: writtenAt(j) } if (prev) carryPositions(prev, lj) this.textOf.set(lj, raw) diff --git a/src/notes/followEdits.ts b/src/notes/followEdits.ts index b430c1b..44d7bf7 100644 --- a/src/notes/followEdits.ts +++ b/src/notes/followEdits.ts @@ -16,7 +16,7 @@ import { locOf, range1Of } from './model/lines' import { notesChanged, notesModel } from './model' import type { Note } from './store' -/** Writes a note (the store's save). */ +/** Writes where a note's code is now (the store's saveFollowing: never over a deleted note file). */ type Save = (n: Note) => Promise export function followEdits(events: WorkspaceEvents, save: Save): vscode.Disposable { diff --git a/src/notes/index.ts b/src/notes/index.ts index 20c6e5c..a6e50e3 100644 --- a/src/notes/index.ts +++ b/src/notes/index.ts @@ -154,7 +154,7 @@ export async function activateNotes(context: vscode.ExtensionContext, ports: Not followFiles: () => vscode.Disposable.from( store.onDidDeleteOnDisk(offerRestore), followNotesOnDisk(), - followEdits(events, (n) => store.save(n)), + followEdits(events, (n) => store.saveFollowing(n)), followNoteFiles(events), events.onDidChangeFolders(() => fireAndForget(store.load(), 'notes: read again for the folders')), ), diff --git a/src/notes/location.ts b/src/notes/location.ts index c7be11c..0017ede 100644 --- a/src/notes/location.ts +++ b/src/notes/location.ts @@ -69,7 +69,7 @@ export function onlyLocalPlacementChanged(n: Note): boolean { export async function saveIfClean(n: Note): Promise { if (openDoc(docUri(n))?.isDirty) return if (onlyLocalPlacementChanged(n)) return - await store().save(n) + await store().saveFollowing(n) } /** The lines of a selection: one ending at column 0 or inside the indentation of a line does not include that line. */ diff --git a/src/notes/moves.ts b/src/notes/moves.ts index 8015f8e..6bfe0ed 100644 --- a/src/notes/moves.ts +++ b/src/notes/moves.ts @@ -54,7 +54,7 @@ export async function followMovedFiles(events: WorkspaceEvents): Promise { (lines) => { const r = findAnchor(lines, n.data.anchor, locOf(n.data.range)); return r.stale ? undefined : r.loc }, ) if (moved) await moveNoteTo(n, moved.uri, moved.found) - else if (reanchor(n, undefined)) await store().save(n) + else if (reanchor(n, undefined)) await store().saveFollowing(n) } notesChanged({ kind: 'placed', ids: changed }) }) @@ -69,7 +69,7 @@ async function moveNoteTo(n: Note, uri: vscode.Uri, loc: Loc): Promise { n.data.stale = false // A past-the-end state stays as it is: reanchorAll, which runs first, left none for a file that is gone. placement.found(n.data.id, true) - await store().save(n) + await store().saveFollowing(n) } /** Files or folders renamed in the editor: notes on them, or inside them, follow. */ @@ -87,6 +87,6 @@ export async function followRename(oldUri: vscode.Uri, newUri: vscode.Uri): Prom if (!folder) continue n.data.file = relPath(folder, vscode.Uri.joinPath(newUri, old.slice(oldUri.path.length))) placement.found(n.data.id, true) - await store().save(n) + await store().saveFollowing(n) } } diff --git a/src/notes/store.ts b/src/notes/store.ts index 448af99..efdd80e 100644 --- a/src/notes/store.ts +++ b/src/notes/store.ts @@ -229,17 +229,30 @@ export class Store implements vscode.Disposable { /** * Writes a note. If its file changed since we read it (an agent appended a reply a moment ago), the change is - * merged in rather than overwritten. False when it could not be written (the failure is said). + * merged in rather than overwritten; if it was deleted, ours is written again (a reply or a resolve on it). False + * when it could not be written (the failure is said). */ - async save(n: Note): Promise { + save(n: Note): Promise { return this.write(n, { ifOnDisk: false }) } + + /** + * Writes where a note's code is now (its lines, stale, its anchor), as `save`, but never over a file deleted since we + * read it: that is no reason to bring a note back, and the watcher's delete, on its way, takes it out of the list. + * False when not written. + */ + saveFollowing(n: Note): Promise { return this.write(n, { ifOnDisk: true }) } + + private async write(n: Note, o: { ifOnDisk: boolean }): Promise { if (serialize(n.data) === n.raw) return true const before = n.base let merged = false if (n.raw !== undefined) { - // Undefined: deleted, write ours. const theirs = await this.changedOnDisk(n) if (theirs === false) return false - if (theirs) { + if (theirs === 'gone' && o.ifOnDisk) { + this.log.appendLine(`${n.uri.fsPath}: deleted on disk; its new place is not written back`) + return false + } + if (theirs && theirs !== 'gone') { n.data = merge(n.base ?? theirs, n.data, theirs) this.log.appendLine(`${n.uri.fsPath}: merged a change made on disk`) merged = true @@ -264,15 +277,16 @@ export class Store implements vscode.Disposable { } /** - * 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. + * The note as its file has it now, when that changed since we read it (undefined: unchanged; 'gone': deleted). 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 { + private async changedOnDisk(n: Note): Promise { const until = Date.now() + this.writingWaitMs for (;;) { const disk = await readText(n.uri) - if (disk === undefined || disk === n.raw) return undefined + if (disk === undefined) return 'gone' + if (disk === n.raw) return undefined const read = parseNote(disk, n.data.id) if (read.ok) return read.value if (Date.now() >= until) { diff --git a/test/integration/main/notesReview.ts b/test/integration/main/notesReview.ts index 398d50c..297ee7d 100644 --- a/test/integration/main/notesReview.ts +++ b/test/integration/main/notesReview.ts @@ -6,7 +6,7 @@ import * as vscode from 'vscode' 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 { agentNote, writeLines, writeNote } from '../fixtures' import { at, bodyOf, commandLinksIn, tour, closeAllEditors, ctx, journeysTree, noteById, notePath, notesTree, snap, until, wsPath } from './context' import { UNREAD_FINDING } from './shared' @@ -149,6 +149,32 @@ export const notesReviewTests = [ await until('lone note gone', () => !notesRows().some((r) => r.label === 'Lone note')) }), + test('a note file deleted on disk is not written back when its code is saved before the delete is seen', async () => { + const code = wsPath('src', 'gone.ts') + writeLines(code, ['export const a = 1', 'export const b = 2', 'export const c = 3']) + const id = noteId('200710', 'gon1') + const anchor = { text: 'export const b = 2', before: 'export const a = 1', after: 'export const c = 3' } + const file = writeNote(ctx.notesDir, id, agentNote('src/gone.ts', 2, 'Deleted note', { anchor })) + try { + await until('listed', () => noteById(id)) + // Edited as a document, not through an editor: one opened over the journey panel is replaced as it moves. + const doc = await vscode.workspace.openTextDocument(vscode.Uri.file(code)) + const edit = new vscode.WorkspaceEdit() + edit.insert(doc.uri, new vscode.Position(0, 0), '// moved down\n') + await vscode.workspace.applyEdit(edit) + await until('the note follows its code in memory', () => noteById(id)?.range.start === 3) + // The save's re-anchor runs at once; the file watcher reports the delete later. + fs.unlinkSync(file) + await doc.save() + await until('the deleted note gone', () => !noteById(id)) + assert.ok(!fs.existsSync(file), 'its file not written back') + } finally { + await closeAllEditors() + fs.rmSync(code, { force: true }) + fs.rmSync(file, { force: true }) + } + }), + test('an agent\'s resolve on disk is recorded and unread; resolve/reopen lines in the thread', async () => { // The thread shows it as a grey line. const thread = await until('thread', () => ctx.api.thread(HIGH)) diff --git a/test/integration/main/repoJourneys.ts b/test/integration/main/repoJourneys.ts index 571ad94..c2e2d91 100644 --- a/test/integration/main/repoJourneys.ts +++ b/test/integration/main/repoJourneys.ts @@ -48,4 +48,32 @@ export const repoJourneysTests = [ await reload() await until('back, fresh', () => saving() && saving().at.every((a: any) => !a.stale)) }), + + test('reading the journeys again (a setting changed, Refresh): every journey stays listed while the files are read', async () => { + await until('listed', () => saving()) + const reading = reload() + // Open Journey asked meanwhile finds it: the list is never empty half-way through a reload. + assert.ok(saving(), `listed while the files are read again: ${snap().journeys.map((x: any) => x.id).join(', ')}`) + await reading + assert.ok(saving(), 'listed once read') + }), + + test('a reload while a personal copy is listed and the repo now has the same id: only the repo\'s stays listed', async () => { + const copy = path.join(journeysDir(), 'twin-copy.json') + fs.writeFileSync(copy, JSON.stringify({ ...savingJourney, id: 'twin', title: 'Twin copy' })) + await until('the copy listed', () => journeyById('twin')) + // Read again before the watcher reports the repo's file: the copy is still listed when the reload starts. + const inRepo = { ...savingJourney, id: 'twin', title: 'Twin in the repo' } + const repo = writeJourney(repoJourneysDir(), inRepo) + await reload() + try { + assert.equal(snap().journeys.filter((x: any) => x.id === 'twin').length, 1, 'one twin journey') + const rows = journeysTree() + assert.ok(rows.some((l) => /journey:.*Twin in the repo/.test(l)) && !rows.some((l) => /Twin copy/.test(l)), `the repo's wins: ${rows.join(' / ')}`) + } finally { + fs.rmSync(copy, { force: true }) + fs.rmSync(repo, { force: true }) + } + await until('the twin gone', () => !journeyById('twin')) + }), ] From e9b2f5e60fbf4473cac43911e9f5ae0f380b1806 Mon Sep 17 00:00:00 2001 From: tomeyer97 <107920881+tomeyer97@users.noreply.github.com> Date: Fri, 27 Nov 2026 18:47:06 +0100 Subject: [PATCH 02/12] Journeys and podcast tests: a reload keeps a journey written meanwhile; commands reach the player that has the audio A reload forgot every journey missing from its folder listing, also one the watcher had read while the folders were being listed, so a journey written just then was never listed. It now forgets only the journeys it knew before the listing. The podcast tests sent their commands to the Listen view even when the journey panel had the audio (the Listen view goes when nothing is listened to for 3 s, and a new one is locked until clicked), so on a slow machine a seek went nowhere. They now go where the extension sends its own, and the test that makes the listened podcast unavailable puts the unlocked Listen view back. --- src/journeys/repository.ts | 16 +++++++++----- src/podcast/testing.ts | 6 ++--- src/testApi.ts | 6 ++--- test/integration/main/podcast/brokenFiles.ts | 3 ++- test/integration/main/podcast/player.ts | 23 +++++++++++++++++--- test/integration/main/repoJourneys.ts | 22 +++++++++++++++++++ 6 files changed, 60 insertions(+), 16 deletions(-) diff --git a/src/journeys/repository.ts b/src/journeys/repository.ts index 0625799..49f6c5c 100644 --- a/src/journeys/repository.ts +++ b/src/journeys/repository.ts @@ -69,22 +69,26 @@ export class JourneyRepository implements vscode.Disposable { /** * Reads every journey file again (all at once), and watches their folders. Each file is read as if for the first * time, but the list keeps what it had until then: a journey is never missing from it (or from Open Journey) while - * the files are read, only the files no longer found leave it before. + * the files are read, only the files no longer found leave it before. A file the watcher read while the folders were + * listed stays: the listing may predate it. */ async load(): Promise { this.watchAll() + const before = new Set([...this.files.keys(), ...this.broken.keys()]) const found = (await Promise.all(this.journeyFiles())).flatMap(({ folder, uris }) => uris.map((uri) => ({ folder, uri }))) - this.forgetAllBut(new Set(found.map(({ uri }) => uri.toString()))) + this.forget(before, new Set(found.map(({ uri }) => uri.toString()))) const oldFormat = await Promise.all(found.map(({ folder, uri }) => this.read(folder, uri, { fresh: true }))) this.keepOrder(found.map(({ uri }) => uri.toString())) this.logOldFormat(oldFormat.filter((name): name is string => !!name)) this.ports.changed() } - /** Forgets the listed and the unreadable journey files whose URI is not in `keys` (not found any more). */ - private forgetAllBut(keys: ReadonlySet): void { - for (const map of [this.files, this.broken]) { - for (const k of [...map.keys()]) if (!keys.has(k)) map.delete(k) + /** Forgets the journey files (listed or unreadable) of `known` that are not in `found` (not found any more). */ + private forget(known: ReadonlySet, found: ReadonlySet): void { + for (const k of known) { + if (found.has(k)) continue + this.files.delete(k) + this.broken.delete(k) } } diff --git a/src/podcast/testing.ts b/src/podcast/testing.ts index b6c1184..1a842d0 100644 --- a/src/podcast/testing.ts +++ b/src/podcast/testing.ts @@ -1,7 +1,7 @@ // The podcast as the integration tests read it (src/testApi.ts, loaded only outside Production): what the player // shows and where the audio is, read through its parts, and the counts of what it did, kept here from its events. import { brokenLinks } from '../core/format/podcast/validate' -import type { ToListen } from '../protocol/listen' +import type { ToPlayer } from '../protocol/podcast' import type { PodcastFeature } from './index' import type { Podcasts } from './player' import type { PodcastPorts } from './ports' @@ -16,8 +16,8 @@ export function podcastProbe(feature: PodcastFeature, ports: Pick snapshot(feature.player(), ports, seen), - /** A message for the Listen view (where the audio plays), as the extension sends it. */ - listenSend: (m: ToListen) => feature.player().host.listen.send(m), + /** A command for the player that has the audio (the Listen view, or the panel), as the extension sends it. */ + hostSend: (m: ToPlayer) => feature.player().host.send(m), /** The Listen view ignores the extension's pauses (a camera wait that can't pause the audio). */ listenIgnorePauses: (on: boolean) => { feature.player().host.listen.ignorePauses = on }, } diff --git a/src/testApi.ts b/src/testApi.ts index d7e3be0..de995ae 100644 --- a/src/testApi.ts +++ b/src/testApi.ts @@ -33,7 +33,7 @@ import { writeJourney } from './write/writeJourney' import { writingRows } from './write/journeyJobs' import type { FromMap as MapMessage, ToMap } from './protocol/map' import type { ToCheck } from './protocol/check' -import type { ToListen } from './protocol/listen' +import type { ToPlayer } from './protocol/podcast' import { stepDraftKey } from './platform/keys' /** What `activate` returns outside Production (src/extension.ts): the integration tests import this type, not `any`. */ @@ -125,8 +125,8 @@ export function testApi(f: TestedFeatures) { mementos: () => f.host.stored.mementos(), /** Sends a message into the map webview (tests drive its real click/key handlers this way). */ mapSend: (m: ToMap) => mapPanel.send(m), - /** A message for the Listen view (where the audio plays): a podcastCmd as the extension sends it. */ - listenSend: (m: ToListen) => podcast.listenSend(m), + /** A podcastCmd for the player that has the audio (the Listen view, or the panel), as the extension sends it. */ + hostSend: (m: ToPlayer) => podcast.hostSend(m), /** The Listen view ignores the extension's pauses (a camera wait that can't pause the audio). */ listenIgnorePauses: (on: boolean) => podcast.listenIgnorePauses(on), /** A message as if the journey panel posted it (a beat the reader picked in the animation, …). */ diff --git a/test/integration/main/podcast/brokenFiles.ts b/test/integration/main/podcast/brokenFiles.ts index 799dc43..cca3be9 100644 --- a/test/integration/main/podcast/brokenFiles.ts +++ b/test/integration/main/podcast/brokenFiles.ts @@ -9,7 +9,7 @@ import { windowShot } from '../../helpers' import { ui } from '../../devtools' import { ctx, journeysDir } from '../context' import { podcastFile, writePodJourney } from './fixtures' -import { diagnostics, lineOf, noChangeFor, pause, podTest, shots, startPlaying, toggle } from './player' +import { diagnostics, lineOf, listenViewUnlocked, noChangeFor, pause, podTest, shots, startPlaying, toggle } from './player' import { LOAD_MS, MOVE_MS, pod, podUntil, QUICK_MS } from './state' import { frameOf, panelText, panelVisible } from './webview' @@ -91,6 +91,7 @@ export const brokenFileTests = [ assert.equal(problems()[0]?.range.start.character, fs.readFileSync(podFile(), 'utf8').indexOf('"audio"'), 'the error on "audio"') fs.renameSync(`${mp3}.away`, mp3) await podUntil('back: the podcast plays again', () => pod().journeys.includes('pod') && !pod().broken.pod, MOVE_MS) + await listenViewUnlocked('pod') }, { consoleClean: true }), // What is wrong with a podcast that plays is said in the player, the row and the Problems view: another diff --git a/test/integration/main/podcast/player.ts b/test/integration/main/podcast/player.ts index 26f15df..8f95951 100644 --- a/test/integration/main/podcast/player.ts +++ b/test/integration/main/podcast/player.ts @@ -9,11 +9,12 @@ import { ui } from '../../devtools' import { ctx, tour } from '../context' import { podcastFile } from './fixtures' import { codeFile, litLine, LOAD_MS, MOVE_MS, pod, podUntil, QUICK_MS } from './state' -import { frameOf, watchConsole } from './webview' +import { frameOf, realClick, watchConsole } from './webview' /* eslint-disable @typescript-eslint/no-explicit-any */ -/** A command to the player, as the Listen view's buttons send it. */ -export const send = (m: { action: string; [k: string]: unknown }) => ctx.api.listenSend({ type: 'podcastCmd', ...m }) +/** A command to the player that has the audio (the Listen view, or the panel when only it may play), as the + * extension passes on a button's. */ +export const send = (m: { action: string; [k: string]: unknown }) => ctx.api.hostSend({ type: 'podcastCmd', ...m }) export const seek = (to: number) => send({ action: 'seek', to }) /** Ctrl+' Space: play or pause. */ export const toggle = () => vscode.commands.executeCommand('codeNotes.podcastToggle') @@ -87,6 +88,22 @@ export async function listenTo(id: string, write: () => void, { panel = true } = if (pod().playing) await pause() } +/** + * The Listen view there and unlocked, as the first playback test leaves it, with journey `id` paused in it. The + * view goes 3 s after nothing is listened to (src/podcast/statusItem.ts LISTENING_OFF_MS), and a new one is locked + * until a click in it: a test whose podcast is unavailable for longer (a slow machine) puts it back with this. + */ +export async function listenViewUnlocked(id: string): Promise { + if (pod().unlocked.listen && pod().listenAlive) return + await startPlaying(id) + if (pod().playing) await pause() + if (pod().mapVisible) await closePanel() + await podUntil('the audio in the Listen view', () => pod().hostIn === 'listen' && pod().hostAlive && pod().hostVisible, MOVE_MS) + await realClick(await frameOf('listen'), '.pod-b.play') + await podUntil('the Listen view\'s ▶ plays there; the view unlocked', () => pod().playing && pod().hostIn === 'listen' && pod().unlocked.listen, MOVE_MS) + await pause() +} + /** Every editor closed but the journey panel. */ export async function closeAllButPanel(): Promise { const tabs = vscode.window.tabGroups.all.flatMap((g) => g.tabs).filter((t) => !(t.input instanceof vscode.TabInputWebview && /codeNotes\.journey/.test(t.input.viewType))) diff --git a/test/integration/main/repoJourneys.ts b/test/integration/main/repoJourneys.ts index c2e2d91..69dcd2d 100644 --- a/test/integration/main/repoJourneys.ts +++ b/test/integration/main/repoJourneys.ts @@ -58,6 +58,27 @@ export const repoJourneysTests = [ assert.ok(saving(), 'listed once read') }), + // A file the watcher reads while the folders are listed may be missing from that listing: the reload must not + // drop it (an Open Journey right after writing a journey found nothing). + test('a journey written while the journeys are read again stays listed', async () => { + const files: string[] = [] + try { + for (let i = 0; i < 12; i++) { + const reading = reload() + files.push(writeJourney(journeysDir(), { ...savingJourney, id: `during-${i}` })) + await reading + await until(`during-${i} listed`, () => journeyById(`during-${i}`)) + } + await reload() + assert.equal(snap().journeys.filter((x: any) => /^during-/.test(x.id)).length, 12, 'all listed') + } finally { + for (const f of files) fs.rmSync(f, { force: true }) + } + // Read again: a delete right after a create may come with no event at all (the watcher merges the two). + await reload() + await until('the written journeys gone', () => !snap().journeys.some((x: any) => /^during-/.test(x.id))) + }), + test('a reload while a personal copy is listed and the repo now has the same id: only the repo\'s stays listed', async () => { const copy = path.join(journeysDir(), 'twin-copy.json') fs.writeFileSync(copy, JSON.stringify({ ...savingJourney, id: 'twin', title: 'Twin copy' })) @@ -74,6 +95,7 @@ export const repoJourneysTests = [ fs.rmSync(copy, { force: true }) fs.rmSync(repo, { force: true }) } + await reload() await until('the twin gone', () => !journeyById('twin')) }), ] From 0ebd1cebe4ec69be9526fde4bf6e84bc1fc8f789 Mon Sep 17 00:00:00 2001 From: tomeyer97 <107920881+tomeyer97@users.noreply.github.com> Date: Fri, 27 Nov 2026 19:44:47 +0100 Subject: [PATCH 03/12] Podcast marks test: the reader scrolls once the playing card has shrunk Playing, the step card above the lines shrinks to its header line; on a slow machine that landed after the test's scroll and shifted the lines it measured. --- test/integration/main/podcast/marks.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/test/integration/main/podcast/marks.ts b/test/integration/main/podcast/marks.ts index 3173d1c..52ea318 100644 --- a/test/integration/main/podcast/marks.ts +++ b/test/integration/main/podcast/marks.ts @@ -74,6 +74,8 @@ export const marksTests = [ await pause() await seekTo(12, `back on the beat, line ${END_LINE} not lit`, () => onScreen(3) && !pod().applying && !litOn(END_LINE)) await play() + // Playing, the step card above the lines shrinks to its header line: the lines shift once it does. + await podUntil('the header-only card', () => tour().card?.body === '', QUICK_MS) await outlast(AFTER_OWN_MOVE_MS, 'the walk\'s own move, so the scroll is the reader\'s') codeEditor()!.revealRange(new vscode.Range(40, 0, 40, 0), vscode.TextEditorRevealType.AtTop) await podUntil('not following', () => pod().follow === false, QUICK_MS) From 7535e58da457fa2ae7684919d2757f7f1df0e486 Mon Sep 17 00:00:00 2001 From: tomeyer97 <107920881+tomeyer97@users.noreply.github.com> Date: Fri, 27 Nov 2026 21:36:49 +0100 Subject: [PATCH 04/12] Podcast tests: the Listen view put back also when nothing is listened to A test that ended with no journey listened to left the Listen view to go 3 s later, during the next test; the helper now requires a journey listened to in an unlocked Listen view. --- test/integration/main/podcast/player.ts | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/test/integration/main/podcast/player.ts b/test/integration/main/podcast/player.ts index 8f95951..45ae869 100644 --- a/test/integration/main/podcast/player.ts +++ b/test/integration/main/podcast/player.ts @@ -91,12 +91,15 @@ export async function listenTo(id: string, write: () => void, { panel = true } = /** * The Listen view there and unlocked, as the first playback test leaves it, with journey `id` paused in it. The * view goes 3 s after nothing is listened to (src/podcast/statusItem.ts LISTENING_OFF_MS), and a new one is locked - * until a click in it: a test whose podcast is unavailable for longer (a slow machine) puts it back with this. + * until a click in it: a test that leaves nothing listened to, or its podcast unavailable for longer, puts it back + * with this (a journey listened to keeps it). */ export async function listenViewUnlocked(id: string): Promise { - if (pod().unlocked.listen && pod().listenAlive) return + const ready = () => pod().listening && pod().hostIn === 'listen' && pod().unlocked.listen && pod().listenAlive + if (ready()) return await startPlaying(id) if (pod().playing) await pause() + if (ready()) return if (pod().mapVisible) await closePanel() await podUntil('the audio in the Listen view', () => pod().hostIn === 'listen' && pod().hostAlive && pod().hostVisible, MOVE_MS) await realClick(await frameOf('listen'), '.pod-b.play') From 50247f5a99a90eb0bba064f59abd906117eebbe1 Mon Sep 17 00:00:00 2001 From: tomeyer97 <107920881+tomeyer97@users.noreply.github.com> Date: Fri, 27 Nov 2026 22:38:29 +0100 Subject: [PATCH 05/12] A closed note box's draft comes back however long the box takes to open; podcast tests read the reader's scroll once it lands Add Note gave up putting a draft back when its box took over a second to get the keyboard (a busy machine): the draft was lost. It now waits for the box's input to become the active editor, and drops the draft's way back when the keyboard goes elsewhere first. Two podcast tests read the editor's first visible line right after their own reveal, while VS Code was still settling it; they now read where the reader's scroll lands. --- src/notes/create.ts | 40 +++++++++++++++------- test/integration/main/podcast/listening.ts | 2 ++ test/integration/main/podcast/marks.ts | 9 +++-- 3 files changed, 35 insertions(+), 16 deletions(-) diff --git a/src/notes/create.ts b/src/notes/create.ts index 8d36a83..94e5766 100644 --- a/src/notes/create.ts +++ b/src/notes/create.ts @@ -5,6 +5,7 @@ import { store } from './ports' import { Loc } from '../core/anchors/anchor' import { chordKey } from '../platform/chordKey' import { log, now } from '../platform/host' +import { fireAndForget } from '../platform/run' import { askClaude } from '../ask/run' import { askAlways, askOnQuestion } from '../ask/settings' import { me } from './identity' @@ -22,7 +23,6 @@ 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…' } @@ -280,20 +280,34 @@ const drafts = new Map() 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 -} +/** A box's input is a text editor of its own (scheme 'comment') once it has the keyboard. */ +const isBoxInput = (e: vscode.TextEditor | undefined) => e?.document.uri.scheme === COMMENT_INPUT +const boxInput = () => (isBoxInput(vscode.window.activeTextEditor) ? vscode.window.activeTextEditor : undefined) +/** A draft on its way into the box just opened, until that box has the keyboard. */ +let draftWaiting: vscode.Disposable | undefined -/** The draft of a box closed on these lines, back in the box just opened there. */ +/** + * The draft of a box closed on these lines, back in the box just opened there: now, or once the box has the keyboard + * (VS Code lays it out first: seconds on a busy machine). Dropped when the keyboard goes elsewhere first. + */ async function restoreDraft(key: string): Promise { - 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) + draftWaiting?.dispose() + draftWaiting = undefined + if (!drafts.has(key)) return + const put = async (input: vscode.TextEditor) => { + const text = drafts.get(key) + if (text === undefined || openBox !== key || input.document.getText()) return + if (await input.edit((b) => b.insert(new vscode.Position(0, 0), text))) drafts.delete(key) + } + const now = boxInput() + if (now) return put(now) + const waiting = vscode.window.onDidChangeActiveTextEditor((e) => { + if (!e) return + waiting.dispose() + if (draftWaiting === waiting) draftWaiting = undefined + if (isBoxInput(e)) fireAndForget(put(e), 'notes: a draft back in its box') + }) + draftWaiting = waiting } /** Esc in a new note box: closed, its draft kept in memory (Add Note on those lines puts it back). The box is emptied diff --git a/test/integration/main/podcast/listening.ts b/test/integration/main/podcast/listening.ts index 6e95767..406a2f2 100644 --- a/test/integration/main/podcast/listening.ts +++ b/test/integration/main/podcast/listening.ts @@ -44,6 +44,8 @@ export const listeningTests = [ codeEditor()!.revealRange(new vscode.Range(185, 0, 185, 0), vscode.TextEditorRevealType.AtTop) await podUntil('not following: the card says Follow along', () => pod().follow === false && /Follow along/.test(tour().card?.body ?? ''), QUICK_MS) const top = () => codeEditor()!.visibleRanges[0].start.line + // VS Code settles a reveal over a few events: the reader's place is where it lands (line 185 near the top). + await podUntil('the reader\'s scroll landed', () => top() <= 185 && 185 - top() <= 8, QUICK_MS) const away = top() assert.ok(away >= 170, `scrolled: ${away}`) // Beat 2 (line 150, same file) at 12 s: lit, but the editor isn't moved. diff --git a/test/integration/main/podcast/marks.ts b/test/integration/main/podcast/marks.ts index 52ea318..c85c922 100644 --- a/test/integration/main/podcast/marks.ts +++ b/test/integration/main/podcast/marks.ts @@ -77,13 +77,16 @@ export const marksTests = [ // Playing, the step card above the lines shrinks to its header line: the lines shift once it does. await podUntil('the header-only card', () => tour().card?.body === '', QUICK_MS) await outlast(AFTER_OWN_MOVE_MS, 'the walk\'s own move, so the scroll is the reader\'s') - codeEditor()!.revealRange(new vscode.Range(40, 0, 40, 0), vscode.TextEditorRevealType.AtTop) + const READER_LINE = 40 + codeEditor()!.revealRange(new vscode.Range(READER_LINE, 0, READER_LINE, 0), vscode.TextEditorRevealType.AtTop) await podUntil('not following', () => pod().follow === false, QUICK_MS) - const top = codeEditor()!.visibleRanges[0].start.line await podUntil(`line ${END_LINE} lit`, () => litOn(END_LINE), 6000) await noChangeFor(500, `the editor moving to line ${END_LINE}`) + // Where the reader went: their line near the top. (VS Code settles a reveal over a few events, so the first + // visible line read just after it may still move by a few lines.) const now = codeEditor()!.visibleRanges[0] - assert.ok(Math.abs(now.start.line - top) <= 1 && !onScreen(END_LINE), `the editor stayed where the reader is (top ${top} → ${now.start.line}-${now.end.line})`) + const atReader = now.start.line <= READER_LINE && READER_LINE - now.start.line <= 8 + assert.ok(atReader && !onScreen(END_LINE), `the editor stayed where the reader is (line ${READER_LINE}: ${now.start.line}-${now.end.line})`) await pause() await vscode.commands.executeCommand('codeNotes.podcastFollow') }), From 2a9be30d2a998f754a0581e57d7eb520b6533c3a Mon Sep 17 00:00:00 2001 From: tomeyer97 <107920881+tomeyer97@users.noreply.github.com> Date: Sat, 28 Nov 2026 01:07:50 +0100 Subject: [PATCH 06/12] Integration tests wait for the box or the player they type into; one nearTop rule MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add Code Note…'s test typed as soon as an input box was visible (the one just closed could still be), and Enter before the text was in it; it now waits for the new box to have the keyboard and the text. startPlaying chose between the panel and the Listen view with a short timeout; a Listen view with no click always hands the audio to the panel, so it now waits for that move, and presses Space only if the audio is not already playing. The reveal-settle rule of two podcast tests is one helper. --- src/notes/create.ts | 4 ++-- test/integration/main/notesAdd.ts | 19 ++++++++++++++++--- test/integration/main/podcast/listening.ts | 4 ++-- test/integration/main/podcast/marks.ts | 5 ++--- test/integration/main/podcast/player.ts | 8 ++++++-- test/integration/main/podcast/state.ts | 8 ++++++++ 6 files changed, 36 insertions(+), 12 deletions(-) diff --git a/src/notes/create.ts b/src/notes/create.ts index 94e5766..c7b1666 100644 --- a/src/notes/create.ts +++ b/src/notes/create.ts @@ -299,8 +299,8 @@ async function restoreDraft(key: string): Promise { if (text === undefined || openBox !== key || input.document.getText()) return if (await input.edit((b) => b.insert(new vscode.Position(0, 0), text))) drafts.delete(key) } - const now = boxInput() - if (now) return put(now) + const input = boxInput() + if (input) return put(input) const waiting = vscode.window.onDidChangeActiveTextEditor((e) => { if (!e) return waiting.dispose() diff --git a/test/integration/main/notesAdd.ts b/test/integration/main/notesAdd.ts index d5ec5f2..c526649 100644 --- a/test/integration/main/notesAdd.ts +++ b/test/integration/main/notesAdd.ts @@ -59,6 +59,17 @@ async function typeLater(editor: vscode.TextEditor, text: string, ms: number): P assert.ok(!editor.document.isDirty, 'nothing typed into the code') } +/** Add Code Note…'s input box on screen, empty, with the keyboard in it. */ +async function pathBoxReady(): Promise { + return (await ui()).evaluate(() => { + const doc = (globalThis as any).document + const box = doc.querySelector('.quick-input-widget') + const shown = !!box && box.style.display !== 'none' && /Note on (file|folder) /.test(box.querySelector('.quick-input-title')?.textContent ?? '') + const el = doc.activeElement + return shown && el?.tagName === 'INPUT' && !!el.closest('.quick-input-widget') && el.value === '' + }) +} + const noteWith = (body: string) => snap().notes.find((n: any) => n.messages[0].body === body) export const notesAddTests = [ @@ -121,16 +132,18 @@ export const notesAddTests = [ // 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') + if (cdp) await until('the input box is shown, with the keyboard', pathBoxReady) + else await settle(500, 'the input box opens') 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('codeNotes.addPathNote', file, { groupId: 0, editorIndex: 1 }) - await until('the input box', () => ui().then((p) => p.locator('.quick-input-widget').isVisible())) + // The box just closed can still be on screen: wait for the new one to have the keyboard, and the text to be in it. + await until('the input box, with the keyboard', pathBoxReady) await (await ui()).keyboard.type('Is this file needed?') + await until('the text in the box', async () => (await (await ui()).locator('.quick-input-widget input').first().inputValue()) === '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') diff --git a/test/integration/main/podcast/listening.ts b/test/integration/main/podcast/listening.ts index 406a2f2..8f997a1 100644 --- a/test/integration/main/podcast/listening.ts +++ b/test/integration/main/podcast/listening.ts @@ -14,7 +14,7 @@ import { AFTER_OWN_MOVE_MS, at, closeAllButPanel, editorLayout, groupsShowing, listenTo, noChangeFor, outlast, pause, play, podTest, seek, seekTo, send, startPlaying, toggle, } from './player' -import { codeEditor, codeFile, litLine, LOAD_MS, MOVE_MS, onScreen, pod, podUntil, QUICK_MS } from './state' +import { codeEditor, codeFile, litLine, LOAD_MS, MOVE_MS, nearTop, onScreen, pod, podUntil, QUICK_MS } from './state' import { listenAudio } from './webview' /* eslint-disable @typescript-eslint/no-explicit-any */ @@ -45,7 +45,7 @@ export const listeningTests = [ await podUntil('not following: the card says Follow along', () => pod().follow === false && /Follow along/.test(tour().card?.body ?? ''), QUICK_MS) const top = () => codeEditor()!.visibleRanges[0].start.line // VS Code settles a reveal over a few events: the reader's place is where it lands (line 185 near the top). - await podUntil('the reader\'s scroll landed', () => top() <= 185 && 185 - top() <= 8, QUICK_MS) + await podUntil('the reader\'s scroll landed', () => nearTop(185), QUICK_MS) const away = top() assert.ok(away >= 170, `scrolled: ${away}`) // Beat 2 (line 150, same file) at 12 s: lit, but the editor isn't moved. diff --git a/test/integration/main/podcast/marks.ts b/test/integration/main/podcast/marks.ts index c85c922..b4eab40 100644 --- a/test/integration/main/podcast/marks.ts +++ b/test/integration/main/podcast/marks.ts @@ -5,7 +5,7 @@ import assert from 'assert' import { tour } from '../context' import { END_LINE, markAt, writeMarksJourney } from './fixtures' import { AFTER_OWN_MOVE_MS, closeAllButPanel, listenTo, noChangeFor, outlast, pause, play, podTest, seek, seekTo, startPlaying } from './player' -import { codeEditor, codeFile, LOAD_MS, litLine, onScreen, pod, podUntil, QUICK_MS } from './state' +import { codeEditor, codeFile, LOAD_MS, litLine, nearTop, onScreen, pod, podUntil, QUICK_MS } from './state' import { listenAudio } from './webview' /* eslint-disable @typescript-eslint/no-explicit-any */ @@ -85,8 +85,7 @@ export const marksTests = [ // Where the reader went: their line near the top. (VS Code settles a reveal over a few events, so the first // visible line read just after it may still move by a few lines.) const now = codeEditor()!.visibleRanges[0] - const atReader = now.start.line <= READER_LINE && READER_LINE - now.start.line <= 8 - assert.ok(atReader && !onScreen(END_LINE), `the editor stayed where the reader is (line ${READER_LINE}: ${now.start.line}-${now.end.line})`) + assert.ok(nearTop(READER_LINE) && !onScreen(END_LINE), `the editor stayed where the reader is (line ${READER_LINE}: ${now.start.line}-${now.end.line})`) await pause() await vscode.commands.executeCommand('codeNotes.podcastFollow') }), diff --git a/test/integration/main/podcast/player.ts b/test/integration/main/podcast/player.ts index 45ae869..ba7a69e 100644 --- a/test/integration/main/podcast/player.ts +++ b/test/integration/main/podcast/player.ts @@ -62,11 +62,15 @@ export async function startPlaying(id: string, { ownMs = 3000 } = {}): Promise tour().map === id && pod().mapVisible, LOAD_MS) const playing = () => pod().playing && pod().session === id if (!(await podUntil('playing on its own', playing, ownMs).catch(() => false))) { - if (await podUntil('the audio moved to the panel', () => pod().hostIn === 'panel', QUICK_MS).catch(() => false)) { + // A Listen view with no click yet refuses, and the audio goes to the panel showing the journey + // (src/podcast/audioHost.ts notAllowed): wait for that move however long it takes. + if (!pod().unlocked.listen) { + await podUntil('the audio moved to the panel', () => pod().hostIn === 'panel', LOAD_MS) const tab = () => vscode.window.tabGroups.activeTabGroup.activeTab?.input await podUntil('the panel is the active editor', () => tab() instanceof vscode.TabInputWebview && /codeNotes\.journey/.test((tab() as vscode.TabInputWebview).viewType), QUICK_MS) await sleep(500) // the focus inside the panel settles on its ▶ (no event for it) - await (await ui()).keyboard.press('Space') + // Space toggles: not when the panel's audio (already unlocked) started on its own meanwhile. + if (!playing()) await (await ui()).keyboard.press('Space') } else { const f = await frameOf('listen') await podUntil('▶ has the keyboard', async () => (await f.evaluate(() => (globalThis as any).document.activeElement?.className)) === 'pod-b play', QUICK_MS) diff --git a/test/integration/main/podcast/state.ts b/test/integration/main/podcast/state.ts index db87507..35df004 100644 --- a/test/integration/main/podcast/state.ts +++ b/test/integration/main/podcast/state.ts @@ -17,6 +17,14 @@ export const codeFile = () => path.basename(codeEditor()?.document.uri.fsPath ?? export const litLine = () => { const b = tour().beat; return b ? b.line + 1 : 0 } /** Is `line` (1-based) on screen in the walk's code editor? */ export const onScreen = (line: number) => !!codeEditor()?.visibleRanges.some((r) => r.contains(new vscode.Position(line - 1, 0))) +/** How far below the top VS Code may leave a line revealed at the top, once its scroll has settled (it settles over a + * few events; seen: 6 lines). */ +const REVEAL_SETTLE_LINES = 8 +/** Line `line` (0-based, as `revealRange` takes it) near the top of the code editor: where a reveal at the top lands. */ +export const nearTop = (line: number) => { + const top = codeEditor()?.visibleRanges[0]?.start.line + return top !== undefined && top <= line && line - top <= REVEAL_SETTLE_LINES +} /** * The podcast tests' wait: main/context.ts's `until` with the podcast's state in the dump (named apart so `until` From 72d6e8cadc4c8009c5f99089a34bb91934674b6e Mon Sep 17 00:00:00 2001 From: tomeyer97 <107920881+tomeyer97@users.noreply.github.com> Date: Sat, 28 Nov 2026 01:53:50 +0100 Subject: [PATCH 07/12] Sidebar: a redraw waits for VS Code's answer to a reveal under way, not one second On a busy machine a reveal took longer than a second; the redraw then dropped the row VS Code was resolving, and it logged "Failed to resolve tree node". The time limit stays only for an answer that never comes. --- src/sidebar/viewSync.ts | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/sidebar/viewSync.ts b/src/sidebar/viewSync.ts index a3f07f3..18c9f18 100644 --- a/src/sidebar/viewSync.ts +++ b/src/sidebar/viewSync.ts @@ -13,8 +13,9 @@ import * as vscode from 'vscode' /** Redraws at least this far apart (VS Code's extension host debounces them by 200 ms). */ const REDRAW_GAP_MS = 250 -/** A reveal under way holds a redraw back at most this long. */ -const REVEAL_HOLDS_MS = 1000 +/** A reveal under way holds a redraw back until VS Code answers it (seconds on a busy machine: a redraw before that + * drops the row it is resolving); at most this long, for an answer that never comes (the window closing). */ +const REVEAL_HOLDS_MS = 10000 /** A reveal that can't go ahead yet (a redraw due, its rows not drawn yet) is tried again this often, so many times. */ const RETRY_MS = 150 const RETRIES = 8 @@ -124,7 +125,7 @@ export class ViewSync { return item.collapsibleState === vscode.TreeItemCollapsibleState.Expanded } - /** A reveal under way: a redraw meanwhile waits for it (not longer than REVEAL_HOLDS_MS). */ + /** A reveal under way: a redraw meanwhile waits for VS Code's answer (not longer than REVEAL_HOLDS_MS). */ private start(reveal: Thenable): void { const holds = new Promise((resolve) => setTimeout(resolve, REVEAL_HOLDS_MS)) const done = Promise.race([Promise.resolve(reveal).then(undefined, () => undefined), holds]) From 23483ecc4d6c571a31edf3d3234e0aebaf3e3db5 Mon Sep 17 00:00:00 2001 From: tomeyer97 <107920881+tomeyer97@users.noreply.github.com> Date: Sat, 28 Nov 2026 09:51:06 +0100 Subject: [PATCH 08/12] Podcast: a mark's camera move stops when the walk moves or the reader seeks meanwhile A mark's move reveals its line in steps, waiting for VS Code to draw it in between; on a busy machine its last step landed after a seek had brought the editor back to the beat, and took it to the far mark again. --- src/podcast/follow.ts | 6 ++++++ src/podcast/markScheduler.ts | 8 ++++++-- 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/src/podcast/follow.ts b/src/podcast/follow.ts index 55421b6..ca87f39 100644 --- a/src/podcast/follow.ts +++ b/src/podcast/follow.ts @@ -145,6 +145,8 @@ export class Follow implements vscode.Disposable { private lastSeekT = -Infinity /** Moves being made now (the walk's changes meanwhile are the podcast's own). */ private moving = 0 + /** Counts the walk's moves and the seeks: a mark's move under way stops when this changes (markScheduler.ts). */ + private turns = 0 private readonly mover = new LatestWins((m, current) => this.move(m, current)) /** The views a playing episode shows, per segment, by journey as loaded. */ private calm = new WeakMap() @@ -167,6 +169,8 @@ export class Follow implements vscode.Disposable { get applying(): number { return this.moving } /** A seek's move is on its way. */ get seeking(): boolean { return !!this.seekTimer } + /** Changes with every move of the walk and every seek. */ + get turn(): number { return this.turns } /** The podcast is playing and the walk on its journey follows it. */ drives(): boolean { @@ -224,6 +228,7 @@ export class Follow implements vscode.Disposable { /** A seek reported at `t`: the view at exactly that time; of seeks in quick succession only the last moves the walk. */ followSeek(lj: LoadedJourney, pod: Loaded, t: number): void { + this.turns++ const v = viewAt(pod.episode, t) const view = viewOf(v) this.lastSeg = v.seg @@ -353,6 +358,7 @@ export class Follow implements vscode.Disposable { private async move(m: Move, current: () => boolean): Promise { const { lj } = m const view = this.live(lj, m.view) + this.turns++ this.moved.fire() this.moving++ let onTheMap = false diff --git a/src/podcast/markScheduler.ts b/src/podcast/markScheduler.ts index 335cfd2..1a75a08 100644 --- a/src/podcast/markScheduler.ts +++ b/src/podcast/markScheduler.ts @@ -150,10 +150,14 @@ export class MarkScheduler implements vscode.Disposable { const where = (from && cueText(from, uri, r.start.line)?.text) ?? `→ ${p.file.split('/').pop()}` const key = this.session.key const onMap = !!key && this.library.get(key)?.episode.segments[this.seg]?.step === 0 + // The walk moved or the reader sought meanwhile (the read time, or VS Code slow to draw): this move is stale, and + // finishing it would take the editor away from the code the walk just showed. + const turn = this.follow.turn + const wanted = () => lock.locked && this.follow.turn === turn await this.camera.move(() => lock.asOurs(async () => { - if (!lock.locked) return + if (!wanted()) return const e = shown() ?? await showInCodeGroup(doc, this.ports.tour().codeColumn, { keepFocus: true }) - await revealKeepingIndent(e, r, () => lock.locked) + await revealKeepingIndent(e, r, wanted) }), where, !onMap && !this.follow.justSought()) } From 6b94ae1e470e85569c7195f14321b901583245a5 Mon Sep 17 00:00:00 2001 From: tomeyer97 <107920881+tomeyer97@users.noreply.github.com> Date: Sat, 28 Nov 2026 09:51:06 +0100 Subject: [PATCH 09/12] Listen view: shown whenever its page isn't there, not only when no view is held VS Code can take the view out (its 'when' turned false) before the dispose arrives; waiting on that view's page waited ten seconds for nothing, and the podcast didn't start. --- src/podcast/listenView.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/podcast/listenView.ts b/src/podcast/listenView.ts index 6721999..8d2f8b1 100644 --- a/src/podcast/listenView.ts +++ b/src/podcast/listenView.ts @@ -111,7 +111,9 @@ export class ListenView implements vscode.WebviewViewProvider, vscode.Disposable async ensure(): Promise { if (this.alive) return true const ready = this.nextReady(READY_TIMEOUT_MS) - if (!this.view && !(await this.show())) { ready.cancel(); return false } + // Shown also when a view is held but its page isn't there: VS Code may have just taken the view out (its + // `when` turned false) without the dispose having arrived; waiting on that view's page would wait for nothing. + if (!(await this.show())) { ready.cancel(); return false } return ready.done } From 27909df51203c288f3dfd46a9bfdc9652bba2f5e Mon Sep 17 00:00:00 2001 From: tomeyer97 <107920881+tomeyer97@users.noreply.github.com> Date: Sat, 28 Nov 2026 09:51:06 +0100 Subject: [PATCH 10/12] Sidebar: rows VS Code asks for before it applies a redraw don't count as held VS Code applies a redraw a little after it is fired (seconds on a busy machine); rows it asks for in between are of the drawing it is about to drop, and a reveal of one of them failed ("Failed to resolve tree node"). --- src/sidebar/viewSync.ts | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/src/sidebar/viewSync.ts b/src/sidebar/viewSync.ts index 18c9f18..37a733d 100644 --- a/src/sidebar/viewSync.ts +++ b/src/sidebar/viewSync.ts @@ -7,7 +7,8 @@ // only when VS Code holds the row, or holds its parents and won't ask for the parent's children itself (they were not // given yet and the parent is folded); and a redraw waits for a reveal under way. VS Code applies a redraw that comes // within 200 ms of the one before only when that time is up (rows given meanwhile are then dropped): redraws are spaced -// further apart than that, so each is applied as it is fired. +// further apart than that. Even so it applies a redraw a little after it is fired (seconds on a busy machine): rows it +// asks for before it asks for the top rows again are of the drawing it is about to drop, so they don't count as held. import * as vscode from 'vscode' @@ -29,6 +30,9 @@ export class ViewSync { /** The rows VS Code was given since the last redraw, and the rows whose children it was given. */ private readonly held = new Set() private readonly opened = new Set() + /** VS Code has applied the last redraw: it asked for the top rows since. It applies one up to 200 ms after it is + * fired (longer on a busy machine), and rows it asks for before that are of the drawing it is about to drop. */ + private applied = true /** What the person expanded (true) or folded (false), by row id: rows are made again, their ids stay. */ private readonly expanded = new Map() /** The rows' provider (set by `provider`). */ @@ -75,6 +79,8 @@ export class ViewSync { } private given(parent: T | undefined, children: T[]): T[] { + if (parent === undefined) this.applied = true + else if (!this.applied) return children this.opened.add(parent ?? TOP) for (const c of children) this.held.add(c) return children @@ -93,6 +99,7 @@ export class ViewSync { this.lastRedraw = Date.now() this.held.clear() this.opened.clear() + this.applied = false this.changed.fire(undefined) } From 6928c9fbf9357514acd7c97284d7ad48c922e3ce Mon Sep 17 00:00:00 2001 From: tomeyer97 <107920881+tomeyer97@users.noreply.github.com> Date: Sat, 28 Nov 2026 10:33:16 +0100 Subject: [PATCH 11/12] Add Note: the box is asked for once VS Code has the file's commenting ranges, however long that takes It waited at most a second for VS Code to ask for the ranges, then opened the box anyway; on a busy machine the box then did not open. It now waits for that request (ten seconds only as a limit for one that never comes). --- src/notes/commentRanges.ts | 31 +++++++++++++++++++++++-------- 1 file changed, 23 insertions(+), 8 deletions(-) diff --git a/src/notes/commentRanges.ts b/src/notes/commentRanges.ts index c50fc0c..0dc3b0e 100644 --- a/src/notes/commentRanges.ts +++ b/src/notes/commentRanges.ts @@ -4,17 +4,23 @@ import * as vscode from 'vscode' import { controller } from './ports' import { inNotesFolder } from './notesFolder' -import { Poll, sleep, waitUntil } from './timing' +import { sleep } from './timing' /** 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() +/** Each runs the next time VS Code asks for a file's commenting ranges (by uri). */ +const askedWaiters = new Map void>>() export const rangeProvider: vscode.CommentingRangeProvider = { provideCommentingRanges: (doc) => { - rangesAskedAt.set(doc.uri.toString(), Date.now()) + const key = doc.uri.toString() + rangesAskedAt.set(key, Date.now()) + const waiting = askedWaiters.get(key) + askedWaiters.delete(key) + for (const w of waiting ?? []) w() 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)] : [] }, @@ -22,9 +28,18 @@ export const rangeProvider: vscode.CommentingRangeProvider = { /** 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 } +/** The window asks for the file's ranges again within a round trip (seconds on a busy machine or a slow remote link); + * at most this long, for a window that never asks (the editor gone meanwhile). */ +const RANGES_ASKED_MS = 10_000 + +/** Resolves when VS Code next asks for `uri`'s commenting ranges, or after `ms`. */ +function nextAsk(uri: string, ms: number): Promise { + return new Promise((resolve) => { + const done = () => { clearTimeout(timer); askedWaiters.get(uri)?.delete(done); resolve() } + const timer = setTimeout(done, ms) + askedWaiters.set(uri, (askedWaiters.get(uri) ?? new Set()).add(done)) + }) +} /** The scheme of a comment box's input editor. */ export const COMMENT_INPUT = 'comment' @@ -40,11 +55,11 @@ export async function allowComments(): Promise { watching?.dispose() watching = undefined addingIn = u + const asked = u ? nextAsk(u, RANGES_ASKED_MS) : Promise.resolve() controller().commentingRangeProvider = rangeProvider const t0 = Date.now() - // 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. - if (u) await waitUntil(() => (rangesAskedAt.get(u) ?? 0) >= t0, RANGES_ASKED) + // At least SETTLE_MS, and until the window has asked for the file's ranges again: before that the box would not open. + await asked const left = SETTLE_MS - (Date.now() - t0) if (left > 0) await sleep(left) } From f7c6b19f867fb638c8b320ecc0187205552dac0e Mon Sep 17 00:00:00 2001 From: tomeyer97 <107920881+tomeyer97@users.noreply.github.com> Date: Sat, 28 Nov 2026 10:59:36 +0100 Subject: [PATCH 12/12] Journeys view: a writing row's clock is redrawn through ViewSync, never during a reveal The clocks of the journeys Claude is writing were redrawn every second straight to VS Code, past the rule that a reveal under way holds redraws back; VS Code then dropped rows a reveal was resolving. --- src/sidebar/journeysTree.ts | 12 ++++-------- src/sidebar/viewSync.ts | 13 ++++++++++++- 2 files changed, 16 insertions(+), 9 deletions(-) diff --git a/src/sidebar/journeysTree.ts b/src/sidebar/journeysTree.ts index d9955d0..d0eba86 100644 --- a/src/sidebar/journeysTree.ts +++ b/src/sidebar/journeysTree.ts @@ -128,12 +128,8 @@ export async function sortJourneys(): Promise { /** 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 { - // The provider's changes: the whole tree's (ViewSync's redraws), or only the writing rows' clocks (followWriting). - const changed = new vscode.EventEmitter() - const synced = journeysTree.sync.provider(journeysTree) - const redraws = synced.onDidChangeTreeData!((e) => changed.fire(e as Node | Node[] | undefined)) - const provider: vscode.TreeDataProvider = { ...synced, onDidChangeTreeData: changed.event } - const view = vscode.window.createTreeView('codeNotes.journeys', { treeDataProvider: provider, showCollapseAll: true }) + // The provider's changes: the whole tree's, or only the writing rows' clocks (followWriting), both through ViewSync. + const view = vscode.window.createTreeView('codeNotes.journeys', { treeDataProvider: journeysTree.sync.provider(journeysTree), showCollapseAll: true }) journeysTree.attach(view) const editorChanged = vscode.window.onDidChangeActiveTextEditor(() => { capHere() @@ -147,8 +143,8 @@ export function createJourneysView(context: vscode.ExtensionContext): void { journeysTree.refresh() if (e.editorChanged) revealHereGroup() }) - context.subscriptions.push(view, editorChanged, selectionChanged, listChanged, ...journeysTree.sync.watch(view), changed, redraws, - followWriting(view, (rows) => changed.fire(rows))) + context.subscriptions.push(view, editorChanged, selectionChanged, listChanged, ...journeysTree.sync.watch(view), + followWriting(view, (rows) => journeysTree.sync.redrawRows(rows))) } /** The journeys Claude is writing: their rows come and go with the runs (the whole tree drawn again), and their clocks diff --git a/src/sidebar/viewSync.ts b/src/sidebar/viewSync.ts index 37a733d..96ec860 100644 --- a/src/sidebar/viewSync.ts +++ b/src/sidebar/viewSync.ts @@ -25,7 +25,7 @@ const RETRIES = 8 const TOP = Symbol('top') export class ViewSync { - private readonly changed = new vscode.EventEmitter() + private readonly changed = new vscode.EventEmitter() readonly onDidChangeTreeData = this.changed.event /** The rows VS Code was given since the last redraw, and the rows whose children it was given. */ private readonly held = new Set() @@ -86,6 +86,17 @@ export class ViewSync { return children } + /** Some rows drawn again (a clock on them), not while a reveal is under way or a redraw is due (the caller draws + * them again soon). VS Code may ask for other rows again meanwhile: it holds nothing for sure until it asks for the + * top rows. */ + redrawRows(rows: T[]): void { + if (!rows.length || this.revealing || this.redrawTimer) return + this.held.clear() + this.opened.clear() + this.applied = false + this.changed.fire(rows) + } + /** A redraw, once the burst of changes is over and no reveal is under way. */ refresh(): void { clearTimeout(this.redrawTimer)