Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,7 @@ const viewerInteraction = {
canSubmit: true,
autoPassRecommended: false,
opportunities: [],
attachmentFans: {},
availability: { type: "inputRequired" },
} as LegalActionsResult["viewerInteraction"];

Expand Down
8 changes: 8 additions & 0 deletions client/src/adapter/engine-worker-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import type {
ViewerSnapshot,
} from "./types";
import { AdapterError, AdapterErrorCode } from "./types";
import type { InteractionSubmission } from "./generated/interaction";
import type { BracketDeckRequest, BracketEstimate } from "../types/bracketEstimate";
import { debugLog } from "../game/debugLog";
import { notifyEngineSlow } from "../game/engineRecovery";
Expand Down Expand Up @@ -238,6 +239,13 @@ export class EngineWorkerClient {
);
}

async submitInteraction(actor: number, submission: InteractionSubmission): Promise<SubmitResult> {
return this.request<SubmitResult>(
{ type: "submitInteraction", actor, submission },
ENGINE_REQUEST_TIMEOUT_MS,
);
}

async previewManaPayment(actor: number, action: GameAction): Promise<number[]> {
return this.request<number[]>(
{ type: "previewManaPayment", actor, action },
Expand Down
16 changes: 16 additions & 0 deletions client/src/adapter/engine-worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import init, {
take_last_panic_message,
initialize_game,
submit_action,
submit_interaction_js,
get_game_state,
get_filtered_game_state,
get_ai_action,
Expand Down Expand Up @@ -43,6 +44,7 @@ import init, {
} from "@wasm/engine";

import type { GameAction } from "./types";
import type { InteractionSubmission } from "./generated/interaction";
import type { BracketDeckRequest } from "../types/bracketEstimate";

// ── Message Protocol ─────────────────────────────────────────────────────
Expand All @@ -61,6 +63,7 @@ type EngineRequest =
firstPlayer?: number;
}
| { type: "submitAction"; id: number; actor: number; action: GameAction }
| { type: "submitInteraction"; id: number; actor: number; submission: InteractionSubmission }
| { type: "previewManaPayment"; id: number; actor: number; action: GameAction }
| { type: "getState"; id: number }
| { type: "getFilteredState"; id: number; viewerId: number }
Expand Down Expand Up @@ -281,6 +284,19 @@ self.onmessage = async (e: MessageEvent<EngineRequest>) => {
break;
}

case "submitInteraction": {
const actionResult = submit_interaction_js(msg.actor, msg.submission);
if (typeof actionResult === "string") {
error(msg.id, actionResult);
break;
}
result(msg.id, {
events: actionResult.events ?? [],
log_entries: actionResult.log_entries ?? [],
});
break;
}

case "previewManaPayment": {
const sources = preview_mana_payment_js(msg.actor, msg.action);
if (typeof sources === "string") {
Expand Down
8 changes: 7 additions & 1 deletion client/src/adapter/generated/interaction/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ export type InteractionActionId = string & { readonly __brand: "InteractionActio

export type PreviewRequestId = string & { readonly __brand: "PreviewRequestId" };

export type InteractionObjectReference = string & { readonly __brand: "InteractionObjectReference" };

export type InteractionSlotKind = "single" | "mulligan" | "openingBottom";

export type ActiveInteractionSlot = { semanticOwner: number, slotKind: InteractionSlotKind, interactionId: InteractionId, };
Expand Down Expand Up @@ -99,9 +101,13 @@ export type InteractionProgress = { selected: number, minimum: number, maximum:

export type InteractionOpportunity = { interactionId: InteractionId, response: InteractionOpportunityResponse, surfaces: Array<InteractionPresentationSurface>, progress: InteractionProgress, };

export type InteractionAttachmentFanChild = { objectId: number, submission: InteractionSubmission, };

export type InteractionAttachmentFan = { hostId: number, children: Array<InteractionAttachmentFanChild>, };

export type InteractionAvailability = { "type": "progressAvailable", "data": { witness: InteractionSubmission, } } | { "type": "inputRequired" } | { "type": "escapeOnly", "data": { reason: InteractionReasonCode, } } | { "type": "waiting" } | { "type": "terminal", "data": { outcome: InteractionOutcomeCode, } } | { "type": "unsupported", "data": { reason: InteractionReasonCode, } } | { "type": "stuck", "data": { reason: InteractionReasonCode, } };

export type ViewerInteraction = { waitingForKind: InteractionWaitingForKind, authorizedSubmitters: Array<number>, canSubmit: boolean, autoPassRecommended: boolean, opportunities: Array<InteractionOpportunity>, availability: InteractionAvailability, };
export type ViewerInteraction = { waitingForKind: InteractionWaitingForKind, authorizedSubmitters: Array<number>, canSubmit: boolean, autoPassRecommended: boolean, opportunities: Array<InteractionOpportunity>, attachmentFans: Record<number, InteractionAttachmentFan>, availability: InteractionAvailability, };

export type AmountAssignment = { choiceId: InteractionChoiceId, amount: number, };

Expand Down
87 changes: 87 additions & 0 deletions client/src/adapter/p2p-adapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import type {
SubmitResult,
WaitingFor,
} from "./types";
import type { InteractionSubmission } from "./generated/interaction";
import type { BracketDeckRequest, BracketEstimate } from "../types/bracketEstimate";

import { AdapterError, AdapterErrorCode, EMPTY_LEGAL_ACTIONS, actionRejectionError, nextSnapshotSeq } from "./types";
Expand Down Expand Up @@ -260,6 +261,13 @@ class NativeP2PBridge {
return this.clientFor(playerId).submitAction(action, playerId);
}

async submitInteraction(
submission: InteractionSubmission,
playerId: PlayerId,
): Promise<SubmitResult> {
return this.clientFor(playerId).submitInteraction(submission, playerId);
}

async previewManaPayment(action: GameAction, playerId: PlayerId): Promise<ObjectId[]> {
return this.clientFor(playerId).previewManaPayment(action, playerId);
}
Expand Down Expand Up @@ -1534,6 +1542,26 @@ export class P2PHostAdapter implements EngineAdapter {
return result;
}

async submitInteraction(
submission: InteractionSubmission,
actor: PlayerId,
): Promise<SubmitResult> {
if (this.gameRunState !== "running") {
throw new AdapterError(
"P2P_PAUSED",
`Cannot submit interaction while game state is ${this.gameRunState}`,
true,
);
}
const result = this.nativeBridge
? await this.nativeBridge.submitInteraction(submission, actor)
: await this.wasm.submitInteraction(submission, actor);
await this.broadcastStateUpdate(result.events, result.log_entries);
await this.runAiLoop();
this.persistAuthoritativeState();
return result;
}

async previewManaPayment(action: GameAction, actor: PlayerId): Promise<ObjectId[]> {
if (this.gameRunState !== "running") {
throw new AdapterError(
Expand Down Expand Up @@ -1818,6 +1846,44 @@ export class P2PHostAdapter implements EngineAdapter {
}
break;
}
case "interaction": {
const session = this.guestSessions.get(pid);
if (!session || msg.senderPlayerId !== pid) {
if (session) session.send({ type: "action_rejected", reason: "senderPlayerId mismatch" });
return;
}
if (this.eliminatedSeats.has(pid) || this.gameRunState !== "running") {
session.send({
type: "action_rejected",
reason: this.eliminatedSeats.has(pid)
? "Player has conceded and can no longer act"
: `Game ${this.gameRunState}`,
});
return;
}
try {
const result = this.nativeBridge
? await this.nativeBridge.submitInteraction(msg.submission, pid)
: await this.wasm.submitInteraction(msg.submission, pid);
await this.broadcastStateUpdate(result.events, result.log_entries);
await this.runAiLoop();
this.persistAuthoritativeState();
if (!this.nativeBridge) {
this.emit({
type: "stateChanged",
snapshot: await this.wasm.getSnapshot(),
events: result.events,
logEntries: result.log_entries,
});
}
} catch (err) {
session.send({
type: "action_rejected",
reason: err instanceof Error ? err.message : String(err),
});
}
break;
}
case "preview_mana_payment": {
const session = this.guestSessions.get(pid);
if (!session) return;
Expand Down Expand Up @@ -2316,6 +2382,27 @@ export class P2PGuestAdapter implements EngineAdapter {
});
}

async submitInteraction(
submission: InteractionSubmission,
_actor: PlayerId,
): Promise<SubmitResult> {
if (!this.session) {
throw new AdapterError("P2P_ERROR", "Not connected to host", true);
}
if (this.assignedPlayerId === null) {
throw new AdapterError("P2P_ERROR", "Not yet assigned a player ID", true);
}
return new Promise<SubmitResult>((resolve, reject) => {
this.pendingResolve = resolve;
this.pendingReject = reject;
this.session!.send({
type: "interaction",
senderPlayerId: this.assignedPlayerId!,
submission,
});
});
}

async previewManaPayment(action: GameAction, _actor: PlayerId): Promise<ObjectId[]> {
if (!this.session) {
throw new AdapterError("P2P_ERROR", "Not connected to host", true);
Expand Down
25 changes: 25 additions & 0 deletions client/src/adapter/server-draft-adapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import type {
PlayerId,
SubmitResult,
} from "./types";
import type { InteractionSubmission } from "./generated/interaction";
import { actionRejectionError, AdapterError, AdapterErrorCode, EMPTY_LEGAL_ACTIONS, nextSnapshotSeq } from "./types";
import type { BracketDeckRequest, BracketEstimate } from "../types/bracketEstimate";
import {
Expand Down Expand Up @@ -199,6 +200,30 @@ export class ServerDraftAdapter implements EngineAdapter {
});
}

async submitInteraction(
submission: InteractionSubmission,
_actor: PlayerId,
): Promise<SubmitResult> {
if (this.phase !== "match") {
throw new AdapterError("PHASE_ERROR", "Not in a match phase", false);
}
if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
throw new AdapterError("WS_ERROR", "WebSocket not connected", false);
}

this.emit({ type: "actionPendingChanged", pending: true });
return new Promise<SubmitResult>((resolve, reject) => {
this.pendingResolve = resolve;
this.pendingReject = reject;
if (!this.send({ type: "Interaction", data: { submission } })) {
this.pendingResolve = null;
this.pendingReject = null;
this.emit({ type: "actionPendingChanged", pending: false });
reject(new AdapterError("WS_CLOSED", "Failed to send interaction", true));
}
});
}

async previewManaPayment(action: GameAction, _actor: PlayerId): Promise<ObjectId[]> {
if (this.phase !== "match") {
throw new AdapterError("PHASE_ERROR", "Not in a match phase", false);
Expand Down
9 changes: 8 additions & 1 deletion client/src/adapter/types.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
import type { BracketDeckRequest, BracketEstimate } from "../types/bracketEstimate";
import type { InteractionActionId, ViewerInteraction } from "./generated/interaction";
import type {
InteractionActionId,
InteractionSubmission,
ViewerInteraction,
} from "./generated/interaction";

// ── Identifiers ──────────────────────────────────────────────────────────

Expand Down Expand Up @@ -3233,6 +3237,7 @@ export const AdapterErrorCode = {
* original dispatch.
*/
ENGINE_UNRESPONSIVE: "ENGINE_UNRESPONSIVE",
UNSUPPORTED: "UNSUPPORTED",
WASM_ERROR: "WASM_ERROR",
INVALID_ACTION: "INVALID_ACTION",
DECK_REJECTED: "DECK_REJECTED",
Expand Down Expand Up @@ -3518,6 +3523,8 @@ export interface EngineAdapter {
* action payload or the UI state.
*/
submitAction(action: GameAction, actor: PlayerId): Promise<SubmitResult>;
/** Submit an opaque response from the engine's current interaction projection. */
submitInteraction?(submission: InteractionSubmission, actor: PlayerId): Promise<SubmitResult>;
/**
* Read-only preview of the exact automatic `CastSpell` action currently
* offered by the engine. Unsupported transports omit this capability.
Expand Down
22 changes: 22 additions & 0 deletions client/src/adapter/wasm-adapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import type {
ViewerSnapshot,
WaitingFor,
} from "./types";
import type { InteractionSubmission } from "./generated/interaction";
import { AdapterError, AdapterErrorCode, isStaleRejectionMessage, isStateLostMessage, nextSnapshotSeq } from "./types";
import type { BracketDeckRequest, BracketEstimate } from "../types/bracketEstimate";
import { isBracketEstimate } from "../types/bracketEstimate";
Expand Down Expand Up @@ -278,6 +279,19 @@ export class WasmAdapter implements EngineAdapter {
}
}

async submitInteraction(
submission: InteractionSubmission,
actor: PlayerId,
): Promise<SubmitResult> {
this.assertInitialized();
try {
if (this.engine) return await this.engine.submitInteraction(actor, submission);
return await this.fallback!.submitInteraction(submission, actor);
} catch (err) {
throw await classifyEngineErrorAsync(err, this.takePanic);
}
}

async previewManaPayment(action: GameAction, actor: PlayerId): Promise<ObjectId[]> {
this.assertInitialized();
try {
Expand Down Expand Up @@ -838,6 +852,7 @@ export class WasmAdapter implements EngineAdapter {
interface MainThreadFallback {
ensureCardDatabase(): Promise<number>;
submitAction(action: GameAction, actor: PlayerId): Promise<SubmitResult>;
submitInteraction(submission: InteractionSubmission, actor: PlayerId): Promise<SubmitResult>;
previewManaPayment(action: GameAction, actor: PlayerId): Promise<ObjectId[]>;
getState(): Promise<GameState>;
getFilteredState(viewerId: number): Promise<GameState>;
Expand Down Expand Up @@ -894,6 +909,13 @@ async function createMainThreadFallback(): Promise<MainThreadFallback> {
return { events: r.events ?? [], log_entries: r.log_entries ?? [] };
}),

submitInteraction: (submission: InteractionSubmission, actor: PlayerId) =>
enqueue(() => {
const r = wasm.submit_interaction_js(actor, submission);
if (typeof r === "string") throw new Error(r);
return { events: r.events ?? [], log_entries: r.log_entries ?? [] };
}),

previewManaPayment: (action: GameAction, actor: PlayerId) =>
enqueue(() => {
const sources = wasm.preview_mana_payment_js(actor, action);
Expand Down
22 changes: 22 additions & 0 deletions client/src/adapter/ws-adapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import type {
SubmitResult,
FormatConfig,
} from "./types";
import type { InteractionSubmission } from "./generated/interaction";
import { AdapterError, AdapterErrorCode, EMPTY_LEGAL_ACTIONS, actionRejectionError, nextSnapshotSeq } from "./types";
import type { BracketDeckRequest, BracketEstimate } from "../types/bracketEstimate";
import {
Expand Down Expand Up @@ -637,6 +638,27 @@ export class WebSocketAdapter implements EngineAdapter {
});
}

async submitInteraction(
submission: InteractionSubmission,
_actor: PlayerId,
): Promise<SubmitResult> {
if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
throw new AdapterError("WS_ERROR", "WebSocket not connected", false);
}

this.emit({ type: "actionPendingChanged", pending: true });
return new Promise<SubmitResult>((resolve, reject) => {
this.pendingResolve = resolve;
this.pendingReject = reject;
if (!this.send({ type: "Interaction", data: { submission } })) {
this.pendingResolve = null;
this.pendingReject = null;
this.emit({ type: "actionPendingChanged", pending: false });
reject(new AdapterError("WS_CLOSED", "Failed to send interaction", true));
}
});
}

async previewManaPayment(action: GameAction, _actor: PlayerId): Promise<ObjectId[]> {
if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
throw new AdapterError("WS_ERROR", "WebSocket not connected", false);
Expand Down
Loading
Loading