forge
Explore
Log in

Don't you dare go Hollow

🔍 correct 21 defects the last 24h of commits shipped green

Browse files at this commit

f9efbbc5d63c137e3597adede5c3bb2e6d57b94fAhmet Kaan GümüşParent: 41d1040
  • fix
    • 🔍 correct 21 defects the last 24h of commits shipped green
Show full message
fix: 🔍 correct 21 defects the last 24h of commits shipped green

Adversarial audit of 49f9928..ffb1d47: four verifiers found 15 defects the
317-test suite passed over, and a two-lens panel found 6 more in the fixes
themselves. Three of those commits claimed fixes they did not deliver.

- exam room: "saved" was still a lie. Acks were keyed on question_id alone,
  so a timed-out send's late frame settled the retry and the badge claimed
  Saved for a payload the server never took. Replaced with per-send FIFO
  plus an integer debt count per question: superseded/timed-out sends are
  disowned and their frames paid off before any live send settles. failAll
  now takes a required cause — an unattributed error frame keeps the debt
  (the socket stays open), only a real close clears it
- shell feed leaked across accounts: the provider outlived logout, so user B
  saw user A's inbox, badge and appointments until the refetch landed. The
  feed is now built inside a memo keyed on the user id, so a switch disposes
  it rather than relying on a mutate call
- appointments offered actions the backend rejects: book on in-progress
  slots (list filter used where the book guard applies), and a teacher lost
  reschedule permanently because the backend never clears proposed_* — action
  availability now derives from a standing proposal, in a tested pure gate
- every 403 and 404 message was dead: formatApiError returned the per-status
  generic before consulting the table, so entries added for the question bank
  never rendered. Table now wins; 8 appointment 409s and the refresh-from-bank
  400 localized against the backend's exact strings
- request deadline escaped as a raw DOMException because the body read sat
  outside its try, showing Turkish users an English abort message
- unread badge under-counted from a capped inbox page, the two shell badges
  disagreed, and dismiss-all could not clear a count above ten
- students and parents saw their own name on every calendar appointment
- question bank stranded the user on an empty page after deleting the last row
- tests: 317 -> 336, all new ones watched failing before they passed. One
  existing test asserted the ack bug as intended behaviour and was rewritten
- comments in create-ack-waiter claimed safety properties the code lacked;
  rewritten to describe actual behaviour

Known and accepted: shell events/exams fetch unpaged (~3.37MB/poll at 5000
rows) because the backend cannot express a schedule window. Follow-ups for
the backend: starts_after on /events and /exams, and a client seq echoed in
the exam ws saved/error frames to replace the debt heuristic with exact
identity.

23 changed files +1005 -108

