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
141 changes: 141 additions & 0 deletions site/src/api/queries/chats.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -98,13 +98,15 @@ import {
mcpServerConfigsKey,
mergeWatchedChatIntoCaches,
mergeWatchedChatSummary,
moveChatToProject,
openChat,
organizationChatModelsKey,
patchChatEntity,
patchChatMessages,
pinChat,
planModeFieldsForCreateMessage,
prependToInfiniteChatsCache,
projectChats,
projectChatsKey,
promoteChatQueuedMessage,
proposeChatTitle,
Expand All @@ -114,6 +116,7 @@ import {
reorderPinnedChat,
replaceChatMessagesHistory,
resetUnloadedChatEntity,
resetUnloadedChatLists,
setChatGroupRole,
setChatUserRole,
shouldInvalidateChatSearches,
Expand Down Expand Up @@ -267,6 +270,34 @@ const observeChatWithDeferredFirstFetch = (
};
};

/** resetQueries refetches only observed queries. */
const observeChatLists = (
queryClient: QueryClient,
options: { staleTime?: number } = {},
) => {
const observers = [
new InfiniteQueryObserver(queryClient, { ...infiniteChats(), ...options }),
new InfiniteQueryObserver(queryClient, {
...projectChats("project-1"),
...options,
}),
];
const unsubscribes = observers.map((observer) =>
observer.subscribe(() => {}),
);
return {
chats: () =>
observers.map((observer) =>
observer.getCurrentResult().data?.pages.flat(),
),
unsubscribe: () => {
for (const unsubscribe of unsubscribes) {
unsubscribe();
}
},
};
};

describe("chat model query factories", () => {
const organizationId = "organization-1";
const otherOrganizationId = "organization-2";
Expand Down Expand Up @@ -1519,6 +1550,32 @@ describe("pinChat optimistic update", () => {
});
});

describe("moveChatToProject", () => {
it("restores the project when the move fails", async () => {
const queryClient = createTestQueryClient();
const chatId = "chat-1";
seedInfiniteChats(queryClient, [
makeChat(chatId, { project_id: "project-a" }),
]);
queryClient.setQueryData(
chatEntityKey(chatId),
makeChat(chatId, { project_id: "project-a" }),
);
const mutation = moveChatToProject(queryClient);
const variables = { chatId, projectId: null };

const context = await mutation.onMutate(variables);
expect(readInfiniteChats(queryClient)?.[0].project_id).toBeUndefined();

mutation.onError(new Error("conflict"), variables, context);
expect(readInfiniteChats(queryClient)?.[0].project_id).toBe("project-a");
expect(
queryClient.getQueryData<TypesGen.Chat>(chatEntityKey(chatId))
?.project_id,
).toBe("project-a");
});
});

describe("unpinChat optimistic update", () => {
it("optimistically sets pin_order to 0 in the chats list", async () => {
const queryClient = createTestQueryClient();
Expand Down Expand Up @@ -3709,6 +3766,34 @@ describe("mergeWatchedChatSummary", () => {
});
});

it("takes project_id only from project_change events", () => {
const cachedChat = makeChat("chat-1", {
project_id: "project-a",
updated_at: "2025-01-01T00:00:00.000Z",
});
// A move does not change updated_at.
const moved = mergeWatchedChatSummary(
cachedChat,
makeChat("chat-1", {
project_id: "project-b",
updated_at: "2025-01-01T00:00:00.000Z",
}),
{ eventKind: "project_change" },
);
expect(moved.project_id).toBe("project-b");

const delayedStatus = makeChat("chat-1", {
project_id: "project-a",
status: "running",
updated_at: "2025-01-01T00:00:00.000Z",
});
expect(
mergeWatchedChatSummary(moved, delayedStatus, {
eventKind: "status_change",
}),
).toMatchObject({ project_id: "project-b", status: "running" });
});

it("does not let an older summary row revert fields a newer event set", () => {
const cachedChat = makeChat("chat-1", {
last_model_config_id: "model-a",
Expand Down Expand Up @@ -4840,6 +4925,62 @@ describe("semantic cache operations: cancellation", () => {
expect(resetSpy).not.toHaveBeenCalled();
});

it("resetUnloadedChatLists restarts first fetches of sidebar and project lists", async () => {
const queryClient = createTestQueryClient();
const staleChat = makeChat("chat-1");
const movedChat = makeChat("chat-1", { project_id: "project-1" });
const firstFetches = [
createDeferred<TypesGen.Chat[]>(),
createDeferred<TypesGen.Chat[]>(),
];
const getChats = vi
.mocked(API.experimental.getChats)
.mockReturnValueOnce(firstFetches[0].promise)
.mockReturnValueOnce(firstFetches[1].promise)
.mockResolvedValueOnce([movedChat])
.mockResolvedValueOnce([movedChat]);
const lists = observeChatLists(queryClient);
try {
expect(getChats).toHaveBeenCalledTimes(2);

const reset = resetUnloadedChatLists(queryClient);
// Both first responses read the lists before the move.
for (const firstFetch of firstFetches) {
firstFetch.resolve([staleChat]);
}
await reset;

expect(getChats).toHaveBeenCalledTimes(4);
expect(lists.chats()).toEqual([[movedChat], [movedChat]]);
} finally {
lists.unsubscribe();
}
});

it("resetUnloadedChatLists keeps loaded lists and sends no request", async () => {
const queryClient = createTestQueryClient();
// Answers any request, so a refetch fails below instead of timing out.
const getChats = vi.mocked(API.experimental.getChats).mockResolvedValue([]);
const loadedChats = [makeChat("chat-1")];
seedInfiniteChats(queryClient, loadedChats);
queryClient.setQueryData<InfiniteData>(projectChatsKey("project-1"), {
pages: [loadedChats],
pageParams: [0],
});
// Fresh data keeps the observers from fetching on mount.
const lists = observeChatLists(queryClient, {
staleTime: Number.POSITIVE_INFINITY,
});
try {
await resetUnloadedChatLists(queryClient);

expect(getChats).not.toHaveBeenCalled();
expect(lists.chats()).toEqual([loadedChats, loadedChats]);
} finally {
lists.unsubscribe();
}
});

it("cancelChatMessages cancels the exact messages entry", async () => {
const queryClient = createTestQueryClient();
const cancelSpy = vi.spyOn(queryClient, "cancelQueries");
Expand Down
82 changes: 82 additions & 0 deletions site/src/api/queries/chats.ts
Original file line number Diff line number Diff line change
Expand Up @@ -724,6 +724,7 @@ export const mergeWatchedChatSummary = (
const isChatSummaryEvent = eventKind === "chat_summary_change";
const isDiffStatusEvent = eventKind === "diff_status_change";
const isContextDirtyEvent = eventKind === "context_dirty";
const isProjectEvent = eventKind === "project_change";
const updatedAtComparison = compareUpdatedAtInstants(
cachedChat.updated_at,
watchedChat.updated_at,
Expand Down Expand Up @@ -832,6 +833,10 @@ export const mergeWatchedChatSummary = (
const nextUpdatedAt = adoptsRowFields
? watchedChat.updated_at
: cachedChat.updated_at;
// A move does not change updated_at, so only its own event can order it.
const nextProjectId = isProjectEvent
? watchedChat.project_id
: cachedChat.project_id;

// Keep updated_at in the no-op guard. This gives up the old streaming
// rerender shortcut so later stale events cannot pass isFreshEnough
Expand All @@ -849,6 +854,7 @@ export const mergeWatchedChatSummary = (
nextHasUnread === cachedChat.has_unread &&
nextUpdatedAt === cachedChat.updated_at &&
nextContext === cachedChat.context &&
nextProjectId === cachedChat.project_id &&
nextQueuedForCapacity === (cachedChat.queued_for_capacity ?? false)
) {
return cachedChat;
Expand All @@ -868,6 +874,7 @@ export const mergeWatchedChatSummary = (
has_unread: nextHasUnread,
updated_at: nextUpdatedAt,
context: nextContext,
project_id: nextProjectId,
queued_for_capacity: nextQueuedForCapacity,
};
};
Expand Down Expand Up @@ -1129,6 +1136,17 @@ export const resetUnloadedChatEntity = (
});
};

/** As resetUnloadedChatEntity, for every chat list that has not loaded. */
export const resetUnloadedChatLists = (queryClient: QueryClient) =>
Promise.all(
[chatListFamilyKey, chatProjectListFamilyKey].map((queryKey) =>
queryClient.resetQueries({
queryKey,
predicate: (query) => query.state.data === undefined,
}),
),
);

export const cancelChatMessages = (queryClient: QueryClient, chatId: string) =>
queryClient.cancelQueries({
queryKey: chatMessagesKey(chatId),
Expand Down Expand Up @@ -1303,6 +1321,11 @@ type UpdateChatWorkspaceVariables = {
workspaceId: string | null;
};

type MoveChatToProjectVariables = {
readonly chatId: string;
readonly projectId: string | null;
};

type UpdateChatPlanModeVariables = {
chatId: string;
planMode?: TypesGen.ChatPlanMode;
Expand Down Expand Up @@ -1916,6 +1939,65 @@ export const updateChatWorkspace = (queryClient: QueryClient) => ({
},
});

const setCachedChatProjectId = (
queryClient: QueryClient,
chatId: string,
projectId: string | undefined,
) => {
updateInfiniteChatsCache(queryClient, (chats) =>
chats.map((chat) =>
chat.id === chatId ? { ...chat, project_id: projectId } : chat,
),
);
patchChatEntity(
queryClient,
chatId,
(chat) => chat && { ...chat, project_id: projectId },
);
};

/**
* Moves a root chat into a project, or out of its project when projectId is
* null. The rollback restores only project_id, so it keeps the fields that
* watch events wrote while the request ran.
*/
export const moveChatToProject = (queryClient: QueryClient) => ({
mutationFn: ({ chatId, projectId }: MoveChatToProjectVariables) =>
Comment thread
ibetitsmike marked this conversation as resolved.
Resolved
API.experimental.updateChat(chatId, {
project_id:
projectId ??
// The API uses the nil UUID to remove the chat from its project.
"00000000-0000-0000-0000-000000000000",
}),
onMutate: async ({ chatId, projectId }: MoveChatToProjectVariables) => {
await cancelChatListQueries(queryClient);
await cancelChatEntity(queryClient, chatId);
const previousChat =
findChatInListCaches(queryClient, chatId) ??
queryClient.getQueryData<TypesGen.Chat>(chatEntityKey(chatId));
setCachedChatProjectId(queryClient, chatId, projectId ?? undefined);
return { previousProjectId: previousChat?.project_id };
},
onError: (
_error: unknown,
{ chatId }: MoveChatToProjectVariables,
context: { previousProjectId?: string } | undefined,
) => {
if (context) {
setCachedChatProjectId(queryClient, chatId, context.previousProjectId);
Comment thread
ibetitsmike marked this conversation as resolved.
Resolved
}
},
onSettled: (
_data: unknown,
_error: unknown,
{ chatId }: MoveChatToProjectVariables,
) =>
Promise.all([
invalidateChatListQueries(queryClient),
invalidateChatEntity(queryClient, chatId),
]),
});

type ChatListSnapshot = ReadonlyArray<
readonly [QueryKey, InfiniteChatsCacheData]
>;
Expand Down
6 changes: 6 additions & 0 deletions site/src/pages/AgentsPage/AgentsPageLayout.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -915,6 +915,12 @@ describe(shouldInvalidateFilteredChatList.name, () => {
eventKind: "diff_status_change",
expected: true,
},
{
name: "invalidates root chats that move to another project",
updatedChat: chatForFilterInvalidation(),
eventKind: "project_change",
expected: true,
},
{
name: "ignores non-membership events",
updatedChat: chatForFilterInvalidation(),
Expand Down
Loading
Loading