From 3d76e0341d60de48be03ae3cb1a18a418b177fa1 Mon Sep 17 00:00:00 2001 From: tomeyer97 <107920881+tomeyer97@users.noreply.github.com> Date: Wed, 18 Nov 2026 13:01:44 +0100 Subject: [PATCH 01/45] Journey podcasts (prototype): play a journey's audio episode; the walk follows the voice MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A journey with `.podcast.json` next to it (and its audio) gets a ▶ on its row and a player at the bottom of the journey panel: play/pause, ±15 s, previous/next step, speed, and a timeline marked by step (hover names the step, click or drag to seek). The walk follows the audio: at any time it is where the podcast is at that time (the step opened as a reader's move would, the animation on that beat). A seek applies that view directly, backwards too, and of quick seeks only the last one. Next, Previous, a step or a beat the reader picks moves the audio to its first part; a step the podcast skips, or ending the walk, pauses it. The audio plays in the panel's webview (kept while hidden), so it goes on behind another tab. Ctrl+' Space / ← / → from anywhere; a status bar item. - src/podcast/model.ts: the format, checked against the journey (a missing beat shows the step only; an unknown step keeps the view before), view at a time, chapters, journey → audio times, LatestWins (seek coalescing). Unit tests. - src/podcast/player.ts: discovery next to the journey, audio → walk and walk → audio, commands, status item. - media/journey-podcast.js/.css: the bar, outside #app so re-renders never touch the audio or a drag. - The panel: audio from the journeys folders (localResourceRoots, CSP media-src); beats preset before the step opens (no first-beat flash); the scene can show a beat without its flight (a jump). - VS Code's webviews play audio only after a click or key in them: the first Play focuses ▶ ("Press Space to play"). - test:podcast harness (three widths, seeks forwards/backwards, drag, hover, keys, step click, missing beat) and an integration suite in real VS Code (mp3 plays; seeks; quick seeks; Next/Previous; hidden panel; a 10-minute file seeked 9 minutes in). The main integration run opens a DevTools port for the real click. - docs/podcast-format.md. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 8 + README.md | 6 + docs/podcast-format.md | 86 +++++ media/journey-map.js | 58 +++- media/journey-podcast.css | 54 +++ media/journey-podcast.js | 401 ++++++++++++++++++++++ media/journey-scene.js | 15 +- package.json | 111 ++++++ src/extension.ts | 6 + src/journeys/journeys.ts | 4 + src/journeys/mapPanel.ts | 28 +- src/podcast/model.ts | 243 +++++++++++++ src/podcast/player.ts | 340 ++++++++++++++++++ src/sidebar/journeyRows.ts | 3 +- src/testApi.ts | 3 + src/tour/mapMessages.ts | 7 +- src/tour/walk.ts | 4 + src/webview/page.ts | 6 +- test/fixtures/podcast/sample.podcast.json | 21 ++ test/fixtures/podcast/tone.mp3 | Bin 0 -> 80432 bytes test/harness/themes.js | 2 + test/integration/helpers.ts | 2 +- test/integration/main/podcast.ts | 198 +++++++++++ test/integration/run.ts | 5 +- test/integration/suite.ts | 3 + test/journey-map/harness.html | 4 +- test/journey-podcast/shoot.mjs | 278 +++++++++++++++ test/keybindings.test.ts | 4 + test/podcastModel.test.ts | 150 ++++++++ 29 files changed, 2028 insertions(+), 22 deletions(-) create mode 100644 docs/podcast-format.md create mode 100644 media/journey-podcast.css create mode 100644 media/journey-podcast.js create mode 100644 src/podcast/model.ts create mode 100644 src/podcast/player.ts create mode 100644 test/fixtures/podcast/sample.podcast.json create mode 100644 test/fixtures/podcast/tone.mp3 create mode 100644 test/integration/main/podcast.ts create mode 100644 test/journey-podcast/shoot.mjs create mode 100644 test/podcastModel.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 7bdc382..89be9e2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,14 @@ ## Unreleased +- **Journey podcasts (prototype).** A journey with an audio episode next to it (`.podcast.json` and its + audio, [docs/podcast-format.md](docs/podcast-format.md)) gets a ▶ on its row and a player at the bottom of the + journey panel: play and pause, back and forward 15 s, previous and next step, speed (1×, 1.25×, 1.5×), and a + timeline marked by step (hover names the step; click or drag to go there). The walk follows the voice: steps open + and animations move beat by beat, exactly as when you walk them; any seek puts the walk where it is at that time, + backwards too. Next, Previous, a step or a beat you pick moves the audio to its part. The audio goes on while the + panel is behind another tab or VS Code is in the background. Ctrl+' Space plays and pauses from anywhere, Ctrl+' ← → + skip; the status bar shows where it is. - **Understanding check: a tour of the change.** Right after the questions, Claude writes a short journey of the change (6-10 steps through the changed code and the code it depends on), each question placed after the step that shows its answer. Check my understanding (or **Walk the tour** in the Check view) walks it in the journey panel: the diff --git a/README.md b/README.md index f250456..a973864 100644 --- a/README.md +++ b/README.md @@ -44,6 +44,10 @@ write one. the line of code that does it, and shows that line with a few around it under the caption. - **Steps follow the code** like notes do: moved code is followed, changed code is flagged. Your own edits to a step's lines (typing, an applied fix) are followed, not flagged. +- **Podcasts:** a journey with an audio episode next to it (`.podcast.json`) has a ▶. The walk follows the + voice: each step's code opens, the animation moves beat by beat. The timeline is marked by step; click or drag + anywhere and the walk is exactly where it is at that time. The audio goes on while VS Code is in the background. + [docs/podcast-format.md](docs/podcast-format.md) describes the format. ![What a step's animation can draw](docs/images/objects.png) @@ -179,6 +183,8 @@ One chord: **Ctrl+'** (or **Ctrl+<** on ISO keyboards), then a letter. | **V** | The journey map | | **P** | The current step's animation, on or off | | **J** | Search journeys | +| **Space** | The journey podcast: play or pause | +| **←** / **→** | The journey podcast: back / forward 15 s | ## Requirements diff --git a/docs/podcast-format.md b/docs/podcast-format.md new file mode 100644 index 0000000..7c7ed0f --- /dev/null +++ b/docs/podcast-format.md @@ -0,0 +1,86 @@ +# Journey podcasts + +A journey can have a podcast: one audio file that talks through the journey, whose parts are linked to the journey's +steps and animation beats. Code Notes plays it in the journey panel and moves the walk with the voice: each step's code +opens as the voice reaches it, and its animation goes to the beat being talked about. The extension only plays +podcasts; how you make one (a text-to-speech service, a recording) is up to you. + +## Where it goes + +Next to its journey, with the same name: + +``` +journeys/ + place-order.json the journey + place-order.podcast.json its podcast (this format) + place-order.mp3 the audio (any name: `audio` says which) +``` + +`audio` is a path relative to the podcast file. It must be inside the journeys folder (or a folder under it): the +panel can only load files from there. mp3 plays in VS Code (tested); so do ogg/opus and wav. + +A journey with a podcast has a ▶ on its row in the Journeys view, and its panel has the player at the bottom. + +## The file + +```jsonc +{ + "version": 1, + "title": "Placing an order, end to end", + "journey": { "id": "place-order", "file": "journeys/place-order.json", "commit": "a1b2c3d" }, + "audio": "place-order.mp3", + "duration": 767.88, + "segments": [ + { "id": "s01", "at": null, "cue": "map", "speaker": "host", "text": "Welcome…", "start": 0, "end": 29.2 }, + { "id": "s04", "at": { "step": "checks-first", "beat": 1 }, "cue": "open", "speaker": "host", "text": "First, the page…", "start": 57.22, "end": 71.14 }, + { "id": "s05", "at": { "step": "checks-first", "beat": 3 }, "cue": "beat", "speaker": "host", "text": "Then it sends…", "start": 71.44, "end": 79.28 } + ] +} +``` + +| Field | | +|---|---| +| `version` | `1` | +| `title` | The episode's title | +| `journey` | The journey it was written for: `id`, and optionally `file` and `commit`. The player uses the journey next to the file; a different `id` is only logged | +| `audio` | The audio file, relative to this file | +| `duration` | Seconds (optional; the audio's own length wins) | +| `segments` | The parts, each with the fields below | + +A segment: + +| Field | | +|---|---| +| `id` | Stable when segments are edited or removed | +| `at` | Where it belongs: `null` (the whole journey: the map, no step open), `{ "step": "" }` (the step, without its animation), or `{ "step": "", "beat": n }` (the step's animation at beat `n`, 1-based, counted in the step's `scene.beats`) | +| `cue` | How the change of place is shown: `map`, `open` or `beat`. The player shows what `at` says; `cue: "map"` on a step shows the step without its animation | +| `speaker`, `text` | Who says what (the panel shows the text as a one-line caption) | +| `start`, `end` | Seconds in the audio. Gaps between segments belong to the segment before them | + +Steps are named by id, so reordering a journey's steps keeps the podcast right. Beats have no ids: they are linked by +position. + +## What the player does + +- **At any time the walk is where the podcast is at that time**: the segment playing then (the last one started) + says the step and beat. Seeking anywhere, backwards too, applies that directly, never the parts in between; of quick + seeks (a drag, a key held down), only the last one moves the walk. +- **Moving the walk yourself moves the audio**: Next, Previous, a step in the storyline or a beat of the animation + (‹ ›) jump the audio to the first segment about it. A step the podcast never talks about pauses it, and so does + ending the walk or opening another journey. Pausing never ends the walk. +- **A link the journey can't show degrades**: a beat the step doesn't have (the journey was edited) shows the step + without its animation; a step id that isn't in the journey keeps the view of the segment before it. Each is logged + in the Code Notes output channel. + +## Playing + +- **▶** on the journey's row, the command **Play Journey Podcast**, or the player's ▶ in the panel. +- In the panel: Space or K play and pause, ← → go back and forward 15 s, Shift+← → the previous and next step; on + the timeline, Home and End, Page Up and Page Down. Hovering over the timeline names the step at that point; click or + drag to go there. +- From anywhere: **Ctrl+' Space** plays and pauses, **Ctrl+' ←** / **→** go back and forward 15 s. The status bar + shows where it is; click it to pause or play. +- The audio plays in the journey panel and goes on while the panel is behind another tab or VS Code isn't focused. + Closing the panel stops it; where it was is kept for next time, per journey. +- VS Code lets a panel play sound only after a click or a key in it: the first time a panel plays, its ▶ takes the + keyboard and says "Press Space to play". After that, the keys and commands play it directly. diff --git a/media/journey-map.js b/media/journey-map.js index 975c93b..e4a4ce5 100644 --- a/media/journey-map.js +++ b/media/journey-map.js @@ -19,6 +19,9 @@ // { type: 'code', n, i, code } the lines of beat i of step n's animation // { type: 'hello' } answered with ready (the extension lost it) // { type: 'test', click?: selector, key?: key } (integration tests drive the real handlers) +// { type: 'podcast', episode? } { type: 'podcastCmd', … } the podcast bar's (journey-podcast.js) +// { type: 'podcastBeat', n, i, still? } the podcast is on step n's beat i (-1: the step without its animation): the +// animation shows it (still: no flight, it was a jump) // Out: // { type: 'ready' } { type: 'error', message } // { type: 'step', n } { type: 'end' } { type: 'finish' } { type: 'nextStop' } (a check's tour: Next) @@ -30,7 +33,8 @@ // { type: 'tutorial', action: 'bar' | 'card' | 'skip' | 'done', card?, editor? } // { type: 'ref', i } (a link in the step card) { type: 'ask', update? } { type: 'details', open } // { type: 'question', id } { type: 'checkpoint', id } { type: 'openFile' } { type: 'restore' } { type: 'authors' } -// { type: 'beat', n, i } (the animation's beat on step n; i = -1: the scene is gone) +// { type: 'beat', n, i, user? } (the animation's beat on step n; i = -1: the scene is gone; user: the reader moved it) +// { type: 'podcastTime', t, playing, rate, seek? } { type: 'podcastError', message } (journey-podcast.js) // These are src/journeys/mapPanel.ts MapMessage (the extension's list, with `close` and `pick`, which it handles but // nothing here posts, and its own `closed`): a name added here goes there too. ;(function () { @@ -95,6 +99,8 @@ let beatAt = {} /** The next render puts the keyboard focus in the scene (it was started: ← → work at once). */ let focusScene = false + /** Scenes ("journey|step") the podcast jumped to: shown at their beat without its flight. */ + const stillAt = {} // Waiting (startup, at the end): the size last rendered ({ w, h }) and the frame a re-layout waits for; the scroll // saved and the panel's width reported once things settle. @@ -180,6 +186,9 @@ }, // The current beat's line and the lines around it, once the extension found them. code(m) { if (scene && animOn && m.n === cur && m.i === scene.beat) scene.code(m.code) }, + podcast(m) { if (podcast) podcast.set(m.episode) }, + podcastCmd(m) { if (podcast) podcast.cmd(m) }, + podcastBeat(m) { podcastBeat(m) }, test(m) { if (m.click) { const t = document.querySelector(m.click) @@ -413,7 +422,8 @@ /** The animation player: one, kept across renders (its beat and its transitions survive them). */ const scene = window.JourneyScene ? window.JourneyScene.create({ - onBeat: (i) => { if (sceneKey) beatAt[sceneKey] = i; post({ type: 'beat', n: cur, i }) }, + // `user`: moved by the reader (‹ ›, the keys), not shown with the step nor set by the podcast. + onBeat: (i, how) => { if (sceneKey) beatAt[sceneKey] = i; post({ type: 'beat', n: cur, i, ...(how === 'go' && !podcastGoing ? { user: true } : {}) }) }, onClose: () => toggleAnim(), // At the last beat › walks on, the animation still on. onNextStep: () => { focusScene = true; goStep(cur + 1) }, @@ -438,9 +448,46 @@ const fresh = k !== sceneKey sceneKey = k scene.layout() - scene.show(sceneOf(cur), k, { file: J.steps[cur - 1].file, next: cur < J.steps.length, beat: beatAt[k] || 0 }) - if (fresh || focusScene) scene.focus() + const still = !!stillAt[k] + delete stillAt[k] + scene.show(sceneOf(cur), k, { file: J.steps[cur - 1].file, next: cur < J.steps.length, beat: beatAt[k] || 0, still }) + // The podcast moved it: the keyboard stays where it was (Space keeps pausing). + if ((fresh || focusScene) && !podcastMoved) scene.focus() focusScene = false + podcastMoved = false + } + + // ---------- the podcast (journey-podcast.js): its bar, and the animation following it ---------- + + const podcast = window.JourneyPodcast ? window.JourneyPodcast({ post, stepTitle: (n) => (J && J.steps[n - 1] ? J.steps[n - 1].title : '') }) : undefined + /** The next scene shown was put there by the podcast, not by a click; the beat being set is the podcast's. */ + let podcastMoved = false + let podcastGoing = false + /** + * The podcast is on step n, beat i (-1: the step without its animation). Sent before the step opens, so the step + * comes up on that beat (never its first beat, then a jump); `still`: a seek, the beat is shown without its flight. + */ + function podcastBeat(m) { + if (!J || !scene) return + const k = `${J.id}|${m.n}` + const on = m.i >= 0 && !!sceneOf(m.n) + if (on) { + beatAt[k] = m.i + if (m.still) stillAt[k] = true + } + const was = animOn + animOn = on + podcastMoved = true + if (m.n !== cur) return // the tour message that follows draws it + if (on && was && sceneKey === k) { + podcastGoing = true + try { scene.go(m.i, false, !!m.still) } finally { podcastGoing = false } + delete stillAt[k] + podcastMoved = false + return + } + if (on !== was) render() + else podcastMoved = false } function mapEl() { @@ -613,7 +660,8 @@ /** Scrolls the page so row rectangle `r` (viewport px) is in view under the header (its bottom at `top`): at the * top when it was above or is taller than the room, else just up from the bottom. */ function scrollRowIntoView(r, top) { - const H = window.innerHeight + // The podcast bar covers the bottom of the window. + const H = window.innerHeight - (parseFloat(getComputedStyle(document.documentElement).getPropertyValue('--podH')) || 0) const above = r.top < top + ROW_MARGIN if (!above && r.bottom <= H - ROW_MARGIN) return const atTop = above || r.height > H - top diff --git a/media/journey-podcast.css b/media/journey-podcast.css new file mode 100644 index 0000000..6b5345d --- /dev/null +++ b/media/journey-podcast.css @@ -0,0 +1,54 @@ +/* The podcast bar (journey-podcast.js): fixed at the panel's bottom; the timeline is one bar per step. Colours: the + tokens in common.css. */ +.pod { + position: fixed; left: 0; right: 0; bottom: 0; z-index: 8; + background: var(--raised); border-top: 1px solid var(--border); + padding: 6px 16px 6px; display: grid; gap: 2px; +} +.pod[hidden] { display: none; } +body.has-pod #app { padding-bottom: calc(20px + var(--podH, 0px)); } +body.has-pod .body.wide .mapwrap { height: calc(100vh - var(--headH, 0px) - var(--podH, 0px) - 16px); } + +/* The timeline: tall enough to hit (18px), the bars thin until hovered. */ +.pod-tl { position: relative; height: 18px; cursor: pointer; touch-action: none; outline: none; border-radius: 3px; } +.pod-tl:focus-visible { outline: 2px solid var(--focus); outline-offset: 1px; } +.pod-track { position: absolute; left: 0; right: 0; top: 7px; height: 4px; } +.pod-bar { position: absolute; top: 0; bottom: 0; background: color-mix(in srgb, var(--fg) 22%, transparent); overflow: hidden; } +/* A gap between parts: where a step starts. */ +.pod-bar + .pod-bar { border-left: 2px solid var(--raised); } +.pod-bar.map { background: color-mix(in srgb, var(--fg) 12%, transparent); } +.pod-fill { height: 100%; width: 0; background: var(--accent); } +.pod-tl:hover .pod-track, .pod.dragging .pod-track { top: 6px; height: 6px; } +.pod-thumb { + position: absolute; top: 4px; width: 10px; height: 10px; margin-left: -5px; border-radius: 50%; + background: var(--accent); opacity: 0; pointer-events: none; +} +.pod-tl:hover .pod-thumb, .pod-tl:focus-visible .pod-thumb, .pod.dragging .pod-thumb { opacity: 1; } +.pod-tip { + position: absolute; bottom: 20px; left: 0; max-width: min(360px, 100%); padding: 3px 7px; border-radius: 3px; + background: var(--vscode-editorHoverWidget-background, var(--raised)); color: var(--vscode-editorHoverWidget-foreground, var(--fg)); + border: 1px solid var(--vscode-editorHoverWidget-border, var(--border)); + font-size: 0.9em; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; pointer-events: none; +} +.pod-tip b { font-weight: 600; margin-right: 8px; } +.pod-tip span { color: var(--muted); font-variant-numeric: tabular-nums; } + +.pod-row { display: flex; align-items: center; gap: 8px; min-width: 0; } +.pod-ctl { display: flex; align-items: center; gap: 2px; flex: none; } +.pod-b { width: 28px; height: 28px; border-radius: 4px; display: inline-flex; align-items: center; justify-content: center; color: var(--fg); } +.pod-b:hover { background: var(--hover); } +.pod-b.play { width: 32px; height: 32px; border-radius: 50%; background: var(--vscode-button-background, var(--accent)); color: var(--vscode-button-foreground, #fff); } +.pod-b.play:hover { background: var(--vscode-button-hoverBackground, var(--vscode-button-background, var(--accent))); } +.pod-time { color: var(--muted); font-size: 0.9em; font-variant-numeric: tabular-nums; white-space: nowrap; } +.pod-err { color: var(--warn); font-size: 0.9em; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; min-width: 0; } +.pod-rate { margin-left: auto; font-size: 0.9em; padding: 2px 6px; border-radius: 3px; color: var(--muted); font-variant-numeric: tabular-nums; } +.pod-rate:hover { background: var(--hover); color: var(--fg); } +/* What is being said: one muted line (the whole of it on hover). */ +.pod-cap { color: var(--muted); font-size: 0.9em; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; min-height: 1.2em; } + +/* Narrow: no part buttons (the timeline and ‹15 15› do it). */ +@media (max-width: 360px) { + .pod { padding: 6px 10px; } + .pod-b.prev, .pod-b.next { display: none; } +} +@media (prefers-reduced-motion: reduce) { .pod-track, .pod-thumb { transition: none; } } diff --git a/media/journey-podcast.js b/media/journey-podcast.js new file mode 100644 index 0000000..8e2cf69 --- /dev/null +++ b/media/journey-podcast.js @@ -0,0 +1,401 @@ +// The journey's podcast player: a bar at the bottom of the journey panel with the audio, its controls and a timeline +// marked by step. The audio plays here (a webview kept alive while hidden: retainContextWhenHidden), so it goes on +// while the panel is in a background tab or VS Code has no focus. Where the journey should be at a time is the +// extension's to work out (src/podcast/): this bar only plays, seeks and says where the audio is. It lives outside +// #app, so journey-map.js's re-renders never touch it (a drag or the audio survive them). +// Needs common.js. Made by journey-map.js: JourneyPodcast({ post, stepTitle(n), onShown(h) }). +// +// In (journey-map.js routes them here): +// { type: 'podcast', episode? } the journey's episode ({ src, title, duration, at, rate, chapters, segments }), or +// none (the bar goes) +// { type: 'podcastCmd', action: 'play' | 'pause' | 'toggle' | 'skip' | 'seek' | 'part', by?, to?, dir? } +// Out: +// { type: 'podcastTime', t, playing, rate, seek? } where the audio is (seek: moved by a seek, not by playing) +// { type: 'podcastError', message } +;(function () { + const { el, svgEl, runKey } = window.common + + /** Back / forward (s). */ + const SKIP_S = 15 + /** Speeds the speed button cycles through. */ + const RATES = [1, 1.25, 1.5] + /** Within this many seconds of a part's start, ⏮ goes to the part before (as src/podcast/model.ts chapterJump). */ + const RESTART_GRACE_S = 3 + + const PATHS = { + play: 'M5 3.5v13l11-6.5z', + pause: 'M5 3h3.5v14H5zM11.5 3H15v14h-3.5z', + prev: 'M4 3h2v14H4zM16 3v14L7 10z', + next: 'M14 3h2v14h-2zM4 3v14l9-7z', + } + function icon(name) { + const s = svgEl('svg', { viewBox: '0 0 20 20', width: 16, height: 16, 'aria-hidden': 'true' }) + s.append(svgEl('path', { d: PATHS[name], fill: 'currentColor' })) + return s + } + /** "Back 15" / "Forward 15": a curved arrow with the seconds in it. */ + function skipIcon(dir) { + const s = svgEl('svg', { viewBox: '0 0 20 20', width: 18, height: 18, 'aria-hidden': 'true' }) + const arc = dir < 0 ? 'M10 3.5a6.5 6.5 0 1 1-6.1 4.3' : 'M10 3.5a6.5 6.5 0 1 0 6.1 4.3' + const head = dir < 0 ? 'M10 1v5L6.5 3.5z' : 'M10 1v5l3.5-2.5z' + s.append(svgEl('path', { d: arc, fill: 'none', stroke: 'currentColor', 'stroke-width': 1.5 }), svgEl('path', { d: head, fill: 'currentColor' })) + const t = svgEl('text', { x: 10, y: 13.3, 'text-anchor': 'middle', 'font-size': 6.5, fill: 'currentColor' }) + t.textContent = String(SKIP_S) + s.append(t) + return s + } + function clock(t) { + const s = Math.max(0, Math.floor(t || 0)) + const h = Math.floor(s / 3600), m = Math.floor((s % 3600) / 60), r = s % 60 + return `${h ? `${h}:` : ''}${h ? String(m).padStart(2, '0') : m}:${String(r).padStart(2, '0')}` + } + const reduced = () => window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches + + window.JourneyPodcast = function (opts) { + const { post } = opts + const audio = el('audio') + audio.preload = 'metadata' + const root = el('div', 'pod') + root.setAttribute('role', 'region') + root.setAttribute('aria-label', 'Podcast') + root.hidden = true + + // The timeline: one bar per part (step), filled as it plays; a thumb; the hover tip. + const tl = el('div', 'pod-tl') + tl.tabIndex = 0 + tl.setAttribute('role', 'slider') + tl.setAttribute('aria-label', 'Position') + const track = el('div', 'pod-track') + const thumb = el('div', 'pod-thumb') + const tip = el('div', 'pod-tip') + tip.hidden = true + tl.append(track, thumb, tip) + + const btn = (cls, label, child, onClick) => { + const b = el('button', `pod-b ${cls}`) + b.title = label + b.setAttribute('aria-label', label) + b.append(child) + b.onclick = onClick + return b + } + const prevB = btn('prev', 'Previous step', icon('prev'), () => part(-1)) + const backB = btn('back', `Back ${SKIP_S} s (←)`, skipIcon(-1), () => skip(-SKIP_S)) + const playB = btn('play', 'Play (Space)', icon('play'), () => toggle()) + const fwdB = btn('fwd', `Forward ${SKIP_S} s (→)`, skipIcon(1), () => skip(SKIP_S)) + const nextB = btn('next', 'Next step', icon('next'), () => part(1)) + const time = el('span', 'pod-time') + const rateB = el('button', 'pod-rate', '1×') + rateB.title = 'Speed' + rateB.onclick = () => setRate(RATES[(RATES.indexOf(audio.playbackRate) + 1) % RATES.length] || 1) + const cap = el('div', 'pod-cap') + const err = el('span', 'pod-err') + err.hidden = true + const row = el('div', 'pod-row') + const ctl = el('div', 'pod-ctl') + ctl.append(prevB, backB, playB, fwdB, nextB) + row.append(ctl, time, err, rateB) + root.append(tl, row, cap, audio) + document.body.append(root) + + /** The episode shown ({ src, duration, chapters: [{ start, end, step }], segments: [{ start, end, text, step }] }). */ + let ep + /** The chapter bars ({ el, fill, c }). */ + let bars = [] + /** A drag on the timeline: the time it would seek to (undefined: none). */ + let dragT + /** The time to seek to once the audio can (an episode set before its metadata). */ + let startAt = 0 + let boundaryTimer = 0 + let frame = 0 + /** Play was refused for want of a click or key here: ▶ takes the keyboard when the panel gets it. */ + let askFocus = false + window.addEventListener('focus', () => { if (askFocus) playB.focus({ preventScroll: true }) }) + + const duration = () => (Number.isFinite(audio.duration) && audio.duration > 0 ? audio.duration : (ep && ep.duration) || 0) + const now = () => (dragT !== undefined ? dragT : audio.currentTime || 0) + const playing = () => !audio.paused && !audio.ended + const chapterAt = (t) => { + if (!ep) return -1 + const cs = ep.chapters + for (let i = cs.length - 1; i >= 0; i--) if (t >= cs[i].start) return i + return 0 + } + const segAt = (t) => { + if (!ep || !ep.segments.length) return -1 + const ss = ep.segments + for (let i = ss.length - 1; i >= 0; i--) if (t >= ss[i].start) return i + return 0 + } + /** What a part is called on the tip and to a screen reader: "3 · title", or Intro / Map / Recap. */ + function partName(i) { + const c = ep.chapters[i] + if (c.step) return `${c.step} · ${opts.stepTitle(c.step) || `Step ${c.step}`}` + if (i === 0) return 'Intro' + return i === ep.chapters.length - 1 ? 'Recap' : 'Map' + } + + function report(seek) { + if (!ep) return + post({ type: 'podcastTime', t: audio.currentTime || 0, playing: playing(), rate: audio.playbackRate, ...(seek ? { seek: true } : {}) }) + scheduleBoundary() + } + /** Says where the audio is again right as the next segment starts (timeupdate comes only every ~250 ms). */ + function scheduleBoundary() { + clearTimeout(boundaryTimer) + if (!ep || !playing()) return + const t = audio.currentTime + const next = ep.segments.find((s) => s.start > t + 0.01) + if (!next) return + const ms = ((next.start - t) / (audio.playbackRate || 1)) * 1000 + 20 + boundaryTimer = setTimeout(() => report(false), Math.max(20, ms)) + } + + function seek(t) { + if (!ep) return + const d = duration() + const to = Math.max(0, Math.min(d ? d - 0.05 : t, t)) + if (audio.readyState < 1) startAt = to + else audio.currentTime = to + draw() + // Said at once: the journey moves now, not once the audio has the new place buffered. + post({ type: 'podcastTime', t: to, playing: playing(), rate: audio.playbackRate, seek: true }) + scheduleBoundary() + } + const skip = (by) => seek(now() + by) + function part(dir) { + if (!ep) return + const t = now() + const cs = ep.chapters + const i = chapterAt(t) + if (dir > 0) seek(i + 1 < cs.length ? cs[i + 1].start : duration()) + else seek(t - cs[i].start > RESTART_GRACE_S || i === 0 ? cs[i].start : cs[i - 1].start) + } + function play() { + if (!ep) return + if (audio.ended) seek(0) + const p = audio.play() + if (p && p.catch) p.catch((e) => { + // VS Code's webviews play audio only after a click or a key in them (once per panel): ▶ takes the keyboard. + const gesture = e && e.name === 'NotAllowedError' + showError(gesture ? 'Press Space to play' : `Can't play: ${e && e.message}`) + if (gesture) { askFocus = true; playB.focus({ preventScroll: true }) } + post({ type: 'podcastError', message: String(e && (e.name || e.message)) }) + }) + } + const toggle = () => (playing() ? audio.pause() : play()) + function setRate(r) { + audio.playbackRate = r + audio.defaultPlaybackRate = r + } + function showError(text) { + err.textContent = text + err.hidden = !text + } + + // ---------- drawing ---------- + + function build() { + track.textContent = '' + bars = [] + const d = duration() || 1 + for (const [i, c] of ep.chapters.entries()) { + const b = el('div', `pod-bar${c.step ? '' : ' map'}`) + b.style.left = `${(c.start / d) * 100}%` + b.style.width = `${(Math.max(0, Math.min(c.end, d) - c.start) / d) * 100}%` + const fill = el('div', 'pod-fill') + b.append(fill) + b.dataset.i = String(i) + track.append(b) + bars.push({ el: b, fill, c }) + } + } + + function draw() { + if (!ep) return + const d = duration() || 1 + const t = now() + const ci = chapterAt(t) + for (const [i, b] of bars.entries()) { + const c = b.c + const f = Math.max(0, Math.min(1, (t - c.start) / Math.max(0.001, Math.min(c.end, d) - c.start))) + b.fill.style.width = `${f * 100}%` + b.el.classList.toggle('cur', i === ci) + } + thumb.style.left = `${(Math.min(t, d) / d) * 100}%` + time.textContent = `${clock(t)} / ${clock(d)}` + const on = playing() + if (playB.dataset.on !== String(on)) { + playB.dataset.on = String(on) + playB.textContent = '' + playB.append(icon(on ? 'pause' : 'play')) + playB.title = on ? 'Pause (Space)' : 'Play (Space)' + playB.setAttribute('aria-label', on ? 'Pause' : 'Play') + root.classList.toggle('on', on) + } + rateB.textContent = `${audio.playbackRate}×` + tl.setAttribute('aria-valuemin', '0') + tl.setAttribute('aria-valuemax', String(Math.round(d))) + tl.setAttribute('aria-valuenow', String(Math.round(t))) + tl.setAttribute('aria-valuetext', `${clock(t)}, ${ci >= 0 ? partName(ci) : ''}`) + const si = segAt(t) + const text = si >= 0 ? ep.segments[si].text : '' + if (cap.textContent !== text) { cap.textContent = text; cap.title = text } + } + + /** Smooth while playing and on screen; timeupdate draws otherwise. */ + function tick() { + cancelAnimationFrame(frame) + if (!playing() || reduced()) return + frame = requestAnimationFrame(() => { draw(); tick() }) + } + + // ---------- the timeline: hover, click, drag, keys ---------- + + const timeAtX = (x) => { + const r = track.getBoundingClientRect() + return (Math.max(0, Math.min(r.width, x - r.left)) / (r.width || 1)) * duration() + } + function showTip(t, x) { + const i = chapterAt(t) + tip.textContent = '' + tip.append(el('b', '', partName(i)), el('span', '', clock(t))) + tip.hidden = false + const r = tl.getBoundingClientRect() + const w = tip.offsetWidth + tip.style.left = `${Math.max(0, Math.min(r.width - w, x - r.left - w / 2))}px` + } + tl.addEventListener('pointermove', (e) => { + if (!ep) return + const t = timeAtX(e.clientX) + showTip(t, e.clientX) + if (dragT !== undefined) { dragT = t; draw() } + }) + tl.addEventListener('pointerleave', () => { if (dragT === undefined) tip.hidden = true }) + tl.addEventListener('pointerdown', (e) => { + if (!ep || e.button !== 0) return + e.preventDefault() + tl.setPointerCapture(e.pointerId) + tl.focus({ preventScroll: true }) + dragT = timeAtX(e.clientX) + root.classList.add('dragging') + draw() + }) + const endDrag = (commit) => { + if (dragT === undefined) return + const t = dragT + dragT = undefined + root.classList.remove('dragging') + tip.hidden = true + if (commit) seek(t) + else draw() + } + tl.addEventListener('pointerup', () => endDrag(true)) + tl.addEventListener('pointercancel', () => endDrag(false)) + tl.addEventListener('lostpointercapture', () => endDrag(true)) + tl.addEventListener('keydown', (e) => { + if (e.altKey || e.ctrlKey || e.metaKey) return + runKey(e, { + Escape: dragT !== undefined && (() => endDrag(false)), + Home: () => seek(0), + End: () => seek(duration()), + PageUp: () => part(-1), + PageDown: () => part(1), + }, true) + }) + + // Space / K play and pause, ← → skip, Shift+← → a step: in the bar, or with nothing else focused (a focused + // button presses itself; the animation and the map keep their own arrows). + document.addEventListener('keydown', (e) => { + if (!ep || e.defaultPrevented || e.altKey || e.ctrlKey || e.metaKey) return + const target = e.target + const inBar = root.contains(target) + const free = target === document.body || target === document.documentElement || !target + if (!inBar && !free) return + const onButton = target && target.tagName === 'BUTTON' + runKey(e, { + ' ': !onButton && toggle, + k: toggle, + ArrowLeft: () => (e.shiftKey ? part(-1) : skip(-SKIP_S)), + ArrowRight: () => (e.shiftKey ? part(1) : skip(SKIP_S)), + }, true) + }) + + // ---------- the audio ---------- + + audio.addEventListener('loadedmetadata', () => { + if (startAt) { audio.currentTime = Math.min(startAt, duration()); startAt = 0 } + build() + draw() + }) + audio.addEventListener('timeupdate', () => { if (dragT === undefined) draw(); report(false) }) + audio.addEventListener('play', () => { askFocus = false; showError(''); draw(); tick(); report(false) }) + audio.addEventListener('pause', () => { draw(); report(false) }) + audio.addEventListener('ended', () => { draw(); report(false) }) + audio.addEventListener('ratechange', () => { draw(); report(false) }) + audio.addEventListener('error', () => { + const e = audio.error + showError("Can't play the audio") + post({ type: 'podcastError', message: `audio error ${e ? e.code : '?'}${e && e.message ? `: ${e.message}` : ''}` }) + }) + + // The bar's height, for the panel's layout (the map's column and the page's end stay clear of it). + // Set a frame later, and only when it changed: set inside the observer it resized the map, whose own observer then + // looped ("ResizeObserver loop completed with undelivered notifications"). + let podH = '' + new ResizeObserver(() => requestAnimationFrame(() => { + const h = root.hidden ? '0px' : `${root.offsetHeight}px` + if (h === podH) return + podH = h + document.documentElement.style.setProperty('--podH', h) + })).observe(root) + + return { + el: root, + /** The journey's episode (none: the bar goes; the same audio again keeps playing). */ + set(e) { + if (!e) { + if (ep) { audio.pause(); audio.removeAttribute('src'); audio.load() } + ep = undefined + root.hidden = true + document.body.classList.remove('has-pod') + podH = '0px' + document.documentElement.style.setProperty('--podH', '0px') + if (opts.onShown) opts.onShown(false) + return + } + const same = ep && ep.src === e.src + ep = e + root.hidden = false + document.body.classList.add('has-pod') + if (!same) { + showError('') + startAt = e.at || 0 + setRate(RATES.includes(e.rate) ? e.rate : 1) + audio.src = e.src + audio.load() + } + build() + draw() + if (opts.onShown) opts.onShown(true) + }, + cmd(m) { + if (!ep) return + const actions = { + play, toggle, + pause: () => audio.pause(), + skip: () => skip(Number(m.by) || 0), + seek: () => seek(Number(m.to) || 0), + part: () => part(m.dir < 0 ? -1 : 1), + rate: () => setRate(Number(m.rate) || 1), + } + if (Object.hasOwn(actions, m.action)) actions[m.action]() + }, + /** For tests: the audio's state. */ + get state() { return { t: audio.currentTime, playing: playing(), paused: audio.paused, ready: audio.readyState, duration: duration(), error: err.hidden ? '' : err.textContent } }, + get shown() { return !!ep }, + /** The journey's titles changed (another journey of the same id, a rename): the tip and labels follow. */ + redraw() { if (ep) draw() }, + } + } +})() diff --git a/media/journey-scene.js b/media/journey-scene.js index 83cf13c..39f775c 100644 --- a/media/journey-scene.js +++ b/media/journey-scene.js @@ -503,7 +503,8 @@ /** play(): a beat is held READ_MS, and READ_MS_PER_CHAR for each character of its caption (videos). */ const READ_MS = 1600, READ_MS_PER_CHAR = 55 - /** opts: { onBeat(i), onClose(), onNextStep?(), height? }. `onNextStep`: at the last beat › becomes "Next step ›". */ + /** opts: { onBeat(i, how), onClose(), onNextStep?(), height? }. `how`: 'go' when the beat was moved to (‹ ›, the keys, + * go()), else it came with the scene shown. `onNextStep`: at the last beat › becomes "Next step ›". */ function create(opts) { opts = opts || {} const { root, prev, next, pos, file, close, view, world, cap, codeEl } = playerEl() @@ -625,14 +626,15 @@ next.disabled = false } - function go(i, quiet) { + /** To beat i; `quiet`: drawn again even when it is the beat shown; `still`: without the beat's flight (a jump). */ + function go(i, quiet, still) { if (!scene) return const n = Math.max(0, Math.min(scene.beats.length - 1, i)) - const fwd = n === beat + 1 + const fwd = !still && n === beat + 1 if (n === beat && !quiet) return beat = n apply(fwd) - if (opts.onBeat) opts.onBeat(beat) + if (opts.onBeat) opts.onBeat(beat, 'go') } prev.onclick = () => go(beat - 1) @@ -659,7 +661,8 @@ code(c) { showCode(codeEl, c) }, get count() { return scene ? scene.beats.length : 0 }, /** Shows a scene; the same key again keeps the beat (a re-render), another starts at `o.beat` (or its first). - * o: { file: the step's file (a beat in another file names it), next: there is a next step, beat }. */ + * o: { file: the step's file (a beat in another file names it), next: there is a next step, beat, still: shown + * without its flight }. */ show(s, k, o) { o = o || {} const same = k === key && !!scene @@ -672,7 +675,7 @@ showCode(codeEl, undefined) beat = Math.max(0, Math.min(s.beats.length - 1, o.beat || 0)) build() - apply(true) + apply(!o.still) if (opts.onBeat) opts.onBeat(beat) }, go, diff --git a/package.json b/package.json index 799f89b..f787a05 100644 --- a/package.json +++ b/package.json @@ -449,6 +449,27 @@ "title": "Play or Stop the Step's Animation", "category": "Code Notes" }, + { + "command": "codeNotes.playPodcast", + "title": "Play Journey Podcast", + "category": "Code Notes", + "icon": "$(play)" + }, + { + "command": "codeNotes.podcastToggle", + "title": "Play or Pause the Journey Podcast", + "category": "Code Notes" + }, + { + "command": "codeNotes.podcastBack", + "title": "Journey Podcast: Back 15 Seconds", + "category": "Code Notes" + }, + { + "command": "codeNotes.podcastForward", + "title": "Journey Podcast: Forward 15 Seconds", + "category": "Code Notes" + }, { "command": "codeNotes.checkUnderstanding", "title": "Check my understanding", @@ -598,6 +619,48 @@ "prefix": "<" } }, + { + "command": "codeNotes.podcastToggle", + "key": "ctrl+[IntlBackslash] ctrl+space", + "args": { + "prefix": "<" + } + }, + { + "command": "codeNotes.podcastToggle", + "key": "ctrl+[IntlBackslash] space", + "args": { + "prefix": "<" + } + }, + { + "command": "codeNotes.podcastBack", + "key": "ctrl+[IntlBackslash] ctrl+left", + "args": { + "prefix": "<" + } + }, + { + "command": "codeNotes.podcastBack", + "key": "ctrl+[IntlBackslash] left", + "args": { + "prefix": "<" + } + }, + { + "command": "codeNotes.podcastForward", + "key": "ctrl+[IntlBackslash] ctrl+right", + "args": { + "prefix": "<" + } + }, + { + "command": "codeNotes.podcastForward", + "key": "ctrl+[IntlBackslash] right", + "args": { + "prefix": "<" + } + }, { "command": "codeNotes.add", "key": "ctrl+' ctrl+c", @@ -696,6 +759,48 @@ "prefix": "'" } }, + { + "command": "codeNotes.podcastToggle", + "key": "ctrl+' ctrl+space", + "args": { + "prefix": "'" + } + }, + { + "command": "codeNotes.podcastToggle", + "key": "ctrl+' space", + "args": { + "prefix": "'" + } + }, + { + "command": "codeNotes.podcastBack", + "key": "ctrl+' ctrl+left", + "args": { + "prefix": "'" + } + }, + { + "command": "codeNotes.podcastBack", + "key": "ctrl+' left", + "args": { + "prefix": "'" + } + }, + { + "command": "codeNotes.podcastForward", + "key": "ctrl+' ctrl+right", + "args": { + "prefix": "'" + } + }, + { + "command": "codeNotes.podcastForward", + "key": "ctrl+' right", + "args": { + "prefix": "'" + } + }, { "command": "codeNotes.cancelMove", "key": "escape", @@ -955,6 +1060,11 @@ "command": "codeNotes.refreshJourney", "group": "inline@1", "when": "view == codeNotes.journeys && viewItem =~ /^journey;stale/" + }, + { + "command": "codeNotes.playPodcast", + "group": "inline@0", + "when": "view == codeNotes.journeys && viewItem =~ /^journey.*;podcast/" } ], "commandPalette": [ @@ -1425,6 +1535,7 @@ "test:checkpanel": "node test/check-panel/shoot.mjs", "test:checktour": "node test/check-tour/shoot.mjs", "test:journeylist": "node test/journey-list/shoot.mjs", + "test:podcast": "node test/journey-podcast/shoot.mjs", "test:grader": "node test/grader/eval.mjs" }, "devDependencies": { diff --git a/src/extension.ts b/src/extension.ts index 163f29e..532622d 100644 --- a/src/extension.ts +++ b/src/extension.ts @@ -49,6 +49,7 @@ import { backToStep, endJourney, openJourney, openStepLink, restoreMapPanel, res import { pickJourneyStep } from './tour/lenses' import { registerRefPages } from './tour/refs' import { createCard, createTourItems, stepDetails, walk } from './tour/instances' +import { podcasts } from './podcast/player' import { tutorial } from './tour/tutorial' import { TutorialSpot } from './tutorialSpot' import { ValueHints } from './valueHints' @@ -127,6 +128,7 @@ function createTourUi(context: vscode.ExtensionContext): () => void { setCtx('codeNotes.showResolved', false) rememberMe() context.subscriptions.push(log, store, controller, treeView, askStatusItem, moveItem, ...Object.values(deco), journeys, mapPanel, ...Object.values(tourItems)) + podcasts.init(context) return journeysLoaded } @@ -246,6 +248,10 @@ function registerCommands(context: vscode.ExtensionContext): void { 'codeNotes.openStepLink': openStepLink, 'codeNotes.toggleAuthorMode': toggleAuthorMode, 'codeNotes.toggleAnimation': chord(toggleAnimation), + 'codeNotes.playPodcast': (arg?: unknown) => podcasts.play(arg), + 'codeNotes.podcastToggle': chord(() => podcasts.toggle()), + 'codeNotes.podcastBack': chord(() => podcasts.back()), + 'codeNotes.podcastForward': chord(() => podcasts.forward()), 'codeNotes.askQuestion': askQuestion, 'codeNotes.backToStep': backToStep, 'codeNotes.askStep': (text?: string) => askStep(text), diff --git a/src/journeys/journeys.ts b/src/journeys/journeys.ts index f5c8438..270c6fe 100644 --- a/src/journeys/journeys.ts +++ b/src/journeys/journeys.ts @@ -6,6 +6,7 @@ import { jsonFilesIn, jsonName, readText, watchJsonFiles } from '../jsonFolder' import { LoadedJourney, carryPositions, posKey, writtenAt } from './steps' import { pathIn, settingFolder } from '../paths' import { StepTracker } from './tracker' +import { isPodcastFile } from '../podcast/model' // Journeys (format v2, docs/journey-format.md): /journeys/.json (codeNotes.journeys.folder: committed, // shared) and, as before, /journeys/.json (personal); steps embedded. A step is not a note. This @@ -116,6 +117,7 @@ export class Journeys extends StepTracker { /** A journey file deleted. */ private gone(u: vscode.Uri): void { + if (isPodcastFile(u.path)) { this.changed.fire(); return } const listed = this.list.delete(u.toString()) const invalid = this.invalid.delete(u.toString()) if (listed || invalid) this.changed.fire() @@ -145,6 +147,8 @@ export class Journeys extends StepTracker { /** 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 { + // 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() const raw = await readText(uri) if (raw === undefined) { diff --git a/src/journeys/mapPanel.ts b/src/journeys/mapPanel.ts index dc0fb6a..4879ed1 100644 --- a/src/journeys/mapPanel.ts +++ b/src/journeys/mapPanel.ts @@ -4,6 +4,8 @@ import type { StepCard } from '../tour/card' import { escapeHtml, webviewPage } from '../webview/page' import { fileName } from '../jsonFolder' import { LoadedJourney } from './steps' +import { journeysFolderName } from './journeys' +import { folderName } from '../store' // The journey panel: one journey's map and storyline (or the Journeys list) in a webview beside the editor, and the // messages between it and media/journey-map.js. @@ -34,7 +36,10 @@ export type MapMessage = | { type: 'openFile' } | { type: 'ref'; i: number } | { type: 'details'; open: boolean } - | { type: 'beat'; n: number; i: number } + | { type: 'beat'; n: number; i: number; user?: boolean } + // The podcast's bar (media/journey-podcast.js): where the audio is, and what went wrong. + | { type: 'podcastTime'; t: number; playing: boolean; rate?: number; seek?: boolean } + | { type: 'podcastError'; message: string } | { type: 'ask'; update?: boolean } | { type: 'restore' } | { type: 'authors' } @@ -121,6 +126,9 @@ export class MapPanel implements vscode.Disposable { focus = '' private ready = false private queue: unknown[] = [] + /** The journey's podcast for the panel's bar (src/podcast/player.ts): undefined when it has none. `toUri`: a file + * as the webview loads it. */ + podcastFor: ((lj: LoadedJourney, toUri: (u: vscode.Uri) => string) => unknown) | undefined constructor(private extensionUri: vscode.Uri, private log: vscode.LogOutputChannel, private onMessage: (lj: LoadedJourney, m: MapMessage) => void, private tourOf: (lj: LoadedJourney) => TourInfo, private state: vscode.Memento) {} @@ -169,6 +177,10 @@ export class MapPanel implements vscode.Disposable { private options(): vscode.WebviewPanelOptions & vscode.WebviewOptions { const roots = [vscode.Uri.joinPath(this.extensionUri, 'media'), vscode.Uri.joinPath(this.extensionUri, 'out', 'src'), vscode.Uri.joinPath(this.extensionUri, 'out', 'vendor')] + // A podcast's audio: next to its journey, in the journeys folders (and below them). + for (const f of vscode.workspace.workspaceFolders ?? []) { + for (const rel of new Set([journeysFolderName(), `${folderName()}/journeys`])) roots.push(vscode.Uri.joinPath(f.uri, rel)) + } // Ctrl+F finds words in the map and the storyline. return { enableScripts: true, enableFindWidget: true, localResourceRoots: roots, retainContextWhenHidden: true } } @@ -306,12 +318,21 @@ export class MapPanel implements vscode.Disposable { if (!all && sig === this.lastTour) return this.lastTour = sig void this.panel.webview.postMessage(all ? { type: 'journey', journey: this.shown.j, ...t } : { type: 'tour', ...t }) + if (all) this.sendPodcast() + } + + /** The shown journey's podcast to the bar (none: the bar goes). */ + sendPodcast(): void { + const panel = this.panel + if (!panel || !this.shown || !this.ready) return + const episode = this.podcastFor?.(this.shown, (u) => panel.webview.asWebviewUri(u).toString()) + void panel.webview.postMessage({ type: 'podcast', episode }) } private html(w: vscode.Webview, loading?: string): string { const file = (...p: string[]) => vscode.Uri.joinPath(this.extensionUri, ...p) return webviewPage(w, { - css: [file('media', 'common.css'), file('media', 'journey-map.css'), file('media', 'journey-home.css'), file('media', 'journey-scene.css')], + css: [file('media', 'common.css'), file('media', 'journey-map.css'), file('media', 'journey-home.css'), file('media', 'journey-scene.css'), file('media', 'journey-podcast.css')], body: `

${loading ? escapeHtml(loading) : 'Loading the map…'}

`, // journeyModel.js is a CommonJS module loaded as a plain script: it fills `exports`, which the page reads as // JourneyModel. @@ -321,9 +342,10 @@ export class MapPanel implements vscode.Disposable { file('out', 'src', 'journeyModel.js'), file('out', 'vendor', 'elk.bundled.js'), ...[ 'common', 'journey-layout', 'journey-farnames', 'journey-graph', 'code-paint', 'journey-scene', 'journey-scene-app', - 'journey-home', 'journey-splitter', 'journey-tutorial', 'journey-map', + 'journey-home', 'journey-splitter', 'journey-tutorial', 'journey-podcast', 'journey-map', ].map((name) => file('media', `${name}.js`)), ], + allow: { media: true }, }) } diff --git a/src/podcast/model.ts b/src/podcast/model.ts new file mode 100644 index 0000000..65d0bbb --- /dev/null +++ b/src/podcast/model.ts @@ -0,0 +1,243 @@ +// A journey's podcast (docs/podcast-format.md): one audio file whose parts are linked to the journey's steps and +// animation beats. This reads the file, checks it against the journey, and answers the one question the player asks +// all the time: at this second of the audio, where should the journey be? No vscode here: unit tests use it as is +// (test/podcast.test.ts), and the player (player.ts) applies what it says. + +/** Where a segment belongs in the journey, as written: null (the whole journey: the map), or a step by id, with the + * 1-based position of a beat in that step's `scene.beats`. */ +export type WrittenAt = null | { step: string; beat?: number } + +/** A segment as written in the file. */ +export interface WrittenSegment { + id?: string + at?: unknown + cue?: unknown + speaker?: unknown + text?: unknown + start?: unknown + end?: unknown +} + +/** The podcast file, checked for its shape only (parsePodcast). */ +export interface Podcast { + version: number + title: string + journey: { id: string; file?: string; commit?: string } + /** The audio file, relative to the podcast file. */ + audio: string + duration?: number + segments: WrittenSegment[] +} + +/** Where the journey is: on a step (1-based; 0: no step, the map) and, on a step, a beat of its animation (0-based; + * undefined: the step without its animation). */ +export interface View { step: number; beat?: number } + +/** A segment as the player uses it: its time, its text, and the view it shows. */ +export interface Segment extends View { + id: string + start: number + end: number + text: string + speaker: string +} + +/** A run of segments on the same step (or on the map): what the timeline marks. */ +export interface Chapter { start: number; end: number; step: number } + +/** A podcast resolved against its journey: every segment's view, in time order, and what did not match. */ +export interface Episode { + title: string + duration: number + segments: Segment[] + chapters: Chapter[] + /** What could not be followed (an unknown step, a beat the step does not have, …): said in the log. */ + warnings: string[] +} + +/** What the player needs of the journey: its steps' ids and how many beats each one's animation has. */ +export interface JourneyShape { steps: { id: string; beats: number }[] } + +/** The podcast file next to a journey file: `x.json` → `x.podcast.json`. */ +export const podcastFileOf = (journeyPath: string) => journeyPath.replace(/\.json$/i, '') + '.podcast.json' +/** A podcast file is never read as a journey. */ +export const isPodcastFile = (name: string) => /\.podcast\.json$/i.test(name) + +const isObj = (v: unknown): v is Record => !!v && typeof v === 'object' && !Array.isArray(v) +const num = (v: unknown) => (typeof v === 'number' && Number.isFinite(v) ? v : undefined) + +/** The file's text as a Podcast, or why it can't be one. Only the shape is checked; each segment is checked later. */ +export function parsePodcast(raw: string): Podcast | string { + let d: unknown + try { d = JSON.parse(raw) } catch (e) { return `not JSON: ${(e as Error).message}` } + if (!isObj(d)) return 'not an object' + if (d.version !== 1) return `version ${JSON.stringify(d.version)} (this player reads version 1)` + if (typeof d.audio !== 'string' || !d.audio.trim()) return 'no "audio" file' + if (!Array.isArray(d.segments) || !d.segments.length) return 'no "segments"' + const j = isObj(d.journey) ? d.journey : {} + return { + version: 1, + title: typeof d.title === 'string' ? d.title : '', + journey: { id: typeof j.id === 'string' ? j.id : '', file: typeof j.file === 'string' ? j.file : undefined, commit: typeof j.commit === 'string' ? j.commit : undefined }, + audio: d.audio, + duration: num(d.duration), + segments: d.segments.filter(isObj) as WrittenSegment[], + } +} + +/** + * The podcast against its journey. Each segment's `at` becomes a view; one the journey can't show degrades instead + * of breaking the episode: a beat the step doesn't have (beats are linked by position) shows the step only; an + * unknown step, or an `at` that isn't one, keeps the view of the segment before it. `cue: "map"` on a step shows the + * step without its animation. Segments without a usable start are dropped; a missing end is the next one's start. + */ +export function resolveEpisode(p: Podcast, journey: JourneyShape): Episode { + const warnings: string[] = [] + const byId = new Map(journey.steps.map((s, i) => [s.id, { n: i + 1, beats: s.beats }])) + const timed = p.segments + .map((s, i) => ({ s, i, start: num(s.start) })) + .filter((x) => { + const ok = x.start !== undefined && x.start >= 0 + if (!ok) warnings.push(`segment ${x.s.id ?? x.i + 1}: no start time; skipped`) + return ok + }) + .sort((a, b) => a.start! - b.start! || a.i - b.i) + let prev: View = { step: 0 } + const segments: Segment[] = timed.map((x, k) => { + const id = typeof x.s.id === 'string' ? x.s.id : `#${x.i + 1}` + const view = viewOf(x.s, id, byId, prev, warnings) + prev = view + const next = timed[k + 1]?.start + const end = num(x.s.end) ?? next ?? num(p.duration) ?? x.start! + return { id, start: x.start!, end: Math.max(end, x.start!), text: typeof x.s.text === 'string' ? x.s.text : '', speaker: typeof x.s.speaker === 'string' ? x.s.speaker : '', ...view } + }) + const last = segments[segments.length - 1] + const duration = Math.max(num(p.duration) ?? 0, last ? last.end : 0) + return { title: p.title, duration, segments, chapters: chaptersOf(segments, duration), warnings } +} + +/** One segment's view (see resolveEpisode); `prev`: the view before it. */ +function viewOf(s: WrittenSegment, id: string, byId: Map, prev: View, warnings: string[]): View { + const at = s.at + if (at === null) return { step: 0 } + if (!isObj(at) || typeof at.step !== 'string') { + warnings.push(`segment ${id}: "at" is ${at === undefined ? 'missing' : 'not null or { step, beat }'}; it keeps the view before it`) + return prev + } + const st = byId.get(at.step) + if (!st) { + warnings.push(`segment ${id}: no step "${at.step}" in the journey; it keeps the view before it`) + return prev + } + if (at.beat === undefined || s.cue === 'map') return { step: st.n } + const b = at.beat + if (typeof b !== 'number' || !Number.isInteger(b) || b < 1 || b > st.beats) { + warnings.push(`segment ${id}: step "${at.step}" has no beat ${JSON.stringify(b)} (it has ${st.beats}); the step only`) + return { step: st.n } + } + return { step: st.n, beat: b - 1 } +} + +/** Runs of segments on one step (or on the map); the first starts at 0, each ends where the next starts. */ +export function chaptersOf(segments: Segment[], duration: number): Chapter[] { + const out: Chapter[] = [] + for (const s of segments) { + const last = out[out.length - 1] + if (last && last.step === s.step) continue + if (last) last.end = s.start + out.push({ start: out.length ? s.start : 0, end: duration, step: s.step }) + } + return out +} + +/** The index of the segment playing at second `t`: the last one started by then (before the first: the first; + * between two: the one before the gap). -1: no segments. */ +export function segmentAt(segments: { start: number }[], t: number): number { + if (!segments.length) return -1 + let lo = 0, hi = segments.length - 1 + if (t < segments[0].start) return 0 + while (lo < hi) { + const mid = (lo + hi + 1) >> 1 + if (segments[mid].start <= t) lo = mid + else hi = mid - 1 + } + return lo +} + +/** Where the journey should be at second `t` (any `t`: before the start, past the end), and the segment saying it. */ +export function viewAt(ep: Episode, t: number): View & { seg: number } { + const i = segmentAt(ep.segments, t) + if (i < 0) return { seg: -1, step: 0 } + const s = ep.segments[i] + return s.beat === undefined ? { seg: i, step: s.step } : { seg: i, step: s.step, beat: s.beat } +} + +export const sameView = (a: View | undefined, b: View | undefined) => !!a && !!b && a.step === b.step && a.beat === b.beat + +/** + * Where the audio goes when the reader moves the journey themselves: the first segment on step `step` (with `beat`: + * the first on that beat). Undefined: the podcast says nothing there (a beat no segment names, a step it skips). + */ +export function timeOf(ep: Episode, step: number, beat?: number): number | undefined { + const s = ep.segments.find((x) => x.step === step && (beat === undefined || x.beat === beat)) + return s?.start +} + +/** Within this many seconds of a chapter's start, "previous" goes to the chapter before (as a music player's ⏮). */ +export const RESTART_GRACE_S = 3 + +/** The start of the chapter before (dir -1: this chapter's start, unless just past it) or after (dir 1) second `t`. */ +export function chapterJump(ep: Episode, t: number, dir: 1 | -1): number { + const cs = ep.chapters + if (!cs.length) return dir > 0 ? ep.duration : 0 + const i = Math.max(0, cs.findIndex((c, k) => t >= c.start && (t < c.end || k === cs.length - 1))) + if (dir > 0) return i + 1 < cs.length ? cs[i + 1].start : ep.duration + return t - cs[i].start > RESTART_GRACE_S || i === 0 ? cs[i].start : cs[i - 1].start +} + +/** + * Runs `job` on the newest value only: one job at a time; values pushed while one runs replace each other, and only + * the last of them runs next (a drag across the timeline, keys held down: the journey moves once, to where it ended). + * `current(v)` tells a running job whether it is still the newest one (a superseded job stops early). + */ +export class LatestWins { + private running = false + private pending: { v: T } | undefined + private gen = 0 + constructor(private job: (v: T, current: () => boolean) => Promise) {} + + push(v: T): void { + this.gen++ + if (this.running) { this.pending = { v }; return } + void this.run(v) + } + + get busy(): boolean { return this.running } + + /** Settles once nothing runs or waits (tests). */ + async idle(): Promise { + while (this.running) await new Promise((r) => setTimeout(r, 5)) + } + + private async run(v: T): Promise { + this.running = true + let next: { v: T } | undefined = { v } + while (next) { + const mine = this.gen + const now = next.v + next = undefined + try { await this.job(now, () => mine === this.gen) } catch { /* the job logs its own errors */ } + next = this.pending + this.pending = undefined + } + this.running = false + } +} + +/** m:ss (h:mm:ss past an hour). */ +export function clock(t: number): string { + const s = Math.max(0, Math.floor(t)) + const h = Math.floor(s / 3600), m = Math.floor((s % 3600) / 60), r = s % 60 + const mm = h ? String(m).padStart(2, '0') : String(m) + return `${h ? `${h}:` : ''}${mm}:${String(r).padStart(2, '0')}` +} diff --git a/src/podcast/player.ts b/src/podcast/player.ts new file mode 100644 index 0000000..a48e19f --- /dev/null +++ b/src/podcast/player.ts @@ -0,0 +1,340 @@ +// Podcast mode: a journey with a podcast file next to it (`.podcast.json`, docs/podcast-format.md) plays in +// the journey panel (media/journey-podcast.js has the audio and the timeline), and the walk follows the voice: at +// every time the panel reports, the view at that time (model.ts viewAt) is applied the way a reader's own move is +// (walk.goToStep; the animation's beat set in the panel). A seek applies the view at the new time directly: never +// the cues in between, and only the newest of quick seeks (LatestWins). The other way round: the reader moving the +// walk (Next, Back, the map, a beat of the animation) moves the audio to the first part about it. + +import * as vscode from 'vscode' +import { gstate, journeys, log, mapPanel, state } from '../app' +import { LoadedJourney, posKey } from '../journeys/steps' +import { readText } from '../jsonFolder' +import { endJourney, openMap } from '../tour/commands' +import { tourState, walk } from '../tour/instances' +import { pickJourney } from '../tour/pick' +import { wfs } from '../workspaceFs' +import { journeysTree } from '../sidebar/journeysTree' +import { clock, Episode, LatestWins, parsePodcast, podcastFileOf, resolveEpisode, sameView, timeOf, View, viewAt } from './model' + +/** Workspace state: where each podcast was left (posKey -> seconds); global: the speed. */ +const POS_KEY = 'codeNotes.podcastPos' +const RATE_KEY = 'codeNotes.podcastRate' +/** While playing, where it is is stored this often (ms). */ +const SAVE_EVERY_MS = 5000 +const SKIP_S = 15 +/** After the podcast asks for a seek, the panel's reports of the old time are ignored for at most this long (ms). */ +const STALE_MS = 1500 + +/** A journey's podcast, read and checked against the journey. */ +interface Loaded { file: vscode.Uri; audio: vscode.Uri; ep: Episode; sig: string } + +/** What the panel sends about the audio (MapMessage podcastTime). */ +export interface TimeReport { t: number; playing: boolean; rate?: number; seek?: boolean } + +class Podcasts { + /** By journey key. */ + private eps = new Map() + private item: vscode.StatusBarItem | undefined + /** The journey whose podcast was played in the panel (its audio is there): the walk follows it. */ + private session: string | undefined + /** The audio as last reported. */ + private t = 0 + private playing = false + private lastSave = 0 + /** The view the podcast asked for last, and the beat it last set in the panel (undefined: none). */ + private want: View | undefined + private beatShown: number | undefined + /** Moves the podcast is making right now (the walk's changes meanwhile are its own). */ + private applying = 0 + private readonly mover = new LatestWins<{ lj: LoadedJourney; view: View; still: boolean }>((m, current) => this.move(m, current)) + /** Errors the panel reported, and how many moves the podcast made (tests read them). */ + lastError = '' + private moves = 0 + /** When the podcast last asked the panel to seek: until the panel says it did, its older reports are stale. */ + private seekSent = 0 + + init(context: vscode.ExtensionContext): void { + this.item = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Left, 49.25) + this.item.command = 'codeNotes.podcastToggle' + context.subscriptions.push(this.item, journeys.onDidChange(() => void this.scan())) + mapPanel.podcastFor = (lj, toUri) => this.episodeFor(lj, toUri) + walk.onMoved = () => this.walkMoved() + } + + has(lj: LoadedJourney): boolean { return this.eps.has(lj.key) } + episode(lj: LoadedJourney): Episode | undefined { return this.eps.get(lj.key)?.ep } + + /** Every journey's podcast read again (a journey or podcast file changed); the panel and the list follow. */ + async scan(): Promise { + const next = new Map() + for (const lj of journeys.all()) { + const l = await this.read(lj) + if (l) next.set(lj.key, l) + } + const sig = (m: Map) => [...m].map(([k, l]) => `${k}=${l.sig}`).join('\n') + const changed = sig(next) !== sig(this.eps) + this.eps = next + if (!changed) return + mapPanel.sendPodcast() + journeysTree?.refresh() + } + + /** The podcast next to `lj`'s file, when there is one and its audio is there. */ + private async read(lj: LoadedJourney): Promise { + const file = lj.uri.with({ path: podcastFileOf(lj.uri.path) }) + const raw = await readText(file) + if (raw === undefined) return undefined + const p = parsePodcast(raw) + if (typeof p === 'string') { + log.warn(`podcast ${file.fsPath}: not played: ${p}`) + return undefined + } + const audio = vscode.Uri.joinPath(file, '..', p.audio) + let size = 0 + try { size = (await wfs.stat(audio)).size } catch { + log.warn(`podcast ${file.fsPath}: its audio ${p.audio} isn't there`) + return undefined + } + if (p.journey.id && p.journey.id !== lj.j.id) log.info(`podcast ${file.fsPath}: written for journey "${p.journey.id}", played with "${lj.j.id}" (the file next to it)`) + const ep = resolveEpisode(p, { steps: lj.j.steps.map((s) => ({ id: s.id, beats: s.scene?.beats?.length ?? 0 })) }) + for (const w of ep.warnings) log.info(`podcast ${file.fsPath}: ${w}`) + return { file, audio, ep, sig: `${raw.length}:${size}:${JSON.stringify(ep.segments.map((s) => [s.start, s.step, s.beat]))}` } + } + + /** What the panel's bar gets for `lj` (undefined: no podcast). */ + private episodeFor(lj: LoadedJourney, toUri: (u: vscode.Uri) => string): unknown { + const l = this.eps.get(lj.key) + if (!l) return undefined + const { ep } = l + return { + src: toUri(l.audio), + title: ep.title, + duration: ep.duration, + at: this.positions()[posKey(lj)] ?? 0, + rate: gstate.get(RATE_KEY) ?? 1, + chapters: ep.chapters, + segments: ep.segments.map((s) => ({ start: s.start, end: s.end, text: s.text, step: s.step })), + } + } + + private positions(): Record { return state.get>(POS_KEY) ?? {} } + private savePos(lj: LoadedJourney, t: number): void { + this.lastSave = Date.now() + void state.update(POS_KEY, { ...this.positions(), [posKey(lj)]: Math.round(t * 10) / 10 }) + } + + // ---------- audio → journey ---------- + + /** The panel says where the audio is. Playing (or seeking), the walk goes where the podcast is at that time. */ + onTime(lj: LoadedJourney, m: TimeReport): void { + const l = this.eps.get(lj.key) + if (!l) return + const wasPlaying = this.playing + this.t = m.t + this.playing = m.playing + if (m.rate && m.rate !== gstate.get(RATE_KEY)) void gstate.update(RATE_KEY, m.rate) + if (m.playing) this.session = lj.key + if (this.session !== lj.key) return + // A report from before the seek just asked for (the walk would go back there for a moment): only the time. + if (m.seek) this.seekSent = 0 + else if (this.seekSent && Date.now() - this.seekSent < STALE_MS) { this.renderItem(); return } + if ((wasPlaying && !m.playing) || m.seek || Date.now() - this.lastSave > SAVE_EVERY_MS) this.savePos(lj, m.t) + this.renderItem() + // Paused and not moved: the walk is the reader's. + if (!m.playing && !m.seek) return + const v = viewAt(l.ep, m.t) + const view: View = v.beat === undefined ? { step: v.step } : { step: v.step, beat: v.beat } + if (sameView(view, this.want) && (this.mover.busy || this.shows(lj, view))) return + this.want = view + this.mover.push({ lj, view, still: !!m.seek }) + } + + /** The walk shows `v` now. */ + private shows(lj: LoadedJourney, v: View): boolean { + const onIt = walk.touring() && tourState.key === lj.key + if (!v.step) return !onIt + return onIt && tourState.step === v.step && this.beatShown === v.beat + } + + /** Puts the walk where the podcast is: the beat set first (the step then opens on it), then the step opened. */ + private async move(m: { lj: LoadedJourney; view: View; still: boolean }, current: () => boolean): Promise { + const { lj, view } = m + this.moves++ + this.applying++ + try { + if (!view.step) { + this.beatShown = undefined + mapPanel.send({ type: 'podcastBeat', n: 0, i: -1 }) + if (walk.touring() && tourState.key === lj.key) await endJourney() + return + } + this.beatShown = view.beat + mapPanel.send({ type: 'podcastBeat', n: view.step, i: view.beat ?? -1, ...(m.still ? { still: true } : {}) }) + if (!(walk.touring() && tourState.isAt(lj, view.step))) await walk.goToStep(lj, view.step, { focus: false }) + } catch (e) { + log.error(`podcast: ${e}`) + } finally { + this.applying-- + } + // A move of the reader's that came in meanwhile (ignored then): the audio goes there now. + if (current()) this.walkMoved(true) + } + + // ---------- journey → audio ---------- + + /** The walk moved (walk.updateTour). The reader's own move (not the podcast's): the audio goes to the first part + * about the step; a step it never talks about, or the walk ended, pauses it. */ + private walkMoved(afterMove = false): void { + const lj = this.sessionJourney() + if (!lj || this.applying || (this.mover.busy && !afterMove)) return + const l = this.eps.get(lj.key)! + const step = walk.touring() && tourState.key === lj.key ? tourState.step : 0 + if (step === (this.want?.step ?? -1)) return + if (!step || tourState.key !== lj.key) { + // Another journey, or the walk ended: the podcast stops; its place is kept. + this.want = { step: 0 } + if (tourState.key !== lj.key) this.session = undefined + this.command('pause') + this.renderItem() + return + } + const t = timeOf(l.ep, step) + if (t === undefined) { + this.want = { step } + this.command('pause') + vscode.window.setStatusBarMessage(`$(info) The podcast doesn't cover step ${step}`, 3000) + return + } + const v = viewAt(l.ep, t) + this.want = v.beat === undefined ? { step: v.step } : { step: v.step, beat: v.beat } + this.command('seek', { to: t }) + } + + /** A beat of the animation shown (the panel's `beat`). The reader's own (‹ › in the animation): the audio goes to + * the first part about that beat, when there is one. */ + onBeat(lj: LoadedJourney, n: number, i: number): void { + if (this.session !== lj.key || this.applying || this.mover.busy || i < 0 || n !== tourState.step || tourState.key !== lj.key) return + if (i === this.beatShown) return + this.beatShown = i + const t = timeOf(this.eps.get(lj.key)!.ep, n, i) + if (t === undefined) return + this.want = { step: n, beat: i } + this.command('seek', { to: t }) + } + + /** The panel closed: its audio is gone. */ + onClosed(): void { + const lj = this.sessionJourney() + if (lj) this.savePos(lj, this.t) + this.session = undefined + this.playing = false + this.want = undefined + this.renderItem() + } + + onError(message: string): void { + this.lastError = message + // Not started by a click or a key in the panel (VS Code's webviews need one, once): the panel takes the keyboard, + // its ▶ focused, so Space starts it. + if (message === 'NotAllowedError') { + mapPanel.takeFocus() + return + } + log.warn(`podcast: ${message}`) + } + + private sessionJourney(): LoadedJourney | undefined { + const lj = this.session ? journeys.list.get(this.session) : undefined + return lj && this.eps.has(lj.key) ? lj : undefined + } + + // ---------- commands ---------- + + private command(action: string, more: Record = {}): void { + if (action === 'seek') this.seekSent = Date.now() + mapPanel.send({ type: 'podcastCmd', action, ...more }) + } + + /** Play Journey Podcast: the journey (a row, a key; else the one walked or on the map; else picked) in the panel, playing. */ + async play(arg?: unknown): Promise { + const lj = await this.journeyFor(arg) + if (!lj) return + if (mapPanel.journey?.key !== lj.key) await openMap(lj) + else if (!mapPanel.visible) walk.showMap(lj, true) + this.session = lj.key + this.want = undefined + this.command('play') + } + + private async journeyFor(arg?: unknown): Promise { + if (arg !== undefined) { + const lj = await pickJourney(arg) + if (lj && !this.has(lj)) vscode.window.setStatusBarMessage(`$(info) ${lj.j.title} has no podcast`, 3000) + return lj && this.has(lj) ? lj : undefined + } + const here = [walk.tourJourney(), mapPanel.journey].find((x) => x && this.has(x)) + if (here) return here + const all = journeys.all().filter((x) => this.has(x)) + if (all.length <= 1) { + if (!all.length) vscode.window.setStatusBarMessage('$(info) No journey here has a podcast', 3000) + return all[0] + } + const pick = await vscode.window.showQuickPick(all.map((x) => ({ label: x.j.title, description: clock(this.eps.get(x.key)!.ep.duration), lj: x })), { placeHolder: 'Play a journey podcast' }) + return pick?.lj + } + + /** Space for the podcast: pause, or play (the session's journey; else as Play). */ + async toggle(): Promise { + if (this.sessionJourney() && mapPanel.journey?.key === this.session) { + this.command(this.playing ? 'pause' : 'play') + return + } + await this.play() + } + + skip(by: number): void { + if (!this.sessionJourney()) { + vscode.window.setStatusBarMessage('$(info) No podcast playing', 2000) + return + } + this.command('skip', { by }) + } + back(): void { this.skip(-SKIP_S) } + forward(): void { this.skip(SKIP_S) } + + // ---------- the status bar ---------- + + /** While a podcast is in the panel: ⏸ (playing) or ▶, where it is in the journey, the time. Click: pause / play. */ + private renderItem(): void { + const item = this.item + if (!item) return + const lj = this.sessionJourney() + if (!lj) { item.hide(); return } + const ep = this.eps.get(lj.key)!.ep + const v = viewAt(ep, this.t) + const where = v.step ? `${v.step}/${lj.j.steps.length}` : mapPartName(ep, this.t) + item.text = `${this.playing ? '$(debug-pause)' : '$(play)'} ${where} · ${clock(this.t)}` + item.tooltip = `${lj.j.title}: ${this.playing ? 'pause' : 'play'} the podcast (${clock(this.t)} of ${clock(ep.duration)})` + item.accessibilityInformation = { label: `Podcast ${this.playing ? 'playing' : 'paused'}, ${v.step ? `step ${v.step}` : where}, ${clock(this.t)}. ${this.playing ? 'Pause' : 'Play'}.` } + item.show() + } + + /** For tests. */ + snapshot() { + const lj = this.sessionJourney() + return { + journeys: journeys.all().filter((x) => this.has(x)).map((x) => x.j.id), + session: lj?.j.id, t: this.t, playing: this.playing, want: this.want, beatShown: this.beatShown, applying: this.applying, + item: this.item?.text, itemShown: !!lj, error: this.lastError, moves: this.moves, mapVisible: mapPanel.visible, + } + } +} + +/** A part on the map (no step) by where it is: the first is the intro, the last the recap. */ +function mapPartName(ep: Episode, t: number): string { + const i = ep.chapters.findIndex((c, k) => t < c.end || k === ep.chapters.length - 1) + if (i <= 0) return 'Intro' + return i === ep.chapters.length - 1 ? 'Recap' : 'Map' +} + +export const podcasts = new Podcasts() diff --git a/src/sidebar/journeyRows.ts b/src/sidebar/journeyRows.ts index f005df7..a38873c 100644 --- a/src/sidebar/journeyRows.ts +++ b/src/sidebar/journeyRows.ts @@ -18,6 +18,7 @@ import { activeRel, listModel, listState, staleCount, staleLine } from './listMo import { badJourneyNodes, cached, jgroupNode, journeyNode, journeyRowNode, Node, noteNode, order } from './nodes' import { matchesFilter } from './notesFilter' import { fileName } from '../jsonFolder' +import { podcasts } from '../podcast/player' /** Every journey's row, then the journey files that can't be read. */ export const journeyRows = (): Node[] => [...journeys.all().map(journeyNode), ...badJourneyNodes()] @@ -113,7 +114,7 @@ export function journeyItem(lj: LoadedJourney, group?: string): vscode.TreeItem item.tooltip = journeyTooltip(lj, s) // The name read is the title and its state; the question is only the tooltip. item.accessibilityInformation = { label: journeyLabel(lj, s) } - item.contextValue = staleCount(lj) ? 'journey;stale' : 'journey' + item.contextValue = (staleCount(lj) ? 'journey;stale' : 'journey') + (podcasts.has(lj) ? ';podcast' : '') item.command = { command: 'codeNotes.openJourney', title: 'Walk Journey', arguments: [lj.key] } return item } diff --git a/src/testApi.ts b/src/testApi.ts index 649f72a..2d44953 100644 --- a/src/testApi.ts +++ b/src/testApi.ts @@ -24,6 +24,7 @@ import { choosing, confirming } from './write/rank' import { requestLog } from './write/requests' import { writeJourney } from './write/writeJourney' import { writingRows } from './write/inProgress' +import { podcasts } from './podcast/player' /** What `activate` returns (src/extension.ts): the integration tests import this type, not `any`. */ export type TestApi = ReturnType @@ -148,6 +149,8 @@ export function testApi() { mementos: () => [state, gstate], /** Sends a message into the map webview (tests drive its real click/key handlers this way). */ mapSend: (m: unknown) => mapPanel.send(m), + /** The podcast (src/podcast/player.ts): which journeys have one, where the audio is, what it last moved. */ + podcast: () => podcasts.snapshot(), resetTutorial, /** Forgets the tour in memory and restores it from workspace state, as after a window reload. */ reloadTour: async () => { diff --git a/src/tour/mapMessages.ts b/src/tour/mapMessages.ts index c52a264..1255c12 100644 --- a/src/tour/mapMessages.ts +++ b/src/tour/mapMessages.ts @@ -22,6 +22,7 @@ import { provenance } from './provenance' import { openRef } from './refs' import { card, tourState, walk } from './instances' import { onTutorial, TUTORIAL_KEY } from './tutorial' +import { podcasts } from '../podcast/player' /** The map column's width in wide panels, as last dragged (0.21.1): every panel, every journey. */ const MAP_WIDTH_KEY = 'codeNotes.mapWidth' @@ -41,8 +42,10 @@ const MAP_MESSAGES: { [K in MapMessage['type']]?: Handler } = { openPath: (lj, m) => void openBoxPath(lj, m.path), // The list over the walk: the walk keeps its place, card and status item. home: () => undefined, - beat: (lj, m) => void showBeat(lj, m.n, m.i), - closed: () => beats.clear(), + beat: (lj, m) => { if (m.user) podcasts.onBeat(lj, m.n, m.i); void showBeat(lj, m.n, m.i) }, + closed: () => { beats.clear(); podcasts.onClosed() }, + podcastTime: (lj, m) => podcasts.onTime(lj, m), + podcastError: (_lj, m) => podcasts.onError(String(m.message)), panelWidth: () => void rememberPanelWidth(), mapWidth: (_lj, m) => void gstate.update(MAP_WIDTH_KEY, m.w > 0 ? Math.round(m.w) : undefined), list: (_lj, m) => homeQueryChanged(m), diff --git a/src/tour/walk.ts b/src/tour/walk.ts index ca0f4b8..fdfe23b 100644 --- a/src/tour/walk.ts +++ b/src/tour/walk.ts @@ -26,6 +26,9 @@ export type TourItems = { prev: vscode.StatusBarItem; pos: vscode.StatusBarItem; export class Walk { constructor(private readonly tour: TourState, private readonly card: StepCard) {} + /** Called once the walk has moved, or the journeys changed (updateTour): the podcast follows a reader's move. */ + onMoved: (() => void) | undefined + tourJourney(): LoadedJourney | undefined { return this.tour.key ? journeys.list.get(this.tour.key) : undefined } /** A tour is running (not just a map open): only then the status bar, the step card and D/A belong to it. */ touring(): boolean { return !!this.tourJourney() && this.tour.step > 0 } @@ -143,6 +146,7 @@ export class Walk { setCtx('codeNotes.hasJourneys', journeys.all().length > 0) mapPanel.update() this.renderStatusItem(lj) + this.onMoved?.() } /** A code link's way back is to the step it was clicked on: the walk moved on or ended, the link (and its Back) goes. */ diff --git a/src/webview/page.ts b/src/webview/page.ts index 9542e4c..808a21a 100644 --- a/src/webview/page.ts +++ b/src/webview/page.ts @@ -18,14 +18,16 @@ export function nonce(): string { return Array.from({ length: 24 }, () => Math.floor(Math.random() * 36).toString(36)).join('') } -/** What a page lets in beyond its own files: images (its source, https:, data:), and style attributes in its markup. */ -export interface PageAllows { images?: boolean; inlineStyles?: boolean } +/** What a page lets in beyond its own files: images (its source, https:, data:), audio (`media`), and style attributes in its markup. */ +export interface PageAllows { images?: boolean; inlineStyles?: boolean; media?: boolean } /** The page's policy: nothing by default; the extension's (`source`) styles and fonts; scripts with the nonce; no forms. */ export function contentSecurityPolicy(source: string, n: string, allow: PageAllows = {}): string { return [ "default-src 'none'", ...(allow.images ? [`img-src ${source} https: data:`] : []), + // Audio and video from the extension's own roots (the journey panel's podcast). + ...(allow.media ? [`media-src ${source}`] : []), `style-src ${source}${allow.inlineStyles ? " 'unsafe-inline'" : ''}`, `font-src ${source}`, `script-src 'nonce-${n}'`, diff --git a/test/fixtures/podcast/sample.podcast.json b/test/fixtures/podcast/sample.podcast.json new file mode 100644 index 0000000..43b4ce1 --- /dev/null +++ b/test/fixtures/podcast/sample.podcast.json @@ -0,0 +1,21 @@ +{ + "version": 1, + "title": "Placing an order, in 40 seconds", + "journey": { "id": "place-order", "file": "test/journey-scene/sample.json" }, + "audio": "tone.mp3", + "duration": 40, + "segments": [ + { "id": "s01", "at": null, "cue": "map", "speaker": "host", "text": "Welcome. Today: an order, end to end.", "start": 0, "end": 2.8 }, + { "id": "s02", "at": { "step": "add", "beat": 1 }, "cue": "open", "speaker": "host", "text": "Ana adds a lamp.", "start": 3, "end": 5.8 }, + { "id": "s03", "at": { "step": "add", "beat": 3 }, "cue": "beat", "speaker": "host", "text": "The cart is saved.", "start": 6, "end": 8.8 }, + { "id": "s04", "at": { "step": "confirm" }, "cue": "open", "speaker": "guest", "text": "And then she confirms?", "start": 9, "end": 11.8 }, + { "id": "s05", "at": { "step": "confirm", "beat": 2 }, "cue": "beat", "speaker": "host", "text": "She does, in a dialog.", "start": 12, "end": 14.8 }, + { "id": "s06", "at": { "step": "live", "beat": 1 }, "cue": "open", "speaker": "host", "text": "The page goes live.", "start": 15, "end": 17.8 }, + { "id": "s07", "at": { "step": "queue", "beat": 4 }, "cue": "open", "speaker": "host", "text": "The order waits in the queue.", "start": 18, "end": 20.8 }, + { "id": "s08", "at": { "step": "deploy", "beat": 2 }, "cue": "open", "speaker": "host", "text": "A worker takes it.", "start": 21, "end": 23.8 }, + { "id": "s09", "at": { "step": "receipt", "beat": 1 }, "cue": "open", "speaker": "host", "text": "The receipt is written.", "start": 24, "end": 26.8 }, + { "id": "s10", "at": { "step": "receipt", "beat": 9 }, "cue": "beat", "speaker": "host", "text": "A beat the step does not have: the step only.", "start": 27, "end": 29.8 }, + { "id": "s11", "at": { "step": "session", "beat": 1 }, "cue": "open", "speaker": "host", "text": "The session is checked.", "start": 30, "end": 33.8 }, + { "id": "s12", "at": null, "cue": "map", "speaker": "guest", "text": "So: cart, confirm, queue, worker, receipt.", "start": 34, "end": 39.5 } + ] +} diff --git a/test/fixtures/podcast/tone.mp3 b/test/fixtures/podcast/tone.mp3 new file mode 100644 index 0000000000000000000000000000000000000000..05fe31f20e99ddd0f97e15c1c6d683ca6a80e7e9 GIT binary patch literal 80432 zcmbSU2|&zg8=vlLt|+ElBP6+|134=~2)S=fNr|Og%UYW0Kx|fW?Bv)Yax0r7EHf(S zhLYSVy6=!=#?1eF-uInapAGYGzR&L0?l(`*^FHtU{+|0CKiBzq1(( z9S`rH{rcPWf&T~u_+OI0Q155TntmL!%r6jr;4m1vvl&{0bQwDOh9)d-D|4P@hfY>q zyZ7kT*Uq8;z`?^@MvQVFJKl5h)ETqqd3pQ#2P|2(eAVi;zXpp#H%9yxxjlOKA2Iu5 z55^}PKXoQ4`9jL&tFp8kx9;A1koD-vvzM=47Z#URRM)=$&>&Z$UkG;sp| zqpPk9{t@_Cacf<_Fa8zv-X@*FeEPe9aWituyvp$hk}v#x|JjSdODfJz?)HYQ$1o1r z_VbE4A-fNCk%dK`y}hQ>?ewHxG4{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zmM}%x0SY;(bxMnSX0`h zD#iBa-#)9?dXQJBQ&-E#ZaWVu6L&a;yYHPdc#og)oI}GW&pA9KpLpK*A^Yxdv)V~; z*LJh!$ZfkLyFJ`S4({5ii&Q$E#}BciZsh*FgW!? { window.__posted.push(m) if (m.type === 'error') window.__errors.push(m) + // A harness playing the extension's part answers here (test/journey-podcast/shoot.mjs). + if (window.__onPost) window.__onPost(m) }, getState: () => (keepState ? window.__state : undefined), setState: (s) => { if (keepState) window.__state = s }, diff --git a/test/integration/helpers.ts b/test/integration/helpers.ts index d4b1b2f..543f5d1 100644 --- a/test/integration/helpers.ts +++ b/test/integration/helpers.ts @@ -10,7 +10,7 @@ // CODE_NOTES_CONSOLE_ALL=1 print every workbench console message, not only the errors (run.ts, check run) // ONLY_MAIN / ONLY_UNTRUSTED / ONLY_CHECK=1 run that suite alone (run.ts; with none set, all three) // Set by run.ts or the tests themselves, not by hand: -// CODE_NOTES_CDP the workbench's DevTools port (check run: devtools.ts) +// CODE_NOTES_CDP the workbench's DevTools port (main and check runs: devtools.ts) // CODE_NOTES_CONSOLE the file the workbench console errors are collected in (check run) // CODE_NOTES_SLOW_GIT a folder with a slow `git` (check run: check/refresh.ts) // FAKE_CLAUDE_LOG the fake claude CLI's log of its runs (`useFakeClaude`, `fakeCalls`) diff --git a/test/integration/main/podcast.ts b/test/integration/main/podcast.ts new file mode 100644 index 0000000..cb62e1a --- /dev/null +++ b/test/integration/main/podcast.ts @@ -0,0 +1,198 @@ +// Podcast mode: a journey with a podcast file next to it plays in the journey panel, and the walk follows the voice +// (the step's code opens, the animation's beat lights its line); seeking anywhere puts the walk exactly where it is at +// that time, backwards too, the last of quick seeks only; Next while it plays moves the audio; the audio goes on in a +// background tab. The audio is a 40 s tone (test/fixtures/podcast/tone.mp3), so this also proves VS Code's own +// Electron plays mp3 from the workspace and seeks in it. Source: src/podcast/, media/journey-podcast.js. +import * as vscode from 'vscode' +import * as fs from 'fs' +import * as path from 'path' +import assert from 'assert' +import { sleep, test } from '../helpers' +import { journey, step, writeJourney, writeLines } from '../fixtures' +import { ctx, journeysDir, tour, wsPath } from './context' +import { waiter } from '../helpers' +import { ui } from '../devtools' + +/* eslint-disable @typescript-eslint/no-explicit-any */ +const pod = () => ctx.api.podcast() as any +/** The suite's wait, printing the podcast's state (and the walk's) on a timeout. */ +const until = waiter({ dump: () => ({ podcast: pod(), step: tour().step, map: tour().map, beat: tour().beat, file: codeFile() }) }) +const send = (m: object) => ctx.api.mapSend({ type: 'podcastCmd', ...m }) +const seek = (to: number) => send({ action: 'seek', to }) +const codeEditor = () => vscode.window.visibleTextEditors.find((e) => e.viewColumn !== tour().mapColumn && e.document.uri.scheme === 'file') +const codeFile = () => path.basename(codeEditor()?.document.uri.fsPath ?? '') +/** The line lit by the animation (1-based), 0: none. */ +const litLine = () => { const b = tour().beat; return b ? b.line + 1 : 0 } + +/** The journey panel's frame (a webview: an iframe in an iframe), over the DevTools connection. */ +async function panelFrame(): Promise { + const page = await ui() + return until('the journey panel\'s frame', async () => { + for (const f of page.frames()) { try { if (await f.evaluate(() => !!(globalThis as any).document.querySelector('.pod'))) return f } catch { /* detached */ } } + return undefined + }, 10000) +} + +/** The journey "pod" (step 1 and 2 with animations, step 3 without) and its podcast, the tone next to it. */ +function writePodJourney() { + writeLines(wsPath('src', 'pod.ts'), ['export function one() {', ' return 1', '}', 'export function two() {', ' return 2', '}']) + writeLines(wsPath('src', 'pod2.ts'), ['export const three = 3']) + const actors = [{ id: 'svc', type: 'service', col: 0, label: 'Server', fn: 'one()', checks: ['a', 'b', 'c'] }] + const beat = (caption: string, line: number, text: string) => ({ focus: 'svc', caption, code: { file: 'src/pod.ts', line, text } }) + writeJourney(journeysDir(), journey('pod', [ + step('src/pod.ts', 1, 3, { id: 'p1', title: 'one returns 1', scene: { actors, wires: [], beats: [beat('Opens.', 1, 'export function one() {'), beat('Returns.', 2, 'return 1'), beat('Closes.', 3, '}')] } }), + step('src/pod.ts', 4, 6, { id: 'p2', title: 'two returns 2', scene: { actors, wires: [], beats: [beat('Opens.', 4, 'export function two() {'), beat('Returns.', 5, 'return 2')] } }), + step('src/pod2.ts', 1, 1, { id: 'p3', title: 'three' }), + ], { title: 'Pod' })) + const seg = (id: string, at: unknown, start: number, end: number) => ({ id, at, speaker: 'host', text: `Part ${id}.`, start, end }) + fs.copyFileSync(path.join(__dirname, '../../../../test/fixtures/podcast/tone.mp3'), path.join(journeysDir(), 'pod.mp3')) + fs.writeFileSync(path.join(journeysDir(), 'pod.podcast.json'), JSON.stringify({ + version: 1, title: 'Pod', journey: { id: 'pod' }, audio: 'pod.mp3', duration: 40, + segments: [ + seg('intro', null, 0, 2.8), + seg('a1', { step: 'p1', beat: 1 }, 3, 5.8), + seg('a3', { step: 'p1', beat: 3 }, 6, 8.8), + seg('b', { step: 'p2' }, 9, 11.8), + seg('b2', { step: 'p2', beat: 2 }, 12, 14.8), + seg('c', { step: 'p3' }, 15, 17.8), + seg('c4', { step: 'p3', beat: 4 }, 18, 20.8), // p3 has no animation: the step only + seg('outro', null, 21, 39), + ], + })) +} + +/** The walk at `step` (0: none), the code group on `file`, the animation's line `line` lit (0: none). */ +const at = (step: number, file?: string, line = 0) => () => + tour().step === step && (!file || codeFile() === file) && litLine() === line && !pod().applying + +export const podcastTests = [ + test('podcast: a journey with a podcast file can be played; Play opens the panel and the mp3 plays in VS Code', async () => { + writePodJourney() + await until('the podcast is found next to its journey (and not listed as a journey)', () => pod().journeys.includes('pod') && !ctx.api.snapshot().journeys.some((j: any) => /podcast/.test(j.id)), 10000) + console.log(` (VS Code window focused: ${vscode.window.state.focused})`) + await vscode.commands.executeCommand('codeNotes.playPodcast', 'pod') + await until('the panel shows it', () => tour().map === 'pod' && pod().mapVisible, 10000) + // VS Code's webviews play audio only after a click or key in them: the first Play asks for one, ▶ focused. + await until('the first Play, from a command: refused until a click in the panel', () => pod().error === 'NotAllowedError' || pod().playing, 10000) + if (!pod().playing) { + const f = await panelFrame() + await until('▶ has the keyboard', async () => (await f.evaluate(() => (globalThis as any).document.activeElement?.className)) === 'pod-b play', 5000) + assert.match(await f.evaluate(() => (globalThis as any).document.querySelector('.pod-err').textContent), /Space/) + await f.click('.pod-b.play') + } + await until('playing, the time moving', () => pod().playing && pod().t > 0.6, 10000) + assert.equal(tour().step, 0, 'the intro: no step open') + assert.match(pod().item, /^\$\(debug-pause\) Intro · 0:0\d$/, `the status bar: ${pod().item}`) + // The voice reaches step 1: its code opens, the animation lights beat 1's line. + await until('3 s: step 1 opened on its first beat', at(1, 'pod.ts', 1), 8000) + assert.match(pod().item, /^\$\(debug-pause\) 1\/3 · /, `the status bar follows: ${pod().item}`) + // Space for the podcast (Ctrl+' Space): paused, and the walk stays. + await vscode.commands.executeCommand('codeNotes.podcastToggle') + await until('paused', () => !pod().playing) + await sleep(500) + assert.equal(tour().step, 1, 'pausing the podcast does not end the walk') + assert.match(pod().item, /^\$\(play\) 1\/3 · /) + }), + + test('podcast: a seek anywhere, forwards or backwards, puts the walk exactly where it is at that time', async () => { + // [time, step, file, lit line] + const points: [number, number, string | undefined, number][] = [ + [13, 2, 'pod.ts', 5], // step 2, beat 2 + [4, 1, 'pod.ts', 1], // back across a step + [16, 3, 'pod2.ts', 0], // a step without animation: nothing lit + [19, 3, 'pod2.ts', 0], // beat 4 that step doesn't have: the step only + [7, 1, 'pod.ts', 3], // far back, to beat 3 + [1, 0, undefined, 0], // the intro: the walk ends, the map shows + [10, 2, 'pod.ts', 0], // step 2 without its animation + [30, 0, undefined, 0], // the recap + [6.5, 1, 'pod.ts', 3], + ] + for (const [t, n, file, line] of points) { + await seek(t) + await until(`seek to ${t}s: the audio there, step ${n}, ${file ?? 'no file'}, line ${line} lit`, () => Math.abs(pod().t - t) < 0.5 && at(n, file, line)(), 8000) + } + assert.ok(!pod().playing, 'seeking while paused stays paused') + }), + + test('podcast: quick seeks (a drag, keys held) move the walk once, to the last one', async () => { + const before = pod().moves + for (const t of [13, 4, 16, 1, 19, 10, 7]) { await seek(t); await sleep(30) } + await until('the last seek wins: step 1, beat 3', at(1, 'pod.ts', 3), 8000) + await sleep(400) + assert.ok(at(1, 'pod.ts', 3)(), 'and stays there (no late move from an older seek)') + assert.ok(pod().moves - before <= 4, `fewer moves than seeks: ${pod().moves - before}`) + }), + + test('podcast: Next or Previous while it plays moves the audio to that step\'s first part', async () => { + await seek(4) + await until('step 1', at(1, 'pod.ts', 1), 8000) + await vscode.commands.executeCommand('codeNotes.podcastToggle') + await until('playing', () => pod().playing) + await vscode.commands.executeCommand('codeNotes.nextStep') + await until('Next: step 2 and the audio at its first part (9 s)', () => tour().step === 2 && pod().t >= 9 && pod().t < 11, 8000) + await vscode.commands.executeCommand('codeNotes.previousStep') + await until('Previous: step 1 and the audio at 3 s', () => tour().step === 1 && pod().t >= 3 && pod().t < 5.5, 8000) + assert.ok(pod().playing, 'still playing') + // Back / forward 15 s (Ctrl+' ← →). + const t0 = pod().t + await vscode.commands.executeCommand('codeNotes.podcastForward') + await until('forward 15 s', () => pod().t > t0 + 13, 5000) + await vscode.commands.executeCommand('codeNotes.podcastBack') + await until('back 15 s', () => pod().t < t0 + 5, 5000) + await vscode.commands.executeCommand('codeNotes.podcastToggle') + await until('paused', () => !pod().playing) + }), + + test('podcast: the audio keeps playing, and the walk following it, while the panel is a background tab', async () => { + await seek(13) + await until('step 2', at(2, 'pod.ts', 5), 8000) + // Another editor in the panel's group, in front of it. + const panelGroup = vscode.window.tabGroups.all.find((g) => g.tabs.some((t) => t.input instanceof vscode.TabInputWebview && /codeNotes\.journey/.test(t.input.viewType)))! + console.log(` (panel in group ${panelGroup.viewColumn}, tour().mapColumn ${tour().mapColumn})`) + // Not a file: those the extension moves out of the panel's group. The Settings editor, in front of the panel. + await vscode.commands.executeCommand(panelGroup.viewColumn === 1 ? 'workbench.action.focusFirstEditorGroup' : 'workbench.action.focusSecondEditorGroup') + await vscode.commands.executeCommand('workbench.action.openSettings2') + await until('the panel is hidden', () => !pod().mapVisible) + await vscode.commands.executeCommand('codeNotes.podcastToggle') + await until('playing while hidden', () => pod().playing, 5000) + const t0 = pod().t + await sleep(2500) + assert.ok(pod().t > t0 + 1.8, `the time moved on while hidden: ${t0} → ${pod().t}`) + await until('crossing 15 s while hidden: step 3 opened', () => tour().step === 3 && codeFile() === 'pod2.ts', 8000) + const groups = () => vscode.window.tabGroups.all.map((g) => `${g.viewColumn}:${g.tabs.map((t) => `${t.label}${t.isActive ? '*' : ''}`).join(',')}`).join(' | ') + assert.ok(!pod().mapVisible, `the panel was not brought back to front: ${groups()}`) + await vscode.commands.executeCommand('codeNotes.podcastToggle') + await until('paused', () => !pod().playing) + await vscode.commands.executeCommand('workbench.action.closeActiveEditor') + }), + + test('podcast: a long recording: a seek 9 minutes in plays from there (the panel loads the audio in ranges)', async () => { + // 10 minutes of silence, 8 kHz 8-bit mono WAV (4.8 MB), and a journey of one step for it. + const secs = 600, rate = 8000 + const wav = Buffer.alloc(44 + secs * rate, 128) + wav.write('RIFF', 0); wav.writeUInt32LE(36 + secs * rate, 4); wav.write('WAVEfmt ', 8); wav.writeUInt32LE(16, 16) + wav.writeUInt16LE(1, 20); wav.writeUInt16LE(1, 22); wav.writeUInt32LE(rate, 24); wav.writeUInt32LE(rate, 28) + wav.writeUInt16LE(1, 32); wav.writeUInt16LE(8, 34); wav.write('data', 36); wav.writeUInt32LE(secs * rate, 40) + fs.writeFileSync(path.join(journeysDir(), 'podlong.wav'), wav) + writeJourney(journeysDir(), journey('podlong', [step('src/pod.ts', 1, 3, { id: 'l1' }), step('src/pod2.ts', 1, 1, { id: 'l2' })], { title: 'Pod long' })) + fs.writeFileSync(path.join(journeysDir(), 'podlong.podcast.json'), JSON.stringify({ + version: 1, title: 'Long', journey: { id: 'podlong' }, audio: 'podlong.wav', duration: secs, + segments: [{ id: 'a', at: { step: 'l1' }, text: 'a', start: 0, end: 300 }, { id: 'b', at: { step: 'l2' }, text: 'b', start: 300, end: 600 }], + })) + await until('its podcast is found', () => pod().journeys.includes('podlong'), 10000) + await vscode.commands.executeCommand('codeNotes.playPodcast', 'podlong') + await until('the panel shows it', () => tour().map === 'podlong', 10000) + await until('playing (this panel was clicked already)', () => pod().playing && pod().session === 'podlong', 10000) + await seek(540) + await until('9 minutes in: step 2, the audio there and going on', () => tour().step === 2 && pod().t > 540.5 && pod().t < 545, 10000) + await vscode.commands.executeCommand('codeNotes.podcastToggle') + await until('paused', () => !pod().playing) + }), + + test('podcast: closing the panel stops it; the status item goes', async () => { + await vscode.commands.executeCommand('codeNotes.showMap') + await until('the panel', () => pod().mapVisible) + await vscode.commands.executeCommand('workbench.action.closeActiveEditor') + await until('the panel closed: no podcast, no status item', () => !pod().mapVisible && !pod().itemShown && !pod().playing, 5000) + }), +] diff --git a/test/integration/run.ts b/test/integration/run.ts index 0a61c3d..8e139f6 100644 --- a/test/integration/run.ts +++ b/test/integration/run.ts @@ -63,10 +63,13 @@ async function main() { const appTs = ['import { readToken, use } from "./lib"', 'export function main() {', ' const token = readToken()', ' use(token)', ' return 0', '}', ''] fs.writeFileSync(path.join(ws, 'src', 'app.ts'), appTs.join('\n')) const userData = roomyEditor(profileDir('main', ws)) + // The DevTools port: the podcast's first Play needs a real click in the journey panel (main/podcast.ts). + const port = 9300 + Math.floor(Math.random() * 500) await runTests({ extensionDevelopmentPath: ROOT, extensionTestsPath: path.join(__dirname, 'suite.js'), - launchArgs: [...baseLaunchArgs(ws, userData), '--disable-workspace-trust'], + launchArgs: [...baseLaunchArgs(ws, userData), '--disable-workspace-trust', `--remote-debugging-port=${port}`], + extensionTestsEnv: { CODE_NOTES_CDP: String(port) }, }) const tree = treeErrors(userData) if (tree.length) throw new Error(`tree view errors in the extension host log:\n${tree.join('\n')}`) diff --git a/test/integration/suite.ts b/test/integration/suite.ts index 6db56f5..1039bb4 100644 --- a/test/integration/suite.ts +++ b/test/integration/suite.ts @@ -12,6 +12,7 @@ // main/requests.ts the request file and vscode:// links write/, match.ts, writing.ts // main/animation.ts code links, value hints, animations codeLinks.ts, codeLinkText.ts, valueHints.ts, beats.ts, lineFollow.ts // main/roundTrips.ts calls into the window per action (remote performance), on the journey animation.ts leaves +// main/podcast.ts a journey's podcast: the walk follows the audio, seeks, the audio while hidden podcast/ // The pure modules have unit tests next to this folder, named after the module: src/.ts in // test/.test.ts, src//.ts in test/.test.ts (src/journeys/steps.ts: // journeySteps.test.ts, src/tour/stepText.ts: tourStepText.test.ts). @@ -32,6 +33,7 @@ import { repoJourneysTests } from './main/repoJourneys' import { requestsTests } from './main/requests' import { animationTests } from './main/animation' import { roundTripsTests } from './main/roundTrips' +import { podcastTests } from './main/podcast' /** The entry point run.ts starts VS Code with (extensionTestsPath). */ export async function run(): Promise { @@ -51,6 +53,7 @@ export async function run(): Promise { ...requestsTests, ...animationTests, ...roundTripsTests, + ...podcastTests, ]) console.log('all passed') } diff --git a/test/journey-map/harness.html b/test/journey-map/harness.html index cbc60ed..f90323b 100644 --- a/test/journey-map/harness.html +++ b/test/journey-map/harness.html @@ -6,12 +6,13 @@ - + +
@@ -38,6 +39,7 @@ + diff --git a/test/journey-podcast/shoot.mjs b/test/journey-podcast/shoot.mjs new file mode 100644 index 0000000..9b871d8 --- /dev/null +++ b/test/journey-podcast/shoot.mjs @@ -0,0 +1,278 @@ +// The journey panel's podcast bar (media/journey-podcast.js) in Chromium, with this script playing the extension's +// part (src/podcast/player.ts, simplified: the same model, out/src/podcast/model.js): a short tone episode on the +// scene sample journey. Checks what a person would notice: the bar and its timeline at three widths (nothing cut, +// nothing outside the window, one bar per step), play advances the audio, a click anywhere on the timeline shows +// exactly the step and beat of that time (forwards and backwards, no step in between shown), a drag moves the +// journey once (where it ended), the hover tip names the step, keys skip, a step clicked moves the audio, a beat the +// step does not have shows the step only, no console errors. Exits 1 on any failure. +// +// Usage (after `npm run build`): node test/journey-podcast/shoot.mjs [screenshot-dir] +// PLAYWRIGHT / CHROME: as test/harness/page.mjs. +import fs from 'node:fs' +import path from 'node:path' +import { createRequire } from 'node:module' +import { fileURLToPath, pathToFileURL } from 'node:url' + +const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..') +const OUT = process.argv[2] ? path.resolve(process.argv[2]) : '' +if (OUT) fs.mkdirSync(OUT, { recursive: true }) +const HARNESS = pathToFileURL(path.join(ROOT, 'test/journey-map/harness.html')).href +const MODEL = path.join(ROOT, 'out/src/podcast/model.js') +if (!fs.existsSync(MODEL)) { console.error('out/src/podcast/model.js is missing: run `npm run build` first'); process.exit(2) } +const { parsePodcast, resolveEpisode, viewAt, timeOf } = createRequire(import.meta.url)(MODEL) + +const raw = JSON.parse(fs.readFileSync(path.join(ROOT, 'test/journey-scene/sample.json'), 'utf8')) +const journey = { ...raw, steps: raw.steps.map((s, i) => ({ ...s, n: i + 1 })), problems: [] } +const podcastFile = path.join(ROOT, 'test/fixtures/podcast/sample.podcast.json') +const p = parsePodcast(fs.readFileSync(podcastFile, 'utf8')) +const ep = resolveEpisode(p, { steps: journey.steps.map((s) => ({ id: s.id, beats: s.scene?.beats?.length ?? 0 })) }) +const src = pathToFileURL(path.join(path.dirname(podcastFile), p.audio)).href +const episode = { src, title: ep.title, duration: ep.duration, at: 0, rate: 1, chapters: ep.chapters, segments: ep.segments.map((s) => ({ start: s.start, end: s.end, text: s.text, step: s.step })) } + +const failures = [] +let tag = '' +const fail = (m) => { failures.push(`${tag}: ${m}`); console.log(` ✗ ${tag}: ${m}`) } +const ok = (cond, m) => { if (!cond) fail(m) } + +async function launch() { + const pw = await import(process.env.PLAYWRIGHT ? pathToFileURL(path.resolve(process.env.PLAYWRIGHT)).href : 'playwright') + const chromium = pw.chromium ?? pw.default.chromium + return chromium.launch({ ...(process.env.CHROME ? { executablePath: process.env.CHROME } : {}), args: ['--autoplay-policy=no-user-gesture-required'] }) +} + +const tour = (current) => ({ current, marks: {}, resume: 0, legendHidden: true, problems: [], key: "Ctrl+'", tutorial: false, list: [] }) + +/** + * The extension's part: what player.ts does with the panel's messages, on the same model. `log` keeps what it did + * (every view it applied, every seek report) so a check can say "moved once", "never showed step 2". + */ +function fakeExtension(page) { + const st = { cur: 0, want: undefined, applied: [], seeks: 0, times: 0, lastT: 0, playing: false, beats: [] } + const send = (m) => page.evaluate((x) => window.postMessage(x, '*'), m).catch(() => {}) + const apply = async (v, still) => { + st.want = v + st.applied.push(v) + await send({ type: 'podcastBeat', n: v.step, i: v.beat ?? -1, ...(still ? { still: true } : {}) }) + if (st.cur !== v.step) { st.cur = v.step; await send({ type: 'tour', ...tour(v.step) }) } + } + const on = async (m) => { + if (m.type === 'podcastTime') { + st.times++ + st.lastT = m.t + st.playing = m.playing + if (m.seek) st.seeks++ + if (!m.playing && !m.seek) return + const v = viewAt(ep, m.t) + const view = v.beat === undefined ? { step: v.step } : { step: v.step, beat: v.beat } + if (st.want && st.want.step === view.step && st.want.beat === view.beat) return + await apply(view, !!m.seek) + } else if (m.type === 'step') { + // The reader walks to a step: the walk goes there, the audio to its first part. + st.cur = m.n + await send({ type: 'tour', ...tour(m.n) }) + const t = timeOf(ep, m.n) + if (t !== undefined) { st.want = viewAt(ep, t); await send({ type: 'podcastCmd', action: 'seek', to: t }) } + } else if (m.type === 'beat') st.beats.push([m.n, m.i]) + } + return { st, on, send } +} + +/** What the panel shows: the current step's number, the animation's beat ("n / N" → n-1), the bar's state. */ +const shown = (page) => page.evaluate(() => { + const cur = document.querySelector('.story .st.cur') + const pos = document.querySelector('#app .scnwrap .scn-pos') + return { + step: cur ? Number(cur.dataset.n) : 0, + beat: pos ? Number(pos.textContent.trim().split(' / ')[0]) - 1 : undefined, + anim: !!document.querySelector('#app .scnwrap'), + time: document.querySelector('.pod-time')?.textContent, + cap: document.querySelector('.pod-cap')?.textContent, + } +}) +const audioState = (page) => page.evaluate(() => { const a = document.querySelector('.pod audio'); return { t: a.currentTime, paused: a.paused, ready: a.readyState, dur: a.duration, err: a.error && a.error.code } }) +const sleep = (ms) => new Promise((r) => setTimeout(r, ms)) +async function until(what, f, ms = 4000) { + const end = Date.now() + ms + for (;;) { + const v = await f() + if (v) return v + if (Date.now() > end) { fail(`timed out: ${what}`); return v } + await sleep(40) + } +} + +/** The timeline's x for time t (page px). */ +async function xAt(page, t) { + const r = await page.evaluate(() => { const b = document.querySelector('.pod-track').getBoundingClientRect(); return { x: b.left, w: b.width, y: b.top + b.height / 2 } }) + return { x: r.x + (t / ep.duration) * r.w, y: r.y } +} + +async function layout(page, w) { + const L = await page.evaluate(() => { + const W = document.documentElement.clientWidth, H = window.innerHeight + const r = (s) => { const e = document.querySelector(s); if (!e) return null; const b = e.getBoundingClientRect(); return { l: b.left, r: b.right, t: b.top, b: b.bottom, w: b.width, h: b.height, vis: getComputedStyle(e).display !== 'none' } } + const bar = r('.pod'), tl = r('.pod-tl') + const buttons = [...document.querySelectorAll('.pod button')].filter((b) => getComputedStyle(b).display !== 'none').map((b) => { const x = b.getBoundingClientRect(); return { l: x.left, r: x.right, t: x.top, b: x.bottom, c: b.className } }) + const time = document.querySelector('.pod-time') + return { + W, H, bar, tl, buttons, + scrollW: document.documentElement.scrollWidth, + timeCut: time.scrollWidth > time.clientWidth + 1, + bars: document.querySelectorAll('.pod-bar').length, + appPad: parseFloat(getComputedStyle(document.getElementById('app')).paddingBottom), + } + }) + ok(L.bar && L.bar.vis, 'the bar is shown') + ok(L.scrollW <= L.W, `no sideways scroll (${L.scrollW} > ${L.W})`) + ok(L.bar.l >= 0 && L.bar.r <= L.W + 0.5 && Math.abs(L.bar.b - L.H) < 1, `the bar at the window's bottom, inside it: ${JSON.stringify(L.bar)}`) + ok(L.tl.w >= L.W - 40, `the timeline spans the bar (${L.tl.w} of ${L.W})`) + ok(L.bars === ep.chapters.length, `one timeline bar per part: ${L.bars} vs ${ep.chapters.length}`) + ok(!L.timeCut, 'elapsed / total not cut') + for (const b of L.buttons) ok(b.l >= 0 && b.r <= L.W + 0.5, `button ${b.c} inside the window`) + for (let i = 0; i < L.buttons.length; i++) for (let j = i + 1; j < L.buttons.length; j++) { + const a = L.buttons[i], c = L.buttons[j] + const overlap = Math.min(a.r, c.r) - Math.max(a.l, c.l) > 0.5 && Math.min(a.b, c.b) - Math.max(a.t, c.t) > 0.5 + ok(!overlap, `buttons ${a.c} and ${c.c} overlap`) + } + ok(L.appPad >= L.bar.h, `the page's end stays clear of the bar (padding ${L.appPad} < ${L.bar.h})`) + if (w < 360) ok(!L.buttons.some((b) => /prev|next/.test(b.c)), 'narrow: no part buttons') +} + +async function run(b, w) { + tag = `${w}px` + const context = await b.newContext({ viewport: { width: w, height: 760 }, deviceScaleFactor: 1, reducedMotion: 'reduce' }) + const page = await context.newPage() + const errors = [] + page.on('console', (m) => { if (m.type() === 'error' || m.type() === 'warning') errors.push(`${m.type()}: ${m.text()}`) }) + page.on('pageerror', (e) => errors.push(`pageerror: ${e.message}`)) + const fx = fakeExtension(page) + await page.exposeFunction('__onPost', (m) => fx.on(m)) + await page.goto(`${HARNESS}?theme=${w === 700 ? 'dark' : 'light'}`) + await page.waitForFunction(() => window.__posted.some((m) => m.type === 'ready')) + await fx.send({ type: 'journey', journey, ...tour(0) }) + await fx.send({ type: 'podcast', episode }) + await page.waitForSelector('.pod:not([hidden])') + const canMp3 = await page.evaluate(() => document.createElement('audio').canPlayType('audio/mpeg')) + ok(!!canMp3, `this Chromium plays mp3 (canPlayType: "${canMp3}")`) + await until('the audio\'s length is known', async () => (await audioState(page)).ready >= 1) + await layout(page, w) + if (OUT) await page.screenshot({ path: path.join(OUT, `podcast-${w}-start.png`) }) + + // Play: the audio goes, the walk follows (the intro: no step). + await page.click('.pod-b.play') + await until('playing, time advancing', async () => (await audioState(page)).t > 0.4) + ok(fx.st.playing, 'the panel says it is playing') + ok((await shown(page)).step === 0, 'the intro: no step yet') + await page.click('.pod-b.play') + await until('paused', async () => (await audioState(page)).paused) + + // Seeks by clicking the timeline, forwards and backwards, far and near: exactly the view of that time. + const points = [16, 4, 7, 25.5, 28, 10, 13, 31, 1, 36, 19, 22] + for (const t of points) { + const before = fx.st.applied.length + const { x, y } = await xAt(page, t) + await page.mouse.click(x, y) + const want = viewAt(ep, t) + await until(`click at ${t}s shows step ${want.step} beat ${want.beat}`, async () => { + const s = await shown(page) + const animOk = want.beat === undefined ? !s.anim : s.anim && s.beat === want.beat + return s.step === want.step && animOk + }) + const moves = fx.st.applied.slice(before) + ok(moves.length <= 1, `click at ${t}s: moved once, not through the steps between (${JSON.stringify(moves)})`) + const a = await audioState(page) + ok(Math.abs(a.t - t) < 0.6, `click at ${t}s: the audio is there (${a.t.toFixed(2)})`) + } + if (OUT) await page.screenshot({ path: path.join(OUT, `podcast-${w}-seeked.png`) }) + + // A drag: the journey moves once, where it ended (never through the steps the pointer crossed). + { + const before = fx.st.applied.length + const seeksBefore = fx.st.seeks + const a = await xAt(page, 2), z = await xAt(page, 33) + await page.mouse.move(a.x, a.y) + await page.mouse.down() + for (let k = 1; k <= 12; k++) await page.mouse.move(a.x + ((z.x - a.x) * k) / 12, a.y) + const tipText = await page.evaluate(() => { const t = document.querySelector('.pod-tip'); return t.hidden ? '' : t.textContent }) + ok(/^8 · /.test(tipText) || /Session|session/.test(tipText) || tipText.startsWith(`${viewAt(ep, 33).step} · `), `dragging: the tip names the step under the pointer ("${tipText}")`) + ok(fx.st.seeks === seeksBefore, 'no seek while dragging') + await page.mouse.up() + const want = viewAt(ep, 33) + await until('after the drag: the step where it ended', async () => (await shown(page)).step === want.step) + ok(fx.st.applied.length - before === 1, `the drag moved the journey once (${fx.st.applied.length - before})`) + ok(fx.st.seeks - seeksBefore === 1, `one seek for the drag (${fx.st.seeks - seeksBefore})`) + } + + // Hover: the tip names the step at that point. + { + const t = 19.5 + const { x, y } = await xAt(page, t) + await page.mouse.move(x, y) + const tip = await page.evaluate(() => { const t = document.querySelector('.pod-tip'); return { text: t.hidden ? '' : t.textContent, r: t.getBoundingClientRect().toJSON() } }) + const n = viewAt(ep, t).step + ok(tip.text.startsWith(`${n} · ${journey.steps[n - 1].title}`.slice(0, 12)), `hover at ${t}s: the tip says step ${n} ("${tip.text}")`) + ok(tip.r.left >= 0 && tip.r.right <= w + 0.5, 'the tip inside the window') + if (OUT) await page.screenshot({ path: path.join(OUT, `podcast-${w}-hover.png`) }) + await page.mouse.move(5, 5) + } + + // A beat the step doesn't have (s10: receipt beat 9): the step only, no animation. + { + const { x, y } = await xAt(page, 28.5) + await page.mouse.click(x, y) + await until('beat 9 of receipt → the receipt step without its animation', async () => { const s = await shown(page); return s.step === 6 && !s.anim }) + } + + // Keys: the timeline focused, → is 15 s on; Shift+← the step before. + { + await page.focus('.pod-tl') + const t0 = (await audioState(page)).t + await page.keyboard.press('ArrowRight') + await until('→: 15 s on', async () => Math.abs((await audioState(page)).t - Math.min(t0 + 15, ep.duration - 0.05)) < 0.3) + await page.keyboard.press('Home') + await until('Home: the start', async () => (await audioState(page)).t < 0.2) + await until('Home: the intro shows no step', async () => (await shown(page)).step === 0) + await page.keyboard.press(' ') + await until('Space plays', async () => !(await audioState(page)).paused) + await page.keyboard.press('k') + await until('K pauses', async () => (await audioState(page)).paused) + } + + // Journey → audio: a step clicked in the storyline moves the audio to its first part. + { + await page.click('.story .st[data-n="4"]') + const t = timeOf(ep, 4) + await until(`step 4 clicked: the audio at ${t}s`, async () => Math.abs((await audioState(page)).t - t) < 0.3) + await until('and step 4 shown', async () => (await shown(page)).step === 4) + } + + // Speed cycles 1× → 1.25× → 1.5× → 1×. + { + const rates = [] + for (let k = 0; k < 3; k++) { await page.click('.pod-rate'); rates.push(await page.evaluate(() => document.querySelector('.pod audio').playbackRate)) } + ok(rates.join() === '1.25,1.5,1', `speeds ${rates}`) + } + + // Play through a step boundary: the walk follows on its own. + { + const { x, y } = await xAt(page, 14.2) + await page.mouse.click(x, y) + await page.click('.pod-b.play') + await until('playing across 15 s: step 3 (live), beat 0', async () => { const s = await shown(page); return s.step === 3 && s.anim && s.beat === 0 }, 4000) + await page.click('.pod-b.play') + } + + await layout(page, w) + if (OUT) await page.screenshot({ path: path.join(OUT, `podcast-${w}-end.png`) }) + for (const e of errors) fail(e) + const pageErrors = await page.evaluate(() => window.__errors.map((e) => e.message)) + for (const e of pageErrors) fail(`page: ${e}`) + await context.close() + console.log(`${tag}: done`) +} + +const b = await launch() +for (const w of [340, 700, 1200]) await run(b, w) +await b.close() +console.log(failures.length ? `${failures.length} problems` : 'all checks passed') +process.exit(failures.length ? 1 : 0) diff --git a/test/keybindings.test.ts b/test/keybindings.test.ts index 24d8a37..33cc1fc 100644 --- a/test/keybindings.test.ts +++ b/test/keybindings.test.ts @@ -21,6 +21,10 @@ test('one chord scheme on two prefixes: Ctrl+< by scan code (ISO key) and Ctrl+\ v: 'codeNotes.showMap', p: 'codeNotes.toggleAnimation', j: 'codeNotes.searchJourneys', + // The journey podcast: play / pause, back and forward 15 s (src/podcast/player.ts). + space: 'codeNotes.podcastToggle', + left: 'codeNotes.podcastBack', + right: 'codeNotes.podcastForward', } const prefixes = ['ctrl+[IntlBackslash]', "ctrl+'"] // Every prefix × letter, with Ctrl released or still held for the second key. diff --git a/test/podcastModel.test.ts b/test/podcastModel.test.ts new file mode 100644 index 0000000..5106810 --- /dev/null +++ b/test/podcastModel.test.ts @@ -0,0 +1,150 @@ +import { test } from 'node:test' +import assert from 'node:assert/strict' +import { chapterJump, clock, isPodcastFile, LatestWins, parsePodcast, podcastFileOf, resolveEpisode, sameView, segmentAt, timeOf, viewAt } from '../src/podcast/model' + +// The podcast's pure parts (src/podcast/model.ts): reading the file, where the journey is at a time, seeking. + +const journey = { steps: [{ id: 'a', beats: 3 }, { id: 'b', beats: 0 }, { id: 'c', beats: 2 }] } +const seg = (id: string, at: unknown, start: number, end: number, extra: object = {}) => ({ id, at, start, end, text: id, speaker: 'host', ...extra }) +const file = (segments: object[], more: object = {}) => JSON.stringify({ version: 1, title: 'T', journey: { id: 'j' }, audio: 'j.mp3', duration: 100, segments, ...more }) +const episode = (segments: object[]) => { + const p = parsePodcast(file(segments)) + assert.ok(typeof p !== 'string', String(p)) + return resolveEpisode(p, journey) +} +const sample = () => episode([ + seg('intro', null, 0, 9), + seg('a1', { step: 'a', beat: 1 }, 10, 19), + seg('a3', { step: 'a', beat: 3 }, 20, 29), + seg('a3b', { step: 'a', beat: 3 }, 30, 39), + seg('b', { step: 'b' }, 40, 49), + seg('c2', { step: 'c', beat: 2 }, 50, 59), + seg('outro', null, 60, 70), +]) + +test('podcast file: shape checked, the reason said', () => { + assert.match(String(parsePodcast('{')), /not JSON/) + assert.match(String(parsePodcast(JSON.stringify({ version: 2, audio: 'a', segments: [{}] }))), /version 2/) + assert.match(String(parsePodcast(JSON.stringify({ version: 1, segments: [{}] }))), /audio/) + assert.match(String(parsePodcast(JSON.stringify({ version: 1, audio: 'a.mp3', segments: [] }))), /segments/) + const p = parsePodcast(file([seg('s', null, 0, 1)])) + assert.ok(typeof p !== 'string') + assert.equal(p.audio, 'j.mp3') + assert.equal(p.journey.id, 'j') +}) + +test('podcast file: found next to its journey, never read as a journey', () => { + assert.equal(podcastFileOf('/r/journeys/scripted-tests.json'), '/r/journeys/scripted-tests.podcast.json') + assert.ok(isPodcastFile('scripted-tests.podcast.json')) + assert.ok(!isPodcastFile('scripted-tests.json')) +}) + +test('segments: each one\'s view; chapters are runs on one step, the first from 0', () => { + const ep = sample() + assert.deepEqual(ep.warnings, []) + assert.deepEqual(ep.segments.map((s) => [s.step, s.beat]), [[0, undefined], [1, 0], [1, 2], [1, 2], [2, undefined], [3, 1], [0, undefined]]) + assert.deepEqual(ep.chapters, [ + { start: 0, end: 10, step: 0 }, { start: 10, end: 40, step: 1 }, { start: 40, end: 50, step: 2 }, { start: 50, end: 60, step: 3 }, { start: 60, end: 100, step: 0 }, + ]) + assert.equal(ep.duration, 100) +}) + +test('segment at a time: the last started; before the first, the first; in a gap, the one before', () => { + const s = [{ start: 1 }, { start: 5 }, { start: 9 }] + assert.equal(segmentAt(s, 0), 0) + assert.equal(segmentAt(s, 1), 0) + assert.equal(segmentAt(s, 4.99), 0) + assert.equal(segmentAt(s, 5), 1) + assert.equal(segmentAt(s, 8), 1) + assert.equal(segmentAt(s, 9), 2) + assert.equal(segmentAt(s, 1e9), 2) + assert.equal(segmentAt([], 3), -1) +}) + +test('view at a time: exactly the segment\'s, in either direction, from anywhere (no intermediate cues)', () => { + const ep = sample() + // Forwards and backwards across steps give the same answers: it depends on the time only. + const at = (t: number) => { const v = viewAt(ep, t); return [v.step, v.beat] } + for (const order of [[0, 15, 35, 45, 55, 65], [65, 55, 45, 35, 15, 0]]) { + const want: Record = { 0: [0, undefined], 15: [1, 0], 35: [1, 2], 45: [2, undefined], 55: [3, 1], 65: [0, undefined] } + for (const t of order) assert.deepEqual(at(t), want[t], `t=${t}`) + } + assert.deepEqual(at(9.5), [0, undefined], 'the gap after the intro is still the intro') + assert.deepEqual(at(-5), [0, undefined]) + assert.deepEqual(at(999), [0, undefined]) + assert.ok(sameView(viewAt(ep, 21), viewAt(ep, 31)), 'two segments on one beat: the same view') + assert.ok(!sameView(viewAt(ep, 15), viewAt(ep, 21))) +}) + +test('a bad link degrades: missing beat → the step only; unknown step or bad "at" → the view before; cue map → no beat', () => { + const ep = episode([ + seg('a9', { step: 'a', beat: 9 }, 0, 1), + seg('b1', { step: 'b', beat: 1 }, 2, 3), // b has no animation + seg('x', { step: 'nope', beat: 1 }, 4, 5), + seg('c1', { step: 'c', beat: 1 }, 6, 7), + seg('bad', 'step c', 8, 9), + seg('none', undefined, 10, 11), + seg('map', { step: 'c', beat: 2 }, 12, 13, { cue: 'map' }), + seg('half', { step: 'a', beat: 1.5 }, 14, 15), + ]) + assert.deepEqual(ep.segments.map((s) => [s.id, s.step, s.beat]), [ + ['a9', 1, undefined], ['b1', 2, undefined], ['x', 2, undefined], ['c1', 3, 0], ['bad', 3, 0], ['none', 3, 0], ['map', 3, undefined], ['half', 1, undefined], + ]) + assert.equal(ep.warnings.length, 6, ep.warnings.join('\n')) + assert.match(ep.warnings[0], /no beat 9 \(it has 3\); the step only/) + assert.match(ep.warnings[2], /no step "nope"/) +}) + +test('segments out of order are sorted; one without a start is dropped; a missing end is the next start', () => { + const ep = episode([seg('two', null, 10, 12), { id: 'nostart', at: null, text: '' }, { id: 'one', at: { step: 'a' }, start: 2, text: '' }]) + assert.deepEqual(ep.segments.map((s) => [s.id, s.start, s.end]), [['one', 2, 10], ['two', 10, 12]]) + assert.equal(ep.warnings.length, 1) + assert.equal(ep.chapters[0].start, 0) +}) + +test('journey → audio: the first segment of a step or of a beat; nothing when the podcast skips it', () => { + const ep = sample() + assert.equal(timeOf(ep, 1), 10) + assert.equal(timeOf(ep, 1, 2), 20) + assert.equal(timeOf(ep, 1, 1), undefined, 'beat 2 of step a is never named') + assert.equal(timeOf(ep, 2), 40) + assert.equal(timeOf(ep, 9), undefined) +}) + +test('previous / next part: by chapter; previous restarts the chapter unless just past its start', () => { + const ep = sample() + assert.equal(chapterJump(ep, 15, 1), 40) + assert.equal(chapterJump(ep, 35, -1), 10) + assert.equal(chapterJump(ep, 11, -1), 0, 'within 3 s of the start: the chapter before') + assert.equal(chapterJump(ep, 2, -1), 0) + assert.equal(chapterJump(ep, 65, 1), 100, 'past the last: the end') +}) + +test('seeks coalesce: one move at a time, and only the newest one waiting runs next', async () => { + const ran: number[] = [] + const stopped: number[] = [] + let release!: () => void + const lw = new LatestWins(async (v, current) => { + ran.push(v) + if (v === 1) await new Promise((r) => { release = r }) + if (!current()) stopped.push(v) + }) + lw.push(1) + lw.push(2) + lw.push(3) + lw.push(4) + assert.ok(lw.busy) + release() + await lw.idle() + assert.deepEqual(ran, [1, 4], 'the drag\'s last position only') + assert.deepEqual(stopped, [1], 'the first job learns it was superseded') + lw.push(5) + await lw.idle() + assert.deepEqual(ran, [1, 4, 5]) +}) + +test('clock', () => { + assert.equal(clock(0), '0:00') + assert.equal(clock(767.88), '12:47') + assert.equal(clock(3725), '1:02:05') +}) From 2645a7f82d9dab8038ca4b68287802962ac5370c Mon Sep 17 00:00:00 2001 From: tomeyer97 <107920881+tomeyer97@users.noreply.github.com> Date: Wed, 18 Nov 2026 13:05:15 +0100 Subject: [PATCH 02/45] Podcast status item: the time beside the walk's own step item (Intro / Recap on the map); real-window shots of the player Co-Authored-By: Claude Opus 5.5 --- src/podcast/player.ts | 6 ++++-- test/integration/main/podcast.ts | 8 +++++--- 2 files changed, 9 insertions(+), 5 deletions(-) diff --git a/src/podcast/player.ts b/src/podcast/player.ts index a48e19f..13fa5f8 100644 --- a/src/podcast/player.ts +++ b/src/podcast/player.ts @@ -304,7 +304,8 @@ class Podcasts { // ---------- the status bar ---------- - /** While a podcast is in the panel: ⏸ (playing) or ▶, where it is in the journey, the time. Click: pause / play. */ + /** While a podcast is in the panel: ⏸ (playing) or ▶ and the time; on the map, Intro or Recap (on a step, the walk's + * own item beside it says which). Click: pause / play. */ private renderItem(): void { const item = this.item if (!item) return @@ -313,7 +314,8 @@ class Podcasts { const ep = this.eps.get(lj.key)!.ep const v = viewAt(ep, this.t) const where = v.step ? `${v.step}/${lj.j.steps.length}` : mapPartName(ep, this.t) - item.text = `${this.playing ? '$(debug-pause)' : '$(play)'} ${where} · ${clock(this.t)}` + const onWalkItem = !!v.step && walk.touring() && tourState.key === lj.key + item.text = `${this.playing ? '$(debug-pause)' : '$(play)'} ${onWalkItem ? '' : `${where} · `}${clock(this.t)}` item.tooltip = `${lj.j.title}: ${this.playing ? 'pause' : 'play'} the podcast (${clock(this.t)} of ${clock(ep.duration)})` item.accessibilityInformation = { label: `Podcast ${this.playing ? 'playing' : 'paused'}, ${v.step ? `step ${v.step}` : where}, ${clock(this.t)}. ${this.playing ? 'Pause' : 'Play'}.` } item.show() diff --git a/test/integration/main/podcast.ts b/test/integration/main/podcast.ts index cb62e1a..edd4592 100644 --- a/test/integration/main/podcast.ts +++ b/test/integration/main/podcast.ts @@ -7,7 +7,7 @@ import * as vscode from 'vscode' import * as fs from 'fs' import * as path from 'path' import assert from 'assert' -import { sleep, test } from '../helpers' +import { sleep, test, windowShot } from '../helpers' import { journey, step, writeJourney, writeLines } from '../fixtures' import { ctx, journeysDir, tour, wsPath } from './context' import { waiter } from '../helpers' @@ -78,6 +78,7 @@ export const podcastTests = [ const f = await panelFrame() await until('▶ has the keyboard', async () => (await f.evaluate(() => (globalThis as any).document.activeElement?.className)) === 'pod-b play', 5000) assert.match(await f.evaluate(() => (globalThis as any).document.querySelector('.pod-err').textContent), /Space/) + await windowShot('podcast-first-play', { wait: 300 }) await f.click('.pod-b.play') } await until('playing, the time moving', () => pod().playing && pod().t > 0.6, 10000) @@ -85,13 +86,14 @@ export const podcastTests = [ assert.match(pod().item, /^\$\(debug-pause\) Intro · 0:0\d$/, `the status bar: ${pod().item}`) // The voice reaches step 1: its code opens, the animation lights beat 1's line. await until('3 s: step 1 opened on its first beat', at(1, 'pod.ts', 1), 8000) - assert.match(pod().item, /^\$\(debug-pause\) 1\/3 · /, `the status bar follows: ${pod().item}`) + await windowShot('podcast-playing', { wait: 300 }) + assert.match(pod().item, /^\$\(debug-pause\) 0:0\d$/, `the status bar: the time (the walk's item beside it says 1/3): ${pod().item}`) // Space for the podcast (Ctrl+' Space): paused, and the walk stays. await vscode.commands.executeCommand('codeNotes.podcastToggle') await until('paused', () => !pod().playing) await sleep(500) assert.equal(tour().step, 1, 'pausing the podcast does not end the walk') - assert.match(pod().item, /^\$\(play\) 1\/3 · /) + assert.match(pod().item, /^\$\(play\) 0:0\d$/) }), test('podcast: a seek anywhere, forwards or backwards, puts the walk exactly where it is at that time', async () => { From 3a7920cf98001565bb849a754751a9efd1fd36e5 Mon Sep 17 00:00:00 2001 From: tomeyer97 <107920881+tomeyer97@users.noreply.github.com> Date: Wed, 18 Nov 2026 14:18:18 +0100 Subject: [PATCH 03/45] Podcasts: one validator for the podcast file (validatePodcast) Every problem with its level (error: it can't be played; warning: it plays, but a part is not what the file says) and where it is (a JSON path, the segment). Covers the shape (invalid JSON with its line and column, version, missing / empty / non-list segments), the audio (a path out of the journeys folder is refused, missing or empty file), the timing (overlaps, out of order, end before start, past the duration, past the real audio, a cut-off audio), the links (unknown step, beat out of range, bad at) and the journey it was written for. Unknown fields (e.g. say) are accepted. The cases live in test/fixtures/podcast/cases.json so another implementation can run them too. Co-Authored-By: Claude Opus 5.5 --- src/podcast/model.ts | 54 +- src/podcast/validate.ts | 341 +++++++++++++ test/fixtures/podcast/cases.json | 822 +++++++++++++++++++++++++++++++ test/podcastValidate.test.ts | 71 +++ 4 files changed, 1275 insertions(+), 13 deletions(-) create mode 100644 src/podcast/validate.ts create mode 100644 test/fixtures/podcast/cases.json create mode 100644 test/podcastValidate.test.ts diff --git a/src/podcast/model.ts b/src/podcast/model.ts index 65d0bbb..4a1fb19 100644 --- a/src/podcast/model.ts +++ b/src/podcast/model.ts @@ -1,13 +1,25 @@ // A journey's podcast (docs/podcast-format.md): one audio file whose parts are linked to the journey's steps and // animation beats. This reads the file, checks it against the journey, and answers the one question the player asks // all the time: at this second of the audio, where should the journey be? No vscode here: unit tests use it as is -// (test/podcast.test.ts), and the player (player.ts) applies what it says. +// (test/podcastModel.test.ts), and the player (player.ts) applies what it says. The full check of a file, with every +// problem and where it is, is validate.ts. /** Where a segment belongs in the journey, as written: null (the whole journey: the map), or a step by id, with the * 1-based position of a beat in that step's `scene.beats`. */ export type WrittenAt = null | { step: string; beat?: number } -/** A segment as written in the file. */ +/** Something wrong with a podcast file (validate.ts). `error`: it can't be played; `warning`: it plays, but a part of + * it is not what the file says. `path`: where in the file (JSON keys and indexes); `segment`: the segment's id. */ +export interface PodcastProblem { + level: 'error' | 'warning' + code: string + message: string + path: (string | number)[] + segment?: string +} + +/** A segment as written in the file. Other fields (e.g. `say`, the spoken form a generator used) are allowed and + * ignored. */ export interface WrittenSegment { id?: string at?: unknown @@ -51,8 +63,10 @@ export interface Episode { duration: number segments: Segment[] chapters: Chapter[] - /** What could not be followed (an unknown step, a beat the step does not have, …): said in the log. */ + /** What could not be followed (an unknown step, a beat the step does not have, …): the messages of `problems`. */ warnings: string[] + /** The same, with the segment and where it is in the file. */ + problems: PodcastProblem[] } /** What the player needs of the journey: its steps' ids and how many beats each one's animation has. */ @@ -73,7 +87,9 @@ export function parsePodcast(raw: string): Podcast | string { if (!isObj(d)) return 'not an object' if (d.version !== 1) return `version ${JSON.stringify(d.version)} (this player reads version 1)` if (typeof d.audio !== 'string' || !d.audio.trim()) return 'no "audio" file' - if (!Array.isArray(d.segments) || !d.segments.length) return 'no "segments"' + if (d.segments === undefined) return 'no "segments"' + if (!Array.isArray(d.segments)) return '"segments" is not a list' + if (!d.segments.length) return '"segments" is empty' const j = isObj(d.journey) ? d.journey : {} return { version: 1, @@ -92,20 +108,20 @@ export function parsePodcast(raw: string): Podcast | string { * step without its animation. Segments without a usable start are dropped; a missing end is the next one's start. */ export function resolveEpisode(p: Podcast, journey: JourneyShape): Episode { - const warnings: string[] = [] + const problems: PodcastProblem[] = [] const byId = new Map(journey.steps.map((s, i) => [s.id, { n: i + 1, beats: s.beats }])) const timed = p.segments .map((s, i) => ({ s, i, start: num(s.start) })) .filter((x) => { const ok = x.start !== undefined && x.start >= 0 - if (!ok) warnings.push(`segment ${x.s.id ?? x.i + 1}: no start time; skipped`) + if (!ok) problems.push(segProblem(x.s, x.i, 'start', `${x.s.start === undefined ? 'no start time' : `start ${JSON.stringify(x.s.start)} is not a time in seconds`}; skipped`, ['start'])) return ok }) .sort((a, b) => a.start! - b.start! || a.i - b.i) let prev: View = { step: 0 } const segments: Segment[] = timed.map((x, k) => { const id = typeof x.s.id === 'string' ? x.s.id : `#${x.i + 1}` - const view = viewOf(x.s, id, byId, prev, warnings) + const view = viewOf(x.s, x.i, byId, prev, problems) prev = view const next = timed[k + 1]?.start const end = num(x.s.end) ?? next ?? num(p.duration) ?? x.start! @@ -113,26 +129,38 @@ export function resolveEpisode(p: Podcast, journey: JourneyShape): Episode { }) const last = segments[segments.length - 1] const duration = Math.max(num(p.duration) ?? 0, last ? last.end : 0) - return { title: p.title, duration, segments, chapters: chaptersOf(segments, duration), warnings } + return { title: p.title, duration, segments, chapters: chaptersOf(segments, duration), warnings: problems.map((w) => w.message), problems } +} + +/** The name a segment goes by in messages: its id, else its place in the file (1-based). */ +export const segmentName = (s: WrittenSegment, i: number) => (typeof s.id === 'string' && s.id ? s.id : `#${i + 1}`) + +/** A warning about segment `i` (index in the file) at `sub` (keys within it). */ +export function segProblem(s: WrittenSegment, i: number, code: string, what: string, sub: (string | number)[] = []): PodcastProblem { + const name = segmentName(s, i) + return { level: 'warning', code, message: `segment ${name}: ${what}`, path: ['segments', i, ...sub], segment: name } } -/** One segment's view (see resolveEpisode); `prev`: the view before it. */ -function viewOf(s: WrittenSegment, id: string, byId: Map, prev: View, warnings: string[]): View { +/** Codes of the problems that are a link the journey can't show (a part that can't be shown as written). */ +export const LINK_CODES = new Set(['at', 'step', 'beat']) + +/** One segment's view (see resolveEpisode); `i`: its index in the file; `prev`: the view before it. */ +function viewOf(s: WrittenSegment, i: number, byId: Map, prev: View, problems: PodcastProblem[]): View { const at = s.at if (at === null) return { step: 0 } if (!isObj(at) || typeof at.step !== 'string') { - warnings.push(`segment ${id}: "at" is ${at === undefined ? 'missing' : 'not null or { step, beat }'}; it keeps the view before it`) + problems.push(segProblem(s, i, 'at', `"at" is ${at === undefined ? 'missing' : 'not null or { step, beat }'}; it keeps the view before it`, at === undefined ? [] : ['at'])) return prev } const st = byId.get(at.step) if (!st) { - warnings.push(`segment ${id}: no step "${at.step}" in the journey; it keeps the view before it`) + problems.push(segProblem(s, i, 'step', `no step "${at.step}" in the journey; it keeps the view before it`, ['at', 'step'])) return prev } if (at.beat === undefined || s.cue === 'map') return { step: st.n } const b = at.beat if (typeof b !== 'number' || !Number.isInteger(b) || b < 1 || b > st.beats) { - warnings.push(`segment ${id}: step "${at.step}" has no beat ${JSON.stringify(b)} (it has ${st.beats}); the step only`) + problems.push(segProblem(s, i, 'beat', `step "${at.step}" has no beat ${JSON.stringify(b)} (it has ${st.beats}); the step only`, ['at', 'beat'])) return { step: st.n } } return { step: st.n, beat: b - 1 } diff --git a/src/podcast/validate.ts b/src/podcast/validate.ts new file mode 100644 index 0000000..e2034d4 --- /dev/null +++ b/src/podcast/validate.ts @@ -0,0 +1,341 @@ +// The full check of a podcast file (docs/podcast-format.md, "Validation"): every problem, its level and where it is in +// the file. One function, used by the player (whether it can play the file, and what to say in the panel and the +// Journeys view), the "Code Notes" output, the Problems view (diagnostics on the `.podcast.json`), and, ported rule +// for rule, by the code-journey skill's `journey.py podcast` (the cases in test/fixtures/podcast/cases.json run +// through both). No vscode here. + +import { clock, Episode, JourneyShape, LINK_CODES, Podcast, PodcastProblem, resolveEpisode, segmentName, segProblem, WrittenSegment } from './model' + +/** What is known around the file: the journey next to it, its audio file (looked at or not), the audio's real length + * (once the panel has loaded it). */ +export interface PodcastContext { + journey?: JourneyShape & { id: string } + /** undefined: not looked at. */ + audio?: { exists: boolean; size?: number } + /** Seconds, as the panel's audio element reports it. */ + audioDuration?: number +} + +export interface Validation { + /** The file read, when its shape is right. */ + podcast?: Podcast + /** The episode, when it can be played. */ + episode?: Episode + problems: PodcastProblem[] + /** No error: it can be played. */ + playable: boolean +} + +const isObj = (v: unknown): v is Record => !!v && typeof v === 'object' && !Array.isArray(v) +const num = (v: unknown) => (typeof v === 'number' && Number.isFinite(v) ? v : undefined) +const error = (code: string, message: string, path: (string | number)[] = []): PodcastProblem => ({ level: 'error', code, message, path }) +const warning = (code: string, message: string, path: (string | number)[] = []): PodcastProblem => ({ level: 'warning', code, message, path }) + +/** Times this close (s) are the same time (rounding in a generator). */ +const SLACK_S = 0.05 +/** The declared duration and the audio's own length may differ this much (s, or this share of it) before it is said. */ +const DURATION_SLACK_S = 1 +const DURATION_SLACK_SHARE = 0.01 +const CUES = new Set(['map', 'open', 'beat']) + +/** + * `audio` as written, when it can't be used: a URL, an absolute path, or a path out of the folder the podcast is in + * (the panel can only load files from the journeys folder: docs/podcast-format.md). + */ +export function audioPathProblem(audio: string): string | undefined { + const a = audio.replace(/\\/g, '/') + if (/^[a-z][a-z0-9+.-]*:/i.test(a) && !/^[a-z]:\//i.test(a)) return `audio must be a file in the journeys folder, not a URL (got ${audio})` + if (a.startsWith('/') || /^[a-z]:\//i.test(a)) return `audio must be in the journeys folder, as a path relative to the podcast file (got ${audio})` + let depth = 0 + for (const part of a.split('/')) { + if (part === '..') depth-- + else if (part && part !== '.') depth++ + if (depth < 0) return `audio must be in the journeys folder (got ${audio})` + } + return undefined +} + +/** The file's text checked, in full. Errors first, then the warnings in file order. */ +export function validatePodcast(raw: string, ctx: PodcastContext = {}): Validation { + const problems: PodcastProblem[] = [] + const fail = (p: PodcastProblem): Validation => ({ problems: [p, ...problems], playable: false }) + let d: unknown + try { d = JSON.parse(raw) } catch (e) { + if (!raw.trim()) return fail(error('json', 'the file is empty')) + return fail(error('json', `not valid JSON: ${jsonSyntaxError(raw) ?? (e as Error).message}`)) + } + if (!isObj(d)) return fail(error('object', 'not a podcast: the file is not a JSON object')) + if (d.version !== 1) { + return fail(error('version', d.version === undefined ? 'no "version" (this player reads version 1)' : `version ${JSON.stringify(d.version)}: this player reads version 1`, d.version === undefined ? [] : ['version'])) + } + const errors: PodcastProblem[] = [] + // The audio. + const audio = typeof d.audio === 'string' ? d.audio.trim() : '' + if (!audio) errors.push(error('audio', d.audio === undefined ? 'no "audio": the audio file, relative to this file' : '"audio" is not a file name', d.audio === undefined ? [] : ['audio'])) + else { + const where = audioPathProblem(audio) + if (where) errors.push(error('audio-outside', where, ['audio'])) + else if (ctx.audio && !ctx.audio.exists) errors.push(error('audio-missing', `the audio file ${audio} isn't there`, ['audio'])) + else if (ctx.audio && ctx.audio.size === 0) errors.push(error('audio-empty', `the audio file ${audio} is empty`, ['audio'])) + } + // The segments: missing, not a list, empty (F42). + if (d.segments === undefined) errors.push(error('segments', 'no "segments": the parts of the episode')) + else if (!Array.isArray(d.segments)) errors.push(error('segments', `"segments" is not a list (it is ${typeof d.segments === 'object' ? 'an object' : `a ${typeof d.segments}`})`, ['segments'])) + else if (!d.segments.length) errors.push(error('segments', '"segments" is empty: the episode has no parts', ['segments'])) + + const j = isObj(d.journey) ? d.journey : {} + const segs: unknown[] = Array.isArray(d.segments) ? d.segments : [] + const written: { s: WrittenSegment; i: number }[] = [] + segs.forEach((s, i) => { + if (isObj(s)) written.push({ s: s as WrittenSegment, i }) + else problems.push(warning('segment', `segment #${i + 1} is not an object; skipped`, ['segments', i])) + }) + const podcast: Podcast = { + version: 1, + title: typeof d.title === 'string' ? d.title : '', + journey: { id: typeof j.id === 'string' ? j.id : '', file: typeof j.file === 'string' ? j.file : undefined, commit: typeof j.commit === 'string' ? j.commit : undefined }, + audio, + duration: num(d.duration), + // Each segment at its index in the file, so that problems point at it (the ones not objects are left out below). + segments: written.map((x) => x.s), + } + // The journey it was written for (F40). + if (podcast.journey.id && ctx.journey && podcast.journey.id !== ctx.journey.id) { + problems.push(warning('journey', `written for journey "${podcast.journey.id}", but it is next to "${ctx.journey.id}": it plays with the journey next to it`, ['journey', 'id'])) + } + if (d.duration !== undefined && !(num(d.duration)! > 0)) problems.push(warning('duration', `"duration" ${JSON.stringify(d.duration)} is not a length in seconds; ignored`, ['duration'])) + + problems.push(...timingProblems(written, podcast.duration)) + // Where each segment is shown (an unknown step, a beat the step doesn't have: F30), when the journey is known. + let episode: Episode | undefined + if (ctx.journey) { + episode = resolveEpisode(podcast, ctx.journey) + // resolveEpisode's indexes are into podcast.segments: back to the file's. + for (const p of episode.problems) { + const k = p.path[1] + if (typeof k === 'number') p.path = ['segments', written[k]?.i ?? k, ...p.path.slice(2)] + } + // Its start-time warnings are timingProblems' already. + problems.push(...episode.problems.filter((p) => p.code !== 'start')) + episode.problems = episode.problems.filter((p) => p.code !== 'start') + episode.warnings = episode.problems.map((p) => p.message) + } + // The audio's real length, once known (F43, F37). + if (ctx.audioDuration !== undefined && ctx.audioDuration > 0) problems.push(...audioLengthProblems(written, podcast.duration, ctx.audioDuration)) + + if (written.length && !written.some((x) => num(x.s.start) !== undefined && num(x.s.start)! >= 0)) { + errors.push(error('segments', 'no segment has a start time: nothing to play', ['segments'])) + } + problems.sort((a, b) => order(a.path) - order(b.path)) + const all = [...errors, ...problems] + const playable = !errors.length + return { podcast, episode: playable ? episode : undefined, problems: all, playable } +} + +/** File order of a problem: the segment's index (file-level ones first). */ +const order = (path: (string | number)[]) => (path[0] === 'segments' && typeof path[1] === 'number' ? path[1] + 1 : 0) + +/** Start, end and order of the segments (F35): each problem on its segment. */ +function timingProblems(written: { s: WrittenSegment; i: number }[], duration: number | undefined): PodcastProblem[] { + const out: PodcastProblem[] = [] + const ids = new Map() + let prevInFile: { name: string; start: number } | undefined + const timed: { s: WrittenSegment; i: number; start: number; end?: number }[] = [] + for (const { s, i } of written) { + const name = segmentName(s, i) + if (typeof s.id === 'string' && s.id) { + if (ids.has(s.id)) out.push(segProblem(s, i, 'id', `the id "${s.id}" is used by segment #${ids.get(s.id)! + 1} too`, ['id'])) + else ids.set(s.id, i) + } + if (s.cue !== undefined && !(typeof s.cue === 'string' && CUES.has(s.cue))) out.push(segProblem(s, i, 'cue', `cue ${JSON.stringify(s.cue)} is not map, open or beat; ignored`, ['cue'])) + const start = num(s.start) + if (start === undefined || start < 0) { + out.push(segProblem(s, i, 'start', `${s.start === undefined ? 'no start time' : `start ${JSON.stringify(s.start)} is not a time in seconds`}; skipped`, s.start === undefined ? [] : ['start'])) + continue + } + let end = num(s.end) + if (s.end !== undefined && end === undefined) out.push(segProblem(s, i, 'end', `end ${JSON.stringify(s.end)} is not a time in seconds; it ends where the next one starts`, ['end'])) + if (end !== undefined && end < start - SLACK_S) { + out.push(segProblem(s, i, 'end-before-start', `ends at ${clockMs(end)}, before it starts (${clockMs(start)})`, ['end'])) + end = undefined + } + if (prevInFile && start < prevInFile.start - SLACK_S) { + out.push(segProblem(s, i, 'order', `starts at ${clockMs(start)}, before segment ${prevInFile.name} above it (${clockMs(prevInFile.start)}): segments play in time order, not in file order`, ['start'])) + } + if (duration !== undefined && duration > 0 && (end ?? start) > duration + SLACK_S) { + out.push(segProblem(s, i, 'past-duration', `${end !== undefined ? `ends at ${clockMs(end)}` : `starts at ${clockMs(start)}`}, after the episode's "duration" (${clockMs(duration)})`, [end !== undefined ? 'end' : 'start'])) + } + prevInFile = { name, start } + timed.push({ s, i, start, end }) + } + // Overlaps, in time order: a segment starting before the one before it ends. + const sorted = [...timed].sort((a, b) => a.start - b.start || a.i - b.i) + for (let k = 1; k < sorted.length; k++) { + const a = sorted[k - 1], b = sorted[k] + if (a.end !== undefined && b.start < a.end - SLACK_S) { + out.push(segProblem(b.s, b.i, 'overlap', `starts at ${clockMs(b.start)}, before segment ${segmentName(a.s, a.i)} ends (${clockMs(a.end)}): the later one wins from its start`, ['start'])) + } + } + return out +} + +/** The segments and the declared duration against the audio's real length. */ +function audioLengthProblems(written: { s: WrittenSegment; i: number }[], duration: number | undefined, audioLen: number): PodcastProblem[] { + const out: PodcastProblem[] = [] + const ends = written.map(({ s }) => num(s.end) ?? num(s.start)).filter((x): x is number => x !== undefined) + const episodeLen = Math.max(duration ?? 0, ...ends, 0) + const slack = Math.max(DURATION_SLACK_S, audioLen * DURATION_SLACK_SHARE) + const past = written.filter(({ s }) => (num(s.start) ?? -1) >= audioLen) + if (episodeLen > audioLen + Math.max(2, slack) && past.length) { + // Cut off: one plain sentence, not a warning per part. + out.push(warning('audio-short', `The audio is ${clock(audioLen)} long but the episode is ${clock(episodeLen)}: the file looks cut off (${past.length} ${past.length === 1 ? 'part starts' : 'parts start'} after its end)`, ['audio'])) + return out + } + if (duration !== undefined && Math.abs(duration - audioLen) > slack) { + out.push(warning('duration', `"duration" says ${clockMs(duration)} but the audio is ${clockMs(audioLen)} long`, ['duration'])) + } + for (const { s, i } of written) { + const end = num(s.end) + if (end !== undefined && end > audioLen + slack) out.push(segProblem(s, i, 'past-audio', `ends at ${clockMs(end)}, after the audio's end (${clockMs(audioLen)})`, ['end'])) + } + return out +} + +/** m:ss.s: a time in a message, precise enough to find the segment. */ +function clockMs(t: number): string { + const tenths = Math.round(t * 10) / 10 + const whole = Math.floor(tenths) + const frac = Math.round((tenths - whole) * 10) + return frac ? `${clock(whole)}.${frac}` : clock(whole) +} + +// ---------- what the panel and the Journeys view say ---------- + +/** How many segments can't be shown as written (an unknown step, a beat the step doesn't have, no "at"). */ +export const brokenLinks = (problems: PodcastProblem[]) => new Set(problems.filter((p) => LINK_CODES.has(p.code)).map((p) => p.segment)).size + +/** + * One short line about what is wrong with a podcast that plays (undefined: nothing to say). `writtenFor`: the title of + * the journey it was written for, when it is another one. + */ +export function playNotice(problems: PodcastProblem[], writtenFor?: string): string | undefined { + const parts: string[] = [] + const short = problems.find((p) => p.code === 'audio-short') + if (short) parts.push(short.message.replace(/ \(\d+ parts? starts? after its end\)$/, '')) + if (problems.some((p) => p.code === 'journey')) parts.push(`Written for “${writtenFor ?? problems.find((p) => p.code === 'journey')!.message.match(/"([^"]*)"/)![1]}”`) + const links = brokenLinks(problems) + if (links) parts.push(`${links} ${links === 1 ? "part can't" : "parts can't"} be shown`) + const rest = problems.filter((p) => p.level === 'warning' && p.code !== 'audio-short' && p.code !== 'journey' && !LINK_CODES.has(p.code)).length + if (rest && parts.length < 2) parts.push(`${rest} ${rest === 1 ? 'problem' : 'problems'} in the podcast file`) + return parts.length ? parts.slice(0, 2).join(' · ') : undefined +} + +// ---------- where a problem is in the text ---------- + +/** A range of the text (offsets). */ +export interface Span { start: number; end: number } + +/** + * Where the value at `path` is in the JSON text (the deepest part of the path that is there; the whole text when + * none is). For invalid JSON, the place the parser stopped. + */ +export function locate(raw: string, path: (string | number)[]): Span { + let spans: Map + try { spans = valueSpans(raw) } catch (e) { + const at = e instanceof JsonSyntax ? e.at : 0 + return { start: at, end: Math.min(raw.length, at + 1) } + } + for (let n = path.length; n >= 0; n--) { + const s = spans.get(JSON.stringify(path.slice(0, n))) + if (s) return s + } + return { start: 0, end: 0 } +} + +/** Where invalid JSON stops being JSON, and what was there. */ +export class JsonSyntax extends Error { + constructor(readonly at: number, what: string) { super(what) } +} + +/** Invalid JSON said for an author: "line 3, column 12: unexpected "}"" (the engine's own message names no place). */ +export function jsonSyntaxError(raw: string): string | undefined { + try { valueSpans(raw); return undefined } catch (e) { + if (!(e instanceof JsonSyntax)) return String(e) + const { line, col } = lineCol(raw, e.at) + return `line ${line + 1}, column ${col + 1}: ${e.message}` + } +} + +/** Every value's span in the JSON text, by its path (JSON of the keys and indexes); a key's value spans from the key. + * Strict: anything that isn't JSON throws a JsonSyntax with its place. */ +function valueSpans(raw: string): Map { + const out = new Map() + let i = 0 + const bad = (what?: string): never => { + throw new JsonSyntax(i, what ?? (i >= raw.length ? 'the file ends too early (cut off?)' : `unexpected ${JSON.stringify(raw[i])}`)) + } + const ws = () => { while (i < raw.length && ' \t\n\r'.includes(raw[i])) i++ } + const expect = (c: string) => { ws(); if (raw[i] !== c) bad(i >= raw.length ? undefined : `expected ${JSON.stringify(c)}, found ${JSON.stringify(raw[i])}`); i++ } + const str = (): string => { + if (raw[i] !== '"') bad() + const s = i + i++ + while (i < raw.length && raw[i] !== '"') { + if (raw[i] === '\n') bad('a line break inside a string') + i += raw[i] === '\\' ? 2 : 1 + } + if (i >= raw.length) bad() + i++ + try { return JSON.parse(raw.slice(s, i)) as string } catch { i = s; return bad('a bad escape in a string') } + } + const value = (path: (string | number)[], from?: number): void => { + ws() + const start = from ?? i + const c = raw[i] + if (c === '{') { + i++ + ws() + if (raw[i] === '}') i++ + else for (;;) { + ws() + const keyAt = i + const k = str() + expect(':') + value([...path, k], keyAt) + ws() + if (raw[i] === ',') { i++; continue } + if (raw[i] === '}') { i++; break } + bad(i >= raw.length ? undefined : `expected "," or "}", found ${JSON.stringify(raw[i])}`) + } + } else if (c === '[') { + i++ + ws() + let n = 0 + if (raw[i] === ']') i++ + else for (;;) { + value([...path, n++]) + ws() + if (raw[i] === ',') { i++; continue } + if (raw[i] === ']') { i++; break } + bad(i >= raw.length ? undefined : `expected "," or "]", found ${JSON.stringify(raw[i])}`) + } + } else if (c === '"') str() + else { + const m = /^(?:true|false|null|-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?)/.exec(raw.slice(i, i + 64)) + if (!m) bad() + i += m![0].length + } + out.set(JSON.stringify(path), { start, end: i }) + } + value([]) + ws() + if (i < raw.length) bad() + return out +} + +/** Line and column (0-based) of an offset. */ +export function lineCol(raw: string, offset: number): { line: number; col: number } { + let line = 0, last = -1 + for (let k = 0; k < offset && k < raw.length; k++) if (raw[k] === '\n') { line++; last = k } + return { line, col: offset - last - 1 } +} diff --git a/test/fixtures/podcast/cases.json b/test/fixtures/podcast/cases.json new file mode 100644 index 0000000..0127d81 --- /dev/null +++ b/test/fixtures/podcast/cases.json @@ -0,0 +1,822 @@ +[ + { + "name": "a good file: no problems, unknown fields (say) accepted", + "audio": { + "exists": true, + "size": 1000 + }, + "audioDuration": 100.3, + "expect": [], + "raw": "{\n \"version\": 1,\n \"title\": \"T\",\n \"journey\": {\n \"id\": \"j\"\n },\n \"audio\": \"j.mp3\",\n \"duration\": 100,\n \"segments\": [\n {\n \"id\": \"intro\",\n \"at\": null,\n \"speaker\": \"host\",\n \"text\": \"intro\",\n \"start\": 0,\n \"end\": 9,\n \"say\": \"spoken intro\",\n \"extra\": 1\n },\n {\n \"id\": \"a1\",\n \"at\": {\n \"step\": \"a\",\n \"beat\": 1\n },\n \"speaker\": \"host\",\n \"text\": \"a1\",\n \"start\": 10,\n \"end\": 19,\n \"say\": \"spoken a1\",\n \"extra\": 1\n },\n {\n \"id\": \"b\",\n \"at\": {\n \"step\": \"b\"\n },\n \"speaker\": \"host\",\n \"text\": \"b\",\n \"start\": 20,\n \"end\": 29,\n \"say\": \"spoken b\",\n \"extra\": 1\n },\n {\n \"id\": \"c2\",\n \"at\": {\n \"step\": \"c\",\n \"beat\": 2\n },\n \"speaker\": \"host\",\n \"text\": \"c2\",\n \"start\": 30,\n \"end\": 39,\n \"say\": \"spoken c2\",\n \"extra\": 1\n },\n {\n \"id\": \"outro\",\n \"at\": null,\n \"speaker\": \"host\",\n \"text\": \"outro\",\n \"start\": 40,\n \"end\": 100,\n \"say\": \"spoken outro\",\n \"extra\": 1\n }\n ],\n \"producer\": \"tts\"\n}", + "journey": { + "id": "j", + "steps": [ + { + "id": "a", + "beats": 3 + }, + { + "id": "b", + "beats": 0 + }, + { + "id": "c", + "beats": 2 + } + ] + } + }, + { + "name": "invalid JSON", + "raw": "{\"version\": 1, \"audio\": \"j.mp3\", \"segments\": [", + "audio": { + "exists": true, + "size": 1000 + }, + "expect": [ + "error:json" + ], + "journey": { + "id": "j", + "steps": [ + { + "id": "a", + "beats": 3 + }, + { + "id": "b", + "beats": 0 + }, + { + "id": "c", + "beats": 2 + } + ] + } + }, + { + "name": "an empty file", + "raw": "", + "expect": [ + "error:json" + ], + "journey": { + "id": "j", + "steps": [ + { + "id": "a", + "beats": 3 + }, + { + "id": "b", + "beats": 0 + }, + { + "id": "c", + "beats": 2 + } + ] + } + }, + { + "name": "not an object", + "raw": "[1, 2]", + "expect": [ + "error:object" + ], + "journey": { + "id": "j", + "steps": [ + { + "id": "a", + "beats": 3 + }, + { + "id": "b", + "beats": 0 + }, + { + "id": "c", + "beats": 2 + } + ] + } + }, + { + "name": "version 2", + "audio": { + "exists": true, + "size": 1000 + }, + "expect": [ + "error:version" + ], + "raw": "{\n \"version\": 2,\n \"title\": \"T\",\n \"journey\": {\n \"id\": \"j\"\n },\n \"audio\": \"j.mp3\",\n \"duration\": 100,\n \"segments\": [\n {\n \"id\": \"intro\",\n \"at\": null,\n \"speaker\": \"host\",\n \"text\": \"intro\",\n \"start\": 0,\n \"end\": 9\n },\n {\n \"id\": \"a1\",\n \"at\": {\n \"step\": \"a\",\n \"beat\": 1\n },\n \"speaker\": \"host\",\n \"text\": \"a1\",\n \"start\": 10,\n \"end\": 19\n },\n {\n \"id\": \"b\",\n \"at\": {\n \"step\": \"b\"\n },\n \"speaker\": \"host\",\n \"text\": \"b\",\n \"start\": 20,\n \"end\": 29\n },\n {\n \"id\": \"c2\",\n \"at\": {\n \"step\": \"c\",\n \"beat\": 2\n },\n \"speaker\": \"host\",\n \"text\": \"c2\",\n \"start\": 30,\n \"end\": 39\n },\n {\n \"id\": \"outro\",\n \"at\": null,\n \"speaker\": \"host\",\n \"text\": \"outro\",\n \"start\": 40,\n \"end\": 100\n }\n ]\n}", + "journey": { + "id": "j", + "steps": [ + { + "id": "a", + "beats": 3 + }, + { + "id": "b", + "beats": 0 + }, + { + "id": "c", + "beats": 2 + } + ] + } + }, + { + "name": "no version", + "audio": { + "exists": true, + "size": 1000 + }, + "expect": [ + "error:version" + ], + "raw": "{\n \"title\": \"T\",\n \"journey\": {\n \"id\": \"j\"\n },\n \"audio\": \"j.mp3\",\n \"duration\": 100,\n \"segments\": [\n {\n \"id\": \"intro\",\n \"at\": null,\n \"speaker\": \"host\",\n \"text\": \"intro\",\n \"start\": 0,\n \"end\": 9\n },\n {\n \"id\": \"a1\",\n \"at\": {\n \"step\": \"a\",\n \"beat\": 1\n },\n \"speaker\": \"host\",\n \"text\": \"a1\",\n \"start\": 10,\n \"end\": 19\n },\n {\n \"id\": \"b\",\n \"at\": {\n \"step\": \"b\"\n },\n \"speaker\": \"host\",\n \"text\": \"b\",\n \"start\": 20,\n \"end\": 29\n },\n {\n \"id\": \"c2\",\n \"at\": {\n \"step\": \"c\",\n \"beat\": 2\n },\n \"speaker\": \"host\",\n \"text\": \"c2\",\n \"start\": 30,\n \"end\": 39\n },\n {\n \"id\": \"outro\",\n \"at\": null,\n \"speaker\": \"host\",\n \"text\": \"outro\",\n \"start\": 40,\n \"end\": 100\n }\n ]\n}", + "journey": { + "id": "j", + "steps": [ + { + "id": "a", + "beats": 3 + }, + { + "id": "b", + "beats": 0 + }, + { + "id": "c", + "beats": 2 + } + ] + } + }, + { + "name": "no audio field", + "expect": [ + "error:audio" + ], + "raw": "{\n \"version\": 1,\n \"title\": \"T\",\n \"journey\": {\n \"id\": \"j\"\n },\n \"duration\": 100,\n \"segments\": [\n {\n \"id\": \"intro\",\n \"at\": null,\n \"speaker\": \"host\",\n \"text\": \"intro\",\n \"start\": 0,\n \"end\": 9\n },\n {\n \"id\": \"a1\",\n \"at\": {\n \"step\": \"a\",\n \"beat\": 1\n },\n \"speaker\": \"host\",\n \"text\": \"a1\",\n \"start\": 10,\n \"end\": 19\n },\n {\n \"id\": \"b\",\n \"at\": {\n \"step\": \"b\"\n },\n \"speaker\": \"host\",\n \"text\": \"b\",\n \"start\": 20,\n \"end\": 29\n },\n {\n \"id\": \"c2\",\n \"at\": {\n \"step\": \"c\",\n \"beat\": 2\n },\n \"speaker\": \"host\",\n \"text\": \"c2\",\n \"start\": 30,\n \"end\": 39\n },\n {\n \"id\": \"outro\",\n \"at\": null,\n \"speaker\": \"host\",\n \"text\": \"outro\",\n \"start\": 40,\n \"end\": 100\n }\n ]\n}", + "journey": { + "id": "j", + "steps": [ + { + "id": "a", + "beats": 3 + }, + { + "id": "b", + "beats": 0 + }, + { + "id": "c", + "beats": 2 + } + ] + } + }, + { + "name": "audio outside the journeys folder", + "expect": [ + "error:audio-outside" + ], + "raw": "{\n \"version\": 1,\n \"title\": \"T\",\n \"journey\": {\n \"id\": \"j\"\n },\n \"audio\": \"../x.mp3\",\n \"duration\": 100,\n \"segments\": [\n {\n \"id\": \"intro\",\n \"at\": null,\n \"speaker\": \"host\",\n \"text\": \"intro\",\n \"start\": 0,\n \"end\": 9\n },\n {\n \"id\": \"a1\",\n \"at\": {\n \"step\": \"a\",\n \"beat\": 1\n },\n \"speaker\": \"host\",\n \"text\": \"a1\",\n \"start\": 10,\n \"end\": 19\n },\n {\n \"id\": \"b\",\n \"at\": {\n \"step\": \"b\"\n },\n \"speaker\": \"host\",\n \"text\": \"b\",\n \"start\": 20,\n \"end\": 29\n },\n {\n \"id\": \"c2\",\n \"at\": {\n \"step\": \"c\",\n \"beat\": 2\n },\n \"speaker\": \"host\",\n \"text\": \"c2\",\n \"start\": 30,\n \"end\": 39\n },\n {\n \"id\": \"outro\",\n \"at\": null,\n \"speaker\": \"host\",\n \"text\": \"outro\",\n \"start\": 40,\n \"end\": 100\n }\n ]\n}", + "journey": { + "id": "j", + "steps": [ + { + "id": "a", + "beats": 3 + }, + { + "id": "b", + "beats": 0 + }, + { + "id": "c", + "beats": 2 + } + ] + } + }, + { + "name": "audio by absolute path", + "expect": [ + "error:audio-outside" + ], + "raw": "{\n \"version\": 1,\n \"title\": \"T\",\n \"journey\": {\n \"id\": \"j\"\n },\n \"audio\": \"/tmp/x.mp3\",\n \"duration\": 100,\n \"segments\": [\n {\n \"id\": \"intro\",\n \"at\": null,\n \"speaker\": \"host\",\n \"text\": \"intro\",\n \"start\": 0,\n \"end\": 9\n },\n {\n \"id\": \"a1\",\n \"at\": {\n \"step\": \"a\",\n \"beat\": 1\n },\n \"speaker\": \"host\",\n \"text\": \"a1\",\n \"start\": 10,\n \"end\": 19\n },\n {\n \"id\": \"b\",\n \"at\": {\n \"step\": \"b\"\n },\n \"speaker\": \"host\",\n \"text\": \"b\",\n \"start\": 20,\n \"end\": 29\n },\n {\n \"id\": \"c2\",\n \"at\": {\n \"step\": \"c\",\n \"beat\": 2\n },\n \"speaker\": \"host\",\n \"text\": \"c2\",\n \"start\": 30,\n \"end\": 39\n },\n {\n \"id\": \"outro\",\n \"at\": null,\n \"speaker\": \"host\",\n \"text\": \"outro\",\n \"start\": 40,\n \"end\": 100\n }\n ]\n}", + "journey": { + "id": "j", + "steps": [ + { + "id": "a", + "beats": 3 + }, + { + "id": "b", + "beats": 0 + }, + { + "id": "c", + "beats": 2 + } + ] + } + }, + { + "name": "audio as a URL", + "expect": [ + "error:audio-outside" + ], + "raw": "{\n \"version\": 1,\n \"title\": \"T\",\n \"journey\": {\n \"id\": \"j\"\n },\n \"audio\": \"https://example.com/x.mp3\",\n \"duration\": 100,\n \"segments\": [\n {\n \"id\": \"intro\",\n \"at\": null,\n \"speaker\": \"host\",\n \"text\": \"intro\",\n \"start\": 0,\n \"end\": 9\n },\n {\n \"id\": \"a1\",\n \"at\": {\n \"step\": \"a\",\n \"beat\": 1\n },\n \"speaker\": \"host\",\n \"text\": \"a1\",\n \"start\": 10,\n \"end\": 19\n },\n {\n \"id\": \"b\",\n \"at\": {\n \"step\": \"b\"\n },\n \"speaker\": \"host\",\n \"text\": \"b\",\n \"start\": 20,\n \"end\": 29\n },\n {\n \"id\": \"c2\",\n \"at\": {\n \"step\": \"c\",\n \"beat\": 2\n },\n \"speaker\": \"host\",\n \"text\": \"c2\",\n \"start\": 30,\n \"end\": 39\n },\n {\n \"id\": \"outro\",\n \"at\": null,\n \"speaker\": \"host\",\n \"text\": \"outro\",\n \"start\": 40,\n \"end\": 100\n }\n ]\n}", + "journey": { + "id": "j", + "steps": [ + { + "id": "a", + "beats": 3 + }, + { + "id": "b", + "beats": 0 + }, + { + "id": "c", + "beats": 2 + } + ] + } + }, + { + "name": "audio in a subfolder is fine", + "audio": { + "exists": true, + "size": 1000 + }, + "expect": [], + "raw": "{\n \"version\": 1,\n \"title\": \"T\",\n \"journey\": {\n \"id\": \"j\"\n },\n \"audio\": \"audio/../audio/j.mp3\",\n \"duration\": 100,\n \"segments\": [\n {\n \"id\": \"intro\",\n \"at\": null,\n \"speaker\": \"host\",\n \"text\": \"intro\",\n \"start\": 0,\n \"end\": 9\n },\n {\n \"id\": \"a1\",\n \"at\": {\n \"step\": \"a\",\n \"beat\": 1\n },\n \"speaker\": \"host\",\n \"text\": \"a1\",\n \"start\": 10,\n \"end\": 19\n },\n {\n \"id\": \"b\",\n \"at\": {\n \"step\": \"b\"\n },\n \"speaker\": \"host\",\n \"text\": \"b\",\n \"start\": 20,\n \"end\": 29\n },\n {\n \"id\": \"c2\",\n \"at\": {\n \"step\": \"c\",\n \"beat\": 2\n },\n \"speaker\": \"host\",\n \"text\": \"c2\",\n \"start\": 30,\n \"end\": 39\n },\n {\n \"id\": \"outro\",\n \"at\": null,\n \"speaker\": \"host\",\n \"text\": \"outro\",\n \"start\": 40,\n \"end\": 100\n }\n ]\n}", + "journey": { + "id": "j", + "steps": [ + { + "id": "a", + "beats": 3 + }, + { + "id": "b", + "beats": 0 + }, + { + "id": "c", + "beats": 2 + } + ] + } + }, + { + "name": "audio file missing", + "audio": { + "exists": false + }, + "expect": [ + "error:audio-missing" + ], + "raw": "{\n \"version\": 1,\n \"title\": \"T\",\n \"journey\": {\n \"id\": \"j\"\n },\n \"audio\": \"j.mp3\",\n \"duration\": 100,\n \"segments\": [\n {\n \"id\": \"intro\",\n \"at\": null,\n \"speaker\": \"host\",\n \"text\": \"intro\",\n \"start\": 0,\n \"end\": 9\n },\n {\n \"id\": \"a1\",\n \"at\": {\n \"step\": \"a\",\n \"beat\": 1\n },\n \"speaker\": \"host\",\n \"text\": \"a1\",\n \"start\": 10,\n \"end\": 19\n },\n {\n \"id\": \"b\",\n \"at\": {\n \"step\": \"b\"\n },\n \"speaker\": \"host\",\n \"text\": \"b\",\n \"start\": 20,\n \"end\": 29\n },\n {\n \"id\": \"c2\",\n \"at\": {\n \"step\": \"c\",\n \"beat\": 2\n },\n \"speaker\": \"host\",\n \"text\": \"c2\",\n \"start\": 30,\n \"end\": 39\n },\n {\n \"id\": \"outro\",\n \"at\": null,\n \"speaker\": \"host\",\n \"text\": \"outro\",\n \"start\": 40,\n \"end\": 100\n }\n ]\n}", + "journey": { + "id": "j", + "steps": [ + { + "id": "a", + "beats": 3 + }, + { + "id": "b", + "beats": 0 + }, + { + "id": "c", + "beats": 2 + } + ] + } + }, + { + "name": "audio file empty", + "audio": { + "exists": true, + "size": 0 + }, + "expect": [ + "error:audio-empty" + ], + "raw": "{\n \"version\": 1,\n \"title\": \"T\",\n \"journey\": {\n \"id\": \"j\"\n },\n \"audio\": \"j.mp3\",\n \"duration\": 100,\n \"segments\": [\n {\n \"id\": \"intro\",\n \"at\": null,\n \"speaker\": \"host\",\n \"text\": \"intro\",\n \"start\": 0,\n \"end\": 9\n },\n {\n \"id\": \"a1\",\n \"at\": {\n \"step\": \"a\",\n \"beat\": 1\n },\n \"speaker\": \"host\",\n \"text\": \"a1\",\n \"start\": 10,\n \"end\": 19\n },\n {\n \"id\": \"b\",\n \"at\": {\n \"step\": \"b\"\n },\n \"speaker\": \"host\",\n \"text\": \"b\",\n \"start\": 20,\n \"end\": 29\n },\n {\n \"id\": \"c2\",\n \"at\": {\n \"step\": \"c\",\n \"beat\": 2\n },\n \"speaker\": \"host\",\n \"text\": \"c2\",\n \"start\": 30,\n \"end\": 39\n },\n {\n \"id\": \"outro\",\n \"at\": null,\n \"speaker\": \"host\",\n \"text\": \"outro\",\n \"start\": 40,\n \"end\": 100\n }\n ]\n}", + "journey": { + "id": "j", + "steps": [ + { + "id": "a", + "beats": 3 + }, + { + "id": "b", + "beats": 0 + }, + { + "id": "c", + "beats": 2 + } + ] + } + }, + { + "name": "segments missing", + "audio": { + "exists": true, + "size": 1000 + }, + "expect": [ + "error:segments" + ], + "raw": "{\n \"version\": 1,\n \"title\": \"T\",\n \"journey\": {\n \"id\": \"j\"\n },\n \"audio\": \"j.mp3\",\n \"duration\": 100\n}", + "journey": { + "id": "j", + "steps": [ + { + "id": "a", + "beats": 3 + }, + { + "id": "b", + "beats": 0 + }, + { + "id": "c", + "beats": 2 + } + ] + } + }, + { + "name": "segments empty", + "audio": { + "exists": true, + "size": 1000 + }, + "expect": [ + "error:segments" + ], + "raw": "{\n \"version\": 1,\n \"title\": \"T\",\n \"journey\": {\n \"id\": \"j\"\n },\n \"audio\": \"j.mp3\",\n \"duration\": 100,\n \"segments\": []\n}", + "journey": { + "id": "j", + "steps": [ + { + "id": "a", + "beats": 3 + }, + { + "id": "b", + "beats": 0 + }, + { + "id": "c", + "beats": 2 + } + ] + } + }, + { + "name": "segments not a list", + "audio": { + "exists": true, + "size": 1000 + }, + "expect": [ + "error:segments" + ], + "raw": "{\n \"version\": 1,\n \"title\": \"T\",\n \"journey\": {\n \"id\": \"j\"\n },\n \"audio\": \"j.mp3\",\n \"duration\": 100,\n \"segments\": {\n \"s1\": {\n \"id\": \"intro\",\n \"at\": null,\n \"speaker\": \"host\",\n \"text\": \"intro\",\n \"start\": 0,\n \"end\": 9\n }\n }\n}", + "journey": { + "id": "j", + "steps": [ + { + "id": "a", + "beats": 3 + }, + { + "id": "b", + "beats": 0 + }, + { + "id": "c", + "beats": 2 + } + ] + } + }, + { + "name": "no segment has a start", + "audio": { + "exists": true, + "size": 1000 + }, + "expect": [ + "error:segments", + "warning:start@x" + ], + "raw": "{\n \"version\": 1,\n \"title\": \"T\",\n \"journey\": {\n \"id\": \"j\"\n },\n \"audio\": \"j.mp3\",\n \"duration\": 100,\n \"segments\": [\n {\n \"id\": \"x\",\n \"at\": null\n }\n ]\n}", + "journey": { + "id": "j", + "steps": [ + { + "id": "a", + "beats": 3 + }, + { + "id": "b", + "beats": 0 + }, + { + "id": "c", + "beats": 2 + } + ] + } + }, + { + "name": "a segment that is not an object is skipped", + "audio": { + "exists": true, + "size": 1000 + }, + "expect": [ + "warning:segment" + ], + "raw": "{\n \"version\": 1,\n \"title\": \"T\",\n \"journey\": {\n \"id\": \"j\"\n },\n \"audio\": \"j.mp3\",\n \"duration\": 100,\n \"segments\": [\n {\n \"id\": \"intro\",\n \"at\": null,\n \"speaker\": \"host\",\n \"text\": \"intro\",\n \"start\": 0,\n \"end\": 9\n },\n {\n \"id\": \"a1\",\n \"at\": {\n \"step\": \"a\",\n \"beat\": 1\n },\n \"speaker\": \"host\",\n \"text\": \"a1\",\n \"start\": 10,\n \"end\": 19\n },\n {\n \"id\": \"b\",\n \"at\": {\n \"step\": \"b\"\n },\n \"speaker\": \"host\",\n \"text\": \"b\",\n \"start\": 20,\n \"end\": 29\n },\n {\n \"id\": \"c2\",\n \"at\": {\n \"step\": \"c\",\n \"beat\": 2\n },\n \"speaker\": \"host\",\n \"text\": \"c2\",\n \"start\": 30,\n \"end\": 39\n },\n {\n \"id\": \"outro\",\n \"at\": null,\n \"speaker\": \"host\",\n \"text\": \"outro\",\n \"start\": 40,\n \"end\": 100\n },\n \"oops\"\n ]\n}", + "journey": { + "id": "j", + "steps": [ + { + "id": "a", + "beats": 3 + }, + { + "id": "b", + "beats": 0 + }, + { + "id": "c", + "beats": 2 + } + ] + } + }, + { + "name": "broken links: a beat out of range, an unknown step, a bad at", + "audio": { + "exists": true, + "size": 1000 + }, + "expect": [ + "warning:beat@a9", + "warning:step@x", + "warning:at@bad" + ], + "raw": "{\n \"version\": 1,\n \"title\": \"T\",\n \"journey\": {\n \"id\": \"j\"\n },\n \"audio\": \"j.mp3\",\n \"duration\": 100,\n \"segments\": [\n {\n \"id\": \"intro\",\n \"at\": null,\n \"speaker\": \"host\",\n \"text\": \"intro\",\n \"start\": 0,\n \"end\": 9\n },\n {\n \"id\": \"a9\",\n \"at\": {\n \"step\": \"a\",\n \"beat\": 9\n },\n \"speaker\": \"host\",\n \"text\": \"a9\",\n \"start\": 10,\n \"end\": 19\n },\n {\n \"id\": \"x\",\n \"at\": {\n \"step\": \"nope\"\n },\n \"speaker\": \"host\",\n \"text\": \"x\",\n \"start\": 20,\n \"end\": 29\n },\n {\n \"id\": \"bad\",\n \"at\": \"step c\",\n \"speaker\": \"host\",\n \"text\": \"bad\",\n \"start\": 30,\n \"end\": 39\n },\n {\n \"id\": \"none\",\n \"at\": null,\n \"speaker\": \"host\",\n \"text\": \"none\",\n \"start\": 40,\n \"end\": 50\n }\n ]\n}", + "journey": { + "id": "j", + "steps": [ + { + "id": "a", + "beats": 3 + }, + { + "id": "b", + "beats": 0 + }, + { + "id": "c", + "beats": 2 + } + ] + } + }, + { + "name": "a missing at", + "audio": { + "exists": true, + "size": 1000 + }, + "expect": [ + "warning:at@noat" + ], + "raw": "{\n \"version\": 1,\n \"title\": \"T\",\n \"journey\": {\n \"id\": \"j\"\n },\n \"audio\": \"j.mp3\",\n \"duration\": 100,\n \"segments\": [\n {\n \"id\": \"intro\",\n \"at\": null,\n \"speaker\": \"host\",\n \"text\": \"intro\",\n \"start\": 0,\n \"end\": 9\n },\n {\n \"id\": \"noat\",\n \"start\": 10,\n \"end\": 20\n }\n ]\n}", + "journey": { + "id": "j", + "steps": [ + { + "id": "a", + "beats": 3 + }, + { + "id": "b", + "beats": 0 + }, + { + "id": "c", + "beats": 2 + } + ] + } + }, + { + "name": "overlap, out of order, end before start", + "audio": { + "exists": true, + "size": 1000 + }, + "expect": [ + "warning:overlap@s2", + "warning:order@s3", + "warning:end-before-start@s3" + ], + "raw": "{\n \"version\": 1,\n \"title\": \"T\",\n \"journey\": {\n \"id\": \"j\"\n },\n \"audio\": \"j.mp3\",\n \"duration\": 100,\n \"segments\": [\n {\n \"id\": \"s1\",\n \"at\": null,\n \"speaker\": \"host\",\n \"text\": \"s1\",\n \"start\": 0,\n \"end\": 10\n },\n {\n \"id\": \"s2\",\n \"at\": {\n \"step\": \"a\"\n },\n \"speaker\": \"host\",\n \"text\": \"s2\",\n \"start\": 8,\n \"end\": 20\n },\n {\n \"id\": \"s4\",\n \"at\": {\n \"step\": \"b\"\n },\n \"speaker\": \"host\",\n \"text\": \"s4\",\n \"start\": 40,\n \"end\": 50\n },\n {\n \"id\": \"s3\",\n \"at\": {\n \"step\": \"c\"\n },\n \"speaker\": \"host\",\n \"text\": \"s3\",\n \"start\": 30,\n \"end\": 25\n }\n ]\n}", + "journey": { + "id": "j", + "steps": [ + { + "id": "a", + "beats": 3 + }, + { + "id": "b", + "beats": 0 + }, + { + "id": "c", + "beats": 2 + } + ] + } + }, + { + "name": "end past the declared duration", + "audio": { + "exists": true, + "size": 1000 + }, + "expect": [ + "warning:past-duration@s2" + ], + "raw": "{\n \"version\": 1,\n \"title\": \"T\",\n \"journey\": {\n \"id\": \"j\"\n },\n \"audio\": \"j.mp3\",\n \"duration\": 100,\n \"segments\": [\n {\n \"id\": \"s1\",\n \"at\": null,\n \"speaker\": \"host\",\n \"text\": \"s1\",\n \"start\": 0,\n \"end\": 10\n },\n {\n \"id\": \"s2\",\n \"at\": {\n \"step\": \"a\"\n },\n \"speaker\": \"host\",\n \"text\": \"s2\",\n \"start\": 10,\n \"end\": 150\n }\n ]\n}", + "journey": { + "id": "j", + "steps": [ + { + "id": "a", + "beats": 3 + }, + { + "id": "b", + "beats": 0 + }, + { + "id": "c", + "beats": 2 + } + ] + } + }, + { + "name": "a start that is not a number is skipped", + "audio": { + "exists": true, + "size": 1000 + }, + "expect": [ + "warning:start@s2" + ], + "raw": "{\n \"version\": 1,\n \"title\": \"T\",\n \"journey\": {\n \"id\": \"j\"\n },\n \"audio\": \"j.mp3\",\n \"duration\": 100,\n \"segments\": [\n {\n \"id\": \"s1\",\n \"at\": null,\n \"speaker\": \"host\",\n \"text\": \"s1\",\n \"start\": 0,\n \"end\": 10\n },\n {\n \"id\": \"s2\",\n \"at\": {\n \"step\": \"a\"\n },\n \"speaker\": \"host\",\n \"text\": \"s2\",\n \"start\": \"10\",\n \"end\": 20\n }\n ]\n}", + "journey": { + "id": "j", + "steps": [ + { + "id": "a", + "beats": 3 + }, + { + "id": "b", + "beats": 0 + }, + { + "id": "c", + "beats": 2 + } + ] + } + }, + { + "name": "an end that is not a number", + "audio": { + "exists": true, + "size": 1000 + }, + "expect": [ + "warning:end@s2" + ], + "raw": "{\n \"version\": 1,\n \"title\": \"T\",\n \"journey\": {\n \"id\": \"j\"\n },\n \"audio\": \"j.mp3\",\n \"duration\": 100,\n \"segments\": [\n {\n \"id\": \"s1\",\n \"at\": null,\n \"speaker\": \"host\",\n \"text\": \"s1\",\n \"start\": 0,\n \"end\": 10\n },\n {\n \"id\": \"s2\",\n \"at\": {\n \"step\": \"a\"\n },\n \"speaker\": \"host\",\n \"text\": \"s2\",\n \"start\": 10,\n \"end\": \"x\"\n }\n ]\n}", + "journey": { + "id": "j", + "steps": [ + { + "id": "a", + "beats": 3 + }, + { + "id": "b", + "beats": 0 + }, + { + "id": "c", + "beats": 2 + } + ] + } + }, + { + "name": "a duplicate id and an unknown cue", + "audio": { + "exists": true, + "size": 1000 + }, + "expect": [ + "warning:id@s1", + "warning:cue@s1" + ], + "raw": "{\n \"version\": 1,\n \"title\": \"T\",\n \"journey\": {\n \"id\": \"j\"\n },\n \"audio\": \"j.mp3\",\n \"duration\": 100,\n \"segments\": [\n {\n \"id\": \"s1\",\n \"at\": null,\n \"speaker\": \"host\",\n \"text\": \"s1\",\n \"start\": 0,\n \"end\": 10\n },\n {\n \"id\": \"s1\",\n \"at\": {\n \"step\": \"a\"\n },\n \"speaker\": \"host\",\n \"text\": \"s1\",\n \"start\": 10,\n \"end\": 20,\n \"cue\": \"zoom\"\n }\n ]\n}", + "journey": { + "id": "j", + "steps": [ + { + "id": "a", + "beats": 3 + }, + { + "id": "b", + "beats": 0 + }, + { + "id": "c", + "beats": 2 + } + ] + } + }, + { + "name": "duration is not a number", + "audio": { + "exists": true, + "size": 1000 + }, + "expect": [ + "warning:duration" + ], + "raw": "{\n \"version\": 1,\n \"title\": \"T\",\n \"journey\": {\n \"id\": \"j\"\n },\n \"audio\": \"j.mp3\",\n \"duration\": \"12:47\",\n \"segments\": [\n {\n \"id\": \"intro\",\n \"at\": null,\n \"speaker\": \"host\",\n \"text\": \"intro\",\n \"start\": 0,\n \"end\": 9\n },\n {\n \"id\": \"a1\",\n \"at\": {\n \"step\": \"a\",\n \"beat\": 1\n },\n \"speaker\": \"host\",\n \"text\": \"a1\",\n \"start\": 10,\n \"end\": 19\n },\n {\n \"id\": \"b\",\n \"at\": {\n \"step\": \"b\"\n },\n \"speaker\": \"host\",\n \"text\": \"b\",\n \"start\": 20,\n \"end\": 29\n },\n {\n \"id\": \"c2\",\n \"at\": {\n \"step\": \"c\",\n \"beat\": 2\n },\n \"speaker\": \"host\",\n \"text\": \"c2\",\n \"start\": 30,\n \"end\": 39\n },\n {\n \"id\": \"outro\",\n \"at\": null,\n \"speaker\": \"host\",\n \"text\": \"outro\",\n \"start\": 40,\n \"end\": 100\n }\n ]\n}", + "journey": { + "id": "j", + "steps": [ + { + "id": "a", + "beats": 3 + }, + { + "id": "b", + "beats": 0 + }, + { + "id": "c", + "beats": 2 + } + ] + } + }, + { + "name": "written for another journey", + "audio": { + "exists": true, + "size": 1000 + }, + "expect": [ + "warning:journey" + ], + "raw": "{\n \"version\": 1,\n \"title\": \"T\",\n \"journey\": {\n \"id\": \"other\"\n },\n \"audio\": \"j.mp3\",\n \"duration\": 100,\n \"segments\": [\n {\n \"id\": \"intro\",\n \"at\": null,\n \"speaker\": \"host\",\n \"text\": \"intro\",\n \"start\": 0,\n \"end\": 9\n },\n {\n \"id\": \"a1\",\n \"at\": {\n \"step\": \"a\",\n \"beat\": 1\n },\n \"speaker\": \"host\",\n \"text\": \"a1\",\n \"start\": 10,\n \"end\": 19\n },\n {\n \"id\": \"b\",\n \"at\": {\n \"step\": \"b\"\n },\n \"speaker\": \"host\",\n \"text\": \"b\",\n \"start\": 20,\n \"end\": 29\n },\n {\n \"id\": \"c2\",\n \"at\": {\n \"step\": \"c\",\n \"beat\": 2\n },\n \"speaker\": \"host\",\n \"text\": \"c2\",\n \"start\": 30,\n \"end\": 39\n },\n {\n \"id\": \"outro\",\n \"at\": null,\n \"speaker\": \"host\",\n \"text\": \"outro\",\n \"start\": 40,\n \"end\": 100\n }\n ]\n}", + "journey": { + "id": "j", + "steps": [ + { + "id": "a", + "beats": 3 + }, + { + "id": "b", + "beats": 0 + }, + { + "id": "c", + "beats": 2 + } + ] + } + }, + { + "name": "declared duration differs from the audio", + "audio": { + "exists": true, + "size": 1000 + }, + "audioDuration": 90, + "expect": [ + "warning:duration", + "warning:past-audio@outro" + ], + "raw": "{\n \"version\": 1,\n \"title\": \"T\",\n \"journey\": {\n \"id\": \"j\"\n },\n \"audio\": \"j.mp3\",\n \"duration\": 100,\n \"segments\": [\n {\n \"id\": \"intro\",\n \"at\": null,\n \"speaker\": \"host\",\n \"text\": \"intro\",\n \"start\": 0,\n \"end\": 9\n },\n {\n \"id\": \"a1\",\n \"at\": {\n \"step\": \"a\",\n \"beat\": 1\n },\n \"speaker\": \"host\",\n \"text\": \"a1\",\n \"start\": 10,\n \"end\": 19\n },\n {\n \"id\": \"b\",\n \"at\": {\n \"step\": \"b\"\n },\n \"speaker\": \"host\",\n \"text\": \"b\",\n \"start\": 20,\n \"end\": 29\n },\n {\n \"id\": \"c2\",\n \"at\": {\n \"step\": \"c\",\n \"beat\": 2\n },\n \"speaker\": \"host\",\n \"text\": \"c2\",\n \"start\": 30,\n \"end\": 39\n },\n {\n \"id\": \"outro\",\n \"at\": null,\n \"speaker\": \"host\",\n \"text\": \"outro\",\n \"start\": 40,\n \"end\": 100\n }\n ]\n}", + "journey": { + "id": "j", + "steps": [ + { + "id": "a", + "beats": 3 + }, + { + "id": "b", + "beats": 0 + }, + { + "id": "c", + "beats": 2 + } + ] + } + }, + { + "name": "cut-off audio: one plain warning", + "audio": { + "exists": true, + "size": 1000 + }, + "audioDuration": 13, + "expect": [ + "warning:audio-short" + ], + "raw": "{\n \"version\": 1,\n \"title\": \"T\",\n \"journey\": {\n \"id\": \"j\"\n },\n \"audio\": \"j.mp3\",\n \"duration\": 100,\n \"segments\": [\n {\n \"id\": \"intro\",\n \"at\": null,\n \"speaker\": \"host\",\n \"text\": \"intro\",\n \"start\": 0,\n \"end\": 9\n },\n {\n \"id\": \"a1\",\n \"at\": {\n \"step\": \"a\",\n \"beat\": 1\n },\n \"speaker\": \"host\",\n \"text\": \"a1\",\n \"start\": 10,\n \"end\": 19\n },\n {\n \"id\": \"b\",\n \"at\": {\n \"step\": \"b\"\n },\n \"speaker\": \"host\",\n \"text\": \"b\",\n \"start\": 20,\n \"end\": 29\n },\n {\n \"id\": \"c2\",\n \"at\": {\n \"step\": \"c\",\n \"beat\": 2\n },\n \"speaker\": \"host\",\n \"text\": \"c2\",\n \"start\": 30,\n \"end\": 39\n },\n {\n \"id\": \"outro\",\n \"at\": null,\n \"speaker\": \"host\",\n \"text\": \"outro\",\n \"start\": 40,\n \"end\": 100\n }\n ]\n}", + "journey": { + "id": "j", + "steps": [ + { + "id": "a", + "beats": 3 + }, + { + "id": "b", + "beats": 0 + }, + { + "id": "c", + "beats": 2 + } + ] + } + }, + { + "name": "audio a little longer than the duration is fine", + "audio": { + "exists": true, + "size": 1000 + }, + "audioDuration": 100.8, + "expect": [], + "raw": "{\n \"version\": 1,\n \"title\": \"T\",\n \"journey\": {\n \"id\": \"j\"\n },\n \"audio\": \"j.mp3\",\n \"duration\": 100,\n \"segments\": [\n {\n \"id\": \"intro\",\n \"at\": null,\n \"speaker\": \"host\",\n \"text\": \"intro\",\n \"start\": 0,\n \"end\": 9\n },\n {\n \"id\": \"a1\",\n \"at\": {\n \"step\": \"a\",\n \"beat\": 1\n },\n \"speaker\": \"host\",\n \"text\": \"a1\",\n \"start\": 10,\n \"end\": 19\n },\n {\n \"id\": \"b\",\n \"at\": {\n \"step\": \"b\"\n },\n \"speaker\": \"host\",\n \"text\": \"b\",\n \"start\": 20,\n \"end\": 29\n },\n {\n \"id\": \"c2\",\n \"at\": {\n \"step\": \"c\",\n \"beat\": 2\n },\n \"speaker\": \"host\",\n \"text\": \"c2\",\n \"start\": 30,\n \"end\": 39\n },\n {\n \"id\": \"outro\",\n \"at\": null,\n \"speaker\": \"host\",\n \"text\": \"outro\",\n \"start\": 40,\n \"end\": 100\n }\n ]\n}", + "journey": { + "id": "j", + "steps": [ + { + "id": "a", + "beats": 3 + }, + { + "id": "b", + "beats": 0 + }, + { + "id": "c", + "beats": 2 + } + ] + } + } +] \ No newline at end of file diff --git a/test/podcastValidate.test.ts b/test/podcastValidate.test.ts new file mode 100644 index 0000000..e221d82 --- /dev/null +++ b/test/podcastValidate.test.ts @@ -0,0 +1,71 @@ +import { test } from 'node:test' +import assert from 'node:assert/strict' +import * as fs from 'fs' +import * as path from 'path' +import { audioPathProblem, brokenLinks, lineCol, locate, playNotice, validatePodcast } from '../src/podcast/validate' + +// The podcast file's full check (src/podcast/validate.ts). The cases in test/fixtures/podcast/cases.json are run here +// and through the code-journey skill's `journey.py podcast` (test/cli/podcast.test.mjs): the same rules in both. + +interface Case { name: string; raw: string; journey: { id: string; steps: { id: string; beats: number }[] }; audio?: { exists: boolean; size?: number }; audioDuration?: number; expect: string[] } +const cases: Case[] = JSON.parse(fs.readFileSync(path.join(__dirname, '../../test/fixtures/podcast/cases.json'), 'utf8')) +const codes = (c: Case) => validatePodcast(c.raw, { journey: c.journey, audio: c.audio, audioDuration: c.audioDuration }).problems.map((p) => `${p.level}:${p.code}${p.segment ? `@${p.segment}` : ''}`) + +for (const c of cases) { + test(`podcast check: ${c.name}`, () => { + assert.deepEqual([...codes(c)].sort(), [...c.expect].sort()) + const v = validatePodcast(c.raw, { journey: c.journey, audio: c.audio, audioDuration: c.audioDuration }) + assert.equal(v.playable, !c.expect.some((e) => e.startsWith('error:')), 'playable = no error') + assert.equal(!!v.episode, v.playable) + }) +} + +test('podcast check: errors come first, the messages say what is wrong in plain words', () => { + const get = (name: string) => { const c = cases.find((x) => x.name === name)!; return validatePodcast(c.raw, { journey: c.journey, audio: c.audio, audioDuration: c.audioDuration }).problems } + assert.match(get('version 2')[0].message, /version 2: this player reads version 1/) + assert.match(get('segments empty')[0].message, /"segments" is empty/) + assert.match(get('segments missing')[0].message, /no "segments"/) + assert.match(get('segments not a list')[0].message, /"segments" is not a list \(it is an object\)/) + assert.equal(get('audio outside the journeys folder')[0].message, 'audio must be in the journeys folder (got ../x.mp3)') + assert.match(get('audio file missing')[0].message, /the audio file j\.mp3 isn't there/) + assert.equal(get('cut-off audio: one plain warning')[0].message, 'The audio is 0:13 long but the episode is 1:40: the file looks cut off (3 parts start after its end)') + const timing = get('overlap, out of order, end before start').map((p) => p.message) + assert.ok(timing.includes('segment s2: starts at 0:08, before segment s1 ends (0:10): the later one wins from its start'), timing.join('\n')) + assert.ok(timing.includes('segment s3: ends at 0:25, before it starts (0:30)'), timing.join('\n')) + assert.ok(timing.includes('segment s3: starts at 0:30, before segment s4 above it (0:40): segments play in time order, not in file order'), timing.join('\n')) + assert.match(get('written for another journey')[0].message, /written for journey "other", but it is next to "j"/) + assert.match(get('end past the declared duration')[0].message, /segment s2: ends at 2:30, after the episode's "duration" \(1:40\)/) +}) + +test('podcast check: audio paths', () => { + for (const ok of ['a.mp3', './a.mp3', 'sub/a.mp3', 'sub/../a.mp3']) assert.equal(audioPathProblem(ok), undefined, ok) + for (const bad of ['../a.mp3', 'sub/../../a.mp3', '/abs/a.mp3', 'C:\\a.mp3', '..\\a.mp3', 'file:///a.mp3', 'http://x/a.mp3']) assert.ok(audioPathProblem(bad), bad) +}) + +test('podcast check: each problem is located in the text (the field, else the segment)', () => { + const raw = '{\n "version": 1,\n "audio": "a.mp3",\n "segments": [\n { "id": "s1", "at": null, "start": 0, "end": 5 },\n { "id": "s2", "at": { "step": "zz" }, "start": 5, "end": 9 }\n ]\n}' + const v = validatePodcast(raw, { journey: { id: 'j', steps: [{ id: 'a', beats: 0 }] } }) + const p = v.problems.find((x) => x.code === 'step')! + assert.deepEqual(p.path, ['segments', 1, 'at', 'step']) + const span = locate(raw, p.path) + assert.equal(raw.slice(span.start, span.end), '"step": "zz"') + assert.deepEqual(lineCol(raw, span.start), { line: 5, col: 26 }) + // A path partly there: the deepest part that is. + assert.equal(raw.slice(locate(raw, ['segments', 0, 'cue']).start, locate(raw, ['segments', 0, 'cue']).end), '{ "id": "s1", "at": null, "start": 0, "end": 5 }') + // Invalid JSON: where the parser stopped. + const broken = '{\n "version": 1,\n "audio": \n}' + const at = locate(broken, []) + assert.ok(at.start > 10, `the error's place: ${at.start}`) +}) + +test('podcast check: what the player says, in one short line', () => { + const v = (name: string) => { const c = cases.find((x) => x.name === name)!; return validatePodcast(c.raw, { journey: c.journey, audio: c.audio, audioDuration: c.audioDuration }).problems } + const links = v('broken links: a beat out of range, an unknown step, a bad at') + assert.equal(brokenLinks(links), 3) + assert.equal(playNotice(links), "3 parts can't be shown") + assert.equal(playNotice(v('written for another journey'), 'Test run'), 'Written for “Test run”') + assert.equal(playNotice(v('written for another journey')), 'Written for “other”') + assert.equal(playNotice(v('cut-off audio: one plain warning')), 'The audio is 0:13 long but the episode is 1:40: the file looks cut off') + assert.equal(playNotice(v('a duplicate id and an unknown cue')), '2 problems in the podcast file') + assert.equal(playNotice([]), undefined) +}) From 5016f8cee0f9dd41ef37908742c5c040f0ff92a4 Mon Sep 17 00:00:00 2001 From: tomeyer97 <107920881+tomeyer97@users.noreply.github.com> Date: Wed, 18 Nov 2026 14:27:39 +0100 Subject: [PATCH 04/45] Podcast player: seeks land where they say, wherever the audio is served from MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The panel loads the audio whole (fetch, then a blob: URL) before it plays: a server that ignores HTTP Range (VS Code for the web, remote windows) serves media Chromium can't seek in, and a seek there fell back to 0:00 while the walk had already moved. When the fetch fails, the file's own URL plays and a seek reports where the audio ended up once it is done, never the time asked; a seek that lands elsewhere is said in the bar and logged. Also: the status bar is told each second the bar shows (one clock); a play() that fails, a media error or a clock that stops while playing leaves it paused with the reason; Space and K play and pause anywhere in the panel but where you type, also after a beat's ‹ › was clicked; a pause can carry a note and where the next ▶ starts. The panel test serves the audio without Range, and checks a failed fetch and an audio that can't play. Co-Authored-By: Claude Opus 5.5 --- media/journey-podcast.css | 2 + media/journey-podcast.js | 240 ++++++++++++++++++++++++++++----- src/webview/page.ts | 7 +- test/journey-map/harness.html | 2 +- test/journey-podcast/shoot.mjs | 127 ++++++++++++++++- 5 files changed, 335 insertions(+), 43 deletions(-) diff --git a/media/journey-podcast.css b/media/journey-podcast.css index 6b5345d..121a113 100644 --- a/media/journey-podcast.css +++ b/media/journey-podcast.css @@ -41,6 +41,8 @@ body.has-pod .body.wide .mapwrap { height: calc(100vh - var(--headH, 0px) - var( .pod-b.play:hover { background: var(--vscode-button-hoverBackground, var(--vscode-button-background, var(--accent))); } .pod-time { color: var(--muted); font-size: 0.9em; font-variant-numeric: tabular-nums; white-space: nowrap; } .pod-err { color: var(--warn); font-size: 0.9em; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; min-width: 0; } +/* A note, not an error ("Step 12 isn't in the podcast"). */ +.pod-err.note { color: var(--muted); } .pod-rate { margin-left: auto; font-size: 0.9em; padding: 2px 6px; border-radius: 3px; color: var(--muted); font-variant-numeric: tabular-nums; } .pod-rate:hover { background: var(--hover); color: var(--fg); } /* What is being said: one muted line (the whole of it on hover). */ diff --git a/media/journey-podcast.js b/media/journey-podcast.js index 8e2cf69..438da60 100644 --- a/media/journey-podcast.js +++ b/media/journey-podcast.js @@ -5,13 +5,20 @@ // #app, so journey-map.js's re-renders never touch it (a drag or the audio survive them). // Needs common.js. Made by journey-map.js: JourneyPodcast({ post, stepTitle(n), onShown(h) }). // +// The audio is loaded whole (fetch, then a blob: URL) before it plays: a server that ignores HTTP Range (VS Code for +// the web, and remote windows) serves media Chromium can't seek in, and a seek there lands at 0:00. If the fetch +// fails, the file's own URL plays, and where a seek lands is what the audio says once it is done, never the time asked. +// // In (journey-map.js routes them here): -// { type: 'podcast', episode? } the journey's episode ({ src, title, duration, at, rate, chapters, segments }), or -// none (the bar goes) -// { type: 'podcastCmd', action: 'play' | 'pause' | 'toggle' | 'skip' | 'seek' | 'part', by?, to?, dir? } +// { type: 'podcast', episode? } the journey's episode ({ key, src, title, duration, at, play?, rate, chapters, +// segments }), or none (the bar goes). `at`: where it starts; `play`: it plays once loaded +// { type: 'podcastCmd', action: 'play' | 'pause' | 'toggle' | 'skip' | 'seek' | 'part' | 'rate', by?, to?, dir?, at?, +// note?, resumeAt? } play `at`: from there; pause `note`: said in the bar; `resumeAt`: where +// the next ▶ starts (the walk is on a step the podcast skips) // Out: -// { type: 'podcastTime', t, playing, rate, seek? } where the audio is (seek: moved by a seek, not by playing) -// { type: 'podcastError', message } +// { type: 'podcastTime', of, t, playing, rate, seek? } where episode `of`'s audio is (seek: moved by a seek, not by +// playing); said each time the shown second changes too +// { type: 'podcastError', message } what went wrong (the extension logs it) ;(function () { const { el, svgEl, runKey } = window.common @@ -21,6 +28,10 @@ const RATES = [1, 1.25, 1.5] /** Within this many seconds of a part's start, ⏮ goes to the part before (as src/podcast/model.ts chapterJump). */ const RESTART_GRACE_S = 3 + /** A seek that lands further than this from where it was asked to go (s) did not get there. */ + const MISS_S = 0.75 + /** Playing, the clock not moving for this long (ms): it is not playing (a broken or cut file); it pauses and says so. */ + const FROZEN_MS = 3000 const PATHS = { play: 'M5 3.5v13l11-6.5z', @@ -89,8 +100,10 @@ rateB.title = 'Speed' rateB.onclick = () => setRate(RATES[(RATES.indexOf(audio.playbackRate) + 1) % RATES.length] || 1) const cap = el('div', 'pod-cap') + // An error, or a note ("not in the podcast"): one short line beside the time. const err = el('span', 'pod-err') err.hidden = true + err.setAttribute('role', 'status') const row = el('div', 'pod-row') const ctl = el('div', 'pod-ctl') ctl.append(prevB, backB, playB, fwdB, nextB) @@ -108,12 +121,29 @@ let startAt = 0 let boundaryTimer = 0 let frame = 0 + /** The audio's blob: URL (undefined: none, or it plays from the file's own URL), and which load is the newest. */ + let blobUrl + let loadGen = 0 + /** The audio is still being fetched: no source yet. Play asked meanwhile (`wantPlay`) starts once it is there. */ + let loading = false + let wantPlay = false + /** The audio is a blob, so a seek always gets there (said at once); else where it got is said once it is done. */ + let blobbed = false + /** A seek under way: where to, and whether the extension asked for it (the walk moved first). */ + let seeking + /** Where the next ▶ starts, set by the extension while the walk is on a step the podcast skips. */ + let resumeAt + /** The whole second last said to the extension (the status bar shows the same clock as the bar). */ + let saidSec = -1 + /** The time last seen moving, and when (FROZEN_MS). */ + let movedT = -1 + let movedAt = 0 /** Play was refused for want of a click or key here: ▶ takes the keyboard when the panel gets it. */ let askFocus = false window.addEventListener('focus', () => { if (askFocus) playB.focus({ preventScroll: true }) }) const duration = () => (Number.isFinite(audio.duration) && audio.duration > 0 ? audio.duration : (ep && ep.duration) || 0) - const now = () => (dragT !== undefined ? dragT : audio.currentTime || 0) + const now = () => (dragT !== undefined ? dragT : seeking ? seeking.to : audio.readyState < 1 ? startAt : audio.currentTime || 0) const playing = () => !audio.paused && !audio.ended const chapterAt = (t) => { if (!ep) return -1 @@ -135,11 +165,17 @@ return i === ep.chapters.length - 1 ? 'Recap' : 'Map' } - function report(seek) { - if (!ep) return - post({ type: 'podcastTime', t: audio.currentTime || 0, playing: playing(), rate: audio.playbackRate, ...(seek ? { seek: true } : {}) }) + /** Says where the audio is: always what the audio itself reports (`t` only for a seek a blob is sure to make). */ + function report(seek, t) { + // Nothing to say before this episode's audio is there (an event of the one before it). + if (!ep || (t === undefined && (loading || audio.readyState < 1))) return + const at = t !== undefined ? t : audio.currentTime || 0 + saidSec = Math.floor(at) + post({ type: 'podcastTime', of: ep.key, t: at, playing: playing(), rate: audio.playbackRate, ...(seek ? { seek: true } : {}) }) scheduleBoundary() } + /** A line for the extension's log. */ + const say = (message) => post({ type: 'podcastError', message }) /** Says where the audio is again right as the next segment starts (timeupdate comes only every ~250 ms). */ function scheduleBoundary() { clearTimeout(boundaryTimer) @@ -151,16 +187,40 @@ boundaryTimer = setTimeout(() => report(false), Math.max(20, ms)) } - function seek(t) { + /** To second `t`. `asked`: the extension asked (the walk is there already). */ + function seek(t, asked) { if (!ep) return + resumeAt = undefined + if (err.classList.contains('note')) showError('') const d = duration() const to = Math.max(0, Math.min(d ? d - 0.05 : t, t)) - if (audio.readyState < 1) startAt = to - else audio.currentTime = to + if (audio.readyState < 1) { + // Not loaded yet: it goes there once it is (loadedmetadata), and says so then. + startAt = to + draw() + return + } + seeking = { to, asked: !!asked } + audio.currentTime = to draw() - // Said at once: the journey moves now, not once the audio has the new place buffered. - post({ type: 'podcastTime', t: to, playing: playing(), rate: audio.playbackRate, seek: true }) - scheduleBoundary() + // A blob always gets there: said at once, so the journey moves now, not once the audio has the place decoded. + if (blobbed) report(true, to) + } + /** A seek done: where the audio is now is what counts. Somewhere else than asked (the source can't seek): logged, + * said in the bar; the walk follows the audio, unless the walk moved first (then the audio pauses there). */ + function seeked() { + const s = seeking + seeking = undefined + const got = audio.currentTime || 0 + if (!s) { report(true); return } + if (Math.abs(got - s.to) <= MISS_S) { + if (!blobbed) report(true) + return + } + say(`seek to ${clock(s.to)} ended at ${clock(got)}${blobbed ? '' : ' (the audio is streamed and its server ignores Range requests)'}`) + showError(`Can't go to ${clock(s.to)} in this audio`) + if (s.asked) { audio.pause(); report(false) } + else report(true) } const skip = (by) => seek(now() + by) function part(dir) { @@ -173,24 +233,72 @@ } function play() { if (!ep) return - if (audio.ended) seek(0) + // Still fetching: it plays once it is there. + if (loading) { wantPlay = true; return } + if (resumeAt !== undefined) seek(resumeAt) + else if (audio.ended) seek(0) + if (err.classList.contains('note')) showError('') + movedT = -1 const p = audio.play() if (p && p.catch) p.catch((e) => { + // A pause before it started (a quick Space, Space): nothing went wrong. + if (e && e.name === 'AbortError') return // VS Code's webviews play audio only after a click or a key in them (once per panel): ▶ takes the keyboard. const gesture = e && e.name === 'NotAllowedError' + // Not playing: never "playing" with the clock still. + if (!audio.paused) audio.pause() showError(gesture ? 'Press Space to play' : `Can't play: ${e && e.message}`) if (gesture) { askFocus = true; playB.focus({ preventScroll: true }) } post({ type: 'podcastError', message: String(e && (e.name || e.message)) }) + draw() + report(false) }) } - const toggle = () => (playing() ? audio.pause() : play()) + function pause() { + wantPlay = false + audio.pause() + draw() + } + const toggle = () => (playing() || wantPlay ? pause() : play()) function setRate(r) { audio.playbackRate = r audio.defaultPlaybackRate = r } - function showError(text) { + function showError(text, note) { err.textContent = text + err.title = text err.hidden = !text + err.classList.toggle('note', !!text && !!note) + } + + /** The audio of episode `e`, loaded whole as a blob (seekable wherever it is served from); else its own URL. */ + function load(e) { + const gen = ++loadGen + if (blobUrl) { URL.revokeObjectURL(blobUrl); blobUrl = undefined } + blobbed = false + seeking = undefined + loading = true + audio.removeAttribute('src') + audio.load() + const use = (src, isBlob) => { + loading = false + blobbed = isBlob + audio.src = src + audio.load() + if (wantPlay) { wantPlay = false; play() } + } + fetch(e.src).then((r) => { + if (!r.ok) throw new Error(`HTTP ${r.status}`) + return r.blob() + }).then((b) => { + if (gen !== loadGen) return + blobUrl = URL.createObjectURL(b) + use(blobUrl, true) + }).catch((x) => { + if (gen !== loadGen) return + say(`the audio could not be loaded whole (${x && x.message}); it is streamed, and seeking may not work where its server ignores Range requests`) + use(e.src, false) + }) } // ---------- drawing ---------- @@ -241,6 +349,8 @@ const si = segAt(t) const text = si >= 0 ? ep.segments[si].text : '' if (cap.textContent !== text) { cap.textContent = text; cap.title = text } + // One clock: the status bar gets each second this bar shows. + if (on && dragT === undefined && !seeking && Math.floor(audio.currentTime || 0) !== saidSec) report(false) } /** Smooth while playing and on screen; timeupdate draws otherwise. */ @@ -304,40 +414,81 @@ }, true) }) - // Space / K play and pause, ← → skip, Shift+← → a step: in the bar, or with nothing else focused (a focused - // button presses itself; the animation and the map keep their own arrows). + // Space / K play and pause anywhere in the panel but where you type. A button the keyboard went to (Tab) presses + // itself with Space; one clicked with the mouse doesn't keep Space (after a beat's ‹ ›, Space pauses; it doesn't + // step back again). ← → skip, Shift+← → a step: in the bar, or with nothing else focused (the animation and the + // map keep their own arrows). + const typing = (t) => !!t && (/^(INPUT|TEXTAREA|SELECT)$/.test(t.tagName) || t.isContentEditable) + const CONTROL = 'button, a, [role="button"], [role="link"]' + /** The control last pressed with the pointer (it has the focus, but not for Space); Tab forgets it. */ + let clicked + document.addEventListener('pointerdown', (e) => { clicked = (e.target && e.target.closest && e.target.closest(CONTROL)) || undefined }, true) + document.addEventListener('keydown', (e) => { if (e.key === 'Tab') clicked = undefined }, true) document.addEventListener('keydown', (e) => { if (!ep || e.defaultPrevented || e.altKey || e.ctrlKey || e.metaKey) return const target = e.target + if (typing(target)) return const inBar = root.contains(target) const free = target === document.body || target === document.documentElement || !target - if (!inBar && !free) return - const onButton = target && target.tagName === 'BUTTON' + const control = target && target.closest && target.closest(CONTROL) + const onButton = !!control && control !== clicked runKey(e, { ' ': !onButton && toggle, k: toggle, - ArrowLeft: () => (e.shiftKey ? part(-1) : skip(-SKIP_S)), - ArrowRight: () => (e.shiftKey ? part(1) : skip(SKIP_S)), + K: toggle, + ArrowLeft: (inBar || free) && (() => (e.shiftKey ? part(-1) : skip(-SKIP_S))), + ArrowRight: (inBar || free) && (() => (e.shiftKey ? part(1) : skip(SKIP_S))), }, true) }) // ---------- the audio ---------- audio.addEventListener('loadedmetadata', () => { - if (startAt) { audio.currentTime = Math.min(startAt, duration()); startAt = 0 } + const to = Math.min(startAt, duration()) + startAt = 0 build() + if (to > 0) { + seeking = { to, asked: false } + audio.currentTime = to + if (blobbed) report(true, to) + } + // Where it starts, said once it is there (the walk, when it follows this podcast, goes there). + else report(true) draw() }) - audio.addEventListener('timeupdate', () => { if (dragT === undefined) draw(); report(false) }) - audio.addEventListener('play', () => { askFocus = false; showError(''); draw(); tick(); report(false) }) + audio.addEventListener('seeked', () => { seeked(); draw() }) + audio.addEventListener('timeupdate', () => { + if (dragT === undefined) draw() + if (!seeking) report(false) + frozenCheck() + }) + audio.addEventListener('play', () => { askFocus = false; if (!err.classList.contains('note')) showError(''); movedT = -1; draw(); tick(); report(false) }) audio.addEventListener('pause', () => { draw(); report(false) }) audio.addEventListener('ended', () => { draw(); report(false) }) audio.addEventListener('ratechange', () => { draw(); report(false) }) audio.addEventListener('error', () => { + if (!audio.getAttribute('src')) return // emptied on purpose (another episode, none) const e = audio.error showError("Can't play the audio") - post({ type: 'podcastError', message: `audio error ${e ? e.code : '?'}${e && e.message ? `: ${e.message}` : ''}` }) + seeking = undefined + // Not playing: never "playing" with the clock still. + if (!audio.paused) audio.pause() + say(`audio error ${e ? e.code : '?'}${e && e.message ? `: ${e.message}` : ''}`) + draw() + report(false) }) + /** Playing with the clock still for FROZEN_MS (a cut or broken file): paused, and said. */ + function frozenCheck() { + if (!playing() || seeking) { movedT = -1; return } + const t = audio.currentTime + if (t !== movedT) { movedT = t; movedAt = Date.now(); return } + if (Date.now() - movedAt < FROZEN_MS) return + audio.pause() + showError(`The audio doesn't play on from ${clock(t)}`) + say(`the audio stopped at ${clock(t)} while playing (readyState ${audio.readyState}, networkState ${audio.networkState})`) + } + // timeupdate stops when the clock does: the check runs on its own too. + setInterval(frozenCheck, 1000) // The bar's height, for the panel's layout (the map's column and the page's end stay clear of it). // Set a frame later, and only when it changed: set inside the observer it resized the map, whose own observer then @@ -355,7 +506,17 @@ /** The journey's episode (none: the bar goes; the same audio again keeps playing). */ set(e) { if (!e) { - if (ep) { audio.pause(); audio.removeAttribute('src'); audio.load() } + if (ep) { + report(false) + loadGen++ + loading = false + wantPlay = false + seeking = undefined + audio.pause() + audio.removeAttribute('src') + audio.load() + if (blobUrl) { URL.revokeObjectURL(blobUrl); blobUrl = undefined } + } ep = undefined root.hidden = true document.body.classList.remove('has-pod') @@ -365,15 +526,18 @@ return } const same = ep && ep.src === e.src + // Another episode: where the one leaving was is said first (kept for next time). + if (ep && !same) { audio.pause(); report(false) } ep = e root.hidden = false document.body.classList.add('has-pod') if (!same) { showError('') + resumeAt = undefined startAt = e.at || 0 + wantPlay = !!e.play setRate(RATES.includes(e.rate) ? e.rate : 1) - audio.src = e.src - audio.load() + load(e) } build() draw() @@ -382,17 +546,23 @@ cmd(m) { if (!ep) return const actions = { - play, toggle, - pause: () => audio.pause(), + play: () => { if (typeof m.at === 'number') seek(m.at); play() }, + toggle, + // With a note: the walk is on a step the podcast skips; ▶ goes on from `resumeAt`. + pause: () => { + pause() + if (m.note) showError(String(m.note), true) + if (typeof m.resumeAt === 'number') resumeAt = m.resumeAt + }, skip: () => skip(Number(m.by) || 0), - seek: () => seek(Number(m.to) || 0), + seek: () => seek(Number(m.to) || 0, true), part: () => part(m.dir < 0 ? -1 : 1), rate: () => setRate(Number(m.rate) || 1), } if (Object.hasOwn(actions, m.action)) actions[m.action]() }, /** For tests: the audio's state. */ - get state() { return { t: audio.currentTime, playing: playing(), paused: audio.paused, ready: audio.readyState, duration: duration(), error: err.hidden ? '' : err.textContent } }, + get state() { return { t: audio.currentTime, playing: playing(), paused: audio.paused, ready: audio.readyState, duration: duration(), error: err.hidden ? '' : err.textContent, blob: blobbed } }, get shown() { return !!ep }, /** The journey's titles changed (another journey of the same id, a rename): the tip and labels follow. */ redraw() { if (ep) draw() }, diff --git a/src/webview/page.ts b/src/webview/page.ts index 808a21a..0061bcd 100644 --- a/src/webview/page.ts +++ b/src/webview/page.ts @@ -18,7 +18,7 @@ export function nonce(): string { return Array.from({ length: 24 }, () => Math.floor(Math.random() * 36).toString(36)).join('') } -/** What a page lets in beyond its own files: images (its source, https:, data:), audio (`media`), and style attributes in its markup. */ +/** What a page lets in beyond its own files: images (its source, https:, data:), audio (`media`: also fetched, as a blob), and style attributes in its markup. */ export interface PageAllows { images?: boolean; inlineStyles?: boolean; media?: boolean } /** The page's policy: nothing by default; the extension's (`source`) styles and fonts; scripts with the nonce; no forms. */ @@ -26,8 +26,9 @@ export function contentSecurityPolicy(source: string, n: string, allow: PageAllo return [ "default-src 'none'", ...(allow.images ? [`img-src ${source} https: data:`] : []), - // Audio and video from the extension's own roots (the journey panel's podcast). - ...(allow.media ? [`media-src ${source}`] : []), + // Audio and video from the extension's own roots (the journey panel's podcast), fetched whole and played from a + // blob: URL (a server that ignores Range serves media Chromium can't seek in). + ...(allow.media ? [`media-src ${source} blob:`, `connect-src ${source}`] : []), `style-src ${source}${allow.inlineStyles ? " 'unsafe-inline'" : ''}`, `font-src ${source}`, `script-src 'nonce-${n}'`, diff --git a/test/journey-map/harness.html b/test/journey-map/harness.html index f90323b..de0d4ee 100644 --- a/test/journey-map/harness.html +++ b/test/journey-map/harness.html @@ -6,7 +6,7 @@ - + diff --git a/test/journey-podcast/shoot.mjs b/test/journey-podcast/shoot.mjs index 9b871d8..d33bf27 100644 --- a/test/journey-podcast/shoot.mjs +++ b/test/journey-podcast/shoot.mjs @@ -4,11 +4,16 @@ // nothing outside the window, one bar per step), play advances the audio, a click anywhere on the timeline shows // exactly the step and beat of that time (forwards and backwards, no step in between shown), a drag moves the // journey once (where it ended), the hover tip names the step, keys skip, a step clicked moves the audio, a beat the -// step does not have shows the step only, no console errors. Exits 1 on any failure. +// step does not have shows the step only, no console errors. The audio is served over HTTP by a server that ignores +// Range (as VS Code for the web serves a webview's files): the bar loads it whole (a blob) so seeks get there. Then: +// Space and K after a beat's ‹ › clicked, a pause "not in the podcast" with ▶ going on after it, a fetch that fails +// (the plain URL, no Range: a seek reports where the audio really is, never the time asked), an audio that can't +// play (▶ stays paused, says why). Exits 1 on any failure. // // Usage (after `npm run build`): node test/journey-podcast/shoot.mjs [screenshot-dir] // PLAYWRIGHT / CHROME: as test/harness/page.mjs. import fs from 'node:fs' +import http from 'node:http' import path from 'node:path' import { createRequire } from 'node:module' import { fileURLToPath, pathToFileURL } from 'node:url' @@ -26,8 +31,21 @@ const journey = { ...raw, steps: raw.steps.map((s, i) => ({ ...s, n: i + 1 })), const podcastFile = path.join(ROOT, 'test/fixtures/podcast/sample.podcast.json') const p = parsePodcast(fs.readFileSync(podcastFile, 'utf8')) const ep = resolveEpisode(p, { steps: journey.steps.map((s) => ({ id: s.id, beats: s.scene?.beats?.length ?? 0 })) }) -const src = pathToFileURL(path.join(path.dirname(podcastFile), p.audio)).href -const episode = { src, title: ep.title, duration: ep.duration, at: 0, rate: 1, chapters: ep.chapters, segments: ep.segments.map((s) => ({ start: s.start, end: s.end, text: s.text, step: s.step })) } +// The audio over HTTP, never in ranges (200, the whole file, every time). `/nofetch/…`: a fetch() of it fails (only the +// audio element gets it); `/missing/…`: 404. +const audioFile = path.join(path.dirname(podcastFile), p.audio) +const server = http.createServer((req, res) => { + const cors = { 'Access-Control-Allow-Origin': '*' } + if (req.url.startsWith('/missing/')) { res.writeHead(404, cors); res.end(); return } + if (req.url.startsWith('/nofetch/') && req.headers['sec-fetch-dest'] === 'empty') { res.writeHead(500, cors); res.end(); return } + const body = fs.readFileSync(audioFile) + res.writeHead(200, { ...cors, 'Content-Type': 'audio/mpeg', 'Content-Length': body.length }) + res.end(body) +}) +await new Promise((r) => server.listen(0, '127.0.0.1', r)) +const base = `http://127.0.0.1:${server.address().port}` +const src = `${base}/${p.audio}` +const episode = { key: 'place-order', src, title: ep.title, duration: ep.duration, at: 0, rate: 1, chapters: ep.chapters, segments: ep.segments.map((s) => ({ start: s.start, end: s.end, text: s.text, step: s.step })) } const failures = [] let tag = '' @@ -89,7 +107,8 @@ const shown = (page) => page.evaluate(() => { cap: document.querySelector('.pod-cap')?.textContent, } }) -const audioState = (page) => page.evaluate(() => { const a = document.querySelector('.pod audio'); return { t: a.currentTime, paused: a.paused, ready: a.readyState, dur: a.duration, err: a.error && a.error.code } }) +const audioState = (page) => page.evaluate(() => { const a = document.querySelector('.pod audio'); return { t: a.currentTime, paused: a.paused, ready: a.readyState, dur: a.duration, err: a.error && a.error.code, blob: a.src.startsWith('blob:') } }) +const barNote = (page) => page.evaluate(() => { const e = document.querySelector('.pod-err'); return e.hidden ? '' : e.textContent }) const sleep = (ms) => new Promise((r) => setTimeout(r, ms)) async function until(what, f, ms = 4000) { const end = Date.now() + ms @@ -155,6 +174,7 @@ async function run(b, w) { const canMp3 = await page.evaluate(() => document.createElement('audio').canPlayType('audio/mpeg')) ok(!!canMp3, `this Chromium plays mp3 (canPlayType: "${canMp3}")`) await until('the audio\'s length is known', async () => (await audioState(page)).ready >= 1) + ok((await audioState(page)).blob, 'served without Range, the audio is loaded whole (a blob: URL)') await layout(page, w) if (OUT) await page.screenshot({ path: path.join(OUT, `podcast-${w}-start.png`) }) @@ -163,6 +183,14 @@ async function run(b, w) { await until('playing, time advancing', async () => (await audioState(page)).t > 0.4) ok(fx.st.playing, 'the panel says it is playing') ok((await shown(page)).step === 0, 'the intro: no step yet') + // One clock: what the extension was last told is the second the bar shows. + for (let k = 0; k < 6; k++) { + await sleep(170) + const said = Math.floor(fx.st.lastT) + const showing = await page.evaluate(() => document.querySelector('.pod-time').textContent.split(' / ')[0]) + const [m, sec] = showing.split(':').map(Number) + ok(Math.abs(m * 60 + sec - said) <= (k ? 0 : 1) || said === m * 60 + sec, `one clock: the bar shows ${showing}, the extension was told ${fx.st.lastT.toFixed(2)}`) + } await page.click('.pod-b.play') await until('paused', async () => (await audioState(page)).paused) @@ -238,6 +266,34 @@ async function run(b, w) { await until('K pauses', async () => (await audioState(page)).paused) } + // Space and K after a beat's › clicked with the mouse: the podcast plays and pauses (the button doesn't keep Space). + { + const { x, y } = await xAt(page, 4) + await page.mouse.click(x, y) + await until('step 1 with its animation', async () => { const s = await shown(page); return s.step === 1 && s.anim }) + const before = (await shown(page)).beat + await page.click('#app .scn-next') + await until('› went a beat on', async () => (await shown(page)).beat === before + 1) + const beat = (await shown(page)).beat + await page.keyboard.press(' ') + + await until('Space after ›: plays', async () => !(await audioState(page)).paused) + ok((await shown(page)).beat >= beat, 'Space did not step the animation back') + await page.keyboard.press('k') + await until('K after ›: pauses', async () => (await audioState(page)).paused) + } + + // A step the podcast skips (the extension pauses it with a note): ▶ goes on after it, not where it was. + { + await fx.send({ type: 'podcastCmd', action: 'pause', note: "Step 2 isn't in the podcast", resumeAt: 15 }) + await until('the bar says so', async () => /isn't in the podcast/.test(await barNote(page))) + await page.click('.pod-b.play') + await until('▶: on from 15 s, playing', async () => { const a = await audioState(page); return !a.paused && a.t >= 15 && a.t < 16.5 }) + ok(!(await barNote(page)), 'the note goes once it plays on') + await page.click('.pod-b.play') + await until('paused', async () => (await audioState(page)).paused) + } + // Journey → audio: a step clicked in the storyline moves the audio to its first part. { await page.click('.story .st[data-n="4"]') @@ -271,8 +327,71 @@ async function run(b, w) { console.log(`${tag}: done`) } +/** An episode at another URL in a fresh page: the page, the fake extension, the console's errors. */ +async function withEpisode(b, url, name) { + tag = name + const context = await b.newContext({ viewport: { width: 900, height: 700 }, deviceScaleFactor: 1, reducedMotion: 'reduce' }) + const page = await context.newPage() + const errors = [] + page.on('console', (m) => { if (m.type() === 'error') errors.push(m.text()) }) + const fx = fakeExtension(page) + const told = [] + await page.exposeFunction('__onPost', (m) => { if (m.type === 'podcastError') told.push(m.message); return fx.on(m) }) + await page.goto(`${HARNESS}?theme=light`) + await page.waitForFunction(() => window.__posted.some((m) => m.type === 'ready')) + await fx.send({ type: 'journey', journey, ...tour(0) }) + await fx.send({ type: 'podcast', episode: { ...episode, src: url } }) + await page.waitForSelector('.pod:not([hidden])') + return { context, page, fx, told, errors } +} + +/** The fetch fails: the audio plays from its URL, whose server ignores Range. A seek reports where the audio is. */ +async function streamed(b) { + const { context, page, fx, told } = await withEpisode(b, `${base}/nofetch/${p.audio}`, 'streamed, no Range') + await until('the audio\'s length is known', async () => (await audioState(page)).ready >= 1) + ok(!(await audioState(page)).blob, 'the fetch failed: its own URL') + ok(told.some((m) => /could not be loaded whole/.test(m)), `the extension is told (${JSON.stringify(told)})`) + for (const t of [20, 7, 31]) { + const seeks = fx.st.seeks + const { x, y } = await xAt(page, t) + await page.mouse.click(x, y) + await until(`seek to ${t}: said once done`, async () => fx.st.seeks > seeks, 6000) + await sleep(300) + const a = await audioState(page) + ok(Math.abs(fx.st.lastT - a.t) < 0.6, `seek to ${t}: the extension is told where the audio is (${fx.st.lastT.toFixed(2)}), the audio says ${a.t.toFixed(2)}`) + const s = await shown(page) + ok(s.step === viewAt(ep, a.t).step, `seek to ${t}: the walk shows step ${s.step}, where the audio is (${viewAt(ep, a.t).step})`) + if (Math.abs(a.t - t) > 0.75) { + ok(/Can't go to/.test(await barNote(page)), `a seek that did not get there says so in the bar ("${await barNote(page)}")`) + ok(told.some((m) => /seek to .* ended at/.test(m)), 'and the extension is told (its log)') + } + } + console.log(` (the extension was told: ${told.join(' / ')})`) + if (OUT) await page.screenshot({ path: path.join(OUT, 'podcast-streamed.png') }) + await context.close() + console.log(`${tag}: done`) +} + +/** An audio that can't be played: ▶ stays paused and says why; the extension never hears "playing". */ +async function unplayable(b) { + const { context, page, fx, told } = await withEpisode(b, `${base}/missing/${p.audio}`, 'unplayable') + await until('the bar says the audio can\'t play', async () => /Can't play/.test(await barNote(page)), 6000) + await page.click('.pod-b.play') + await sleep(800) + const a = await audioState(page) + ok(a.paused, '▶ on an audio that can\'t play: paused') + ok(!fx.st.playing, 'the extension is never told it plays') + ok(/Can't play/.test(await barNote(page)), `the bar says why ("${await barNote(page)}")`) + ok(told.length > 0, `the extension is told (${JSON.stringify(told)})`) + await context.close() + console.log(`${tag}: done`) +} + const b = await launch() for (const w of [340, 700, 1200]) await run(b, w) +await streamed(b) +await unplayable(b) await b.close() +server.close() console.log(failures.length ? `${failures.length} problems` : 'all checks passed') process.exit(failures.length ? 1 : 0) From f73c3578206752108ef76efb804ede75ac6b8e7b Mon Sep 17 00:00:00 2001 From: tomeyer97 <107920881+tomeyer97@users.noreply.github.com> Date: Wed, 18 Nov 2026 14:32:44 +0100 Subject: [PATCH 05/45] Walk: a step can open on a beat whose code is in another file; the walk's tabs close on their own goToStep takes the beat of the animation it opens on: when that beat's code is in another file, that file is the one opened (by the beat), never the step's own file first. closeWalkTabs closes the walk's preview tab (a step's file, or a file its animations show), as Finish did. Co-Authored-By: Claude Opus 5.5 --- src/tour/commands.ts | 19 ++++++++++++++----- src/tour/walk.ts | 34 +++++++++++++++++++++++++++++++--- 2 files changed, 45 insertions(+), 8 deletions(-) diff --git a/src/tour/commands.ts b/src/tour/commands.ts index a478230..abd6dbd 100644 --- a/src/tour/commands.ts +++ b/src/tour/commands.ts @@ -67,9 +67,7 @@ export async function finishTour(): Promise { await endJourney() if (!lj) return await state.update(POS_KEY, Object.fromEntries(Object.entries(walk.positions()).filter(([k]) => k !== posKey(lj)))) - // Only the walk's own preview tab (not one you kept open or edited). - const tabs = doc ? walkPreviewTabs(lj, doc.column) : [] - if (tabs.length) await vscode.window.tabGroups.close(tabs, true) + await closeWalkTabs(lj, doc?.column) tourState.finishedKey = lj.key // The panel says Done when it is open or has the room; else the status bar says it. if (mapPanel.journey || (await panelFits())) walk.showMap(lj) @@ -78,9 +76,20 @@ export async function finishTour(): Promise { tree.refresh() } -/** Preview tabs in `column` showing one of the journey's step files, not edited. */ +/** The walk's own preview tab in `column` (the code group it used), not one you kept open or edited: closed. */ +export async function closeWalkTabs(lj: LoadedJourney, column: vscode.ViewColumn | undefined): Promise { + const tabs = column ? walkPreviewTabs(lj, column) : [] + if (tabs.length) await vscode.window.tabGroups.close(tabs, true) +} + +/** Preview tabs in `column` showing one of the journey's step files (or a file its animations show), not edited. */ function walkPreviewTabs(lj: LoadedJourney, column: vscode.ViewColumn): vscode.Tab[] { - const stepFiles = new Set(lj.j.steps.map((s) => vscode.Uri.joinPath(lj.folder.uri, fileOf(lj, s.n)).toString())) + const renames = journeys.renames(lj) + const beatFiles = lj.j.steps.flatMap((s) => (s.scene?.beats ?? []).map((b) => b.code?.file).filter((f): f is string => typeof f === 'string')) + const stepFiles = new Set([ + ...lj.j.steps.map((s) => vscode.Uri.joinPath(lj.folder.uri, fileOf(lj, s.n)).toString()), + ...beatFiles.map((f) => vscode.Uri.joinPath(lj.folder.uri, renames.get(f) ?? f).toString()), + ]) return vscode.window.tabGroups.all.filter((g) => g.viewColumn === column).flatMap((g) => g.tabs) .filter((t) => t.isPreview && !t.isDirty && t.input instanceof vscode.TabInputText && stepFiles.has(t.input.uri.toString())) } diff --git a/src/tour/walk.ts b/src/tour/walk.ts index fdfe23b..6df7f3a 100644 --- a/src/tour/walk.ts +++ b/src/tour/walk.ts @@ -19,6 +19,7 @@ import { MAP_KEY, POS_KEY, ShownAt, TOUR_KEY, TourState } from './state' import { foldNotesOverlapping, syncStepNotes } from './stepNotes' import { cardLine, stepUri, wroteAt } from './stepPlace' import { baseName } from '../paths' +import { stepFileUri } from '../journeys/codeGroup' type Pos = { step: number; id?: string; at: string } export type TourItems = { prev: vscode.StatusBarItem; pos: vscode.StatusBarItem; next: vscode.StatusBarItem; end: vscode.StatusBarItem } @@ -223,14 +224,18 @@ export class Walk { void state.update(MAP_KEY, posKey(lj)) } - /** Opens step n: the code in the code group as a preview tab (one tab, reused:), the step card above its lines. */ - async goToStep(lj: LoadedJourney, n: number, opts: { focus?: boolean } = {}): Promise { + /** + * Opens step n: the code in the code group as a preview tab (one tab, reused:), the step card above its lines. + * `beat`: the step opens on that beat of its animation (the podcast); when the beat's code is in another file, that + * file is the one opened (by the beat, beats.ts), never the step's own first. + */ + async goToStep(lj: LoadedJourney, n: number, opts: { focus?: boolean; beat?: number } = {}): Promise { this.tour.stepping++ try { await this.openStep(lj, n, opts) } finally { this.tour.stepping-- } } /** Three phases, each ending early once a step opened since has taken over (`superseded`). */ - private async openStep(lj: LoadedJourney, requested: number, opts: { focus?: boolean }): Promise { + private async openStep(lj: LoadedJourney, requested: number, opts: { focus?: boolean; beat?: number }): Promise { if (!lj.j.steps.length) return const gen = ++this.tour.stepGen const n = Math.max(1, Math.min(requested, lj.j.steps.length)) @@ -238,6 +243,10 @@ export class Walk { const superseded = () => gen !== this.tour.stepGen && !this.tour.isAt(lj, n) if (!(await this.enterStep(lj, n, superseded))) return const uri = stepUri(lj, n) + if (this.beatElsewhere(lj, n, uri, opts.beat)) { + this.onBeatElsewhere(lj, n) + return + } const editor = await this.openStepFile(lj, n, uri, opts, superseded) if (editor) await this.revealStep(lj, n, editor, uri) } @@ -308,6 +317,25 @@ export class Walk { return editor } + /** Beat `beat` of step n's animation shows code in another file than the step's (`uri`). */ + private beatElsewhere(lj: LoadedJourney, n: number, uri: vscode.Uri, beat: number | undefined): boolean { + if (beat === undefined || lj.at[n - 1]?.removed) return false + const code = lj.j.steps[n - 1]?.scene?.beats?.[beat]?.code + if (!code || typeof code.file !== 'string') return false + return stepFileUri(lj.folder.uri, journeys.renames(lj), code.file).toString() !== uri.toString() + } + + /** Step n opened on a beat in another file: the beat opens its file (showBeat); the step's card is made, unseen. */ + private onBeatElsewhere(lj: LoadedJourney, n: number): void { + const { tour } = this + tour.fileGone = false + if (tour.cardNotice && tour.cardNotice.id !== tour.stepId) tour.cardNotice = undefined + tour.shownAt = this.shownAt(lj, n, fileOf(lj, n)) + tour.refHere = undefined + this.card.show(lj, n) + revealJourneyRow(lj) + } + /** Where step n is shown now (to see that the agent moved it). */ private shownAt(lj: LoadedJourney, n: number, file: string): ShownAt { const at = lj.at[n - 1] From ebc7324e09c37843227d0e0df1a8b87cbcc78ea6 Mon Sep 17 00:00:00 2001 From: tomeyer97 <107920881+tomeyer97@users.noreply.github.com> Date: Wed, 18 Nov 2026 14:32:44 +0100 Subject: [PATCH 06/45] Podcast: the place is kept per journey; skipped steps, rewritten files and reports from before a seek no longer move the walk back MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Each report of the panel keeps where that journey's podcast is (in memory, and in the workspace state on a pause, a seek, leaving): another journey, the walk ending or the panel closing never lose it, and ▶ (the row, the command, the player) goes on there, or at the step the walk is on. - Next, Previous or the storyline onto a step the podcast skips: the walk stays there, the audio pauses and says so; ▶ goes on with the next part after that step. Reports from before a pause, like those from before a seek, are ignored. - The podcast file rewritten: the same moment of the same part (by segment id when its times moved), playing on if it was. - A seek onto a beat in another file opens that file directly; the intro (the map, no step) closes the walk's code tab. - The panel tells which journey a report is about, so a report of the audio leaving is never taken for the one arriving. Co-Authored-By: Claude Opus 5.5 --- media/journey-podcast.js | 4 +- src/journeys/mapPanel.ts | 2 +- src/podcast/player.ts | 121 ++++++++++++++++++++++++++++--------- src/podcast/resume.ts | 45 ++++++++++++++ test/podcastResume.test.ts | 60 ++++++++++++++++++ 5 files changed, 200 insertions(+), 32 deletions(-) create mode 100644 src/podcast/resume.ts create mode 100644 test/podcastResume.test.ts diff --git a/media/journey-podcast.js b/media/journey-podcast.js index 438da60..44059a8 100644 --- a/media/journey-podcast.js +++ b/media/journey-podcast.js @@ -503,7 +503,7 @@ return { el: root, - /** The journey's episode (none: the bar goes; the same audio again keeps playing). */ + /** The journey's episode (none: the bar goes; the same journey's same audio again keeps playing). */ set(e) { if (!e) { if (ep) { @@ -525,7 +525,7 @@ if (opts.onShown) opts.onShown(false) return } - const same = ep && ep.src === e.src + const same = ep && ep.key === e.key && ep.src === e.src // Another episode: where the one leaving was is said first (kept for next time). if (ep && !same) { audio.pause(); report(false) } ep = e diff --git a/src/journeys/mapPanel.ts b/src/journeys/mapPanel.ts index 4879ed1..59036d5 100644 --- a/src/journeys/mapPanel.ts +++ b/src/journeys/mapPanel.ts @@ -38,7 +38,7 @@ export type MapMessage = | { type: 'details'; open: boolean } | { type: 'beat'; n: number; i: number; user?: boolean } // The podcast's bar (media/journey-podcast.js): where the audio is, and what went wrong. - | { type: 'podcastTime'; t: number; playing: boolean; rate?: number; seek?: boolean } + | { type: 'podcastTime'; t: number; playing: boolean; rate?: number; seek?: boolean; of?: string } | { type: 'podcastError'; message: string } | { type: 'ask'; update?: boolean } | { type: 'restore' } diff --git a/src/podcast/player.ts b/src/podcast/player.ts index 13fa5f8..26125ec 100644 --- a/src/podcast/player.ts +++ b/src/podcast/player.ts @@ -3,18 +3,22 @@ // every time the panel reports, the view at that time (model.ts viewAt) is applied the way a reader's own move is // (walk.goToStep; the animation's beat set in the panel). A seek applies the view at the new time directly: never // the cues in between, and only the newest of quick seeks (LatestWins). The other way round: the reader moving the -// walk (Next, Back, the map, a beat of the animation) moves the audio to the first part about it. +// walk (Next, Back, the map, a beat of the animation) moves the audio to the first part about it; a step the podcast +// skips pauses it, and ▶ then goes on after that step (resume.ts). Where each journey's podcast is is kept (in memory +// and in the workspace state) from every time the panel reports, so another journey, the walk ending, the panel +// closing or the podcast file being rewritten never loses it. import * as vscode from 'vscode' import { gstate, journeys, log, mapPanel, state } from '../app' import { LoadedJourney, posKey } from '../journeys/steps' import { readText } from '../jsonFolder' -import { endJourney, openMap } from '../tour/commands' +import { closeWalkTabs, endJourney, openMap } from '../tour/commands' import { tourState, walk } from '../tour/instances' import { pickJourney } from '../tour/pick' import { wfs } from '../workspaceFs' import { journeysTree } from '../sidebar/journeysTree' import { clock, Episode, LatestWins, parsePodcast, podcastFileOf, resolveEpisode, sameView, timeOf, View, viewAt } from './model' +import { afterStep, remapTime, resumeTime } from './resume' /** Workspace state: where each podcast was left (posKey -> seconds); global: the speed. */ const POS_KEY = 'codeNotes.podcastPos' @@ -22,14 +26,14 @@ const RATE_KEY = 'codeNotes.podcastRate' /** While playing, where it is is stored this often (ms). */ const SAVE_EVERY_MS = 5000 const SKIP_S = 15 -/** After the podcast asks for a seek, the panel's reports of the old time are ignored for at most this long (ms). */ +/** After the podcast asks for a seek or a pause, the panel's reports from before it are ignored for at most this long (ms). */ const STALE_MS = 1500 /** A journey's podcast, read and checked against the journey. */ interface Loaded { file: vscode.Uri; audio: vscode.Uri; ep: Episode; sig: string } -/** What the panel sends about the audio (MapMessage podcastTime). */ -export interface TimeReport { t: number; playing: boolean; rate?: number; seek?: boolean } +/** What the panel sends about the audio (MapMessage podcastTime): `of`, the journey (key) whose audio it is. */ +export interface TimeReport { t: number; playing: boolean; rate?: number; seek?: boolean; of?: string } class Podcasts { /** By journey key. */ @@ -37,10 +41,13 @@ class Podcasts { private item: vscode.StatusBarItem | undefined /** The journey whose podcast was played in the panel (its audio is there): the walk follows it. */ private session: string | undefined - /** The audio as last reported. */ - private t = 0 + /** Where each journey's podcast is (key -> seconds), as the panel last said (or as stored, until it says). */ + private pos = new Map() + /** The session's audio is playing, as last reported. */ private playing = false private lastSave = 0 + /** Journeys whose podcast was playing when its file stopped being playable: it plays on once it is back. */ + private playOnReturn = new Set() /** The view the podcast asked for last, and the beat it last set in the panel (undefined: none). */ private want: View | undefined private beatShown: number | undefined @@ -50,8 +57,9 @@ class Podcasts { /** Errors the panel reported, and how many moves the podcast made (tests read them). */ lastError = '' private moves = 0 - /** When the podcast last asked the panel to seek: until the panel says it did, its older reports are stale. */ - private seekSent = 0 + /** What the podcast last asked the panel for, and when: until the panel says it did (a seek report; a report not + * playing), its older reports are stale. */ + private asked: { kind: 'seek' | 'pause'; at: number } | undefined init(context: vscode.ExtensionContext): void { this.item = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Left, 49.25) @@ -73,9 +81,27 @@ class Podcasts { } const sig = (m: Map) => [...m].map(([k, l]) => `${k}=${l.sig}`).join('\n') const changed = sig(next) !== sig(this.eps) + const before = this.eps this.eps = next if (!changed) return + // The same moment again where the file moved it (a segment's times changed); playing on if it was. + let seekTo: number | undefined + for (const [key, was] of before) { + const now = next.get(key) + if (!now) { + if (key === this.session && this.playing) this.playOnReturn.add(key) + continue + } + if (now.sig === was.sig || !this.pos.has(key)) continue + const t = this.pos.get(key)! + const t2 = remapTime(was.ep, now.ep, t) + if (Math.abs(t2 - t) < 0.05) continue + const lj = journeys.list.get(key) + if (lj) this.savePos(lj, t2, true) + if (key === mapPanel.journey?.key && now.audio.toString() === was.audio.toString()) seekTo = t2 + } mapPanel.sendPodcast() + if (seekTo !== undefined) this.command('seek', { to: seekTo }) journeysTree?.refresh() } @@ -106,11 +132,14 @@ class Podcasts { const l = this.eps.get(lj.key) if (!l) return undefined const { ep } = l + const play = this.playOnReturn.delete(lj.key) return { + key: lj.key, src: toUri(l.audio), title: ep.title, duration: ep.duration, - at: this.positions()[posKey(lj)] ?? 0, + at: this.posOf(lj), + ...(play ? { play: true } : {}), rate: gstate.get(RATE_KEY) ?? 1, chapters: ep.chapters, segments: ep.segments.map((s) => ({ start: s.start, end: s.end, text: s.text, step: s.step })), @@ -118,27 +147,42 @@ class Podcasts { } private positions(): Record { return state.get>(POS_KEY) ?? {} } - private savePos(lj: LoadedJourney, t: number): void { + /** Where `lj`'s podcast is: as last reported, else as stored, else the start. */ + posOf(lj: LoadedJourney): number { return this.pos.get(lj.key) ?? this.positions()[posKey(lj)] ?? 0 } + /** Kept in memory at once; stored when `store` (a pause, a seek, leaving) or every SAVE_EVERY_MS. */ + private savePos(lj: LoadedJourney, t: number, store = false): void { + this.pos.set(lj.key, t) + if (!store && Date.now() - this.lastSave < SAVE_EVERY_MS) return this.lastSave = Date.now() void state.update(POS_KEY, { ...this.positions(), [posKey(lj)]: Math.round(t * 10) / 10 }) } + /** The session's time (the status bar's). */ + private get t(): number { + const lj = this.sessionJourney() + return lj ? this.posOf(lj) : 0 + } // ---------- audio → journey ---------- /** The panel says where the audio is. Playing (or seeking), the walk goes where the podcast is at that time. */ - onTime(lj: LoadedJourney, m: TimeReport): void { + onTime(shown: LoadedJourney, m: TimeReport): void { + // The journey the audio is of (the panel may have moved on to another one since it said it). + const lj = (m.of && journeys.list.get(m.of)) || shown const l = this.eps.get(lj.key) if (!l) return - const wasPlaying = this.playing - this.t = m.t - this.playing = m.playing + // A report from before the seek or pause just asked for (the walk would go back there for a moment): ignored. + const asked = this.asked + if (asked && lj.key === this.session) { + const answers = asked.kind === 'seek' ? !!m.seek : !m.playing + if (!answers && Date.now() - asked.at < STALE_MS) return + this.asked = undefined + } + const wasPlaying = lj.key === this.session && this.playing if (m.rate && m.rate !== gstate.get(RATE_KEY)) void gstate.update(RATE_KEY, m.rate) + this.savePos(lj, m.t, (wasPlaying && !m.playing) || !!m.seek) if (m.playing) this.session = lj.key if (this.session !== lj.key) return - // A report from before the seek just asked for (the walk would go back there for a moment): only the time. - if (m.seek) this.seekSent = 0 - else if (this.seekSent && Date.now() - this.seekSent < STALE_MS) { this.renderItem(); return } - if ((wasPlaying && !m.playing) || m.seek || Date.now() - this.lastSave > SAVE_EVERY_MS) this.savePos(lj, m.t) + this.playing = m.playing this.renderItem() // Paused and not moved: the walk is the reader's. if (!m.playing && !m.seek) return @@ -165,12 +209,18 @@ class Podcasts { if (!view.step) { this.beatShown = undefined mapPanel.send({ type: 'podcastBeat', n: 0, i: -1 }) - if (walk.touring() && tourState.key === lj.key) await endJourney() + if (walk.touring() && tourState.key === lj.key) { + // The map, no step: the walk ends, and the code tab it opened goes with it. + const doc = tourState.doc + await endJourney() + await closeWalkTabs(lj, doc?.column) + } return } this.beatShown = view.beat mapPanel.send({ type: 'podcastBeat', n: view.step, i: view.beat ?? -1, ...(m.still ? { still: true } : {}) }) - if (!(walk.touring() && tourState.isAt(lj, view.step))) await walk.goToStep(lj, view.step, { focus: false }) + // On a beat whose code is in another file, that file opens (the beat's), not the step's first. + if (!(walk.touring() && tourState.isAt(lj, view.step))) await walk.goToStep(lj, view.step, { focus: false, beat: view.beat }) } catch (e) { log.error(`podcast: ${e}`) } finally { @@ -191,18 +241,20 @@ class Podcasts { const step = walk.touring() && tourState.key === lj.key ? tourState.step : 0 if (step === (this.want?.step ?? -1)) return if (!step || tourState.key !== lj.key) { - // Another journey, or the walk ended: the podcast stops; its place is kept. + // Another journey, or the walk ended: the podcast stops; its place is kept (stored now: the panel's pause + // report may come once the session is over). this.want = { step: 0 } - if (tourState.key !== lj.key) this.session = undefined + this.savePos(lj, this.posOf(lj), true) this.command('pause') + if (tourState.key !== lj.key) { this.session = undefined; this.playing = false } this.renderItem() return } const t = timeOf(l.ep, step) if (t === undefined) { + // A step the podcast skips: the walk stays there, the audio pauses and says so; ▶ goes on after the step. this.want = { step } - this.command('pause') - vscode.window.setStatusBarMessage(`$(info) The podcast doesn't cover step ${step}`, 3000) + this.command('pause', { note: `Step ${step} isn't in the podcast`, ...resumeAfter(l.ep, step) }) return } const v = viewAt(l.ep, t) @@ -225,7 +277,7 @@ class Podcasts { /** The panel closed: its audio is gone. */ onClosed(): void { const lj = this.sessionJourney() - if (lj) this.savePos(lj, this.t) + if (lj) this.savePos(lj, this.posOf(lj), true) this.session = undefined this.playing = false this.want = undefined @@ -251,7 +303,7 @@ class Podcasts { // ---------- commands ---------- private command(action: string, more: Record = {}): void { - if (action === 'seek') this.seekSent = Date.now() + if (action === 'seek' || action === 'pause') this.asked = { kind: action, at: Date.now() } mapPanel.send({ type: 'podcastCmd', action, ...more }) } @@ -259,11 +311,16 @@ class Podcasts { async play(arg?: unknown): Promise { const lj = await this.journeyFor(arg) if (!lj) return + // Not the podcast playing in the panel: it goes on where it was left (or where the walk is: resumeTime). + const fresh = this.session !== lj.key || mapPanel.journey?.key !== lj.key if (mapPanel.journey?.key !== lj.key) await openMap(lj) else if (!mapPanel.visible) walk.showMap(lj, true) + const walkStep = walk.touring() && tourState.key === lj.key ? tourState.step : 0 + const at = fresh ? resumeTime(this.eps.get(lj.key)!.ep, this.posOf(lj), walkStep) : undefined this.session = lj.key - this.want = undefined - this.command('play') + // Where the walk is now (the walk telling of a move that isn't one pauses nothing). + this.want = { step: walkStep } + this.command('play', at === undefined || Math.abs(at - this.posOf(lj)) < 0.05 ? {} : { at }) } private async journeyFor(arg?: unknown): Promise { @@ -332,6 +389,12 @@ class Podcasts { } } +/** The pause command's `resumeAt` for a step the podcast skips (none when nothing comes after it). */ +function resumeAfter(ep: Episode, step: number): { resumeAt?: number } { + const t = afterStep(ep, step) + return t === undefined ? {} : { resumeAt: t } +} + /** A part on the map (no step) by where it is: the first is the intro, the last the recap. */ function mapPartName(ep: Episode, t: number): string { const i = ep.chapters.findIndex((c, k) => t < c.end || k === ep.chapters.length - 1) diff --git a/src/podcast/resume.ts b/src/podcast/resume.ts new file mode 100644 index 0000000..eb15c5a --- /dev/null +++ b/src/podcast/resume.ts @@ -0,0 +1,45 @@ +// Where a podcast goes on from: after the walk moved to a step it skips, when it is played again, when its file was +// rewritten. Pure (no vscode): unit tests use it as is (test/podcastResume.test.ts); player.ts applies it. + +import { Episode, segmentAt, timeOf, viewAt } from './model' + +/** + * The walk is on step `step`, which the podcast never talks about: where ▶ goes on. The first part about a later + * step; else (no step after it is covered) the part after the last one about an earlier step (the recap); else + * undefined (nothing after it: ▶ plays from where the audio is). + */ +export function afterStep(ep: Episode, step: number): number | undefined { + const later = ep.segments.find((s) => s.step > step) + if (later) return later.start + let last = -1 + ep.segments.forEach((s, i) => { if (s.step && s.step < step) last = i }) + return last >= 0 && last + 1 < ep.segments.length ? ep.segments[last + 1].start : undefined +} + +/** + * Where ▶ starts a podcast that isn't playing in the panel: where it was left (`saved`), unless the walk is on a step + * (`walkStep`, 0: none) that time isn't about; then the first part about that step, or, a step it skips, the part + * after it (afterStep). + */ +export function resumeTime(ep: Episode, saved: number, walkStep: number): number { + const t = Math.max(0, Math.min(saved, ep.duration)) + if (!walkStep || viewAt(ep, t).step === walkStep) return t + return timeOf(ep, walkStep) ?? afterStep(ep, walkStep) ?? t +} + +/** + * The podcast file was rewritten while at second `t` of `from`: the same moment in `to`. Times unchanged: `t`. The + * segment playing then moved: the same place in that segment (by id), kept inside it; it is gone: `t`, kept inside the + * episode. + */ +export function remapTime(from: Episode, to: Episode, t: number): number { + const i = segmentAt(from.segments, t) + const clamp = (x: number) => Math.max(0, Math.min(x, to.duration)) + if (i < 0) return clamp(t) + const was = from.segments[i] + const now = to.segments.find((s) => s.id === was.id) + if (!now) return clamp(t) + if (now.start === was.start) return clamp(t) + const into = Math.max(0, t - was.start) + return clamp(Math.min(now.start + into, Math.max(now.start, now.end - 0.05))) +} diff --git a/test/podcastResume.test.ts b/test/podcastResume.test.ts new file mode 100644 index 0000000..aa49701 --- /dev/null +++ b/test/podcastResume.test.ts @@ -0,0 +1,60 @@ +import { test } from 'node:test' +import assert from 'node:assert/strict' +import { parsePodcast, resolveEpisode } from '../src/podcast/model' +import { afterStep, remapTime, resumeTime } from '../src/podcast/resume' + +// Where a podcast goes on from (src/podcast/resume.ts): after a step it skips, when played again, after its file was +// rewritten. + +const journey = { steps: [{ id: 'a', beats: 3 }, { id: 'b', beats: 0 }, { id: 'c', beats: 2 }, { id: 'd', beats: 0 }] } +const seg = (id: string, at: unknown, start: number, end: number) => ({ id, at, start, end, text: id, speaker: 'host' }) +const episode = (segments: object[]) => { + const p = parsePodcast(JSON.stringify({ version: 1, title: 'T', journey: { id: 'j' }, audio: 'j.mp3', duration: 100, segments })) + assert.ok(typeof p !== 'string', String(p)) + return resolveEpisode(p, journey) +} +// Steps 1 and 3 are covered; 2 and 4 are not. +const sample = () => episode([ + seg('intro', null, 0, 9), + seg('a1', { step: 'a', beat: 1 }, 10, 19), + seg('a3', { step: 'a', beat: 3 }, 20, 29), + seg('map', null, 30, 39), + seg('c', { step: 'c' }, 40, 49), + seg('outro', null, 60, 70), +]) + +test('a step the podcast skips: ▶ goes on with the next covered step, else what follows the last covered one', () => { + const ep = sample() + assert.equal(afterStep(ep, 2), 40, 'step 2 skipped: step 3, not back to step 1 nor the map between') + assert.equal(afterStep(ep, 4), 60, 'step 4 (nothing covered after it): the outro after step 3') + const noOutro = episode([seg('a1', { step: 'a' }, 0, 9), seg('c', { step: 'c' }, 10, 19)]) + assert.equal(afterStep(noOutro, 4), undefined, 'nothing after it: ▶ plays from where it is') +}) + +test('played again: where it was left, unless the walk is on another step', () => { + const ep = sample() + assert.equal(resumeTime(ep, 24, 0), 24, 'no walk: where it was') + assert.equal(resumeTime(ep, 24, 1), 24, 'the walk on the step that time is about: where it was') + assert.equal(resumeTime(ep, 24, 3), 40, 'the walk on step 3: its first part') + assert.equal(resumeTime(ep, 24, 2), 40, 'the walk on a skipped step: the part after it') + assert.equal(resumeTime(ep, 500, 0), 100, 'kept inside the episode') +}) + +test('the file rewritten: the same moment, by segment id when the times moved', () => { + const was = sample() + assert.equal(remapTime(was, sample(), 23.5), 23.5, 'same times: same time') + const moved = episode([ + seg('intro', null, 0, 4), + seg('a1', { step: 'a', beat: 1 }, 5, 14), + seg('a3', { step: 'a', beat: 3 }, 15, 24), + seg('map', null, 25, 39), + seg('c', { step: 'c' }, 40, 49), + seg('outro', null, 60, 70), + ]) + assert.equal(remapTime(was, moved, 23.5), 18.5, 'a3 starts 5 s earlier: 3.5 s into a3 again') + assert.equal(remapTime(was, moved, 42), 42, 'c did not move') + const shorter = episode([seg('intro', null, 0, 4), seg('a3', { step: 'a', beat: 3 }, 5, 7)]) + assert.ok(remapTime(was, shorter, 28) < 7, 'kept inside its segment when it got shorter') + const gone = episode([seg('intro', null, 0, 4), seg('x', { step: 'c' }, 5, 50)]) + assert.equal(remapTime(was, gone, 23.5), 23.5, 'its segment gone: the same time') +}) From 603a5079a8c2192d3cc336c6e1b6e6d2ff41c7e6 Mon Sep 17 00:00:00 2001 From: tomeyer97 <107920881+tomeyer97@users.noreply.github.com> Date: Wed, 18 Nov 2026 14:32:44 +0100 Subject: [PATCH 07/45] Podcast integration tests: real audio time after seeks, skipped steps, rewritten file, kept place, beat in another file ONLY_PODCAST=1 (with ONLY_MAIN=1) runs main/podcast.ts alone. Co-Authored-By: Claude Opus 5.5 --- test/integration/helpers.ts | 1 + test/integration/main/podcast.ts | 141 ++++++++++++++++++++++++++++++- test/integration/suite.ts | 6 ++ 3 files changed, 144 insertions(+), 4 deletions(-) diff --git a/test/integration/helpers.ts b/test/integration/helpers.ts index 543f5d1..7da8d13 100644 --- a/test/integration/helpers.ts +++ b/test/integration/helpers.ts @@ -9,6 +9,7 @@ // CODE_NOTES_PROFILE= keep VS Code's profiles (user data) there instead of in temp folders (run.ts) // CODE_NOTES_CONSOLE_ALL=1 print every workbench console message, not only the errors (run.ts, check run) // ONLY_MAIN / ONLY_UNTRUSTED / ONLY_CHECK=1 run that suite alone (run.ts; with none set, all three) +// ONLY_PODCAST=1 with ONLY_MAIN=1: main/podcast.ts alone (suite.ts) // Set by run.ts or the tests themselves, not by hand: // CODE_NOTES_CDP the workbench's DevTools port (main and check runs: devtools.ts) // CODE_NOTES_CONSOLE the file the workbench console errors are collected in (check run) diff --git a/test/integration/main/podcast.ts b/test/integration/main/podcast.ts index edd4592..7af42dd 100644 --- a/test/integration/main/podcast.ts +++ b/test/integration/main/podcast.ts @@ -1,8 +1,10 @@ // Podcast mode: a journey with a podcast file next to it plays in the journey panel, and the walk follows the voice // (the step's code opens, the animation's beat lights its line); seeking anywhere puts the walk exactly where it is at -// that time, backwards too, the last of quick seeks only; Next while it plays moves the audio; the audio goes on in a -// background tab. The audio is a 40 s tone (test/fixtures/podcast/tone.mp3), so this also proves VS Code's own -// Electron plays mp3 from the workspace and seeks in it. Source: src/podcast/, media/journey-podcast.js. +// that time, backwards too, the last of quick seeks only, and the extension is told where the audio really is; Next +// while it plays moves the audio; the audio goes on in a background tab; a step the podcast skips keeps the walk there +// and ▶ goes on after it; each journey's place is kept (another journey, a rewritten podcast file). The audio is a +// 40 s tone (test/fixtures/podcast/tone.mp3), so this also proves VS Code's own Electron plays mp3 from the workspace +// (fetched whole, as a blob) and seeks in it. Source: src/podcast/, media/journey-podcast.js. import * as vscode from 'vscode' import * as fs from 'fs' import * as path from 'path' @@ -33,6 +35,35 @@ async function panelFrame(): Promise { }, 10000) } +/** What the panel's audio itself says: its time, paused, the bar's note or error. */ +async function panelAudio(): Promise<{ t: number; paused: boolean; note: string; blob: boolean }> { + const f = await panelFrame() + return f.evaluate(() => { + const d = (globalThis as any).document + const a = d.querySelector('.pod audio') + const e = d.querySelector('.pod-err') + return { t: a.currentTime, paused: a.paused, note: e.hidden ? '' : e.textContent, blob: a.src.startsWith('blob:') } + }) +} + +/** The journey "podgap": three steps, the podcast says nothing about step 2 (its own copy of the tone). */ +function writeGapJourney(g3start = 9) { + writeJourney(journeysDir(), journey('podgap', [ + step('src/pod.ts', 1, 3, { id: 'g1', title: 'one' }), + step('src/pod.ts', 4, 6, { id: 'g2', title: 'two, not in the podcast' }), + step('src/pod2.ts', 1, 1, { id: 'g3', title: 'three' }), + ], { title: 'Pod gap' })) + fs.copyFileSync(path.join(__dirname, '../../../../test/fixtures/podcast/tone.mp3'), path.join(journeysDir(), 'podgap.mp3')) + writeGapPodcast(g3start) +} +function writeGapPodcast(g3start: number) { + const seg = (id: string, at: unknown, start: number, end: number) => ({ id, at, speaker: 'host', text: `Part ${id}.`, start, end }) + fs.writeFileSync(path.join(journeysDir(), 'podgap.podcast.json'), JSON.stringify({ + version: 1, title: 'Pod gap', journey: { id: 'podgap' }, audio: 'podgap.mp3', duration: 40, + segments: [seg('intro', null, 0, 2.8), seg('g1', { step: 'g1' }, 3, g3start - 0.2), seg('g3', { step: 'g3' }, g3start, 20), seg('outro', null, 21, 39)], + })) +} + /** The journey "pod" (step 1 and 2 with animations, step 3 without) and its podcast, the tone next to it. */ function writePodJourney() { writeLines(wsPath('src', 'pod.ts'), ['export function one() {', ' return 1', '}', 'export function two() {', ' return 2', '}']) @@ -112,7 +143,11 @@ export const podcastTests = [ for (const [t, n, file, line] of points) { await seek(t) await until(`seek to ${t}s: the audio there, step ${n}, ${file ?? 'no file'}, line ${line} lit`, () => Math.abs(pod().t - t) < 0.5 && at(n, file, line)(), 8000) + // What the extension (and the status bar) has is what the audio itself says. + const a = await panelAudio() + assert.ok(Math.abs(a.t - t) < 0.5 && Math.abs(a.t - pod().t) < 0.5, `seek to ${t}s: the audio says ${a.t}, the extension has ${pod().t}`) } + assert.ok((await panelAudio()).blob, 'the audio was loaded whole (a blob)') assert.ok(!pod().playing, 'seeking while paused stays paused') }), @@ -168,7 +203,7 @@ export const podcastTests = [ await vscode.commands.executeCommand('workbench.action.closeActiveEditor') }), - test('podcast: a long recording: a seek 9 minutes in plays from there (the panel loads the audio in ranges)', async () => { + test('podcast: a long recording: a seek 9 minutes in plays from there', async () => { // 10 minutes of silence, 8 kHz 8-bit mono WAV (4.8 MB), and a journey of one step for it. const secs = 600, rate = 8000 const wav = Buffer.alloc(44 + secs * rate, 128) @@ -191,6 +226,104 @@ export const podcastTests = [ await until('paused', () => !pod().playing) }), + test('podcast: Next onto a step the podcast skips: the walk stays there, the audio pauses and says so; ▶ goes on after it', async () => { + writeGapJourney() + await until('its podcast is found', () => pod().journeys.includes('podgap'), 10000) + await vscode.commands.executeCommand('codeNotes.playPodcast', 'podgap') + await until('playing podgap', () => pod().playing && pod().session === 'podgap', 10000) + await seek(4) + await until('step 1', () => tour().step === 1 && pod().t >= 4, 8000) + await vscode.commands.executeCommand('codeNotes.nextStep') + await until('Next: step 2, the audio paused', () => tour().step === 2 && !pod().playing, 5000) + await sleep(1200) + assert.equal(tour().step, 2, 'the walk stays on step 2 (no late report takes it back)') + assert.ok(!pod().playing, 'still paused') + assert.match((await panelAudio()).note, /isn't in the podcast/) + await vscode.commands.executeCommand('codeNotes.podcastToggle') + await until('▶: on after step 2, at step 3\'s part (9 s), not back to step 1', () => pod().playing && tour().step === 3 && pod().t >= 9 && pod().t < 12, 8000) + assert.equal((await panelAudio()).note, '', 'the note went once it played on') + }), + + test('podcast: the podcast file rewritten: the same moment of the same part, still playing; walk and audio agree', async () => { + await vscode.commands.executeCommand('codeNotes.podcastToggle') + await until('paused', () => !pod().playing) + const t0 = pod().t + // Step 3's part now starts 2 s earlier: the same place in it is 2 s earlier. + writeGapPodcast(7) + await until(`the time follows its part: ${(t0 - 2).toFixed(1)}`, () => Math.abs(pod().t - (t0 - 2)) < 0.3, 8000) + const a = await panelAudio() + assert.ok(Math.abs(a.t - (t0 - 2)) < 0.3, `the audio is there too: ${a.t}`) + assert.equal(tour().step, 3, 'the walk stays on step 3') + await vscode.commands.executeCommand('codeNotes.podcastToggle') + await until('playing', () => pod().playing) + writeGapPodcast(9) + await sleep(1500) + assert.ok(pod().playing && (await panelAudio()).paused === false, 'rewritten while playing: it plays on') + assert.equal(tour().step, 3, 'still step 3') + assert.ok(pod().t >= 9, `the same moment, moved back with its part: ${pod().t}`) + await vscode.commands.executeCommand('codeNotes.podcastToggle') + await until('paused', () => !pod().playing) + }), + + test('podcast: each journey\'s place is kept: another journey, then ▶ goes on where it was', async () => { + await vscode.commands.executeCommand('codeNotes.playPodcast', 'pod') + await until('pod in the panel, playing', () => pod().session === 'pod' && pod().playing, 10000) + await seek(13) + await until('step 2', () => tour().step === 2 && pod().t >= 13, 8000) + await vscode.commands.executeCommand('codeNotes.podcastToggle') + await until('paused', () => !pod().playing) + const kept = pod().t + // Another journey: the walk leaves pod. + await vscode.commands.executeCommand('codeNotes.startJourney', 'podgap') + await until('walking podgap', () => tour().journey === 'podgap' || tour().map === 'podgap', 8000) + await vscode.commands.executeCommand('codeNotes.playPodcast', 'pod') + await until(`▶ pod: on from ${kept.toFixed(1)}, step 2 (not 0:00)`, () => pod().session === 'pod' && pod().playing && pod().t >= kept - 0.3 && pod().t < kept + 3 && tour().step === 2, 10000) + await vscode.commands.executeCommand('codeNotes.podcastToggle') + await until('paused', () => !pod().playing) + }), + + test('podcast: the intro closes the walk\'s code tab; a seek onto a beat in another file opens that file, never the step\'s first', async () => { + const actors = [{ id: 'svc', type: 'service', col: 0, label: 'Server', fn: 'one()', checks: ['a'] }] + writeJourney(journeysDir(), journey('podbeat', [ + step('src/pod.ts', 1, 3, { id: 'b1', title: 'one', scene: { actors, wires: [], beats: [ + { focus: 'svc', caption: 'Here.', code: { file: 'src/pod.ts', line: 2, text: 'return 1' } }, + { focus: 'svc', caption: 'There.', code: { file: 'src/pod2.ts', line: 1, text: 'export const three = 3' } }, + ] } }), + ], { title: 'Pod beat' })) + fs.copyFileSync(path.join(__dirname, '../../../../test/fixtures/podcast/tone.mp3'), path.join(journeysDir(), 'podbeat.mp3')) + const seg = (id: string, at: unknown, start: number, end: number) => ({ id, at, speaker: 'host', text: id, start, end }) + fs.writeFileSync(path.join(journeysDir(), 'podbeat.podcast.json'), JSON.stringify({ + version: 1, title: 'Pod beat', journey: { id: 'podbeat' }, audio: 'podbeat.mp3', duration: 40, + segments: [seg('intro', null, 0, 2.8), seg('here', { step: 'b1', beat: 1 }, 3, 5.8), seg('there', { step: 'b1', beat: 2 }, 6, 20), seg('outro', null, 21, 39)], + })) + await until('its podcast is found', () => pod().journeys.includes('podbeat'), 10000) + await vscode.commands.executeCommand('codeNotes.playPodcast', 'podbeat') + await until('playing podbeat', () => pod().playing && pod().session === 'podbeat', 10000) + await vscode.commands.executeCommand('codeNotes.podcastToggle') + await until('paused', () => !pod().playing) + await seek(4) + await until('step 1, beat 1: pod.ts line 2 lit', at(1, 'pod.ts', 2), 8000) + const walkTabs = () => vscode.window.tabGroups.all.filter((g) => g.viewColumn !== tour().mapColumn).flatMap((g) => g.tabs) + .filter((t) => t.isPreview && t.input instanceof vscode.TabInputText && /pod2?\.ts$/.test(t.input.uri.path)).map((t) => t.label) + assert.ok(walkTabs().length > 0, 'the walk opened its code in a preview tab') + await seek(1) + await until('the intro: no step, the walk\'s preview tab closed', () => tour().step === 0 && !pod().applying && walkTabs().length === 0, 8000) + // Every file the code group shows from here on. + const shown: string[] = [] + const note = (u: vscode.Uri) => { if (u.scheme === 'file') shown.push(path.basename(u.fsPath)) } + const subs = [ + vscode.window.onDidChangeVisibleTextEditors((es) => { for (const e of es) if (e.viewColumn !== tour().mapColumn) note(e.document.uri) }), + vscode.window.tabGroups.onDidChangeTabs((e) => { for (const t of [...e.opened, ...e.changed]) if (t.input instanceof vscode.TabInputText) note(t.input.uri) }), + ] + const sub = { dispose: () => subs.forEach((x) => x.dispose()) } + try { + await seek(7) + await until('step 1, beat 2: pod2.ts line 1 lit', at(1, 'pod2.ts', 1), 8000) + await sleep(300) + } finally { sub.dispose() } + assert.ok(!shown.includes('pod.ts'), `the step's own file was never shown first: ${shown.join(' → ')}`) + }), + test('podcast: closing the panel stops it; the status item goes', async () => { await vscode.commands.executeCommand('codeNotes.showMap') await until('the panel', () => pod().mapVisible) diff --git a/test/integration/suite.ts b/test/integration/suite.ts index 1039bb4..1695fcc 100644 --- a/test/integration/suite.ts +++ b/test/integration/suite.ts @@ -42,6 +42,12 @@ export async function run(): Promise { ctx.ws = ctx.folder.uri.fsPath ctx.notesDir = path.join(ctx.ws, '.code-notes') ctx.api = await activate() + // ONLY_PODCAST=1: main/podcast.ts alone (it builds on nothing before it). + if (process.env.ONLY_PODCAST) { + await runTests(podcastTests) + console.log('all passed') + return + } await runTests([ ...notesTests, ...journeyTourTests, From f95c6a9e1c2eb4dd70d49154fdf9db2384ebba38 Mon Sep 17 00:00:00 2001 From: tomeyer97 <107920881+tomeyer97@users.noreply.github.com> Date: Wed, 18 Nov 2026 14:35:05 +0100 Subject: [PATCH 08/45] Podcasts: a broken podcast leaves a trace; problems in the Problems view A podcast file that can't be played no longer vanishes: its row keeps a greyed play button and the tooltip says why, the panel shows one line, "Podcast unavailable", with Show why (the Problems view), and Play says why. Every problem is a diagnostic on the .podcast.json (on the field or segment at fault) and a warning line in the output, once per change. One that plays says what is wrong in one short line in the panel and the row's tooltip ("2 parts can't be shown", "Written for ...", a cut-off audio in plain words, measured once the panel has loaded the audio). A file that breaks while it plays (half-written) keeps the last good version playing and says so; the status item goes when its podcast goes, so a click on it always does something. The audio file is watched too: putting it back brings the podcast back. An interrupted play (AbortError) is no longer a warning; a media error names the file and what it most likely is. Co-Authored-By: Claude Opus 5.5 --- media/journey-map.js | 1 + media/journey-podcast.css | 9 ++ media/journey-podcast.js | 35 ++++++-- package.json | 18 +++- src/extension.ts | 2 + src/journeys/mapPanel.ts | 3 + src/podcast/load.ts | 108 +++++++++++++++++++++++ src/podcast/player.ts | 171 +++++++++++++++++++++++++++++-------- src/sidebar/journeyRows.ts | 14 ++- src/testApi.ts | 7 ++ src/tour/mapMessages.ts | 2 + 11 files changed, 325 insertions(+), 45 deletions(-) create mode 100644 src/podcast/load.ts diff --git a/media/journey-map.js b/media/journey-map.js index e4a4ce5..8cabda3 100644 --- a/media/journey-map.js +++ b/media/journey-map.js @@ -35,6 +35,7 @@ // { type: 'question', id } { type: 'checkpoint', id } { type: 'openFile' } { type: 'restore' } { type: 'authors' } // { type: 'beat', n, i, user? } (the animation's beat on step n; i = -1: the scene is gone; user: the reader moved it) // { type: 'podcastTime', t, playing, rate, seek? } { type: 'podcastError', message } (journey-podcast.js) +// { type: 'podcastMeta', duration } { type: 'podcastWhy' } (journey-podcast.js) // These are src/journeys/mapPanel.ts MapMessage (the extension's list, with `close` and `pick`, which it handles but // nothing here posts, and its own `closed`): a name added here goes there too. ;(function () { diff --git a/media/journey-podcast.css b/media/journey-podcast.css index 6b5345d..d7e1b97 100644 --- a/media/journey-podcast.css +++ b/media/journey-podcast.css @@ -52,3 +52,12 @@ body.has-pod .body.wide .mapwrap { height: calc(100vh - var(--headH, 0px) - var( .pod-b.prev, .pod-b.next { display: none; } } @media (prefers-reduced-motion: reduce) { .pod-track, .pod-thumb { transition: none; } } + +/* What is wrong with the podcast (journey-podcast.js `notice`), or that it can't be played: one muted line and + "Show why". Unavailable: that line alone. */ +.pod-note { display: flex; align-items: baseline; gap: 8px; min-width: 0; font-size: 0.9em; color: var(--muted); } +.pod-note[hidden] { display: none; } +.pod-note-t { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; min-width: 0; } +.pod-note::before { content: '⚠'; color: var(--warn); flex: none; } +.pod-why { flex: none; } +.pod.unavail .pod-tl, .pod.unavail .pod-row, .pod.unavail .pod-cap { display: none; } diff --git a/media/journey-podcast.js b/media/journey-podcast.js index 8e2cf69..3cae0f1 100644 --- a/media/journey-podcast.js +++ b/media/journey-podcast.js @@ -6,12 +6,15 @@ // Needs common.js. Made by journey-map.js: JourneyPodcast({ post, stepTitle(n), onShown(h) }). // // In (journey-map.js routes them here): -// { type: 'podcast', episode? } the journey's episode ({ src, title, duration, at, rate, chapters, segments }), or -// none (the bar goes) +// { type: 'podcast', episode? } the journey's episode ({ src, title, duration, at, rate, chapters, segments, +// notice? }), or { unavailable: why } (a podcast that can't be played: one line +// saying so), or none (the bar goes). notice: what is wrong with one that plays // { type: 'podcastCmd', action: 'play' | 'pause' | 'toggle' | 'skip' | 'seek' | 'part', by?, to?, dir? } // Out: // { type: 'podcastTime', t, playing, rate, seek? } where the audio is (seek: moved by a seek, not by playing) // { type: 'podcastError', message } +// { type: 'podcastMeta', duration } the audio's real length, once loaded (the extension checks the file against it) +// { type: 'podcastWhy' } "Show why": the problems of the podcast file ;(function () { const { el, svgEl, runKey } = window.common @@ -91,11 +94,18 @@ const cap = el('div', 'pod-cap') const err = el('span', 'pod-err') err.hidden = true + // What is wrong with the podcast (or that it can't be played), and the way to the details. + const note = el('div', 'pod-note') + note.hidden = true + const noteText = el('span', 'pod-note-t') + const whyB = el('button', 'link pod-why', 'Show why') + whyB.onclick = () => post({ type: 'podcastWhy' }) + note.append(noteText, whyB) const row = el('div', 'pod-row') const ctl = el('div', 'pod-ctl') ctl.append(prevB, backB, playB, fwdB, nextB) row.append(ctl, time, err, rateB) - root.append(tl, row, cap, audio) + root.append(note, tl, row, cap, audio) document.body.append(root) /** The episode shown ({ src, duration, chapters: [{ start, end, step }], segments: [{ start, end, text, step }] }). */ @@ -324,6 +334,7 @@ // ---------- the audio ---------- audio.addEventListener('loadedmetadata', () => { + if (Number.isFinite(audio.duration)) post({ type: 'podcastMeta', duration: audio.duration }) if (startAt) { audio.currentTime = Math.min(startAt, duration()); startAt = 0 } build() draw() @@ -354,13 +365,21 @@ el: root, /** The journey's episode (none: the bar goes; the same audio again keeps playing). */ set(e) { + const unavailable = e && e.unavailable + note.hidden = !(e && (e.notice || unavailable)) + noteText.textContent = unavailable ? 'Podcast unavailable' : (e && e.notice) || '' + note.title = unavailable || (e && e.notice) || '' + root.classList.toggle('unavail', !!unavailable) + if (unavailable) e = undefined if (!e) { if (ep) { audio.pause(); audio.removeAttribute('src'); audio.load() } ep = undefined - root.hidden = true - document.body.classList.remove('has-pod') - podH = '0px' - document.documentElement.style.setProperty('--podH', '0px') + root.hidden = !unavailable + document.body.classList.toggle('has-pod', !!unavailable) + if (!unavailable) { + podH = '0px' + document.documentElement.style.setProperty('--podH', '0px') + } if (opts.onShown) opts.onShown(false) return } @@ -392,7 +411,7 @@ if (Object.hasOwn(actions, m.action)) actions[m.action]() }, /** For tests: the audio's state. */ - get state() { return { t: audio.currentTime, playing: playing(), paused: audio.paused, ready: audio.readyState, duration: duration(), error: err.hidden ? '' : err.textContent } }, + get state() { return { t: audio.currentTime, playing: playing(), paused: audio.paused, ready: audio.readyState, duration: duration(), error: err.hidden ? '' : err.textContent, note: note.hidden ? '' : noteText.textContent } }, get shown() { return !!ep }, /** The journey's titles changed (another journey of the same id, a rename): the tip and labels follow. */ redraw() { if (ep) draw() }, diff --git a/package.json b/package.json index f787a05..96bfddd 100644 --- a/package.json +++ b/package.json @@ -455,6 +455,13 @@ "category": "Code Notes", "icon": "$(play)" }, + { + "command": "codeNotes.podcastUnavailable", + "title": "Podcast Unavailable (the Journey's Tooltip Says Why)", + "category": "Code Notes", + "icon": "$(play)", + "enablement": "false" + }, { "command": "codeNotes.podcastToggle", "title": "Play or Pause the Journey Podcast", @@ -1064,10 +1071,19 @@ { "command": "codeNotes.playPodcast", "group": "inline@0", - "when": "view == codeNotes.journeys && viewItem =~ /^journey.*;podcast/" + "when": "view == codeNotes.journeys && viewItem =~ /^journey.*;podcast($|;)/" + }, + { + "command": "codeNotes.podcastUnavailable", + "group": "inline@0", + "when": "view == codeNotes.journeys && viewItem =~ /^journey.*;podcastBroken/" } ], "commandPalette": [ + { + "command": "codeNotes.podcastUnavailable", + "when": "false" + }, { "command": "codeNotes.reply", "when": "false" diff --git a/src/extension.ts b/src/extension.ts index 532622d..e0517fb 100644 --- a/src/extension.ts +++ b/src/extension.ts @@ -249,6 +249,8 @@ function registerCommands(context: vscode.ExtensionContext): void { 'codeNotes.toggleAuthorMode': toggleAuthorMode, 'codeNotes.toggleAnimation': chord(toggleAnimation), 'codeNotes.playPodcast': (arg?: unknown) => podcasts.play(arg), + // The greyed ▶ of a podcast that can't be played (disabled in the menu): why, if it is ever run. + 'codeNotes.podcastUnavailable': (arg?: unknown) => podcasts.play(arg), 'codeNotes.podcastToggle': chord(() => podcasts.toggle()), 'codeNotes.podcastBack': chord(() => podcasts.back()), 'codeNotes.podcastForward': chord(() => podcasts.forward()), diff --git a/src/journeys/mapPanel.ts b/src/journeys/mapPanel.ts index 4879ed1..cc0c765 100644 --- a/src/journeys/mapPanel.ts +++ b/src/journeys/mapPanel.ts @@ -40,6 +40,9 @@ export type MapMessage = // The podcast's bar (media/journey-podcast.js): where the audio is, and what went wrong. | { type: 'podcastTime'; t: number; playing: boolean; rate?: number; seek?: boolean } | { type: 'podcastError'; message: string } + // The audio's real length once loaded; "Show why" on a podcast with problems (src/podcast/validate.ts). + | { type: 'podcastMeta'; duration: number } + | { type: 'podcastWhy' } | { type: 'ask'; update?: boolean } | { type: 'restore' } | { type: 'authors' } diff --git a/src/podcast/load.ts b/src/podcast/load.ts new file mode 100644 index 0000000..d662b10 --- /dev/null +++ b/src/podcast/load.ts @@ -0,0 +1,108 @@ +// Reading a journey's podcast file and telling the author what is wrong with it (validate.ts says what): Problems-view +// diagnostics on the `.podcast.json` (on the segment or field at fault), warning lines in the "Code Notes" output +// (once per change, not per scan), and a watch on the audio files the podcasts name, so a podcast comes back as soon +// as its audio is there (or goes when it goes) without touching the JSON. The player (player.ts) decides what it +// plays from the result. + +import * as vscode from 'vscode' +import { log } from '../app' +import { LoadedJourney } from '../journeys/steps' +import { readText } from '../jsonFolder' +import { wfs } from '../workspaceFs' +import { podcastFileOf, PodcastProblem } from './model' +import { audioPathProblem, lineCol, locate, validatePodcast, Validation } from './validate' + +/** A podcast file next to a journey, read and checked. */ +export interface PodcastRead { + file: vscode.Uri + raw: string + /** The audio file it names (undefined: it names none, or one outside the journeys folder). */ + audio?: vscode.Uri + audioSize: number + v: Validation +} + +/** The podcast next to `lj` (undefined: there is none), checked against `lj` and, once known, its audio's length. */ +export async function readPodcast(lj: LoadedJourney, audioLength: (audio: vscode.Uri, size: number) => number | undefined): Promise { + const file = lj.uri.with({ path: podcastFileOf(lj.uri.path) }) + const raw = await readText(file) + if (raw === undefined) return undefined + const journey = { id: lj.j.id, steps: lj.j.steps.map((s) => ({ id: s.id, beats: s.scene?.beats?.length ?? 0 })) } + // The audio, when the file names one that can be used: is it there, and how big. + const first = validatePodcast(raw, { journey }) + const name = first.podcast?.audio + let audio: vscode.Uri | undefined + let exists = false, size = 0 + if (name && !audioPathProblem(name)) { + audio = vscode.Uri.joinPath(file, '..', name) + try { size = (await wfs.stat(audio)).size; exists = true } catch { /* not there */ } + } + if (!audio) return { file, raw, audioSize: 0, v: first } + const audioDuration = exists ? audioLength(audio, size) : undefined + return { file, raw, audio, audioSize: size, v: validatePodcast(raw, { journey, audio: { exists, size }, audioDuration }) } +} + +/** The audio files podcasts name (there or not), by path: a change to one reads the podcasts again. */ +const WATCHED_AUDIO = new Set() + +/** Problems-view diagnostics on podcast files, and the output's lines about them. */ +class PodcastReports { + private diags: vscode.DiagnosticCollection | undefined + /** What was last reported per file (its problems): unchanged problems are not logged again. */ + private said = new Map() + + init(context: vscode.ExtensionContext, rescan: () => void): void { + this.diags = vscode.languages.createDiagnosticCollection('codeNotes.podcast') + // The audio files: any change to one that a podcast names (created, rewritten, deleted) reads the podcasts again. + const w = vscode.workspace.createFileSystemWatcher('**/*.{mp3,ogg,oga,opus,wav,m4a,aac,flac,webm}') + let timer: NodeJS.Timeout | undefined + const onAudio = (u: vscode.Uri) => { + if (!WATCHED_AUDIO.has(u.path)) return + clearTimeout(timer) + timer = setTimeout(rescan, 300) + } + w.onDidCreate(onAudio) + w.onDidChange(onAudio) + w.onDidDelete(onAudio) + context.subscriptions.push(this.diags, w, { dispose: () => clearTimeout(timer) }) + } + + /** The podcasts read in one scan: diagnostics set on each, cleared on files gone; new problems logged. */ + report(reads: PodcastRead[]): void { + WATCHED_AUDIO.clear() + const seen = new Set() + for (const r of reads) { + if (r.audio) WATCHED_AUDIO.add(r.audio.path) + const key = r.file.toString() + seen.add(key) + this.diags?.set(r.file, r.v.problems.map((p) => diagnostic(r.raw, p))) + const sig = r.v.problems.map((p) => `${p.level}:${p.message}`).join('\n') + if (this.said.get(key) === sig) continue + this.said.set(key, sig) + for (const p of r.v.problems) log.warn(`podcast ${r.file.fsPath}: ${p.level === 'error' ? 'not played: ' : ''}${p.message}`) + } + for (const key of [...this.said.keys()]) { + if (seen.has(key)) continue + this.said.delete(key) + this.diags?.delete(vscode.Uri.parse(key)) + } + } + + /** The problems of one file (tests). */ + of(file: vscode.Uri): readonly vscode.Diagnostic[] { return this.diags?.get(file) ?? [] } +} + +/** A problem as a diagnostic: on the field or segment at fault. */ +function diagnostic(raw: string, p: PodcastProblem): vscode.Diagnostic { + const span = locate(raw, p.path) + const a = lineCol(raw, span.start) + // A long value (a whole segment): its first line only. + const end = Math.min(span.end, raw.indexOf('\n', span.start) >= 0 ? raw.indexOf('\n', span.start) : span.end) + const b = lineCol(raw, Math.max(end, span.start + 1)) + const d = new vscode.Diagnostic(new vscode.Range(a.line, a.col, b.line, b.col), p.message, p.level === 'error' ? vscode.DiagnosticSeverity.Error : vscode.DiagnosticSeverity.Warning) + d.source = 'Code Notes podcast' + d.code = p.code + return d +} + +export const podcastReports = new PodcastReports() diff --git a/src/podcast/player.ts b/src/podcast/player.ts index 13fa5f8..37b8ab0 100644 --- a/src/podcast/player.ts +++ b/src/podcast/player.ts @@ -8,13 +8,13 @@ import * as vscode from 'vscode' import { gstate, journeys, log, mapPanel, state } from '../app' import { LoadedJourney, posKey } from '../journeys/steps' -import { readText } from '../jsonFolder' import { endJourney, openMap } from '../tour/commands' import { tourState, walk } from '../tour/instances' import { pickJourney } from '../tour/pick' -import { wfs } from '../workspaceFs' import { journeysTree } from '../sidebar/journeysTree' -import { clock, Episode, LatestWins, parsePodcast, podcastFileOf, resolveEpisode, sameView, timeOf, View, viewAt } from './model' +import { clock, Episode, LatestWins, PodcastProblem, sameView, timeOf, View, viewAt } from './model' +import { podcastReports, PodcastRead, readPodcast } from './load' +import { brokenLinks, playNotice } from './validate' /** Workspace state: where each podcast was left (posKey -> seconds); global: the speed. */ const POS_KEY = 'codeNotes.podcastPos' @@ -25,8 +25,14 @@ const SKIP_S = 15 /** After the podcast asks for a seek, the panel's reports of the old time are ignored for at most this long (ms). */ const STALE_MS = 1500 -/** A journey's podcast, read and checked against the journey. */ -interface Loaded { file: vscode.Uri; audio: vscode.Uri; ep: Episode; sig: string } +/** A journey's podcast, read and checked against the journey. `notice`: one line about what is wrong with it (the + * panel and the row's tooltip say it); `lastGood`: the file has errors now, this is the version read before. */ +interface Loaded { file: vscode.Uri; audio: vscode.Uri; audioSize: number; ep: Episode; sig: string; problems: PodcastProblem[]; notice?: string; lastGood?: boolean } +/** A podcast file next to a journey that can't be played, and why (its first error). */ +interface Broken { file: vscode.Uri; reason: string } + +/** What the panel says over a podcast that plays from its last good version. */ +const LAST_GOOD = 'The podcast file has errors: playing the last good version' /** What the panel sends about the audio (MapMessage podcastTime). */ export interface TimeReport { t: number; playing: boolean; rate?: number; seek?: boolean } @@ -34,6 +40,12 @@ export interface TimeReport { t: number; playing: boolean; rate?: number; seek?: class Podcasts { /** By journey key. */ private eps = new Map() + /** By journey key: podcast files that can't be played. */ + private broken = new Map() + /** The audio's real length as the panel loaded it, by its path and size (a rewritten file is measured again). */ + private audioLen = new Map() + /** An audio file the panel failed to play, by path: what to say (it looks cut off or damaged). */ + private audioFault = new Map() private item: vscode.StatusBarItem | undefined /** The journey whose podcast was played in the panel (its audio is there): the walk follows it. */ private session: string | undefined @@ -50,6 +62,8 @@ class Podcasts { /** Errors the panel reported, and how many moves the podcast made (tests read them). */ lastError = '' private moves = 0 + /** "Show why" asked (tests). */ + private whyShown = 0 /** When the podcast last asked the panel to seek: until the panel says it did, its older reports are stale. */ private seekSent = 0 @@ -57,54 +71,84 @@ class Podcasts { this.item = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Left, 49.25) this.item.command = 'codeNotes.podcastToggle' context.subscriptions.push(this.item, journeys.onDidChange(() => void this.scan())) + podcastReports.init(context, () => void this.scan()) mapPanel.podcastFor = (lj, toUri) => this.episodeFor(lj, toUri) walk.onMoved = () => this.walkMoved() } has(lj: LoadedJourney): boolean { return this.eps.has(lj.key) } episode(lj: LoadedJourney): Episode | undefined { return this.eps.get(lj.key)?.ep } + /** What the Journeys view says about a journey's podcast: none, playable (with a line about what is wrong with it, + * if anything), or unavailable and why. */ + status(lj: LoadedJourney): { state: 'ok' | 'broken'; text?: string } | undefined { + const l = this.eps.get(lj.key) + if (l) return { state: 'ok', text: l.notice } + const b = this.broken.get(lj.key) + return b && { state: 'broken', text: b.reason } + } - /** Every journey's podcast read again (a journey or podcast file changed); the panel and the list follow. */ + /** Every journey's podcast read again (a journey, podcast or audio file changed); the panel, the list and the status + * bar follow. A file that has errors now while it played fine before keeps its last good version. */ async scan(): Promise { const next = new Map() + const broken = new Map() + const reads: PodcastRead[] = [] for (const lj of journeys.all()) { - const l = await this.read(lj) - if (l) next.set(lj.key, l) + const r = await readPodcast(lj, (u, size) => this.audioLen.get(`${u.path}:${size}`)) + if (!r) continue + reads.push(r) + if (r.v.playable && r.v.episode && r.audio) { + next.set(lj.key, this.loaded(lj, r)) + continue + } + const reason = r.v.problems.find((p) => p.level === 'error')?.message ?? 'it has errors' + // The file itself broke (half-written, a typo) while it plays and its audio is still there: the last good + // version plays on (paused or not played, the file is what it is now: unavailable). + const last = this.eps.get(lj.key) + const audioGone = r.v.problems.some((p) => p.code === 'audio-missing' || p.code === 'audio-empty' || p.code === 'audio-outside') + const playingIt = this.session === lj.key && (this.playing || !!last?.lastGood) + if (last && playingIt && !audioGone && last.file.toString() === r.file.toString()) next.set(lj.key, { ...last, notice: LAST_GOOD, lastGood: true, sig: last.lastGood ? last.sig : `${last.sig}:last-good` }) + else broken.set(lj.key, { file: r.file, reason }) } - const sig = (m: Map) => [...m].map(([k, l]) => `${k}=${l.sig}`).join('\n') - const changed = sig(next) !== sig(this.eps) + podcastReports.report(reads) + const sig = (m: Map, b: Map) => [...m].map(([k, l]) => `${k}=${l.sig}|${l.notice ?? ''}`).concat([...b].map(([k, x]) => `${k}!${x.reason}`)).join('\n') + const changed = sig(next, broken) !== sig(this.eps, this.broken) this.eps = next + this.broken = broken + // The podcast played went (deleted, or it can't be played now): the panel's audio stops with it, and the status + // item goes. + if (this.session && !next.has(this.session)) { + this.session = undefined + this.playing = false + this.want = undefined + } + this.renderItem() if (!changed) return mapPanel.sendPodcast() journeysTree?.refresh() } - /** The podcast next to `lj`'s file, when there is one and its audio is there. */ - private async read(lj: LoadedJourney): Promise { - const file = lj.uri.with({ path: podcastFileOf(lj.uri.path) }) - const raw = await readText(file) - if (raw === undefined) return undefined - const p = parsePodcast(raw) - if (typeof p === 'string') { - log.warn(`podcast ${file.fsPath}: not played: ${p}`) - return undefined - } - const audio = vscode.Uri.joinPath(file, '..', p.audio) - let size = 0 - try { size = (await wfs.stat(audio)).size } catch { - log.warn(`podcast ${file.fsPath}: its audio ${p.audio} isn't there`) - return undefined + /** A podcast that can be played, as the player keeps it. */ + private loaded(lj: LoadedJourney, r: PodcastRead): Loaded { + const ep = r.v.episode! + const audio = r.audio! + const writtenFor = r.v.podcast?.journey.id + const forTitle = writtenFor && writtenFor !== lj.j.id ? journeys.all().find((x) => x.j.id === writtenFor)?.j.title : undefined + const fault = this.audioFault.get(`${audio.path}:${r.audioSize}`) + const notice = fault ?? playNotice(r.v.problems, forTitle) + return { + file: r.file, audio, audioSize: r.audioSize, ep, problems: r.v.problems, notice, + sig: `${r.raw.length}:${r.audioSize}:${JSON.stringify(ep.segments.map((s) => [s.start, s.step, s.beat]))}`, } - if (p.journey.id && p.journey.id !== lj.j.id) log.info(`podcast ${file.fsPath}: written for journey "${p.journey.id}", played with "${lj.j.id}" (the file next to it)`) - const ep = resolveEpisode(p, { steps: lj.j.steps.map((s) => ({ id: s.id, beats: s.scene?.beats?.length ?? 0 })) }) - for (const w of ep.warnings) log.info(`podcast ${file.fsPath}: ${w}`) - return { file, audio, ep, sig: `${raw.length}:${size}:${JSON.stringify(ep.segments.map((s) => [s.start, s.step, s.beat]))}` } } - /** What the panel's bar gets for `lj` (undefined: no podcast). */ + /** What the panel's bar gets for `lj` (undefined: no podcast; `unavailable`: one that can't be played, and why). */ private episodeFor(lj: LoadedJourney, toUri: (u: vscode.Uri) => string): unknown { const l = this.eps.get(lj.key) - if (!l) return undefined + if (!l) { + const b = this.broken.get(lj.key) + return b && { unavailable: b.reason } + } const { ep } = l return { src: toUri(l.audio), @@ -114,9 +158,29 @@ class Podcasts { rate: gstate.get(RATE_KEY) ?? 1, chapters: ep.chapters, segments: ep.segments.map((s) => ({ start: s.start, end: s.end, text: s.text, step: s.step })), + ...(l.notice ? { notice: l.notice } : {}), } } + /** The panel loaded the audio: its real length. Checked against the file (a cut-off audio, a wrong "duration"). */ + onAudioMeta(lj: LoadedJourney, duration: number): void { + const l = this.eps.get(lj.key) + if (!l || !(duration > 0) || !Number.isFinite(duration)) return + const key = `${l.audio.path}:${l.audioSize}` + if (this.audioLen.get(key) === duration) return + this.audioLen.set(key, duration) + void this.scan() + } + + /** "Show why" in the panel (or on a podcast that can't be played): the Problems view, on the podcast file. */ + async showWhy(lj?: LoadedJourney): Promise { + this.whyShown++ + const j = lj ?? mapPanel.journey + const file = j && (this.eps.get(j.key)?.file ?? this.broken.get(j.key)?.file) + await vscode.commands.executeCommand('workbench.actions.view.problems') + if (file && !podcastReports.of(file).length) log.show(true) + } + private positions(): Record { return state.get>(POS_KEY) ?? {} } private savePos(lj: LoadedJourney, t: number): void { this.lastSave = Date.now() @@ -240,6 +304,28 @@ class Podcasts { mapPanel.takeFocus() return } + // A play() cut short by a pause or another source: what the reader asked for, not a failure. + if (message === 'AbortError') { + log.debug('podcast: a play was interrupted (paused, or another audio loaded)') + return + } + const lj = mapPanel.journey + const l = lj && this.eps.get(lj.key) + if (l && /^audio error/.test(message)) { + // The media pipeline's own words ("PIPELINE_ERROR_READ: FFmpegDemuxer …") mean nothing to an author: the file + // and what it most likely is. + const name = vscode.workspace.asRelativePath(l.audio, false) + const text = `The audio ${name} (${kb(l.audioSize)}) can't be played at ${clock(this.t)}: the file looks cut off or damaged` + log.warn(`podcast ${l.file.fsPath}: ${text} (${message})`) + const key = `${l.audio.path}:${l.audioSize}` + if (this.audioFault.get(key) !== text) { + this.audioFault.set(key, text) + this.eps.set(lj.key, { ...l, notice: text }) + mapPanel.sendPodcast() + journeysTree?.refresh() + } + return + } log.warn(`podcast: ${message}`) } @@ -269,11 +355,14 @@ class Podcasts { private async journeyFor(arg?: unknown): Promise { if (arg !== undefined) { const lj = await pickJourney(arg) - if (lj && !this.has(lj)) vscode.window.setStatusBarMessage(`$(info) ${lj.j.title} has no podcast`, 3000) + if (lj && !this.has(lj)) this.cantPlay(lj) return lj && this.has(lj) ? lj : undefined } const here = [walk.tourJourney(), mapPanel.journey].find((x) => x && this.has(x)) if (here) return here + // The journey here has a podcast that can't be played: why, not another journey's. + const broken = [walk.tourJourney(), mapPanel.journey].find((x) => x && this.broken.has(x.key)) + if (broken) { this.cantPlay(broken); return undefined } const all = journeys.all().filter((x) => this.has(x)) if (all.length <= 1) { if (!all.length) vscode.window.setStatusBarMessage('$(info) No journey here has a podcast', 3000) @@ -283,6 +372,13 @@ class Podcasts { return pick?.lj } + /** Asked to play a journey whose podcast can't be (or that has none): says why, with the way to the details. */ + private cantPlay(lj: LoadedJourney): void { + const b = this.broken.get(lj.key) + if (!b) { vscode.window.setStatusBarMessage(`$(info) ${lj.j.title} has no podcast`, 3000); return } + void vscode.window.showWarningMessage(`The podcast of “${lj.j.title}” can't be played: ${b.reason}`, 'Show Why').then((a) => { if (a) void this.showWhy(lj) }) + } + /** Space for the podcast: pause, or play (the session's journey; else as Play). */ async toggle(): Promise { if (this.sessionJourney() && mapPanel.journey?.key === this.session) { @@ -315,8 +411,9 @@ class Podcasts { const v = viewAt(ep, this.t) const where = v.step ? `${v.step}/${lj.j.steps.length}` : mapPartName(ep, this.t) const onWalkItem = !!v.step && walk.touring() && tourState.key === lj.key - item.text = `${this.playing ? '$(debug-pause)' : '$(play)'} ${onWalkItem ? '' : `${where} · `}${clock(this.t)}` - item.tooltip = `${lj.j.title}: ${this.playing ? 'pause' : 'play'} the podcast (${clock(this.t)} of ${clock(ep.duration)})` + const l = this.eps.get(lj.key)! + item.text = `${this.playing ? '$(debug-pause)' : '$(play)'} ${onWalkItem ? '' : `${where} · `}${clock(this.t)}${l.lastGood ? ' $(warning)' : ''}` + item.tooltip = `${lj.j.title}: ${this.playing ? 'pause' : 'play'} the podcast (${clock(this.t)} of ${clock(ep.duration)})${l.notice ? `\n${l.notice}` : ''}` item.accessibilityInformation = { label: `Podcast ${this.playing ? 'playing' : 'paused'}, ${v.step ? `step ${v.step}` : where}, ${clock(this.t)}. ${this.playing ? 'Pause' : 'Play'}.` } item.show() } @@ -328,10 +425,16 @@ class Podcasts { journeys: journeys.all().filter((x) => this.has(x)).map((x) => x.j.id), session: lj?.j.id, t: this.t, playing: this.playing, want: this.want, beatShown: this.beatShown, applying: this.applying, item: this.item?.text, itemShown: !!lj, error: this.lastError, moves: this.moves, mapVisible: mapPanel.visible, + why: this.whyShown, + broken: Object.fromEntries([...this.broken].map(([k, b]) => [journeys.list.get(k)?.j.id ?? k, b.reason])), + notices: Object.fromEntries([...this.eps].filter(([, l]) => l.notice).map(([k, l]) => [journeys.list.get(k)?.j.id ?? k, l.notice])), + links: Object.fromEntries([...this.eps].map(([k, l]) => [journeys.list.get(k)?.j.id ?? k, brokenLinks(l.problems)])), } } } +const kb = (n: number) => (n >= 1024 * 1024 ? `${(n / 1024 / 1024).toFixed(1)} MB` : `${Math.round(n / 1024)} KB`) + /** A part on the map (no step) by where it is: the first is the intro, the last the recap. */ function mapPartName(ep: Episode, t: number): string { const i = ep.chapters.findIndex((c, k) => t < c.end || k === ep.chapters.length - 1) diff --git a/src/sidebar/journeyRows.ts b/src/sidebar/journeyRows.ts index a38873c..817df46 100644 --- a/src/sidebar/journeyRows.ts +++ b/src/sidebar/journeyRows.ts @@ -114,7 +114,9 @@ export function journeyItem(lj: LoadedJourney, group?: string): vscode.TreeItem item.tooltip = journeyTooltip(lj, s) // The name read is the title and its state; the question is only the tooltip. item.accessibilityInformation = { label: journeyLabel(lj, s) } - item.contextValue = (staleCount(lj) ? 'journey;stale' : 'journey') + (podcasts.has(lj) ? ';podcast' : '') + // A podcast that plays: ▶ on the row; one that can't: a greyed ▶ (the tooltip says why). + const pod = podcasts.status(lj) + item.contextValue = (staleCount(lj) ? 'journey;stale' : 'journey') + (pod ? (pod.state === 'ok' ? ';podcast' : ';podcastBroken') : '') item.command = { command: 'codeNotes.openJourney', title: 'Walk Journey', arguments: [lj.key] } return item } @@ -151,7 +153,15 @@ function journeyIcon(s: JourneyState): vscode.ThemeIcon | undefined { * unread answer is said in full here). */ function journeyTooltip(lj: LoadedJourney, s: JourneyState): string { const unreadReplies = s.newReplies ? `${plural(s.newReplies, 'unread reply', 'unread replies')} from Claude` : '' - return [lj.j.question, lj.j.summary, provenance(lj).text, staleLine(lj), unreadReplies].filter(Boolean).join('\n') + return [lj.j.question, lj.j.summary, provenance(lj).text, staleLine(lj), unreadReplies, podcastLine(lj)].filter(Boolean).join('\n') +} + +/** The podcast's line in the tooltip: one that can't be played and why, or what is wrong with one that plays. */ +function podcastLine(lj: LoadedJourney): string { + const pod = podcasts.status(lj) + if (!pod) return '' + if (pod.state === 'broken') return `Podcast unavailable: ${pod.text}` + return pod.text ? `Podcast: ${pod.text}` : '' } /** What a screen reader says: the title, then where the walk is, unread replies, new. */ diff --git a/src/testApi.ts b/src/testApi.ts index 2d44953..36805fb 100644 --- a/src/testApi.ts +++ b/src/testApi.ts @@ -9,6 +9,7 @@ import { Note } from './store' import { applySuggestion } from './notes/suggestion' import { unread } from './seen' import { journeysTree } from './sidebar/journeysTree' +import { journeyItem } from './sidebar/journeyRows' import { listModel } from './sidebar/listModel' import { cached, Node, order, sessionOf } from './sidebar/nodes' import { groupMode, matchesFilter } from './sidebar/notesFilter' @@ -151,6 +152,12 @@ export function testApi() { mapSend: (m: unknown) => mapPanel.send(m), /** The podcast (src/podcast/player.ts): which journeys have one, where the audio is, what it last moved. */ podcast: () => podcasts.snapshot(), + /** A journey's row in the Journeys view (by journey id): its context value (which inline buttons) and tooltip. */ + journeyRow: (id: string) => { + const lj = journeys.all().find((x) => x.j.id === id) + const it = lj && journeyItem(lj) + return it && { contextValue: it.contextValue, tooltip: typeof it.tooltip === 'string' ? it.tooltip : it.tooltip?.value } + }, resetTutorial, /** Forgets the tour in memory and restores it from workspace state, as after a window reload. */ reloadTour: async () => { diff --git a/src/tour/mapMessages.ts b/src/tour/mapMessages.ts index 1255c12..dfff4ae 100644 --- a/src/tour/mapMessages.ts +++ b/src/tour/mapMessages.ts @@ -46,6 +46,8 @@ const MAP_MESSAGES: { [K in MapMessage['type']]?: Handler } = { closed: () => { beats.clear(); podcasts.onClosed() }, podcastTime: (lj, m) => podcasts.onTime(lj, m), podcastError: (_lj, m) => podcasts.onError(String(m.message)), + podcastMeta: (lj, m) => podcasts.onAudioMeta(lj, Number(m.duration)), + podcastWhy: (lj) => void podcasts.showWhy(lj), panelWidth: () => void rememberPanelWidth(), mapWidth: (_lj, m) => void gstate.update(MAP_WIDTH_KEY, m.w > 0 ? Math.round(m.w) : undefined), list: (_lj, m) => homeQueryChanged(m), From d00fcc9c11efd4f59c677e010fef475b76e20dfd Mon Sep 17 00:00:00 2001 From: tomeyer97 <107920881+tomeyer97@users.noreply.github.com> Date: Wed, 18 Nov 2026 14:35:05 +0100 Subject: [PATCH 09/45] Podcast integration tests: broken files, the audio coming back, warnings in the player ONLY_PODCAST=1 runs the podcast's tests alone. Co-Authored-By: Claude Opus 5.5 --- test/integration/helpers.ts | 1 + test/integration/main/podcast.ts | 152 +++++++++++++++++++++++++++++++ test/integration/suite.ts | 2 + 3 files changed, 155 insertions(+) diff --git a/test/integration/helpers.ts b/test/integration/helpers.ts index 543f5d1..73629ef 100644 --- a/test/integration/helpers.ts +++ b/test/integration/helpers.ts @@ -9,6 +9,7 @@ // CODE_NOTES_PROFILE= keep VS Code's profiles (user data) there instead of in temp folders (run.ts) // CODE_NOTES_CONSOLE_ALL=1 print every workbench console message, not only the errors (run.ts, check run) // ONLY_MAIN / ONLY_UNTRUSTED / ONLY_CHECK=1 run that suite alone (run.ts; with none set, all three) +// ONLY_PODCAST=1 in the main suite, only the podcast's tests (suite.ts) // Set by run.ts or the tests themselves, not by hand: // CODE_NOTES_CDP the workbench's DevTools port (main and check runs: devtools.ts) // CODE_NOTES_CONSOLE the file the workbench console errors are collected in (check run) diff --git a/test/integration/main/podcast.ts b/test/integration/main/podcast.ts index edd4592..b8685f6 100644 --- a/test/integration/main/podcast.ts +++ b/test/integration/main/podcast.ts @@ -197,4 +197,156 @@ export const podcastTests = [ await vscode.commands.executeCommand('workbench.action.closeActiveEditor') await until('the panel closed: no podcast, no status item', () => !pod().mapVisible && !pod().itemShown && !pod().playing, 5000) }), + + // ---------- broken podcast files (src/podcast/validate.ts, load.ts) ---------- + + test('podcast: a half-written podcast file mid-play keeps the last good version playing, and says so', async () => { + watchConsole() + await playPod() + const good = fs.readFileSync(podFile(), 'utf8') + // An agent or editor caught mid-write: the file cut off. + // Settled first: a new panel's first play, started by a click, can pause once right after it. + await sleep(1500) + assert.ok(pod().playing, 'playing') + fs.writeFileSync(podFile(), good.slice(0, 120)) + await until('the panel says the file has errors', () => /last good version/.test(pod().notices.pod ?? ''), 8000) + const t0 = pod().t + await sleep(1200) + assert.ok(pod().playing && pod().t > t0 + 0.6, `still playing: ${t0} → ${pod().t}`) + assert.match(pod().item, /\$\(warning\)/, `the status item says it: ${pod().item}`) + assert.match(await panelText('.pod-note'), /last good version/) + const errs = diagnostics() + assert.equal(errs[0]?.severity, vscode.DiagnosticSeverity.Error, 'an error in the Problems view') + assert.match(errs[0].message, /not valid JSON: line \d+, column \d+/) + // Written in full again: read again, nothing to say. + fs.writeFileSync(podFile(), good) + await until('the file is good again (the fixture\'s one warning: beat 4 of a step without an animation)', () => pod().notices.pod === "1 part can't be shown" && diagnostics().length === 1, 8000) + assert.ok(pod().playing, 'it played on throughout') + await vscode.commands.executeCommand('codeNotes.podcastToggle') + await until('paused', () => !pod().playing) + }), + + test('podcast: a podcast file that can\'t be played leaves a trace: a greyed ▶ with the reason, "Podcast unavailable" in the panel', async () => { + const good = fs.readFileSync(podFile(), 'utf8') + await playPod() + // Paused (playing, a broken file keeps the last good version: the test before). + await vscode.commands.executeCommand('codeNotes.podcastToggle') + await until('paused', () => !pod().playing) + fs.writeFileSync(podFile(), good.replace('"version":1', '"version":2')) + await until('unavailable: version 2', () => /version 2/.test(pod().broken.pod ?? ''), 8000) + await until('the status item went with it', () => !pod().itemShown, 5000) + const row = ctx.api.journeyRow('pod')! + assert.match(row.contextValue!, /;podcastBroken/, 'the greyed ▶') + assert.doesNotMatch(row.contextValue!, /;podcast(;|$)/, 'not the ▶ that plays') + assert.match(row.tooltip!, /Podcast unavailable: version 2: this player reads version 1/) + await until('the panel: one line, "Podcast unavailable", and Show why', async () => /Podcast unavailable/.test(await panelText('.pod-note')) && !(await panelVisible('.pod-tl')), 5000) + // The row's ▶ is there, greyed (disabled): hovered, in the Journeys view. + await vscode.commands.executeCommand('codeNotes.journeys.focus') + const page = await ui() + const rowSel = '.monaco-list-row[aria-label^="Pod,"], .monaco-list-row[aria-label^="Pod "], .monaco-list-row[aria-label="Pod"]' + await until('the row in the Journeys view', async () => (await page.locator(rowSel).count()) > 0, 5000) + await page.locator(rowSel).first().hover() + const play = await until('its greyed ▶', async () => page.locator(rowSel).first().evaluate((r) => { + const a = r.querySelector('.actions .codicon-play')?.closest('.action-label') + return a ? { disabled: a.classList.contains('disabled') || a.getAttribute('aria-disabled') === 'true', title: a.getAttribute('aria-label') ?? '' } : undefined + }), 5000) + assert.ok(play.disabled, `the ▶ is disabled: ${JSON.stringify(play)}`) + await windowShot('podcast-unavailable', { wait: 300 }) + const before = pod().why + await (await panelFrame()).click('.pod-why') + await until('Show why: the Problems view', () => pod().why === before + 1, 5000) + assert.equal(diagnostics()[0]?.range.start.character, good.indexOf('"version"'), 'the error on the version') + // Play and Space say why, never nothing. + await vscode.commands.executeCommand('codeNotes.playPodcast', 'pod') + await vscode.commands.executeCommand('codeNotes.podcastToggle') + assert.ok(!pod().playing) + // Invalid JSON, 0 segments: each its own reason. + fs.writeFileSync(podFile(), good.slice(0, 50)) + await until('unavailable: not JSON', () => /not valid JSON/.test(pod().broken.pod ?? ''), 8000) + fs.writeFileSync(podFile(), JSON.stringify({ ...JSON.parse(good), segments: [] })) + await until('unavailable: segments empty', () => /"segments" is empty/.test(pod().broken.pod ?? ''), 8000) + fs.writeFileSync(podFile(), good) + await until('playable again: the ▶, the player', async () => pod().journeys.includes('pod') && !pod().broken.pod && await panelVisible('.pod-tl'), 8000) + assert.match(ctx.api.journeyRow('pod')!.contextValue!, /;podcast$/) + }), + + test('podcast: the audio removed, then put back: the podcast goes and comes back without touching its file', async () => { + const mp3 = path.join(journeysDir(), 'pod.mp3') + fs.renameSync(mp3, `${mp3}.away`) + await until('unavailable: the audio isn\'t there', () => /pod\.mp3 isn't there/.test(pod().broken.pod ?? ''), 8000) + assert.equal(diagnostics()[0]?.range.start.character, fs.readFileSync(podFile(), 'utf8').indexOf('"audio"'), 'the error on "audio"') + fs.renameSync(`${mp3}.away`, mp3) + await until('back: the podcast plays again', () => pod().journeys.includes('pod') && !pod().broken.pod, 8000) + }), + + test('podcast: what is wrong with one that plays is said in the player, the row and the Problems view', async () => { + const good = fs.readFileSync(podFile(), 'utf8') + const p = JSON.parse(good) + p.journey.id = 'podlong' + p.segments[2].at = { step: 'nope' } + p.segments.push({ id: 'late', at: null, text: 'late', start: 300, end: 600 }) + p.duration = 600 + fs.writeFileSync(podFile(), JSON.stringify(p, null, 2)) + // The panel loads the 40 s audio and reports its length: the file says 10 minutes. + await until('the player says it in plain words', () => /The audio is 0:40 long but the episode is 10:00/.test(pod().notices.pod ?? ''), 10000) + assert.equal(pod().links.pod, 2, 'two parts can\'t be shown (the fixture\'s beat 4 of a step without one, and "nope")') + await vscode.commands.executeCommand('codeNotes.playPodcast', 'pod') + await until('the note in the panel', async () => /The audio is 0:40 long/.test(await panelText('.pod-note')), 5000) + p.segments.pop() + p.duration = 40 + fs.writeFileSync(podFile(), JSON.stringify(p, null, 2)) + await until('the other journey and the broken link', () => pod().notices.pod === 'Written for “Pod long” · 2 parts can\'t be shown', 8000) + assert.match(ctx.api.journeyRow('pod')!.tooltip!, /Podcast: Written for “Pod long” · 2 parts can't be shown/) + const ws = diagnostics() + assert.ok(ws.every((d) => d.severity === vscode.DiagnosticSeverity.Warning), 'warnings only') + const link = ws.find((d) => d.code === 'step')! + assert.equal(link.range.start.line, lineOf(podFile(), '"step": "nope"'), 'the squiggle on the segment\'s step') + await vscode.commands.executeCommand('codeNotes.podcastToggle') + await until('paused', () => !pod().playing, 5000) + fs.writeFileSync(podFile(), good) + await until('back to the fixture\'s one warning', () => pod().notices.pod === "1 part can't be shown" && diagnostics().length === 1, 8000) + const errors = consoleErrors() + assert.deepEqual(errors, [], `console errors from the extension's panel:\n${errors.join('\n')}`) + }), ] + +const podFile = () => path.join(journeysDir(), 'pod.podcast.json') +const diagnostics = () => vscode.languages.getDiagnostics(vscode.Uri.file(podFile())) +/** The 0-based line of the first line of `file` with `text`. */ +const lineOf = (file: string, text: string) => fs.readFileSync(file, 'utf8').split('\n').findIndex((l) => l.includes(text)) +async function panelText(sel: string): Promise { + const f = await panelFrame() + return f.evaluate((s) => { const e = (globalThis as any).document.querySelector(s); return e && !e.hidden ? e.textContent : '' }, sel) +} +async function panelVisible(sel: string): Promise { + const f = await panelFrame() + return f.evaluate((s) => { const e = (globalThis as any).document.querySelector(s); return !!e && e.getClientRects().length > 0 }, sel) +} + +/** "pod" in the panel, playing (a new panel needs one click in it first). */ +async function playPod(): Promise { + await vscode.commands.executeCommand('codeNotes.playPodcast', 'pod') + await until('the panel shows it', () => tour().map === 'pod' && pod().mapVisible, 10000) + await until('playing, or asking for a click', () => pod().playing || pod().error === 'NotAllowedError', 10000) + // As the first test: once ▶ has the keyboard, a click on it (the click the webview needs before it plays). + for (let i = 0; i < 3 && !pod().playing; i++) { + const f = await panelFrame() + await until('▶ has the keyboard', async () => (await f.evaluate(() => (globalThis as any).document.activeElement?.className)) === 'pod-b play', 5000).catch(() => undefined) + await f.click('.pod-b.play') + await until('playing after the click', () => pod().playing, 3000).catch(() => undefined) + } + await until('playing', () => pod().playing && pod().session === 'pod', 10000) +} + +/** The workbench's console errors and uncaught errors from here on (the panel's frames included). */ +let seen: string[] | undefined +function watchConsole(): void { + if (seen) return + seen = [] + void ui().then((page) => { + page.on('console', (m) => { if (m.type() === 'error') seen!.push(`${m.location().url}: ${m.text()}`) }) + page.on('pageerror', (e) => seen!.push(`uncaught: ${e.message}`)) + }) +} +/** The errors seen that come from the extension (its panel, its media files). */ +const consoleErrors = () => (seen ?? []).filter((e) => /vscode-webview|code-notes|journey-|podcast/i.test(e)) diff --git a/test/integration/suite.ts b/test/integration/suite.ts index 1039bb4..1198eea 100644 --- a/test/integration/suite.ts +++ b/test/integration/suite.ts @@ -42,6 +42,8 @@ export async function run(): Promise { ctx.ws = ctx.folder.uri.fsPath ctx.notesDir = path.join(ctx.ws, '.code-notes') ctx.api = await activate() + // ONLY_PODCAST=1: the podcast's tests alone (they set up their own journeys). + if (process.env.ONLY_PODCAST) { await runTests(podcastTests); console.log('all passed'); return } await runTests([ ...notesTests, ...journeyTourTests, From 37c835f3c777974a980474148211cf68eeed09c0 Mon Sep 17 00:00:00 2001 From: tomeyer97 <107920881+tomeyer97@users.noreply.github.com> Date: Wed, 18 Nov 2026 14:35:37 +0100 Subject: [PATCH 10/45] Podcast docs: seeking anywhere, the kept place, skipped steps, rewritten files, keys Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 9 +++++++++ docs/podcast-format.md | 29 ++++++++++++++++++++++++----- 2 files changed, 33 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 89be9e2..23cd2a2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,15 @@ backwards too. Next, Previous, a step or a beat you pick moves the audio to its part. The audio goes on while the panel is behind another tab or VS Code is in the background. Ctrl+' Space plays and pauses from anywhere, Ctrl+' ← → skip; the status bar shows where it is. + - Seeking works in VS Code for the web and remote windows too: the panel loads the audio whole, and the walk, the + player and the status bar always show where the audio actually is (a seek that can't get there is said and + logged). One clock: the status bar shows the player's second. + - Where you were is kept per journey: another journey, ending the walk, closing the panel, a reload, or saving the + podcast file again (the same moment of the same segment) keep it, and ▶ goes on from there. + - A step the podcast skips: the walk stays on it, the audio pauses and says so, and ▶ goes on after that step. + - A beat whose code is in another file opens that file directly; a part on the map closes the walk's code tab. + - Space and K play and pause anywhere in the panel, also after clicking the animation's ‹ ›. An audio that can't + play stays paused and says why. - **Understanding check: a tour of the change.** Right after the questions, Claude writes a short journey of the change (6-10 steps through the changed code and the code it depends on), each question placed after the step that shows its answer. Check my understanding (or **Walk the tour** in the Check view) walks it in the journey panel: the diff --git a/docs/podcast-format.md b/docs/podcast-format.md index 7c7ed0f..5fca31a 100644 --- a/docs/podcast-format.md +++ b/docs/podcast-format.md @@ -17,7 +17,10 @@ journeys/ ``` `audio` is a path relative to the podcast file. It must be inside the journeys folder (or a folder under it): the -panel can only load files from there. mp3 plays in VS Code (tested); so do ogg/opus and wav. +panel can only load files from there. mp3 plays in VS Code (tested); so do ogg/opus and wav. The panel loads the file +whole before it plays (it is held in memory while the panel is open), so seeking works wherever VS Code runs: in the +browser and in remote windows the panel's files are served without HTTP Range requests, and a streamed file can't be +sought in. A journey with a podcast has a ▶ on its row in the Journeys view, and its panel has the player at the bottom. @@ -66,8 +69,21 @@ position. says the step and beat. Seeking anywhere, backwards too, applies that directly, never the parts in between; of quick seeks (a drag, a key held down), only the last one moves the walk. - **Moving the walk yourself moves the audio**: Next, Previous, a step in the storyline or a beat of the animation - (‹ ›) jump the audio to the first segment about it. A step the podcast never talks about pauses it, and so does - ending the walk or opening another journey. Pausing never ends the walk. + (‹ ›) jump the audio to the first segment about it. Ending the walk or opening another journey pauses it. Pausing + never ends the walk. +- **A step the podcast never talks about**: the walk stays on it, the audio pauses, and the player says the step isn't + in the podcast. ▶ then goes on with the first segment after that step (the next step it talks about), not back to + where the audio was. +- **On a beat whose code is in another file**, that file opens directly (never the step's own file first). A segment + on the map (`at: null`) ends the walk and closes the code tab the walk opened. +- **Where it was is kept, per journey**: opening another journey, ending the walk, closing the panel or reloading the + window keeps the time, and ▶ goes on from there. When the walk is on another step than that time is about, ▶ starts + at that step's first segment. +- **The podcast file saved again** while it plays keeps its place: the same time, or, when the segment playing then has + new times, the same moment of that segment (by `id`); it keeps playing if it was. +- **The time shown is the audio's own**: after a seek, the walk, the player and the status bar show where the audio + actually is. If it could not get there, the player says so and the Code Notes output channel logs it, as it logs + audio errors. - **A link the journey can't show degrades**: a beat the step doesn't have (the journey was edited) shows the step without its animation; a step id that isn't in the journey keeps the view of the segment before it. Each is logged in the Code Notes output channel. @@ -75,12 +91,15 @@ position. ## Playing - **▶** on the journey's row, the command **Play Journey Podcast**, or the player's ▶ in the panel. -- In the panel: Space or K play and pause, ← → go back and forward 15 s, Shift+← → the previous and next step; on - the timeline, Home and End, Page Up and Page Down. Hovering over the timeline names the step at that point; click or +- In the panel: Space or K play and pause (anywhere in the panel but a text field, also after clicking a button + such as the animation's ‹ ›; a button you reached with Tab still presses with Space), ← → go back and forward 15 s, + Shift+← → the previous and next step; on the timeline, Home and End, Page Up and Page Down. Hovering over the timeline names the step at that point; click or drag to go there. - From anywhere: **Ctrl+' Space** plays and pauses, **Ctrl+' ←** / **→** go back and forward 15 s. The status bar shows where it is; click it to pause or play. - The audio plays in the journey panel and goes on while the panel is behind another tab or VS Code isn't focused. Closing the panel stops it; where it was is kept for next time, per journey. +- If the audio can't play (a broken or cut file), ▶ stays paused and the player says why; it never shows "playing" + with the clock standing still. - VS Code lets a panel play sound only after a click or a key in it: the first time a panel plays, its ▶ takes the keyboard and says "Press Space to play". After that, the keys and commands play it directly. From c5a95b225e4d853d0aac4e2f3a0ed8d0d977711c Mon Sep 17 00:00:00 2001 From: tomeyer97 <107920881+tomeyer97@users.noreply.github.com> Date: Wed, 18 Nov 2026 14:37:26 +0100 Subject: [PATCH 11/45] journey.py podcast: the podcast check for authors (and in check) The extension's podcast validator, rule for rule, in the code-journey skill's script: PROBLEM when the extension won't play the file, WARNING when a part is not what the file says. The audio's length comes from the argument, a WAV header or ffprobe. check runs it when the podcast exists. The shared cases run through both implementations. Co-Authored-By: Claude Opus 5.5 --- skills/code-journey/scripts/journey.py | 261 ++++++++++++++++++++++++- test/cli/podcast.test.mjs | 85 ++++++++ 2 files changed, 345 insertions(+), 1 deletion(-) create mode 100644 test/cli/podcast.test.mjs diff --git a/skills/code-journey/scripts/journey.py b/skills/code-journey/scripts/journey.py index a660fe0..6eebb3a 100755 --- a/skills/code-journey/scripts/journey.py +++ b/skills/code-journey/scripts/journey.py @@ -80,6 +80,13 @@ journey.py reset deletes the journey file (nothing else) journey.py restore puts back the last good copy (journeys/.bak/.json, kept on every write and every load of a valid file) + journey.py podcast [