Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 6 additions & 7 deletions README-GUI.md
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ You can also check the backend's health endpoints directly:

```bash
curl -i http://<server-ip>/api/health # 200 OK: the process is up
curl -i http://<server-ip>/api/ready # 200 OK: DuckDB *and* Redis are both reachable
curl -i http://<server-ip>/api/ready # 200 OK: DuckDB and Redis are both reachable
```

For local runs, use `http://localhost:4005` in place of `<server-ip>`.
Expand Down Expand Up @@ -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
Expand Down
92 changes: 7 additions & 85 deletions gui/src/client/src/components/workspace/Workspace.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -451,7 +451,9 @@ export const WorkspaceDiscovery: React.FC<WorkspaceDiscoveryProps> = ({ 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);
Expand All @@ -465,7 +467,7 @@ export const WorkspaceDiscovery: React.FC<WorkspaceDiscoveryProps> = ({ 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");
Expand Down Expand Up @@ -512,7 +514,7 @@ export const WorkspaceDiscovery: React.FC<WorkspaceDiscoveryProps> = ({ 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");
Expand Down
7 changes: 3 additions & 4 deletions gui/src/client/src/components/workspace/WorkspaceUpload.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -162,8 +162,7 @@ export const WorkspaceUpload: React.FC<WorkspaceUploadProps> = ({ 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");
Expand All @@ -185,7 +184,7 @@ export const WorkspaceUpload: React.FC<WorkspaceUploadProps> = ({ 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");
Expand Down Expand Up @@ -406,4 +405,4 @@ export const WorkspaceUpload: React.FC<WorkspaceUploadProps> = ({ session, setSe

</Box>
);
};
};
5 changes: 3 additions & 2 deletions gui/src/client/src/features/discovery/api.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { getJson, postJson } from "../http";
import { withSessionWrite } from "../session/api";
import {
SubmitDiscoveryQueryRespSchema,
GetDiscoveryQueryResultRespSchema,
Expand Down Expand Up @@ -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<DiscoveryQueryItem> {
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;
}

Expand Down
45 changes: 28 additions & 17 deletions gui/src/client/src/features/session/api.ts
Original file line number Diff line number Diff line change
@@ -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<T>(operation: () => Promise<T>): Promise<T> {
pendingSessionWrites += 1;
sessionWriteVersion += 1;
try {
return await operation();
} finally {
pendingSessionWrites -= 1;
}
}

export async function createSession(): Promise<string> {
const newSession = initSession();
const data = await postJson("/api/createSession", { session: newSession }, CreateSessionRespSchema);
return data.sessionId;
};

export async function getSession(sessionIdArg?: string): Promise<Session> {
export async function getSession(sessionIdArg?: string, signal?: AbortSignal): Promise<Session> {
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<Session> {
return getSession(sessionId);
export async function refreshSession(sessionId: string, signal?: AbortSignal): Promise<Session> {
return getSession(sessionId, signal);
};

export async function saveSession(session: Session): Promise<void> {
// 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<void> {
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<void> {
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<Session> {
Expand All @@ -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<string> {
const data = await postJson("/api/sessionEventsTicket", { sessionId }, SseTicketRespSchema);
return data.ticket;
};
6 changes: 1 addition & 5 deletions gui/src/client/src/features/session/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -127,12 +127,8 @@ export type Session = z.output<typeof SessionSchema>;
// 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;
};
};
Loading
Loading