From 06c90390c8632fc3a79677a7b32220b1673148e5 Mon Sep 17 00:00:00 2001 From: Alexander Date: Sun, 6 Sep 2026 23:08:57 -0500 Subject: [PATCH 01/11] fix(client): coalesce concurrent access-token refresh calls (BUG #1) Two requests expiring at the same time each independently triggered a 401-retry refresh. The refresh token is single-use and rotates server-side, so the second concurrent call replayed an already-rotated token, tripped reuse-detection, and revoked the whole session chain -- logging out a legitimately-authenticated user. refreshAccessToken() now coalesces overlapping callers into a single in-flight request, and is exported so other call sites can share it. Co-Authored-By: Claude Sonnet 5 --- client/src/lib/api-client.test.ts | 33 +++++++++++++++++++++++++ client/src/lib/api-client.ts | 41 ++++++++++++++++++++++--------- 2 files changed, 63 insertions(+), 11 deletions(-) diff --git a/client/src/lib/api-client.test.ts b/client/src/lib/api-client.test.ts index 1247ba7..37ca53e 100644 --- a/client/src/lib/api-client.test.ts +++ b/client/src/lib/api-client.test.ts @@ -68,6 +68,39 @@ describe("apiRequest", () => { expect(fetch).toHaveBeenCalledTimes(3); }); + it("coalesces concurrent 401s into a single refresh call (BUG #1 regression)", async () => { + // Two requests expire at once (e.g. two parallel queries after the access token TTL elapses). + // Each hits a 401 independently; without de-duplication, both would call /api/auth/refresh + // with the same pre-rotation cookie, and the backend's single-use rotation would treat the + // second call as a replay -- revoking the whole session chain and logging the user out. + useAuthStore.getState().setSession({ accessToken: "stale-token", user: { id: "u1", email: "a@b.com", displayName: null } }); + vi.mocked(fetch).mockImplementation((input) => { + const url = typeof input === "string" ? input : (input as Request).url; + if (url.includes("/api/auth/refresh")) { + return Promise.resolve(jsonResponse(200, { success: true, data: { accessToken: "fresh-token" } })); + } + if (url.includes("/projects/a") || url.includes("/projects/b")) { + const alreadyRefreshed = useAuthStore.getState().accessToken === "fresh-token"; + return Promise.resolve( + alreadyRefreshed + ? jsonResponse(200, { success: true, data: { ok: true } }) + : jsonResponse(401, { success: false, error: { message: "Unauthorized", code: "UNAUTHORIZED", correlationId: "c" } }), + ); + } + throw new Error(`Unexpected fetch to ${url}`); + }); + + const [resultA, resultB] = await Promise.all([apiRequest("/projects/a"), apiRequest("/projects/b")]); + + expect(resultA).toEqual({ ok: true }); + expect(resultB).toEqual({ ok: true }); + const refreshCalls = vi.mocked(fetch).mock.calls.filter(([input]) => { + const url = typeof input === "string" ? input : (input as Request).url; + return url.includes("/api/auth/refresh"); + }); + expect(refreshCalls).toHaveLength(1); + }); + it("clears the session when the refresh itself fails", async () => { useAuthStore.getState().setSession({ accessToken: "stale-token", user: { id: "u1", email: "a@b.com", displayName: null } }); vi.mocked(fetch) diff --git a/client/src/lib/api-client.ts b/client/src/lib/api-client.ts index d468871..0b74063 100644 --- a/client/src/lib/api-client.ts +++ b/client/src/lib/api-client.ts @@ -37,21 +37,40 @@ async function rawRequest(path: string, options: RequestOptions): Promise<{ s return { status: response.status, envelope }; } +// Coalesces concurrent refresh attempts into a single in-flight request. The refresh token is +// single-use and rotates server-side (SEC-004); if multiple 401s fired one refresh call each, +// every call after the first would replay an already-rotated token, tripping reuse-detection +// and revoking the whole session chain -- including the just-issued one -- and spuriously +// logging out a legitimately-authenticated user (BUG #1). +let inFlightRefresh: Promise | null = null; + /** * Refreshes the access token once via the BFF route (never the backend directly -- only the * route handler can read the httpOnly refresh cookie, SEC-035). Returns the new token, or null - * if the refresh itself failed (session is gone; caller must sign the user out). + * if the refresh itself failed (session is gone; caller must sign the user out). Safe to call + * concurrently -- overlapping callers share the same underlying request. Exported so every call + * site (the 401-retry path here and `useBootstrapSession`'s hard-reload bootstrap) shares this + * one de-duped implementation rather than each racing its own raw `fetch` (BUG #2, same root + * cause as BUG #1 -- React Strict Mode's double-effect-invoke on mount was enough to trigger it). */ -async function refreshAccessToken(): Promise { - try { - const response = await fetch("/api/auth/refresh", { method: "POST", credentials: "include" }); - const envelope = (await response.json()) as ApiEnvelope<{ accessToken: string }>; - if (!envelope.success) return null; - useAuthStore.getState().setAccessToken(envelope.data.accessToken); - return envelope.data.accessToken; - } catch { - return null; - } +export async function refreshAccessToken(): Promise { + if (inFlightRefresh) return inFlightRefresh; + + inFlightRefresh = (async () => { + try { + const response = await fetch("/api/auth/refresh", { method: "POST", credentials: "include" }); + const envelope = (await response.json()) as ApiEnvelope<{ accessToken: string }>; + if (!envelope.success) return null; + useAuthStore.getState().setAccessToken(envelope.data.accessToken); + return envelope.data.accessToken; + } catch { + return null; + } finally { + inFlightRefresh = null; + } + })(); + + return inFlightRefresh; } /** From 5c36b9683c02192f982c75047f605d69ae7c4c0c Mon Sep 17 00:00:00 2001 From: Alexander Date: Sun, 6 Sep 2026 23:09:14 -0500 Subject: [PATCH 02/11] fix(client): reuse the shared refresh call in session bootstrap (BUG #2) useBootstrapSession's hard-reload bootstrap ran its own raw fetch to /api/auth/refresh instead of going through api-client's refreshAccessToken(). Under React Strict Mode's double-effect-invoke on mount (and in general, any overlapping caller), this raced a second, independent refresh against the same single-use, rotating refresh cookie -- the same root cause as BUG #1 -- and could revoke a just-issued session. Bootstrap now calls the shared, de-duped refreshAccessToken() (BUG #1) instead of duplicating the refresh logic. Co-Authored-By: Claude Sonnet 5 --- .../auth/use-bootstrap-session.test.ts | 19 +++++-------------- .../features/auth/use-bootstrap-session.ts | 11 ++++------- 2 files changed, 9 insertions(+), 21 deletions(-) diff --git a/client/src/features/auth/use-bootstrap-session.test.ts b/client/src/features/auth/use-bootstrap-session.test.ts index c2855b2..3fce587 100644 --- a/client/src/features/auth/use-bootstrap-session.test.ts +++ b/client/src/features/auth/use-bootstrap-session.test.ts @@ -11,20 +11,12 @@ vi.mock("next/navigation", () => ({ vi.mock("@/lib/api-client", () => ({ apiRequest: vi.fn(), + refreshAccessToken: vi.fn(), })); -function jsonResponse(status: number, body: unknown): Response { - return new Response(JSON.stringify(body), { status, headers: { "Content-Type": "application/json" } }); -} - describe("useBootstrapSession", () => { - beforeEach(() => { - vi.stubGlobal("fetch", vi.fn()); - }); - afterEach(() => { cleanup(); - vi.unstubAllGlobals(); replace.mockClear(); useAuthStore.getState().clear(); }); @@ -38,8 +30,8 @@ describe("useBootstrapSession", () => { }); it("silently refreshes the session on a hard reload and becomes ready", async () => { - const { apiRequest } = await import("@/lib/api-client"); - vi.mocked(fetch).mockResolvedValueOnce(jsonResponse(200, { success: true, data: { accessToken: "fresh" } })); + const { apiRequest, refreshAccessToken } = await import("@/lib/api-client"); + vi.mocked(refreshAccessToken).mockResolvedValueOnce("fresh"); vi.mocked(apiRequest).mockResolvedValueOnce({ id: "u1", email: "a@b.com", displayName: null }); const { result } = renderHook(() => useBootstrapSession()); @@ -50,9 +42,8 @@ describe("useBootstrapSession", () => { }); it("clears the store and redirects to /login when the refresh cookie is missing or invalid", async () => { - vi.mocked(fetch).mockResolvedValueOnce( - jsonResponse(401, { success: false, error: { message: "No session", code: "UNAUTHORIZED", correlationId: "c" } }), - ); + const { refreshAccessToken } = await import("@/lib/api-client"); + vi.mocked(refreshAccessToken).mockResolvedValueOnce(null); renderHook(() => useBootstrapSession()); diff --git a/client/src/features/auth/use-bootstrap-session.ts b/client/src/features/auth/use-bootstrap-session.ts index 7202519..1358bee 100644 --- a/client/src/features/auth/use-bootstrap-session.ts +++ b/client/src/features/auth/use-bootstrap-session.ts @@ -2,8 +2,7 @@ import { useEffect, useState } from "react"; import { useRouter } from "next/navigation"; -import { apiRequest } from "@/lib/api-client"; -import type { ApiEnvelope } from "@/lib/api-envelope"; +import { apiRequest, refreshAccessToken } from "@/lib/api-client"; import { useAuthStore, useIsAuthenticated, type AuthUser } from "./auth.store"; /** @@ -27,17 +26,15 @@ export function useBootstrapSession(): { isReady: boolean } { async function bootstrap(): Promise { try { - const response = await fetch("/api/auth/refresh", { method: "POST", credentials: "include" }); - const envelope = (await response.json()) as ApiEnvelope<{ accessToken: string }>; - if (!envelope.success) { + const accessToken = await refreshAccessToken(); + if (!accessToken) { throw new Error("Session expired"); } - useAuthStore.getState().setAccessToken(envelope.data.accessToken); const user = await apiRequest("/auth/me"); if (cancelled) return; - useAuthStore.getState().setSession({ accessToken: envelope.data.accessToken, user }); + useAuthStore.getState().setSession({ accessToken, user }); setBootstrapped(true); } catch { if (cancelled) return; From af13898f0e73cd86284fae493d011fb629261a0d Mon Sep 17 00:00:00 2001 From: Alexander Date: Sun, 6 Sep 2026 23:09:31 -0500 Subject: [PATCH 03/11] fix(client): reveal graph data immediately for interactive consumers (BUG #3) setGraphData() always started with an empty visibility set, relying on something else to progressively reveal nodes/edges over time. That's correct for the Hero's scripted timeline, but interactive consumers (the Workspace graph, the Report builder's node picker) have no timeline script -- useGraphTimeline flips status to 'interactive' synchronously on mount before setGraphData ever runs, so real data loaded into the store stayed permanently hidden behind an empty visibility set nothing would ever repopulate. setGraphData() now reveals everything up front whenever status isn't 'playing', leaving the scripted Hero timeline's progressive reveal untouched. Co-Authored-By: Claude Sonnet 5 --- .../graph-engine/store/graphStore.test.ts | 56 +++++++++++++++++++ .../modules/graph-engine/store/graphStore.ts | 18 +++++- 2 files changed, 73 insertions(+), 1 deletion(-) create mode 100644 client/src/modules/graph-engine/store/graphStore.test.ts diff --git a/client/src/modules/graph-engine/store/graphStore.test.ts b/client/src/modules/graph-engine/store/graphStore.test.ts new file mode 100644 index 0000000..39d0c16 --- /dev/null +++ b/client/src/modules/graph-engine/store/graphStore.test.ts @@ -0,0 +1,56 @@ +import { describe, expect, it } from "vitest"; +import { createGraphStore } from "./graphStore"; +import type { NodeModel } from "../types/node.types"; +import type { EdgeModel } from "../types/edge.types"; + +const nodeA: NodeModel = { id: "a", type: "asset", data: { label: "a" } }; +const nodeB: NodeModel = { id: "b", type: "finding", data: { label: "b" } }; +const edgeAB: EdgeModel = { id: "e1", source: "a", target: "b", type: "discovery" }; + +describe("graphStore setGraphData", () => { + it("reveals nodes/edges immediately when not mid-timeline (BUG #3 regression)", () => { + // Interactive consumers (Workspace graph, Report builder's node picker) never play a + // timeline script -- `useGraphTimeline` flips status to 'interactive' before this ever runs. + // Without the fix, setGraphData always reset visibility to empty and nothing repopulated it, + // so real graph data silently never rendered. + const store = createGraphStore(); + store.getState().setStatus("interactive"); + + store.getState().setGraphData([nodeA, nodeB], [edgeAB], null); + + const state = store.getState(); + expect(state.visibleNodeIds).toEqual(new Set(["a", "b"])); + expect(state.visibleEdgeIds).toEqual(new Set(["e1"])); + }); + + it("reveals nodes/edges immediately in the default idle status", () => { + const store = createGraphStore(); + + store.getState().setGraphData([nodeA], [], null); + + expect(store.getState().visibleNodeIds).toEqual(new Set(["a"])); + }); + + it("keeps visibility empty while a scripted timeline is playing", () => { + // Preserves the Hero's progressive-reveal animation: nodes only become visible as the + // timeline script explicitly calls revealNode/revealEdge. + const store = createGraphStore(); + store.getState().setStatus("playing"); + + store.getState().setGraphData([nodeA, nodeB], [edgeAB], null); + + const state = store.getState(); + expect(state.visibleNodeIds).toEqual(new Set()); + expect(state.visibleEdgeIds).toEqual(new Set()); + }); + + it("re-reveals newly loaded data (e.g. a refetch) once already interactive", () => { + const store = createGraphStore(); + store.getState().setStatus("interactive"); + store.getState().setGraphData([nodeA], [], null); + + store.getState().setGraphData([nodeA, nodeB], [edgeAB], null); + + expect(store.getState().visibleNodeIds).toEqual(new Set(["a", "b"])); + }); +}); diff --git a/client/src/modules/graph-engine/store/graphStore.ts b/client/src/modules/graph-engine/store/graphStore.ts index fda616f..dee03d9 100644 --- a/client/src/modules/graph-engine/store/graphStore.ts +++ b/client/src/modules/graph-engine/store/graphStore.ts @@ -80,8 +80,24 @@ export function createGraphStore() { rootNodeId: null, visibleNodeIds: new Set(), visibleEdgeIds: new Set(), + // Interactive consumers (no timeline script, e.g. the Workspace graph and the Report + // builder's node picker) reveal everything up front -- `useGraphTimeline` flips `status` to + // 'interactive' synchronously on mount before this ever runs (child effects fire before the + // parent `GraphProvider` effect that calls this), so gating on `status` here means real graph + // data actually renders instead of staying hidden behind an empty visibility set that nothing + // else would ever repopulate (BUG #3). A scripted Hero timeline is still mid-'playing' at this + // point and keeps its empty-then-progressively-revealed behavior untouched. setGraphData: (nodes, edges, rootNodeId) => - set({ nodes, edges, rootNodeId: rootNodeId ?? null, visibleNodeIds: new Set(), visibleEdgeIds: new Set() }), + set((state) => { + const revealImmediately = state.status !== 'playing' + return { + nodes, + edges, + rootNodeId: rootNodeId ?? null, + visibleNodeIds: revealImmediately ? new Set(nodes.map((n) => n.id)) : new Set(), + visibleEdgeIds: revealImmediately ? new Set(edges.map((e) => e.id)) : new Set(), + } + }), revealNode: (nodeId) => set((state) => ({ visibleNodeIds: new Set(state.visibleNodeIds).add(nodeId) })), revealEdge: (edgeId) => set((state) => ({ visibleEdgeIds: new Set(state.visibleEdgeIds).add(edgeId) })), revealAll: () => From ceaea2540d7bcda8a39257f24bc92f2ca58ecf6e Mon Sep 17 00:00:00 2001 From: Alexander Date: Sun, 6 Sep 2026 23:09:47 -0500 Subject: [PATCH 04/11] fix(server): unwrap Drizzle-wrapped driver errors in isUniqueViolation (BUG #4) Creating a project whose slug collided with an existing project owned by a different user crashed with a raw, unhandled 500 instead of the intended 409 Conflict. isUniqueViolation() only checked error.code on the top-level thrown error, but Drizzle ORM wraps the real pg driver error (carrying the actual 23505 code) inside .cause on its DrizzleQueryError -- the check never matched, so the unique-violation escaped instead of being converted to ConflictError. isUniqueViolation() now walks up to 5 levels of .cause looking for the code, bounded to guard against any accidental cycle. Co-Authored-By: Claude Sonnet 5 --- server/src/core/database/pg-error.ts | 36 +++++++++++++++--- server/tests/unit/core/pg-error.test.ts | 50 +++++++++++++++++++++++++ 2 files changed, 80 insertions(+), 6 deletions(-) create mode 100644 server/tests/unit/core/pg-error.test.ts diff --git a/server/src/core/database/pg-error.ts b/server/src/core/database/pg-error.ts index 10681d2..6c7839a 100644 --- a/server/src/core/database/pg-error.ts +++ b/server/src/core/database/pg-error.ts @@ -1,15 +1,39 @@ /** Postgres error code for a unique-constraint violation (23505). */ const UNIQUE_VIOLATION_CODE = "23505"; +/** Bounds how far up an `error.cause` chain we'll look before giving up (BUG #4). */ +const MAX_CAUSE_DEPTH = 5; + +function getPgErrorCode(error: unknown): unknown { + return typeof error === "object" && error !== null && "code" in error + ? (error as { code?: unknown }).code + : undefined; +} + +function getCause(error: unknown): unknown { + return typeof error === "object" && error !== null && "cause" in error + ? (error as { cause?: unknown }).cause + : undefined; +} + /** * Narrows an unknown thrown value to a node-postgres error carrying a `code`, without pulling * in the `pg` package types here (repositories only depend on Drizzle's `Database` type). + * + * Drizzle wraps the real driver error in a `DrizzleQueryError` whose own `code` is undefined -- + * the actual pg error (and its `23505` code) lives on `.cause` instead. Checking only the + * top-level `code` silently missed every real unique-violation raised through a Drizzle query, + * letting it escape as an unhandled 500 instead of the intended `ConflictError` (BUG #4). Walk + * the `cause` chain so this works whether the code sits on the error itself or is nested behind + * one (or more) wrapping layers. */ export function isUniqueViolation(error: unknown): boolean { - return ( - typeof error === "object" && - error !== null && - "code" in error && - (error as { code?: unknown }).code === UNIQUE_VIOLATION_CODE - ); + let current = error; + for (let depth = 0; depth < MAX_CAUSE_DEPTH && current; depth += 1) { + if (getPgErrorCode(current) === UNIQUE_VIOLATION_CODE) { + return true; + } + current = getCause(current); + } + return false; } diff --git a/server/tests/unit/core/pg-error.test.ts b/server/tests/unit/core/pg-error.test.ts new file mode 100644 index 0000000..3ed91d0 --- /dev/null +++ b/server/tests/unit/core/pg-error.test.ts @@ -0,0 +1,50 @@ +import { describe, expect, it } from "vitest"; +import { isUniqueViolation } from "../../../src/core/database/pg-error"; + +describe("isUniqueViolation", () => { + it("recognizes a bare pg error with a top-level code (BUG #4 baseline case)", () => { + expect(isUniqueViolation({ code: "23505" })).toBe(true); + }); + + it("recognizes a Drizzle-wrapped error, where the real pg error is nested in `cause` (BUG #4 regression)", () => { + // Mirrors drizzle-orm's DrizzleQueryError: the top-level error has no `code` of its own, + // the real node-postgres error (with the actual 23505) is one level down in `.cause`. + const pgError = { code: "23505", message: "duplicate key value violates unique constraint" }; + const drizzleQueryError = new Error("Failed query: select * from create_project_with_owner(...)", { + cause: pgError, + }); + + expect(isUniqueViolation(drizzleQueryError)).toBe(true); + }); + + it("walks multiple levels of nested causes", () => { + const pgError = { code: "23505" }; + const wrapped = new Error("outer", { cause: new Error("inner", { cause: pgError }) }); + + expect(isUniqueViolation(wrapped)).toBe(true); + }); + + it("returns false for an unrelated error code", () => { + expect(isUniqueViolation({ code: "23503" })).toBe(false); + }); + + it("returns false for a wrapped error whose cause has an unrelated code", () => { + const wrapped = new Error("outer", { cause: { code: "23503" } }); + expect(isUniqueViolation(wrapped)).toBe(false); + }); + + it("returns false for non-object and nullish values", () => { + expect(isUniqueViolation(null)).toBe(false); + expect(isUniqueViolation(undefined)).toBe(false); + expect(isUniqueViolation("some string")).toBe(false); + expect(isUniqueViolation(new Error("plain error, no cause"))).toBe(false); + }); + + it("does not loop forever on a cause cycle", () => { + const a: { cause?: unknown } = {}; + const b: { cause?: unknown } = { cause: a }; + a.cause = b; + + expect(isUniqueViolation(a)).toBe(false); + }); +}); From 0a0c7a0aac6abe4739a7597c6d2a5913329177d2 Mon Sep 17 00:00:00 2001 From: Alexander Date: Sun, 6 Sep 2026 23:10:06 -0500 Subject: [PATCH 05/11] fix(server,client): show member email/display name instead of raw userId (BUG #5) Project Settings -> Members listed each member only by their bare userId UUID (e.g. e566b5cd-5f5c-498f-ac2e-c55bc4a45666), even though members are invited by email -- an owner had no way to tell which UUID corresponded to which teammate. ProjectMemberDto/ProjectMemberRow never carried email or displayName: listByProject was a plain SELECT on project_members with no join to users, and the mapper only forwarded userId. listByProject now joins project_members to users (ProjectMemberWithUserRow). addOrAssignMember attaches the already-fetched targetUser's email/ displayName to the DTO it returns, with no extra query needed. Updated the shared ProjectMemberDto, the frontend Zod schema, and MembersPanel's row rendering (display name primary, email secondary, falls back to email-only when no display name is set). Co-Authored-By: Claude Sonnet 5 --- .../settings/api/use-project-members.test.tsx | 2 + .../settings/api/use-project-members.ts | 2 + .../settings/components/MembersPanel.test.tsx | 22 +++++++++++ .../settings/components/MembersPanel.tsx | 7 +++- .../workspace/api/use-current-role.test.tsx | 4 ++ .../projects/mappers/project.mapper.ts | 10 +++-- .../src/modules/projects/projects.service.ts | 4 +- .../project-members.repository.ts | 37 ++++++++++++++++--- .../project-members.repository.test.ts | 3 +- 9 files changed, 79 insertions(+), 12 deletions(-) diff --git a/client/src/features/settings/api/use-project-members.test.tsx b/client/src/features/settings/api/use-project-members.test.tsx index 2084e53..b63a0ca 100644 --- a/client/src/features/settings/api/use-project-members.test.tsx +++ b/client/src/features/settings/api/use-project-members.test.tsx @@ -11,6 +11,8 @@ const MEMBER = { id: "22222222-2222-2222-2222-222222222222", projectId: PROJECT_ID, userId: "33333333-3333-3333-3333-333333333333", + email: "member@example.com", + displayName: null, role: "admin", createdAt: new Date().toISOString(), }; diff --git a/client/src/features/settings/api/use-project-members.ts b/client/src/features/settings/api/use-project-members.ts index a0db416..52acc75 100644 --- a/client/src/features/settings/api/use-project-members.ts +++ b/client/src/features/settings/api/use-project-members.ts @@ -9,6 +9,8 @@ export const projectMemberSchema = z.object({ id: z.string().uuid(), projectId: z.string().uuid(), userId: z.string().uuid(), + email: z.string().email(), + displayName: z.string().nullable(), role: z.enum(["owner", "admin", "member", "viewer"]), createdAt: z.coerce.date(), }); diff --git a/client/src/features/settings/components/MembersPanel.test.tsx b/client/src/features/settings/components/MembersPanel.test.tsx index 4aec646..31321d2 100644 --- a/client/src/features/settings/components/MembersPanel.test.tsx +++ b/client/src/features/settings/components/MembersPanel.test.tsx @@ -40,6 +40,8 @@ function makeMember(overrides: Partial = {}): ProjectMember { id: "22222222-2222-2222-2222-222222222222", projectId: PROJECT_ID, userId: "33333333-3333-3333-3333-333333333333", + email: "member@example.com", + displayName: null, role: "admin", createdAt: new Date(), ...overrides, @@ -80,6 +82,26 @@ describe("MembersPanel", () => { expect(screen.getByText("admin")).toBeInTheDocument(); }); + it("shows a member's identifying email/display name instead of the raw userId (BUG #5)", () => { + vi.mocked(useProjectMembers).mockReturnValue( + queryResult({ data: [makeMember({ email: "ana@example.com", displayName: "Ana" })] }), + ); + vi.mocked(useAddOrAssignMember).mockReturnValue(mutationResult({})); + render(); + expect(screen.getByText("Ana")).toBeInTheDocument(); + expect(screen.getByText("ana@example.com")).toBeInTheDocument(); + expect(screen.queryByText("33333333-3333-3333-3333-333333333333")).not.toBeInTheDocument(); + }); + + it("falls back to the email when a member has no display name (BUG #5)", () => { + vi.mocked(useProjectMembers).mockReturnValue( + queryResult({ data: [makeMember({ email: "no-name@example.com", displayName: null })] }), + ); + vi.mocked(useAddOrAssignMember).mockReturnValue(mutationResult({})); + render(); + expect(screen.getByText("no-name@example.com")).toBeInTheDocument(); + }); + it("opens the add/reassign dialog and submits an email + role", async () => { const user = userEvent.setup(); const mutate = vi.fn(); diff --git a/client/src/features/settings/components/MembersPanel.tsx b/client/src/features/settings/components/MembersPanel.tsx index e1b0008..68871fc 100644 --- a/client/src/features/settings/components/MembersPanel.tsx +++ b/client/src/features/settings/components/MembersPanel.tsx @@ -62,7 +62,12 @@ export function MembersPanel({ projectId }: Props) { function MemberRow({ member }: { member: ProjectMember }) { return (
  • - {member.userId} +
    + {member.displayName ?? member.email} + {member.displayName ? ( + {member.email} + ) : null} +
    {member.role}
  • ); diff --git a/client/src/features/workspace/api/use-current-role.test.tsx b/client/src/features/workspace/api/use-current-role.test.tsx index fdfea07..2f0a9ed 100644 --- a/client/src/features/workspace/api/use-current-role.test.tsx +++ b/client/src/features/workspace/api/use-current-role.test.tsx @@ -31,6 +31,8 @@ describe("useCurrentRole", () => { id: "33333333-3333-3333-3333-333333333333", projectId: PROJECT_ID, userId: USER_ID, + email: "a@b.com", + displayName: null, role: "admin", createdAt: new Date(), }, @@ -38,6 +40,8 @@ describe("useCurrentRole", () => { id: "44444444-4444-4444-4444-444444444444", projectId: PROJECT_ID, userId: "55555555-5555-5555-5555-555555555555", + email: "other@example.com", + displayName: null, role: "viewer", createdAt: new Date(), }, diff --git a/server/src/modules/projects/mappers/project.mapper.ts b/server/src/modules/projects/mappers/project.mapper.ts index 67fb97f..f4a03be 100644 --- a/server/src/modules/projects/mappers/project.mapper.ts +++ b/server/src/modules/projects/mappers/project.mapper.ts @@ -1,5 +1,5 @@ import type { ProjectRow } from "../repositories/projects.repository"; -import type { ProjectMemberRow } from "../repositories/project-members.repository"; +import type { ProjectMemberWithUserRow } from "../repositories/project-members.repository"; export interface ProjectDto { id: string; @@ -14,7 +14,9 @@ export interface ProjectMemberDto { id: string; projectId: string; userId: string; - role: ProjectMemberRow["role"]; + email: string; + displayName: string | null; + role: ProjectMemberWithUserRow["role"]; createdAt: Date; } @@ -30,11 +32,13 @@ export function toProjectDto(row: ProjectRow): ProjectDto { }; } -export function toProjectMemberDto(row: ProjectMemberRow): ProjectMemberDto { +export function toProjectMemberDto(row: ProjectMemberWithUserRow): ProjectMemberDto { return { id: row.id, projectId: row.projectId, userId: row.userId, + email: row.email, + displayName: row.displayName, role: row.role, createdAt: row.createdAt, }; diff --git a/server/src/modules/projects/projects.service.ts b/server/src/modules/projects/projects.service.ts index bbe4c4f..605edb4 100644 --- a/server/src/modules/projects/projects.service.ts +++ b/server/src/modules/projects/projects.service.ts @@ -103,7 +103,9 @@ export class ProjectsService { if (!result) { throw new NotFoundError("Project membership not found"); } - return toProjectMemberDto(result); + // addMember/updateRole only touch project_members, so they can't return the joined user + // fields listMembers does -- attach them from targetUser, already fetched above (BUG #5). + return toProjectMemberDto({ ...result, email: targetUser.email, displayName: targetUser.displayName }); } async removeMember(actingUserId: string, projectId: string, targetUserId: string): Promise { diff --git a/server/src/modules/projects/repositories/project-members.repository.ts b/server/src/modules/projects/repositories/project-members.repository.ts index a896979..88c418e 100644 --- a/server/src/modules/projects/repositories/project-members.repository.ts +++ b/server/src/modules/projects/repositories/project-members.repository.ts @@ -1,7 +1,7 @@ import { and, eq, sql } from "drizzle-orm"; import type { Database } from "../../../core/database/client"; import { isUniqueViolation } from "../../../core/database/pg-error"; -import { projectMembers } from "../../../core/database/schema"; +import { projectMembers, users } from "../../../core/database/schema"; import { ConflictError } from "../../../core/http/domain-error"; import { extractTotal, @@ -21,6 +21,17 @@ export interface ProjectMemberRow { createdAt: Date; } +/** + * A member row joined with the identifying fields off `users` -- everything the UI needs to show + * *who* a member actually is instead of a bare `userId` (BUG #5). `addMember`/`updateRole` don't + * join (their `.returning()` only covers `project_members`); callers that already have the target + * `UserRow` in hand (e.g. `addOrAssignMember`, which looked it up by email) attach it themselves. + */ +export interface ProjectMemberWithUserRow extends ProjectMemberRow { + email: string; + displayName: string | null; +} + export interface ProjectMemberCreateInput { projectId: string; userId: string; @@ -34,7 +45,7 @@ export interface ProjectMemberCreateInput { export interface ProjectMembersRepository { addMember(input: ProjectMemberCreateInput): Promise; findByProjectAndUser(projectId: string, userId: string): Promise; - listByProject(projectId: string, pagination?: PaginationParams): Promise>; + listByProject(projectId: string, pagination?: PaginationParams): Promise>; updateRole(projectId: string, userId: string, role: ProjectRole): Promise; removeMember(projectId: string, userId: string): Promise; } @@ -66,16 +77,30 @@ export class DrizzleProjectMembersRepository implements ProjectMembersRepository return (row as ProjectMemberRow) ?? null; } - async listByProject(projectId: string, pagination?: PaginationParams): Promise> { + async listByProject(projectId: string, pagination?: PaginationParams): Promise> { const { page, pageSize, offset } = normalizePagination(pagination); const where = eq(projectMembers.projectId, projectId); - const [items, countRows] = await Promise.all([ - this.db.select().from(projectMembers).where(where).limit(pageSize).offset(offset), + const [rows, countRows] = await Promise.all([ + this.db + .select({ + id: projectMembers.id, + projectId: projectMembers.projectId, + userId: projectMembers.userId, + role: projectMembers.role, + createdAt: projectMembers.createdAt, + email: users.email, + displayName: users.displayName, + }) + .from(projectMembers) + .innerJoin(users, eq(projectMembers.userId, users.id)) + .where(where) + .limit(pageSize) + .offset(offset), this.db.select({ count: sql`count(*)::int` }).from(projectMembers).where(where), ]); - return { items: items as ProjectMemberRow[], page, pageSize, total: extractTotal(countRows) }; + return { items: rows as ProjectMemberWithUserRow[], page, pageSize, total: extractTotal(countRows) }; } async updateRole(projectId: string, userId: string, role: ProjectRole): Promise { diff --git a/server/tests/integration/project-members.repository.test.ts b/server/tests/integration/project-members.repository.test.ts index 05418e8..43a3ce9 100644 --- a/server/tests/integration/project-members.repository.test.ts +++ b/server/tests/integration/project-members.repository.test.ts @@ -40,7 +40,7 @@ describe("ProjectMembersRepository", () => { expect(await repo.findByProjectAndUser(project.id, user.id)).toMatchObject({ id: created.id }); }); - it("lists members for a project, paginated", async () => { + it("lists members for a project, paginated, joined with their identifying user fields (BUG #5)", async () => { const { project, user } = await createFixtures(); await repo.addMember({ projectId: project.id, userId: user.id, role: "owner" }); @@ -48,6 +48,7 @@ describe("ProjectMembersRepository", () => { expect(page.items).toHaveLength(1); expect(page.total).toBe(1); + expect(page.items[0]).toMatchObject({ userId: user.id, email: "owner@example.com", displayName: null }); }); it("updates a member's role", async () => { From ffee6df7d7278d3b27850200b98bf30f60881dee Mon Sep 17 00:00:00 2001 From: Alexander Date: Mon, 7 Sep 2026 23:13:07 -0500 Subject: [PATCH 06/11] fix(client): fall back to a direct project fetch when active project isn't paginated in, and clear query cache on logout (BUG #6) - ProjectSwitcher only searched the first page of useProjects() for the active project, silently showing "Select a project" for any project past that page even though it's a real, accessible project. It now falls back to fetching the project directly by id. - useLogout() cleared the auth store but left the TanStack Query cache intact, so a different account logging in next in the same tab could briefly render the previous account's cached projects/graph data. Co-Authored-By: Claude Sonnet 5 --- client/src/features/auth/auth.api.test.tsx | 39 +++++++++++++++++++ client/src/features/auth/auth.api.ts | 7 +++- .../components/ProjectSwitcher.test.tsx | 15 +++++++ .../workspace/components/ProjectSwitcher.tsx | 8 +++- 4 files changed, 67 insertions(+), 2 deletions(-) create mode 100644 client/src/features/auth/auth.api.test.tsx diff --git a/client/src/features/auth/auth.api.test.tsx b/client/src/features/auth/auth.api.test.tsx new file mode 100644 index 0000000..e0f703d --- /dev/null +++ b/client/src/features/auth/auth.api.test.tsx @@ -0,0 +1,39 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; +import { renderHook, waitFor } from "@testing-library/react"; +import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; +import { useLogout } from "./auth.api"; +import { useAuthStore } from "./auth.store"; + +function renderWithClient(client: QueryClient) { + return renderHook(() => useLogout(), { + wrapper: ({ children }) => {children}, + }); +} + +describe("useLogout", () => { + afterEach(() => { + vi.restoreAllMocks(); + useAuthStore.getState().clear(); + }); + + it("clears the auth store and the entire query cache on success (BUG #6)", async () => { + vi.stubGlobal( + "fetch", + vi.fn().mockResolvedValue({ ok: true, json: async () => ({ success: true, data: undefined }) }), + ); + useAuthStore.getState().setSession({ accessToken: "token", user: { id: "1", email: "a@b.com", displayName: null } }); + + const queryClient = new QueryClient(); + // Simulates data left over from the session being logged out of -- must not survive into + // whichever account logs in next in this same tab. + queryClient.setQueryData(["projects"], [{ id: "p1", name: "Stale Project" }]); + + const { result } = renderWithClient(queryClient); + result.current.mutate(); + + await waitFor(() => expect(result.current.isSuccess).toBe(true)); + + expect(useAuthStore.getState().accessToken).toBeNull(); + expect(queryClient.getQueryData(["projects"])).toBeUndefined(); + }); +}); diff --git a/client/src/features/auth/auth.api.ts b/client/src/features/auth/auth.api.ts index 45f08f6..6ee0547 100644 --- a/client/src/features/auth/auth.api.ts +++ b/client/src/features/auth/auth.api.ts @@ -1,6 +1,6 @@ "use client"; -import { useMutation } from "@tanstack/react-query"; +import { useMutation, useQueryClient } from "@tanstack/react-query"; import { ApiError, type ApiEnvelope } from "@/lib/api-envelope"; import { useAuthStore, type AuthUser } from "./auth.store"; @@ -55,6 +55,7 @@ export function useRegister() { } export function useLogout() { + const queryClient = useQueryClient(); return useMutation({ mutationFn: async () => { const accessToken = useAuthStore.getState().accessToken; @@ -66,6 +67,10 @@ export function useLogout() { }, onSuccess: () => { useAuthStore.getState().clear(); + // Drops every cached query (projects, graph data, members, ...) so a different account + // logging in next in this same tab never renders the previous account's cached server + // state (BUG #6 -- discovered while investigating a stale "Select a project" header). + queryClient.clear(); }, }); } diff --git a/client/src/features/workspace/components/ProjectSwitcher.test.tsx b/client/src/features/workspace/components/ProjectSwitcher.test.tsx index 5c5eb8d..1f4438f 100644 --- a/client/src/features/workspace/components/ProjectSwitcher.test.tsx +++ b/client/src/features/workspace/components/ProjectSwitcher.test.tsx @@ -1,9 +1,11 @@ import { afterEach, describe, expect, it, vi } from "vitest"; import { cleanup, render, screen } from "@testing-library/react"; import { useProjects } from "../api/use-projects"; +import { useProject } from "../api/use-project"; import { ProjectSwitcher } from "./ProjectSwitcher"; vi.mock("../api/use-projects", () => ({ useProjects: vi.fn() })); +vi.mock("../api/use-project", () => ({ useProject: vi.fn() })); describe("ProjectSwitcher", () => { afterEach(() => { @@ -13,6 +15,7 @@ describe("ProjectSwitcher", () => { it("shows a placeholder when no project is active", () => { vi.mocked(useProjects).mockReturnValue({ data: undefined } as never); + vi.mocked(useProject).mockReturnValue({ data: undefined } as never); render(); @@ -25,6 +28,7 @@ describe("ProjectSwitcher", () => { { id: "22222222-2222-2222-2222-222222222222", name: "Globex", slug: "globex" }, ]; vi.mocked(useProjects).mockReturnValue({ data: projects } as never); + vi.mocked(useProject).mockReturnValue({ data: undefined } as never); render(); @@ -34,4 +38,15 @@ describe("ProjectSwitcher", () => { "/app/projects/22222222-2222-2222-2222-222222222222", ); }); + + it("falls back to fetching the active project directly when it's not on the first page of the list (BUG #6)", () => { + vi.mocked(useProjects).mockReturnValue({ data: [] } as never); + vi.mocked(useProject).mockReturnValue({ + data: { id: "33333333-3333-3333-3333-333333333333", name: "Old Project", slug: "old-project" }, + } as never); + + render(); + + expect(screen.getByRole("button", { name: "Old Project" })).toBeInTheDocument(); + }); }); diff --git a/client/src/features/workspace/components/ProjectSwitcher.tsx b/client/src/features/workspace/components/ProjectSwitcher.tsx index f78e779..f8153b8 100644 --- a/client/src/features/workspace/components/ProjectSwitcher.tsx +++ b/client/src/features/workspace/components/ProjectSwitcher.tsx @@ -2,6 +2,7 @@ import Link from "next/link"; import { useProjects } from "../api/use-projects"; +import { useProject } from "../api/use-project"; type Props = { activeProjectId: string | null; @@ -11,6 +12,11 @@ type Props = { export function ProjectSwitcher({ activeProjectId }: Props) { const { data: projects } = useProjects(); const activeProject = projects?.find((project) => project.id === activeProjectId); + // `projects` is only the first page of the user's projects (BUG #6): the active project can be + // a real, accessible project that simply isn't on that page. Fall back to fetching it directly + // by id instead of silently falling back to the placeholder. + const fallbackQuery = useProject(!activeProject && activeProjectId ? activeProjectId : ""); + const activeProjectName = activeProject?.name ?? fallbackQuery.data?.name; return (
    @@ -18,7 +24,7 @@ export function ProjectSwitcher({ activeProjectId }: Props) { type="button" className="flex h-8 items-center gap-2 rounded-full border border-[var(--color-border)] bg-[var(--color-surface)] px-3.5 text-sm text-[var(--color-foreground-muted)] transition-colors hover:text-[var(--color-foreground)]" > - {activeProject?.name ?? "Select a project"} + {activeProjectName ?? "Select a project"} {projects && projects.length > 0 ? (
    From 148c9ca4f46826f6dcb492e83ac8b3f807d01323 Mon Sep 17 00:00:00 2001 From: Alexander Date: Mon, 7 Sep 2026 23:13:17 -0500 Subject: [PATCH 07/11] fix(client): make the Graph Engine wrapper actually fill its flex-grown container (BUG #7) WorkspaceGraphView's graph pane sizes purely from flex-grow (no explicit CSS height anywhere up the chain to WorkspaceShell's min-h-screen), so the Graph Engine's own h-full wrapper resolved to 0 and the graph silently failed to render for any project that actually had data. Wrapping it in a relative parent + absolute inset-0 sizes it against the parent's laid-out box instead, which is reliable against a flex-grown ancestor. Co-Authored-By: Claude Sonnet 5 --- .../features/workspace/graph/WorkspaceGraphView.tsx | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/client/src/features/workspace/graph/WorkspaceGraphView.tsx b/client/src/features/workspace/graph/WorkspaceGraphView.tsx index 8b39fdb..333a099 100644 --- a/client/src/features/workspace/graph/WorkspaceGraphView.tsx +++ b/client/src/features/workspace/graph/WorkspaceGraphView.tsx @@ -57,7 +57,17 @@ export function WorkspaceGraphView({ projectId }: Props) {

    {project.data?.name}

    - + {/* + * `h-full` on GraphEngine's own wrapper can resolve to 0 here: this ancestor's height + * comes purely from flex-grow (no explicit CSS height anywhere in the chain up to + * WorkspaceShell's `min-h-screen`), and percentage heights are unreliable against that. + * `absolute inset-0` sizes against the actual laid-out box of this `relative` parent + * instead, which is the same trick used to make anything fill a flex-grown container + * reliably (BUG #7 -- the graph silently failed to render for any project with data). + */} +
    + +
    ); From a543aeaddbf17615934920297cca4e60cd38a660 Mon Sep 17 00:00:00 2001 From: Alexander Date: Mon, 7 Sep 2026 23:13:27 -0500 Subject: [PATCH 08/11] fix(client): roll back an optimistic scope edit when the server rejects it (BUG #8) The server independently re-validates every scope entry's format (FE-006) and can reject an entry the lenient client-side check let through. ScopeEditor applied add/remove edits optimistically but never rolled them back on mutation failure, so a rejected entry stayed visible in the In scope / Excluded lists as if it were saved -- misleading for a value that gates what the Orchestrator will let a tool run touch. Co-Authored-By: Claude Sonnet 5 --- .../settings/components/ScopeEditor.test.tsx | 26 +++++++++++++++++-- .../settings/components/ScopeEditor.tsx | 26 ++++++++++++++----- 2 files changed, 44 insertions(+), 8 deletions(-) diff --git a/client/src/features/settings/components/ScopeEditor.test.tsx b/client/src/features/settings/components/ScopeEditor.test.tsx index 2c966ab..f6272de 100644 --- a/client/src/features/settings/components/ScopeEditor.test.tsx +++ b/client/src/features/settings/components/ScopeEditor.test.tsx @@ -86,7 +86,7 @@ describe("ScopeEditor", () => { await user.type(includeInput, "sub.example.com"); await user.click(screen.getAllByRole("button", { name: "Add" })[0]); - expect(mutate).toHaveBeenCalledWith({ + expect(mutate.mock.calls[0][0]).toEqual({ scope: { includes: ["example.com", "sub.example.com"], excludes: [] }, }); }); @@ -101,6 +101,28 @@ describe("ScopeEditor", () => { await user.click(screen.getByRole("button", { name: "Remove example.com" })); - expect(mutate).toHaveBeenCalledWith({ scope: { includes: [], excludes: [] } }); + expect(mutate.mock.calls[0][0]).toEqual({ scope: { includes: [], excludes: [] } }); + }); + + it("rolls back an optimistic add when the server rejects it (BUG #8)", async () => { + // The server independently re-validates each scope entry's format (FE-006) and can reject + // an entry the lenient client-side check let through. Before this fix, the rejected entry + // stayed visible in the "In scope" list as if it were saved -- misleading for a value that + // gates what the Orchestrator will let a tool run touch. + const user = userEvent.setup(); + const mutate: UpdateProjectMutation["mutate"] = vi.fn((_input, options) => { + options?.onError?.(new Error("Invalid request payload"), _input, undefined, {} as never); + }); + vi.mocked(useProject).mockReturnValue(queryResult({ data: makeProject() })); + vi.mocked(useUpdateProject).mockReturnValue(mutationResult({ mutate })); + + render(); + + const [includeInput] = screen.getAllByLabelText("Add entry"); + await user.type(includeInput, ""); + await user.click(screen.getAllByRole("button", { name: "Add" })[0]); + + expect(screen.queryByText("")).not.toBeInTheDocument(); + expect(screen.getByText("example.com")).toBeInTheDocument(); }); }); diff --git a/client/src/features/settings/components/ScopeEditor.tsx b/client/src/features/settings/components/ScopeEditor.tsx index 66a6dec..ade9681 100644 --- a/client/src/features/settings/components/ScopeEditor.tsx +++ b/client/src/features/settings/components/ScopeEditor.tsx @@ -66,8 +66,20 @@ export function ScopeEditor({ projectId }: Props) { return

    Failed to load the project scope.

    ; } - function save(nextIncludes: string[], nextExcludes: string[]): void { - updateProject.mutate({ scope: { includes: nextIncludes, excludes: nextExcludes } }); + // On rejection (e.g. the server's stricter hostname/CIDR format check -- see the + // scopeEntrySchema comment above), roll the optimistic edit back to the pre-edit lists. + // Without this, a rejected entry stayed visible as if it were in effect (BUG #8): misleading + // for a value that gates what the Orchestrator will let a tool run touch. + function save(nextIncludes: string[], nextExcludes: string[], rollback: { includes: string[]; excludes: string[] }): void { + updateProject.mutate( + { scope: { includes: nextIncludes, excludes: nextExcludes } }, + { + onError: () => { + setIncludes(rollback.includes); + setExcludes(rollback.excludes); + }, + }, + ); } function addEntry(list: ScopeList, value: string): { ok: boolean; error?: string } { @@ -75,27 +87,29 @@ export function ScopeEditor({ projectId }: Props) { if (!parsed.success) { return { ok: false, error: parsed.error.issues[0]?.message }; } + const rollback = { includes, excludes }; if (list === "includes") { const next = [...includes, parsed.data]; setIncludes(next); - save(next, excludes); + save(next, excludes, rollback); } else { const next = [...excludes, parsed.data]; setExcludes(next); - save(includes, next); + save(includes, next, rollback); } return { ok: true }; } function removeEntry(list: ScopeList, entry: string): void { + const rollback = { includes, excludes }; if (list === "includes") { const next = includes.filter((item) => item !== entry); setIncludes(next); - save(next, excludes); + save(next, excludes, rollback); } else { const next = excludes.filter((item) => item !== entry); setExcludes(next); - save(includes, next); + save(includes, next, rollback); } } From 13c64edb505f46c41d85ff73a4c49f4bc265b93a Mon Sep 17 00:00:00 2001 From: Alexander Date: Mon, 7 Sep 2026 23:13:38 -0500 Subject: [PATCH 09/11] fix(client): stop the session bootstrap from cancelling itself before the user loads (BUG #9) useBootstrapSession's effect depended on the reactive isAuthenticated value. refreshAccessToken() flips accessToken (and therefore isAuthenticated) as soon as it resolves, *before* /auth/me returns. Because the effect depended on isAuthenticated, that flip re-ran it, tearing down (cancelled = true) the in-flight bootstrap right as it awaited /auth/me -- so setSession() never ran and the auth store's user stayed null forever after every hard reload, even though accessToken was set and all API calls kept working. Every user-derived UI silently broke as a result: useCurrentRole() always resolved to no role, hiding e.g. RunDetail's owner/admin-gated 'View raw output' button from a confirmed project owner. The effect now reads accessToken via a direct store snapshot instead of subscribing to it, and runs exactly once per mount so neither its own side effects nor an unstable router reference can re-trigger it. Co-Authored-By: Claude Sonnet 5 --- .../auth/use-bootstrap-session.test.ts | 20 +++++++++++++++++++ .../features/auth/use-bootstrap-session.ts | 16 +++++++++++++-- 2 files changed, 34 insertions(+), 2 deletions(-) diff --git a/client/src/features/auth/use-bootstrap-session.test.ts b/client/src/features/auth/use-bootstrap-session.test.ts index 3fce587..8ee3940 100644 --- a/client/src/features/auth/use-bootstrap-session.test.ts +++ b/client/src/features/auth/use-bootstrap-session.test.ts @@ -41,6 +41,26 @@ describe("useBootstrapSession", () => { expect(replace).not.toHaveBeenCalled(); }); + it("still sets the user even though refreshAccessToken flips accessToken mid-bootstrap (BUG #9)", async () => { + // The real `refreshAccessToken` sets `accessToken` on the store as soon as it resolves, + // *before* `/auth/me` returns -- reproduce that here instead of a bare resolved value, since + // a mock that only returns a token (as the test above does) can't expose the effect + // re-running and tearing down the in-flight bootstrap before `setSession` runs. + const { apiRequest, refreshAccessToken } = await import("@/lib/api-client"); + vi.mocked(refreshAccessToken).mockImplementationOnce(async () => { + useAuthStore.getState().setAccessToken("fresh"); + return "fresh"; + }); + vi.mocked(apiRequest).mockResolvedValueOnce({ id: "u1", email: "a@b.com", displayName: null }); + + renderHook(() => useBootstrapSession()); + + // `isReady` flips true as soon as `accessToken` is set (by design, see auth.store.ts's + // `useIsAuthenticated`), which is exactly what let this race hide before -- so this + // assertion waits on `user` directly rather than on `isReady`. + await waitFor(() => expect(useAuthStore.getState().user).toEqual({ id: "u1", email: "a@b.com", displayName: null })); + }); + it("clears the store and redirects to /login when the refresh cookie is missing or invalid", async () => { const { refreshAccessToken } = await import("@/lib/api-client"); vi.mocked(refreshAccessToken).mockResolvedValueOnce(null); diff --git a/client/src/features/auth/use-bootstrap-session.ts b/client/src/features/auth/use-bootstrap-session.ts index 1358bee..544aa2e 100644 --- a/client/src/features/auth/use-bootstrap-session.ts +++ b/client/src/features/auth/use-bootstrap-session.ts @@ -18,7 +18,15 @@ export function useBootstrapSession(): { isReady: boolean } { const [bootstrapped, setBootstrapped] = useState(false); useEffect(() => { - if (isAuthenticated) { + // Read the store directly instead of depending on the reactive `isAuthenticated` value below. + // `refreshAccessToken()` inside `bootstrap()` calls `setAccessToken` as soon as it resolves, + // which flips `isAuthenticated` true *before* `/auth/me` has returned. If this effect + // depended on `isAuthenticated`, that flip would re-run it -- tearing down this in-flight + // call (`cancelled = true`) right as it awaits `/auth/me`, so `setSession` never lands and + // `user` stays `null` forever even though `accessToken` is set (BUG #9: every user-derived + // UI, e.g. RunDetail's owner/admin-gated "View raw output" button, silently stayed hidden for + // a real owner after any hard reload). + if (useAuthStore.getState().accessToken !== null) { return; } @@ -47,7 +55,11 @@ export function useBootstrapSession(): { isReady: boolean } { return () => { cancelled = true; }; - }, [isAuthenticated, router]); + // Bootstrap must run exactly once per mount, regardless of `isAuthenticated` or `router` + // identity changing along the way -- see the comment above for why depending on either + // reopens the same race. + // eslint-disable-next-line react-hooks/exhaustive-deps + }, []); return { isReady: isAuthenticated || bootstrapped }; } From a939371e4fbbb1c1cc33fdaa5ce751717d474096 Mon Sep 17 00:00:00 2001 From: Alexander Date: Mon, 7 Sep 2026 23:13:47 -0500 Subject: [PATCH 10/11] fix(client): surface a failed run's error message on the run detail page (BUG #10) ToolRun.error carries the orchestrator worker's failure detail (typically { code, message }) but RunDetail never read it -- a failed run showed only the red 'failed' badge with zero diagnostic information, for every role. The value is typed z.unknown() end to end, so it's parsed defensively with a local schema (never cast) before being rendered; an unrecognized shape renders nothing extra instead of crashing the page. Co-Authored-By: Claude Sonnet 5 --- .../runs/components/RunDetail.test.tsx | 30 +++++++++++++++++++ .../features/runs/components/RunDetail.tsx | 23 ++++++++++++++ 2 files changed, 53 insertions(+) diff --git a/client/src/features/runs/components/RunDetail.test.tsx b/client/src/features/runs/components/RunDetail.test.tsx index 0826b46..9652e82 100644 --- a/client/src/features/runs/components/RunDetail.test.tsx +++ b/client/src/features/runs/components/RunDetail.test.tsx @@ -54,6 +54,36 @@ describe("RunDetail", () => { expect(screen.queryByRole("button", { name: "View raw output" })).not.toBeInTheDocument(); }); + it("shows the run's error message for a failed run (BUG #10)", () => { + const failedRun = { ...RUN, status: "failed" as const, error: { code: "NON_ZERO_EXIT", message: "nmap exited with status 1" } }; + vi.mocked(useRun).mockReturnValue({ isLoading: false, isError: false, data: failedRun } as never); + vi.mocked(useCurrentRole).mockReturnValue({ role: "member", isLoading: false, isError: false }); + + render(); + + expect(screen.getByRole("alert")).toHaveTextContent("NON_ZERO_EXIT"); + expect(screen.getByRole("alert")).toHaveTextContent("nmap exited with status 1"); + }); + + it("shows nothing extra for a failed run with an unreadable error shape", () => { + const failedRun = { ...RUN, status: "failed" as const, error: "some unstructured string" }; + vi.mocked(useRun).mockReturnValue({ isLoading: false, isError: false, data: failedRun } as never); + vi.mocked(useCurrentRole).mockReturnValue({ role: "member", isLoading: false, isError: false }); + + render(); + + expect(screen.queryByRole("alert")).not.toBeInTheDocument(); + }); + + it("does not show an error block for a succeeded run", () => { + vi.mocked(useRun).mockReturnValue({ isLoading: false, isError: false, data: RUN } as never); + vi.mocked(useCurrentRole).mockReturnValue({ role: "member", isLoading: false, isError: false }); + + render(); + + expect(screen.queryByRole("alert")).not.toBeInTheDocument(); + }); + it("fetches and opens the raw output as a blob URL for an owner", async () => { vi.mocked(useRun).mockReturnValue({ isLoading: false, isError: false, data: RUN } as never); vi.mocked(useCurrentRole).mockReturnValue({ role: "owner", isLoading: false, isError: false }); diff --git a/client/src/features/runs/components/RunDetail.tsx b/client/src/features/runs/components/RunDetail.tsx index 55e5468..0780c51 100644 --- a/client/src/features/runs/components/RunDetail.tsx +++ b/client/src/features/runs/components/RunDetail.tsx @@ -1,6 +1,7 @@ "use client"; import { useState } from "react"; +import { z } from "zod"; import { Badge, runStatusTone } from "@/components/ui/badge"; import { Button } from "@/components/ui/button"; import { useCurrentRole } from "@/features/workspace/api/use-current-role"; @@ -12,12 +13,24 @@ type Props = { runId: string; }; +// `ToolRun.error` is typed `z.unknown()` (use-runs.ts) -- the server attaches whatever shape the +// failure came from (orchestrator.worker.ts's `{ code, message }`), so parse it defensively +// instead of casting (no `as`, per the project's "no unsafe casts" standard). Any shape that +// doesn't match is treated as "no readable error" rather than crashing the page. +const runErrorSchema = z + .object({ code: z.string().optional(), message: z.string() }) + .nullable() + .catch(null); + /** * Polls a single run's status until it's terminal. The raw-output link is only surfaced to * owner/admin roles -- the backend's `GET :runId/raw` endpoint already enforces this * server-side (`@Roles("owner","admin")`); the UI mirrors it so members don't see a dead link. * Fetched via `apiRequestBlob` (not a plain ``) because auth is a Bearer header, not a * cookie the browser would attach to a bare navigation. + * + * A `failed` run also surfaces `run.error` (BUG #10 -- it used to render only the "failed" badge + * with zero diagnostic information, for every role). */ export function RunDetail({ projectId, runId }: Props) { const runQuery = useRun(projectId, runId); @@ -48,6 +61,7 @@ export function RunDetail({ projectId, runId }: Props) { } const run = runQuery.data; + const runError = run.status === "failed" ? runErrorSchema.parse(run.error) : null; return (
    @@ -63,6 +77,15 @@ export function RunDetail({ projectId, runId }: Props) {
    Queued
    {run.queuedAt.toLocaleString()}
    + {runError ? ( +
    +

    {runError.code ?? "Run failed"}

    +

    {runError.message}

    +
    + ) : null} {canViewRaw ? (