docs/navigation-patterns.mdmodified+7 -0
@@ -50,6 +50,13 @@ Pagination and request rules:
50 - If a page intentionally fetches the full list and paginates in memory, document that the expected dataset is small or temporary.50 - If a page intentionally fetches the full list and paginates in memory, document that the expected dataset is small or temporary.
51 - Search/filter/sort UI should match the request model: server-side controls for server-paginated lists, client-side controls only for accepted small lists.51 - Search/filter/sort UI should match the request model: server-side controls for server-paginated lists, client-side controls only for accepted small lists.
52 52
53+Question bank rules:
54+
55+- The question bank (`/question-bank`, teacher+) lives in the **classes** nav group next to Exams, and is a full page because it is a durable, browsable school-wide resource.
56+- Its list is server-paginated/filtered (`limit`/`offset`, owner/subject/visibility/`q`); every filter or search change resets to the first page, and a delete that empties the last page clamps the page index back so the user is never left on a page with no pagination controls.
57+- Creating and editing a template uses a `SidePanel` from the table header; deleting uses a confirm dialog.
58+- Templates are private by default; exam ↔ bank transfers are copies, never links.
59+
53 Table action rules:60 Table action rules:
54 61
55 - Row actions use `TableRowActions` with a centered three-dot trigger.62 - Row actions use `TableRowActions` with a centered three-dot trigger.
docs/role-scope-matrix.mdmodified+4 -0
@@ -14,6 +14,7 @@
14 | Exam detail `/exams/:id` | ✅ | ✅ | ✅ | ✅ |14 | Exam detail `/exams/:id` | ✅ | ✅ | ✅ | ✅ |
15 | Exam room `/exam-room/:id` | ✅ | ❌ | ❌ | ❌ |15 | Exam room `/exam-room/:id` | ✅ | ❌ | ❌ | ❌ |
16 | Live monitor `/exams/:id/live` | ❌ | ✅ | ✅ | ✅ |16 | Live monitor `/exams/:id/live` | ❌ | ✅ | ✅ | ✅ |
17+| Question bank `/question-bank` | ❌ | ✅ | ✅ | ✅ |
17 | Events `/events` | ✅ | ✅ | ✅ | ✅ |18 | Events `/events` | ✅ | ✅ | ✅ | ✅ |
18 | Event detail `/events/:id` | ✅ | ✅ | ✅ | ✅ |19 | Event detail `/events/:id` | ✅ | ✅ | ✅ | ✅ |
19 | Appointments `/appointments` | ✅ (book + own) | ✅ (publish/manage own) | ✅ (manage all) | ✅ (manage all) |20 | Appointments `/appointments` | ✅ (book + own) | ✅ (publish/manage own) | ✅ (manage all) | ✅ (manage all) |
@@ -32,6 +33,7 @@
32 | Sidebar group / item | Student | Teacher | Manager | Admin |33 | Sidebar group / item | Student | Teacher | Manager | Admin |
33 |---|---|---|---|---|34 |---|---|---|---|---|
34 | **classes** — Courses / Exams / Events / exam grades | ✅ | ✅ | ✅ | ✅ |35 | **classes** — Courses / Exams / Events / exam grades | ✅ | ✅ | ✅ | ✅ |
36+| **classes** — Question bank (`/question-bank`) | ❌ | ✅ | ✅ | ✅ |
35 | **grades** — Defter (`/notes`) | ✅ | ✅ | ✅ | ✅ |37 | **grades** — Defter (`/notes`) | ✅ | ✅ | ✅ | ✅ |
36 | **community** — Messages / Question pool | ✅ | ✅ | ✅ | ✅ |38 | **community** — Messages / Question pool | ✅ | ✅ | ✅ | ✅ |
37 | **students** — My attendance (`/attendance`) | ✅ | ✅ | ✅ | ✅ |39 | **students** — My attendance (`/attendance`) | ✅ | ✅ | ✅ | ✅ |
@@ -82,6 +84,8 @@
82 <!-- Own-result review (own answer sheet + past attempts) is additionally gated on the exam's `allow_review` flag AND the teacher having marked the student. -->84 <!-- Own-result review (own answer sheet + past attempts) is additionally gated on the exam's `allow_review` flag AND the teacher having marked the student. -->
83 85
84 | Write exam questions | ❌ | ✅ (course manager) | ✅ | ✅ |86 | Write exam questions | ❌ | ✅ (course manager) | ✅ | ✅ |
87+| Create bank templates | ❌ | ✅ (course manager) | ✅ | ✅ |
88+| Edit / delete bank templates | ❌ | ✅ (own only) | ✅ (own only) | ✅ (any) |
85 | Start / finish own pomodoro focus session | ✅ | ❌ | ❌ | ❌ |89 | Start / finish own pomodoro focus session | ✅ | ❌ | ❌ | ❌ |
86 | Read answer sheets | ❌ | ✅ (course manager) | ✅ | ✅ |90 | Read answer sheets | ❌ | ✅ (course manager) | ✅ | ✅ |
87 | Watch live monitor | ❌ | ✅ (course manager) | ✅ | ✅ |91 | Watch live monitor | ❌ | ✅ (course manager) | ✅ | ✅ |
src/api/__tests__/client/client.test.tsmodified+122 -0
@@ -64,6 +64,76 @@ describe("client", () => {
64 });64 });
65 });65 });
66 66
67+ describe("client() timeout", () => {
68+ // hang until whatever signal fetch was given aborts
69+ const hangingFetch = () =>
70+ vi.spyOn(globalThis, "fetch").mockImplementation(
71+ (_url, init?: RequestInit) =>
72+ new Promise<Response>((_resolve, reject) => {
73+ const signal = init?.signal;
74+ if (!signal) return; // no deadline at all -> test times out, which is the bug
75+ signal.addEventListener("abort", () => reject(signal.reason));
76+ }),
77+ );
78+
79+ it("fails a hung request as a localized ApiError instead of hanging forever", async () => {
80+ // shrink the real deadline; everything else (AbortSignal.any, the catch) runs for real
81+ const realTimeout = AbortSignal.timeout.bind(AbortSignal);
82+ vi.spyOn(AbortSignal, "timeout").mockImplementation(() => realTimeout(5));
83+ hangingFetch();
84+ await expect(client("/slow")).rejects.toMatchObject({ name: "ApiError", status: 408 });
85+ try {
86+ await client("/slow");
87+ } catch (err) {
88+ expect(formatApiError(err, "tr")).toBe("Sunucu zamanında yanıt vermedi. Bağlantını kontrol edip tekrar dene.");
89+ expect(formatApiError(err, "en")).toBe("The server did not respond in time. Check your connection and try again.");
90+ }
91+ });
92+
93+ // headers arrive promptly, the body stalls — the multi-MB shell feed on a
94+ // school connection. The deadline lands while res.text() is streaming.
95+ const stallingBodyFetch = () =>
96+ vi.spyOn(globalThis, "fetch").mockImplementation((_url, init?: RequestInit) => {
97+ const signal = init?.signal;
98+ const stream = new ReadableStream({
99+ start(ctrl) {
100+ ctrl.enqueue(new TextEncoder().encode('{"items":['));
101+ signal?.addEventListener("abort", () => ctrl.error(signal.reason));
102+ },
103+ });
104+ return Promise.resolve(new Response(stream, { status: 200 }));
105+ });
106+
107+ it("fails a timeout during body streaming as ApiError 408, not a raw DOMException", async () => {
108+ const realTimeout = AbortSignal.timeout.bind(AbortSignal);
109+ vi.spyOn(AbortSignal, "timeout").mockImplementation(() => realTimeout(5));
110+ stallingBodyFetch();
111+ await expect(client("/big-feed")).rejects.toMatchObject({ name: "ApiError", status: 408 });
112+ try {
113+ await client("/big-feed");
114+ } catch (err) {
115+ expect(formatApiError(err, "tr")).toBe("Sunucu zamanında yanıt vermedi. Bağlantını kontrol edip tekrar dene.");
116+ }
117+ });
118+
119+ it("still surfaces a caller abort mid-body as AbortError, not a timeout", async () => {
120+ stallingBodyFetch();
121+ const ctrl = new AbortController();
122+ const pending = client("/big-feed", { signal: ctrl.signal });
123+ await Promise.resolve();
124+ ctrl.abort();
125+ await expect(pending).rejects.toMatchObject({ name: "AbortError" });
126+ });
127+
128+ it("still surfaces a caller abort as AbortError, not a timeout", async () => {
129+ hangingFetch();
130+ const ctrl = new AbortController();
131+ const pending = client("/slow", { signal: ctrl.signal });
132+ ctrl.abort();
133+ await expect(pending).rejects.toMatchObject({ name: "AbortError" });
134+ });
135+ });
136+
67 describe("formClient()", () => {137 describe("formClient()", () => {
68 it("makes POST request with FormData", async () => {138 it("makes POST request with FormData", async () => {
69 mockFetchSuccess({ ok: true });139 mockFetchSuccess({ ok: true });
@@ -197,6 +267,58 @@ describe("client", () => {
197 expect(formatApiError(new ApiError(404, ""), "en")).toBe("The requested record was not found.");267 expect(formatApiError(new ApiError(404, ""), "en")).toBe("The requested record was not found.");
198 });268 });
199 269
270+ it("prefers the table entry over the per-status generic message", () => {
271+ // the whole 403 table was dead code: every 403 rendered "forbidden"
272+ expect(formatApiError(new ApiError(403, "only the template's owner or an admin can change it"), "tr")).toBe(
273+ "Bu şablonu yalnızca onu oluşturan öğretmen (veya bir yönetici) değiştirebilir.",
274+ );
275+ expect(
276+ formatApiError(new ApiError(403, "only the course creator, an assigned teacher, or a manager/admin can author questions"), "tr"),
277+ ).toBe("Bu sınava yalnızca dersin öğretmenleri veya bir müdür soru ekleyebilir.");
278+ expect(
279+ formatApiError(
280+ new ApiError(403, "only the course creator, an assigned teacher, or a manager/admin can save questions to the bank"),
281+ "en",
282+ ),
283+ ).toBe("Only this course's teachers or a manager can save this question to the bank.");
284+ // same ordering bug shape for 404 ("course not found" / "exam not found")
285+ expect(formatApiError(new ApiError(404, "exam not found"), "tr")).toBe("Sınav bulunamadı.");
286+ expect(formatApiError(new ApiError(404, "course not found"), "en")).toBe("Course not found.");
287+ // unmatched messages still fall back to the generic per-status message
288+ expect(formatApiError(new ApiError(403, "some brand new refusal"), "tr")).toBe("Bu işlem için yetkin yok.");
289+ expect(formatApiError(new ApiError(404, ""), "en")).toBe("The requested record was not found.");
290+ });
291+
292+ it("localizes appointment booking and decision conflicts", () => {
293+ // exact backend strings from domain/appointment.rs — a miss renders
294+ // "İşlem tamamlanamadı: <English>"
295+ const cases: Array<[string, string]> = [
296+ ["the slot is already booked", "Bu saati senden önce başkası aldı."],
297+ ["the slot has already started", "Bu saat başladığı için artık randevu alınamaz."],
298+ ["you already have an appointment at that time", "O saatte zaten bir randevun var."],
299+ ["the appointment is already settled", "Bu randevu zaten sonuçlanmış."],
300+ ["the appointment has already started", "Bu randevu çoktan başladı."],
301+ ["that time has already started", "O saat çoktan başladı. Daha ileri bir saat seç."],
302+ ["no time has been proposed", "Bu randevu için henüz bir saat önerilmedi."],
303+ ["the appointment is no longer pending", "Bu randevu artık yanıt bekliyor değil."],
304+ ];
305+ for (const [backend, turkish] of cases) {
306+ expect(formatApiError(new ApiError(409, backend), "tr")).toBe(turkish);
307+ expect(formatApiError(new ApiError(409, backend), "en")).not.toMatch(/^İşlem/);
308+ expect(formatApiErrorMessage(backend, "en")).toMatch(/\.$/);
309+ }
310+ });
311+
312+ it("localizes the refresh-from-bank validation error", () => {
313+ // ValidationError::Invalid renders "{field}: {reason}" (web/exams.rs:2013)
314+ expect(formatApiError(new ApiError(400, "question: this question did not come from a bank template"), "tr")).toBe(
315+ "Bu soru bir banka şablonundan kopyalanmadığı için yenilenecek bir kaynağı yok.",
316+ );
317+ expect(formatApiError(new ApiError(400, "question: this question did not come from a bank template"), "en")).toBe(
318+ "This question was not copied from a bank template, so there is nothing to refresh it from.",
319+ );
320+ });
321+
200 it("formats 500+", () => {322 it("formats 500+", () => {
201 expect(formatApiError(new ApiError(500, ""), "en")).toBe("Server error. Please try again.");323 expect(formatApiError(new ApiError(500, ""), "en")).toBe("Server error. Please try again.");
202 expect(formatApiError(new ApiError(503, ""), "tr")).toBe("Sunucuda bir sorun oluştu. Lütfen tekrar dene.");324 expect(formatApiError(new ApiError(503, ""), "tr")).toBe("Sunucuda bir sorun oluştu. Lütfen tekrar dene.");
src/api/client/client.tsmodified+81 -11
@@ -21,6 +21,11 @@ type RequestOptions = {
21 21
22 const API_PREFIX = "/api";22 const API_PREFIX = "/api";
23 23
24+// Deadline for a JSON request. Generous enough for the slowest real call
25+// (login's Argon2 hash under load), short enough that a hung socket surfaces
26+// as an error instead of a permanently disabled button.
27+const REQUEST_TIMEOUT_MS = 20_000;
28+
24 const API_ERROR_MESSAGES: Record<string, Record<Locale, string>> = {29 const API_ERROR_MESSAGES: Record<string, Record<Locale, string>> = {
25 // Settings lists reject two entries that fold to the same word — İZİN/izin,30 // Settings lists reject two entries that fold to the same word — İZİN/izin,
26 // ÖDEV/odev. Keyed on the whole normalized string, so both fields are listed.31 // ÖDEV/odev. Keyed on the whole normalized string, so both fields are listed.
@@ -100,6 +105,47 @@ const API_ERROR_MESSAGES: Record<string, Record<Locale, string>> = {
100 en: "The repeated slots overlap each other.",105 en: "The repeated slots overlap each other.",
101 tr: "Tekrarlanan müsaitlikler birbiriyle çakışıyor.",106 tr: "Tekrarlanan müsaitlikler birbiriyle çakışıyor.",
102 },107 },
108+ // Booking/decision conflicts from domain/appointment.rs — byte-exact.
109+ "the slot is already booked": {
110+ en: "Someone else booked this time first.",
111+ tr: "Bu saati senden önce başkası aldı.",
112+ },
113+ "the slot has already started": {
114+ en: "This time has already started, so it can no longer be booked.",
115+ tr: "Bu saat başladığı için artık randevu alınamaz.",
116+ },
117+ "you already have an appointment at that time": {
118+ en: "You already have an appointment at that time.",
119+ tr: "O saatte zaten bir randevun var.",
120+ },
121+ "the appointment is already settled": {
122+ en: "This appointment is already settled.",
123+ tr: "Bu randevu zaten sonuçlanmış.",
124+ },
125+ "the appointment has already started": {
126+ en: "This appointment has already started.",
127+ tr: "Bu randevu çoktan başladı.",
128+ },
129+ "that time has already started": {
130+ en: "That time has already started. Pick a later one.",
131+ tr: "O saat çoktan başladı. Daha ileri bir saat seç.",
132+ },
133+ "no time has been proposed": {
134+ en: "No time has been proposed for this appointment yet.",
135+ tr: "Bu randevu için henüz bir saat önerilmedi.",
136+ },
137+ "the appointment is no longer pending": {
138+ en: "This appointment is no longer waiting for an answer.",
139+ tr: "Bu randevu artık yanıt bekliyor değil.",
140+ },
141+ "question: this question did not come from a bank template": {
142+ en: "This question was not copied from a bank template, so there is nothing to refresh it from.",
143+ tr: "Bu soru bir banka şablonundan kopyalanmadığı için yenilenecek bir kaynağı yok.",
144+ },
145+ "request timed out": {
146+ en: "The server did not respond in time. Check your connection and try again.",
147+ tr: "Sunucu zamanında yanıt vermedi. Bağlantını kontrol edip tekrar dene.",
148+ },
103 "only the template's owner or an admin can change it": {149 "only the template's owner or an admin can change it": {
104 en: "Only the teacher who created this template (or an admin) can change it.",150 en: "Only the teacher who created this template (or an admin) can change it.",
105 tr: "Bu şablonu yalnızca onu oluşturan öğretmen (veya bir yönetici) değiştirebilir.",151 tr: "Bu şablonu yalnızca onu oluşturan öğretmen (veya bir yönetici) değiştirebilir.",
@@ -294,20 +340,42 @@ export async function client<T>(path: string, options: RequestOptions = {}): Pro
294 body = JSON.stringify(options.body);340 body = JSON.stringify(options.body);
295 }341 }
296 342
297- const res = await fetch(`${API_PREFIX}${path}`, {343+ // JSON calls only — uploads (formClient) and downloads (blobClient) stay
298- method: options.method ?? "GET",344+ // untimed. Without this a dead connection leaves callers (exam-room REST
299- headers,345+ // autosave) stuck on "saving…" until the browser gives up.
300- body,346+ const timeout = AbortSignal.timeout(REQUEST_TIMEOUT_MS);
301- credentials: "same-origin",347+ // Caller-initiated aborts keep their original AbortError so cancellation
302- signal: options.signal,348+ // handling upstream is untouched; only our own deadline becomes an ApiError.
303- cache: options.cache,349+ const asDeadlineError = (err: unknown) =>
304- });350+ timeout.aborted && !options.signal?.aborted ? new ApiError(408, "request timed out") : err;
351+
352+ let res: Response;
353+ try {
354+ res = await fetch(`${API_PREFIX}${path}`, {
355+ method: options.method ?? "GET",
356+ headers,
357+ body,
358+ credentials: "same-origin",
359+ signal: options.signal ? AbortSignal.any([options.signal, timeout]) : timeout,
360+ cache: options.cache,
361+ });
362+ } catch (err) {
363+ throw asDeadlineError(err);
364+ }
305 365
306 if (res.status === 204) {366 if (res.status === 204) {
307 return undefined as T;367 return undefined as T;
308 }368 }
309 369
310- const text = await res.text();370+ // The deadline aborts the body stream too, so headers can arrive in time and
371+ // res.text() still blow up mid-download on a multi-MB response.
372+ let text: string;
373+ try {
374+ text = await res.text();
375+ } catch (err) {
376+ throw asDeadlineError(err);
377+ }
378+
311 let data: unknown = null;379 let data: unknown = null;
312 if (text) {380 if (text) {
313 try {381 try {
@@ -398,12 +466,14 @@ export function formatApiError(err: unknown, locale: Locale = currentLocale()):
398 if ((err.status === 429 || err.status === 503) && err.retryAfter != null) {466 if ((err.status === 429 || err.status === 503) && err.retryAfter != null) {
399 return locale === "tr" ? `${err.retryAfter} sn sonra tekrar dene.` : `Try again in ${err.retryAfter}s.`;467 return locale === "tr" ? `${err.retryAfter} sn sonra tekrar dene.` : `Try again in ${err.retryAfter}s.`;
400 }468 }
469+ // The specific backend message wins over the per-status generic one —
470+ // otherwise every 401/403/404/413/5xx entry in the table is dead code.
471+ const known = API_ERROR_MESSAGES[normalizeApiMessage(err.message)]?.[locale];
472+ if (known) return known;
401 if (err.status === 401) return API_ERROR_MESSAGES.unauthorized[locale];473 if (err.status === 401) return API_ERROR_MESSAGES.unauthorized[locale];
402 if (err.status === 403) return API_ERROR_MESSAGES.forbidden[locale];474 if (err.status === 403) return API_ERROR_MESSAGES.forbidden[locale];
403 if (err.status === 404) return API_ERROR_MESSAGES["not found"][locale];475 if (err.status === 404) return API_ERROR_MESSAGES["not found"][locale];
404- if (err.status === 409) return formatApiErrorMessage(err.message, locale);
405 if (err.status === 413) return API_ERROR_MESSAGES["payload too large"][locale];476 if (err.status === 413) return API_ERROR_MESSAGES["payload too large"][locale];
406- if (err.status === 422) return formatApiErrorMessage(err.message, locale);
407 if (err.status >= 500) return locale === "tr" ? "Sunucuda bir sorun oluştu. Lütfen tekrar dene." : "Server error. Please try again.";477 if (err.status >= 500) return locale === "tr" ? "Sunucuda bir sorun oluştu. Lütfen tekrar dene." : "Server error. Please try again.";
408 return formatApiErrorMessage(err.message, locale);478 return formatApiErrorMessage(err.message, locale);
409 }479 }
src/api/client/types.tsmodified+2 -1
@@ -107,7 +107,8 @@ export type Appointment = {
107 requester: PersonRef;107 requester: PersonRef;
108 status: AppointmentStatus;108 status: AppointmentStatus;
109 reason: string;109 reason: string;
110- starts_at: number | null; // effective window (proposal if accepted, else slot's)110+ starts_at: number | null; // effective window: the proposal whenever one is on the
111+ // row (accepted or not), else the slot's own time
111 ends_at: number | null;112 ends_at: number | null;
112 proposed_starts_at: number | null;113 proposed_starts_at: number | null;
113 proposed_ends_at: number | null;114 proposed_ends_at: number | null;
src/components/appointments/publish-slots-form.tsxmodified+2 -1
@@ -36,7 +36,8 @@ export function PublishSlotsForm(props: {
36 36
37 const validate = (starts: number | null, ends: number | null, until: number | null): string | null => {37 const validate = (starts: number | null, ends: number | null, until: number | null): string | null => {
38 if (starts == null || ends == null) return t("form.timeOrder");38 if (starts == null || ends == null) return t("form.timeOrder");
39- if (ends < starts) return t("form.timeOrder");39+ // `check_window` rejects `starts >= ends` (400) — a zero-length slot is not a window.
40+ if (ends <= starts) return t("form.timeOrder");
40 const grace = now() - 60_000;41 const grace = now() - 60_000;
41 if (starts < grace || ends < grace) return t("form.timePast");42 if (starts < grace || ends < grace) return t("form.timePast");
42 if (repeatWeekly()) {43 if (repeatWeekly()) {
src/components/appointments/reschedule-form.tsxmodified+2 -1
@@ -26,7 +26,8 @@ export function RescheduleForm(props: {
26 e.preventDefault();26 e.preventDefault();
27 const starts_at = dateTimeInputToMs(startsDate(), startsTime());27 const starts_at = dateTimeInputToMs(startsDate(), startsTime());
28 const ends_at = dateTimeInputToMs(endsDate(), endsTime());28 const ends_at = dateTimeInputToMs(endsDate(), endsTime());
29- if (starts_at == null || ends_at == null || ends_at < starts_at) {29+ // `propose` rejects `starts_at >= ends_at` (400 "must be after proposed_starts_at").
30+ if (starts_at == null || ends_at == null || ends_at <= starts_at) {
30 setError(t("form.timeOrder"));31 setError(t("form.timeOrder"));
31 return;32 return;
32 }33 }
src/components/exams/exam-room-ws.tsxmodified+22 -11
@@ -147,7 +147,7 @@ export function ExamRoomWS(props: { exam: Exam }) {
147 ws.onerror = null;147 ws.onerror = null;
148 ws.onmessage = null;148 ws.onmessage = null;
149 ws.close();149 ws.close();
150- acks.failAll(new Error(t("attempt.saveDisconnected")));150+ acks.failAll(new Error(t("attempt.saveDisconnected")), "socket-closed");
151 }151 }
152 setWsState("connecting");152 setWsState("connecting");
153 const socket = new WebSocket(wsUrl());153 const socket = new WebSocket(wsUrl());
@@ -161,7 +161,7 @@ export function ExamRoomWS(props: { exam: Exam }) {
161 setWsState("disconnected");161 setWsState("disconnected");
162 ws = null;162 ws = null;
163 // Anything still waiting for a `saved` frame will never get one.163 // Anything still waiting for a `saved` frame will never get one.
164- acks.failAll(new Error(t("attempt.saveDisconnected")));164+ acks.failAll(new Error(t("attempt.saveDisconnected")), "socket-closed");
165 scheduleReconnect();165 scheduleReconnect();
166 };166 };
167 socket.onclose = dropped;167 socket.onclose = dropped;
@@ -215,11 +215,13 @@ export function ExamRoomWS(props: { exam: Exam }) {
215 case "error": {215 case "error": {
216 const message = formatApiErrorMessage(msg.message, locale());216 const message = formatApiErrorMessage(msg.message, locale());
217 setError(message);217 setError(message);
218- // A frame that names a question refused that one save; anything else218+ // A frame that names a question refused that one save; anything else is
219- // is room- or connection-level (bad frame, sitting over, unenrolled),219+ // room-level (bad frame, sitting over, unenrolled, internal error), so
220- // so everything in flight is treated as rejected — never as saved.220+ // everything in flight is treated as rejected — never as saved. The
221+ // socket stays open on this path, so each rejected send is still owed a
222+ // frame of its own: `error-frame` keeps that debt instead of wiping it.
221 if (msg.question_id) acks.fail(msg.question_id, new Error(message));223 if (msg.question_id) acks.fail(msg.question_id, new Error(message));
222- else acks.failAll(new Error(message));224+ else acks.failAll(new Error(message), "error-frame");
223 break;225 break;
224 }226 }
225 }227 }
@@ -299,10 +301,13 @@ export function ExamRoomWS(props: { exam: Exam }) {
299 } else {301 } else {
300 await postExamAttemptAnswer(props.exam.id, { question_id: question.id, text: value });302 await postExamAttemptAnswer(props.exam.id, { question_id: question.id, text: value });
301 }303 }
302- const next = await getExamAttempt(props.exam.id);304+ // The POST above is the save. Refreshing is only about the badges, so a
303- setAttempt(next);305+ // failed refresh must not report a stored answer as lost.
304- const qs = await getExamAttemptQuestions(props.exam.id);306+ try {
305- setQuestions(qs);307+ await refreshAnswers();
308+ } catch {
309+ // ignore — the countdown/updated_at catch up on the next poll
310+ }
306 return true;311 return true;
307 } catch (err) {312 } catch (err) {
308 setError(formatApiError(err, locale()));313 setError(formatApiError(err, locale()));
@@ -735,13 +740,19 @@ function QuestionAnswerCardWS(props: {
735 // "Saved" means the server said so. A failure leaves the typed/picked answer740 // "Saved" means the server said so. A failure leaves the typed/picked answer
736 // untouched in the card so the student can just press save again.741 // untouched in the card so the student can just press save again.
737 const save = async () => {742 const save = async () => {
743+ // The card is reused across questions, and switching question resets
744+ // `saveState` — so an outcome that lands after the switch would paint a
745+ // badge for a question it never belonged to. Only the question that started
746+ // this save may be told about it.
747+ const savedId = props.question.id;
738 setSaveState("saving");748 setSaveState("saving");
739 try {749 try {
740 const confirmed = await props.onSave(value());750 const confirmed = await props.onSave(value());
741- if (!confirmed) return; // a newer save owns the outcome751+ if (!confirmed || props.question.id !== savedId) return; // a newer save owns the outcome
742 setSaveState("saved");752 setSaveState("saved");
743 props.onSaved?.();753 props.onSaved?.();
744 } catch {754 } catch {
755+ if (props.question.id !== savedId) return;
745 setSaveState("failed"); // the parent banner carries the reason756 setSaveState("failed"); // the parent banner carries the reason
746 }757 }
747 };758 };
src/components/layout/app-shell.tsxmodified+3 -1
@@ -203,10 +203,12 @@ export function AppShell(props: ParentProps) {
203 <RightNav />203 <RightNav />
204 </Show>204 </Show>
205 </div>205 </div>
206- </ShellFeedProvider>206+ {/* MobileTabBar stays inside the provider — it is a shell surface, so a
207+ useShellFeed() badge there must not throw. */}
207 <Show when={auth.user() && !wide()}>208 <Show when={auth.user() && !wide()}>
208 <MobileTabBar onMenu={() => setMobileOpen(true)} />209 <MobileTabBar onMenu={() => setMobileOpen(true)} />
209 </Show>210 </Show>
211+ </ShellFeedProvider>
210 <Show when={auth.user()}>212 <Show when={auth.user()}>
211 <CelebiPanel open={celebiOpen()} onOpenChange={setCelebiOpen} />213 <CelebiPanel open={celebiOpen()} onOpenChange={setCelebiOpen} />
212 <CommandPalette214 <CommandPalette
src/components/layout/notification-center.tsxmodified+25 -4
@@ -50,9 +50,10 @@ export function NotificationCenter() {
50 const allNotifications = createMemo<NotificationItem[]>(() => {50 const allNotifications = createMemo<NotificationItem[]>(() => {
51 const list: NotificationItem[] = [];51 const list: NotificationItem[] = [];
52 52
53- // 1. Unread Messages — shared inbox is the full list, filter to unread here53+ // 1. Unread messages — the dedicated `read=false` page from the shell feed.
54- // (was a dedicated read:false fetch before the shell feed consolidation).54+ // Never filter the shared inbox page instead: it is capped and ordered by
55- const msgs = feed.messages().items.filter((m) => !m.read);55+ // id DESC, so an older unread message is simply not in it.
56+ const msgs = feed.unreadMessages().items;
56 for (const m of msgs) {57 for (const m of msgs) {
57 list.push({58 list.push({
58 id: `msg_${m.id}`,59 id: `msg_${m.id}`,
@@ -143,7 +144,26 @@ export function NotificationCenter() {
143 return allNotifications().filter((item) => !dismissed.has(item.id));144 return allNotifications().filter((item) => !dismissed.has(item.id));
144 });145 });
145 146
146- const unreadCount = () => activeNotifications().length;147+ // The list only holds the newest 10 unread messages; `total` is the real
148+ // server-side unread count, so the rest still counts towards the badge.
149+ // Those extra rows have no id here, so they cannot be dismissed one by one:
150+ // "dismiss all" snapshots the unread total instead. Everything at or below the
151+ // snapshot counts as dismissed; anything above it arrived afterwards and still
152+ // raises the badge (minus the new rows already listed, which the active list
153+ // counts). Without the snapshot, 11 unread → dismiss all → badge stuck at 1
154+ // over an empty popover.
155+ // ponytail: the snapshot is in-memory while dismissed ids are persisted, so a
156+ // reload re-shows unlisted unread — upgrade path is storing it next to the ids
157+ // in `lib/notifications`.
158+ const [dismissedUnreadTotal, setDismissedUnreadTotal] = createSignal(0);
159+ const activeMessageCount = () => activeNotifications().filter((item) => item.type === "message").length;
160+ const unlistedUnread = () => {
161+ const page = feed.unreadMessages();
162+ const beyondPage = page.total - page.items.length;
163+ const sinceDismissAll = page.total - dismissedUnreadTotal() - activeMessageCount();
164+ return Math.max(0, Math.min(beyondPage, sinceDismissAll));
165+ };
166+ const unreadCount = () => activeNotifications().length + unlistedUnread();
147 167
148 const handleDismissSingle = (evt: MouseEvent, id: string) => {168 const handleDismissSingle = (evt: MouseEvent, id: string) => {
149 evt.stopPropagation();169 evt.stopPropagation();
@@ -155,6 +175,7 @@ export function NotificationCenter() {
155 const ids = activeNotifications().map((item) => item.id);175 const ids = activeNotifications().map((item) => item.id);
156 const updated = dismissAllNotificationIds(ids);176 const updated = dismissAllNotificationIds(ids);
157 setDismissedIds(new Set(updated));177 setDismissedIds(new Set(updated));
178+ setDismissedUnreadTotal(feed.unreadMessages().total);
158 };179 };
159 180
160 const handleSelectNotification = async (item: NotificationItem) => {181 const handleSelectNotification = async (item: NotificationItem) => {
src/components/layout/right-nav.tsxmodified+10 -5
@@ -17,7 +17,8 @@ import {
17 IconX,17 IconX,
18 } from "@/components/ui/icons";18 } from "@/components/ui/icons";
19 import { cn } from "@/lib/cn";19 import { cn } from "@/lib/cn";
20-import { personLabel } from "@/lib/person";20+import { appointmentCounterpart, personLabel } from "@/lib/person";
21+import { useAuth } from "@/stores/auth-context";
21 import { usePreferences, useT } from "@/stores/preferences-context";22 import { usePreferences, useT } from "@/stores/preferences-context";
22 import { useShellFeed } from "@/stores/shell-feed-context";23 import { useShellFeed } from "@/stores/shell-feed-context";
23 24
@@ -35,6 +36,7 @@ export function RightNav() {
35 const location = useLocation();36 const location = useLocation();
36 const { locale } = usePreferences();37 const { locale } = usePreferences();
37 const feed = useShellFeed();38 const feed = useShellFeed();
39+ const auth = useAuth();
38 40
39 const isMessagesActive = () => location().pathname === "/messages";41 const isMessagesActive = () => location().pathname === "/messages";
40 const isCalendarActive = () => location().pathname === "/calendar";42 const isCalendarActive = () => location().pathname === "/calendar";
@@ -63,7 +65,11 @@ export function RightNav() {
63 // on every 60s refetch and — since RightNav sits beside <Outlet> in AppShell —65 // on every 60s refetch and — since RightNav sits beside <Outlet> in AppShell —
64 // blanks the whole page for the fetch duration. `.latest` keeps the last value.66 // blanks the whole page for the fetch duration. `.latest` keeps the last value.
65 const allMessages = () => feed.messages().items;67 const allMessages = () => feed.messages().items;
66- const unreadCount = createMemo(() => allMessages().filter((m: Message) => !m.read).length);68+ // Same source of truth as NotificationCenter: the dedicated `read=false` page,
69+ // whose `total` is the exact server-side unread count. The inbox page above is
70+ // capped at 100 and ordered by id DESC, so filtering it silently drops older
71+ // unread messages and the two shell badges disagree.
72+ const unreadCount = createMemo(() => feed.unreadMessages().total);
67 73
68 const filteredMessages = createMemo(() => {74 const filteredMessages = createMemo(() => {
69 let list = allMessages();75 let list = allMessages();
@@ -599,8 +605,7 @@ export function RightNav() {
599 const isEvent = item.type === "event";605 const isEvent = item.type === "event";
600 const isAppt = item.type === "appointment";606 const isAppt = item.type === "appointment";
601 const title = item.type === "appointment"607 const title = item.type === "appointment"
602- ? ((item.data.teacher?.display_name ?? item.data.teacher?.username)608+ ? appointmentCounterpart(item.data, auth.user()?.id)
603- ?? item.data.requester.display_name ?? item.data.requester.username)
604 : item.data.title;609 : item.data.title;
605 return (610 return (
606 <div611 <div
@@ -694,7 +699,7 @@ export function RightNav() {
694 const appt = () => (cur.type === "appointment" ? cur.data : null);699 const appt = () => (cur.type === "appointment" ? cur.data : null);
695 const title = () => {700 const title = () => {
696 const a = appt();701 const a = appt();
697- if (a) return (a.teacher?.display_name ?? a.teacher?.username) ?? a.requester.display_name ?? a.requester.username;702+ if (a) return appointmentCounterpart(a, auth.user()?.id);
698 return (cur.data as Event | Exam).title;703 return (cur.data as Event | Exam).title;
699 };704 };
700 return (705 return (
src/components/layout/shell-unread-badge.test.tsxadded+93 -0
@@ -0,0 +1,93 @@
1+import { createSignal } from "solid-js";
2+import { fireEvent, render, screen } from "@solidjs/testing-library";
3+import { NotificationCenter } from "@/components/layout/notification-center";
4+import { RightNav } from "@/components/layout/right-nav";
5+import { PreferencesProvider } from "@/stores/preferences-context";
6+
7+// The shell feed is the single source of truth for both badges; the test drives
8+// it through signals so a refetch (new message arriving) is reproducible.
9+const h = vi.hoisted(() => ({ feed: null as never }));
10+
11+vi.mock("@/stores/shell-feed-context", () => ({ useShellFeed: () => h.feed }));
12+vi.mock("@/stores/auth-context", () => ({ useAuth: () => ({ user: () => ({ id: "u-1" }) }) }));
13+vi.mock("@tanstack/solid-router", () => ({
14+ useNavigate: () => () => {},
15+ useLocation: () => () => ({ pathname: "/" }),
16+}));
17+// Kobalte's popover keeps its content unmounted in jsdom; the badge and the
18+// "dismiss all" button are the surfaces under test, so render both inline.
19+vi.mock("@/components/ui/popover", () => ({
20+ Popover: (props: never) => (props as { children: unknown }).children,
21+ PopoverTrigger: (props: never) => <div>{(props as { children: unknown }).children}</div>,
22+ PopoverContent: (props: never) => <div>{(props as { children: unknown }).children}</div>,
23+}));
24+
25+const emptyPage = { items: [], total: 0, limit: null, offset: 0 };
26+const msg = (id: string) => ({
27+ id,
28+ sender: { id: "s", name: "Ada", surname: "L" },
29+ subject: `subject ${id}`,
30+ body: "",
31+ read: false,
32+ sent_at: 1,
33+});
34+
35+function mountFeed(inbox: unknown[], unread: { items: unknown[]; total: number }) {
36+ const [messages, setMessages] = createSignal({ ...emptyPage, items: inbox, total: inbox.length });
37+ const [unreadMessages, setUnreadMessages] = createSignal({ ...emptyPage, ...unread });
38+ h.feed = {
39+ messages,
40+ unreadMessages,
41+ events: () => emptyPage,
42+ exams: () => emptyPage,
43+ appointments: () => emptyPage,
44+ homework: () => emptyPage,
45+ nowMs: () => Date.now(),
46+ refetchMessages: () => {},
47+ refreshAll: () => {},
48+ } as never;
49+ return { setMessages, setUnreadMessages };
50+}
51+
52+const badges = () => Array.from(document.querySelectorAll(".bg-rose-500")).map((n) => n.textContent);
53+
54+beforeEach(() => localStorage.clear());
55+afterEach(() => vi.restoreAllMocks());
56+
57+// DEFECT 1: RightNav used to filter the capped `limit:100` inbox page, so an
58+// unread message that fell off that page was counted by one badge only.
59+test("both shell badges report the same unread count", () => {
60+ // 7 unread server-side, but only 2 of them are on the capped inbox page.
61+ mountFeed([msg("m6"), msg("m7")], { items: [msg("m3"), msg("m6"), msg("m7")], total: 7 });
62+
63+ render(() => (
64+ <PreferencesProvider>
65+ <RightNav />
66+ <NotificationCenter />
67+ </PreferencesProvider>
68+ ));
69+
70+ expect(badges()).toEqual(["7", "7"]);
71+});
72+
73+// DEFECT 2: unlisted unread ignored dismissal, so dismiss-all left the badge
74+// stuck at (total - listed) over an empty popover.
75+test("dismiss all clears the badge, a later message raises it again", () => {
76+ const listed = Array.from({ length: 10 }, (_, i) => msg(`m${i}`));
77+ const { setUnreadMessages } = mountFeed([], { items: listed, total: 11 });
78+
79+ render(() => (
80+ <PreferencesProvider>
81+ <NotificationCenter />
82+ </PreferencesProvider>
83+ ));
84+
85+ expect(badges()).toEqual(["9+"]);
86+
87+ fireEvent.click(screen.getByTitle("Tüm Bildirimleri Temizle"));
88+ expect(badges()).toEqual([]);
89+
90+ // A genuinely new message pushes the oldest listed one off the page.
91+ setUnreadMessages({ ...emptyPage, items: [msg("new"), ...listed.slice(0, 9)], total: 12 });
92+ expect(badges()).toEqual(["1"]);
93+});
src/lib/appointment-actions.test.tsadded+65 -0
@@ -0,0 +1,65 @@
1+import type { Appointment, AppointmentStatus } from "@/api/client";
2+import { appointmentActions, hasStandingProposal } from "./appointment-actions";
3+
4+const NOW = 1_800_000_000_000;
5+const FUTURE = NOW + 60 * 60 * 1000;
6+const PAST = NOW - 60 * 60 * 1000;
7+
8+const appt = (status: AppointmentStatus, opts: { proposed?: boolean; startsAt?: number | null } = {}): Appointment =>
9+ ({
10+ id: "a1",
11+ slot: "s1",
12+ teacher: null,
13+ requester: { id: "u1", username: "ali", display_name: null },
14+ status,
15+ reason: "ödev",
16+ starts_at: opts.startsAt === undefined ? FUTURE : opts.startsAt,
17+ ends_at: FUTURE + 1000,
18+ proposed_starts_at: opts.proposed ? FUTURE : null,
19+ proposed_ends_at: opts.proposed ? FUTURE + 1000 : null,
20+ proposed_by: null,
21+ decided_by: null,
22+ cancelled_by: null,
23+ cancel_reason: null,
24+ reject_reason: null,
25+ created_at: PAST,
26+ }) as Appointment;
27+
28+it("counts a proposal as standing only while the row is still pending", () => {
29+ expect(hasStandingProposal(appt("pending", { proposed: true }))).toBe(true);
30+ // The backend never clears proposed_* on accept — an approved row with a
31+ // proposal is an ANSWERED one, so the teacher keeps their reschedule action.
32+ expect(hasStandingProposal(appt("approved", { proposed: true }))).toBe(false);
33+ expect(hasStandingProposal(appt("cancelled", { proposed: true }))).toBe(false);
34+});
35+
36+it("offers staff exactly what the backend accepts", () => {
37+ expect(appointmentActions(appt("pending"), "staff", NOW)).toEqual(["approve", "reject", "reschedule"]);
38+ // Standing proposal: no self-approval of one's own counter-proposal, but the
39+ // teacher can still withdraw it (reject) or propose again.
40+ expect(appointmentActions(appt("pending", { proposed: true }), "staff", NOW)).toEqual(["reject", "reschedule"]);
41+ // Answered proposal: reschedule must come back (the old `proposed_* != null`
42+ // gate lost it forever after one accepted reschedule).
43+ expect(appointmentActions(appt("approved", { proposed: true }), "staff", NOW)).toEqual(["reschedule"]);
44+ expect(appointmentActions(appt("approved"), "staff", NOW)).toEqual(["reschedule"]);
45+ // Window opened: approve 409s ("that time has already started"), reject does not.
46+ expect(appointmentActions(appt("pending", { startsAt: PAST }), "staff", NOW)).toEqual(["reject", "reschedule"]);
47+ expect(appointmentActions(appt("rejected"), "staff", NOW)).toEqual([]);
48+ expect(appointmentActions(appt("cancelled"), "staff", NOW)).toEqual([]);
49+});
50+
51+it("offers the requester exactly what the backend accepts", () => {
52+ expect(appointmentActions(appt("pending"), "requester", NOW)).toEqual(["cancel"]);
53+ expect(appointmentActions(appt("approved"), "requester", NOW)).toEqual(["cancel"]);
54+ expect(appointmentActions(appt("pending", { proposed: true }), "requester", NOW)).toEqual([
55+ "acceptReschedule",
56+ "declineReschedule",
57+ ]);
58+ // Started windows: cancel/accept/decline all 409.
59+ expect(appointmentActions(appt("approved", { startsAt: PAST }), "requester", NOW)).toEqual([]);
60+ expect(appointmentActions(appt("pending", { proposed: true, startsAt: PAST }), "requester", NOW)).toEqual([]);
61+ // Slot vanished -> every call 404s.
62+ expect(appointmentActions(appt("pending", { startsAt: null }), "requester", NOW)).toEqual([]);
63+ expect(appointmentActions(appt("cancelled"), "requester", NOW)).toEqual([]);
64+ expect(appointmentActions(appt("rejected"), "requester", NOW)).toEqual([]);
65+});
src/lib/appointment-actions.tsadded+71 -0
@@ -0,0 +1,71 @@
1+/**
2+ * Which appointment actions the backend will actually accept, per viewer.
3+ *
4+ * Mirrors the guards in `hezarfen_backend/src/web/appointments.rs` and
5+ * `src/domain/appointment.rs`. This app serves children: an action must never
6+ * be offered when the server is going to answer 403/409.
7+ */
8+import type { Appointment } from "@/api/client";
9+
10+export type AppointmentAction =
11+ // staff = the slot's teacher, or any manager+ (`can_manage`)
12+ | "approve"
13+ | "reject"
14+ | "reschedule"
15+ // requester = the person who asked for the meeting (`ensure_requester`)
16+ | "cancel"
17+ | "acceptReschedule"
18+ | "declineReschedule";
19+
20+export type AppointmentViewer = "staff" | "requester";
21+
22+/**
23+ * A counter-proposal still waiting for the requester's answer.
24+ *
25+ * The backend NEVER clears `proposed_*` — `accept_proposal` delegates to
26+ * `approve`, which writes `status`/`decided_by` only. So `proposed_* != null`
27+ * on a settled or approved row is an *answered* proposal, not a standing one,
28+ * and gating on it would strand the teacher without a reschedule action forever.
29+ */
30+export function hasStandingProposal(a: Appointment): boolean {
31+ return a.status === "pending" && a.proposed_starts_at != null && a.proposed_ends_at != null;
32+}
33+
34+const isLive = (a: Appointment) => a.status === "pending" || a.status === "approved";
35+
36+/**
37+ * Has the *effective* window opened? `starts_at` is already the effective one
38+ * (`Appointment::window` prefers a proposal whenever the row carries one), which
39+ * is exactly the value every `<= now` 409 guard compares. `null` means the slot
40+ * is gone, so every action would 404 — treat it as closed.
41+ */
42+const hasStarted = (a: Appointment, now: number) => a.starts_at == null || a.starts_at <= now;
43+
44+export function appointmentActions(a: Appointment, viewer: AppointmentViewer, now: number): AppointmentAction[] {
45+ const standing = hasStandingProposal(a);
46+ const actions: AppointmentAction[] = [];
47+ if (viewer === "staff") {
48+ // `approve` needs pending + a window that has not opened. While the
49+ // teacher's own counter-proposal stands the backend would still take it,
50+ // but accepting it is the requester's call — we do not offer a way to move
51+ // someone else's meeting without their answer.
52+ if (a.status === "pending" && !standing && !hasStarted(a, now)) actions.push("approve");
53+ // `reject` is guarded by `read_pending` alone — no time check — so a passed
54+ // pending request (or a standing proposal the teacher wants back) can
55+ // always be turned down.
56+ if (a.status === "pending") actions.push("reject");
57+ // `propose` needs a live row only; the *new* time must be in the future,
58+ // which the reschedule form validates. Re-proposing over an answered or a
59+ // standing proposal is legal.
60+ if (isLive(a)) actions.push("reschedule");
61+ return actions;
62+ }
63+ // Requester side. Accepting is `approve` at the proposed time and declining
64+ // is `cancel`, so both close once that window opens.
65+ if (standing) {
66+ if (!hasStarted(a, now)) actions.push("acceptReschedule", "declineReschedule");
67+ return actions;
68+ }
69+ if (isLive(a) && !hasStarted(a, now)) actions.push("cancel");
70+ return actions;
71+}
src/lib/create-ack-waiter.test.tsmodified+105 -4
@@ -27,12 +27,51 @@ describe("createAckWaiter", () => {
27 const w = createAckWaiter(1000);27 const w = createAckWaiter(1000);
28 const a = w.wait("q1");28 const a = w.wait("q1");
29 const b = w.wait("q2");29 const b = w.wait("q2");
30- w.failAll(new Error("disconnected"));30+ w.failAll(new Error("disconnected"), "socket-closed");
31 await expect(a).rejects.toThrow("disconnected");31 await expect(a).rejects.toThrow("disconnected");
32 await expect(b).rejects.toThrow("disconnected");32 await expect(b).rejects.toThrow("disconnected");
33 expect(w.size).toBe(0);33 expect(w.size).toBe(0);
34 });34 });
35 35
36+ // Regression (defect 1): an unattributed error frame does NOT close the socket
37+ // (`exam_ws.rs:496` keeps serving), so the frames owed to the sends it rejected
38+ // are still on their way. One of them must not confirm the student's retry.
39+ it("does not let an in-flight ack confirm the retry after an unattributed error frame", async () => {
40+ const w = createAckWaiter(1000);
41+ const first = w.wait("q1");
42+ const firstAssertion = expect(first).rejects.toThrow("state unavailable");
43+ w.failAll(new Error("state unavailable"), "error-frame"); // socket stays open
44+ await firstAssertion;
45+
46+ const retry = w.wait("q1");
47+ let outcome: string | undefined;
48+ void retry.then(
49+ (r) => { outcome = `resolved:${r}`; },
50+ (e: Error) => { outcome = `rejected:${e.message}`; },
51+ );
52+ w.ack("q1"); // the FIRST send's `saved` frame, still in flight
53+ await Promise.resolve();
54+ expect(outcome).toBeUndefined(); // must NOT claim the retry was saved
55+
56+ w.ack("q1"); // now the retry's own frame
57+ await expect(retry).resolves.toBe("ok");
58+ });
59+
60+ // A genuine socket close means nothing is coming: the debt must not survive
61+ // into the reconnect, or the next save on that question would eat its own ack.
62+ it("clears owed frames when the socket actually closes", async () => {
63+ const w = createAckWaiter(1000);
64+ const first = w.wait("q1");
65+ const firstAssertion = expect(first).rejects.toThrow("state unavailable");
66+ w.failAll(new Error("state unavailable"), "error-frame");
67+ await firstAssertion;
68+
69+ w.failAll(new Error("disconnected"), "socket-closed"); // socket drops, reconnect
70+ const afterReconnect = w.wait("q1");
71+ w.ack("q1");
72+ await expect(afterReconnect).resolves.toBe("ok");
73+ });
74+
36 it("fails only the named save when the error frame blames one question", async () => {75 it("fails only the named save when the error frame blames one question", async () => {
37 const w = createAckWaiter(1000);76 const w = createAckWaiter(1000);
38 const a = w.wait("q1");77 const a = w.wait("q1");
@@ -49,16 +88,78 @@ describe("createAckWaiter", () => {
49 void w.wait("q1").catch(() => {});88 void w.wait("q1").catch(() => {});
50 w.fail("q2", new Error("boom")); // late/unknown blame must not touch q189 w.fail("q2", new Error("boom")); // late/unknown blame must not touch q1
51 expect(w.size).toBe(1);90 expect(w.size).toBe(1);
52- w.failAll(new Error("cleanup"));91+ w.failAll(new Error("cleanup"), "socket-closed");
53 });92 });
54 93
55- it("marks an overtaken save superseded instead of failing it", async () => {94+ it("marks an overtaken save superseded and lets its own ack settle nobody", async () => {
56 const w = createAckWaiter(1000);95 const w = createAckWaiter(1000);
57 const first = w.wait("q1");96 const first = w.wait("q1");
58 const second = w.wait("q1");97 const second = w.wait("q1");
59 await expect(first).resolves.toBe("superseded");98 await expect(first).resolves.toBe("superseded");
60- w.ack("q1");99+ expect(w.size).toBe(1);
100+ w.ack("q1"); // the first send's ack — the second is still unconfirmed
101+ expect(w.size).toBe(1);
102+ w.ack("q1"); // now the second send's own ack
61 await expect(second).resolves.toBe("ok");103 await expect(second).resolves.toBe("ok");
104+ expect(w.size).toBe(0);
105+ });
106+
107+ // Regression: a `saved` frame for a send that already timed out must never
108+ // confirm the retry that replaced it — that told students "Saved" for an
109+ // answer the server had refused.
110+ it("does not let a timed-out send's late ack confirm the retry", async () => {
111+ vi.useFakeTimers();
112+ const w = createAckWaiter(8000);
113+ const first = w.wait("q1"); // student saves "A"
114+ const firstAssertion = expect(first).rejects.toThrow("ack timeout");
115+ await vi.advanceTimersByTimeAsync(8000);
116+ await firstAssertion;
117+
118+ const retry = w.wait("q1"); // student presses save again with "B"
119+ let outcome: string | undefined;
120+ void retry.then(
121+ (r) => { outcome = `resolved:${r}`; },
122+ (e: Error) => { outcome = `rejected:${e.message}`; },
123+ );
124+
125+ w.ack("q1"); // the FIRST send's late `saved` frame finally lands
126+ await vi.advanceTimersByTimeAsync(0);
127+ expect(outcome).toBeUndefined(); // must NOT claim the retry was saved
128+
129+ w.fail("q1", new Error("a choice question takes selected")); // the retry's own error frame
130+ await vi.advanceTimersByTimeAsync(0);
131+ expect(outcome).toBe("rejected:a choice question takes selected");
132+ vi.useRealTimers();
133+ });
134+
135+ // Regression (defect 2): the old tombstone was dropped by a timer after one
136+ // more timeout window, so a frame arriving after that settled the NEXT live
137+ // send "ok". Debt has no expiry — it is only ever paid off by a frame.
138+ it("does not let a very late ack confirm a newer send once the tombstone window would have lapsed", async () => {
139+ vi.useFakeTimers();
140+ const w = createAckWaiter(8000);
141+ const first = w.wait("q1"); // t=0, send #1
142+ const firstAssertion = expect(first).rejects.toThrow("ack timeout");
143+ await vi.advanceTimersByTimeAsync(8000); // t=8s, send #1 times out
144+ await firstAssertion;
145+
146+ await vi.advanceTimersByTimeAsync(1000); // t=9s
147+ const second = w.wait("q1"); // send #2, live
148+ let outcome: string | undefined;
149+ void second.then(
150+ (r) => { outcome = `resolved:${r}`; },
151+ (e: Error) => { outcome = `rejected:${e.message}`; },
152+ );
153+
154+ await vi.advanceTimersByTimeAsync(7000); // t=16s, old tombstone expiry moment
155+ w.ack("q1"); // send #1's frame lands at last
156+ await vi.advanceTimersByTimeAsync(0);
157+ expect(outcome).toBeUndefined(); // must NOT confirm send #2
158+
159+ w.ack("q1"); // send #2's own frame
160+ await vi.advanceTimersByTimeAsync(0);
161+ expect(outcome).toBe("resolved:ok");
162+ vi.useRealTimers();
62 });163 });
63 164
64 it("does not confirm after a timeout has already fired", async () => {165 it("does not confirm after a timeout has already fired", async () => {
src/lib/create-ack-waiter.tsmodified+100 -23
@@ -5,9 +5,28 @@
5 * exam room waits for the server's `{"type":"saved", question_id}` frame before5 * exam room waits for the server's `{"type":"saved", question_id}` frame before
6 * it may tell a student their answer is stored. `wait(key)` hands back a promise6 * it may tell a student their answer is stored. `wait(key)` hands back a promise
7 * that settles on `ack(key)`, rejects on `fail(key)` (an error frame that names7 * that settles on `ack(key)`, rejects on `fail(key)` (an error frame that names
8- * the question it refused), rejects on `failAll()` (an unattributed error frame,8+ * the question it refused), rejects on `failAll()` (a socket drop, or an
9- * or a socket drop — which invalidates every pending save) and rejects on its9+ * unattributed error frame) and rejects on its own timeout when nothing ever
10- * own timeout when nothing ever comes back.10+ * comes back.
11+ *
12+ * **Acks are matched per send, not per question.** The server answers every
13+ * `answer` frame with exactly one `saved`/`error` frame, in order
14+ * (`exam_ws.rs:396,410`), so each key keeps a FIFO queue of the sends that still
15+ * own a promise, plus `owed`: a count of frames the server still has to send for
16+ * sends that no longer own anybody's promise (they timed out, a newer save
17+ * overtook them, or an unattributed error frame rejected them while the socket
18+ * stayed open). Those dead sends are always older than any live one, so an
19+ * incoming frame pays off `owed` first and is discarded; only once the debt is
20+ * clear does a frame settle the oldest live send. That is exact and timer-free —
21+ * nothing can expire into the wrong match, and send #1's late `saved` can never
22+ * confirm send #2.
23+ *
24+ * Trade-off: if the server truly never answers a send, its debt sits there and
25+ * swallows one later legitimate frame, so that question's next save reads "not
26+ * saved" and the student presses save again. Wrong in the safe direction — the
27+ * badge never claims "Saved" for a payload the server did not accept. The debt
28+ * is not permanent: a socket close clears it (`failAll(..., "socket-closed")`),
29+ * so a reconnect always starts from zero.
11 *30 *
12 * A second `wait()` for the same key means the student saved again: the older31 * A second `wait()` for the same key means the student saved again: the older
13 * promise resolves `"superseded"` so its caller stays quiet and the newer save32 * promise resolves `"superseded"` so its caller stays quiet and the newer save
@@ -18,44 +37,102 @@ export type AckResult = "ok" | "superseded";
18 /** Rejection reason when nothing came back at all — callers localize it. */37 /** Rejection reason when nothing came back at all — callers localize it. */
19 export const ACK_TIMEOUT = "ack timeout";38 export const ACK_TIMEOUT = "ack timeout";
20 39
40+type Entry = {
41+ settle: (result: AckResult) => void;
42+ fail: (reason: Error) => void;
43+ timer: ReturnType<typeof setTimeout>;
44+};
45+
46+/**
47+ * Why every pending save is being rejected at once:
48+ * - `socket-closed` — the socket dropped or we replaced it. Nothing is coming,
49+ * ever, so both the queue and the debt are wiped.
50+ * - `error-frame` — the server refused something it could not attribute to one
51+ * question and **kept the socket open** (`exam_ws.rs:496` sends
52+ * `error_frame_for(err, None)` and keeps serving). Each in-flight send is
53+ * still owed its own frame, so rejecting them turns them into debt.
54+ */
55+export type FailAllCause = "socket-closed" | "error-frame";
56+
21 export function createAckWaiter(timeoutMs = 8000) {57 export function createAckWaiter(timeoutMs = 8000) {
22- const pending = new Map<58+ const queues = new Map<string, Entry[]>();
23- string,59+ /** key → frames the server still owes for sends nobody is waiting on anymore. */
24- { settle: (result: AckResult) => void; fail: (reason: Error) => void; timer: ReturnType<typeof setTimeout> }60+ const owed = new Map<string, number>();
25- >();61+
62+ /** This send lost its owner but the server will still answer it: bank the debt. */
63+ const disown = (key: string, entry: Entry) => {
64+ clearTimeout(entry.timer);
65+ const queue = queues.get(key);
66+ const at = queue?.indexOf(entry) ?? -1;
67+ if (queue && at >= 0) queue.splice(at, 1);
68+ if (queue && queue.length === 0) queues.delete(key);
69+ owed.set(key, (owed.get(key) ?? 0) + 1);
70+ };
26 71
27- const take = (key: string) => {72+ /**
28- const entry = pending.get(key);73+ * Pop the send an incoming frame belongs to, or `undefined` when the frame
29- if (entry) {74+ * pays off an older dead send instead (debt is always older than live sends).
30- clearTimeout(entry.timer);75+ */
31- pending.delete(key);76+ const takeOldest = (key: string) => {
77+ const debt = owed.get(key) ?? 0;
78+ if (debt > 0) {
79+ if (debt === 1) owed.delete(key);
80+ else owed.set(key, debt - 1);
81+ return undefined;
32 }82 }
83+ const queue = queues.get(key);
84+ if (!queue || queue.length === 0) return undefined;
85+ const entry = queue.shift()!;
86+ if (queue.length === 0) queues.delete(key);
87+ clearTimeout(entry.timer);
33 return entry;88 return entry;
34 };89 };
35 90
36 return {91 return {
37 wait(key: string): Promise<AckResult> {92 wait(key: string): Promise<AckResult> {
38- take(key)?.settle("superseded");93+ // Disowning the last live entry drops the queue, so re-seat it afterwards.
94+ for (const entry of [...(queues.get(key) ?? [])]) {
95+ entry.settle("superseded");
96+ disown(key, entry);
97+ }
98+ const queue = queues.get(key) ?? [];
99+ queues.set(key, queue);
39 return new Promise<AckResult>((resolve, reject) => {100 return new Promise<AckResult>((resolve, reject) => {
40- const timer = setTimeout(() => {101+ const entry: Entry = {
41- pending.delete(key);102+ settle: resolve,
42- reject(new Error(ACK_TIMEOUT));103+ fail: reject,
43- }, timeoutMs);104+ timer: setTimeout(() => {
44- pending.set(key, { settle: resolve, fail: reject, timer });105+ entry.fail(new Error(ACK_TIMEOUT));
106+ disown(key, entry);
107+ }, timeoutMs),
108+ };
109+ queue.push(entry);
45 });110 });
46 },111 },
47 ack(key: string) {112 ack(key: string) {
48- take(key)?.settle("ok");113+ takeOldest(key)?.settle("ok");
49 },114 },
50 /** Reject one save — the server blamed this question and no other. */115 /** Reject one save — the server blamed this question and no other. */
51 fail(key: string, reason: Error) {116 fail(key: string, reason: Error) {
52- take(key)?.fail(reason);117+ takeOldest(key)?.fail(reason);
53 },118 },
54- failAll(reason: Error) {119+ failAll(reason: Error, cause: FailAllCause) {
55- for (const key of [...pending.keys()]) take(key)?.fail(reason);120+ for (const [key, queue] of [...queues]) {
121+ for (const entry of [...queue]) {
122+ entry.fail(reason);
123+ if (cause === "error-frame") disown(key, entry);
124+ else clearTimeout(entry.timer);
125+ }
126+ if (cause === "socket-closed") queues.delete(key);
127+ }
128+ // A dead socket answers nothing: the reconnect must not inherit old debt.
129+ if (cause === "socket-closed") owed.clear();
56 },130 },
131+ /** Sends still waiting for an outcome — banked debt doesn't count. */
57 get size() {132 get size() {
58- return pending.size;133+ let n = 0;
134+ for (const queue of queues.values()) n += queue.length;
135+ return n;
59 },136 },
60 };137 };
61 }138 }
src/lib/person.tsmodified+8 -1
@@ -1,4 +1,4 @@
1-import type { PersonRef } from "@/api/client";1+import type { Appointment, PersonRef } from "@/api/client";
2 2
3 export type PersonLike = PersonRef | string | null | undefined;3 export type PersonLike = PersonRef | string | null | undefined;
4 4
@@ -13,6 +13,13 @@ export function personLabel(person: PersonLike): string {
13 return person.display_name || person.username || person.id;13 return person.display_name || person.username || person.id;
14 }14 }
15 15
16+// Every appointment listing is scoped to the viewer (`list_for_requester` /
17+// `list_for_teacher`), so one of the two sides is always the viewer themselves.
18+// Show the OTHER person, or the row reads "Ali" to Ali.
19+export function appointmentCounterpart(a: Appointment, viewerId: string | undefined): string {
20+ return personLabel(a.requester.id === viewerId ? a.teacher ?? a.requester : a.requester);
21+}
22+
16 export function personLabelWithId(person: PersonLike): string {23 export function personLabelWithId(person: PersonLike): string {
17 if (!person) return "—";24 if (!person) return "—";
18 if (typeof person === "string") return person;25 if (typeof person === "string") return person;
src/pages/appointments-page.tsxmodified+39 -21
@@ -31,6 +31,7 @@ import { Dialog, DialogBody, DialogContent, DialogHeader, DialogTitle } from "@/
31 import { IconCalendarX, IconCheck, IconEye, IconPlus, IconRefresh, IconTrash, IconX } from "@/components/ui/icons";31 import { IconCalendarX, IconCheck, IconEye, IconPlus, IconRefresh, IconTrash, IconX } from "@/components/ui/icons";
32 import { SidePanel } from "@/components/ui/side-panel";32 import { SidePanel } from "@/components/ui/side-panel";
33 import { TableRowActions } from "@/components/ui/table-row-actions";33 import { TableRowActions } from "@/components/ui/table-row-actions";
34+import { appointmentActions, hasStandingProposal } from "@/lib/appointment-actions";
34 import { appointmentStatusClass, appointmentStatusDotClass, appointmentStatusLabelKey } from "@/lib/appointment-status";35 import { appointmentStatusClass, appointmentStatusDotClass, appointmentStatusLabelKey } from "@/lib/appointment-status";
35 import { cn } from "@/lib/cn";36 import { cn } from "@/lib/cn";
36 import { createFlash } from "@/lib/flash";37 import { createFlash } from "@/lib/flash";
@@ -42,6 +43,7 @@ import { useAuth } from "@/stores/auth-context";
42 import { usePreferences, useT } from "@/stores/preferences-context";43 import { usePreferences, useT } from "@/stores/preferences-context";
43 44
44 const PAGE_SIZE = 10;45 const PAGE_SIZE = 10;
46+const PAGE_LIMIT = 100;
45 const isLive = (status: AppointmentStatus) => status === "pending" || status === "approved";47 const isLive = (status: AppointmentStatus) => status === "pending" || status === "approved";
46 48
47 export default function AppointmentsPage() {49 export default function AppointmentsPage() {
@@ -69,8 +71,21 @@ function AppointmentsContent() {
69 const isStaff = () => hasMinRole(me()?.role, "teacher");71 const isStaff = () => hasMinRole(me()?.role, "teacher");
70 const isManager = () => hasMinRole(me()?.role, "manager");72 const isManager = () => hasMinRole(me()?.role, "manager");
71 73
72- const [slots, { refetch: refetchSlots }] = createResource(async () => (await getSlots({ limit: 100 })).items);74+ // Staff get EVERY slot they ever published (`list_for_teacher`, `starts_at ASC`,
73- const [appts, { refetch: refetchAppts }] = createResource(async () => (await getAppointments({ limit: 100 })).items);75+ // no past filter), so past ~100 lifetime slots page one is nothing but expired
76+ // rows and the upcoming ones are unreachable. Take the last page instead — they
77+ // always sit at the tail. Requesters get `list_upcoming` (future-only, ASC), so
78+ // their first page is the near one and must stay first.
79+ // ponytail: shows the newest PAGE_LIMIT slots; >100 upcoming slots would need
80+ // real paging, and the endpoint takes only limit/offset today.
81+ const fetchSlots = async () => {
82+ const first = await getSlots({ limit: PAGE_LIMIT });
83+ if (!isStaff() || first.total <= PAGE_LIMIT) return first.items;
84+ return (await getSlots({ limit: PAGE_LIMIT, offset: first.total - PAGE_LIMIT })).items;
85+ };
86+ const [slots, { refetch: refetchSlots }] = createResource(fetchSlots);
87+ // Appointments come back newest-first (`ORDER BY id DESC`), so page one is right.
88+ const [appts, { refetch: refetchAppts }] = createResource(async () => (await getAppointments({ limit: PAGE_LIMIT })).items);
74 89
75 const refetchAll = () => Promise.all([refetchSlots(), refetchAppts()]);90 const refetchAll = () => Promise.all([refetchSlots(), refetchAppts()]);
76 const loaded = () => slots.latest !== undefined && appts.latest !== undefined;91 const loaded = () => slots.latest !== undefined && appts.latest !== undefined;
@@ -78,8 +93,10 @@ function AppointmentsContent() {
78 // Poll so statuses stay in sync when the other party acts (approve, book,93 // Poll so statuses stay in sync when the other party acts (approve, book,
79 // cancel…). Visibility-aware: pauses on hidden tabs, refetches on tab-back so94 // cancel…). Visibility-aware: pauses on hidden tabs, refetches on tab-back so
80 // a cross-actor status change isn't stale on a parked tab. Reads use `.latest`,95 // a cross-actor status change isn't stale on a parked tab. Reads use `.latest`,
81- // so a refetch never re-suspends/blanks the tables.96+ // so a refetch never re-suspends/blanks the tables. 30s (the primitive's
82- createLivePoll(refetchAll, 10_000);97+ // default): this page fans out to 2 GETs a tick, and tab-back freshness comes
98+ // from the visibility/focus wake, not from a short period.
99+ createLivePoll(refetchAll);
83 const act = async (fn: () => Promise<unknown>, successKey?: MessageKey) => {100 const act = async (fn: () => Promise<unknown>, successKey?: MessageKey) => {
84 setError("");101 setError("");
85 try {102 try {
@@ -138,7 +155,6 @@ function AppointmentsContent() {
138 {t(appointmentStatusLabelKey(status))}155 {t(appointmentStatusLabelKey(status))}
139 </Badge>156 </Badge>
140 );157 );
141- const hasProposal = (a: Appointment) => a.proposed_starts_at != null;
142 // Cancelled/rejected appointments carry a record (who + optional reason) shown in the details dialog.158 // Cancelled/rejected appointments carry a record (who + optional reason) shown in the details dialog.
143 const hasRecord = (a: Appointment) => a.status === "cancelled" || a.status === "rejected";159 const hasRecord = (a: Appointment) => a.status === "cancelled" || a.status === "rejected";
144 const detailAction = (a: Appointment) =>160 const detailAction = (a: Appointment) =>
@@ -241,7 +257,7 @@ function AppointmentsContent() {
241 cell: (cell) => (257 cell: (cell) => (
242 <div class="flex flex-col gap-0.5">258 <div class="flex flex-col gap-0.5">
243 {timeCell(cell.row.original.starts_at, cell.row.original.ends_at)}259 {timeCell(cell.row.original.starts_at, cell.row.original.ends_at)}
244- <Show when={hasProposal(cell.row.original) && cell.row.original.status === "pending"}>260+ <Show when={hasStandingProposal(cell.row.original)}>
245 <div class="text-info text-xs">{t("appointments.rescheduleProposed")}</div>261 <div class="text-info text-xs">{t("appointments.rescheduleProposed")}</div>
246 </Show>262 </Show>
247 </div>263 </div>
@@ -260,12 +276,10 @@ function AppointmentsContent() {
260 cell: (cell) => {276 cell: (cell) => {
261 const a = cell.row.original;277 const a = cell.row.original;
262 const actions = [] as { label: string; icon: import("solid-js").JSX.Element; destructive?: boolean; onSelect: () => void }[];278 const actions = [] as { label: string; icon: import("solid-js").JSX.Element; destructive?: boolean; onSelect: () => void }[];
263- if (a.status === "pending" && !hasProposal(a)) {279+ for (const action of appointmentActions(a, "staff", now())) {
264- actions.push({ label: t("appointments.approve"), icon: <IconCheck class="h-4 w-4" />, onSelect: () => void act(() => patchApproveAppointment(a.id), "appointments.status.approved") });280+ if (action === "approve") actions.push({ label: t("appointments.approve"), icon: <IconCheck class="h-4 w-4" />, onSelect: () => void act(() => patchApproveAppointment(a.id), "appointments.status.approved") });
265- actions.push({ label: t("appointments.reject"), icon: <IconX class="h-4 w-4" />, destructive: true, onSelect: () => askReject(a.id) });281+ if (action === "reject") actions.push({ label: t("appointments.reject"), icon: <IconX class="h-4 w-4" />, destructive: true, onSelect: () => askReject(a.id) });
266- }282+ if (action === "reschedule") actions.push({ label: t("appointments.reschedule"), icon: <IconRefresh class="h-4 w-4" />, onSelect: () => setReschedAppt(a) });
267- if (isLive(a.status) && !hasProposal(a)) {
268- actions.push({ label: t("appointments.reschedule"), icon: <IconRefresh class="h-4 w-4" />, onSelect: () => setReschedAppt(a) });
269 }283 }
270 // Staff never cancel — a booking is declined via reject (pending) or reschedule; only the requester cancels (their own bookings table).284 // Staff never cancel — a booking is declined via reject (pending) or reschedule; only the requester cancels (their own bookings table).
271 actions.push(...detailAction(a));285 actions.push(...detailAction(a));
@@ -278,7 +292,10 @@ function AppointmentsContent() {
278 const myLiveSlotIds = () => new Set((appts.latest ?? []).filter((a) => a.requester.id === me()?.id && isLive(a.status)).map((a) => a.slot));292 const myLiveSlotIds = () => new Set((appts.latest ?? []).filter((a) => a.requester.id === me()?.id && isLive(a.status)).map((a) => a.slot));
279 const availableSlots = () => {293 const availableSlots = () => {
280 const taken = myLiveSlotIds();294 const taken = myLiveSlotIds();
281- return (slots.latest ?? []).filter((s) => s.ends_at > now() && !taken.has(s.id));295+ // `book` refuses a slot whose window has OPENED ("the slot has already
296+ // started", no skew grace), not one that has ended — an in-progress slot
297+ // listed here would show a Book button that always 409s.
298+ return (slots.latest ?? []).filter((s) => s.starts_at > now() && !taken.has(s.id));
282 };299 };
283 300
284 const availableColumns = createMemo<ColumnDef<AppointmentSlot>[]>(() => [301 const availableColumns = createMemo<ColumnDef<AppointmentSlot>[]>(() => [
@@ -326,11 +343,13 @@ function AppointmentsContent() {
326 meta: { headerClass: "w-44", cellClass: "align-top pr-4" },343 meta: { headerClass: "w-44", cellClass: "align-top pr-4" },
327 cell: (cell) => (344 cell: (cell) => (
328 <div class="flex flex-col gap-0.5">345 <div class="flex flex-col gap-0.5">
329- {timeCell(cell.row.original.starts_at, cell.row.original.ends_at)}346+ {/* The effective window IS the proposal while one stands (backend
330- <Show when={hasProposal(cell.row.original) && cell.row.original.status === "pending"}>347+ `Appointment::window`), so the row's own time already shows the
348+ proposed one — label it instead of printing it twice. */}
349+ <Show when={hasStandingProposal(cell.row.original)}>
331 <div class="text-info text-xs">{t("appointments.proposedTime")}:</div>350 <div class="text-info text-xs">{t("appointments.proposedTime")}:</div>
332- {timeCell(cell.row.original.proposed_starts_at, cell.row.original.proposed_ends_at)}
333 </Show>351 </Show>
352+ {timeCell(cell.row.original.starts_at, cell.row.original.ends_at)}
334 </div>353 </div>
335 ),354 ),
336 },355 },
@@ -347,11 +366,10 @@ function AppointmentsContent() {
347 cell: (cell) => {366 cell: (cell) => {
348 const a = cell.row.original;367 const a = cell.row.original;
349 const actions = [] as { label: string; icon: import("solid-js").JSX.Element; destructive?: boolean; onSelect: () => void }[];368 const actions = [] as { label: string; icon: import("solid-js").JSX.Element; destructive?: boolean; onSelect: () => void }[];
350- if (a.status === "pending" && hasProposal(a)) {369+ for (const action of appointmentActions(a, "requester", now())) {
351- actions.push({ label: t("appointments.acceptReschedule"), icon: <IconCheck class="h-4 w-4" />, onSelect: () => void act(() => patchAcceptReschedule(a.id), "appointments.status.approved") });370+ if (action === "acceptReschedule") actions.push({ label: t("appointments.acceptReschedule"), icon: <IconCheck class="h-4 w-4" />, onSelect: () => void act(() => patchAcceptReschedule(a.id), "appointments.status.approved") });
352- actions.push({ label: t("appointments.declineReschedule"), icon: <IconX class="h-4 w-4" />, destructive: true, onSelect: () => askCancel(() => patchDeclineReschedule(a.id), false) });371+ if (action === "declineReschedule") actions.push({ label: t("appointments.declineReschedule"), icon: <IconX class="h-4 w-4" />, destructive: true, onSelect: () => askCancel(() => patchDeclineReschedule(a.id), false) });
353- } else if (isLive(a.status)) {372+ if (action === "cancel") actions.push({ label: t("appointments.cancel"), icon: <IconX class="h-4 w-4" />, destructive: true, onSelect: () => askCancel((reason) => patchCancelAppointment(a.id, reason ? { reason } : undefined)) });
354- actions.push({ label: t("appointments.cancel"), icon: <IconX class="h-4 w-4" />, destructive: true, onSelect: () => askCancel((reason) => patchCancelAppointment(a.id, reason ? { reason } : undefined)) });
355 }373 }
356 actions.push(...detailAction(a));374 actions.push(...detailAction(a));
357 return <Show when={actions.length > 0} fallback={<span class="text-muted-foreground">—</span>}><TableRowActions label={t("common.actions")} actions={actions} /></Show>;375 return <Show when={actions.length > 0} fallback={<span class="text-muted-foreground">—</span>}><TableRowActions label={t("common.actions")} actions={actions} /></Show>;
src/pages/calendar-page.tsxmodified+7 -2
@@ -11,6 +11,8 @@ import { PageSpinner } from "@/components/ui/page-spinner";
11 import { IconCalendarDays, IconChevronLeft, IconChevronRight } from "@/components/ui/icons";11 import { IconCalendarDays, IconChevronLeft, IconChevronRight } from "@/components/ui/icons";
12 import { cn } from "@/lib/cn";12 import { cn } from "@/lib/cn";
13 import { createNow } from "@/lib/create-now";13 import { createNow } from "@/lib/create-now";
14+import { appointmentCounterpart } from "@/lib/person";
15+import { useAuth } from "@/stores/auth-context";
14 import { usePreferences, useT } from "@/stores/preferences-context";16 import { usePreferences, useT } from "@/stores/preferences-context";
15 17
16 const DAY_NAMES_SHORT = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];18 const DAY_NAMES_SHORT = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
@@ -31,6 +33,7 @@ export default function CalendarPage() {
31 }33 }
32 34
33 function CalendarContent() {35 function CalendarContent() {
36+ const auth = useAuth();
34 const t = useT();37 const t = useT();
35 const { locale } = usePreferences();38 const { locale } = usePreferences();
36 const now = createNow();39 const now = createNow();
@@ -43,6 +46,8 @@ function CalendarContent() {
43 const [exams] = createResource(async () => (await getExams({ limit: 100 })).items, { initialValue: [] });46 const [exams] = createResource(async () => (await getExams({ limit: 100 })).items, { initialValue: [] });
44 const [appointments] = createResource(async () => (await getAppointments({ limit: 100 })).items, { initialValue: [] });47 const [appointments] = createResource(async () => (await getAppointments({ limit: 100 })).items, { initialValue: [] });
45 48
49+ const counterpart = (a: Appointment) => appointmentCounterpart(a, auth.user()?.id);
50+
46 const monthLabel = () => {51 const monthLabel = () => {
47 const names = locale() === "tr" ? MONTH_NAMES_TR : MONTH_NAMES;52 const names = locale() === "tr" ? MONTH_NAMES_TR : MONTH_NAMES;
48 return `${names[viewMonth()]} ${viewYear()}`;53 return `${names[viewMonth()]} ${viewYear()}`;
@@ -197,7 +202,7 @@ function CalendarContent() {
197 {(appt) => (202 {(appt) => (
198 <span class="inline-flex min-w-0 items-center gap-1 rounded bg-violet-100 px-1 py-0.5 text-[9px] font-medium leading-none text-violet-700 dark:border dark:border-violet-800/50 dark:bg-violet-950/60 dark:text-violet-300">203 <span class="inline-flex min-w-0 items-center gap-1 rounded bg-violet-100 px-1 py-0.5 text-[9px] font-medium leading-none text-violet-700 dark:border dark:border-violet-800/50 dark:bg-violet-950/60 dark:text-violet-300">
199 <span class="h-1.5 w-1.5 shrink-0 rounded-full bg-violet-500" />204 <span class="h-1.5 w-1.5 shrink-0 rounded-full bg-violet-500" />
200- <span class="truncate">{appt().requester.display_name ?? appt().requester.username}</span>205+ <span class="truncate">{counterpart(appt())}</span>
201 <Show when={dayItems().appointments.length > 1}>206 <Show when={dayItems().appointments.length > 1}>
202 <span class="shrink-0 opacity-70">+{dayItems().appointments.length - 1}</span>207 <span class="shrink-0 opacity-70">+{dayItems().appointments.length - 1}</span>
203 </Show>208 </Show>
@@ -281,7 +286,7 @@ function CalendarContent() {
281 class="group flex items-start justify-between gap-2 rounded-lg border border-violet-500/40 bg-card p-2.5 shadow-xs transition-all hover:border-violet-500/70 hover:shadow-md dark:border-violet-500/30 dark:hover:border-violet-500/70"286 class="group flex items-start justify-between gap-2 rounded-lg border border-violet-500/40 bg-card p-2.5 shadow-xs transition-all hover:border-violet-500/70 hover:shadow-md dark:border-violet-500/30 dark:hover:border-violet-500/70"
282 >287 >
283 <div class="min-w-0">288 <div class="min-w-0">
284- <p class="truncate text-xs font-semibold group-hover:text-violet-500">{appt.requester.display_name ?? appt.requester.username}</p>289+ <p class="truncate text-xs font-semibold group-hover:text-violet-500">{counterpart(appt)}</p>
285 <p class="mt-0.5 text-[11px] text-muted-foreground">290 <p class="mt-0.5 text-[11px] text-muted-foreground">
286 {appt.starts_at ? new Date(appt.starts_at).toLocaleTimeString(locale() === "tr" ? "tr-TR" : "en-US", { hour: "2-digit", minute: "2-digit" }) : ""}291 {appt.starts_at ? new Date(appt.starts_at).toLocaleTimeString(locale() === "tr" ? "tr-TR" : "en-US", { hour: "2-digit", minute: "2-digit" }) : ""}
287 {appt.ends_at ? ` — ${new Date(appt.ends_at).toLocaleTimeString(locale() === "tr" ? "tr-TR" : "en-US", { hour: "2-digit", minute: "2-digit" })}` : ""}292 {appt.ends_at ? ` — ${new Date(appt.ends_at).toLocaleTimeString(locale() === "tr" ? "tr-TR" : "en-US", { hour: "2-digit", minute: "2-digit" })}` : ""}
src/pages/question-bank-page.test.tsxadded+81 -0
@@ -0,0 +1,81 @@
1+import { fireEvent, render, screen } from "@solidjs/testing-library";
2+import { Show } from "solid-js";
3+import QuestionBankPage from "@/pages/question-bank-page";
4+import { PreferencesProvider } from "@/stores/preferences-context";
5+
6+// 13 templates, page size 12: the last page holds exactly one row.
7+let templates = Array.from({ length: 13 }, (_, index) => ({
8+ id: `bq-${index}`,
9+ text: `Template ${index}`,
10+ kind: "text",
11+ points: 1,
12+ subject: "s-1",
13+ subject_name: "Algebra",
14+ visibility: "private",
15+ owner: "u-1",
16+ owner_name: "Teacher",
17+ used_count: 0,
18+ created_at: 0,
19+}));
20+
21+vi.mock("@/api/bank-questions", () => ({
22+ getBankQuestions: async (params: { limit: number; offset: number }) => ({
23+ items: templates.slice(params.offset, params.offset + params.limit),
24+ total: templates.length,
25+ }),
26+ deleteBankQuestionById: async (id: string) => {
27+ templates = templates.filter((item) => item.id !== id);
28+ },
29+}));
30+vi.mock("@/api/courses", () => ({ getCourses: async () => ({ items: [] }) }));
31+vi.mock("@/stores/auth-context", () => ({
32+ useAuth: () => ({
33+ user: () => ({ id: "u-1", role: "teacher" }),
34+ loading: () => false,
35+ error: () => undefined,
36+ refresh: async () => {},
37+ }),
38+}));
39+// Kobalte's dropdown/dialog chrome is not what this test is about — flatten both
40+// to plain buttons so the delete path can be driven in jsdom.
41+vi.mock("@/components/ui/table-row-actions", () => ({
42+ TableRowActions: (props: { actions: { label: string; onSelect: () => void }[] }) => (
43+ <button type="button" onClick={() => props.actions[1].onSelect()}>
44+ delete-row
45+ </button>
46+ ),
47+}));
48+vi.mock("@/components/ui/confirm-dialog", () => ({
49+ ConfirmDialog: (props: { open: boolean; onConfirm: () => void | Promise<void> }) => (
50+ <Show when={props.open}>
51+ <button type="button" onClick={() => void props.onConfirm()}>
52+ confirm-delete
53+ </button>
54+ </Show>
55+ ),
56+}));
57+
58+const tick = () => new Promise((resolve) => setTimeout(resolve, 0));
59+
60+afterEach(() => vi.restoreAllMocks());
61+
62+test("deleting the last row of the last page clamps back instead of stranding the user", async () => {
63+ render(() => (
64+ <PreferencesProvider>
65+ <QuestionBankPage />
66+ </PreferencesProvider>
67+ ));
68+
69+ fireEvent.click(await screen.findByRole("button", { name: "Next" }));
70+ expect(await screen.findByText("Template 12")).toBeTruthy();
71+ expect(screen.getByText("2 / 2")).toBeTruthy();
72+
73+ fireEvent.click(screen.getByRole("button", { name: "delete-row" }));
74+ fireEvent.click(screen.getByRole("button", { name: "confirm-delete" }));
75+ await tick();
76+ await tick();
77+
78+ // 12 left → one page: the user must be on it, not on the vanished page 2.
79+ expect(screen.queryByText("Template 12")).toBeNull();
80+ expect(await screen.findByText("Template 0")).toBeTruthy();
81+});
src/pages/question-bank-page.tsxmodified+8 -1
@@ -1,4 +1,4 @@
1-import { Show, Suspense, createMemo, createResource, createSignal } from "solid-js";1+import { Show, Suspense, createEffect, createMemo, createResource, createSignal } from "solid-js";
2 import type { ColumnDef } from "@tanstack/solid-table";2 import type { ColumnDef } from "@tanstack/solid-table";
3 import { deleteBankQuestionById, getBankQuestions } from "@/api/bank-questions";3 import { deleteBankQuestionById, getBankQuestions } from "@/api/bank-questions";
4 import { getCourses } from "@/api/courses";4 import { getCourses } from "@/api/courses";
@@ -76,6 +76,13 @@ function QuestionBankContent() {
76 },76 },
77 );77 );
78 const total = () => list.latest?.total ?? 0;78 const total = () => list.latest?.total ?? 0;
79+ // Deleting the last row of the last page shrinks the page count under the
80+ // current page; the table then hides its pagination bar entirely and the user
81+ // is stranded with no control to get back. Same clamp as exam-questions-panel.
82+ const pageCount = () => Math.max(1, Math.ceil(total() / BANK_PAGE_SIZE));
83+ createEffect(() => {
84+ if (page() >= pageCount()) setPage(pageCount() - 1);
85+ });
79 86
80 // Only courses the teacher can author in supply subjects for a new template.87 // Only courses the teacher can author in supply subjects for a new template.
81 const [courses] = createResource(async () => (await getCourses({ limit: 100 })).items);88 const [courses] = createResource(async () => (await getCourses({ limit: 100 })).items);
src/stores/shell-feed-context.test.tsxadded+61 -0
@@ -0,0 +1,61 @@
1+import { render, waitFor } from "@solidjs/testing-library";
2+import { createSignal } from "solid-js";
3+import type { User } from "@/api/client";
4+import { ShellFeedProvider, useShellFeed } from "@/stores/shell-feed-context";
5+
6+// The provider only reads `auth.user()`; drive it from a signal the test owns.
7+const [user, setUser] = createSignal<User | null>(null);
8+vi.mock("@/stores/auth-context", () => ({ useAuth: () => ({ user }) }));
9+
10+const page = <T,>(items: T[]) => ({ items, total: items.length, limit: null, offset: 0 });
11+
12+// Message previews are the account-scoped payload under test; the rest stay empty.
13+vi.mock("@/api/messages", () => ({
14+ getMessages: async () => page([{ id: `${user()?.id}-msg`, read: false }]),
15+}));
16+vi.mock("@/api/events", () => ({ getEvents: async () => page([]) }));
17+vi.mock("@/api/exams", () => ({ getExams: async () => page([]) }));
18+vi.mock("@/api/appointments", () => ({ getAppointments: async () => page([]) }));
19+vi.mock("@/api/homework", () => ({ getHomework: async () => page([]) }));
20+
21+const as = (id: string) => ({ id }) as User;
22+
23+function Probe() {
24+ const feed = useShellFeed();
25+ return <span data-testid="ids">{feed.messages().items.map((m) => m.id).join(",")}</span>;
26+}
27+
28+test("logout clears the feed and login as another user never shows the previous one's rows", async () => {
29+ setUser(as("alice"));
30+ const { getByTestId } = render(() => (
31+ <ShellFeedProvider>
32+ <Probe />
33+ </ShellFeedProvider>
34+ ));
35+ await waitFor(() => expect(getByTestId("ids").textContent).toBe("alice-msg"));
36+
37+ setUser(null);
38+ expect(getByTestId("ids").textContent).toBe(""); // no leftover value after logout
39+
40+ setUser(as("bob"));
41+ expect(getByTestId("ids").textContent).toBe(""); // and none while bob's fetch is in flight
42+ await waitFor(() => expect(getByTestId("ids").textContent).toBe("bob-msg"));
43+});
44+
45+test("no fetch fires while logged out", async () => {
46+ const messages = await import("@/api/messages");
47+ const spy = vi.spyOn(messages, "getMessages");
48+ setUser(null);
49+ render(() => (
50+ <ShellFeedProvider>
51+ <Probe />
52+ </ShellFeedProvider>
53+ ));
54+ await Promise.resolve();
55+ expect(spy).not.toHaveBeenCalled();
56+});
57+
58+afterEach(() => {
59+ setUser(null);
60+ vi.restoreAllMocks();
61+});
src/stores/shell-feed-context.tsxmodified+87 -21
@@ -2,6 +2,7 @@ import {
2 type Accessor,2 type Accessor,
3 type ParentProps,3 type ParentProps,
4 createContext,4 createContext,
5+ createMemo,
5 createResource,6 createResource,
6 createSignal,7 createSignal,
7 useContext,8 useContext,
@@ -27,6 +28,8 @@ import { useAuth } from "@/stores/auth-context";
27 28
28 type ShellFeedContextValue = {29 type ShellFeedContextValue = {
29 messages: Accessor<Page<Message>>;30 messages: Accessor<Page<Message>>;
31+ /** Newest unread inbox rows; `.total` is the *exact* server-side unread count. */
32+ unreadMessages: Accessor<Page<Message>>;
30 events: Accessor<Page<Event>>;33 events: Accessor<Page<Event>>;
31 exams: Accessor<Page<Exam>>;34 exams: Accessor<Page<Exam>>;
32 appointments: Accessor<Page<Appointment>>;35 appointments: Accessor<Page<Appointment>>;
@@ -44,13 +47,20 @@ const ShellFeedContext = createContext<ShellFeedContextValue>();
44 47
45 const emptyPage = <T,>(): Page<T> => ({ items: [], total: 0, limit: null, offset: 0 });48 const emptyPage = <T,>(): Page<T> => ({ items: [], total: 0, limit: null, offset: 0 });
46 49
47-export function ShellFeedProvider(props: ParentProps) {50+type UserFeed = Omit<ShellFeedContextValue, "nowMs">;
48- const auth = useAuth();51+
49- // Only fetch for a logged-in user: source is falsy while logged out, so the52+// Everything user-scoped lives here so it can be created per account id and
53+// disposed with it (see ShellFeedProvider): a logged-out or switched account
54+// gets brand-new resources seeded with empty pages, so no previous user's rows
55+// can survive into the next session. Solid keeps a resource's last value when
56+// its source goes falsy, so gating alone would leak user A's inbox into user
57+// B's shell until the refetch resolved.
58+function createUserFeed(loggedIn: boolean): UserFeed {
59+ // Only fetch for a logged-in user: source is false while logged out, so the
50 // resource keeps its seeded empty value and never hits the network.60 // resource keeps its seeded empty value and never hits the network.
51- const source = () => !!auth.user();61+ const source = () => loggedIn;
52 62
53- const [messagesRes, { refetch: refetchMessages }] = createResource(63+ const [messagesRes, { refetch: refetchInbox }] = createResource(
54 source,64 source,
55 async () => {65 async () => {
56 try {66 try {
@@ -62,11 +72,34 @@ export function ShellFeedProvider(props: ParentProps) {
62 { initialValue: emptyPage<Message>() }72 { initialValue: emptyPage<Message>() }
63 );73 );
64 74
75+ // The badge cannot be derived from the inbox page above: that page is
76+ // ORDER BY id DESC capped at 100, so an old unread message falls off it.
77+ // `read=false` makes `total` the exact server-side unread count, and the 10
78+ // items are the newest unread ones the popover lists.
79+ const [unreadRes, { refetch: refetchUnread }] = createResource(
80+ source,
81+ async () => {
82+ try {
83+ return await getMessages("inbox", { read: false, limit: 10 });
84+ } catch {
85+ return emptyPage<Message>();
86+ }
87+ },
88+ { initialValue: emptyPage<Message>() }
89+ );
90+
91+ // No limit on events/exams: the backend has no schedule filter or ordering
92+ // param (`GET /events`, `GET /exams` take limit/offset only and serve
93+ // ORDER BY id DESC = creation order), so any cap drops an event scheduled
94+ // for tomorrow that was created before the newest N rows. The server loads
95+ // the full list either way and only slices it afterwards.
96+ // ponytail: payload grows with school history — upgrade path is a backend
97+ // `starts_after`/`ends_after` query param, then cap again.
65 const [eventsRes, { refetch: refetchEvents }] = createResource(98 const [eventsRes, { refetch: refetchEvents }] = createResource(
66 source,99 source,
67 async () => {100 async () => {
68 try {101 try {
69- return await getEvents({ limit: 100 });102+ return await getEvents();
70 } catch {103 } catch {
71 return emptyPage<Event>();104 return emptyPage<Event>();
72 }105 }
@@ -78,7 +111,7 @@ export function ShellFeedProvider(props: ParentProps) {
78 source,111 source,
79 async () => {112 async () => {
80 try {113 try {
81- return await getExams({ limit: 100 });114+ return await getExams();
82 } catch {115 } catch {
83 return emptyPage<Exam>();116 return emptyPage<Exam>();
84 }117 }
@@ -110,38 +143,71 @@ export function ShellFeedProvider(props: ParentProps) {
110 { initialValue: emptyPage<Homework>() }143 { initialValue: emptyPage<Homework>() }
111 );144 );
112 145
146+ // One call refreshes both message views — marking a message read changes the
147+ // preview list and the unread count together.
148+ const refetchMessages = () => {
149+ void refetchInbox();
150+ void refetchUnread();
151+ };
152+
113 const refreshAll = () => {153 const refreshAll = () => {
114- void refetchMessages();154+ refetchMessages();
115 void refetchEvents();155 void refetchEvents();
116 void refetchExams();156 void refetchExams();
117 void refetchAppointments();157 void refetchAppointments();
118 void refetchHomework();158 void refetchHomework();
119 };159 };
120 160
121- // Reactive clock so passed items drop off without a remount. Visibility-aware:161+ return {
122- // no ticks/GETs while the tab is hidden, refetch on tab-back so nothing is
123- // stale on a parked tab. This is the single shell poller.
124- const [nowMs, setNowMs] = createSignal(Date.now());
125- createLivePoll(() => {
126- if (!auth.user()) return;
127- setNowMs(Date.now());
128- refreshAll();
129- }, 60_000);
130-
131- const value: ShellFeedContextValue = {
132 messages: () => messagesRes.latest,162 messages: () => messagesRes.latest,
163+ unreadMessages: () => unreadRes.latest,
133 events: () => eventsRes.latest,164 events: () => eventsRes.latest,
134 exams: () => examsRes.latest,165 exams: () => examsRes.latest,
135 appointments: () => appointmentsRes.latest,166 appointments: () => appointmentsRes.latest,
136 homework: () => homeworkRes.latest,167 homework: () => homeworkRes.latest,
137- nowMs,168+ refetchMessages,
138- refetchMessages: () => void refetchMessages(),
139 refetchEvents: () => void refetchEvents(),169 refetchEvents: () => void refetchEvents(),
140 refetchExams: () => void refetchExams(),170 refetchExams: () => void refetchExams(),
141 refetchAppointments: () => void refetchAppointments(),171 refetchAppointments: () => void refetchAppointments(),
142 refetchHomework: () => void refetchHomework(),172 refetchHomework: () => void refetchHomework(),
143 refreshAll,173 refreshAll,
144 };174 };
175+}
176+
177+export function ShellFeedProvider(props: ParentProps) {
178+ const auth = useAuth();
179+ // Keyed on the account id: logging out (null) or switching account disposes
180+ // the whole feed and builds a fresh one. Children never remount, so the
181+ // router tree below is untouched.
182+ const userId = createMemo(() => auth.user()?.id ?? null);
183+ const feed = createMemo(() => createUserFeed(userId() !== null));
184+
185+ // Reactive clock so passed items drop off without a remount. Visibility-aware:
186+ // no ticks/GETs while the tab is hidden, refetch on tab-back so nothing is
187+ // stale on a parked tab. This is the single shell poller — it outlives the
188+ // per-user feeds and always drives the current one.
189+ const [nowMs, setNowMs] = createSignal(Date.now());
190+ createLivePoll(() => {
191+ if (!auth.user()) return;
192+ setNowMs(Date.now());
193+ feed().refreshAll();
194+ }, 60_000);
195+
196+ const value: ShellFeedContextValue = {
197+ messages: () => feed().messages(),
198+ unreadMessages: () => feed().unreadMessages(),
199+ events: () => feed().events(),
200+ exams: () => feed().exams(),
201+ appointments: () => feed().appointments(),
202+ homework: () => feed().homework(),
203+ nowMs,
204+ refetchMessages: () => feed().refetchMessages(),
205+ refetchEvents: () => feed().refetchEvents(),
206+ refetchExams: () => feed().refetchExams(),
207+ refetchAppointments: () => feed().refetchAppointments(),
208+ refetchHomework: () => feed().refetchHomework(),
209+ refreshAll: () => feed().refreshAll(),
210+ };
145 211
146 return <ShellFeedContext.Provider value={value}>{props.children}</ShellFeedContext.Provider>;212 return <ShellFeedContext.Provider value={value}>{props.children}</ShellFeedContext.Provider>;
147 }213 }