Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
16 commits
Select commit Hold shift + click to select a range
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
27 changes: 12 additions & 15 deletions site/src/pages/AgentsPage/AgentChatPage/AgentChatPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,10 @@ import {
isChatHookDispatchFailedResponse,
} from "../components/ChatConversation/chatError";
import { getWorkspaceAgent } from "../components/ChatConversation/chatHelpers";
import { runPromoteQueuedMessage } from "../components/ChatConversation/chatQueueReconciliation";
import {
runDeleteQueuedMessage,
runPromoteQueuedMessage,
} from "../components/ChatConversation/chatQueueReconciliation";
import {
selectChatStatus,
useChatSelector,
Expand Down Expand Up @@ -580,24 +583,19 @@ const AgentChatPage: React.FC = () => {
});
};

const handleDeleteQueuedMessage = async (id: number) => {
const previousQueuedMessages = store.getSnapshot().queuedMessages;
store.setQueuedMessages(
previousQueuedMessages.filter((message) => message.id !== id),
);
try {
await deleteQueuedMessage(id);
} catch (error) {
store.setQueuedMessages(previousQueuedMessages);
throw error;
}
};
const handleDeleteQueuedMessage = (id: number) =>
runDeleteQueuedMessage({ id, store, deleteQueuedMessage });

const fetchQueueConvergence = (chatId: string) =>
queryClient.fetchQuery(chatQueueConvergence(chatId));

