Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
fix(agent): harden agent request limits and error handling (#21720)
ecmadao29fa29c18dc3
diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.jsonindex e1453cdc09..9566b4f1ce 100644--- a/frontend/src/locales/en-US.json+++ b/frontend/src/locales/en-US.json@@ -177,6 +177,7 @@},"rename-chat-placeholder": "Enter chat name","reply": "Reply",+ "request-failed": "The assistant couldn't complete this request.","request-stopped-by-user": "Request stopped by user","request-stopped-retry-hint": "An action already sent may still complete. Check its status before retrying.","resource-picker": {diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.jsonindex b210d37326..cd2a69e4a2 100644--- a/frontend/src/locales/es-ES.json+++ b/frontend/src/locales/es-ES.json@@ -177,6 +177,7 @@},"rename-chat-placeholder": "Ingrese el nombre del chat","reply": "Responder",+ "request-failed": "El asistente no pudo completar esta solicitud.","request-stopped-by-user": "Solicitud detenida por el usuario","request-stopped-retry-hint": "Una acción ya enviada puede completarse igualmente. Compruebe su estado antes de reintentar.","resource-picker": {diff --git a/frontend/src/locales/ja-JP.json b/frontend/src/locales/ja-JP.jsonindex 7edda1c385..faecab502e 100644--- a/frontend/src/locales/ja-JP.json+++ b/frontend/src/locales/ja-JP.json@@ -177,6 +177,7 @@},"rename-chat-placeholder": "チャット名を入力","reply": "返信",+ "request-failed": "アシスタントはこのリクエストを完了できませんでした。","request-stopped-by-user": "ユーザーがリクエストを停止しました","request-stopped-retry-hint": "送信済みの操作は完了する可能性があります。再試行する前に状態を確認してください。","resource-picker": {diff --git a/frontend/src/locales/vi-VN.json b/frontend/src/locales/vi-VN.jsonindex 1e973c7e4a..4aa01fee3a 100644--- a/frontend/src/locales/vi-VN.json+++ b/frontend/src/locales/vi-VN.json@@ -177,6 +177,7 @@},"rename-chat-placeholder": "Nhập tên cuộc trò chuyện","reply": "Trả lời",+ "request-failed": "Trợ lý không thể hoàn tất yêu cầu này.","request-stopped-by-user": "Yêu cầu đã được người dùng dừng","request-stopped-retry-hint": "Thao tác đã gửi vẫn có thể hoàn tất. Hãy kiểm tra trạng thái trước khi thử lại.","resource-picker": {diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.jsonindex 6d75eab4a7..ecd42f6d3c 100644--- a/frontend/src/locales/zh-CN.json+++ b/frontend/src/locales/zh-CN.json@@ -177,6 +177,7 @@},"rename-chat-placeholder": "输入对话名称","reply": "回复",+ "request-failed": "助手未能完成此请求。","request-stopped-by-user": "用户已停止请求","request-stopped-retry-hint": "已发送的操作仍可能完成。重试前请先检查其状态。","resource-picker": {diff --git a/frontend/src/modules/agent/components/AgentChat.test.tsx b/frontend/src/modules/agent/components/AgentChat.test.tsxindex ec8b237596..510259af4f 100644--- a/frontend/src/modules/agent/components/AgentChat.test.tsx+++ b/frontend/src/modules/agent/components/AgentChat.test.tsx@@ -2044,4 +2044,36 @@ describe("AgentChat", () => {unmount();});++ test("shows one concise provider error and reveals its raw detail on demand", () => {+ const store = useAgentStore.getState();+ const chat = store.ensureCurrentChat();+ const rawError =+ 'OpenAI API error: {"error":{"message":"API key not valid. Please pass a valid API key."}}';+ store.addMessage({+ chatId: chat.id,+ role: "assistant",+ content: `Error: ${rawError}`,+ metadata: { error: rawError },+ });+ store.finishChatRun(chat.id, { status: "error", lastError: rawError });++ const { container, render, unmount } = renderIntoContainer(<AgentChat />);+ render();++ expect(container.querySelectorAll("[data-agent-error-summary]")).toHaveLength(1);+ expect(container.querySelector("[data-agent-error-summary]")?.textContent).toBe(+ "API key not valid. Please pass a valid API key."+ );+ expect(container.textContent).not.toContain("OpenAI API error:");++ const details = container.querySelector<HTMLButtonElement>(+ "[data-agent-error-details]"+ );+ expect(details?.getAttribute("aria-expanded")).toBe("false");+ act(() => details?.click());+ expect(container.textContent).toContain(rawError);++ unmount();+ });});diff --git a/frontend/src/modules/agent/components/AgentChat.tsx b/frontend/src/modules/agent/components/AgentChat.tsxindex d24ea26795..3e95d86769 100644--- a/frontend/src/modules/agent/components/AgentChat.tsx+++ b/frontend/src/modules/agent/components/AgentChat.tsx@@ -50,6 +50,7 @@ import {DeniedQueryRequestDraftStorageError,prepareAgentDeniedQueryRequestRoute,} from "../logic/deniedQueryAccess";+import { getAgentErrorSummary } from "../logic/errorDisplay";import { resolveAgentHandoffRoute } from "../logic/handoff";import type { LandingStarterId } from "../logic/landingStarters";import {@@ -682,9 +683,14 @@ export function AgentChat({() =>messages.filter((message): message is AgentMessage =>- message.role === "user" || message.role === "assistant"+ (message.role === "user" || message.role === "assistant") &&+ !(+ message.role === "assistant" &&+ error &&+ message.metadata?.error === error+ )),- [messages]+ [error, messages]);const emptyChatScope = currentChat?.context?.startsWith(projectNamePrefix)? "project"@@ -1194,8 +1200,27 @@ export function AgentChat({</div>) : (error && (- <div className="rounded-sm bg-error/10 px-3 py-2 text-sm text-error">- {error}+ <div+ className="rounded-sm bg-error/10 px-3 py-2 text-sm text-error"+ role="alert"+ >+ <div data-agent-error-summary>+ {getAgentErrorSummary(error) ?? t("agent.request-failed")}+ </div>+ <Collapsible className="mt-1">+ <CollapsibleTrigger+ className="w-fit text-xs underline decoration-dotted underline-offset-2"+ data-agent-error-details+ >+ <ChevronRight className="size-3" />+ {t("error-page.error-details")}+ </CollapsibleTrigger>+ <CollapsiblePanel className="pt-1">+ <pre className="max-h-40 overflow-auto whitespace-pre-wrap break-words font-mono text-xs">+ {error}+ </pre>+ </CollapsiblePanel>+ </Collapsible></div>))}diff --git a/frontend/src/modules/agent/components/AgentInput.test.tsx b/frontend/src/modules/agent/components/AgentInput.test.tsxindex 38972f6e33..20922abaac 100644--- a/frontend/src/modules/agent/components/AgentInput.test.tsx+++ b/frontend/src/modules/agent/components/AgentInput.test.tsx@@ -1546,6 +1546,46 @@ describe("AgentInput", () => {view.unmount();});+ test("stores a failed provider request once instead of duplicating it in chat history", async () => {+ const providerError = new Error(+ 'OpenAI API error: {"error":{"message":"API key not valid. Please pass a valid API key."}}'+ );+ mocks.runAgentLoop.mockResolvedValue({+ kind: "error",+ error: providerError,+ totalTokensUsed: 0,+ });+ const page = { path: "/projects/orders", title: "Orders" };+ const chat = useAgentStore.getState().createChat({+ context: "projects/orders",+ page,+ });+ useAgentStore.getState().queueUserMessage({+ chatId: chat.id,+ text: "Check the API configuration",+ page,+ });++ const view = renderIntoContainer(<AgentInput />);+ view.render();+ await act(async () => {+ await vi.waitFor(() =>+ expect(useAgentStore.getState().getChat(chat.id)?.status).toBe("error")+ );+ });++ expect(useAgentStore.getState().getChat(chat.id)?.lastError).toBe(+ providerError.message+ );+ expect(+ useAgentStore+ .getState()+ .getMessages(chat.id)+ .filter((message) => message.role === "assistant")+ ).toHaveLength(0);+ view.unmount();+ });+test("offers an Access Grant draft only after one actual denied Query", async () => {const args = {operationId: "SQLService/Query",diff --git a/frontend/src/modules/agent/components/AgentInput.tsx b/frontend/src/modules/agent/components/AgentInput.tsxindex e2380b4937..cbb8f8843e 100644--- a/frontend/src/modules/agent/components/AgentInput.tsx+++ b/frontend/src/modules/agent/components/AgentInput.tsx@@ -868,12 +868,7 @@ export function AgentInput({);const handleOutcome = useCallback(- (- chatId: string,- page: { path: string; title: string },- errorPrefix: string,- outcome: Awaited<ReturnType<typeof runAgentLoop>>- ) => {+ (chatId: string, outcome: Awaited<ReturnType<typeof runAgentLoop>>) => {const store = useAgentStore.getState();switch (outcome.kind) {case "completed":@@ -886,17 +881,6 @@ export function AgentInput({store.interruptChatRun(chatId, getCurrentPageSnapshot());return;case "error": {- if (!isAgentAIConfigurationError(outcome.error)) {- store.addMessage({- chatId,- role: "assistant",- content: `${errorPrefix}${outcome.error.message}`,- metadata: {- route: page.path,- error: outcome.error.message,- },- });- }store.finishChatRun(chatId, {status: "error",lastError: outcome.error.message,@@ -1377,7 +1361,7 @@ export function AgentInput({}}- handleOutcome(chatId, page, "Error: ", outcome);+ handleOutcome(chatId, outcome);if (followUpRequest && finalText) {const followUp = await generateFollowUpQuestion(lastUserMessage?.content ?? "",diff --git a/frontend/src/modules/agent/logic/agentLoop.test.ts b/frontend/src/modules/agent/logic/agentLoop.test.tsindex 304d1d6e0a..87ed271e73 100644--- a/frontend/src/modules/agent/logic/agentLoop.test.ts+++ b/frontend/src/modules/agent/logic/agentLoop.test.ts@@ -359,6 +359,134 @@ describe("runAgentLoop", () => {});});+ test("stops after cumulative provider usage reaches the run budget", async () => {+ vi.mocked(aiServiceClientConnect.chat)+ .mockResolvedValueOnce({+ content: "",+ toolCalls: [+ {+ id: "tool-1",+ name: "lookup",+ arguments: "{}",+ metadata: "",+ },+ ],+ usage: { totalTokens: 60_000 },+ } as never)+ .mockResolvedValueOnce({+ content: "",+ toolCalls: [+ {+ id: "done-1",+ name: "done",+ arguments: JSON.stringify({ text: "Done", success: true }),+ metadata: "",+ },+ ],+ } as never);++ const outcome = await runAgentLoop(+ [+ { role: "system", content: "system" },+ { role: "user", content: "Inspect" },+ ],+ [{ name: "lookup", description: "Lookup", parametersSchema: {} }],+ vi.fn(async (name, args) =>+ name === "done"+ ? { kind: "done" as const, text: String(args.text), success: true }+ : { kind: "tool_result" as const, result: "ok" }+ )+ );++ expect(outcome.kind).toBe("completed");+ expect(outcome).toMatchObject({ success: false, totalTokensUsed: 60_000 });+ expect(aiServiceClientConnect.chat).toHaveBeenCalledOnce();+ });++ test("refuses a request that exceeds the serialized payload budget", async () => {+ const outcome = await runAgentLoop(+ [+ { role: "system", content: "s".repeat(300_000) },+ { role: "user", content: "Inspect" },+ ],+ [],+ vi.fn()+ );++ expect(outcome).toMatchObject({ kind: "completed", success: false });+ expect(aiServiceClientConnect.chat).not.toHaveBeenCalled();+ });++ test("prunes completed tool output while retaining the current question", async () => {+ vi.mocked(aiServiceClientConnect.chat).mockResolvedValueOnce({+ content: "",+ toolCalls: [+ {+ id: "done-1",+ name: "done",+ arguments: JSON.stringify({ text: "Finished", success: true }),+ metadata: "",+ },+ ],+ } as never);+ const largeResult = "schema".repeat(50_000);+ const outcome = await runAgentLoop(+ [+ { role: "system", content: "system" },+ { role: "user", content: "Inspect the schema" },+ {+ role: "assistant",+ content: "Reading schema",+ toolCalls: [{ id: "old-tool", name: "get_schema", arguments: "{}" }],+ },+ { role: "tool", toolCallId: "old-tool", content: largeResult },+ { role: "user", content: "Now summarize it" },+ ],+ [],+ vi.fn(async () => ({+ kind: "done" as const,+ text: "Finished",+ success: true,+ }))+ );++ expect(outcome).toMatchObject({ kind: "completed", success: true });+ const request = vi.mocked(aiServiceClientConnect.chat).mock.calls[0]?.[0];+ const sentMessages = request?.messages?.map((message) => message.content);+ expect(sentMessages).toContain("Now summarize it");+ expect(sentMessages?.join(" ")).toContain(+ "omitted to fit the context limit"+ );+ expect(sentMessages?.join(" ")).not.toContain(largeResult);+ });++ test("limits provider attempts within one agent run", async () => {+ vi.mocked(aiServiceClientConnect.chat).mockImplementation(async () => {+ const callNumber = vi.mocked(aiServiceClientConnect.chat).mock.calls+ .length;+ return {+ content: "",+ toolCalls: [+ {+ id: `tool-${callNumber}`,+ name: "lookup",+ arguments: "{}",+ metadata: "",+ },+ ],+ } as never;+ });++ const outcome = await runAgentLoop(+ [{ role: "user", content: "Inspect" }],+ [{ name: "lookup", description: "Lookup", parametersSchema: {} }],+ vi.fn(async () => ({ kind: "tool_result" as const, result: "ok" }))+ );++ expect(outcome).toMatchObject({ kind: "completed", success: false });+ expect(aiServiceClientConnect.chat).toHaveBeenCalledTimes(12);+ });+test("replays completed tool flows with matched tool results", async () => {vi.mocked(aiServiceClientConnect.chat).mockResolvedValueOnce({diff --git a/frontend/src/modules/agent/logic/agentLoop.ts b/frontend/src/modules/agent/logic/agentLoop.tsindex ba14fdd9b3..d651c594e3 100644--- a/frontend/src/modules/agent/logic/agentLoop.ts+++ b/frontend/src/modules/agent/logic/agentLoop.ts@@ -21,19 +21,30 @@ import type {ToolExecutor,} from "./types";-const MAX_ITERATIONS = 1000;+const MAX_PROVIDER_CALLS = 12;+const MAX_TOTAL_TOKENS = 60_000;+const MAX_REQUEST_BYTES = 256 * 1024;const MAX_RETRIES = 2;const RETRY_DELAY_MS = 1000;+const COMPACTION_NOTE =+ "Earlier tool calls and results were omitted to fit the context limit. Re-fetch any state you need and verify it before repeating an action.";++class ProviderCallLimitError extends Error {}async function callWithRetry<T>(fn: () => Promise<T>,- signal?: AbortSignal+ signal: AbortSignal | undefined,+ reserveProviderCall: () => boolean): Promise<T> {let lastError: Error | undefined;for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) {if (signal?.aborted) {throw new DOMException("Agent loop aborted", "AbortError");}+ if (!reserveProviderCall()) {+ if (lastError) throw lastError;+ throw new ProviderCallLimitError("Agent provider call limit reached.");+ }try {return await fn();} catch (err) {@@ -56,6 +67,61 @@ async function callWithRetry<T>(throw lastError!;}+function serializedRequestSize(+ messages: AIChatMessage[],+ toolDefinitions: AIChatToolDefinition[]+): number {+ return new TextEncoder().encode(JSON.stringify({ messages, toolDefinitions }))+ .byteLength;+}++function removeOldestCompletedToolCallGroup(messages: Message[]): boolean {+ for (let index = 0; index < messages.length; index++) {+ const message = messages[index];+ if (message?.role !== "assistant" || !message.toolCalls?.length) continue;++ const callIds = new Set(message.toolCalls.map((toolCall) => toolCall.id));+ const groupEnd = messages.findIndex(+ (candidate, candidateIndex) =>+ candidateIndex > index && candidate.role === "assistant"+ );+ const end = groupEnd < 0 ? messages.length : groupEnd;+ const completedIds = new Set<string>();+ for (const candidate of messages.slice(index + 1, end)) {+ if (+ candidate.role === "tool" &&+ candidate.toolCallId &&+ callIds.has(candidate.toolCallId)+ ) {+ completedIds.add(candidate.toolCallId);+ }+ }+ if (![...callIds].every((id) => completedIds.has(id))) continue;++ for (let current = end - 1; current >= index; current--) {+ const candidate = messages[current];+ if (+ current === index ||+ (candidate?.role === "tool" &&+ candidate.toolCallId &&+ callIds.has(candidate.toolCallId))+ ) {+ messages.splice(current, 1);+ }+ }+ return true;+ }+ return false;+}++function addCompactionNote(messages: Message[]): void {+ const insertAt = messages.findIndex((message) => message.role !== "system");+ messages.splice(insertAt < 0 ? messages.length : insertAt, 0, {+ role: "system",+ content: COMPACTION_NOTE,+ });+}+const ROLE_MAP: Record<Message["role"], AIChatMessageRole> = {system: AIChatMessageRole.AI_CHAT_MESSAGE_ROLE_SYSTEM,user: AIChatMessageRole.AI_CHAT_MESSAGE_ROLE_USER,@@ -187,6 +253,8 @@ export async function runAgentLoop((tool) => tool.name === "done" || tool.name === "ask_user");let totalTokensUsed = 0;+ let providerCallCount = 0;+ let contextCompacted = false;let awaitingTerminalCall = false;const apiAttempts = getCurrentTurnApiAttempts(messages);@@ -195,29 +263,70 @@ export async function runAgentLoop(return { kind: "completed", text: error, success: false, totalTokensUsed };};+ const completeWithRunLimit = (): AgentLoopOutcome => {+ const text =+ "I stopped before making another AI request because this run reached its usage limit. Earlier actions may already have completed; check their status before asking me to retry.";+ callbacks?.onText?.(text);+ return { kind: "completed", text, success: false, totalTokensUsed };+ };++ const completeWithRequestLimit = (): AgentLoopOutcome => {+ const text =+ "This request is too large to send safely, even after removing earlier tool results. Start a new chat or shorten the request.";+ callbacks?.onText?.(text);+ return { kind: "completed", text, success: false, totalTokensUsed };+ };+try {- for (let i = 0; i < MAX_ITERATIONS; i++) {+ for (;;) {if (signal?.aborted) {return { kind: "aborted", totalTokensUsed };}+ if (+ totalTokensUsed >= MAX_TOTAL_TOKENS ||+ providerCallCount >= MAX_PROVIDER_CALLS+ ) {+ return completeWithRunLimit();+ }- const protoMessages = conversation.map(messageToProto);+ const toolDefinitions = awaitingTerminalCall ? terminalTools : protoTools;+ let protoMessages = conversation.map(messageToProto);+ while (+ serializedRequestSize(protoMessages, toolDefinitions) >+ MAX_REQUEST_BYTES &&+ removeOldestCompletedToolCallGroup(conversation)+ ) {+ if (!contextCompacted) {+ addCompactionNote(conversation);+ contextCompacted = true;+ }+ protoMessages = conversation.map(messageToProto);+ }+ if (+ serializedRequestSize(protoMessages, toolDefinitions) >+ MAX_REQUEST_BYTES+ ) {+ return completeWithRequestLimit();+ }const response = await callWithRetry(() =>aiServiceClientConnect.chat({messages: protoMessages,- toolDefinitions: awaitingTerminalCall- ? terminalTools- : protoTools,+ toolDefinitions,},{signal,contextValues: createContextValues().set(silentContextKey, true),}),- signal+ signal,+ () => {+ if (providerCallCount >= MAX_PROVIDER_CALLS) return false;+ providerCallCount++;+ return true;+ });if (signal?.aborted) {@@ -424,17 +533,14 @@ export async function runAgentLoop(totalTokensUsed,};}-- return {- kind: "error",- error: new Error("Agent loop exceeded maximum iterations"),- totalTokensUsed,- };} catch (err) {const error = err instanceof Error ? err : new Error(String(err));if (signal?.aborted || error.name === "AbortError") {return { kind: "aborted", totalTokensUsed };}+ if (error instanceof ProviderCallLimitError) {+ return completeWithRunLimit();+ }return {kind: "error",error,diff --git a/frontend/src/modules/agent/logic/errorDisplay.test.ts b/frontend/src/modules/agent/logic/errorDisplay.test.tsnew file mode 100644index 0000000000..b55793ce7a--- /dev/null+++ b/frontend/src/modules/agent/logic/errorDisplay.test.ts@@ -0,0 +1,22 @@+import { describe, expect, test } from "vitest";+import { getAgentErrorSummary } from "./errorDisplay";++describe("getAgentErrorSummary", () => {+ test("uses the provider's actionable message instead of its transport wrapper", () => {+ expect(+ getAgentErrorSummary(+ 'OpenAI API error: {"error":{"message":"API key not valid. Please pass a valid API key."}}'+ )+ ).toBe("API key not valid. Please pass a valid API key.");+ });++ test("falls back to the first line and keeps long raw errors bounded", () => {+ expect(getAgentErrorSummary("Error: Request failed\nprovider trace")).toBe(+ "Request failed"+ );+ expect(getAgentErrorSummary(`Error: ${"x".repeat(300)}`)).toBe(+ `${"x".repeat(239)}…`+ );+ expect(getAgentErrorSummary(" \n ")).toBeUndefined();+ });+});diff --git a/frontend/src/modules/agent/logic/errorDisplay.ts b/frontend/src/modules/agent/logic/errorDisplay.tsnew file mode 100644index 0000000000..805428c3cb--- /dev/null+++ b/frontend/src/modules/agent/logic/errorDisplay.ts@@ -0,0 +1,26 @@+const providerMessagePattern = /"message"\s*:\s*("(?:\\.|[^"\\])*")/g;+const maxSummaryLength = 240;++export function getAgentErrorSummary(error: string): string | undefined {+ for (const match of error.matchAll(providerMessagePattern)) {+ try {+ const message: unknown = JSON.parse(match[1]!);+ if (typeof message === "string" && message.trim()) {+ return truncateSummary(message.trim());+ }+ } catch {+ // Ignore malformed provider payloads and fall back to the original error.+ }+ }++ const firstLine = error+ .trim()+ .split(/\r?\n/, 1)[0]+ ?.replace(/^(?:Error|ConnectError):\s*/i, "");+ return firstLine ? truncateSummary(firstLine) : undefined;+}++function truncateSummary(summary: string): string {+ if (summary.length <= maxSummaryLength) return summary;+ return `${summary.slice(0, maxSummaryLength - 1).trimEnd()}…`;+}diff --git a/frontend/src/modules/agent/logic/outboundHistory.test.ts b/frontend/src/modules/agent/logic/outboundHistory.test.tsindex 994a2b8122..5ba13babd2 100644--- a/frontend/src/modules/agent/logic/outboundHistory.test.ts+++ b/frontend/src/modules/agent/logic/outboundHistory.test.ts@@ -15,6 +15,44 @@ const userMessage = (metadata?: AgentMessage["metadata"]): AgentMessage => ({});describe("sanitizeOutboundHistory", () => {+ test("keeps prior user-visible turns but omits their tool transcript", () => {+ const history = sanitizeOutboundHistory([+ { ...userMessage(), content: "Inspect the orders database" },+ {+ ...userMessage(),+ id: "call-1",+ role: "assistant",+ content: "I will inspect it.",+ toolCalls: [+ { id: "tool-1", name: "get_database_overview", arguments: "{}" },+ ],+ },+ {+ ...userMessage(),+ id: "result-1",+ role: "tool",+ toolCallId: "tool-1",+ content: '{"schema":"large result"}',+ },+ {+ ...userMessage(),+ id: "answer-1",+ role: "assistant",+ content: "The database has three tables.",+ },+ { ...userMessage(), id: "turn-2", content: "List those tables" },+ ]);++ expect(history.map(({ role, content }) => [role, content])).toEqual([+ ["user", "Inspect the orders database"],+ ["assistant", "I will inspect it."],+ ["assistant", "The database has three tables."],+ ["user", "List those tables"],+ ]);+ expect(history.some((message) => message.role === "tool")).toBe(false);+ expect(history.some((message) => message.toolCalls?.length)).toBe(false);+ });+test("adds one-turn Project reference without changing the chat question or later turns", () => {const message = userMessage({resourceReference: {@@ -448,8 +486,10 @@ describe("buildOutboundHistory", () => {"projects/billing");- expect(history).toHaveLength(projectTurn.length + 2);+ expect(history).toHaveLength(4);expect(history[1].content).toContain('"name":"projects/billing"');+ expect(history[1].content).toContain("How many databases?");+ expect(history[2].content).toBe("Billing has one database.");expect(history.at(-1)?.content).toBe("How many instances?");});@@ -465,8 +505,10 @@ describe("buildOutboundHistory", () => {"workspaces/default");- expect(history).toHaveLength(projectTurn.length + 2);+ expect(history).toHaveLength(4);expect(history[1].content).toContain('"name":"projects/billing"');+ expect(history[1].content).toContain("How many databases?");+ expect(history[2].content).toBe("Billing has one database.");expect(history.at(-1)?.content).toContain('"name":"projects/orders"');});diff --git a/frontend/src/modules/agent/logic/outboundHistory.ts b/frontend/src/modules/agent/logic/outboundHistory.tsindex fece6758cd..1ec3d5760b 100644--- a/frontend/src/modules/agent/logic/outboundHistory.ts+++ b/frontend/src/modules/agent/logic/outboundHistory.ts@@ -47,7 +47,7 @@ export const sanitizeOutboundHistory = (let omitTurn = false;let omitInterruptedTurnMessages = false;- return messages.flatMap((message) => {+ const outboundMessages = messages.flatMap((message): Message[] => {const references =message.role === "user"? normalizeAgentResourceReferences(@@ -101,6 +101,21 @@ export const sanitizeOutboundHistory = (}return [outbound];});++ const currentTurnStart = outboundMessages.findLastIndex(+ (message) => message.role === "user"+ );+ const historyEnd =+ currentTurnStart < 0 ? outboundMessages.length : currentTurnStart;++ return outboundMessages.flatMap((message, index) => {+ if (index >= historyEnd) return [message];+ if (message.role === "tool") return [];+ if (message.role === "assistant" && message.toolCalls?.length) {+ return message.content ? [{ ...message, toolCalls: undefined }] : [];+ }+ return [message];+ });};export const buildOutboundHistory = (diff --git a/frontend/src/modules/agent/logic/prompt.ts b/frontend/src/modules/agent/logic/prompt.tsindex 844869c3cc..e6fd1f1ff9 100644--- a/frontend/src/modules/agent/logic/prompt.ts+++ b/frontend/src/modules/agent/logic/prompt.ts@@ -38,7 +38,7 @@ export function buildSystemPrompt(pageContext: {? `- This is a referenced-resource request. Stay on the current page and answer in chat; navigation and DOM actions are unavailable. For details beyond bounded project tools, use search_api to find a suitable endpoint, inspect its schema, then call_api using ${referencedApiScope}. API calls use the member's existing permissions and may change data; do not make changes unless the member explicitly asks. Use get_database_count for a bounded active-database count in the referenced Project. If the current turn selects @Database and the member asks for a bounded active-database count on its instance, use get_database_count with scope "referenced-instance". A workspace instance may span projects; a project instance remains in its owning project. For filtered counts in the referenced Project, use search_api and call_api SearchDatabases with a project filter and inspect one page. For other instance-specific counts, use SearchDatabases with the precise instance filter and inspect one page. Ask the member to clarify an ambiguous scope or filter; if the result has a nextPageToken, report only a lower bound, not a total. Only report results the API actually returned.\n`: isReadOnly? "- This is a read-only request. Stay on the current page and answer in chat. Do not navigate, call APIs, or use DOM actions. For a request about the user's open Issues in this project, call get_project_open_issues and summarize its result. For a request about what needs the user's attention in the workspace, call get_workspace_attention. For a request about what changed recently in this project, call get_project_recent_activity. For a request about what changed recently in the workspace, call get_workspace_recent_activity. Summarize only the returned events; do not infer details omitted from their safe summaries. Invite the user to send a follow-up message for other work.\n"- : '- Use navigate for "show me" / "go to" requests. Call navigate(list=true) first if unsure about the path — never guess routes.\n';+ : '- Use navigate for "show me" / "go to" requests. If the exact path is unclear, call navigate(list=true, query="<resource keyword>") to discover matching routes; avoid unfiltered route discovery and never guess paths.\n';const interactionInstructions ='- Use get_skill to load step-by-step workflow guides before multi-step tasks (SQL queries, schema changes, permission grants).\n- For call_api, submit the exact request; the executor pauses requests that need permission before execution, including SQL execution. Do not separately call ask_user to confirm the same API request. If permission is denied, do not retry unless the member explicitly asks again.\n- If call_api reports "Not called", the target API was not invoked. Explain the missing permission and resource when provided; do not imply that the member denied a confirmation request.\n- If call_api returns an error or HTTP status 400 or higher, or a SQL Query result contains permissionDenied, treat the request as unsuccessful. Do not claim the query or change succeeded. If no safe recovery is possible, explain the API error with done({ text, success: false, actions: [] }); do not silently retry a write.\n- Confirm destructive DOM actions with ask_user before executing them. When required input is missing, call ask_user instead of guessing.\n- 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.\n- In done, propose one primary action: Open, draft-plan, or draft-issue-comment. Use Open when a successful answer has a relevant next step supported by current-turn overview evidence. Use a typed target with its exact canonical resource; never provide a URL, invent a target, or imply it has already opened or executed. The member must click it. Supported Open target kinds are review-workspace-issues (workspace), review-project-issues (project), review-database-changes (project), transfer-project-databases (project), connect-project-instance (project), create-project-database (project), view-failed-tasks (plan), open-issue (issue), review-issue-plan (plan), and view-failed-task (task). An Open action only navigates; it never approves, retries, or executes. Only use draft-plan under the selected @Database guidance above; never use it to execute SQL. If the member asked for a security review of an Issue and you found a specific concern from current-turn evidence, use draft-issue-comment with the exact observed Issue name and a concise review comment. It opens an unsent editor draft; it never posts the comment. Do not include speculative findings.\n- For a successful answer, normally include 2-3 distinct, contextual Continue questions in English about useful next decisions or alternatives, with or without a primary action. Do not echo the click action. Do not add filler questions; include fewer or none when no further meaningful question exists. Continue only fills the composer and does not send or execute anything. Selected resources from this user turn stay bound to the prepared follow-ups, but resources only discovered in tool results do not; make questions about those resources self-contained. Do not include an API request, SQL statement, resource @ mention, or instruction that assumes the member already approved a change. Use actions: [] for a failed answer or when neither a supported primary action nor useful follow-up exists.\n- Call done({ text, success, actions }) when you are ready to finish. Do not reply with plain assistant text.\n- Do not call ask_user and done in the same response.\n';const resourceChoiceInstruction =diff --git a/frontend/src/modules/agent/logic/tools/index.ts b/frontend/src/modules/agent/logic/tools/index.tsindex 8771eb200a..9dc1caf65f 100644--- a/frontend/src/modules/agent/logic/tools/index.ts+++ b/frontend/src/modules/agent/logic/tools/index.ts@@ -336,14 +336,14 @@ call_api(operationId="SQLService/Query", body={"name": "instances/i/databases/db},{name: "navigate",- description: `Navigate to a page in Bytebase, or list all available routes.+ description: `Navigate to a page in Bytebase, or list a bounded set of valid routes.| Mode | Parameters | Result ||------|------------|--------|| Navigate | path="/projects" | Navigates to the page |-| List | list=true | Returns all valid route patterns |+| List | list=true, query="database" | Returns up to 30 matching route patterns, plus the total and whether results were truncated |-**Always call with list=true first if you are unsure about the exact path.** Do not guess paths — a wrong path causes a 404.`,+Use list=true only when the exact path is unclear. Pass a focused query to avoid broad route discovery. Do not guess paths — a wrong path causes a 404.`,parametersSchema: {type: "object",properties: {@@ -355,7 +355,12 @@ call_api(operationId="SQLService/Query", body={"name": "instances/i/databases/dblist: {type: "boolean",description:- "Set to true to list all available route patterns instead of navigating.",+ "Set to true to list up to 30 matching route patterns instead of navigating.",+ },+ query: {+ type: "string",+ description:+ "Optional case-insensitive substring filter for route patterns when list is true.",},},},diff --git a/frontend/src/modules/agent/logic/tools/navigate.test.ts b/frontend/src/modules/agent/logic/tools/navigate.test.tsnew file mode 100644index 0000000000..9c446a2b7d--- /dev/null+++ b/frontend/src/modules/agent/logic/tools/navigate.test.ts@@ -0,0 +1,50 @@+import { describe, expect, test, vi } from "vitest";+import type { AppRouterInstance } from "@/app/router";+import { createNavigateTool } from "./navigate";++const routerWithRoutes = (paths: string[]) =>+ ({+ getRoutes: () => paths.map((path) => ({ path, name: path, children: [] })),+ push: vi.fn(),+ currentRoute: { value: { fullPath: "/" } },+ }) as unknown as AppRouterInstance;++describe("createNavigateTool", () => {+ test("bounds route discovery and reports omitted matches", async () => {+ const paths = Array.from(+ { length: 45 },+ (_, index) => `/route-${String(index).padStart(2, "0")}`+ );+ const navigate = createNavigateTool(routerWithRoutes(paths));++ const result = JSON.parse(await navigate({ list: true })) as {+ routes: string[];+ total: number;+ truncated: boolean;+ };++ expect(result.routes).toHaveLength(30);+ expect(result.total).toBe(45);+ expect(result.truncated).toBe(true);+ });++ test("filters route discovery by a user-provided query", async () => {+ const navigate = createNavigateTool(+ routerWithRoutes([+ "/projects/:projectId/databases",+ "/projects/:projectId/issues",+ "/instances/:instanceId",+ ])+ );++ const result = JSON.parse(+ await navigate({ list: true, query: "database" })+ ) as { routes: string[]; total: number; truncated: boolean };++ expect(result).toEqual({+ routes: ["/projects/:projectId/databases"],+ total: 1,+ truncated: false,+ });+ });+});diff --git a/frontend/src/modules/agent/logic/tools/navigate.ts b/frontend/src/modules/agent/logic/tools/navigate.tsindex 2b2bb73cfb..35a855182d 100644--- a/frontend/src/modules/agent/logic/tools/navigate.ts+++ b/frontend/src/modules/agent/logic/tools/navigate.ts@@ -1,5 +1,7 @@import type { AppRouterInstance } from "@/app/router";+const MAX_ROUTE_RESULTS = 30;+function getRouteMap(router: AppRouterInstance): string[] {const routes = router.getRoutes();const paths = new Set<string>();@@ -25,10 +27,21 @@ function getRouteMap(router: AppRouterInstance): string[] {}export function createNavigateTool(router: AppRouterInstance) {- return async (args: { path?: string; list?: boolean }): Promise<string> => {+ return async (args: {+ path?: string;+ list?: boolean;+ query?: string;+ }): Promise<string> => {if (args.list) {- const routes = getRouteMap(router);- return JSON.stringify({ routes });+ const query = args.query?.trim().toLowerCase();+ const matchingRoutes = getRouteMap(router).filter(+ (path) => !query || path.toLowerCase().includes(query)+ );+ return JSON.stringify({+ routes: matchingRoutes.slice(0, MAX_ROUTE_RESULTS),+ total: matchingRoutes.length,+ truncated: matchingRoutes.length > MAX_ROUTE_RESULTS,+ });}if (!args.path) {