diff --git a/components/Home/HomeRunRow.tsx b/components/Home/HomeRunRow.tsx index 264cd9cfa..c2675107e 100644 --- a/components/Home/HomeRunRow.tsx +++ b/components/Home/HomeRunRow.tsx @@ -13,9 +13,15 @@ import { getRunHref } from "@/lib/tasks/getRunHref"; * by `GET /api/tasks/runs` yet, so this shows what is available: run * name, status, and finished-at (recoupable/chat#1850). */ -const HomeRunRow = ({ run }: { run: TaskRunItem }) => ( +const HomeRunRow = ({ + run, + accountId, +}: { + run: TaskRunItem; + accountId?: string; +}) => (
diff --git a/components/Home/TasksModule.tsx b/components/Home/TasksModule.tsx index 47a04d618..cfefbe97e 100644 --- a/components/Home/TasksModule.tsx +++ b/components/Home/TasksModule.tsx @@ -1,6 +1,7 @@ "use client"; import Link from "next/link"; +import { getAccountScopedHref } from "@/lib/tasks/getAccountScopedHref"; import useHomeTasksModuleState from "@/hooks/useHomeTasksModuleState"; import HomeRunRow from "./HomeRunRow"; import StarterTaskCard from "./StarterTaskCard"; @@ -28,7 +29,7 @@ const TasksModule = () => { Your label at work View all @@ -37,7 +38,7 @@ const TasksModule = () => { {state.view === "runs" ? (
{state.runs.map((run) => ( - + ))}
) : state.view === "scheduled" ? ( diff --git a/components/TasksPage/RecentRunsList.tsx b/components/TasksPage/RecentRunsList.tsx index 1a8131e3f..043c4588f 100644 --- a/components/TasksPage/RecentRunsList.tsx +++ b/components/TasksPage/RecentRunsList.tsx @@ -6,9 +6,15 @@ interface RecentRunsListProps { runs: TaskRunItem[]; isLoading: boolean; isError: boolean; + accountId?: string; } -const RecentRunsList: React.FC = ({ runs, isLoading, isError }) => { +const RecentRunsList: React.FC = ({ + runs, + isLoading, + isError, + accountId, +}) => { if (isError) { return (
@@ -42,7 +48,7 @@ const RecentRunsList: React.FC = ({ runs, isLoading, isErro key={run.id} className={index !== runs.length - 1 ? "border-b border-border" : ""} > - +
))}
diff --git a/components/TasksPage/Run/RunBreadcrumb.tsx b/components/TasksPage/Run/RunBreadcrumb.tsx index a4ff516db..5ad590d20 100644 --- a/components/TasksPage/Run/RunBreadcrumb.tsx +++ b/components/TasksPage/Run/RunBreadcrumb.tsx @@ -1,4 +1,5 @@ import Link from "next/link"; +import { getAccountScopedHref } from "@/lib/tasks/getAccountScopedHref"; import { Breadcrumb, BreadcrumbList, @@ -10,15 +11,21 @@ import { interface RunBreadcrumbProps { runId: string; + accountId?: string; } -export default function RunBreadcrumb({ runId }: RunBreadcrumbProps) { +export default function RunBreadcrumb({ + runId, + accountId, +}: RunBreadcrumbProps) { return ( - Tasks + + Tasks + diff --git a/components/TasksPage/Run/RunDetails.tsx b/components/TasksPage/Run/RunDetails.tsx index b18449885..cfc93f7bd 100644 --- a/components/TasksPage/Run/RunDetails.tsx +++ b/components/TasksPage/Run/RunDetails.tsx @@ -1,6 +1,7 @@ "use client"; import Link from "next/link"; +import { useAccountOverride } from "@/providers/AccountOverrideProvider"; import type { TaskRunStatus } from "@/lib/tasks/getTaskRunStatus"; import { getTaskDisplayName } from "@/lib/tasks/getTaskDisplayName"; import { getRunWorkflowLink } from "@/lib/tasks/getRunWorkflowLink"; @@ -15,6 +16,7 @@ import AccountIdDisplay from "@/components/ArtistSetting/AccountIdDisplay"; interface RunDetailsProps { runId: string; data: TaskRunStatus; + accountId?: string; } const openChatClass = @@ -25,9 +27,19 @@ const openChatClass = * work off; status and timeline come from the workflow run linked in its * metadata, and the transcript is the chat that run wrote to. */ -export default function RunDetails({ runId, data }: RunDetailsProps) { +export default function RunDetails({ + runId, + data, + accountId, +}: RunDetailsProps) { + const selection = useAccountOverride(); + const canOpenChat = + accountId === (selection.accountIdOverride ?? undefined) && + (!selection.email || Boolean(selection.accountIdOverride)); const link = getRunWorkflowLink(data.metadata); - const { data: workflow, isError } = useChatRunStatus(link?.workflowRunId); + const { data: workflow, isError } = useChatRunStatus(link?.workflowRunId, { + accountIdOverride: accountId, + }); const state = getRunPageState({ triggerRun: data, workflow, @@ -68,6 +80,10 @@ export default function RunDetails({ runId, data }: RunDetailsProps) { No chat recorded for this run. It fired before run pages linked to their chats, so only the schedule status is available.

+ ) : !canOpenChat ? ( +

+ Select the matching workspace account before opening this chat. +

) : ( Open chat diff --git a/components/TasksPage/Run/RunPage.tsx b/components/TasksPage/Run/RunPage.tsx index b69bc5458..a8d99dcdd 100644 --- a/components/TasksPage/Run/RunPage.tsx +++ b/components/TasksPage/Run/RunPage.tsx @@ -1,5 +1,7 @@ "use client"; +import { useSearchParams } from "next/navigation"; +import RunAccountNotice from "../RunAccountNotice"; import { XCircle } from "lucide-react"; import { useTaskRunStatus } from "@/hooks/useTaskRunStatus"; import RunBreadcrumb from "./RunBreadcrumb"; @@ -12,11 +14,18 @@ interface RunPageProps { } export default function RunPage({ runId }: RunPageProps) { - const { data, isPending, error } = useTaskRunStatus(runId); + const searchParams = useSearchParams(); + const accountIdOverride = searchParams.get("account_id") ?? undefined; + const { data, isPending, error, scopeReady, accountId } = useTaskRunStatus( + runId, + { accountIdOverride }, + ); let content; - if (isPending) { + if (scopeReady === false) { + content = null; + } else if (isPending) { content = ; } else if (error || !data) { content = ( @@ -28,12 +37,19 @@ export default function RunPage({ runId }: RunPageProps) { ); } else { - content = ; + content = ; } return ( - + +
+ +
{content}
); diff --git a/components/TasksPage/Run/__tests__/RunNavigation.scope.test.tsx b/components/TasksPage/Run/__tests__/RunNavigation.scope.test.tsx new file mode 100644 index 000000000..5264a792a --- /dev/null +++ b/components/TasksPage/Run/__tests__/RunNavigation.scope.test.tsx @@ -0,0 +1,119 @@ +// @vitest-environment jsdom +import React from "react"; +import { render, screen, waitFor } from "@testing-library/react"; +import { expect, it, vi } from "vitest"; +import { + context, + fetchMock, + wrapper, + response, +} from "@/hooks/__tests__/taskRunScope.fixture"; +import RecentRunsList from "@/components/TasksPage/RecentRunsList"; +import RunPage from "../RunPage"; +import RunDetails from "../RunDetails"; +import HomeRunRow from "@/components/Home/HomeRunRow"; +import type { TaskRunItem } from "@/lib/tasks/getTaskRuns"; +import type { TaskRunStatus } from "@/lib/tasks/getTaskRunStatus"; +const route = vi.hoisted(() => ({ query: "account_id=target-b" })); +vi.mock("next/navigation", () => ({ + useSearchParams: () => new URLSearchParams(route.query), +})); +vi.mock("next/link", () => ({ + default: ({ + href, + children, + ...props + }: React.AnchorHTMLAttributes) => ( + + {children} + + ), +})); +const run = { + id: "run-a", + status: "COMPLETED", + taskIdentifier: "scheduled-task", + createdAt: "2026-10-25T12:00:00Z", + startedAt: null, + finishedAt: null, + durationMs: null, +} satisfies TaskRunItem; +const detail = { + ...run, + metadata: { + workflowRunId: "workflow-a", + sessionId: "session-a", + chatId: "chat-a", + }, +} satisfies TaskRunStatus; + +it("retains the list target through detail and the back link despite a conflicting global selection", async () => { + context.account = "global-c"; + const list = render( + , + ); + const href = screen.getByRole("link").getAttribute("href")!; + expect(href).toBe("/runs/run-a?account_id=target-b"); + route.query = href.split("?")[1]; + list.unmount(); + fetchMock.mockResolvedValue(response()); + render(, { wrapper }); + await waitFor(() => expect(fetchMock).toHaveBeenCalled()); + expect( + new URL(fetchMock.mock.calls[0][0]).searchParams.get("account_id"), + ).toBe("target-b"); + expect(screen.getByRole("link", { name: "Tasks" }).getAttribute("href")).toBe( + "/tasks?tab=recents&account_id=target-b", + ); + expect(screen.getByText(/Runs for account target-b/).textContent).toContain( + "takes precedence", + ); +}); +it("homepage run rows preserve the fetched target", () => { + render(); + expect(screen.getByRole("link").getAttribute("href")).toBe( + "/runs/run-a?account_id=target-b", + ); +}); +it("unresolved detail selection is not an infinite skeleton or empty history", () => { + route.query = ""; + context.email = "pending@example.test"; + render(, { wrapper }); + expect(screen.getByRole("status").textContent).toContain("resolve or clear"); + expect(fetchMock).not.toHaveBeenCalled(); +}); +it.each(["self", "matching", "conflicting", "unresolved"] as const)( + "keeps workflow metadata but opens chat only with a %s compatible selection", + async (mode) => { + context.account = + mode === "matching" + ? "target-b" + : mode === "conflicting" + ? "global-c" + : null; + context.email = mode === "unresolved" ? "pending@example.test" : null; + const accountId = mode === "self" ? undefined : "target-b"; + render(, { + wrapper, + }); + await waitFor(() => expect(screen.getByText("Completed")).toBeTruthy()); + expect(String(fetchMock.mock.calls[0][0])).toContain( + "/api/chat/runs/workflow-a", + ); + if (mode === "self" || mode === "matching") + expect( + screen.getByRole("link", { name: "Open chat" }).getAttribute("href"), + ).toBe("/sessions/session-a/chats/chat-a"); + else { + expect(screen.queryByRole("link", { name: "Open chat" })).toBeNull(); + expect( + screen.getByText(/Select the matching workspace account/), + ).toBeTruthy(); + } + }, +); diff --git a/components/TasksPage/Run/__tests__/RunPage.test.tsx b/components/TasksPage/Run/__tests__/RunPage.test.tsx index d9ce5c5ad..6143d79fd 100644 --- a/components/TasksPage/Run/__tests__/RunPage.test.tsx +++ b/components/TasksPage/Run/__tests__/RunPage.test.tsx @@ -4,12 +4,23 @@ import { render, screen } from "@testing-library/react"; import { beforeEach, describe, expect, it, vi } from "vitest"; import RunPage from "@/components/TasksPage/Run/RunPage"; +vi.mock("next/navigation", () => ({ + useSearchParams: () => new URLSearchParams(), +})); + const runQuery: { data: { status: string } | undefined; isPending: boolean; isLoading: boolean; error: Error | null; -} = { data: undefined, isPending: true, isLoading: false, error: null }; + scopeReady: boolean; +} = { + data: undefined, + isPending: true, + isLoading: false, + error: null, + scopeReady: true, +}; vi.mock("@/hooks/useTaskRunStatus", () => ({ useTaskRunStatus: () => runQuery, })); @@ -30,6 +41,7 @@ describe("RunPage", () => { isPending: true, isLoading: false, error: null, + scopeReady: true, }); }); diff --git a/components/TasksPage/RunAccountNotice.tsx b/components/TasksPage/RunAccountNotice.tsx new file mode 100644 index 000000000..85a167fcf --- /dev/null +++ b/components/TasksPage/RunAccountNotice.tsx @@ -0,0 +1,26 @@ +interface RunAccountNoticeProps { + scopeReady: boolean; + accountId?: string; + explicit?: boolean; +} + +export default function RunAccountNotice({ + scopeReady, + accountId, + explicit, +}: RunAccountNoticeProps) { + if (!scopeReady) + return ( +

+ Sign in and resolve or clear the selected account to view runs. +

+ ); + if (!accountId) return null; + return ( +

+ Runs for account {accountId}. + {explicit && + " The account in this link takes precedence over the workspace selection."} +

+ ); +} diff --git a/components/TasksPage/RunCard.tsx b/components/TasksPage/RunCard.tsx index 957c07e27..d8259b835 100644 --- a/components/TasksPage/RunCard.tsx +++ b/components/TasksPage/RunCard.tsx @@ -11,14 +11,15 @@ import AccountIdDisplay from "@/components/ArtistSetting/AccountIdDisplay"; interface RunCardProps { run: TaskRunItem; + accountId?: string; } -const RunCard: React.FC = ({ run }) => { +const RunCard: React.FC = ({ run, accountId }) => { const duration = formatDuration(run.durationMs); return (
diff --git a/components/TasksPage/TasksTabs.tsx b/components/TasksPage/TasksTabs.tsx index a97e55ed9..07d293308 100644 --- a/components/TasksPage/TasksTabs.tsx +++ b/components/TasksPage/TasksTabs.tsx @@ -5,6 +5,7 @@ import { useScheduledActions } from "@/hooks/useScheduledActions"; import { useTaskRuns } from "@/hooks/useTaskRuns"; import TasksList from "./TasksList"; import RecentRunsList from "./RecentRunsList"; +import RunAccountNotice from "./RunAccountNotice"; import PulseHeader from "@/components/Pulse/PulseHeader"; import { Tabs, TabsList, TabsTrigger, TabsContent } from "@/components/ui/tabs"; @@ -25,6 +26,8 @@ const TasksTabs = () => { data: taskRuns, isLoading: isRunsLoading, isError: isRunsError, + scopeReady, + accountId, } = useTaskRuns({ accountIdOverride }); const tasks = data ?? []; @@ -44,11 +47,19 @@ const TasksTabs = () => {
- + {scopeReady && ( + + )}
diff --git a/hooks/__tests__/taskRunScope.fixture.tsx b/hooks/__tests__/taskRunScope.fixture.tsx new file mode 100644 index 000000000..e01fb1c55 --- /dev/null +++ b/hooks/__tests__/taskRunScope.fixture.tsx @@ -0,0 +1,83 @@ +import React from "react"; +import { cleanup } from "@testing-library/react"; +import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; +import { afterEach, beforeEach, vi } from "vitest"; + +const context = vi.hoisted(() => ({ + actor: "actor-a" as string | null, + authenticated: true, + account: null as string | null, + email: null as string | null, + origin: "https://api.example.test", +})); +const token = vi.hoisted(() => vi.fn<() => Promise>()); +vi.mock("@privy-io/react-auth", () => ({ + usePrivy: () => ({ + user: context.actor ? { id: context.actor } : null, + authenticated: context.authenticated, + getAccessToken: token, + }), +})); +vi.mock("@/providers/AccountOverrideProvider", () => ({ + useAccountOverride: () => ({ + accountIdOverride: context.account, + email: context.email, + }), +})); +vi.mock("@/lib/api/getClientApiBaseUrl", () => ({ + getClientApiBaseUrl: () => context.origin, +})); +export const fetchMock = vi.fn(); +export let client: QueryClient; +export const wrapper = ({ children }: { children: React.ReactNode }) => ( + {children} +); +export function response(label = "current", status = "COMPLETED") { + return { + ok: true, + status: 200, + json: async () => ({ + status: "completed", + createdAt: label, + runs: [ + { + id: label, + status, + metadata: null, + taskIdentifier: "scheduled-task", + createdAt: label, + }, + ], + }), + } as Response; +} +export function deferred() { + let resolve!: (value: T) => void; + const promise = new Promise((done) => { + resolve = done; + }); + return { promise, resolve }; +} +beforeEach(() => { + Object.assign(context, { + actor: "actor-a", + authenticated: true, + account: null, + email: null, + origin: "https://api.example.test", + }); + token.mockReset().mockResolvedValue("token-a"); + fetchMock.mockReset().mockResolvedValue(response()); + vi.stubGlobal("fetch", fetchMock); + client = new QueryClient({ + defaultOptions: { queries: { retry: false, retryDelay: 0 } }, + }); +}); +afterEach(() => { + cleanup(); + client.clear(); + vi.unstubAllGlobals(); + vi.useRealTimers(); +}); + +export { context, token }; diff --git a/hooks/__tests__/useHomeTasksModuleState.scope.test.tsx b/hooks/__tests__/useHomeTasksModuleState.scope.test.tsx new file mode 100644 index 000000000..667aa570e --- /dev/null +++ b/hooks/__tests__/useHomeTasksModuleState.scope.test.tsx @@ -0,0 +1,42 @@ +// @vitest-environment jsdom +import { renderHook, waitFor } from "@testing-library/react"; +import { expect, it, vi } from "vitest"; +import { context, fetchMock, wrapper } from "./taskRunScope.fixture"; +import useHomeTasksModuleState from "../useHomeTasksModuleState"; +const tasks = vi.hoisted(() => ({ existing: null as null | { id: string } })); +vi.mock("@/hooks/useScheduledActions", () => ({ + useScheduledActions: () => ({ + data: tasks.existing ? [tasks.existing] : [], + isSuccess: true, + isLoading: false, + }), +})); +vi.mock("@/lib/onboarding/findExistingWeeklyReportTask", () => ({ + findExistingWeeklyReportTask: () => tasks.existing, +})); +vi.mock("@/providers/ArtistProvider", () => ({ + useArtistProvider: () => ({ selectedArtist: { account_id: "artist-a" } }), +})); +it.each([true, false])( + "never substitutes a self schedule/starter for an empty selected account (self schedule: %s)", + async (exists) => { + tasks.existing = exists ? { id: "self-task" } : null; + context.account = "target-b"; + fetchMock.mockResolvedValue({ ok: true, json: async () => ({ runs: [] }) }); + const { result } = renderHook(() => useHomeTasksModuleState(), { wrapper }); + await waitFor(() => expect(fetchMock).toHaveBeenCalled()); + await waitFor(() => expect(result.current.accountId).toBe("target-b")); + expect(result.current.view).toBe("hidden"); + }, +); +it.each([true, false])( + "retains normal self fallback (self schedule: %s)", + async (exists) => { + tasks.existing = exists ? { id: "self-task" } : null; + fetchMock.mockResolvedValue({ ok: true, json: async () => ({ runs: [] }) }); + const { result } = renderHook(() => useHomeTasksModuleState(), { wrapper }); + await waitFor(() => + expect(result.current.view).toBe(exists ? "scheduled" : "starter"), + ); + }, +); diff --git a/hooks/__tests__/useTaskRunScope.test.tsx b/hooks/__tests__/useTaskRunScope.test.tsx new file mode 100644 index 000000000..ad18ff7ad --- /dev/null +++ b/hooks/__tests__/useTaskRunScope.test.tsx @@ -0,0 +1,200 @@ +// @vitest-environment jsdom +import { act, renderHook, waitFor } from "@testing-library/react"; +import { describe, expect, it, vi } from "vitest"; +import { + context, + token, + fetchMock, + wrapper, + response, + deferred, + client, +} from "./taskRunScope.fixture"; +import { useTaskRuns } from "../useTaskRuns"; +import { useTaskRunStatus } from "../useTaskRunStatus"; +import { useChatRunStatus } from "../useChatRunStatus"; + +const readers = [ + ["list", (accountIdOverride?: string) => useTaskRuns({ accountIdOverride })], + [ + "detail", + (accountIdOverride?: string) => + useTaskRunStatus("same-run", { accountIdOverride }), + ], + [ + "workflow", + (accountIdOverride?: string) => + useChatRunStatus("same-workflow", { accountIdOverride }), + ], +] as const; +for (const [name, useReader] of readers) { + describe(name, () => { + it("blocks unresolved email instead of requesting self, and recovers after clear", async () => { + context.email = "unresolved@example.test"; + const { result, rerender } = renderHook(() => useReader(), { wrapper }); + await act(async () => {}); + expect(fetchMock).not.toHaveBeenCalled(); + expect(result.current.scopeReady).toBe(false); + expect(result.current.data).toBeUndefined(); + context.email = null; + rerender(); + await waitFor(() => expect(result.current.data).toBeDefined()); + }); + it("URL selection wins over unresolved or conflicting global selection", async () => { + context.email = "unresolved@example.test"; + const { result, rerender } = renderHook(() => useReader("url-account"), { + wrapper, + }); + await waitFor(() => expect(result.current.data).toBeDefined()); + expect(result.current.accountId).toBe("url-account"); + if (name !== "workflow") + expect( + new URL(fetchMock.mock.calls[0][0]).searchParams.get("account_id"), + ).toBe("url-account"); + context.account = "global-account"; + rerender(); + expect(result.current.accountId).toBe("url-account"); + }); + it.each(["account", "actor", "origin", "authenticated"] as const)( + "hides cached data immediately when %s changes", + async (field) => { + const { result, rerender } = renderHook(() => useReader(), { wrapper }); + await waitFor(() => expect(result.current.data).toBeDefined()); + fetchMock.mockReturnValue(new Promise(() => {})); + if (field === "authenticated") context.authenticated = false; + else + context[field] = + field === "origin" ? "https://new.example.test" : "other"; + rerender(); + expect(result.current.data).toBeUndefined(); + }, + ); + it("does not resurrect cached data after same-actor sign-out/sign-in", async () => { + const { result, rerender } = renderHook(() => useReader(), { wrapper }); + await waitFor(() => expect(result.current.data).toBeDefined()); + context.authenticated = false; + rerender(); + fetchMock.mockReturnValue(new Promise(() => {})); + context.authenticated = true; + rerender(); + expect(result.current.data).toBeUndefined(); + }); + it("a pending A to B to A switch recovers without accepting the original response", async () => { + const pending = deferred(); + fetchMock.mockReturnValueOnce(pending.promise); + const { result, rerender } = renderHook(() => useReader(), { wrapper }); + await waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(1)); + context.account = "account-b"; + rerender(); + await waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(2)); + context.account = null; + fetchMock.mockResolvedValue(response("fresh")); + rerender(); + await waitFor(() => + expect(JSON.stringify(result.current.data)).toContain("fresh"), + ); + await act(async () => pending.resolve(response("obsolete"))); + expect(JSON.stringify(result.current.data)).toContain("fresh"); + }); + it("an empty explicit account does not fall back to global or self", async () => { + context.account = "global-account"; + const { result } = renderHook(() => useReader(""), { wrapper }); + await act(async () => {}); + expect(fetchMock).not.toHaveBeenCalled(); + expect(result.current.scopeReady).toBe(false); + }); + it("rejects stale token completion before sending a request", async () => { + const pending = deferred(); + token.mockReturnValueOnce(pending.promise); + const { rerender } = renderHook(() => useReader(), { wrapper }); + await waitFor(() => expect(token).toHaveBeenCalledTimes(1)); + context.account = "account-b"; + rerender(); + await waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(1)); + await act(async () => pending.resolve("old-token")); + expect(fetchMock).toHaveBeenCalledTimes(1); + }); + it("aborts obsolete fetches and rejects late response completion", async () => { + const pending = deferred(); + fetchMock.mockReturnValueOnce(pending.promise); + const { result, rerender } = renderHook(() => useReader(), { wrapper }); + await waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(1)); + const signal = fetchMock.mock.calls[0][1].signal as AbortSignal; + context.account = "account-b"; + rerender(); + await waitFor(() => expect(result.current.data).toBeDefined()); + expect(signal.aborted).toBe(true); + await act(async () => pending.resolve(response("obsolete"))); + expect( + JSON.stringify( + client + .getQueryCache() + .findAll() + .map((q) => q.state.data), + ), + ).not.toContain("obsolete"); + }); + it("rejects an origin change during token acquisition even without rerender", async () => { + const pending = deferred(); + token.mockReturnValueOnce(pending.promise); + renderHook(() => useReader(), { wrapper }); + await waitFor(() => expect(token).toHaveBeenCalledTimes(1)); + context.origin = "https://new.example.test"; + await act(async () => pending.resolve("old-token")); + expect(fetchMock).not.toHaveBeenCalled(); + }); + it("rejects missing tokens without an empty bearer request, then recovers", async () => { + token.mockResolvedValue(null); + const { result } = renderHook(() => useReader(), { wrapper }); + await waitFor(() => expect(token).toHaveBeenCalled()); + expect(fetchMock).not.toHaveBeenCalled(); + token.mockResolvedValue("fresh-token"); + await act(async () => { + await result.current.refetch(); + }); + await waitFor(() => expect(result.current.data).toBeDefined()); + }); + it("never displays old success data after a denied refetch", async () => { + const { result } = renderHook(() => useReader(), { wrapper }); + await waitFor(() => expect(result.current.data).toBeDefined()); + fetchMock.mockResolvedValue({ + ok: false, + status: 403, + json: async () => ({ error: "Access denied" }), + }); + await act(async () => { + await result.current.refetch(); + }); + await waitFor(() => expect(result.current.data).toBeUndefined()); + expect(result.current.error?.message).toBe("Access denied"); + }, 15000); + }); +} + +for (const [name, useReader] of readers.filter(([name]) => name !== "list")) { + it(`${name} polls nonterminal runs every 3 seconds and stops on completion`, async () => { + vi.useFakeTimers(); + fetchMock.mockResolvedValue({ + ok: true, + json: async () => ({ + status: "running", + runs: [{ status: "EXECUTING", metadata: null }], + }), + }); + const { result } = renderHook(() => useReader(), { wrapper }); + await act(async () => { + await vi.advanceTimersByTimeAsync(1); + }); + expect(fetchMock).toHaveBeenCalledTimes(1); + expect(result.current.data).toBeDefined(); + fetchMock.mockResolvedValue(response()); + await act(async () => { + await vi.advanceTimersByTimeAsync(3000); + }); + expect(fetchMock).toHaveBeenCalledTimes(2); + await act(async () => { + await vi.advanceTimersByTimeAsync(9000); + }); + expect(fetchMock).toHaveBeenCalledTimes(2); + }); +} diff --git a/hooks/useChatRunStatus.ts b/hooks/useChatRunStatus.ts index 1b35f2cb8..3043b549c 100644 --- a/hooks/useChatRunStatus.ts +++ b/hooks/useChatRunStatus.ts @@ -1,5 +1,5 @@ import { useQuery } from "@tanstack/react-query"; -import { usePrivy } from "@privy-io/react-auth"; +import { useTaskRunScope, type TaskRunScopeOptions } from "./useTaskRunScope"; import { getChatRunStatus, type ChatRunStatus, @@ -10,16 +10,24 @@ import { getChatRunPollInterval } from "@/lib/tasks/getChatRunPollInterval"; * Polls a workflow run's status every 3s until it settles or the fetch * fails (chat#2006 item 4b). Disabled until a workflow run id is known. */ -export function useChatRunStatus(workflowRunId: string | undefined) { - const { getAccessToken, authenticated } = usePrivy(); +export function useChatRunStatus( + workflowRunId: string | undefined, + options: TaskRunScopeOptions = {}, +) { + const scope = useTaskRunScope(options); + const enabled = Boolean(workflowRunId) && scope.ready; - return useQuery({ - queryKey: ["chatRunStatus", workflowRunId], - queryFn: async () => { - const accessToken = await getAccessToken(); - return getChatRunStatus(workflowRunId!, accessToken!); - }, - enabled: !!workflowRunId && authenticated, + const query = useQuery({ + queryKey: ["chatRunStatus", scope.scopeKey, workflowRunId], + queryFn: ({ signal }) => + scope.read(signal, (token) => + getChatRunStatus(workflowRunId!, token, { + apiBaseUrl: scope.apiBaseUrl, + signal, + }), + ), + enabled, + gcTime: 0, refetchInterval: (query) => getChatRunPollInterval({ status: query.state.data?.status, @@ -28,4 +36,10 @@ export function useChatRunStatus(workflowRunId: string | undefined) { retry: 3, staleTime: 1000, }); + return { + ...query, + data: enabled && !query.error ? query.data : undefined, + scopeReady: scope.ready, + accountId: scope.accountId, + }; } diff --git a/hooks/useHomeTasksModuleState.ts b/hooks/useHomeTasksModuleState.ts index f7490789e..d530dac6d 100644 --- a/hooks/useHomeTasksModuleState.ts +++ b/hooks/useHomeTasksModuleState.ts @@ -10,26 +10,34 @@ import { /** * Composed hook behind the homepage tasks module. Shared by `TasksModule` * and `HomePage` (which needs the visibility to dock the command bar); - * react-query dedupes the underlying `GET /api/tasks/runs` and - * `GET /api/tasks` reads by key. The tasks read gates the starter card so + * Run reads are isolated by reader/auth session; scheduled task reads + * are shared by query key. The tasks read gates the starter card so * an account with an enabled report is never offered a duplicate. */ -const useHomeTasksModuleState = (): HomeTasksModuleState => { - const { data: runs, isLoading, isError } = useTaskRuns(); +const useHomeTasksModuleState = (): HomeTasksModuleState & { + accountId?: string; +} => { + const { data: runs, isLoading, isError, accountId } = useTaskRuns(); const tasksQuery = useScheduledActions({}); const { selectedArtist } = useArtistProvider(); - return getHomeTasksModuleState({ - runs, - runsFailed: isError, - isLoading: isLoading || tasksQuery.isLoading, - hasArtist: !!selectedArtist?.account_id, - // isSuccess, not data: react-query keeps the last list around after a - // failed refetch, and an unknown task list must hide the starter. - existingTask: tasksQuery.isSuccess - ? findExistingWeeklyReportTask(tasksQuery.data) - : undefined, - }); + return { + ...getHomeTasksModuleState({ + runs, + runsFailed: isError, + isLoading: isLoading || tasksQuery.isLoading, + hasArtist: !!selectedArtist?.account_id, + // isSuccess, not data: react-query keeps the last list around after a + // failed refetch, and an unknown task list must hide the starter. + // Selected-account run reads must not expose self-account schedules or + // offer self-account mutations when the selected history is empty. + existingTask: + !accountId && tasksQuery.isSuccess + ? findExistingWeeklyReportTask(tasksQuery.data) + : undefined, + }), + accountId, + }; }; export default useHomeTasksModuleState; diff --git a/hooks/useTaskRunScope.ts b/hooks/useTaskRunScope.ts new file mode 100644 index 000000000..10c444282 --- /dev/null +++ b/hooks/useTaskRunScope.ts @@ -0,0 +1,81 @@ +import { + useCallback, + useId, + useLayoutEffect, + useMemo, + useRef, + useState, +} from "react"; +import { usePrivy } from "@privy-io/react-auth"; +import { useAccountOverride } from "@/providers/AccountOverrideProvider"; +import { getClientApiBaseUrl } from "@/lib/api/getClientApiBaseUrl"; + +export interface TaskRunScopeOptions { + accountIdOverride?: string; +} + +/** URL account_id explicitly wins; absent it, an unresolved email blocks reads. */ +export function useTaskRunScope({ + accountIdOverride, +}: TaskRunScopeOptions = {}) { + const { user, authenticated, getAccessToken } = usePrivy(); + const selection = useAccountOverride(); + const actor = authenticated ? (user?.id ?? "") : ""; + const readerId = useId(); + // Keep a previous login's successful cache out of a later login, even when + // Privy retains the user object or the same user signs back in. + const [session, setSession] = useState({ actor, generation: 0 }); + if (session.actor !== actor) { + setSession({ actor, generation: session.generation + 1 }); + } + const explicit = accountIdOverride !== undefined; + const accountId = explicit + ? accountIdOverride + : (selection.accountIdOverride ?? undefined); + const email = explicit ? null : selection.email; + const apiBaseUrl = getClientApiBaseUrl(); + const ready = Boolean(actor && (explicit ? accountId : !email || accountId)); + const scopeKey = JSON.stringify([ + readerId, + session.generation, + actor, + accountId, + email, + apiBaseUrl, + ]); + const context = useMemo(() => ({ scopeKey, ready }), [scopeKey, ready]); + const current = useRef(context); + useLayoutEffect(() => { + current.current = context; + return () => { + current.current = null; + }; + }, [context]); + + const read = useCallback( + async (signal: AbortSignal, request: (token: string) => Promise) => { + const assertCurrent = () => { + if ( + !ready || + signal.aborted || + current.current !== context || + getClientApiBaseUrl() !== apiBaseUrl + ) { + throw new Error( + "The account or connection changed. Reload the runs.", + ); + } + }; + assertCurrent(); + const token = await getAccessToken(); + assertCurrent(); + if (!token) throw new Error("Please sign in to view runs."); + const data = await request(token); + assertCurrent(); + return data; + }, + [ready, context, apiBaseUrl, getAccessToken], + ); + + return { accountId, apiBaseUrl, scopeKey, ready, read }; +} diff --git a/hooks/useTaskRunStatus.ts b/hooks/useTaskRunStatus.ts index 6b9d08e30..a9d6da3c5 100644 --- a/hooks/useTaskRunStatus.ts +++ b/hooks/useTaskRunStatus.ts @@ -1,5 +1,5 @@ import { useQuery } from "@tanstack/react-query"; -import { usePrivy } from "@privy-io/react-auth"; +import { useTaskRunScope, type TaskRunScopeOptions } from "./useTaskRunScope"; import { getTaskRunStatus, type TaskRunStatus, @@ -20,18 +20,33 @@ const isTerminal = (data: TaskRunStatus | undefined): boolean => /** * Polls the task run status every 3s until the run reaches a terminal state. */ -export function useTaskRunStatus(runId: string) { - const { getAccessToken, authenticated } = usePrivy(); +export function useTaskRunStatus( + runId: string, + options: TaskRunScopeOptions = {}, +) { + const scope = useTaskRunScope(options); + const enabled = Boolean(runId) && scope.ready; - return useQuery({ - queryKey: ["taskRunStatus", runId], - queryFn: async () => { - const accessToken = await getAccessToken(); - return getTaskRunStatus(runId, accessToken!); - }, - enabled: !!runId && authenticated, + const query = useQuery({ + queryKey: ["taskRunStatus", scope.scopeKey, runId], + queryFn: ({ signal }) => + scope.read(signal, (token) => + getTaskRunStatus(runId, token, { + accountIdOverride: scope.accountId, + apiBaseUrl: scope.apiBaseUrl, + signal, + }), + ), + enabled, + gcTime: 0, refetchInterval: (query) => (isTerminal(query.state.data) ? false : 3000), retry: 3, staleTime: 1000, }); + return { + ...query, + data: enabled && !query.error ? query.data : undefined, + scopeReady: scope.ready, + accountId: scope.accountId, + }; } diff --git a/hooks/useTaskRuns.ts b/hooks/useTaskRuns.ts index acbcaeed5..6ee480307 100644 --- a/hooks/useTaskRuns.ts +++ b/hooks/useTaskRuns.ts @@ -1,23 +1,26 @@ import { useQuery } from "@tanstack/react-query"; -import { usePrivy } from "@privy-io/react-auth"; -import { getTaskRuns, type TaskRunItem } from "@/lib/tasks/getTaskRuns"; +import { getTaskRuns } from "@/lib/tasks/getTaskRuns"; +import { useTaskRunScope, type TaskRunScopeOptions } from "./useTaskRunScope"; -interface UseTaskRunsParams { - accountIdOverride?: string; -} - -export function useTaskRuns({ accountIdOverride }: UseTaskRunsParams = {}) { - const { getAccessToken, authenticated } = usePrivy(); - - return useQuery({ - queryKey: ["task-runs", { accountIdOverride }], - queryFn: async () => { - const accessToken = await getAccessToken(); - if (!accessToken) { - throw new Error("Please sign in to view task runs"); - } - return getTaskRuns(accessToken, { accountIdOverride }); - }, - enabled: authenticated, +export function useTaskRuns(options: TaskRunScopeOptions = {}) { + const scope = useTaskRunScope(options); + const query = useQuery({ + queryKey: ["task-runs", scope.scopeKey], + queryFn: ({ signal }) => + scope.read(signal, (token) => + getTaskRuns(token, { + accountIdOverride: scope.accountId, + apiBaseUrl: scope.apiBaseUrl, + signal, + }), + ), + enabled: scope.ready, + gcTime: 0, }); + return { + ...query, + data: scope.ready && !query.error ? query.data : undefined, + scopeReady: scope.ready, + accountId: scope.accountId, + }; } diff --git a/lib/tasks/__tests__/getChatRunStatus.test.ts b/lib/tasks/__tests__/getChatRunStatus.test.ts index 98f08a5db..c241a8234 100644 --- a/lib/tasks/__tests__/getChatRunStatus.test.ts +++ b/lib/tasks/__tests__/getChatRunStatus.test.ts @@ -25,6 +25,7 @@ describe("getChatRunStatus", () => { "https://api.test/api/chat/runs/wrun_abc", { method: "GET", + signal: undefined, headers: { Authorization: "Bearer privy-token" }, }, ); diff --git a/lib/tasks/__tests__/taskRunRequests.scope.test.ts b/lib/tasks/__tests__/taskRunRequests.scope.test.ts new file mode 100644 index 000000000..3520c22f1 --- /dev/null +++ b/lib/tasks/__tests__/taskRunRequests.scope.test.ts @@ -0,0 +1,82 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; +import { getTaskRuns } from "../getTaskRuns"; +import { getTaskRunStatus } from "../getTaskRunStatus"; +import { getChatRunStatus } from "../getChatRunStatus"; +const state = vi.hoisted(() => ({ origin: "https://selected.example.test" })); +vi.mock("@/lib/api/getClientApiBaseUrl", () => ({ + getClientApiBaseUrl: () => state.origin, +})); +afterEach(() => vi.unstubAllGlobals()); + +describe("run request context", () => { + it.each(["list", "detail", "workflow"] as const)( + "%s captures the dynamic origin and propagates cancellation", + async (kind) => { + const signal = new AbortController().signal; + const fetchMock = vi + .fn() + .mockResolvedValue({ + ok: true, + json: async () => ({ + runs: [ + { + status: "COMPLETED", + metadata: { workflowRunId: "workflow-a" }, + }, + ], + status: "completed", + }), + }); + vi.stubGlobal("fetch", fetchMock); + if (kind === "list") + await getTaskRuns("token", { accountIdOverride: "target", signal }); + else if (kind === "detail") + await getTaskRunStatus("run-a", "token", { + accountIdOverride: "target", + signal, + }); + else await getChatRunStatus("workflow-a", "token", { signal }); + const [href, options] = fetchMock.mock.calls[0]; + const url = new URL(href); + expect(url.origin).toBe(state.origin); + expect(options.signal).toBe(signal); + expect(options.headers.Authorization).toBe("Bearer token"); + if (kind === "workflow") + expect(url.searchParams.has("account_id")).toBe(false); + else expect(url.searchParams.get("account_id")).toBe("target"); + if (kind === "detail") + expect(url.searchParams.get("runId")).toBe("run-a"); + if (kind === "list") expect(url.searchParams.get("limit")).toBe("20"); + }, + ); + it("keeps kickoff metadata while a run is unfinished", async () => { + vi.stubGlobal( + "fetch", + vi + .fn() + .mockResolvedValue({ + ok: true, + json: async () => ({ + runs: [ + { + status: "EXECUTING", + metadata: { + workflowRunId: "workflow-a", + sessionId: "session-a", + chatId: "chat-a", + }, + durationMs: 22, + }, + ], + }), + }), + ); + const run = await getTaskRunStatus("run-a", "token"); + expect(run.metadata).toEqual({ + workflowRunId: "workflow-a", + sessionId: "session-a", + chatId: "chat-a", + }); + expect(run.durationMs).toBeNull(); + }); +}); diff --git a/lib/tasks/getAccountScopedHref.ts b/lib/tasks/getAccountScopedHref.ts new file mode 100644 index 000000000..89d3144ef --- /dev/null +++ b/lib/tasks/getAccountScopedHref.ts @@ -0,0 +1,8 @@ +/** Preserve the run's explicit read target without changing global selection. */ +export function getAccountScopedHref(href: string, accountId?: string): string { + if (accountId === undefined) return href; + const [path, query] = href.split("?"); + const params = new URLSearchParams(query); + params.set("account_id", accountId); + return `${path}?${params}`; +} diff --git a/lib/tasks/getChatRunStatus.ts b/lib/tasks/getChatRunStatus.ts index b8e4b15dd..bcc95245a 100644 --- a/lib/tasks/getChatRunStatus.ts +++ b/lib/tasks/getChatRunStatus.ts @@ -1,4 +1,4 @@ -import { NEW_API_BASE_URL } from "@/lib/consts"; +import { getClientApiBaseUrl } from "@/lib/api/getClientApiBaseUrl"; export type ChatRunLifecycle = | "queued" @@ -23,10 +23,15 @@ export interface ChatRunStatus { export async function getChatRunStatus( workflowRunId: string, accessToken: string, + options: { apiBaseUrl?: string; signal?: AbortSignal } = {}, ): Promise { const response = await fetch( - `${NEW_API_BASE_URL}/api/chat/runs/${workflowRunId}`, - { method: "GET", headers: { Authorization: `Bearer ${accessToken}` } }, + `${options.apiBaseUrl ?? getClientApiBaseUrl()}/api/chat/runs/${encodeURIComponent(workflowRunId)}`, + { + method: "GET", + signal: options.signal, + headers: { Authorization: `Bearer ${accessToken}` }, + }, ); if (!response.ok) { let message = `Failed to fetch workflow run status (HTTP ${response.status})`; diff --git a/lib/tasks/getRunHref.ts b/lib/tasks/getRunHref.ts index 41520b4d3..0d4809f1b 100644 --- a/lib/tasks/getRunHref.ts +++ b/lib/tasks/getRunHref.ts @@ -1,8 +1,10 @@ +import { getAccountScopedHref } from "./getAccountScopedHref"; + /** * Path of a single run's page. Runs live at the top-level `/runs/{runId}` * route: a run is not owned by a task (the run object carries no task id), * and `/tasks/{id}` is the task page (chat#2006 item 2). */ -export function getRunHref(runId: string): string { - return `/runs/${runId}`; +export function getRunHref(runId: string, accountId?: string): string { + return getAccountScopedHref(`/runs/${encodeURIComponent(runId)}`, accountId); } diff --git a/lib/tasks/getTaskRunStatus.ts b/lib/tasks/getTaskRunStatus.ts index 2d0673679..b15b0b6ed 100644 --- a/lib/tasks/getTaskRunStatus.ts +++ b/lib/tasks/getTaskRunStatus.ts @@ -1,4 +1,4 @@ -import { TASKS_API_URL } from "@/lib/consts"; +import { getClientApiBaseUrl } from "@/lib/api/getClientApiBaseUrl"; /** * Trigger.dev run metadata. For scheduled runs `api` writes the link to the @@ -26,12 +26,22 @@ export interface TaskRunStatus { export async function getTaskRunStatus( runId: string, accessToken: string, + options: { + accountIdOverride?: string; + apiBaseUrl?: string; + signal?: AbortSignal; + } = {}, ): Promise { - const url = new URL(`${TASKS_API_URL}/runs`); + const url = new URL( + `${options.apiBaseUrl ?? getClientApiBaseUrl()}/api/tasks/runs`, + ); url.searchParams.set("runId", runId); + if (options.accountIdOverride) + url.searchParams.set("account_id", options.accountIdOverride); const response = await fetch(url.toString(), { method: "GET", + signal: options.signal, headers: { Authorization: `Bearer ${accessToken}`, }, diff --git a/lib/tasks/getTaskRuns.ts b/lib/tasks/getTaskRuns.ts index 11d3bf7d2..8df3002b2 100644 --- a/lib/tasks/getTaskRuns.ts +++ b/lib/tasks/getTaskRuns.ts @@ -21,6 +21,8 @@ interface TaskRunListResponse { interface GetTaskRunsOptions { accountIdOverride?: string; + apiBaseUrl?: string; + signal?: AbortSignal; } /** @@ -34,7 +36,9 @@ export async function getTaskRuns( accessToken: string, options: GetTaskRunsOptions = {}, ): Promise { - const url = new URL(`${getClientApiBaseUrl()}/api/tasks/runs`); + const url = new URL( + `${options.apiBaseUrl ?? getClientApiBaseUrl()}/api/tasks/runs`, + ); url.searchParams.set("limit", "20"); if (options.accountIdOverride) { @@ -43,6 +47,7 @@ export async function getTaskRuns( const response = await fetch(url.toString(), { method: "GET", + signal: options.signal, headers: { Authorization: `Bearer ${accessToken}`, },