const handlePromoteQueuedMessage = (id: number) =>
runPromoteQueuedMessage({
id,
store,
promoteQueuedMessage,
fetchQueueConvergence,
setCacheQueuedMessages,
agentId,
clearChatErrorReason,
onError: handleRequestError,
Expand Down Expand Up @@ -705,8 +703,7 @@ const AgentChatPage: React.FC = () => {
upsertCacheMessages,
getCacheQueuedMessages,
setCacheQueuedMessages,
fetchQueueConvergence: (chatId: string) =>
queryClient.fetchQuery(chatQueueConvergence(chatId)),
fetchQueueConvergence,
setCachedChatPlanMode,
};

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,12 @@ import type * as TypesGen from "#/api/typesGenerated";
import type { ChatMessagePart } from "#/api/typesGenerated";
import type { ModelSelectorOption } from "#/modules/aiModels/ModelSelector";
import { AGENT_BROWSER_APP_SLUG } from "#/modules/apps/apps";
import { MockChat, MockChatDiffStatus } from "#/testHelpers/chatEntities";
import {
MockChat,
MockChatDiffStatus,
MockChatQueuedMessage,
MockChatQueuedMessageUnderEdit,
} from "#/testHelpers/chatEntities";
import {
MockDefaultOrganization,
MockGroup,
Expand Down Expand Up @@ -863,10 +868,14 @@ const buildMessage = (
const buildStoreWithMessages = (
msgs: TypesGen.ChatMessage[],
status: TypesGen.ChatStatus = "waiting",
queuedMessages?: TypesGen.ChatQueuedMessage[],
) => {
const store = createChatStore();
store.replaceMessages(msgs);
store.setChatStatus(status);
if (queuedMessages) {
store.setQueuedMessages(queuedMessages);
}
return store;
};

Expand Down Expand Up @@ -954,6 +963,28 @@ export const EditingMessage: Story = {
),
};

/** The turn finished while the queue head was under edit. The composer
* queues a send. */
export const PausedAtQueuedEdit: Story = {
render: () => (
<StoryAgentChatPageView
store={buildStoreWithMessages(editingMessages, "paused", [
{
...MockChatQueuedMessageUnderEdit,
id: 1,
content: [{ type: "text", text: "Run the migrations" }],
},
{
...MockChatQueuedMessage,
id: 2,
content: [{ type: "text", text: "Start the dev server" }],
},
])}
chat={{ status: "paused" }}
/>
),
};

// ---------------------------------------------------------------------------
// AgentChatPageNotFoundView stories
// ---------------------------------------------------------------------------
Expand Down
39 changes: 39 additions & 0 deletions site/src/pages/AgentsPage/components/AgentChatInput.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ import { preferenceSettingsKey } from "#/api/queries/users";
import type * as TypesGen from "#/api/typesGenerated";
import {
MockChatContextClean,
MockChatQueuedMessage,
MockChatQueuedMessageUnderEdit,
MockMCPServerConfig,
} from "#/testHelpers/chatEntities";
import {
Expand Down Expand Up @@ -132,6 +134,43 @@ export const PromptHistorySuppressedWhileLoading: Story = {
},
};

export const ChatPaused: Story = {
args: {
isChatPaused: true,
queuedMessages: [
MockChatQueuedMessageUnderEdit,
{ ...MockChatQueuedMessage, id: 2 },
],
},
play: async ({ canvasElement }) => {
const canvas = within(canvasElement);
await userEvent.type(
canvas.getByRole("textbox", { name: "Chat message" }),
"Also update the docs",
);
await userEvent.hover(canvas.getByRole("button", { name: "Queue" }));
},
};

// The queue head is under edit on a chat that is not paused, for example
// one in error.
export const QueueHeadUnderEdit: Story = {
args: {
queuedMessages: [
MockChatQueuedMessageUnderEdit,
{ ...MockChatQueuedMessage, id: 2 },
],
},
play: async ({ canvasElement }) => {
const canvas = within(canvasElement);
await userEvent.type(
canvas.getByRole("textbox", { name: "Chat message" }),
"Also update the docs",
);
await userEvent.hover(canvas.getByRole("button", { name: "Queue" }));
},
};

export const DisablesSendUntilInput: Story = {};

export const SendsAndClearsInput: Story = {
Expand Down
58 changes: 57 additions & 1 deletion site/src/pages/AgentsPage/components/AgentChatInput.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,11 @@ import {
import { userSkills } from "#/api/queries/userSkills";
import type * as TypesGen from "#/api/typesGenerated";
import { toast } from "#/components/Toaster/toast";
import { MockMCPServerConfig } from "#/testHelpers/chatEntities";
import {
MockChatQueuedMessage,
MockChatQueuedMessageUnderEdit,
MockMCPServerConfig,
} from "#/testHelpers/chatEntities";
import { MockChatProject, MockWorkspace } from "#/testHelpers/entities";
import { createMockFile } from "#/testHelpers/files";
import {
Expand Down Expand Up @@ -1152,4 +1156,56 @@ describe("AgentChatInput", () => {
"This file type is uploaded into the chat's workspace. Attach a running workspace to the chat, then try again.",
);
});

it.each([
["sends the queue head when nothing is under edit", {}, true],
[
"does not send a queue head the server marks as under edit",
{ queuedMessages: [MockChatQueuedMessageUnderEdit] },
false,
],
] satisfies Array<
[string, Partial<React.ComponentProps<typeof AgentChatInput>>, boolean]
>)("Enter with an empty composer %s", async (_name, props, sendsHead) => {
const user = userEvent.setup();
const onPromoteQueuedMessage = vi.fn();

renderInput(
<AgentChatInput
onSend={vi.fn()}
isDisabled={false}
isLoading={false}
selectedModel={modelOptions[0].id}
onModelChange={vi.fn()}
modelOptions={modelOptions}
modelSelectorPlaceholder="Select model"
hasModelOptions
canConfigureAgentSetup={false}
initialValue=""
onContentChange={vi.fn()}
planModeEnabled={false}
onPlanModeToggle={vi.fn()}
isModelCatalogLoading={false}
queuedMessages={[MockChatQueuedMessage]}
onPromoteQueuedMessage={onPromoteQueuedMessage}
{...props}
/>,
);

// Plain Enter sends only once the shortcut preference has loaded.
await waitFor(() => {
expect(
screen.getByRole("button", { name: /^(Send|Queue)$/ }),
).toHaveAttribute("aria-keyshortcuts", "Enter");
});
await user.click(screen.getByRole("textbox", { name: "Chat message" }));
await user.keyboard("{Enter}");
Comment thread
mafredri marked this conversation as resolved.
Resolved
if (sendsHead) {
expect(onPromoteQueuedMessage).toHaveBeenCalledWith(
MockChatQueuedMessage.id,
);
} else {
expect(onPromoteQueuedMessage).not.toHaveBeenCalled();
}
});
});
18 changes: 12 additions & 6 deletions site/src/pages/AgentsPage/components/AgentChatInput.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -192,6 +192,7 @@ type AgentChatInputProps = {
warning?: string;
// When set, also hides the editor and every control (view-only mode).
readOnlyNotice?: string;
isChatPaused?: boolean;
// Editing state, owned by the parent.
editingKind?: EditingTarget["kind"];
onCancelEdit?: () => void;
Expand Down Expand Up @@ -559,6 +560,7 @@ export const AgentChatInput: React.FC<AgentChatInputProps> = ({
onPromoteQueuedMessage,
warning,
readOnlyNotice,
isChatPaused = false,
editingKind,
onCancelEdit,
userPromptHistory = [],
Expand Down Expand Up @@ -1182,7 +1184,7 @@ export const AgentChatInput: React.FC<AgentChatInputProps> = ({
const handleSubmit = () => {
const text = internalRef.current?.getValue()?.trim() ?? "";

// An empty composer sends the queue head.
// An empty composer sends the queue head unless the head is under edit.
if (
!text &&
!hasUploadedAttachments &&
Expand All @@ -1192,6 +1194,7 @@ export const AgentChatInput: React.FC<AgentChatInputProps> = ({
!isLoading &&
!hasActiveUploads &&
queuedMessages.length > 0 &&
!queuedMessages[0].editing_since &&
Comment thread
mafredri marked this conversation as resolved.
Resolved
onPromoteQueuedMessage
) {
void onPromoteQueuedMessage(queuedMessages[0].id);
Expand Down Expand Up @@ -1338,11 +1341,14 @@ export const AgentChatInput: React.FC<AgentChatInputProps> = ({
applyCycleValue(nextPrompt);
};

const sendButtonLabel = isEditingMessage
? "Save Edit"
: isStreaming
? "Queue"
: "Send";
let sendButtonLabel = "Send";
if (isEditingMessage) {
sendButtonLabel = "Save Edit";
} else if (isStreaming || isChatPaused || queuedMessages[0]?.editing_since) {
// The server queues a send while a turn runs or the queue head is
// under edit.
sendButtonLabel = "Queue";
}
// Stop and the send button are mutually exclusive while streaming; a
// non-empty draft or a live recording selects the send button. A live
// recording also takes precedence over history editing.
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import { describe, expect, it } from "vitest";
import type * as TypesGen from "#/api/typesGenerated";
import { MockChat } from "#/testHelpers/chatEntities";
import { MockUserOwner } from "#/testHelpers/entities";
import { canManageChat } from "./ChatActionsMenuItems";
import { canManageChat, getArchiveBlockedReason } from "./ChatActionsMenuItems";

const sharedByAnotherUser = {
...MockChat,
Expand All @@ -15,3 +16,42 @@ describe("canManageChat", () => {
expect(canManageChat(sharedByAnotherUser, MockUserOwner.id)).toBe(false);
});
});

const childWithStatus = (status: TypesGen.ChatStatus): TypesGen.Chat => ({
...MockChat,
id: `child-${status}`,
status,
});

describe("getArchiveBlockedReason", () => {
it("returns undefined when the whole family is waiting", () => {
expect(
getArchiveBlockedReason("waiting", [childWithStatus("waiting")]),
).toBeUndefined();
});

it("returns paused for a paused child on a waiting root", () => {
expect(
getArchiveBlockedReason("waiting", [childWithStatus("paused")]),
).toBe("paused");
});

it("returns undefined for an errored root with a waiting child", () => {
expect(
getArchiveBlockedReason("error", [childWithStatus("waiting")]),
).toBeUndefined();
});

it("returns paused for a paused chat with no children", () => {
expect(getArchiveBlockedReason("paused", undefined)).toBe("paused");
});

it("prefers active over paused", () => {
expect(
getArchiveBlockedReason("paused", [childWithStatus("running")]),
).toBe("active");
expect(
getArchiveBlockedReason("running", [childWithStatus("paused")]),
).toBe("active");
});
});
Loading
Loading