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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 15 additions & 1 deletion Sources/Kaset/KasetApp.swift
Original file line number Diff line number Diff line change
Expand Up @@ -322,6 +322,13 @@ struct KasetApp: App {
arbiter: self.playbackArbiter
)
}
.onChange(of: NetworkMonitor.shared.isConnected) { _, isConnected in
// Auto-retry (issue #19): when connectivity returns, revive a
// video that stalled during the outage instead of leaving it stuck.
if isConnected {
self.youtubePlayerService.handleNetworkRestored()
}
}
.onChange(of: self.playerService.isMiniPlayerVisible) { _, isVisible in
self.handleMiniPlayerVisibilityChange(isVisible)
}
Expand Down Expand Up @@ -449,10 +456,17 @@ struct KasetApp: App {
}
.keyboardShortcut("s", modifiers: .command)

// Repeat - ⌘R
// Repeat - ⌘⇧R (⌘R is Refresh, below)
Button(self.repeatModeLabel) {
self.playerService.cycleRepeatMode()
}
.keyboardShortcut("r", modifiers: [.command, .shift])

// Refresh video playback - ⌘R. Recovers a stuck/black player
// after a network interruption, reloading at the same position.
Button(String(localized: "Refresh")) {
self.youtubePlayerService.refreshCurrentVideo()
}
.keyboardShortcut("r", modifiers: .command)
Comment on lines +467 to 470

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggestion: The new refresh command is always enabled and directly targets the YouTube service, unlike the existing video seek commands, which are disabled unless media keys are routed to video and a current video exists. When music is the active source but a YouTube video remains loaded in the background, ⌘R still reloads that video and can cause it to reclaim the playback arbiter, unexpectedly disrupting music. Apply the same active-video routing and availability guard used by the other video playback commands. [api mismatch]

Severity Level: Critical 🚨
- ❌ ⌘R can interrupt active music playback.
- ⚠️ Background YouTube state remains addressable globally.
- ⚠️ Refresh behavior differs from existing video command routing.
Steps of Reproduction ✅
1. Start a YouTube video through `YouTubePlayerService.play(video:)` at
`Sources/Kaset/Services/Player/YouTubePlayerService.swift:448`; this sets `currentVideo`
and causes `PlaybackArbiter.videoWillStartPlaying()` to set the active source to video at
`Sources/Kaset/Services/Player/PlaybackArbiter.swift:32-35`.

2. Start music afterward; `PlaybackArbiter.musicDidStartPlaying()` at
`Sources/Kaset/Services/Player/PlaybackArbiter.swift:48-57` changes `activeSource` to
music and pauses the video, but does not clear `youtubePlayerService.currentVideo`.

3. With music active and the paused YouTube video still loaded, press ⌘R. The command at
`Sources/Kaset/KasetApp.swift:467-470` is always enabled and directly calls
`refreshCurrentVideo()`, unlike the seek commands at
`Sources/Kaset/KasetApp.swift:383-394`, which use `shouldDisableVideoSeekCommands`.

4. `refreshCurrentVideo()` at
`Sources/Kaset/Services/Player/YouTubePlayerService.swift:558-570` reloads the retained
video. The reloaded watch page can autoplay, and playback updates call `playbackWillStart`
from `Sources/Kaset/Services/Player/YouTubePlayerService.swift:1519-1521`, allowing the
arbiter to reclaim the video source and disrupt music.

Fix in Cursor Fix in VSCode Claude

(Use Cmd/Ctrl + Click for best experience)

Prompt for AI Agent 🤖
This is a comment left during a code review.

**Path:** Sources/Kaset/KasetApp.swift
**Line:** 467:470
**Comment:**
	*Api Mismatch: The new refresh command is always enabled and directly targets the YouTube service, unlike the existing video seek commands, which are disabled unless media keys are routed to video and a current video exists. When music is the active source but a YouTube video remains loaded in the background, ⌘R still reloads that video and can cause it to reclaim the playback arbiter, unexpectedly disrupting music. Apply the same active-video routing and availability guard used by the other video playback commands.

Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix
👍 | 👎


Divider()
Expand Down
36 changes: 36 additions & 0 deletions Sources/Kaset/Services/Player/YouTubePlayerService.swift
Original file line number Diff line number Diff line change
Expand Up @@ -605,6 +605,42 @@ final class YouTubePlayerService {
self.isPlaybackLoading = true
}

// MARK: - Refresh (⌘R) & network auto-retry

