Step 9.5: add dispatch flow

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
fireshaper 2026-10-03 02:13:05 -04:00
parent ea31eeab59
commit 7101b26abf
5 changed files with 400 additions and 2 deletions

View File

@ -418,3 +418,11 @@ Implementation decisions not spelled out in `memory-bank/implementation-plan.md`
- **The distance shown on a contract is the current distance** (sim, at the server clock), which is what fuel and travel time use when dispatching now. The payout was fixed at the distance when the contract was offered (decision 0.5.11). - **The distance shown on a contract is the current distance** (sim, at the server clock), which is what fuel and travel time use when dispatching now. The payout was fixed at the distance when the contract was offered (decision 0.5.11).
- **Requirements are shown as text** ("Needs Heavy Cargo 2, Long Haul 1"); whether a particular pilot meets them is shown in the dispatch sheet (Step 9.5). - **Requirements are shown as text** ("Needs Heavy Cargo 2, Long Haul 1"); whether a particular pilot meets them is shown in the dispatch sheet (Step 9.5).
- **The bay selector is a native `<select>`**, which works well on phones. - **The bay selector is a native `<select>`**, which works well on phones.
## Step 9.5
- **Eligibility in the sheet comes from sim `validateDispatch`**, given the client's copy of state and the synced clock, so the client shows the same reasons the server would return. The server still decides (rule 0.1.6).
- **Pairs are the idle ships at the pickup with their assigned pilots.** Uncrewed ships there are listed as "No pilot assigned"; ships elsewhere are not listed.
- **Net profit = payout − fuel − pilot pay** (no pilot pay when the avatar flies; decision 0.5.12).
- **ETA is shown twice:** in-game (`YYYY-MM-DD HH:MM`) and real local time on the device.
- **The first eligible pair is preselected**; Confirm is disabled when none is eligible.

View File

@ -1,14 +1,19 @@
import type { Contract } from "@deadhead/schema";
import { useState } from "react";
import { useLoadedPlayer } from "../state/actions"; import { useLoadedPlayer } from "../state/actions";
import { BayBoards } from "./BayBoards"; import { BayBoards } from "./BayBoards";
import { DispatchSheet } from "./DispatchSheet";
import { TutorialBoard } from "./TutorialBoard"; import { TutorialBoard } from "./TutorialBoard";
/** Contracts: the tutorial board during the tutorial, bay boards afterwards. */ /** Contracts: the tutorial board during the tutorial, bay boards afterwards. */
export function Contracts() { export function Contracts() {
const state = useLoadedPlayer(); const state = useLoadedPlayer();
const [selected, setSelected] = useState<Contract | null>(null);
return ( return (
<section className="space-y-3 p-4"> <section className="space-y-3 p-4">
<h1 className="text-xl font-semibold">Contracts</h1> <h1 className="text-xl font-semibold">Contracts</h1>
{state.tutorial ? <TutorialBoard /> : <BayBoards />} {state.tutorial ? <TutorialBoard /> : <BayBoards onSelect={setSelected} />}
{selected && <DispatchSheet contract={selected} onClose={() => setSelected(null)} />}
</section> </section>
); );
} }

View File

