feat(assessment): record capture hints and keep one window per attempt

This commit is contained in:
shira committed 2026-10-11 13:16:52 +03:00
1 parent c975a0d506
commit bb917bf62e
108 files changed
+6649 -139

No files matched your search

+58 -3
View File
@@ -35,9 +35,21 @@ export type SignalEvent = {
[field: string]: unknown;
};
/**
* The work session of the attempt as the server holds it. Pages that mock the
* same attempt share one object, so a second tab meets the hold of the first.
*/
export type LeaseState = { holder: string | null };
export type MockedAttempt = {
/** Events of every signal batch the page sent, in order. */
signals: SignalEvent[];
/** The page identifier of every hold or renewal the page sent. */
holds: string[];
/** The page identifier of every release the page sent. */
releases: string[];
/** The page identifier of every session start the page sent (null: no header). */
starts: Array<string | null>;
/** Bodies of the answers the page sent. */
answers: unknown[];
/** Calls to the notice acknowledgement, to see what was stored. */
@@ -46,7 +58,7 @@ export type MockedAttempt = {
export const watermarkCode = "7K3QD-9XM2T";
/** The notice text version the page knows; the mock server requires the same one. */
export const noticeVersion = 3;
export const noticeVersion = 4;
type Options = {
content: MockItemContent;
@@ -56,6 +68,10 @@ type Options = {
prompt?: string;
/** The visible code of the attempt, or null for an attempt without one. */
watermark?: string | null;
/** The work session shared by the pages of one attempt; one page has its own by default. */
lease?: LeaseState;
/** How often the server asks the page to renew its hold. */
renewAfterSeconds?: number;
};
function isoSeconds(ms: number): string {
@@ -93,7 +109,15 @@ function attemptBody(version: number, options: Options) {
/** Answers the API calls of the attempt page; every other API call gets a 404. */
export async function mockAttemptApi(page: Page, options: Options): Promise<MockedAttempt> {
const recorded: MockedAttempt = { signals: [], answers: [], acknowledgements: [] };
const recorded: MockedAttempt = {
signals: [],
holds: [],
releases: [],
starts: [],
answers: [],
acknowledgements: [],
};
const lease = options.lease ?? { holder: null };
let acknowledged = options.noticeAcknowledged ?? true;
await page.route("**/api/v1/**", async (route: Route) => {
@@ -133,9 +157,40 @@ export async function mockAttemptApi(page: Page, options: Options): Promise<Mock
acknowledged_at: acknowledged ? "2026-10-10T10:00:00Z" : null,
});
}
const client = request.headers()["x-attempt-client"] ?? null;
const heldByAnother = lease.holder !== null && lease.holder !== client;
const busy = () =>
reply(
{
type: "urn:lincodex:problem:state_conflict",
title: "Conflict",
status: 409,
code: "state_conflict",
},
409,
);
if (path === `${base}/work-session`) {
if (method === "DELETE") {
recorded.releases.push(client ?? "");
if (lease.holder === client) lease.holder = null;
return route.fulfill({ status: 204, headers: { "cache-control": "no-store" } });
}
recorded.holds.push(client ?? "");
if (heldByAnother) return busy();
lease.holder = client;
return reply({
held_until: isoSeconds(Date.now() + 120_000),
renew_after_seconds: options.renewAfterSeconds ?? 15,
});
}
if (path === base && method === "GET") return reply(attemptBody(1, options));
if (path === `${base}/sessions`) return reply(attemptBody(2, options));
if (path === `${base}/sessions`) {
recorded.starts.push(client);
if (heldByAnother) return busy();
return reply(attemptBody(2, options));
}
if (path === `${base}/answers`) {
if (heldByAnother) return busy();
recorded.answers.push(JSON.parse(request.postData() ?? "{}"));
return reply(attemptBody(3, options));
}
+162
View File
@@ -0,0 +1,162 @@
import { expect, test } from "@playwright/test";
import {
attemptId,
mockAttemptApi,
numberContent,
startAttempt,
type LeaseState,
} from "./assessment-attempt-mock";
// Weak capture hints and the one-open-window rule of a real attempt. The API is
// mocked: these specs check what the page sends and shows, not what the server
// decides. A screenshot or a phone photo cannot be prevented, so the page never
// tries: it only reports that a screenshot key was pressed.
const answerName = /^Числовой ответ/;
const flushTimeout = 15_000;
test.use({ actionTimeout: 10_000, trace: "off", screenshot: "off", video: "off" });
test("PrintScreen and the macOS shortcuts are recorded as a signal and the test goes on", async ({
page,
}) => {
const recorded = await mockAttemptApi(page, { content: numberContent });
await startAttempt(page);
await expect(page.getByRole("heading", { name: "Задание 1" })).toBeVisible();
// The page only watches: the key event is not cancelled, so the system still takes the screenshot.
const notCancelled = await page.evaluate(() =>
document.dispatchEvent(
new KeyboardEvent("keydown", { key: "PrintScreen", code: "PrintScreen", cancelable: true }),
),
);
expect(notCancelled).toBe(true);
await page.waitForTimeout(1_100);
await page.keyboard.press("Meta+Shift+4");
await expect
.poll(() => recorded.signals.filter((event) => event.kind === "screenshot_key").length, {
timeout: flushTimeout,
})
.toBe(2);
const event = recorded.signals.find((signal) => signal.kind === "screenshot_key");
// The event holds the fact and the item, never the key, the screen, or any image.
expect(Object.keys(event ?? {}).sort()).toEqual(["item_instance_id", "kind", "occurred_at"]);
// The task goes on: nothing was covered, and the answer is typed and sent.
await expect(page.getByRole("heading", { name: "Задание 1" })).toBeVisible();
await page.getByRole("textbox", { name: answerName }).fill("42");
await page.getByRole("button", { name: "Отправить ответ" }).click();
await expect.poll(() => recorded.answers.length).toBe(1);
});
test("open developer tools, guessed from the window size, are recorded as a weak signal", async ({
page,
}) => {
const recorded = await mockAttemptApi(page, { content: numberContent });
await startAttempt(page);
await expect(page.getByRole("heading", { name: "Задание 1" })).toBeVisible();
expect(recorded.signals.some((signal) => signal.kind === "devtools_open")).toBe(false);
// A docked panel makes the outer window much taller than the page.
await page.evaluate(() => {
Object.defineProperty(window, "outerHeight", {
configurable: true,
get: () => window.innerHeight + 420,
});
window.dispatchEvent(new Event("resize"));
});
await expect
.poll(() => recorded.signals.filter((signal) => signal.kind === "devtools_open").length, {
timeout: flushTimeout,
})
.toBe(1);
await expect(page.getByRole("heading", { name: "Задание 1" })).toBeVisible();
});
test("a second tab of the attempt is refused with an explanation until the first one is closed", async ({
browser,
}) => {
const context = await browser.newContext({ locale: "ru-RU" });
const lease: LeaseState = { holder: null };
const first = await context.newPage();
const second = await context.newPage();
const firstApi = await mockAttemptApi(first, { content: numberContent, lease });
const secondApi = await mockAttemptApi(second, { content: numberContent, lease });
await startAttempt(first);
await expect(first.getByRole("heading", { name: "Задание 1" })).toBeVisible();
expect(firstApi.holds).toHaveLength(1);
const firstClient = firstApi.holds[0] ?? "";
expect(firstClient).toMatch(/^[A-Za-z0-9_-]{16,64}$/);
// The session start and the answer carry the page identifier as well.
expect(firstApi.starts).toEqual([firstClient]);
// The attempt in a second tab: refused, explained, and the task is not shown.
await startAttempt(second);
const explanation = second
.getByRole("alert")
.filter({ hasText: "Попытка открыта в другом окне" });
await expect(explanation).toBeVisible();
await expect(explanation).toContainText("Работать над попыткой можно только в одном окне");
await expect(second.getByRole("heading", { name: "Задание 1" })).toHaveCount(0);
expect(await second.content()).not.toContain("SECRET-PROMPT");
expect(secondApi.holds).toHaveLength(1);
expect(secondApi.holds[0]).not.toBe(firstClient);
// Nothing was started in the second tab, and the first tab is undisturbed.
expect(secondApi.starts).toEqual([]);
await expect(first.getByRole("heading", { name: "Задание 1" })).toBeVisible();
// The first tab goes to the list of checks: its page releases the session at once.
await first.getByRole("link", { name: "К доступным проверкам" }).click();
await expect.poll(() => firstApi.releases).toEqual([firstClient]);
expect(lease.holder).toBeNull();
// The second tab continues.
await second.getByRole("button", { name: "Начать или продолжить" }).click();
await expect(second.getByRole("heading", { name: "Задание 1" })).toBeVisible();
await expect(explanation).toHaveCount(0);
expect(secondApi.holds).toHaveLength(2);
expect(lease.holder).toBe(secondApi.holds[1]);
await context.close();
});
test("a page that is going away releases the work session", async ({ page }) => {
const lease: LeaseState = { holder: null };
const recorded = await mockAttemptApi(page, { content: numberContent, lease });
await startAttempt(page);
await expect(page.getByRole("heading", { name: "Задание 1" })).toBeVisible();
expect(lease.holder).not.toBeNull();
await page.evaluate(() => window.dispatchEvent(new Event("pagehide")));
await expect.poll(() => recorded.releases.length).toBe(1);
expect(lease.holder).toBeNull();
});
test("a tab that loses the work session to another window stops and says so", async ({
browser,
}) => {
const context = await browser.newContext({ locale: "ru-RU" });
const lease: LeaseState = { holder: null };
const page = await context.newPage();
const recorded = await mockAttemptApi(page, {
content: numberContent,
lease,
renewAfterSeconds: 5,
});
await startAttempt(page);
await expect(page.getByRole("heading", { name: "Задание 1" })).toBeVisible();
expect(recorded.holds).toHaveLength(1);
// Another window takes the session over (the mock server hands it away).
lease.holder = "another-window-AAAAAAAAAAAAAAAA";
await expect(page.getByRole("heading", { name: "Задание 1" })).toHaveCount(0, {
timeout: 12_000,
});
await expect(
page.getByRole("alert").filter({ hasText: "Попытка открыта в другом окне" }),
).toBeVisible();
// The attempt in the page is the same one; it only waits for the session to be free.
expect(page.url()).toContain(attemptId);
await context.close();
});
+1 -1
View File
@@ -806,7 +806,7 @@ test("closing the notice does not start the attempt and a confirmation is rememb
await page.getByRole("button", { name: "Закрыть без подтверждения" }).click();
await expect(dialog).toBeHidden();
expect(creates).toHaveLength(0);
expect(await readNotice(page)).toMatchObject({ acknowledged: false, notice_version: 3 });
expect(await readNotice(page)).toMatchObject({ acknowledged: false, notice_version: 4 });
await start.click();
await expect(dialog).toBeVisible();