diff --git a/.changes/stalker-smart-discovery.md b/.changes/stalker-smart-discovery.md
index 49926d2be..c7da574e0 100644
--- a/.changes/stalker-smart-discovery.md
+++ b/.changes/stalker-smart-discovery.md
@@ -5,4 +5,5 @@ area: stalker
Stalker setup now accepts a host or `/c` address, discovers the working API
endpoint and authentication mode, and rechecks connection details edited
-later. Failed edits leave the saved playlist and active session unchanged.
+later. Canceled or failed edits leave the saved playlist and active session
+unchanged.
diff --git a/CLAUDE.md b/CLAUDE.md
index 992401574..c063d4caa 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -1262,7 +1262,7 @@ engine` (restart required) or
- Portal mode (full vs. simple) follows OBSERVED behavior, never a URL substring. The single predicate is `isFullStalkerPortalPlaylist()` / `isFullStalkerPortalUrl()` in `@iptvnator/shared/interfaces` (`stalker-portal-mode.util.ts`): the persisted `Playlist.isFullStalkerPortal` flag is authoritative and the URL shape is a fallback for legacy rows only. Three diverging copies of this rule used to exist and shipped broken configurations (#850/#686/#755) — never re-implement it. A token-enforcing `portal.php` panel is a full portal; a `server/load.php` endpoint that answers without a token is a simple one.
- Import requires an explicit HTTP(S) scheme but accepts a bare host, `/c`, or a concrete `.php` address. It probes candidates in order (a pasted `.php` endpoint first, then `/portal.php` → `/server/load.php` → `/stalker_portal/server/load.php`) and classifies each by behavior — a token-less `itv/get_genres` returning data proves a token-free panel; the plain-text auth failure proves a full portal, confirmed by a real handshake + `get_profile`. `StalkerPortalDiscoveryService` (`libs/portal/stalker/data-access`) persists and displays the proven endpoint and mode. An unreachable panel-style import remains allowed with a warning; a bare host falls back to `/portal.php`, while canonical-shaped unreachable addresses still abort.
-- The playlist-info Edit dialog loads the complete persisted Stalker row before enabling the form, because Electron's startup metadata projection omits payload-only serial/device/signature/mode fields; a summarized row must never render and then persist an empty portal identity. It preserves an unchanged connection byte-for-byte and skips discovery. Changing URL, MAC, credentials, serial, device IDs or signatures blocks duplicate saves, disables dialog closure for the validation window, and runs the existing discovery service through the app-provided `STALKER_PLAYLIST_CONNECTION_EDITOR` token, keeping Stalker data-access out of `playlist-shared-ui`. Before discovery it reserves the playlist ID; a second Edit cannot replace that owner. The reservation blocks every new authentication (including fingerprint-equivalent URL edits) and repair, drains existing work, and rechecks ownership after every asynchronous drain/rebase; failure releases it without changing the saved or runtime connection. Success uses one awaited write to atomically replace endpoint, mode, normalized identity and session metadata, then feeds its complete merged row into the state-only NgRx update and active `StalkerStore`/session/watchdog replacement before another same-route request can use the old connection. This preserves playback headers and other metadata absent from the form. Runtime session authority may rebase a changed fingerprint only when the persisted row proves that it owns the same playlist ID, so delete/restore and backup merge remain usable. The transient `PlaylistMetaUpdate.stalkerSessionPatch` preserves on absence, clears on `null`, and fully replaces from an object before storage; it is projected onto existing flat playlist fields and never changes the DB or backup shape.
+- The playlist-info Edit dialog loads the complete persisted Stalker row before enabling the form, because Electron's startup metadata projection omits payload-only serial/device/signature/mode fields; a summarized row must never render and then persist an empty portal identity. It preserves an unchanged connection byte-for-byte and skips discovery. Changing URL, MAC, credentials, serial, device IDs or signatures blocks duplicate saves, disables dialog closure for the validation window, and runs the existing discovery service through the app-provided `STALKER_PLAYLIST_CONNECTION_EDITOR` token, keeping Stalker data-access out of `playlist-shared-ui`. Before discovery it reserves the playlist ID; a second Edit cannot replace that owner. The reservation blocks every new authentication (including fingerprint-equivalent URL edits) and repair, drains existing work, and rechecks ownership after every asynchronous drain/rebase; failure releases it without changing the saved or runtime connection. If navigation or another owner closes/destroys the dialog while discovery is in flight, the UI discards a later successful result through `discardResolvedConnection()` and releases both reservations without persisting it. Success uses one awaited write to atomically replace endpoint, mode, normalized identity and session metadata, then feeds its complete merged row into the state-only NgRx update and active `StalkerStore`/session/watchdog replacement before another same-route request can use the old connection. This preserves playback headers and other metadata absent from the form. Runtime session authority may rebase a changed fingerprint only when the persisted row proves that it owns the same playlist ID, so delete/restore and backup merge remain usable. The transient `PlaylistMetaUpdate.stalkerSessionPatch` preserves on absence, clears on `null`, and fully replaces from an object before storage; it is projected onto existing flat playlist fields and never changes the DB or backup shape.
- `executeStalkerRequest()` (`stores/utils/stalker-request.utils.ts`) is the choke point for catalog, content and playback requests: mode routing, the in-session repair override, and retry-once all live there. Four callers are deliberately outside it because they run below or before the thing it routes on — `StalkerAuthApi` (handshake/`get_profile`/`do_auth`, which the full-portal branch is built from; routing them back would recurse), `StalkerPortalDiscoveryService` (probes precede the mode they determine), `StalkerAccountInfoService.fetchViaProfile()`, and `StreamResolverService` for a collection item with no playlist row. They are exempt from the routing, not from the repair it hooks, but only `fetchViaProfile()` wires `StalkerPortalRepairService` itself: discovery is what repair _drives_, the row-less resolver branch has no playlist to repair, and the auth layer needs nothing — a terminal handshake failure propagates out of the full-portal branch into whichever `executeStalkerRequest()` call triggered the authentication, which is why terminal handshake failures are a repair trigger. Anything new that is not auth or discovery belongs on `executeStalkerRequest()`. Existing playlists are repaired LAZILY (`StalkerPortalRepairService`) — only after a request fails with a shape a wrong endpoint/mode produces, at most once per source configuration per playlist per session, persisted through the atomic `PlaylistsService.transformPlaylistMeta`. There is deliberately **no eager one-shot migration**: a portal that works is never re-probed.
- Explicit Edit advances the repair generation before installing its resolved session. A lazy repair that started earlier is discarded even if it had already verified its row, so it cannot restore an older endpoint, mode or token after Edit.
- Both transports build the wire format from the same shared builders in `@iptvnator/shared/interfaces` — `buildStalkerRequestUrl()`, `buildStalkerIdentityRequestContext()`, `encodeStalkerCmdValue()` — so the Electron and PWA legs cannot drift. The mock's `/stalker` mirror shares the identity builder only — it dispatches in-process, so there is no portal URL to build and it mirrors the `JsHttpRequest` default by hand. Never fork any of them.
diff --git a/apps/web/src/app/services/stalker-playlist-connection-editor.service.spec.ts b/apps/web/src/app/services/stalker-playlist-connection-editor.service.spec.ts
index 8ec94ac97..0e70ef381 100644
--- a/apps/web/src/app/services/stalker-playlist-connection-editor.service.spec.ts
+++ b/apps/web/src/app/services/stalker-playlist-connection-editor.service.spec.ts
@@ -126,6 +126,23 @@ describe('AppStalkerPlaylistConnectionEditorService', () => {
});
});
+ it('releases a successful discovery fence when the resolved edit is discarded', async () => {
+ discovery.discover.mockResolvedValue({
+ status: 'resolved',
+ portalUrl: 'https://portal.example.com/portal.php',
+ isFullStalkerPortal: false,
+ });
+
+ await service.resolveConnection(draft);
+ service.discardResolvedConnection(draft._id);
+ expect(stalkerSession.cancelEditDiscovery).toHaveBeenCalledWith(
+ expect.objectContaining({ playlistId: draft._id })
+ );
+ expect(portalRepair.releasePlaylistEdit).toHaveBeenCalledWith(
+ draft._id
+ );
+ });
+
it('replaces a full-portal session with the confirmed authorization result', async () => {
discovery.discover.mockResolvedValue({
status: 'resolved',
diff --git a/apps/web/src/app/services/stalker-playlist-connection-editor.service.ts b/apps/web/src/app/services/stalker-playlist-connection-editor.service.ts
index 05c5c28f7..24887d76f 100644
--- a/apps/web/src/app/services/stalker-playlist-connection-editor.service.ts
+++ b/apps/web/src/app/services/stalker-playlist-connection-editor.service.ts
@@ -77,6 +77,13 @@ export class AppStalkerPlaylistConnectionEditorService implements StalkerPlaylis
}
}
+ discardResolvedConnection(playlistId: string): void {
+ const fence = this.editFences.get(playlistId);
+ if (fence) {
+ this.releaseEditFence(playlistId, fence);
+ }
+ }
+
async resolveConnection(
playlist: PlaylistMeta
): Promise {
diff --git a/docs/architecture/stalker-portal.md b/docs/architecture/stalker-portal.md
index a728dd2f9..f72e43ae2 100644
--- a/docs/architecture/stalker-portal.md
+++ b/docs/architecture/stalker-portal.md
@@ -204,7 +204,10 @@ then persist empty serial, device ID, signature, or mode values.
Changing any connection field disables the form while the same discovery
service validates the draft. Auth rejection or an unreachable portal leaves
the dialog open and writes nothing. Escape/backdrop closure is disabled for the
-validation window. Before discovery starts, Edit reserves the playlist ID; an
+validation window. If navigation or another owner starts closing/destroys the
+dialog while discovery is in flight, the successful result is discarded before
+persistence and both the session and repair reservations are released. Before
+discovery starts, Edit reserves the playlist ID; an
overlapping Edit cannot replace that owner. The reservation blocks every new
authentication (including a URL edit with the same normalized fingerprint) and
repair, and drains any work already in flight. Ownership is rechecked after
@@ -231,9 +234,10 @@ schema or backup-version migration is required.
The shared playlist UI exposes only
`STALKER_PLAYLIST_CONNECTION_EDITOR` and its
-`resolved | auth-rejected | unreachable` result contract. The web composition
-layer implements the token with Stalker data-access; the UI library must not
-import Stalker discovery directly.
+`resolved | auth-rejected | unreachable` result contract, plus the narrow
+`discardResolvedConnection()` cleanup hook for a closing dialog. The web
+composition layer implements the token with Stalker data-access; the UI library
+must not import Stalker discovery directly.
**Lazy repair (existing playlists).** The flag is frozen in the DB, so
records persisted by the old guess stay broken without repair — but a large
diff --git a/libs/playlist/shared/ui/src/lib/recent-playlists/playlist-info/playlist-info.component.spec.ts b/libs/playlist/shared/ui/src/lib/recent-playlists/playlist-info/playlist-info.component.spec.ts
index e8a22cd4d..863dd6d43 100644
--- a/libs/playlist/shared/ui/src/lib/recent-playlists/playlist-info/playlist-info.component.spec.ts
+++ b/libs/playlist/shared/ui/src/lib/recent-playlists/playlist-info/playlist-info.component.spec.ts
@@ -51,10 +51,14 @@ describe('PlaylistInfoComponent', () => {
dispatch: jest.Mock;
};
let dialogRef: {
+ beforeClosed: jest.Mock;
close: jest.Mock;
disableClose: boolean;
};
+ let dialogBeforeClosed: Subject;
let stalkerConnectionEditor: {
+ applyResolvedConnection: jest.Mock;
+ discardResolvedConnection: jest.Mock;
resolveConnection: jest.Mock;
};
const originalElectron = window.electron;
@@ -105,12 +109,15 @@ describe('PlaylistInfoComponent', () => {
store = {
dispatch: jest.fn(),
};
+ dialogBeforeClosed = new Subject();
dialogRef = {
+ beforeClosed: jest.fn(() => dialogBeforeClosed),
close: jest.fn(),
disableClose: false,
};
stalkerConnectionEditor = {
applyResolvedConnection: jest.fn().mockResolvedValue(undefined),
+ discardResolvedConnection: jest.fn(),
resolveConnection: jest.fn(
async (updatedPlaylist: PlaylistMeta) => ({
status: STALKER_PLAYLIST_CONNECTION_EDITOR_STATUS.RESOLVED,
@@ -825,6 +832,98 @@ describe('PlaylistInfoComponent', () => {
expect(dialogRef.close).toHaveBeenCalledTimes(1);
});
+ it('discards a resolved edit when the dialog closes before discovery finishes', async () => {
+ await createStalkerComponent();
+ const resolvedPlaylist = {
+ ...component.playlistDetails.getRawValue(),
+ portalUrl: 'https://portal.example.com/server/load.php',
+ isFullStalkerPortal: true,
+ stalkerSessionPatch: {
+ stalkerToken: 'NEW_TOKEN',
+ stalkerSessionIdentity: 'new-fingerprint',
+ },
+ };
+ let finishDiscovery:
+ | ((value: {
+ status: 'resolved';
+ playlist: typeof resolvedPlaylist;
+ }) => void)
+ | undefined;
+ stalkerConnectionEditor.resolveConnection.mockReturnValueOnce(
+ new Promise((resolve) => {
+ finishDiscovery = resolve;
+ })
+ );
+ component.playlistDetails
+ .get('portalUrl')
+ ?.setValue('https://new.example.com');
+ const saving = component.saveChanges(
+ component.playlistDetails.getRawValue() as PlaylistMeta
+ );
+ await Promise.resolve();
+
+ fixture.destroy();
+ finishDiscovery?.({
+ status: STALKER_PLAYLIST_CONNECTION_EDITOR_STATUS.RESOLVED,
+ playlist: resolvedPlaylist,
+ });
+ await saving;
+
+ expect(
+ stalkerConnectionEditor.discardResolvedConnection
+ ).toHaveBeenCalledWith('playlist-1');
+ expect(
+ stalkerConnectionEditor.applyResolvedConnection
+ ).not.toHaveBeenCalled();
+ expect(store.dispatch).not.toHaveBeenCalled();
+ });
+
+ it('discards a resolved edit while the dialog close animation is pending', async () => {
+ await createStalkerComponent();
+ const resolvedPlaylist = {
+ ...component.playlistDetails.getRawValue(),
+ portalUrl: 'https://portal.example.com/server/load.php',
+ isFullStalkerPortal: true,
+ stalkerSessionPatch: {
+ stalkerToken: 'NEW_TOKEN',
+ stalkerSessionIdentity: 'new-fingerprint',
+ },
+ };
+ let finishDiscovery:
+ | ((value: {
+ status: 'resolved';
+ playlist: typeof resolvedPlaylist;
+ }) => void)
+ | undefined;
+ stalkerConnectionEditor.resolveConnection.mockReturnValueOnce(
+ new Promise((resolve) => {
+ finishDiscovery = resolve;
+ })
+ );
+ component.playlistDetails
+ .get('portalUrl')
+ ?.setValue('https://new.example.com');
+ const saving = component.saveChanges(
+ component.playlistDetails.getRawValue() as PlaylistMeta
+ );
+ await Promise.resolve();
+
+ dialogBeforeClosed.next();
+ finishDiscovery?.({
+ status: STALKER_PLAYLIST_CONNECTION_EDITOR_STATUS.RESOLVED,
+ playlist: resolvedPlaylist,
+ });
+ await saving;
+
+ expect(
+ stalkerConnectionEditor.discardResolvedConnection
+ ).toHaveBeenCalledWith('playlist-1');
+ expect(
+ stalkerConnectionEditor.applyResolvedConnection
+ ).not.toHaveBeenCalled();
+ expect(store.dispatch).not.toHaveBeenCalled();
+ });
+
it('does not update UI state or report success when resolved persistence fails', async () => {
const consoleError = jest
.spyOn(console, 'error')
diff --git a/libs/playlist/shared/ui/src/lib/recent-playlists/playlist-info/playlist-info.component.ts b/libs/playlist/shared/ui/src/lib/recent-playlists/playlist-info/playlist-info.component.ts
index 8aca05ede..29636ef50 100644
--- a/libs/playlist/shared/ui/src/lib/recent-playlists/playlist-info/playlist-info.component.ts
+++ b/libs/playlist/shared/ui/src/lib/recent-playlists/playlist-info/playlist-info.component.ts
@@ -1,6 +1,6 @@
import { Clipboard, ClipboardModule } from '@angular/cdk/clipboard';
import { DatePipe } from '@angular/common';
-import { Component, inject, signal } from '@angular/core';
+import { Component, DestroyRef, inject, signal } from '@angular/core';
import {
FormControl,
ReactiveFormsModule,
@@ -184,6 +184,7 @@ export class PlaylistInfoComponent {
private runtime = inject(RuntimeCapabilitiesService);
private readonly epgBridge = inject(EpgRuntimeBridgeService);
private readonly settingsStore = inject(SettingsStore);
+ private readonly destroyRef = inject(DestroyRef);
private readonly stalkerConnectionEditor = inject(
STALKER_PLAYLIST_CONNECTION_EDITOR
);
@@ -194,6 +195,7 @@ export class PlaylistInfoComponent {
readonly isSaving = signal(false);
readonly isHydratingStalkerPlaylist = signal(false);
readonly stalkerPlaylistHydrationFailed = signal(false);
+ private dialogClosing = false;
private readonly stalkerPlaylistHydration: Promise;
get isDesktop(): boolean {
@@ -296,6 +298,9 @@ export class PlaylistInfoComponent {
playlistDetails!: UntypedFormGroup;
constructor() {
+ this.dialogRef?.beforeClosed().subscribe(() => {
+ this.dialogClosing = true;
+ });
this.playlist = this.playlistData;
this.createForm();
if (this.playlist.portalUrl) {
@@ -418,6 +423,12 @@ export class PlaylistInfoComponent {
);
return;
}
+ if (this.dialogClosing || this.destroyRef.destroyed) {
+ this.stalkerConnectionEditor.discardResolvedConnection(
+ result.playlist._id
+ );
+ return;
+ }
normalizedPlaylist = result.playlist;
resolvedStalkerConnection = true;
} else {
diff --git a/libs/playlist/shared/ui/src/lib/recent-playlists/playlist-info/stalker-playlist-connection-editor.token.ts b/libs/playlist/shared/ui/src/lib/recent-playlists/playlist-info/stalker-playlist-connection-editor.token.ts
index 1cc383de4..968325953 100644
--- a/libs/playlist/shared/ui/src/lib/recent-playlists/playlist-info/stalker-playlist-connection-editor.token.ts
+++ b/libs/playlist/shared/ui/src/lib/recent-playlists/playlist-info/stalker-playlist-connection-editor.token.ts
@@ -40,6 +40,8 @@ export interface StalkerPlaylistConnectionEditor {
): Promise;
/** Atomically persists a resolved edit, then synchronizes in-run state. */
applyResolvedConnection(playlist: PlaylistMetaUpdate): Promise;
+ /** Releases a resolved edit that the dialog closed without applying. */
+ discardResolvedConnection(playlistId: string): void;
}
export const STALKER_PLAYLIST_CONNECTION_EDITOR =