diff --git a/docs/guides/collections.md b/docs/guides/collections.md index a048782..d40a844 100644 --- a/docs/guides/collections.md +++ b/docs/guides/collections.md @@ -14,7 +14,9 @@ when provisioning begins. For example, a collection targeting four Kino and two Der Riese lobbies, with two Kino already registered, creates two Kino and two Der Riese lobbies. -The preview shows **Target / Existing or queued / To create** for each map. +The preview groups maps by game and shows **Target / Existing or queued / +Create** for each map, with **Remove** in exact mode. Existing totals in exact +mode include the listed removals, including those already awaiting cleanup. Matching is by game and exact map variant; T6 Town and Farm are distinct even though they share an engine map. Provisioning identities are counted once when they appear in both the server registry and active creation queue. @@ -30,15 +32,24 @@ It fills deficits without changing existing servers' files. 1. Choose **Create collection** on **Fleet → Collections** and name the lineup. 2. Add maps from Black Ops I or II and set the desired total lobbies for each. 3. Choose **Save & preview** (or **Preview fleet changes** on a saved collection). - Choose **Fill missing servers** or **Match collection exactly**, then review - the server IDs and estimated capacity. Native host ports are assigned later. -4. Launches covered by unused keys show **Game key available**. Each game’s - available keys are counted once across the full lineup. If more keys are - needed, add them under **Administration → Keys**, then refresh the preview. - Launch is enabled when every new server has an available game key. -5. Choose **Queue N servers** (or confirm removals and choose **Apply** in exact - mode) and follow the collection progress page. - If every target is already met, choose **Done**; no operation is created. + The dialog prepares its preview automatically. Both **Fill missing** + and **Match exactly** are visible; selecting a mode rechecks the + plan. Review the change summary and the map table grouped by game. +4. Check the required key coverage for each game. Available keys count once + across the full lineup, and every new server needs a key. If a game is short, + open **Administration → Keys** to add keys or wait for assigned keys to be + released. Returning to the dialog rechecks the pools and fleet. +5. Review the capacity summary. Expand its details for CPU, memory, ports, and + startup slots. Capacity estimates are advisory: queued launches can wait for + hosts or resources. Native host ports are assigned during provisioning. +6. Expand **Server details** to inspect server IDs, launch order, retained servers, + and existing-server health. **Advanced settings** holds the runtime override; + **Setup details** shows configuration, managed files, and game-file upload + information. +7. Use **Queue N servers** in the persistent footer, or review and confirm + the removal list before choosing **Create N · Remove M** when removals are + needed. Follow the collection progress page after submission. If no changes are needed, + choose **Done**; no operation is created. ### Match collection exactly @@ -49,9 +60,10 @@ variant. It removes excess lobbies and maps outside the collection. Retained servers keep their containers, files, ports, and configuration without a restart. The option is chosen per launch; opening another preview defaults to fill mode. -Review the removal list and check its confirmation before applying. Removed -servers lose their containers, files, and registrations; their keys return to the -game pool only after confirmed removal. +The removal list stays visible in exact mode. Review it and check its confirmation +before applying. Every refreshed preview clears that confirmation so it must be +reviewed again. Removed servers lose their containers, files, and registrations; +their keys return to the game pool only after confirmed removal. Unstarted creations are cancelled without booting a container. Running servers use the normal removal queue and require a fresh zero-player RCON response. Occupied or unreachable servers wait. Already pending removals are reused. @@ -94,6 +106,11 @@ when preparing new launches. ### Preview and submission +A preview runs automatically when the dialog opens, the mode or launch settings +change, the user returns from managing keys, or the current preview expires. +Refreshing also resets removal confirmation. The preview lasts 30 minutes; +checks and displayed counts describe the fleet when it was prepared. + A native collection preview reads a shared capacity snapshot, maintained from host heartbeats and fleet changes. It estimates available ports, CPU, memory, and startup slots without running placement for each server. Missing or insufficient capacity @@ -107,11 +124,15 @@ no jobs or key reservations from that submission are committed. Legacy submissio also revalidate their reviewed ports. Refreshing the preview rechecks pool availability and resets removal confirmation. -Submitting the same preview again returns the same collection, including after -a lost response or an application restart. Reusing the collection with a new -preview recomputes the shortfall, including servers queued by earlier launches. -It does not add another full copy of the lineup. If the shortfall or reviewed -identities change before submission, the request is rejected without changes and +If a submission response is lost or cannot be confirmed, retry that same +submission. The dialog keeps the reviewed preview while the outcome is uncertain +instead of automatically replacing it. If the original request committed, +submitting the same preview again returns the same collection, including after +its original expiry or an application restart, without repeating operations. + +Reusing the collection with a new preview recomputes the shortfall, including +servers queued by earlier launches. It does not add another full copy of the +lineup. If the shortfall or reviewed identities change before submission, the request is rejected without changes and requires a fresh preview. Previously saved additive previews are checked against the current shortfall too. diff --git a/docs/guides/provisioning.md b/docs/guides/provisioning.md index af9edd6..0de2ae0 100644 --- a/docs/guides/provisioning.md +++ b/docs/guides/provisioning.md @@ -14,6 +14,14 @@ managed files, upload time, and internal server ID are under **Setup details**. The footer keeps **Cancel** and **Launch server** available while reviewing the setup. Create and launch reusable lineups separately in **Fleet → Collections**. +Collection launches prepare their fleet preview automatically and show fill and +exact modes together. Review changes and game key coverage, then use the +persistent footer to queue work. Capacity estimates are advisory; jobs can wait +for hosts and resources. Exact mode covers both games and requires confirmation +of its explicit removal list, which resets whenever the preview is refreshed. +See [Collections](collections.md) for the review details and safe submission +retries when a response is lost. + | Action | Behavior | | --- | --- | | Create | Create a new instance using the latest promoted files and verify container health, game status, the selected map, and the Plutonium revision. | diff --git a/src/lib/ui/collection-launch.ts b/src/lib/ui/collection-launch.ts new file mode 100644 index 0000000..426223c --- /dev/null +++ b/src/lib/ui/collection-launch.ts @@ -0,0 +1,157 @@ +import type { CollectionMode, CollectionPreview } from '../deployment-plan.js'; +import type { ZombieGame } from '../map-aliases.js'; + +export interface CollectionLaunchInput { + blueprintId: string; + mode: CollectionMode; + libraryIds: Partial>; + image: string; +} + +export interface CollectionLaunchState { + preview: CollectionPreview | null; + checking: boolean; + error: string; + changeNotice: string; +} + +function changesSince(previous: CollectionPreview | null, next: CollectionPreview): string { + if (!previous) return ''; + const sorted = (values: unknown[]) => JSON.stringify(values.map(value => JSON.stringify(value)).sort()); + const removals = (preview: CollectionPreview) => sorted(preview.removals.map(server => [server.name, server.reason])); + const creations = (preview: CollectionPreview) => sorted(preview.servers.map(server => { + const recipe = preview.entries[server.entryIndex]?.recipe; + return [server.name, recipe?.game, recipe?.mapSlug]; + })); + const retained = (preview: CollectionPreview) => sorted([...new Set(preview.retainedServers)]); + if (removals(previous) !== removals(next)) { + return 'Servers to remove changed. Review the updated removal list before applying this collection.'; + } + const createsChanged = creations(previous) !== creations(next); + const keepsChanged = retained(previous) !== retained(next); + if (createsChanged && keepsChanged) return 'Servers to create and keep changed. Review the updated fleet changes before applying.'; + if (createsChanged) return 'Servers to create changed. Review the updated launch list before applying.'; + if (keepsChanged) return 'Servers to keep changed. Review the updated fleet changes before applying.'; + return ''; +} + +/** Refresh collection plans without retaining a launchable preview while its inputs are changing. */ +export function createCollectionLaunchController( + onChange: (state: CollectionLaunchState) => void, + dependencies: { fetch?: typeof fetch; debounceMs?: number } = {}, +) { + const fetchPreview = dependencies.fetch ?? ((...args: Parameters) => fetch(...args)); + const debounceMs = dependencies.debounceMs ?? 200; + let selection: string | null = null; + let context: string | null = null; + let previous: CollectionPreview | null = null; + let state: CollectionLaunchState = { preview: null, checking: false, error: '', changeNotice: '' }; + let revision = 0; + let timer: ReturnType | undefined; + let request: AbortController | undefined; + let suspended = false; + let disposed = false; + + function publish(next: CollectionLaunchState) { + if (state.preview === next.preview && state.checking === next.checking + && state.error === next.error && state.changeNotice === next.changeNotice) return; + state = next; + onChange(next); + } + + function cancel() { + revision++; + clearTimeout(timer); + timer = undefined; + request?.abort(); + request = undefined; + } + + async function check(current: number) { + if (disposed || suspended || current !== revision || !selection) return; + timer = undefined; + const controller = new AbortController(); + request = controller; + try { + const response = await fetchPreview('/api/deployment-collections/preview', { + method: 'POST', headers: { 'Content-Type': 'application/json' }, body: selection, signal: controller.signal, + }); + const body = await response.json(); + if (disposed || suspended || current !== revision) return; + if (!response.ok) throw new Error(body.error ?? 'Could not check collection readiness. Try again.'); + const preview = body as CollectionPreview; + const expiresAt = Date.parse(preview.expiresAt); + if (!Number.isFinite(expiresAt) || expiresAt <= Date.now()) throw new Error('The collection check expired. Try again.'); + const changeNotice = changesSince(previous, preview); + previous = preview; + publish({ preview, checking: false, error: '', changeNotice }); + if (!disposed && !suspended && current === revision) { + timer = setTimeout(refresh, Math.min(expiresAt - Date.now(), 2_147_483_647)); + } + } catch (error) { + if (!disposed && !suspended && current === revision) { + publish({ preview: null, checking: false, changeNotice: '', + error: error instanceof Error ? error.message : 'Could not check collection readiness. Try again.' }); + } + } finally { + if (current === revision) request = undefined; + } + } + + function refresh() { + if (disposed || !selection || (request && !suspended)) return; + suspended = false; + cancel(); + publish({ preview: null, checking: true, error: '', changeNotice: '' }); + void check(revision); + } + + function invalidate() { + cancel(); + selection = null; + suspended = false; + publish({ preview: null, checking: false, error: '', changeNotice: '' }); + } + + return { + /** A null selection pauses checks during host reloads while preserving the last plan for comparison. */ + select(input: CollectionLaunchInput | null) { + if (disposed) return; + if (!input) { invalidate(); return; } + const nextContext = JSON.stringify([input.blueprintId, input.mode]); + const next = JSON.stringify({ blueprintId: input.blueprintId, mode: input.mode, + libraryIds: { t5: input.libraryIds.t5, t6: input.libraryIds.t6 }, image: input.image }); + if (selection === next) return; + cancel(); + if (context !== nextContext) previous = null; + context = nextContext; + selection = next; + suspended = false; + publish({ preview: null, checking: true, error: '', changeNotice: '' }); + const current = revision; + timer = setTimeout(() => void check(current), debounceMs); + }, + refresh, + /** Start a fresh dialog session without comparing it with any earlier plan. */ + clear() { + if (disposed) return; + previous = null; + context = null; + invalidate(); + }, + /** Preserve the reviewed ID during submission; refresh() resumes after a definite rejection. */ + suspend() { + if (disposed) return; + suspended = true; + cancel(); + publish({ ...state, checking: false }); + }, + dispose() { + cancel(); + selection = null; + previous = null; + context = null; + disposed = true; + }, + }; +} diff --git a/src/lib/ui/collection-summary.ts b/src/lib/ui/collection-summary.ts new file mode 100644 index 0000000..49ddfa8 --- /dev/null +++ b/src/lib/ui/collection-summary.ts @@ -0,0 +1,109 @@ +import type { CollectionPreview, LaunchAvailability } from '../deployment-plan.js'; +import { parseServerName, selectedZombieMap, type ZombieGame } from '../map-aliases.js'; + +const gameLabels: Record = { t5: 'Black Ops I', t6: 'Black Ops II' }; + +export interface CollectionMapRow { + key: string; + mapName: string; + target: number; + existing: number; + create: number; + remove: number; +} + +export interface CollectionMapGroup { + game: ZombieGame | null; + label: string; + rows: CollectionMapRow[]; +} + +export interface CollectionKeyCoverage { + game: ZombieGame; + label: string; + required: number; + /** Reviewed creations covered by their game pool, not the pool's total size. */ + available: number; + /** Creations without lobby identities have not been checked against the pool. */ + unassigned: number; +} + +/** Keep pool coverage separate for each game, including creations without a free lobby. */ +export function collectionKeyCoverage(preview: CollectionPreview): CollectionKeyCoverage[] { + const coverage = new Map(); + for (const server of preview.servers) { + const game = preview.entries[server.entryIndex].recipe.game; + const pool = coverage.get(game) ?? { game, label: gameLabels[game], required: 0, available: 0, unassigned: 0 }; + pool.required++; + if (!server.name) pool.unassigned++; + else if (server.hasSavedKey) pool.available++; + coverage.set(game, pool); + } + return [...coverage.values()].sort((a, b) => a.game.localeCompare(b.game)); +} + +function removalMap(name: string): { game: ZombieGame | null; key: string; mapName: string } { + const parsed = parseServerName(name); + const game = parsed?.game.toLowerCase(); + const supportedGame = game === 't5' || game === 't6' ? game : null; + if (parsed && supportedGame && (!parsed.gameMode || parsed.gameMode === 'zombie')) { + // Resolve friendly legacy aliases without merging T6 variants that share an engine map. + const map = selectedZombieMap(supportedGame, parsed.mapCanonical, parsed.mapSlug); + if (map) return { game: supportedGame, key: `${supportedGame}:${map.slug}`, mapName: map.friendly }; + } + // A raw identity is preferable to assigning an unknown server to the wrong map. + return { game: supportedGame, key: `${supportedGame ?? 'other'}:server:${name}`, mapName: name }; +} + +/** Summarize affected inventory, including exact-mode removals outside the saved collection. */ +export function collectionMapGroups(preview: CollectionPreview): CollectionMapGroup[] { + const groups = new Map(); + const rows = new Map(); + const existingNames = new Map>(); + const serverRows = new Map(); + const addRow = (game: ZombieGame | null, row: CollectionMapRow) => { + const group = groups.get(game) ?? { game, label: game ? gameLabels[game] : 'Other servers', rows: [] }; + group.rows.push(row); + groups.set(game, group); + rows.set(row.key, row); + existingNames.set(row.key, new Set()); + return row; + }; + + for (const entry of preview.entries) { + const { game, mapSlug, mapName } = entry.recipe; + const row = addRow(game, { key: `${game}:${mapSlug}`, mapName, target: entry.count, + existing: entry.existing, create: entry.missing, remove: 0 }); + for (const name of entry.existingServers) { + existingNames.get(row.key)!.add(name); + // Backend coverage knows stored map selections even when a name is nonstandard. + serverRows.set(name, row); + } + } + + if (preview.mode === 'exact') { + for (const { name } of preview.removals) { + const identity = removalMap(name); + const row = serverRows.get(name) ?? rows.get(identity.key) ?? addRow(identity.game, { + key: identity.key, mapName: identity.mapName, target: 0, existing: 0, create: 0, remove: 0, + }); + row.remove++; + const counted = existingNames.get(row.key)!; + // Coverage excludes pending removals. Include those identities in displayed inventory + // while counting ordinary excess servers only once. + if (!counted.has(name)) { row.existing++; counted.add(name); } + } + } + + return [...groups.values()].sort((a, b) => (a.game ?? 'z').localeCompare(b.game ?? 'z')); +} + +/** Capacity remains an estimate: insufficient capacity can wait in the startup queue. */ +export function collectionCapacitySummary(availability?: LaunchAvailability): string { + if (availability?.requested === 0) return 'No new server capacity needed.'; + if (!availability || availability.estimatedAvailable === null) return 'Capacity estimate unavailable; launches can wait for capacity.'; + if (availability.estimatedAvailable >= availability.requested) { + return availability.requested === 1 ? 'Estimated capacity for 1 server.' : `Estimated capacity for all ${availability.requested} servers.`; + } + return `Estimated capacity for ${availability.estimatedAvailable} of ${availability.requested} server${availability.requested === 1 ? '' : 's'}; launches can wait for capacity.`; +} diff --git a/src/lib/ui/components/DeployCollectionDialog.svelte b/src/lib/ui/components/DeployCollectionDialog.svelte index 5ccb4f9..c766307 100644 --- a/src/lib/ui/components/DeployCollectionDialog.svelte +++ b/src/lib/ui/components/DeployCollectionDialog.svelte @@ -1,188 +1,339 @@ - { if (isDialogBackdrop(event, dialog) && !busy) open = false; }} oncancel={event => { if (busy) event.preventDefault(); }} onclose={() => open = false}> -
-
Collection launch

{preview?.blueprintName ?? collectionName}

- - {#if open && games.length} { preview = null; confirmRemovals = false; }} />{/if} -

{mode === 'exact' ? 'Keep matching lobbies, add missing ones, and remove excess lobbies and maps outside this collection across both games.' : 'Create missing lobbies and keep all existing servers.'}

- {#if error}{/if} - {#if !preview}

{busy ? 'Preparing the collection…' : 'Review the fleet changes, capacity estimate, and game key availability. Queued launches wait automatically when hosts need more capacity or preparation.'}

{#if !busy}{/if} + +
+ {#if loadingError} + + + {:else if !loaded} +

Loading collection…

{:else} - {#if assignmentNotice}

{assignmentNotice}

{/if} - {#if expired}

This preview expired. Refresh before launch to recheck capacity and key availability.

{/if} -
{preview.mode === 'exact' ? `${preview.retainedServers.length} keep · ${preview.servers.length} create · ${preview.removals.length} remove` : preview.servers.length ? `${preview.servers.length} missing server${preview.servers.length === 1 ? '' : 's'} to create` : 'Collection already satisfied'} - {#each preview.entries as entry}{/each}
MapTargetExisting / queuedTo create
{entry.recipe.mapName} {entry.recipe.game.toUpperCase()}{entry.count}{entry.existing}{entry.missing}
-

Targets count inventory, including stopped servers; they do not mean every server is ready to play. {preview.mode === 'exact' ? 'Existing deployed lobbies are kept before queued creations, then the lowest lobby numbers. Retained servers are not changed or restarted.' : 'Only missing servers are created. Extra servers remain and existing servers are not updated.'}

- {#if preview.mode === 'exact' && preview.retainedServers.length}
Servers to keep ({preview.retainedServers.length})
    {#each preview.retainedServers as name}
  • {name}
  • {/each}
{/if} - {#if preview.mode === 'fill' && preview.entries.some(entry => entry.existing)}
Review existing servers{#each preview.entries.filter(entry => entry.existing) as entry}
{entry.recipe.mapName}: {entry.existing} existing

{[...new Set((entry.coverage ?? []).map(server => server.health))].map(health => `${entry.coverage.filter(server => server.health === health).length} ${health}`).join(', ')}

    {#each entry.coverage ?? [] as server}
  • {server.health === 'online' ? 'Healthy' : server.health}
  • {/each}
{/each}
{/if} +
+
+ Apply collection + + +
+

{mode === 'exact' ? 'Match the entire fleet across both games. Excess lobbies and maps outside this collection will be removed.' : 'Create missing lobbies. All existing servers and their settings stay as they are.'}

- {#if preview.availability && preview.servers.length} -
-

Latest reported capacity

- View capacity and history ↗ -

{preview.availability.estimatedAvailable === null ? 'An estimate is not available yet.' : `${preview.availability.estimatedAvailable} additional servers estimated to fit.`} {preview.availability.requested} requested.

-
-
CPU available
{preview.availability.cpuCoresAvailable === null ? 'Unknown' : `${preview.availability.cpuCoresAvailable.toFixed(1)} cores`}
-
Memory available
{preview.availability.memoryBytesAvailable === null ? 'Unknown' : `${(preview.availability.memoryBytesAvailable / 1024 ** 3).toFixed(1)} GiB`}
-
Ports available
{preview.availability.portsAvailable ?? 'Unknown'}
-
Startup slots
{preview.availability.startupSlots ?? 'Unknown'}{#if preview.availability.startupLimit !== null} / {preview.availability.startupLimit}{/if}
-
-

{preview.availability.updatedAt ? `Updated ${$timeFormat.dateTime(preview.availability.updatedAt)}.` : 'Waiting for host reports.'}{#if preview.availability.queued !== null} {preview.availability.queued} servers already queued.{/if} Provisioning checks capacity separately for each server before it starts.

-
- {/if} -

{preview.mode === 'exact' ? 'Review fleet changes' : preview.servers.length ? 'Your launch order' : 'Nothing to create'}

- {#each preview.blockers as blocker}{/each} - {#each preview.warnings ?? [] as warning}

{warning}

{/each} - {#if preview.servers.length || preview.removals.length} - {#if preview.servers.length}

Available keys are assigned automatically from each game’s pool. Apply saves the reviewed jobs and opens their progress page. Each launch waits for a startup slot and host capacity.

{/if} - {#if preview.servers.some(server => !server.hasSavedKey)}

There are not enough unused keys for these launches. Add keys to the affected game pools in Keys (opens in a new tab), then Refresh preview to enable launch.

{/if} - {#if preview.removals.length && preview.servers.some(server => !server.hasSavedKey)}

Keys held by servers awaiting removal are still in use. To reuse those keys, remove the servers first and refresh this preview after cleanup finishes.

{/if} -
{ event.preventDefault(); void launch(); }}> - {#if preview.removals.length} -
-

Remove {preview.removals.length} server{preview.removals.length === 1 ? '' : 's'}

-

Containers, files, and registrations will be removed after a fresh zero-player check. Busy or unreachable servers wait. Unstarted creations are cancelled. Saved keys are kept. New servers reusing these ports wait for removal to finish.

-
    {#each preview.removals as server}
  • {server.name}{server.reason}
  • {/each}
- -
- {/if} - {#if preview.servers.length} -
    - {#each preview.servers as server, index (server.name ?? `unavailable-${index}`)} -
  1. - -
    {#if index === 0 || preview.servers[index - 1].entryIndex !== server.entryIndex}{preview.entries[server.entryIndex].recipe.game.toUpperCase()} · {preview.entries[server.entryIndex].recipe.mapName}{/if}{#if server.name}{:else}{preview.entries[server.entryIndex].recipe.mapName}{/if}{server.name ?? 'No available lobby'} · {server.native ? 'Host and port assigned when provisioning starts' : server.port === null ? 'No available port' : `Port ${server.port}`}
    - {#if server.name} - {#if server.hasSavedKey}

    Game key available

    - {:else}

    No unused {preview.entries[server.entryIndex].recipe.game.toUpperCase()} key available

    {/if} - {/if} -
  2. + +
    + {#if preview} + {noChanges ? 'Collection targets met' : `${preview.servers.length} to create · ${preview.removals.length} to remove`} + {#if mode === 'exact' && preview.retainedServers.length}

    {preview.retainedServers.length} existing or queued servers kept.

    {/if} +
    + {#each keyCoverage as pool}= pool.required} class:warning={pool.available < pool.required}>{pool.game.toUpperCase()} keys: {pool.unassigned ? 'waiting for lobby availability' : `${pool.available} of ${pool.required} required available`}{/each} + {#if preview.servers.length}{hostStatus.filesReady ? 'Game files ready' : 'Game files preparing'}{/if} +
    + {#if preview.servers.length}

    {collectionCapacitySummary(preview.availability)}

    {/if} + {#if noChanges}

    {mode === 'exact' ? 'Your fleet already matches this collection.' : 'Your fleet meets or exceeds every target.'} Existing servers keep their current settings.

    {/if} + {:else}

    {checking ? 'Checking fleet changes…' : 'Resolve the issues below to check this collection.'}

    {/if} +
    + + {#if launchError}{/if} + {#if view.changeNotice}

    {view.changeNotice}

    {/if} + {#if hostStatus.error} + {:else if !hostStatus.loading && hostStatus.missingGames.length}

    Upload {hostStatus.missingGames.map(game => game.toUpperCase()).join(' and ')} game files before launching.

    Manage game files ↗
    + {:else if !hostStatus.loading && !imageValid}

    Enter a valid runtime image in Advanced settings.

    + {:else if view.error}{/if} + {#if missingKeys.length}
    + {#each missingKeys as pool}{@const shortfall = pool.required - pool.unassigned - pool.available}

    {pool.game.toUpperCase()} needs {shortfall} more unused key{shortfall === 1 ? '' : 's'}. Manage keys ↗

    {/each} + {#if preview?.removals.length}

    Keys assigned to removals stay in use until cleanup finishes. Complete those removals first to reuse their keys.

    {/if} +
    {/if} + {#each preview?.blockers ?? [] as blocker}{/each} + {#if !checking && !unconfirmedLaunch && (view.error || hostStatus.error || missingKeys.length || preview?.blockers.length)}{/if} + + {#if preview} +
    + {#each mapGroups as group} + + + {#if mode === 'exact'}{/if} + {#each group.rows as row}{#if mode === 'exact'}{/if}{/each} +
    {group.label}
    MapTargetExisting / queuedCreateRemove
    {row.mapName}{row.target}{row.existing} 0}>{row.create} 0}>{row.remove}
    {/each} -
- {/if} - -
- {:else}

{preview.mode === 'exact' ? 'Your fleet already matches this collection.' : 'Your fleet already meets or exceeds every target in this collection.'} No servers will be created or removed.

{/if} -
Setup and launch requirements

Each new server is automatically placed on an eligible host with the latest game files and prepared runtime. CPU, memory, host readiness, synced files, runtime availability, and local port reservations are checked again before deployment. Existing servers keep their current files.

{#each preview.entries as entry}
{/each}
+

Stopped and unhealthy servers also count toward targets. See Server details for health.{#if mode === 'exact'} Existing totals include the listed removals.{/if}

+ + + {#if preview.removals.length}
+

Remove {preview.removals.length} server{preview.removals.length === 1 ? '' : 's'}

+

Containers, files, and registrations will be removed. Occupied or unreachable servers wait for a fresh empty-player check; unstarted creations are cancelled.

+
    {#each preview.removals as server}
  • {serverTitle(server.name)}{server.name}{server.reason}
  • {/each}
+ +
{/if} + +
+ Server details +
+ {#if preview.servers.length}

Launch order

Hosts and ports are assigned when provisioning starts.

+
    {#each preview.servers as server}
  1. {server.name ? serverTitle(server.name) : preview.entries[server.entryIndex].recipe.mapName}{server.name ?? 'No available lobby'}
  2. {/each}
+ {/if} + {#if preview.entries.some(entry => entry.existing)}

Existing and queued servers

+
    {#each preview.entries as entry}{#each entry.coverage ?? [] as server}
  • {serverTitle(server.name)} ↗{server.health === 'online' ? 'Healthy' : server.health}{#if mode === 'exact'} · {preview.retainedServers.includes(server.name) ? 'Keep' : 'Remove'}{/if}
  • {/each}{/each}
+ {/if} + {#if !preview.servers.length && !preview.entries.some(entry => entry.existing)}

No new or matching servers.

{/if} +
+
+ + {#if preview.availability && preview.servers.length}
+ Capacity details +
+
+
CPU available
{preview.availability.cpuCoresAvailable === null ? 'Unknown' : `${preview.availability.cpuCoresAvailable.toFixed(1)} cores`}
+
Memory available
{preview.availability.memoryBytesAvailable === null ? 'Unknown' : `${(preview.availability.memoryBytesAvailable / 1024 ** 3).toFixed(1)} GiB`}
+
Ports available
{preview.availability.portsAvailable ?? 'Unknown'}
+
Startup slots
{preview.availability.startupSlots ?? 'Unknown'}{#if preview.availability.startupLimit !== null} / {preview.availability.startupLimit}{/if}
+
+ {#each preview.warnings ?? [] as warning}

{warning}

{/each} +

{preview.availability.updatedAt ? `Updated ${$timeFormat.dateTime(preview.availability.updatedAt)}.` : 'Waiting for host reports.'} Capacity is checked for each server when it starts.

+ View capacity and history ↗ +
+
{/if} + {/if} + + {#if open}{/if} + + {#if preview}
+ Setup details +
+

New servers use the current production setup when provisioning starts. Existing servers keep their files and configuration.

+
Runtime image
{selection.image}
+ {#each games as game}{@const files = hostStatus.gameFiles?.[game]} + {#if files?.uploadedAt}
{game.toUpperCase()} game files uploaded
{$timeFormat.dateTime(files.uploadedAt)}
{/if} + {/each} +
+ {#each preview.entries as entry}
+ {entry.recipe.mapName} · {entry.recipe.game.toUpperCase()} +

{entry.recipe.configSource}

{entry.recipe.files.length} managed files

+
    {#each entry.recipe.files as file}
  • {file.name}{file.version === null ? 'Generated' : `v${file.version}`} · {file.kind}{file.path}
  • {/each}
+
+
{/each} +
+
{/if} {/if}
-
+ {#snippet actions()} +
+

{footerStatus}

+
{#if noChanges} + {:else}{/if} +
+
+ {/snippet} +
diff --git a/src/lib/ui/components/NativeHostSelection.svelte b/src/lib/ui/components/NativeHostSelection.svelte index 322ed2e..dc56f2f 100644 --- a/src/lib/ui/components/NativeHostSelection.svelte +++ b/src/lib/ui/components/NativeHostSelection.svelte @@ -27,6 +27,8 @@ missingGames: games.filter(game => !latest[game]?.id), uploadedAt: games.map(game => latest[game]?.publishedAt ?? latest[game]?.createdAt) .filter((value): value is string => !!value).sort().at(-1) ?? null, + gameFiles: Object.fromEntries(games.map(game => [game, { ready: cacheReady(game), + uploadedAt: latest[game]?.publishedAt ?? latest[game]?.createdAt ?? null }])), }; }); $effect(() => { diff --git a/src/lib/ui/native-game-files.ts b/src/lib/ui/native-game-files.ts index ad66b2b..57ed50f 100644 --- a/src/lib/ui/native-game-files.ts +++ b/src/lib/ui/native-game-files.ts @@ -10,6 +10,7 @@ export interface NativeHostSelectionStatus { filesReady: boolean; missingGames: ZombieGame[]; uploadedAt: string | null; + gameFiles?: Partial>; } /** Use the controller's latest upload, even while that upload is still syncing to a host. */ diff --git a/tests/unit/ui-collection-launch.test.ts b/tests/unit/ui-collection-launch.test.ts new file mode 100644 index 0000000..cdf7b15 --- /dev/null +++ b/tests/unit/ui-collection-launch.test.ts @@ -0,0 +1,252 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import type { CollectionPreview } from '../../src/lib/deployment-plan.js'; +import { createCollectionLaunchController, type CollectionLaunchInput, type CollectionLaunchState } from '../../src/lib/ui/collection-launch.js'; + +const selection: CollectionLaunchInput = { blueprintId: 'collection-1', mode: 'exact', libraryIds: { t5: 'library-1' }, image: 'runtime:latest' }; +const response = (body: unknown, status = 200) => new Response(JSON.stringify(body), { status }); +const preview = (overrides: Partial = {}): CollectionPreview => ({ + id: 'preview-1', expiresAt: new Date(Date.now() + 60_000).toISOString(), blueprintName: 'Zombies', + mode: 'exact', launchConcurrency: 2, retainedServers: ['t5_zombie_theater_1'], + removals: [{ name: 't5_zombie_theater_3', reason: 'Exceeds the collection target.' }], + servers: [{ name: 't5_zombie_theater_2', port: null, entryIndex: 0, hasSavedKey: true }], blockers: [], ready: true, + entries: [{ count: 2, existing: 1, missing: 1, existingServers: ['t5_zombie_theater_1'], coverage: [], + recipe: { game: 't5', mapSlug: 'kino', mapName: 'Kino Der Toten', expectedMap: 'zombie_theater', + capturedAt: new Date().toISOString(), image: 'runtime:latest', configFile: 'server.cfg', + configSource: 'T5 Zombies', files: [], fingerprint: 'recipe-1' } }], + ...overrides, +}); + +function deferred() { + let resolve!: (value: T) => void; + let reject!: (error: Error) => void; + const promise = new Promise((done, fail) => { resolve = done; reject = fail; }); + return { promise, resolve, reject }; +} + +let controller: ReturnType; +let state: CollectionLaunchState; +let fetchPreview: ReturnType>; +let changes: ReturnType void>>; + +beforeEach(() => { + vi.useFakeTimers(); + vi.setSystemTime(new Date('2026-10-07T18:00:00Z')); + state = { preview: null, checking: false, error: '', changeNotice: '' }; + fetchPreview = vi.fn(); + changes = vi.fn((next: CollectionLaunchState) => { state = next; }); + controller = createCollectionLaunchController(changes, { fetch: fetchPreview }); +}); +afterEach(() => { controller.dispose(); vi.useRealTimers(); vi.restoreAllMocks(); }); + +async function settle(value = preview(), input = selection) { + fetchPreview.mockResolvedValueOnce(response(value)); + controller.select(input); + await vi.advanceTimersByTimeAsync(200); +} + +describe('automatic collection launch checks', () => { + it('debounces selections and checks only the final collection mode and host inputs', async () => { + fetchPreview.mockResolvedValueOnce(response(preview({ mode: 'fill' }))); + controller.select(selection); + expect(state).toEqual({ preview: null, checking: true, error: '', changeNotice: '' }); + await vi.advanceTimersByTimeAsync(150); + controller.select({ ...selection, mode: 'fill', libraryIds: { t6: 'library-2', t5: 'library-1' } }); + await vi.advanceTimersByTimeAsync(199); + expect(fetchPreview).not.toHaveBeenCalled(); + await vi.advanceTimersByTimeAsync(1); + expect(fetchPreview).toHaveBeenCalledTimes(1); + expect(fetchPreview.mock.calls[0][0]).toBe('/api/deployment-collections/preview'); + expect(JSON.parse(fetchPreview.mock.calls[0][1]!.body as string)).toEqual({ + ...selection, mode: 'fill', libraryIds: { t5: 'library-1', t6: 'library-2' }, + }); + expect(state.preview?.mode).toBe('fill'); + expect(state.checking).toBe(false); + expect(state.changeNotice).toBe(''); + }); + + it('invalidates a settled preview synchronously when the runtime changes', async () => { + await settle(); + expect(state.preview).not.toBeNull(); + controller.select({ ...selection, image: 'runtime:other' }); + expect(state).toEqual({ preview: null, checking: true, error: '', changeNotice: '' }); + }); + + it('deduplicates identical selections and active checks, and refreshes a debounce immediately', async () => { + const request = deferred(); + fetchPreview.mockReturnValueOnce(request.promise); + const libraries = { t5: 'library-1', t6: 'library-2' }; + controller.select({ ...selection, libraryIds: libraries }); + controller.refresh(); + expect(fetchPreview).toHaveBeenCalledTimes(1); + controller.select({ ...selection, libraryIds: { t6: 'library-2', t5: 'library-1' } }); + controller.refresh(); + controller.refresh(); + await vi.advanceTimersByTimeAsync(200); + expect(fetchPreview).toHaveBeenCalledTimes(1); + request.resolve(response(preview())); + await vi.advanceTimersByTimeAsync(0); + controller.select({ ...selection, libraryIds: libraries }); + await vi.advanceTimersByTimeAsync(200); + expect(fetchPreview).toHaveBeenCalledTimes(1); + }); + + it.each(['success', 'error'] as const)('aborts changed requests and ignores stale %s responses', async (result) => { + const first = deferred(); + fetchPreview.mockReturnValueOnce(first.promise).mockResolvedValueOnce(response(preview({ id: 'new', mode: 'fill' }))); + controller.select(selection); + await vi.advanceTimersByTimeAsync(200); + const signal = fetchPreview.mock.calls[0][1]!.signal!; + controller.select({ ...selection, mode: 'fill' }); + expect(signal.aborted).toBe(true); + await vi.advanceTimersByTimeAsync(200); + if (result === 'success') first.resolve(response(preview({ id: 'old' }))); + else first.reject(new Error('Old request failed')); + await vi.advanceTimersByTimeAsync(0); + expect(state.preview?.id).toBe('new'); + expect(state.error).toBe(''); + expect(state.changeNotice).toBe(''); + expect(state.checking).toBe(false); + }); + + it.each([ + { name: 't5_zombie_theater_4', reason: 'Exceeds the collection target.' }, + { name: 't5_zombie_theater_3', reason: 'Map is outside this collection.' }, + ])('warns when a removal name or reason changes across a host refresh: %j', async (removal) => { + await settle(); + controller.select(null); + expect(state).toEqual({ preview: null, checking: false, error: '', changeNotice: '' }); + await settle(preview({ id: 'refreshed', removals: [removal] })); + expect(state.changeNotice).toMatch(/Servers to remove changed/); + expect(state.preview?.id).toBe('refreshed'); + }); + + it('warns when creation identities change without changing the number of servers', async () => { + await settle(); + fetchPreview.mockResolvedValueOnce(response(preview({ + servers: [{ name: 't5_zombie_theater_4', port: null, entryIndex: 0, hasSavedKey: true }], + }))); + controller.refresh(); + await vi.advanceTimersByTimeAsync(0); + expect(state.changeNotice).toMatch(/Servers to create changed/); + }); + + it('warns when retained identities change and gives removal changes priority', async () => { + await settle(); + fetchPreview.mockResolvedValueOnce(response(preview({ retainedServers: ['t5_zombie_theater_5'] }))); + controller.refresh(); + await vi.advanceTimersByTimeAsync(0); + expect(state.changeNotice).toMatch(/Servers to keep changed/); + fetchPreview.mockResolvedValueOnce(response(preview({ removals: [] }))); + controller.refresh(); + await vi.advanceTimersByTimeAsync(0); + expect(state.changeNotice).toMatch(/Servers to remove changed/); + }); + + it('does not report changed plans for reordering or changes in readiness alone', async () => { + const original = preview({ + retainedServers: ['t5_zombie_theater_1', 't5_zombie_five_1'], + removals: [{ name: 't5_zombie_theater_3', reason: 'Excess.' }, { name: 't5_zombie_theater_4', reason: 'Excess.' }], + servers: [{ name: 't5_zombie_theater_2', port: null, entryIndex: 0, hasSavedKey: false }, + { name: 't5_zombie_theater_5', port: null, entryIndex: 0, hasSavedKey: false }], + }); + await settle(original); + fetchPreview.mockResolvedValueOnce(response(preview({ + retainedServers: [...original.retainedServers].reverse(), removals: [...original.removals].reverse(), + servers: [...original.servers].reverse().map(server => ({ ...server, hasSavedKey: true })), + }))); + controller.refresh(); + await vi.advanceTimersByTimeAsync(0); + expect(state.changeNotice).toBe(''); + }); + + it.each(['blueprint', 'mode'] as const)('starts a fresh comparison when the %s changes', async (change) => { + await settle(); + const input = change === 'mode' ? { ...selection, mode: 'fill' as const } : { ...selection, blueprintId: 'other' }; + await settle(preview({ mode: input.mode, removals: [], retainedServers: [], servers: [] }), input); + expect(state.changeNotice).toBe(''); + }); + + it('clears history and ignores a dismissed response when reopening the same collection', async () => { + await settle(); + const dismissed = deferred(); + fetchPreview.mockReturnValueOnce(dismissed.promise); + controller.refresh(); + controller.clear(); + expect(fetchPreview.mock.calls[1][1]!.signal!.aborted).toBe(true); + await settle(preview({ id: 'reopened', removals: [], retainedServers: [], servers: [] })); + dismissed.resolve(response(preview({ id: 'dismissed' }))); + await vi.advanceTimersByTimeAsync(0); + expect(state.preview?.id).toBe('reopened'); + expect(state.changeNotice).toBe(''); + }); + + it('keeps failed refreshes unlaunchable and compares a successful retry with the last settled plan', async () => { + await settle(); + fetchPreview.mockResolvedValueOnce(response({ error: 'Host information unavailable.' }, 503)); + controller.refresh(); + expect(state.preview).toBeNull(); + await vi.advanceTimersByTimeAsync(0); + expect(state).toEqual({ preview: null, checking: false, error: 'Host information unavailable.', changeNotice: '' }); + fetchPreview.mockResolvedValueOnce(response(preview({ removals: [] }))); + controller.refresh(); + expect(state.error).toBe(''); + await vi.advanceTimersByTimeAsync(0); + expect(state.changeNotice).toMatch(/Servers to remove changed/); + }); + + it('automatically renews expired plans and compares the updated removal list', async () => { + await settle(preview({ expiresAt: new Date(Date.now() + 1000).toISOString() })); + const renewal = deferred(); + fetchPreview.mockReturnValueOnce(renewal.promise); + await vi.advanceTimersByTimeAsync(799); + expect(state.preview).not.toBeNull(); + await vi.advanceTimersByTimeAsync(1); + expect(state).toEqual({ preview: null, checking: true, error: '', changeNotice: '' }); + renewal.resolve(response(preview({ id: 'renewed', removals: [] }))); + await vi.advanceTimersByTimeAsync(0); + expect(state.preview?.id).toBe('renewed'); + expect(state.changeNotice).toMatch(/Servers to remove changed/); + }); + + it('rejects expired responses without repeatedly retrying them', async () => { + await settle(preview({ expiresAt: new Date(Date.now() + 100).toISOString() })); + await vi.advanceTimersByTimeAsync(2000); + expect(fetchPreview).toHaveBeenCalledTimes(1); + expect(state).toEqual({ preview: null, checking: false, error: 'The collection check expired. Try again.', changeNotice: '' }); + }); + + it('preserves the same preview ID while an apply is unconfirmed and resumes after definite rejection', async () => { + await settle(preview({ expiresAt: new Date(Date.now() + 1000).toISOString() })); + controller.suspend(); + controller.select({ ...selection }); + await vi.advanceTimersByTimeAsync(2000); + expect(state.preview?.id).toBe('preview-1'); + expect(fetchPreview).toHaveBeenCalledTimes(1); + fetchPreview.mockResolvedValueOnce(response(preview({ id: 'retry', removals: [] }))); + controller.refresh(); + expect(state.preview).toBeNull(); + await vi.advanceTimersByTimeAsync(0); + expect(state.preview?.id).toBe('retry'); + expect(state.changeNotice).toMatch(/Servers to remove changed/); + }); + + it('cancels pending selections and prevents disposed responses from publishing', async () => { + controller.select(selection); + controller.select(null); + await vi.advanceTimersByTimeAsync(200); + expect(fetchPreview).not.toHaveBeenCalled(); + const request = deferred(); + fetchPreview.mockReturnValueOnce(request.promise); + controller.select(selection); + await vi.advanceTimersByTimeAsync(200); + const count = changes.mock.calls.length; + controller.dispose(); + request.resolve(response(preview())); + controller.select(selection); + controller.refresh(); + await vi.advanceTimersByTimeAsync(60_000); + expect(changes).toHaveBeenCalledTimes(count); + expect(fetchPreview).toHaveBeenCalledTimes(1); + expect(fetchPreview.mock.calls[0][1]!.signal!.aborted).toBe(true); + }); +}); diff --git a/tests/unit/ui-collection-summary.test.ts b/tests/unit/ui-collection-summary.test.ts new file mode 100644 index 0000000..66dd25b --- /dev/null +++ b/tests/unit/ui-collection-summary.test.ts @@ -0,0 +1,129 @@ +import { describe, expect, it } from 'vitest'; +import type { CollectionPreview, LaunchAvailability } from '../../src/lib/deployment-plan.js'; +import { zombieMapBySlug, type ZombieGame } from '../../src/lib/map-aliases.js'; +import { collectionCapacitySummary, collectionKeyCoverage, collectionMapGroups } from '../../src/lib/ui/collection-summary.js'; + +function entry(game: ZombieGame, mapSlug: string, count: number, existingServers: string[] = []): CollectionPreview['entries'][number] { + const map = zombieMapBySlug(game, mapSlug)!; + return { count, existing: existingServers.length, missing: Math.max(0, count - existingServers.length), existingServers, + coverage: existingServers.map(name => ({ name, health: 'stopped', href: `/servers/${name}` })), + recipe: { game, mapSlug, mapName: map.friendly, expectedMap: map.canonical, capturedAt: '', image: 'runtime:latest', + configFile: 'server.cfg', configSource: 'Current setup', files: [], fingerprint: '' } }; +} + +function preview(overrides: Partial = {}): CollectionPreview { + return { id: 'preview', expiresAt: '2030-01-01T00:00:00Z', blueprintName: 'Collection', launchConcurrency: 1, + mode: 'fill', retainedServers: [], removals: [], entries: [], servers: [], blockers: [], ready: true, ...overrides }; +} + +function capacity(overrides: Partial = {}): LaunchAvailability { + return { requested: 5, estimatedAvailable: null, updatedAt: null, portsAvailable: null, cpuCoresAvailable: null, + memoryBytesAvailable: null, startupSlots: null, startupLimit: null, queued: null, ...overrides }; +} + +describe('collection key coverage', () => { + it('counts coverage separately by game without treating removals as available keys', () => { + const plan = preview({ mode: 'exact', entries: [entry('t5', 'theater', 2), entry('t6', 'town', 1)], + removals: [{ name: 't5_zombie_moon_1', reason: 'Outside collection' }], servers: [ + { entryIndex: 0, name: 't5_zombie_theater_1', hasSavedKey: true, port: null }, + { entryIndex: 0, name: 't5_zombie_theater_2', hasSavedKey: false, port: null }, + { entryIndex: 1, name: 't6_zombie_town_1', hasSavedKey: true, port: null }, + ] }); + expect(collectionKeyCoverage(plan)).toEqual([ + { game: 't5', label: 'Black Ops I', required: 2, available: 1, unassigned: 0 }, + { game: 't6', label: 'Black Ops II', required: 1, available: 1, unassigned: 0 }, + ]); + }); + + it('counts an unavailable lobby as required but never covered, and omits games without creations', () => { + expect(collectionKeyCoverage(preview({ entries: [entry('t5', 'theater', 1), entry('t6', 'town', 1)], + servers: [{ entryIndex: 1, name: null, hasSavedKey: true, port: null }] }))).toEqual([ + { game: 't6', label: 'Black Ops II', required: 1, available: 0, unassigned: 1 }, + ]); + expect(collectionKeyCoverage(preview({ mode: 'exact', removals: [{ name: 't5_zombie_theater_1', reason: 'Remove' }] }))).toEqual([]); + }); + + it('distinguishes known key shortages from creations waiting for a lobby', () => { + const [pool] = collectionKeyCoverage(preview({ entries: [entry('t5', 'theater', 3)], servers: [ + { entryIndex: 0, name: 't5_zombie_theater_19', hasSavedKey: true, port: null }, + { entryIndex: 0, name: 't5_zombie_theater_20', hasSavedKey: false, port: null }, + { entryIndex: 0, name: null, hasSavedKey: false, port: null }, + ] })); + expect(pool).toMatchObject({ required: 3, available: 1, unassigned: 1 }); + expect(pool.required - pool.unassigned - pool.available).toBe(1); + }); +}); + +describe('collection map summaries', () => { + it('preserves full existing counts in fill mode, including stopped inventory and excess lobbies', () => { + const plan = preview({ entries: [entry('t5', 'theater', 1, ['t5_zombie_theater_1', 't5_zombie_theater_2']), entry('t5', 'moon', 2)] }); + expect(collectionMapGroups(plan)).toEqual([{ game: 't5', label: 'Black Ops I', rows: [ + { key: 't5:theater', mapName: 'Kino Der Toten', target: 1, existing: 2, create: 0, remove: 0 }, + { key: 't5:moon', mapName: 'Moon', target: 2, existing: 0, create: 2, remove: 0 }, + ] }]); + }); + + it('counts ordinary excess once and adds already-pending removals missing from backend coverage', () => { + const plan = preview({ mode: 'exact', entries: [entry('t5', 'theater', 1, ['t5_zombie_theater_1', 't5_zombie_theater_2'])], + retainedServers: ['t5_zombie_theater_1'], removals: [ + { name: 't5_zombie_theater_2', reason: 'Excess' }, + { name: 't5_zombie_theater_3', reason: 'Already awaiting removal' }, + ] }); + expect(collectionMapGroups(plan)[0].rows).toEqual([ + { key: 't5:theater', mapName: 'Kino Der Toten', target: 1, existing: 3, create: 0, remove: 2 }, + ]); + }); + + it('shows outside maps with target zero across both games without combining T6 variants', () => { + const plan = preview({ mode: 'exact', entries: [entry('t6', 'town', 1, ['t6_zombie_town_1'])], + retainedServers: ['t6_zombie_town_1'], removals: [ + { name: 't5_zombie_moon_1', reason: 'Outside collection' }, + { name: 't6_zombie_farm_1', reason: 'Outside collection' }, + { name: 't6_zombie_town_grief_1', reason: 'Outside collection' }, + ] }); + expect(collectionMapGroups(plan)).toEqual([ + { game: 't5', label: 'Black Ops I', rows: [{ key: 't5:moon', mapName: 'Moon', target: 0, existing: 1, create: 0, remove: 1 }] }, + { game: 't6', label: 'Black Ops II', rows: [ + { key: 't6:town', mapName: 'Town Survival', target: 1, existing: 1, create: 0, remove: 0 }, + { key: 't6:farm', mapName: 'Farm Survival', target: 0, existing: 1, create: 0, remove: 1 }, + { key: 't6:towngrief', mapName: 'Town Grief', target: 0, existing: 1, create: 0, remove: 1 }, + ] }, + ]); + }); + + it('uses authoritative coverage before names and resolves friendly legacy aliases', () => { + const plan = preview({ mode: 'exact', entries: [entry('t6', 'town', 1, ['custom-town', 't6_zombie_town_1']), entry('t5', 'theater', 1, ['t5_zombie_theater_1'])], + removals: [{ name: 'custom-town', reason: 'Excess' }, { name: 'T5_ZOMBIE_KINO_DER_TOTEN_2', reason: 'Awaiting removal' }] }); + expect(collectionMapGroups(plan).map(group => group.rows)).toEqual([ + [{ key: 't5:theater', mapName: 'Kino Der Toten', target: 1, existing: 2, create: 0, remove: 1 }], + [{ key: 't6:town', mapName: 'Town Survival', target: 1, existing: 2, create: 0, remove: 1 }], + ]); + }); + + it('keeps unknown removals visible without guessing a shared engine-map variant', () => { + const plan = preview({ mode: 'exact', removals: [ + { name: 't6_zombie_zm_transit_1', reason: 'Unknown variant' }, + { name: 'custom-instance', reason: 'Outside collection' }, + ] }); + expect(collectionMapGroups(plan)).toEqual([ + { game: 't6', label: 'Black Ops II', rows: [{ key: 't6:server:t6_zombie_zm_transit_1', mapName: 't6_zombie_zm_transit_1', target: 0, existing: 1, create: 0, remove: 1 }] }, + { game: null, label: 'Other servers', rows: [{ key: 'other:server:custom-instance', mapName: 'custom-instance', target: 0, existing: 1, create: 0, remove: 1 }] }, + ]); + }); +}); + +describe('collection capacity summary', () => { + it('keeps unknown and insufficient capacity queueable', () => { + expect(collectionCapacitySummary()).toBe('Capacity estimate unavailable; launches can wait for capacity.'); + expect(collectionCapacitySummary(capacity())).toBe('Capacity estimate unavailable; launches can wait for capacity.'); + expect(collectionCapacitySummary(capacity({ estimatedAvailable: 0 }))).toBe('Estimated capacity for 0 of 5 servers; launches can wait for capacity.'); + expect(collectionCapacitySummary(capacity({ estimatedAvailable: 2 }))).toBe('Estimated capacity for 2 of 5 servers; launches can wait for capacity.'); + expect(collectionCapacitySummary(capacity({ requested: 1, estimatedAvailable: 0 }))).toBe('Estimated capacity for 0 of 1 server; launches can wait for capacity.'); + }); + + it('uses requested counts when enough capacity exists and handles plans without creations', () => { + expect(collectionCapacitySummary(capacity({ estimatedAvailable: 20 }))).toBe('Estimated capacity for all 5 servers.'); + expect(collectionCapacitySummary(capacity({ requested: 1, estimatedAvailable: 1 }))).toBe('Estimated capacity for 1 server.'); + expect(collectionCapacitySummary(capacity({ requested: 0 }))).toBe('No new server capacity needed.'); + }); +});