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(agent): add threaded, resumable page-agent flows (#19678)
p0ny5f04b245e3c0
diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.jsonindex 6d80ffc972..94feae37c3 100644--- a/frontend/src/locales/en-US.json+++ b/frontend/src/locales/en-US.json@@ -2963,7 +2963,6 @@"assistant-title": "Bytebase Assistant","self": "Agent","resize": "Resize",- "new-chat": "New chat","minimize": "Minimize","close": "Close","input-placeholder": "Ask anything...",@@ -2971,6 +2970,33 @@"args": "Args:","result": "Result:","stop": "Stop",- "interrupted": "Interrupted"+ "interrupted": "Interrupted",+ "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",+ "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.",+ "tool-ask-user": "Awaiting your response",+ "tool-ask-user-input": "Input requested",+ "tool-ask-user-confirm": "Confirmation requested",+ "tool-ask-user-choose": "Choice requested",+ "tool-response-submitted": "Response submitted",+ "tool-prompt": "Prompt:",+ "tool-default-value": "Default:",+ "tool-options": "Options:",+ "tool-answer": "Answer:",+ "tool-value": "Value:",+ "tool-completed": "Completed",+ "tool-failed": "Completed with issues"}}diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.jsonindex 828d86dd02..480f2e7fd4 100644--- a/frontend/src/locales/es-ES.json+++ b/frontend/src/locales/es-ES.json@@ -2469,18 +2469,44 @@"tooltip-for-resource": "También es configurable a nivel {scope}. Bytebase dará prioridad a la configuración a nivel de entorno."},"agent": {- "assistant-title": "Bytebase Assistant",+ "assistant-title": "Asistente de Bytebase","self": "Agent","resize": "Resize",- "new-chat": "New chat",- "minimize": "Minimize",- "close": "Close",- "input-placeholder": "Ask anything...",- "send": "Send",- "args": "Args:",- "result": "Result:",- "stop": "Stop",- "interrupted": "Interrupted"+ "minimize": "Minimizar",+ "close": "Cerrar",+ "input-placeholder": "Pregunta lo que sea...",+ "send": "Enviar",+ "args": "Argumentos:",+ "result": "Resultado:",+ "stop": "Detener",+ "interrupted": "Interrumpido",+ "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",+ "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.",+ "tool-ask-user": "Esperando tu respuesta",+ "tool-ask-user-input": "Se requiere una entrada",+ "tool-ask-user-confirm": "Se requiere confirmación",+ "tool-ask-user-choose": "Se requiere una selección",+ "tool-response-submitted": "Respuesta enviada",+ "tool-prompt": "Pregunta:",+ "tool-default-value": "Valor predeterminado:",+ "tool-options": "Opciones:",+ "tool-answer": "Respuesta:",+ "tool-value": "Valor:",+ "tool-completed": "Completado",+ "tool-failed": "Completado con problemas"},"audit-log": {"export-finished": "Exportación finalizada",diff --git a/frontend/src/locales/ja-JP.json b/frontend/src/locales/ja-JP.jsonindex e467642225..7c0ed1abe1 100644--- a/frontend/src/locales/ja-JP.json+++ b/frontend/src/locales/ja-JP.json@@ -2469,18 +2469,44 @@"tooltip-for-resource": "{scope} レベルでも設定可能です。Bytebase は環境レベルの設定を優先します。"},"agent": {- "assistant-title": "Bytebase Assistant",+ "assistant-title": "Bytebase アシスタント","self": "Agent","resize": "Resize",- "new-chat": "New chat",- "minimize": "Minimize",- "close": "Close",- "input-placeholder": "Ask anything...",- "send": "Send",- "args": "Args:",- "result": "Result:",- "stop": "Stop",- "interrupted": "Interrupted"+ "minimize": "最小化",+ "close": "閉じる",+ "input-placeholder": "何でも質問してください...",+ "send": "送信",+ "args": "引数:",+ "result": "結果:",+ "stop": "停止",+ "interrupted": "中断",+ "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": "中断",+ "reply": "返信",+ "confirm": "確認",+ "cancel": "キャンセル",+ "pending-input-hint": "このスレッドを続けるには、下に返信してください。",+ "pending-confirm-hint": "このスレッドを続けるには、確認またはキャンセルを選択してください。",+ "pending-choose-hint": "このスレッドを続けるには、選択肢を選んでください。",+ "tool-ask-user": "あなたの回答を待っています",+ "tool-ask-user-input": "入力が必要です",+ "tool-ask-user-confirm": "確認が必要です",+ "tool-ask-user-choose": "選択が必要です",+ "tool-response-submitted": "回答を送信しました",+ "tool-prompt": "質問:",+ "tool-default-value": "既定値:",+ "tool-options": "選択肢:",+ "tool-answer": "回答:",+ "tool-value": "値:",+ "tool-completed": "完了",+ "tool-failed": "問題ありで完了"},"audit-log": {"export-finished": "エクスポートが完了しました",diff --git a/frontend/src/locales/vi-VN.json b/frontend/src/locales/vi-VN.jsonindex 240a9e3669..d81307d95f 100644--- a/frontend/src/locales/vi-VN.json+++ b/frontend/src/locales/vi-VN.json@@ -2469,18 +2469,44 @@"tooltip-for-resource": "Bạn cũng có thể cấu hình ở cấp độ {scope}. Bytebase sẽ ưu tiên cấu hình ở cấp độ môi trường."},"agent": {- "assistant-title": "Bytebase Assistant",+ "assistant-title": "Trợ lý Bytebase","self": "Agent","resize": "Resize",- "new-chat": "New chat",- "minimize": "Minimize",- "close": "Close",- "input-placeholder": "Ask anything...",- "send": "Send",- "args": "Args:",- "result": "Result:",- "stop": "Stop",- "interrupted": "Interrupted"+ "minimize": "Thu nhỏ",+ "close": "Đóng",+ "input-placeholder": "Hỏi bất cứ điều gì...",+ "send": "Gửi",+ "args": "Tham số:",+ "result": "Kết quả:",+ "stop": "Dừng",+ "interrupted": "Bị gián đoạn",+ "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",+ "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.",+ "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",+ "tool-ask-user-choose": "Cần lựa chọn",+ "tool-response-submitted": "Đã gửi phản hồi",+ "tool-prompt": "Câu hỏi:",+ "tool-default-value": "Giá trị mặc định:",+ "tool-options": "Tùy chọn:",+ "tool-answer": "Câu trả lời:",+ "tool-value": "Giá trị:",+ "tool-completed": "Hoàn tất",+ "tool-failed": "Hoàn tất kèm vấn đề"},"audit-log": {"export-finished": "Xuất hoàn tất",diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.jsonindex bee5b409f0..15da1bc3dd 100644--- a/frontend/src/locales/zh-CN.json+++ b/frontend/src/locales/zh-CN.json@@ -2963,7 +2963,6 @@"assistant-title": "Bytebase 助手","self": "助手","resize": "调整大小",- "new-chat": "新对话","minimize": "最小化","close": "关闭","input-placeholder": "输入任何问题...",@@ -2971,6 +2970,33 @@"args": "参数:","result": "结果:","stop": "停止",- "interrupted": "已中断"+ "interrupted": "已中断",+ "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": "已中断",+ "reply": "回复",+ "confirm": "确认",+ "cancel": "取消",+ "pending-input-hint": "请在下方回复以继续当前线程。",+ "pending-confirm-hint": "请选择确认或取消以继续当前线程。",+ "pending-choose-hint": "请选择一个选项以继续当前线程。",+ "tool-ask-user": "等待你的回复",+ "tool-ask-user-input": "需要输入",+ "tool-ask-user-confirm": "需要确认",+ "tool-ask-user-choose": "需要选择",+ "tool-response-submitted": "已提交回复",+ "tool-prompt": "提示:",+ "tool-default-value": "默认值:",+ "tool-options": "选项:",+ "tool-answer": "回答:",+ "tool-value": "值:",+ "tool-completed": "已完成",+ "tool-failed": "已完成,但存在问题"}}diff --git a/frontend/src/plugins/agent/components/AgentChat.vue b/frontend/src/plugins/agent/components/AgentChat.vueindex daf908a065..f392be427d 100644--- a/frontend/src/plugins/agent/components/AgentChat.vue+++ b/frontend/src/plugins/agent/components/AgentChat.vue@@ -4,6 +4,7 @@ import remarkParse from "remark-parse";import { unified } from "unified";import { computed, nextTick, ref, watch } from "vue";import AstToMarkdown from "@/plugins/ai/components/ChatView/Markdown/AstToVNode.vue";+import type { AgentMessage } from "../logic/types";import { useAgentStore } from "../store/agent";import ToolCallCard from "./ToolCallCard.vue";@@ -18,29 +19,32 @@ const chatContainer = ref<HTMLElement | null>(null);const displayMessages = computed(() =>agentStore.messages.filter(- (msg) => msg.role === "user" || msg.role === "assistant"+ (message): message is AgentMessage =>+ message.role === "user" || message.role === "assistant"));function getToolResult(- displayIndex: number,+ messageId: string,toolCallId: string): string | undefined {- // Map display index back to the full messages array- const msg = displayMessages.value[displayIndex];- if (!msg) return undefined;-- const fullIndex = agentStore.messages.indexOf(msg);- if (fullIndex < 0) return undefined;+ const fullIndex = agentStore.messages.findIndex(+ (message) => message.id === messageId+ );+ if (fullIndex < 0) {+ return undefined;+ }- // Look forward in the full messages array for the tool result- for (let i = fullIndex + 1; i < agentStore.messages.length; i++) {- const m = agentStore.messages[i];- if (m.role === "tool" && m.toolCallId === toolCallId) {- return m.content;+ for (let index = fullIndex + 1; index < agentStore.messages.length; index++) {+ const message = agentStore.messages[index];+ if (message.role === "tool" && message.toolCallId === toolCallId) {+ return message.content;}- // Stop if we hit another assistant message (new turn)- if (m.role === "assistant" && m.content && !m.toolCalls?.length) {+ if (+ message.role === "assistant" &&+ message.content &&+ !message.toolCalls?.length+ ) {break;}}@@ -48,50 +52,45 @@ function getToolResult(}watch(- () => agentStore.messages.length,+ [() => agentStore.currentThreadId, () => agentStore.messages.length],async () => {await nextTick();if (chatContainer.value) {- const el = chatContainer.value;- el.scrollTop = el.scrollHeight;+ chatContainer.value.scrollTop = chatContainer.value.scrollHeight;}});</script><template>- <div ref="chatContainer" class="overflow-y-auto p-3 space-y-3">- <template v-for="(msg, i) in displayMessages" :key="i">- <!-- User message -->+ <div ref="chatContainer" class="overflow-y-auto space-y-3 p-3">+ <template v-for="msg in displayMessages" :key="msg.id"><div v-if="msg.role === 'user'" class="flex justify-end">- <div class="max-w-[80%] rounded-lg px-3 py-2 bg-blue-50 text-sm">+ <div class="max-w-[80%] rounded-lg bg-blue-50 px-3 py-2 text-sm">{{ msg.content }}</div></div>- <!-- Assistant message -->- <div v-else-if="msg.role === 'assistant'" class="flex flex-col gap-y-2">+ <div v-else class="flex flex-col gap-y-2"><divv-if="msg.content"- class="max-w-[80%] rounded-lg px-3 py-2 bg-gray-50 text-sm markdown-content"+ class="max-w-[80%] rounded-lg bg-gray-50 px-3 py-2 text-sm markdown-content"><AstToMarkdown :ast="parseMarkdown(msg.content)" /></div><ToolCallCard- v-for="tc in msg.toolCalls"- :key="tc.id"- :tool-call="tc"- :result="getToolResult(i, tc.id)"+ v-for="toolCall in msg.toolCalls"+ :key="toolCall.id"+ :tool-call="toolCall"+ :result="getToolResult(msg.id, toolCall.id)"/></div></template>- <!-- Loading --><divv-if="agentStore.loading"class="flex items-center gap-x-2 text-sm text-gray-400"><span class="animate-pulse">●</span> {{ $t("common.loading") }}</div>- <!-- Error --><divv-if="agentStore.error"class="rounded-lg bg-red-50 px-3 py-2 text-sm text-red-600"@@ -112,10 +111,10 @@ watch(@apply mb-0;}.markdown-content :deep(pre) {- @apply my-1 p-2 bg-gray-100 rounded text-xs overflow-x-auto;+ @apply my-1 overflow-x-auto rounded bg-gray-100 p-2 text-xs;}.markdown-content :deep(code) {- @apply bg-gray-200 px-1 rounded text-xs;+ @apply rounded bg-gray-200 px-1 text-xs;}.markdown-content :deep(pre code) {@apply bg-transparent px-0;@@ -136,13 +135,13 @@ watch(.markdown-content :deep(h1),.markdown-content :deep(h2),.markdown-content :deep(h3) {- @apply font-semibold my-1;+ @apply my-1 font-semibold;}.markdown-content :deep(a) {@apply text-blue-600 underline;}.markdown-content :deep(blockquote) {- @apply border-l-2 border-gray-300 pl-2 my-1 text-gray-600;+ @apply my-1 border-l-2 border-gray-300 pl-2 text-gray-600;}.markdown-content :deep(table) {@apply my-1 border-collapse text-xs;diff --git a/frontend/src/plugins/agent/components/AgentInput.test.ts b/frontend/src/plugins/agent/components/AgentInput.test.tsnew file mode 100644index 0000000000..6782e41e3c--- /dev/null+++ b/frontend/src/plugins/agent/components/AgentInput.test.ts@@ -0,0 +1,615 @@+import { mount } from "@vue/test-utils";+import { createPinia, setActivePinia } from "pinia";+import { beforeEach, describe, expect, test, vi } from "vitest";+import { createI18n } from "vue-i18n";+import type { AgentLoopOutcome } from "../logic/types";+import { useAgentStore } from "../store/agent";+import AgentInput from "./AgentInput.vue";++const {+ mockRunAgentLoop,+ mockBuildSystemPrompt,+ mockCreateToolExecutor,+ mockGetToolDefinitions,+ mockRoute,+} = vi.hoisted(() => ({+ mockRunAgentLoop: vi.fn(),+ mockBuildSystemPrompt: vi.fn(() => "system-prompt"),+ mockCreateToolExecutor: vi.fn((_router?: unknown, _options?: unknown) =>+ vi.fn()+ ),+ mockGetToolDefinitions: vi.fn(() => []),+ mockRoute: { fullPath: "/projects/demo" },+}));++vi.mock("../logic/agentLoop", () => ({+ runAgentLoop: mockRunAgentLoop,+}));++vi.mock("../logic/prompt", () => ({+ buildSystemPrompt: mockBuildSystemPrompt,+}));++vi.mock("../logic/tools", () => ({+ createToolExecutor: mockCreateToolExecutor,+ getToolDefinitions: mockGetToolDefinitions,+}));++vi.mock("vue-router", () => ({+ useRoute: () => mockRoute,+ useRouter: () => ({}),+}));++const getTextareaValue = (wrapper: ReturnType<typeof mount>) => {+ return (wrapper.find("textarea").element as HTMLTextAreaElement).value;+};+const flushPromises = async () => {+ await Promise.resolve();+ await Promise.resolve();+};++const createDeferred = <T>() => {+ let resolve!: (value: T) => void;+ const promise = new Promise<T>((resolver) => {+ resolve = resolver;+ });+ return { promise, resolve };+};++const i18n = createI18n({+ legacy: false,+ locale: "en-US",+ messages: {+ "en-US": {+ agent: {+ interrupted: "Interrupted",+ "input-placeholder": "Ask anything...",+ send: "Send",+ reply: "Reply",+ stop: "Stop",+ 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.",+ },+ },+ },+});++describe("AgentInput", () => {+ let pinia: ReturnType<typeof createPinia>;++ beforeEach(() => {+ localStorage.clear();+ pinia = createPinia();+ setActivePinia(pinia);+ mockRunAgentLoop.mockReset();+ mockBuildSystemPrompt.mockClear();+ mockCreateToolExecutor.mockClear();+ mockGetToolDefinitions.mockClear();+ });++ beforeEach(() => {+ mockRoute.fullPath = "/projects/demo";+ document.title = "Demo Page";+ });++ test("submits pending input as a tool result and resumes the same thread", async () => {+ const store = useAgentStore();+ const threadId = store.currentThreadId!;++ store.addMessage({+ threadId,+ role: "assistant",+ toolCalls: [+ {+ id: "tool-ask",+ name: "ask_user",+ arguments: JSON.stringify({+ prompt: "Which project should I use?",+ kind: "input",+ }),+ },+ ],+ });+ store.awaitUser(threadId, {+ toolCallId: "tool-ask",+ prompt: "Which project should I use?",+ kind: "input",+ });++ mockRunAgentLoop.mockImplementation(+ async (+ messages: unknown,+ _tools: unknown,+ _executor: unknown,+ callbacks?: { onText?: (text: string) => void }+ ) => {+ callbacks?.onText?.("Using project demo.");+ return {+ kind: "completed",+ text: "Using project demo.",+ success: true,+ explicit: true,+ };+ }+ );++ const wrapper = mount(AgentInput, {+ global: {+ plugins: [pinia, i18n],+ },+ });++ await wrapper.find("textarea").setValue("demo-project");+ await wrapper.find("button").trigger("click");+ await flushPromises();++ const toolMessages = store+ .getMessages(threadId)+ .filter((message) => message.role === "tool");+ expect(toolMessages).toHaveLength(1);+ expect(toolMessages[0].toolCallId).toBe("tool-ask");+ expect(JSON.parse(toolMessages[0].content ?? "{}")).toEqual({+ kind: "input",+ answer: "demo-project",+ });+ expect(store.getPendingAsk(threadId)).toBeNull();+ expect(store.currentThreadId).toBe(threadId);+ expect(mockRunAgentLoop).toHaveBeenCalledTimes(1);++ const [messages] = mockRunAgentLoop.mock.calls[0];+ expect(messages).toEqual(+ expect.arrayContaining([+ expect.objectContaining({ role: "system", content: "system-prompt" }),+ expect.objectContaining({+ role: "tool",+ toolCallId: "tool-ask",+ }),+ ])+ );+ });++ test("resumes pending asks with the saved thread page snapshot", async () => {+ const store = useAgentStore();+ const threadId = store.currentThreadId!;++ store.updateThreadPage(threadId, {+ path: "/projects/original",+ title: "Original Page",+ });+ store.awaitUser(threadId, {+ toolCallId: "tool-ask",+ prompt: "Which project should I use?",+ kind: "input",+ });++ mockRoute.fullPath = "/projects/other";+ document.title = "Other Page";+ mockRunAgentLoop.mockResolvedValue({+ kind: "completed",+ text: "Using project demo.",+ success: true,+ explicit: true,+ });++ const wrapper = mount(AgentInput, {+ global: {+ plugins: [pinia, i18n],+ },+ });++ await wrapper.find("textarea").setValue("demo-project");+ await wrapper.find("button").trigger("click");+ await flushPromises();++ expect(mockBuildSystemPrompt).toHaveBeenCalledWith({+ path: "/projects/original",+ title: "Original Page",+ });+ expect(store.getThread(threadId)?.page).toEqual({+ path: "/projects/original",+ title: "Original Page",+ });+ });++ test("refreshes the saved thread page snapshot after navigate before a follow-up turn", async () => {+ const store = useAgentStore();+ const threadId = store.currentThreadId!;+ let runCount = 0;++ store.updateThreadPage(threadId, {+ path: "/projects/original",+ title: "Original Page",+ });++ mockCreateToolExecutor.mockImplementation((_router: unknown, _options) => {+ const options = _options as { onNavigate?: () => void } | undefined;+ return vi.fn(async (name: string) => {+ if (name !== "navigate") {+ throw new Error(`Unexpected tool: ${name}`);+ }+ mockRoute.fullPath = "/projects/navigated";+ document.title = "Navigated Page";+ options?.onNavigate?.();+ return {+ kind: "tool_result",+ result: JSON.stringify({+ navigated: true,+ currentPath: "/projects/navigated",+ }),+ };+ });+ });+ mockRunAgentLoop.mockImplementation(+ async (+ _messages: unknown,+ _tools: unknown,+ executor: (+ name: string,+ args: Record<string, unknown>,+ toolCallId: string+ ) => Promise<{ kind: string; result?: string }>,+ callbacks?: {+ onAssistantMessage?: (message: {+ content?: string;+ toolCalls?: unknown[];+ }) => void;+ onToolResult?: (toolCallId: string, result: string) => void;+ }+ ) => {+ runCount += 1;+ if (runCount === 1) {+ callbacks?.onAssistantMessage?.({+ content: "",+ toolCalls: [+ {+ id: "tool-nav",+ name: "navigate",+ arguments: JSON.stringify({ path: "/projects/navigated" }),+ },+ ],+ });+ const result = await executor(+ "navigate",+ { path: "/projects/navigated" },+ "tool-nav"+ );+ if (result.kind === "tool_result" && result.result) {+ callbacks?.onToolResult?.("tool-nav", result.result);+ }+ return {+ kind: "awaiting_user",+ ask: {+ toolCallId: "tool-ask",+ prompt: "Continue?",+ kind: "input",+ },+ };+ }+ return {+ kind: "completed",+ text: "Done",+ success: true,+ explicit: true,+ };+ }+ );++ const wrapper = mount(AgentInput, {+ global: {+ plugins: [pinia, i18n],+ },+ });++ await wrapper.find("textarea").setValue("navigate first");+ await wrapper.find("button").trigger("click");+ await flushPromises();++ expect(store.getThread(threadId)?.page).toEqual({+ path: "/projects/navigated",+ title: "Navigated Page",+ });+ expect(store.getPendingAsk(threadId)).toEqual({+ toolCallId: "tool-ask",+ prompt: "Continue?",+ kind: "input",+ });++ mockRoute.fullPath = "/projects/elsewhere";+ document.title = "Elsewhere Page";++ await wrapper.find("textarea").setValue("continue");+ await wrapper.find("button").trigger("click");+ await flushPromises();++ expect(mockBuildSystemPrompt).toHaveBeenNthCalledWith(1, {+ path: "/projects/original",+ title: "Original Page",+ });+ expect(mockBuildSystemPrompt).toHaveBeenNthCalledWith(2, {+ path: "/projects/navigated",+ title: "Navigated Page",+ });+ });++ test("keeps the latest run cancellable when an earlier aborted run settles late", async () => {+ const store = useAgentStore();+ const threadId = store.currentThreadId!;+ const firstRun = createDeferred<AgentLoopOutcome>();+ const secondRun = createDeferred<AgentLoopOutcome>();+ let firstSignal: AbortSignal | undefined;+ let secondSignal: AbortSignal | undefined;++ mockRunAgentLoop+ .mockImplementationOnce(+ async (+ _messages: unknown,+ _tools: unknown,+ _executor: unknown,+ _callbacks: unknown,+ signal?: AbortSignal+ ) => {+ firstSignal = signal;+ return firstRun.promise;+ }+ )+ .mockImplementationOnce(+ async (+ _messages: unknown,+ _tools: unknown,+ _executor: unknown,+ _callbacks: unknown,+ signal?: AbortSignal+ ) => {+ secondSignal = signal;+ return secondRun.promise;+ }+ );++ const wrapper = mount(AgentInput, {+ global: {+ plugins: [pinia, i18n],+ },+ });++ await wrapper.find("textarea").setValue("first request");+ await wrapper.find("button").trigger("click");+ await flushPromises();++ expect(store.abortController?.signal).toBe(firstSignal);+ expect(store.loading).toBe(true);++ await wrapper.find("button").trigger("click");+ await flushPromises();++ expect(firstSignal?.aborted).toBe(true);+ expect(store.abortController).toBeNull();+ expect(store.loading).toBe(false);++ await wrapper.find("textarea").setValue("second request");+ await wrapper.find("button").trigger("click");+ await flushPromises();++ expect(store.abortController?.signal).toBe(secondSignal);+ expect(store.loading).toBe(true);++ firstRun.resolve({ kind: "aborted" });+ await flushPromises();++ expect(store.abortController?.signal).toBe(secondSignal);+ expect(store.loading).toBe(true);+ expect(+ store+ .getMessages(threadId)+ .some((message) => message.content === "_Interrupted_")+ ).toBe(false);++ secondRun.resolve({+ kind: "completed",+ text: "Done",+ success: true,+ explicit: true,+ });+ await flushPromises();++ expect(store.abortController).toBeNull();+ expect(store.loading).toBe(false);+ });++ test("clears stale composer input when pending asks disappear", async () => {+ const store = useAgentStore();+ const threadId = store.currentThreadId!;++ store.awaitUser(threadId, {+ toolCallId: "tool-ask",+ prompt: "Which project should I use?",+ kind: "input",+ defaultValue: "demo-project",+ });++ const wrapper = mount(AgentInput, {+ global: {+ plugins: [pinia, i18n],+ },+ });++ expect(getTextareaValue(wrapper)).toBe("demo-project");+ await wrapper.find("textarea").setValue("stale input");++ store.clearPendingAsk(threadId);+ await flushPromises();++ expect(getTextareaValue(wrapper)).toBe("");+ });++ test("clears stale composer input when switching threads", async () => {+ const store = useAgentStore();+ const firstThreadId = store.currentThreadId!;++ store.awaitUser(firstThreadId, {+ toolCallId: "tool-ask",+ prompt: "Which project should I use?",+ kind: "input",+ defaultValue: "demo-project",+ });++ const secondThread = store.createThread({ title: "Second" });+ store.setCurrentThread(firstThreadId);++ const wrapper = mount(AgentInput, {+ global: {+ plugins: [pinia, i18n],+ },+ });++ expect(getTextareaValue(wrapper)).toBe("demo-project");+ await wrapper.find("textarea").setValue("stale input");++ store.setCurrentThread(secondThread.id);+ await flushPromises();+ expect(getTextareaValue(wrapper)).toBe("");++ store.setCurrentThread(firstThreadId);+ await flushPromises();+ expect(getTextareaValue(wrapper)).toBe("demo-project");+ });++ test("uses choose buttons to answer pending choose prompts", async () => {+ const store = useAgentStore();+ const threadId = store.currentThreadId!;++ store.addMessage({+ threadId,+ role: "assistant",+ toolCalls: [+ {+ id: "tool-choose",+ name: "ask_user",+ arguments: JSON.stringify({+ prompt: "Which environment should I use?",+ kind: "choose",+ options: [+ {+ label: "Production",+ value: "prod",+ description: "Use the production environment",+ },+ {+ label: "Staging",+ value: "staging",+ },+ ],+ }),+ },+ ],+ });+ store.awaitUser(threadId, {+ toolCallId: "tool-choose",+ prompt: "Which environment should I use?",+ kind: "choose",+ options: [+ {+ label: "Production",+ value: "prod",+ description: "Use the production environment",+ },+ {+ label: "Staging",+ value: "staging",+ },+ ],+ });++ mockRunAgentLoop.mockResolvedValue({+ kind: "completed",+ text: "Using production.",+ success: true,+ explicit: true,+ });++ const wrapper = mount(AgentInput, {+ global: {+ plugins: [pinia, i18n],+ },+ });++ const buttons = wrapper.findAll("button");+ expect(buttons).toHaveLength(2);+ await buttons[0].trigger("click");+ await flushPromises();++ const toolMessages = store+ .getMessages(threadId)+ .filter((message) => message.role === "tool");+ expect(toolMessages).toHaveLength(1);+ expect(JSON.parse(toolMessages[0].content ?? "{}")).toEqual({+ kind: "choose",+ answer: "Production",+ value: "prod",+ });+ expect(store.getPendingAsk(threadId)).toBeNull();+ expect(mockRunAgentLoop).toHaveBeenCalledTimes(1);+ });++ test("uses confirm buttons to answer pending confirmation prompts", async () => {+ const store = useAgentStore();+ const threadId = store.currentThreadId!;++ store.addMessage({+ threadId,+ role: "assistant",+ toolCalls: [+ {+ id: "tool-confirm",+ name: "ask_user",+ arguments: JSON.stringify({+ prompt: "Delete the database?",+ kind: "confirm",+ confirmLabel: "Delete",+ cancelLabel: "Keep it",+ }),+ },+ ],+ });+ store.awaitUser(threadId, {+ toolCallId: "tool-confirm",+ prompt: "Delete the database?",+ kind: "confirm",+ confirmLabel: "Delete",+ cancelLabel: "Keep it",+ });++ mockRunAgentLoop.mockResolvedValue({+ kind: "completed",+ text: "Canceled.",+ success: true,+ explicit: true,+ });++ const wrapper = mount(AgentInput, {+ global: {+ plugins: [pinia, i18n],+ },+ });++ const buttons = wrapper.findAll("button");+ expect(buttons).toHaveLength(2);+ await buttons[0].trigger("click");+ await flushPromises();++ const toolMessages = store+ .getMessages(threadId)+ .filter((message) => message.role === "tool");+ expect(toolMessages).toHaveLength(1);+ expect(JSON.parse(toolMessages[0].content ?? "{}")).toEqual({+ kind: "confirm",+ answer: "Delete",+ confirmed: true,+ });+ expect(store.getPendingAsk(threadId)).toBeNull();+ expect(mockRunAgentLoop).toHaveBeenCalledTimes(1);+ });+});diff --git a/frontend/src/plugins/agent/components/AgentInput.vue b/frontend/src/plugins/agent/components/AgentInput.vueindex 629353752a..4c9e0666b9 100644--- a/frontend/src/plugins/agent/components/AgentInput.vue+++ b/frontend/src/plugins/agent/components/AgentInput.vue@@ -1,11 +1,11 @@<script setup lang="ts">-import { ref } from "vue";+import { computed, ref, watch } from "vue";import { useI18n } from "vue-i18n";import { useRoute, useRouter } from "vue-router";import { runAgentLoop } from "../logic/agentLoop";import { buildSystemPrompt } from "../logic/prompt";import { createToolExecutor, getToolDefinitions } from "../logic/tools";-import type { Message } from "../logic/types";+import type { AgentAskUserOption, Message } from "../logic/types";import { useAgentStore } from "../store/agent";const { t } = useI18n();@@ -13,108 +13,406 @@ const router = useRouter();const route = useRoute();const agentStore = useAgentStore();const input = ref("");+let currentRunToken = 0;-async function send() {- const text = input.value.trim();- if (!text || agentStore.loading) return;- agentStore.clearError();- input.value = "";+const currentPendingAsk = computed(() => agentStore.currentPendingAsk);+const chooseOptions = computed(() =>+ currentPendingAsk.value?.kind === "choose"+ ? (currentPendingAsk.value.options ?? [])+ : []+);+const isAwaitingConfirm = computed(+ () => currentPendingAsk.value?.kind === "confirm"+);+const isAwaitingChoose = computed(+ () =>+ currentPendingAsk.value?.kind === "choose" && chooseOptions.value.length > 0+);+const sendLabel = computed(() =>+ currentPendingAsk.value ? t("agent.reply") : t("agent.send")+);+const inputPlaceholder = computed(() => {+ if (currentPendingAsk.value?.kind === "input") {+ return currentPendingAsk.value.prompt;+ }+ if (currentPendingAsk.value?.kind === "choose") {+ return currentPendingAsk.value.prompt;+ }+ return t("agent.input-placeholder");+});+const confirmLabel = computed(+ () => currentPendingAsk.value?.confirmLabel ?? t("agent.confirm")+);+const cancelLabel = computed(+ () => currentPendingAsk.value?.cancelLabel ?? t("agent.cancel")+);+const isSendDisabled = computed(() => {+ if (+ agentStore.hasRunningThread ||+ isAwaitingConfirm.value ||+ isAwaitingChoose.value+ ) {+ return true;+ }+ return !input.value.trim();+});- agentStore.addMessage({ role: "user", content: text });- agentStore.loading = true;+const getThreadPageSnapshot = (threadId: string) => {+ return agentStore.getThread(threadId)?.page;+};- const controller = new AbortController();- agentStore.abortController = controller;+const resolveThreadPageSnapshot = (+ threadId: string,+ fallbackPage: { path: string; title: string }+) => {+ return getThreadPageSnapshot(threadId) ?? fallbackPage;+};- const systemPrompt = buildSystemPrompt({- path: route.fullPath,- title: document.title,- });+const getCurrentPageSnapshot = () => ({+ path: route.fullPath,+ title: document.title,+});- const allMessages: Message[] = [+const buildConversation = (+ threadId: string,+ systemPrompt: string+): Message[] => {+ return [{ role: "system", content: systemPrompt },- ...agentStore.messages,+ ...agentStore.getMessages(threadId),];+};+const handleOutcome = (+ threadId: string,+ page: { path: string; title: string },+ errorPrefix: string,+ outcome: Awaited<ReturnType<typeof runAgentLoop>>+) => {+ switch (outcome.kind) {+ case "completed":+ agentStore.finishRun(threadId);+ return;+ case "awaiting_user":+ agentStore.awaitUser(threadId, outcome.ask);+ return;+ case "aborted":+ agentStore.addMessage({+ threadId,+ role: "assistant",+ content: `_${t("agent.interrupted")}_`,+ metadata: {+ route: page.path,+ },+ });+ agentStore.finishRun(threadId);+ return;+ case "error":+ agentStore.addMessage({+ threadId,+ role: "assistant",+ content: `${errorPrefix}${outcome.error.message}`,+ metadata: {+ route: page.path,+ error: outcome.error.message,+ },+ });+ agentStore.finishRun(threadId, {+ status: "error",+ lastError: outcome.error.message,+ });+ return;+ }+};++async function runThread(+ threadId: string,+ page: { path: string; title: string }+) {+ const controller = new AbortController();+ const runToken = ++currentRunToken;+ agentStore.abortController = controller;++ const systemPrompt = buildSystemPrompt(page);const tools = getToolDefinitions();- const executor = createToolExecutor(router);+ const executor = createToolExecutor(router, {+ onNavigate: () => {+ agentStore.updateThreadPage(threadId, getCurrentPageSnapshot());+ },+ });try {- await runAgentLoop(- allMessages,+ const outcome = await runAgentLoop(+ buildConversation(threadId, systemPrompt),tools,executor,{- onToolCall: (tc) => {- // The agent loop calls onToolCall for each tool call in an assistant- // turn. All tool calls from the same turn arrive before any- // onToolResult. We batch them into one assistant message.- const lastMsg = agentStore.messages[agentStore.messages.length - 1];- if (- lastMsg?.role === "assistant" &&- lastMsg.toolCalls &&- !agentStore.messages.some(- (m) =>- m.role === "tool" &&- lastMsg.toolCalls!.some((t) => t.id === m.toolCallId)- )- ) {- // Same turn — append to existing assistant message- lastMsg.toolCalls.push(tc);- } else {- agentStore.addMessage({- role: "assistant",- toolCalls: [tc],- });+ onAssistantMessage: (message) => {+ if (!message.content && !message.toolCalls?.length) {+ return;}+ agentStore.addMessage({+ threadId,+ role: "assistant",+ content: message.content,+ toolCalls: message.toolCalls,+ metadata: {+ route: page.path,+ },+ });},onToolResult: (toolCallId, result) => {agentStore.addMessage({+ threadId,role: "tool",toolCallId,content: result,+ metadata: {+ route: page.path,+ },});},onText: (text) => {+ if (!text) {+ return;+ }agentStore.addMessage({+ threadId,role: "assistant",content: text,+ metadata: {+ route: page.path,+ },});},},controller.signal);- } catch (err) {- const error = err instanceof Error ? err : new Error(String(err));- // AbortError from DOMException or ConnectError with "[canceled]"- const isAbort =- error.name === "AbortError" || error.message.includes("[canceled]");- if (isAbort) {- agentStore.addMessage({- role: "assistant",- content: `_${t("agent.interrupted")}_`,- });- } else {- agentStore.addMessage({- role: "assistant",- content: `Error: ${error.message}`,- });++ if (runToken !== currentRunToken) {+ return;}++ handleOutcome(threadId, page, "Error: ", outcome);} finally {- agentStore.loading = false;- agentStore.abortController = null;+ if (+ runToken === currentRunToken &&+ agentStore.abortController === controller+ ) {+ agentStore.abortController = null;+ }+ }+}++async function send() {+ if (agentStore.hasRunningThread) {+ return;+ }++ const currentPage = getCurrentPageSnapshot();+ const thread = agentStore.ensureCurrentThread(currentPage);+ const threadId = thread.id;+ const threadPage = resolveThreadPageSnapshot(threadId, currentPage);++ agentStore.clearError(threadId);++ if (currentPendingAsk.value) {+ const answer = input.value.trim();+ if (!answer) {+ return;+ }+ input.value = "";++ if (currentPendingAsk.value.kind === "choose") {+ agentStore.answerPendingAsk(+ threadId,+ {+ kind: "choose",+ answer,+ value: answer,+ },+ {+ route: currentPage.path,+ }+ );+ } else if (currentPendingAsk.value.kind === "input") {+ agentStore.answerPendingAsk(+ threadId,+ {+ kind: "input",+ answer,+ },+ {+ route: currentPage.path,+ }+ );+ } else {+ return;+ }+ agentStore.startRun(threadId, threadPage);+ await runThread(threadId, threadPage);+ return;+ }++ const text = input.value.trim();+ if (!text) {+ return;}++ input.value = "";+ agentStore.addMessage({+ threadId,+ role: "user",+ content: text,+ metadata: {+ route: currentPage.path,+ },+ });+ agentStore.startRun(threadId, threadPage);+ await runThread(threadId, threadPage);}++async function submitConfirmation(confirmed: boolean) {+ const pendingAsk = currentPendingAsk.value;+ if (+ !pendingAsk ||+ pendingAsk.kind !== "confirm" ||+ agentStore.hasRunningThread+ ) {+ return;+ }++ const currentPage = getCurrentPageSnapshot();+ const thread = agentStore.ensureCurrentThread(currentPage);+ const threadId = thread.id;+ const threadPage = resolveThreadPageSnapshot(threadId, currentPage);+ const answer = confirmed ? confirmLabel.value : cancelLabel.value;++ agentStore.clearError(threadId);+ agentStore.answerPendingAsk(+ threadId,+ {+ kind: "confirm",+ answer,+ confirmed,+ },+ {+ route: currentPage.path,+ }+ );+ agentStore.startRun(threadId, threadPage);+ await runThread(threadId, threadPage);+}++async function submitChoice(option: AgentAskUserOption) {+ const pendingAsk = currentPendingAsk.value;+ if (+ !pendingAsk ||+ pendingAsk.kind !== "choose" ||+ agentStore.hasRunningThread+ ) {+ return;+ }++ const currentPage = getCurrentPageSnapshot();+ const thread = agentStore.ensureCurrentThread(currentPage);+ const threadId = thread.id;+ const threadPage = resolveThreadPageSnapshot(threadId, currentPage);++ agentStore.clearError(threadId);+ agentStore.answerPendingAsk(+ threadId,+ {+ kind: "choose",+ answer: option.label,+ value: option.value,+ },+ {+ route: currentPage.path,+ }+ );+ agentStore.startRun(threadId, threadPage);+ await runThread(threadId, threadPage);+}++watch(+ () => [+ agentStore.currentThreadId,+ currentPendingAsk.value?.toolCallId,+ currentPendingAsk.value?.kind,+ currentPendingAsk.value?.defaultValue,+ ],+ () => {+ if (+ currentPendingAsk.value?.kind === "input" ||+ currentPendingAsk.value?.kind === "choose"+ ) {+ input.value = currentPendingAsk.value.defaultValue ?? "";+ return;+ }+ input.value = "";+ },+ { immediate: true }+);</script><template><div class="border-t p-3">- <div class="flex items-end gap-x-2">+ <div+ v-if="currentPendingAsk"+ class="mb-3 rounded-md bg-amber-50 px-3 py-2 text-xs text-amber-700"+ >+ <div class="font-medium">{{ currentPendingAsk.prompt }}</div>+ <div class="mt-1">+ {{+ currentPendingAsk.kind === "confirm"+ ? $t("agent.pending-confirm-hint")+ : currentPendingAsk.kind === "choose"+ ? $t("agent.pending-choose-hint")+ : $t("agent.pending-input-hint")+ }}+ </div>+ </div>++ <div v-if="isAwaitingConfirm" class="flex flex-wrap gap-x-2 gap-y-2">+ <button+ class="rounded-md bg-blue-500 px-3 py-2 text-sm text-white hover:bg-blue-600 disabled:opacity-50"+ :disabled="agentStore.hasRunningThread"+ @click="submitConfirmation(true)"+ >+ {{ confirmLabel }}+ </button>+ <button+ class="rounded-md border px-3 py-2 text-sm text-gray-700 hover:bg-gray-50 disabled:opacity-50"+ :disabled="agentStore.hasRunningThread"+ @click="submitConfirmation(false)"+ >+ {{ cancelLabel }}+ </button>+ </div>++ <div v-else-if="isAwaitingChoose" class="flex flex-col gap-y-2">+ <button+ 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"+ @click="submitChoice(option)"+ >+ <div class="font-medium text-gray-800">{{ option.label }}</div>+ <div v-if="option.description" class="mt-1 text-xs text-gray-500">+ {{ option.description }}+ </div>+ </button>+ </div>++ <div v-else class="flex items-end gap-x-2"><textareav-model="input"rows="1"- :placeholder="$t('agent.input-placeholder')"- class="flex-1 resize-none rounded-md border px-3 py-2 text-sm focus:outline-none focus:ring-1 focus:ring-blue-500"+ :placeholder="inputPlaceholder"+ class="flex-1 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"@keydown.enter.exact.prevent="send"/><button@@ -127,10 +425,10 @@ async function send() {<buttonv-elseclass="rounded-md bg-blue-500 px-3 py-2 text-sm text-white hover:bg-blue-600 disabled:opacity-50"- :disabled="!input.trim()"+ :disabled="isSendDisabled"@click="send">- {{ $t("agent.send") }}+ {{ sendLabel }}</button></div></div>diff --git a/frontend/src/plugins/agent/components/AgentWindow.vue b/frontend/src/plugins/agent/components/AgentWindow.vueindex 29813f0b12..d0d5822ba0 100644--- a/frontend/src/plugins/agent/components/AgentWindow.vue+++ b/frontend/src/plugins/agent/components/AgentWindow.vue@@ -1,9 +1,14 @@<script setup lang="ts">import { computed, onBeforeUnmount, onMounted, ref, watch } from "vue";+import { useI18n } from "vue-i18n";+import { useRoute } from "vue-router";+import type { AgentThread } from "../logic/types";import { useAgentStore } from "../store/agent";import AgentChat from "./AgentChat.vue";import AgentInput from "./AgentInput.vue";+const { t } = useI18n();+const route = useRoute();const agentStore = useAgentStore();const MIN_WIDTH = 300;@@ -71,6 +76,40 @@ 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");+ }+ if (thread.interrupted) {+ return t("agent.thread-status-interrupted");+ }+ switch (thread.status) {+ case "running":+ return t("agent.thread-status-running");+ case "awaiting_user":+ return t("agent.thread-status-awaiting-user");+ case "error":+ return t("agent.thread-status-error");+ default:+ return t("agent.thread-status-idle");+ }+});+const currentThreadStatusClass = computed(() => {+ const thread = agentStore.currentThread;+ if (!thread || thread.status === "idle") {+ return "bg-gray-100 text-gray-600";+ }+ if (thread.status === "running") {+ return "bg-blue-50 text-blue-600";+ }+ if (thread.interrupted || thread.status === "error") {+ return "bg-red-50 text-red-600";+ }+ return "bg-amber-50 text-amber-600";+});+function syncSize(width: number, height: number) {const size = getDisplaySize(width, height);agentStore.size.width = size.width;@@ -94,14 +133,29 @@ function syncStoreToDisplayState() {agentStore.position.y = displayWindowState.value.position.y;}-// Drag logic+const getCurrentPageSnapshot = () => ({+ path: route.fullPath,+ 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 isDragging = ref(false);const dragOffset = ref({ x: 0, y: 0 });-function startDrag(e: MouseEvent) {+function startDrag(event: MouseEvent) {if (- e.target instanceof HTMLElement &&- e.target.closest("[data-agent-window-action], [data-agent-window-resize]")+ event.target instanceof HTMLElement &&+ event.target.closest(+ "[data-agent-window-action], [data-agent-window-resize]"+ )) {return;}@@ -109,17 +163,19 @@ function startDrag(e: MouseEvent) {syncStoreToDisplayState();isDragging.value = true;dragOffset.value = {- x: e.clientX - agentStore.position.x,- y: e.clientY - agentStore.position.y,+ x: event.clientX - agentStore.position.x,+ y: event.clientY - agentStore.position.y,};document.addEventListener("mousemove", onDrag);document.addEventListener("mouseup", stopDrag);}-function onDrag(e: MouseEvent) {- if (!isDragging.value) return;- agentStore.position.x = e.clientX - dragOffset.value.x;- agentStore.position.y = e.clientY - dragOffset.value.y;+function onDrag(event: MouseEvent) {+ if (!isDragging.value) {+ return;+ }+ agentStore.position.x = event.clientX - dragOffset.value.x;+ agentStore.position.y = event.clientY - dragOffset.value.y;syncPosition();}@@ -130,19 +186,18 @@ function stopDrag() {agentStore.saveWindowState();}-// Resize logicconst isResizing = ref(false);const resizeStart = ref({ x: 0, y: 0, w: 0, h: 0 });let resizeObserver: ResizeObserver | null = null;-function startResize(e: MouseEvent) {- e.preventDefault();- e.stopPropagation();+function startResize(event: MouseEvent) {+ event.preventDefault();+ event.stopPropagation();syncStoreToDisplayState();isResizing.value = true;resizeStart.value = {- x: e.clientX,- y: e.clientY,+ x: event.clientX,+ y: event.clientY,w: agentStore.size.width,h: agentStore.size.height,};@@ -150,10 +205,12 @@ function startResize(e: MouseEvent) {document.addEventListener("mouseup", stopResize);}-function onResize(e: MouseEvent) {- if (!isResizing.value) return;- const dx = e.clientX - resizeStart.value.x;- const dy = e.clientY - resizeStart.value.y;+function onResize(event: MouseEvent) {+ if (!isResizing.value) {+ return;+ }+ const dx = event.clientX - resizeStart.value.x;+ const dy = event.clientY - resizeStart.value.y;syncSize(resizeStart.value.w + dx, resizeStart.value.h + dy);syncPosition();}@@ -167,14 +224,15 @@ function stopResize() {function observeWindowSize() {resizeObserver?.disconnect();- if (!windowRef.value) return;+ if (!windowRef.value) {+ return;+ }resizeObserver = new ResizeObserver(([entry]) => {- if (!entry || isResizing.value || isViewportResizing.value) return;+ if (!entry || isResizing.value || isViewportResizing.value) {+ return;+ }- // `contentRect` excludes borders, but the inline width/height we persist are- // border-box dimensions. Reading the content box here creates a feedback loop- // where every observer callback writes a slightly smaller size back.const target = entry.target as HTMLElement;const width = clampWidth(target.offsetWidth);const height = clampHeight(target.offsetHeight);@@ -206,6 +264,19 @@ watch(windowRef, () => {observeWindowSize();});+function createThread() {+ agentStore.createThread({ page: getCurrentPageSnapshot() });+}++function resetCurrentThread() {+ agentStore.clearConversation();+}++function selectThread(event: Event) {+ const target = event.target as HTMLSelectElement;+ agentStore.setCurrentThread(target.value);+}+onMounted(() => {agentStore.loadWindowState();handleViewportResize();@@ -224,7 +295,6 @@ onBeforeUnmount(() => {<template><Teleport to="body">- <!-- Minimized button --><divv-if="agentStore.visible && agentStore.minimized"data-agent-window@@ -245,72 +315,92 @@ onBeforeUnmount(() => {</svg></div>- <!-- Full window --><divv-if="agentStore.visible && !agentStore.minimized"ref="windowRef"data-agent-window- class="fixed z-[1999] flex resize flex-col overflow-hidden rounded-lg border border-gray-200 bg-white shadow-xl"+ class="fixed z-[1999] flex flex-col overflow-hidden rounded-lg border border-gray-200 bg-white shadow-xl":style="windowStyle">- <!-- Title bar --><div- class="cursor-move select-none border-b bg-gray-50 px-3 py-2"+ class="flex cursor-move select-none items-center justify-between border-b bg-gray-50 px-3 py-2"@mousedown="startDrag">- <div class="flex items-center justify-between gap-x-2">- <span class="text-sm font-medium">{{ $t("agent.assistant-title") }}</span>- <div class="flex items-center gap-x-1">- <button- data-agent-window-action- class="flex h-5 w-5 items-center justify-center rounded text-gray-400 hover:bg-gray-200 hover:text-gray-600"- :title="$t('agent.new-chat')"- @click.stop="agentStore.clearMessages()"- >- <svg- xmlns="http://www.w3.org/2000/svg"- class="h-3.5 w-3.5"- viewBox="0 0 20 20"- fill="currentColor"- >- <path- fill-rule="evenodd"- d="M4 2a1 1 0 011 1v2.101a7.002 7.002 0 0111.601 2.566 1 1 0 11-1.885.666A5.002 5.002 0 005.999 7H9a1 1 0 010 2H4a1 1 0 01-1-1V3a1 1 0 011-1zm.008 9.057a1 1 0 011.276.61A5.002 5.002 0 0014.001 13H11a1 1 0 110-2h5a1 1 0 011 1v5a1 1 0 11-2 0v-2.101a7.002 7.002 0 01-11.601-2.566 1 1 0 01.61-1.276z"- clip-rule="evenodd"- />- </svg>- </button>- <button- data-agent-window-action- class="flex h-5 w-5 items-center justify-center rounded text-gray-400 hover:bg-gray-200 hover:text-gray-600"- :title="$t('agent.minimize')"- @click.stop="agentStore.minimize()"- >- −- </button>- <button- data-agent-window-action- class="flex h-5 w-5 items-center justify-center rounded text-gray-400 hover:bg-gray-200 hover:text-gray-600"- :title="$t('agent.close')"- @click.stop="agentStore.toggle()"+ <div class="flex min-w-0 items-center gap-x-2">+ <span class="truncate text-sm font-medium">+ {{ $t("agent.assistant-title") }}+ </span>+ <span+ class="inline-flex rounded-full px-2 py-0.5 text-xs font-medium"+ :class="currentThreadStatusClass"+ >+ {{ currentThreadStatusLabel }}+ </span>+ </div>+ <div class="flex items-center gap-x-1">+ <button+ data-agent-window-action+ class="flex h-5 w-5 items-center justify-center rounded text-gray-400 hover:bg-gray-200 hover:text-gray-600"+ :title="$t('agent.minimize')"+ @click.stop="agentStore.minimize()"+ >+ −+ </button>+ <button+ data-agent-window-action+ class="flex h-5 w-5 items-center justify-center rounded text-gray-400 hover:bg-gray-200 hover:text-gray-600"+ :title="$t('agent.close')"+ @click.stop="agentStore.toggle()"+ >+ ✕+ </button>+ </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">- ✕- </button>- </div>+ {{ 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></div>- <!-- Chat --><AgentChat class="min-h-0 flex-1" />-- <!-- Input --><AgentInput />- <!-- Resize handle --><buttontype="button"+ data-agent-window-actiondata-agent-window-resize- class="absolute bottom-0 right-0 flex h-5 w-5 cursor-se-resize items-end justify-end pr-0.5 pb-0.5 text-gray-300 hover:text-gray-400"+ class="absolute bottom-0 right-0 flex h-5 w-5 cursor-se-resize items-end justify-end pb-0.5 pr-0.5 text-gray-300 hover:text-gray-400":title="$t('agent.resize')"@mousedown="startResize">diff --git a/frontend/src/plugins/agent/components/ToolCallCard.vue b/frontend/src/plugins/agent/components/ToolCallCard.vueindex 7948782f98..b22b68ddc9 100644--- a/frontend/src/plugins/agent/components/ToolCallCard.vue+++ b/frontend/src/plugins/agent/components/ToolCallCard.vue@@ -1,45 +1,273 @@<script setup lang="ts">-import { ref } from "vue";-import type { ToolCall } from "../logic/types";+import { computed, ref } from "vue";+import type {+ AgentAskUserOption,+ AgentAskUserResponse,+ ToolCall,+} from "../logic/types";-defineProps<{+const props = defineProps<{toolCall: ToolCall;result?: string;}>();const expanded = ref(false);-function formatJson(value: string): string {+const parseJson = (value?: string): unknown => {+ if (!value) {+ return undefined;+ }+ try {+ return JSON.parse(value);+ } catch {+ return value;+ }+};++const formatJson = (value?: string): string => {+ if (!value) {+ return "";+ }try {return JSON.stringify(JSON.parse(value), null, 2);} catch {return value;}-}+};++const parseAskUserOption = (value: unknown): AgentAskUserOption | null => {+ if (!value || typeof value !== "object") {+ return null;+ }++ const option = value as Record<string, unknown>;+ const label =+ typeof option.label === "string"+ ? option.label.trim()+ : typeof option.value === "string"+ ? option.value.trim()+ : "";+ const optionValue =+ typeof option.value === "string" ? option.value.trim() : "";++ if (!label || !optionValue) {+ return null;+ }++ return {+ label,+ value: optionValue,+ description:+ typeof option.description === "string" && option.description.trim()+ ? option.description.trim()+ : undefined,+ };+};++const resultText = computed(() => props.result ?? "");+const parsedArguments = computed(() => parseJson(props.toolCall.arguments));+const parsedResult = computed(() => parseJson(resultText.value));+const isAskUser = computed(() => props.toolCall.name === "ask_user");+const isDone = computed(() => props.toolCall.name === "done");+const askPrompt = computed(() => {+ if (+ typeof parsedArguments.value === "object" &&+ parsedArguments.value &&+ "prompt" in parsedArguments.value &&+ typeof parsedArguments.value.prompt === "string"+ ) {+ return parsedArguments.value.prompt;+ }+ return "";+});+const askKind = computed(() => {+ if (+ typeof parsedArguments.value === "object" &&+ parsedArguments.value &&+ "kind" in parsedArguments.value+ ) {+ if (parsedArguments.value.kind === "confirm") {+ return "confirm";+ }+ if (parsedArguments.value.kind === "choose") {+ return "choose";+ }+ }+ return "input";+});+const askDefaultValue = computed(() => {+ if (+ typeof parsedArguments.value === "object" &&+ parsedArguments.value &&+ "defaultValue" in parsedArguments.value &&+ typeof parsedArguments.value.defaultValue === "string"+ ) {+ return parsedArguments.value.defaultValue;+ }+ return "";+});+const askOptions = computed<AgentAskUserOption[]>(() => {+ if (+ typeof parsedArguments.value !== "object" ||+ !parsedArguments.value ||+ !("options" in parsedArguments.value) ||+ !Array.isArray(parsedArguments.value.options)+ ) {+ return [];+ }++ return parsedArguments.value.options+ .map((option) => parseAskUserOption(option))+ .filter((option): option is AgentAskUserOption => !!option);+});+const askResponse = computed<AgentAskUserResponse | null>(() => {+ if (+ typeof parsedResult.value !== "object" ||+ !parsedResult.value ||+ !("kind" in parsedResult.value) ||+ typeof parsedResult.value.kind !== "string" ||+ !("answer" in parsedResult.value) ||+ typeof parsedResult.value.answer !== "string"+ ) {+ return null;+ }++ const response = parsedResult.value as Record<string, unknown>;++ if (response.kind === "confirm") {+ if (typeof response.confirmed !== "boolean") {+ return null;+ }+ return response as AgentAskUserResponse;+ }++ if (response.kind === "choose") {+ if (typeof response.value !== "string") {+ return null;+ }+ return response as AgentAskUserResponse;+ }++ if (response.kind === "input") {+ return response as AgentAskUserResponse;+ }++ return null;+});+const doneText = computed(() => {+ if (+ typeof parsedArguments.value === "object" &&+ parsedArguments.value &&+ "text" in parsedArguments.value &&+ typeof parsedArguments.value.text === "string"+ ) {+ return parsedArguments.value.text;+ }+ return "";+});+const doneSuccess = computed(() => {+ if (+ typeof parsedArguments.value === "object" &&+ parsedArguments.value &&+ "success" in parsedArguments.value+ ) {+ return parsedArguments.value.success !== false;+ }+ return true;+});</script><template><div class="rounded border bg-gray-50 text-xs"><div- class="flex items-center gap-x-2 px-2 py-1.5 cursor-pointer"+ class="flex cursor-pointer items-center gap-x-2 px-2 py-1.5"@click="expanded = !expanded"><span class="font-mono text-gray-600">{{ toolCall.name }}</span>- <span v-if="result" class="text-green-500">✓</span>- <span v-else class="animate-pulse text-gray-400">●</span>+ <template v-if="isAskUser">+ <span v-if="resultText" class="text-green-500">+ {{ $t("agent.tool-response-submitted") }}+ </span>+ <span v-else class="text-amber-600">{{ $t("agent.tool-ask-user") }}</span>+ </template>+ <template v-else-if="isDone">+ <span :class="doneSuccess ? 'text-green-500' : 'text-red-500'">+ {{ doneSuccess ? $t("agent.tool-completed") : $t("agent.tool-failed") }}+ </span>+ </template>+ <template v-else>+ <span v-if="resultText" class="text-green-500">✓</span>+ <span v-else class="animate-pulse text-gray-400">●</span>+ </template><span class="ml-auto text-gray-400">{{ expanded ? "\u25BE" : "\u25B8" }}</span></div>- <div v-if="expanded" class="border-t px-2 py-1.5 space-y-1">- <div class="text-gray-500">{{ $t("agent.args") }}</div>- <pre class="text-gray-700 whitespace-pre-wrap break-all">{{- formatJson(toolCall.arguments)- }}</pre>- <template v-if="result">++ <div v-if="expanded" class="space-y-1 border-t px-2 py-1.5">+ <template v-if="isAskUser">+ <div class="text-gray-500">+ {{+ askKind === "confirm"+ ? $t("agent.tool-ask-user-confirm")+ : askKind === "choose"+ ? $t("agent.tool-ask-user-choose")+ : $t("agent.tool-ask-user-input")+ }}+ </div>+ <div class="text-gray-500">{{ $t("agent.tool-prompt") }}</div>+ <pre class="whitespace-pre-wrap break-all text-gray-700">{{ askPrompt }}</pre>+ <template v-if="askDefaultValue">+ <div class="text-gray-500">{{ $t("agent.tool-default-value") }}</div>+ <pre class="whitespace-pre-wrap break-all text-gray-700">{{+ askDefaultValue+ }}</pre>+ </template>+ <template v-if="askKind === 'choose' && askOptions.length > 0">+ <div class="text-gray-500">{{ $t("agent.tool-options") }}</div>+ <div class="space-y-1">+ <div+ v-for="option in askOptions"+ :key="option.value"+ class="rounded border border-gray-200 bg-white px-2 py-1"+ >+ <div class="font-medium text-gray-700">{{ option.label }}</div>+ <div class="text-gray-500">{{ option.value }}</div>+ <div v-if="option.description" class="text-gray-500">+ {{ option.description }}+ </div>+ </div>+ </div>+ </template>+ <template v-if="askResponse">+ <div class="text-gray-500">{{ $t("agent.tool-answer") }}</div>+ <pre class="whitespace-pre-wrap break-all text-gray-700">{{+ askResponse.answer+ }}</pre>+ <template v-if="askResponse.kind === 'choose'">+ <div class="text-gray-500">{{ $t("agent.tool-value") }}</div>+ <pre class="whitespace-pre-wrap break-all text-gray-700">{{+ askResponse.value+ }}</pre>+ </template>+ </template>+ </template>++ <template v-else-if="isDone"><div class="text-gray-500">{{ $t("agent.result") }}</div>- <pre- class="text-gray-700 whitespace-pre-wrap break-all max-h-32 overflow-y-auto"- >{{ formatJson(result) }}</pre- >+ <pre class="whitespace-pre-wrap break-all text-gray-700">{{ doneText }}</pre>+ </template>++ <template v-else>+ <div class="text-gray-500">{{ $t("agent.args") }}</div>+ <pre class="whitespace-pre-wrap break-all text-gray-700">{{+ formatJson(toolCall.arguments)+ }}</pre>+ <template v-if="resultText">+ <div class="text-gray-500">{{ $t("agent.result") }}</div>+ <pre+ class="max-h-32 overflow-y-auto whitespace-pre-wrap break-all text-gray-700"+ >{{ formatJson(resultText) }}</pre+ >+ </template></template></div></div>diff --git a/frontend/src/plugins/agent/logic/agentLoop.test.ts b/frontend/src/plugins/agent/logic/agentLoop.test.tsnew file mode 100644index 0000000000..ab6f2d5f80--- /dev/null+++ b/frontend/src/plugins/agent/logic/agentLoop.test.ts@@ -0,0 +1,417 @@+import { beforeEach, describe, expect, test, vi } from "vitest";+import { aiServiceClientConnect } from "@/connect";+import { AIChatMessageRole } from "@/types/proto-es/v1/ai_service_pb";+import { runAgentLoop } from "./agentLoop";+import type { ToolExecutor } from "./types";++vi.mock("@/connect", () => ({+ aiServiceClientConnect: {+ chat: vi.fn(),+ },+}));++describe("runAgentLoop", () => {+ beforeEach(() => {+ vi.mocked(aiServiceClientConnect.chat).mockReset();+ });++ test("returns a completed outcome for explicit done", async () => {+ vi.mocked(aiServiceClientConnect.chat).mockResolvedValue({+ content: "",+ toolCalls: [+ {+ id: "tool-1",+ name: "done",+ arguments: JSON.stringify({+ text: "Finished successfully",+ success: true,+ }),+ metadata: "",+ },+ ],+ } as never);++ const executeTool: ToolExecutor = vi.fn(+ async (_name, args: Record<string, unknown>) => ({+ kind: "done" as const,+ text: String(args.text),+ success: args.success !== false,+ })+ );+ const onText = vi.fn();+ const onAssistantMessage = vi.fn();+ const onToolResult = vi.fn();++ const outcome = await runAgentLoop(+ [{ role: "system", content: "system" }],+ [],+ executeTool,+ { onText, onAssistantMessage, onToolResult }+ );++ expect(outcome).toEqual({+ kind: "completed",+ text: "Finished successfully",+ success: true,+ explicit: true,+ });+ expect(onToolResult).toHaveBeenCalledWith(+ "tool-1",+ JSON.stringify({+ text: "Finished successfully",+ success: true,+ })+ );+ expect(onText).toHaveBeenCalledWith("Finished successfully");+ expect(onAssistantMessage).toHaveBeenCalledWith({+ role: "assistant",+ content: "",+ toolCalls: [+ {+ id: "tool-1",+ name: "done",+ arguments: JSON.stringify({+ text: "Finished successfully",+ success: true,+ }),+ metadata: "",+ },+ ],+ });+ });++ test("replays completed tool flows with matched tool results", async () => {+ vi.mocked(aiServiceClientConnect.chat)+ .mockResolvedValueOnce({+ content: "",+ toolCalls: [+ {+ id: "tool-1",+ name: "done",+ arguments: JSON.stringify({+ text: "Finished successfully",+ success: true,+ }),+ metadata: "",+ },+ ],+ } as never)+ .mockResolvedValueOnce({+ content: "Follow-up answer",+ toolCalls: [],+ } as never);++ const executeTool: ToolExecutor = vi.fn(+ async (_name, args: Record<string, unknown>) => ({+ kind: "done" as const,+ text: String(args.text),+ success: args.success !== false,+ })+ );++ const completed = await runAgentLoop(+ [{ role: "system", content: "system" }],+ [],+ executeTool+ );+ expect(completed.kind).toBe("completed");++ await runAgentLoop(+ [+ { role: "system", content: "system" },+ {+ role: "assistant",+ content: "",+ toolCalls: [+ {+ id: "tool-1",+ name: "done",+ arguments: JSON.stringify({+ text: "Finished successfully",+ success: true,+ }),+ metadata: "",+ },+ ],+ },+ {+ role: "tool",+ toolCallId: "tool-1",+ content: JSON.stringify({+ text: "Finished successfully",+ success: true,+ }),+ },+ { role: "assistant", content: "Finished successfully" },+ { role: "user", content: "What next?" },+ ],+ [],+ vi.fn()+ );++ expect(aiServiceClientConnect.chat).toHaveBeenCalledTimes(2);+ const secondCallMessages = vi.mocked(aiServiceClientConnect.chat).mock+ .calls[1]?.[0].messages;+ expect(secondCallMessages).toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ role: AIChatMessageRole.AI_CHAT_MESSAGE_ROLE_ASSISTANT,+ toolCalls: [+ expect.objectContaining({+ id: "tool-1",+ name: "done",+ }),+ ],+ }),+ expect.objectContaining({+ role: AIChatMessageRole.AI_CHAT_MESSAGE_ROLE_TOOL,+ toolCallId: "tool-1",+ content: JSON.stringify({+ text: "Finished successfully",+ success: true,+ }),+ }),+ ])+ );+ });+ test("keeps plain assistant text as a compatibility fallback", async () => {+ vi.mocked(aiServiceClientConnect.chat).mockResolvedValue({+ content: "Here is the answer",+ toolCalls: [],+ } as never);++ const executeTool: ToolExecutor = vi.fn();+ const onText = vi.fn();++ const outcome = await runAgentLoop(+ [{ role: "system", content: "system" }],+ [],+ executeTool,+ { onText }+ );++ expect(outcome).toEqual({+ kind: "completed",+ text: "Here is the answer",+ success: true,+ explicit: false,+ });+ expect(onText).toHaveBeenCalledWith("Here is the answer");+ expect(executeTool).not.toHaveBeenCalled();+ });++ test("returns awaiting_user without synthesizing an immediate tool result", async () => {+ vi.mocked(aiServiceClientConnect.chat).mockResolvedValue({+ content: "",+ toolCalls: [+ {+ id: "tool-ask",+ name: "ask_user",+ arguments: JSON.stringify({+ prompt: "Which environment should I use?",+ kind: "choose",+ options: [+ { label: "Production", value: "prod" },+ { label: "Staging", value: "staging" },+ ],+ }),+ metadata: "",+ },+ ],+ } as never);++ const executeTool: ToolExecutor = vi.fn(+ async (_name, _args, toolCallId) => ({+ kind: "ask_user" as const,+ ask: {+ toolCallId,+ prompt: "Which environment should I use?",+ kind: "choose" as const,+ options: [+ { label: "Production", value: "prod" },+ { label: "Staging", value: "staging" },+ ],+ },+ })+ );+ const onToolResult = vi.fn();++ const outcome = await runAgentLoop(+ [{ role: "system", content: "system" }],+ [],+ executeTool,+ { onToolResult }+ );++ expect(outcome).toEqual({+ kind: "awaiting_user",+ ask: {+ toolCallId: "tool-ask",+ prompt: "Which environment should I use?",+ kind: "choose",+ options: [+ { label: "Production", value: "prod" },+ { label: "Staging", value: "staging" },+ ],+ },+ });+ expect(onToolResult).not.toHaveBeenCalled();+ });++ test("records skipped tool results after ask_user and does not execute later tool calls", async () => {+ vi.mocked(aiServiceClientConnect.chat).mockResolvedValue({+ content: "",+ toolCalls: [+ {+ id: "tool-ask",+ name: "ask_user",+ arguments: JSON.stringify({+ prompt: "Which environment should I use?",+ kind: "input",+ }),+ metadata: "",+ },+ {+ id: "tool-late",+ name: "search_api",+ arguments: JSON.stringify({ service: "SQLService" }),+ metadata: "",+ },+ ],+ } as never);++ const executeTool: ToolExecutor = vi.fn(async (name, _args, toolCallId) => {+ if (name === "ask_user") {+ return {+ kind: "ask_user" as const,+ ask: {+ toolCallId,+ prompt: "Which environment should I use?",+ kind: "input" as const,+ },+ };+ }+ return {+ kind: "tool_result" as const,+ result: "should not run",+ };+ });+ const onToolResult = vi.fn();++ const outcome = await runAgentLoop(+ [{ role: "system", content: "system" }],+ [],+ executeTool,+ { onToolResult }+ );++ expect(outcome).toEqual({+ kind: "awaiting_user",+ ask: {+ toolCallId: "tool-ask",+ prompt: "Which environment should I use?",+ kind: "input",+ },+ });+ expect(executeTool).toHaveBeenCalledTimes(1);+ expect(executeTool).toHaveBeenCalledWith(+ "ask_user",+ {+ prompt: "Which environment should I use?",+ kind: "input",+ },+ "tool-ask"+ );+ expect(onToolResult).toHaveBeenCalledTimes(1);+ expect(onToolResult).toHaveBeenCalledWith(+ "tool-late",+ JSON.stringify({+ skipped: true,+ blockedByToolCallId: "tool-ask",+ blockedByKind: "ask_user",+ reason: "Skipped because this assistant turn already emitted ask_user",+ })+ );+ });++ test("records skipped tool results after done and does not execute later tool calls", async () => {+ vi.mocked(aiServiceClientConnect.chat).mockResolvedValue({+ content: "",+ toolCalls: [+ {+ id: "tool-done",+ name: "done",+ arguments: JSON.stringify({+ text: "Finished successfully",+ success: true,+ }),+ metadata: "",+ },+ {+ id: "tool-late",+ name: "navigate",+ arguments: JSON.stringify({ path: "/projects/demo" }),+ metadata: "",+ },+ ],+ } as never);++ const executeTool: ToolExecutor = vi.fn(async (name, args) => {+ if (name === "done") {+ return {+ kind: "done" as const,+ text: String(args.text),+ success: args.success !== false,+ };+ }+ return {+ kind: "tool_result" as const,+ result: "should not run",+ };+ });+ const onToolResult = vi.fn();+ const onText = vi.fn();++ const outcome = await runAgentLoop(+ [{ role: "system", content: "system" }],+ [],+ executeTool,+ { onToolResult, onText }+ );++ expect(outcome).toEqual({+ kind: "completed",+ text: "Finished successfully",+ success: true,+ explicit: true,+ });+ expect(executeTool).toHaveBeenCalledTimes(1);+ expect(executeTool).toHaveBeenCalledWith(+ "done",+ {+ text: "Finished successfully",+ success: true,+ },+ "tool-done"+ );+ expect(onToolResult).toHaveBeenNthCalledWith(+ 1,+ "tool-done",+ JSON.stringify({+ text: "Finished successfully",+ success: true,+ })+ );+ expect(onToolResult).toHaveBeenNthCalledWith(+ 2,+ "tool-late",+ JSON.stringify({+ skipped: true,+ blockedByToolCallId: "tool-done",+ blockedByKind: "done",+ reason: "Skipped because this assistant turn already emitted done",+ })+ );+ expect(onText).toHaveBeenCalledWith("Finished successfully");+ });+});diff --git a/frontend/src/plugins/agent/logic/agentLoop.ts b/frontend/src/plugins/agent/logic/agentLoop.tsindex c33a0a2077..8966250926 100644--- a/frontend/src/plugins/agent/logic/agentLoop.ts+++ b/frontend/src/plugins/agent/logic/agentLoop.ts@@ -11,7 +11,13 @@ import {AIChatMessageSchema,AIChatToolDefinitionSchema,} from "@/types/proto-es/v1/ai_service_pb";-import type { Message, ToolCall, ToolDefinition, ToolExecutor } from "./types";+import type {+ AgentLoopOutcome,+ Message,+ ToolCall,+ ToolDefinition,+ ToolExecutor,+} from "./types";const MAX_ITERATIONS = 50;const MAX_RETRIES = 2;@@ -85,87 +91,186 @@ function toolDefToProto(tool: ToolDefinition): AIChatToolDefinition {}export interface AgentCallbacks {- onToolCall?: (toolCall: ToolCall) => void;+ onAssistantMessage?: (+ message: Pick<Message, "content" | "toolCalls">+ ) => void;onToolResult?: (toolCallId: string, result: string) => void;onText?: (text: string) => void;onError?: (error: Error) => void;}+function createSkippedToolResult(blockedBy: {+ toolCallId: string;+ kind: "ask_user" | "done";+}): string {+ return JSON.stringify({+ skipped: true,+ blockedByToolCallId: blockedBy.toolCallId,+ blockedByKind: blockedBy.kind,+ reason: `Skipped because this assistant turn already emitted ${blockedBy.kind}`,+ });+}+export async function runAgentLoop(messages: Message[],tools: ToolDefinition[],executeTool: ToolExecutor,callbacks?: AgentCallbacks,signal?: AbortSignal-): Promise<string> {+): Promise<AgentLoopOutcome> {const conversation: Message[] = [...messages];const protoTools = tools.map(toolDefToProto);- for (let i = 0; i < MAX_ITERATIONS; i++) {- if (signal?.aborted) {- throw new DOMException("Agent loop aborted", "AbortError");- }+ try {+ for (let i = 0; i < MAX_ITERATIONS; i++) {+ if (signal?.aborted) {+ return { kind: "aborted" };+ }++ const protoMessages = conversation.map(messageToProto);++ const response = await callWithRetry(+ () =>+ aiServiceClientConnect.chat(+ { messages: protoMessages, toolDefinitions: protoTools },+ {+ signal,+ contextValues: createContextValues().set(silentContextKey, true),+ }+ ),+ signal+ );++ if (response.toolCalls.length > 0) {+ const toolCalls: ToolCall[] = response.toolCalls.map((tc) => ({+ id: tc.id,+ name: tc.name,+ arguments: tc.arguments,+ metadata: tc.metadata,+ }));++ const assistantMessage: Message = {+ role: "assistant",+ content: response.content,+ toolCalls,+ };+ conversation.push(assistantMessage);+ callbacks?.onAssistantMessage?.(assistantMessage);- const protoMessages = conversation.map(messageToProto);+ let terminalState:+ | {+ outcome: AgentLoopOutcome;+ blockedBy: { toolCallId: string; kind: "ask_user" | "done" };+ }+ | undefined;- const response = await callWithRetry(- () =>- aiServiceClientConnect.chat(- { messages: protoMessages, toolDefinitions: protoTools },- {- signal,- contextValues: createContextValues().set(silentContextKey, true),+ for (const tc of toolCalls) {+ if (terminalState) {+ const skippedResult = createSkippedToolResult(+ terminalState.blockedBy+ );+ callbacks?.onToolResult?.(tc.id, skippedResult);+ conversation.push({+ role: "tool",+ content: skippedResult,+ toolCallId: tc.id,+ });+ continue;}- ),- signal- );-- if (response.toolCalls.length > 0) {- const toolCalls: ToolCall[] = response.toolCalls.map((tc) => ({- id: tc.id,- name: tc.name,- arguments: tc.arguments,- metadata: tc.metadata,- }));-- // Append assistant message with tool calls- conversation.push({- role: "assistant",- content: response.content,- toolCalls,- });-- // Execute each tool call and append results- for (const tc of toolCalls) {- callbacks?.onToolCall?.(tc);-- let result: string;- try {- const args = JSON.parse(tc.arguments) as Record<string, unknown>;- result = await executeTool(tc.name, args);- } catch (err) {- const error = err instanceof Error ? err : new Error(String(err));- callbacks?.onError?.(error);- result = `Error: ${error.message}`;++ let executionResult;+ try {+ const args = JSON.parse(tc.arguments) as Record<string, unknown>;+ executionResult = await executeTool(tc.name, args, tc.id);+ } catch (err) {+ const error = err instanceof Error ? err : new Error(String(err));+ callbacks?.onError?.(error);+ executionResult = {+ kind: "tool_result" as const,+ result: `Error: ${error.message}`,+ };+ }++ if (executionResult.kind === "tool_result") {+ callbacks?.onToolResult?.(tc.id, executionResult.result);+ conversation.push({+ role: "tool",+ content: executionResult.result,+ toolCallId: tc.id,+ });+ continue;+ }++ if (executionResult.kind === "ask_user") {+ terminalState = {+ outcome: {+ kind: "awaiting_user",+ ask: executionResult.ask,+ },+ blockedBy: {+ toolCallId: tc.id,+ kind: "ask_user",+ },+ };+ continue;+ }++ const doneResult = JSON.stringify({+ text: executionResult.text,+ success: executionResult.success,+ });+ callbacks?.onToolResult?.(tc.id, doneResult);+ conversation.push({+ role: "tool",+ content: doneResult,+ toolCallId: tc.id,+ });+ terminalState = {+ outcome: {+ kind: "completed",+ text: executionResult.text,+ success: executionResult.success,+ explicit: true,+ },+ blockedBy: {+ toolCallId: tc.id,+ kind: "done",+ },+ };}- callbacks?.onToolResult?.(tc.id, result);+ if (terminalState) {+ if (terminalState.outcome.kind === "completed") {+ callbacks?.onText?.(terminalState.outcome.text);+ }+ return terminalState.outcome;+ }- conversation.push({- role: "tool",- content: result,- toolCallId: tc.id,- });+ continue;}- continue;+ const text = response.content ?? "";+ callbacks?.onText?.(text);+ return {+ kind: "completed",+ text,+ success: true,+ explicit: false,+ };}- // Text-only response — return final answer- const text = response.content ?? "";- callbacks?.onText?.(text);- return text;+ return {+ kind: "error",+ error: new Error("Agent loop exceeded maximum iterations"),+ };+ } catch (err) {+ const error = err instanceof Error ? err : new Error(String(err));+ if (error.name === "AbortError") {+ return { kind: "aborted" };+ }+ return {+ kind: "error",+ error,+ };}-- throw new Error("Agent loop exceeded maximum iterations");}diff --git a/frontend/src/plugins/agent/logic/prompt.ts b/frontend/src/plugins/agent/logic/prompt.tsindex 9cc7c10ea7..005a0654fc 100644--- a/frontend/src/plugins/agent/logic/prompt.ts+++ b/frontend/src/plugins/agent/logic/prompt.ts@@ -63,7 +63,10 @@ Rules:- Always call get_page_state first to understand the current page context.- Use navigate for "show me" / "go to" requests. Call navigate(list=true) first if unsure about the path — never guess routes.- Use get_skill to load step-by-step workflow guides before multi-step tasks (SQL queries, schema changes, permission grants).-- Always confirm destructive actions (drop database, delete project) before executing.+- Always confirm destructive actions before executing them. When you need confirmation or missing input from the user, call ask_user instead of guessing.+- Use ask_user(kind="input") for free-form answers, ask_user(kind="confirm") for confirm/cancel decisions, and ask_user(kind="choose") when the user must pick from explicit options.+- Call done({ text, success }) when you are ready to finish. Plain assistant text without done is allowed only as a fallback.+- Do not call ask_user and done in the same response.Tool selection — choose based on context, not a fixed preference:- DOM-first when the user is on a form, preview, editor, or creation page. These pages have unsaved/in-progress state that only exists in the UI — APIs cannot access it. Read from and write to visible elements directly.diff --git a/frontend/src/plugins/agent/logic/tools/index.test.ts b/frontend/src/plugins/agent/logic/tools/index.test.tsnew file mode 100644index 0000000000..c0b789ceee--- /dev/null+++ b/frontend/src/plugins/agent/logic/tools/index.test.ts@@ -0,0 +1,143 @@+import { describe, expect, test, vi } from "vitest";+import type { Router } from "vue-router";++vi.mock("../skills", () => ({+ getSkill: vi.fn(async () => "skill"),+}));+vi.mock("./callApi", () => ({+ callApi: vi.fn(async () => "call_api"),+}));+vi.mock("./domAction", () => ({+ createDomActionTool: vi.fn(() => vi.fn(async () => "dom_action")),+}));+vi.mock("./navigate", () => ({+ createNavigateTool: vi.fn(() => vi.fn(async () => "navigate")),+}));+vi.mock("./pageState", () => ({+ createPageStateTool: vi.fn(() => vi.fn(async () => "page_state")),+}));+vi.mock("./searchApi", () => ({+ searchApi: vi.fn(async () => "search_api"),+}));++import { createToolExecutor, getToolDefinitions } from ".";+import { createNavigateTool } from "./navigate";++describe("agent tools navigate", () => {+ test("calls onNavigate after a successful navigation result", async () => {+ const navigateTool = vi.fn(async () =>+ JSON.stringify({+ navigated: true,+ currentPath: "/projects/demo",+ })+ );+ vi.mocked(createNavigateTool).mockReturnValue(navigateTool);+ const onNavigate = vi.fn();+ const executeTool = createToolExecutor({} as Router, { onNavigate });++ const result = await executeTool(+ "navigate",+ {+ path: "/projects/demo",+ },+ "tool-navigate"+ );++ expect(result).toEqual({+ kind: "tool_result",+ result: JSON.stringify({+ navigated: true,+ currentPath: "/projects/demo",+ }),+ });+ expect(onNavigate).toHaveBeenCalledTimes(1);+ });+});++describe("agent tools ask_user", () => {+ test("exposes choose in the ask_user schema", () => {+ const askUser = getToolDefinitions().find(+ (tool) => tool.name === "ask_user"+ );++ expect(askUser).toBeDefined();+ expect(askUser?.parametersSchema).toEqual(+ expect.objectContaining({+ properties: expect.objectContaining({+ kind: expect.objectContaining({+ enum: ["input", "confirm", "choose"],+ }),+ options: expect.any(Object),+ }),+ })+ );+ });++ test("parses choose prompts with sanitized options", async () => {+ const executeTool = createToolExecutor({} as Router);++ const result = await executeTool(+ "ask_user",+ {+ prompt: "Which environment should I use?",+ kind: "choose",+ options: [+ {+ label: " Production ",+ value: " prod ",+ description: " Primary ",+ },+ {+ value: "staging",+ },+ {+ label: "Broken",+ },+ ],+ },+ "tool-choose"+ );++ expect(result).toEqual({+ kind: "ask_user",+ ask: {+ toolCallId: "tool-choose",+ prompt: "Which environment should I use?",+ kind: "choose",+ options: [+ {+ label: "Production",+ value: "prod",+ description: "Primary",+ },+ {+ label: "staging",+ value: "staging",+ },+ ],+ },+ });+ });++ test("falls back to input when choose options are missing", async () => {+ const executeTool = createToolExecutor({} as Router);++ const result = await executeTool(+ "ask_user",+ {+ prompt: "Which environment should I use?",+ kind: "choose",+ },+ "tool-choose"+ );++ expect(result).toEqual({+ kind: "ask_user",+ ask: {+ toolCallId: "tool-choose",+ prompt: "Which environment should I use?",+ kind: "input",+ },+ });+ });+});diff --git a/frontend/src/plugins/agent/logic/tools/index.ts b/frontend/src/plugins/agent/logic/tools/index.tsindex 4465166306..ae69398a07 100644--- a/frontend/src/plugins/agent/logic/tools/index.ts+++ b/frontend/src/plugins/agent/logic/tools/index.ts@@ -1,12 +1,121 @@import type { Router } from "vue-router";-import type { ToolDefinition, ToolExecutor } from "../types";import { getSkill, type GetSkillArgs } from "../skills";+import type {+ AgentAskUserKind,+ AgentAskUserOption,+ AgentPendingAsk,+ ToolDefinition,+ ToolExecutionResult,+ ToolExecutor,+} from "../types";import { callApi, type CallApiArgs } from "./callApi";import { createDomActionTool, type DomActionArgs } from "./domAction";import { createNavigateTool } from "./navigate";import { createPageStateTool, type PageStateArgs } from "./pageState";import { searchApi, type SearchApiArgs } from "./searchApi";+const toToolResult = (result: string): ToolExecutionResult => ({+ kind: "tool_result",+ result,+});++const parseAskUserOption = (value: unknown): AgentAskUserOption | null => {+ if (!value || typeof value !== "object") {+ return null;+ }++ const option = value as Record<string, unknown>;+ const label =+ typeof option.label === "string"+ ? option.label.trim()+ : typeof option.value === "string"+ ? option.value.trim()+ : "";+ const optionValue =+ typeof option.value === "string" ? option.value.trim() : "";++ if (!label || !optionValue) {+ return null;+ }++ return {+ label,+ value: optionValue,+ description:+ typeof option.description === "string" && option.description.trim()+ ? option.description.trim()+ : undefined,+ };+};++const parseAskUserOptions = (value: unknown): AgentAskUserOption[] => {+ if (!Array.isArray(value)) {+ return [];+ }++ return value+ .map((option) => parseAskUserOption(option))+ .filter((option): option is AgentAskUserOption => !!option);+};++const parseAskUserKind = (+ value: unknown,+ options: AgentAskUserOption[]+): AgentAskUserKind => {+ if (value === "confirm") {+ return "confirm";+ }+ if (value === "choose" && options.length > 0) {+ return "choose";+ }+ return "input";+};++const parseDoneArgs = (args: Record<string, unknown>): ToolExecutionResult => {+ if (typeof args.text !== "string" || !args.text.trim()) {+ throw new Error("done requires a non-empty text string");+ }+ return {+ kind: "done",+ text: args.text,+ success: args.success !== false,+ };+};++const parseAskUserArgs = (+ args: Record<string, unknown>,+ toolCallId: string+): ToolExecutionResult => {+ if (typeof args.prompt !== "string" || !args.prompt.trim()) {+ throw new Error("ask_user requires a non-empty prompt string");+ }++ const options = parseAskUserOptions(args.options);+ const ask: AgentPendingAsk = {+ toolCallId,+ prompt: args.prompt,+ kind: parseAskUserKind(args.kind, options),+ };++ if (typeof args.defaultValue === "string") {+ ask.defaultValue = args.defaultValue;+ }+ if (typeof args.confirmLabel === "string") {+ ask.confirmLabel = args.confirmLabel;+ }+ if (typeof args.cancelLabel === "string") {+ ask.cancelLabel = args.cancelLabel;+ }+ if (ask.kind === "choose") {+ ask.options = options;+ }++ return {+ kind: "ask_user",+ ask,+ };+};+export function getToolDefinitions(): ToolDefinition[] {return [{@@ -176,33 +285,138 @@ Use mode="dom" before dom_action to get element indices. Use semantic mode (defa},},},+ {+ name: "ask_user",+ description:+ "Ask the user for missing information, confirmation, or an explicit choice. Use kind='input' for free-form text, kind='confirm' for confirm/cancel decisions, and kind='choose' with options=[{label,value}] when the user must pick from explicit options.",+ parametersSchema: {+ type: "object",+ properties: {+ prompt: {+ type: "string",+ description: "The question to show to the user.",+ },+ kind: {+ type: "string",+ enum: ["input", "confirm", "choose"],+ description:+ 'Defaults to "input" when omitted. kind="choose" requires a non-empty options array.',+ },+ defaultValue: {+ type: "string",+ description:+ "Optional default answer to prefill for input prompts, or the default option value for choose prompts.",+ },+ confirmLabel: {+ type: "string",+ description: "Optional confirm button label for confirm prompts.",+ },+ cancelLabel: {+ type: "string",+ description: "Optional cancel button label for confirm prompts.",+ },+ options: {+ type: "array",+ description:+ "Required for choose prompts. Each option should include a user-visible label and a stable value.",+ items: {+ type: "object",+ properties: {+ label: {+ type: "string",+ description: "User-visible option label.",+ },+ value: {+ type: "string",+ description: "Stable option value returned to the model.",+ },+ description: {+ type: "string",+ description: "Optional helper text shown with the option.",+ },+ },+ required: ["label", "value"],+ },+ },+ },+ required: ["prompt"],+ },+ },+ {+ name: "done",+ description:+ "Complete the current task explicitly. Provide the final user-visible text and whether the task succeeded.",+ parametersSchema: {+ type: "object",+ properties: {+ text: {+ type: "string",+ description: "Final assistant response shown to the user.",+ },+ success: {+ type: "boolean",+ description:+ "Set to false when the task could not be completed successfully.",+ },+ },+ required: ["text"],+ },+ },];}-export function createToolExecutor(router: Router): ToolExecutor {+interface CreateToolExecutorOptions {+ onNavigate?: () => void;+}++export function createToolExecutor(+ router: Router,+ options: CreateToolExecutorOptions = {}+): ToolExecutor {const navigateTool = createNavigateTool(router);const pageStateTool = createPageStateTool(router);const domActionTool = createDomActionTool(router);return async (name: string,- args: Record<string, unknown>- ): Promise<string> => {+ args: Record<string, unknown>,+ toolCallId: string+ ): Promise<ToolExecutionResult> => {switch (name) {case "search_api":- return searchApi(args as SearchApiArgs);+ return toToolResult(await searchApi(args as SearchApiArgs));case "call_api":- return callApi(args as unknown as CallApiArgs);- case "navigate":- return navigateTool(args as { path?: string; list?: boolean });+ return toToolResult(await callApi(args as unknown as CallApiArgs));+ case "navigate": {+ const result = await navigateTool(+ args as { path?: string; list?: boolean }+ );+ try {+ const payload = JSON.parse(result) as {+ navigated?: boolean;+ };+ if (payload.navigated) {+ options.onNavigate?.();+ }+ } catch {+ // Ignore malformed tool output and return the raw result.+ }+ return toToolResult(result);+ }case "get_page_state":- return pageStateTool(args as PageStateArgs);+ return toToolResult(await pageStateTool(args as PageStateArgs));case "dom_action":- return domActionTool(args as unknown as DomActionArgs);+ return toToolResult(+ await domActionTool(args as unknown as DomActionArgs)+ );case "get_skill":- return getSkill(args as GetSkillArgs);+ return toToolResult(await getSkill(args as GetSkillArgs));+ case "ask_user":+ return parseAskUserArgs(args, toolCallId);+ case "done":+ return parseDoneArgs(args);default:- return JSON.stringify({ error: `Unknown tool: ${name}` });+ return toToolResult(JSON.stringify({ error: `Unknown tool: ${name}` }));}};}diff --git a/frontend/src/plugins/agent/logic/types.ts b/frontend/src/plugins/agent/logic/types.tsindex 989e76cea5..4180dc0f1f 100644--- a/frontend/src/plugins/agent/logic/types.ts+++ b/frontend/src/plugins/agent/logic/types.ts@@ -18,7 +18,109 @@ export interface Message {toolCallId?: string;}+export type AgentThreadStatus = "idle" | "running" | "awaiting_user" | "error";++export interface AgentThreadSnapshot {+ path: string;+ title: string;+}++export interface AgentMessageMetadata {+ route?: string;+ pending?: boolean;+ hidden?: boolean;+ error?: string;+ runId?: string;+}++export interface AgentMessage extends Message {+ id: string;+ threadId: string;+ createdTs: number;+ metadata?: AgentMessageMetadata;+}++export interface AgentThread {+ id: string;+ title: string;+ createdTs: number;+ updatedTs: number;+ status: AgentThreadStatus;+ page?: AgentThreadSnapshot;+ lastError?: string | null;+ interrupted?: boolean;+}++export type AgentAskUserKind = "input" | "confirm" | "choose";++export interface AgentAskUserOption {+ label: string;+ value: string;+ description?: string;+}++export interface AgentPendingAsk {+ toolCallId: string;+ prompt: string;+ kind: AgentAskUserKind;+ defaultValue?: string;+ confirmLabel?: string;+ cancelLabel?: string;+ options?: AgentAskUserOption[];+}++export type AgentAskUserResponse =+ | {+ kind: "input";+ answer: string;+ }+ | {+ kind: "confirm";+ answer: string;+ confirmed: boolean;+ }+ | {+ kind: "choose";+ answer: string;+ value: string;+ };++export type ToolExecutionResult =+ | {+ kind: "tool_result";+ result: string;+ }+ | {+ kind: "done";+ text: string;+ success: boolean;+ }+ | {+ kind: "ask_user";+ ask: AgentPendingAsk;+ };++export type AgentLoopOutcome =+ | {+ kind: "completed";+ text: string;+ success: boolean;+ explicit: boolean;+ }+ | {+ kind: "awaiting_user";+ ask: AgentPendingAsk;+ }+ | {+ kind: "aborted";+ }+ | {+ kind: "error";+ error: Error;+ };+export type ToolExecutor = (name: string,- args: Record<string, unknown>-) => Promise<string>;+ args: Record<string, unknown>,+ toolCallId: string+) => Promise<ToolExecutionResult>;diff --git a/frontend/src/plugins/agent/store/agent.test.ts b/frontend/src/plugins/agent/store/agent.test.tsnew file mode 100644index 0000000000..80800f9810--- /dev/null+++ b/frontend/src/plugins/agent/store/agent.test.ts@@ -0,0 +1,332 @@+import { createPinia, setActivePinia } from "pinia";+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";+import { nextTick } from "vue";+import {+ AGENT_STATE_KEY,+ LEGACY_AGENT_MESSAGES_KEY,+ useAgentStore,+} from "./agent";++function createMockStorage(): Storage {+ let store: Record<string, string> = {};+ return {+ get length() {+ return Object.keys(store).length;+ },+ key(index: number) {+ return Object.keys(store)[index] ?? null;+ },+ getItem(key: string) {+ return store[key] ?? null;+ },+ setItem(key: string, value: string) {+ store[key] = String(value);+ },+ removeItem(key: string) {+ delete store[key];+ },+ clear() {+ store = {};+ },+ };+}++const createStore = () => {+ setActivePinia(createPinia());+ return useAgentStore();+};++let mockStorage: Storage;++beforeEach(() => {+ mockStorage = createMockStorage();+ vi.stubGlobal("localStorage", mockStorage);+});++afterEach(() => {+ vi.unstubAllGlobals();+});++describe("useAgentStore", () => {+ test("creates a default thread when no persisted state exists", () => {+ const store = createStore();++ expect(store.threads).toHaveLength(1);+ expect(store.currentThreadId).toBe(store.threads[0].id);+ expect(store.messages).toEqual([]);+ });++ test("migrates legacy flat messages into a thread-aware state", () => {+ localStorage.setItem(+ LEGACY_AGENT_MESSAGES_KEY,+ JSON.stringify([+ { role: "user", content: "Help me inspect this page" },+ { role: "assistant", content: "Sure" },+ ])+ );++ const store = createStore();++ expect(store.threads).toHaveLength(1);+ expect(store.currentThreadId).toBe(store.threads[0].id);+ expect(store.messages).toHaveLength(2);+ expect(store.messages[0].id).toBeTruthy();+ expect(store.messages[0].threadId).toBe(store.currentThreadId);+ expect(store.messages[0].createdTs).toBeTypeOf("number");+ expect(store.threads[0].title).toContain("Help me inspect this page");+ expect(localStorage.getItem(LEGACY_AGENT_MESSAGES_KEY)).toBeNull();+ });++ test("normalizes stale running threads on load", () => {+ localStorage.setItem(+ AGENT_STATE_KEY,+ JSON.stringify({+ currentThreadId: "thread-1",+ threads: [+ {+ id: "thread-1",+ title: "Existing thread",+ createdTs: 10,+ updatedTs: 20,+ status: "running",+ },+ ],+ messagesByThreadId: {+ "thread-1": [+ {+ id: "msg-1",+ threadId: "thread-1",+ createdTs: 30,+ role: "user",+ content: "hello",+ },+ ],+ },+ pendingAskByThreadId: {},+ })+ );++ const store = createStore();+ const thread = store.currentThread;++ expect(thread).not.toBeNull();+ expect(thread?.status).toBe("error");+ expect(thread?.interrupted).toBe(true);+ expect(store.loading).toBe(false);+ });++ test("persists the selected thread and resets thread messages in place", async () => {+ const store = createStore();+ const firstThreadId = store.currentThreadId!;++ store.addMessage({+ threadId: firstThreadId,+ role: "user",+ content: "Initial prompt",+ });+ const secondThread = store.createThread({+ title: "Second",+ page: {+ path: "/projects/original",+ title: "Original Page",+ },+ });+ store.setCurrentThread(secondThread.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",+ });+ });++ test("preserves an existing thread page when resuming a run", () => {+ const store = createStore();+ const threadId = store.currentThreadId!;++ store.updateThreadPage(threadId, {+ path: "/projects/original",+ title: "Original Page",+ });++ store.ensureCurrentThread({+ path: "/projects/other",+ title: "Other Page",+ });+ store.startRun(threadId, {+ path: "/projects/other",+ title: "Other Page",+ });++ expect(store.getThread(threadId)?.page).toEqual({+ path: "/projects/original",+ title: "Original Page",+ });+ });++ test("persists pending choose asks for awaiting-user threads", async () => {+ const store = createStore();+ const threadId = store.currentThreadId!;++ store.awaitUser(threadId, {+ toolCallId: "tool-1",+ prompt: "Which database should I use?",+ kind: "choose",+ defaultValue: "prod-db",+ options: [+ {+ label: "Production",+ value: "prod-db",+ description: "Primary production database",+ },+ {+ label: "Staging",+ value: "staging-db",+ },+ ],+ });++ await nextTick();++ const rehydratedStore = createStore();+ expect(rehydratedStore.getThread(threadId)?.status).toBe("awaiting_user");+ expect(rehydratedStore.getPendingAsk(threadId)).toEqual({+ toolCallId: "tool-1",+ prompt: "Which database should I use?",+ kind: "choose",+ defaultValue: "prod-db",+ confirmLabel: undefined,+ cancelLabel: undefined,+ options: [+ {+ label: "Production",+ value: "prod-db",+ description: "Primary production database",+ },+ {+ label: "Staging",+ value: "staging-db",+ },+ ],+ });+ });++ test("normalizes invalid persisted choose asks to input", () => {+ localStorage.setItem(+ AGENT_STATE_KEY,+ JSON.stringify({+ currentThreadId: "thread-1",+ threads: [+ {+ id: "thread-1",+ title: "Existing thread",+ createdTs: 10,+ updatedTs: 20,+ status: "awaiting_user",+ },+ ],+ messagesByThreadId: {+ "thread-1": [],+ },+ pendingAskByThreadId: {+ "thread-1": {+ toolCallId: "tool-1",+ prompt: "Choose a database",+ kind: "choose",+ options: [{ label: "Broken option" }],+ },+ },+ })+ );++ const store = createStore();++ expect(store.getPendingAsk("thread-1")).toEqual({+ toolCallId: "tool-1",+ prompt: "Choose a database",+ kind: "input",+ defaultValue: undefined,+ confirmLabel: undefined,+ cancelLabel: undefined,+ options: undefined,+ });+ });++ test("answerPendingAsk appends a synthetic tool result and clears pending state", () => {+ const store = createStore();+ const threadId = store.currentThreadId!;++ store.awaitUser(threadId, {+ toolCallId: "tool-1",+ prompt: "Proceed?",+ kind: "confirm",+ confirmLabel: "Proceed",+ cancelLabel: "Cancel",+ });++ store.answerPendingAsk(threadId, {+ kind: "confirm",+ answer: "Proceed",+ confirmed: true,+ });++ const messages = store.getMessages(threadId);+ expect(messages).toHaveLength(1);+ expect(messages[0].role).toBe("tool");+ expect(messages[0].toolCallId).toBe("tool-1");+ expect(JSON.parse(messages[0].content ?? "{}")).toEqual({+ kind: "confirm",+ answer: "Proceed",+ confirmed: true,+ });+ expect(store.getPendingAsk(threadId)).toBeNull();+ });++ test("answerPendingAsk stores choose labels and values", () => {+ const store = createStore();+ const threadId = store.currentThreadId!;++ store.awaitUser(threadId, {+ toolCallId: "tool-choose",+ prompt: "Choose an environment",+ kind: "choose",+ options: [+ { label: "Production", value: "prod" },+ { label: "Staging", value: "staging" },+ ],+ });++ store.answerPendingAsk(threadId, {+ kind: "choose",+ answer: "Production",+ value: "prod",+ });++ const messages = store.getMessages(threadId);+ expect(messages).toHaveLength(1);+ expect(messages[0].role).toBe("tool");+ expect(messages[0].toolCallId).toBe("tool-choose");+ expect(JSON.parse(messages[0].content ?? "{}")).toEqual({+ kind: "choose",+ answer: "Production",+ value: "prod",+ });+ expect(store.getPendingAsk(threadId)).toBeNull();+ });+});diff --git a/frontend/src/plugins/agent/store/agent.ts b/frontend/src/plugins/agent/store/agent.tsindex 980c4669f0..93fca4a7e7 100644--- a/frontend/src/plugins/agent/store/agent.ts+++ b/frontend/src/plugins/agent/store/agent.ts@@ -1,11 +1,304 @@import { defineStore } from "pinia";-import { ref, watch } from "vue";-import type { Message } from "../logic/types";+import { v4 as uuidv4 } from "uuid";+import { computed, ref, watch } from "vue";+import type {+ AgentAskUserOption,+ AgentAskUserResponse,+ AgentMessage,+ AgentPendingAsk,+ AgentThread,+ AgentThreadSnapshot,+ AgentThreadStatus,+ Message,+ ToolCall,+} from "../logic/types";-const MESSAGES_KEY = "bb-agent-messages";+export const AGENT_STATE_KEY = "bb-agent-state";+export const AGENT_WINDOW_KEY = "bb-agent-window";+export const LEGACY_AGENT_MESSAGES_KEY = "bb-agent-messages";++interface PersistedAgentState {+ currentThreadId: string | null;+ threads: AgentThread[];+ messagesByThreadId: Record<string, AgentMessage[]>;+ pendingAskByThreadId: Record<string, AgentPendingAsk>;+}++interface CreateThreadOptions {+ page?: AgentThreadSnapshot;+ select?: boolean;+ title?: string;+}++interface AddMessageOptions extends Message {+ threadId?: string;+ metadata?: AgentMessage["metadata"];+}++const DEFAULT_THREAD_STATUS: AgentThreadStatus = "idle";++const createThreadRecord = (options: CreateThreadOptions = {}): AgentThread => {+ const now = Date.now();+ return {+ id: uuidv4(),+ title: options.title ?? "",+ createdTs: now,+ updatedTs: now,+ status: DEFAULT_THREAD_STATUS,+ page: options.page,+ lastError: null,+ interrupted: false,+ };+};++const getThreadTitleFromMessage = (content?: string) => {+ const title = (content ?? "").trim().replace(/\s+/g, " ");+ if (!title) {+ return "";+ }+ return title.length <= 48 ? title : `${title.slice(0, 45)}...`;+};++const isRecord = (value: unknown): value is Record<string, unknown> => {+ return typeof value === "object" && value !== null;+};++const normalizeMessage = (+ raw: unknown,+ threadId: 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,+ createdTs:+ typeof message.createdTs === "number" ? message.createdTs : fallbackTs,+ role:+ message.role === "assistant" ||+ message.role === "system" ||+ message.role === "tool"+ ? message.role+ : "user",+ content: typeof message.content === "string" ? message.content : undefined,+ toolCalls: Array.isArray(message.toolCalls)+ ? (message.toolCalls as ToolCall[])+ : undefined,+ toolCallId:+ typeof message.toolCallId === "string" ? message.toolCallId : undefined,+ metadata: isRecord(message.metadata)+ ? { ...(message.metadata as AgentMessage["metadata"]) }+ : undefined,+ };+};++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 (+ typeof pendingAsk.toolCallId !== "string" ||+ typeof pendingAsk.prompt !== "string"+ ) {+ return null;+ }++ const options = Array.isArray(pendingAsk.options)+ ? pendingAsk.options+ .map((option) => normalizeAskUserOption(option))+ .filter((option): option is AgentAskUserOption => !!option)+ : [];+ const kind =+ pendingAsk.kind === "confirm"+ ? "confirm"+ : pendingAsk.kind === "choose" && options.length > 0+ ? "choose"+ : "input";++ return {+ toolCallId: pendingAsk.toolCallId,+ prompt: pendingAsk.prompt,+ kind,+ defaultValue:+ typeof pendingAsk.defaultValue === "string"+ ? pendingAsk.defaultValue+ : undefined,+ confirmLabel:+ typeof pendingAsk.confirmLabel === "string"+ ? pendingAsk.confirmLabel+ : undefined,+ cancelLabel:+ typeof pendingAsk.cancelLabel === "string"+ ? pendingAsk.cancelLabel+ : undefined,+ options: kind === "choose" ? options : undefined,+ };+};++const normalizeThread = (raw: unknown): AgentThread => {+ const thread = isRecord(raw) ? raw : {};+ const now = Date.now();+ const status =+ thread.status === "running" ||+ thread.status === "awaiting_user" ||+ thread.status === "error"+ ? thread.status+ : DEFAULT_THREAD_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,+ status,+ page:+ isRecord(thread.page) &&+ typeof thread.page.path === "string" &&+ typeof thread.page.title === "string"+ ? {+ path: thread.page.path,+ title: thread.page.title,+ }+ : undefined,+ lastError:+ typeof thread.lastError === "string"+ ? thread.lastError+ : thread.lastError === null+ ? null+ : null,+ interrupted: Boolean(thread.interrupted),+ };+};++const sortMessages = (messages: AgentMessage[]) => {+ messages.sort((a, b) => a.createdTs - b.createdTs);+ return messages;+};++const migrateLegacyState = (legacyMessages: unknown[]): PersistedAgentState => {+ const thread = createThreadRecord();+ const startTs = Date.now();+ const messages = sortMessages(+ legacyMessages.map((message, index) =>+ normalizeMessage(message, thread.id, startTs + index)+ )+ );+ const firstUserMessage = messages.find((message) => message.role === "user");+ const lastMessage = messages.at(-1);+ thread.title = getThreadTitleFromMessage(firstUserMessage?.content);+ if (lastMessage) {+ thread.updatedTs = lastMessage.createdTs;+ }+ return {+ currentThreadId: thread.id,+ threads: [thread],+ messagesByThreadId: {+ [thread.id]: messages,+ },+ pendingAskByThreadId: {},+ };+};++const normalizePersistedState = (raw: unknown): PersistedAgentState => {+ if (!isRecord(raw)) {+ return {+ currentThreadId: null,+ threads: [],+ messagesByThreadId: {},+ pendingAskByThreadId: {},+ };+ }++ 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 messages = sortMessages(+ rawMessages.map((message, index) =>+ normalizeMessage(message, thread.id, thread.createdTs + index)+ )+ );++ const firstUserMessage = messages.find(+ (message) => message.role === "user"+ );+ const lastMessage = messages.at(-1);++ if (!thread.title) {+ thread.title = getThreadTitleFromMessage(firstUserMessage?.content);+ }+ if (lastMessage) {+ thread.updatedTs = Math.max(thread.updatedTs, lastMessage.createdTs);+ }+ if (thread.status === "running") {+ thread.status = "error";+ thread.interrupted = true;+ thread.lastError = null;+ }++ const pendingAsk = normalizePendingAsk(rawPendingAskByThreadId[thread.id]);+ if (thread.status === "awaiting_user") {+ if (pendingAsk) {+ pendingAskByThreadId[thread.id] = pendingAsk;+ } else {+ thread.status = DEFAULT_THREAD_STATUS;+ }+ }++ messagesByThreadId[thread.id] = messages;+ }++ const currentThreadId =+ typeof raw.currentThreadId === "string" &&+ threads.some((thread) => thread.id === raw.currentThreadId)+ ? raw.currentThreadId+ : (threads[0]?.id ?? null);++ return {+ currentThreadId,+ threads,+ messagesByThreadId,+ pendingAskByThreadId,+ };+};export const useAgentStore = defineStore("agent", () => {- // Window stateconst visible = ref(false);const position = ref({x: window.innerWidth - 420,@@ -14,103 +307,411 @@ export const useAgentStore = defineStore("agent", () => {const size = ref({ width: 400, height: 500 });const minimized = ref(false);- // Conversation- const messages = ref<Message[]>([]);- const loading = ref(false);- const error = ref<string | null>(null);+ 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);- function toggle() {- visible.value = !visible.value;- if (visible.value) minimized.value = false;- }+ const orderedThreads = computed(() =>+ [...threads.value].sort((a, b) => b.updatedTs - a.updatedTs)+ );+ const currentThread = computed(+ () =>+ threads.value.find((thread) => thread.id === currentThreadId.value) ??+ null+ );+ const messages = computed(+ () =>+ (currentThreadId.value+ ? messagesByThreadId.value[currentThreadId.value]+ : undefined) ?? []+ );+ const currentPendingAsk = computed(+ () =>+ (currentThreadId.value+ ? pendingAskByThreadId.value[currentThreadId.value]+ : undefined) ?? null+ );+ const runningThread = computed(+ () => threads.value.find((thread) => thread.status === "running") ?? null+ );+ 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);- function minimize() {- minimized.value = true;- }+ const getThread = (threadId?: string | null) => {+ if (!threadId) {+ return null;+ }+ return threads.value.find((thread) => thread.id === threadId) ?? null;+ };- function restore() {- minimized.value = false;- }+ const getMessages = (threadId?: string | null) => {+ if (!threadId) {+ return [];+ }+ return messagesByThreadId.value[threadId] ?? [];+ };- function addMessage(message: Message) {- messages.value.push(message);- }+ const getPendingAsk = (threadId = currentThreadId.value) => {+ if (!threadId) {+ return null;+ }+ return pendingAskByThreadId.value[threadId] ?? null;+ };- function clearMessages() {- messages.value = [];- localStorage.removeItem(MESSAGES_KEY);- }+ const touchThread = (threadId: string) => {+ const thread = getThread(threadId);+ if (!thread) {+ return null;+ }+ thread.updatedTs = Date.now();+ return thread;+ };- function clearConversation() {- clearMessages();- cancel();- }+ const clearPendingAsk = (threadId = currentThreadId.value) => {+ if (!threadId || !pendingAskByThreadId.value[threadId]) {+ return;+ }+ delete pendingAskByThreadId.value[threadId];+ touchThread(threadId);+ };- function clearError() {- error.value = null;- }+ const setPendingAsk = (threadId: string, pendingAsk: AgentPendingAsk) => {+ pendingAskByThreadId.value[threadId] = pendingAsk;+ touchThread(threadId);+ return pendingAsk;+ };++ const setThreadStatus = (+ threadId: string,+ status: AgentThreadStatus,+ options: {+ interrupted?: boolean;+ lastError?: string | null;+ page?: AgentThreadSnapshot;+ } = {}+ ) => {+ const thread = getThread(threadId);+ if (!thread) {+ return null;+ }+ thread.status = status;+ thread.interrupted = options.interrupted ?? false;+ thread.lastError = options.lastError ?? null;+ if (options.page) {+ thread.page = options.page;+ }+ if (status !== "awaiting_user") {+ delete pendingAskByThreadId.value[threadId];+ }+ touchThread(threadId);+ return thread;+ };++ 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);+ if (existing) {+ if (page && !existing.page) {+ existing.page = page;+ touchThread(existing.id);+ }+ return existing;+ }+ return createThread({ page });+ };- function cancel() {+ const setCurrentThread = (threadId: string) => {+ if (getThread(threadId)) {+ currentThreadId.value = threadId;+ }+ };++ const updateThreadPage = (threadId: string, page: AgentThreadSnapshot) => {+ const thread = getThread(threadId);+ if (!thread) {+ return null;+ }+ thread.page = page;+ touchThread(threadId);+ return thread;+ };++ const addMessage = (message: AddMessageOptions) => {+ const thread = getThread(message.threadId) ?? ensureCurrentThread();+ const createdTs = Date.now();+ const agentMessage: AgentMessage = {+ ...message,+ id: uuidv4(),+ threadId: thread.id,+ createdTs,+ };+ const threadMessages = getMessages(thread.id);+ if (threadMessages.length === 0) {+ messagesByThreadId.value[thread.id] = threadMessages;+ }+ threadMessages.push(agentMessage);+ if (message.role === "user" && !thread.title) {+ thread.title = getThreadTitleFromMessage(message.content);+ }+ thread.lastError = null;+ thread.interrupted = false;+ thread.updatedTs = createdTs;+ return agentMessage;+ };++ const appendToolCall = (+ threadId: string,+ messageId: string,+ toolCall: ToolCall+ ) => {+ const message = getMessages(threadId).find(+ (message) => message.id === messageId+ );+ if (!message) {+ return null;+ }+ message.toolCalls = [...(message.toolCalls ?? []), toolCall];+ touchThread(threadId);+ return message;+ };++ const awaitUser = (threadId: string, pendingAsk: AgentPendingAsk) => {+ setThreadStatus(threadId, "awaiting_user");+ return setPendingAsk(threadId, pendingAsk);+ };++ const answerPendingAsk = (+ threadId: string,+ response: AgentAskUserResponse,+ metadata?: AgentMessage["metadata"]+ ) => {+ const pendingAsk = getPendingAsk(threadId);+ if (!pendingAsk) {+ return null;+ }+ const toolMessage = addMessage({+ threadId,+ role: "tool",+ toolCallId: pendingAsk.toolCallId,+ content: JSON.stringify(response),+ metadata,+ });+ clearPendingAsk(threadId);+ return toolMessage;+ };++ const clearMessages = (threadId = currentThreadId.value) => {+ const thread = getThread(threadId);+ if (!thread) {+ return;+ }+ messagesByThreadId.value[thread.id] = [];+ delete pendingAskByThreadId.value[thread.id];+ thread.title = "";+ thread.page = undefined;+ thread.status = DEFAULT_THREAD_STATUS;+ thread.lastError = null;+ thread.interrupted = false;+ thread.updatedTs = Date.now();+ };++ const clearConversation = (threadId = currentThreadId.value) => {+ if (threadId && runningThreadId.value === threadId) {+ cancel();+ }+ clearMessages(threadId);+ };++ const clearError = (threadId = currentThreadId.value) => {+ const thread = getThread(threadId);+ if (!thread) {+ return;+ }+ thread.lastError = null;+ thread.interrupted = false;+ if (thread.status === "error") {+ thread.status = DEFAULT_THREAD_STATUS;+ }+ touchThread(thread.id);+ };++ const cancel = () => {abortController.value?.abort();abortController.value = null;- loading.value = false;- }+ if (runningThreadId.value) {+ setThreadStatus(runningThreadId.value, DEFAULT_THREAD_STATUS);+ }+ };++ const startRun = (threadId: string, page?: AgentThreadSnapshot) => {+ const thread = getThread(threadId);+ setThreadStatus(threadId, "running", {+ page: thread?.page ?? page,+ });+ };- function saveWindowState() {+ const finishRun = (+ threadId: string,+ options: {+ status?: Extract<AgentThreadStatus, "idle" | "error">;+ lastError?: string | null;+ } = {}+ ) => {+ setThreadStatus(threadId, options.status ?? DEFAULT_THREAD_STATUS, {+ lastError: options.lastError ?? null,+ interrupted: false,+ });+ };++ const saveWindowState = () => {localStorage.setItem(- "bb-agent-window",+ AGENT_WINDOW_KEY,JSON.stringify({ position: position.value, size: size.value }));- }+ };- function saveMessages() {- localStorage.setItem(MESSAGES_KEY, JSON.stringify(messages.value));- }+ const saveState = () => {+ const persistedState: PersistedAgentState = {+ currentThreadId: currentThreadId.value,+ threads: threads.value,+ messagesByThreadId: messagesByThreadId.value,+ pendingAskByThreadId: pendingAskByThreadId.value,+ };+ localStorage.setItem(AGENT_STATE_KEY, JSON.stringify(persistedState));+ };- function loadMessages() {- const saved = localStorage.getItem(MESSAGES_KEY);+ const loadState = () => {+ const saved = localStorage.getItem(AGENT_STATE_KEY);if (saved) {try {- const parsed = JSON.parse(saved);- if (Array.isArray(parsed)) {- messages.value = parsed;- }+ const state = normalizePersistedState(JSON.parse(saved));+ threads.value = state.threads;+ messagesByThreadId.value = state.messagesByThreadId;+ pendingAskByThreadId.value = state.pendingAskByThreadId;+ currentThreadId.value = state.currentThreadId;} catch {- // Ignore corrupted data- localStorage.removeItem(MESSAGES_KEY);+ localStorage.removeItem(AGENT_STATE_KEY);+ }+ } else {+ const legacySaved = localStorage.getItem(LEGACY_AGENT_MESSAGES_KEY);+ if (legacySaved) {+ try {+ const parsed = JSON.parse(legacySaved);+ if (Array.isArray(parsed)) {+ const state = migrateLegacyState(parsed);+ threads.value = state.threads;+ messagesByThreadId.value = state.messagesByThreadId;+ pendingAskByThreadId.value = state.pendingAskByThreadId;+ currentThreadId.value = state.currentThreadId;+ }+ } catch {+ localStorage.removeItem(LEGACY_AGENT_MESSAGES_KEY);+ }+ localStorage.removeItem(LEGACY_AGENT_MESSAGES_KEY);}}- }- function loadWindowState() {- const saved = localStorage.getItem("bb-agent-window");- if (saved) {- const state = JSON.parse(saved);- if (state.position) position.value = state.position;- if (state.size) size.value = state.size;+ if (!currentThreadId.value || !getThread(currentThreadId.value)) {+ const thread = createThread();+ currentThreadId.value = thread.id;}- }+ };- // Persist messages on every change- watch(messages, saveMessages, { deep: true });+ const loadWindowState = () => {+ const saved = localStorage.getItem(AGENT_WINDOW_KEY);+ if (!saved) {+ return;+ }+ try {+ const state = JSON.parse(saved) as {+ position?: { x?: number; y?: number };+ size?: { width?: number; height?: number };+ };+ if (state.position?.x && state.position?.y) {+ position.value = {+ x: state.position.x,+ y: state.position.y,+ };+ }+ if (state.size?.width && state.size?.height) {+ size.value = {+ width: state.size.width,+ height: state.size.height,+ };+ }+ } catch {+ localStorage.removeItem(AGENT_WINDOW_KEY);+ }+ };++ watch(+ [threads, messagesByThreadId, pendingAskByThreadId, currentThreadId],+ saveState,+ {+ deep: true,+ }+ );- // Load persisted messages on init- loadMessages();+ loadState();return {visible,position,size,minimized,+ threads,+ orderedThreads,+ currentThreadId,+ currentThread,messages,+ currentPendingAsk,loading,error,+ hasRunningThread,+ runningThreadId,abortController,- toggle,- minimize,- restore,+ toggle() {+ visible.value = !visible.value;+ if (visible.value) {+ minimized.value = false;+ }+ },+ minimize() {+ minimized.value = true;+ },+ restore() {+ minimized.value = false;+ },+ getThread,+ getMessages,+ getPendingAsk,+ createThread,+ ensureCurrentThread,+ setCurrentThread,+ updateThreadPage,+ setPendingAsk,+ clearPendingAsk,+ setThreadStatus,+ startRun,+ finishRun,+ awaitUser,+ answerPendingAsk,+ touchThread,addMessage,+ appendToolCall,clearMessages,clearConversation,clearError,