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}`,
},