feat(assessment): add the review band of attempt signals and the disclosed collector

This commit is contained in:
shira committed 2026-10-08 23:04:57 +03:00
1 parent 68286af8b7
commit b3c6dc870b
124 files changed
+13522 -633

No files matched your search

@@ -1,20 +1,24 @@
import { useQuery, type QueryClient } from "@tanstack/react-query";
import {
acknowledgeMyAssessmentSignalNotice,
getMyAssessmentAvailability,
getMyAssessmentAttempt,
getMyAssessmentResult,
getMyAssessmentSignalNotice,
} from "../../../shared/api/endpoints/assessment/assessment";
import { getMyQuestionnaire } from "../../../shared/api/endpoints/candidate/candidate";
import type {
AssessmentAttempt,
AssessmentAvailability,
AssessmentResult,
AssessmentSignalNotice,
Session,
} from "../../../shared/api/schemas";
import {
parseAssessmentAvailabilityResponse,
parseAssessmentAttemptResponse,
parseAssessmentResultResponse,
parseAssessmentSignalNoticeResponse,
parseCandidateQuestionnaireResponse,
} from "../model/contract-validation";
import { assessmentQueryKeys, assertCurrentAssessmentSession } from "../model/session";
@@ -119,4 +123,50 @@ export function useAssessmentResult({
});
}
/**
* Server-owned state of the notice about the collected signals. It is read
* again on mount so an acknowledgement made in another window or browser is
* honored and a reload never asks twice.
*/
export function useAssessmentSignalNotice({
actor,
enabled = true,
queryClient,
}: AssessmentQueryOptions) {
return useQuery<AssessmentSignalNotice, Error>({
queryKey: actor
? assessmentQueryKeys.signalNotice(actor)
: [...assessmentQueryKeysPrefix, "signal-notice"],
enabled: Boolean(actor && enabled),
...privateQueryOptions,
queryFn: async ({ signal }) => {
assertCurrentAssessmentSession(queryClient, actor);
const response = await getMyAssessmentSignalNotice({ signal });
assertCurrentAssessmentSession(queryClient, actor);
return parseAssessmentSignalNoticeResponse(response);
},
});
}
/**
* Records that the candidate read the notice of the given version and stores
* the server answer in the query cache. The request is idempotent on the
* server, so a retry after a lost response is safe.
*/
export async function acknowledgeAssessmentSignalNotice(
queryClient: QueryClient,
actor: Session,
noticeVersion: number,
): Promise<AssessmentSignalNotice> {
assertCurrentAssessmentSession(queryClient, actor);
const response = await acknowledgeMyAssessmentSignalNotice(
{ notice_version: noticeVersion },
{ headers: { "X-CSRF-Token": actor.csrf_token } },
);
const notice = parseAssessmentSignalNoticeResponse(response);
assertCurrentAssessmentSession(queryClient, actor);
queryClient.setQueryData(assessmentQueryKeys.signalNotice(actor), notice);
return notice;
}
const assessmentQueryKeysPrefix = ["candidate-assessment"] as const;
@@ -1,8 +1,10 @@
export {
acknowledgeAssessmentSignalNotice,
useAssessmentAttempt,
useAssessmentAvailability,
useAssessmentQuestionnaire,
useAssessmentResult,
useAssessmentSignalNotice,
} from "./api/assessment-queries";
export {
assessmentQueryKeys,
@@ -5,6 +5,7 @@ import {
parseAssessmentAvailabilityResponse,
parseAssessmentAttemptResponse,
parseAssessmentResultResponse,
parseAssessmentSignalNoticeResponse,
parseCandidateQuestionnaireResponse,
} from "./contract-validation";
@@ -90,4 +91,17 @@ describe("assessment response contract validation", () => {
expect.objectContaining({ status: 200, code: invalidResponseCode }),
);
});
it("accepts the signal notice before and after the acknowledgement", () => {
const pending = { notice_version: 1, acknowledged: false, acknowledged_at: null };
const done = { notice_version: 1, acknowledged: true, acknowledged_at: "2026-10-08T10:00:00Z" };
expect(parseAssessmentSignalNoticeResponse(pending)).toEqual(pending);
expect(parseAssessmentSignalNoticeResponse(done)).toEqual(done);
});
it("rejects an incomplete signal notice payload", () => {
expect(() => parseAssessmentSignalNoticeResponse({ notice_version: 1 })).toThrowError(
expect.objectContaining({ code: invalidResponseCode }),
);
});
});
@@ -3,10 +3,12 @@ import {
AssessmentAttempt as assessmentAttemptSchema,
AssessmentAvailability as assessmentAvailabilitySchema,
AssessmentResult as assessmentResultSchema,
AssessmentSignalNotice as assessmentSignalNoticeSchema,
CandidateQuestionnaire as candidateQuestionnaireSchema,
type AssessmentAttempt,
type AssessmentAvailability,
type AssessmentResult,
type AssessmentSignalNotice,
type CandidateQuestionnaire,
} from "../../../shared/api/schemas";
@@ -47,3 +49,12 @@ export function parseAssessmentResultResponse(value: unknown, status = 200): Ass
if (!parsed.success) throw invalidAssessmentResponse(status);
return parsed.data;
}
export function parseAssessmentSignalNoticeResponse(
value: unknown,
status = 200,
): AssessmentSignalNotice {
const parsed = assessmentSignalNoticeSchema.safeParse(value);
if (!parsed.success) throw invalidAssessmentResponse(status);
return parsed.data;
}
@@ -47,6 +47,8 @@ export const assessmentQueryKeys = {
[...assessmentQueryPrefix, actor.account.id, actor.csrf_token, "attempt", attemptId] as const,
result: (actor: Session, attemptId: string) =>
[...assessmentQueryPrefix, actor.account.id, actor.csrf_token, "result", attemptId] as const,
signalNotice: (actor: Session) =>
[...assessmentQueryPrefix, actor.account.id, actor.csrf_token, "signal-notice"] as const,
};
export function removeAssessmentQueries(queryClient: QueryClient): void {
@@ -0,0 +1,5 @@
export { useAssessmentSignals } from "./model/use-assessment-signals";
export { useSignalNoticeGate } from "./model/use-signal-notice-gate";
export type { SignalNoticeGate } from "./model/use-signal-notice-gate";
export { SignalNoticeDialog, SignalNoticeSummary } from "./ui/signal-notice";
export { shouldCollectSignals } from "./model/signal-session";
@@ -0,0 +1,259 @@
import { describe, expect, it, vi } from "vitest";
import { ApiRequestError, invalidResponseCode } from "../../../shared/api";
import type { AssessmentSignalEvent } from "../../../shared/api/schemas";
import {
classifySendFailure,
createSignalBatcher,
type SignalBatch,
type SignalSender,
} from "./batcher";
const itemId = "0198d3a0-0000-7000-8000-000000000001";
function event(index: number): AssessmentSignalEvent {
return {
kind: "copy",
item_instance_id: itemId,
occurred_at: new Date(Date.UTC(2026, 9, 8, 12, 0, index)).toISOString(),
size_bytes: index,
};
}
function apiError(status: number, extra: Partial<{ code: never; retryAfterSeconds: number }> = {}) {
return new ApiRequestError({
status,
code: (extra.code ?? (status === 0 ? "network_error" : "http_error")) as never,
title: "failure",
retryAfterSeconds: extra.retryAfterSeconds,
});
}
function harness(send: (batch: SignalBatch) => Promise<void>, overrides = {}) {
const timers: Array<{ id: number; delay: number; run: () => void }> = [];
let nextId = 1;
let keyCounter = 0;
const batcher = createSignalBatcher({
send,
newKey: () => `key-${++keyCounter}`,
schedule: (run, delay) => {
const timer = { id: nextId++, delay, run };
timers.push(timer);
return timer.id;
},
cancel: (handle) => {
const index = timers.findIndex((timer) => timer.id === handle);
if (index >= 0) timers.splice(index, 1);
},
...overrides,
});
const fire = async () => {
const timer = timers.shift();
if (!timer) throw new Error("no timer is scheduled");
timer.run();
await Promise.resolve();
await new Promise((resolve) => setTimeout(resolve, 0));
};
return { batcher, timers, fire };
}
describe("signal batcher", () => {
it("collects events and sends them as one batch after the interval", async () => {
const send = vi.fn<SignalSender>(async () => undefined);
const { batcher, timers, fire } = harness(send);
batcher.enqueue(event(1));
batcher.enqueue(event(2));
expect(send).not.toHaveBeenCalled();
expect(timers).toHaveLength(1);
expect(timers[0]?.delay).toBe(10_000);
await fire();
expect(send).toHaveBeenCalledTimes(1);
expect(send.mock.calls[0]?.[0]).toMatchObject({ key: "key-1", events: [event(1), event(2)] });
});
it("splits a large queue into batches of at most fifty events", async () => {
const send = vi.fn<SignalSender>(async () => undefined);
const { batcher, fire } = harness(send);
for (let index = 0; index < 120; index += 1) batcher.enqueue(event(index));
await fire();
const sizes = send.mock.calls.map(([batch]) => batch.events.length);
expect(sizes).toEqual([50, 50, 20]);
const keys = send.mock.calls.map(([batch]) => batch.key);
expect(new Set(keys).size).toBe(3);
});
it("retries a failed batch with the same key and the same events, once, without duplicates", async () => {
const calls: SignalBatch[] = [];
let online = false;
const send = vi.fn(async (batch: SignalBatch) => {
calls.push({ key: batch.key, events: [...batch.events] });
if (!online) throw apiError(0);
});
const { batcher, timers, fire } = harness(send);
batcher.enqueue(event(1));
await fire();
expect(calls).toHaveLength(1);
expect(timers).toHaveLength(1);
// An event that arrives while the retry waits joins the next batch, not the retried one.
batcher.enqueue(event(2));
expect(timers).toHaveLength(1);
online = true;
await fire();
expect(calls.map((call) => call.key)).toEqual(["key-1", "key-1", "key-2"]);
expect(calls[1]?.events).toEqual(calls[0]?.events);
expect(calls[2]?.events).toEqual([event(2)]);
expect(timers).toHaveLength(0);
});
it("backs off exponentially and abandons a batch after the attempt limit", async () => {
const send = vi.fn<SignalSender>(async () => {
throw apiError(503);
});
const { batcher, timers, fire } = harness(send, { maxAttempts: 3 });
batcher.enqueue(event(1));
await fire();
expect(timers[0]?.delay).toBe(2_000);
await fire();
expect(timers[0]?.delay).toBe(4_000);
await fire();
expect(send).toHaveBeenCalledTimes(3);
expect(timers).toHaveLength(0);
});
it("waits for the server's Retry-After on a rate limit", async () => {
const send = vi.fn<SignalSender>(async () => {
throw apiError(429, { retryAfterSeconds: 30 });
});
const { batcher, timers, fire } = harness(send);
batcher.enqueue(event(1));
await fire();
expect(timers[0]?.delay).toBe(30_000);
});
it("drops an unusable batch and keeps collecting", async () => {
const send = vi
.fn<(batch: SignalBatch) => Promise<void>>()
.mockRejectedValueOnce(apiError(400))
.mockResolvedValue(undefined);
const { batcher, fire } = harness(send, { flushThreshold: 1 });
batcher.enqueue(event(1));
await fire();
batcher.enqueue(event(2));
await fire();
expect(send).toHaveBeenCalledTimes(2);
expect(send.mock.calls[1]?.[0].events).toEqual([event(2)]);
});
it("stops collecting when the server refuses the attempt", async () => {
const send = vi.fn<SignalSender>(async () => {
throw apiError(403);
});
const { batcher, timers, fire } = harness(send);
batcher.enqueue(event(1));
await fire();
batcher.enqueue(event(2));
expect(timers).toHaveLength(0);
expect(send).toHaveBeenCalledTimes(1);
});
it("bounds the queue by dropping the oldest events", async () => {
const send = vi.fn<SignalSender>(async () => undefined);
const { batcher, fire } = harness(send, { maxQueuedEvents: 60, maxBatchEvents: 100 });
for (let index = 0; index < 100; index += 1) batcher.enqueue(event(index));
await fire();
const batch = send.mock.calls[0]?.[0];
expect(batch?.events).toHaveLength(60);
expect(batch?.events[0]).toEqual(event(40));
});
it("never lets a sender failure escape", async () => {
const { batcher, fire } = harness(async () => {
throw new TypeError("unexpected");
});
batcher.enqueue(event(1));
await expect(fire()).resolves.toBeUndefined();
expect(() => batcher.dispose()).not.toThrow();
});
it("dispose sends the remaining events once and then ignores new ones", async () => {
const send = vi.fn<SignalSender>(async () => undefined);
const { batcher, timers } = harness(send);
batcher.enqueue(event(1));
batcher.dispose();
expect(send).toHaveBeenCalledTimes(1);
expect(timers).toHaveLength(0);
batcher.enqueue(event(2));
expect(timers).toHaveLength(0);
});
});
describe("signal batcher on exit", () => {
it("sends the queued events once with keepalive and keeps working afterwards", async () => {
const send = vi.fn<SignalSender>(async () => undefined);
const { batcher, timers, fire } = harness(send);
batcher.enqueue(event(1));
batcher.flushOnExit();
expect(send).toHaveBeenCalledTimes(1);
expect(send.mock.calls[0]?.[1]).toEqual({ keepalive: true });
expect(timers).toHaveLength(0);
// The page may come back from the back/forward cache.
batcher.enqueue(event(2));
await fire();
expect(send).toHaveBeenCalledTimes(2);
expect(send.mock.calls[1]?.[1]).toBeUndefined();
});
it("takes over a batch that is waiting for its retry and does not schedule another", async () => {
const send = vi
.fn<SignalSender>()
.mockRejectedValueOnce(apiError(0))
.mockResolvedValue(undefined);
const { batcher, timers, fire } = harness(send);
batcher.enqueue(event(1));
await fire();
expect(timers).toHaveLength(1);
batcher.flushOnExit();
expect(send).toHaveBeenCalledTimes(2);
expect(send.mock.calls[1]?.[0].key).toBe(send.mock.calls[0]?.[0].key);
expect(send.mock.calls[1]?.[1]).toEqual({ keepalive: true });
expect(timers).toHaveLength(0);
});
it("sends nothing and fails nothing when the queue is empty or the send rejects", () => {
const send = vi.fn<SignalSender>(async () => {
throw apiError(0);
});
const { batcher } = harness(send);
batcher.flushOnExit();
expect(send).not.toHaveBeenCalled();
batcher.enqueue(event(1));
expect(() => batcher.flushOnExit()).not.toThrow();
expect(() => batcher.dispose()).not.toThrow();
});
it("dispose uses keepalive for the last send", () => {
const send = vi.fn<SignalSender>(async () => undefined);
const { batcher } = harness(send);
batcher.enqueue(event(1));
batcher.dispose();
expect(send.mock.calls[0]?.[1]).toEqual({ keepalive: true });
});
});
describe("classifySendFailure", () => {
it("separates temporary failures from permanent ones", () => {
expect(classifySendFailure(apiError(0)).kind).toBe("retry");
expect(classifySendFailure(apiError(502)).kind).toBe("retry");
expect(classifySendFailure(apiError(200, { code: invalidResponseCode as never })).kind).toBe(
"retry",
);
expect(classifySendFailure(apiError(403, { code: "csrf_check_failed" as never })).kind).toBe(
"retry",
);
expect(classifySendFailure(apiError(403)).kind).toBe("stop");
expect(classifySendFailure(apiError(401)).kind).toBe("stop");
expect(classifySendFailure(apiError(409)).kind).toBe("stop");
expect(classifySendFailure(apiError(422)).kind).toBe("drop");
expect(classifySendFailure(new Error("x")).kind).toBe("drop");
});
});
@@ -0,0 +1,179 @@
import { ApiRequestError, invalidResponseCode } from "../../../shared/api";
import type { AssessmentSignalEvent } from "../../../shared/api/schemas";
/** One request body with the key that makes its retries harmless. */
export type SignalBatch = { readonly key: string; readonly events: AssessmentSignalEvent[] };
/**
* Sends one batch. `keepalive` asks the transport to let the request outlive
* the page; it is set only for the final sends when the page is going away.
*/
export type SignalSender = (batch: SignalBatch, options?: { keepalive?: boolean }) => Promise<void>;
export type SignalBatcherOptions = {
send: SignalSender;
newKey: () => string;
/** Timer functions are injected so tests control time. */
schedule: (callback: () => void, delayMs: number) => unknown;
cancel: (handle: unknown) => void;
flushIntervalMs?: number;
/** Queue length that triggers an early send. */
flushThreshold?: number;
maxBatchEvents?: number;
/** Oldest events are dropped beyond this many, so memory stays bounded. */
maxQueuedEvents?: number;
/** Sends of one batch before it is abandoned. */
maxAttempts?: number;
baseBackoffMs?: number;
maxBackoffMs?: number;
};
export type SignalBatcher = {
/** Adds an event. Never throws and never waits for the network. */
enqueue(event: AssessmentSignalEvent): void;
/** Sends what is queued now, unless a failed batch is waiting for its retry. */
flush(): void;
/**
* Sends what is queued once, as a keepalive request, for a page that is
* going away. The result is not awaited and nothing is retried; the batcher
* stays usable in case the page is restored from the back/forward cache.
*/
flushOnExit(): void;
/** Stops the timers and makes one last keepalive send attempt without retries. */
dispose(): void;
};
type Verdict = { kind: "retry"; delayMs?: number } | { kind: "drop" } | { kind: "stop" };
/**
* Decides what a failed send means. Signals are a hint, so a failure is never
* shown and never reaches the answer flow: it only decides whether the same
* batch is sent again.
*
* - No response, a server error, an unreadable success body, a rate limit, and
* a rejected CSRF token are temporary: the same batch and key are sent again.
* - An unauthenticated, forbidden (for example without C3), unknown, or
* conflicting attempt will not improve: collection stops.
* - Any other client error means this batch is unusable: it is dropped.
*/
export function classifySendFailure(error: unknown): Verdict {
if (!(error instanceof ApiRequestError)) return { kind: "drop" };
if (error.status === 429) {
return { kind: "retry", delayMs: Math.max(error.retryAfterSeconds ?? 5, 1) * 1000 };
}
if (error.status === 403 && error.code === "csrf_check_failed") return { kind: "retry" };
if (error.status === 0 || error.status >= 500 || error.code === invalidResponseCode) {
return { kind: "retry" };
}
if ([401, 403, 404, 409].includes(error.status)) return { kind: "stop" };
return { kind: "drop" };
}
export function createSignalBatcher(options: SignalBatcherOptions): SignalBatcher {
const flushIntervalMs = options.flushIntervalMs ?? 10_000;
const flushThreshold = options.flushThreshold ?? 20;
const maxBatchEvents = options.maxBatchEvents ?? 50;
const maxQueuedEvents = options.maxQueuedEvents ?? 500;
const maxAttempts = options.maxAttempts ?? 8;
const baseBackoffMs = options.baseBackoffMs ?? 2_000;
const maxBackoffMs = options.maxBackoffMs ?? 60_000;
const queue: AssessmentSignalEvent[] = [];
let inFlight: SignalBatch | null = null;
let attempts = 0;
let timer: unknown = null;
let retryWaiting = false;
let running = false;
let stopped = false;
let disposed = false;
function clearTimer(): void {
if (timer !== null) options.cancel(timer);
timer = null;
}
function arm(delayMs: number): void {
clearTimer();
timer = options.schedule(() => {
timer = null;
retryWaiting = false;
void run();
}, delayMs);
}
function nextBatch(): SignalBatch | null {
if (queue.length === 0) return null;
return { key: options.newKey(), events: queue.splice(0, maxBatchEvents) };
}
async function run(): Promise<void> {
if (running || stopped || disposed) return;
running = true;
try {
while (!stopped && !disposed) {
if (!inFlight) {
inFlight = nextBatch();
attempts = 0;
if (!inFlight) return;
}
try {
await options.send(inFlight);
inFlight = null;
} catch (error: unknown) {
const verdict = classifySendFailure(error);
if (verdict.kind === "stop") {
stopped = true;
inFlight = null;
queue.length = 0;
return;
}
attempts += 1;
if (verdict.kind === "drop" || attempts >= maxAttempts) {
inFlight = null;
continue;
}
retryWaiting = true;
const backoff = Math.min(baseBackoffMs * 2 ** (attempts - 1), maxBackoffMs);
arm(Math.max(verdict.delayMs ?? 0, backoff));
return;
}
}
} finally {
running = false;
}
}
return {
enqueue(event) {
if (stopped || disposed) return;
queue.push(event);
if (queue.length > maxQueuedEvents) queue.shift();
if (running || retryWaiting) return;
if (queue.length >= flushThreshold) arm(0);
else if (timer === null) arm(flushIntervalMs);
},
flush() {
if (stopped || disposed || retryWaiting) return;
clearTimer();
void run();
},
flushOnExit() {
if (stopped || disposed || running) return;
clearTimer();
retryWaiting = false;
const last = inFlight ?? nextBatch();
inFlight = null;
if (last) void options.send(last, { keepalive: true }).catch(() => undefined);
},
dispose() {
if (disposed) return;
clearTimer();
const last = inFlight ?? nextBatch();
disposed = true;
if (last && !stopped && !running) {
// Best effort only: the answer flow never waits for this request.
void options.send(last, { keepalive: true }).catch(() => undefined);
}
},
};
}
@@ -0,0 +1,228 @@
import { describe, expect, it } from "vitest";
import type { AssessmentSignalEvent } from "../../../shared/api/schemas";
import { attachSignalCollector, type CollectorEnvironment } from "./collector";
const itemId = "0198d3a0-0000-7000-8000-000000000001";
class FakeDocument extends EventTarget {
visibilityState = "visible";
fullscreenElement: unknown = null;
focused = true;
activeElement: { selectionStart: number; selectionEnd: number } | null = null;
selected = "";
hasFocus(): boolean {
return this.focused;
}
getSelection() {
return { rangeCount: this.selected ? 1 : 0, toString: () => this.selected };
}
}
function setup(item: string | null = itemId) {
const doc = new FakeDocument();
const win = new EventTarget();
let clock = Date.UTC(2026, 9, 8, 12, 0, 0);
const events: AssessmentSignalEvent[] = [];
let hidden = 0;
const detach = attachSignalCollector({
environment: { document: doc, window: win, now: () => clock } as CollectorEnvironment,
currentItemId: () => item,
onEvent: (event) => events.push(event),
onHidden: () => {
hidden += 1;
},
});
return {
doc,
win,
events,
detach,
hidden: () => hidden,
advance: (ms: number) => {
clock += ms;
},
};
}
function pasteEvent(text: string, files: Array<{ size: number }> = []) {
const event = new Event("paste", { cancelable: true });
Object.defineProperty(event, "clipboardData", {
value: { types: ["text/plain"], files, getData: () => text },
});
return event;
}
describe("signal collector", () => {
it("records a paste with its size and never the text", () => {
const { doc, events } = setup();
const secret = "SECRET-ANSWER-TEXT";
const event = pasteEvent(secret);
doc.dispatchEvent(event);
expect(events).toHaveLength(1);
expect(events[0]).toMatchObject({ kind: "paste", item_instance_id: itemId, size_bytes: 18 });
expect(Object.keys(events[0] ?? {}).sort()).toEqual(
["item_instance_id", "kind", "occurred_at", "size_bytes"].sort(),
);
expect(JSON.stringify(events)).not.toContain(secret);
expect(event.defaultPrevented).toBe(false);
});
it("records copy and cut by selection length only", () => {
const { doc, events } = setup();
doc.activeElement = { selectionStart: 0, selectionEnd: 5 };
doc.dispatchEvent(new Event("copy"));
doc.activeElement = null;
doc.selected = "условие задачи";
doc.dispatchEvent(new Event("cut"));
expect(events.map((event) => event.kind)).toEqual(["copy", "cut"]);
expect(events.map((event) => ("size_bytes" in event ? event.size_bytes : -1))).toEqual([5, 14]);
});
it("measures the time away between hiding and showing the tab", () => {
const { doc, events, advance, hidden } = setup();
doc.visibilityState = "hidden";
doc.dispatchEvent(new Event("visibilitychange"));
expect(hidden()).toBe(1);
advance(7_250);
doc.visibilityState = "visible";
doc.dispatchEvent(new Event("visibilitychange"));
expect(events).toHaveLength(1);
expect(events[0]).toMatchObject({
kind: "focus_loss",
duration_ms: 7_250,
item_instance_id: itemId,
});
});
it("counts a window blur and focus as one absence, even with both signals", () => {
const { doc, win, events, advance } = setup();
doc.focused = false;
win.dispatchEvent(new Event("blur"));
doc.visibilityState = "hidden";
doc.dispatchEvent(new Event("visibilitychange"));
advance(3_000);
doc.visibilityState = "visible";
doc.dispatchEvent(new Event("visibilitychange"));
expect(events).toHaveLength(0);
doc.focused = true;
win.dispatchEvent(new Event("focus"));
expect(events).toHaveLength(1);
expect(events[0]).toMatchObject({ kind: "focus_loss", duration_ms: 3_000 });
});
it("waits for the window focus before ending an absence", () => {
const { doc, win, events, advance } = setup();
win.dispatchEvent(new Event("blur"));
advance(1_000);
doc.focused = false;
doc.dispatchEvent(new Event("visibilitychange"));
expect(events).toHaveLength(0);
doc.focused = true;
win.dispatchEvent(new Event("focus"));
expect(events).toHaveLength(1);
});
it("records only an exit from fullscreen, not entering it", () => {
const { doc, events } = setup();
doc.fullscreenElement = {};
doc.dispatchEvent(new Event("fullscreenchange"));
expect(events).toHaveLength(0);
doc.fullscreenElement = null;
doc.dispatchEvent(new Event("fullscreenchange"));
expect(events).toHaveLength(1);
expect(events[0]).toMatchObject({ kind: "fullscreen_exit" });
});
it("ignores events while no item is shown", () => {
const { doc, events } = setup(null);
doc.dispatchEvent(new Event("copy"));
expect(events).toHaveLength(0);
});
it("contains a failing consumer and stops after detach", () => {
const doc = new FakeDocument();
const detach = attachSignalCollector({
environment: {
document: doc,
window: new EventTarget(),
now: () => 0,
} as CollectorEnvironment,
currentItemId: () => itemId,
onEvent: () => {
throw new Error("consumer failure");
},
});
expect(() => doc.dispatchEvent(new Event("copy"))).not.toThrow();
detach();
const { events } = setup();
expect(events).toHaveLength(0);
});
it("maps timestamps to server time without changing durations", () => {
const doc = new FakeDocument();
const win = new EventTarget();
let clock = Date.UTC(2026, 9, 8, 12, 0, 0);
const events: AssessmentSignalEvent[] = [];
const offset = -3_600_000;
attachSignalCollector({
environment: {
document: doc,
window: win,
now: () => clock,
toServerTime: (deviceMs) => deviceMs + offset,
} as CollectorEnvironment,
currentItemId: () => itemId,
onEvent: (event) => events.push(event),
});
doc.visibilityState = "hidden";
doc.dispatchEvent(new Event("visibilitychange"));
const startedAt = clock;
clock += 4_000;
doc.visibilityState = "visible";
doc.dispatchEvent(new Event("visibilitychange"));
doc.dispatchEvent(new Event("copy"));
expect(events[0]).toMatchObject({
kind: "focus_loss",
duration_ms: 4_000,
occurred_at: new Date(startedAt + offset).toISOString(),
});
expect(events[1]?.occurred_at).toBe(new Date(clock + offset).toISOString());
});
it("reports the end of the page life", () => {
const doc = new FakeDocument();
const win = new EventTarget();
let exits = 0;
attachSignalCollector({
environment: { document: doc, window: win, now: () => 0 } as CollectorEnvironment,
currentItemId: () => itemId,
onEvent: () => undefined,
onPageHide: () => {
exits += 1;
},
});
win.dispatchEvent(new Event("pagehide"));
expect(exits).toBe(1);
});
it("registers passive listeners so input is never delayed", () => {
const doc = new FakeDocument();
const options: unknown[] = [];
const original = doc.addEventListener.bind(doc);
doc.addEventListener = ((type: string, listener: EventListener, opts?: unknown) => {
options.push(opts);
original(type, listener, opts as AddEventListenerOptions);
}) as typeof doc.addEventListener;
attachSignalCollector({
environment: {
document: doc,
window: new EventTarget(),
now: () => 0,
} as CollectorEnvironment,
currentItemId: () => itemId,
onEvent: () => undefined,
});
expect(options.length).toBeGreaterThan(0);
for (const entry of options) expect(entry).toMatchObject({ passive: true });
});
});
@@ -0,0 +1,117 @@
import type { AssessmentSignalEvent } from "../../../shared/api/schemas";
import { pasteSizeBytes, selectionSize, type PasteSource, type SelectionSource } from "./measure";
import { clipboardEvent, focusLossEvent, fullscreenExitEvent } from "./signal-events";
/** The browser objects the collector listens to; tests pass small fakes. */
export type CollectorEnvironment = {
document: EventTarget &
SelectionSource & {
readonly visibilityState: string;
readonly fullscreenElement: unknown;
hasFocus(): boolean;
};
window: EventTarget;
/** Device clock in milliseconds; only differences of it are used as durations. */
now: () => number;
/**
* Maps a device timestamp to server time for the event metadata. It is kept
* apart from `now` so that a clock offset learned while an absence is being
* measured can never distort the duration.
*/
toServerTime?: (deviceMs: number) => number;
};
export type CollectorOptions = {
environment: CollectorEnvironment;
/** Identifier of the item on screen now, or null when none is shown. */
currentItemId: () => string | null;
onEvent: (event: AssessmentSignalEvent) => void;
/** Called when the page is hidden, a good moment to send what is queued. */
onHidden?: () => void;
/** Called when the page is being unloaded; the last chance to send. */
onPageHide?: () => void;
};
type ClipboardLike = Event & { clipboardData?: PasteSource | null };
/**
* Observes the disclosed signals and reports them through onEvent.
*
* All listeners are passive, never call preventDefault or stopPropagation, and
* never touch the page, so typing, pasting, and answering behave exactly as
* without collection. A listener that throws is contained and cannot reach the
* page.
*/
export function attachSignalCollector(options: CollectorOptions): () => void {
const { document: doc, window: win, now } = options.environment;
const stamp = options.environment.toServerTime ?? ((deviceMs: number) => deviceMs);
let awaySince: number | null = null;
let wasFullscreen = doc.fullscreenElement != null;
function emit(build: (itemId: string) => AssessmentSignalEvent): void {
const itemId = options.currentItemId();
if (!itemId) return;
options.onEvent(build(itemId));
}
function beginAway(): void {
if (awaySince === null) awaySince = now();
}
function endAway(): void {
if (awaySince === null || doc.visibilityState !== "visible" || !doc.hasFocus()) return;
const startedAt = awaySince;
awaySince = null;
const duration = now() - startedAt;
emit((itemId) => focusLossEvent(itemId, stamp(startedAt), duration));
}
const handlers: Array<[EventTarget, string, EventListener]> = [];
function listen(target: EventTarget, type: string, handler: (event: Event) => void): void {
const guarded: EventListener = (event) => {
try {
handler(event);
} catch {
// Collection must never disturb the test.
}
};
target.addEventListener(type, guarded, { capture: true, passive: true });
handlers.push([target, type, guarded]);
}
listen(doc, "visibilitychange", () => {
if (doc.visibilityState === "hidden") {
beginAway();
options.onHidden?.();
} else {
endAway();
}
});
listen(win, "pagehide", () => options.onPageHide?.());
listen(win, "blur", beginAway);
listen(win, "focus", endAway);
listen(doc, "copy", () => {
const size = selectionSize(doc);
emit((itemId) => clipboardEvent("copy", itemId, stamp(now()), size));
});
listen(doc, "cut", () => {
const size = selectionSize(doc);
emit((itemId) => clipboardEvent("cut", itemId, stamp(now()), size));
});
listen(doc, "paste", (event) => {
const size = pasteSizeBytes((event as ClipboardLike).clipboardData);
emit((itemId) => clipboardEvent("paste", itemId, stamp(now()), size));
});
listen(doc, "fullscreenchange", () => {
const isFullscreen = doc.fullscreenElement != null;
if (wasFullscreen && !isFullscreen) emit((itemId) => fullscreenExitEvent(itemId, stamp(now())));
wasFullscreen = isFullscreen;
});
return () => {
for (const [target, type, handler] of handlers) {
target.removeEventListener(type, handler, { capture: true });
}
handlers.length = 0;
};
}
@@ -0,0 +1,82 @@
import { describe, expect, it, vi } from "vitest";
import { pasteSizeBytes, selectionSize, utf8ByteLength } from "./measure";
describe("utf8ByteLength", () => {
it("matches the platform encoder for ASCII, Cyrillic, emoji, and lone surrogates", () => {
for (const sample of ["", "abc", "привет, мир", "a😀b", "\ud800", "x\udc00y", "日本語"]) {
expect(utf8ByteLength(sample)).toBe(new TextEncoder().encode(sample).length);
}
});
});
describe("pasteSizeBytes", () => {
it("returns only a number for plain text and adds file sizes", () => {
const source = {
types: ["text/plain", "text/html", "Files"],
files: [{ size: 100 }, { size: 20 }],
getData: vi.fn((format: string) => (format === "text/plain" ? "привет" : "<b>x</b>")),
};
const size = pasteSizeBytes(source);
expect(size).toBe(12 + 120);
expect(typeof size).toBe("number");
expect(source.getData).toHaveBeenCalledTimes(1);
expect(source.getData).toHaveBeenCalledWith("text/plain");
});
it("does not read any data when the clipboard has no plain text", () => {
const getData = vi.fn(() => "secret");
expect(pasteSizeBytes({ types: ["text/html"], files: [], getData })).toBe(0);
expect(getData).not.toHaveBeenCalled();
});
it("treats a missing source as an empty paste", () => {
expect(pasteSizeBytes(null)).toBe(0);
expect(pasteSizeBytes(undefined)).toBe(0);
});
it("stays within the contract range", () => {
const huge = { types: [], files: [{ size: 5_000_000_000 }], getData: () => "" };
expect(pasteSizeBytes(huge)).toBe(2_147_483_647);
});
});
describe("selectionSize", () => {
it("uses the offsets of a text control without reading its value", () => {
const control = {
selectionStart: 2,
selectionEnd: 9,
get value(): string {
throw new Error("the typed value must not be read");
},
};
expect(selectionSize({ activeElement: control })).toBe(7);
});
it("never falls back to the page selection while a form field has focus", () => {
const getSelection = vi.fn(() => ({ rangeCount: 1, toString: () => "typed secret" }));
expect(
selectionSize({ activeElement: { selectionStart: null, selectionEnd: null }, getSelection }),
).toBe(0);
expect(
selectionSize({ activeElement: { selectionStart: 3, selectionEnd: 3 }, getSelection }),
).toBe(0);
const throwing = {
get selectionStart(): number {
throw new DOMException("not supported");
},
selectionEnd: 0,
};
expect(selectionSize({ activeElement: throwing, getSelection })).toBe(0);
expect(getSelection).not.toHaveBeenCalled();
});
it("uses the length of the page selection when no form field has focus", () => {
const doc = {
activeElement: {},
getSelection: () => ({ rangeCount: 1, toString: () => "условие" }),
};
expect(selectionSize(doc)).toBe(7);
expect(selectionSize({ getSelection: () => ({ rangeCount: 0, toString: () => "x" }) })).toBe(0);
expect(selectionSize({})).toBe(0);
});
});
@@ -0,0 +1,106 @@
/**
* Size measurement for clipboard events.
*
* Only a number leaves this module. Clipboard contents, selections, and typed
* text are never stored, returned, logged, or sent.
*
* Paste: the paste event is the only moment the browser exposes what is being
* pasted, and DataTransfer has no size accessor for text. Dropped or pasted
* files report their size through File.size without reading them. For text,
* the length is taken from the plain-text item inside this function: the string
* lives in one local variable, is measured without copying it, and goes out of
* scope on return. The Clipboard API (navigator.clipboard) is never used, so no
* permission prompt appears and nothing outside the event is read.
*
* Copy and cut: the length of the current selection in UTF-16 code units. For
* form fields it comes from the selection offsets and does not read the typed
* value at all; a field without numeric offsets counts as zero. The page
* selection is measured only when no form field has focus.
*/
const maxSizeBytes = 2_147_483_647;
/** The part of DataTransfer that paste measurement needs. */
export type PasteSource = {
readonly types: ReadonlyArray<string>;
readonly files: ArrayLike<{ readonly size: number }>;
getData(format: string): string;
};
/** UTF-8 byte length of a string without allocating an encoded copy. */
export function utf8ByteLength(text: string): number {
let bytes = 0;
for (let index = 0; index < text.length; index += 1) {
const unit = text.charCodeAt(index);
if (unit < 0x80) {
bytes += 1;
} else if (unit < 0x800) {
bytes += 2;
} else if (unit >= 0xd800 && unit <= 0xdbff && index + 1 < text.length) {
const next = text.charCodeAt(index + 1);
if (next >= 0xdc00 && next <= 0xdfff) {
bytes += 4;
index += 1;
} else {
bytes += 3;
}
} else {
bytes += 3;
}
}
return bytes;
}
function clampSize(value: number): number {
if (!Number.isFinite(value) || value <= 0) return 0;
return Math.min(Math.floor(value), maxSizeBytes);
}
/** Size in bytes of what a paste event carries: plain text plus file sizes. */
export function pasteSizeBytes(source: PasteSource | null | undefined): number {
if (!source) return 0;
let total = 0;
for (let index = 0; index < source.files.length; index += 1) {
total += source.files[index]?.size ?? 0;
}
if (Array.from(source.types).includes("text/plain")) {
total += utf8ByteLength(source.getData("text/plain"));
}
return clampSize(total);
}
/** The part of a text control or document that selection measurement needs. */
export type SelectionSource = {
readonly activeElement?: object | null;
getSelection?(): { readonly rangeCount: number; toString(): string } | null;
};
/**
* Length of the current selection in UTF-16 code units.
*
* When a form field has focus, only its selection offsets are used. A field
* without numeric offsets (for example a number input) counts as zero rather
* than falling back to the page selection, so typed text is never read, not
* even to measure it. The page selection is used only when no form field is
* active, for example when the task statement is selected.
*/
export function selectionSize(doc: SelectionSource): number {
const active = doc.activeElement as object | null | undefined;
if (active && "selectionStart" in active) {
try {
const { selectionStart, selectionEnd } = active as {
selectionStart: unknown;
selectionEnd: unknown;
};
if (typeof selectionStart === "number" && typeof selectionEnd === "number") {
return clampSize(selectionEnd - selectionStart);
}
} catch {
// Some field types refuse to expose offsets; treat the size as unknown.
}
return 0;
}
const selection = doc.getSelection?.();
if (!selection || selection.rangeCount === 0) return 0;
return clampSize(selection.toString().length);
}
@@ -0,0 +1,60 @@
/**
* Version of the notice text below. The server stores which version a
* candidate acknowledged; change this number together with the text and with
* the version the server requires, so that everyone acknowledges the new text.
*/
export const knownSignalNoticeVersion = 1;
export type DisclosedSignal = { code: string; title: string; detail: string };
/** Signals measured in the browser and sent in batches, only while C3 is current. */
export const browserSignals: readonly DisclosedSignal[] = [
{
code: "tab_switch",
title: "Смена вкладки или окна",
detail: "Сколько времени страница теста была не в фокусе.",
},
{
code: "clipboard",
title: "Копирование, вставка и вырезание",
detail: "Сколько раз это происходило и какого размера было действие.",
},
{
code: "fullscreen",
title: "Выход из полноэкранного режима",
detail: "Только факт выхода. Полноэкранный режим включать не нужно.",
},
];
/** Signals the server derives while it handles the attempt. */
export const serverSignals: readonly DisclosedSignal[] = [
{
code: "answer_time",
title: "Время ответа на каждое задание",
detail: "Его измеряет сервер между показом задания и получением ответа.",
},
{
code: "network_change",
title: "Смена сетевого адреса во время попытки",
detail:
"Сам адрес не хранится, только односторонний ключевой отпечаток, привязанный к попытке.",
},
{
code: "parallel_sessions",
title: "Параллельные сессии",
detail: "Токен сессии не хранится, только односторонний ключевой отпечаток.",
},
{
code: "answer_match",
title: "Совпадение ответов с ответами других кандидатов",
detail:
"Сравниваются односторонние отпечатки ответов на варианты одного задания. Текст ответа для этого не сохраняется.",
},
];
/** What is explicitly not collected. */
export const notCollected: readonly string[] = [
"Изображение: камера и запись экрана не используются.",
"Звук: микрофон не используется.",
"Содержимое буфера обмена и вводимый текст: отправляется только размер вставки.",
];
@@ -0,0 +1,89 @@
import { describe, expect, it } from "vitest";
import { ApiRequestError } from "../../../shared/api";
import {
closedNoticeDialog,
confirmationError,
decideNotice,
noticeDialogReducer,
type NoticeDialogState,
} from "./notice-gate";
import { knownSignalNoticeVersion } from "./notice-content";
function conflict(status: number): ApiRequestError {
return new ApiRequestError({ status, code: "state_conflict", title: "failure" });
}
describe("decideNotice", () => {
it("does not proceed without data from the server", () => {
expect(decideNotice(undefined).kind).toBe("unavailable");
});
it("refuses to confirm a text version the screen does not know", () => {
const decision = decideNotice({
notice_version: knownSignalNoticeVersion + 1,
acknowledged: true,
});
expect(decision.kind).toBe("outdated");
});
it("proceeds at once when the server already has the acknowledgement", () => {
expect(decideNotice({ notice_version: knownSignalNoticeVersion, acknowledged: true })).toEqual({
kind: "proceed",
});
});
it("asks for confirmation when the acknowledgement is missing", () => {
expect(decideNotice({ notice_version: knownSignalNoticeVersion, acknowledged: false })).toEqual(
{ kind: "confirm" },
);
});
});
describe("confirmationError", () => {
it("tells the candidate to reload after a version conflict", () => {
expect(confirmationError(conflict(409))).toContain("Текст уведомления изменился");
});
it("asks to retry after any other failure", () => {
expect(confirmationError(conflict(0))).toContain("Не удалось сохранить");
expect(confirmationError(new Error("x"))).toContain("Не удалось сохранить");
});
});
describe("noticeDialogReducer", () => {
const open = noticeDialogReducer(closedNoticeDialog, { type: "open" });
it("opens and closes without a confirmation", () => {
expect(open).toEqual({ open: true, busy: false, errorMessage: null });
expect(noticeDialogReducer(open, { type: "close" })).toEqual(closedNoticeDialog);
});
it("ignores a second confirmation while one is being saved", () => {
const busy = noticeDialogReducer(open, { type: "confirm" });
expect(busy.busy).toBe(true);
expect(noticeDialogReducer(busy, { type: "confirm" })).toBe(busy);
});
it("cannot be closed while the confirmation is being saved", () => {
const busy: NoticeDialogState = noticeDialogReducer(open, { type: "confirm" });
expect(noticeDialogReducer(busy, { type: "close" })).toBe(busy);
});
it("closes after the server stored the confirmation", () => {
const busy = noticeDialogReducer(open, { type: "confirm" });
expect(noticeDialogReducer(busy, { type: "confirmed" })).toEqual(closedNoticeDialog);
});
it("stays open with a message after a version conflict and can be closed again", () => {
const busy = noticeDialogReducer(open, { type: "confirm" });
const failed = noticeDialogReducer(busy, { type: "failed", error: conflict(409) });
expect(failed.open).toBe(true);
expect(failed.busy).toBe(false);
expect(failed.errorMessage).toContain("Текст уведомления изменился");
expect(noticeDialogReducer(failed, { type: "close" })).toEqual(closedNoticeDialog);
});
it("does not confirm a dialog that is closed", () => {
expect(noticeDialogReducer(closedNoticeDialog, { type: "confirm" })).toBe(closedNoticeDialog);
});
});
@@ -0,0 +1,72 @@
import { ApiRequestError } from "../../../shared/api";
import { knownSignalNoticeVersion } from "./notice-content";
/** What the screen does with the notice state read from the server. */
export type NoticeDecision =
| { kind: "unavailable"; message: string }
| { kind: "outdated"; message: string }
| { kind: "proceed" }
| { kind: "confirm" };
export function decideNotice(
notice: { notice_version: number; acknowledged: boolean } | undefined,
): NoticeDecision {
if (!notice) {
return {
kind: "unavailable",
message: "Не удалось проверить уведомление о сигналах. Повторите действие.",
};
}
if (notice.notice_version !== knownSignalNoticeVersion) {
return {
kind: "outdated",
message: "Текст уведомления обновился. Обновите страницу и повторите действие.",
};
}
return notice.acknowledged ? { kind: "proceed" } : { kind: "confirm" };
}
export function confirmationError(error: unknown): string {
if (error instanceof ApiRequestError && error.status === 409) {
return "Текст уведомления изменился. Обновите страницу и прочитайте его еще раз.";
}
return "Не удалось сохранить подтверждение. Проверьте соединение и повторите.";
}
export type NoticeDialogState = { open: boolean; busy: boolean; errorMessage: string | null };
export type NoticeDialogEvent =
| { type: "open" }
| { type: "confirm" }
| { type: "confirmed" }
| { type: "failed"; error: unknown }
| { type: "close" };
export const closedNoticeDialog: NoticeDialogState = {
open: false,
busy: false,
errorMessage: null,
};
/**
* State of the confirmation dialog. While a confirmation is being saved the
* dialog cannot be closed, so a stored confirmation is never hidden by a closed
* dialog and the action that waits for it is not dropped.
*/
export function noticeDialogReducer(
state: NoticeDialogState,
event: NoticeDialogEvent,
): NoticeDialogState {
switch (event.type) {
case "open":
return { open: true, busy: false, errorMessage: null };
case "confirm":
return state.open && !state.busy ? { ...state, busy: true, errorMessage: null } : state;
case "confirmed":
return closedNoticeDialog;
case "failed":
return { open: true, busy: false, errorMessage: confirmationError(event.error) };
case "close":
return state.busy ? state : closedNoticeDialog;
}
}
@@ -0,0 +1,43 @@
import type { AssessmentSignalEvent } from "../../../shared/api/schemas";
const maxDurationMs = 259_200_000;
const maxSizeBytes = 2_147_483_647;
export type ClipboardKind = "copy" | "paste" | "cut";
function timestamp(epochMs: number): string {
return new Date(epochMs).toISOString();
}
/** Time away from the test tab or window. Durations are clamped to the contract range. */
export function focusLossEvent(
itemId: string,
startedAtMs: number,
durationMs: number,
): AssessmentSignalEvent {
return {
kind: "focus_loss",
item_instance_id: itemId,
occurred_at: timestamp(startedAtMs),
duration_ms: Math.min(Math.max(Math.floor(durationMs), 1), maxDurationMs),
};
}
/** A copy, paste, or cut with its size only. */
export function clipboardEvent(
kind: ClipboardKind,
itemId: string,
atMs: number,
sizeBytes: number,
): AssessmentSignalEvent {
return {
kind,
item_instance_id: itemId,
occurred_at: timestamp(atMs),
size_bytes: Math.min(Math.max(Math.floor(sizeBytes), 0), maxSizeBytes),
};
}
export function fullscreenExitEvent(itemId: string, atMs: number): AssessmentSignalEvent {
return { kind: "fullscreen_exit", item_instance_id: itemId, occurred_at: timestamp(atMs) };
}
@@ -0,0 +1,116 @@
import { describe, expect, it, vi } from "vitest";
import type { SignalSender } from "./batcher";
import type { CollectorEnvironment } from "./collector";
import { shouldCollectSignals, startSignalSession } from "./signal-session";
const itemId = "0198d3a0-0000-7000-8000-000000000001";
class FakeDocument extends EventTarget {
visibilityState = "visible";
fullscreenElement: unknown = null;
activeElement: { selectionStart: number; selectionEnd: number } | null = null;
hasFocus(): boolean {
return true;
}
}
function start(overrides: { itemId?: string | null; offsetMs?: number } = {}) {
const doc = new FakeDocument();
const win = new EventTarget();
const send = vi.fn<SignalSender>(async () => undefined);
const timers: Array<() => void> = [];
const clock = Date.UTC(2026, 9, 8, 12, 0, 0);
const item = overrides.itemId === undefined ? itemId : overrides.itemId;
const stop = startSignalSession({
environment: {
document: doc,
window: win,
now: () => clock,
toServerTime: (deviceMs) => deviceMs + (overrides.offsetMs ?? 0),
} as CollectorEnvironment,
send,
newKey: () => "key",
schedule: (callback) => timers.push(callback),
cancel: () => undefined,
currentItemId: () => item,
});
return { doc, win, send, timers, stop, clock };
}
describe("signal session life cycle", () => {
it("batches an event and sends it when the timer fires", async () => {
const { doc, send, timers } = start();
doc.dispatchEvent(new Event("copy"));
expect(send).not.toHaveBeenCalled();
timers[0]?.();
await Promise.resolve();
expect(send).toHaveBeenCalledTimes(1);
expect(send.mock.calls[0]?.[0].events[0]).toMatchObject({
kind: "copy",
item_instance_id: itemId,
});
});
it("sends what is queued when the tab is hidden", () => {
const { doc, send } = start();
doc.dispatchEvent(new Event("copy"));
doc.visibilityState = "hidden";
doc.dispatchEvent(new Event("visibilitychange"));
expect(send).toHaveBeenCalledTimes(1);
expect(send.mock.calls[0]?.[1]).toBeUndefined();
});
it("sends with keepalive when the page is being unloaded", () => {
const { doc, win, send } = start();
doc.dispatchEvent(new Event("copy"));
win.dispatchEvent(new Event("pagehide"));
expect(send).toHaveBeenCalledTimes(1);
expect(send.mock.calls[0]?.[1]).toEqual({ keepalive: true });
});
it("shifts event timestamps to server time", () => {
const { doc, send, stop, clock } = start({ offsetMs: -3_600_000 });
doc.dispatchEvent(new Event("copy"));
stop();
const event = send.mock.calls[0]?.[0].events[0];
expect(event?.occurred_at).toBe(new Date(clock - 3_600_000).toISOString());
});
it("stops listening and sends the rest once when disabled", () => {
const { doc, send, stop } = start();
doc.dispatchEvent(new Event("copy"));
stop();
expect(send).toHaveBeenCalledTimes(1);
expect(send.mock.calls[0]?.[1]).toEqual({ keepalive: true });
doc.dispatchEvent(new Event("copy"));
doc.dispatchEvent(new Event("cut"));
expect(send).toHaveBeenCalledTimes(1);
});
it("does nothing while no item is on screen", () => {
const { doc, stop, send } = start({ itemId: null });
doc.dispatchEvent(new Event("copy"));
stop();
expect(send).not.toHaveBeenCalled();
});
});
describe("shouldCollectSignals", () => {
const base = { ready: true, kind: "root" as const, workReady: true, terminal: false };
it("collects for a real attempt that is being worked on", () => {
expect(shouldCollectSignals(base)).toBe(true);
expect(shouldCollectSignals({ ...base, kind: "corrective" })).toBe(true);
});
it("does not collect for a demonstration run", () => {
expect(shouldCollectSignals({ ...base, kind: "demo_express" })).toBe(false);
});
it.each([{ ready: false }, { workReady: false }, { terminal: true }])(
"does not collect when %o",
(change) => {
expect(shouldCollectSignals({ ...base, ...change })).toBe(false);
},
);
});
@@ -0,0 +1,55 @@
import { createSignalBatcher, type SignalBatcher, type SignalSender } from "./batcher";
import { attachSignalCollector, type CollectorEnvironment } from "./collector";
export type SignalSessionOptions = {
environment: CollectorEnvironment;
send: SignalSender;
newKey: () => string;
schedule: (callback: () => void, delayMs: number) => unknown;
cancel: (handle: unknown) => void;
currentItemId: () => string | null;
};
/**
* Starts collecting and batching for one attempt and returns the function that
* stops it. Stopping removes every listener, cancels the timers, and makes one
* last keepalive send of what is still queued. It is the whole life cycle that
* the React hook ties to the effect of an enabled attempt.
*/
export function startSignalSession(options: SignalSessionOptions): () => void {
const batcher: SignalBatcher = createSignalBatcher({
send: options.send,
newKey: options.newKey,
schedule: options.schedule,
cancel: options.cancel,
});
const detach = attachSignalCollector({
environment: options.environment,
currentItemId: options.currentItemId,
onEvent: (event) => batcher.enqueue(event),
onHidden: () => batcher.flush(),
onPageHide: () => batcher.flushOnExit(),
});
return () => {
detach();
batcher.dispose();
};
}
/** The part of an attempt that decides whether signals are collected. */
export type SignalCollectionContext = {
/** The candidate session is current and the attempt has been read. */
ready: boolean;
kind: "root" | "corrective" | "demo_express";
/** The candidate started or resumed the work in this page. */
workReady: boolean;
terminal: boolean;
};
/**
* Signals are collected only while a real attempt is being worked on. A
* demonstration run stores none, and a finished attempt accepts none.
*/
export function shouldCollectSignals(context: SignalCollectionContext): boolean {
return context.ready && context.workReady && !context.terminal && context.kind !== "demo_express";
}
@@ -0,0 +1,59 @@
import { useEffect, useRef } from "react";
import { recordMyAssessmentAttemptSignals } from "../../../shared/api/endpoints/assessment/assessment";
import { toServerTime } from "../../../shared/api";
import { startSignalSession } from "./signal-session";
export type UseAssessmentSignalsOptions = {
attemptId: string;
/** Identifier of the item on screen now; events are bound to it. */
itemId: string | null;
csrfToken: string;
/** True only while a real attempt is being worked on. */
enabled: boolean;
};
/**
* Collects the disclosed signals of a real attempt and sends them in batches.
*
* The hook has no output: nothing is rendered, nothing is awaited, and a failed
* request never reaches the answer flow. Each batch keeps one Idempotency-Key
* for all its retries, so a retry after a lost response cannot store it twice.
* Timestamps are shifted to server time, so a wrong device clock cannot make
* the server reject a batch.
*/
export function useAssessmentSignals({
attemptId,
itemId,
csrfToken,
enabled,
}: UseAssessmentSignalsOptions): void {
const itemRef = useRef<string | null>(itemId);
const csrfRef = useRef(csrfToken);
useEffect(() => {
itemRef.current = itemId;
csrfRef.current = csrfToken;
}, [itemId, csrfToken]);
useEffect(() => {
if (!enabled || !attemptId) return undefined;
return startSignalSession({
environment: { document, window, now: () => Date.now(), toServerTime },
send: async (batch, sendOptions) => {
await recordMyAssessmentAttemptSignals(
attemptId,
{ events: batch.events },
{ "Idempotency-Key": batch.key },
{
headers: { "X-CSRF-Token": csrfRef.current },
...(sendOptions?.keepalive ? { keepalive: true } : {}),
},
);
},
newKey: () => crypto.randomUUID(),
schedule: (callback, delayMs) => window.setTimeout(callback, delayMs),
cancel: (handle) => window.clearTimeout(handle as number),
currentItemId: () => itemRef.current,
});
}, [attemptId, enabled]);
}
@@ -0,0 +1,87 @@
import { useReducer, useRef, useState } from "react";
import type { QueryClient } from "@tanstack/react-query";
import { ApiRequestError } from "../../../shared/api";
import type { Session } from "../../../shared/api/schemas";
import {
acknowledgeAssessmentSignalNotice,
useAssessmentSignalNotice,
} from "../../../entities/assessment";
import { knownSignalNoticeVersion } from "./notice-content";
import { closedNoticeDialog, decideNotice, noticeDialogReducer } from "./notice-gate";
export type SignalNoticeGate = {
/**
* Runs the action at once when the notice is acknowledged on the server.
* Otherwise the notice dialog opens, and the action runs only after the
* candidate confirms and the server stores the confirmation.
*/
guard: (action: () => void) => Promise<void>;
/** A message when the notice state could not be read or is outdated. */
checkError: string | null;
dialog: {
open: boolean;
busy: boolean;
errorMessage: string | null;
onConfirm: () => void;
onClose: () => void;
};
};
type Options = { actor: Session | undefined; queryClient: QueryClient; enabled: boolean };
/**
* Gate for actions that start a real attempt. The acknowledgement lives on the
* server, so it survives a reload and a new browser; closing the notice leaves
* it unset and the guarded action never runs. The decisions are in
* notice-gate.ts so they can be tested without a DOM.
*/
export function useSignalNoticeGate({ actor, queryClient, enabled }: Options): SignalNoticeGate {
const notice = useAssessmentSignalNotice({ actor, enabled, queryClient });
const [dialog, dispatch] = useReducer(noticeDialogReducer, closedNoticeDialog);
const [checkError, setCheckError] = useState<string | null>(null);
const pendingAction = useRef<(() => void) | null>(null);
async function guard(action: () => void): Promise<void> {
setCheckError(null);
const current = notice.data ?? (await notice.refetch()).data;
const decision = decideNotice(current);
if (decision.kind === "unavailable" || decision.kind === "outdated") {
setCheckError(decision.message);
return;
}
if (decision.kind === "proceed") {
action();
return;
}
pendingAction.current = action;
dispatch({ type: "open" });
}
async function confirm(): Promise<void> {
if (!actor || dialog.busy) return;
dispatch({ type: "confirm" });
try {
await acknowledgeAssessmentSignalNotice(queryClient, actor, knownSignalNoticeVersion);
} catch (error: unknown) {
dispatch({ type: "failed", error });
if (error instanceof ApiRequestError && error.status === 409) void notice.refetch();
return;
}
dispatch({ type: "confirmed" });
const action = pendingAction.current;
pendingAction.current = null;
action?.();
}
function close(): void {
if (dialog.busy) return;
pendingAction.current = null;
dispatch({ type: "close" });
}
return {
guard,
checkError,
dialog: { ...dialog, onConfirm: () => void confirm(), onClose: close },
};
}
@@ -0,0 +1,107 @@
.content {
display: grid;
gap: var(--space-3);
min-width: 0;
}
.content h3,
.content h4,
.content p,
.content ul {
margin: 0;
}
.content h3,
.content h4 {
font-size: var(--font-size-s);
letter-spacing: var(--letter-spacing-label);
text-transform: uppercase;
}
.content ul {
display: grid;
gap: var(--space-2);
padding-inline-start: var(--space-5);
}
.content p,
.content li {
color: var(--color-text-secondary);
overflow-wrap: anywhere;
}
.content strong {
color: var(--color-text);
}
.summary {
display: grid;
gap: var(--space-3);
min-width: 0;
padding: var(--space-4);
border: var(--line-thin) solid var(--color-divider);
border-inline-start: var(--line-strong) solid var(--color-accent);
border-radius: var(--radius-m);
background: var(--color-canvas);
}
.summary h3 {
margin: 0;
font-size: var(--font-size-m);
}
.dialog {
box-sizing: border-box;
width: min(40rem, calc(100vw - 2 * var(--space-4)));
max-height: calc(100dvh - 2 * var(--space-4));
padding: var(--space-5);
overflow-y: auto;
border: var(--line-strong) solid var(--color-border-strong);
border-radius: var(--radius-m);
color: var(--color-text);
background: var(--color-surface);
}
.dialog[open] {
display: grid;
gap: var(--space-4);
}
.dialog::backdrop {
background: color-mix(in srgb, var(--color-text) 60%, transparent);
}
.title {
margin: 0;
font-size: var(--font-size-l);
}
.title:focus-visible {
outline: var(--focus-ring-width) solid var(--color-focus-ring);
outline-offset: var(--focus-ring-offset);
}
.error {
margin: 0;
color: var(--color-danger);
}
.actions {
display: flex;
flex-wrap: wrap;
gap: var(--space-3);
}
@media (width < 42rem) {
.summary {
padding: var(--space-3);
}
.dialog {
padding: var(--space-4);
}
.actions > * {
flex: 1 1 100%;
}
}
@@ -0,0 +1,69 @@
import { renderToStaticMarkup } from "react-dom/server";
import { describe, expect, it } from "vitest";
import { SignalNoticeContent, SignalNoticeDialog, SignalNoticeSummary } from "./signal-notice";
describe("signal notice", () => {
it("lists the browser signals and the server signals", () => {
const markup = renderToStaticMarkup(<SignalNoticeContent headingLevel="h3" />);
expect(markup).toContain("Смена вкладки или окна");
expect(markup).toContain("Копирование, вставка и вырезание");
expect(markup).toContain("Выход из полноэкранного режима");
expect(markup).toContain("Время ответа на каждое задание");
expect(markup).toContain("Смена сетевого адреса во время попытки");
expect(markup).toContain("Параллельные сессии");
});
it("states that addresses and session tokens are kept only as digests", () => {
const markup = renderToStaticMarkup(<SignalNoticeContent headingLevel="h3" />);
expect(markup).toContain("Адреса и токены сессий не хранятся");
expect(markup).toContain("односторонний ключевой отпечаток");
});
it("says that browser events are stored only while C3 is current", () => {
const markup = renderToStaticMarkup(<SignalNoticeContent headingLevel="h3" />);
expect(markup).toContain("только пока действует согласие C3");
});
it("uses the heading level it is given and states the camera rule once", () => {
const dialogMarkup = renderToStaticMarkup(<SignalNoticeContent headingLevel="h3" />);
expect(dialogMarkup).toContain("<h3>Что не собирается</h3>");
expect(dialogMarkup).not.toContain("<h4");
expect(renderToStaticMarkup(<SignalNoticeContent headingLevel="h4" />)).toContain(
"<h4>Что не собирается</h4>",
);
expect(dialogMarkup.match(/микрофон/g)).toHaveLength(1);
});
it("states that image, sound, and clipboard contents are not collected", () => {
const markup = renderToStaticMarkup(<SignalNoticeContent headingLevel="h3" />);
expect(markup).toContain("Что не собирается");
expect(markup).toContain("Изображение");
expect(markup).toContain("Звук");
expect(markup).toContain("камера и запись экрана не используются");
expect(markup).toContain("микрофон не используется");
expect(markup).toContain("Содержимое буфера обмена и вводимый текст");
});
it("says that the confirmation is stored on the server and is not the C3 consent", () => {
const markup = renderToStaticMarkup(<SignalNoticeSummary />);
expect(markup).toContain("Подтверждение хранится на сервере");
expect(markup).toContain("не заменяет согласие C3");
});
it("is a labelled dialog with an explicit confirm and a close action", () => {
const markup = renderToStaticMarkup(
<SignalNoticeDialog
open
busy={false}
errorMessage="Не удалось сохранить подтверждение."
onConfirm={() => undefined}
onClose={() => undefined}
/>,
);
expect(markup).toContain('aria-labelledby="signal-notice-title"');
expect(markup).toContain('id="signal-notice-title"');
expect(markup).toContain("Подтверждаю ознакомление и начинаю");
expect(markup).toContain("Закрыть без подтверждения");
expect(markup).toContain('role="alert"');
});
});
@@ -0,0 +1,149 @@
import { useEffect, useRef } from "react";
import { Button } from "../../../shared/ui";
import {
browserSignals,
notCollected,
serverSignals,
type DisclosedSignal,
} from "../model/notice-content";
import styles from "./signal-notice.module.css";
type ContentProps = { headingLevel: "h3" | "h4" };
function SignalList({ signals }: { signals: readonly DisclosedSignal[] }) {
return (
<ul>
{signals.map((signal) => (
<li key={signal.code}>
<strong>{signal.title}.</strong> {signal.detail}
</li>
))}
</ul>
);
}
/**
* The disclosed list, shared by the page summary and the confirmation dialog.
* The heading level follows the heading that precedes it in each place.
*/
export function SignalNoticeContent({ headingLevel }: ContentProps) {
const Heading = headingLevel;
return (
<div className={styles.content}>
<p>
Во время полной проверки собираются технические сигналы. Они помогают назначить ручную
перепроверку и сами по себе не меняют результат, категорию и квоты.
</p>
<Heading>Что фиксирует браузер</Heading>
<p>События сохраняются, только пока действует согласие C3.</p>
<SignalList signals={browserSignals} />
<Heading>Что измеряет сервер</Heading>
<SignalList signals={serverSignals} />
<Heading>Что не собирается</Heading>
<ul>
{notCollected.map((item) => (
<li key={item}>{item}</li>
))}
</ul>
<p>
Адреса и токены сессий не хранятся: для них есть только односторонние отпечатки. Во время
теста сбор ничего не показывает и не блокирует: ввод, вставка и отправка ответов работают
как обычно. Браузерные сигналы легко исказить, а ложные срабатывания возможны, например при
случайном переключении окна, поэтому это только подсказка. Демонстрационный запуск сигналы
не собирает.
</p>
<p>
Подтверждение хранится на сервере. Оно не заменяет согласие C3, которое управляется отдельно
на странице приватности.
</p>
</div>
);
}
/** Always visible description on the screen where the attempt is started. */
export function SignalNoticeSummary() {
return (
<aside className={styles.summary} aria-labelledby="assessment-signals-title">
<h3 id="assessment-signals-title">Какие данные фиксируются во время проверки</h3>
<SignalNoticeContent headingLevel="h4" />
</aside>
);
}
export type SignalNoticeDialogProps = {
open: boolean;
busy: boolean;
errorMessage: string | null;
onConfirm: () => void;
onClose: () => void;
};
/**
* Modal notice shown before a real attempt starts. It is a native dialog, so
* the browser traps focus inside, closes it with Escape, and returns focus to
* the control that opened it. Closing never confirms anything.
*/
export function SignalNoticeDialog({
open,
busy,
errorMessage,
onConfirm,
onClose,
}: SignalNoticeDialogProps) {
const dialogRef = useRef<HTMLDialogElement>(null);
useEffect(() => {
const dialog = dialogRef.current;
if (!dialog) return;
if (open && !dialog.open) {
dialog.showModal();
// Start at the heading so a screen reader reads the notice before any action.
dialog.querySelector<HTMLElement>("#signal-notice-title")?.focus();
}
if (!open && dialog.open) dialog.close();
}, [open]);
return (
<dialog
ref={dialogRef}
className={styles.dialog}
aria-labelledby="signal-notice-title"
onCancel={(event) => {
// A request in flight finishes first, so a closed notice never hides a stored confirmation.
if (busy) event.preventDefault();
}}
onClose={() => {
// A second Escape can close the dialog even though the first was refused.
// While the confirmation is being saved the dialog stays modal.
const dialog = dialogRef.current;
if (busy && dialog && !dialog.open) {
dialog.showModal();
return;
}
onClose();
}}
>
{open ? (
<>
<h2 id="signal-notice-title" tabIndex={-1} className={styles.title}>
Перед началом: какие сигналы собираются
</h2>
<SignalNoticeContent headingLevel="h3" />
{errorMessage ? (
<p className={styles.error} role="alert">
{errorMessage}
</p>
) : null}
<div className={styles.actions}>
<Button isBusy={busy} onClick={onConfirm}>
{busy ? "Сохраняем подтверждение..." : "Подтверждаю ознакомление и начинаю"}
</Button>
<Button variant="secondary" disabled={busy} onClick={onClose}>
Закрыть без подтверждения
</Button>
</div>
</>
) : null}
</dialog>
);
}
@@ -46,6 +46,12 @@ import {
submitPendingAnswerCommand,
} from "../../../features/answer-assessment";
import type { AnswerDraft, PendingAnswerCommand } from "../../../features/answer-assessment";
import {
SignalNoticeDialog,
shouldCollectSignals,
useAssessmentSignals,
useSignalNoticeGate,
} from "../../../features/assessment-signals";
import attemptStyles from "./assessment-attempt-page.module.css";
type PendingFinalize = { key: string; body: AssessmentFinalization };
@@ -107,6 +113,28 @@ function AssessmentAttemptContent({ attemptId }: { attemptId: string }) {
queryClient,
});
const [workReady, setWorkReady] = useState(false);
const collectsSignals = Boolean(attempt && attempt.kind !== "demo_express");
const signalNotice = useSignalNoticeGate({
actor,
queryClient,
enabled: actorReady && collectsSignals,
});
// Signals are collected only while a real attempt is being worked on. The hook
// renders nothing and never waits for the network.
useAssessmentSignals({
attemptId,
itemId: attempt?.current_item?.id ?? null,
csrfToken: actor?.csrf_token ?? "",
enabled: Boolean(
attempt &&
shouldCollectSignals({
ready: actorReady,
kind: attempt.kind,
workReady,
terminal: isTerminal(attempt),
}),
),
});
const [resumeBusy, setResumeBusy] = useState(false);
const [pendingResume, setPendingResume] = useState<{ key: string; version: number } | null>(null);
const [pendingAnswer, setPendingAnswer] = useState<PendingAnswerCommand | null>(null);
@@ -529,7 +557,19 @@ function AssessmentAttemptContent({ attemptId }: { attemptId: string }) {
Продолжение сверит актуальную версию с сервером. При перезагрузке задания не
меняются, а ответ не отправляется повторно автоматически.
</p>
<Button isBusy={resumeBusy} onClick={() => void resumeWork()}>
{signalNotice.checkError ? (
<p className={attemptStyles.error} role="alert">
{signalNotice.checkError}
</p>
) : null}
<Button
isBusy={resumeBusy}
onClick={() =>
void (collectsSignals
? signalNotice.guard(() => void resumeWork())
: resumeWork())
}
>
{resumeBusy
? "Проверяем попытку..."
: pendingResume
@@ -630,6 +670,7 @@ function AssessmentAttemptContent({ attemptId }: { attemptId: string }) {
</ButtonLink>
</div>
</div>
<SignalNoticeDialog {...signalNotice.dialog} />
</Page>
);
}
@@ -50,8 +50,7 @@
}
.availability,
.express,
.notice {
.express {
display: grid;
gap: var(--space-3);
min-width: 0;
@@ -61,8 +60,7 @@
}
.availability p,
.express p,
.notice p {
.express p {
margin: 0;
}
@@ -102,17 +100,6 @@
overflow-wrap: anywhere;
}
.notice {
border-inline-start: var(--line-strong) solid var(--color-accent);
background: var(--color-canvas);
}
.notice h3 {
margin: 0;
font-size: var(--font-size-m);
}
.notice p,
.express p,
.pending {
color: var(--color-text-secondary);
@@ -134,8 +121,7 @@
}
.availability,
.express,
.notice {
.express {
padding: var(--space-3);
}
}
@@ -39,6 +39,11 @@ import {
useAssessmentQuestionnaire,
} from "../../../entities/assessment";
import { newIdempotencyKey } from "../../../features/answer-assessment";
import {
SignalNoticeDialog,
SignalNoticeSummary,
useSignalNoticeGate,
} from "../../../features/assessment-signals";
import {
buildRootAttemptCreate,
preservePendingCreate,
@@ -171,20 +176,6 @@ export function AssessmentPolicyParameters({ grade }: { grade: AssessmentGradeAv
);
}
function AssessmentSignalsNotice() {
return (
<aside className={styles.notice} aria-labelledby="assessment-signals-title">
<h3 id="assessment-signals-title">Какие данные фиксируются во время проверки</h3>
<p>
Сохраняются время ответов и технические события: смена вкладки, выход из полноэкранного
режима и размер операций копирования или вставки. Содержимое ответов и буфера не
отправляется как сигнал. Камера, микрофон и запись экрана не используются.
</p>
<p>Сигналы помогают назначить ручную перепроверку и сами по себе не меняют результат.</p>
</aside>
);
}
export function AssessmentPage() {
const queryClient = useQueryClient();
const navigate = useNavigate();
@@ -197,6 +188,7 @@ export function AssessmentPage() {
);
const availability = useAssessmentAvailability({ actor, enabled: actorReady, queryClient });
const questionnaire = useAssessmentQuestionnaire({ actor, enabled: actorReady, queryClient });
const signalNotice = useSignalNoticeGate({ actor, queryClient, enabled: actorReady });
const [selection, setSelection] = useState<{
specialization: SpecializationCode | "";
grade: GradeCode | "";
@@ -374,7 +366,8 @@ export function AssessmentPage() {
setFormError("Выберите язык задания перед началом проверки.");
return;
}
void startAttempt(body);
// A real attempt collects signals, so the disclosed list is confirmed first.
void signalNotice.guard(() => void startAttempt(body));
};
const handleStartExpress = () => {
@@ -541,7 +534,12 @@ export function AssessmentPage() {
) : null}
</>
)}
<AssessmentSignalsNotice />
<SignalNoticeSummary />
{signalNotice.checkError ? (
<p className={styles.error} role="alert">
{signalNotice.checkError}
</p>
) : null}
</Section>
<Section
@@ -563,6 +561,7 @@ export function AssessmentPage() {
</div>
</Section>
</div>
<SignalNoticeDialog {...signalNotice.dialog} />
</Page>
);
}
+3
View File
@@ -1,4 +1,5 @@
import type { z } from "zod";
import { recordServerDate } from "./server-clock";
import { Problem, type ProblemCode, type ProblemFieldError } from "./schemas";
const apiPrefix = "/api/v1";
@@ -166,6 +167,8 @@ export async function apiRequest<T>(
});
}
recordServerDate(response.headers.get("date"), Date.now());
if (!response.ok) {
throw await toApiError(response);
}
@@ -32,6 +32,7 @@ import type {
AssessmentQualifiedResult,
AssessmentResult,
AssessmentSessions,
AssessmentSignalNotice,
AssessmentSignalReceipt,
AssessmentUncertainty,
BasicScore,
@@ -48,6 +49,10 @@ import type {
export const getGetMyAssessmentAvailabilityResponseMock = (overrideResponse: Partial<Extract<AssessmentAvailability, object>> = {}): AssessmentAvailability => ({specializations: Array.from({ length: faker.number.int({min: 1, max: 2}) }, (_, i) => i + 1).map(() => ({specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), confirmed_grade: faker.helpers.arrayElement([faker.helpers.arrayElement(['intern','junior','middle','senior'] as const),null,]), active_attempt_id: faker.helpers.arrayElement([faker.string.uuid(), null]), grades: Array.from({ length: faker.number.int({min: 1, max: 10}) }, (_, i) => i + 1).map(() => ({grade: faker.helpers.arrayElement(['intern','junior','middle','senior'] as const), status: faker.helpers.arrayElement(['available','active_attempt','cooldown','insufficient_bank'] as const), mode: faker.helpers.arrayElement([faker.helpers.arrayElement(['demo_basic','adaptive'] as const),null,]), available_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), time_limit_seconds: faker.helpers.arrayElement([faker.number.int({min: 1}), null]), max_sessions: faker.helpers.arrayElement([faker.number.int({min: 1, max: 10}), null]), max_items: faker.helpers.arrayElement([faker.number.int({min: 1, max: 100}), null]), practice_required: faker.helpers.arrayElement([faker.datatype.boolean(), null])}))})), ...overrideResponse})
export const getGetMyAssessmentSignalNoticeResponseMock = (overrideResponse: Partial<Extract<AssessmentSignalNotice, object>> = {}): AssessmentSignalNotice => ({notice_version: faker.number.int({min: 1, max: 2147483647}), acknowledged: faker.datatype.boolean(), acknowledged_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), ...overrideResponse})
export const getAcknowledgeMyAssessmentSignalNoticeResponseMock = (overrideResponse: Partial<Extract<AssessmentSignalNotice, object>> = {}): AssessmentSignalNotice => ({notice_version: faker.number.int({min: 1, max: 2147483647}), acknowledged: faker.datatype.boolean(), acknowledged_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), ...overrideResponse})
export const getCreateMyAssessmentAttemptResponseAssessmentSessionsMock = (overrideResponse: Partial<AssessmentSessions> = {}): AssessmentSessions => ({...{used: faker.number.int({min: 1, max: 10}), max: faker.number.int({min: 1, max: 10}), idle_timeout_seconds: faker.number.int({min: 60, max: 86400})}, ...overrideResponse});
export const getCreateMyAssessmentAttemptResponseChoiceItemContentMock = (overrideResponse: Partial<ChoiceItemContent> = {}): ChoiceItemContent => ({...{format: faker.helpers.arrayElement(['choice'] as const), options: Array.from({ length: faker.number.int({min: 2, max: 10}) }, (_, i) => i + 1).map(() => ({id: fakeFromPattern("^[A-Za-z0-9_-]+$", {minLength: 1, maxLength: 32}), text: faker.string.alpha({length: {min: 1, max: 2000}})})), multiple: faker.datatype.boolean()}, ...overrideResponse});
@@ -215,6 +220,30 @@ export const getGetMyAssessmentAvailabilityMockHandler = (overrideResponse?: Ass
}, options)
}
export const getGetMyAssessmentSignalNoticeMockHandler = (overrideResponse?: AssessmentSignalNotice | ((info: Parameters<Parameters<typeof http.get>[1]>[0]) => Promise<AssessmentSignalNotice> | AssessmentSignalNotice), options?: RequestHandlerOptions) => {
return http.get('*/api/v1/me/assessment-signal-notice', async (info: Parameters<Parameters<typeof http.get>[1]>[0]) => {
return HttpResponse.json(overrideResponse !== undefined
? (typeof overrideResponse === "function" ? await overrideResponse(info) : overrideResponse)
: getGetMyAssessmentSignalNoticeResponseMock(),
{ status: 200
})
}, options)
}
export const getAcknowledgeMyAssessmentSignalNoticeMockHandler = (overrideResponse?: AssessmentSignalNotice | ((info: Parameters<Parameters<typeof http.put>[1]>[0]) => Promise<AssessmentSignalNotice> | AssessmentSignalNotice), options?: RequestHandlerOptions) => {
return http.put('*/api/v1/me/assessment-signal-notice', async (info: Parameters<Parameters<typeof http.put>[1]>[0]) => {
return HttpResponse.json(overrideResponse !== undefined
? (typeof overrideResponse === "function" ? await overrideResponse(info) : overrideResponse)
: getAcknowledgeMyAssessmentSignalNoticeResponseMock(),
{ status: 200
})
}, options)
}
export const getCreateMyAssessmentAttemptMockHandler = (overrideResponse?: AssessmentAttempt | ((info: Parameters<Parameters<typeof http.post>[1]>[0]) => Promise<AssessmentAttempt> | AssessmentAttempt), options?: RequestHandlerOptions) => {
return http.post('*/api/v1/me/assessment-attempts', async (info: Parameters<Parameters<typeof http.post>[1]>[0]) => {
@@ -300,6 +329,8 @@ export const getGetMyAssessmentResultMockHandler = (overrideResponse?: Assessmen
}
export const getAssessmentMock = () => [
getGetMyAssessmentAvailabilityMockHandler(),
getGetMyAssessmentSignalNoticeMockHandler(),
getAcknowledgeMyAssessmentSignalNoticeMockHandler(),
getCreateMyAssessmentAttemptMockHandler(),
getGetMyAssessmentAttemptMockHandler(),
getStartMyAssessmentAttemptSessionMockHandler(),
@@ -33,6 +33,8 @@ import type {
AssessmentFinalizeConflictProblem,
AssessmentResult,
AssessmentSignalBatch,
AssessmentSignalNotice,
AssessmentSignalNoticeAcknowledgement,
AssessmentSignalReceipt,
CreateMyAssessmentAttemptHeaders,
FinalizeMyAssessmentAttemptHeaders,
@@ -170,7 +172,206 @@ export function useGetMyAssessmentAvailability<TData = Awaited<ReturnType<typeof
export const getCreateMyAssessmentAttemptUrl = () => {
export const getGetMyAssessmentSignalNoticeUrl = () => {
return `/api/v1/me/assessment-signal-notice`
}
/**
* Requires the session cookie of a candidate account with a confirmed email; the candidate comes from the session. Returns the notice version that the server requires now and whether this candidate acknowledged it. The notice lists the signals that are collected during a real assessment attempt and states that images, sound, and clipboard contents are not collected. Client signals are the time away from the tab or window, copy, paste and cut with a size only, and exits from fullscreen mode. Server signals are the response time of each item measured by the server, a change of network address during the attempt, parallel sessions, and the comparison of answers to variants of the same task by candidates. The server stores for these only one-way keyed digests: it stores no network address, no session token, and no answer text. Client signals are stored only while the C3 consent is current. The client shows it before a real attempt starts and does not start the attempt until the notice is acknowledged.
*
* The acknowledgement is stored on the server per account and notice version, so it survives a reload and a new browser. It is not a consent and never changes C3: the signal operation still requires a current C3 consent, and an unacknowledged notice does not make that operation fail. The demo_express training mode collects no signals and needs no acknowledgement.
*
* A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account or an unconfirmed email answers 403 forbidden.
* @summary Read whether the current candidate acknowledged the signal notice.
*/
export const getMyAssessmentSignalNotice = async ( options?: Parameters<typeof apiRequest>[1]): Promise<AssessmentSignalNotice> => {
return apiRequest<AssessmentSignalNotice>(getGetMyAssessmentSignalNoticeUrl(),
{
...options,
method: 'GET'
}
);}
export const getGetMyAssessmentSignalNoticeQueryKey = () => {
return [
`/api/v1/me/assessment-signal-notice`
] as const;
}
export const getGetMyAssessmentSignalNoticeQueryOptions = <TData = Awaited<ReturnType<typeof getMyAssessmentSignalNotice>>, TError = ErrorType<Problem>>( options?: { query?:Partial<UseQueryOptions<Awaited<ReturnType<typeof getMyAssessmentSignalNotice>>, TError, TData>>, request?: SecondParameter<typeof apiRequest>}
) => {
const {query: queryOptions, request: requestOptions} = options ?? {};
const queryKey = queryOptions?.queryKey ?? getGetMyAssessmentSignalNoticeQueryKey();
const queryFn: QueryFunction<Awaited<ReturnType<typeof getMyAssessmentSignalNotice>>> = ({ signal }) => getMyAssessmentSignalNotice({ signal, ...requestOptions });
return { queryKey, queryFn, ...queryOptions} as UseQueryOptions<Awaited<ReturnType<typeof getMyAssessmentSignalNotice>>, TError, TData> & { queryKey: DataTag<QueryKey, TData, TError> }
}
export type GetMyAssessmentSignalNoticeQueryResult = NonNullable<Awaited<ReturnType<typeof getMyAssessmentSignalNotice>>>
export type GetMyAssessmentSignalNoticeQueryError = ErrorType<Problem>
export function useGetMyAssessmentSignalNotice<TData = Awaited<ReturnType<typeof getMyAssessmentSignalNotice>>, TError = ErrorType<Problem>>(
options: { query:Partial<UseQueryOptions<Awaited<ReturnType<typeof getMyAssessmentSignalNotice>>, TError, TData>> & Pick<
DefinedInitialDataOptions<
Awaited<ReturnType<typeof getMyAssessmentSignalNotice>>,
TError,
Awaited<ReturnType<typeof getMyAssessmentSignalNotice>>
> , 'initialData'
>, request?: SecondParameter<typeof apiRequest>}
, queryClient?: QueryClient
): DefinedUseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> }
export function useGetMyAssessmentSignalNotice<TData = Awaited<ReturnType<typeof getMyAssessmentSignalNotice>>, TError = ErrorType<Problem>>(
options?: { query?:Partial<UseQueryOptions<Awaited<ReturnType<typeof getMyAssessmentSignalNotice>>, TError, TData>> & Pick<
UndefinedInitialDataOptions<
Awaited<ReturnType<typeof getMyAssessmentSignalNotice>>,
TError,
Awaited<ReturnType<typeof getMyAssessmentSignalNotice>>
> , 'initialData'
>, request?: SecondParameter<typeof apiRequest>}
, queryClient?: QueryClient
): UseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> }
export function useGetMyAssessmentSignalNotice<TData = Awaited<ReturnType<typeof getMyAssessmentSignalNotice>>, TError = ErrorType<Problem>>(
options?: { query?:Partial<UseQueryOptions<Awaited<ReturnType<typeof getMyAssessmentSignalNotice>>, TError, TData>>, request?: SecondParameter<typeof apiRequest>}
, queryClient?: QueryClient
): UseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> }
/**
* @summary Read whether the current candidate acknowledged the signal notice.
*/
export function useGetMyAssessmentSignalNotice<TData = Awaited<ReturnType<typeof getMyAssessmentSignalNotice>>, TError = ErrorType<Problem>>(
options?: { query?:Partial<UseQueryOptions<Awaited<ReturnType<typeof getMyAssessmentSignalNotice>>, TError, TData>>, request?: SecondParameter<typeof apiRequest>}
, queryClient?: QueryClient
): UseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> } {
const queryOptions = getGetMyAssessmentSignalNoticeQueryOptions(options)
const query = useQuery(queryOptions, queryClient) as UseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> };
return withQueryKey(query, queryOptions.queryKey);
}
export const getAcknowledgeMyAssessmentSignalNoticeUrl = () => {
return `/api/v1/me/assessment-signal-notice`
}
/**
* Requires the session cookie of a candidate account with a confirmed email, the CSRF token of that session in X-CSRF-Token, and an allowed Origin. The body carries the notice version the candidate was shown. The server stores the acknowledgement for the account and that version; the response carries the server time of the first acknowledgement.
*
* The operation needs no Idempotency-Key: it is idempotent. Repeating it for an acknowledged version changes nothing, keeps the first time, and answers 200, so a retry after a lost response succeeds. A version other than the one the server requires answers 409 state_conflict and stores nothing; the client reads the notice again.
*
* The acknowledgement is not a consent. It does not grant, replace, or hide C3, and it does not affect the signal operation or any score, category, or quota. The body carries no signal, answer, or clipboard data.
*
* Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account (403 forbidden), then the version (409).
* @summary Record that the current candidate read the signal notice.
*/
export const acknowledgeMyAssessmentSignalNotice = async (assessmentSignalNoticeAcknowledgement: AssessmentSignalNoticeAcknowledgement, options?: Parameters<typeof apiRequest>[1]): Promise<AssessmentSignalNotice> => {
const getHeaders = (h?: NonNullable<RequestInit['headers']>): Record<string, string | readonly string[]> => {
if (!h) return {};
if (h instanceof Headers) return Object.fromEntries(h.entries());
if (Symbol.iterator in h) {
return Object.fromEntries(
Array.from(h as Iterable<Iterable<string>>, (entry) => Array.from(entry) as [string, string]),
);
}
const headers: Record<string, string | readonly string[]> = {};
for (const [name, value] of Object.entries<string | readonly string[] | undefined>(h)) {
if (value !== undefined) headers[name] = value;
}
return headers;
};
return apiRequest<AssessmentSignalNotice>(getAcknowledgeMyAssessmentSignalNoticeUrl(),
{
...options,
method: 'PUT',
headers: { 'Content-Type': 'application/json', ...getHeaders(options?.headers) },
body: JSON.stringify(assessmentSignalNoticeAcknowledgement)
}
);}
export const getAcknowledgeMyAssessmentSignalNoticeMutationKey = () => ['acknowledgeMyAssessmentSignalNotice'] as const;
export const getAcknowledgeMyAssessmentSignalNoticeMutationOptions = <TError = ErrorType<Problem>,
TContext = unknown>(options?: { mutation?:UseMutationOptions<Awaited<ReturnType<typeof acknowledgeMyAssessmentSignalNotice>>, TError,AcknowledgeMyAssessmentSignalNoticeMutationVariables, TContext>, request?: SecondParameter<typeof apiRequest>}
): UseMutationOptions<Awaited<ReturnType<typeof acknowledgeMyAssessmentSignalNotice>>, TError,AcknowledgeMyAssessmentSignalNoticeMutationVariables, TContext> => {
const mutationKey = getAcknowledgeMyAssessmentSignalNoticeMutationKey();
const {mutation: mutationOptions, request: requestOptions} = options ?
options.mutation && 'mutationKey' in options.mutation && options.mutation.mutationKey ?
options
: {...options, mutation: {...options.mutation, mutationKey}}
: {mutation: { mutationKey, }, request: undefined};
const mutationFn: MutationFunction<Awaited<ReturnType<typeof acknowledgeMyAssessmentSignalNotice>>, AcknowledgeMyAssessmentSignalNoticeMutationVariables> = (props) => {
const {data} = props ?? {};
return acknowledgeMyAssessmentSignalNotice(data,requestOptions)
}
return { mutationFn, ...mutationOptions }}
export type AcknowledgeMyAssessmentSignalNoticeMutationResult = NonNullable<Awaited<ReturnType<typeof acknowledgeMyAssessmentSignalNotice>>>
export type AcknowledgeMyAssessmentSignalNoticeMutationBody = AssessmentSignalNoticeAcknowledgement
export type AcknowledgeMyAssessmentSignalNoticeMutationError = ErrorType<Problem>
export type AcknowledgeMyAssessmentSignalNoticeMutationVariables = {data: AssessmentSignalNoticeAcknowledgement}
/**
* @summary Record that the current candidate read the signal notice.
*/
export const useAcknowledgeMyAssessmentSignalNotice = <TError = ErrorType<Problem>,
TContext = unknown>(options?: { mutation?:UseMutationOptions<Awaited<ReturnType<typeof acknowledgeMyAssessmentSignalNotice>>, TError,AcknowledgeMyAssessmentSignalNoticeMutationVariables, TContext>, request?: SecondParameter<typeof apiRequest>}
, queryClient?: QueryClient): UseMutationResult<
Awaited<ReturnType<typeof acknowledgeMyAssessmentSignalNotice>>,
TError,
AcknowledgeMyAssessmentSignalNoticeMutationVariables,
TContext
> => {
return useMutation(getAcknowledgeMyAssessmentSignalNoticeMutationOptions(options), queryClient);
}
export const getCreateMyAssessmentAttemptUrl = () => {
+1
View File
@@ -6,3 +6,4 @@ export {
unknownErrorCode,
type ApiErrorCode,
} from "./client";
export { serverClockOffsetMs, toServerTime } from "./server-clock";
@@ -0,0 +1,17 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const acknowledgeMyAssessmentSignalNoticeBodyNoticeVersionMax = 2147483647;
export const AcknowledgeMyAssessmentSignalNoticeBody = zod.object({
"notice_version": zod.int().min(1).max(acknowledgeMyAssessmentSignalNoticeBodyNoticeVersionMax).describe('Version of the notice text about the collected signals. The client shows the text of the version it knows and sends that version back when the candidate confirms; a changed text gets a new version and needs a new confirmation.')
}).describe('The notice version the candidate was shown and acknowledged.')
export type AcknowledgeMyAssessmentSignalNoticeBody = zod.input<typeof AcknowledgeMyAssessmentSignalNoticeBody>;
export type AcknowledgeMyAssessmentSignalNoticeBodyOutput = zod.output<typeof AcknowledgeMyAssessmentSignalNoticeBody>;
@@ -14,7 +14,7 @@ export const AssessmentClipboardSignal = zod.object({
"kind": zod.enum(['copy', 'paste', 'cut']),
"item_instance_id": zod.uuid().describe('Identifier of an item instance in one attempt. It identifies the fixed variant served to this candidate and reveals neither the task family, its version, nor the variant seed.'),
"occurred_at": zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.'),
"size_bytes": zod.int().min(assessmentClipboardSignalSizeBytesMin).max(assessmentClipboardSignalSizeBytesMax).describe('Byte count only. Clipboard or selection contents are not transmitted or retained.')
"size_bytes": zod.int().min(assessmentClipboardSignalSizeBytesMin).max(assessmentClipboardSignalSizeBytesMax).describe('Size only; clipboard and selection contents are never transmitted or retained. For `paste` it is the UTF-8 byte count of the pasted plain text plus the byte size of pasted files, counted on the device from the paste event. For `copy` and `cut` it is the selection length in UTF-16 code units taken from the selection offsets of a form field, or zero when the field offsets are unavailable; it is an approximate size and the selected text is not read. The server applies no conversion and treats the value as an order-of-magnitude indicator.')
})
export type AssessmentClipboardSignal = zod.input<typeof AssessmentClipboardSignal>;
@@ -24,7 +24,7 @@ export const AssessmentSignalBatch = zod.object({
"kind": zod.enum(['copy', 'paste', 'cut']),
"item_instance_id": zod.uuid().describe('Identifier of an item instance in one attempt. It identifies the fixed variant served to this candidate and reveals neither the task family, its version, nor the variant seed.'),
"occurred_at": zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.'),
"size_bytes": zod.int().min(assessmentSignalBatchEventsItemTwoSizeBytesMin).max(assessmentSignalBatchEventsItemTwoSizeBytesMax).describe('Byte count only. Clipboard or selection contents are not transmitted or retained.')
"size_bytes": zod.int().min(assessmentSignalBatchEventsItemTwoSizeBytesMin).max(assessmentSignalBatchEventsItemTwoSizeBytesMax).describe('Size only; clipboard and selection contents are never transmitted or retained. For `paste` it is the UTF-8 byte count of the pasted plain text plus the byte size of pasted files, counted on the device from the paste event. For `copy` and `cut` it is the selection length in UTF-16 code units taken from the selection offsets of a form field, or zero when the field offsets are unavailable; it is an approximate size and the selected text is not read. The server applies no conversion and treats the value as an order-of-magnitude indicator.')
}),zod.object({
"kind": zod.enum(['fullscreen_exit']),
"item_instance_id": zod.uuid().describe('Identifier of an item instance in one attempt. It identifies the fixed variant served to this candidate and reveals neither the task family, its version, nor the variant seed.'),
@@ -21,7 +21,7 @@ export const AssessmentSignalEvent = zod.union([zod.object({
"kind": zod.enum(['copy', 'paste', 'cut']),
"item_instance_id": zod.uuid().describe('Identifier of an item instance in one attempt. It identifies the fixed variant served to this candidate and reveals neither the task family, its version, nor the variant seed.'),
"occurred_at": zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.'),
"size_bytes": zod.int().min(assessmentSignalEventTwoSizeBytesMin).max(assessmentSignalEventTwoSizeBytesMax).describe('Byte count only. Clipboard or selection contents are not transmitted or retained.')
"size_bytes": zod.int().min(assessmentSignalEventTwoSizeBytesMin).max(assessmentSignalEventTwoSizeBytesMax).describe('Size only; clipboard and selection contents are never transmitted or retained. For `paste` it is the UTF-8 byte count of the pasted plain text plus the byte size of pasted files, counted on the device from the paste event. For `copy` and `cut` it is the selection length in UTF-16 code units taken from the selection offsets of a form field, or zero when the field offsets are unavailable; it is an approximate size and the selected text is not read. The server applies no conversion and treats the value as an order-of-magnitude indicator.')
}),zod.object({
"kind": zod.enum(['fullscreen_exit']),
"item_instance_id": zod.uuid().describe('Identifier of an item instance in one attempt. It identifies the fixed variant served to this candidate and reveals neither the task family, its version, nor the variant seed.'),
@@ -0,0 +1,19 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const assessmentSignalNoticeNoticeVersionOneMax = 2147483647;
export const AssessmentSignalNotice = zod.object({
"notice_version": zod.int().min(1).max(assessmentSignalNoticeNoticeVersionOneMax).describe('Version of the notice text about the collected signals. The client shows the text of the version it knows and sends that version back when the candidate confirms; a changed text gets a new version and needs a new confirmation.').describe('The version the server currently requires the candidate to acknowledge.'),
"acknowledged": zod.boolean().describe('True when the candidate acknowledged `notice_version`.'),
"acknowledged_at": zod.union([zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.'),zod.null()]).describe('Server time of the first acknowledgement of this version, or null.')
}).describe('State of the notice about the signals that are collected during a real assessment attempt. The acknowledgement is a record that the candidate was informed. It is not a consent, grants no purpose, and neither enables nor blocks signal storage; C3 remains the only consent that the signal operation checks.')
export type AssessmentSignalNotice = zod.input<typeof AssessmentSignalNotice>;
export type AssessmentSignalNoticeOutput = zod.output<typeof AssessmentSignalNotice>;
@@ -0,0 +1,17 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const assessmentSignalNoticeAcknowledgementNoticeVersionMax = 2147483647;
export const AssessmentSignalNoticeAcknowledgement = zod.object({
"notice_version": zod.int().min(1).max(assessmentSignalNoticeAcknowledgementNoticeVersionMax).describe('Version of the notice text about the collected signals. The client shows the text of the version it knows and sends that version back when the candidate confirms; a changed text gets a new version and needs a new confirmation.')
}).describe('The notice version the candidate was shown and acknowledged.')
export type AssessmentSignalNoticeAcknowledgement = zod.input<typeof AssessmentSignalNoticeAcknowledgement>;
export type AssessmentSignalNoticeAcknowledgementOutput = zod.output<typeof AssessmentSignalNoticeAcknowledgement>;
@@ -0,0 +1,15 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const AssessmentSignalNoticeVersionMax = 2147483647;
export const AssessmentSignalNoticeVersion = zod.int().min(1).max(AssessmentSignalNoticeVersionMax).describe('Version of the notice text about the collected signals. The client shows the text of the version it knows and sends that version back when the candidate confirms; a changed text gets a new version and needs a new confirmation.')
export type AssessmentSignalNoticeVersion = zod.input<typeof AssessmentSignalNoticeVersion>;
export type AssessmentSignalNoticeVersionOutput = zod.output<typeof AssessmentSignalNoticeVersion>;
@@ -5,6 +5,7 @@
* OpenAPI spec version: 0.1.0
*/
export * from './acknowledgeMyAssessmentSignalNoticeBody.zod';
export * from './assessmentAnswer.zod';
export * from './assessmentAnswerSubmission.zod';
export * from './assessmentAttempt.zod';
@@ -53,6 +54,9 @@ export * from './assessmentResult.zod';
export * from './assessmentSessions.zod';
export * from './assessmentSignalBatch.zod';
export * from './assessmentSignalEvent.zod';
export * from './assessmentSignalNotice.zod';
export * from './assessmentSignalNoticeAcknowledgement.zod';
export * from './assessmentSignalNoticeVersion.zod';
export * from './assessmentSignalReceipt.zod';
export * from './assessmentSpecializationAvailability.zod';
export * from './assessmentStrength.zod';
@@ -24,7 +24,7 @@ export const RecordMyAssessmentAttemptSignalsBody = zod.object({
"kind": zod.enum(['copy', 'paste', 'cut']),
"item_instance_id": zod.uuid().describe('Identifier of an item instance in one attempt. It identifies the fixed variant served to this candidate and reveals neither the task family, its version, nor the variant seed.'),
"occurred_at": zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.'),
"size_bytes": zod.int().min(recordMyAssessmentAttemptSignalsBodyEventsItemTwoSizeBytesMin).max(recordMyAssessmentAttemptSignalsBodyEventsItemTwoSizeBytesMax).describe('Byte count only. Clipboard or selection contents are not transmitted or retained.')
"size_bytes": zod.int().min(recordMyAssessmentAttemptSignalsBodyEventsItemTwoSizeBytesMin).max(recordMyAssessmentAttemptSignalsBodyEventsItemTwoSizeBytesMax).describe('Size only; clipboard and selection contents are never transmitted or retained. For `paste` it is the UTF-8 byte count of the pasted plain text plus the byte size of pasted files, counted on the device from the paste event. For `copy` and `cut` it is the selection length in UTF-16 code units taken from the selection offsets of a form field, or zero when the field offsets are unavailable; it is an approximate size and the selected text is not read. The server applies no conversion and treats the value as an order-of-magnitude indicator.')
}),zod.object({
"kind": zod.enum(['fullscreen_exit']),
"item_instance_id": zod.uuid().describe('Identifier of an item instance in one attempt. It identifies the fixed variant served to this candidate and reveals neither the task family, its version, nor the variant seed.'),
@@ -0,0 +1,36 @@
import { afterEach, describe, expect, it } from "vitest";
import {
recordServerDate,
resetServerClock,
serverClockOffsetMs,
toServerTime,
} from "./server-clock";
afterEach(resetServerClock);
describe("server clock", () => {
it("has no offset before any response", () => {
expect(serverClockOffsetMs()).toBe(0);
expect(toServerTime(1_000)).toBe(1_000);
});
it("learns the offset of a device clock that runs an hour ahead", () => {
const serverNow = Date.UTC(2026, 9, 8, 12, 0, 0);
recordServerDate(new Date(serverNow).toUTCString(), serverNow + 3_600_000);
expect(serverClockOffsetMs()).toBe(-3_600_000);
expect(toServerTime(serverNow + 3_600_000 + 5_000)).toBe(serverNow + 5_000);
});
it("learns the offset of a device clock that runs behind", () => {
const serverNow = Date.UTC(2026, 9, 8, 12, 0, 0);
recordServerDate(new Date(serverNow).toUTCString(), serverNow - 600_000);
expect(toServerTime(serverNow - 600_000)).toBe(serverNow);
});
it("ignores a missing or malformed header", () => {
recordServerDate(null, 1_000);
recordServerDate("not a date", 1_000);
recordServerDate("", 1_000);
expect(serverClockOffsetMs()).toBe(0);
});
});
+33
View File
@@ -0,0 +1,33 @@
/**
* Offset between the device clock and the server clock, learned from the Date
* header of API responses. A device clock that is minutes off would otherwise
* make the server reject event timestamps; applying the offset keeps client
* metadata inside the window the server accepts.
*
* The Date header has one-second resolution, which is far below the minutes of
* tolerance the server allows, so no round-trip correction is attempted.
*/
let offsetMs = 0;
/** Records the offset from a Date header value; an invalid value changes nothing. */
export function recordServerDate(header: string | null, deviceNowMs: number): void {
if (!header) return;
const serverMs = Date.parse(header);
if (!Number.isFinite(serverMs) || !Number.isFinite(deviceNowMs)) return;
offsetMs = serverMs - deviceNowMs;
}
/** Server time estimated from a device timestamp in milliseconds. */
export function toServerTime(deviceMs: number): number {
return deviceMs + offsetMs;
}
/** Current offset in milliseconds; 0 until a response with a Date header arrived. */
export function serverClockOffsetMs(): number {
return offsetMs;
}
/** Resets the learned offset; used by tests. */
export function resetServerClock(): void {
offsetMs = 0;
}