@ -0,0 +1,220 @@
import { content } from "@deadhead/content";
import type { Contract, PlayerState } from "@deadhead/schema";
import { realToGame, tripFuelCost, validateDispatch, type DispatchFailure } from "@deadhead/sim";
import { useState } from "react";
import { useClock } from "../clock/clock";
import { formatGameTime } from "../clock/GameClock";
import { formatCredits, formatDuration, locationName } from "../format";
import { location, shipModel, tripRealMs } from "../game";
import { errorMessage, useGameAction, useLoadedPlayer } from "../state/actions";
/** Short player-facing reasons a ship+pilot cannot take a contract. */
export const INELIGIBLE_REASONS: Record<DispatchFailure, string> = {
"ship-not-idle": "Ship is flying",
"ship-not-at-origin": "Not at pickup",
"pilot-not-idle": "Pilot is flying",
"pilot-not-assigned": "No pilot assigned",
"over-capacity": "Too heavy",
"cannot-land": "Can't land there",
"out-of-range": "Out of range",
"cargo-skill-too-low": "Cargo skill too low",
"long-haul-too-low": "Long Haul too low",
"contract-expired": "Contract expired",
"insufficient-credits": "Not enough credits for fuel",
};
/** Real-world arrival time on the device, e.g. "14:05". */
export function formatLocalTime(time: number): string {
return new Date(time).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" });
}
export interface PairOption {
shipId: string;
shipName: string;
modelName: string;
pilotId: string | null;
pilotName: string | null;
reason: string | null;
tripMs: number;
fuelCost: number;
netProfit: number;
arrivalAt: number;
}
/** Every ship at the contract's origin, with its pilot, numbers and eligibility. */
export function pairOptions(state: PlayerState, contract: Contract, now: number): PairOption[] {
const gameNow = realToGame(now, content.config);
return state.ships
.filter((ship) => ship.status === "idle" && ship.locationId === contract.originId)
.map((ship) => {
const model = shipModel(ship.modelId);
const pilot = state.pilots.find((p) => p.assignedShipId === ship.id) ?? null;
const tripMs = tripRealMs(model, contract.originId, contract.destinationId, now);
const fuelCost = tripFuelCost(
model,
location(contract.originId),
location(contract.destinationId),
gameNow,
);
const pilotPay = pilot && !pilot.isAvatar ? content.config.pilotPayPerDelivery : 0;
let reason: string | null = INELIGIBLE_REASONS["pilot-not-assigned"];
if (pilot) {
const check = validateDispatch(
{
ship: {
id: ship.id,
modelId: ship.modelId,
locationId: ship.locationId!,
inFlight: false,
},
pilot: {
id: pilot.id,
isAvatar: pilot.isAvatar,
assignedShipId: pilot.assignedShipId,
inFlight: pilot.status === "in-flight",
skills: pilot.skills,
},
contract,
tutorial: false,
credits: state.company.credits,
now,
},
content,
);
reason = check.ok ? null : INELIGIBLE_REASONS[check.reason];
}
return {
shipId: ship.id,
shipName: ship.name,
modelName: model.name,
pilotId: pilot?.id ?? null,
pilotName: pilot?.name ?? null,
reason,
tripMs,
fuelCost,
netProfit: contract.payout - fuelCost - pilotPay,
arrivalAt: now + tripMs,
};
});
}
/** Choose a ship and pilot for a contract, see the numbers, and confirm (Step 9.5). */
export function DispatchSheet({ contract, onClose }: { contract: Contract; onClose: () => void }) {
const state = useLoadedPlayer();
const now = useClock((s) => s.now);
const dispatch = useGameAction("createDispatch");
const options = pairOptions(state, contract, now);
const [chosen, setChosen] = useState<string | null>(
options.find((o) => o.reason === null)?.shipId ?? null,
);
const selected = options.find((o) => o.shipId === chosen && o.reason === null);
const confirm = () => {
if (!selected?.pilotId) return;
dispatch.mutate(
{
kind: "contract",
contractId: contract.id,
shipId: selected.shipId,
pilotId: selected.pilotId,
},
{ onSuccess: onClose },
);
};
return (
<div className="fixed inset-0 z-20 flex items-end justify-center bg-black/60 sm:items-center">
<div
role="dialog"
aria-modal="true"
aria-labelledby="dispatch-title"
className="max-h-[85dvh] w-full max-w-md overflow-y-auto rounded-t-xl border border-slate-700 bg-slate-900 p-4 sm:rounded-xl"
>
<h2 id="dispatch-title" className="text-lg font-semibold">
{locationName(contract.originId)} → {locationName(contract.destinationId)}
</h2>
<p className="text-sm text-slate-400">Payout {formatCredits(contract.payout)}</p>
{options.length === 0 ? (
<p className="mt-3 text-sm text-slate-400">
No idle ships at {locationName(contract.originId)}.
</p>
) : (
<ul className="mt-3 space-y-2">
{options.map((option) => (
<li key={option.shipId}>
<label
aria-disabled={option.reason !== null}
className={`block rounded-lg border p-3 text-sm ${
option.reason
? "border-slate-800 opacity-60"
: chosen === option.shipId
? "border-amber-400"
: "border-slate-700"
}`}
>
<div className="flex items-center gap-2">
<input
type="radio"
name="pair"
value={option.shipId}
disabled={option.reason !== null}
checked={chosen === option.shipId}
onChange={() => setChosen(option.shipId)}
/>
<span className="font-medium">{option.shipName}</span>
<span className="text-slate-400">
{option.modelName} · {option.pilotName ?? "no pilot"}
</span>
</div>
{option.reason ? (
<p className="mt-1 text-red-400">{option.reason}</p>
) : (
<dl className="mt-1 grid grid-cols-2 gap-x-3 text-slate-300">
<dt>Trip</dt>
<dd className="tabular-nums">{formatDuration(option.tripMs)}</dd>
<dt>Fuel</dt>
<dd className="tabular-nums">{formatCredits(option.fuelCost)}</dd>
<dt>Net profit</dt>
<dd className="tabular-nums">{formatCredits(option.netProfit)}</dd>
<dt>ETA (game)</dt>
<dd className="tabular-nums">
{formatGameTime(realToGame(option.arrivalAt, content.config))}
</dd>
<dt>ETA (real)</dt>
<dd className="tabular-nums">{formatLocalTime(option.arrivalAt)}</dd>
</dl>
)}
</label>
</li>
))}
</ul>
)}
{dispatch.isError && (
<p role="alert" className="mt-3 text-sm text-red-400">
{errorMessage(dispatch.error)}
</p>
)}
<div className="mt-4 flex gap-2">
<button
type="button"
onClick={onClose}
className="flex-1 rounded-lg border border-slate-700 py-2"
>
Cancel
</button>
<button
type="button"
onClick={confirm}
disabled={!selected || dispatch.isPending}
className="flex-1 rounded-lg bg-amber-500 py-2 font-semibold text-slate-950 disabled:opacity-40"
>
Confirm
</button>
</div>
</div>
</div>
);
}

