Skip to content

Database governance built for humans and agents — controlling changes and access across every major database.

feat(agent): adopt nmention for page agent dom refs (#19731)

p0nya51adde95f18
diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.json
index 53d33e62e5..759075ce84 100644
--- a/frontend/src/locales/en-US.json
+++ b/frontend/src/locales/en-US.json
@@ -2979,8 +2979,8 @@
"archive-chat": "Archive",
"unarchive-chat": "Unarchive",
"delete-chat": "Delete",
- "show-archived-chats": "Show archived chats",
- "hide-archived-chats": "Hide archived chats",
+ "active-only-chats": "Active only",
+ "archived-only-chats": "Archived only",
"archive-chat-confirmation": "Archive this chat?",
"delete-chat-confirmation": "Delete this chat?",
"chat-list-label": "Chats",
diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.json
index 1a2662fa6d..8d98718fba 100644
--- a/frontend/src/locales/es-ES.json
+++ b/frontend/src/locales/es-ES.json
@@ -2488,8 +2488,8 @@
"archive-chat": "Archivar",
"unarchive-chat": "Desarchivar",
"delete-chat": "Eliminar",
- "show-archived-chats": "Mostrar chats archivados",
- "hide-archived-chats": "Ocultar chats archivados",
+ "active-only-chats": "Solo activas",
+ "archived-only-chats": "Solo archivadas",
"archive-chat-confirmation": "¿Archivar este chat?",
"delete-chat-confirmation": "¿Eliminar este chat?",
"chat-list-label": "Chats",
diff --git a/frontend/src/locales/ja-JP.json b/frontend/src/locales/ja-JP.json
index d1c37df474..3a5b4be673 100644
--- a/frontend/src/locales/ja-JP.json
+++ b/frontend/src/locales/ja-JP.json
@@ -2488,8 +2488,8 @@
"archive-chat": "アーカイブ",
"unarchive-chat": "アーカイブ解除",
"delete-chat": "削除",
- "show-archived-chats": "アーカイブ済みのチャットを表示",
- "hide-archived-chats": "アーカイブ済みのチャットを非表示",
+ "active-only-chats": "アクティブのみ",
+ "archived-only-chats": "アーカイブのみ",
"archive-chat-confirmation": "このチャットをアーカイブしますか?",
"delete-chat-confirmation": "このチャットを削除しますか?",
"chat-list-label": "チャット",
diff --git a/frontend/src/locales/vi-VN.json b/frontend/src/locales/vi-VN.json
index ead7179e23..b01f4e0a98 100644
--- a/frontend/src/locales/vi-VN.json
+++ b/frontend/src/locales/vi-VN.json
@@ -2488,8 +2488,8 @@
"archive-chat": "Lưu trữ",
"unarchive-chat": "Bỏ lưu trữ",
"delete-chat": "Xóa",
- "show-archived-chats": "Hiện chat đã lưu trữ",
- "hide-archived-chats": "Ẩn chat đã lưu trữ",
+ "active-only-chats": "Chỉ hoạt động",
+ "archived-only-chats": "Chỉ lưu trữ",
"archive-chat-confirmation": "Lưu trữ chat này?",
"delete-chat-confirmation": "Xóa chat này?",
"chat-list-label": "Các chat",
diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.json
index a106f2d83a..d60ef9c5f8 100644
--- a/frontend/src/locales/zh-CN.json
+++ b/frontend/src/locales/zh-CN.json
@@ -2979,8 +2979,8 @@
"archive-chat": "归档",
"unarchive-chat": "取消归档",
"delete-chat": "删除",
- "show-archived-chats": "显示已归档聊天",
- "hide-archived-chats": "隐藏已归档聊天",
+ "active-only-chats": "仅显示活跃",
+ "archived-only-chats": "仅显示已归档",
"archive-chat-confirmation": "要归档这个聊天吗?",
"delete-chat-confirmation": "要删除这个聊天吗?",
"chat-list-label": "聊天",
diff --git a/frontend/src/plugins/agent/components/AgentInput.test.ts b/frontend/src/plugins/agent/components/AgentInput.test.ts
index 582bc5540e..06426b6baf 100644
--- a/frontend/src/plugins/agent/components/AgentInput.test.ts
+++ b/frontend/src/plugins/agent/components/AgentInput.test.ts
@@ -1,4 +1,5 @@
import { mount } from "@vue/test-utils";
+import { NButton, NMention } from "naive-ui";
import { createPinia, setActivePinia } from "pinia";
import { beforeEach, describe, expect, test, vi } from "vitest";
import { createI18n } from "vue-i18n";
@@ -58,6 +59,8 @@ const findButtonByText = (wrapper: ReturnType<typeof mount>, text: string) => {
const flushPromises = async () => {
await Promise.resolve();
await Promise.resolve();
+ await new Promise((resolve) => window.setTimeout(resolve, 0));
+ await Promise.resolve();
};
const createDeferred = <T>() => {
@@ -128,6 +131,29 @@ describe("AgentInput", () => {
document.title = "Demo Page";
});
+ test("renders the composer as a Naive UI textarea with a primary send button", () => {
+ const wrapper = mount(AgentInput, {
+ global: {
+ plugins: [pinia, i18n],
+ },
+ });
+
+ const inputRow = wrapper.find("[data-agent-input-row]");
+ expect(inputRow.exists()).toBe(true);
+
+ const input = wrapper.findComponent(NMention);
+ expect(input.exists()).toBe(true);
+ expect(input.props("type")).toBe("textarea");
+ expect(input.props("placement")).toBe("top-start");
+ expect(input.props("to")).toBe("body");
+
+ const sendButton = wrapper.findComponent(NButton);
+ expect(sendButton.exists()).toBe(true);
+ expect(sendButton.props("type")).toBe("primary");
+ expect(sendButton.text()).toBe("Send");
+ expect(sendButton.classes()).not.toContain("h-[38px]");
+ });
+
test("submits pending input as a tool result and resumes the same chat", async () => {
const store = useAgentStore();
const chatId = store.currentChatId!;
@@ -175,7 +201,7 @@ describe("AgentInput", () => {
});
await wrapper.find("textarea").setValue("demo-project");
- await wrapper.find("button").trigger("click");
+ await findButtonByText(wrapper, "Reply")!.trigger("click");
await flushPromises();
const toolMessages = store
@@ -232,7 +258,7 @@ describe("AgentInput", () => {
});
await wrapper.find("textarea").setValue("demo-project");
- await wrapper.find("button").trigger("click");
+ await findButtonByText(wrapper, "Reply")!.trigger("click");
await flushPromises();
expect(mockBuildSystemPrompt).toHaveBeenCalledWith({
@@ -358,7 +384,7 @@ describe("AgentInput", () => {
});
await wrapper.find("textarea").setValue("navigate first");
- await wrapper.find("button").trigger("click");
+ await findButtonByText(wrapper, "Send")!.trigger("click");
await flushPromises();
expect(store.getChat(chatId)?.page).toEqual({
@@ -375,7 +401,7 @@ describe("AgentInput", () => {
document.title = "Elsewhere Page";
await wrapper.find("textarea").setValue("continue");
- await wrapper.find("button").trigger("click");
+ await findButtonByText(wrapper, "Reply")!.trigger("click");
await flushPromises();
expect(mockBuildSystemPrompt).toHaveBeenNthCalledWith(1, {
@@ -716,7 +742,7 @@ describe("AgentInput", () => {
expect(getTextareaValue(wrapper)).toBe("demo-project");
});
- test("shows filtered DOM ref suggestions and inserts the selected ref", async () => {
+ test("filters DOM ref mention options and keeps bracket insertion semantics", async () => {
mockLazyExtractDomRefSuggestions.mockResolvedValue([
createDomRefSuggestion({
ref: "e1",
@@ -739,27 +765,29 @@ describe("AgentInput", () => {
});
const textarea = wrapper.find("textarea");
+ const mention = wrapper.findComponent(NMention);
await textarea.setValue("Click @sav");
(textarea.element as HTMLTextAreaElement).setSelectionRange(10, 10);
- await textarea.trigger("select");
+ await textarea.trigger("keyup");
await flushPromises();
expect(mockLazyExtractDomRefSuggestions).toHaveBeenCalled();
- const items = wrapper.findAll('[data-testid="dom-ref-autocomplete-item"]');
- expect(items).toHaveLength(1);
- expect(items[0].text()).toContain("[e1]");
- expect(items[0].text()).toContain("Save changes");
-
- await textarea.trigger("keydown", { key: "Enter" });
+ const options = mention.props("options") as {
+ value: string;
+ label: string;
+ suggestion: DomRefSuggestion;
+ }[];
+ expect(options).toHaveLength(1);
+ expect(options[0]?.value).toBe("[e1]");
+ expect(options[0]?.suggestion.label).toBe("Save changes");
+
+ mention.vm.$emit("update:value", "Click [e1] ");
await flushPromises();
expect(getTextareaValue(wrapper)).toBe("Click [e1] ");
- expect(wrapper.find('[data-testid="dom-ref-autocomplete"]').exists()).toBe(
- false
- );
});
- test("uses arrow keys to change the active DOM ref suggestion before selecting", async () => {
+ test("keeps DOM ref mention options ordered for keyboard navigation", async () => {
mockLazyExtractDomRefSuggestions.mockResolvedValue([
createDomRefSuggestion({
ref: "e1",
@@ -782,19 +810,78 @@ describe("AgentInput", () => {
});
const textarea = wrapper.find("textarea");
+ const mention = wrapper.findComponent(NMention);
+ await textarea.setValue("Use @");
+ (textarea.element as HTMLTextAreaElement).setSelectionRange(5, 5);
+ await textarea.trigger("keyup");
+ await flushPromises();
+
+ const options = mention.props("options") as { value: string }[];
+ expect(options.map((option) => option.value)).toEqual(["[e1]", "[e2]"]);
+ });
+
+ test("keeps all DOM ref mention options accessible and scrollable", async () => {
+ mockLazyExtractDomRefSuggestions.mockResolvedValue(
+ Array.from({ length: 10 }, (_, index) =>
+ createDomRefSuggestion({
+ ref: `e${index + 1}`,
+ tag: "BUTTON",
+ role: "button",
+ label: `Option ${index + 1}`,
+ })
+ )
+ );
+
+ const wrapper = mount(AgentInput, {
+ global: {
+ plugins: [pinia, i18n],
+ },
+ });
+
+ const textarea = wrapper.find("textarea");
+ const mention = wrapper.findComponent(NMention);
await textarea.setValue("Use @");
(textarea.element as HTMLTextAreaElement).setSelectionRange(5, 5);
- await textarea.trigger("select");
+ await textarea.trigger("keyup");
await flushPromises();
+ const options = mention.props("options") as { value: string }[];
+ expect(options).toHaveLength(10);
+ expect(options[0]?.value).toBe("[e1]");
+ expect(options[9]?.value).toBe("[e10]");
+ expect(mention.props("scrollbarProps")).toEqual({
+ containerStyle: { maxHeight: "320px" },
+ });
+ });
+
+ test("keeps the active DOM ref option scrolled into view during keyboard navigation", async () => {
+ const scrollIntoView = vi.fn();
+ const pendingOption = document.createElement("div");
+ pendingOption.className = "n-base-select-option--pending";
+ pendingOption.scrollIntoView = scrollIntoView;
+ const menu = document.createElement("div");
+ menu.className = "n-base-select-menu";
+ menu.appendChild(pendingOption);
+ document.body.appendChild(menu);
+
+ const wrapper = mount(AgentInput, {
+ global: {
+ plugins: [pinia, i18n],
+ },
+ });
+
+ const textarea = wrapper.find("textarea");
+ const mention = wrapper.findComponent(NMention);
+ mention.vm.$emit("update:show", true);
await textarea.trigger("keydown", { key: "ArrowDown" });
- await textarea.trigger("keydown", { key: "Enter" });
await flushPromises();
- expect(getTextareaValue(wrapper)).toBe("Use [e2] ");
+ expect(scrollIntoView).toHaveBeenCalledWith({ block: "nearest" });
+
+ menu.remove();
});
- test("does not send while the DOM ref menu is open and escape closes it", async () => {
+ test("does not send when Enter selects a DOM ref mention", async () => {
mockRunAgentLoop.mockResolvedValue({
kind: "completed",
text: "Done",
@@ -816,16 +903,19 @@ describe("AgentInput", () => {
});
const textarea = wrapper.find("textarea");
+ const mention = wrapper.findComponent(NMention);
await textarea.setValue("Inspect @save");
(textarea.element as HTMLTextAreaElement).setSelectionRange(13, 13);
- await textarea.trigger("select");
+ await textarea.trigger("keyup");
await flushPromises();
- await textarea.trigger("keydown", { key: "Escape" });
+ mention.vm.$emit("update:show", true);
+ await textarea.trigger("keydown", { key: "Enter" });
+ mention.vm.$emit("update:value", "Inspect [e1] ");
+ mention.vm.$emit("update:show", false);
await flushPromises();
- expect(wrapper.find('[data-testid="dom-ref-autocomplete"]').exists()).toBe(
- false
- );
+ expect(mockRunAgentLoop).not.toHaveBeenCalled();
+ expect(getTextareaValue(wrapper)).toBe("Inspect [e1] ");
await textarea.trigger("keydown", { key: "Enter" });
await flushPromises();
diff --git a/frontend/src/plugins/agent/components/AgentInput.vue b/frontend/src/plugins/agent/components/AgentInput.vue
index 5c40922aa2..6d69ce181e 100644
--- a/frontend/src/plugins/agent/components/AgentInput.vue
+++ b/frontend/src/plugins/agent/components/AgentInput.vue
@@ -1,6 +1,7 @@
<script setup lang="ts">
+import { type InputInst, NButton, NMention } from "naive-ui";
import { v4 as uuidv4 } from "uuid";
-import { computed, nextTick, ref, watch } from "vue";
+import { computed, h, ref, watch } from "vue";
import { useI18n } from "vue-i18n";
import { useRoute, useRouter } from "vue-router";
import type { DomRefSuggestion } from "../dom";
@@ -65,15 +66,27 @@ const isSendDisabled = computed(() => {
return !input.value.trim();
});
-const inputRef = ref<HTMLTextAreaElement>();
+type MentionInst = {
+ inputInstRef?: InputInst | null;
+};
+
+type DomRefMentionOption = {
+ label: string;
+ value: string;
+ suggestion: DomRefSuggestion;
+};
+
+const inputInstRef = ref<MentionInst | null>(null);
+const getTextareaEl = () =>
+ inputInstRef.value?.inputInstRef?.textareaElRef ?? null;
const domRefSuggestions = ref<DomRefSuggestion[]>([]);
const isDomRefMenuOpen = ref(false);
-const activeDomRefIndex = ref(0);
const selectionStart = ref(0);
const selectionEnd = ref(0);
let domRefRequestToken = 0;
-const DOM_REF_SUGGESTION_LIMIT = 8;
+const DOM_REF_PENDING_OPTION_SELECTOR =
+ ".n-base-select-menu .n-base-select-option--pending";
const normalizeSearchText = (value?: string) =>
value?.toLowerCase().trim() ?? "";
@@ -116,17 +129,8 @@ const activeDomRefQuery = computed(() =>
getDomRefQuery(input.value, selectionStart.value, selectionEnd.value)
);
-const filteredDomRefSuggestions = computed(() => {
- const query = activeDomRefQuery.value?.query ?? "";
- return domRefSuggestions.value
- .filter((suggestion: DomRefSuggestion) =>
- matchDomRefSuggestion(suggestion, query)
- )
- .slice(0, DOM_REF_SUGGESTION_LIMIT);
-});
-
const updateSelection = () => {
- const textarea = inputRef.value;
+ const textarea = getTextareaEl();
if (!textarea) {
return;
}
@@ -134,23 +138,30 @@ const updateSelection = () => {
selectionEnd.value = textarea.selectionEnd ?? selectionStart.value;
};
-const closeDomRefMenu = () => {
- isDomRefMenuOpen.value = false;
- activeDomRefIndex.value = 0;
-};
+const filteredDomRefSuggestions = computed(() => {
+ const query = activeDomRefQuery.value?.query ?? "";
+ return domRefSuggestions.value.filter((suggestion: DomRefSuggestion) =>
+ matchDomRefSuggestion(suggestion, query)
+ );
+});
-const openDomRefMenu = () => {
- isDomRefMenuOpen.value = true;
- activeDomRefIndex.value = 0;
-};
+const domRefMentionOptions = computed<DomRefMentionOption[]>(() =>
+ filteredDomRefSuggestions.value.map((suggestion) => ({
+ label: `[${suggestion.ref}] ${suggestion.label}`,
+ value: `[${suggestion.ref}]`,
+ suggestion,
+ }))
+);
const loadDomRefSuggestions = async () => {
const query = activeDomRefQuery.value;
if (!query) {
- closeDomRefMenu();
domRefSuggestions.value = [];
return;
}
+ if (domRefSuggestions.value.length > 0) {
+ return;
+ }
const requestToken = ++domRefRequestToken;
const suggestions = await lazyExtractDomRefSuggestions();
@@ -159,74 +170,36 @@ const loadDomRefSuggestions = async () => {
}
domRefSuggestions.value = suggestions;
- if (filteredDomRefSuggestions.value.length > 0) {
- openDomRefMenu();
- return;
- }
- closeDomRefMenu();
+ getTextareaEl()?.dispatchEvent(new Event("input", { bubbles: true }));
};
-const selectDomRefSuggestion = async (suggestion: DomRefSuggestion) => {
- const query = activeDomRefQuery.value;
- const textarea = inputRef.value;
- if (!query || !textarea) {
- return;
- }
-
- const before = input.value.slice(0, query.start);
- const after = input.value.slice(query.end);
- const token = `[${suggestion.ref}]`;
- const suffix = after.startsWith(" ") ? "" : " ";
- const nextValue = `${before}${token}${suffix}${after}`;
- const caret = before.length + token.length + suffix.length;
-
- input.value = nextValue;
- closeDomRefMenu();
- await nextTick();
- textarea.focus();
- textarea.setSelectionRange(caret, caret);
- updateSelection();
+const handleDomRefMenuShow = (show: boolean) => {
+ isDomRefMenuOpen.value = show;
};
-const moveDomRefSelection = (offset: number) => {
- const total = filteredDomRefSuggestions.value.length;
- if (total === 0) {
- return;
- }
- activeDomRefIndex.value = (activeDomRefIndex.value + offset + total) % total;
+const scrollPendingDomRefOptionIntoView = () => {
+ window.setTimeout(() => {
+ document
+ .querySelector<HTMLElement>(DOM_REF_PENDING_OPTION_SELECTOR)
+ ?.scrollIntoView({ block: "nearest" });
+ }, 0);
};
const handleTextareaKeydown = async (event: KeyboardEvent) => {
if (isDomRefMenuOpen.value) {
- if (event.key === "ArrowDown") {
- event.preventDefault();
- moveDomRefSelection(1);
- return;
- }
- if (event.key === "ArrowUp") {
- event.preventDefault();
- moveDomRefSelection(-1);
- return;
- }
- if (event.key === "Escape") {
- event.preventDefault();
- closeDomRefMenu();
- return;
- }
- if (event.key === "Enter") {
- event.preventDefault();
- const suggestion =
- filteredDomRefSuggestions.value[activeDomRefIndex.value];
- if (suggestion) {
- await selectDomRefSuggestion(suggestion);
- } else {
- closeDomRefMenu();
- }
- return;
+ if (event.key === "ArrowUp" || event.key === "ArrowDown") {
+ scrollPendingDomRefOptionIntoView();
}
+ return;
}
- if (event.key === "Enter" && !event.shiftKey) {
+ if (
+ event.key === "Enter" &&
+ !event.shiftKey &&
+ !event.altKey &&
+ !event.ctrlKey &&
+ !event.metaKey
+ ) {
event.preventDefault();
await send();
}
@@ -238,6 +211,19 @@ const formatDomRefSuggestionMeta = (suggestion: DomRefSuggestion) => {
.join(" · ");
};
+const renderDomRefMentionLabel = (option: DomRefMentionOption) => {
+ const suggestion = option.suggestion;
+ const meta = formatDomRefSuggestionMeta(suggestion);
+
+ return h("div", { class: "flex flex-col text-sm" }, [
+ h("div", { class: "flex items-center gap-x-2 text-gray-800" }, [
+ h("span", { class: "font-medium" }, `[${suggestion.ref}]`),
+ h("span", { class: "truncate" }, suggestion.label),
+ ]),
+ meta ? h("div", { class: "mt-1 text-xs text-gray-500" }, meta) : null,
+ ]);
+};
+
const getCurrentPageSnapshot = () => ({
path: route.fullPath,
title: document.title,
@@ -561,7 +547,7 @@ watch(
() => isCurrentChatRunning.value,
(running) => {
if (running) {
- closeDomRefMenu();
+ isDomRefMenuOpen.value = false;
}
}
);
@@ -641,64 +627,51 @@ watch(
</button>
</div>
- <div v-else class="flex items-end gap-x-2">
- <div class="relative min-w-0 flex-1">
- <textarea
- ref="inputRef"
- v-model="input"
- rows="1"
- :placeholder="inputPlaceholder"
- class="block w-full resize-none rounded-md border px-3 py-2 text-sm focus:outline-none focus:ring-1 focus:ring-blue-500 disabled:bg-gray-50"
- :disabled="isCurrentChatRunning"
- @click="updateSelection"
- @blur="closeDomRefMenu"
- @input="updateSelection"
- @keyup="updateSelection"
- @select="updateSelection"
- @keydown.exact="handleTextareaKeydown"
- />
- <div
- v-if="isDomRefMenuOpen"
- data-testid="dom-ref-autocomplete"
- class="absolute bottom-full left-0 z-10 mb-2 w-full overflow-hidden rounded-md border bg-white shadow-lg"
- >
- <button
- v-for="(suggestion, index) in filteredDomRefSuggestions"
- :key="suggestion.ref"
- type="button"
- data-testid="dom-ref-autocomplete-item"
- class="flex w-full flex-col px-3 py-2 text-left text-sm hover:bg-gray-50"
- :class="index === activeDomRefIndex ? 'bg-blue-50' : 'bg-white'"
- @mousedown.prevent="selectDomRefSuggestion(suggestion)"
- >
- <div class="flex items-center gap-x-2 text-gray-800">
- <span class="font-medium">[{{ suggestion.ref }}]</span>
- <span class="truncate">{{ suggestion.label }}</span>
- </div>
- <div
- v-if="formatDomRefSuggestionMeta(suggestion)"
- class="mt-1 text-xs text-gray-500"
- >
- {{ formatDomRefSuggestionMeta(suggestion) }}
- </div>
- </button>
- </div>
- </div>
- <button
+ <div v-else class="flex items-end gap-x-2" data-agent-input-row>
+ <NMention
+ ref="inputInstRef"
+ v-model:value="input"
+ type="textarea"
+ size="small"
+ class="w-full"
+ :autosize="{
+ minRows: 1,
+ maxRows: 6,
+ }"
+ :placeholder="inputPlaceholder"
+ :disabled="isCurrentChatRunning"
+ prefix="@"
+ :options="domRefMentionOptions"
+ :filter="() => true"
+ placement="top-start"
+ to="body"
+ :scrollbar-props="{ containerStyle: { maxHeight: '320px' } }"
+ @update:show="handleDomRefMenuShow"
+ @click="updateSelection"
+ @input="updateSelection"
+ @keyup="updateSelection"
+ @keydown.capture="handleTextareaKeydown"
+ :render-label="renderDomRefMentionLabel"
+ />
+ <NButton
v-if="agentStore.loading"
- class="rounded-md bg-red-500 px-3 py-2 text-sm text-white hover:bg-red-600"
+ type="error"
+ size="small"
+ class="whitespace-nowrap"
@click="agentStore.cancel(currentChat?.id)"
>
{{ $t("agent.stop") }}
- </button>
- <button
+ </NButton>
+ <NButton
v-else
- class="rounded-md bg-blue-500 px-3 py-2 text-sm text-white hover:bg-blue-600 disabled:opacity-50"
+ type="primary"
+ size="small"
+ class="whitespace-nowrap"
:disabled="isSendDisabled"
@click="send"
>
{{ sendLabel }}
- </button>
+ </NButton>
</div>
</div>
</template>
diff --git a/frontend/src/plugins/agent/components/AgentWindow.test.ts b/frontend/src/plugins/agent/components/AgentWindow.test.ts
index 5093182dad..395c2c54fb 100644
--- a/frontend/src/plugins/agent/components/AgentWindow.test.ts
+++ b/frontend/src/plugins/agent/components/AgentWindow.test.ts
@@ -52,8 +52,8 @@ const i18n = createI18n({
"archive-chat": "Archive",
"unarchive-chat": "Unarchive",
"delete-chat": "Delete",
- "show-archived-chats": "Show archived chats",
- "hide-archived-chats": "Hide archived chats",
+ "active-only-chats": "Active only",
+ "archived-only-chats": "Archived only",
"archive-chat-confirmation": "Archive this chat?",
"delete-chat-confirmation": "Delete this chat?",
"chat-default-title": "New chat",
@@ -268,27 +268,94 @@ describe("AgentWindow", () => {
expect(wrapper.find("aside").attributes("style")).toContain("width: 180px");
});
- test("archives and deletes chats through popconfirm", async () => {
+ test("shows mode-specific sidebar actions for active and archived chats", async () => {
const { store, wrapper } = mountAgentWindow();
const originalChatId = store.currentChatId!;
const secondChat = store.createChat({ title: "Disposable thread" });
store.setCurrentChat(secondChat.id);
await nextTick();
- const popconfirms = wrapper.findAllComponents(NPopconfirm);
- expect(popconfirms).toHaveLength(2);
+ const actionArea = () => wrapper.find("[data-agent-chat-sidebar-actions]");
+ const modeToggle = () => wrapper.find("[data-agent-chat-list-mode]");
+ const buttonLabels = () =>
+ actionArea()
+ .findAll("button")
+ .map((button) => button.text());
- await popconfirms[0].vm.$emit("positive-click");
+ expect(modeToggle().text()).toBe("");
+ expect(modeToggle().attributes("aria-label")).toBe("Active only");
+ expect(buttonLabels()).toEqual(["Archive", ""]);
+ expect(
+ actionArea()
+ .findAll("button")
+ .at(-1)
+ ?.attributes("data-agent-chat-list-mode")
+ ).toBe("");
+ expect(modeToggle().classes()).toContain("ml-auto");
+ expect(modeToggle().find("svg").exists()).toBe(true);
+ expect(wrapper.findAllComponents(NPopconfirm)).toHaveLength(1);
+
+ await wrapper.findComponent(NPopconfirm).vm.$emit("positive-click");
await nextTick();
+
expect(store.getChat(secondChat.id)?.archived).toBe(true);
+ expect(store.currentChatId).toBe(originalChatId);
- store.setCurrentChat(originalChatId);
- await nextTick();
- const deletePopconfirm = wrapper.findAllComponents(NPopconfirm)[1];
- await deletePopconfirm.vm.$emit("positive-click");
+ await modeToggle().trigger("click");
await nextTick();
- expect(store.getChat(originalChatId)).toBeNull();
+ expect(modeToggle().text()).toBe("");
+ expect(modeToggle().attributes("aria-label")).toBe("Archived only");
expect(store.currentChatId).toBe(secondChat.id);
+ expect(buttonLabels()).toEqual(["Unarchive", "Delete", ""]);
+ expect(
+ actionArea()
+ .findAll("button")
+ .at(-1)
+ ?.attributes("data-agent-chat-list-mode")
+ ).toBe("");
+ expect(modeToggle().classes()).toContain("ml-auto");
+ expect(modeToggle().find("svg").exists()).toBe(true);
+ expect(wrapper.findAllComponents(NPopconfirm)).toHaveLength(1);
+ });
+
+ test("unarchives and deletes chats from archived-only mode", async () => {
+ const { store, wrapper } = mountAgentWindow();
+ const originalChatId = store.currentChatId!;
+ const archivedChat = store.createChat({ title: "Disposable thread" });
+ store.setCurrentChat(archivedChat.id);
+ await nextTick();
+
+ await wrapper.findComponent(NPopconfirm).vm.$emit("positive-click");
+ await nextTick();
+ await wrapper.find("[data-agent-chat-list-mode]").trigger("click");
+ await nextTick();
+
+ await wrapper.find("[data-agent-unarchive-chat]").trigger("click");
+ await nextTick();
+
+ expect(store.getChat(archivedChat.id)?.archived).toBe(false);
+ expect(
+ wrapper.find("[data-agent-chat-list-mode]").attributes("aria-label")
+ ).toBe("Active only");
+ expect(wrapper.find("[data-agent-chat-list-mode]").text()).toBe("");
+ expect(store.currentChatId).toBe(archivedChat.id);
+
+ await wrapper.findComponent(NPopconfirm).vm.$emit("positive-click");
+ await nextTick();
+ await wrapper.find("[data-agent-chat-list-mode]").trigger("click");
+ await nextTick();
+
+ expect(store.currentChatId).toBe(archivedChat.id);
+
+ await wrapper.findComponent(NPopconfirm).vm.$emit("positive-click");
+ await nextTick();
+
+ expect(store.getChat(archivedChat.id)).toBeNull();
+ expect(
+ wrapper.find("[data-agent-chat-list-mode]").attributes("aria-label")
+ ).toBe("Active only");
+ expect(wrapper.find("[data-agent-chat-list-mode]").text()).toBe("");
+ expect(store.currentChatId).toBe(originalChatId);
});
});
diff --git a/frontend/src/plugins/agent/components/AgentWindow.vue b/frontend/src/plugins/agent/components/AgentWindow.vue
index f8e57163cb..bc66236e5d 100644
--- a/frontend/src/plugins/agent/components/AgentWindow.vue
+++ b/frontend/src/plugins/agent/components/AgentWindow.vue
@@ -1,4 +1,5 @@
<script setup lang="ts">
+import { ArchiveIcon, InboxIcon } from "lucide-vue-next";
import { NInput, NPopconfirm } from "naive-ui";
import {
computed,
@@ -112,16 +113,16 @@ const windowStyle = computed(() => ({
height: `${displayWindowState.value.size.height}px`,
}));
-const showArchivedChats = ref(false);
+const showArchivedOnly = ref(false);
const displayedChats = computed(() =>
- agentStore.orderedChats.filter((chat) => {
- return (
- showArchivedChats.value ||
- !chat.archived ||
- chat.id === agentStore.currentChatId
- );
- })
+ agentStore.orderedChats.filter(
+ (chat) => chat.archived === showArchivedOnly.value
+ )
);
+const isCurrentChatInDisplayedMode = computed(() => {
+ const chat = agentStore.currentChat;
+ return !!chat && chat.archived === showArchivedOnly.value;
+});
const currentChatStatusLabel = computed(() => {
const chat = agentStore.currentChat;
if (!chat) {
@@ -209,8 +210,42 @@ const getChatLabel = (chat: AgentChatRecord) => {
: baseLabel;
};
-function toggleArchivedChats() {
- showArchivedChats.value = !showArchivedChats.value;
+function selectFirstDisplayedChat() {
+ const firstDisplayedChat = displayedChats.value[0];
+ if (!firstDisplayedChat || !agentStore.canSelectChat(firstDisplayedChat.id)) {
+ return false;
+ }
+ agentStore.setCurrentChat(firstDisplayedChat.id);
+ return agentStore.currentChatId === firstDisplayedChat.id;
+}
+
+function ensureCurrentChatMatchesDisplayedMode(
+ options: { fallbackToActiveWhenEmpty?: boolean } = {}
+) {
+ if (isCurrentChatInDisplayedMode.value) {
+ return;
+ }
+ if (selectFirstDisplayedChat()) {
+ return;
+ }
+ if (showArchivedOnly.value) {
+ if (!options.fallbackToActiveWhenEmpty) {
+ return;
+ }
+ showArchivedOnly.value = false;
+ if (isCurrentChatInDisplayedMode.value || selectFirstDisplayedChat()) {
+ return;
+ }
+ }
+ if (agentStore.hasRunningChat) {
+ return;
+ }
+ agentStore.createChat({ page: getCurrentPageSnapshot() });
+}
+
+function toggleChatListMode() {
+ showArchivedOnly.value = !showArchivedOnly.value;
+ ensureCurrentChatMatchesDisplayedMode();
}
const isRenamingCurrentChat = ref(false);
@@ -280,9 +315,11 @@ function toggleArchiveCurrentChat() {
}
if (chat.archived) {
agentStore.unarchiveChat(chat.id);
+ ensureCurrentChatMatchesDisplayedMode({ fallbackToActiveWhenEmpty: true });
return;
}
agentStore.archiveChat(chat.id);
+ ensureCurrentChatMatchesDisplayedMode();
}
function deleteCurrentChat() {
@@ -291,6 +328,7 @@ function deleteCurrentChat() {
return;
}
agentStore.deleteChat(chat.id);
+ ensureCurrentChatMatchesDisplayedMode({ fallbackToActiveWhenEmpty: true });
}
const isDragging = ref(false);
@@ -654,48 +692,68 @@ onBeforeUnmount(() => {
<div class="border-t border-gray-200 px-3 py-3">
<div class="flex flex-col gap-y-2">
- <div class="flex flex-wrap gap-x-2 gap-y-2">
- <button
- v-if="agentStore.currentChat?.archived"
- class="rounded-md border px-2 py-1.5 text-xs font-medium text-gray-600 hover:bg-white"
- @click="toggleArchiveCurrentChat"
- >
- {{ $t("agent.unarchive-chat") }}
- </button>
- <NPopconfirm
- v-else
- @positive-click="toggleArchiveCurrentChat"
- >
- <template #trigger>
- <button
- class="rounded-md border px-2 py-1.5 text-xs font-medium text-gray-600 hover:bg-white"
- >
- {{ $t("agent.archive-chat") }}
- </button>
- </template>
- {{ $t("agent.archive-chat-confirmation") }}
- </NPopconfirm>
- <NPopconfirm
- @positive-click="deleteCurrentChat"
- >
- <template #trigger>
- <button
- class="rounded-md border px-2 py-1.5 text-xs font-medium text-red-600 hover:bg-red-50"
- >
- {{ $t("agent.delete-chat") }}
- </button>
- </template>
- {{ $t("agent.delete-chat-confirmation") }}
- </NPopconfirm>
+ <div
+ class="flex flex-wrap gap-x-2 gap-y-2"
+ data-agent-chat-sidebar-actions
+ >
+ <template v-if="isCurrentChatInDisplayedMode">
+ <button
+ v-if="showArchivedOnly"
+ class="rounded-md border px-2 py-1.5 text-xs font-medium text-gray-600 hover:bg-white"
+ data-agent-unarchive-chat
+ @click="toggleArchiveCurrentChat"
+ >
+ {{ $t("agent.unarchive-chat") }}
+ </button>
+ <NPopconfirm
+ v-else
+ @positive-click="toggleArchiveCurrentChat"
+ >
+ <template #trigger>
+ <button
+ class="rounded-md border px-2 py-1.5 text-xs font-medium text-gray-600 hover:bg-white"
+ data-agent-archive-chat
+ >
+ {{ $t("agent.archive-chat") }}
+ </button>
+ </template>
+ {{ $t("agent.archive-chat-confirmation") }}
+ </NPopconfirm>
+ <NPopconfirm
+ v-if="showArchivedOnly"
+ @positive-click="deleteCurrentChat"
+ >
+ <template #trigger>
+ <button
+ class="rounded-md border px-2 py-1.5 text-xs font-medium text-red-600 hover:bg-red-50"
+ data-agent-delete-chat
+ >
+ {{ $t("agent.delete-chat") }}
+ </button>
+ </template>
+ {{ $t("agent.delete-chat-confirmation") }}
+ </NPopconfirm>
+ </template>
<button
- class="rounded-md border px-2 py-1.5 text-xs font-medium text-gray-600 hover:bg-white"
- @click="toggleArchivedChats"
+ class="ml-auto inline-flex items-center rounded-md border p-1.5 text-xs font-medium text-gray-600 hover:bg-white"
+ :aria-label="
+ showArchivedOnly
+ ? $t('agent.archived-only-chats')
+ : $t('agent.active-only-chats')
+ "
+ :title="
+ showArchivedOnly
+ ? $t('agent.archived-only-chats')
+ : $t('agent.active-only-chats')
+ "
+ data-agent-chat-list-mode
+ @click="toggleChatListMode"
>
- {{
- showArchivedChats
- ? $t("agent.hide-archived-chats")
- : $t("agent.show-archived-chats")
- }}
+ <component
+ :is="showArchivedOnly ? ArchiveIcon : InboxIcon"
+ class="h-3.5 w-3.5"
+ aria-hidden="true"
+ />
</button>
</div>
</div>