Skip to content

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

feat: support switch context for agent chat (#21576)

ecmadao1d99043cb9f6
diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.json
index cb099ad9f8..3d8cf9b252 100644
--- a/frontend/src/locales/en-US.json
+++ b/frontend/src/locales/en-US.json
@@ -41,6 +41,11 @@
"chat-total-tokens": "Total tokens: {{count}}",
"close": "Close",
"confirm": "Confirm",
+ "context": "Context",
+ "context-no-projects": "No accessible projects",
+ "context-select": "Select context",
+ "context-start-new-chat": "Start new chat in {{name}}",
+ "context-workspace": "Workspace",
"delete-all-chats": "Delete all chats",
"delete-all-chats-confirmation": "Are you sure you want to delete all archived chats? This action cannot be undone.",
"delete-chat": "Delete chat",
diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.json
index 3b6f91ad74..5605ebecf1 100644
--- a/frontend/src/locales/es-ES.json
+++ b/frontend/src/locales/es-ES.json
@@ -41,6 +41,11 @@
"chat-total-tokens": "Tokens totales: {{count}}",
"close": "Cerrar",
"confirm": "Confirmar",
+ "context": "Contexto",
+ "context-no-projects": "No hay proyectos accesibles",
+ "context-select": "Seleccionar contexto",
+ "context-start-new-chat": "Iniciar un chat nuevo en {{name}}",
+ "context-workspace": "Espacio de trabajo",
"delete-all-chats": "Eliminar todos los chats",
"delete-all-chats-confirmation": "¿Está seguro de que desea eliminar todos los chats archivados? Esta acción no se puede deshacer.",
"delete-chat": "Eliminar chat",
diff --git a/frontend/src/locales/ja-JP.json b/frontend/src/locales/ja-JP.json
index 7bbca28161..a9ba6d8810 100644
--- a/frontend/src/locales/ja-JP.json
+++ b/frontend/src/locales/ja-JP.json
@@ -41,6 +41,11 @@
"chat-total-tokens": "合計トークン数: {{count}}",
"close": "閉じる",
"confirm": "確認",
+ "context": "コンテキスト",
+ "context-no-projects": "アクセス可能なプロジェクトがありません",
+ "context-select": "コンテキストを選択",
+ "context-start-new-chat": "{{name}} で新しいチャットを開始",
+ "context-workspace": "ワークスペース",
"delete-all-chats": "すべてのチャットを削除",
"delete-all-chats-confirmation": "アーカイブ済みのチャットをすべて削除しますか?この操作は元に戻せません。",
"delete-chat": "チャットを削除",
diff --git a/frontend/src/locales/vi-VN.json b/frontend/src/locales/vi-VN.json
index f1253de9cc..2d7c2f3eea 100644
--- a/frontend/src/locales/vi-VN.json
+++ b/frontend/src/locales/vi-VN.json
@@ -41,6 +41,11 @@
"chat-total-tokens": "Tổng số token: {{count}}",
"close": "Đóng",
"confirm": "Xác nhận",
+ "context": "Ngữ cảnh",
+ "context-no-projects": "Không có dự án nào có thể truy cập",
+ "context-select": "Chọn ngữ cảnh",
+ "context-start-new-chat": "Bắt đầu cuộc trò chuyện mới trong {{name}}",
+ "context-workspace": "Không gian làm việc",
"delete-all-chats": "Xóa tất cả cuộc trò chuyện",
"delete-all-chats-confirmation": "Bạn có chắc chắn muốn xóa tất cả cuộc trò chuyện đã lưu trữ không? Hành động này không thể hoàn tác.",
"delete-chat": "Xóa cuộc trò chuyện",
diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.json
index 9c0d06b485..4584afdd17 100644
--- a/frontend/src/locales/zh-CN.json
+++ b/frontend/src/locales/zh-CN.json
@@ -41,6 +41,11 @@
"chat-total-tokens": "总 token 数:{{count}}",
"close": "关闭",
"confirm": "确认",
+ "context": "上下文",
+ "context-no-projects": "没有可访问的项目",
+ "context-select": "选择上下文",
+ "context-start-new-chat": "在 {{name}} 中开始新对话",
+ "context-workspace": "工作区",
"delete-all-chats": "删除所有对话",
"delete-all-chats-confirmation": "确定要删除所有已归档对话吗?此操作无法撤销。",
"delete-chat": "删除对话",
diff --git a/frontend/src/modules/agent/components/AgentContextPicker.tsx b/frontend/src/modules/agent/components/AgentContextPicker.tsx
new file mode 100644
index 0000000000..14500427ed
--- /dev/null
+++ b/frontend/src/modules/agent/components/AgentContextPicker.tsx
@@ -0,0 +1,176 @@
+import { Popover as BasePopover } from "@base-ui/react/popover";
+import { Building2, Check, ChevronDown, FolderKanban } from "lucide-react";
+import { useEffect, useState } from "react";
+import { useTranslation } from "react-i18next";
+import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+import { getLayerRoot, LAYER_SURFACE_CLASS } from "@/components/ui/layer";
+import { useProjectList } from "@/hooks/useAppState";
+import { getProjectName } from "@/lib/resourceName";
+
+interface AgentContextPickerProps {
+ context?: string;
+ contextTitle?: string;
+ workspace?: { name: string; title: string };
+ hasMessages: boolean;
+ disabled: boolean;
+ onSelect: (context: string) => boolean;
+}
+
+interface ContextOptionsProps extends AgentContextPickerProps {
+ close: () => void;
+}
+
+function ContextOptions({
+ context,
+ workspace,
+ hasMessages,
+ onSelect,
+ close,
+}: ContextOptionsProps) {
+ const { t } = useTranslation();
+ const [query, setQuery] = useState("");
+ const { projects, isLoading, isFetchingMore, hasMore, loadMore } =
+ useProjectList(query);
+
+ const select = (resource: string) => {
+ if (onSelect(resource)) close();
+ };
+
+ const optionLabel = (name: string, title: string) =>
+ hasMessages && name !== context
+ ? t("agent.context-start-new-chat", { name: title })
+ : title;
+
+ return (
+ <div className="flex max-h-80 flex-col" data-agent-context-options>
+ <Input
+ size="sm"
+ className="mb-2 shrink-0"
+ autoComplete="off"
+ value={query}
+ onChange={(event) => setQuery(event.target.value)}
+ placeholder={t("common.filter-by-name")}
+ aria-label={t("common.filter-by-name")}
+ />
+ <div className="min-h-0 overflow-y-auto">
+ {workspace?.name ? (
+ <div>
+ <div className="px-2 py-1 text-xs font-medium text-control-light">
+ {t("agent.context-workspace")}
+ </div>
+ <Button
+ appearance="secondary"
+ size="sm"
+ className="h-auto w-full justify-start gap-2 px-2 py-2 text-left text-sm"
+ data-agent-context-option={workspace.name}
+ onClick={() => select(workspace.name)}
+ >
+ <Building2 className="size-4 shrink-0" />
+ <span className="min-w-0 flex-1 truncate">
+ {optionLabel(workspace.name, workspace.title || workspace.name)}
+ </span>
+ {context === workspace.name ? <Check className="size-4" /> : null}
+ </Button>
+ </div>
+ ) : null}
+ <div className="px-2 py-1 text-xs font-medium text-control-light">
+ {t("common.projects")}
+ </div>
+ {projects.map((project) => (
+ <Button
+ key={project.name}
+ appearance="secondary"
+ size="sm"
+ className="h-auto w-full justify-start gap-2 px-2 py-2 text-left text-sm"
+ data-agent-context-option={project.name}
+ onClick={() => select(project.name)}
+ >
+ <FolderKanban className="size-4 shrink-0" />
+ <span className="min-w-0 flex-1 text-left">
+ <span className="block truncate">
+ {optionLabel(project.name, project.title || project.name)}
+ </span>
+ <span className="block truncate text-xs text-control-light">
+ {getProjectName(project.name)}
+ </span>
+ </span>
+ {context === project.name ? <Check className="size-4" /> : null}
+ </Button>
+ ))}
+ {!isLoading && projects.length === 0 ? (
+ <p className="px-2 py-2 text-xs text-control-light">
+ {t("agent.context-no-projects")}
+ </p>
+ ) : null}
+ {isLoading ? (
+ <p className="px-2 py-2 text-xs text-control-light">
+ {t("common.loading")}
+ </p>
+ ) : null}
+ {hasMore ? (
+ <Button
+ appearance="secondary"
+ size="sm"
+ className="w-full justify-start"
+ disabled={isFetchingMore}
+ onClick={loadMore}
+ >
+ {t("common.load-more")}
+ </Button>
+ ) : null}
+ </div>
+ </div>
+ );
+}
+
+export function AgentContextPicker(props: AgentContextPickerProps) {
+ const { t } = useTranslation();
+ const [open, setOpen] = useState(false);
+
+ useEffect(() => {
+ if (props.disabled) setOpen(false);
+ }, [props.disabled]);
+
+ return (
+ <BasePopover.Root open={open} onOpenChange={setOpen}>
+ <BasePopover.Trigger
+ render={
+ <Button
+ appearance="secondary"
+ size="sm"
+ className="h-auto min-w-0 max-w-full justify-start px-0 py-0 text-xs text-control-light hover:bg-transparent hover:text-control"
+ />
+ }
+ disabled={props.disabled}
+ data-agent-context-trigger
+ title={props.context}
+ >
+ <span className="min-w-0 truncate">
+ {t("agent.context")}:{" "}
+ <span data-agent-context>
+ {props.contextTitle || t("agent.context-select")}
+ </span>
+ </span>
+ <ChevronDown className="size-3 shrink-0" />
+ </BasePopover.Trigger>
+ <BasePopover.Portal container={getLayerRoot("agent")}>
+ <BasePopover.Positioner
+ side="top"
+ align="start"
+ sideOffset={6}
+ className={LAYER_SURFACE_CLASS}
+ >
+ <BasePopover.Popup
+ aria-label={t("agent.context-select")}
+ className="w-80 max-w-[calc(100vw-2rem)] rounded-sm border border-control-border bg-background p-2 shadow-md focus:outline-hidden"
+ >
+ {open ? (
+ <ContextOptions {...props} close={() => setOpen(false)} />
+ ) : null}
+ </BasePopover.Popup>
+ </BasePopover.Positioner>
+ </BasePopover.Portal>
+ </BasePopover.Root>
+ );
+}
diff --git a/frontend/src/modules/agent/components/AgentInput.test.tsx b/frontend/src/modules/agent/components/AgentInput.test.tsx
index a04fe374eb..098eb1f738 100644
--- a/frontend/src/modules/agent/components/AgentInput.test.tsx
+++ b/frontend/src/modules/agent/components/AgentInput.test.tsx
@@ -30,6 +30,12 @@ const mocks = vi.hoisted(() => ({
createToolExecutor: vi.fn(() => ({})),
getToolDefinitions: vi.fn(() => []),
getOrFetchSettingByName: vi.fn(),
+ getOrFetchProjectByName: vi.fn(),
+ projectsByName: {} as Record<string, { title: string }>,
+ availableProjects: [] as { name: string; title: string }[],
+ workspace: { name: "workspaces/demo", title: "Demo workspace" },
+ currentContext: "projects/orders" as string | undefined,
+ currentPath: "/demo",
}));
let AgentInput: typeof import("./AgentInput").AgentInput;
@@ -67,7 +73,9 @@ vi.mock("@/app/router", async (importOriginal) => ({
router: {
currentRoute: {
value: {
- fullPath: "/demo",
+ get fullPath() {
+ return mocks.currentPath;
+ },
},
},
push: mocks.routerPush,
@@ -77,7 +85,14 @@ vi.mock("@/app/router", async (importOriginal) => ({
vi.mock("@/stores/app", () => {
const state = {
getOrFetchSettingByName: mocks.getOrFetchSettingByName,
+ getOrFetchProjectByName: mocks.getOrFetchProjectByName,
getSettingByName: () => undefined,
+ get projectsByName() {
+ return mocks.projectsByName;
+ },
+ get workspace() {
+ return mocks.workspace;
+ },
};
const useAppStore = <T,>(selector: (value: typeof state) => T) =>
selector(state);
@@ -85,6 +100,16 @@ vi.mock("@/stores/app", () => {
return { useAppStore };
});
+vi.mock("@/hooks/useAppState", () => ({
+ useProjectList: () => ({
+ projects: mocks.availableProjects,
+ isLoading: false,
+ isFetchingMore: false,
+ hasMore: false,
+ loadMore: vi.fn(),
+ }),
+}));
+
vi.mock("../dom", () => ({
lazyExtractDomRefSuggestions: mocks.lazyExtractDomRefSuggestions,
}));
@@ -106,6 +131,10 @@ vi.mock("../logic/prompt", () => ({
buildSystemPrompt: mocks.buildSystemPrompt,
}));
+vi.mock("../logic/chatContext", () => ({
+ getCurrentChatContext: () => mocks.currentContext,
+}));
+
vi.mock("../logic/tools", () => ({
createToolExecutor: mocks.createToolExecutor,
getToolDefinitions: mocks.getToolDefinitions,
@@ -170,11 +199,21 @@ const stubAnimationFrames = () => {
beforeEach(async () => {
vi.stubGlobal("localStorage", createMockStorage());
- useAgentStore.setState(createAgentStore().getState(), true);
+ const initialState = createAgentStore().getState();
+ useAgentStore.setState({
+ chats: initialState.chats,
+ messagesByChatId: initialState.messagesByChatId,
+ pendingAskByChatId: initialState.pendingAskByChatId,
+ currentChatId: initialState.currentChatId,
+ abortControllersByChatId: {},
+ });
mocks.useTranslation.mockReset();
mocks.useTranslation.mockReturnValue({
- t: (key: string) => key,
+ t: (key: string, options?: { name?: string }) =>
+ key === "agent.context-start-new-chat"
+ ? `Start new chat in ${options?.name}`
+ : key,
});
mocks.routerPush.mockReset();
mocks.lazyExtractDomRefSuggestions.mockReset();
@@ -192,6 +231,16 @@ beforeEach(async () => {
mocks.getToolDefinitions.mockReturnValue([]);
mocks.getOrFetchSettingByName.mockReset();
mocks.getOrFetchSettingByName.mockResolvedValue(undefined);
+ mocks.getOrFetchProjectByName.mockReset();
+ mocks.getOrFetchProjectByName.mockResolvedValue(undefined);
+ mocks.projectsByName = { "projects/orders": { title: "Order service" } };
+ mocks.availableProjects = [
+ { name: "projects/orders", title: "Order service" },
+ { name: "projects/billing", title: "Billing" },
+ ];
+ mocks.workspace = { name: "workspaces/demo", title: "Demo workspace" };
+ mocks.currentContext = "projects/orders";
+ mocks.currentPath = "/demo";
({ AgentInput } = await import("./AgentInput"));
});
@@ -201,6 +250,236 @@ afterEach(() => {
});
describe("AgentInput", () => {
+ test("binds an initial empty chat and uses its context for every run", async () => {
+ mocks.runAgentLoop.mockResolvedValue({
+ kind: "completed",
+ totalTokensUsed: 0,
+ });
+ const { container, render, unmount } = renderIntoContainer(<AgentInput />);
+ render();
+
+ const textarea = container.querySelector("textarea") as HTMLTextAreaElement;
+ await act(async () => {
+ setTextareaValue(textarea, "First question");
+ textarea.dispatchEvent(new Event("input", { bubbles: true }));
+ });
+ await act(async () => {
+ (container.querySelector("[data-agent-send]") as HTMLButtonElement).click();
+ await Promise.resolve();
+ });
+
+ const chatId = useAgentStore.getState().currentChatId!;
+ expect(useAgentStore.getState().getChat(chatId)?.context).toBe(
+ "projects/orders"
+ );
+ expect(mocks.buildSystemPrompt).toHaveBeenLastCalledWith(
+ expect.objectContaining({ context: "projects/orders" })
+ );
+
+ mocks.currentContext = "projects/other";
+ mocks.currentPath = "/projects/other/issues";
+ await act(async () => {
+ setTextareaValue(textarea, "Follow-up question");
+ textarea.dispatchEvent(new Event("input", { bubbles: true }));
+ });
+ await act(async () => {
+ (container.querySelector("[data-agent-send]") as HTMLButtonElement).click();
+ await Promise.resolve();
+ });
+
+ expect(mocks.buildSystemPrompt).toHaveBeenCalledTimes(2);
+ expect(mocks.buildSystemPrompt).toHaveBeenLastCalledWith(
+ expect.objectContaining({
+ context: "projects/orders",
+ path: "/projects/other/issues",
+ })
+ );
+ expect(useAgentStore.getState().getChat(chatId)?.context).toBe(
+ "projects/orders"
+ );
+ unmount();
+ });
+
+ test("shows the project title while retaining its resource context", () => {
+ useAgentStore.getState().ensureCurrentChat(undefined, "projects/orders");
+ const { container, render, unmount } = renderIntoContainer(<AgentInput />);
+ render();
+
+ expect(container.querySelector("[data-agent-context]")?.textContent).toBe(
+ "Order service"
+ );
+ expect(useAgentStore.getState().chats[0].context).toBe("projects/orders");
+ unmount();
+ });
+
+ test("fetches a project title when the bound project is not cached", () => {
+ mocks.projectsByName = {};
+ useAgentStore.getState().ensureCurrentChat(undefined, "projects/orders");
+ const { container, render, unmount } = renderIntoContainer(<AgentInput />);
+ render();
+
+ expect(mocks.getOrFetchProjectByName).toHaveBeenCalledWith(
+ "projects/orders",
+ true
+ );
+ expect(container.querySelector("[data-agent-context]")?.textContent).toBe(
+ "orders"
+ );
+ unmount();
+ });
+
+ test("shows the workspace title for a workspace-bound chat", () => {
+ useAgentStore.getState().ensureCurrentChat(undefined, "workspaces/demo");
+ const { container, render, unmount } = renderIntoContainer(<AgentInput />);
+ render();
+
+ expect(container.querySelector("[data-agent-context]")?.textContent).toBe(
+ "Demo workspace"
+ );
+ unmount();
+ });
+
+ test("changes the context of an empty chat from the composer", async () => {
+ useAgentStore.getState().ensureCurrentChat(undefined, "projects/orders");
+ const { container, render, unmount } = renderIntoContainer(<AgentInput />);
+ render();
+
+ await act(async () => {
+ container
+ .querySelector<HTMLButtonElement>("[data-agent-context-trigger]")
+ ?.click();
+ });
+ await act(async () => {
+ document
+ .querySelector<HTMLButtonElement>(
+ '[data-agent-context-option="workspaces/demo"]'
+ )
+ ?.click();
+ });
+
+ expect(useAgentStore.getState().chats).toHaveLength(1);
+ expect(useAgentStore.getState().chats[0].context).toBe("workspaces/demo");
+ expect(container.querySelector("[data-agent-context]")?.textContent).toBe(
+ "Demo workspace"
+ );
+ unmount();
+ });
+
+ test("starts a new chat when choosing a different context after a message", async () => {
+ const original = useAgentStore
+ .getState()
+ .ensureCurrentChat(undefined, "projects/orders");
+ act(() => {
+ useAgentStore.getState().addMessage({
+ chatId: original.id,
+ role: "user",
+ content: "What changed?",
+ });
+ });
+ const { container, render, unmount } = renderIntoContainer(<AgentInput />);
+ render();
+
+ await act(async () => {
+ container
+ .querySelector<HTMLButtonElement>("[data-agent-context-trigger]")
+ ?.click();
+ });
+ expect(document.body.textContent).toContain("Start new chat in Billing");
+ await act(async () => {
+ document
+ .querySelector<HTMLButtonElement>(
+ '[data-agent-context-option="projects/billing"]'
+ )
+ ?.click();
+ });
+
+ expect(useAgentStore.getState().chats).toHaveLength(2);
+ expect(useAgentStore.getState().getChat(original.id)?.context).toBe(
+ "projects/orders"
+ );
+ expect(useAgentStore.getState().getMessages(original.id)).toHaveLength(1);
+ expect(
+ useAgentStore
+ .getState()
+ .getChat(useAgentStore.getState().currentChatId)?.context
+ ).toBe("projects/billing");
+ unmount();
+ });
+
+ test("closes the context picker when an agent run starts", async () => {
+ const chat = useAgentStore
+ .getState()
+ .ensureCurrentChat(undefined, "projects/orders");
+ const { container, render, unmount } = renderIntoContainer(<AgentInput />);
+ render();
+
+ await act(async () => {
+ container
+ .querySelector<HTMLButtonElement>("[data-agent-context-trigger]")
+ ?.click();
+ });
+ expect(document.querySelector("[data-agent-context-options]")).not.toBeNull();
+
+ await act(async () => {
+ useAgentStore.getState().setChatStatus(chat.id, "running");
+ });
+
+ expect(
+ container.querySelector<HTMLButtonElement>("[data-agent-context-trigger]")
+ ?.disabled
+ ).toBe(true);
+ expect(document.querySelector("[data-agent-context-options]")).toBeNull();
+ unmount();
+ });
+
+ test("shows resource IDs for every project in the context picker", async () => {
+ mocks.availableProjects = [
+ { name: "projects/billing-a", title: "Billing" },
+ { name: "projects/billing-b", title: "Billing" },
+ { name: "projects/orders", title: "Orders" },
+ ];
+ const { container, render, unmount } = renderIntoContainer(<AgentInput />);
+ render();
+
+ await act(async () => {
+ container
+ .querySelector<HTMLButtonElement>("[data-agent-context-trigger]")
+ ?.click();
+ });
+
+ expect(
+ document.querySelector('[data-agent-context-option="projects/billing-a"]')
+ ?.textContent
+ ).toContain("billing-a");
+ expect(
+ document.querySelector('[data-agent-context-option="projects/billing-b"]')
+ ?.textContent
+ ).toContain("billing-b");
+ expect(
+ document.querySelector('[data-agent-context-option="projects/orders"]')
+ ?.textContent
+ ).toContain("orders");
+ unmount();
+ });
+
+ test("disables browser autocomplete for the context filter", async () => {
+ const { container, render, unmount } = renderIntoContainer(<AgentInput />);
+ render();
+
+ await act(async () => {
+ container
+ .querySelector<HTMLButtonElement>("[data-agent-context-trigger]")
+ ?.click();
+ });
+
+ expect(
+ document.querySelector<HTMLInputElement>(
+ '[data-agent-context-options] input'
+ )?.autocomplete
+ ).toBe("off");
+ unmount();
+ });
+
test("shows AI setup before the first prompt when AI is disabled", async () => {
mocks.getOrFetchSettingByName.mockResolvedValue({
value: {
@@ -445,7 +724,9 @@ describe("AgentInput", () => {
"max-h-[134px]"
);
expect(container.querySelector("textarea")?.className).toContain("block");
- expect(container.querySelector("button")?.className).toContain("h-9");
+ expect(container.querySelector("[data-agent-send]")?.className).toContain(
+ "h-9"
+ );
unmount();
});
diff --git a/frontend/src/modules/agent/components/AgentInput.tsx b/frontend/src/modules/agent/components/AgentInput.tsx
index 667ed2c354..0b75d8c99a 100644
--- a/frontend/src/modules/agent/components/AgentInput.tsx
+++ b/frontend/src/modules/agent/components/AgentInput.tsx
@@ -14,6 +14,7 @@ import { router } from "@/app/router";
import { Button } from "@/components/ui/button";
import { getLayerRoot, LAYER_SURFACE_CLASS } from "@/components/ui/layer";
import { Textarea } from "@/components/ui/textarea";
+import { projectNamePrefix } from "@/lib/resourceName";
import { useAppStore } from "@/stores/app";
import { Setting_SettingName } from "@/types/proto-es/v1/setting_service_pb";
import type { DomRefSuggestion } from "../dom";
@@ -23,6 +24,7 @@ import {
getAgentAIConfigurationEnabled,
isAgentAIConfigurationError,
} from "../logic/aiConfiguration";
+import { getCurrentChatContext } from "../logic/chatContext";
import { buildOutboundHistory } from "../logic/outboundHistory";
import { buildSystemPrompt } from "../logic/prompt";
import { createToolExecutor, getToolDefinitions } from "../logic/tools";
@@ -31,9 +33,11 @@ import {
selectCurrentChat,
selectCurrentChatRequiresAIConfiguration,
selectCurrentPendingAsk,
+ selectHasRunningChat,
selectLoading,
useAgentStore,
} from "../store/agent";
+import { AgentContextPicker } from "./AgentContextPicker";
// Module-level map — survives across renders.
const runTokens = new Map<string, number>();
@@ -115,11 +119,24 @@ export function AgentInput() {
const currentChat = useAgentStore(selectCurrentChat);
const currentPendingAsk = useAgentStore(selectCurrentPendingAsk);
const loading = useAgentStore(selectLoading);
+ const hasRunningChat = useAgentStore(selectHasRunningChat);
+ const hasMessages = useAgentStore((s) =>
+ Boolean(s.messagesByChatId[s.currentChatId ?? ""]?.length)
+ );
const isAIConfigurationBlocked = useAgentStore(
selectCurrentChatRequiresAIConfiguration
);
const currentChatId = useAgentStore((s) => s.currentChatId);
const getOrFetchSettingByName = useAppStore((s) => s.getOrFetchSettingByName);
+ const context = currentChat?.context;
+ const projectContext = context?.startsWith(projectNamePrefix)
+ ? context
+ : undefined;
+ const contextProject = useAppStore((s) =>
+ projectContext ? s.projectsByName[projectContext] : undefined
+ );
+ const workspace = useAppStore((s) => s.workspace);
+ const getOrFetchProjectByName = useAppStore((s) => s.getOrFetchProjectByName);
const aiConfigurationEnabled = useAppStore((s) =>
getAgentAIConfigurationEnabled(s.getSettingByName(Setting_SettingName.AI))
);
@@ -172,6 +189,25 @@ export function AgentInput() {
}),
[currentChat?.totalTokensUsed, t]
);
+ const contextTitle = projectContext
+ ? contextProject?.title || projectContext.slice(projectNamePrefix.length)
+ : context === workspace?.name
+ ? workspace?.title || context
+ : context;
+
+ const selectContext = useCallback((resource: string) => {
+ return Boolean(
+ useAgentStore
+ .getState()
+ .selectChatContext(resource, getCurrentPageSnapshot())
+ );
+ }, []);
+
+ useEffect(() => {
+ if (projectContext && !contextProject) {
+ void getOrFetchProjectByName(projectContext, true);
+ }
+ }, [contextProject, getOrFetchProjectByName, projectContext]);
const blockWhenAIIsNotConfigured = useCallback(
async (chatId: string) => {
@@ -464,7 +500,10 @@ export function AgentInput() {
runTokens.set(chatId, runToken);
store.setAbortController(chatId, controller);
- const systemPrompt = buildSystemPrompt(page);
+ const systemPrompt = buildSystemPrompt({
+ ...page,
+ context: store.getChat(chatId)?.context,
+ });
const tools = getToolDefinitions();
const executor = createToolExecutor(router, {
chatId,
@@ -548,7 +587,10 @@ export function AgentInput() {
if (store.isChatRunning(chat?.id)) return;
const currentPage = getCurrentPageSnapshot();
- const thread = store.ensureCurrentChat(currentPage);
+ const thread = store.ensureCurrentChat(
+ currentPage,
+ getCurrentChatContext()
+ );
const chatId = thread.id;
if (await blockWhenAIIsNotConfigured(chatId)) return;
store.clearError(chatId);
@@ -772,10 +814,18 @@ export function AgentInput() {
)}
<div
- className="mb-1 flex justify-end text-xs text-control-light"
+ className="mb-1 flex items-center justify-between gap-2 text-xs text-control-light"
data-agent-input-footer
>
- {currentChatTokenUsageLabel}
+ <AgentContextPicker
+ context={context}
+ contextTitle={contextTitle}
+ workspace={workspace}
+ hasMessages={hasMessages}
+ disabled={hasRunningChat || Boolean(currentPendingAsk)}
+ onSelect={selectContext}
+ />
+ <span className="shrink-0">{currentChatTokenUsageLabel}</span>
</div>
{/* Confirm buttons */}
@@ -916,6 +966,7 @@ export function AgentInput() {
<Button
size="md"
className="shrink-0 self-end whitespace-nowrap"
+ data-agent-send
disabled={isSendDisabled}
onClick={() => void send()}
>
diff --git a/frontend/src/modules/agent/components/AgentWindow.test.tsx b/frontend/src/modules/agent/components/AgentWindow.test.tsx
index b72893ba34..2ceb0df9ac 100644
--- a/frontend/src/modules/agent/components/AgentWindow.test.tsx
+++ b/frontend/src/modules/agent/components/AgentWindow.test.tsx
@@ -15,6 +15,7 @@ const mocks = vi.hoisted(() => ({
i18n: { language: "en-US" },
})),
getOrFetchSettingByName: vi.fn(),
+ currentContext: "projects/orders" as string | undefined,
}));
function createMockStorage(): Storage {
@@ -56,6 +57,10 @@ vi.mock("@/stores/app", () => {
return { useAppStore };
});
+vi.mock("../logic/chatContext", () => ({
+ getCurrentChatContext: () => mocks.currentContext,
+}));
+
vi.mock("./AgentChat", () => ({
AgentChat: () => <div data-testid="agent-chat" />,
}));
@@ -138,6 +143,7 @@ beforeEach(async () => {
});
mocks.getOrFetchSettingByName.mockReset();
mocks.getOrFetchSettingByName.mockResolvedValue(undefined);
+ mocks.currentContext = "projects/orders";
({ AgentWindow } = await import("./AgentWindow"));
});
@@ -149,6 +155,36 @@ afterEach(() => {
});
describe("AgentWindow", () => {
+ test("binds the initial empty chat when opened under a project", () => {
+ const chatId = useAgentStore.getState().currentChatId!;
+ expect(useAgentStore.getState().getChat(chatId)?.context).toBeUndefined();
+
+ const { render, unmount } = renderIntoContainer(<AgentWindow />);
+ render();
+
+ expect(useAgentStore.getState().getChat(chatId)?.context).toBe(
+ "projects/orders"
+ );
+ unmount();
+ });
+
+ test("binds a new empty chat to the current resource context", async () => {
+ const { render, unmount } = renderIntoContainer(<AgentWindow />);
+ render();
+
+ const trigger = document.body.querySelector(
+ "[aria-label='agent.new-chat']"
+ ) as HTMLButtonElement | null;
+ await act(async () => trigger?.click());
+
+ const chatId = useAgentStore.getState().currentChatId!;
+ expect(useAgentStore.getState().getChat(chatId)?.context).toBe(
+ "projects/orders"
+ );
+ expect(useAgentStore.getState().getMessages(chatId)).toEqual([]);
+ unmount();
+ });
+
test("checks AI configuration when opening an existing chat", async () => {
const chatId = useAgentStore.getState().currentChatId!;
mocks.getOrFetchSettingByName.mockResolvedValue({
diff --git a/frontend/src/modules/agent/components/AgentWindow.tsx b/frontend/src/modules/agent/components/AgentWindow.tsx
index bbd6caa535..dac80b232c 100644
--- a/frontend/src/modules/agent/components/AgentWindow.tsx
+++ b/frontend/src/modules/agent/components/AgentWindow.tsx
@@ -24,6 +24,7 @@ import { useAppStore } from "@/stores/app";
import { Setting_SettingName } from "@/types/proto-es/v1/setting_service_pb";
import { formatAbsoluteDateTime } from "@/utils";
import { getAgentAIConfigurationEnabled } from "../logic/aiConfiguration";
+import { getCurrentChatContext } from "../logic/chatContext";
import type { AgentChat as AgentChatRecord } from "../logic/types";
import {
selectCurrentChat,
@@ -365,7 +366,10 @@ export function AgentWindow() {
store.clearCurrentChat();
return;
}
- store.createChat({ page: getCurrentPageSnapshot() });
+ store.createChat({
+ page: getCurrentPageSnapshot(),
+ context: getCurrentChatContext(),
+ });
},
[showArchivedOnly, selectFirstDisplayedChat, getCurrentPageSnapshot]
);
@@ -433,7 +437,10 @@ export function AgentWindow() {
const createChat = useCallback(() => {
if (isChatCreationDisabled) return;
- useAgentStore.getState().createChat({ page: getCurrentPageSnapshot() });
+ useAgentStore.getState().createChat({
+ page: getCurrentPageSnapshot(),
+ context: getCurrentChatContext(),
+ });
}, [isChatCreationDisabled, getCurrentPageSnapshot]);
const handleChatRowClick = useCallback(
@@ -829,6 +836,13 @@ export function AgentWindow() {
useAgentStore.getState().loadWindowState();
}, []);
+ useEffect(() => {
+ if (!visible || !currentChatId) return;
+ useAgentStore
+ .getState()
+ .ensureCurrentChat(getCurrentPageSnapshot(), getCurrentChatContext());
+ }, [currentChatId, getCurrentPageSnapshot, visible]);
+
useEffect(() => {
if (!visible || !currentChatId) return;
@@ -973,7 +987,7 @@ export function AgentWindow() {
maxSize={maxSidebarWidth}
groupResizeBehavior="preserve-pixel-size"
>
- <aside className="flex size-full flex-col border-r border-block-border bg-control-bg">
+ <aside className="flex size-full flex-col bg-control-bg">
{/* Sidebar header */}
<div className="border-b border-block-border px-3 py-3">
<div className="flex items-center justify-between gap-x-2">
@@ -1067,8 +1081,8 @@ export function AgentWindow() {
</div>
{/* Chat list */}
- <div className="min-h-0 flex-1 overflow-y-auto px-2 py-2">
- <div className="flex flex-col gap-y-1" data-agent-chat-list>
+ <div className="min-h-0 flex-1 overflow-y-auto">
+ <div className="flex flex-col" data-agent-chat-list>
{displayedChats.map((chat) => (
<div
key={chat.id}
diff --git a/frontend/src/modules/agent/logic/chatContext.test.ts b/frontend/src/modules/agent/logic/chatContext.test.ts
new file mode 100644
index 0000000000..0a74aeefef
--- /dev/null
+++ b/frontend/src/modules/agent/logic/chatContext.test.ts
@@ -0,0 +1,33 @@
+import { describe, expect, test } from "vitest";
+import type { ReactRoute } from "@/app/router";
+import { resolveChatContext } from "./chatContext";
+
+const routeWithParams = (params: ReactRoute["params"]) =>
+ ({ params }) as ReactRoute;
+
+describe("resolveChatContext", () => {
+ test("uses the project resource on project routes", () => {
+ expect(
+ resolveChatContext(
+ routeWithParams({ projectId: "orders" }),
+ "workspaces/demo"
+ )
+ ).toBe("projects/orders");
+ expect(
+ resolveChatContext(
+ routeWithParams({ project: "orders" }),
+ "workspaces/demo"
+ )
+ ).toBe("projects/orders");
+ });
+
+ test("uses the active workspace on other routes", () => {
+ expect(resolveChatContext(routeWithParams({}), "workspaces/demo")).toBe(
+ "workspaces/demo"
+ );
+ });
+
+ test("does not invent a context before the workspace is known", () => {
+ expect(resolveChatContext(routeWithParams({}), "")).toBeUndefined();
+ });
+});
diff --git a/frontend/src/modules/agent/logic/chatContext.ts b/frontend/src/modules/agent/logic/chatContext.ts
new file mode 100644
index 0000000000..a16ca756be
--- /dev/null
+++ b/frontend/src/modules/agent/logic/chatContext.ts
@@ -0,0 +1,26 @@
+import { type ReactRoute, router } from "@/app/router";
+import { projectNamePrefix, workspaceNamePrefix } from "@/lib/resourceName";
+import { useAppStore } from "@/stores/app";
+
+export function resolveChatContext(
+ route: ReactRoute,
+ workspaceName: string
+): string | undefined {
+ const projectId = route.params.projectId ?? route.params.project;
+ if (typeof projectId === "string" && projectId && projectId !== "-") {
+ return `${projectNamePrefix}${projectId}`;
+ }
+ return workspaceName.startsWith(workspaceNamePrefix)
+ ? workspaceName
+ : undefined;
+}
+
+export function getCurrentChatContext(): string | undefined {
+ const state = useAppStore.getState();
+ const workspaceName =
+ state.workspace?.name ||
+ state.currentUser?.workspace ||
+ state.serverInfo?.workspace ||
+ "";
+ return resolveChatContext(router.currentRoute.value, workspaceName);
+}
diff --git a/frontend/src/modules/agent/logic/prompt.test.ts b/frontend/src/modules/agent/logic/prompt.test.ts
index b85d58dadf..d7620dddf0 100644
--- a/frontend/src/modules/agent/logic/prompt.test.ts
+++ b/frontend/src/modules/agent/logic/prompt.test.ts
@@ -3,6 +3,28 @@ import { describe, expect, test } from "vitest";
import { buildSystemPrompt } from "./prompt";
describe("buildSystemPrompt", () => {
+ test("names the chat context separately from the live page", () => {
+ const prompt = buildSystemPrompt({
+ path: "/projects/other/issues",
+ title: "Other project",
+ context: "projects/orders",
+ });
+
+ expect(prompt).toContain("Chat context: projects/orders");
+ expect(prompt).toContain("Current page: /projects/other/issues");
+ expect(prompt).toContain("Navigation does not change the chat context");
+ });
+
+ test("accepts a workspace resource as the chat context", () => {
+ expect(
+ buildSystemPrompt({
+ path: "/landing",
+ title: "Workspace",
+ context: "workspaces/demo",
+ })
+ ).toContain("Chat context: workspaces/demo");
+ });
+
test("teaches the ref-based DOM workflow", () => {
const prompt = buildSystemPrompt({
path: "/issues/123",
diff --git a/frontend/src/modules/agent/logic/prompt.ts b/frontend/src/modules/agent/logic/prompt.ts
index b998677dbf..cc8bb464eb 100644
--- a/frontend/src/modules/agent/logic/prompt.ts
+++ b/frontend/src/modules/agent/logic/prompt.ts
@@ -56,6 +56,7 @@ export function buildSystemPrompt(pageContext: {
path: string;
title: string;
role?: string;
+ context?: string;
}): string {
return `You are Bytebase Assistant, an AI agent embedded in the Bytebase console.
You help DBAs and developers manage databases, write SQL, review changes,
@@ -63,6 +64,7 @@ and navigate the platform.
Rules:
- Always call get_page_state first to understand the current page context.
+- Treat the chat context as the default resource for unqualified requests and API scope fields when applicable. Navigation does not change the chat context; get_page_state reports the live page, which may differ. Follow an explicit resource named by the user instead.
- 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 before executing them. When you need confirmation or missing input from the user, call ask_user instead of guessing.
@@ -90,6 +92,6 @@ Core concepts:
Flow: create → review → approve → roll out.
- SQL Editor: interactive query tool with access control.
-Current page: ${pageContext.path}
+${pageContext.context ? `Chat context: ${pageContext.context}\n` : ""}Current page: ${pageContext.path}
Page title: ${pageContext.title}${pageContext.role ? `\nYour role: ${pageContext.role}` : ""}`;
}
diff --git a/frontend/src/modules/agent/logic/types.ts b/frontend/src/modules/agent/logic/types.ts
index bcc99c8093..4777f26548 100644
--- a/frontend/src/modules/agent/logic/types.ts
+++ b/frontend/src/modules/agent/logic/types.ts
@@ -43,6 +43,7 @@ export interface AgentMessage extends Message {
export interface AgentChat {
id: string;
title: string;
+ context?: string;
createdTs: number;
updatedTs: number;
status: AgentChatStatus;
diff --git a/frontend/src/modules/agent/store/agent.test.ts b/frontend/src/modules/agent/store/agent.test.ts
index 7fbd26f78a..eb8c544e21 100644
--- a/frontend/src/modules/agent/store/agent.test.ts
+++ b/frontend/src/modules/agent/store/agent.test.ts
@@ -71,6 +71,93 @@ describe("useAgentStore (Zustand)", () => {
expect(s(store).chats[0].totalTokensUsed).toBe(0);
});
+ test("keeps a chat's resource context when its page changes and after reload", () => {
+ const store = createAgentStore();
+ const chat = s(store).createChat({ context: "projects/orders" });
+
+ s(store).updateChatPage(chat.id, {
+ path: "/projects/other/issues",
+ title: "Other project",
+ });
+
+ expect(s(store).getChat(chat.id)?.context).toBe("projects/orders");
+ expect(s(createAgentStore()).getChat(chat.id)?.context).toBe(
+ "projects/orders"
+ );
+ });
+
+ test("binds only an empty legacy chat when a context is supplied", () => {
+ const store = createAgentStore();
+ const emptyChatId = s(store).currentChatId!;
+
+ s(store).ensureCurrentChat(undefined, "workspaces/demo");
+ expect(s(store).getChat(emptyChatId)?.context).toBe("workspaces/demo");
+
+ const legacy = s(store).createChat();
+ s(store).addMessage({
+ chatId: legacy.id,
+ role: "user",
+ content: "Earlier work",
+ });
+ s(store).ensureCurrentChat(undefined, "projects/orders");
+ expect(s(store).getChat(legacy.id)?.context).toBeUndefined();
+ });
+
+ test("changes the context of an empty chat without creating another chat", () => {
+ const store = createAgentStore();
+ const chat = s(store).ensureCurrentChat(undefined, "projects/orders");
+
+ const selected = s(store).selectChatContext("workspaces/demo");
+
+ expect(selected?.id).toBe(chat.id);
+ expect(s(store).chats).toHaveLength(1);
+ expect(s(store).getChat(chat.id)?.context).toBe("workspaces/demo");
+ expect(s(createAgentStore()).getChat(chat.id)?.context).toBe(
+ "workspaces/demo"
+ );
+ });
+
+ test("starts a new chat when changing the context of a populated chat", () => {
+ const store = createAgentStore();
+ const original = s(store).ensureCurrentChat(undefined, "projects/orders");
+ s(store).addMessage({
+ chatId: original.id,
+ role: "user",
+ content: "Hello",
+ });
+
+ const selected = s(store).selectChatContext("projects/billing", {
+ path: "/projects/orders",
+ title: "Orders",
+ });
+
+ expect(selected?.id).not.toBe(original.id);
+ expect(selected?.context).toBe("projects/billing");
+ expect(s(store).currentChatId).toBe(selected?.id);
+ expect(s(store).getMessages(selected?.id)).toEqual([]);
+ expect(s(store).getChat(original.id)?.context).toBe("projects/orders");
+ expect(s(store).getMessages(original.id)).toHaveLength(1);
+ });
+
+ test("does not change context while any chat is running", () => {
+ const store = createAgentStore();
+ const chat = s(store).ensureCurrentChat(undefined, "projects/orders");
+ s(store).setChatStatus(chat.id, "running");
+
+ expect(s(store).selectChatContext("projects/billing")).toBeNull();
+ expect(s(store).getChat(chat.id)?.context).toBe("projects/orders");
+ expect(s(store).chats).toHaveLength(1);
+ });
+
+ test("keeps a populated chat when its current context is selected", () => {
+ const store = createAgentStore();
+ const chat = s(store).ensureCurrentChat(undefined, "projects/orders");
+ s(store).addMessage({ chatId: chat.id, role: "user", content: "Hello" });
+
+ expect(s(store).selectChatContext("projects/orders")?.id).toBe(chat.id);
+ expect(s(store).chats).toHaveLength(1);
+ });
+
test("uses larger bottom-right window defaults when no saved window state exists", () => {
setViewportSize(1440, 900);
diff --git a/frontend/src/modules/agent/store/agent.ts b/frontend/src/modules/agent/store/agent.ts
index 00a1175374..ce5a2f2682 100644
--- a/frontend/src/modules/agent/store/agent.ts
+++ b/frontend/src/modules/agent/store/agent.ts
@@ -29,6 +29,7 @@ interface PersistedAgentState {
interface CreateChatOptions {
page?: AgentChatSnapshot;
+ context?: string;
select?: boolean;
title?: string;
archived?: boolean;
@@ -48,6 +49,7 @@ const createChatRecord = (options: CreateChatOptions = {}): AgentChat => {
return {
id: uuidv4(),
title: options.title ?? "",
+ context: options.context,
createdTs: now,
updatedTs: now,
status: DEFAULT_CHAT_STATUS,
@@ -189,6 +191,10 @@ const normalizeChat = (raw: unknown): AgentChat => {
return {
id: typeof chat.id === "string" ? chat.id : uuidv4(),
title: typeof chat.title === "string" ? chat.title : "",
+ context:
+ typeof chat.context === "string" && chat.context.trim()
+ ? chat.context
+ : undefined,
createdTs: typeof chat.createdTs === "number" ? chat.createdTs : now,
updatedTs: typeof chat.updatedTs === "number" ? chat.updatedTs : now,
status,
@@ -353,7 +359,11 @@ export interface AgentState {
// Chat CRUD
createChat: (options?: CreateChatOptions) => AgentChat;
- ensureCurrentChat: (page?: AgentChatSnapshot) => AgentChat;
+ ensureCurrentChat: (page?: AgentChatSnapshot, context?: string) => AgentChat;
+ selectChatContext: (
+ context: string,
+ page?: AgentChatSnapshot
+ ) => AgentChat | null;
setCurrentChat: (chatId: string) => void;
clearCurrentChat: () => void;
updateChatPage: (chatId: string, page: AgentChatSnapshot) => AgentChat | null;
@@ -719,21 +729,52 @@ export const createAgentStore = () => {
return chat;
},
- ensureCurrentChat: (page) => {
+ ensureCurrentChat: (page, context) => {
const existing = _getChat(get().currentChatId);
if (existing) {
- if (page && !existing.page) {
+ if (
+ (page && !existing.page) ||
+ (context &&
+ !existing.context &&
+ get().getMessages(existing.id).length === 0)
+ ) {
set((state) => {
const chat = state.chats.find((c) => c.id === existing.id);
if (chat) {
- chat.page = page;
+ if (page && !chat.page) chat.page = page;
+ if (
+ context &&
+ !chat.context &&
+ !state.messagesByChatId[chat.id]?.length
+ ) {
+ chat.context = context;
+ }
_touchChatInDraft(state.chats, chat.id);
}
});
}
return _getChat(existing.id)!;
}
- return get().createChat({ page });
+ return get().createChat({ page, context });
+ },
+
+ selectChatContext: (context, page) => {
+ if (!context || _hasRunningChat()) return null;
+ const current = _getChat(get().currentChatId);
+ if (!current) return get().createChat({ page, context });
+ if (current.context === context) return current;
+ if (get().getPendingAsk(current.id)) return null;
+ if (get().getMessages(current.id).length > 0) {
+ return get().createChat({ page, context });
+ }
+ set((state) => {
+ const chat = state.chats.find((c) => c.id === current.id);
+ if (chat) {
+ chat.context = context;
+ _touchChatInDraft(state.chats, chat.id);
+ }
+ });
+ return _getChat(current.id);
},
setCurrentChat: (chatId) => {