View File

@ -0,0 +1,165 @@
import { content } from "@deadhead/content";
import type { Contract, Pilot, Ship } from "@deadhead/schema";
import {
MS_PER_HOUR,
realToGame,
routeDistance,
travelTimeGameHours,
tripFuelCost,
} from "@deadhead/sim";
import { screen, waitFor, within } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { ApiError } from "../src/api/client";
import { useClock } from "../src/clock/clock";
import { formatGameTime } from "../src/clock/GameClock";
import { formatCredits, formatDuration } from "../src/format";
import { formatLocalTime } from "../src/screens/DispatchSheet";
import { fakeApi, renderApp, samplePlayerState } from "./render";
const NOW = Date.parse("2100-01-01T00:00:00Z");
const ship = (id: string, name: string, modelId: string, pilotId: string | null): Ship => ({
id,
name,
modelId,
status: "idle",
locationId: "earth",
dispatchId: null,
pilotId,
});
const pilot = (id: string, name: string, shipId: string, isAvatar: boolean): Pilot => ({
id,
name,
isAvatar,
xp: 0,
level: 0,
skills: {},
skillPointsAvailable: 0,
assignedShipId: shipId,
status: "idle",
locationId: "earth",
});
const marsJob: Contract = {
id: "c-mars",
originId: "earth",
destinationId: "mars",
cargoTypeId: "standard",
tier: 0,
massTonnes: 15,
payout: 500_000,
requiredSkill: null,
requiredLongHaulLevel: 0,
offeredAt: NOW,
expiresAt: NOW + 3_600_000,
firstContact: false,
};
const state = samplePlayerState({
tutorial: null,
company: { id: "c", name: "D", credits: 1_000_000 },
bays: [{ id: "b1", locationId: "earth" }],
ships: [
ship("s-courier", "Dusty Mule", "courier", "avatar"),
ship("s-freighter", "Slow Ox", "freighter", "p-rae"),
ship("s-spare", "Spare Kettle", "courier", null),
],
pilots: [
pilot("avatar", "Captain", "s-courier", true),
pilot("p-rae", "Rae Okafor", "s-freighter", false),
],
});
function api(createDispatch?: () => never) {
return fakeApi({
getPlayerState: () => state,
getContractBoard: () => ({ contracts: [marsJob], periodEndsAt: NOW + 3_600_000 }),
...(createDispatch ? { createDispatch } : {}),
});
}
async function openSheet() {
await userEvent.click(await screen.findByRole("button", { name: "Dispatch" }));
return screen.getByRole("dialog");
}
const option = (dialog: HTMLElement, shipName: string) =>
within(dialog).getByText(shipName).closest("li")!;
describe("dispatch sheet", () => {
beforeEach(() => {
vi.useFakeTimers({ toFake: ["Date", "setInterval", "clearInterval"] });
vi.setSystemTime(NOW);
useClock.setState({ offsetMs: 0, synced: true, now: NOW });
});
afterEach(() => vi.useRealTimers());
it("shows the sim's trip time, fuel, net profit and ETAs for an eligible pair", async () => {
renderApp(api(), "/contracts");
const dialog = await openSheet();
const freighter = option(dialog, "Slow Ox");
const model = content.shipModel("freighter")!;
const earth = content.location("earth")!;
const mars = content.location("mars")!;
const gameNow = realToGame(NOW, content.config);
const tripMs =
(travelTimeGameHours(model, routeDistance(earth, mars, gameNow)) * MS_PER_HOUR) /
content.config.timeCompression;
const fuel = tripFuelCost(model, earth, mars, gameNow);
const net = marsJob.payout - fuel - content.config.pilotPayPerDelivery;
expect(within(freighter).getByRole("radio")).toBeEnabled();
expect(freighter).toHaveTextContent(`Trip${formatDuration(tripMs)}`);
expect(freighter).toHaveTextContent(`Fuel${formatCredits(fuel)}`);
expect(freighter).toHaveTextContent(`Net profit${formatCredits(net)}`);
expect(freighter).toHaveTextContent(
`ETA (game)${formatGameTime(realToGame(NOW + tripMs, content.config))}`,
);
expect(freighter).toHaveTextContent(`ETA (real)${formatLocalTime(NOW + tripMs)}`);
});
it("lists ineligible pairs disabled, with the reason", async () => {
renderApp(api(), "/contracts");
const dialog = await openSheet();
const courier = option(dialog, "Dusty Mule");
expect(within(courier).getByRole("radio")).toBeDisabled();
expect(courier).toHaveTextContent("Out of range");
const spare = option(dialog, "Spare Kettle");
expect(within(spare).getByRole("radio")).toBeDisabled();
expect(spare).toHaveTextContent("No pilot assigned");
});
it("sends the dispatch for the chosen pair on Confirm", async () => {
const fake = api();
renderApp(fake, "/contracts");
const dialog = await openSheet();
await userEvent.click(within(dialog).getByRole("button", { name: "Confirm" }));
await waitFor(() =>
expect(fake.call).toHaveBeenCalledWith("createDispatch", {
kind: "contract",
contractId: "c-mars",
shipId: "s-freighter",
pilotId: "p-rae",
}),
);
});
it("shows the server's message when the dispatch is refused", async () => {
renderApp(
api(() => {
throw new ApiError(409, "contract-expired", "This contract has expired.");
}),
"/contracts",
);
const dialog = await openSheet();
await userEvent.click(within(dialog).getByRole("button", { name: "Confirm" }));
expect(await within(dialog).findByRole("alert")).toHaveTextContent(
"This contract has expired.",
);
});
});

