diff --git a/docs/superpowers/plans/2026-07-20-unified-logo-bug.md b/docs/superpowers/plans/2026-07-20-unified-logo-bug.md index 054cf3d3b..15699ba3e 100644 --- a/docs/superpowers/plans/2026-07-20-unified-logo-bug.md +++ b/docs/superpowers/plans/2026-07-20-unified-logo-bug.md @@ -39,12 +39,15 @@ npm test && npm run lint && npm run typecheck && npm run build ### Task 1: Seed the shared `Channel Bug` watermark preset **Files:** -- Modify: `ErsatzTV.Infrastructure/Data/DbInitializer.cs:134` (add the call) and append a new private method after `SeedChannelTemplates` (which ends at `:186`) +- Modify: `ErsatzTV.Core/Domain/ConfigElementKey.cs` (add one key property) +- Modify: `ErsatzTV.Infrastructure/Data/DbInitializer.cs:134` (call order), `SeedChannelTemplates` (`:140-186`, takes the new id), `NewSystemTemplate` (`:233-265`, stamps it); append the new seed method - Test: `ErsatzTV.Tests/Infrastructure/DbInitializerChannelBugWatermarkTests.cs` (create) **Interfaces:** -- Consumes: `TvContext.ChannelWatermarks` (`ErsatzTV.Infrastructure/Data/TvContext.cs:44`), `ChannelWatermark` (`ErsatzTV.Core/Domain/ChannelWatermark.cs:6-36`), enums `ChannelWatermarkMode` / `ChannelWatermarkImageSource` (same file, `:38-52`), `WatermarkLocation` / `WatermarkSize` (`ErsatzTV.FFmpeg/State/WatermarkState.cs`). -- Produces: a `ChannelWatermark` row named exactly `Channel Bug` with `ImageSource = ChannelLogo`. Tasks 5 and 6 locate it by `imageSource`, not by name. +- Consumes: `TvContext.ChannelWatermarks` (`ErsatzTV.Infrastructure/Data/TvContext.cs:44`), `ChannelWatermark` (`ErsatzTV.Core/Domain/ChannelWatermark.cs:6-36`), enums `ChannelWatermarkMode` / `ChannelWatermarkImageSource` (same file, `:38-52`), `WatermarkLocation` / `WatermarkSize` (`ErsatzTV.FFmpeg/State/WatermarkState.cs`), `ChannelTemplate.WatermarkId` (`ErsatzTV.Core/Domain/ChannelTemplate.cs:14`). +- Produces: `private static async Task SeedChannelBugWatermark(TvContext, CancellationToken)` returning the preset's id; a `ChannelWatermark` row named `Channel Bug` with `ImageSource = ChannelLogo`; freshly seeded `ChannelTemplate` rows carrying its `WatermarkId`; a `ConfigElement` row keyed `watermark.channel_bug_seeded`. + +**Why the marker and the ordering (do not simplify these away):** `ChannelWatermark` has no `IsSystem` flag, so a pure name-guard resurrects the row on every restart after a deliberate delete — `DbInitializer.Initialize` runs at every startup (`ErsatzTV/Services/RunOnce/DatabaseMigratorService.cs:89`). The watermark must be seeded **before** the templates so its id can be stamped on them. - [ ] **Step 1: Write the failing tests** @@ -134,6 +137,37 @@ public class DbInitializerChannelBugWatermarkTests context.ChannelWatermarks.Count(w => w.Name == "Channel Bug").ShouldBe(1); } + + // No IsSystem flag exists on ChannelWatermark, and Initialize runs on every startup, so without + // a seed marker a deliberate delete would be undone forever. + [Test] + public async Task Initialize_Should_Not_Resurrect_A_Deleted_Preset() + { + await using TvContext context = _db.CreateContext(); + await DbInitializer.Initialize(context, CancellationToken.None); + + ChannelWatermark seeded = context.ChannelWatermarks.Single(w => w.Name == "Channel Bug"); + context.ChannelWatermarks.Remove(seeded); + await context.SaveChangesAsync(); + + await DbInitializer.Initialize(context, CancellationToken.None); + + context.ChannelWatermarks.Any(w => w.Name == "Channel Bug").ShouldBeFalse(); + } + + [Test] + public async Task Initialize_Should_Stamp_The_Preset_On_Freshly_Seeded_Templates() + { + await using TvContext context = _db.CreateContext(); + + await DbInitializer.Initialize(context, CancellationToken.None); + + ChannelWatermark watermark = context.ChannelWatermarks.Single(w => w.Name == "Channel Bug"); + foreach (ChannelTemplate template in context.ChannelTemplates.Where(t => t.IsSystem).ToList()) + { + template.WatermarkId.ShouldBe(watermark.Id); + } + } } ``` @@ -146,29 +180,49 @@ Expected: FAIL — `Sequence contains no elements` from `.Single(...)` (no seede - [ ] **Step 3: Implement the seed** -In `ErsatzTV.Infrastructure/Data/DbInitializer.cs`, add the call immediately after the existing `SeedChannelTemplates` call at `:134`: +**3a.** In `ErsatzTV.Core/Domain/ConfigElementKey.cs`, add the key next to `ChannelTemplatesDefaultTemplateId` (`:26`), matching the file's existing property style: ```csharp - await SeedChannelTemplates(context, cancellationToken); - await SeedChannelBugWatermark(context, cancellationToken); + public static ConfigElementKey WatermarkChannelBugSeeded => new("watermark.channel_bug_seeded"); ``` -Then add this private method directly after `SeedChannelTemplates` (which ends at `:186`): +**3b.** In `ErsatzTV.Infrastructure/Data/DbInitializer.cs`, replace the single call at `:134`. The watermark seeds **first** so its id can be stamped on the templates: + +```csharp + int? channelBugWatermarkId = await SeedChannelBugWatermark(context, cancellationToken); + await SeedChannelTemplates(context, cancellationToken, channelBugWatermarkId); +``` + +**3c.** Add this private method directly after `SeedChannelTemplates` (which ends at `:186`): ```csharp // A single shared preset is all that's needed: ImageSource.ChannelLogo resolves each channel's // own logo artwork at render time (WatermarkSelector), so one row makes every channel use its - // own logo as its on-screen bug. Name-guarded so an existing hand-made row keeps its tuned - // geometry — adopt, never overwrite. - private static async Task SeedChannelBugWatermark(TvContext context, CancellationToken cancellationToken) + // own logo as its on-screen bug. + // + // Guarded by a ConfigElement marker rather than by name alone: ChannelWatermark has no IsSystem + // flag, and Initialize runs on every startup, so a name-only guard would resurrect the row + // forever after a deliberate delete. Adopting an existing same-name row (an operator's tuned + // one) also sets the marker — adopt, never overwrite. + private static async Task SeedChannelBugWatermark( + TvContext context, + CancellationToken cancellationToken) { - if (await context.ChannelWatermarks.AnyAsync(w => w.Name == "Channel Bug", cancellationToken)) + string seededKey = ConfigElementKey.WatermarkChannelBugSeeded.Key; + bool alreadySeeded = await context.ConfigElements + .AnyAsync(c => c.Key == seededKey, cancellationToken); + + ChannelWatermark existing = await context.ChannelWatermarks + .FirstOrDefaultAsync(w => w.Name == "Channel Bug", cancellationToken); + + if (alreadySeeded) { - return; + return existing?.Id; } - await context.ChannelWatermarks.AddAsync( - new ChannelWatermark + if (existing is null) + { + existing = new ChannelWatermark { Name = "Channel Bug", Mode = ChannelWatermarkMode.Permanent, @@ -184,21 +238,52 @@ Then add this private method directly after `SeedChannelTemplates` (which ends a Opacity = 80, PlaceWithinSourceContent = false, ZIndex = 0 - }, - cancellationToken); + }; + await context.ChannelWatermarks.AddAsync(existing, cancellationToken); + } + await context.ConfigElements.AddAsync( + new ConfigElement { Key = seededKey, Value = "true" }, + cancellationToken); await context.SaveChangesAsync(cancellationToken); + + return existing.Id; } ``` +**3d.** Thread the id through the template seed. Change the signature at `:140`: + +```csharp + private static async Task SeedChannelTemplates( + TvContext context, + CancellationToken cancellationToken, + int? channelBugWatermarkId) +``` + +Pass `channelBugWatermarkId` as a new final argument to **both** `NewSystemTemplate(...)` calls (`:157-166` and `:172-181`), add the matching parameter to `NewSystemTemplate` (`:233-240`): + +```csharp + bool randomStartPoint, + int? watermarkId) => +``` + +and add one line to its object initializer (`:241-264`): + +```csharp + WatermarkId = watermarkId, +``` + +This only ever touches templates the seed is creating for the first time — the existing name-guards at `:142-147` and `:155`/`:170` mean an install that already has these templates is untouched. + Add `using ErsatzTV.FFmpeg.State;` to the file's usings if `WatermarkLocation`/`WatermarkSize` do not already resolve. - [ ] **Step 4: Run the tests to verify they pass** ```bash dotnet test ErsatzTV.Tests/ErsatzTV.Tests.csproj --filter FullyQualifiedName~DbInitializerChannelBugWatermarkTests +dotnet test ErsatzTV.Tests/ErsatzTV.Tests.csproj --filter FullyQualifiedName~DbInitializerChannelTemplateTests ``` -Expected: PASS, 3 tests. Confirm the build output shows `Build succeeded` / `0 Error(s)` — a failed build with `--no-build` elsewhere can silently run a stale dll. +Expected: PASS, 5 tests in the first fixture; the pre-existing template fixture must still pass (you changed its seed signature). Confirm the build output shows `Build succeeded` / `0 Error(s)` — a failed build with `--no-build` elsewhere can silently run a stale dll. - [ ] **Step 5: Strip the BOM and commit** @@ -211,8 +296,8 @@ if b.startswith(b'\xef\xbb\xbf'): print('stripped', p) EOF head -c3 ErsatzTV.Infrastructure/Data/DbInitializer.cs | xxd -p # must NOT be efbbbf -git add ErsatzTV.Infrastructure/Data/DbInitializer.cs ErsatzTV.Tests/Infrastructure/DbInitializerChannelBugWatermarkTests.cs -git commit -m "feat(67): seed shared Channel Bug watermark preset (adopts an existing row untouched)" +git add ErsatzTV.Core/Domain/ConfigElementKey.cs ErsatzTV.Infrastructure/Data/DbInitializer.cs ErsatzTV.Tests/Infrastructure/DbInitializerChannelBugWatermarkTests.cs +git commit -m "feat(67): seed shared Channel Bug watermark preset, once per database" ``` --- @@ -264,12 +349,7 @@ public class WatermarkMapperTests } ``` -`Mapper` is `internal static`, so `ErsatzTV.Application` must expose internals to the test project. Check first: - -```bash -grep -rn "InternalsVisibleTo" ErsatzTV.Application/ -``` -If `ErsatzTV.Tests` is not already listed, do NOT add an `InternalsVisibleTo` — instead assert the same behavior through the public query handler by writing the test against `GetAllWatermarksForApiHandler` with an `InMemoryTvContext` (same harness as Task 1), seeding one `ChannelWatermark` with `ImageSource = ChannelLogo` and asserting the returned `List` single item carries it. +`Mapper` is `internal static`, but `ErsatzTV.Application.csproj:30-32` already exposes internals to `ErsatzTV.Tests` via an `InternalsVisibleTo` assembly attribute — verified, so this test compiles as written. Do **not** add another `InternalsVisibleTo`. - [ ] **Step 2: Run the test to verify it fails** @@ -643,8 +723,19 @@ git commit -m "feat(67): show resolved bug geometry on the watermarks screen" - Test: `web/src/screens/ChannelEditScreen.test.tsx` (extend) **Interfaces:** -- Consumes: `BugPreview` (Task 3); `Watermark.imageSource` (Task 2); existing `data.watermarks`, `draft.watermarkId`, `previewSrc`, `set()`. -- Behavior contract: the toggle is a **pure reflection of stored state** — ticked iff `draft.watermarkId` points at a watermark whose `imageSource === 'ChannelLogo'`. Loading and re-saving a channel without touching the toggle must leave `watermarkId` byte-identical. The existing watermark `` stays — the toggle is a shortcut, not a replacement. - [ ] **Step 1: Write the failing test** @@ -684,9 +775,76 @@ Append to `web/src/screens/ChannelEditScreen.test.tsx` (match the file's existin await waitFor(() => expect(bodies).toHaveLength(1)); expect((bodies[0] as { watermarkId: null | number }).watermarkId).toBeNull(); }); + + // Regression: a search-by-imageSource implementation binds to the alphabetically-first + // ChannelLogo preset (getWatermarks sorts by name), silently repointing this channel. + it('reflects a non-first ChannelLogo preset without repointing the channel', async () => { + const bodies: unknown[] = []; + mockApi({ + onRequest: (url, method, body) => { + if (url === '/api/v1/watermarks' && method === 'GET') { + return jsonResponse([ + { id: 4, imageSource: 'ChannelLogo', name: 'Alpha Bug' }, + { id: 9, imageSource: 'ChannelLogo', name: 'Channel Bug' } + ]); + } + if (url.startsWith('/api/v1/channels/') && method === 'PUT') { + bodies.push(body); + } + return null; + } + }); + // channel fixture must have watermarkId: 9 (the NON-first preset by name order) + render(); + + fireEvent.click(await screen.findByRole('tab', { name: /Branding/ })); + expect(screen.getByRole('switch', { name: /Use logo as on-screen bug/ })).toHaveAttribute( + 'aria-checked', + 'true' + ); + + fireEvent.click(screen.getByRole('button', { name: /Save/ })); + await waitFor(() => expect(bodies).toHaveLength(1)); + expect((bodies[0] as { watermarkId: null | number }).watermarkId).toBe(9); + }); + + // The guarantee protecting the existing production channels. + it('leaves watermarkId unchanged when an untouched channel is re-saved', async () => { + const bodies: unknown[] = []; + mockApi({ + onRequest: (url, method, body) => { + if (url === '/api/v1/watermarks' && method === 'GET') { + return jsonResponse([ + { id: 2, imageSource: 'Custom', name: 'Sponsor bug' }, + { id: 9, imageSource: 'ChannelLogo', name: 'Channel Bug' } + ]); + } + if (url.startsWith('/api/v1/channels/') && method === 'PUT') { + bodies.push(body); + } + return null; + } + }); + // channel fixture must have watermarkId: 2 (a NON-ChannelLogo watermark) + render(); + + fireEvent.click(await screen.findByRole('tab', { name: /Branding/ })); + expect(screen.getByRole('switch', { name: /Use logo as on-screen bug/ })).toHaveAttribute( + 'aria-checked', + 'false' + ); + + // change something unrelated so the form is dirty and Save is enabled + fireEvent.click(screen.getByRole('tab', { name: /General/ })); + fireEvent.change(screen.getByDisplayValue(/./), { target: { value: 'Renamed channel' } }); + fireEvent.click(screen.getByRole('button', { name: /Save/ })); + + await waitFor(() => expect(bodies).toHaveLength(1)); + expect((bodies[0] as { watermarkId: null | number }).watermarkId).toBe(2); + }); ``` -If the Branding section is selected by something other than `role="tab"`, read `SECTIONS`/the nav markup and use the real selector. +If the Branding section is selected by something other than `role="tab"`, read `SECTIONS`/the nav markup and use the real selector. For the last test, read the General pane and pick a concrete, unambiguous field to dirty (the placeholder `getByDisplayValue(/./)` above will match several inputs — replace it with the channel-name input's real selector). - [ ] **Step 2: Run the tests to verify they fail** @@ -697,49 +855,105 @@ Expected: FAIL — no element with role `switch` named "Use logo as on-screen bu - [ ] **Step 3: Implement the toggle** -Add `BugPreview` to the existing `'../components'` import (line 15 — `Switch` is already imported). Inside `BrandingPane`, after the `previewSrc` line (`:673`), add: +**5a.** Add the shared selector to `web/src/api/watermarks.ts` and export it from the `'../api'` barrel: -```tsx - const logoBugWatermark = data.watermarks.find((watermark) => watermark.imageSource === 'ChannelLogo') ?? null; - const logoBugEnabled = logoBugWatermark != null && draft.watermarkId === logoBugWatermark.id; +```ts +// Identifies THE default logo-driven preset. imageSource alone is not enough once a second +// ChannelLogo preset exists (the design invites creating one for per-channel geometry), and +// getWatermarks() sorts by name — so prefer the seeded name, then fall back deterministically. +export function findLogoBugWatermark( + watermarks: T[] +): T | null { + const logoDriven = watermarks.filter((watermark) => watermark.imageSource === 'ChannelLogo'); + return logoDriven.find((watermark) => watermark.name === 'Channel Bug') ?? logoDriven[0] ?? null; +} ``` -Then insert this Row immediately after the "External logo URL" Row and before the "Watermark" Row: +**5b.** Add `BugPreview` to the existing `'../components'` import (line 15 — `Switch` is already imported) and `findLogoBugWatermark`, `getWatermark` to the `'../api'` import. Inside `BrandingPane`, after the `previewSrc` line (`:673`), add: + +```tsx + // Reflect the referenced row — never a search — so a channel bound to a second ChannelLogo + // preset reads correctly and is never silently repointed. + const referenced = data.watermarks.find((watermark) => watermark.id === draft.watermarkId) ?? null; + const logoBugEnabled = referenced?.imageSource === 'ChannelLogo'; + const logoBugTarget = findLogoBugWatermark(data.watermarks); + // An external-URL logo is resolved by WatermarkSelector to the URL itself and then File.Exists-ed, + // which is never true, so no bug renders (#502). Don't promise one in the preview. + const externalUrlLogo = trimmedUrl.length > 0; + + const [bugGeometry, setBugGeometry] = useState(null); + + useEffect(() => { + if (!logoBugEnabled || draft.watermarkId == null) { + setBugGeometry(null); + return; + } + + let cancelled = false; + void getWatermark(draft.watermarkId) + .then((watermark) => { + if (!cancelled) { + setBugGeometry({ + horizontalMargin: watermark.horizontalMargin, + location: watermark.location, + opacity: watermark.opacity, + size: watermark.size, + verticalMargin: watermark.verticalMargin, + width: watermark.width + }); + } + }) + .catch(() => { + if (!cancelled) { + setBugGeometry(null); + } + }); + + return () => { + cancelled = true; + }; + }, [draft.watermarkId, logoBugEnabled]); +``` + +Import `useEffect`/`useState` (already imported at `:1`) and `type BugPreviewGeometry` from `'../components'`. + +**5c.** Insert this Row immediately after the "External logo URL" Row and before the "Watermark" Row: ```tsx
set({ watermarkId: next ? (logoBugWatermark?.id ?? null) : null })} + onChange={(next) => set({ watermarkId: next ? (logoBugTarget?.id ?? null) : null })} size="sm" /> - {logoBugEnabled && previewSrc && ( - + {logoBugEnabled && bugGeometry && previewSrc && !externalUrlLogo && ( + )}
``` -**Known limitation, state it in the PR:** the picker DTO carries only `id`/`name`/`imageSource`, so this preview uses the seeded preset's default geometry rather than the row's live values. Fetching `GET /api/v1/watermarks/{id}` here to read the real geometry is a reasonable follow-up; do NOT widen the picker DTO further in this PR. +Check the rendered result for a duplicated caption — the `Row` supplies a visible `label` and `Switch` also renders its `label` prop when set. If both show, keep `Switch`'s for accessibility but render it visually hidden, or pass the accessible name another way; do not simply delete it, as the tests select the switch by accessible name. - [ ] **Step 4: Run the tests to verify they pass** @@ -764,7 +978,7 @@ git commit -m "feat(67): add Use logo as on-screen bug toggle with preview to th - Test: `web/src/screens/ChannelsScreen.test.tsx` (extend) **Interfaces:** -- Consumes: `getWatermarks()` (`web/src/api/pickers.ts`) returning `Watermark[]` with `imageSource` (Task 2). +- Consumes: `getWatermarks()` (`web/src/api/pickers.ts`) returning `Watermark[]` with `imageSource` (Task 2), and `findLogoBugWatermark()` from Task 5a. **Use that shared helper — do not re-implement the lookup here**, or the two paths will drift apart (a plain `.find(imageSource === 'ChannelLogo')` binds to the alphabetically-first preset, since `getWatermarks()` sorts by name). - Behavior: the create body's `watermarkId` becomes the logo-driven preset's id when one exists, else stays `null`. **Never fail channel creation because the lookup failed** — a watermark-list error must degrade to `null`, not abort. - **Scope note — do NOT also change `web/src/builder/ChannelBuilder.tsx`.** That flow inherits `watermarkId` from the selected `ChannelTemplate` (`:1025` `eff('watermarkId')`, `:2046`), so "defaulting" it would mean stamping the preset onto the seeded `Standard` / `Music videos` template rows. Those are user-editable and the seed's name-guard leaves them alone on existing installs, so the change would be a no-op on production while mutating fresh installs' data. Template-driven inheritance is the intended mechanism there. See the spec's §4 exclusion. @@ -796,6 +1010,29 @@ Append to `web/src/screens/ChannelsScreen.test.tsx` (read its existing `mockApi` }); ``` + it('still creates the channel when the watermark lookup fails', async () => { + const bodies: unknown[] = []; + mockApi({ + onRequest: (url, method, body) => { + if (url === '/api/v1/watermarks' && method === 'GET') { + return new Response(null, { status: 500 }); + } + if (url === '/api/v1/channels' && method === 'POST') { + bodies.push(body); + return jsonResponse({ id: 42 }, 201); + } + return null; + } + }); + render(); + + fireEvent.click(await screen.findByRole('button', { name: /New Channel/ })); + + await waitFor(() => expect(bodies).toHaveLength(1)); + expect((bodies[0] as { watermarkId: null | number }).watermarkId).toBeNull(); + }); +``` + Use the real button label from the screen — read it, do not assume `/New Channel/`. - [ ] **Step 2: Run the test to verify it fails** @@ -807,15 +1044,14 @@ Expected: FAIL — `expected null to be 9`. - [ ] **Step 3: Implement the default** -Add `getWatermarks` to the existing import from `'../api'`. In `createBlankChannel`, after the `getFfmpegSettings()` call, add: +Add `findLogoBugWatermark` and `getWatermarks` to the existing import from `'../api'`. In `createBlankChannel`, after the `getFfmpegSettings()` call, add: ```tsx // New channels default to the seeded logo-driven preset so one uploaded logo drives both the // guide listing and the on-screen bug (#67). A lookup failure must not block channel creation. let watermarkId: null | number = null; try { - const watermarks = await getWatermarks(); - watermarkId = watermarks.find((watermark) => watermark.imageSource === 'ChannelLogo')?.id ?? null; + watermarkId = findLogoBugWatermark(await getWatermarks())?.id ?? null; } catch { watermarkId = null; } @@ -864,9 +1100,21 @@ per-channel state. Permanent, TopLeft, Scaled 5% width, 1%/1% margins, 80% opacity). Because `ChannelLogo` resolves each channel's own `ArtworkKind.Logo` artwork at render time, this single row makes every channel that points at it use its own logo as its on-screen bug — one uploaded image drives both the guide -listing and the bug (#67). The seed is name-guarded: an existing `Channel Bug` row is adopted -untouched, never overwritten. New channels created in the SPA default to it; the channel editor's -Branding tab exposes it as a "Use logo as on-screen bug" toggle. +listing and the bug (#67). An existing `Channel Bug` row is adopted untouched, never overwritten, and +a `ConfigElement` marker (`watermark.channel_bug_seeded`) makes the seed run once per database, so a +deliberately deleted preset is not resurrected on the next restart. + +Quick-add channel creation defaults to the preset, and the channel editor's Branding tab exposes it +as a "Use logo as on-screen bug" toggle. On a **fresh** install the seed also stamps the preset onto +the system channel templates it creates, so the library-to-lineup builder (which inherits +`WatermarkId` from the selected template) gets the default too. On an existing install the templates +are left alone, so builder-created and auto-tuned channels there inherit whatever the template +already specifies. + +**Limitation:** a logo set via **External logo URL** cannot drive the bug. `WatermarkSelector` +resolves it to the URL and then `File.Exists`-checks it, which is never true, so the watermark is +silently dropped — the URL wins for the guide listing but disables the on-screen bug. Tracked as +**#502**; the editor does not offer a bug preview in that case. Note: `ChannelLogoGenerator.GenerateChannelLogoUrl()` hardcodes `localhost` for watermark logo fetching — see issue #1 for details. @@ -890,16 +1138,29 @@ entity, so per-channel geometry would need either a dual-provider migration or o channel (under a unique-name index). Since `ChannelLogo` resolves per channel at render time, a single shared row already delivers the user-visible behavior with no schema change. -- The seed is name-guarded and **adopts** an existing `Channel Bug` row untouched, so an operator's - tuned geometry is never overwritten. Covered by `DbInitializerChannelBugWatermarkTests`. +- The seed **adopts** an existing `Channel Bug` row untouched, so an operator's tuned geometry is never + overwritten, and a `ConfigElement` marker (`watermark.channel_bug_seeded`) makes it run once per + database rather than once per name-absence — `ChannelWatermark` has no `IsSystem` flag and + `DbInitializer.Initialize` runs at every startup, so a name-only guard would resurrect a deliberately + deleted preset forever. Covered by `DbInitializerChannelBugWatermarkTests`. - `WatermarkResponseModel` gained `imageSource` (additive under the frozen `/api/v1`, #286) so clients - identify logo-driven presets generically instead of matching a user-editable name. -- The default is applied by the SPA's **creation** paths, not by inferring "newness" in the editor — - quick-add creates through the API and then navigates to the editor, so the editor only ever loads an - existing row. The editor toggle is a pure reflection of stored `watermarkId`. + identify logo-driven presets generically instead of matching a user-editable name. Note the limit: + once a *second* logo-driven preset exists, `imageSource` identifies the class but not *the* default, + so `findLogoBugWatermark` prefers the seeded name as a deterministic tiebreak. +- The default is applied by the SPA's quick-add **creation** path, not by inferring "newness" in the + editor — quick-add creates through the API and then navigates to the editor, so the editor only ever + loads an existing row. The editor toggle reflects the **referenced** watermark's `imageSource`; an + earlier draft searched the list instead, which (because `getWatermarks()` sorts by name) would have + silently repointed channels bound to a non-first logo-driven preset. Caught in independent review + and pinned by a regression test. +- The builder flow is covered on **fresh installs only**, by stamping the preset onto the system + channel templates the seed itself creates; existing installs' templates are never mutated. - Server-side create defaulting was rejected: making an omitted `watermarkId` mean "give me a watermark" would surprise machine clients of the frozen API. `POST /api/v1/channels/auto-tune` is therefore unchanged. +- **Not fixed here:** external-URL logos never render a bug (`WatermarkSelector` `File.Exists`-checks a + URL). Pre-existing, lands in the FFmpeg render path, tracked as **#502**. This change only stops the + preview from promising it. **Accepted trade-off:** every channel on the shared preset shares one geometry; per-channel tweaks mean creating a second preset on the Watermarks screen. diff --git a/docs/superpowers/specs/2026-07-20-unified-logo-bug-design.md b/docs/superpowers/specs/2026-07-20-unified-logo-bug-design.md index f8cd12ce7..4b444427d 100644 --- a/docs/superpowers/specs/2026-07-20-unified-logo-bug-design.md +++ b/docs/superpowers/specs/2026-07-20-unified-logo-bug-design.md @@ -65,12 +65,24 @@ creating a second preset — which the existing Watermarks screen already suppor ## 3. Backend `DbInitializer.SeedChannelBugWatermark(context, cancellationToken)`, invoked from `Initialize` -alongside the existing `SeedChannelTemplates` call (`ErsatzTV.Infrastructure/Data/DbInitializer.cs:134`), -following that method's idempotent name-guard pattern (`:140-186`): +**before** the existing `SeedChannelTemplates` call (`ErsatzTV.Infrastructure/Data/DbInitializer.cs:134`) +so the seeded watermark's id is available to the template seed. It returns `int?` — the preset's id. -- If a `ChannelWatermark` named `Channel Bug` already exists → **return without touching it.** An - existing hand-made row (as on prod) is adopted, never duplicated and never overwritten. +- If a `ChannelWatermark` named `Channel Bug` already exists → **adopt it untouched**, never + duplicated and never overwritten. An operator's tuned geometry (as on prod) survives. - Otherwise insert one row with the geometry in §1. +- **Seed-once marker.** `ChannelWatermark` has no `IsSystem` flag (unlike `ChannelTemplate`), so a + pure name-guard would resurrect the row on every restart after a deliberate delete or rename. A + `ConfigElement` marker (`ConfigElementKey.WatermarkChannelBugSeeded`, key + `watermark.channel_bug_seeded`) is written on first seed **or adopt**; once present, the seed is a + no-op. This follows the file's own `EnsureDefaultChannelTemplateConfig` precedent (`:210-231`). + A deliberate delete stays deleted. + +`SeedChannelTemplates` takes the returned id and stamps it as `WatermarkId` on the **newly seeded** +system templates (`ChannelTemplate.WatermarkId`, `ErsatzTV.Core/Domain/ChannelTemplate.cs:14`). This +only ever touches rows the seed is creating for the first time — the existing name-guard means an +install that already has `Standard` / `Music videos` is untouched, so no operator's template is +mutated. No schema change. No `WatermarkSelector` change. No change to how watermarks render. @@ -89,18 +101,35 @@ user-editable name. Legal under frozen-additive `/api/v1`; also useful to MCP/ma reliably tell "new" from "existing". The default is therefore applied at the SPA's quick-add creation path — `ChannelsScreen.tsx:377`, which currently hardcodes `watermarkId: null` — by setting `watermarkId` to the seeded preset at create time. -- **The `ChannelBuilder` lineup flow is deliberately excluded.** It does not hardcode a watermark: it - *inherits* `watermarkId` from the selected `ChannelTemplate` (`web/src/builder/ChannelBuilder.tsx:1025`, - `:2046`). Defaulting it would mean stamping the preset onto the seeded `Standard` / `Music videos` - templates — user-editable rows that the name-guard intentionally leaves alone on existing installs, - so it would silently do nothing on production anyway. Template-driven inheritance is the documented - mechanism for that flow; a user who wants it sets the watermark on the template. -- **`ChannelEditScreen`** (Branding tab, `:55`): a **"Use logo as on-screen bug"** toggle that purely - reflects and edits the stored `watermarkId` — ticked when it points at a `ChannelLogo`-sourced - preset, unticked when `null`. Toggling writes the preset id or `null`. Because it is a pure - reflection of stored state, loading and re-saving an existing channel never changes its watermark. - A `` beneath it is fed by the draft logo (local object URL or - `draft.logo.urlWithContentType`), so the bug is visible before saving. +- **The `ChannelBuilder` lineup flow is covered via template stamping** (revised after independent + review). It does not hardcode a watermark: it *inherits* `watermarkId` from the selected + `ChannelTemplate` (`web/src/builder/ChannelBuilder.tsx:1025`, `:2046`). Because §3's seed stamps the + preset onto templates **it is creating for the first time**, a fresh install gets the default through + both creation flows with no user data mutated. On an existing install (including production) the + template name-guard means nothing is stamped, so builder-created channels there keep inheriting + whatever the template already says — a user who wants it sets the watermark on the template. + `POST /api/v1/channels/auto-tune` is unchanged either way. +- **`ChannelEditScreen`** (Branding tab, `:55`): a **"Use logo as on-screen bug"** toggle. Loading and + re-saving an existing channel never changes its watermark. + - **Reflect from the referenced row, not from a search.** Ticked iff the watermark + `draft.watermarkId` *points at* has `imageSource === 'ChannelLogo'`. An earlier draft searched the + list for the first `ChannelLogo` preset; because `getWatermarks()` sorts by name + (`web/src/api/pickers.ts:14`), that silently repointed a channel to the alphabetically-first + logo-driven preset the moment a second one existed — which this design's own trade-off invites + users to create. Caught in independent review. + - **Tick-on target is deterministic**: prefer the preset named `Channel Bug`, else the first + `ChannelLogo` preset. With multiple logo-driven presets, `imageSource` alone cannot identify *the* + default, so a name preference is unavoidable here; it is a tiebreak, not the identification + mechanism. + - **The preview shows the referenced preset's real geometry**, fetched via the existing + `GET /api/v1/watermarks/{id}` when the toggle is on. Hardcoding the seeded defaults would show + the wrong position and size for exactly the users who tuned theirs — the case this feature exists + to serve. + - **External-URL logos get no bug preview.** `WatermarkSelector` resolves an external-URL logo to + the URL itself and then calls `File.Exists` on it (`ErsatzTV.Core/FFmpeg/WatermarkSelector.cs:269-286`), + which is never true, so the bug is silently dropped. The preview must not promise a bug that will + never render; the toggle's help text and `docs/channels.md` say so. The underlying defect is + pre-existing and tracked in its own issue, not fixed here. - **Batch auto-tune (`POST /api/v1/channels/auto-tune`) is left alone** — it is a server-side create, and the rejected "server-side default on create" option is what would have changed it. - **`WatermarksScreen`**: the raw `` at `:534-539` is replaced by ``. @@ -112,10 +141,17 @@ Existing logo-upload and external-URL-precedence behavior (`docs/decisions.md:45 - **NUnit**, mirroring `ErsatzTV.Tests/Infrastructure/DbInitializerChannelTemplateTests.cs`: seeds the preset when absent; **adopts an existing same-name row without duplicating or mutating it** (the production case — this test is what protects the operator's tuned geometry); is - idempotent across repeated `Initialize` calls. -- **Vitest**: `BugPreview` geometry mapping across all 9 locations, plus opacity/size/margins; the - toggle's `watermarkId` wiring, including that loading and re-saving an existing channel without - touching the toggle leaves `watermarkId` unchanged, and that the creation paths stamp the preset. + idempotent across repeated `Initialize` calls; **does not resurrect a deleted preset** once the + seed marker exists; stamps `WatermarkId` on freshly seeded templates only. +- **Vitest**: `BugPreview` geometry mapping across all 9 locations, plus opacity/size/margins. For the + toggle: + - **loading and re-saving an existing channel without touching the toggle leaves `watermarkId` + byte-identical** — the guarantee protecting the 43 production channels, and the test the first + draft of this plan promised but omitted; + - with **two** `ChannelLogo` presets, a channel pointing at the non-first one still reads as ticked + and is not repointed (the review's blocker, pinned by a regression test); + - the creation path stamps the preset, and **degrades to `null` rather than aborting** when the + watermark lookup fails. ## 6. Docs to update in the same PR @@ -130,6 +166,11 @@ Per `CLAUDE.md`'s docs-update rule: ## 7. Out of scope - Any dual-provider migration. +- **Fixing the external-URL-logo defect.** `WatermarkSelector.cs:269-286` resolves an external-URL + logo to the URL and then `File.Exists`-checks it, so such channels never render a bug even though + the editor advertises the URL as winning. Pre-existing, unrelated to this change, and a fix lands in + the FFmpeg render path — a different risk class than this seed-plus-SPA PR. Tracked as **#502**; + this PR only stops the preview from promising it. - The dead generated-initials FFmpeg fallback: `WatermarkSelector.cs:230-236` runs `File.Exists` against a URL produced by `ChannelLogoGenerator.GenerateChannelLogoUrl`, which hardcodes localhost (`ChannelLogoGenerator.cs:93-94`, issue #1). Deliberately deferred in `docs/decisions.md:1617-1623`.