Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
feat: refine page agent chat management and sidebar UX (#19715)
p0ny17798601516d
diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.jsonindex 2279912614..53d33e62e5 100644--- a/frontend/src/locales/en-US.json+++ b/frontend/src/locales/en-US.json@@ -2972,24 +2972,33 @@"result": "Result:","stop": "Stop","interrupted": "Interrupted",- "retry-last-turn": "Retry last turn",+ "retry-last-chat-turn": "Retry last turn","interrupted-retry-hint": "Retry reruns the interrupted turn with the current page state.",- "new-thread": "New thread",- "reset-thread": "Reset thread",- "thread-select-label": "Thread",- "thread-default-title": "New thread",- "thread-status-idle": "Idle",- "thread-status-running": "Running",- "thread-status-awaiting-user": "Awaiting input",- "thread-status-error": "Error",- "thread-status-interrupted": "Interrupted",- "thread-total-tokens": "Tokens used: {count}",+ "new-chat": "New chat",+ "rename-chat-placeholder": "Enter a chat name",+ "archive-chat": "Archive",+ "unarchive-chat": "Unarchive",+ "delete-chat": "Delete",+ "show-archived-chats": "Show archived chats",+ "hide-archived-chats": "Hide archived chats",+ "archive-chat-confirmation": "Archive this chat?",+ "delete-chat-confirmation": "Delete this chat?",+ "chat-list-label": "Chats",+ "chat-switch-locked": "Finish the running chat before switching to another one.",+ "chat-default-title": "New chat",+ "chat-archived-label": "Archived",+ "chat-status-idle": "Idle",+ "chat-status-running": "Running",+ "chat-status-awaiting-user": "Awaiting input",+ "chat-status-error": "Error",+ "chat-status-interrupted": "Interrupted",+ "chat-total-tokens": "Tokens used: {count}","reply": "Reply","confirm": "Confirm","cancel": "Cancel",- "pending-input-hint": "Reply below to continue this thread.",- "pending-confirm-hint": "Choose confirm or cancel to continue this thread.",- "pending-choose-hint": "Choose an option to continue this thread.",+ "pending-input-hint": "Reply below to continue this chat.",+ "pending-confirm-hint": "Choose confirm or cancel to continue this chat.",+ "pending-choose-hint": "Choose an option to continue this chat.","tool-ask-user": "Awaiting your response","tool-ask-user-input": "Input requested","tool-ask-user-confirm": "Confirmation requested",diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.jsonindex b490c27ddf..1a2662fa6d 100644--- a/frontend/src/locales/es-ES.json+++ b/frontend/src/locales/es-ES.json@@ -2481,24 +2481,33 @@"result": "Resultado:","stop": "Detener","interrupted": "Interrumpido",- "retry-last-turn": "Reintentar el último turno",+ "retry-last-chat-turn": "Reintentar el último turno","interrupted-retry-hint": "Reintentar vuelve a ejecutar el turno interrumpido con el estado actual de la página.",- "new-thread": "Nuevo hilo",- "reset-thread": "Restablecer hilo",- "thread-select-label": "Hilo",- "thread-default-title": "Nuevo hilo",- "thread-status-idle": "Inactivo",- "thread-status-running": "En ejecución",- "thread-status-awaiting-user": "Esperando entrada",- "thread-status-error": "Error",- "thread-status-interrupted": "Interrumpido",- "thread-total-tokens": "Tokens usados: {count}",+ "new-chat": "Nuevo chat",+ "rename-chat-placeholder": "Introduce un nombre para el chat",+ "archive-chat": "Archivar",+ "unarchive-chat": "Desarchivar",+ "delete-chat": "Eliminar",+ "show-archived-chats": "Mostrar chats archivados",+ "hide-archived-chats": "Ocultar chats archivados",+ "archive-chat-confirmation": "¿Archivar este chat?",+ "delete-chat-confirmation": "¿Eliminar este chat?",+ "chat-list-label": "Chats",+ "chat-switch-locked": "Finaliza el chat en ejecución antes de cambiar a otro.",+ "chat-default-title": "Nuevo chat",+ "chat-archived-label": "Archivado",+ "chat-status-idle": "Inactivo",+ "chat-status-running": "En ejecución",+ "chat-status-awaiting-user": "Esperando entrada",+ "chat-status-error": "Error",+ "chat-status-interrupted": "Interrumpido",+ "chat-total-tokens": "Tokens usados: {count}","reply": "Responder","confirm": "Confirmar","cancel": "Cancelar",- "pending-input-hint": "Responde abajo para continuar este hilo.",- "pending-confirm-hint": "Elige confirmar o cancelar para continuar este hilo.",- "pending-choose-hint": "Elige una opción para continuar este hilo.",+ "pending-input-hint": "Responde abajo para continuar este chat.",+ "pending-confirm-hint": "Elige confirmar o cancelar para continuar este chat.",+ "pending-choose-hint": "Elige una opción para continuar este chat.","tool-ask-user": "Esperando tu respuesta","tool-ask-user-input": "Se requiere una entrada","tool-ask-user-confirm": "Se requiere confirmación",diff --git a/frontend/src/locales/ja-JP.json b/frontend/src/locales/ja-JP.jsonindex 5b493f0188..d1c37df474 100644--- a/frontend/src/locales/ja-JP.json+++ b/frontend/src/locales/ja-JP.json@@ -2481,24 +2481,33 @@"result": "結果:","stop": "停止","interrupted": "中断",- "retry-last-turn": "直前のターンを再試行",+ "retry-last-chat-turn": "直前のターンを再試行","interrupted-retry-hint": "再試行すると、現在のページ状態で中断されたターンをやり直します。",- "new-thread": "新しいスレッド",- "reset-thread": "スレッドをリセット",- "thread-select-label": "スレッド",- "thread-default-title": "新しいスレッド",- "thread-status-idle": "待機中",- "thread-status-running": "実行中",- "thread-status-awaiting-user": "入力待ち",- "thread-status-error": "エラー",- "thread-status-interrupted": "中断",- "thread-total-tokens": "使用済みトークン: {count}",+ "new-chat": "新しいチャット",+ "rename-chat-placeholder": "チャット名を入力してください",+ "archive-chat": "アーカイブ",+ "unarchive-chat": "アーカイブ解除",+ "delete-chat": "削除",+ "show-archived-chats": "アーカイブ済みのチャットを表示",+ "hide-archived-chats": "アーカイブ済みのチャットを非表示",+ "archive-chat-confirmation": "このチャットをアーカイブしますか?",+ "delete-chat-confirmation": "このチャットを削除しますか?",+ "chat-list-label": "チャット",+ "chat-switch-locked": "別のチャットに切り替える前に、実行中のチャットを完了してください。",+ "chat-default-title": "新しいチャット",+ "chat-archived-label": "アーカイブ済み",+ "chat-status-idle": "待機中",+ "chat-status-running": "実行中",+ "chat-status-awaiting-user": "入力待ち",+ "chat-status-error": "エラー",+ "chat-status-interrupted": "中断",+ "chat-total-tokens": "使用済みトークン: {count}","reply": "返信","confirm": "確認","cancel": "キャンセル",- "pending-input-hint": "このスレッドを続けるには、下に返信してください。",- "pending-confirm-hint": "このスレッドを続けるには、確認またはキャンセルを選択してください。",- "pending-choose-hint": "このスレッドを続けるには、選択肢を選んでください。",+ "pending-input-hint": "このチャットを続けるには、下に返信してください。",+ "pending-confirm-hint": "このチャットを続けるには、確認またはキャンセルを選択してください。",+ "pending-choose-hint": "このチャットを続けるには、選択肢を選んでください。","tool-ask-user": "あなたの回答を待っています","tool-ask-user-input": "入力が必要です","tool-ask-user-confirm": "確認が必要です",diff --git a/frontend/src/locales/vi-VN.json b/frontend/src/locales/vi-VN.jsonindex 36bc1b064f..ead7179e23 100644--- a/frontend/src/locales/vi-VN.json+++ b/frontend/src/locales/vi-VN.json@@ -2481,24 +2481,33 @@"result": "Kết quả:","stop": "Dừng","interrupted": "Bị gián đoạn",- "retry-last-turn": "Thử lại lượt trước",+ "retry-last-chat-turn": "Thử lại lượt trước","interrupted-retry-hint": "Thử lại sẽ chạy lại lượt bị gián đoạn với trạng thái trang hiện tại.",- "new-thread": "Luồng mới",- "reset-thread": "Đặt lại luồng",- "thread-select-label": "Luồng",- "thread-default-title": "Luồng mới",- "thread-status-idle": "Rảnh",- "thread-status-running": "Đang chạy",- "thread-status-awaiting-user": "Đang chờ nhập",- "thread-status-error": "Lỗi",- "thread-status-interrupted": "Bị gián đoạn",- "thread-total-tokens": "Token đã dùng: {count}",+ "new-chat": "Chat mới",+ "rename-chat-placeholder": "Nhập tên chat",+ "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ữ",+ "archive-chat-confirmation": "Lưu trữ chat này?",+ "delete-chat-confirmation": "Xóa chat này?",+ "chat-list-label": "Các chat",+ "chat-switch-locked": "Hãy hoàn tất chat đang chạy trước khi chuyển sang chat khác.",+ "chat-default-title": "Chat mới",+ "chat-archived-label": "Đã lưu trữ",+ "chat-status-idle": "Rảnh",+ "chat-status-running": "Đang chạy",+ "chat-status-awaiting-user": "Đang chờ nhập",+ "chat-status-error": "Lỗi",+ "chat-status-interrupted": "Bị gián đoạn",+ "chat-total-tokens": "Token đã dùng: {count}","reply": "Trả lời","confirm": "Xác nhận","cancel": "Hủy",- "pending-input-hint": "Hãy trả lời bên dưới để tiếp tục luồng này.",- "pending-confirm-hint": "Chọn xác nhận hoặc hủy để tiếp tục luồng này.",- "pending-choose-hint": "Chọn một tùy chọn để tiếp tục luồng này.",+ "pending-input-hint": "Hãy trả lời bên dưới để tiếp tục chat này.",+ "pending-confirm-hint": "Chọn xác nhận hoặc hủy để tiếp tục chat này.",+ "pending-choose-hint": "Chọn một tùy chọn để tiếp tục chat này.","tool-ask-user": "Đang chờ phản hồi của bạn","tool-ask-user-input": "Cần nhập dữ liệu","tool-ask-user-confirm": "Cần xác nhận",diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.jsonindex 7b84b9fb26..a106f2d83a 100644--- a/frontend/src/locales/zh-CN.json+++ b/frontend/src/locales/zh-CN.json@@ -2972,24 +2972,33 @@"result": "结果:","stop": "停止","interrupted": "已中断",- "retry-last-turn": "重试上一轮",+ "retry-last-chat-turn": "重试上一轮","interrupted-retry-hint": "重试会基于当前页面状态重新运行已中断的这一轮。",- "new-thread": "新线程",- "reset-thread": "重置线程",- "thread-select-label": "线程",- "thread-default-title": "新线程",- "thread-status-idle": "空闲",- "thread-status-running": "运行中",- "thread-status-awaiting-user": "等待输入",- "thread-status-error": "错误",- "thread-status-interrupted": "已中断",- "thread-total-tokens": "已用令牌:{count}",+ "new-chat": "新聊天",+ "rename-chat-placeholder": "输入聊天名称",+ "archive-chat": "归档",+ "unarchive-chat": "取消归档",+ "delete-chat": "删除",+ "show-archived-chats": "显示已归档聊天",+ "hide-archived-chats": "隐藏已归档聊天",+ "archive-chat-confirmation": "要归档这个聊天吗?",+ "delete-chat-confirmation": "要删除这个聊天吗?",+ "chat-list-label": "聊天",+ "chat-switch-locked": "请先完成当前运行中的聊天,再切换到其他聊天。",+ "chat-default-title": "新聊天",+ "chat-archived-label": "已归档",+ "chat-status-idle": "空闲",+ "chat-status-running": "运行中",+ "chat-status-awaiting-user": "等待输入",+ "chat-status-error": "错误",+ "chat-status-interrupted": "已中断",+ "chat-total-tokens": "已用令牌:{count}","reply": "回复","confirm": "确认","cancel": "取消",- "pending-input-hint": "请在下方回复以继续当前线程。",- "pending-confirm-hint": "请选择确认或取消以继续当前线程。",- "pending-choose-hint": "请选择一个选项以继续当前线程。",+ "pending-input-hint": "请在下方回复以继续当前聊天。",+ "pending-confirm-hint": "请选择确认或取消以继续当前聊天。",+ "pending-choose-hint": "请选择一个选项以继续当前聊天。","tool-ask-user": "等待你的回复","tool-ask-user-input": "需要输入","tool-ask-user-confirm": "需要确认",diff --git a/frontend/src/plugins/agent/components/AgentChat.vue b/frontend/src/plugins/agent/components/AgentChat.vueindex f392be427d..a78b8f05a1 100644--- a/frontend/src/plugins/agent/components/AgentChat.vue+++ b/frontend/src/plugins/agent/components/AgentChat.vue@@ -52,7 +52,7 @@ function getToolResult(}watch(- [() => agentStore.currentThreadId, () => agentStore.messages.length],+ [() => agentStore.currentChatId, () => agentStore.messages.length],async () => {await nextTick();if (chatContainer.value) {diff --git a/frontend/src/plugins/agent/components/AgentInput.test.ts b/frontend/src/plugins/agent/components/AgentInput.test.tsindex 88ecd25173..582bc5540e 100644--- a/frontend/src/plugins/agent/components/AgentInput.test.ts+++ b/frontend/src/plugins/agent/components/AgentInput.test.ts@@ -78,7 +78,7 @@ const i18n = createI18n({},agent: {interrupted: "Interrupted",- "retry-last-turn": "Retry last turn",+ "retry-last-chat-turn": "Retry last turn","interrupted-retry-hint":"Retry reruns the interrupted turn with the current page state.","input-placeholder": "Ask anything...",@@ -87,10 +87,10 @@ const i18n = createI18n({stop: "Stop",confirm: "Confirm",cancel: "Cancel",- "pending-input-hint": "Reply below to continue this thread.",+ "pending-input-hint": "Reply below to continue this chat.","pending-confirm-hint":- "Choose confirm or cancel to continue this thread.",- "pending-choose-hint": "Choose an option to continue this thread.",+ "Choose confirm or cancel to continue this chat.",+ "pending-choose-hint": "Choose an option to continue this chat.",},},},@@ -128,12 +128,12 @@ describe("AgentInput", () => {document.title = "Demo Page";});- test("submits pending input as a tool result and resumes the same thread", async () => {+ test("submits pending input as a tool result and resumes the same chat", async () => {const store = useAgentStore();- const threadId = store.currentThreadId!;+ const chatId = store.currentChatId!;store.addMessage({- threadId,+ chatId,role: "assistant",toolCalls: [{@@ -146,7 +146,7 @@ describe("AgentInput", () => {},],});- store.awaitUser(threadId, {+ store.awaitUser(chatId, {toolCallId: "tool-ask",prompt: "Which project should I use?",kind: "input",@@ -179,7 +179,7 @@ describe("AgentInput", () => {await flushPromises();const toolMessages = store- .getMessages(threadId)+ .getMessages(chatId).filter((message) => message.role === "tool");expect(toolMessages).toHaveLength(1);expect(toolMessages[0].toolCallId).toBe("tool-ask");@@ -187,8 +187,8 @@ describe("AgentInput", () => {kind: "input",answer: "demo-project",});- expect(store.getPendingAsk(threadId)).toBeNull();- expect(store.currentThreadId).toBe(threadId);+ expect(store.getPendingAsk(chatId)).toBeNull();+ expect(store.currentChatId).toBe(chatId);expect(mockRunAgentLoop).toHaveBeenCalledTimes(1);const [messages] = mockRunAgentLoop.mock.calls[0];@@ -203,15 +203,15 @@ describe("AgentInput", () => {);});- test("resumes pending asks with the saved thread page snapshot", async () => {+ test("resumes pending asks with the current page snapshot", async () => {const store = useAgentStore();- const threadId = store.currentThreadId!;+ const chatId = store.currentChatId!;- store.updateThreadPage(threadId, {+ store.updateChatPage(chatId, {path: "/projects/original",title: "Original Page",});- store.awaitUser(threadId, {+ store.awaitUser(chatId, {toolCallId: "tool-ask",prompt: "Which project should I use?",kind: "input",@@ -236,18 +236,18 @@ describe("AgentInput", () => {await flushPromises();expect(mockBuildSystemPrompt).toHaveBeenCalledWith({- path: "/projects/original",- title: "Original Page",+ path: "/projects/other",+ title: "Other Page",});- expect(store.getThread(threadId)?.page).toEqual({- path: "/projects/original",- title: "Original Page",+ expect(store.getChat(chatId)?.page).toEqual({+ path: "/projects/other",+ title: "Other Page",});});- test("increments the current thread token total from loop usage", async () => {+ test("increments the current chat token total from loop usage", async () => {const store = useAgentStore();- const threadId = store.currentThreadId!;+ const chatId = store.currentChatId!;mockRunAgentLoop.mockResolvedValue({kind: "completed",@@ -266,15 +266,15 @@ describe("AgentInput", () => {await findButtonByText(wrapper, "Send")!.trigger("click");await flushPromises();- expect(store.getThread(threadId)?.totalTokensUsed).toBe(123);+ expect(store.getChat(chatId)?.totalTokensUsed).toBe(123);});- test("refreshes the saved thread page snapshot after navigate before a follow-up turn", async () => {+ test("refreshes the saved chat page snapshot after navigate before a follow-up turn", async () => {const store = useAgentStore();- const threadId = store.currentThreadId!;+ const chatId = store.currentChatId!;let runCount = 0;- store.updateThreadPage(threadId, {+ store.updateChatPage(chatId, {path: "/projects/original",title: "Original Page",});@@ -361,11 +361,11 @@ describe("AgentInput", () => {await wrapper.find("button").trigger("click");await flushPromises();- expect(store.getThread(threadId)?.page).toEqual({+ expect(store.getChat(chatId)?.page).toEqual({path: "/projects/navigated",title: "Navigated Page",});- expect(store.getPendingAsk(threadId)).toEqual({+ expect(store.getPendingAsk(chatId)).toEqual({toolCallId: "tool-ask",prompt: "Continue?",kind: "input",@@ -379,25 +379,25 @@ describe("AgentInput", () => {await flushPromises();expect(mockBuildSystemPrompt).toHaveBeenNthCalledWith(1, {- path: "/projects/original",- title: "Original Page",+ path: "/projects/demo",+ title: "Demo Page",});expect(mockBuildSystemPrompt).toHaveBeenNthCalledWith(2, {- path: "/projects/navigated",- title: "Navigated Page",+ path: "/projects/elsewhere",+ title: "Elsewhere Page",});});test("shows retry CTA and reruns interrupted turns from the last stable input", async () => {const store = useAgentStore();- const threadId = store.currentThreadId!;+ const chatId = store.currentChatId!;- store.updateThreadPage(threadId, {+ store.updateChatPage(chatId, {path: "/projects/original",title: "Original Page",});store.addMessage({- threadId,+ chatId,role: "user",content: "inspect this page",metadata: {@@ -405,7 +405,7 @@ describe("AgentInput", () => {},});store.addMessage({- threadId,+ chatId,role: "assistant",content: "Partial answer",metadata: {@@ -414,7 +414,7 @@ describe("AgentInput", () => {},});store.addMessage({- threadId,+ chatId,role: "tool",toolCallId: "tool-1",content: JSON.stringify({ partial: true }),@@ -423,8 +423,8 @@ describe("AgentInput", () => {runId: "run-1",},});- store.interruptRun(threadId);- store.getThread(threadId)!.runId = "run-1";+ store.interruptChatRun(chatId);+ store.getChat(chatId)!.runId = "run-1";mockRoute.fullPath = "/projects/current";document.title = "Current Page";@@ -473,16 +473,16 @@ describe("AgentInput", () => {);expect(store- .getMessages(threadId)+ .getMessages(chatId).some((message) => message.content === "Partial answer")).toBe(false);expect(store- .getMessages(threadId)+ .getMessages(chatId).some((message) => message.toolCallId === "tool-1")).toBe(false);- expect(store.getThread(threadId)?.interrupted).toBe(false);- expect(store.getThread(threadId)?.page).toEqual({+ expect(store.getChat(chatId)?.interrupted).toBe(false);+ expect(store.getChat(chatId)?.page).toEqual({path: "/projects/current",title: "Current Page",});@@ -490,9 +490,9 @@ describe("AgentInput", () => {test("preserves the latest page snapshot when an interrupted run ends on a new page", async () => {const store = useAgentStore();- const threadId = store.currentThreadId!;+ const chatId = store.currentChatId!;- store.updateThreadPage(threadId, {+ store.updateChatPage(chatId, {path: "/projects/original",title: "Original Page",});@@ -513,8 +513,8 @@ describe("AgentInput", () => {await findButtonByText(wrapper, "Send")!.trigger("click");await flushPromises();- expect(store.getThread(threadId)?.interrupted).toBe(true);- expect(store.getThread(threadId)?.page).toEqual({+ expect(store.getChat(chatId)?.interrupted).toBe(true);+ expect(store.getChat(chatId)?.page).toEqual({path: "/projects/navigated",title: "Navigated Page",});@@ -522,15 +522,15 @@ describe("AgentInput", () => {test("dismissing interrupted state removes partial run output", async () => {const store = useAgentStore();- const threadId = store.currentThreadId!;+ const chatId = store.currentChatId!;store.addMessage({- threadId,+ chatId,role: "user",content: "inspect this page",});store.addMessage({- threadId,+ chatId,role: "assistant",content: "Partial answer",metadata: {@@ -538,7 +538,7 @@ describe("AgentInput", () => {},});store.addMessage({- threadId,+ chatId,role: "tool",toolCallId: "tool-1",content: JSON.stringify({ partial: true }),@@ -546,8 +546,8 @@ describe("AgentInput", () => {runId: "run-1",},});- store.interruptRun(threadId);- store.getThread(threadId)!.runId = "run-1";+ store.interruptChatRun(chatId);+ store.getChat(chatId)!.runId = "run-1";const wrapper = mount(AgentInput, {global: {@@ -558,10 +558,10 @@ describe("AgentInput", () => {await findButtonByText(wrapper, "Dismiss")!.trigger("click");await flushPromises();- expect(store.getThread(threadId)?.interrupted).toBe(false);- expect(store.getThread(threadId)?.runId).toBeNull();+ expect(store.getChat(chatId)?.interrupted).toBe(false);+ expect(store.getChat(chatId)?.runId).toBeNull();expect(- store.getMessages(threadId).map((message) => ({+ store.getMessages(chatId).map((message) => ({role: message.role,content: message.content,toolCallId: message.toolCallId,@@ -577,7 +577,7 @@ describe("AgentInput", () => {test("keeps the latest run cancellable when an earlier aborted run settles late", async () => {const store = useAgentStore();- const threadId = store.currentThreadId!;+ const chatId = store.currentChatId!;const firstRun = createDeferred<AgentLoopOutcome>();const secondRun = createDeferred<AgentLoopOutcome>();let firstSignal: AbortSignal | undefined;@@ -619,31 +619,31 @@ describe("AgentInput", () => {await findButtonByText(wrapper, "Send")!.trigger("click");await flushPromises();- expect(store.abortController?.signal).toBe(firstSignal);+ expect(store.getAbortController(chatId)?.signal).toBe(firstSignal);expect(store.loading).toBe(true);await findButtonByText(wrapper, "Stop")!.trigger("click");await flushPromises();expect(firstSignal?.aborted).toBe(true);- expect(store.abortController).toBeNull();+ expect(store.getAbortController(chatId)).toBeNull();expect(store.loading).toBe(false);await wrapper.find("textarea").setValue("second request");await findButtonByText(wrapper, "Send")!.trigger("click");await flushPromises();- expect(store.abortController?.signal).toBe(secondSignal);+ expect(store.getAbortController(chatId)?.signal).toBe(secondSignal);expect(store.loading).toBe(true);firstRun.resolve({ kind: "aborted" });await flushPromises();- expect(store.abortController?.signal).toBe(secondSignal);+ expect(store.getAbortController(chatId)?.signal).toBe(secondSignal);expect(store.loading).toBe(true);expect(store- .getMessages(threadId)+ .getMessages(chatId).some((message) => message.content === "_Interrupted_")).toBe(false);@@ -654,15 +654,15 @@ describe("AgentInput", () => {});await flushPromises();- expect(store.abortController).toBeNull();+ expect(store.getAbortController(chatId)).toBeNull();expect(store.loading).toBe(false);});test("clears stale composer input when pending asks disappear", async () => {const store = useAgentStore();- const threadId = store.currentThreadId!;+ const chatId = store.currentChatId!;- store.awaitUser(threadId, {+ store.awaitUser(chatId, {toolCallId: "tool-ask",prompt: "Which project should I use?",kind: "input",@@ -678,25 +678,25 @@ describe("AgentInput", () => {expect(getTextareaValue(wrapper)).toBe("demo-project");await wrapper.find("textarea").setValue("stale input");- store.clearPendingAsk(threadId);+ store.clearPendingAsk(chatId);await flushPromises();expect(getTextareaValue(wrapper)).toBe("");});- test("clears stale composer input when switching threads", async () => {+ test("clears stale composer input when switching chats", async () => {const store = useAgentStore();- const firstThreadId = store.currentThreadId!;+ const firstChatId = store.currentChatId!;- store.awaitUser(firstThreadId, {+ store.awaitUser(firstChatId, {toolCallId: "tool-ask",prompt: "Which project should I use?",kind: "input",defaultValue: "demo-project",});- const secondThread = store.createThread({ title: "Second" });- store.setCurrentThread(firstThreadId);+ const secondChat = store.createChat({ title: "Second" });+ store.setCurrentChat(firstChatId);const wrapper = mount(AgentInput, {global: {@@ -707,11 +707,11 @@ describe("AgentInput", () => {expect(getTextareaValue(wrapper)).toBe("demo-project");await wrapper.find("textarea").setValue("stale input");- store.setCurrentThread(secondThread.id);+ store.setCurrentChat(secondChat.id);await flushPromises();expect(getTextareaValue(wrapper)).toBe("");- store.setCurrentThread(firstThreadId);+ store.setCurrentChat(firstChatId);await flushPromises();expect(getTextareaValue(wrapper)).toBe("demo-project");});@@ -835,10 +835,10 @@ describe("AgentInput", () => {test("uses choose buttons to answer pending choose prompts", async () => {const store = useAgentStore();- const threadId = store.currentThreadId!;+ const chatId = store.currentChatId!;store.addMessage({- threadId,+ chatId,role: "assistant",toolCalls: [{@@ -862,7 +862,7 @@ describe("AgentInput", () => {},],});- store.awaitUser(threadId, {+ store.awaitUser(chatId, {toolCallId: "tool-choose",prompt: "Which environment should I use?",kind: "choose",@@ -897,7 +897,7 @@ describe("AgentInput", () => {await flushPromises();const toolMessages = store- .getMessages(threadId)+ .getMessages(chatId).filter((message) => message.role === "tool");expect(toolMessages).toHaveLength(1);expect(JSON.parse(toolMessages[0].content ?? "{}")).toEqual({@@ -905,16 +905,16 @@ describe("AgentInput", () => {answer: "Production",value: "prod",});- expect(store.getPendingAsk(threadId)).toBeNull();+ expect(store.getPendingAsk(chatId)).toBeNull();expect(mockRunAgentLoop).toHaveBeenCalledTimes(1);});test("uses confirm buttons to answer pending confirmation prompts", async () => {const store = useAgentStore();- const threadId = store.currentThreadId!;+ const chatId = store.currentChatId!;store.addMessage({- threadId,+ chatId,role: "assistant",toolCalls: [{@@ -929,7 +929,7 @@ describe("AgentInput", () => {},],});- store.awaitUser(threadId, {+ store.awaitUser(chatId, {toolCallId: "tool-confirm",prompt: "Delete the database?",kind: "confirm",@@ -955,7 +955,7 @@ describe("AgentInput", () => {await flushPromises();const toolMessages = store- .getMessages(threadId)+ .getMessages(chatId).filter((message) => message.role === "tool");expect(toolMessages).toHaveLength(1);expect(JSON.parse(toolMessages[0].content ?? "{}")).toEqual({@@ -963,7 +963,43 @@ describe("AgentInput", () => {answer: "Delete",confirmed: true,});- expect(store.getPendingAsk(threadId)).toBeNull();+ expect(store.getPendingAsk(chatId)).toBeNull();+ expect(mockRunAgentLoop).toHaveBeenCalledTimes(1);+ });++ test("keeps the running chat selected while another chat is running", async () => {+ const store = useAgentStore();+ const firstChatId = store.currentChatId!;+ const secondChat = store.createChat({+ title: "Second thread",+ select: false,+ });+ const firstRun = createDeferred<AgentLoopOutcome>();++ mockRunAgentLoop.mockImplementationOnce(async () => firstRun.promise);++ const wrapper = mount(AgentInput, {+ global: {+ plugins: [pinia, i18n],+ },+ });++ await wrapper.find("textarea").setValue("first request");+ await findButtonByText(wrapper, "Send")!.trigger("click");+ await flushPromises();++ expect(store.isChatRunning(firstChatId)).toBe(true);++ store.setCurrentChat(secondChat.id);+ await flushPromises();++ const textarea = wrapper.find("textarea");+ expect(store.currentChatId).toBe(firstChatId);+ expect((textarea.element as HTMLTextAreaElement).disabled).toBe(true);expect(mockRunAgentLoop).toHaveBeenCalledTimes(1);+ expect(store.getMessages(secondChat.id)).toEqual([]);++ firstRun.resolve({ kind: "completed", text: "First done", success: true });+ await flushPromises();});});diff --git a/frontend/src/plugins/agent/components/AgentInput.vue b/frontend/src/plugins/agent/components/AgentInput.vueindex d9b8c3afb1..5c40922aa2 100644--- a/frontend/src/plugins/agent/components/AgentInput.vue+++ b/frontend/src/plugins/agent/components/AgentInput.vue@@ -16,11 +16,11 @@ const router = useRouter();const route = useRoute();const agentStore = useAgentStore();const input = ref("");-let currentRunToken = 0;+const runTokens = new Map<string, number>();-const currentThread = computed(() => agentStore.currentThread);+const currentChat = computed(() => agentStore.currentChat);const currentPendingAsk = computed(() => agentStore.currentPendingAsk);-const isInterrupted = computed(() => Boolean(currentThread.value?.interrupted));+const isInterrupted = computed(() => Boolean(currentChat.value?.interrupted));const chooseOptions = computed(() =>currentPendingAsk.value?.kind === "choose"? (currentPendingAsk.value.options ?? [])@@ -51,9 +51,12 @@ const confirmLabel = computed(const cancelLabel = computed(() => currentPendingAsk.value?.cancelLabel ?? t("agent.cancel"));+const isCurrentChatRunning = computed(() =>+ agentStore.isChatRunning(currentChat.value?.id)+);const isSendDisabled = computed(() => {if (- agentStore.hasRunningThread ||+ isCurrentChatRunning.value ||isAwaitingConfirm.value ||isAwaitingChoose.value) {@@ -235,51 +238,37 @@ const formatDomRefSuggestionMeta = (suggestion: DomRefSuggestion) => {.join(" · ");};-const getThreadPageSnapshot = (threadId: string) => {- return agentStore.getThread(threadId)?.page;-};--const resolveThreadPageSnapshot = (- threadId: string,- fallbackPage: { path: string; title: string }-) => {- return getThreadPageSnapshot(threadId) ?? fallbackPage;-};-const getCurrentPageSnapshot = () => ({path: route.fullPath,title: document.title,});-const buildConversation = (- threadId: string,- systemPrompt: string-): Message[] => {+const buildChatHistory = (chatId: string, systemPrompt: string): Message[] => {return [{ role: "system", content: systemPrompt },- ...agentStore.getMessages(threadId),+ ...agentStore.getMessages(chatId),];};const handleOutcome = (- threadId: string,+ chatId: string,page: { path: string; title: string },errorPrefix: string,outcome: Awaited<ReturnType<typeof runAgentLoop>>) => {switch (outcome.kind) {case "completed":- agentStore.finishRun(threadId);+ agentStore.finishChatRun(chatId);return;case "awaiting_user":- agentStore.awaitUser(threadId, outcome.ask);+ agentStore.awaitUser(chatId, outcome.ask);return;case "aborted":- agentStore.interruptRun(threadId, getCurrentPageSnapshot());+ agentStore.interruptChatRun(chatId, getCurrentPageSnapshot());return;case "error":agentStore.addMessage({- threadId,+ chatId,role: "assistant",content: `${errorPrefix}${outcome.error.message}`,metadata: {@@ -287,7 +276,7 @@ const handleOutcome = (error: outcome.error.message,},});- agentStore.finishRun(threadId, {+ agentStore.finishChatRun(chatId, {status: "error",lastError: outcome.error.message,});@@ -295,26 +284,28 @@ const handleOutcome = (}};-async function runThread(- threadId: string,+async function runChat(+ chatId: string,page: { path: string; title: string },runId: string) {const controller = new AbortController();- const runToken = ++currentRunToken;- agentStore.abortController = controller;+ const runToken = (runTokens.get(chatId) ?? 0) + 1;+ runTokens.set(chatId, runToken);+ agentStore.setAbortController(chatId, controller);const systemPrompt = buildSystemPrompt(page);const tools = getToolDefinitions();const executor = createToolExecutor(router, {+ chatId,onNavigate: () => {- agentStore.updateThreadPage(threadId, getCurrentPageSnapshot());+ agentStore.updateChatPage(chatId, getCurrentPageSnapshot());},});try {const outcome = await runAgentLoop(- buildConversation(threadId, systemPrompt),+ buildChatHistory(chatId, systemPrompt),tools,executor,{@@ -323,7 +314,7 @@ async function runThread(return;}agentStore.addMessage({- threadId,+ chatId,role: "assistant",content: message.content,toolCalls: message.toolCalls,@@ -335,7 +326,7 @@ async function runThread(},onToolResult: (toolCallId, result) => {agentStore.addMessage({- threadId,+ chatId,role: "tool",toolCallId,content: result,@@ -350,7 +341,7 @@ async function runThread(return;}agentStore.addMessage({- threadId,+ chatId,role: "assistant",content: text,metadata: {@@ -363,59 +354,43 @@ async function runThread(controller.signal);- agentStore.incrementThreadTotalTokens(- threadId,- outcome.totalTokensUsed ?? 0- );+ agentStore.incrementChatTotalTokens(chatId, outcome.totalTokensUsed ?? 0);- if (runToken !== currentRunToken) {+ if (runToken !== runTokens.get(chatId)) {return;}- handleOutcome(threadId, page, "Error: ", outcome);+ handleOutcome(chatId, page, "Error: ", outcome);} finally {- if (- runToken === currentRunToken &&- agentStore.abortController === controller- ) {- agentStore.abortController = null;+ if (agentStore.getAbortController(chatId) === controller) {+ agentStore.setAbortController(chatId, null);}}}-async function startThreadRun(- threadId: string,- currentPage: { path: string; title: string },- options: {- preferCurrentPage?: boolean;- } = {}+async function startChatRun(+ chatId: string,+ currentPage: { path: string; title: string }) {- const threadPage = options.preferCurrentPage- ? currentPage- : resolveThreadPageSnapshot(threadId, currentPage);const runId = uuidv4();- if (options.preferCurrentPage) {- agentStore.updateThreadPage(threadId, threadPage);- }-- agentStore.startRun(threadId, threadPage, {- replacePage: options.preferCurrentPage,+ agentStore.updateChatPage(chatId, currentPage);+ agentStore.startChatRun(chatId, currentPage, {runId,});- await runThread(threadId, threadPage, runId);+ await runChat(chatId, currentPage, runId);}async function send() {- if (agentStore.hasRunningThread) {+ if (agentStore.isChatRunning(currentChat.value?.id)) {return;}const currentPage = getCurrentPageSnapshot();- const thread = agentStore.ensureCurrentThread(currentPage);- const threadId = thread.id;+ const thread = agentStore.ensureCurrentChat(currentPage);+ const chatId = thread.id;- agentStore.clearError(threadId);+ agentStore.clearError(chatId);if (currentPendingAsk.value) {const answer = input.value.trim();@@ -426,7 +401,7 @@ async function send() {if (currentPendingAsk.value.kind === "choose") {agentStore.answerPendingAsk(- threadId,+ chatId,{kind: "choose",answer,@@ -438,7 +413,7 @@ async function send() {);} else if (currentPendingAsk.value.kind === "input") {agentStore.answerPendingAsk(- threadId,+ chatId,{kind: "input",answer,@@ -450,7 +425,7 @@ async function send() {} else {return;}- await startThreadRun(threadId, currentPage);+ await startChatRun(chatId, currentPage);return;}@@ -461,39 +436,40 @@ async function send() {input.value = "";agentStore.addMessage({- threadId,+ chatId,role: "user",content: text,metadata: {route: currentPage.path,},});- await startThreadRun(threadId, currentPage);+ await startChatRun(chatId, currentPage);}async function retryLastTurn() {- if (agentStore.hasRunningThread || !currentThread.value?.interrupted) {+ if (+ agentStore.isChatRunning(currentChat.value?.id) ||+ !currentChat.value?.interrupted+ ) {return;}- const threadId = currentThread.value.id;+ const chatId = currentChat.value.id;const currentPage = getCurrentPageSnapshot();- agentStore.removeMessagesByRunId(threadId, currentThread.value.runId);- agentStore.clearError(threadId);- await startThreadRun(threadId, currentPage, {- preferCurrentPage: true,- });+ agentStore.removeMessagesByRunId(chatId, currentChat.value.runId);+ agentStore.clearError(chatId);+ await startChatRun(chatId, currentPage);}function dismissInterrupted() {- if (!currentThread.value) {+ if (!currentChat.value) {return;}agentStore.removeMessagesByRunId(- currentThread.value.id,- currentThread.value.runId+ currentChat.value.id,+ currentChat.value.runId);- agentStore.clearError(currentThread.value.id);+ agentStore.clearError(currentChat.value.id);}async function submitConfirmation(confirmed: boolean) {@@ -501,19 +477,19 @@ async function submitConfirmation(confirmed: boolean) {if (!pendingAsk ||pendingAsk.kind !== "confirm" ||- agentStore.hasRunningThread+ agentStore.isChatRunning(currentChat.value?.id)) {return;}const currentPage = getCurrentPageSnapshot();- const thread = agentStore.ensureCurrentThread(currentPage);- const threadId = thread.id;+ const thread = agentStore.ensureCurrentChat(currentPage);+ const chatId = thread.id;const answer = confirmed ? confirmLabel.value : cancelLabel.value;- agentStore.clearError(threadId);+ agentStore.clearError(chatId);agentStore.answerPendingAsk(- threadId,+ chatId,{kind: "confirm",answer,@@ -523,7 +499,7 @@ async function submitConfirmation(confirmed: boolean) {route: currentPage.path,});- await startThreadRun(threadId, currentPage);+ await startChatRun(chatId, currentPage);}async function submitChoice(option: AgentAskUserOption) {@@ -531,18 +507,18 @@ async function submitChoice(option: AgentAskUserOption) {if (!pendingAsk ||pendingAsk.kind !== "choose" ||- agentStore.hasRunningThread+ agentStore.isChatRunning(currentChat.value?.id)) {return;}const currentPage = getCurrentPageSnapshot();- const thread = agentStore.ensureCurrentThread(currentPage);- const threadId = thread.id;+ const thread = agentStore.ensureCurrentChat(currentPage);+ const chatId = thread.id;- agentStore.clearError(threadId);+ agentStore.clearError(chatId);agentStore.answerPendingAsk(- threadId,+ chatId,{kind: "choose",answer: option.label,@@ -552,12 +528,12 @@ async function submitChoice(option: AgentAskUserOption) {route: currentPage.path,});- await startThreadRun(threadId, currentPage);+ await startChatRun(chatId, currentPage);}watch(() => [- agentStore.currentThreadId,+ agentStore.currentChatId,currentPendingAsk.value?.toolCallId,currentPendingAsk.value?.kind,currentPendingAsk.value?.defaultValue,@@ -582,7 +558,7 @@ watch();watch(- () => agentStore.hasRunningThread,+ () => isCurrentChatRunning.value,(running) => {if (running) {closeDomRefMenu();@@ -618,14 +594,14 @@ watch(<div class="mt-2 flex flex-wrap gap-x-2 gap-y-2"><buttonclass="rounded-md bg-red-500 px-3 py-2 text-sm text-white hover:bg-red-600 disabled:opacity-50"- :disabled="agentStore.hasRunningThread"+ :disabled="isCurrentChatRunning"@click="retryLastTurn">- {{ $t("agent.retry-last-turn") }}+ {{ $t("agent.retry-last-chat-turn") }}</button><buttonclass="rounded-md border px-3 py-2 text-sm text-gray-700 hover:bg-gray-50 disabled:opacity-50"- :disabled="agentStore.hasRunningThread"+ :disabled="isCurrentChatRunning"@click="dismissInterrupted">{{ $t("common.dismiss") }}@@ -636,14 +612,14 @@ watch(<div v-if="isAwaitingConfirm" class="flex flex-wrap gap-x-2 gap-y-2"><buttonclass="rounded-md bg-blue-500 px-3 py-2 text-sm text-white hover:bg-blue-600 disabled:opacity-50"- :disabled="agentStore.hasRunningThread"+ :disabled="isCurrentChatRunning"@click="submitConfirmation(true)">{{ confirmLabel }}</button><buttonclass="rounded-md border px-3 py-2 text-sm text-gray-700 hover:bg-gray-50 disabled:opacity-50"- :disabled="agentStore.hasRunningThread"+ :disabled="isCurrentChatRunning"@click="submitConfirmation(false)">{{ cancelLabel }}@@ -655,7 +631,7 @@ watch(v-for="option in chooseOptions":key="option.value"class="rounded-md border px-3 py-2 text-left text-sm hover:bg-gray-50 disabled:opacity-50"- :disabled="agentStore.hasRunningThread"+ :disabled="isCurrentChatRunning"@click="submitChoice(option)"><div class="font-medium text-gray-800">{{ option.label }}</div>@@ -673,7 +649,7 @@ watch(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="agentStore.hasRunningThread"+ :disabled="isCurrentChatRunning"@click="updateSelection"@blur="closeDomRefMenu"@input="updateSelection"@@ -711,7 +687,7 @@ watch(<buttonv-if="agentStore.loading"class="rounded-md bg-red-500 px-3 py-2 text-sm text-white hover:bg-red-600"- @click="agentStore.cancel()"+ @click="agentStore.cancel(currentChat?.id)">{{ $t("agent.stop") }}</button>diff --git a/frontend/src/plugins/agent/components/AgentWindow.test.ts b/frontend/src/plugins/agent/components/AgentWindow.test.tsnew file mode 100644index 0000000000..ea5b3b8026--- /dev/null+++ b/frontend/src/plugins/agent/components/AgentWindow.test.ts@@ -0,0 +1,270 @@+import { mount } from "@vue/test-utils";+import { NInput, NPopconfirm } from "naive-ui";+import { createPinia, setActivePinia } from "pinia";+import { beforeEach, describe, expect, test, vi } from "vitest";+import { nextTick } from "vue";+import { createI18n } from "vue-i18n";+import { useAgentStore } from "../store/agent";++vi.mock("./AgentChat.vue", () => ({+ default: {+ name: "AgentChat",+ template: "<div data-agent-chat />",+ },+}));++vi.mock("./AgentInput.vue", () => ({+ default: {+ name: "AgentInput",+ template: "<div data-agent-input />",+ },+}));++import AgentWindow from "./AgentWindow.vue";++const mockRoute = vi.hoisted(() => ({ fullPath: "/projects/demo" }));++vi.mock("vue-router", () => ({+ useRoute: () => mockRoute,+}));++class ResizeObserverMock {+ observe() {}+ disconnect() {}+ unobserve() {}+}++const i18n = createI18n({+ legacy: false,+ locale: "en-US",+ messages: {+ "en-US": {+ agent: {+ "assistant-title": "Bytebase Assistant",+ minimize: "Minimize",+ close: "Close",+ resize: "Resize",+ "chat-list-label": "Chats",+ "chat-switch-locked":+ "Finish the running chat before switching to another one.",+ "new-chat": "New chat",+ "rename-chat-placeholder": "Enter a chat name",+ "archive-chat": "Archive",+ "unarchive-chat": "Unarchive",+ "delete-chat": "Delete",+ "show-archived-chats": "Show archived chats",+ "hide-archived-chats": "Hide archived chats",+ "archive-chat-confirmation": "Archive this chat?",+ "delete-chat-confirmation": "Delete this chat?",+ "chat-default-title": "New chat",+ "chat-archived-label": "Archived",+ "chat-status-idle": "Idle",+ "chat-status-running": "Running",+ "chat-status-awaiting-user": "Awaiting input",+ "chat-status-error": "Error",+ "chat-status-interrupted": "Interrupted",+ "chat-total-tokens": "Tokens used: {count}",+ },+ },+ },+});++const mountAgentWindow = () => {+ const pinia = createPinia();+ setActivePinia(pinia);+ const store = useAgentStore();+ store.visible = true;+ return {+ store,+ wrapper: mount(AgentWindow, {+ global: {+ plugins: [pinia, i18n],+ components: {+ NInput,+ NPopconfirm,+ },+ stubs: {+ Teleport: true,+ },+ },+ }),+ };+};++describe("AgentWindow", () => {+ beforeEach(() => {+ localStorage.clear();+ vi.stubGlobal("ResizeObserver", ResizeObserverMock);+ document.title = "Demo Page";+ });++ test("renders chats in a left sidebar instead of a select picker", async () => {+ const { store, wrapper } = mountAgentWindow();+ const firstChatId = store.currentChatId!;+ store.addMessage({+ chatId: firstChatId,+ role: "user",+ content: "Summarize the production incident timeline",+ });+ const secondChat = store.createChat({+ title: "Renamed thread",+ select: false,+ });++ await wrapper.vm.$nextTick();++ expect(wrapper.find("select").exists()).toBe(false);+ const chatRows = wrapper.findAll("[data-agent-chat-list] button");+ expect(chatRows).toHaveLength(2);+ expect(chatRows[0].text()).toContain("Renamed thread");+ expect(chatRows[1].text()).toContain(+ "Summarize the production incident timeline"+ );+ await chatRows[0].trigger("click");+ expect(store.currentChatId).toBe(secondChat.id);+ expect(+ wrapper.findAll("button").some((button) => button.text() === "Rename")+ ).toBe(false);+ });++ test("disables switching chats while a chat is running", async () => {+ const { store, wrapper } = mountAgentWindow();+ const firstChatId = store.currentChatId!;+ const secondChat = store.createChat({+ title: "Second thread",+ select: false,+ });++ store.startChatRun(firstChatId, {+ path: "/projects/demo",+ title: "Demo Page",+ });+ await wrapper.vm.$nextTick();++ const chatRows = wrapper.findAll("[data-agent-chat-list] button");+ const currentRow = chatRows.find(+ (row) => row.attributes("aria-current") === "true"+ );+ const otherRow = chatRows.find((row) =>+ row.text().includes("Second thread")+ );+ const newChatButton = wrapper+ .findAll("button")+ .find((button) => button.text() === "New chat");++ expect(wrapper.find("[data-agent-chat-lock-message]").text()).toContain(+ "Finish the running chat before switching to another one."+ );+ expect(currentRow?.attributes("disabled")).toBeUndefined();+ expect(otherRow?.attributes("disabled")).toBe("");+ expect(newChatButton?.attributes("disabled")).toBe("");++ await otherRow?.trigger("click");+ expect(store.currentChatId).toBe(firstChatId);+ expect(store.canSelectChat(secondChat.id)).toBe(false);+ });++ test("renames the current chat with inline editing on the selected row", async () => {+ const { store, wrapper } = mountAgentWindow();+ const currentRowButton = wrapper.find(+ "[data-agent-chat-list] button[aria-current='true']"+ );+ const currentChatId = store.currentChatId!;++ await currentRowButton.trigger("click");+ await nextTick();++ const currentRow = wrapper.find(`[data-agent-chat-row='${currentChatId}']`);+ const input = currentRow.find("input");+ expect(input.exists()).toBe(true);+ expect(currentRow.findComponent(NInput).exists()).toBe(true);+ await input.setValue(" Renamed thread in app ");+ await input.trigger("keydown", { key: "Enter" });+ await nextTick();++ expect(store.currentChat?.title).toBe("Renamed thread in app");+ expect(wrapper.find("input").exists()).toBe(false);+ });++ test("cancels inline rename on escape", async () => {+ const { store, wrapper } = mountAgentWindow();+ const originalTitle = store.currentChat?.title;+ const currentRow = wrapper.find(+ "[data-agent-chat-list] button[aria-current='true']"+ );++ await currentRow.trigger("click");+ await nextTick();++ const input = wrapper.find("input");+ await input.setValue("Should not save");+ await input.trigger("keydown", { key: "Escape" });+ await nextTick();++ expect(store.currentChat?.title).toBe(originalTitle);+ expect(wrapper.find("input").exists()).toBe(false);+ });++ test("resizes and persists the sidebar width", async () => {+ const { store, wrapper } = mountAgentWindow();+ store.size.width = 760;+ store.sidebarWidth = 240;++ await nextTick();++ const sidebar = wrapper.find("aside");+ expect(sidebar.attributes("style")).toContain("width: 240px");++ await wrapper+ .find("[data-agent-sidebar-resize]")+ .trigger("mousedown", { clientX: 240 });+ document.dispatchEvent(new MouseEvent("mousemove", { clientX: 320 }));+ document.dispatchEvent(new MouseEvent("mouseup", { clientX: 320 }));+ await nextTick();++ expect(store.sidebarWidth).toBe(320);+ expect(wrapper.find("aside").attributes("style")).toContain("width: 320px");+ expect(localStorage.getItem("bb-agent-window")).toContain(+ '"sidebarWidth":320'+ );+ });++ test("clamps the sidebar width when the window narrows", async () => {+ const { store, wrapper } = mountAgentWindow();+ store.size.width = 760;+ store.sidebarWidth = 420;++ await nextTick();+ expect(wrapper.find("aside").attributes("style")).toContain("width: 420px");++ store.size.width = 360;+ await nextTick();++ expect(store.sidebarWidth).toBe(180);+ expect(wrapper.find("aside").attributes("style")).toContain("width: 180px");+ });++ test("archives and deletes chats through popconfirm", 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);++ await popconfirms[0].vm.$emit("positive-click");+ await nextTick();+ expect(store.getChat(secondChat.id)?.archived).toBe(true);++ store.setCurrentChat(originalChatId);+ await nextTick();+ const deletePopconfirm = wrapper.findAllComponents(NPopconfirm)[1];+ await deletePopconfirm.vm.$emit("positive-click");+ await nextTick();++ expect(store.getChat(originalChatId)).toBeNull();+ expect(store.currentChatId).toBe(secondChat.id);+ });+});diff --git a/frontend/src/plugins/agent/components/AgentWindow.vue b/frontend/src/plugins/agent/components/AgentWindow.vueindex bc0a4ef3d0..915b306c0b 100644--- a/frontend/src/plugins/agent/components/AgentWindow.vue+++ b/frontend/src/plugins/agent/components/AgentWindow.vue@@ -1,8 +1,16 @@<script setup lang="ts">-import { computed, onBeforeUnmount, onMounted, ref, watch } from "vue";+import { NInput, NPopconfirm } from "naive-ui";+import {+ computed,+ nextTick,+ onBeforeUnmount,+ onMounted,+ ref,+ watch,+} from "vue";import { useI18n } from "vue-i18n";import { useRoute } from "vue-router";-import type { AgentThread } from "../logic/types";+import type { AgentChat as AgentChatRecord } from "../logic/types";import { useAgentStore } from "../store/agent";import AgentChat from "./AgentChat.vue";import AgentInput from "./AgentInput.vue";@@ -14,6 +22,8 @@ const agentStore = useAgentStore();const MIN_WIDTH = 300;const MIN_HEIGHT = 400;const WINDOW_MARGIN = 16;+const MIN_SIDEBAR_WIDTH = 180;+const MIN_MAIN_PANEL_WIDTH = 240;const windowRef = ref<HTMLElement | null>(null);const viewportSize = ref({@@ -69,6 +79,31 @@ const displayWindowState = computed(() => {return { position, size };});+const getSidebarWidthBounds = (+ windowWidth = displayWindowState.value.size.width+) => {+ const maxSidebarWidth = Math.max(+ MIN_SIDEBAR_WIDTH,+ windowWidth - MIN_MAIN_PANEL_WIDTH+ );+ return {+ min: Math.min(MIN_SIDEBAR_WIDTH, maxSidebarWidth),+ max: maxSidebarWidth,+ };+};++const clampSidebarWidth = (+ width: number,+ windowWidth = displayWindowState.value.size.width+) => {+ const bounds = getSidebarWidthBounds(windowWidth);+ return Math.min(bounds.max, Math.max(bounds.min, Math.round(width)));+};++const sidebarStyle = computed(() => ({+ width: `${clampSidebarWidth(agentStore.sidebarWidth)}px`,+}));+const windowStyle = computed(() => ({left: `${displayWindowState.value.position.x}px`,top: `${displayWindowState.value.position.y}px`,@@ -76,48 +111,57 @@ const windowStyle = computed(() => ({height: `${displayWindowState.value.size.height}px`,}));-const threadControlsDisabled = computed(() => agentStore.hasRunningThread);-const currentThreadStatusLabel = computed(() => {- const thread = agentStore.currentThread;- if (!thread) {- return t("agent.thread-status-idle");+const showArchivedChats = ref(false);+const displayedChats = computed(() =>+ agentStore.orderedChats.filter((chat) => {+ return (+ showArchivedChats.value ||+ !chat.archived ||+ chat.id === agentStore.currentChatId+ );+ })+);+const currentChatStatusLabel = computed(() => {+ const chat = agentStore.currentChat;+ if (!chat) {+ return t("agent.chat-status-idle");}- if (thread.interrupted) {- return t("agent.thread-status-interrupted");+ if (chat.interrupted) {+ return t("agent.chat-status-interrupted");}- switch (thread.status) {+ switch (chat.status) {case "running":- return t("agent.thread-status-running");+ return t("agent.chat-status-running");case "awaiting_user":- return t("agent.thread-status-awaiting-user");+ return t("agent.chat-status-awaiting-user");case "error":- return t("agent.thread-status-error");+ return t("agent.chat-status-error");default:- return t("agent.thread-status-idle");+ return t("agent.chat-status-idle");}});-const currentThreadStatusClass = computed(() => {- const thread = agentStore.currentThread;- if (!thread || thread.status === "idle") {+const currentChatStatusClass = computed(() => {+ const chat = agentStore.currentChat;+ if (!chat || chat.status === "idle") {return "bg-gray-100 text-gray-600";}- if (thread.status === "running") {+ if (chat.status === "running") {return "bg-blue-50 text-blue-600";}- if (thread.interrupted || thread.status === "error") {+ if (chat.interrupted || chat.status === "error") {return "bg-red-50 text-red-600";}return "bg-amber-50 text-amber-600";});const tokenFormatter = new Intl.NumberFormat();-const currentThreadTokenUsageLabel = computed(() =>- t("agent.thread-total-tokens", {- count: tokenFormatter.format(- agentStore.currentThread?.totalTokensUsed ?? 0- ),+const currentChatTokenUsageLabel = computed(() =>+ t("agent.chat-total-tokens", {+ count: tokenFormatter.format(agentStore.currentChat?.totalTokensUsed ?? 0),}));+const isChatSwitchLocked = computed(() => agentStore.hasRunningChat);+const isChatCreationDisabled = computed(() => agentStore.hasRunningChat);function syncSize(width: number, height: number) {const size = getDisplaySize(width, height);@@ -135,6 +179,13 @@ function syncPosition() {agentStore.position.y = position.y;}+function syncSidebarWidth(+ width = agentStore.sidebarWidth,+ windowWidth = displayWindowState.value.size.width+) {+ agentStore.sidebarWidth = clampSidebarWidth(width, windowWidth);+}+function syncStoreToDisplayState() {agentStore.size.width = displayWindowState.value.size.width;agentStore.size.height = displayWindowState.value.size.height;@@ -147,15 +198,104 @@ const getCurrentPageSnapshot = () => ({title: document.title,});-const getThreadLabel = (thread: AgentThread) => {- if (thread.title) {- return thread.title;- }- return `${t("agent.thread-default-title")} · ${new Date(- thread.createdTs- ).toLocaleString()}`;+const getEditableChatTitle = (chat: AgentChatRecord) =>+ chat.title+ ? chat.title+ : `${t("agent.chat-default-title")} · ${new Date(+ chat.createdTs+ ).toLocaleString()}`;++const getChatLabel = (chat: AgentChatRecord) => {+ const baseLabel = getEditableChatTitle(chat);+ return chat.archived+ ? `${baseLabel} (${t("agent.chat-archived-label")})`+ : baseLabel;};+function toggleArchivedChats() {+ showArchivedChats.value = !showArchivedChats.value;+}++const isRenamingCurrentChat = ref(false);+const renamingTitle = ref("");+const renameInputRef = ref<+ InstanceType<typeof NInput> | InstanceType<typeof NInput>[] | null+>(null);++function focusRenameInput() {+ const input = Array.isArray(renameInputRef.value)+ ? renameInputRef.value[0]+ : renameInputRef.value;+ input?.focus?.();+ input?.select?.();+}++function beginRenameCurrentChat() {+ const chat = agentStore.currentChat;+ if (!chat) {+ return;+ }+ renamingTitle.value = getEditableChatTitle(chat);+ isRenamingCurrentChat.value = true;+ nextTick(() => {+ focusRenameInput();+ });+}++function cancelRenameCurrentChat() {+ isRenamingCurrentChat.value = false;+ renamingTitle.value = "";+}++function commitRenameCurrentChat() {+ const chat = agentStore.currentChat;+ const title = renamingTitle.value.trim();+ if (!chat || !isRenamingCurrentChat.value) {+ return;+ }+ if (!title) {+ cancelRenameCurrentChat();+ return;+ }+ agentStore.renameChat(chat.id, title);+ cancelRenameCurrentChat();+}++function onRenameCurrentChatKeydown(event: KeyboardEvent) {+ if (event.isComposing) {+ return;+ }+ if (event.key === "Escape") {+ event.preventDefault();+ cancelRenameCurrentChat();+ return;+ }+ if (event.key === "Enter") {+ event.preventDefault();+ commitRenameCurrentChat();+ }+}++function toggleArchiveCurrentChat() {+ const chat = agentStore.currentChat;+ if (!chat) {+ return;+ }+ if (chat.archived) {+ agentStore.unarchiveChat(chat.id);+ return;+ }+ agentStore.archiveChat(chat.id);+}++function deleteCurrentChat() {+ const chat = agentStore.currentChat;+ if (!chat) {+ return;+ }+ agentStore.deleteChat(chat.id);+}+const isDragging = ref(false);const dragOffset = ref({ x: 0, y: 0 });@@ -199,6 +339,37 @@ const isResizing = ref(false);const resizeStart = ref({ x: 0, y: 0, w: 0, h: 0 });let resizeObserver: ResizeObserver | null = null;+const isSidebarResizing = ref(false);+const sidebarResizeStart = ref({ x: 0, width: 0 });++function startSidebarResize(event: MouseEvent) {+ event.preventDefault();+ event.stopPropagation();+ syncStoreToDisplayState();+ isSidebarResizing.value = true;+ sidebarResizeStart.value = {+ x: event.clientX,+ width: clampSidebarWidth(agentStore.sidebarWidth),+ };+ document.addEventListener("mousemove", onSidebarResize);+ document.addEventListener("mouseup", stopSidebarResize);+}++function onSidebarResize(event: MouseEvent) {+ if (!isSidebarResizing.value) {+ return;+ }+ const dx = event.clientX - sidebarResizeStart.value.x;+ syncSidebarWidth(sidebarResizeStart.value.width + dx);+}++function stopSidebarResize() {+ isSidebarResizing.value = false;+ document.removeEventListener("mousemove", onSidebarResize);+ document.removeEventListener("mouseup", stopSidebarResize);+ agentStore.saveWindowState();+}+function startResize(event: MouseEvent) {event.preventDefault();event.stopPropagation();@@ -269,26 +440,58 @@ function handleViewportResize() {});}+watch(+ () => displayWindowState.value.size.width,+ (windowWidth) => {+ const sidebarWidth = clampSidebarWidth(+ agentStore.sidebarWidth,+ windowWidth+ );+ if (sidebarWidth === agentStore.sidebarWidth) {+ return;+ }+ agentStore.sidebarWidth = sidebarWidth;+ agentStore.saveWindowState();+ }+);+watch(windowRef, () => {observeWindowSize();});-function createThread() {- agentStore.createThread({ page: getCurrentPageSnapshot() });+function createChat() {+ if (isChatCreationDisabled.value) {+ return;+ }+ agentStore.createChat({ page: getCurrentPageSnapshot() });}-function resetCurrentThread() {- agentStore.clearConversation();+function handleChatRowClick(chatId: string) {+ if (chatId === agentStore.currentChatId) {+ if (!isRenamingCurrentChat.value) {+ beginRenameCurrentChat();+ }+ return;+ }+ if (isRenamingCurrentChat.value) {+ cancelRenameCurrentChat();+ }+ agentStore.setCurrentChat(chatId);}-function selectThread(event: Event) {- const target = event.target as HTMLSelectElement;- agentStore.setCurrentThread(target.value);-}+watch(+ () => agentStore.currentChatId,+ () => {+ if (isRenamingCurrentChat.value) {+ cancelRenameCurrentChat();+ }+ }+);onMounted(() => {agentStore.loadWindowState();handleViewportResize();+ syncSidebarWidth();observeWindowSize();window.addEventListener("resize", handleViewportResize);});@@ -296,6 +499,7 @@ onMounted(() => {onBeforeUnmount(() => {stopDrag();stopResize();+ stopSidebarResize();resizeObserver?.disconnect();cancelAnimationFrame(viewportResizeFrame);window.removeEventListener("resize", handleViewportResize);@@ -341,12 +545,12 @@ onBeforeUnmount(() => {</span><spanclass="inline-flex rounded-full px-2 py-0.5 text-xs font-medium"- :class="currentThreadStatusClass"+ :class="currentChatStatusClass">- {{ currentThreadStatusLabel }}+ {{ currentChatStatusLabel }}</span><span class="truncate text-xs text-gray-500">- {{ currentThreadTokenUsageLabel }}+ {{ currentChatTokenUsageLabel }}</span></div><div class="flex items-center gap-x-1">@@ -369,45 +573,146 @@ onBeforeUnmount(() => {</div></div>- <div class="border-b bg-white px-3 py-2">- <label class="mb-1 block text-xs font-medium text-gray-500">- {{ $t("agent.thread-select-label") }}- </label>- <div class="flex items-center gap-x-2">- <select- class="min-w-0 flex-1 rounded-md border px-2 py-1.5 text-sm focus:outline-none focus:ring-1 focus:ring-blue-500 disabled:bg-gray-50"- :value="agentStore.currentThreadId ?? ''"- :disabled="threadControlsDisabled"- @change="selectThread"- >- <option- v-for="thread in agentStore.orderedThreads"- :key="thread.id"- :value="thread.id"- >- {{ getThreadLabel(thread) }}- </option>- </select>- <button- class="rounded-md border px-2 py-1.5 text-xs font-medium text-gray-600 hover:bg-gray-50 disabled:opacity-50"- :disabled="threadControlsDisabled"- @click="createThread"- >- {{ $t("agent.new-thread") }}- </button>- <button- class="rounded-md border px-2 py-1.5 text-xs font-medium text-gray-600 hover:bg-gray-50 disabled:opacity-50"- :disabled="threadControlsDisabled"- @click="resetCurrentThread"- >- {{ $t("agent.reset-thread") }}- </button>+ <div class="flex min-h-0 flex-1 overflow-hidden bg-white">+ <aside+ class="flex shrink-0 flex-col border-r border-gray-200 bg-gray-50"+ :style="sidebarStyle"+ >+ <div class="border-b border-gray-200 px-3 py-3">+ <div class="flex items-center justify-between gap-x-2">+ <div>+ <h2 class="text-xs font-semibold uppercase tracking-wide text-gray-500">+ {{ $t("agent.chat-list-label") }}+ </h2>+ <p+ v-if="isChatSwitchLocked"+ class="mt-1 text-xs text-amber-600"+ data-agent-chat-lock-message+ >+ {{ $t("agent.chat-switch-locked") }}+ </p>+ </div>+ <button+ class="rounded-md border px-2 py-1.5 text-xs font-medium text-gray-600 hover:bg-gray-100 disabled:cursor-not-allowed disabled:bg-gray-100 disabled:text-gray-400"+ :disabled="isChatCreationDisabled"+ @click="createChat"+ >+ {{ $t("agent.new-chat") }}+ </button>+ </div>+ </div>++ <div class="min-h-0 flex-1 overflow-y-auto px-2 py-2">+ <div class="flex flex-col gap-y-1" data-agent-chat-list>+ <div+ v-for="chat in displayedChats"+ :key="chat.id"+ class="w-full rounded-md px-3 py-2 text-left text-sm transition-colors"+ :class="+ chat.id === agentStore.currentChatId+ ? 'bg-blue-50 text-blue-700'+ : 'text-gray-700 hover:bg-white'+ "+ :data-agent-chat-row="chat.id"+ >+ <NInput+ v-if="+ chat.id === agentStore.currentChatId && isRenamingCurrentChat+ "+ ref="renameInputRef"+ v-model:value="renamingTitle"+ size="small"+ :placeholder="$t('agent.rename-chat-placeholder')"+ data-agent-inline-rename-input+ @blur="commitRenameCurrentChat"+ @keydown="onRenameCurrentChatKeydown"+ />+ <button+ v-else+ type="button"+ class="w-full text-left font-medium disabled:cursor-not-allowed disabled:opacity-60"+ :disabled="!agentStore.canSelectChat(chat.id)"+ :aria-current="+ chat.id === agentStore.currentChatId ? 'true' : undefined+ "+ @click="handleChatRowClick(chat.id)"+ >+ <div class="truncate">+ {{ getChatLabel(chat) }}+ </div>+ </button>+ </div>+ </div>+ </div>++ <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>+ <button+ class="rounded-md border px-2 py-1.5 text-xs font-medium text-gray-600 hover:bg-white"+ @click="toggleArchivedChats"+ >+ {{+ showArchivedChats+ ? $t("agent.hide-archived-chats")+ : $t("agent.show-archived-chats")+ }}+ </button>+ </div>+ </div>+ </div>+ </aside>++ <button+ type="button"+ data-agent-window-action+ data-agent-sidebar-resize+ class="group relative w-1 shrink-0 cursor-col-resize bg-gray-100 transition-colors hover:bg-blue-100"+ @mousedown="startSidebarResize"+ >+ <span+ class="pointer-events-none absolute inset-y-0 left-1/2 w-px -translate-x-1/2 bg-transparent transition-colors group-hover:bg-blue-400"+ />+ </button>++ <div class="flex min-w-0 flex-1 flex-col">+ <AgentChat class="min-h-0 flex-1" />+ <AgentInput /></div></div>- <AgentChat class="min-h-0 flex-1" />- <AgentInput />-<buttontype="button"data-agent-window-actiondiff --git a/frontend/src/plugins/agent/logic/tools/index.test.ts b/frontend/src/plugins/agent/logic/tools/index.test.tsindex dc85c89af5..8a03a74968 100644--- a/frontend/src/plugins/agent/logic/tools/index.test.ts+++ b/frontend/src/plugins/agent/logic/tools/index.test.ts@@ -196,3 +196,49 @@ describe("agent tools ask_user", () => {});});});++describe("agent tools concurrency guard", () => {+ test("blocks concurrent page-changing tools across threads", async () => {+ let releaseNavigation: (() => void) | undefined;+ vi.mocked(createNavigateTool).mockImplementation(() => {+ return vi.fn(+ () =>+ new Promise<string>((resolve) => {+ releaseNavigation = () =>+ resolve(+ JSON.stringify({+ navigated: true,+ currentPath: "/projects/demo",+ })+ );+ })+ );+ });++ const firstExecutor = createToolExecutor({} as Router, {+ chatId: "thread-1",+ });+ const secondExecutor = createToolExecutor({} as Router, {+ chatId: "thread-2",+ });++ const firstRun = firstExecutor(+ "navigate",+ { path: "/projects/demo" },+ "tool-navigate-1"+ );++ await expect(+ secondExecutor("navigate", { path: "/projects/other" }, "tool-navigate-2")+ ).rejects.toThrow("Another chat is already using a page-changing tool");++ releaseNavigation?.();+ await expect(firstRun).resolves.toEqual({+ kind: "tool_result",+ result: JSON.stringify({+ navigated: true,+ currentPath: "/projects/demo",+ }),+ });+ });+});diff --git a/frontend/src/plugins/agent/logic/tools/index.ts b/frontend/src/plugins/agent/logic/tools/index.tsindex 099ddd61ae..1226d2d8a9 100644--- a/frontend/src/plugins/agent/logic/tools/index.ts+++ b/frontend/src/plugins/agent/logic/tools/index.ts@@ -366,9 +366,37 @@ Use mode="dom" before dom_action to get element refs like [e1]. Use semantic mod}interface CreateToolExecutorOptions {+ chatId?: string;onNavigate?: () => void;}+const PAGE_MUTATION_TOOL_NAMES = new Set(["navigate", "dom_action"]);+let pageMutationChatId: string | null = null;++const withPageMutationLock = async <T>(+ chatId: string | undefined,+ toolName: string,+ run: () => Promise<T>+): Promise<T> => {+ if (!PAGE_MUTATION_TOOL_NAMES.has(toolName) || !chatId) {+ return run();+ }+ if (pageMutationChatId && pageMutationChatId !== chatId) {+ throw new Error(+ "Another chat is already using a page-changing tool. Wait for it to finish, then retry this chat."+ );+ }++ pageMutationChatId = chatId;+ try {+ return await run();+ } finally {+ if (pageMutationChatId === chatId) {+ pageMutationChatId = null;+ }+ }+};+export function createToolExecutor(router: Router,options: CreateToolExecutorOptions = {}@@ -388,8 +416,11 @@ export function createToolExecutor(case "call_api":return toToolResult(await callApi(args as unknown as CallApiArgs));case "navigate": {- const result = await navigateTool(- args as { path?: string; list?: boolean }+ const result = await withPageMutationLock(+ options.chatId,+ name,+ async () =>+ await navigateTool(args as { path?: string; list?: boolean }));try {const payload = JSON.parse(result) as {@@ -407,7 +438,9 @@ export function createToolExecutor(return toToolResult(await pageStateTool(args as PageStateArgs));case "dom_action":return toToolResult(- await domActionTool(args as unknown as DomActionArgs)+ await withPageMutationLock(options.chatId, name, async () => {+ return await domActionTool(args as unknown as DomActionArgs);+ }));case "get_skill":return toToolResult(await getSkill(args as GetSkillArgs));diff --git a/frontend/src/plugins/agent/logic/types.ts b/frontend/src/plugins/agent/logic/types.tsindex 9991a58948..36ca968fb0 100644--- a/frontend/src/plugins/agent/logic/types.ts+++ b/frontend/src/plugins/agent/logic/types.ts@@ -18,9 +18,9 @@ export interface Message {toolCallId?: string;}-export type AgentThreadStatus = "idle" | "running" | "awaiting_user" | "error";+export type AgentChatStatus = "idle" | "running" | "awaiting_user" | "error";-export interface AgentThreadSnapshot {+export interface AgentChatSnapshot {path: string;title: string;}@@ -35,19 +35,20 @@ export interface AgentMessageMetadata {export interface AgentMessage extends Message {id: string;- threadId: string;+ chatId: string;createdTs: number;metadata?: AgentMessageMetadata;}-export interface AgentThread {+export interface AgentChat {id: string;title: string;createdTs: number;updatedTs: number;- status: AgentThreadStatus;+ status: AgentChatStatus;totalTokensUsed: number;- page?: AgentThreadSnapshot;+ page?: AgentChatSnapshot;+ archived: boolean;lastError?: string | null;interrupted?: boolean;runId?: string | null;diff --git a/frontend/src/plugins/agent/store/agent.test.ts b/frontend/src/plugins/agent/store/agent.test.tsindex a689d23b13..604c413a38 100644--- a/frontend/src/plugins/agent/store/agent.test.ts+++ b/frontend/src/plugins/agent/store/agent.test.ts@@ -44,13 +44,13 @@ afterEach(() => {});describe("useAgentStore", () => {- test("creates a default thread when no persisted state exists", () => {+ test("creates a default chat when no persisted state exists", () => {const store = createStore();- expect(store.threads).toHaveLength(1);- expect(store.currentThreadId).toBe(store.threads[0].id);+ expect(store.chats).toHaveLength(1);+ expect(store.currentChatId).toBe(store.chats[0].id);expect(store.messages).toEqual([]);- expect(store.threads[0].totalTokensUsed).toBe(0);+ expect(store.chats[0].totalTokensUsed).toBe(0);});test("loads persisted window state", () => {@@ -59,24 +59,29 @@ describe("useAgentStore", () => {JSON.stringify({position: { x: 120, y: 240 },size: { width: 480, height: 640 },+ sidebarWidth: 280,}));const store = createStore();store.loadWindowState();+ expect(store.sidebarWidth).toBe(280);expect(store.position).toEqual({ x: 120, y: 240 });expect(store.size).toEqual({ width: 480, height: 640 });expect(localStorage.getItem(AGENT_WINDOW_KEY)).toContain('"width":480');+ expect(localStorage.getItem(AGENT_WINDOW_KEY)).toContain(+ '"sidebarWidth":280'+ );expect(localStorage.getItem(AGENT_STATE_KEY)).toBeNull();});- test("normalizes stale running threads on load", () => {+ test("normalizes stale running chats on load", () => {localStorage.setItem(AGENT_STATE_KEY,JSON.stringify({- currentThreadId: "thread-1",- threads: [+ currentChatId: "thread-1",+ chats: [{id: "thread-1",title: "Existing thread",@@ -86,38 +91,38 @@ describe("useAgentStore", () => {runId: "run-1",},],- messagesByThreadId: {+ messagesByChatId: {"thread-1": [{id: "msg-1",- threadId: "thread-1",+ chatId: "thread-1",createdTs: 30,role: "user",content: "hello",},],},- pendingAskByThreadId: {},+ pendingAskByChatId: {},}));const store = createStore();- const thread = store.currentThread;+ const chat = store.currentChat;- expect(thread).not.toBeNull();- expect(thread?.status).toBe("idle");- expect(thread?.interrupted).toBe(true);- expect(thread?.runId).toBe("run-1");+ expect(chat).not.toBeNull();+ expect(chat?.status).toBe("idle");+ expect(chat?.interrupted).toBe(true);+ expect(chat?.runId).toBe("run-1");expect(store.loading).toBe(false);});test("clears interruption markers when a new run starts", () => {const store = createStore();- const threadId = store.currentThreadId!;+ const chatId = store.currentChatId!;- store.interruptRun(threadId);- store.startRun(- threadId,+ store.interruptChatRun(chatId);+ store.startChatRun(+ chatId,{path: "/projects/demo",title: "Demo",@@ -127,99 +132,162 @@ describe("useAgentStore", () => {});- expect(store.getThread(threadId)?.status).toBe("running");- expect(store.getThread(threadId)?.interrupted).toBe(false);- expect(store.getThread(threadId)?.runId).toBe("run-2");+ expect(store.getChat(chatId)?.status).toBe("running");+ expect(store.getChat(chatId)?.interrupted).toBe(false);+ expect(store.getChat(chatId)?.runId).toBe("run-2");});- test("persists the selected thread and resets thread messages in place", async () => {+ test("persists the selected chat across store reloads", async () => {const store = createStore();- const firstThreadId = store.currentThreadId!;+ const firstChatId = store.currentChatId!;store.addMessage({- threadId: firstThreadId,+ chatId: firstChatId,role: "user",content: "Initial prompt",});- const secondThread = store.createThread({+ const secondChat = store.createChat({title: "Second",page: {path: "/projects/original",title: "Original Page",},});- store.setCurrentThread(secondThread.id);+ store.setCurrentChat(secondChat.id);await nextTick();const rehydratedStore = createStore();- expect(rehydratedStore.currentThreadId).toBe(secondThread.id);- expect(rehydratedStore.getMessages(firstThreadId)).toHaveLength(1);-- rehydratedStore.clearConversation(secondThread.id);-- expect(rehydratedStore.getMessages(secondThread.id)).toEqual([]);- expect(rehydratedStore.getThread(secondThread.id)?.status).toBe("idle");- expect(rehydratedStore.getThread(secondThread.id)?.page).toBeUndefined();-- rehydratedStore.ensureCurrentThread({- path: "/projects/current",- title: "Current Page",- });-- expect(rehydratedStore.getThread(secondThread.id)?.page).toEqual({- path: "/projects/current",- title: "Current Page",+ expect(rehydratedStore.currentChatId).toBe(secondChat.id);+ expect(rehydratedStore.getMessages(firstChatId)).toHaveLength(1);+ expect(rehydratedStore.getChat(secondChat.id)?.page).toEqual({+ path: "/projects/original",+ title: "Original Page",});});- test("increments and resets thread token totals", async () => {+ test("increments and persists chat token totals", async () => {const store = createStore();- const threadId = store.currentThreadId!;+ const chatId = store.currentChatId!;- store.incrementThreadTotalTokens(threadId, 120);- store.incrementThreadTotalTokens(threadId, 30);+ store.incrementChatTotalTokens(chatId, 120);+ store.incrementChatTotalTokens(chatId, 30);- expect(store.getThread(threadId)?.totalTokensUsed).toBe(150);+ expect(store.getChat(chatId)?.totalTokensUsed).toBe(150);await nextTick();const rehydratedStore = createStore();- expect(rehydratedStore.getThread(threadId)?.totalTokensUsed).toBe(150);-- rehydratedStore.clearConversation(threadId);- expect(rehydratedStore.getThread(threadId)?.totalTokensUsed).toBe(0);+ expect(rehydratedStore.getChat(chatId)?.totalTokensUsed).toBe(150);});- test("preserves an existing thread page when resuming a run", () => {+ test("updates the chat page to the latest current page when starting a run", () => {const store = createStore();- const threadId = store.currentThreadId!;+ const chatId = store.currentChatId!;- store.updateThreadPage(threadId, {+ store.updateChatPage(chatId, {path: "/projects/original",title: "Original Page",});- store.ensureCurrentThread({+ store.ensureCurrentChat({path: "/projects/other",title: "Other Page",});- store.startRun(threadId, {+ store.startChatRun(chatId, {path: "/projects/other",title: "Other Page",});- expect(store.getThread(threadId)?.page).toEqual({- path: "/projects/original",- title: "Original Page",+ expect(store.getChat(chatId)?.page).toEqual({+ path: "/projects/other",+ title: "Other Page",+ });+ });++ test("uses the first user message as the default chat title", () => {+ const store = createStore();+ const chatId = store.currentChatId!;++ store.addMessage({+ chatId,+ role: "user",+ content: "Investigate unexpected production migration failures now",+ });++ expect(store.getChat(chatId)?.title).toBe(+ "Investigate unexpected production migration f..."+ );+ });++ test("orders equally updated chats by recency of creation", () => {+ const dateNow = vi.spyOn(Date, "now");+ dateNow.mockReturnValue(1000);++ const store = createStore();+ const firstChatId = store.currentChatId!;++ dateNow.mockReturnValue(2000);+ store.addMessage({+ chatId: firstChatId,+ role: "user",+ content: "Summarize the production incident timeline",+ });++ dateNow.mockReturnValue(2000);+ const secondChat = store.createChat({+ title: "Renamed thread",+ select: false,+ });++ expect(store.orderedChats.map((chat) => chat.id)).toEqual([+ secondChat.id,+ firstChatId,+ ]);++ dateNow.mockRestore();+ });++ test("does not switch chats while another chat is running", () => {+ const store = createStore();+ const firstChatId = store.currentChatId!;+ const secondChat = store.createChat({+ title: "Second",+ select: false,});++ store.startChatRun(firstChatId, {+ path: "/projects/demo",+ title: "Demo",+ });+ store.setCurrentChat(secondChat.id);++ expect(store.currentChatId).toBe(firstChatId);+ expect(store.canSelectChat(secondChat.id)).toBe(false);+ expect(store.canSelectChat(firstChatId)).toBe(true);});- test("persists pending choose asks for awaiting-user threads", async () => {+ test("creates a new chat without switching while a chat is running", () => {const store = createStore();- const threadId = store.currentThreadId!;+ const firstChatId = store.currentChatId!;- store.awaitUser(threadId, {+ store.startChatRun(firstChatId, {+ path: "/projects/demo",+ title: "Demo",+ });+ const secondChat = store.createChat({+ title: "Second",+ });++ expect(store.currentChatId).toBe(firstChatId);+ expect(store.getChat(secondChat.id)?.title).toBe("Second");+ });++ test("persists pending choose asks for awaiting-user chats", async () => {+ const store = createStore();+ const chatId = store.currentChatId!;++ store.awaitUser(chatId, {toolCallId: "tool-1",prompt: "Which database should I use?",kind: "choose",@@ -240,8 +308,8 @@ describe("useAgentStore", () => {await nextTick();const rehydratedStore = createStore();- expect(rehydratedStore.getThread(threadId)?.status).toBe("awaiting_user");- expect(rehydratedStore.getPendingAsk(threadId)).toEqual({+ expect(rehydratedStore.getChat(chatId)?.status).toBe("awaiting_user");+ expect(rehydratedStore.getPendingAsk(chatId)).toEqual({toolCallId: "tool-1",prompt: "Which database should I use?",kind: "choose",@@ -266,8 +334,8 @@ describe("useAgentStore", () => {localStorage.setItem(AGENT_STATE_KEY,JSON.stringify({- currentThreadId: "thread-1",- threads: [+ currentChatId: "thread-1",+ chats: [{id: "thread-1",title: "Existing thread",@@ -276,10 +344,10 @@ describe("useAgentStore", () => {status: "awaiting_user",},],- messagesByThreadId: {+ messagesByChatId: {"thread-1": [],},- pendingAskByThreadId: {+ pendingAskByChatId: {"thread-1": {toolCallId: "tool-1",prompt: "Choose a database",@@ -305,9 +373,9 @@ describe("useAgentStore", () => {test("answerPendingAsk appends a synthetic tool result and clears pending state", () => {const store = createStore();- const threadId = store.currentThreadId!;+ const chatId = store.currentChatId!;- store.awaitUser(threadId, {+ store.awaitUser(chatId, {toolCallId: "tool-1",prompt: "Proceed?",kind: "confirm",@@ -315,13 +383,13 @@ describe("useAgentStore", () => {cancelLabel: "Cancel",});- store.answerPendingAsk(threadId, {+ store.answerPendingAsk(chatId, {kind: "confirm",answer: "Proceed",confirmed: true,});- const messages = store.getMessages(threadId);+ const messages = store.getMessages(chatId);expect(messages).toHaveLength(1);expect(messages[0].role).toBe("tool");expect(messages[0].toolCallId).toBe("tool-1");@@ -330,14 +398,14 @@ describe("useAgentStore", () => {answer: "Proceed",confirmed: true,});- expect(store.getPendingAsk(threadId)).toBeNull();+ expect(store.getPendingAsk(chatId)).toBeNull();});test("answerPendingAsk stores choose labels and values", () => {const store = createStore();- const threadId = store.currentThreadId!;+ const chatId = store.currentChatId!;- store.awaitUser(threadId, {+ store.awaitUser(chatId, {toolCallId: "tool-choose",prompt: "Choose an environment",kind: "choose",@@ -347,13 +415,13 @@ describe("useAgentStore", () => {],});- store.answerPendingAsk(threadId, {+ store.answerPendingAsk(chatId, {kind: "choose",answer: "Production",value: "prod",});- const messages = store.getMessages(threadId);+ const messages = store.getMessages(chatId);expect(messages).toHaveLength(1);expect(messages[0].role).toBe("tool");expect(messages[0].toolCallId).toBe("tool-choose");@@ -362,6 +430,90 @@ describe("useAgentStore", () => {answer: "Production",value: "prod",});- expect(store.getPendingAsk(threadId)).toBeNull();+ expect(store.getPendingAsk(chatId)).toBeNull();+ });++ test("migrates persisted chats without archived state", () => {+ localStorage.setItem(+ AGENT_STATE_KEY,+ JSON.stringify({+ currentChatId: "thread-1",+ chats: [+ {+ id: "thread-1",+ title: "Existing thread",+ createdTs: 10,+ updatedTs: 20,+ status: "idle",+ },+ ],+ messagesByChatId: {+ "thread-1": [],+ },+ pendingAskByChatId: {},+ })+ );++ const store = createStore();++ expect(store.getChat("thread-1")?.archived).toBe(false);+ });++ test("does not update updatedTs when rename normalization keeps the same title", () => {+ const dateNow = vi.spyOn(Date, "now");+ dateNow.mockReturnValue(1000);++ const store = createStore();+ const chatId = store.currentChatId!;++ store.renameChat(chatId, "Renamed thread");+ const updatedTs = store.getChat(chatId)?.updatedTs;++ dateNow.mockReturnValue(2000);+ store.renameChat(chatId, " Renamed thread ");++ expect(store.getChat(chatId)?.title).toBe("Renamed thread");+ expect(store.getChat(chatId)?.updatedTs).toBe(updatedTs);++ dateNow.mockRestore();+ });++ test("supports renaming, archiving, unarchiving, and deleting chats", () => {+ const store = createStore();+ const firstChatId = store.currentChatId!;+ const secondChat = store.createChat({ title: "Second thread" });++ store.renameChat(firstChatId, " Renamed thread ");+ store.archiveChat(firstChatId);++ expect(store.getChat(firstChatId)?.title).toBe("Renamed thread");+ expect(store.getChat(firstChatId)?.archived).toBe(true);++ store.unarchiveChat(firstChatId);+ expect(store.getChat(firstChatId)?.archived).toBe(false);++ store.deleteChat(secondChat.id);+ expect(store.getChat(secondChat.id)).toBeNull();+ expect(store.currentChatId).toBe(firstChatId);+ });++ test("tracks abort controllers per chat and cancels only the requested chat", () => {+ const store = createStore();+ const firstChatId = store.currentChatId!;+ const secondChat = store.createChat({ title: "Second thread" });+ const firstController = new AbortController();+ const secondController = new AbortController();++ store.startChatRun(firstChatId, { path: "/projects/one", title: "One" });+ store.startChatRun(secondChat.id, { path: "/projects/two", title: "Two" });+ store.setAbortController(firstChatId, firstController);+ store.setAbortController(secondChat.id, secondController);++ store.cancel(firstChatId);++ expect(firstController.signal.aborted).toBe(true);+ expect(secondController.signal.aborted).toBe(false);+ expect(store.isChatRunning(firstChatId)).toBe(false);+ expect(store.isChatRunning(secondChat.id)).toBe(true);});});diff --git a/frontend/src/plugins/agent/store/agent.ts b/frontend/src/plugins/agent/store/agent.tsindex 4198ac54bc..27133434ed 100644--- a/frontend/src/plugins/agent/store/agent.ts+++ b/frontend/src/plugins/agent/store/agent.ts@@ -2,13 +2,12 @@ import { defineStore } from "pinia";import { v4 as uuidv4 } from "uuid";import { computed, ref, watch } from "vue";import type {- AgentAskUserOption,AgentAskUserResponse,+ AgentChat,+ AgentChatSnapshot,+ AgentChatStatus,AgentMessage,AgentPendingAsk,- AgentThread,- AgentThreadSnapshot,- AgentThreadStatus,Message,ToolCall,} from "../logic/types";@@ -17,43 +16,49 @@ export const AGENT_STATE_KEY = "bb-agent-state-v2";export const AGENT_WINDOW_KEY = "bb-agent-window";interface PersistedAgentState {- currentThreadId: string | null;- threads: AgentThread[];- messagesByThreadId: Record<string, AgentMessage[]>;- pendingAskByThreadId: Record<string, AgentPendingAsk>;+ currentChatId: string | null;+ chats: AgentChat[];+ messagesByChatId: Record<string, AgentMessage[]>;+ pendingAskByChatId: Record<string, AgentPendingAsk>;}-interface CreateThreadOptions {- page?: AgentThreadSnapshot;+interface CreateChatOptions {+ page?: AgentChatSnapshot;select?: boolean;title?: string;+ archived?: boolean;}interface AddMessageOptions extends Message {- threadId?: string;+ chatId?: string;metadata?: AgentMessage["metadata"];}-const DEFAULT_THREAD_STATUS: AgentThreadStatus = "idle";+const DEFAULT_CHAT_STATUS: AgentChatStatus = "idle";-const createThreadRecord = (options: CreateThreadOptions = {}): AgentThread => {+const createChatRecord = (options: CreateChatOptions = {}): AgentChat => {const now = Date.now();return {id: uuidv4(),title: options.title ?? "",createdTs: now,updatedTs: now,- status: DEFAULT_THREAD_STATUS,+ status: DEFAULT_CHAT_STATUS,totalTokensUsed: 0,page: options.page,+ archived: options.archived ?? false,lastError: null,interrupted: false,runId: null,};};-const getThreadTitleFromMessage = (content?: string) => {- const title = (content ?? "").trim().replace(/\s+/g, " ");+const normalizeChatTitle = (title?: string) => {+ return (title ?? "").trim();+};++const getChatTitleFromMessage = (content?: string) => {+ const title = normalizeChatTitle(content).replace(/\s+/g, " ");if (!title) {return "";}@@ -66,14 +71,18 @@ const isRecord = (value: unknown): value is Record<string, unknown> => {const normalizeMessage = (raw: unknown,- threadId: string,+ chatId: string,fallbackTs: number): AgentMessage => {const message = isRecord(raw) ? raw : {};return {id: typeof message.id === "string" ? message.id : uuidv4(),- threadId:- typeof message.threadId === "string" ? message.threadId : threadId,+ chatId:+ typeof message.chatId === "string"+ ? message.chatId+ : typeof message.threadId === "string"+ ? message.threadId+ : chatId,createdTs:typeof message.createdTs === "number" ? message.createdTs : fallbackTs,role:@@ -94,30 +103,6 @@ const normalizeMessage = (};};-const normalizeAskUserOption = (raw: unknown): AgentAskUserOption | null => {- const option = isRecord(raw) ? raw : {};- const label =- typeof option.label === "string"- ? option.label.trim()- : typeof option.value === "string"- ? option.value.trim()- : "";- const value = typeof option.value === "string" ? option.value.trim() : "";-- if (!label || !value) {- return null;- }-- return {- label,- value,- description:- typeof option.description === "string" && option.description.trim()- ? option.description.trim()- : undefined,- };-};-const normalizePendingAsk = (raw: unknown): AgentPendingAsk | null => {const pendingAsk = isRecord(raw) ? raw : {};if (@@ -129,9 +114,34 @@ const normalizePendingAsk = (raw: unknown): AgentPendingAsk | null => {const options = Array.isArray(pendingAsk.options)? pendingAsk.options- .map((option) => normalizeAskUserOption(option))- .filter((option): option is AgentAskUserOption => !!option)+ .map((option) => {+ const candidate = isRecord(option) ? option : {};+ const label =+ typeof candidate.label === "string"+ ? candidate.label.trim()+ : typeof candidate.value === "string"+ ? candidate.value.trim()+ : "";+ const value =+ typeof candidate.value === "string" ? candidate.value.trim() : "";+ if (!label || !value) {+ return null;+ }+ return {+ label,+ value,+ description:+ typeof candidate.description === "string" &&+ candidate.description.trim()+ ? candidate.description.trim()+ : undefined,+ };+ })+ .filter(+ (option): option is NonNullable<typeof option> => option !== null+ ): [];+const kind =pendingAsk.kind === "confirm"? "confirm"@@ -159,44 +169,45 @@ const normalizePendingAsk = (raw: unknown): AgentPendingAsk | null => {};};-const normalizeThread = (raw: unknown): AgentThread => {- const thread = isRecord(raw) ? raw : {};+const normalizeChat = (raw: unknown): AgentChat => {+ const chat = isRecord(raw) ? raw : {};const now = Date.now();const status =- thread.status === "running" ||- thread.status === "awaiting_user" ||- thread.status === "error"- ? thread.status- : DEFAULT_THREAD_STATUS;+ chat.status === "running" ||+ chat.status === "awaiting_user" ||+ chat.status === "error"+ ? chat.status+ : DEFAULT_CHAT_STATUS;return {- id: typeof thread.id === "string" ? thread.id : uuidv4(),- title: typeof thread.title === "string" ? thread.title : "",- createdTs: typeof thread.createdTs === "number" ? thread.createdTs : now,- updatedTs: typeof thread.updatedTs === "number" ? thread.updatedTs : now,+ id: typeof chat.id === "string" ? chat.id : uuidv4(),+ title: typeof chat.title === "string" ? chat.title : "",+ createdTs: typeof chat.createdTs === "number" ? chat.createdTs : now,+ updatedTs: typeof chat.updatedTs === "number" ? chat.updatedTs : now,status,totalTokensUsed:- typeof thread.totalTokensUsed === "number" &&- Number.isFinite(thread.totalTokensUsed) &&- thread.totalTokensUsed >= 0- ? thread.totalTokensUsed+ typeof chat.totalTokensUsed === "number" &&+ Number.isFinite(chat.totalTokensUsed) &&+ chat.totalTokensUsed >= 0+ ? chat.totalTokensUsed: 0,page:- isRecord(thread.page) &&- typeof thread.page.path === "string" &&- typeof thread.page.title === "string"+ isRecord(chat.page) &&+ typeof chat.page.path === "string" &&+ typeof chat.page.title === "string"? {- path: thread.page.path,- title: thread.page.title,+ path: chat.page.path,+ title: chat.page.title,}: undefined,+ archived: Boolean(chat.archived),lastError:- typeof thread.lastError === "string"- ? thread.lastError- : thread.lastError === null+ typeof chat.lastError === "string"+ ? chat.lastError+ : chat.lastError === null? null: null,- interrupted: Boolean(thread.interrupted),- runId: typeof thread.runId === "string" ? thread.runId : null,+ interrupted: Boolean(chat.interrupted),+ runId: typeof chat.runId === "string" ? chat.runId : null,};};@@ -205,37 +216,45 @@ const sortMessages = (messages: AgentMessage[]) => {return messages;};+const createEmptyPersistedState = (): PersistedAgentState => ({+ currentChatId: null,+ chats: [],+ messagesByChatId: {},+ pendingAskByChatId: {},+});+const normalizePersistedState = (raw: unknown): PersistedAgentState => {if (!isRecord(raw)) {- return {- currentThreadId: null,- threads: [],- messagesByThreadId: {},- pendingAskByThreadId: {},- };+ return createEmptyPersistedState();}- const rawThreads = Array.isArray(raw.threads) ? raw.threads : [];- const rawMessagesByThreadId = isRecord(raw.messagesByThreadId)- ? raw.messagesByThreadId- : {};- const rawPendingAskByThreadId = isRecord(raw.pendingAskByThreadId)- ? raw.pendingAskByThreadId- : {};-- const threads = rawThreads.map((thread) => normalizeThread(thread));- const messagesByThreadId: Record<string, AgentMessage[]> = {};- const pendingAskByThreadId: Record<string, AgentPendingAsk> = {};-- for (const thread of threads) {- const rawMessages: unknown[] = Array.isArray(- rawMessagesByThreadId[thread.id]- )- ? (rawMessagesByThreadId[thread.id] as unknown[])+ const rawChats = Array.isArray(raw.chats)+ ? raw.chats+ : Array.isArray(raw.threads)+ ? raw.threads+ : [];+ const rawMessagesByChatId = isRecord(raw.messagesByChatId)+ ? raw.messagesByChatId+ : isRecord(raw.messagesByThreadId)+ ? raw.messagesByThreadId+ : {};+ const rawPendingAskByChatId = isRecord(raw.pendingAskByChatId)+ ? raw.pendingAskByChatId+ : isRecord(raw.pendingAskByThreadId)+ ? raw.pendingAskByThreadId+ : {};++ const chats = rawChats.map((chat) => normalizeChat(chat));+ const messagesByChatId: Record<string, AgentMessage[]> = {};+ const pendingAskByChatId: Record<string, AgentPendingAsk> = {};++ for (const chat of chats) {+ const rawMessages: unknown[] = Array.isArray(rawMessagesByChatId[chat.id])+ ? (rawMessagesByChatId[chat.id] as unknown[]): [];const messages = sortMessages(rawMessages.map((message, index) =>- normalizeMessage(message, thread.id, thread.createdTs + index)+ normalizeMessage(message, chat.id, chat.createdTs + index)));@@ -244,41 +263,46 @@ const normalizePersistedState = (raw: unknown): PersistedAgentState => {);const lastMessage = messages.at(-1);- if (!thread.title) {- thread.title = getThreadTitleFromMessage(firstUserMessage?.content);+ if (!chat.title) {+ chat.title = getChatTitleFromMessage(firstUserMessage?.content);}if (lastMessage) {- thread.updatedTs = Math.max(thread.updatedTs, lastMessage.createdTs);+ chat.updatedTs = Math.max(chat.updatedTs, lastMessage.createdTs);}- if (thread.status === "running") {- thread.status = DEFAULT_THREAD_STATUS;- thread.interrupted = true;- thread.lastError = null;+ if (chat.status === "running") {+ chat.status = DEFAULT_CHAT_STATUS;+ chat.interrupted = true;+ chat.lastError = null;}- const pendingAsk = normalizePendingAsk(rawPendingAskByThreadId[thread.id]);- if (thread.status === "awaiting_user") {+ const pendingAsk = normalizePendingAsk(rawPendingAskByChatId[chat.id]);+ if (chat.status === "awaiting_user") {if (pendingAsk) {- pendingAskByThreadId[thread.id] = pendingAsk;+ pendingAskByChatId[chat.id] = pendingAsk;} else {- thread.status = DEFAULT_THREAD_STATUS;+ chat.status = DEFAULT_CHAT_STATUS;}}- messagesByThreadId[thread.id] = messages;+ messagesByChatId[chat.id] = messages;}- const currentThreadId =- typeof raw.currentThreadId === "string" &&- threads.some((thread) => thread.id === raw.currentThreadId)- ? raw.currentThreadId- : (threads[0]?.id ?? null);+ const savedCurrentChatId =+ typeof raw.currentChatId === "string"+ ? raw.currentChatId+ : typeof raw.currentThreadId === "string"+ ? raw.currentThreadId+ : null;+ const currentChatId =+ savedCurrentChatId && chats.some((chat) => chat.id === savedCurrentChatId)+ ? savedCurrentChatId+ : (chats[0]?.id ?? null);return {- currentThreadId,- threads,- messagesByThreadId,- pendingAskByThreadId,+ currentChatId,+ chats,+ messagesByChatId,+ pendingAskByChatId,};};@@ -289,351 +313,429 @@ export const useAgentStore = defineStore("agent", () => {y: window.innerHeight - 520,});const size = ref({ width: 400, height: 500 });+ const sidebarWidth = ref(256);const minimized = ref(false);- const threads = ref<AgentThread[]>([]);- const messagesByThreadId = ref<Record<string, AgentMessage[]>>({});- const pendingAskByThreadId = ref<Record<string, AgentPendingAsk>>({});- const currentThreadId = ref<string | null>(null);- const abortController = ref<AbortController | null>(null);+ const chats = ref<AgentChat[]>([]);+ const messagesByChatId = ref<Record<string, AgentMessage[]>>({});+ const pendingAskByChatId = ref<Record<string, AgentPendingAsk>>({});+ const currentChatId = ref<string | null>(null);+ const abortControllersByChatId = ref<Record<string, AbortController>>({});- const orderedThreads = computed(() =>- [...threads.value].sort((a, b) => b.updatedTs - a.updatedTs)+ const orderedChats = computed(() =>+ [...chats.value].sort((a, b) => {+ if (b.updatedTs !== a.updatedTs) {+ return b.updatedTs - a.updatedTs;+ }+ return b.createdTs - a.createdTs;+ }));- const currentThread = computed(- () =>- threads.value.find((thread) => thread.id === currentThreadId.value) ??- null+ const currentChat = computed(+ () => chats.value.find((chat) => chat.id === currentChatId.value) ?? null);const messages = computed(() =>- (currentThreadId.value- ? messagesByThreadId.value[currentThreadId.value]+ (currentChatId.value+ ? messagesByChatId.value[currentChatId.value]: undefined) ?? []);const currentPendingAsk = computed(() =>- (currentThreadId.value- ? pendingAskByThreadId.value[currentThreadId.value]+ (currentChatId.value+ ? pendingAskByChatId.value[currentChatId.value]: undefined) ?? null);- const runningThread = computed(- () => threads.value.find((thread) => thread.status === "running") ?? null+ const loading = computed(() => currentChat.value?.status === "running");+ const error = computed(() => currentChat.value?.lastError ?? null);+ const runningChatIds = computed(() =>+ chats.value+ .filter((chat) => chat.status === "running")+ .map((chat) => chat.id));- const loading = computed(() => currentThread.value?.status === "running");- const error = computed(() => currentThread.value?.lastError ?? null);- const hasRunningThread = computed(() => !!runningThread.value);- const runningThreadId = computed(() => runningThread.value?.id ?? null);+ const hasRunningChat = computed(() => runningChatIds.value.length > 0);- const getThread = (threadId?: string | null) => {- if (!threadId) {+ const getChat = (chatId?: string | null) => {+ if (!chatId) {return null;}- return threads.value.find((thread) => thread.id === threadId) ?? null;+ return chats.value.find((chat) => chat.id === chatId) ?? null;};- const getMessages = (threadId?: string | null) => {- if (!threadId) {+ const getMessages = (chatId?: string | null) => {+ if (!chatId) {return [];}- return messagesByThreadId.value[threadId] ?? [];+ return messagesByChatId.value[chatId] ?? [];+ };++ const getPendingAsk = (chatId = currentChatId.value) => {+ if (!chatId) {+ return null;+ }+ return pendingAskByChatId.value[chatId] ?? null;};- const getPendingAsk = (threadId = currentThreadId.value) => {- if (!threadId) {+ const getAbortController = (chatId?: string | null) => {+ if (!chatId) {return null;}- return pendingAskByThreadId.value[threadId] ?? null;+ return abortControllersByChatId.value[chatId] ?? null;+ };++ const isChatRunning = (chatId?: string | null) => {+ return getChat(chatId)?.status === "running";};- const touchThread = (threadId: string) => {- const thread = getThread(threadId);- if (!thread) {+ const touchChat = (chatId: string) => {+ const chat = getChat(chatId);+ if (!chat) {return null;}- thread.updatedTs = Date.now();- return thread;+ chat.updatedTs = Date.now();+ return chat;+ };++ const setAbortController = (+ chatId: string,+ controller: AbortController | null+ ) => {+ if (controller) {+ abortControllersByChatId.value[chatId] = controller;+ return controller;+ }+ delete abortControllersByChatId.value[chatId];+ return null;};- const clearPendingAsk = (threadId = currentThreadId.value) => {- if (!threadId || !pendingAskByThreadId.value[threadId]) {+ const clearPendingAsk = (chatId = currentChatId.value) => {+ if (!chatId || !pendingAskByChatId.value[chatId]) {return;}- delete pendingAskByThreadId.value[threadId];- touchThread(threadId);+ delete pendingAskByChatId.value[chatId];+ touchChat(chatId);};- const setPendingAsk = (threadId: string, pendingAsk: AgentPendingAsk) => {- pendingAskByThreadId.value[threadId] = pendingAsk;- touchThread(threadId);+ const setPendingAsk = (chatId: string, pendingAsk: AgentPendingAsk) => {+ pendingAskByChatId.value[chatId] = pendingAsk;+ touchChat(chatId);return pendingAsk;};- const setThreadStatus = (- threadId: string,- status: AgentThreadStatus,+ const setChatStatus = (+ chatId: string,+ status: AgentChatStatus,options: {interrupted?: boolean;lastError?: string | null;- page?: AgentThreadSnapshot;+ page?: AgentChatSnapshot;} = {}) => {- const thread = getThread(threadId);- if (!thread) {+ const chat = getChat(chatId);+ if (!chat) {return null;}- thread.status = status;- thread.interrupted = options.interrupted ?? false;- thread.lastError = options.lastError ?? null;+ chat.status = status;+ chat.interrupted = options.interrupted ?? false;+ chat.lastError = options.lastError ?? null;if (options.page) {- thread.page = options.page;+ chat.page = options.page;}if (status !== "awaiting_user") {- delete pendingAskByThreadId.value[threadId];+ delete pendingAskByChatId.value[chatId];}- touchThread(threadId);- return thread;+ touchChat(chatId);+ return chat;};- const createThread = (options: CreateThreadOptions = {}) => {- const thread = createThreadRecord(options);- threads.value.push(thread);- messagesByThreadId.value[thread.id] = [];- if (options.select ?? true) {- currentThreadId.value = thread.id;- }- return thread;- };-- const ensureCurrentThread = (page?: AgentThreadSnapshot) => {- const existing = getThread(currentThreadId.value);+ const ensureCurrentChat = (page?: AgentChatSnapshot) => {+ const existing = getChat(currentChatId.value);if (existing) {if (page && !existing.page) {existing.page = page;- touchThread(existing.id);+ touchChat(existing.id);}return existing;}- return createThread({ page });+ return createChat({ page });};- const setCurrentThread = (threadId: string) => {- if (getThread(threadId)) {- currentThreadId.value = threadId;+ const createChat = (options: CreateChatOptions = {}) => {+ const chat = createChatRecord(options);+ chats.value.push(chat);+ messagesByChatId.value[chat.id] = [];+ const shouldSelect =+ (options.select ?? true) &&+ (!hasRunningChat.value || currentChatId.value === null);+ if (shouldSelect) {+ currentChatId.value = chat.id;}+ return chat;};- const updateThreadPage = (threadId: string, page: AgentThreadSnapshot) => {- const thread = getThread(threadId);- if (!thread) {+ const selectNextAvailableChat = (preferredChatId?: string | null) => {+ const preferredChat = getChat(preferredChatId);+ if (preferredChat) {+ currentChatId.value = preferredChat.id;+ return preferredChat;+ }+ const fallbackChat = orderedChats.value[0] ?? createChat();+ currentChatId.value = fallbackChat.id;+ return fallbackChat;+ };++ const canSelectChat = (chatId?: string | null) => {+ if (!chatId || !getChat(chatId)) {+ return false;+ }+ return !hasRunningChat.value || currentChatId.value === chatId;+ };++ const setCurrentChat = (chatId: string) => {+ if (canSelectChat(chatId)) {+ currentChatId.value = chatId;+ }+ };++ const updateChatPage = (chatId: string, page: AgentChatSnapshot) => {+ const chat = getChat(chatId);+ if (!chat) {+ return null;+ }+ chat.page = page;+ touchChat(chatId);+ return chat;+ };++ const renameChat = (chatId: string, title: string) => {+ const chat = getChat(chatId);+ if (!chat) {+ return null;+ }+ const normalizedTitle = normalizeChatTitle(title);+ if (chat.title === normalizedTitle) {+ return chat;+ }+ chat.title = normalizedTitle;+ touchChat(chatId);+ return chat;+ };++ const archiveChat = (chatId: string) => {+ const chat = getChat(chatId);+ if (!chat) {+ return null;+ }+ chat.archived = true;+ touchChat(chatId);+ return chat;+ };++ const unarchiveChat = (chatId: string) => {+ const chat = getChat(chatId);+ if (!chat) {return null;}- thread.page = page;- touchThread(threadId);- return thread;+ chat.archived = false;+ touchChat(chatId);+ return chat;};const addMessage = (message: AddMessageOptions) => {- const thread = getThread(message.threadId) ?? ensureCurrentThread();+ const chat = getChat(message.chatId) ?? ensureCurrentChat();const createdTs = Date.now();const agentMessage: AgentMessage = {...message,id: uuidv4(),- threadId: thread.id,+ chatId: chat.id,createdTs,};- const threadMessages = getMessages(thread.id);- if (threadMessages.length === 0) {- messagesByThreadId.value[thread.id] = threadMessages;+ const chatMessages = getMessages(chat.id);+ if (chatMessages.length === 0) {+ messagesByChatId.value[chat.id] = chatMessages;}- threadMessages.push(agentMessage);- if (message.role === "user" && !thread.title) {- thread.title = getThreadTitleFromMessage(message.content);+ chatMessages.push(agentMessage);+ if (message.role === "user" && !chat.title) {+ chat.title = getChatTitleFromMessage(message.content);}- thread.lastError = null;- thread.interrupted = false;- thread.updatedTs = createdTs;+ chat.lastError = null;+ chat.interrupted = false;+ chat.updatedTs = createdTs;return agentMessage;};- const removeMessagesByRunId = (threadId: string, runId?: string | null) => {+ const removeMessagesByRunId = (chatId: string, runId?: string | null) => {if (!runId) {return [];}- const thread = getThread(threadId);- if (!thread) {+ const chat = getChat(chatId);+ if (!chat) {return [];}- const existingMessages = getMessages(threadId);+ const existingMessages = getMessages(chatId);const removedMessages = existingMessages.filter((message) => message.metadata?.runId === runId);if (removedMessages.length === 0) {return [];}- messagesByThreadId.value[threadId] = existingMessages.filter(+ messagesByChatId.value[chatId] = existingMessages.filter((message) => message.metadata?.runId !== runId);- touchThread(threadId);+ touchChat(chatId);return removedMessages;};const appendToolCall = (- threadId: string,+ chatId: string,messageId: string,toolCall: ToolCall) => {- const message = getMessages(threadId).find(- (message) => message.id === messageId+ const message = getMessages(chatId).find(+ (candidate) => candidate.id === messageId);if (!message) {return null;}message.toolCalls = [...(message.toolCalls ?? []), toolCall];- touchThread(threadId);+ touchChat(chatId);return message;};- const incrementThreadTotalTokens = (- threadId: string,+ const incrementChatTotalTokens = (+ chatId: string,totalTokensUsed: number) => {- const thread = getThread(threadId);- if (!thread || totalTokensUsed <= 0) {+ const chat = getChat(chatId);+ if (!chat || totalTokensUsed <= 0) {return null;}- thread.totalTokensUsed += totalTokensUsed;- touchThread(threadId);- return thread;+ chat.totalTokensUsed += totalTokensUsed;+ touchChat(chatId);+ return chat;};- const awaitUser = (threadId: string, pendingAsk: AgentPendingAsk) => {- setThreadStatus(threadId, "awaiting_user");- return setPendingAsk(threadId, pendingAsk);+ const awaitUser = (chatId: string, pendingAsk: AgentPendingAsk) => {+ setChatStatus(chatId, "awaiting_user");+ return setPendingAsk(chatId, pendingAsk);};const answerPendingAsk = (- threadId: string,+ chatId: string,response: AgentAskUserResponse,metadata?: AgentMessage["metadata"]) => {- const pendingAsk = getPendingAsk(threadId);+ const pendingAsk = getPendingAsk(chatId);if (!pendingAsk) {return null;}const toolMessage = addMessage({- threadId,+ chatId,role: "tool",toolCallId: pendingAsk.toolCallId,content: JSON.stringify(response),metadata,});- clearPendingAsk(threadId);+ clearPendingAsk(chatId);return toolMessage;};- const clearMessages = (threadId = currentThreadId.value) => {- const thread = getThread(threadId);- if (!thread) {+ const cancel = (chatId = currentChatId.value) => {+ if (!chatId) {return;}- messagesByThreadId.value[thread.id] = [];- delete pendingAskByThreadId.value[thread.id];- thread.title = "";- thread.page = undefined;- thread.status = DEFAULT_THREAD_STATUS;- thread.totalTokensUsed = 0;- thread.lastError = null;- thread.interrupted = false;- thread.runId = null;- thread.updatedTs = Date.now();- };-- const clearConversation = (threadId = currentThreadId.value) => {- if (threadId && runningThreadId.value === threadId) {- cancel();+ getAbortController(chatId)?.abort();+ setAbortController(chatId, null);+ if (isChatRunning(chatId)) {+ interruptChatRun(chatId);}- clearMessages(threadId);};- const clearError = (threadId = currentThreadId.value) => {- const thread = getThread(threadId);- if (!thread) {+ const clearError = (chatId = currentChatId.value) => {+ const chat = getChat(chatId);+ if (!chat) {return;}- thread.lastError = null;- thread.interrupted = false;- thread.runId = null;- if (thread.status === "error") {- thread.status = DEFAULT_THREAD_STATUS;+ chat.lastError = null;+ chat.interrupted = false;+ chat.runId = null;+ if (chat.status === "error") {+ chat.status = DEFAULT_CHAT_STATUS;}- touchThread(thread.id);+ touchChat(chat.id);};- const interruptRun = (threadId: string, page?: AgentThreadSnapshot) => {- setThreadStatus(threadId, DEFAULT_THREAD_STATUS, {+ const interruptChatRun = (chatId: string, page?: AgentChatSnapshot) => {+ setChatStatus(chatId, DEFAULT_CHAT_STATUS, {interrupted: true,page,});};- const cancel = () => {- abortController.value?.abort();- abortController.value = null;- if (runningThreadId.value) {- interruptRun(runningThreadId.value);- }- };-- const startRun = (- threadId: string,- page?: AgentThreadSnapshot,+ const startChatRun = (+ chatId: string,+ page?: AgentChatSnapshot,options: {- replacePage?: boolean;runId?: string;} = {}) => {- const thread = getThread(threadId);- const nextPage = options.replacePage ? page : (thread?.page ?? page);- setThreadStatus(threadId, "running", {- page: nextPage,+ setChatStatus(chatId, "running", {+ page,});- const updatedThread = getThread(threadId);- if (updatedThread) {- updatedThread.runId = options.runId ?? updatedThread.runId ?? null;+ const chat = getChat(chatId);+ if (chat) {+ chat.runId = options.runId ?? chat.runId ?? null;}};- const finishRun = (- threadId: string,+ const finishChatRun = (+ chatId: string,options: {- status?: Extract<AgentThreadStatus, "idle" | "error">;+ status?: Extract<AgentChatStatus, "idle" | "error">;lastError?: string | null;} = {}) => {- setThreadStatus(threadId, options.status ?? DEFAULT_THREAD_STATUS, {+ setChatStatus(chatId, options.status ?? DEFAULT_CHAT_STATUS, {lastError: options.lastError ?? null,interrupted: false,});- const thread = getThread(threadId);- if (thread) {- thread.runId = null;+ const chat = getChat(chatId);+ if (chat) {+ chat.runId = null;+ }+ };++ const deleteChat = (chatId: string) => {+ if (!getChat(chatId)) {+ return false;}+ cancel(chatId);+ chats.value = chats.value.filter((chat) => chat.id !== chatId);+ delete messagesByChatId.value[chatId];+ delete pendingAskByChatId.value[chatId];+ delete abortControllersByChatId.value[chatId];+ if (currentChatId.value === chatId) {+ selectNextAvailableChat();+ }+ return true;};const saveWindowState = () => {localStorage.setItem(AGENT_WINDOW_KEY,- JSON.stringify({ position: position.value, size: size.value })+ JSON.stringify({+ position: position.value,+ size: size.value,+ sidebarWidth: sidebarWidth.value,+ }));};const saveState = () => {const persistedState: PersistedAgentState = {- currentThreadId: currentThreadId.value,- threads: threads.value,- messagesByThreadId: messagesByThreadId.value,- pendingAskByThreadId: pendingAskByThreadId.value,+ currentChatId: currentChatId.value,+ chats: chats.value,+ messagesByChatId: messagesByChatId.value,+ pendingAskByChatId: pendingAskByChatId.value,};localStorage.setItem(AGENT_STATE_KEY, JSON.stringify(persistedState));};@@ -643,18 +745,18 @@ export const useAgentStore = defineStore("agent", () => {if (saved) {try {const state = normalizePersistedState(JSON.parse(saved));- threads.value = state.threads;- messagesByThreadId.value = state.messagesByThreadId;- pendingAskByThreadId.value = state.pendingAskByThreadId;- currentThreadId.value = state.currentThreadId;+ chats.value = state.chats;+ messagesByChatId.value = state.messagesByChatId;+ pendingAskByChatId.value = state.pendingAskByChatId;+ currentChatId.value = state.currentChatId;} catch {localStorage.removeItem(AGENT_STATE_KEY);}}- if (!currentThreadId.value || !getThread(currentThreadId.value)) {- const thread = createThread();- currentThreadId.value = thread.id;+ if (!currentChatId.value || !getChat(currentChatId.value)) {+ const chat = createChat();+ currentChatId.value = chat.id;}};@@ -667,26 +769,36 @@ export const useAgentStore = defineStore("agent", () => {const state = JSON.parse(saved) as {position?: { x?: number; y?: number };size?: { width?: number; height?: number };+ sidebarWidth?: number;};- if (state.position?.x && state.position?.y) {+ if (+ typeof state.position?.x === "number" &&+ typeof state.position?.y === "number"+ ) {position.value = {x: state.position.x,y: state.position.y,};}- if (state.size?.width && state.size?.height) {+ if (+ typeof state.size?.width === "number" &&+ typeof state.size?.height === "number"+ ) {size.value = {width: state.size.width,height: state.size.height,};}+ if (typeof state.sidebarWidth === "number") {+ sidebarWidth.value = state.sidebarWidth;+ }} catch {localStorage.removeItem(AGENT_WINDOW_KEY);}};watch(- [threads, messagesByThreadId, pendingAskByThreadId, currentThreadId],+ [chats, messagesByChatId, pendingAskByChatId, currentChatId],saveState,{deep: true,@@ -699,18 +811,19 @@ export const useAgentStore = defineStore("agent", () => {visible,position,size,+ sidebarWidth,minimized,- threads,- orderedThreads,- currentThreadId,- currentThread,+ chats,+ orderedChats,+ currentChatId,+ currentChat,messages,currentPendingAsk,loading,error,- hasRunningThread,- runningThreadId,- abortController,+ runningChatIds,+ hasRunningChat,+ abortControllersByChatId,toggle() {visible.value = !visible.value;if (visible.value) {@@ -723,28 +836,34 @@ export const useAgentStore = defineStore("agent", () => {restore() {minimized.value = false;},- getThread,+ getChat,getMessages,getPendingAsk,- createThread,- ensureCurrentThread,- setCurrentThread,- updateThreadPage,+ getAbortController,+ isChatRunning,+ canSelectChat,+ setAbortController,+ createChat,+ ensureCurrentChat,+ setCurrentChat,+ updateChatPage,+ renameChat,+ archiveChat,+ unarchiveChat,+ deleteChat,setPendingAsk,clearPendingAsk,- setThreadStatus,- startRun,- finishRun,- interruptRun,+ setChatStatus,+ startChatRun,+ finishChatRun,+ interruptChatRun,awaitUser,answerPendingAsk,- touchThread,- incrementThreadTotalTokens,+ touchChat,+ incrementChatTotalTokens,addMessage,removeMessagesByRunId,appendToolCall,- clearMessages,- clearConversation,clearError,cancel,saveWindowState,