View File

@ -89,7 +89,7 @@
- [x] **Step 9.2 — "While you were away" summary.** `src/components/AwaySummary.tsx`: dialog over every screen listing each unacknowledged delivery (ship or "Company loaner", route, credits, XP, discovery); "Got it" hides it at once and calls `acknowledgeSummaries`. - [x] **Step 9.2 — "While you were away" summary.** `src/components/AwaySummary.tsx`: dialog over every screen listing each unacknowledged delivery (ship or "Company loaner", route, credits, XP, discovery); "Got it" hides it at once and calls `acknowledgeSummaries`.
- [x] **Step 9.3 — Tutorial contract board.** Contracts screen shows the tutorial board during the tutorial (`src/screens/TutorialBoard.tsx`): route, cargo, mass, payout, sim-predicted trip time (`src/game.ts`), and "Fly it" (disabled while a run is in flight; server errors shown). - [x] **Step 9.3 — Tutorial contract board.** Contracts screen shows the tutorial board during the tutorial (`src/screens/TutorialBoard.tsx`): route, cargo, mass, payout, sim-predicted trip time (`src/game.ts`), and "Fly it" (disabled while a run is in flight; server errors shown).
- [x] **Step 9.4 — Bay contract boards.** After the tutorial the Contracts screen shows `BayBoards`: a bay selector and, per contract, route, cargo (and tier), mass, current distance, payout, required skills, live expiry countdown and a first-contact badge. - [x] **Step 9.4 — Bay contract boards.** After the tutorial the Contracts screen shows `BayBoards`: a bay selector and, per contract, route, cargo (and tier), mass, current distance, payout, required skills, live expiry countdown and a first-contact badge.
- [ ] Step 9.5 — Dispatch flow - [x] **Step 9.5 — Dispatch flow.** `src/screens/DispatchSheet.tsx`: each idle ship at the pickup with its pilot, checked with sim `validateDispatch`; eligible pairs show trip time, fuel, net profit and game/real ETA; ineligible pairs are disabled with a short reason; Confirm sends the dispatch and shows server errors.
- [ ] Step 9.6 — Fleet screen - [ ] Step 9.6 — Fleet screen
- [ ] Step 9.7 — Pilots screen - [ ] Step 9.7 — Pilots screen
- [ ] Step 9.8 — Market screen - [ ] Step 9.8 — Market screen