/// User-triggered refresh (⌘R): reloads the current video's playback surface
/// at its last position, to recover a stuck/black player after a network
/// interruption without losing the user's place. No-op when nothing is loaded.
///
/// ponytail: a reload autoplays the watch page, so hitting this on a
/// deliberately-paused video resumes it — acceptable for a "refresh" action,
/// and the auto-retry path below only calls it when playback should be running.
func refreshCurrentVideo() {
guard let currentVideo = self.currentVideo else { return }
self.logger.info("Manual refresh: reloading current video")
self.beginYouTubePlaybackIntent()
let resumeAt = self.interruptionResumeAt(for: currentVideo.videoId)
self.playbackController.prepare(
webKitManager: self.webKitManager,
playerService: self,
usesCookieFreeDataStore: self.usesCookieFreePlaybackDataStore
)
self.playbackController.reloadVideo(videoId: currentVideo.videoId, resumeAt: resumeAt)
self.isPlaybackLoading = true
Comment on lines +620 to +628

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggestion: The refresh path starts a new autoplaying document without clearing isExplicitPauseIntentActive, isAwaitingResumeConfirmation, or changing desiredPlaybackIntent to .playing. If the current video was deliberately paused, the new page's playing updates are suppressed and immediately paused again, so the documented refresh behavior does not resume the refreshed surface and native/WebView state becomes inconsistent. Use the same intent reset and reload state transitions as the resume or identity-reload path, or preserve the paused state explicitly. [stale reference]

Severity Level: Major ⚠️
- ❌ Manual refresh fails to resume paused video surfaces.
- ⚠️ Native playback state disagrees with WebView autoplay state.
- ⚠️ Recovery refresh can leave the player apparently stuck.
Steps of Reproduction ✅
1. Load and play a video through `YouTubePlayerService.play(video:)` at
`Sources/Kaset/Services/Player/YouTubePlayerService.swift:448-489`, then explicitly pause
it through `pause()` and `performPause()` at
`Sources/Kaset/Services/Player/YouTubePlayerService.swift:822-837`.

2. The explicit pause sets `desiredPlaybackIntent` to `.paused`, sets
`isExplicitPauseIntentActive` to `true`, and clears resume confirmation at
`Sources/Kaset/Services/Player/YouTubePlayerService.swift:899-916`.

3. Press ⌘R, which invokes `refreshCurrentVideo()` at
`Sources/Kaset/Services/Player/YouTubePlayerService.swift:558-570`. That method calls
`beginYouTubePlaybackIntent()` but does not reset `desiredPlaybackIntent`,
`isExplicitPauseIntentActive`, or `isAwaitingResumeConfirmation`.

4. The new watch page is requested through `reloadVideo()` at
`Sources/Kaset/Services/Player/YouTubePlayerService.swift:562-569`. When its playing
update arrives, `reconciledPlayingState()` suppresses it whenever the pause fence remains
active at `Sources/Kaset/Services/Player/YouTubePlayerService.swift:1717-1722`, so the
refreshed surface remains natively paused instead of following the documented autoplaying
refresh behavior.

Fix in Cursor Fix in VSCode Claude

(Use Cmd/Ctrl + Click for best experience)

Prompt for AI Agent 🤖
This is a comment left during a code review.

**Path:** Sources/Kaset/Services/Player/YouTubePlayerService.swift
**Line:** 620:628
**Comment:**
	*Stale Reference: The refresh path starts a new autoplaying document without clearing `isExplicitPauseIntentActive`, `isAwaitingResumeConfirmation`, or changing `desiredPlaybackIntent` to `.playing`. If the current video was deliberately paused, the new page's playing updates are suppressed and immediately paused again, so the documented refresh behavior does not resume the refreshed surface and native/WebView state becomes inconsistent. Use the same intent reset and reload state transitions as the resume or identity-reload path, or preserve the paused state explicitly.

Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix
👍 | 👎

}

