diff --git a/src/journeys/repository.ts b/src/journeys/repository.ts index 5b93264..49f6c5c 100644 --- a/src/journeys/repository.ts +++ b/src/journeys/repository.ts @@ -66,18 +66,32 @@ 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. A file the watcher read while the folders were + * listed stays: the listing may predate it. + */ async load(): Promise { - this.files.clear() - this.broken.clear() 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 }))) - const oldFormat = await Promise.all(found.map(({ folder, uri }) => this.read(folder, uri))) + 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 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) + } + } + /** 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 +198,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 +212,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/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) } diff --git a/src/notes/create.ts b/src/notes/create.ts index 8d36a83..c7b1666 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 input = boxInput() + if (input) return put(input) + 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/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/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/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 } 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()) } 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/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 a3f07f3..96ec860 100644 --- a/src/sidebar/viewSync.ts +++ b/src/sidebar/viewSync.ts @@ -7,14 +7,16 @@ // 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' /** 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 @@ -23,11 +25,14 @@ 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() 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`). */ @@ -74,11 +79,24 @@ 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 } + /** 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) @@ -92,6 +110,7 @@ export class ViewSync { this.lastRedraw = Date.now() this.held.clear() this.opened.clear() + this.applied = false this.changed.fire(undefined) } @@ -124,7 +143,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]) 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/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/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/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/listening.ts b/test/integration/main/podcast/listening.ts index 6e95767..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 */ @@ -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', () => 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 3173d1c..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 */ @@ -74,14 +74,18 @@ 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) + 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})`) + 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 26f15df..ba7a69e 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') @@ -61,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) @@ -87,6 +92,25 @@ 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 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 { + 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') + 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/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` diff --git a/test/integration/main/repoJourneys.ts b/test/integration/main/repoJourneys.ts index 571ad94..69dcd2d 100644 --- a/test/integration/main/repoJourneys.ts +++ b/test/integration/main/repoJourneys.ts @@ -48,4 +48,54 @@ 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') + }), + + // 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' })) + 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 reload() + await until('the twin gone', () => !journeyById('twin')) + }), ]