AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.
fix(frontend/copilot): the "Waiting for you" box leaves once its last card is answered (#15051)
Reinier van der Leerabf3c548accb
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ApprovalQueue/ApprovalQueue.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ApprovalQueue/ApprovalQueue.tsxindex 5b47451560..ad9101b9e8 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ApprovalQueue/ApprovalQueue.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ApprovalQueue/ApprovalQueue.tsx@@ -1,5 +1,6 @@"use client";+import { cn } from "@/lib/utils";import { ApprovalCard } from "./components/ApprovalCard/ApprovalCard";import { CompactApprovalLine } from "./components/CompactApprovalLine";import { QueueHeader } from "./components/QueueHeader";@@ -27,7 +28,7 @@ export const COMPACT_FROM = 4;export function ApprovalQueue({ items, expertName = null, onAnswered }: Props) {const queue = useApprovalQueue({ items, onAnswered });- const { pending, receipts } = queue;+ const { pending, receipts, leaving } = queue;if (pending.length === 0 && receipts.length === 0) return null;const compact = pending.length >= COMPACT_FROM;@@ -41,7 +42,10 @@ export function ApprovalQueue({ items, expertName = null, onAnswered }: Props) {return (<sectionaria-label="Waiting for you"- className="overflow-hidden rounded-xl border border-zinc-200 bg-white"+ className={cn(+ "overflow-hidden rounded-xl border border-zinc-200 bg-white transition-opacity duration-200 motion-reduce:transition-none",+ leaving && "opacity-0",+ )}><QueueHeadercount={pending.length}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ApprovalQueue/__tests__/leaving.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ApprovalQueue/__tests__/leaving.test.tsxnew file mode 100644index 0000000000..ef728ef9a9--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ApprovalQueue/__tests__/leaving.test.tsx@@ -0,0 +1,107 @@+import userEvent from "@testing-library/user-event";+import { http, HttpResponse } from "msw";+import { afterEach, beforeEach, expect, test, vi } from "vitest";+import type { PendingHumanReviewModel } from "@/app/api/__generated__/models/pendingHumanReviewModel";+import { server } from "@/mocks/mock-server";+import { act, render, screen, within } from "@/tests/integrations/test-utils";+import { CopilotChatActionsProvider } from "../../CopilotChatActionsProvider/CopilotChatActionsProvider";+import { CopilotPendingReviews } from "../../CopilotPendingReviews/CopilotPendingReviews";+import { useHeldAnswersStore } from "../heldAnswersStore";+import { CHAT_SESSION, folder } from "./fixtures";++// The server's list: a review leaves it once it is answered.+let waiting: PendingHumanReviewModel[] = [];++beforeEach(() => {+ vi.useFakeTimers({ shouldAdvanceTime: true });+ server.use(+ http.get(`*/api/review/session/${CHAT_SESSION}`, () =>+ HttpResponse.json(waiting),+ ),+ http.post("*/api/review/action", async ({ request }) => {+ const { reviews } = (await request.json()) as {+ reviews: { node_exec_id: string }[];+ };+ const answered = new Set(reviews.map((r) => r.node_exec_id));+ waiting = waiting.filter((r) => !answered.has(r.node_exec_id));+ return HttpResponse.json({+ approved_count: reviews.length,+ rejected_count: 0,+ failed_count: 0,+ });+ }),+ );+});++afterEach(() => {+ vi.useRealTimers();+ useHeldAnswersStore.setState({ answers: {} });+});++test("the box leaves about a second after its last card is answered", async () => {+ waiting = [folder("a", "Q3 reports")];+ const user = renderQueue();++ await approve(user, "Create library folder Q3 reports");+ const answeredAt = Date.now();+ for (let i = 0; i < 30 && box(); i++) await advance(100);++ expect(box()).toBeNull();+ expect(Date.now() - answeredAt).toBeGreaterThanOrEqual(900);+});++test("the box and its receipts stay while a card still waits", async () => {+ waiting = [folder("a", "Q3 reports"), folder("b", "Invoices")];+ const user = renderQueue();++ await approve(user, "Create library folder Q3 reports");+ await advance(5000);++ expect(box()).not.toBeNull();+ expect(screen.getByText("· Approved")).toBeDefined();+ expect(+ screen.getByRole("heading", { name: "Create library folder Invoices" }),+ ).toBeDefined();+});++test("a new held call brings the box back without the earlier receipt", async () => {+ waiting = [folder("a", "Q3 reports")];+ const user = renderQueue();++ await approve(user, "Create library folder Q3 reports");+ await advance(1500);+ expect(box()).toBeNull();++ waiting = [folder("b", "Invoices")];+ await advance(2500);++ expect(+ await screen.findByRole("heading", {+ name: "Create library folder Invoices",+ }),+ ).toBeDefined();+ expect(screen.queryByText("· Approved")).toBeNull();+});++function renderQueue() {+ render(+ <CopilotChatActionsProvider onSend={vi.fn()} onBackendTurn={vi.fn()}>+ <CopilotPendingReviews chatSessionId={CHAT_SESSION} />+ </CopilotChatActionsProvider>,+ );+ return userEvent.setup({ advanceTimers: vi.advanceTimersByTime });+}++function box() {+ return screen.queryByRole("region", { name: "Waiting for you" });+}++async function approve(user: ReturnType<typeof userEvent.setup>, name: string) {+ const card = (await screen.findByRole("heading", { name })).closest("li")!;+ await user.click(within(card).getByRole("button", { name: "Approve" }));+ await screen.findByText("· Approved");+}++async function advance(ms: number) {+ await act(() => vi.advanceTimersByTimeAsync(ms));+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ApprovalQueue/useApprovalQueue.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ApprovalQueue/useApprovalQueue.tsindex f8e0129105..6005cc2cce 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ApprovalQueue/useApprovalQueue.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ApprovalQueue/useApprovalQueue.ts@@ -20,6 +20,10 @@ interface Args {onAnswered: () => void;}+// How long the box lingers once nothing waits, then how long it fades.+const LINGER_MS = 1000;+const FADE_MS = 200;+export function useApprovalQueue({ items, onAnswered }: Args) {const outcomes = useContext(HeldOutcomesContext);const { processReviews } = useProcessReviews();@@ -29,6 +33,7 @@ export function useApprovalQueue({ items, onAnswered }: Args) {const [receipts, setReceipts] = useState<Receipt[]>([]);const [openId, setOpenId] = useState<string | null>(null);const [confirmRejectAll, setConfirmRejectAll] = useState(false);+ const [leaving, setLeaving] = useState(false);const seen = useRef(new Map<string, ApprovalItem>());const answeredHere = useRef(new Set<string>());@@ -102,14 +107,38 @@ export function useApprovalQueue({ items, onAnswered }: Args) {const receiptIds = new Set(receipts.map((r) => r.item.reviewId));const currentIds = new Set(items.map((item) => item.reviewId));+ const pending = items.filter((item) => !receiptIds.has(item.reviewId));+ // A receipt stays until the chain row shows the answer.+ const shown = receipts.filter((r) =>+ r.item.toolCallId+ ? !outcomes.has(r.item.toolCallId)+ : currentIds.has(r.item.reviewId),+ );+ // Once every card is answered and off the server's list, the box leaves; a+ // card still listed would come back if its receipt went with it.+ const settled =+ pending.length === 0 &&+ shown.length > 0 &&+ shown.every((r) => !currentIds.has(r.item.reviewId));++ useEffect(() => {+ if (!settled) return;+ const fade = setTimeout(() => setLeaving(true), LINGER_MS);+ const gone = setTimeout(+ () => setReceipts([]),+ LINGER_MS + (prefersReducedMotion() ? 0 : FADE_MS),+ );+ return () => {+ clearTimeout(fade);+ clearTimeout(gone);+ setLeaving(false);+ };+ }, [settled]);+return {- pending: items.filter((item) => !receiptIds.has(item.reviewId)),- // A receipt stays until the chain row shows the answer.- receipts: receipts.filter((r) =>- r.item.toolCallId- ? !outcomes.has(r.item.toolCallId)- : currentIds.has(r.item.reviewId),- ),+ pending,+ receipts: shown,+ leaving,statusOf: (id: string) => statuses[id] ?? "idle",hasFailed: (id: string) => failed.includes(id),openId,@@ -124,3 +153,7 @@ function receiptText(item: ApprovalItem, approved: boolean) {if (isHeldRead(item)) return approved ? "Released" : "Kept out";return approved ? "Approved" : "Rejected";}++function prefersReducedMotion() {+ return window.matchMedia("(prefers-reduced-motion: reduce)").matches;+}