Python
Merge remote-tracking branch 'origin/main' into fix/right-rail-stale-artifact-responses
jeremy gude09362f0e68
diff --cc surfaces/gui/src/components/RightRail.requests.test.tsxindex 3d70fdd6,00000000..55a869c0mode 100644,000000..100644--- a/surfaces/gui/src/components/RightRail.requests.test.tsx+++ b/surfaces/gui/src/components/RightRail.requests.test.tsx@@@ -1,126 -1,0 +1,136 @@@+// Async artifact reads are session-owned: late work must never overwrite the active rail.+import { act, cleanup, fireEvent, render, screen } from "@testing-library/react";+import { afterEach, describe, expect, it, vi } from "vitest";+import type { ArtifactContent, ArtifactInfo } from "../api";+import { getArtifacts, readArtifact } from "../api";+import { RightRail } from "./RightRail";++vi.mock("../api", () => ({+ getArtifacts: vi.fn(),++ getJournalCases: vi.fn().mockResolvedValue([]),++ getRoots: vi.fn().mockResolvedValue([]),+ readArtifact: vi.fn(),+ revealArtifact: vi.fn(),+}));++vi.mock("./AccessSection", () => ({ AccessSection: () => null }));++const artifact = (name: string): ArtifactInfo => ({+ path: name,+ name,+ kind: "markdown",+ size: 10,+ modified_at: 1,+});++const content = (path: string, body: string): ArtifactContent => ({+ ok: true,+ path,+ kind: "markdown",+ content: body,+});++function deferred<T>() {+ let resolve!: (value: T) => void;+ let reject!: (reason?: unknown) => void;+ const promise = new Promise<T>((res, rej) => {+ resolve = res;+ reject = rej;+ });+ return { promise, resolve, reject };+}++const baseProps = {+ active: true,+ sessionId: "session-a",+ refreshKey: 0,+ toolNames: [],+ todo: [],+ running: false,+};+++function openArtifacts() {++ fireEvent.click(screen.getByTestId("rail-toggle-artifacts"));++}+++afterEach(() => {+ cleanup();+ vi.clearAllMocks();+});++describe("RightRail artifact request ownership", () => {+ it("clears the previous session's artifacts while the current list is loading", async () => {+ const currentRequest = deferred<ArtifactInfo[]>();+ vi.mocked(getArtifacts)+ .mockResolvedValueOnce([artifact("previous.md")])+ .mockReturnValueOnce(currentRequest.promise);++ const { rerender } = render(<RightRail {...baseProps} />);++ openArtifacts();+ expect(await screen.findByText("previous.md")).toBeTruthy();++ rerender(<RightRail {...baseProps} sessionId="session-b" />);+ expect(screen.queryByText("previous.md")).toBeNull();++ await act(async () => currentRequest.resolve([artifact("current.md")]));+ expect(screen.getByText("current.md")).toBeTruthy();+ });++ it("ignores an artifact-list response from the previous session", async () => {+ const oldRequest = deferred<ArtifactInfo[]>();+ const currentRequest = deferred<ArtifactInfo[]>();+ vi.mocked(getArtifacts)+ .mockReturnValueOnce(oldRequest.promise)+ .mockReturnValueOnce(currentRequest.promise);++ const { rerender } = render(<RightRail {...baseProps} />);++ openArtifacts();+ rerender(<RightRail {...baseProps} sessionId="session-b" />);++ await act(async () => currentRequest.resolve([artifact("current.md")]));+ expect(screen.getByText("current.md")).toBeTruthy();++ await act(async () => oldRequest.resolve([artifact("stale.md")]));+ expect(screen.getByText("current.md")).toBeTruthy();+ expect(screen.queryByText("stale.md")).toBeNull();+ });++ it("ignores a rejected artifact-list request after a newer request succeeds", async () => {+ const oldRequest = deferred<ArtifactInfo[]>();+ const currentRequest = deferred<ArtifactInfo[]>();+ vi.mocked(getArtifacts)+ .mockReturnValueOnce(oldRequest.promise)+ .mockReturnValueOnce(currentRequest.promise);++ const { rerender } = render(<RightRail {...baseProps} />);++ openArtifacts();+ rerender(<RightRail {...baseProps} sessionId="session-b" />);++ await act(async () => currentRequest.resolve([artifact("current.md")]));+ await act(async () => oldRequest.reject(new Error("stale failure")));++ expect(screen.getByText("current.md")).toBeTruthy();+ });++ it("ignores file content that finishes after the user selects another artifact", async () => {+ const firstRead = deferred<ArtifactContent>();+ const secondRead = deferred<ArtifactContent>();+ vi.mocked(getArtifacts).mockResolvedValue([artifact("first.md"), artifact("second.md")]);+ vi.mocked(readArtifact).mockImplementation((_sessionId, path) =>+ path === "first.md" ? firstRead.promise : secondRead.promise,+ );++ render(<RightRail {...baseProps} />);++ openArtifacts();+ fireEvent.click(await screen.findByText("first.md"));- fireEvent.click(screen.getByLabelText("Back to artifacts"));++ fireEvent.click(screen.getByTestId("artifact-crumb-back"));+ fireEvent.click(screen.getByText("second.md"));++ await act(async () => secondRead.resolve(content("second.md", "Current content")));+ expect(screen.getByText("Current content")).toBeTruthy();++ await act(async () => firstRead.resolve(content("first.md", "Stale content")));+ expect(screen.getByText("Current content")).toBeTruthy();+ expect(screen.queryByText("Stale content")).toBeNull();+ });+});diff --cc surfaces/gui/src/components/RightRail.tsxindex a7d9f8ed,7628fafc..96774c81--- a/surfaces/gui/src/components/RightRail.tsx+++ b/surfaces/gui/src/components/RightRail.tsx@@@ -75,79 -96,83 +96,129 @@@ export function RightRail(scratchPrimary,openAccessKey = 0,onOpenIntegrations,+ board,+ onExpandBoard,+ onOpenBoardItem,+ isLead = false,+ teamMembers = [],+ teamChatEnabled = false,+ teamChatUnread = 0,+ onOpenTeamChat,+ onOpenWorker,+ openBoardKey = 0,}: Props) {+ // Seventeenth pass: every panel starts collapsed and nothing auto-expands — a count+ // chip is the maximum signal. One exception survives (solo sessions only): Progress+ // still auto-opens the first time a live turn has todos.const [open, setOpen] = useState<Record<Panel, boolean>>({- progress: true,- artifacts: true,+ progress: false,+ artifacts: false,+ board: false,+ journal: false,+ team: false,+ files: false,});+ const autoOpenedProgress = useRef(false);+ useEffect(() => {+ if (!isLead && running && todo.length > 0 && !autoOpenedProgress.current) {+ autoOpenedProgress.current = true;+ setOpen((prev) => ({ ...prev, progress: true }));+ }+ }, [running, todo.length, isLead]);+ // A board chip in the transcript deep-links here: expand the Board section.+ const seenBoardKey = useRef(openBoardKey);+ useEffect(() => {+ if (openBoardKey === seenBoardKey.current) return;+ seenBoardKey.current = openBoardKey;+ setOpen((prev) => ({ ...prev, board: true }));+ }, [openBoardKey]);const [artifacts, setArtifacts] = useState<ArtifactInfo[]>([]);+ // UX-037 Files: the session's roots (workspace/scratch/grants) — the entry points of+ // the file explorer.+ const [rootDirs, setRootDirs] = useState<RootInfo[]>([]);+ const [journal, setJournal] = useState<JournalCase[]>([]);const [selected, setSelected] = useState<ArtifactInfo | null>(null);const [content, setContent] = useState<ArtifactContent | null>(null);+ const artifactListRequest = useRef(0);+ const artifactContentRequest = useRef(0);- const refreshArtifacts = () => getArtifacts(sessionId).then(setArtifacts).catch(() => setArtifacts([]));+ // Every refresh owns a monotonically increasing request id. Session switches, live refreshes,+ // and manual refreshes can overlap; only the newest response may update this rail.+ const refreshArtifacts = (+ onLoaded?: (list: ArtifactInfo[]) => void,+ onError?: () => void,+ ) => {+ const request = ++artifactListRequest.current;+ return getArtifacts(sessionId)+ .then((list) => {+ if (request !== artifactListRequest.current) return;+ setArtifacts(list);+ onLoaded?.(list);+ })+ .catch(() => {+ if (request !== artifactListRequest.current) return;+ setArtifacts([]);+ onError?.();+ });+ };++ const loadArtifactContent = (artifact: ArtifactInfo) => {+ const request = ++artifactContentRequest.current;+ setContent(null);+ return readArtifact(sessionId, artifact.path)+ .then((next) => {+ if (request === artifactContentRequest.current) setContent(next);+ })+ .catch(() => {+ if (request === artifactContentRequest.current) setContent(null);+ });+ };+ // Artifacts are session-owned. Drop the previous session's visible state before starting+ // this session's fetch so filenames never linger while the replacement request is pending.useEffect(() => {- if (!active) return;- if (showArtifacts) refreshArtifacts();+ artifactListRequest.current += 1;+ artifactContentRequest.current += 1;+ setArtifacts([]);+ setSelected(null);+ setContent(null);+ }, [sessionId]);++ useEffect(() => {+ if (!active || !showArtifacts) {+ artifactListRequest.current += 1;+ return;+ }+ refreshArtifacts();+ return () => {+ artifactListRequest.current += 1;+ };}, [active, sessionId, refreshKey, showArtifacts]);+ useEffect(() => {+ if (!active) return;+ getRoots(sessionId).then(setRootDirs).catch(() => setRootDirs([]));+ }, [active, sessionId, refreshKey]);++ // Journal cases surface only when a board exists — same visibility rule as the+ // Board section, so plain sessions carry zero team chrome.+ useEffect(() => {+ if (!active || !board?.space) {+ setJournal([]);+ return;+ }+ getJournalCases().then(setJournal).catch(() => setJournal([]));+ }, [active, sessionId, refreshKey, board?.space]);+- // Switching conversations closes any open artifact — it belongs to the previous session's- // workspace, which the new session can't (and shouldn't) read.useEffect(() => {- setSelected(null);- setContent(null);- }, [sessionId]);-- useEffect(() => {- setContent(null);- if (!selected) return;- readArtifact(sessionId, selected.path).then(setContent).catch(() => setContent(null));+ if (selected) loadArtifactContent(selected);+ else {+ artifactContentRequest.current += 1;+ setContent(null);+ }+ return () => {+ artifactContentRequest.current += 1;+ };}, [selected?.path, sessionId]);// Notify the app when a preview opens/closes (drives the left-nav auto-collapse).