feat(assessment): add the review band of attempt signals and the disclosed collector
This commit is contained in:
1 parent
68286af8b7
commit
b3c6dc870b
124 files changed
+13522
-633
No files matched your search
@@ -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>
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user