ui/phase-14: auto-sync order draft + always GET on boot + header headline

Replaces the manual Submit button with an auto-sync pipeline driven
by `OrderDraftStore`: every successful add / remove / move
coalesces a `submitOrder` call so the engine always mirrors the
local draft. Removing the last command sends an empty cmd[] PUT —
the engine, repo, and rest model now accept that as a valid
"player cleared their draft" state.

`hydrateFromServer` is now invoked unconditionally on game boot so
a fresh device picks up the player's stored order, and the local
cache is overwritten by the server's view (server is the source of
truth).

Header replaces the static "race ?" + turn counter with a single
headline string `<race> @ <game>, turn <n>`, sourced from the
engine's Report.race + the lobby's GameSummary.gameName + the live
turn number, with a `?` fallback while any piece is loading.

Tests:
- engine: empty PUT round-trips, repo round-trips empty Commands
- order-draft: auto-sync sends full draft on every mutation,
  rejected response surfaces error sync status, rapid mutations
  coalesce, server hydration overwrites cache
- order-tab: per-row status flips through the auto-sync lifecycle,
  remove → empty cmd[] PUT, rejected → retry button
- inspector overlay: applied + valid + submitting all participate
  in the optimistic projection
- header: live race / game / turn rendering with fall-back

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
Ilia Denisov
2026-05-09 13:34:10 +02:00
parent 68d8607eaa
commit 229c43beb5
26 changed files with 1144 additions and 728 deletions
+109 -153
View File
@@ -1,53 +1,33 @@
// Component coverage for the Phase 14 order-tab submit flow. Drives
// the tab against an in-memory `OrderDraftStore`, a synthetic
// `GalaxyClient`, and a stubbed `GameStateStore.refresh`. Every
// case asserts both the rendered DOM (status badges, button state)
// and the side effect on the draft store (per-command status flips).
// Component coverage for the Phase 14 order tab. The Submit button
// has been retired — every successful `add` / `remove` triggers
// `OrderDraftStore.scheduleSync`, so the tab is mostly a status
// surface. Tests assert the per-row status badge transitions and
// the bottom-bar sync state.
import "@testing-library/jest-dom/vitest";
import "fake-indexeddb/auto";
import { fireEvent, render, waitFor } from "@testing-library/svelte";
import { Builder } from "flatbuffers";
import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
import { afterEach, beforeEach, describe, expect, test } from "vitest";
import OrderTab from "../src/lib/sidebar/order-tab.svelte";
import {
ORDER_DRAFT_CONTEXT_KEY,
OrderDraftStore,
} from "../src/sync/order-draft.svelte";
import {
GAME_STATE_CONTEXT_KEY,
GameStateStore,
} from "../src/lib/game-state.svelte";
import {
GALAXY_CLIENT_CONTEXT_KEY,
GalaxyClientHolder,
} from "../src/lib/galaxy-client-context.svelte";
import { i18n } from "../src/lib/i18n/index.svelte";
import { uuidToHiLo } from "../src/api/game-state";
import type { GalaxyClient } from "../src/api/galaxy-client";
import type { OrderCommand } from "../src/sync/order-types";
import { IDBCache } from "../src/platform/store/idb-cache";
import { openGalaxyDB, type GalaxyDB } from "../src/platform/store/idb";
import type { Cache } from "../src/platform/store/index";
import { UUID } from "../src/proto/galaxy/fbs/common";
import {
CommandItem,
CommandPayload,
CommandPlanetRename,
UserGamesOrderResponse,
} from "../src/proto/galaxy/fbs/order";
import { openGalaxyDB } from "../src/platform/store/idb";
import { recordingClient } from "./helpers/fake-order-client";
const GAME_ID = "11111111-2222-3333-4444-555555555555";
let db: Awaited<ReturnType<typeof openGalaxyDB>>;
let dbName: string;
let cache: Cache;
beforeEach(async () => {
dbName = `galaxy-order-tab-${crypto.randomUUID()}`;
db = await openGalaxyDB(dbName);
cache = new IDBCache(db);
i18n.resetForTests("en");
});
@@ -61,162 +41,138 @@ afterEach(async () => {
});
});
interface Setup {
context: Map<unknown, unknown>;
draft: OrderDraftStore;
gameState: GameStateStore;
clientHolder: GalaxyClientHolder;
exec: ReturnType<typeof vi.fn>;
refresh: ReturnType<typeof vi.fn>;
}
function buildResponse(
commands: { id: string; applied: boolean | null; errorCode: number | null }[],
updatedAt: number,
): Uint8Array {
const builder = new Builder(256);
const itemOffsets = commands.map((c) => {
const cmdIdOffset = builder.createString(c.id);
const nameOffset = builder.createString("ignored");
const inner = CommandPlanetRename.createCommandPlanetRename(
builder,
BigInt(0),
nameOffset,
);
CommandItem.startCommandItem(builder);
CommandItem.addCmdId(builder, cmdIdOffset);
if (c.applied !== null) CommandItem.addCmdApplied(builder, c.applied);
if (c.errorCode !== null) {
CommandItem.addCmdErrorCode(builder, BigInt(c.errorCode));
}
CommandItem.addPayloadType(builder, CommandPayload.CommandPlanetRename);
CommandItem.addPayload(builder, inner);
return CommandItem.endCommandItem(builder);
});
const commandsVec = UserGamesOrderResponse.createCommandsVector(
builder,
itemOffsets,
);
const [hi, lo] = uuidToHiLo(GAME_ID);
const gameIdOffset = UUID.createUUID(builder, hi, lo);
UserGamesOrderResponse.startUserGamesOrderResponse(builder);
UserGamesOrderResponse.addGameId(builder, gameIdOffset);
UserGamesOrderResponse.addUpdatedAt(builder, BigInt(updatedAt));
UserGamesOrderResponse.addCommands(builder, commandsVec);
const offset = UserGamesOrderResponse.endUserGamesOrderResponse(builder);
builder.finish(offset);
return builder.asUint8Array();
}
async function makeSetup(commands: OrderCommand[]): Promise<Setup> {
async function makeDraft(
commands: OrderCommand[],
): Promise<{ draft: OrderDraftStore; context: Map<unknown, unknown> }> {
const cache = new IDBCache(db);
const draft = new OrderDraftStore();
await draft.init({ cache, gameId: GAME_ID });
for (const cmd of commands) {
await draft.add(cmd);
}
const gameState = new GameStateStore();
gameState.gameId = GAME_ID;
gameState.status = "ready";
const refresh = vi.fn(async () => {});
gameState.refresh = refresh as unknown as typeof gameState.refresh;
const clientHolder = new GalaxyClientHolder();
const exec = vi.fn(async (_messageType: string, _payload: Uint8Array) => ({
resultCode: "ok",
payloadBytes: buildResponse(
commands.map((cmd) => ({
id: cmd.id,
applied: true,
errorCode: null,
})),
17,
),
}));
clientHolder.set({ executeCommand: exec } as unknown as GalaxyClient);
const context = new Map<unknown, unknown>([
[ORDER_DRAFT_CONTEXT_KEY, draft],
[GAME_STATE_CONTEXT_KEY, gameState],
[GALAXY_CLIENT_CONTEXT_KEY, clientHolder],
]);
return { context, draft, gameState, clientHolder, exec, refresh };
return { draft, context };
}
describe("order-tab", () => {
test("renders the empty state when the draft has no commands", async () => {
const { context } = await makeSetup([]);
const { draft, context } = await makeDraft([]);
const ui = render(OrderTab, { context });
expect(ui.getByTestId("order-empty")).toBeVisible();
expect(ui.queryByTestId("order-submit")).toBeNull();
expect(ui.queryByTestId("order-list")).toBeNull();
// The sync bar still renders so the user can see the
// idle / synced / error transitions.
expect(ui.getByTestId("order-sync")).toBeVisible();
draft.dispose();
});
test("Submit is disabled when every entry is invalid", async () => {
const { context } = await makeSetup([
test("invalid command shows the invalid status badge", async () => {
const { draft, context } = await makeDraft([
{ kind: "planetRename", id: "id-1", planetNumber: 1, name: "" },
]);
const ui = render(OrderTab, { context });
const submit = ui.getByTestId("order-submit");
expect(submit).toBeDisabled();
expect(ui.getByTestId("order-command-status-0")).toHaveTextContent(
"invalid",
);
draft.dispose();
});
test("Submit posts every valid command and applies returned statuses", async () => {
const { context, draft, exec, refresh } = await makeSetup([
{ kind: "planetRename", id: "id-1", planetNumber: 1, name: "Earth" },
]);
test("auto-sync flips the row to applied and the sync bar to synced", async () => {
const handle = recordingClient(GAME_ID, "ok");
const { draft, context } = await makeDraft([]);
draft.bindClient(handle.client);
const ui = render(OrderTab, { context });
const submit = ui.getByTestId("order-submit");
expect(submit).not.toBeDisabled();
expect(ui.getByTestId("order-command-status-0")).toHaveTextContent("valid");
await fireEvent.click(submit);
await draft.add({
kind: "planetRename",
id: "id-1",
planetNumber: 1,
name: "Earth",
});
await handle.waitForCalls(1);
await waitFor(() => {
expect(ui.getByTestId("order-command-status-0")).toHaveTextContent(
"applied",
);
});
await waitFor(() => {
expect(ui.getByTestId("order-sync")).toHaveAttribute(
"data-sync-status",
"synced",
);
});
expect(handle.calls).toHaveLength(1);
expect(handle.calls[0]!.commandIds).toEqual(["id-1"]);
draft.dispose();
});
test("removing the last command sends an empty cmd[] PUT", async () => {
const handle = recordingClient(GAME_ID, "ok");
const { draft, context } = await makeDraft([]);
draft.bindClient(handle.client);
await draft.add({
kind: "planetRename",
id: "id-1",
planetNumber: 1,
name: "Earth",
});
await handle.waitForCalls(1);
const ui = render(OrderTab, { context });
await fireEvent.click(ui.getByTestId("order-command-delete-0"));
await handle.waitForCalls(2);
expect(handle.calls[1]!.commandIds).toEqual([]);
expect(draft.commands).toEqual([]);
await waitFor(() => {
expect(ui.getByTestId("order-empty")).toBeVisible();
});
draft.dispose();
});
test("non-ok response surfaces the sync error and a retry button", async () => {
const handle = recordingClient(GAME_ID, "rejected");
const { draft, context } = await makeDraft([]);
draft.bindClient(handle.client);
const ui = render(OrderTab, { context });
await draft.add({
kind: "planetRename",
id: "id-1",
planetNumber: 1,
name: "Earth",
});
await handle.waitForCalls(1);
await waitFor(() => {
expect(ui.getByTestId("order-sync")).toHaveAttribute(
"data-sync-status",
"error",
);
});
expect(ui.getByTestId("order-sync-retry")).toBeVisible();
expect(ui.getByTestId("order-command-status-0")).toHaveTextContent(
"rejected",
);
// Retry the call now that the fixture answers ok.
handle.setOutcome("ok");
await fireEvent.click(ui.getByTestId("order-sync-retry"));
await handle.waitForCalls(2);
await waitFor(() => {
expect(draft.statuses["id-1"]).toBe("applied");
});
expect(exec).toHaveBeenCalledTimes(1);
expect(refresh).toHaveBeenCalledTimes(1);
expect(ui.getByTestId("order-command-status-0")).toHaveTextContent(
"applied",
);
});
test("Non-ok response marks every submitting entry as rejected", async () => {
const { context, draft, refresh } = await makeSetup([
{ kind: "planetRename", id: "id-1", planetNumber: 1, name: "Earth" },
]);
const exec = vi.fn(async () => ({
resultCode: "invalid_request",
payloadBytes: new TextEncoder().encode(
JSON.stringify({ code: "boom", message: "down" }),
),
}));
const holder = context.get(GALAXY_CLIENT_CONTEXT_KEY) as GalaxyClientHolder;
holder.set({ executeCommand: exec } as unknown as GalaxyClient);
const ui = render(OrderTab, { context });
await fireEvent.click(ui.getByTestId("order-submit"));
await waitFor(() => {
expect(draft.statuses["id-1"]).toBe("rejected");
expect(ui.getByTestId("order-sync")).toHaveAttribute(
"data-sync-status",
"synced",
);
});
expect(refresh).not.toHaveBeenCalled();
expect(ui.getByTestId("order-submit-error")).toHaveTextContent("down");
});
test("Already-applied entries do not get re-submitted", async () => {
const { context, draft, exec } = await makeSetup([
{ kind: "planetRename", id: "id-1", planetNumber: 1, name: "Earth" },
]);
draft.markSubmitting(["id-1"]);
draft.applyResults({
results: new Map([["id-1", "applied"] as const]),
updatedAt: 1,
});
const ui = render(OrderTab, { context });
const submit = ui.getByTestId("order-submit");
expect(submit).toBeDisabled();
expect(exec).not.toHaveBeenCalled();
draft.dispose();
});
});