Resume episodes from the progress register and keep saving after a takeover

A reload or a Play after a pause continues from the register instead of
this page's saved position, a seek during preparation is kept, a player
that keeps listening after being superseded writes again as a new
session, a player that loses the playback role records its listening,
marking the loaded episode closes its session, and Prev no longer
resets an episode to 0.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
sanapachandClaude Opus 5.5 committed 2026-11-20 15:12:38 +02:00
1 parent 4050214912
commit 9b43a25d8f
4 files changed
+644 -55

No files matched your search

+298 -38
View File
@@ -790,6 +790,7 @@ document.addEventListener('alpine:init', () => {
_episodeToken: 0,
_episodeSeekTimer: null,
_episodeCheckpointMs: 20000,
_episodeRewindSeconds: 15,
_remoteExecuting: false,
_remoteStateBaseTime: 0,
_remoteStateReceivedAt: 0,
@@ -1187,7 +1188,11 @@ document.addEventListener('alpine:init', () => {
// is nothing to restart: Prev goes to the previous item.
const restartable = !this._isUnplayableQueueItem(this.currentTrack);
if (restartable && this.currentTime > 3) {
this.seek(0);
// An episode goes back a little: Prev (also a headset or
// lock-screen button) must not reset its saved position;
// "Start over" does that.
if (this._isPodcastEpisode(this.currentTrack)) this._rewindEpisode(this._episodeRewindSeconds);
else this.seek(0);
return;
}
const queue = Alpine.store('queue');
@@ -1763,7 +1768,17 @@ document.addEventListener('alpine:init', () => {
sessionId: null, pendingSessionId: start ? this._newEpisodeSessionId() : null,
generation: null, startedAtMs: null, startPositionSeconds: position,
lastPosition: known ? position : null,
// A position that is not the register's: a handoff or the
// user's own seek. Only such a position is sent with a
// start; otherwise the server resumes from the register.
explicitPosition: known,
// A seek made while the source is still being prepared.
pendingSeek: null,
superseded: false, completed: false, closed: false,
// Superseded while this player kept playing: its next write
// starts a new session (see _takeOverEpisode).
takeOverPending: false, takingOver: false, handedOff: false,
reportedListenedMs: 0,
lastWriteAt: 0, writes: Promise.resolve(),
};
const body = {
@@ -1787,7 +1802,11 @@ document.addEventListener('alpine:init', () => {
episode.startedAtMs = Date.now();
episode.lastWriteAt = Date.now();
}
const at = Math.max(0, Number(info.position_ms || 0) / 1000);
const served = Math.max(0, Number(info.position_ms || 0) / 1000);
// The user moved the position while this was prepared.
const pending = episode.pendingSeek;
episode.pendingSeek = null;
const at = pending != null ? pending : served;
episode.startPositionSeconds = at;
episode.lastPosition = at;
if (Number(info.duration_ms) > 0 && !(this.duration > 0)) this.duration = Number(info.duration_ms) / 1000;
@@ -1795,8 +1814,15 @@ document.addEventListener('alpine:init', () => {
this.currentTime = at;
this._remoteStateBaseTime = at;
this.progress = this.duration > 0 ? (at / this.duration) * 100 : 0;
// Play was pressed while a paused episode was being prepared.
if (!info.session_id && episode.wantPlay) this._startEpisodeSession(at);
if (!info.session_id && episode.wantPlay) {
// Play was pressed while a paused episode was being prepared.
this._startEpisodeSession(episode.explicitPosition ? at : null);
} else if (info.session_id && pending != null && Math.abs(pending - served) >= 1) {
// The session started where the server said; the
// user's seek is the explicit action that follows.
clearTimeout(this._episodeSeekTimer);
this._reportEpisode('seek', { position: pending });
}
this._loadEpisodeAudio(at, episode.wantPlay);
})
.catch(error => {
@@ -1826,6 +1852,9 @@ document.addEventListener('alpine:init', () => {
const token = episode.token;
const url = this._episodeAudioUrl(episode);
episode.url = url;
// Where the audio starts once loaded (_moveEpisodeAudio may
// change it before that).
episode.loadPosition = position;
episode.ready = false;
episode.seekBlocked = false;
episode.wantPlay = !!play;
@@ -1847,6 +1876,7 @@ document.addEventListener('alpine:init', () => {
audio.removeEventListener('loadedmetadata', onLoaded);
const now = current();
if (!now) return;
const position = Number(now.loadPosition ?? 0);
if (Number.isFinite(audio.duration) && audio.duration > 0) this.duration = audio.duration;
now.ready = true;
this.episodeLoading = false;
@@ -1905,42 +1935,128 @@ document.addEventListener('alpine:init', () => {
// A new listening session (explicit action) while the episode stays
// loaded: Play after a paused load, after another device took over
// or after the end, and the choice to listen from the start when
// the source cannot seek.
// the source cannot seek. `positionSeconds` null: where the
// register says (an ordinary Play). Resolves with the server's
// answer (null when it failed or is stale).
const episode = this._episode;
if (!episode) return Promise.resolve();
if (!episode) return Promise.resolve(null);
const token = episode.token;
const sessionId = this._newEpisodeSessionId();
const known = positionSeconds != null;
const at = Math.max(0, Number(positionSeconds || 0));
episode.sessionId = null;
episode.generation = null;
episode.pendingSessionId = sessionId;
episode.startPositionSeconds = at;
episode.takeOverPending = false;
episode.reportedListenedMs = 0;
this._resetPlaybackTracking();
return this._episodeRequest(episode.episodeId, 'playback', {
const body = {
episode: episode.ref,
start: true,
session_id: sessionId,
position_ms: Math.round(at * 1000),
carried_generation: episode.carried,
}).then(info => {
};
if (known) body.position_ms = Math.round(at * 1000);
return this._episodeRequest(episode.episodeId, 'playback', body).then(info => {
const current = this._episode;
if (!current || current.token !== token || current.pendingSessionId !== sessionId) return;
if (!current || current.token !== token || current.pendingSessionId !== sessionId) return null;
current.sessionId = info.session_id;
current.pendingSessionId = null;
current.generation = info.generation;
current.startedAtMs = Date.now();
current.lastWriteAt = Date.now();
current.startPositionSeconds = Math.max(0, Number(info.position_ms || 0) / 1000);
current.superseded = false;
current.completed = false;
}).catch(() => {});
return info;
}).catch(() => null);
},
_resumeFromRegister(episode) {
// Ordinary Play of an episode whose register this player no
// longer holds: a new session where the register says, the
// audio moved there, then played.
const token = episode.token;
return this._startEpisodeSession(null).then(info => {
const current = this._episode;
if (!info || !current || current.token !== token) return;
this._moveEpisodeAudio(Number(info.position_ms || 0) / 1000);
if (current.ready && current.wantPlay && !current.seekBlocked) audio.play().catch(() => {});
});
},
_continuePausedEpisode(episode) {
// Play after a pause: the session continues only while the
// register is still its own; if another device or an action
// wrote the episode meanwhile, Play resumes from the register.
const token = episode.token;
const sessionId = episode.sessionId;
return this._episodeRequest(episode.episodeId, 'playback', { episode: episode.ref, start: false })
.then(info => {
const current = this._episode;
if (!current || current.token !== token || !current.wantPlay) return;
if (current.sessionId === sessionId && info.register_session_id === sessionId) {
if (current.ready) audio.play().catch(() => {});
return;
}
if (current.sessionId !== sessionId) return;
current.superseded = true;
return this._resumeFromRegister(current);
})
.catch(() => {
const current = this._episode;
if (current && current.token === token && current.wantPlay && current.ready) audio.play().catch(() => {});
});
},
_moveEpisodeAudio(seconds) {
// Moves the loaded episode without an explicit write (the
// session's next report carries the position).
const episode = this._episode;
const at = Math.max(0, Number(seconds || 0));
if (episode) episode.lastPosition = at;
this.currentTime = at;
this._remoteStateBaseTime = at;
this._remoteStateReceivedAt = Date.now();
this.progress = this.duration > 0 ? (at / this.duration) * 100 : 0;
this._positionUnknown = false;
if (episode && !episode.ready) episode.loadPosition = at;
if (!episode?.ready || episode.seekBlocked) return;
if (Math.abs((audio.currentTime || 0) - at) < 1) return;
if (at > 1 && !this._episodeCanSeek(at)) {
episode.seekBlocked = true;
this.episodeNotice = T.podcastCannotSeek;
audio.pause();
this.isPlaying = false;
return;
}
audio.currentTime = at;
this._lastAudioTime = audio.currentTime || at;
},
_rewindEpisode(seconds) {
// Prev on an episode: back a little, never to 0. Inside a
// session this is not an explicit action; the next checkpoint
// saves it. Without one, the next Play starts there.
const episode = this._episode;
const now = this._episodePosition() ?? this.currentTime ?? 0;
const at = Math.max(0, Number(now || 0) - seconds);
if (episode?.sessionId && !episode.superseded) {
this._moveEpisodeAudio(at);
return;
}
this._seekEpisode(at);
},
_resumeEpisode() {
const episode = this._episode;
if (!episode || episode.failed) {
// Not prepared, or the source failed: prepare it again.
// Not prepared, or the source failed: prepare it again (from
// the register unless a handoff or a seek set the position).
this.episodeNotice = '';
this._playEpisodeLocal(this.currentTrack, { position_seconds: this._knownPosition(), paused: false });
const position = episode?.explicitPosition ? this._knownPosition() : null;
this._playEpisodeLocal(this.currentTrack, { position_seconds: position, paused: false });
return;
}
episode.wantPlay = true;
@@ -1952,16 +2068,34 @@ document.addEventListener('alpine:init', () => {
this.episodeNotice = '';
this.currentTime = audio.currentTime || 0;
this._startEpisodeSession(this.currentTime);
} else if ((!episode.sessionId && !episode.pendingSessionId) || episode.superseded || episode.completed) {
// Play at the end of the stream starts the audio over.
} else if (episode.completed) {
// Listening again: from the start after the end of the stream.
this._startEpisodeSession(audio.ended ? 0 : this._episodePosition());
} else if (episode.pendingSessionId) {
// A session is being started already.
} else if (!episode.sessionId && episode.explicitPosition) {
// A handoff or the user's seek chose the position.
this._startEpisodeSession(this._episodePosition());
} else if (!episode.sessionId || episode.superseded) {
// Ordinary Play: from the register, wherever it was written.
this._resumeFromRegister(episode);
return;
} else if (!this.isPlaying && !episode.seekPending) {
// (A pending seek is an explicit write of its own.)
this._continuePausedEpisode(episode);
return;
}
if (episode.ready) audio.play().catch(() => {});
},
_seekEpisode(time) {
const episode = this._episode;
if (episode) episode.lastPosition = time;
if (episode) {
episode.lastPosition = time;
episode.explicitPosition = true;
// Applied when the source arrives (see _playEpisodeLocal).
if (!episode.source) episode.pendingSeek = time;
}
this.currentTime = time;
this._remoteStateBaseTime = time;
this._remoteStateReceivedAt = Date.now();
@@ -1975,9 +2109,11 @@ document.addEventListener('alpine:init', () => {
if (episode.seekBlocked) return;
// An explicit action, written once the user stops dragging.
clearTimeout(this._episodeSeekTimer);
episode.seekPending = true;
this._episodeSeekTimer = setTimeout(() => {
const current = this._episode;
if (!current || current.token !== episode.token) return;
current.seekPending = false;
if (current.completed && current.wantPlay) {
// Listening again after the end is a new session.
this._startEpisodeSession(time);
@@ -2013,20 +2149,13 @@ document.addEventListener('alpine:init', () => {
this._reportEpisode('pause');
},
_reportEpisode(event, options = {}) {
const episode = this._episode;
if (!episode?.sessionId || episode.generation == null || episode.closed) return Promise.resolve();
// Another device or an explicit action elsewhere took over: only
// a new explicit action of this player writes again.
if (episode.superseded && event !== 'seek') return Promise.resolve();
// The audio is not where the register says (source cannot seek).
if (episode.seekBlocked) return Promise.resolve();
// After a handoff the new device writes; this one stays quiet.
if (event !== 'handoff' && !this._isLocalPlaybackDevice()) return Promise.resolve();
_episodeReportBody(episode, event, options = {}) {
// A progress report of `episode`'s session, or null when its
// position is unknown here.
const position = options.position != null ? options.position : this._episodePosition(episode);
if (position == null) return Promise.resolve();
if (position == null) return null;
const duration = episode.ready && Number.isFinite(audio.duration) && audio.duration > 0 ? audio.duration : null;
const body = {
return {
session_id: episode.sessionId,
generation: episode.generation,
event,
@@ -2036,6 +2165,39 @@ document.addEventListener('alpine:init', () => {
started_at_ms: episode.startedAtMs,
start_position_ms: Math.round(Math.max(0, Number(episode.startPositionSeconds || 0)) * 1000),
};
},
_reportEpisode(event, options = {}) {
// `options.final`: the last report of a player that just lost
// the playback role (it records the listening; a newer explicit
// action of the new device keeps the register).
const episode = this._episode;
if (!episode?.sessionId || episode.generation == null || episode.closed) return Promise.resolve();
// The audio is not where the register says (source cannot seek).
if (episode.seekBlocked) return Promise.resolve();
const local = this._isLocalPlaybackDevice();
// After a handoff the new device writes; this one stays quiet.
if (event !== 'handoff' && !options.final && !local) return Promise.resolve();
if (episode.superseded && event !== 'seek') {
// The user kept listening here after another device or an
// action wrote the episode: the next write is an explicit
// action of this player (a new session).
if (episode.takeOverPending && local && !options.final && !options.beacon && event !== 'handoff') {
const body = this._episodeReportBody(episode, event, options);
return body ? this._takeOverEpisode(episode, body, false) : Promise.resolve();
}
// Otherwise only closing reports are sent: the register
// refuses them, but the listening session is recorded.
if (event === 'checkpoint') return Promise.resolve();
}
const body = this._episodeReportBody(episode, event, options);
if (!body) return Promise.resolve();
const listenedMore = body.listened_ms - (episode.reportedListenedMs || 0) >= 1000;
episode.reportedListenedMs = Math.max(episode.reportedListenedMs || 0, body.listened_ms);
// Superseded while this player was playing it: the user keeps
// listening here (not after a handoff or the loss of the role).
const keepsListening = listenedMore && local && !options.final && event !== 'handoff' && event !== 'seek';
if (event === 'handoff') episode.handedOff = true;
episode.lastWriteAt = Date.now();
if (options.beacon && navigator.sendBeacon) {
const url = `/api/podcasts/episodes/${episode.episodeId}/progress`;
@@ -2050,7 +2212,18 @@ document.addEventListener('alpine:init', () => {
try {
const data = await this._episodeRequest(episode.episodeId, 'progress', body, { keepalive: !!options.keepalive });
if (data.outcome === 'superseded') {
const first = !episode.superseded;
episode.superseded = true;
if (first && keepsListening) {
if (event === 'checkpoint') {
// Periodic: wait one interval, so a handoff
// that caused it can end this session first.
episode.takeOverPending = true;
} else {
// Pause, stop, end of stream: the user acted here.
await this._takeOverEpisode(episode, body, true);
}
}
} else {
episode.generation = Math.max(Number(episode.generation || 0), Number(data.generation || 0));
if (event === 'seek') episode.superseded = false;
@@ -2063,14 +2236,92 @@ document.addEventListener('alpine:init', () => {
return episode.writes;
},
_endEpisode(event = 'stop') {
async _takeOverEpisode(episode, report, recorded) {
// The episode's register was written elsewhere while the user
// kept listening here: write this player's position as an
// explicit action (a new session above everything seen) and
// keep reporting with it. `report`: the refused report of the
// old session; `recorded`: it was sent (pause/stop/ended record
// the listening); a checkpoint is resent as 'stop' to record it.
if (episode.takingOver) return;
episode.takingOver = true;
const sessionId = this._newEpisodeSessionId();
try {
if (!recorded || report.event === 'checkpoint') {
const event = report.event === 'checkpoint' ? 'stop' : report.event;
await this._episodeRequest(episode.episodeId, 'progress', { ...report, event }, { keepalive: true }).catch(() => null);
}
const info = await this._episodeRequest(episode.episodeId, 'playback', {
episode: episode.ref,
start: true,
session_id: sessionId,
position_ms: report.position_ms,
carried_generation: episode.carried,
}, { keepalive: true });
let completed = false;
if (report.event === 'ended') {
// The end of the stream completes the episode; the
// listening was recorded with the old session.
const done = await this._episodeRequest(episode.episodeId, 'progress', {
session_id: sessionId,
generation: info.generation,
event: 'ended',
position_ms: report.position_ms,
duration_ms: report.duration_ms,
}, { keepalive: true });
completed = done?.status === 'completed';
Alpine.store('podcasts')?.episodeProgressChanged?.(episode.episodeId, done);
}
if (this._episode === episode && !episode.closed) {
episode.sessionId = info.session_id;
episode.pendingSessionId = null;
episode.generation = info.generation;
episode.startedAtMs = Date.now();
episode.lastWriteAt = Date.now();
episode.startPositionSeconds = Math.max(0, Number(report.position_ms || 0) / 1000);
episode.superseded = false;
episode.takeOverPending = false;
episode.completed = completed;
episode.reportedListenedMs = 0;
this._resetPlaybackTracking();
}
} catch {
} finally {
episode.takingOver = false;
}
},
async _releaseEpisodeSession(episodeId) {
// The user marks the episode loaded here played or unplayed from
// the list: the listening so far is saved, the audio stops and
// the session closes, so nothing written here overrides the
// mark; the next Play starts from the register.
const episode = this._episode;
if (!episode || episode.episodeId !== episodeId) return;
clearTimeout(this._episodeSeekTimer);
episode.seekPending = false;
episode.pendingSeek = null;
episode.wantPlay = false;
// `final`: recorded even when superseded, and never taken over.
if (episode.sessionId) await this._reportEpisode('stop', { keepalive: true, final: true });
Object.assign(episode, {
sessionId: null, pendingSessionId: null, generation: null,
superseded: false, takeOverPending: false, completed: false,
explicitPosition: false, reportedListenedMs: 0,
});
this._pauseLocal();
},
_endEpisode(event = 'stop', options = {}) {
// The current episode is replaced or playback stops here: report
// the final position (kept alive past a page change) and close
// the session.
// the session. `options.final`: this player lost the playback
// role; it still records the listening unless it handed off.
const episode = this._episode;
if (!episode) return;
clearTimeout(this._episodeSeekTimer);
if (!episode.closed) this._reportEpisode(event, { keepalive: true });
const report = !episode.closed && !(options.final && episode.handedOff);
if (report) this._reportEpisode(event, { keepalive: true, final: !!options.final });
episode.closed = true;
this._episode = null;
this._episodeToken += 1;
@@ -2184,12 +2435,13 @@ document.addEventListener('alpine:init', () => {
queue.currentIndex = idx;
const currentTrack = restored.tracks[idx];
if (this._isPodcastEpisode(currentTrack) && !this._isUnplayableQueueItem(currentTrack)) {
// Paused, at the saved position; a saved 0 means
// "resume from the progress register".
// Paused, where the progress register says: this
// page's saved position may be older than what
// other devices (or a mark) wrote since.
const position = state.position_ms ? state.position_ms / 1000 : null;
const prepared = this._episode?.episodeId === this._episodeRef(currentTrack)?.episode_id;
if (!prepared && this._isLocalPlaybackDevice()) {
this._playEpisodeLocal(currentTrack, { position_seconds: position, paused: true });
this._playEpisodeLocal(currentTrack, { position_seconds: null, paused: true });
} else if (!prepared) {
this.currentTrack = currentTrack;
this.currentTime = position || 0;
@@ -2507,10 +2759,11 @@ document.addEventListener('alpine:init', () => {
}
if (!this.isActive() && !this.shouldPlayJamLocally()) {
Alpine.store('player')?._pauseLocal();
// Another device plays now and writes the episode's progress;
// the session here ends without a report (a handoff from
// here already sent its final position).
Alpine.store('player')?._endEpisode('stop');
// Another device plays now and writes the episode's progress.
// A final report records the listening done here (at this
// session's generation, so the new device's start wins);
// after a handoff from here it was already sent.
Alpine.store('player')?._endEpisode('stop', { final: true });
}
if (wasControllingJam && !this.isControllingRemoteJam()) {
Alpine.store('player')?._dropJamPlaceholders();
@@ -3652,7 +3905,14 @@ document.addEventListener('alpine:init', () => {
this.busy = { ...this.busy, [id]: true };
this.actionError = '';
try {
// The episode loaded in this player: its session must not
// write over the mark (see _releaseEpisodeSession).
const player = Alpine.store('player');
if (action !== 'restart') await player?._releaseEpisodeSession?.(id);
const updated = await this._json(`/api/podcasts/episodes/${id}/${action}`, { method: 'POST' });
if (player?._episode?.episodeId === id && !player._episode.sessionId) {
player._moveEpisodeAudio(Number(updated?.resume_position_ms || 0) / 1000);
}
this._replaceEpisode(updated);
this.loadDetail();
return true;