Skip to content
Open
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
2 changes: 1 addition & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,7 @@ Each `quizGroupId` uses two AnyCable public streams:

Answers are POSTed to a serverless function, which broadcasts to the `:results` stream via AnyCable's HTTP broadcast API. This keeps the broadcast key server-side.

The presenter sends one sync request at a time, built from the state at the moment it is sent, at most every 200ms. A failed or hung request (10s timeout) is retried with backoff, always with the latest state, and a phone joining or the presenter reconnecting triggers a resend (at most every 2 seconds), and a keepalive resends the state every 60 seconds, also when no question is active, so the sync stream's history (five minutes on AnyCable by default) always holds the current state for phones that join or reconnect. Only a deck window that has activated a question broadcasts; every window that opens the deck runs a presenter manager. Phones retry a lost connection within a second, then at most every 3 seconds, and abandon a handshake with no answer after 6 seconds (8 for later attempts). Every sync carries a `seq` that increases per presenter tab, saved with the presenter state so it survives a reload; phones drop a broadcast older than one they already applied, which can happen when a timed-out request still reaches AnyCable. Phones apply incoming sync 100ms after it arrives, using the latest message, so a history replay applies only its newest state.
The presenter sends one sync request at a time, built from the state at the moment it is sent, at most every 200ms. A failed or hung request (10s timeout) is retried with backoff, always with the latest state, and a phone joining or the presenter reconnecting triggers a resend (at most every 2 seconds), and a keepalive resends the state every 60 seconds, also when no question is active, so the sync stream's history (five minutes on AnyCable by default) always holds the current state for phones that join or reconnect. Only a deck window that has activated a question broadcasts; every window that opens the deck runs a presenter manager. Phones retry a lost connection within a second, then at most every 3 seconds, and abandon a handshake with no answer after 6 seconds (8 for later attempts). Every sync carries a `seq` that increases per presenter tab, saved with the presenter state so it survives a reload; phones drop a broadcast older than one they already applied, which can happen when a timed-out request still reaches AnyCable. Phones apply incoming sync 100ms after it arrives, using the latest message, so a history replay applies only its newest state. The sync payload carries each question's total only (`votes: {}`); phones display nothing else, and only the presenter keeps the full tally. An answer request is aborted after 8 seconds and retried twice on a network error, timeout or 5xx. Every answer carries a `seq` that increases per phone (and across reloads, since it starts from the clock); retries reuse it, and the presenter, which saves it with each session's vote, ignores an answer whose `seq` is not above the one it counted.

## CSS for Motion, JS for State

Expand Down
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,16 @@ The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).

## Unreleased

Copy the serverless functions again: `quiz-answer` forwards the new `seq` field. Audience pages load the phone code from the CDN (`slide-quiz@0.7`), so they get the answer retries without a new copy of `quiz.html`; older functions accept the extra field.

### slide-quiz

#### Fixed
- An answer sent on bad wifi could leave the phone on "Sending..." with its buttons disabled for minutes, since the request had no timeout. An answer request is now aborted after 8 seconds, and a request that fails on the network, times out or gets a server error is retried twice, about 1 and 2 seconds later. The phone shows the error only after the last attempt fails; a request the function rejects (4xx) is not retried.
- With answers retried, a slow request could reach the presenter after the same phone's newer answer and replace it. Each answer now carries a `seq` that increases per phone, and the presenter ignores an answer older than one it already counted from that phone, also after a presenter reload. This needs the updated `quiz-answer` function; with an older one the presenter counts answers in the order they arrive, as before.

#### Changed
- The sync broadcast carries each question's total without the per-option tally, since phones show only how many people answered. Every phone receives every broadcast, and a free-text question's tally grows with each distinct answer, so on a busy word cloud this was most of the traffic. The payload keeps its shape (`votes` is empty), so older audience pages accept it. A custom audience page that read `votes` from `ParticipantQuizManager` gets an empty object now; the presenter still has the full tally.
- Accepts Reveal.js 6. Installing slide-quiz into a deck on Reveal.js 6 failed with a peer dependency conflict; the plugin itself needed no change. In TypeScript, pass the Reveal.js options through a variable (see the README), since Reveal.js 6's `RevealConfig` type does not list plugin options.