/// Auto-retry when connectivity returns (issue #19): if a video was meant to
/// be playing but stalled during a network drop — still "loading", or not
/// playing while the user intends to — reload it. Deliberately-paused
/// playback is left alone so a network blip never yanks it back to life.
func handleNetworkRestored() {
guard self.currentVideo != nil else { return }
let stalled = self.isPlaybackLoading
|| (self.desiredPlaybackIntent == .playing && !self.isPlaying)
guard stalled else { return }
Comment on lines +637 to +639

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggestion: The loading-only branch ignores the user's playback intent. In particular, refreshCurrentVideo() sets isPlaybackLoading even when refreshing a deliberately paused video, so a later connectivity restoration can call this handler and reload/autoplay that paused video despite the documented guarantee that deliberate pauses are left untouched. Require desiredPlaybackIntent == .playing before retrying the loading state, or distinguish user refresh loading from outage-stall loading. [incorrect condition logic]

Severity Level: Major ⚠️
- ❌ Paused videos can receive unintended automatic reloads.
- ⚠️ Connectivity restoration ignores deliberate pause intent.
- ⚠️ Repeated reloads can disrupt the paused playback surface.
Steps of Reproduction ✅
1. Load a video and deliberately pause it using `performPause()` at
`Sources/Kaset/Services/Player/YouTubePlayerService.swift:828-837`; this records `.paused`
intent and clears loading through `activateExplicitPauseIntent()` at
`Sources/Kaset/Services/Player/YouTubePlayerService.swift:840-858`.

2. While paused, press ⌘R. `refreshCurrentVideo()` at
`Sources/Kaset/Services/Player/YouTubePlayerService.swift:558-570` starts a new navigation
and unconditionally sets `isPlaybackLoading = true`, even though the pause intent remains
active.

3. When connectivity subsequently transitions to connected, `KasetApp` calls
`handleNetworkRestored()` at `Sources/Kaset/KasetApp.swift:325-330`.

4. The loading-only condition at
`Sources/Kaset/Services/Player/YouTubePlayerService.swift:576-582` ignores
`desiredPlaybackIntent` and calls `refreshCurrentVideo()` again. Thus a user-initiated
paused refresh is treated as an outage stall, violating the documented guarantee that
deliberate pauses remain untouched and repeatedly reloading an autoplay-capable page.

Fix in Cursor Fix in VSCode Claude

(Use Cmd/Ctrl + Click for best experience)

Prompt for AI Agent 🤖
This is a comment left during a code review.

**Path:** Sources/Kaset/Services/Player/YouTubePlayerService.swift
**Line:** 637:639
**Comment:**
	*Incorrect Condition Logic: The loading-only branch ignores the user's playback intent. In particular, `refreshCurrentVideo()` sets `isPlaybackLoading` even when refreshing a deliberately paused video, so a later connectivity restoration can call this handler and reload/autoplay that paused video despite the documented guarantee that deliberate pauses are left untouched. Require `desiredPlaybackIntent == .playing` before retrying the loading state, or distinguish user refresh loading from outage-stall loading.

Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix
👍 | 👎

self.logger.info("Network restored: auto-reloading stalled video")
self.refreshCurrentVideo()
}

/// Returns the best native resume target for an interrupted document.
/// Native seek intent wins until the observer proves it was applied;
/// otherwise use the last genuine content clock.
Expand Down
48 changes: 48 additions & 0 deletions Tests/KasetTests/YouTubePlayerServiceTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -218,6 +218,54 @@ struct YouTubePlayerServiceTests {
#expect(self.controller.reloadedVideoIds.isEmpty)
}

@Test("Manual refresh (⌘R) reloads the current video")
func refreshReloadsCurrentVideo() {
self.sut.play(video: MockYouTubeClient.makeVideo(videoId: "abc"))
self.sut.updatePlaybackState(.init(isPlaying: true, progress: 12, duration: 60, videoId: "abc"))

self.sut.refreshCurrentVideo()

// A forced reload of the same id (not a no-op loadVideo). The resume
// target is the existing interruption-resume machinery, covered above.
#expect(self.controller.reloadedVideoIds == ["abc"])
}

@Test("Manual refresh is a no-op when nothing is playing")
func refreshNoOpWhenIdle() {
self.sut.refreshCurrentVideo()
#expect(self.controller.reloadedVideoIds.isEmpty)
}

@Test("Network restored reloads a stalled (still-loading) video")
func networkRestoredReloadsStalledVideo() {
// play() leaves the surface loading (no playback update yet) — the
// stuck-after-network-drop state.
self.sut.play(video: MockYouTubeClient.makeVideo(videoId: "abc"))
#expect(self.sut.isPlaybackLoading)

self.sut.handleNetworkRestored()

#expect(self.controller.reloadedVideoIds == ["abc"])
}

@Test("Network restored leaves a normally-playing video alone")
func networkRestoredIgnoresHealthyPlayback() {
self.sut.play(video: MockYouTubeClient.makeVideo(videoId: "abc"))
// A playback update clears the loading state and marks it playing.
self.sut.updatePlaybackState(.init(isPlaying: true, progress: 5, duration: 60, videoId: "abc"))
#expect(!self.sut.isPlaybackLoading)

self.sut.handleNetworkRestored()

#expect(self.controller.reloadedVideoIds.isEmpty)
}

@Test("Network restored is a no-op when nothing is playing")
func networkRestoredNoOpWhenIdle() {
self.sut.handleNetworkRestored()
#expect(self.controller.reloadedVideoIds.isEmpty)
}

@Test("Identity-switch during an ad resumes the content, not the ad position")
func reloadDuringAdUsesContentProgress() {
self.sut.play(video: MockYouTubeClient.makeVideo(videoId: "abc"))
Expand Down
Loading