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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 26 additions & 8 deletions src/journeys/repository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<void> {
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<string>, found: ReadonlySet<string>): 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) ?? [])
Expand Down Expand Up @@ -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<string | undefined> {
/** 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<string | undefined> {
// 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()
Expand All @@ -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)
Expand Down
31 changes: 23 additions & 8 deletions src/notes/commentRanges.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,27 +4,42 @@
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<string, number>()
/** Each runs the next time VS Code asks for a file's commenting ranges (by uri). */
const askedWaiters = new Map<string, Set<() => 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)] : []
},
}

/** 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<void> {
return new Promise<void>((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'
Expand All @@ -40,11 +55,11 @@ export async function allowComments(): Promise<void> {
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)
}
Expand Down
40 changes: 27 additions & 13 deletions src/notes/create.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand All @@ -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…' }
Expand Down Expand Up @@ -280,20 +280,34 @@ const drafts = new Map<string, string>()
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<void> {
const text = drafts.get(key)
if (text === undefined || !(await waitUntil(() => !!boxInput(), BOX_INPUT))) return
const input = boxInput()!
if (input.document.getText()) return
if (await input.edit((b) => b.insert(new vscode.Position(0, 0), text))) drafts.delete(key)
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
Expand Down
2 changes: 1 addition & 1 deletion src/notes/followEdits.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<boolean>

export function followEdits(events: WorkspaceEvents, save: Save): vscode.Disposable {
Expand Down
2 changes: 1 addition & 1 deletion src/notes/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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')),
),
Expand Down
2 changes: 1 addition & 1 deletion src/notes/location.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ export function onlyLocalPlacementChanged(n: Note): boolean {
export async function saveIfClean(n: Note): Promise<void> {
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. */
Expand Down
6 changes: 3 additions & 3 deletions src/notes/moves.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ export async function followMovedFiles(events: WorkspaceEvents): Promise<void> {
(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 })
})
Expand All @@ -69,7 +69,7 @@ async function moveNoteTo(n: Note, uri: vscode.Uri, loc: Loc): Promise<void> {
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. */
Expand All @@ -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)
}
}
32 changes: 23 additions & 9 deletions src/notes/store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<boolean> {
save(n: Note): Promise<boolean> { 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<boolean> { return this.write(n, { ifOnDisk: true }) }

private async write(n: Note, o: { ifOnDisk: boolean }): Promise<boolean> {
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
Expand All @@ -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<NoteData | undefined | false> {
private async changedOnDisk(n: Note): Promise<NoteData | undefined | false | 'gone'> {
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) {
Expand Down
6 changes: 6 additions & 0 deletions src/podcast/follow.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<Move>((m, current) => this.move(m, current))
/** The views a playing episode shows, per segment, by journey as loaded. */
private calm = new WeakMap<LoadedJourney, { sig: string; views: View[] }>()
Expand All @@ -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 {
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -353,6 +358,7 @@ export class Follow implements vscode.Disposable {
private async move(m: Move, current: () => boolean): Promise<void> {
const { lj } = m
const view = this.live(lj, m.view)
this.turns++
this.moved.fire()
this.moving++
let onTheMap = false
Expand Down
4 changes: 3 additions & 1 deletion src/podcast/listenView.ts
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,9 @@ export class ListenView implements vscode.WebviewViewProvider, vscode.Disposable
async ensure(): Promise<boolean> {
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
}

Expand Down
8 changes: 6 additions & 2 deletions src/podcast/markScheduler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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())
}

Expand Down
6 changes: 3 additions & 3 deletions src/podcast/testing.ts
Original file line number Diff line number Diff line change
@@ -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'
Expand All @@ -16,8 +16,8 @@ export function podcastProbe(feature: PodcastFeature, ports: Pick<PodcastPorts,
})
return {
snapshot: () => 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 },
}
Expand Down
Loading
Loading