diff --git a/README-GUI.md b/README-GUI.md index e0695a5..db394c1 100644 --- a/README-GUI.md +++ b/README-GUI.md @@ -54,7 +54,7 @@ You can also check the backend's health endpoints directly: ```bash curl -i http:///api/health # 200 OK: the process is up -curl -i http:///api/ready # 200 OK: DuckDB *and* Redis are both reachable +curl -i http:///api/ready # 200 OK: DuckDB and Redis are both reachable ``` For local runs, use `http://localhost:4005` in place of ``. @@ -165,13 +165,12 @@ WORKER_QUEUES=heavy_compute bash ./gui/scripts/dev_worker.sh ### Run the frontend locally -Make sure to add `.env.development.local` to `src/client` and add the following line for SSE: +Workspace updates use short requests through the normal API proxy: every 2 seconds +while jobs are queued or processing, and every 10 seconds when idle. Hidden tabs +pause refreshes and refresh immediately when shown again. No SSE-specific URL or +additional service is required. -``` -REACT_APP_SSE_BASE=http://localhost:4000 -``` - -From the React client directory `src/client`, install dependencies and start the development server: +From the React client directory `gui/src/client`, install dependencies and start the development server: ```bash cd ./gui/src/client diff --git a/gui/src/client/src/components/workspace/Workspace.tsx b/gui/src/client/src/components/workspace/Workspace.tsx index a8c9709..4a618e0 100644 --- a/gui/src/client/src/components/workspace/Workspace.tsx +++ b/gui/src/client/src/components/workspace/Workspace.tsx @@ -7,7 +7,8 @@ import { Routes, Route, useNavigate } from "react-router-dom"; import { useNotifications } from "../NotificationProvider"; import { useOverlay } from "../OverlayProvider"; import { Session } from "../../features/session/types"; -import { getSession, refreshSession, getSessionEventsTicket } from "../../features/session/api"; +import { getSession } from "../../features/session/api"; +import { useSessionPolling } from "../../features/session/useSessionPolling"; import { WorkspaceNavbar } from "./WorkspaceNavbar"; import { WorkspaceSideMenu } from "./WorkspaceSideMenu"; import { WorkspaceHeader } from "./WorkspaceHeader"; @@ -53,90 +54,11 @@ export const Workspace: React.FC = () => { else hideOverlay(); }, [loading, showOverlay, hideOverlay]); - // SSE: refresh session when server says something changed. - // - // EventSource can only ever issue a plain GET, so whatever authorizes the - // stream has to live in the URL. To avoid putting the real sessionId there - // (URLs end up in access logs, browser history, Referer headers), the - // stream is authorized by a short-lived, single-use ticket instead. That - // means we can't lean on EventSource's built-in auto-retry — it would just - // keep replaying the same already-spent ticket and 401 forever — so - // reconnection is handled manually here, minting a fresh ticket each time. - React.useEffect(() => { - const sessionId = session?.sessionId; - if (!sessionId) return; - - let alive = true; - let es: EventSource | null = null; - let refreshTimer: number | null = null; - let reconnectTimer: number | null = null; - - const scheduleRefresh = () => { - if (!alive) return; - if (refreshTimer !== null) return; - - refreshTimer = window.setTimeout(() => { - refreshTimer = null; - - refreshSession(sessionId) - .then((fresh) => { - if (!alive) return; - setSession(fresh); - }) - .catch((err) => { - const msg = err instanceof Error ? err.message : String(err); - pushNotification(`Failed to refresh session: ${msg}`, "error"); - }); - }, 250); - }; - - const SSE_BASE = process.env.REACT_APP_SSE_BASE ?? ""; - - const scheduleReconnect = () => { - if (!alive || reconnectTimer !== null) return; - reconnectTimer = window.setTimeout(() => { - reconnectTimer = null; - connect(); - }, 2000); - }; - - const connect = () => { - if (!alive) return; - - getSessionEventsTicket(sessionId) - .then((ticket) => { - if (!alive) return; - - es = new EventSource(`${SSE_BASE}/api/sessionEvents?ticket=${encodeURIComponent(ticket)}`); - - es.addEventListener("hello", scheduleRefresh); - es.addEventListener("item_updated", scheduleRefresh); - es.addEventListener("session_merged", scheduleRefresh); - - es.onerror = () => { - // Don't let the browser's native retry replay this (now spent, - // or about to be stale) ticket — close it out and reconnect - // ourselves with a fresh one. - es?.close(); - es = null; - scheduleReconnect(); - }; - }) - .catch(() => { - // Couldn't even mint a ticket (e.g. backend briefly unreachable) — retry - scheduleReconnect(); - }); - }; - - connect(); - - return () => { - alive = false; - if (refreshTimer !== null) window.clearTimeout(refreshTimer); - if (reconnectTimer !== null) window.clearTimeout(reconnectTimer); - es?.close(); - }; - }, [session?.sessionId, pushNotification]); + const reportRefreshError = React.useCallback( + (message: string) => pushNotification(message, "error"), + [pushNotification], + ); + useSessionPolling(session, setSession, reportRefreshError); // Determine what to show const showContent = !!session && !loading; diff --git a/gui/src/client/src/components/workspace/WorkspaceDiscovery.tsx b/gui/src/client/src/components/workspace/WorkspaceDiscovery.tsx index f672462..53aee01 100644 --- a/gui/src/client/src/components/workspace/WorkspaceDiscovery.tsx +++ b/gui/src/client/src/components/workspace/WorkspaceDiscovery.tsx @@ -451,7 +451,9 @@ export const WorkspaceDiscovery: React.FC = ({ session, queryOriginSmiles, flags: { computeMsa, computeCompare, computeEnrichment }, }); - setSession((prev) => (prev ? { ...prev, items: [...prev.items, item] } : prev)); + setSession((prev) => (prev && !prev.items.some((existing) => existing.id === item.id) + ? { ...prev, items: [...prev.items, item] } + : prev)); setViewingItemId(item.id); } catch (err) { const msg = err instanceof Error ? err.message : String(err); @@ -465,7 +467,7 @@ export const WorkspaceDiscovery: React.FC = ({ session, setDeletingIds((prev) => new Set(prev).add(id)); try { await deleteSessionItem(session.sessionId, id); - // SSE refresh will remove the item from session; nothing else to do here. + setSession((prev) => prev ? { ...prev, items: prev.items.filter((item) => item.id !== id) } : prev); } catch (err) { const msg = err instanceof Error ? err.message : String(err); pushNotification(`Failed to delete query: ${msg}`, "error"); @@ -512,7 +514,7 @@ export const WorkspaceDiscovery: React.FC = ({ session, for (const id of ids) { await deleteSessionItem(session.sessionId, id); } - // SSE will update the session state + setSession((prev) => prev ? { ...prev, items: prev.items.filter((item) => !ids.includes(item.id)) } : prev); } catch (err) { const msg = err instanceof Error ? err.message : String(err); pushNotification(`Failed to delete selected queries: ${msg}`, "error"); diff --git a/gui/src/client/src/components/workspace/WorkspaceUpload.tsx b/gui/src/client/src/components/workspace/WorkspaceUpload.tsx index 57833cf..31c4ca4 100644 --- a/gui/src/client/src/components/workspace/WorkspaceUpload.tsx +++ b/gui/src/client/src/components/workspace/WorkspaceUpload.tsx @@ -162,8 +162,7 @@ export const WorkspaceUpload: React.FC = ({ session, setSe try { await deleteSessionItem(session.sessionId, id); - // DO NOTHING ELSE - // SSE refresh will remove item from session + setSession((prev) => prev ? { ...prev, items: prev.items.filter((item) => item.id !== id) } : prev); } catch (err) { const msg = err instanceof Error ? err.message : String(err); pushNotification(`Failed to delete item: ${msg}`, "error"); @@ -185,7 +184,7 @@ export const WorkspaceUpload: React.FC = ({ session, setSe for (const id of ids) { await deleteSessionItem(session.sessionId, id); } - // SSE will update the session state + setSession((prev) => prev ? { ...prev, items: prev.items.filter((item) => !ids.includes(item.id)) } : prev); } catch (err) { const msg = err instanceof Error ? err.message : String(err); pushNotification(`Failed to delete selected items from session: ${msg}`, "error"); @@ -406,4 +405,4 @@ export const WorkspaceUpload: React.FC = ({ session, setSe ); -}; \ No newline at end of file +}; diff --git a/gui/src/client/src/features/discovery/api.ts b/gui/src/client/src/features/discovery/api.ts index b65b7b5..558174a 100644 --- a/gui/src/client/src/features/discovery/api.ts +++ b/gui/src/client/src/features/discovery/api.ts @@ -1,4 +1,5 @@ import { getJson, postJson } from "../http"; +import { withSessionWrite } from "../session/api"; import { SubmitDiscoveryQueryRespSchema, GetDiscoveryQueryResultRespSchema, @@ -56,12 +57,12 @@ export async function runDiscoveryCompareTanimoto( } // Fire-and-forget: the created item (status "queued") comes back immediately, and its -// status/payload updates flow through the existing SSE + getSession mechanism from +// status/payload updates flow through workspace session polling from // there -- same pattern as jobs/api.ts's submitCompoundJob, just returning the item // since (unlike a compound) it isn't created client-side first. export async function submitDiscoveryQuery(payload: SubmitDiscoveryQueryReq): Promise { const validated = SubmitDiscoveryQueryReqSchema.parse(payload); - const data = await postJson("/api/submitDiscoveryQuery", validated, SubmitDiscoveryQueryRespSchema); + const data = await withSessionWrite(() => postJson("/api/submitDiscoveryQuery", validated, SubmitDiscoveryQueryRespSchema)); return data.item; } diff --git a/gui/src/client/src/features/session/api.ts b/gui/src/client/src/features/session/api.ts index bce248e..303e20c 100644 --- a/gui/src/client/src/features/session/api.ts +++ b/gui/src/client/src/features/session/api.ts @@ -1,42 +1,62 @@ import { postJson } from "../http"; -import { Session, initSession, SessionSchema, CreateSessionRespSchema, GetSessionRespSchema, SseTicketRespSchema } from "./types"; +import { Session, initSession, SessionSchema, CreateSessionRespSchema, GetSessionRespSchema } from "./types"; import { getCookie } from "./utils"; import { z } from "zod"; const OkRespSchema = z.object({ ok: z.boolean() }).partial(); +let pendingSessionWrites = 0; +let sessionWriteVersion = 0; + +// A poll may only apply its snapshot if no write was pending when it started +// and no write has begun since. Track writes independently of React renders, +// including optimistic edits whose save has not reached the server yet. +export function getSessionWriteVersion(): number | null { + return pendingSessionWrites ? null : sessionWriteVersion; +} + +export async function withSessionWrite(operation: () => Promise): Promise { + pendingSessionWrites += 1; + sessionWriteVersion += 1; + try { + return await operation(); + } finally { + pendingSessionWrites -= 1; + } +} + export async function createSession(): Promise { const newSession = initSession(); const data = await postJson("/api/createSession", { session: newSession }, CreateSessionRespSchema); return data.sessionId; }; -export async function getSession(sessionIdArg?: string): Promise { +export async function getSession(sessionIdArg?: string, signal?: AbortSignal): Promise { const sessionId = sessionIdArg ?? getCookie("sessionId"); if (!sessionId) throw new Error("No sessionId provided or found in cookies"); - const data = await postJson("/api/getSession", { sessionId }, GetSessionRespSchema); + const data = await postJson("/api/getSession", { sessionId }, GetSessionRespSchema, signal); // Dont have to sanitize session: postJson already validates with GetSessionRespSchema return data.session; }; -export async function refreshSession(sessionId: string): Promise { - return getSession(sessionId); +export async function refreshSession(sessionId: string, signal?: AbortSignal): Promise { + return getSession(sessionId, signal); }; export async function saveSession(session: Session): Promise { // Runtime validate before sending (especially useful because session is user-mutated in UI) const sanitized = SessionSchema.parse(session); - await postJson("/api/saveSession", { session: sanitized }, z.unknown()); + await withSessionWrite(() => postJson("/api/saveSession", { session: sanitized }, z.unknown())); }; export async function deleteSession(): Promise { const sessionId = getCookie("sessionId"); if (!sessionId) throw new Error("No sessionId cookie found"); - await postJson("/api/deleteSession", { sessionId }, z.unknown()); + await withSessionWrite(() => postJson("/api/deleteSession", { sessionId }, z.unknown())); }; export async function deleteSessionItem(sessionId: string, itemId: string): Promise { - await postJson("/api/deleteSessionItem", { sessionId, itemId }, OkRespSchema); + await withSessionWrite(() => postJson("/api/deleteSessionItem", { sessionId, itemId }, OkRespSchema)); }; export async function renameSessionItem(session: Session, itemId: string, name: string): Promise { @@ -47,12 +67,3 @@ export async function renameSessionItem(session: Session, itemId: string, name: await saveSession(nextSession); return nextSession; }; - -// EventSource can only issue a plain GET (no custom headers/body), so the SSE -// endpoint can't be authorized with a POSTed sessionId like everything else -// here. Instead we mint a short-lived, single-use ticket via a normal POST, -// and only that opaque ticket ever ends up in the SSE URL. -export async function getSessionEventsTicket(sessionId: string): Promise { - const data = await postJson("/api/sessionEventsTicket", { sessionId }, SseTicketRespSchema); - return data.ticket; -}; \ No newline at end of file diff --git a/gui/src/client/src/features/session/types.ts b/gui/src/client/src/features/session/types.ts index 4eadc3f..921c927 100644 --- a/gui/src/client/src/features/session/types.ts +++ b/gui/src/client/src/features/session/types.ts @@ -127,12 +127,8 @@ export type Session = z.output; // Simple response wrappers export const CreateSessionRespSchema = z.object({ sessionId: z.string() }); export const GetSessionRespSchema = z.object({ session: SessionSchema }); -export const SseTicketRespSchema = z.object({ - ticket: z.string(), - expiresInSeconds: z.number().optional(), -}); export function initSession(): Session { const newSession = SessionSchema.parse({}); return newSession; -}; \ No newline at end of file +}; diff --git a/gui/src/client/src/features/session/useSessionPolling.test.tsx b/gui/src/client/src/features/session/useSessionPolling.test.tsx new file mode 100644 index 0000000..7a79ce4 --- /dev/null +++ b/gui/src/client/src/features/session/useSessionPolling.test.tsx @@ -0,0 +1,202 @@ +import React from "react"; +import { act, renderHook } from "@testing-library/react"; +import { deleteSessionItem, refreshSession, saveSession } from "./api"; +import { postJson } from "../http"; +import type { Session } from "./types"; +import { useSessionPolling } from "./useSessionPolling"; + +jest.mock("./api", () => ({ ...jest.requireActual("./api"), refreshSession: jest.fn() })); +jest.mock("../http"); +const refresh = refreshSession as jest.Mock; +const post = postJson as jest.Mock; + +function makeSession(status: "queued" | "processing" | "done" = "queued", sessionId = "s1"): Session { + return { + sessionId, created: 1, + items: [{ id: "i1", name: "Compound", kind: "compound", smiles: "C", matchStereochemistry: false, status, updatedAt: 1 }], + }; +} + +function setup(initial = makeSession()) { + const onError = jest.fn(); + const view = renderHook(() => { + const [session, setSession] = React.useState(initial); + useSessionPolling(session, setSession, onError); + return { session, setSession }; + }); + return { ...view, onError }; +} + +async function advance(ms: number) { + await act(async () => { jest.advanceTimersByTime(ms); }); +} + +async function setHidden(hidden: boolean) { + await act(async () => { + Object.defineProperty(document, "hidden", { configurable: true, value: hidden }); + document.dispatchEvent(new Event("visibilitychange")); + }); +} + +describe("workspace session polling", () => { + beforeEach(() => { + jest.useFakeTimers(); + jest.resetAllMocks(); + Object.defineProperty(document, "hidden", { configurable: true, value: false }); + refresh.mockResolvedValue(makeSession()); + }); + + afterEach(() => { + jest.useRealTimers(); + delete (document as any).hidden; + }); + + it("refreshes job progress, then slows down when all jobs finish", async () => { + refresh.mockResolvedValueOnce(makeSession("processing")).mockResolvedValue(makeSession("done")); + const { result } = setup(); + await advance(2_000); + expect(result.current.session?.items[0].status).toBe("processing"); + await advance(2_000); + expect(result.current.session?.items[0].status).toBe("done"); + await advance(9_999); + expect(refresh).toHaveBeenCalledTimes(2); + await advance(1); + expect(refresh).toHaveBeenCalledTimes(3); + }); + + it("never overlaps requests when a refresh is slow", async () => { + let resolve!: (session: Session) => void; + refresh.mockReturnValueOnce(new Promise((done) => { resolve = done; })); + setup(); + await advance(2_000); + await advance(8_000); + expect(refresh).toHaveBeenCalledTimes(1); + await act(async () => { resolve(makeSession()); }); + await advance(2_000); + expect(refresh).toHaveBeenCalledTimes(2); + }); + + it("pauses hidden tabs and refreshes immediately when visible again", async () => { + setup(makeSession("done")); + await setHidden(true); + await advance(60_000); + expect(refresh).not.toHaveBeenCalled(); + await setHidden(false); + expect(refresh).toHaveBeenCalledTimes(1); + }); + + it("aborts on unmount and does not schedule another request", async () => { + let resolve!: (session: Session) => void; + refresh.mockReturnValueOnce(new Promise((done) => { resolve = done; })); + const { unmount, onError } = setup(); + await advance(2_000); + const signal = refresh.mock.calls[0][1] as AbortSignal; + unmount(); + expect(signal.aborted).toBe(true); + await act(async () => { resolve(makeSession()); }); + await advance(60_000); + expect(refresh).toHaveBeenCalledTimes(1); + expect(onError).not.toHaveBeenCalled(); + }); + + it("does not overwrite local changes made while a refresh is in flight", async () => { + let resolve!: (session: Session) => void; + refresh.mockReturnValueOnce(new Promise((done) => { resolve = done; })); + const { result } = setup(); + await advance(2_000); + const local = makeSession(); + local.items[0].name = "Edited locally"; + act(() => result.current.setSession(local)); + await act(async () => { resolve(makeSession()); }); + expect(result.current.session).toBe(local); + }); + + it("discards late responses after switching sessions", async () => { + let resolve!: (session: Session) => void; + refresh.mockReturnValueOnce(new Promise((done) => { resolve = done; })); + const { result } = setup(); + await advance(2_000); + const signal = refresh.mock.calls[0][1] as AbortSignal; + const next = makeSession("queued", "s2"); + act(() => result.current.setSession(next)); + expect(signal.aborted).toBe(true); + await act(async () => { resolve(makeSession()); }); + expect(result.current.session).toBe(next); + await advance(2_000); + expect(refresh.mock.calls[1][0]).toBe("s2"); + }); + + it("waits for an optimistic save to finish before polling", async () => { + let finishSave!: () => void; + post.mockReturnValueOnce(new Promise((resolve) => { finishSave = resolve; })); + setup(); + const saving = saveSession(makeSession()); + await advance(6_000); + expect(refresh).not.toHaveBeenCalled(); + await act(async () => { finishSave(); await saving; }); + await advance(2_000); + expect(refresh).toHaveBeenCalledTimes(1); + }); + + it("discards a snapshot if a server write completed while it was in flight", async () => { + let resolve!: (session: Session) => void; + refresh.mockReturnValueOnce(new Promise((done) => { resolve = done; })); + const { result } = setup(); + const before = result.current.session; + await advance(2_000); + // No React state change here: the write-version guard must catch this race. + await deleteSessionItem("s1", "i1"); + await act(async () => { resolve(makeSession("done")); }); + expect(result.current.session).toBe(before); + }); + + it("keeps polling paused until all concurrent writes settle, including failures", async () => { + let finishSave!: () => void; + let failDelete!: (error: Error) => void; + post.mockReturnValueOnce(new Promise((resolve) => { finishSave = resolve; })) + .mockReturnValueOnce(new Promise((_resolve, reject) => { failDelete = reject; })); + setup(); + const saving = saveSession(makeSession()); + const deleting = deleteSessionItem("s1", "i1").catch(() => undefined); + await act(async () => { finishSave(); await saving; }); + await advance(2_000); + expect(refresh).not.toHaveBeenCalled(); + await act(async () => { failDelete(new Error("Delete failed")); await deleting; }); + await advance(2_000); + expect(refresh).toHaveBeenCalledTimes(1); + }); + + it("backs off on failures, reports once, and resumes normal polling after recovery", async () => { + refresh.mockRejectedValue(new Error("Server unavailable")); + const { onError } = setup(); + await advance(2_000); + await advance(3_999); + expect(refresh).toHaveBeenCalledTimes(1); + await advance(1); + expect(refresh).toHaveBeenCalledTimes(2); + await advance(8_000); + expect(refresh).toHaveBeenCalledTimes(3); + await advance(16_000); + expect(refresh).toHaveBeenCalledTimes(4); + await advance(29_999); + expect(refresh).toHaveBeenCalledTimes(4); + expect(onError).toHaveBeenCalledTimes(1); + refresh.mockResolvedValue(makeSession()); + await advance(1); + await advance(2_000); + expect(refresh).toHaveBeenCalledTimes(6); + }); + + it("times out a stalled request and retries with backoff", async () => { + refresh.mockImplementationOnce((_id, signal: AbortSignal) => new Promise((_resolve, reject) => { + signal.addEventListener("abort", () => reject(new Error("Aborted"))); + })); + const { onError } = setup(); + await advance(2_000); + await advance(10_000); + expect((refresh.mock.calls[0][1] as AbortSignal).aborted).toBe(true); + expect(onError).toHaveBeenCalledWith(expect.stringContaining("Request timed out")); + await advance(4_000); + expect(refresh).toHaveBeenCalledTimes(2); + }); +}); diff --git a/gui/src/client/src/features/session/useSessionPolling.ts b/gui/src/client/src/features/session/useSessionPolling.ts new file mode 100644 index 0000000..fb2d727 --- /dev/null +++ b/gui/src/client/src/features/session/useSessionPolling.ts @@ -0,0 +1,95 @@ +import { useEffect, useRef } from "react"; +import type { Dispatch, SetStateAction } from "react"; +import { getSessionWriteVersion, refreshSession } from "./api"; +import type { Session } from "./types"; + +// Ordinary requests release the Gunicorn thread between refreshes. A persistent +// SSE request occupied one of only eight API threads for every open workspace. +const BUSY_INTERVAL_MS = 2_000; +const IDLE_INTERVAL_MS = 10_000; +const MAX_BACKOFF_MS = 30_000; +const REQUEST_TIMEOUT_MS = 10_000; + +export function useSessionPolling( + session: Session | null, + setSession: Dispatch>, + onError: (message: string) => void, +) { + const latestSession = useRef(session); + latestSession.current = session; + const sessionId = session?.sessionId; + const busy = session?.items.some((item) => item.status === "queued" || item.status === "processing") ?? false; + + useEffect(() => { + if (!sessionId) return; + + let alive = true; + let timer: number | undefined; + let controller: AbortController | null = null; + let failures = 0; + const interval = busy ? BUSY_INTERVAL_MS : IDLE_INTERVAL_MS; + + const schedule = (delay: number) => { + window.clearTimeout(timer); + if (alive && !document.hidden) timer = window.setTimeout(poll, delay); + }; + + const poll = async () => { + // Schedule only after the previous request settles: a slow server must + // never build up overlapping polls from one workspace. + if (!alive || document.hidden || controller) return; + window.clearTimeout(timer); + const writeVersion = getSessionWriteVersion(); + if (writeVersion === null) { + schedule(interval); + return; + } + const snapshot = latestSession.current; + const request = new AbortController(); + controller = request; + let timedOut = false; + const timeout = window.setTimeout(() => { + timedOut = true; + request.abort(); + }, REQUEST_TIMEOUT_MS); + + try { + const fresh = await refreshSession(sessionId, request.signal); + if (!alive || request.signal.aborted) return; + failures = 0; + // Do not overwrite a local edit or submission made during this request. + setSession((current) => + alive && current === snapshot && getSessionWriteVersion() === writeVersion ? fresh : current + ); + } catch (err) { + if (!alive || document.hidden || (request.signal.aborted && !timedOut)) return; + failures += 1; + if (failures === 1) { + const message = request.signal.aborted + ? "Request timed out" + : err instanceof Error ? err.message : String(err); + onError(`Failed to refresh session: ${message}. Retrying automatically.`); + } + } finally { + window.clearTimeout(timeout); + controller = null; + schedule(failures ? Math.min(interval * 2 ** Math.min(failures, 5), MAX_BACKOFF_MS) : interval); + } + }; + + const onVisibilityChange = () => { + window.clearTimeout(timer); + if (document.hidden) controller?.abort(); + else void poll(); + }; + + schedule(interval); + document.addEventListener("visibilitychange", onVisibilityChange); + return () => { + alive = false; + window.clearTimeout(timer); + controller?.abort(); + document.removeEventListener("visibilitychange", onVisibilityChange); + }; + }, [sessionId, busy, setSession, onError]); +} diff --git a/gui/src/server/routes/events.py b/gui/src/server/routes/events.py index d7c08ee..e5abc5f 100644 --- a/gui/src/server/routes/events.py +++ b/gui/src/server/routes/events.py @@ -1,12 +1,8 @@ import json -import time -from typing import Iterator -import redis -from flask import Blueprint, Response, jsonify, request, stream_with_context +from flask import Blueprint, Response, jsonify, request from routes.session_store import ( - REDIS_URL, SSE_TICKET_TTL_SECONDS, consume_sse_ticket, create_sse_ticket, @@ -17,15 +13,6 @@ blp_sse_ticket = Blueprint("sse_ticket", __name__) -def _get_redis() -> "redis.Redis": - """ - Get a Redis client. - - :return: redis.Redis - """ - return redis.Redis.from_url(REDIS_URL, decode_responses=True) - - @blp_sse_ticket.post("/api/sessionEventsTicket") def session_events_ticket() -> tuple[Response, int]: """ @@ -53,7 +40,7 @@ def session_events_ticket() -> tuple[Response, int]: @blp_events.get("/api/sessionEvents") def session_events() -> Response: """ - SSE endpoint. Client connects once per session and receives notifications. + Compatibility endpoint for browser tabs loaded before session polling. Authorized via a one-time ticket (see /api/sessionEventsTicket above) rather than a raw sessionId, since EventSource can only send a GET and @@ -72,51 +59,9 @@ def session_events() -> Response: if load_session_meta(session_id) is None: return Response("session not found\n", status=404, mimetype="text/plain") - r = _get_redis() - pubsub = r.pubsub(ignore_subscribe_messages=True) - channel = f"session_events:{session_id}" - pubsub.subscribe(channel) - - def sse(event: str, data: dict) -> str: - return f"event: {event}\ndata: {json.dumps(data)}\n\n" - - @stream_with_context - def gen() -> Iterator[str]: - # Initial hello - yield sse("hello", {"sessionId": session_id}) - - # Keepalive cadence (seconds) - keepalive_every = 15 - last_keepalive = time.time() - - try: - while True: - msg = pubsub.get_message(timeout=1.0) - if msg and msg.get("type") == "message": - try: - payload = json.loads(msg["data"]) - except Exception: - payload = {"type": "unknown", "raw": msg.get("data")} - - # Event name comes from payload["type"] - evt_type = payload.get("type", "message") - yield sse(evt_type, payload) - - # Keepalive so proxies don't kill the stream - now = time.time() - if now - last_keepalive >= keepalive_every: - yield sse("keepalive", {"timestamp": int(now * 1000)}) - last_keepalive = now - - finally: - try: - pubsub.close() - except Exception: - pass - headers = { "Cache-Control": "no-cache", - "X-Accel-Buffering": "no", # helps if behind nginx - "Connection": "keep-alive", + "X-Accel-Buffering": "no", } - return Response(gen(), mimetype="text/event-stream", headers=headers) + body = f"event: hello\ndata: {json.dumps({'sessionId': session_id})}\n\n" + return Response(body, mimetype="text/event-stream", headers=headers)