Skip to content
Closed
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
10 changes: 6 additions & 4 deletions site/src/pages/AgentsPage/AgentChatPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,7 @@ import { isChatAgentBindingUnresolved } from "./components/ChatConversation/watc
import { workspaceSkillsFromChat } from "./components/ChatPageContent";
import { getModelSelectorHelp } from "./components/ModelSelectorHelp";
import { useAgentChatPanelPreference } from "./components/RightPanel/useAgentChatPanelPreference";
import { useChatProjectId } from "./hooks/useChatProjectId";
import {
type SendChatTurnOptions,
useConversationEditingState,
Expand Down Expand Up @@ -327,9 +328,8 @@ const AgentChatPage: React.FC = () => {
enabled: Boolean(chatOrganizationId),
staleTime: 60_000,
});
const chatProjectId = experiments.includes("chat-projects")
? chatQuery.data?.project_id
: undefined;
const { projectId: chatProjectId, isResolved: isChatProjectResolved } =
useChatProjectId(chatQuery.data, experiments.includes("chat-projects"));
const hasChatProject = Boolean(chatOrganizationId && chatProjectId);
const projectSkillsQuery = useQuery({
...chatProjectSkills(chatOrganizationId, chatProjectId ?? ""),
Expand Down Expand Up @@ -649,7 +649,9 @@ const AgentChatPage: React.FC = () => {
),
projectSkills: hasChatProject
? projectSkillsQuery.data?.filter((skill) => skill.enabled)
: [],
: isChatProjectResolved
? []
: undefined,
workspaceSkills: chatWorkspaceSkills,
compact,
clearChatContext,
Expand Down
5 changes: 5 additions & 0 deletions site/src/pages/AgentsPage/components/AgentChatInput.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -185,6 +185,7 @@ type AgentChatInputProps = {
chatOrganizationId?: string;
// Project of the chat, whose skills the "/" menu offers.
chatProjectId?: string;
isChatProjectPending?: boolean;
isWorkspaceLoading?: boolean;
// Queued user messages rendered above the textarea.
queuedMessages?: readonly ChatQueuedMessage[];
Expand Down Expand Up @@ -529,6 +530,7 @@ export const AgentChatInput: React.FC<AgentChatInputProps> = ({
onWorkspaceChange,
chatOrganizationId,
chatProjectId,
isChatProjectPending,
isWorkspaceLoading,
queuedMessages = [],
onDeleteQueuedMessage,
Expand Down Expand Up @@ -1469,6 +1471,9 @@ export const AgentChatInput: React.FC<AgentChatInputProps> = ({
projectId={
experiments.includes("chat-projects") ? chatProjectId : undefined
}
isProjectPending={
experiments.includes("chat-projects") && isChatProjectPending
}
workspaceSkills={workspaceSkills}
slashCommands={slashCommands}
skillsMenuAnchor={composerElement}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -558,6 +558,11 @@ type ChatMessageInputProps = Omit<
organizationId?: string;
/** Project, in organizationId, whose skills the chat loads, if any. */
projectId?: string;
/**
* True while the chat's project is still unknown, such as a subagent
* chat whose root chat is loading. Project skills then stay loading.
*/
isProjectPending?: boolean;
/**
* Story and test seam for deterministic personal skill menu data.
*/
Expand Down Expand Up @@ -636,15 +641,28 @@ const useStoredSkillSource = (
queryOptions: SkillsScope["list"],
{
hasSource,
isSourcePending = false,
isTriggerActive,
}: { hasSource: boolean; isTriggerActive: boolean },
}: {
hasSource: boolean;
isSourcePending?: boolean;
isTriggerActive: boolean;
},
) => {
const queryEnabled = isTriggerActive && hasSource;
const query = useQuery({
...queryOptions,
enabled: queryEnabled,
staleTime: 60_000,
});
if (isSourcePending) {
return {
skills: undefined,
isResolvedEmpty: false,
isLoading: isTriggerActive,
isError: false,
};
}
const skills = hasSource ? query.data?.filter((skill) => skill.enabled) : [];
const isUnresolved = queryEnabled && query.data === undefined;
return {
Expand Down Expand Up @@ -672,6 +690,7 @@ const ChatMessageInput = ({
hasWorkspace,
organizationId,
projectId,
isProjectPending = false,
personalSkillsOverride,
workspaceSkills,
slashCommands,
Expand Down Expand Up @@ -723,7 +742,11 @@ const ChatMessageInput = ({
const hasProject = Boolean(organizationId && projectId);
const projectSource = useStoredSkillSource(
chatProjectSkills(organizationId ?? "", projectId ?? ""),
{ hasSource: hasProject, isTriggerActive: hasSkillsTrigger },
{
hasSource: hasProject,
isSourcePending: isProjectPending,
isTriggerActive: hasSkillsTrigger,
},
);
// chatd skips disabled skills, so they never offer or collide.
const personalSkills = (personalSkillsOverride ?? skillsQuery.data)?.filter(
Expand Down Expand Up @@ -1086,7 +1109,7 @@ const ChatMessageInput = ({
projectSkills={projectSkillItems}
workspaceSkills={workspaceSkillItems}
organizationSkillsEnabled={Boolean(organizationId)}
projectSkillsEnabled={hasProject}
projectSkillsEnabled={hasProject || isProjectPending}
workspaceSkillsEnabled={hasWorkspace}
isPersonalLoading={isPersonalSkillsLoading}
isPersonalError={
Expand Down
87 changes: 86 additions & 1 deletion site/src/pages/AgentsPage/components/ChatPageContent.test.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
import { screen, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { describe, expect, it, vi } from "vitest";
import { createRef } from "react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { API } from "#/api/api";
import type * as TypesGen from "#/api/typesGenerated";
import { MockChat } from "#/testHelpers/chatEntities";
import { renderWithAuth } from "#/testHelpers/renderHelpers";
import { MockSkill } from "#/testHelpers/skills";
import type { ChatMessageInputRef } from "./AgentChatInput";
import { createChatStore } from "./ChatConversation/chatStore";
import { ChatPageInput } from "./ChatPageContent";

Expand Down Expand Up @@ -69,7 +73,88 @@ const workspaceFileReference = (
workspace_file_media_type: "text/csv",
});

const mockRootChat: TypesGen.Chat = {
...MockChat,
id: "root-chat",
organization_id: "org-1",
project_id: "project-1",
};
const mockSubagentChat: TypesGen.Chat = {
...MockChat,
id: "subagent-chat",
organization_id: "org-1",
parent_chat_id: mockRootChat.id,
root_chat_id: mockRootChat.id,
};

const mockSkillRequests = () => {
vi.spyOn(API, "getExperiments").mockResolvedValue(["chat-projects"]);
vi.spyOn(API.experimental, "getUserSkills").mockResolvedValue([
{ ...MockSkill, name: "compactor" },
]);
vi.spyOn(API.experimental, "getOrganizationSkills").mockResolvedValue([]);
return vi
.spyOn(API.experimental, "getChatProjectSkills")
.mockResolvedValue([]);
};

beforeEach(() => {
// jsdom lacks Range geometry, which the slash menu reads to anchor.
// The method does not exist to spy on, so add it per test and remove
// it afterwards.
Range.prototype.getBoundingClientRect = () => new DOMRect(0, 0, 1, 16);
});

afterEach(() => {
vi.restoreAllMocks();
Reflect.deleteProperty(Range.prototype, "getBoundingClientRect");
});

describe("ChatPageInput", () => {
it("keeps a subagent chat's project skills unknown while its root chat loads", async () => {
const user = userEvent.setup();
const getChatProjectSkills = mockSkillRequests();
vi.spyOn(API.experimental, "getChat").mockReturnValue(
new Promise(() => {}),
);
const inputRef = createRef<ChatMessageInputRef>();

renderChatPageInput(createChatStore(), {
chat: mockSubagentChat,
inputRef,
});

await user.click(
await screen.findByRole("textbox", { name: "Chat message" }),
);
await user.paste("/comp");
// An inherited project skill may shadow /compact, so the command
// stays hidden and Enter picks the qualified personal skill.
await screen.findByRole("option", { name: /compactor/ });
await user.keyboard("{Enter}");
expect(inputRef.current?.getValue()).toBe("/personal/compactor");
expect(getChatProjectSkills).not.toHaveBeenCalled();
});

it("loads the root chat's project skills for a subagent chat", async () => {
const user = userEvent.setup();
const getChatProjectSkills = mockSkillRequests();
const getChat = vi
.spyOn(API.experimental, "getChat")
.mockResolvedValue(mockRootChat);

renderChatPageInput(createChatStore(), { chat: mockSubagentChat });

await user.click(
await screen.findByRole("textbox", { name: "Chat message" }),
);
await user.paste("/");
await waitFor(() => {
expect(getChatProjectSkills).toHaveBeenCalledWith("org-1", "project-1");
});
expect(getChat).toHaveBeenCalledWith(mockRootChat.id, expect.anything());
});

it("routes Stop to onInterrupt while the chat requires action", async () => {
const user = userEvent.setup();
const onInterrupt = vi.fn();
Expand Down
8 changes: 7 additions & 1 deletion site/src/pages/AgentsPage/components/ChatPageContent.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,12 @@ import type * as TypesGen from "#/api/typesGenerated";
import { toast } from "#/components/Toaster/toast";
import { useAuthenticated } from "#/hooks/useAuthenticated";
import type { ModelSelectorOption } from "#/modules/aiModels/ModelSelector";
import { useDashboard } from "#/modules/dashboard/useDashboard";
import { getWorkspaceAgents } from "#/utils/workspace";
import { resolveChatCompactionThreshold } from "../compactionTriggers";
import { useChatDraftAttachments } from "../hooks/useChatDraftAttachments";
import { chatWidthClass, useChatFullWidth } from "../hooks/useChatFullWidth";
import { useChatProjectId } from "../hooks/useChatProjectId";
import { useFileAttachments } from "../hooks/useFileAttachments";
import {
isWorkspaceUploadInProgress,
Expand Down Expand Up @@ -392,6 +394,9 @@ export const ChatPageInput: React.FC<ChatPageInputProps> = ({
folder,
}) => {
const { user: currentUser } = useAuthenticated();
const { experiments } = useDashboard();
const { projectId: chatProjectId, isResolved: isChatProjectResolved } =
useChatProjectId(chat, experiments.includes("chat-projects"));
const organizationId = chat.organization_id;
const chatId = chat.id;
const chatContext = chat.context;
Expand Down Expand Up @@ -843,7 +848,8 @@ export const ChatPageInput: React.FC<ChatPageInputProps> = ({
isModelCatalogLoading={isModelCatalogLoading}
workspaceOptions={workspaceOptions}
chatOrganizationId={organizationId}
chatProjectId={chat.project_id}
chatProjectId={chatProjectId}
isChatProjectPending={!isChatProjectResolved}
selectedWorkspaceId={selectedWorkspaceId}
onWorkspaceChange={onWorkspaceChange}
isWorkspaceLoading={workspacesQuery.isLoading || isWorkspaceLoading}
Expand Down
72 changes: 72 additions & 0 deletions site/src/pages/AgentsPage/hooks/useChatProjectId.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
import { renderHook, waitFor } from "@testing-library/react";
import { QueryClientProvider } from "react-query";
import { afterEach, describe, expect, it, vi } from "vitest";
import { API } from "#/api/api";
import type { Chat } from "#/api/typesGenerated";
import { MockChat } from "#/testHelpers/chatEntities";
import { createTestQueryClient } from "#/testHelpers/renderHelpers";
import { useChatProjectId } from "./useChatProjectId";

const mockRootChat: Chat = {
...MockChat,
id: "root-chat",
project_id: "project-1",
};
const mockSubagentChat: Chat = {
...MockChat,
id: "subagent-chat",
parent_chat_id: mockRootChat.id,
root_chat_id: mockRootChat.id,
};

const renderUseChatProjectId = (chat: Chat, enabled = true) => {
const queryClient = createTestQueryClient();
return renderHook(() => useChatProjectId(chat, enabled), {
Comment thread
jaaydenh marked this conversation as resolved.
Resolved
wrapper: ({ children }: React.PropsWithChildren) => (
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
),
});
};

afterEach(() => {
vi.restoreAllMocks();
});

describe("useChatProjectId", () => {
it("resolves no project when the root chat fails to load", async () => {
vi.spyOn(API.experimental, "getChat").mockRejectedValue(new Error("boom"));

const { result } = renderUseChatProjectId(mockSubagentChat);

await waitFor(() => {
expect(result.current).toEqual({
projectId: undefined,
isResolved: true,
});
});
});

it("uses the chat's own project without fetching the root chat", () => {
const getChat = vi.spyOn(API.experimental, "getChat");

const { result } = renderUseChatProjectId({
...mockSubagentChat,
project_id: "project-2",
});

expect(result.current).toEqual({
projectId: "project-2",
isResolved: true,
});
expect(getChat).not.toHaveBeenCalled();
});

it("resolves no project while the chat-projects experiment is off", () => {
const getChat = vi.spyOn(API.experimental, "getChat");

const { result } = renderUseChatProjectId(mockSubagentChat, false);

expect(result.current).toEqual({ projectId: undefined, isResolved: true });
expect(getChat).not.toHaveBeenCalled();
});
});
44 changes: 44 additions & 0 deletions site/src/pages/AgentsPage/hooks/useChatProjectId.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import { useQuery } from "react-query";
import { chat as chatQuery } from "#/api/queries/chats";
import type { Chat } from "#/api/typesGenerated";

type ChatProjectId = {
/** The project whose skills apply to the chat, if any. */
projectId: string | undefined;
/**
* False while the project is unknown, so callers can avoid treating
* project skills as absent before the root chat loads. A failed root
* chat lookup resolves to no project so built-in commands keep working.
*/
isResolved: boolean;
};

/**
* Resolves the project a chat belongs to. Subagent chats have no
* project_id of their own and inherit the root chat's project, matching
* chatd's project resolution.
*/
export const useChatProjectId = (
chat: Chat | undefined,
enabled: boolean,
): ChatProjectId => {
const rootChatId = chat?.root_chat_id;
const needsRootChat = Boolean(
enabled && chat && !chat.project_id && rootChatId && rootChatId !== chat.id,
);
const rootChatQuery = useQuery({
...chatQuery(rootChatId ?? ""),
enabled: needsRootChat,
});

if (!enabled) {
return { projectId: undefined, isResolved: true };
}
if (!needsRootChat) {
return { projectId: chat?.project_id, isResolved: true };
}
return {
projectId: rootChatQuery.data?.project_id,
isResolved: rootChatQuery.data !== undefined || rootChatQuery.isError,
};
};
Loading