Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
103 changes: 80 additions & 23 deletions apps/app/src/hooks/queries/thread-queries.test.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// @vitest-environment jsdom

import { act, cleanup, renderHook, waitFor } from "@testing-library/react";
import { useQueryClient } from "@tanstack/react-query";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { PendingInteraction, ThreadListEntry } from "@bb/domain";
import type {
Expand All @@ -13,6 +14,7 @@ import * as api from "@/lib/api";
import { sdk } from "@/lib/sdk";
import { makeThreadListEntry } from "@/test/fixtures/thread-list-entries";
import { createQueryClientTestHarness } from "@/test/queryClientTestHarness";
import { createPerfPhaseLog } from "@/test/perf-phase";
import { ARCHIVED_THREADS_PAGE_SIZE } from "./archived-threads-page-size";
import {
sidebarNavigationQueryKey,
Expand All @@ -27,6 +29,7 @@ import {
COMPACT_THREAD_TIMELINE_SEGMENT_LIMIT,
didThreadDetailBootstrapRefreshAfterMount,
isPendingInteractionStateUnknown,
resolveThreadDetailQueryMount,
useArchivedThreads,
useChildThreads,
useThread,
Expand Down Expand Up @@ -319,18 +322,9 @@ describe("useThreadDetailBootstrap", () => {
updatedAt,
});

const result = renderHook(
() => {
const bootstrap = useThreadDetailBootstrap("thread-1");
return useThread("thread-1", {
enabled: bootstrap.isSuccess,
refetchOnMount: didThreadDetailBootstrapRefreshAfterMount(bootstrap)
? false
: "always",
});
},
{ wrapper },
);
const result = renderHook(() => useMountedThreadQuery("thread-1"), {
wrapper,
});

await waitFor(() => {
expect(result.result.current.isSuccess).toBe(true);
Expand All @@ -349,29 +343,92 @@ describe("useThreadDetailBootstrap", () => {
updatedAt: 1,
});

renderHook(
() => {
const bootstrap = useThreadDetailBootstrap("thread-1");
return useThread("thread-1", {
enabled: bootstrap.isSuccess,
refetchOnMount: didThreadDetailBootstrapRefreshAfterMount(bootstrap)
? false
: "always",
});
},
{ wrapper },
renderHook(() => useMountedThreadQuery("thread-1"), { wrapper });

await waitFor(() => {
expect(sdk.threads.get).toHaveBeenCalledTimes(1);
});
expect(sdk.threads.get).toHaveBeenCalledWith({
signal: expect.any(AbortSignal),
threadId: "thread-1",
});
});

it("reads a cached thread while bootstrap is still in flight", async () => {
const phase = createPerfPhaseLog();
let resolveThread:
| ((thread: ThreadWithIncludesResponse) => void)
| undefined;
vi.mocked(sdk.threads.get).mockReturnValue(
new Promise<ThreadWithIncludesResponse>((resolve) => {
resolveThread = (thread) => {
phase.mark("bootstrap-settled");
resolve(thread);
};
}),
);
const { queryClient, wrapper } = createQueryClientTestHarness();
queryClient.setQueryData(threadQueryKey("thread-1"), THREAD_WITH_INCLUDES);

const result = renderHook(() => useMountedThreadQuery("thread-1"), {
wrapper,
});

expect(result.result.current.data).toEqual(THREAD_WITH_INCLUDES);
expect(result.result.current.isSuccess).toBe(true);
phase.mark("thread-chrome-ready");
expect(phase.names()).not.toContain("bootstrap-settled");
await waitFor(() => {
expect(sdk.threads.get).toHaveBeenCalledTimes(1);
});
expect(sdk.threads.get).toHaveBeenCalledWith({
include: "environment,host",
signal: expect.any(AbortSignal),
threadId: "thread-1",
});
resolveThread?.(THREAD_WITH_INCLUDES);
await waitFor(() => {
expect(phase.names()).toContain("bootstrap-settled");
});
phase.expectBefore("thread-chrome-ready", "bootstrap-settled");
});

it("does not start a thread read until bootstrap when the thread cache is empty", async () => {
vi.mocked(sdk.threads.get).mockReturnValue(
new Promise<ThreadWithIncludesResponse>(() => {}),
);
const { wrapper } = createQueryClientTestHarness();

const result = renderHook(() => useMountedThreadQuery("thread-1"), {
wrapper,
});

expect(result.result.current.data).toBeUndefined();
expect(result.result.current.fetchStatus).toBe("idle");
await waitFor(() => {
expect(sdk.threads.get).toHaveBeenCalledTimes(1);
});
expect(sdk.threads.get).toHaveBeenCalledWith({
include: "environment,host",
signal: expect.any(AbortSignal),
threadId: "thread-1",
});
});
});

function useMountedThreadQuery(threadId: string) {
const queryClient = useQueryClient();
const bootstrap = useThreadDetailBootstrap(threadId);
return useThread(
threadId,
resolveThreadDetailQueryMount({
bootstrap,
queryClient,
threadId,
}),
);
}

describe("useArchivedThreads", () => {
it("loads archived threads across all projects when no scope is selected", async () => {
const { wrapper } = createQueryClientTestHarness();
Expand Down
24 changes: 24 additions & 0 deletions apps/app/src/hooks/queries/thread-queries.ts
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,30 @@ export function didThreadDetailBootstrapRefreshAfterMount(query: {
);
}

export function resolveThreadDetailQueryMount(args: {
bootstrap: {
dataUpdatedAt: number;
isError: boolean;
isFetchedAfterMount: boolean;
isSuccess: boolean;
};
queryClient: QueryClient;
threadId: string;
}): { enabled: boolean; refetchOnMount: boolean | "always" } {
const bootstrapSettled = args.bootstrap.isSuccess || args.bootstrap.isError;
const hasCachedThread =
Boolean(args.threadId) &&
args.queryClient.getQueryData(threadQueryKey(args.threadId)) !== undefined;
return {
enabled: hasCachedThread || bootstrapSettled,
refetchOnMount: didThreadDetailBootstrapRefreshAfterMount(args.bootstrap)
? false
: bootstrapSettled
? "always"
: false,
};
}

type ThreadTimelineQueryOptions = QueryOptions;

type ThreadTimelineTurnSummaryDetailsQueryOptions = QueryOptions;
Expand Down
33 changes: 33 additions & 0 deletions apps/app/src/test/perf-phase.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { expect } from "vitest";

interface PerfPhaseEvent {
at: number;
name: string;
}

export function createPerfPhaseLog() {
const events: PerfPhaseEvent[] = [];

return {
mark(name: string) {
events.push({ at: performance.now(), name });
},
names(): string[] {
return events.map((event) => event.name);
},
expectBefore(earlier: string, later: string) {
const earlierEvent = events.find((event) => event.name === earlier);
const laterEvent = events.find((event) => event.name === later);
expect(earlierEvent, `missing phase "${earlier}"`).toEqual(
expect.objectContaining({ name: earlier }),
);
expect(laterEvent, `missing phase "${later}"`).toEqual(
expect.objectContaining({ name: later }),
);
expect(
earlierEvent!.at,
`expected "${earlier}" before "${later}"`,
).toBeLessThan(laterEvent!.at);
},
};
}
20 changes: 11 additions & 9 deletions apps/app/src/views/thread-detail/ThreadDetailView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
useState,
type ReactNode,
} from "react";
import { useQueryClient } from "@tanstack/react-query";
import { nanoid } from "nanoid";
import { useSystemProviderInfo } from "@/hooks/queries/system-queries";
import { useNavigate } from "react-router-dom";
Expand Down Expand Up @@ -66,9 +67,9 @@ import {
type ChildThreadPendingAttentionSource,
} from "../../hooks/queries/child-thread-pending-interactions";
import {
didThreadDetailBootstrapRefreshAfterMount,
getLatestPendingInteraction,
isPendingInteractionStateUnknown,
resolveThreadDetailQueryMount,
useChildThreads,
useProjectThreadSubset,
useThread,
Expand Down Expand Up @@ -514,6 +515,7 @@ function ThreadDetailViewInternal(props: ThreadRoutePathArgs) {
const { isFocused, navigateInPane, onRequestClose, isBoundedPane } =
usePaneContext();
const navigate = useNavigate();
const queryClient = useQueryClient();
useFixedPanelTabsStorageMaintenance();
const systemConfigQuery = useSystemConfig();
const threadDetailBootstrapQuery = useThreadDetailBootstrap(threadId);
Expand All @@ -524,14 +526,14 @@ function ThreadDetailViewInternal(props: ThreadRoutePathArgs) {
isFetching,
isLoadingError,
error,
} = useThread(threadId, {
enabled: hasThreadDetailBootstrapSettled,
refetchOnMount: didThreadDetailBootstrapRefreshAfterMount(
threadDetailBootstrapQuery,
)
? false
: "always",
});
} = useThread(
threadId,
resolveThreadDetailQueryMount({
bootstrap: threadDetailBootstrapQuery,
queryClient,
threadId,
}),
);
const environmentQuery = useEnvironment(thread?.environmentId, {
enabled: hasThreadDetailBootstrapSettled,
staleTime: 5_000,
Expand Down