## 0.7.2 (slide-quiz) / 0.5.2 (slidev-addon-slide-quiz), 2026-10-15
Expand Down
3 changes: 2 additions & 1 deletion functions/netlify/quiz-answer.mts
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,14 @@ import { broadcastTo, jsonResponse, handle, broadcastFailed, AnswerSchema, resul

export default handle(
AnswerSchema,
async ({ quizId, answer, sessionId, quizGroupId }) => {
async ({ quizId, answer, sessionId, quizGroupId, seq }) => {
console.log("[quiz-answer]", { quizId, answer, quizGroupId });
try {
await broadcastTo(resultsStream(quizGroupId), {
quizId,
answer,
sessionId,
seq,
});
console.log("[quiz-answer] broadcast ok");
} catch (err) {
Expand Down
1 change: 1 addition & 0 deletions functions/netlify/shared.mts
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ export const AnswerSchema = v.object({
answer: v.pipe(v.string(), v.minLength(1)),
sessionId: v.pipe(v.string(), v.minLength(1)),
quizGroupId: v.pipe(v.string(), v.minLength(1)),
seq: v.optional(v.number()),
});

const VoteStateSchema = v.object({
Expand Down
3 changes: 2 additions & 1 deletion functions/vercel/quiz-answer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,14 @@ import { broadcastTo, jsonResponse, handle, broadcastFailed, AnswerSchema, resul

const handler = handle(
AnswerSchema,
async ({ quizId, answer, sessionId, quizGroupId }) => {
async ({ quizId, answer, sessionId, quizGroupId, seq }) => {
console.log("[quiz-answer]", { quizId, answer, quizGroupId });
try {
await broadcastTo(resultsStream(quizGroupId), {
quizId,
answer,
sessionId,
seq,
});
console.log("[quiz-answer] broadcast ok");
} catch (err) {
Expand Down
1 change: 1 addition & 0 deletions functions/vercel/shared.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ export const AnswerSchema = v.object({
answer: v.pipe(v.string(), v.minLength(1)),
sessionId: v.pipe(v.string(), v.minLength(1)),
quizGroupId: v.pipe(v.string(), v.minLength(1)),
seq: v.optional(v.number()),
});

const VoteStateSchema = v.object({
Expand Down
138 changes: 111 additions & 27 deletions src/quiz-manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,14 @@ const SYNC_RETRY_MAX_MS = 10_000;
// Minimum gap for a resend when nothing changed (a phone joined, a connection
// came back). A room of phones joining at once shares one resend.
const SYNC_REFRESH_GAP_MS = 2_000;
// An answer request that takes longer is aborted. Wifi that accepts a
// connection and then carries nothing would otherwise leave the phone on
// "Sending..." for minutes.
const ANSWER_TIMEOUT_MS = 8_000;
// Attempts per answer when the network or the function fails; the n-th retry
// waits about n × ANSWER_RETRY_MS, with jitter so a room of phones spreads out.
const ANSWER_ATTEMPTS = 3;
const ANSWER_RETRY_MS = 1_000;

// ── Throttle utility ──

Expand Down Expand Up @@ -159,6 +167,16 @@ export function isValidSyncPayload(data: unknown): data is SyncPayload {
return v.safeParse(SyncPayloadSchema, data).success;
}

/**
* Phones show only how many people answered, so the sync broadcast carries
* each question's total without the per-option tally. Every phone receives
* every broadcast, and a free-text question's tally grows with every distinct
* answer. The shape stays the same, so older audience pages accept it.
*/
function totalsOnly(results: Record<string, VoteState>): Record<string, VoteState> {
return Object.fromEntries(Object.entries(results).map(([quizId, { total }]) => [quizId, { votes: {}, total }]));
}

export function isValidAnswerPayload(data: unknown): data is AnswerPayload {
return v.safeParse(AnswerPayloadSchema, data).success;
}
Expand Down Expand Up @@ -608,8 +626,11 @@ export class PresenterQuizManager extends QuizManager {
this.sessionVotes.set(quizId, new Map());
}
const quizVotes = this.sessionVotes.get(quizId)!;
const previousKeys = quizVotes.get(sessionId)?.keys;
quizVotes.set(sessionId, { answer: data.answer, keys });
const previous = quizVotes.get(sessionId);
// A retried or slow request can arrive after the phone's newer answer
if (data.seq !== undefined && previous?.seq !== undefined && data.seq <= previous.seq) return;
const previousKeys = previous?.keys;
quizVotes.set(sessionId, { answer: data.answer, keys, ...(data.seq !== undefined && { seq: data.seq }) });

if (previousKeys && JSON.stringify(previousKeys) === JSON.stringify(keys)) return; // Same answer — no-op

Expand Down Expand Up @@ -703,7 +724,7 @@ export class PresenterQuizManager extends QuizManager {
activeQuestionId: activeId,
sessionId: this.sessionId,
quizGroupId: this.quizGroupId,
results: this.store.results.get(),
results: totalsOnly(this.store.results.get()),
question: questionIndex >= 0 ? questions[questionIndex] : undefined,
questionIndex,
totalCount: questions.length,
Expand Down Expand Up @@ -838,6 +859,13 @@ export class PresenterQuizManager extends QuizManager {
export class ParticipantQuizManager extends QuizManager {
private onSyncThrottled: ReturnType<typeof throttle>;
private lastSeq: { sessionId: string; seq: number } | undefined;
// Numbers every answer this phone sends, so the presenter can ignore one
// that arrives after a newer answer. Saved for the tab like its session id,
// so it keeps increasing after a reload, even if the clock moved back.
private answerSeq = 0;
private latestAnswer = new Map<string, number>();
private answerRequests = new Set<AbortController>();
private stopped = false;
// Log the first state applied after each (re)connect: the line that tells
// whether a phone actually got the current question.
private awaitingState = true;
Expand All @@ -858,45 +886,100 @@ export class ParticipantQuizManager extends QuizManager {
this.restoreSubmitted();
}

/** Submit an answer (or change a previous one) */
/**
* Submit an answer (or change a previous one). A request that fails on the
* network, times out or gets a server error is retried; the promise settles
* once the answer is delivered or every attempt failed.
*/
async submitAnswer(quizId: string, answer: string): Promise<boolean> {
if (this.getVotedAnswer(quizId) === answer) return false; // Same answer — no-op

this.answerSeq = Math.max(this.answerSeq + 1, Date.now());
const seq = this.answerSeq;
try {
const res = await fetch(this.endpoints.answer, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
quizId,
answer,
sessionId: this.sessionId,
quizGroupId: this.quizGroupId,
}),
});
if (res.ok) {
this.store.submitted.setKey(quizId, answer);
this.saveSubmitted();
} else {
sessionStorage.setItem(`quiz-answer-seq-${this.quizGroupId}`, String(seq));
} catch {
/* ignore */
}
this.latestAnswer.set(quizId, seq);
const body = JSON.stringify({
quizId,
answer,
sessionId: this.sessionId,
quizGroupId: this.quizGroupId,
seq,
});

for (let attempt = 1; ; attempt++) {
const result = await this.postAnswer(body);
if (this.stopped) return false;
if (result.ok) {
// A newer answer to the same question may have been sent meanwhile
if (this.latestAnswer.get(quizId) === seq) {
this.store.submitted.setKey(quizId, answer);
this.saveSubmitted();
}
return true;
}
if (!result.retry || attempt === ANSWER_ATTEMPTS) {
this.emitError({
kind: "answer",
message: `Answer function returned ${res.status} from ${this.endpoints.answer}`,
cause: res.status,
message: result.message,
cause: result.cause,
context: { endpoint: this.endpoints.answer, quizGroupId: this.quizGroupId, quizId },
});
return false;
}
return res.ok;
const delay = ANSWER_RETRY_MS * attempt * (0.5 + Math.random());
console.warn(`[slide-quiz:participant] ${result.message}; retrying in ${(delay / 1000).toFixed(1)}s`);
await new Promise((resolve) => setTimeout(resolve, delay));
if (this.stopped) return false;
}
}

private async postAnswer(body: string): Promise<
{ ok: true } | { ok: false; retry: boolean; message: string; cause: unknown }
> {
const request = new AbortController();
this.answerRequests.add(request);
let timedOut = false;
const timeout = setTimeout(() => {
timedOut = true;
request.abort();
}, ANSWER_TIMEOUT_MS);
try {
const res = await fetch(this.endpoints.answer, {
method: "POST",
headers: { "Content-Type": "application/json" },
body,
signal: request.signal,
});
if (res.ok) return { ok: true };
return {
ok: false,
// A 4xx other than timeout and rate limit means the request itself is rejected
retry: res.status >= 500 || res.status === 408 || res.status === 429,
message: `Answer function returned ${res.status} from ${this.endpoints.answer}`,
cause: res.status,
};
} catch (err) {
this.emitError({
kind: "answer",
message: `Can't reach ${this.endpoints.answer}`,
return {
ok: false,
retry: true,
message: timedOut
? `${this.endpoints.answer} did not respond within ${ANSWER_TIMEOUT_MS / 1000}s`
: `Can't reach ${this.endpoints.answer}`,
cause: err,
context: { endpoint: this.endpoints.answer, quizGroupId: this.quizGroupId, quizId },
});
return false;
};
} finally {
clearTimeout(timeout);
this.answerRequests.delete(request);
}
}

override disconnect(): void {
this.stopped = true;
for (const request of this.answerRequests) request.abort();
this.onSyncThrottled.cancel();
this.syncChannel.presence.leave().catch(() => {});
super.disconnect();
Expand Down Expand Up @@ -991,6 +1074,7 @@ export class ParticipantQuizManager extends QuizManager {

private restoreSubmitted(): void {
try {
this.answerSeq = Number(sessionStorage.getItem(`quiz-answer-seq-${this.quizGroupId}`)) || 0;
const raw = sessionStorage.getItem(
`quiz-submitted-${this.quizGroupId}`,
);
Expand Down
4 changes: 4 additions & 0 deletions src/quiz-types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,8 @@ export const AnswerPayloadSchema = v.object({
quizId: v.string(),
answer: v.string(),
sessionId: v.string(),
/** Increases with every answer from one phone. Absent from functions older than 0.7.3. */
seq: v.optional(v.number()),
});
export type AnswerPayload = v.InferOutput<typeof AnswerPayloadSchema>;

Expand Down Expand Up @@ -190,6 +192,8 @@ export type ParticipantConfig = v.InferOutput<typeof ParticipantConfigSchema>;
export const SessionVoteSchema = v.object({
answer: v.string(),
keys: v.array(v.string()),
/** The answer's sequence number, if the function forwarded one */
seq: v.optional(v.number()),
});
export type SessionVote = v.InferOutput<typeof SessionVoteSchema>;

Expand Down
38 changes: 35 additions & 3 deletions tests/functions.test.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
// @vitest-environment node
import { describe, it, expect, vi, beforeAll, afterAll } from "vitest";

// AnyCable is down: every broadcast fails the way a wrong URL or key does
// By default AnyCable is down: every broadcast fails the way a wrong URL or key does
const broadcast = vi.hoisted(() => ({ fails: true, sent: [] as unknown[][] }));
vi.mock("@anycable/serverless-js", () => ({
broadcaster: () => async () => {
throw new Error("connect ECONNREFUSED");
broadcaster: () => async (...args: unknown[]) => {
if (broadcast.fails) throw new Error("connect ECONNREFUSED");
broadcast.sent.push(args);
},
}));

Expand Down Expand Up @@ -49,3 +51,33 @@ describe("serverless functions when the broadcast fails", () => {
});
}
});

describe("quiz-answer", () => {
beforeAll(() => {
broadcast.fails = false;
vi.spyOn(console, "log").mockImplementation(() => {});
});
afterAll(() => {
broadcast.fails = true;
vi.restoreAllMocks();
});

const handlers = [
["netlify", async () => (await import("../functions/netlify/quiz-answer.mts")).default],
["vercel", async () => (await import("../functions/vercel/quiz-answer")).POST],
] as const;

for (const [name, load] of handlers) {
it(`${name} forwards the answer's number to the presenter`, async () => {
const handler = (await load()) as (req: Request) => Promise<Response>;
broadcast.sent.length = 0;
const res = await handler(new Request("https://deck.example/fn", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ quizId: "q1", answer: "A", sessionId: "s1", quizGroupId: "g1", seq: 42 }),
}));
expect(res.status).toBe(200);
expect(broadcast.sent).toEqual([["quiz:g1:results", { quizId: "q1", answer: "A", sessionId: "s1", seq: 42 }]]);
});
}
});
Loading
Loading