Skip to content

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

feat: built-in prompts for agent (#21624)

ecmadao2ebb0c1d456f
diff --git a/frontend/scripts/check-i18n.mjs b/frontend/scripts/check-i18n.mjs
index 7d5fd3b6cd..f2431deab4 100644
--- a/frontend/scripts/check-i18n.mjs
+++ b/frontend/scripts/check-i18n.mjs
@@ -66,6 +66,13 @@ const DYNAMIC_PREFIXES = [
"workspace-setup-guide.generic.",
"workspace-setup-guide.scenarios.",
"workspace-setup-guide.steps.",
+ // Landing starter IDs are ranked in a pure helper and translated by the
+ // shared selector using the selected ID.
+ "agent.landing-starters.",
+ // Attention result labels use the Issue relation returned by a bounded
+ // read-only lookup to choose the corresponding translation key.
+ "agent.project-attention.issue-",
+ "agent.workspace-attention.issue-",
// MCP mode cards and the broken-ceiling banner, rendered via
// t(`settings.mcp.policy.mode.${key}.title`) and a ternary over two key
// strings in MCPAccessPolicySection.tsx, not as literal t("…") calls.
diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.json
index 0ec324b31f..edccdeac06 100644
--- a/frontend/src/locales/en-US.json
+++ b/frontend/src/locales/en-US.json
@@ -53,11 +53,49 @@
"input-placeholder": "Ask AI anything...",
"interrupted": "Interrupted",
"interrupted-retry-hint": "The conversation was interrupted. You can retry or send a new message.",
+ "landing-starters": {
+ "menu": "Suggestions",
+ "more": "More suggestions",
+ "project-access": "What should I set up before collaborating on this project?",
+ "project-collaborate": "How do I invite teammates to this project?",
+ "project-connect": "How do I connect a database to this project?",
+ "project-next": "What can I do next?",
+ "project-open-blockers": "What needs my attention in this project?",
+ "project-open-recent": "What changed recently in this project?",
+ "project-organize": "How should I organize databases and environments for this project?",
+ "project-propose-change": "How do I propose a database change?",
+ "project-review": "How are database changes reviewed in this project?",
+ "workspace-attention": "What needs my attention?",
+ "workspace-concepts": "Help me understand Projects, Instances, and Databases",
+ "workspace-governance": "How does Bytebase govern database changes?",
+ "workspace-recent": "What changed recently in this workspace?",
+ "workspace-setup-first": "What should I set up first?"
+ },
"minimize": "Minimize",
"new-chat": "New Chat",
+ "other-chats": "Other chats",
"pending-choose-hint": "Please select an option above",
"pending-confirm-hint": "Please confirm or cancel above",
"pending-input-hint": "Please provide input above",
+ "project-attention": {
+ "checking": "Checking items needing your attention...",
+ "empty": "You have no open issues needing attention in this project.",
+ "issue-created": "- {{title}} (created by you)",
+ "issue-review": "- {{title}} (awaiting your approval)",
+ "more": "More open issues need your attention in this project.",
+ "partial": "I could not check every open issue needing your attention in this project.",
+ "summary": "These issues need your attention in this project:",
+ "unavailable": "Unable to load items needing your attention in this project."
+ },
+ "recent-activity": {
+ "checking": "Checking recent activity...",
+ "empty": "No meaningful activity was recorded in the last 3 days.",
+ "event": "{{actor}} {{action}} {{resource}} at {{time}}",
+ "more": "More recent activity is available.",
+ "summary": "Recent activity from the last 3 days:",
+ "unavailable": "Unable to load recent activity.",
+ "unknown-time": "an unknown time"
+ },
"rename-chat-placeholder": "Enter chat name",
"reply": "Reply",
"result": "Result",
@@ -78,7 +116,17 @@
"tool-response-submitted": "Response submitted",
"tool-value": "Value",
"unarchive-all-chats": "Unarchive all chats",
- "unarchive-chat": "Unarchive chat"
+ "unarchive-chat": "Unarchive chat",
+ "workspace-attention": {
+ "checking": "Checking items needing your attention...",
+ "empty": "You have no open issues needing attention.",
+ "issue-created": "- {{title}} (created by you)",
+ "issue-review": "- {{title}} (awaiting your approval)",
+ "more": "More open issues need your attention.",
+ "partial": "I could not check every open issue needing your attention.",
+ "summary": "These issues need your attention:",
+ "unavailable": "Unable to load items needing your attention."
+ }
},
"audit-log": {
"advanced-search": {
diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.json
index 94e3ac1a2e..35e061341e 100644
--- a/frontend/src/locales/es-ES.json
+++ b/frontend/src/locales/es-ES.json
@@ -53,11 +53,49 @@
"input-placeholder": "Pregunta algo a la IA...",
"interrupted": "Interrumpido",
"interrupted-retry-hint": "La conversación fue interrumpida. Puede reintentar o enviar un nuevo mensaje.",
+ "landing-starters": {
+ "menu": "Sugerencias",
+ "more": "Más sugerencias",
+ "project-access": "¿Qué debo configurar antes de colaborar en este Proyecto?",
+ "project-collaborate": "¿Cómo invito a compañeros de equipo a este Proyecto?",
+ "project-connect": "¿Cómo conecto una base de datos a este proyecto?",
+ "project-next": "¿Qué puedo hacer a continuación?",
+ "project-open-blockers": "¿Qué necesita mi atención en este Proyecto?",
+ "project-open-recent": "¿Qué cambió recientemente en este Proyecto?",
+ "project-organize": "¿Cómo debo organizar las bases de datos y los entornos de este Proyecto?",
+ "project-propose-change": "¿Cómo propongo un cambio de base de datos?",
+ "project-review": "¿Cómo se revisan los cambios de base de datos en este Proyecto?",
+ "workspace-attention": "¿Qué requiere mi atención?",
+ "workspace-concepts": "Ayúdame a entender Proyectos, Instancias y Bases de datos",
+ "workspace-governance": "¿Cómo gobierna Bytebase los cambios de base de datos?",
+ "workspace-recent": "¿Qué cambió recientemente en este espacio de trabajo?",
+ "workspace-setup-first": "¿Qué debería configurar primero?"
+ },
"minimize": "Minimizar",
"new-chat": "Nuevo chat",
+ "other-chats": "Otros chats",
"pending-choose-hint": "Seleccione una opción arriba",
"pending-confirm-hint": "Confirme o cancele arriba",
"pending-input-hint": "Proporcione la entrada arriba",
+ "project-attention": {
+ "checking": "Comprobando los elementos que necesitan tu atención...",
+ "empty": "No tienes issues abiertos que requieran tu atención en este proyecto.",
+ "issue-created": "- {{title}} (creado por ti)",
+ "issue-review": "- {{title}} (esperando tu aprobación)",
+ "more": "Hay más issues abiertos que requieren tu atención en este proyecto.",
+ "partial": "No se pudieron comprobar todos los issues abiertos que requieren tu atención en este proyecto.",
+ "summary": "Estos issues requieren tu atención en este proyecto:",
+ "unavailable": "No se pueden cargar los elementos que necesitan tu atención en este proyecto."
+ },
+ "recent-activity": {
+ "checking": "Comprobando la actividad reciente...",
+ "empty": "No se registró actividad importante en los últimos 3 días.",
+ "event": "{{actor}} {{action}} {{resource}} a las {{time}}",
+ "more": "Hay más actividad reciente disponible.",
+ "summary": "Actividad reciente de los últimos 3 días:",
+ "unavailable": "No se puede cargar la actividad reciente.",
+ "unknown-time": "una hora desconocida"
+ },
"rename-chat-placeholder": "Ingrese el nombre del chat",
"reply": "Responder",
"result": "Resultado",
@@ -78,7 +116,17 @@
"tool-response-submitted": "Respuesta enviada",
"tool-value": "Valor",
"unarchive-all-chats": "Desarchivar todos los chats",
- "unarchive-chat": "Desarchivar chat"
+ "unarchive-chat": "Desarchivar chat",
+ "workspace-attention": {
+ "checking": "Comprobando los elementos que necesitan tu atención...",
+ "empty": "No tienes issues abiertos que requieran tu atención.",
+ "issue-created": "- {{title}} (creado por ti)",
+ "issue-review": "- {{title}} (esperando tu aprobación)",
+ "more": "Hay más issues abiertos que requieren tu atención.",
+ "partial": "No se pudieron comprobar todos los issues abiertos que requieren tu atención.",
+ "summary": "Estos issues requieren tu atención:",
+ "unavailable": "No se pueden cargar los elementos que necesitan tu atención."
+ }
},
"audit-log": {
"advanced-search": {
diff --git a/frontend/src/locales/ja-JP.json b/frontend/src/locales/ja-JP.json
index c6755ccdb6..86cbe8589a 100644
--- a/frontend/src/locales/ja-JP.json
+++ b/frontend/src/locales/ja-JP.json
@@ -53,11 +53,49 @@
"input-placeholder": "AI に何でも聞いてください...",
"interrupted": "中断",
"interrupted-retry-hint": "会話が中断されました。再試行するか、新しいメッセージを送信できます。",
+ "landing-starters": {
+ "menu": "候補",
+ "more": "候補をさらに表示",
+ "project-access": "このプロジェクトで共同作業を始める前に何を設定すればよいですか?",
+ "project-collaborate": "このプロジェクトにチームメンバーを招待するにはどうすればよいですか?",
+ "project-connect": "このプロジェクトにデータベースを接続するにはどうすればよいですか?",
+ "project-next": "次に何ができますか?",
+ "project-open-blockers": "このプロジェクトで私の対応が必要なことは何ですか?",
+ "project-open-recent": "このプロジェクトで最近何が変わりましたか?",
+ "project-organize": "このプロジェクトのデータベースと環境をどのように整理すればよいですか?",
+ "project-propose-change": "データベース変更を提案するにはどうすればよいですか?",
+ "project-review": "このプロジェクトのデータベース変更はどのようにレビューされますか?",
+ "workspace-attention": "私が確認すべきことは何ですか?",
+ "workspace-concepts": "プロジェクト、インスタンス、データベースについて教えてください",
+ "workspace-governance": "Bytebase はデータベース変更をどのように管理しますか?",
+ "workspace-recent": "このワークスペースで最近何が変わりましたか?",
+ "workspace-setup-first": "最初に何を設定すればよいですか?"
+ },
"minimize": "最小化",
"new-chat": "新しいチャット",
+ "other-chats": "その他のチャット",
"pending-choose-hint": "上のオプションから選択してください",
"pending-confirm-hint": "上で確認またはキャンセルしてください",
"pending-input-hint": "上に入力してください",
+ "project-attention": {
+ "checking": "対応が必要な項目を確認しています...",
+ "empty": "このプロジェクトに対応が必要なオープン issue はありません。",
+ "issue-created": "- {{title}}(自分が作成)",
+ "issue-review": "- {{title}}(承認待ち)",
+ "more": "このプロジェクトに対応が必要なオープン issue がさらにあります。",
+ "partial": "このプロジェクトで対応が必要なすべてのオープン issue を確認できませんでした。",
+ "summary": "このプロジェクトの次の issue はあなたの対応が必要です:",
+ "unavailable": "このプロジェクトで対応が必要な項目を読み込めません。"
+ },
+ "recent-activity": {
+ "checking": "最近のアクティビティを確認しています...",
+ "empty": "過去 3 日間に重要なアクティビティは記録されていません。",
+ "event": "{{time}} に {{actor}} が {{resource}} を {{action}}",
+ "more": "さらに最近のアクティビティがあります。",
+ "summary": "過去 3 日間の最近のアクティビティ:",
+ "unavailable": "最近のアクティビティを読み込めません。",
+ "unknown-time": "不明な時刻"
+ },
"rename-chat-placeholder": "チャット名を入力",
"reply": "返信",
"result": "結果",
@@ -78,7 +116,17 @@
"tool-response-submitted": "回答が送信されました",
"tool-value": "値",
"unarchive-all-chats": "すべてのチャットのアーカイブを解除",
- "unarchive-chat": "アーカイブ解除"
+ "unarchive-chat": "アーカイブ解除",
+ "workspace-attention": {
+ "checking": "対応が必要な項目を確認しています...",
+ "empty": "対応が必要なオープン issue はありません。",
+ "issue-created": "- {{title}}(自分が作成)",
+ "issue-review": "- {{title}}(承認待ち)",
+ "more": "対応が必要なオープン issue がさらにあります。",
+ "partial": "対応が必要なすべてのオープン issue を確認できませんでした。",
+ "summary": "次の issue はあなたの対応が必要です:",
+ "unavailable": "対応が必要な項目を読み込めません。"
+ }
},
"audit-log": {
"advanced-search": {
diff --git a/frontend/src/locales/vi-VN.json b/frontend/src/locales/vi-VN.json
index e5e2ea3a42..01606fdd22 100644
--- a/frontend/src/locales/vi-VN.json
+++ b/frontend/src/locales/vi-VN.json
@@ -53,11 +53,49 @@
"input-placeholder": "Hỏi AI bất cứ điều gì...",
"interrupted": "Bị gián đoạn",
"interrupted-retry-hint": "Cuộc trò chuyện đã bị gián đoạn. Bạn có thể thử lại hoặc gửi tin nhắn mới.",
+ "landing-starters": {
+ "menu": "Gợi ý",
+ "more": "Thêm gợi ý",
+ "project-access": "Tôi nên thiết lập gì trước khi cộng tác trong Dự án này?",
+ "project-collaborate": "Làm cách nào để mời đồng đội vào Dự án này?",
+ "project-connect": "Làm cách nào để kết nối cơ sở dữ liệu với dự án này?",
+ "project-next": "Tôi có thể làm gì tiếp theo?",
+ "project-open-blockers": "Điều gì trong Dự án này cần tôi chú ý?",
+ "project-open-recent": "Gần đây có gì thay đổi trong Dự án này?",
+ "project-organize": "Tôi nên tổ chức cơ sở dữ liệu và môi trường cho Dự án này như thế nào?",
+ "project-propose-change": "Tôi đề xuất thay đổi cơ sở dữ liệu như thế nào?",
+ "project-review": "Các thay đổi cơ sở dữ liệu được xem xét như thế nào trong Dự án này?",
+ "workspace-attention": "Điều gì cần tôi chú ý?",
+ "workspace-concepts": "Giúp tôi hiểu Dự án, Phiên bản và Cơ sở dữ liệu",
+ "workspace-governance": "Bytebase quản trị thay đổi cơ sở dữ liệu như thế nào?",
+ "workspace-recent": "Gần đây có gì thay đổi trong không gian làm việc này?",
+ "workspace-setup-first": "Tôi nên thiết lập gì trước?"
+ },
"minimize": "Thu nhỏ",
"new-chat": "Cuộc trò chuyện mới",
+ "other-chats": "Các cuộc trò chuyện khác",
"pending-choose-hint": "Vui lòng chọn một tùy chọn ở trên",
"pending-confirm-hint": "Vui lòng xác nhận hoặc hủy ở trên",
"pending-input-hint": "Vui lòng cung cấp đầu vào ở trên",
+ "project-attention": {
+ "checking": "Đang kiểm tra các mục cần bạn chú ý...",
+ "empty": "Bạn không có issue mở nào cần chú ý trong dự án này.",
+ "issue-created": "- {{title}} (do bạn tạo)",
+ "issue-review": "- {{title}} (đang chờ bạn phê duyệt)",
+ "more": "Có thêm issue mở cần bạn chú ý trong dự án này.",
+ "partial": "Không thể kiểm tra tất cả issue mở cần bạn chú ý trong dự án này.",
+ "summary": "Các issue này cần bạn chú ý trong dự án này:",
+ "unavailable": "Không thể tải các mục cần bạn chú ý trong dự án này."
+ },
+ "recent-activity": {
+ "checking": "Đang kiểm tra hoạt động gần đây...",
+ "empty": "Không có hoạt động quan trọng nào được ghi nhận trong 3 ngày qua.",
+ "event": "{{actor}} {{action}} {{resource}} lúc {{time}}",
+ "more": "Có thêm hoạt động gần đây.",
+ "summary": "Hoạt động gần đây trong 3 ngày qua:",
+ "unavailable": "Không thể tải hoạt động gần đây.",
+ "unknown-time": "thời gian không xác định"
+ },
"rename-chat-placeholder": "Nhập tên cuộc trò chuyện",
"reply": "Trả lời",
"result": "Kết quả",
@@ -78,7 +116,17 @@
"tool-response-submitted": "Phản hồi đã được gửi",
"tool-value": "Giá trị",
"unarchive-all-chats": "Bỏ lưu trữ tất cả cuộc trò chuyện",
- "unarchive-chat": "Bỏ lưu trữ"
+ "unarchive-chat": "Bỏ lưu trữ",
+ "workspace-attention": {
+ "checking": "Đang kiểm tra các mục cần bạn chú ý...",
+ "empty": "Bạn không có issue mở nào cần chú ý.",
+ "issue-created": "- {{title}} (do bạn tạo)",
+ "issue-review": "- {{title}} (đang chờ bạn phê duyệt)",
+ "more": "Có thêm issue mở cần bạn chú ý.",
+ "partial": "Không thể kiểm tra tất cả issue mở cần bạn chú ý.",
+ "summary": "Các issue này cần bạn chú ý:",
+ "unavailable": "Không thể tải các mục cần bạn chú ý."
+ }
},
"audit-log": {
"advanced-search": {
diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.json
index d837cf9fc9..a3a0a59ed2 100644
--- a/frontend/src/locales/zh-CN.json
+++ b/frontend/src/locales/zh-CN.json
@@ -53,11 +53,49 @@
"input-placeholder": "向 AI 提问...",
"interrupted": "已中断",
"interrupted-retry-hint": "对话已中断。您可以重试或发送新消息。",
+ "landing-starters": {
+ "menu": "建议",
+ "more": "更多建议",
+ "project-access": "在此项目中协作前,我应该设置什么?",
+ "project-collaborate": "如何邀请团队成员加入此项目?",
+ "project-connect": "如何将数据库连接到此项目?",
+ "project-next": "下一步我可以做什么?",
+ "project-open-blockers": "此项目中有哪些事项需要我关注?",
+ "project-open-recent": "这个项目最近有哪些变化?",
+ "project-organize": "我应该如何为这个项目组织数据库和环境?",
+ "project-propose-change": "如何提出数据库变更?",
+ "project-review": "此项目中的数据库变更如何审批?",
+ "workspace-attention": "有哪些事情需要我关注?",
+ "workspace-concepts": "帮我了解项目、实例和数据库",
+ "workspace-governance": "Bytebase 如何治理数据库变更?",
+ "workspace-recent": "这个工作区最近有哪些变化?",
+ "workspace-setup-first": "我应该先设置什么?"
+ },
"minimize": "最小化",
"new-chat": "新对话",
+ "other-chats": "其他对话",
"pending-choose-hint": "请在上方选择一个选项",
"pending-confirm-hint": "请在上方确认或取消",
"pending-input-hint": "请在上方提供输入",
+ "project-attention": {
+ "checking": "正在检查需要你关注的事项...",
+ "empty": "此项目中没有需要你关注的开放 issue。",
+ "issue-created": "- {{title}}(由你创建)",
+ "issue-review": "- {{title}}(等待你的审批)",
+ "more": "此项目中还有更多开放 issue 需要你关注。",
+ "partial": "无法检查此项目中所有需要你关注的开放 issue。",
+ "summary": "此项目中的这些 issue 需要你关注:",
+ "unavailable": "无法加载此项目中需要你关注的事项。"
+ },
+ "recent-activity": {
+ "checking": "正在检查最近活动...",
+ "empty": "过去 3 天内没有记录到重要活动。",
+ "event": "{{actor}} 于 {{time}} {{action}} {{resource}}",
+ "more": "还有更多最近活动。",
+ "summary": "过去 3 天的最近活动:",
+ "unavailable": "无法加载最近活动。",
+ "unknown-time": "未知时间"
+ },
"rename-chat-placeholder": "输入对话名称",
"reply": "回复",
"result": "结果",
@@ -78,7 +116,17 @@
"tool-response-submitted": "已提交回复",
"tool-value": "值",
"unarchive-all-chats": "取消归档所有对话",
- "unarchive-chat": "取消归档"
+ "unarchive-chat": "取消归档",
+ "workspace-attention": {
+ "checking": "正在检查需要你关注的事项...",
+ "empty": "没有需要你关注的开放 issue。",
+ "issue-created": "- {{title}}(由你创建)",
+ "issue-review": "- {{title}}(等待你的审批)",
+ "more": "还有更多开放 issue 需要你关注。",
+ "partial": "无法检查所有需要你关注的开放 issue。",
+ "summary": "这些 issue 需要你关注:",
+ "unavailable": "无法加载需要你关注的事项。"
+ }
},
"audit-log": {
"advanced-search": {
diff --git a/frontend/src/modules/agent/components/AgentChat.test.tsx b/frontend/src/modules/agent/components/AgentChat.test.tsx
index f1a64b828e..48ca0a709e 100644
--- a/frontend/src/modules/agent/components/AgentChat.test.tsx
+++ b/frontend/src/modules/agent/components/AgentChat.test.tsx
@@ -12,6 +12,7 @@ import { createAgentStore, useAgentStore } from "../store/agent";
const mocks = vi.hoisted(() => ({
useTranslation: vi.fn(() => ({
t: (key: string) => key,
+ i18n: { language: "en-US" },
})),
hasWorkspacePermissionV2: vi.fn(() => true),
routerPush: vi.fn(),
@@ -106,6 +107,7 @@ beforeEach(async () => {
mocks.useTranslation.mockReset();
mocks.useTranslation.mockReturnValue({
t: (key: string) => key,
+ i18n: { language: "en-US" },
});
mocks.hasWorkspacePermissionV2.mockReset();
mocks.hasWorkspacePermissionV2.mockReturnValue(true);
@@ -167,6 +169,97 @@ describe("AgentChat", () => {
unmount();
});
+ test("sizes user and assistant message bubbles to their content", () => {
+ useAgentStore.getState().addMessage({
+ role: "user",
+ content: "List databases",
+ });
+ useAgentStore.getState().addMessage({
+ role: "assistant",
+ content: "No databases found.",
+ });
+
+ const { container, render, unmount } = renderIntoContainer(<AgentChat />);
+ render();
+
+ const bubbles = Array.from(container.querySelectorAll("div")).filter(
+ (element) =>
+ element.className.includes("bg-info/10") ||
+ element.className.includes("bg-control-bg px-3 py-2")
+ );
+ expect(bubbles).toHaveLength(2);
+ for (const bubble of bubbles) {
+ const classes = bubble.className.split(/\s+/);
+ expect(classes).toContain("w-fit");
+ expect(classes).toContain("max-w-full");
+ expect(classes).not.toContain("w-full");
+ expect(classes).not.toContain("max-w-[80%]");
+ }
+
+ unmount();
+ });
+
+ test("shows timestamps for user messages and final assistant replies", () => {
+ const userMessage = useAgentStore.getState().addMessage({
+ role: "user",
+ content: "List databases",
+ });
+ useAgentStore.getState().addMessage({
+ role: "assistant",
+ toolCalls: [
+ {
+ id: "call_list_databases",
+ name: "list_databases",
+ arguments: "{}",
+ },
+ ],
+ });
+ const assistantMessage = useAgentStore.getState().addMessage({
+ role: "assistant",
+ content: "You can find databases from the Database section.",
+ });
+
+ const { container, render, unmount } = renderIntoContainer(<AgentChat />);
+ render();
+
+ const timestamps = Array.from(
+ container.querySelectorAll("[data-agent-message-timestamp]")
+ ) as HTMLTimeElement[];
+ expect(timestamps).toHaveLength(2);
+ expect(timestamps.map((timestamp) => timestamp.dateTime)).toEqual([
+ new Date(userMessage.createdTs).toISOString(),
+ new Date(assistantMessage.createdTs).toISOString(),
+ ]);
+ expect(timestamps[1]?.parentElement?.className).not.toContain("gap-y-2");
+ expect(timestamps[1]?.previousElementSibling?.className).toContain(
+ "gap-y-2"
+ );
+ expect(container.querySelector("[data-agent-message-day]")).toBeNull();
+
+ unmount();
+ });
+
+ test("renders a pending starter as one compact status instead of progress cards", () => {
+ const chat = useAgentStore.getState().ensureCurrentChat();
+ useAgentStore.getState().setChatStatus(chat.id, "running");
+ useAgentStore.getState().addMessage({
+ role: "assistant",
+ content: "Checking recent activity...",
+ metadata: { pending: true },
+ });
+
+ const { container, render, unmount } = renderIntoContainer(<AgentChat />);
+ render();
+
+ expect(container.querySelector("[data-agent-pending-message]")?.textContent).toContain(
+ "Checking recent activity..."
+ );
+ expect(container.querySelector("[data-agent-message-timestamp]")).toBeNull();
+ expect(container.textContent).not.toContain("common.loading");
+
+ unmount();
+ });
+
test("renders inline code with wrap-safe styling", () => {
useAgentStore.getState().addMessage({
role: "assistant",
diff --git a/frontend/src/modules/agent/components/AgentChat.tsx b/frontend/src/modules/agent/components/AgentChat.tsx
index 7be7d45f97..15188756a0 100644
--- a/frontend/src/modules/agent/components/AgentChat.tsx
+++ b/frontend/src/modules/agent/components/AgentChat.tsx
@@ -3,6 +3,7 @@ import { useTranslation } from "react-i18next";
import ReactMarkdown from "react-markdown";
import remarkGfm from "remark-gfm";
import { SETTING_ROUTE_WORKSPACE_GENERAL } from "@/app/router/handles";
+import { HumanizeTs } from "@/components/HumanizeTs";
import { RouterLink } from "@/components/RouterLink";
import { Button, buttonVariants } from "@/components/ui/button";
import { Table } from "@/components/ui/table";
@@ -134,107 +135,145 @@ export function AgentChat({ className }: AgentChatProps) {
ref={chatContainerRef}
className={`flex flex-col overflow-y-auto gap-3 p-3 ${className ?? ""}`}
>
- {displayMessages.map((msg) =>
- msg.role === "user" ? (
- <div key={msg.id} className="flex justify-end">
- <div className="max-w-[80%] rounded-sm bg-info/10 px-3 py-2 text-sm">
- {msg.content}
- </div>
- </div>
- ) : (
- <div key={msg.id} className="flex flex-col gap-y-2">
- {msg.content && (
- <div className="max-w-[80%] rounded-sm bg-control-bg px-3 py-2 text-sm">
- <ReactMarkdown
- remarkPlugins={[remarkGfm]}
- components={{
- p: ({ children }) => (
- <p className="my-1 first:mt-0 last:mb-0">{children}</p>
- ),
- pre: ({ children }) => (
- <pre className="my-1 overflow-x-auto rounded-xs bg-control-bg p-2 text-xs">
- {children}
- </pre>
- ),
- code: ({ children }) => (
- <code className="break-all rounded-xs bg-control-bg-hover px-1 text-xs">
- {children}
- </code>
- ),
- ul: ({ children }) => (
- <ul className="my-1 list-disc pl-5">{children}</ul>
- ),
- ol: ({ children }) => (
- <ol className="my-1 list-decimal pl-5">{children}</ol>
- ),
- li: ({ children }) => (
- <li className="my-0.5">{children}</li>
- ),
- h1: ({ children }) => (
- <h1 className="my-1 font-semibold">{children}</h1>
- ),
- h2: ({ children }) => (
- <h2 className="my-1 font-semibold">{children}</h2>
- ),
- h3: ({ children }) => (
- <h3 className="my-1 font-semibold">{children}</h3>
- ),
- a: ({ children, href }) => (
- <a
- className="break-all text-accent underline"
- href={href}
- target="_blank"
- rel="noopener noreferrer"
- >
- {children}
- </a>
- ),
- blockquote: ({ children }) => (
- <blockquote className="my-1 border-l-2 border-control-border pl-2 text-control-light">
- {children}
- </blockquote>
- ),
- table: ({ children }) => (
- <Table className="my-1 border-collapse text-xs">
- {children}
- </Table>
- ),
- th: ({ children }) => (
- <th className="border border-control-border px-2 py-1">
- {children}
- </th>
- ),
- td: ({ children }) => (
- <td className="border border-control-border px-2 py-1">
- {children}
- </td>
- ),
- }}
- >
+ {displayMessages.map((msg) => {
+ const isPending = msg.metadata?.pending === true;
+ const showTimestamp =
+ msg.role === "user" ||
+ (msg.role === "assistant" &&
+ !isPending &&
+ !!msg.content &&
+ !msg.toolCalls?.length);
+ const timestamp = (
+ <time
+ className="mt-1 text-xs text-control-light"
+ dateTime={new Date(msg.createdTs).toISOString()}
+ data-agent-message-timestamp
+ >
+ <HumanizeTs tsMs={msg.createdTs} tooltip={false} />
+ </time>
+ );
+
+ return (
+ <div key={msg.id}>
+ {msg.role === "user" ? (
+ <div className="flex flex-col items-end">
+ <div className="w-fit max-w-full rounded-sm bg-info/10 px-3 py-2 text-sm">
{msg.content}
- </ReactMarkdown>
+ </div>
+ {showTimestamp && timestamp}
+ </div>
+ ) : (
+ <div className="flex flex-col">
+ <div className="flex flex-col gap-y-2">
+ {isPending && msg.content ? (
+ <div
+ className="flex items-center gap-x-2 text-sm text-control-placeholder"
+ data-agent-pending-message
+ >
+ <span className="animate-pulse">&#9679;</span>
+ {msg.content}
+ </div>
+ ) : msg.content ? (
+ <div className="w-fit max-w-full rounded-sm bg-control-bg px-3 py-2 text-sm">
+ <ReactMarkdown
+ remarkPlugins={[remarkGfm]}
+ components={{
+ p: ({ children }) => (
+ <p className="my-1 first:mt-0 last:mb-0">
+ {children}
+ </p>
+ ),
+ pre: ({ children }) => (
+ <pre className="my-1 overflow-x-auto rounded-xs bg-control-bg p-2 text-xs">
+ {children}
+ </pre>
+ ),
+ code: ({ children }) => (
+ <code className="break-all rounded-xs bg-control-bg-hover px-1 text-xs">
+ {children}
+ </code>
+ ),
+ ul: ({ children }) => (
+ <ul className="my-1 list-disc pl-5">{children}</ul>
+ ),
+ ol: ({ children }) => (
+ <ol className="my-1 list-decimal pl-5">
+ {children}
+ </ol>
+ ),
+ li: ({ children }) => (
+ <li className="my-0.5">{children}</li>
+ ),
+ h1: ({ children }) => (
+ <h1 className="my-1 font-semibold">{children}</h1>
+ ),
+ h2: ({ children }) => (
+ <h2 className="my-1 font-semibold">{children}</h2>
+ ),
+ h3: ({ children }) => (
+ <h3 className="my-1 font-semibold">{children}</h3>
+ ),
+ a: ({ children, href }) => (
+ <a
+ className="break-all text-accent underline"
+ href={href}
+ target="_blank"
+ rel="noopener noreferrer"
+ >
+ {children}
+ </a>
+ ),
+ blockquote: ({ children }) => (
+ <blockquote className="my-1 border-l-2 border-control-border pl-2 text-control-light">
+ {children}
+ </blockquote>
+ ),
+ table: ({ children }) => (
+ <Table className="my-1 border-collapse text-xs">
+ {children}
+ </Table>
+ ),
+ th: ({ children }) => (
+ <th className="border border-control-border px-2 py-1">
+ {children}
+ </th>
+ ),
+ td: ({ children }) => (
+ <td className="border border-control-border px-2 py-1">
+ {children}
+ </td>
+ ),
+ }}
+ >
+ {msg.content}
+ </ReactMarkdown>
+ </div>
+ ) : null}
+ {msg.toolCalls?.map((toolCall, index, toolCalls) => (
+ <ToolCallCard
+ key={`${msg.id}:${toolCall.id}:${index}`}
+ toolCall={toolCall}
+ result={getToolResult(
+ msg.id,
+ toolCall.id,
+ getToolCallDuplicateIndex(toolCalls, index)
+ )}
+ />
+ ))}
+ </div>
+ {showTimestamp && timestamp}
</div>
)}
- {msg.toolCalls?.map((toolCall, index, toolCalls) => (
- <ToolCallCard
- key={`${msg.id}:${toolCall.id}:${index}`}
- toolCall={toolCall}
- result={getToolResult(
- msg.id,
- toolCall.id,
- getToolCallDuplicateIndex(toolCalls, index)
- )}
- />
- ))}
</div>
- )
- )}
+ );
+ })}
- {loading && (
- <div className="flex items-center gap-x-2 text-sm text-control-placeholder">
- <span className="animate-pulse">&#9679;</span> {t("common.loading")}
- </div>
- )}
+ {loading &&
+ !displayMessages.some((message) => message.metadata?.pending) && (
+ <div className="flex items-center gap-x-2 text-sm text-control-placeholder">
+ <span className="animate-pulse">&#9679;</span> {t("common.loading")}
+ </div>
+ )}
{showAIConfigurationRecovery ? (
<div className="max-w-[80%] rounded-sm border border-warning/20 bg-warning/10 px-3 py-3 text-sm text-warning">
diff --git a/frontend/src/modules/agent/components/AgentContextPicker.tsx b/frontend/src/modules/agent/components/AgentContextPicker.tsx
index 243a50bbdc..ba237de74d 100644
--- a/frontend/src/modules/agent/components/AgentContextPicker.tsx
+++ b/frontend/src/modules/agent/components/AgentContextPicker.tsx
@@ -6,7 +6,6 @@ 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;
@@ -84,9 +83,6 @@ function ContextOptions({
<span className="block truncate">
{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>
diff --git a/frontend/src/modules/agent/components/AgentInput.test.tsx b/frontend/src/modules/agent/components/AgentInput.test.tsx
index 2f697308a8..0d27d69aa6 100644
--- a/frontend/src/modules/agent/components/AgentInput.test.tsx
+++ b/frontend/src/modules/agent/components/AgentInput.test.tsx
@@ -18,6 +18,7 @@ import { createAgentStore, useAgentStore } from "../store/agent";
const mocks = vi.hoisted(() => ({
useTranslation: vi.fn(() => ({
t: (key: string) => key,
+ i18n: { language: "en-US" },
})),
routerPush: vi.fn(),
lazyExtractDomRefSuggestions: vi.fn<() => Promise<DomRefSuggestion[]>>(
@@ -29,6 +30,9 @@ const mocks = vi.hoisted(() => ({
buildSystemPrompt: vi.fn(() => "system"),
createToolExecutor: vi.fn(() => ({})),
getToolDefinitions: vi.fn(() => []),
+ getRecentActivity: vi.fn(),
+ getWorkspaceAttention: vi.fn(),
+ getProjectAttention: vi.fn(),
getOrFetchSettingByName: vi.fn(),
getOrFetchProjectByName: vi.fn(),
projectsByName: {} as Record<string, { title: string }>,
@@ -140,6 +144,18 @@ vi.mock("../logic/tools", () => ({
getToolDefinitions: mocks.getToolDefinitions,
}));
+vi.mock("../logic/tools/recentActivity", () => ({
+ getRecentActivity: mocks.getRecentActivity,
+}));
+
+vi.mock("../logic/tools/workspaceAttention", () => ({
+ createWorkspaceAttentionTool: vi.fn(() => mocks.getWorkspaceAttention),
+}));
+
+vi.mock("../logic/tools/projectOpenIssues", () => ({
+ createProjectOpenIssuesTool: vi.fn(() => mocks.getProjectAttention),
+}));
+
const renderIntoContainer = (element: ReactElement) => {
const container = document.createElement("div");
document.body.appendChild(container);
@@ -213,6 +229,7 @@ beforeEach(async () => {
mocks.useTranslation.mockReset();
mocks.useTranslation.mockReturnValue({
t: (key: string) => key,
+ i18n: { language: "en-US" },
});
mocks.routerPush.mockReset();
mocks.lazyExtractDomRefSuggestions.mockReset();
@@ -228,6 +245,9 @@ beforeEach(async () => {
mocks.createToolExecutor.mockReturnValue({});
mocks.getToolDefinitions.mockReset();
mocks.getToolDefinitions.mockReturnValue([]);
+ mocks.getRecentActivity.mockReset();
+ mocks.getWorkspaceAttention.mockReset();
+ mocks.getProjectAttention.mockReset();
mocks.getOrFetchSettingByName.mockReset();
mocks.getOrFetchSettingByName.mockResolvedValue(undefined);
mocks.getOrFetchProjectByName.mockReset();
@@ -270,7 +290,12 @@ describe("AgentInput", () => {
const page = { path: "/projects/billing", title: "Billing" };
const store = useAgentStore.getState();
const chat = store.createChat({ context: "projects/billing", page });
- store.queueUserMessage({ chatId: chat.id, text: "List billing databases", page });
+ store.queueUserMessage({
+ chatId: chat.id,
+ text: "List billing databases",
+ page,
+ runMode: "read-only",
+ });
const view = renderIntoContainer(<AgentInput />);
view.render();
@@ -282,12 +307,528 @@ describe("AgentInput", () => {
expect.objectContaining({ role: "user", content: "List billing databases" })
);
expect(mocks.buildSystemPrompt).toHaveBeenCalledWith(
- expect.objectContaining({ context: "projects/billing" })
+ expect.objectContaining({
+ context: "projects/billing",
+ runMode: "read-only",
+ })
+ );
+ expect(mocks.getToolDefinitions).toHaveBeenCalledWith({
+ runMode: "read-only",
+ });
+ expect(mocks.createToolExecutor).toHaveBeenCalledWith(
+ expect.anything(),
+ expect.objectContaining({
+ context: "projects/billing",
+ runMode: "read-only",
+ })
);
expect(useAgentStore.getState().queuedUserMessage).toBeNull();
view.unmount();
});
+ test("runs the workspace recent starter with one direct audit read", async () => {
+ let resolveRecentActivity!: (value: string) => void;
+ mocks.getRecentActivity.mockReturnValue(
+ new Promise<string>((resolve) => {
+ resolveRecentActivity = resolve;
+ })
+ );
+ const page = { path: "/landing", title: "Workspace" };
+ const store = useAgentStore.getState();
+ const chat = store.createChat({ context: "workspaces/demo", page });
+ store.queueUserMessage({
+ chatId: chat.id,
+ text: "What changed recently in this workspace?",
+ page,
+ runMode: "read-only",
+ starterId: "workspace-recent",
+ });
+
+ const view = renderIntoContainer(<AgentInput />);
+ view.render();
+
+ await act(async () => {
+ await vi.waitFor(() =>
+ expect(mocks.getRecentActivity).toHaveBeenCalledWith("projects/-")
+ );
+ });
+ expect(mocks.runAgentLoop).not.toHaveBeenCalled();
+ expect(useAgentStore.getState().getMessages(chat.id)).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ role: "assistant",
+ content: "agent.recent-activity.checking",
+ metadata: expect.objectContaining({ pending: true }),
+ }),
+ ])
+ );
+
+ await act(async () => {
+ resolveRecentActivity(
+ JSON.stringify({
+ events: [
+ {
+ actor: "users/[email protected]",
+ action: "approved an Issue",
+ resource: "projects/orders/issues/42",
+ occurredAt: "2026-10-20T08:00:00.000Z",
+ },
+ ],
+ partial: true,
+ })
+ );
+ });
+ await act(async () => {
+ await vi.waitFor(() =>
+ expect(
+ useAgentStore
+ .getState()
+ .getMessages(chat.id)
+ .some((message) => message.metadata?.pending)
+ ).toBe(false)
+ );
+ });
+
+ expect(useAgentStore.getState().getMessages(chat.id)).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ role: "assistant",
+ content: expect.stringContaining("agent.recent-activity.event"),
+ }),
+ ])
+ );
+ view.unmount();
+ });
+
+ test("runs the project recent starter with one direct project audit read", async () => {
+ mocks.getRecentActivity.mockResolvedValue(
+ JSON.stringify({ events: [], partial: false })
+ );
+ const page = { path: "/projects/orders", title: "Orders" };
+ const store = useAgentStore.getState();
+ const chat = store.createChat({ context: "projects/orders", page });
+ store.queueUserMessage({
+ chatId: chat.id,
+ text: "What changed recently in this project?",
+ page,
+ runMode: "read-only",
+ starterId: "project-open-recent",
+ });
+
+ const view = renderIntoContainer(<AgentInput />);
+ view.render();
+
+ await act(async () => {
+ await vi.waitFor(() =>
+ expect(mocks.getRecentActivity).toHaveBeenCalledWith("projects/orders")
+ );
+ });
+ expect(mocks.runAgentLoop).not.toHaveBeenCalled();
+ view.unmount();
+ });
+
+ test("runs a typed project recent-activity prompt directly in a project chat", async () => {
+ mocks.useTranslation.mockReturnValue({
+ t: (key: string) =>
+ key === "agent.landing-starters.project-open-recent"
+ ? "What changed recently in this project?"
+ : key,
+ i18n: { language: "en-US" },
+ });
+ mocks.getRecentActivity.mockResolvedValue(
+ JSON.stringify({ events: [], partial: false })
+ );
+ const view = renderIntoContainer(<AgentInput />);
+ view.render();
+ const textarea = view.container.querySelector("textarea") as HTMLTextAreaElement;
+
+ await act(async () => {
+ setTextareaValue(textarea, "What changed recently in this project?");
+ textarea.dispatchEvent(new Event("input", { bubbles: true }));
+ });
+ await act(async () => {
+ view.container.querySelector<HTMLButtonElement>("[data-agent-send]")?.click();
+ });
+
+ await vi.waitFor(() =>
+ expect(mocks.getRecentActivity).toHaveBeenCalledWith("projects/orders")
+ );
+ expect(mocks.runAgentLoop).not.toHaveBeenCalled();
+ view.unmount();
+ });
+
+ test("runs a typed workspace recent-activity prompt directly in a workspace chat", async () => {
+ mocks.useTranslation.mockReturnValue({
+ t: (key: string) =>
+ key === "agent.landing-starters.workspace-recent"
+ ? "What changed recently in this workspace?"
+ : key,
+ i18n: { language: "en-US" },
+ });
+ mocks.currentContext = "workspaces/demo";
+ mocks.getRecentActivity.mockResolvedValue(
+ JSON.stringify({ events: [], partial: false })
+ );
+ const view = renderIntoContainer(<AgentInput />);
+ view.render();
+ const textarea = view.container.querySelector("textarea") as HTMLTextAreaElement;
+
+ await act(async () => {
+ setTextareaValue(textarea, "What changed recently in this workspace?");
+ textarea.dispatchEvent(new Event("input", { bubbles: true }));
+ });
+ await act(async () => {
+ view.container.querySelector<HTMLButtonElement>("[data-agent-send]")?.click();
+ });
+
+ await vi.waitFor(() =>
+ expect(mocks.getRecentActivity).toHaveBeenCalledWith("projects/-")
+ );
+ expect(mocks.runAgentLoop).not.toHaveBeenCalled();
+ view.unmount();
+ });
+
+ test("runs a typed workspace attention prompt directly in a workspace chat", async () => {
+ mocks.useTranslation.mockReturnValue({
+ t: (key: string) =>
+ key === "agent.landing-starters.workspace-attention"
+ ? "What needs my attention?"
+ : key,
+ i18n: { language: "en-US" },
+ });
+ mocks.currentContext = "workspaces/demo";
+ mocks.getWorkspaceAttention.mockResolvedValue(
+ JSON.stringify({ issues: [], partial: false })
+ );
+ const view = renderIntoContainer(<AgentInput />);
+ view.render();
+ const textarea = view.container.querySelector("textarea") as HTMLTextAreaElement;
+
+ await act(async () => {
+ setTextareaValue(textarea, "What needs my attention?");
+ textarea.dispatchEvent(new Event("input", { bubbles: true }));
+ });
+ await act(async () => {
+ view.container.querySelector<HTMLButtonElement>("[data-agent-send]")?.click();
+ });
+
+ await vi.waitFor(() =>
+ expect(mocks.getWorkspaceAttention).toHaveBeenCalledOnce()
+ );
+ expect(mocks.runAgentLoop).not.toHaveBeenCalled();
+ view.unmount();
+ });
+
+ test("runs a typed project attention prompt directly in a project chat", async () => {
+ mocks.useTranslation.mockReturnValue({
+ t: (key: string) =>
+ key === "agent.landing-starters.project-open-blockers"
+ ? "What needs my attention in this project?"
+ : key,
+ i18n: { language: "en-US" },
+ });
+ mocks.getProjectAttention.mockResolvedValue(
+ JSON.stringify({ issues: [], partial: false })
+ );
+ const view = renderIntoContainer(<AgentInput />);
+ view.render();
+ const textarea = view.container.querySelector("textarea") as HTMLTextAreaElement;
+
+ await act(async () => {
+ setTextareaValue(textarea, "What needs my attention in this project?");
+ textarea.dispatchEvent(new Event("input", { bubbles: true }));
+ });
+ await act(async () => {
+ view.container.querySelector<HTMLButtonElement>("[data-agent-send]")?.click();
+ });
+
+ await vi.waitFor(() =>
+ expect(mocks.getProjectAttention).toHaveBeenCalledOnce()
+ );
+ expect(mocks.runAgentLoop).not.toHaveBeenCalled();
+ view.unmount();
+ });
+
+ test("finishes the workspace recent starter when its audit read fails", async () => {
+ mocks.getRecentActivity.mockRejectedValue(new Error("network unavailable"));
+ const page = { path: "/landing", title: "Workspace" };
+ const store = useAgentStore.getState();
+ const chat = store.createChat({ context: "workspaces/demo", page });
+ store.queueUserMessage({
+ chatId: chat.id,
+ text: "What changed recently in this workspace?",
+ page,
+ runMode: "read-only",
+ starterId: "workspace-recent",
+ });
+
+ const view = renderIntoContainer(<AgentInput />);
+ view.render();
+
+ await act(async () => {
+ await vi.waitFor(() =>
+ expect(
+ useAgentStore
+ .getState()
+ .getMessages(chat.id)
+ .some(
+ (message) => message.content === "agent.recent-activity.unavailable"
+ )
+ ).toBe(true)
+ );
+ });
+
+ expect(useAgentStore.getState().getMessages(chat.id)).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ role: "assistant",
+ content: "agent.recent-activity.unavailable",
+ }),
+ ])
+ );
+ expect(
+ useAgentStore
+ .getState()
+ .getMessages(chat.id)
+ .some((message) => message.metadata?.pending)
+ ).toBe(false);
+ expect(useAgentStore.getState().getChat(chat.id)?.status).toBe("idle");
+ view.unmount();
+ });
+
+ test("runs the workspace attention starter without an activity lookup", async () => {
+ mocks.getWorkspaceAttention.mockResolvedValue(
+ JSON.stringify({
+ issues: [
+ {
+ name: "projects/orders/issues/42",
+ title: "Add customer table",
+ },
+ ],
+ partial: false,
+ })
+ );
+ const page = { path: "/landing", title: "Workspace" };
+ const store = useAgentStore.getState();
+ const chat = store.createChat({ context: "workspaces/demo", page });
+ store.queueUserMessage({
+ chatId: chat.id,
+ text: "What needs my attention?",
+ page,
+ runMode: "read-only",
+ starterId: "workspace-attention",
+ });
+
+ const view = renderIntoContainer(<AgentInput />);
+ view.render();
+
+ await act(async () => {
+ await vi.waitFor(() =>
+ expect(mocks.getWorkspaceAttention).toHaveBeenCalledOnce()
+ );
+ });
+ expect(mocks.getRecentActivity).not.toHaveBeenCalled();
+ expect(mocks.runAgentLoop).not.toHaveBeenCalled();
+ expect(useAgentStore.getState().getMessages(chat.id)).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ role: "assistant",
+ content: expect.stringContaining("agent.workspace-attention.issue"),
+ }),
+ ])
+ );
+ view.unmount();
+ });
+
+ test("does not call a partial workspace attention result empty", async () => {
+ mocks.getWorkspaceAttention.mockResolvedValue(
+ JSON.stringify({ issues: [], partial: true })
+ );
+ const page = { path: "/landing", title: "Workspace" };
+ const store = useAgentStore.getState();
+ const chat = store.createChat({ context: "workspaces/demo", page });
+ store.queueUserMessage({
+ chatId: chat.id,
+ text: "What needs my attention?",
+ page,
+ runMode: "read-only",
+ starterId: "workspace-attention",
+ });
+
+ const view = renderIntoContainer(<AgentInput />);
+ view.render();
+
+ await act(async () => {
+ await vi.waitFor(() =>
+ expect(
+ useAgentStore
+ .getState()
+ .getMessages(chat.id)
+ .some(
+ (message) =>
+ message.content === "agent.workspace-attention.partial"
+ )
+ ).toBe(true)
+ );
+ });
+
+ view.unmount();
+ });
+
+ test("does not call a partial project attention result empty", async () => {
+ mocks.getProjectAttention.mockResolvedValue(
+ JSON.stringify({ issues: [], partial: true })
+ );
+ const page = { path: "/projects/orders", title: "Orders" };
+ const store = useAgentStore.getState();
+ const chat = store.createChat({ context: "projects/orders", page });
+ store.queueUserMessage({
+ chatId: chat.id,
+ text: "What needs my attention in this project?",
+ page,
+ runMode: "read-only",
+ starterId: "project-open-blockers",
+ });
+
+ const view = renderIntoContainer(<AgentInput />);
+ view.render();
+
+ await act(async () => {
+ await vi.waitFor(() =>
+ expect(
+ useAgentStore
+ .getState()
+ .getMessages(chat.id)
+ .some(
+ (message) => message.content === "agent.project-attention.partial"
+ )
+ ).toBe(true)
+ );
+ });
+
+ view.unmount();
+ });
+
+ test("returns to the default tool mode for a typed follow-up", async () => {
+ mocks.runAgentLoop.mockResolvedValue({ kind: "completed", totalTokensUsed: 0 });
+ const page = { path: "/projects/billing", title: "Billing" };
+ const store = useAgentStore.getState();
+ const chat = store.createChat({ context: "projects/billing", page });
+ store.queueUserMessage({
+ chatId: chat.id,
+ text: "What is this Project ready for?",
+ page,
+ runMode: "read-only",
+ });
+
+ const view = renderIntoContainer(<AgentInput />);
+ view.render();
+ await act(async () => {
+ await vi.waitFor(() => expect(mocks.runAgentLoop).toHaveBeenCalledOnce());
+ });
+
+ const textarea = view.container.querySelector("textarea") as HTMLTextAreaElement;
+ await act(async () => {
+ setTextareaValue(textarea, "Show me the databases");
+ textarea.dispatchEvent(new Event("input", { bubbles: true }));
+ });
+ await act(async () => {
+ (view.container.querySelector("[data-agent-send]") as HTMLButtonElement).click();
+ await vi.waitFor(() => expect(mocks.runAgentLoop).toHaveBeenCalledTimes(2));
+ });
+
+ expect(mocks.buildSystemPrompt).toHaveBeenLastCalledWith(
+ expect.objectContaining({ runMode: "default" })
+ );
+ expect(mocks.getToolDefinitions).toHaveBeenLastCalledWith({
+ runMode: "default",
+ });
+ expect(mocks.createToolExecutor).toHaveBeenLastCalledWith(
+ expect.anything(),
+ expect.objectContaining({ runMode: "default" })
+ );
+ view.unmount();
+ });
+
+ test("keeps a read-only starter read-only after answering a pending question", async () => {
+ mocks.runAgentLoop
+ .mockResolvedValueOnce({
+ kind: "awaiting_user",
+ ask: {
+ toolCallId: "ask-1",
+ prompt: "Which database?",
+ kind: "input",
+ },
+ })
+ .mockResolvedValueOnce({ kind: "completed", totalTokensUsed: 0 });
+ const page = { path: "/projects/billing", title: "Billing" };
+ const store = useAgentStore.getState();
+ const chat = store.createChat({ context: "projects/billing", page });
+ store.queueUserMessage({
+ chatId: chat.id,
+ text: "What should I review?",
+ page,
+ runMode: "read-only",
+ });
+
+ const view = renderIntoContainer(<AgentInput />);
+ view.render();
+ await act(async () => {
+ await vi.waitFor(() =>
+ expect(useAgentStore.getState().getChat(chat.id)?.status).toBe(
+ "awaiting_user"
+ )
+ );
+ });
+
+ const textarea = view.container.querySelector("textarea") as HTMLTextAreaElement;
+ await act(async () => {
+ setTextareaValue(textarea, "Billing database");
+ textarea.dispatchEvent(new Event("input", { bubbles: true }));
+ (view.container.querySelector("[data-agent-send]") as HTMLButtonElement).click();
+ await vi.waitFor(() => expect(mocks.runAgentLoop).toHaveBeenCalledTimes(2));
+ });
+
+ expect(mocks.getToolDefinitions).toHaveBeenLastCalledWith({
+ runMode: "read-only",
+ });
+ view.unmount();
+ });
+
+ test("keeps a read-only starter read-only when retrying an interrupted run", async () => {
+ mocks.runAgentLoop
+ .mockResolvedValueOnce({ kind: "aborted" })
+ .mockResolvedValueOnce({ kind: "completed", totalTokensUsed: 0 });
+ const page = { path: "/projects/billing", title: "Billing" };
+ const store = useAgentStore.getState();
+ const chat = store.createChat({ context: "projects/billing", page });
+ store.queueUserMessage({
+ chatId: chat.id,
+ text: "What should I review?",
+ page,
+ runMode: "read-only",
+ });
+
+ const view = renderIntoContainer(<AgentInput />);
+ view.render();
+ await act(async () => {
+ await vi.waitFor(() =>
+ expect(useAgentStore.getState().getChat(chat.id)?.interrupted).toBe(true)
+ );
+ });
+ await act(async () => {
+ [...view.container.querySelectorAll("button")]
+ .find((button) => button.textContent === "agent.retry-last-chat-turn")
+ ?.click();
+ await vi.waitFor(() => expect(mocks.runAgentLoop).toHaveBeenCalledTimes(2));
+ });
+
+ expect(mocks.getToolDefinitions).toHaveBeenLastCalledWith({
+ runMode: "read-only",
+ });
+ view.unmount();
+ });
+
test("keeps the queued message busy while AI configuration loads", async () => {
let resolveSetting!: (value: undefined) => void;
mocks.getOrFetchSettingByName.mockReturnValue(
@@ -514,7 +1055,7 @@ describe("AgentInput", () => {
unmount();
});
- test("shows resource IDs for every project in the context picker", async () => {
+ test("shows project titles without resource IDs in the context picker", async () => {
mocks.availableProjects = [
{ name: "projects/billing-a", title: "Billing" },
{ name: "projects/billing-b", title: "Billing" },
@@ -532,15 +1073,15 @@ describe("AgentInput", () => {
expect(
document.querySelector('[data-agent-context-option="projects/billing-a"]')
?.textContent
- ).toContain("billing-a");
+ ).toBe("Billing");
expect(
document.querySelector('[data-agent-context-option="projects/billing-b"]')
?.textContent
- ).toContain("billing-b");
+ ).toBe("Billing");
expect(
document.querySelector('[data-agent-context-option="projects/orders"]')
?.textContent
- ).toContain("orders");
+ ).toBe("Orders");
unmount();
});
@@ -641,6 +1182,7 @@ describe("AgentInput", () => {
key === "agent.chat-total-tokens"
? `Tokens used: ${values?.count ?? ""}`
: key,
+ i18n: { language: "en-US" },
});
const { container, render, unmount } = renderIntoContainer(<AgentInput />);
@@ -677,6 +1219,7 @@ describe("AgentInput", () => {
key === "agent.chat-total-tokens"
? `Tokens used: ${values?.count ?? ""}`
: key,
+ i18n: { language: "en-US" },
});
const { container, render, unmount } = renderIntoContainer(<AgentInput />);
diff --git a/frontend/src/modules/agent/components/AgentInput.tsx b/frontend/src/modules/agent/components/AgentInput.tsx
index 889336514a..5ed798a636 100644
--- a/frontend/src/modules/agent/components/AgentInput.tsx
+++ b/frontend/src/modules/agent/components/AgentInput.tsx
@@ -14,7 +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 { projectNamePrefix, workspaceNamePrefix } from "@/lib/resourceName";
import { useAppStore } from "@/stores/app";
import { Setting_SettingName } from "@/types/proto-es/v1/setting_service_pb";
import type { DomRefSuggestion } from "../dom";
@@ -25,10 +25,14 @@ import {
isAgentAIConfigurationError,
} from "../logic/aiConfiguration";
import { getCurrentChatContext } from "../logic/chatContext";
+import type { LandingStarterId } from "../logic/landingStarters";
import { buildOutboundHistory } from "../logic/outboundHistory";
import { buildSystemPrompt } from "../logic/prompt";
import { createToolExecutor, getToolDefinitions } from "../logic/tools";
-import type { AgentAskUserOption, Message } from "../logic/types";
+import { createProjectOpenIssuesTool } from "../logic/tools/projectOpenIssues";
+import { getRecentActivity } from "../logic/tools/recentActivity";
+import { createWorkspaceAttentionTool } from "../logic/tools/workspaceAttention";
+import type { AgentAskUserOption, AgentRunMode, Message } from "../logic/types";
import {
selectCurrentChat,
selectCurrentChatRequiresAIConfiguration,
@@ -102,6 +106,98 @@ const buildMentionListStyle = (rect: DOMRect): CSSProperties => ({
const getMentionListStyleKey = (rect: DOMRect) =>
`${rect.left}:${rect.top}:${rect.width}`;
+interface RecentActivityEvent {
+ actor: string;
+ action: string;
+ resource: string;
+ occurredAt?: string;
+}
+
+interface RecentActivityResult {
+ events: RecentActivityEvent[];
+ partial: boolean;
+ error?: string;
+}
+
+interface AttentionResult {
+ issues: {
+ name: string;
+ title: string;
+ relation: "review" | "created";
+ }[];
+ partial: boolean;
+ error?: string;
+}
+
+const parseRecentActivityResult = (value: string): RecentActivityResult => {
+ try {
+ const parsed = JSON.parse(value) as Record<string, unknown>;
+ if (typeof parsed.error === "string") {
+ return { events: [], partial: false, error: parsed.error };
+ }
+ const events = Array.isArray(parsed.events)
+ ? parsed.events.flatMap((event) => {
+ if (
+ typeof event !== "object" ||
+ event === null ||
+ typeof event.actor !== "string" ||
+ typeof event.action !== "string" ||
+ typeof event.resource !== "string"
+ ) {
+ return [];
+ }
+ return [
+ {
+ actor: event.actor,
+ action: event.action,
+ resource: event.resource,
+ ...(typeof event.occurredAt === "string"
+ ? { occurredAt: event.occurredAt }
+ : {}),
+ },
+ ];
+ })
+ : [];
+ return { events, partial: parsed.partial === true };
+ } catch {
+ return { events: [], partial: false, error: "invalid result" };
+ }
+};
+
+const parseAttentionResult = (value: string): AttentionResult => {
+ try {
+ const parsed = JSON.parse(value) as Record<string, unknown>;
+ if (typeof parsed.error === "string") {
+ return { issues: [], partial: false, error: parsed.error };
+ }
+ const issues = Array.isArray(parsed.issues)
+ ? parsed.issues.flatMap((issue) => {
+ if (
+ typeof issue !== "object" ||
+ issue === null ||
+ typeof issue.name !== "string" ||
+ typeof issue.title !== "string"
+ ) {
+ return [];
+ }
+ return [
+ {
+ name: issue.name,
+ title: issue.title,
+ relation:
+ issue.relation === "created"
+ ? ("created" as const)
+ : ("review" as const),
+ },
+ ];
+ })
+ : [];
+ return { issues, partial: parsed.partial === true };
+ } catch {
+ return { issues: [], partial: false, error: "invalid result" };
+ }
+};
+
// ---------------------------------------------------------------------------
// Component
// ---------------------------------------------------------------------------
@@ -113,7 +209,7 @@ interface DomRefMentionOption {
}
export function AgentInput() {
- const { t } = useTranslation();
+ const { t, i18n } = useTranslation();
// Zustand selectors
const currentChat = useAgentStore(selectCurrentChat);
const currentPendingAsk = useAgentStore(selectCurrentPendingAsk);
@@ -138,6 +234,97 @@ export function AgentInput() {
getAgentAIConfigurationEnabled(s.getSettingByName(Setting_SettingName.AI))
);
+ const formatRecentActivity = useCallback(
+ (result: string) => {
+ const payload = parseRecentActivityResult(result);
+ if (payload.error) {
+ return t("agent.recent-activity.unavailable");
+ }
+ if (payload.events.length === 0) {
+ return t("agent.recent-activity.empty");
+ }
+
+ const formatTime = (value: string | undefined) => {
+ if (!value) return t("agent.recent-activity.unknown-time");
+ const timestamp = Date.parse(value);
+ if (Number.isNaN(timestamp)) {
+ return t("agent.recent-activity.unknown-time");
+ }
+ return new Intl.DateTimeFormat(i18n.language, {
+ month: "short",
+ day: "numeric",
+ hour: "numeric",
+ minute: "2-digit",
+ }).format(timestamp);
+ };
+
+ return [
+ t("agent.recent-activity.summary"),
+ ...payload.events.map(
+ (event) =>
+ `- ${t("agent.recent-activity.event", {
+ actor: event.actor,
+ action: event.action,
+ resource: event.resource,
+ time: formatTime(event.occurredAt),
+ })}`
+ ),
+ ...(payload.partial ? [t("agent.recent-activity.more")] : []),
+ ].join("\n");
+ },
+ [i18n.language, t]
+ );
+
+ const formatWorkspaceAttention = useCallback(
+ (result: string) => {
+ const payload = parseAttentionResult(result);
+ if (payload.error) {
+ return t("agent.workspace-attention.unavailable");
+ }
+ if (payload.issues.length === 0 && payload.partial) {
+ return t("agent.workspace-attention.partial");
+ }
+ if (payload.issues.length === 0) {
+ return t("agent.workspace-attention.empty");
+ }
+ return [
+ t("agent.workspace-attention.summary"),
+ ...payload.issues.map((issue) =>
+ t(`agent.workspace-attention.issue-${issue.relation}`, {
+ title: issue.title,
+ })
+ ),
+ ...(payload.partial ? [t("agent.workspace-attention.more")] : []),
+ ].join("\n");
+ },
+ [t]
+ );
+
+ const formatProjectAttention = useCallback(
+ (result: string) => {
+ const payload = parseAttentionResult(result);
+ if (payload.error) {
+ return t("agent.project-attention.unavailable");
+ }
+ if (payload.issues.length === 0 && payload.partial) {
+ return t("agent.project-attention.partial");
+ }
+ if (payload.issues.length === 0) {
+ return t("agent.project-attention.empty");
+ }
+ return [
+ t("agent.project-attention.summary"),
+ ...payload.issues.map((issue) =>
+ t(`agent.project-attention.issue-${issue.relation}`, {
+ title: issue.title,
+ })
+ ),
+ ...(payload.partial ? [t("agent.project-attention.more")] : []),
+ ].join("\n");
+ },
+ [t]
+ );
+
// Local state
const [input, setInput] = useState("");
const [selectionStart, setSelectionStart] = useState(0);
@@ -192,13 +379,20 @@ export function AgentInput() {
? workspace?.title || context
: context;
- const selectContext = useCallback((resource: string) => {
- return Boolean(
- useAgentStore
- .getState()
- .selectChatContext(resource, getCurrentPageSnapshot())
- );
- }, []);
+ const selectContext = useCallback(
+ (resource: string) => {
+ return Boolean(
+ useAgentStore
+ .getState()
+ .selectChatContext(
+ resource,
+ getCurrentPageSnapshot(),
+ workspace?.name
+ )
+ );
+ },
+ [workspace?.name]
+ );
useEffect(() => {
if (projectContext && !contextProject) {
@@ -489,7 +683,8 @@ export function AgentInput() {
async (
chatId: string,
page: { path: string; title: string },
- runId: string
+ runId: string,
+ runMode: AgentRunMode
) => {
const store = useAgentStore.getState();
const controller = new AbortController();
@@ -500,10 +695,13 @@ export function AgentInput() {
const systemPrompt = buildSystemPrompt({
...page,
context: store.getChat(chatId)?.context,
+ runMode,
});
- const tools = getToolDefinitions();
+ const tools = getToolDefinitions({ runMode });
const executor = createToolExecutor(router, {
chatId,
+ context: store.getChat(chatId)?.context,
+ runMode,
onNavigate: () => {
useAgentStore
.getState()
@@ -546,7 +744,8 @@ export function AgentInput() {
});
},
},
- controller.signal
+ controller.signal,
+ { allowPlainTextCompletion: runMode === "read-only" }
);
useAgentStore
@@ -567,15 +766,224 @@ export function AgentInput() {
[buildChatHistory, handleOutcome]
);
+ const runRecentActivityStarter = useCallback(
+ async (
+ chatId: string,
+ page: { path: string; title: string },
+ runId: string,
+ parent: string
+ ) => {
+ const store = useAgentStore.getState();
+ const controller = new AbortController();
+ const runToken = (runTokens.get(chatId) ?? 0) + 1;
+ runTokens.set(chatId, runToken);
+ store.setAbortController(chatId, controller);
+ store.addMessage({
+ chatId,
+ role: "assistant",
+ content: t("agent.recent-activity.checking"),
+ metadata: { route: page.path, runId, pending: true },
+ });
+
+ try {
+ const result = await getRecentActivity(parent);
+ if (controller.signal.aborted || runToken !== runTokens.get(chatId)) {
+ store.removeMessagesByRunId(chatId, runId);
+ return;
+ }
+ store.removeMessagesByRunId(chatId, runId);
+ store.addMessage({
+ chatId,
+ role: "assistant",
+ content: formatRecentActivity(result),
+ metadata: { route: page.path, runId },
+ });
+ store.finishChatRun(chatId);
+ } catch {
+ if (controller.signal.aborted || runToken !== runTokens.get(chatId)) {
+ store.removeMessagesByRunId(chatId, runId);
+ return;
+ }
+ store.removeMessagesByRunId(chatId, runId);
+ store.addMessage({
+ chatId,
+ role: "assistant",
+ content: t("agent.recent-activity.unavailable"),
+ metadata: { route: page.path, runId },
+ });
+ store.finishChatRun(chatId);
+ } finally {
+ if (store.getAbortController(chatId) === controller) {
+ store.setAbortController(chatId, null);
+ }
+ }
+ },
+ [formatRecentActivity, t]
+ );
+
+ const runWorkspaceAttentionStarter = useCallback(
+ async (
+ chatId: string,
+ page: { path: string; title: string },
+ runId: string
+ ) => {
+ const store = useAgentStore.getState();
+ const controller = new AbortController();
+ const runToken = (runTokens.get(chatId) ?? 0) + 1;
+ runTokens.set(chatId, runToken);
+ store.setAbortController(chatId, controller);
+ store.addMessage({
+ chatId,
+ role: "assistant",
+ content: t("agent.workspace-attention.checking"),
+ metadata: { route: page.path, runId, pending: true },
+ });
+
+ try {
+ const result = await createWorkspaceAttentionTool({
+ workspaceName: store.getChat(chatId)?.context,
+ })();
+ if (controller.signal.aborted || runToken !== runTokens.get(chatId)) {
+ store.removeMessagesByRunId(chatId, runId);
+ return;
+ }
+ store.removeMessagesByRunId(chatId, runId);
+ store.addMessage({
+ chatId,
+ role: "assistant",
+ content: formatWorkspaceAttention(result),
+ metadata: { route: page.path, runId },
+ });
+ store.finishChatRun(chatId);
+ } catch {
+ if (controller.signal.aborted || runToken !== runTokens.get(chatId)) {
+ store.removeMessagesByRunId(chatId, runId);
+ return;
+ }
+ store.removeMessagesByRunId(chatId, runId);
+ store.addMessage({
+ chatId,
+ role: "assistant",
+ content: t("agent.workspace-attention.unavailable"),
+ metadata: { route: page.path, runId },
+ });
+ store.finishChatRun(chatId);
+ } finally {
+ if (store.getAbortController(chatId) === controller) {
+ store.setAbortController(chatId, null);
+ }
+ }
+ },
+ [formatWorkspaceAttention, t]
+ );
+
+ const runProjectAttentionStarter = useCallback(
+ async (
+ chatId: string,
+ page: { path: string; title: string },
+ runId: string
+ ) => {
+ const store = useAgentStore.getState();
+ const controller = new AbortController();
+ const runToken = (runTokens.get(chatId) ?? 0) + 1;
+ runTokens.set(chatId, runToken);
+ store.setAbortController(chatId, controller);
+ store.addMessage({
+ chatId,
+ role: "assistant",
+ content: t("agent.project-attention.checking"),
+ metadata: { route: page.path, runId, pending: true },
+ });
+
+ try {
+ const result = await createProjectOpenIssuesTool({
+ projectName: store.getChat(chatId)?.context,
+ })();
+ if (controller.signal.aborted || runToken !== runTokens.get(chatId)) {
+ store.removeMessagesByRunId(chatId, runId);
+ return;
+ }
+ store.removeMessagesByRunId(chatId, runId);
+ store.addMessage({
+ chatId,
+ role: "assistant",
+ content: formatProjectAttention(result),
+ metadata: { route: page.path, runId },
+ });
+ store.finishChatRun(chatId);
+ } catch {
+ if (controller.signal.aborted || runToken !== runTokens.get(chatId)) {
+ store.removeMessagesByRunId(chatId, runId);
+ return;
+ }
+ store.removeMessagesByRunId(chatId, runId);
+ store.addMessage({
+ chatId,
+ role: "assistant",
+ content: t("agent.project-attention.unavailable"),
+ metadata: { route: page.path, runId },
+ });
+ store.finishChatRun(chatId);
+ } finally {
+ if (store.getAbortController(chatId) === controller) {
+ store.setAbortController(chatId, null);
+ }
+ }
+ },
+ [formatProjectAttention, t]
+ );
+
const startChatRun = useCallback(
- async (chatId: string, currentPage: { path: string; title: string }) => {
+ async (
+ chatId: string,
+ currentPage: { path: string; title: string },
+ runMode: AgentRunMode = "default",
+ starterId?: LandingStarterId
+ ) => {
const runId = uuidv4();
const store = useAgentStore.getState();
store.updateChatPage(chatId, currentPage);
- store.startChatRun(chatId, currentPage, { runId });
- await runChat(chatId, currentPage, runId);
+ store.startChatRun(chatId, currentPage, { runId, runMode });
+ if (starterId === "workspace-recent") {
+ await runRecentActivityStarter(
+ chatId,
+ currentPage,
+ runId,
+ "projects/-"
+ );
+ return;
+ }
+ if (starterId === "project-open-recent") {
+ const projectName = store.getChat(chatId)?.context;
+ if (projectName?.startsWith(projectNamePrefix)) {
+ await runRecentActivityStarter(
+ chatId,
+ currentPage,
+ runId,
+ projectName
+ );
+ return;
+ }
+ }
+ if (starterId === "workspace-attention") {
+ await runWorkspaceAttentionStarter(chatId, currentPage, runId);
+ return;
+ }
+ if (starterId === "project-open-blockers") {
+ const projectName = store.getChat(chatId)?.context;
+ if (projectName?.startsWith(projectNamePrefix)) {
+ await runProjectAttentionStarter(chatId, currentPage, runId);
+ return;
+ }
+ }
+ await runChat(chatId, currentPage, runId, runMode);
},
- [runChat]
+ [
+ runChat,
+ runProjectAttentionStarter,
+ runRecentActivityStarter,
+ runWorkspaceAttentionStarter,
+ ]
);
useEffect(() => {
@@ -597,7 +1005,12 @@ export function AgentInput() {
content: message.text,
metadata: { route: message.page.path },
});
- await startChatRun(message.chatId, message.page);
+ await startChatRun(
+ message.chatId,
+ message.page,
+ message.runMode ?? "default",
+ message.starterId
+ );
} finally {
store.finishQueuedUserMessage(message.chatId);
}
@@ -617,7 +1030,8 @@ export function AgentInput() {
const currentPage = getCurrentPageSnapshot();
const thread = store.ensureCurrentChat(
currentPage,
- getCurrentChatContext()
+ getCurrentChatContext(),
+ workspace?.name
);
const chatId = thread.id;
if (await blockWhenAIIsNotConfigured(chatId)) return;
@@ -644,7 +1058,11 @@ export function AgentInput() {
} else {
return;
}
- await startChatRun(chatId, currentPage);
+ await startChatRun(
+ chatId,
+ currentPage,
+ store.getChat(chatId)?.runMode ?? "default"
+ );
return;
}
@@ -657,8 +1075,22 @@ export function AgentInput() {
content: text,
metadata: { route: currentPage.path },
});
- await startChatRun(chatId, currentPage);
- }, [blockWhenAIIsNotConfigured, input, startChatRun]);
+ const starterId =
+ thread.context?.startsWith(workspaceNamePrefix) &&
+ text === t("agent.landing-starters.workspace-recent")
+ ? "workspace-recent"
+ : thread.context?.startsWith(workspaceNamePrefix) &&
+ text === t("agent.landing-starters.workspace-attention")
+ ? "workspace-attention"
+ : thread.context?.startsWith(projectNamePrefix) &&
+ text === t("agent.landing-starters.project-open-recent")
+ ? "project-open-recent"
+ : thread.context?.startsWith(projectNamePrefix) &&
+ text === t("agent.landing-starters.project-open-blockers")
+ ? "project-open-blockers"
+ : undefined;
+ await startChatRun(chatId, currentPage, "default", starterId);
+ }, [blockWhenAIIsNotConfigured, input, startChatRun, t, workspace?.name]);
const retryLastTurn = useCallback(async () => {
const store = useAgentStore.getState();
@@ -670,7 +1102,7 @@ export function AgentInput() {
if (await blockWhenAIIsNotConfigured(chatId)) return;
store.removeMessagesByRunId(chatId, chat.runId);
store.clearError(chatId);
- await startChatRun(chatId, currentPage);
+ await startChatRun(chatId, currentPage, chat.runMode ?? "default");
}, [blockWhenAIIsNotConfigured, startChatRun]);
const dismissInterrupted = useCallback(() => {
@@ -706,7 +1138,11 @@ export function AgentInput() {
{ kind: "confirm", answer, confirmed },
{ route: currentPage.path }
);
- await startChatRun(chatId, currentPage);
+ await startChatRun(
+ chatId,
+ currentPage,
+ store.getChat(chatId)?.runMode ?? "default"
+ );
},
[blockWhenAIIsNotConfigured, confirmLabel, cancelLabel, startChatRun]
);
@@ -735,7 +1171,11 @@ export function AgentInput() {
{ kind: "choose", answer: option.label, value: option.value },
{ route: currentPage.path }
);
- await startChatRun(chatId, currentPage);
+ await startChatRun(
+ chatId,
+ currentPage,
+ store.getChat(chatId)?.runMode ?? "default"
+ );
},
[blockWhenAIIsNotConfigured, startChatRun]
);
diff --git a/frontend/src/modules/agent/components/AgentWindow.test.tsx b/frontend/src/modules/agent/components/AgentWindow.test.tsx
index 2ceb0df9ac..9ed8355083 100644
--- a/frontend/src/modules/agent/components/AgentWindow.test.tsx
+++ b/frontend/src/modules/agent/components/AgentWindow.test.tsx
@@ -15,7 +15,14 @@ const mocks = vi.hoisted(() => ({
i18n: { language: "en-US" },
})),
getOrFetchSettingByName: vi.fn(),
+ batchFetchProjects: vi.fn(),
+ projectErrorsByName: {} as Record<string, Error | undefined>,
currentContext: "projects/orders" as string | undefined,
+ projectsByName: {
+ "projects/orders": { title: "Order service" },
+ "projects/analytics": { title: "Analytics" },
+ } as Record<string, { title: string }>,
+ workspace: { name: "workspaces/acme", title: "Acme workspace" },
}));
function createMockStorage(): Storage {
@@ -50,6 +57,16 @@ vi.mock("react-i18next", () => ({
vi.mock("@/stores/app", () => {
const state = {
getOrFetchSettingByName: mocks.getOrFetchSettingByName,
+ batchFetchProjects: mocks.batchFetchProjects,
+ get projectsByName() {
+ return mocks.projectsByName;
+ },
+ get projectErrorsByName() {
+ return mocks.projectErrorsByName;
+ },
+ get workspace() {
+ return mocks.workspace;
+ },
};
const useAppStore = <T,>(selector: (value: typeof state) => T) =>
selector(state);
@@ -122,12 +139,14 @@ beforeEach(async () => {
size: initialState.size,
sidebarWidth: initialState.sidebarWidth,
minimized: initialState.minimized,
+ workspaceName: initialState.workspaceName,
chats: initialState.chats,
messagesByChatId: initialState.messagesByChatId,
pendingAskByChatId: initialState.pendingAskByChatId,
currentChatId: initialState.currentChatId,
abortControllersByChatId: {},
});
+ useAgentStore.getState().setWorkspaceName(mocks.workspace.name);
useAgentStore.setState({
visible: true,
minimized: false,
@@ -143,6 +162,13 @@ beforeEach(async () => {
});
mocks.getOrFetchSettingByName.mockReset();
mocks.getOrFetchSettingByName.mockResolvedValue(undefined);
+ mocks.batchFetchProjects.mockReset();
+ mocks.batchFetchProjects.mockResolvedValue([]);
+ mocks.projectsByName = {
+ "projects/orders": { title: "Order service" },
+ "projects/analytics": { title: "Analytics" },
+ };
+ mocks.projectErrorsByName = {};
mocks.currentContext = "projects/orders";
({ AgentWindow } = await import("./AgentWindow"));
@@ -185,6 +211,154 @@ describe("AgentWindow", () => {
unmount();
});
+ test("keeps context groups in a stable workspace-first order", () => {
+ const store = useAgentStore.getState();
+ const legacyChat = store.createChat({
+ title: "Legacy chat",
+ select: false,
+ });
+ const workspaceChat = store.createChat({
+ title: "List databases",
+ context: "workspaces/acme",
+ select: false,
+ });
+ const analyticsChat = store.createChat({
+ title: "Investigate analytics",
+ context: "projects/analytics",
+ select: false,
+ });
+ useAgentStore.setState((state) => ({
+ chats: state.chats.map((chat) => {
+ if (chat.id === legacyChat.id) return { ...chat, updatedTs: 4_000 };
+ if (chat.id === analyticsChat.id) return { ...chat, updatedTs: 3_000 };
+ if (chat.id === workspaceChat.id) return { ...chat, updatedTs: 2_000 };
+ return { ...chat, updatedTs: 1_000 };
+ }),
+ }));
+
+ const { render, unmount } = renderIntoContainer(<AgentWindow />);
+ render();
+
+ const groups = Array.from(
+ document.body.querySelectorAll("[data-agent-chat-group]")
+ ) as HTMLDivElement[];
+ expect(groups.map((group) => group.dataset.agentChatGroup)).toEqual([
+ "workspaces/acme",
+ "projects/orders",
+ "projects/analytics",
+ "unscoped",
+ ]);
+ expect(groups[0]?.textContent).toContain("Acme workspace");
+ expect(groups[1]?.textContent).toContain("Order service");
+ expect(groups[2]?.textContent).toContain("Analytics");
+ expect(groups[3]?.textContent).toContain("agent.other-chats");
+ expect(groups[3]?.textContent).toContain("Legacy chat");
+ expect(
+ document.body.querySelector("[data-agent-chat-updated-ts]")
+ ).toBeNull();
+
+ unmount();
+ });
+
+ test("creates a new chat in the selected context group", async () => {
+ const store = useAgentStore.getState();
+ store.createChat({
+ title: "Workspace chat",
+ context: "workspaces/acme",
+ select: false,
+ });
+ store.createChat({
+ title: "Analytics chat",
+ context: "projects/analytics",
+ select: false,
+ });
+
+ const { render, unmount } = renderIntoContainer(<AgentWindow />);
+ render();
+
+ const workspaceButton = document.body.querySelector(
+ '[data-agent-new-chat-for-context="workspaces/acme"]'
+ ) as HTMLButtonElement | null;
+ expect(workspaceButton).toBeInstanceOf(HTMLButtonElement);
+ await act(async () => workspaceButton?.click());
+
+ const workspaceChatId = useAgentStore.getState().currentChatId!;
+ expect(useAgentStore.getState().getChat(workspaceChatId)?.context).toBe(
+ "workspaces/acme"
+ );
+ expect(useAgentStore.getState().getMessages(workspaceChatId)).toEqual([]);
+
+ const projectButton = document.body.querySelector(
+ '[data-agent-new-chat-for-context="projects/analytics"]'
+ ) as HTMLButtonElement | null;
+ expect(projectButton).toBeInstanceOf(HTMLButtonElement);
+ await act(async () => projectButton?.click());
+
+ const projectChatId = useAgentStore.getState().currentChatId!;
+ expect(useAgentStore.getState().getChat(projectChatId)?.context).toBe(
+ "projects/analytics"
+ );
+ expect(useAgentStore.getState().getMessages(projectChatId)).toEqual([]);
+ expect(
+ document.body.querySelector('[data-agent-new-chat-for-context="unscoped"]')
+ ).toBeNull();
+
+ unmount();
+ });
+
+ test("hydrates uncached project chat contexts before rendering their labels", async () => {
+ mocks.projectsByName = {};
+ mocks.batchFetchProjects.mockImplementation(async () => {
+ mocks.projectsByName = {
+ "projects/new-project-8i6r": { title: "New project" },
+ };
+ return [];
+ });
+ useAgentStore.getState().createChat({
+ title: "Set up collaboration",
+ context: "projects/new-project-8i6r",
+ select: false,
+ });
+
+ const { render, unmount } = renderIntoContainer(<AgentWindow />);
+ render();
+
+ await act(async () => {
+ await vi.waitFor(() =>
+ expect(mocks.batchFetchProjects).toHaveBeenCalledWith(
+ ["projects/new-project-8i6r"],
+ true
+ )
+ );
+ });
+ render();
+ expect(document.body.textContent).toContain("New project");
+ unmount();
+ });
+
+ test("keeps the project resource id when an old chat's project is unavailable", async () => {
+ mocks.projectsByName = {};
+ useAgentStore.getState().createChat({
+ title: "Set up collaboration",
+ context: "projects/deleted-project",
+ select: false,
+ });
+
+ const { render, unmount } = renderIntoContainer(<AgentWindow />);
+ render();
+
+ await act(async () => {
+ await vi.waitFor(() =>
+ expect(mocks.batchFetchProjects).toHaveBeenCalledWith(
+ ["projects/deleted-project"],
+ true
+ )
+ );
+ });
+ expect(document.body.textContent).toContain("deleted-project");
+ unmount();
+ });
+
test("checks AI configuration when opening an existing chat", async () => {
const chatId = useAgentStore.getState().currentChatId!;
mocks.getOrFetchSettingByName.mockResolvedValue({
@@ -541,6 +715,25 @@ describe("AgentWindow", () => {
unmount();
});
+ test("vertically aligns each chat title with its archive action", () => {
+ const { render, unmount } = renderIntoContainer(<AgentWindow />);
+ render();
+
+ const archiveButton = document.body.querySelector(
+ "[data-agent-archive-chat]"
+ ) as HTMLButtonElement | null;
+ const title = document.body.querySelector(
+ "[data-agent-chat-title]"
+ ) as HTMLDivElement | null;
+ const rowContent = title?.parentElement?.parentElement;
+
+ expect(archiveButton).toBeInstanceOf(HTMLButtonElement);
+ expect(rowContent).toBeInstanceOf(HTMLDivElement);
+ expect(rowContent?.className).toContain("items-center");
+
+ unmount();
+ });
+
test("commits drag position only on pointerup", () => {
const { render, unmount } = renderIntoContainer(<AgentWindow />);
diff --git a/frontend/src/modules/agent/components/AgentWindow.tsx b/frontend/src/modules/agent/components/AgentWindow.tsx
index dac80b232c..e8597afd8a 100644
--- a/frontend/src/modules/agent/components/AgentWindow.tsx
+++ b/frontend/src/modules/agent/components/AgentWindow.tsx
@@ -1,8 +1,17 @@
-import { Archive, EllipsisVertical, Plus, Trash2, Undo2 } from "lucide-react";
+import {
+ Archive,
+ Building2,
+ EllipsisVertical,
+ FolderKanban,
+ Plus,
+ Trash2,
+ Undo2,
+} from "lucide-react";
import {
type ReactNode,
useCallback,
useEffect,
+ useLayoutEffect,
useMemo,
useRef,
useState,
@@ -15,14 +24,17 @@ import {
type PanelImperativeHandle,
Separator as PanelResizeHandle,
} from "react-resizable-panels";
-import { HumanizeTs } from "@/components/HumanizeTs";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { getLayerRoot } from "@/components/ui/layer";
+import {
+ getProjectName,
+ projectNamePrefix,
+ workspaceNamePrefix,
+} from "@/lib/resourceName";
import { cn } from "@/lib/utils";
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";
@@ -78,6 +90,40 @@ const resizeZoneClasses: Record<ResizeDirection, string> = {
sw: "bottom-[-6px] left-[-6px] size-[12px] cursor-sw-resize",
};
+interface AgentChatGroup {
+ context?: string;
+ chats: AgentChatRecord[];
+}
+
+function groupChatsByContext(chats: AgentChatRecord[]): AgentChatGroup[] {
+ const groups = new Map<string, AgentChatGroup>();
+ for (const chat of chats) {
+ const key = chat.context ?? "";
+ const group = groups.get(key);
+ if (group) {
+ group.chats.push(chat);
+ continue;
+ }
+ groups.set(key, { context: chat.context, chats: [chat] });
+ }
+ const unscopedGroup = groups.get("");
+ const groupRank = (context: string) => {
+ if (context.startsWith(workspaceNamePrefix)) return 0;
+ if (context.startsWith(projectNamePrefix)) return 1;
+ return 2;
+ };
+ return [
+ ...[...groups.entries()]
+ .filter(([context]) => context)
+ .sort(([left], [right]) => {
+ const rankDifference = groupRank(left) - groupRank(right);
+ return rankDifference || right.localeCompare(left);
+ })
+ .map(([, group]) => group),
+ ...(unscopedGroup ? [unscopedGroup] : []),
+ ];
+}
+
export function AgentWindow() {
const { t } = useTranslation();
@@ -91,6 +137,14 @@ export function AgentWindow() {
const currentChatId = useAgentStore((s) => s.currentChatId);
const hasRunningChat = useAgentStore(selectHasRunningChat);
const getOrFetchSettingByName = useAppStore((s) => s.getOrFetchSettingByName);
+ const batchFetchProjects = useAppStore((s) => s.batchFetchProjects);
+ const projectsByName = useAppStore((s) => s.projectsByName);
+ const projectErrorsByName = useAppStore((s) => s.projectErrorsByName);
+ const workspace = useAppStore((s) => s.workspace);
+
+ useLayoutEffect(() => {
+ useAgentStore.getState().setWorkspaceName(workspace?.name);
+ }, [hasRunningChat, workspace?.name]);
const windowRef = useRef<HTMLDivElement>(null);
const renameInputRef = useRef<HTMLInputElement>(null);
@@ -253,6 +307,23 @@ export function AgentWindow() {
() => orderedChats.filter((chat) => chat.archived === showArchivedOnly),
[orderedChats, showArchivedOnly]
);
+ const displayedChatGroups = useMemo(
+ () => groupChatsByContext(displayedChats),
+ [displayedChats]
+ );
+ const missingProjectContexts = useMemo(
+ () =>
+ [
+ ...new Set(
+ displayedChatGroups.flatMap((group) =>
+ group.context?.startsWith(projectNamePrefix) ? [group.context] : []
+ )
+ ),
+ ].filter(
+ (context) => !projectsByName[context] && !projectErrorsByName[context]
+ ),
+ [displayedChatGroups, projectErrorsByName, projectsByName]
+ );
const activeChats = useMemo(
() => orderedChats.filter((chat) => !chat.archived),
[orderedChats]
@@ -271,6 +342,13 @@ export function AgentWindow() {
hasRunningChat || !showArchivedOnly || archivedChats.length === 0;
const canResizeWindow = supportsFinePointer;
+ useEffect(() => {
+ if (!visible || missingProjectContexts.length === 0) return;
+ void batchFetchProjects(missingProjectContexts, true).catch(() => {
+ // Keep the stable resource-id fallback when a context cannot be loaded.
+ });
+ }, [batchFetchProjects, missingProjectContexts, visible]);
+
const syncStoreToDisplayState = useCallback(() => {
const store = useAgentStore.getState();
store.setSize(
@@ -308,6 +386,19 @@ export function AgentWindow() {
[getEditableChatTitle, t]
);
+ const getContextLabel = useCallback(
+ (context: string) => {
+ if (context.startsWith(projectNamePrefix)) {
+ return projectsByName[context]?.title || getProjectName(context);
+ }
+ if (context === workspace?.name) {
+ return workspace.title || workspace.name;
+ }
+ return context;
+ },
+ [projectsByName, workspace]
+ );
+
const selectFirstDisplayedChat = useCallback(() => {
const store = useAgentStore.getState();
const first = selectOrderedChats(store).find(
@@ -369,9 +460,15 @@ export function AgentWindow() {
store.createChat({
page: getCurrentPageSnapshot(),
context: getCurrentChatContext(),
+ workspaceName: workspace?.name,
});
},
- [showArchivedOnly, selectFirstDisplayedChat, getCurrentPageSnapshot]
+ [
+ showArchivedOnly,
+ selectFirstDisplayedChat,
+ getCurrentPageSnapshot,
+ workspace?.name,
+ ]
);
// --- Rename ---
@@ -440,8 +537,21 @@ export function AgentWindow() {
useAgentStore.getState().createChat({
page: getCurrentPageSnapshot(),
context: getCurrentChatContext(),
+ workspaceName: workspace?.name,
});
- }, [isChatCreationDisabled, getCurrentPageSnapshot]);
+ }, [isChatCreationDisabled, getCurrentPageSnapshot, workspace?.name]);
+
+ const createChatForContext = useCallback(
+ (context: string) => {
+ if (isChatCreationDisabled) return;
+ useAgentStore.getState().createChat({
+ page: getCurrentPageSnapshot(),
+ context,
+ workspaceName: workspace?.name,
+ });
+ },
+ [isChatCreationDisabled, getCurrentPageSnapshot, workspace?.name]
+ );
const handleChatRowClick = useCallback(
(chatId: string) => {
@@ -830,18 +940,16 @@ export function AgentWindow() {
useAgentStore.getState().saveWindowState();
}, [clampSidebarWidth]);
- // --- Mount: load window state ---
-
- useEffect(() => {
- useAgentStore.getState().loadWindowState();
- }, []);
-
useEffect(() => {
if (!visible || !currentChatId) return;
useAgentStore
.getState()
- .ensureCurrentChat(getCurrentPageSnapshot(), getCurrentChatContext());
- }, [currentChatId, getCurrentPageSnapshot, visible]);
+ .ensureCurrentChat(
+ getCurrentPageSnapshot(),
+ getCurrentChatContext(),
+ workspace?.name
+ );
+ }, [currentChatId, getCurrentPageSnapshot, visible, workspace?.name]);
useEffect(() => {
if (!visible || !currentChatId) return;
@@ -1083,109 +1191,142 @@ export function AgentWindow() {
{/* Chat list */}
<div className="min-h-0 flex-1 overflow-y-auto">
<div className="flex flex-col" data-agent-chat-list>
- {displayedChats.map((chat) => (
+ {displayedChatGroups.map((group) => (
<div
- key={chat.id}
- className={`group w-full rounded-xs px-3 py-2 text-left text-sm transition-colors ${
- chat.id === currentChatId
- ? "bg-accent/10 text-accent"
- : "text-control hover:bg-control-bg-hover"
- }`}
- data-agent-chat-row={chat.id}
+ key={group.context ?? "unscoped"}
+ className="flex flex-col"
+ data-agent-chat-group={group.context ?? "unscoped"}
>
- {chat.id === currentChatId && isRenamingCurrentChat ? (
- <Input
- ref={renameInputRef}
- value={renamingTitle}
- onChange={(e) => setRenamingTitle(e.target.value)}
- className="h-7 text-sm"
- placeholder={t("agent.rename-chat-placeholder")}
- data-agent-inline-rename-input
- onBlur={commitRenameCurrentChat}
- onKeyDown={onRenameKeydown}
- />
- ) : (
- <div className="flex items-start gap-x-2">
- <Button
- appearance="secondary"
- size="md"
- type="button"
- className="h-auto min-w-0 flex-1 flex-col items-start p-0 text-left whitespace-normal hover:bg-transparent disabled:cursor-not-allowed disabled:opacity-60"
- disabled={
- !useAgentStore.getState().canSelectChat(chat.id)
- }
- aria-current={
- chat.id === currentChatId ? "true" : undefined
- }
- onClick={() => handleChatRowClick(chat.id)}
+ <div className="flex min-w-0 items-center justify-between gap-x-2 px-3 pt-3 pb-1 text-xs font-medium text-control-light">
+ {group.context ? (
+ <div className="flex min-w-0 items-center gap-x-1.5">
+ {group.context.startsWith(projectNamePrefix) ? (
+ <FolderKanban className="size-3.5 shrink-0" />
+ ) : (
+ <Building2 className="size-3.5 shrink-0" />
+ )}
+ <span className="truncate">
+ {getContextLabel(group.context)}
+ </span>
+ </div>
+ ) : (
+ <span className="truncate">
+ {t("agent.other-chats")}
+ </span>
+ )}
+ {group.context && (
+ <AgentTooltip
+ content={`${t("agent.new-chat")}: ${getContextLabel(group.context)}`}
>
- <div
- className="w-full truncate font-medium"
- data-agent-chat-title
- >
- {getChatLabel(chat)}
- </div>
- <span
- className={`mt-1 block w-full truncate text-xs ${
- chat.id === currentChatId
- ? "text-accent/80"
- : "text-control-light"
- }`}
- data-agent-chat-updated-ts
+ <Button
+ appearance="secondary"
+ size="xs"
+ className="shrink-0 px-1 text-control-light hover:bg-control-bg-hover"
+ aria-label={`${t("agent.new-chat")}: ${getContextLabel(group.context)}`}
+ data-agent-new-chat-for-context={group.context}
+ disabled={isChatCreationDisabled}
+ onClick={() =>
+ createChatForContext(group.context!)
+ }
>
- <AgentTooltip
- content={formatAbsoluteDateTime(chat.updatedTs)}
+ <Plus className="size-3.5" aria-hidden="true" />
+ </Button>
+ </AgentTooltip>
+ )}
+ </div>
+ {group.chats.map((chat) => (
+ <div
+ key={chat.id}
+ className={`group w-full rounded-xs px-3 py-2 text-left text-sm transition-colors ${
+ chat.id === currentChatId
+ ? "bg-accent/10 text-accent"
+ : "text-control hover:bg-control-bg-hover"
+ }`}
+ data-agent-chat-row={chat.id}
+ >
+ {chat.id === currentChatId &&
+ isRenamingCurrentChat ? (
+ <Input
+ ref={renameInputRef}
+ value={renamingTitle}
+ onChange={(e) => setRenamingTitle(e.target.value)}
+ className="h-7 text-sm"
+ placeholder={t("agent.rename-chat-placeholder")}
+ data-agent-inline-rename-input
+ onBlur={commitRenameCurrentChat}
+ onKeyDown={onRenameKeydown}
+ />
+ ) : (
+ <div className="flex items-center gap-x-2">
+ <Button
+ appearance="secondary"
+ size="md"
+ type="button"
+ className="h-auto min-w-0 flex-1 flex-col items-start p-0 text-left whitespace-normal hover:bg-transparent disabled:cursor-not-allowed disabled:opacity-60"
+ disabled={
+ !useAgentStore
+ .getState()
+ .canSelectChat(chat.id)
+ }
+ aria-current={
+ chat.id === currentChatId ? "true" : undefined
+ }
+ onClick={() => handleChatRowClick(chat.id)}
>
- <HumanizeTs
- tsMs={chat.updatedTs}
- tooltip={false}
- />
- </AgentTooltip>
- </span>
- </Button>
- <div className="pointer-events-none flex shrink-0 items-center gap-x-2 opacity-0 transition-opacity group-hover:pointer-events-auto group-hover:opacity-100 group-focus-within:pointer-events-auto group-focus-within:opacity-100">
- {chat.archived ? (
- <>
- <SidebarIconButton
- tooltip={t("agent.unarchive-chat")}
- ariaLabel={t("agent.unarchive-chat")}
- dataAttr="data-agent-unarchive-chat"
- onClick={() => unarchiveChat(chat.id)}
+ <div
+ className="w-full truncate font-medium"
+ data-agent-chat-title
>
- <Undo2
- className="size-3.5"
- aria-hidden="true"
- />
- </SidebarIconButton>
- <ConfirmDialog
- message={t("agent.delete-chat-confirmation")}
- onConfirm={() => deleteChat(chat.id)}
- triggerLabel={t("agent.delete-chat")}
- triggerDataAttr="data-agent-delete-chat"
- triggerVariant="icon"
- >
- <Trash2
- className="size-3.5"
- aria-hidden="true"
- />
- </ConfirmDialog>
- </>
- ) : (
- <SidebarIconButton
- tooltip={t("agent.archive-chat")}
- ariaLabel={t("agent.archive-chat")}
- dataAttr="data-agent-archive-chat"
- onClick={() => archiveChat(chat.id)}
- >
- <Archive
- className="size-3.5"
- aria-hidden="true"
- />
- </SidebarIconButton>
- )}
- </div>
+ {getChatLabel(chat)}
+ </div>
+ </Button>
+ <div className="pointer-events-none flex shrink-0 items-center gap-x-2 opacity-0 transition-opacity group-hover:pointer-events-auto group-hover:opacity-100 group-focus-within:pointer-events-auto group-focus-within:opacity-100">
+ {chat.archived ? (
+ <>
+ <SidebarIconButton
+ tooltip={t("agent.unarchive-chat")}
+ ariaLabel={t("agent.unarchive-chat")}
+ dataAttr="data-agent-unarchive-chat"
+ onClick={() => unarchiveChat(chat.id)}
+ >
+ <Undo2
+ className="size-3.5"
+ aria-hidden="true"
+ />
+ </SidebarIconButton>
+ <ConfirmDialog
+ message={t(
+ "agent.delete-chat-confirmation"
+ )}
+ onConfirm={() => deleteChat(chat.id)}
+ triggerLabel={t("agent.delete-chat")}
+ triggerDataAttr="data-agent-delete-chat"
+ triggerVariant="icon"
+ >
+ <Trash2
+ className="size-3.5"
+ aria-hidden="true"
+ />
+ </ConfirmDialog>
+ </>
+ ) : (
+ <SidebarIconButton
+ tooltip={t("agent.archive-chat")}
+ ariaLabel={t("agent.archive-chat")}
+ dataAttr="data-agent-archive-chat"
+ onClick={() => archiveChat(chat.id)}
+ >
+ <Archive
+ className="size-3.5"
+ aria-hidden="true"
+ />
+ </SidebarIconButton>
+ )}
+ </div>
+ </div>
+ )}
</div>
- )}
+ ))}
</div>
))}
</div>
diff --git a/frontend/src/modules/agent/components/LandingStarterSelector.test.tsx b/frontend/src/modules/agent/components/LandingStarterSelector.test.tsx
new file mode 100644
index 0000000000..7e63a92096
--- /dev/null
+++ b/frontend/src/modules/agent/components/LandingStarterSelector.test.tsx
@@ -0,0 +1,194 @@
+import { act } from "react";
+import { createRoot } from "react-dom/client";
+import { afterEach, describe, expect, test, vi } from "vitest";
+import type { LandingStarterId } from "../logic/landingStarters";
+
+const prompts: Record<LandingStarterId, string> = {
+ "workspace-setup-first": "What should I set up first?",
+ "workspace-concepts": "Help me understand Projects, Instances, and Databases",
+ "workspace-governance": "How does Bytebase govern database changes?",
+ "workspace-attention": "What needs my attention?",
+ "workspace-recent": "What changed recently across my projects?",
+ "project-connect": "How do I connect a database to this project?",
+ "project-organize": "How should I organize databases and environments for this project?",
+ "project-next": "What can I do next?",
+ "project-propose-change": "How do I propose a database change?",
+ "project-open-blockers": "What needs my attention in this project?",
+ "project-open-recent": "What changed recently in this project?",
+ "project-collaborate": "How do I invite teammates to this project?",
+ "project-access": "What should I set up before collaborating on this project?",
+ "project-review": "How are database changes reviewed in this project?",
+};
+
+vi.mock("react-i18next", () => ({
+ useTranslation: () => ({
+ t: (key: string) => {
+ const id = key.replace("agent.landing-starters.", "") as LandingStarterId;
+ return prompts[id] ?? key;
+ },
+ }),
+}));
+
+vi.mock("@/components/ui/dropdown-menu", () => ({
+ DropdownMenu: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
+ DropdownMenuTrigger: ({ render }: { render: React.ReactElement }) => render,
+ DropdownMenuContent: ({ children, ...props }: React.HTMLAttributes<HTMLDivElement>) => (
+ <div {...props}>{children}</div>
+ ),
+ DropdownMenuItem: ({ children, ...props }: React.HTMLAttributes<HTMLButtonElement>) => (
+ <button type="button" {...props}>{children}</button>
+ ),
+}));
+
+import { LandingStarterSelector } from "./LandingStarterSelector";
+
+afterEach(() => {
+ document.body.replaceChildren();
+});
+
+const render = (props: React.ComponentProps<typeof LandingStarterSelector>) => {
+ const container = document.createElement("div");
+ document.body.append(container);
+ const root = createRoot(container);
+ act(() => root.render(<LandingStarterSelector {...props} />));
+ return { container, unmount: () => act(() => root.unmount()) };
+};
+
+describe("LandingStarterSelector", () => {
+ test("sends the highest-ranked prompt directly", () => {
+ const onSelect = vi.fn();
+ const view = render({
+ starterIds: ["project-next", "project-propose-change"],
+ disabled: false,
+ onSelect,
+ });
+
+ const primary = view.container.querySelector<HTMLButtonElement>(
+ '[data-testid="landing-starter-primary"]'
+ );
+ expect(primary?.textContent).toBe("What can I do next?");
+ act(() => primary?.click());
+ expect(onSelect).toHaveBeenCalledWith("project-next");
+ view.unmount();
+ });
+
+ test("uses setup-oriented prompts for a solo Project", () => {
+ const view = render({
+ starterIds: ["project-collaborate", "project-access", "project-review"],
+ disabled: false,
+ onSelect: vi.fn(),
+ });
+
+ expect(
+ view.container.querySelector('[data-testid="landing-starter-primary"]')
+ ?.textContent
+ ).toBe("How do I invite teammates to this project?");
+ expect(
+ view.container.querySelector('[data-starter-id="project-access"]')
+ ?.textContent
+ ).toBe("What should I set up before collaborating on this project?");
+ view.unmount();
+ });
+
+ test("only renders overflow alternatives when there is more than one prompt", () => {
+ const single = render({
+ starterIds: ["project-next"],
+ disabled: false,
+ onSelect: vi.fn(),
+ });
+ expect(
+ single.container.querySelector('[data-testid="landing-starter-overflow"]')
+ ).toBeNull();
+ single.unmount();
+
+ const multiple = render({
+ starterIds: ["project-next", "project-propose-change"],
+ disabled: false,
+ onSelect: vi.fn(),
+ });
+ expect(
+ multiple.container.querySelector('[data-testid="landing-starter-overflow"]')
+ ).not.toBeNull();
+ multiple.unmount();
+ });
+
+ test("vertically centers the overflow control with the prompt", () => {
+ const view = render({
+ starterIds: ["project-next", "project-propose-change"],
+ disabled: false,
+ onSelect: vi.fn(),
+ });
+
+ expect(view.container.firstElementChild?.className).toContain(
+ "items-center"
+ );
+ view.unmount();
+ });
+
+ test("sends an alternative from the compact menu", () => {
+ const onSelect = vi.fn();
+ const view = render({
+ starterIds: ["project-next", "project-organize", "project-propose-change"],
+ disabled: false,
+ onSelect,
+ });
+
+ const alternative = view.container.querySelector<HTMLButtonElement>(
+ '[data-starter-id="project-propose-change"]'
+ );
+ act(() => alternative?.click());
+ expect(onSelect).toHaveBeenCalledWith("project-propose-change");
+ view.unmount();
+ });
+
+ test("prevents selection while the agent is busy", () => {
+ const onSelect = vi.fn();
+ const view = render({
+ starterIds: ["project-next", "project-propose-change"],
+ disabled: true,
+ onSelect,
+ });
+
+ expect(
+ view.container.querySelector<HTMLButtonElement>(
+ '[data-testid="landing-starter-primary"]'
+ )?.disabled
+ ).toBe(true);
+ expect(
+ view.container.querySelector<HTMLButtonElement>(
+ '[data-testid="landing-starter-overflow"]'
+ )?.disabled
+ ).toBe(true);
+ expect(
+ view.container.querySelector<HTMLButtonElement>(
+ '[data-starter-id="project-propose-change"]'
+ )?.disabled
+ ).toBe(true);
+ view.unmount();
+ });
+
+ test("keeps many wrapped alternatives inside a scrollable menu", () => {
+ const view = render({
+ starterIds: [
+ "project-organize",
+ "project-next",
+ "project-propose-change",
+ "project-connect",
+ ],
+ disabled: false,
+ onSelect: vi.fn(),
+ });
+
+ const menu = view.container.querySelector('[data-testid="landing-starter-menu"]');
+ expect(menu?.className).toContain("max-h-64");
+ expect(menu?.className).toContain("overflow-y-auto");
+ expect(
+ view.container.querySelector('[data-starter-id="project-propose-change"]')
+ ?.className
+ ).toContain("whitespace-normal");
+ expect(
+ view.container.querySelectorAll("[data-starter-id]")
+ ).toHaveLength(3);
+ view.unmount();
+ });
+});
diff --git a/frontend/src/modules/agent/components/LandingStarterSelector.tsx b/frontend/src/modules/agent/components/LandingStarterSelector.tsx
new file mode 100644
index 0000000000..97b75cd379
--- /dev/null
+++ b/frontend/src/modules/agent/components/LandingStarterSelector.tsx
@@ -0,0 +1,88 @@
+import { ChevronDown } from "lucide-react";
+import { useTranslation } from "react-i18next";
+import { Button } from "@/components/ui/button";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+} from "@/components/ui/dropdown-menu";
+import { Tooltip } from "@/components/ui/tooltip";
+import type { LandingStarterId } from "../logic/landingStarters";
+
+interface LandingStarterSelectorProps {
+ starterIds: LandingStarterId[];
+ disabled: boolean;
+ onSelect: (starterId: LandingStarterId) => void;
+}
+
+export function LandingStarterSelector({
+ starterIds,
+ disabled,
+ onSelect,
+}: LandingStarterSelectorProps) {
+ const { t } = useTranslation();
+ const [primary, ...alternatives] = starterIds;
+
+ if (!primary) {
+ return null;
+ }
+
+ const labelFor = (starterId: LandingStarterId) =>
+ t(`agent.landing-starters.${starterId}`);
+
+ return (
+ <div className="flex min-w-0 items-center gap-1">
+ <Button
+ type="button"
+ appearance="link"
+ size="xs"
+ className="h-auto min-w-0 max-w-full px-0 text-left whitespace-normal"
+ disabled={disabled}
+ data-testid="landing-starter-primary"
+ onClick={() => onSelect(primary)}
+ >
+ {labelFor(primary)}
+ </Button>
+ {alternatives.length > 0 && (
+ <DropdownMenu>
+ <Tooltip content={t("agent.landing-starters.more")}>
+ <DropdownMenuTrigger
+ render={
+ <Button
+ type="button"
+ appearance="secondary"
+ size="xs"
+ className="shrink-0"
+ disabled={disabled}
+ aria-label={t("agent.landing-starters.more")}
+ data-testid="landing-starter-overflow"
+ >
+ <ChevronDown className="size-3.5" />
+ </Button>
+ }
+ />
+ </Tooltip>
+ <DropdownMenuContent
+ align="start"
+ aria-label={t("agent.landing-starters.menu")}
+ data-testid="landing-starter-menu"
+ className="w-80 max-w-[calc(100vw-2rem)] max-h-64 overflow-y-auto p-1"
+ >
+ {alternatives.map((starterId) => (
+ <DropdownMenuItem
+ key={starterId}
+ disabled={disabled}
+ data-starter-id={starterId}
+ className="h-auto min-w-0 whitespace-normal break-words py-1.5"
+ onClick={() => onSelect(starterId)}
+ >
+ {labelFor(starterId)}
+ </DropdownMenuItem>
+ ))}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ )}
+ </div>
+ );
+}
diff --git a/frontend/src/modules/agent/logic/agentLoop.test.ts b/frontend/src/modules/agent/logic/agentLoop.test.ts
index 2c86e5b979..2f433cfc8b 100644
--- a/frontend/src/modules/agent/logic/agentLoop.test.ts
+++ b/frontend/src/modules/agent/logic/agentLoop.test.ts
@@ -267,6 +267,50 @@ describe("runAgentLoop", () => {
expect(executeTool).not.toHaveBeenCalled();
});
+ test("completes a read-only starter when the model answers in plain text after a tool result", async () => {
+ vi.mocked(aiServiceClientConnect.chat)
+ .mockResolvedValueOnce({
+ content: "",
+ toolCalls: [
+ {
+ id: "tool-open-issues",
+ name: "get_project_open_issues",
+ arguments: "{}",
+ metadata: "",
+ },
+ ],
+ } as never)
+ .mockResolvedValueOnce({
+ content: "You have two open Issues in this Project.",
+ toolCalls: [],
+ } as never);
+
+ const executeTool: ToolExecutor = vi.fn(async () => ({
+ kind: "tool_result" as const,
+ result: JSON.stringify({ issues: [] }),
+ }));
+ const onText = vi.fn();
+
+ const outcome = await runAgentLoop(
+ [{ role: "system", content: "system" }],
+ [],
+ executeTool,
+ { onText },
+ undefined,
+ { allowPlainTextCompletion: true }
+ );
+
+ expect(outcome).toEqual({
+ kind: "completed",
+ text: "You have two open Issues in this Project.",
+ success: true,
+ totalTokensUsed: 0,
+ });
+ expect(onText).toHaveBeenCalledWith(
+ "You have two open Issues in this Project."
+ );
+ });
+
test("returns awaiting_user without synthesizing an immediate tool result", async () => {
vi.mocked(aiServiceClientConnect.chat).mockResolvedValue({
content: "",
diff --git a/frontend/src/modules/agent/logic/agentLoop.ts b/frontend/src/modules/agent/logic/agentLoop.ts
index ba5d67b695..d7891174f0 100644
--- a/frontend/src/modules/agent/logic/agentLoop.ts
+++ b/frontend/src/modules/agent/logic/agentLoop.ts
@@ -99,6 +99,10 @@ export interface AgentCallbacks {
onError?: (error: Error) => void;
}
+export interface AgentLoopOptions {
+ allowPlainTextCompletion?: boolean;
+}
+
function createSkippedToolResult(blockedBy: {
toolCallId: string;
kind: "ask_user" | "done";
@@ -116,7 +120,8 @@ export async function runAgentLoop(
tools: ToolDefinition[],
executeTool: ToolExecutor,
callbacks?: AgentCallbacks,
- signal?: AbortSignal
+ signal?: AbortSignal,
+ options: AgentLoopOptions = {}
): Promise<AgentLoopOutcome> {
const conversation: Message[] = [...messages];
const protoTools = tools.map(toolDefToProto);
@@ -253,6 +258,17 @@ export async function runAgentLoop(
continue;
}
+ const text = response.content?.trim() ?? "";
+ if (options.allowPlainTextCompletion && text) {
+ callbacks?.onText?.(text);
+ return {
+ kind: "completed",
+ text,
+ success: true,
+ totalTokensUsed,
+ };
+ }
+
const error = new Error(
"Agent must finish with done({ text, success }) or ask_user(...), not plain assistant text."
);
diff --git a/frontend/src/modules/agent/logic/landingStarters.test.ts b/frontend/src/modules/agent/logic/landingStarters.test.ts
new file mode 100644
index 0000000000..3b9153cca7
--- /dev/null
+++ b/frontend/src/modules/agent/logic/landingStarters.test.ts
@@ -0,0 +1,206 @@
+import { describe, expect, test } from "vitest";
+import { getLandingStarterIds } from "./landingStarters";
+
+describe("getLandingStarterIds", () => {
+ test("offers setup guidance in a workspace without setup resources", () => {
+ expect(
+ getLandingStarterIds({
+ scope: "workspace",
+ setupResources: "empty",
+ canViewRecentActivity: false,
+ })
+ ).toEqual([
+ "workspace-setup-first",
+ "workspace-concepts",
+ "workspace-governance",
+ ]);
+ });
+
+ test("offers normal workspace prompts when setup resources exist", () => {
+ expect(
+ getLandingStarterIds({
+ scope: "workspace",
+ setupResources: "present",
+ canViewRecentActivity: true,
+ })
+ ).toEqual(["workspace-attention", "workspace-recent"]);
+ });
+
+ test.each(["loading", "unknown"] as const)(
+ "does not infer missing setup resources while discovery is %s",
+ (setupResources) => {
+ expect(
+ getLandingStarterIds({
+ scope: "workspace",
+ setupResources,
+ canViewRecentActivity: false,
+ })
+ ).toEqual(["workspace-attention"]);
+ }
+ );
+
+ test("does not offer workspace recent activity without audit-log access", () => {
+ expect(
+ getLandingStarterIds({
+ scope: "workspace",
+ setupResources: "present",
+ canViewRecentActivity: false,
+ })
+ ).toEqual(["workspace-attention"]);
+ });
+
+ test("combines open work, database setup, and solo collaboration prompts", () => {
+ expect(
+ getLandingStarterIds({
+ scope: "project",
+ activeWork: "present",
+ database: "empty",
+ change: "not-started",
+ membership: "solo",
+ canConnectInstance: true,
+ canCreateChange: true,
+ canViewRecentActivity: true,
+ })
+ ).toEqual([
+ "project-open-blockers",
+ "project-connect",
+ "project-collaborate",
+ "project-open-recent",
+ "project-organize",
+ "project-access",
+ "project-review",
+ ]);
+ });
+
+ test.each(["loading", "unknown"] as const)(
+ "combines known database and collaboration prompts while active work discovery is %s",
+ (activeWork) => {
+ expect(
+ getLandingStarterIds({
+ scope: "project",
+ activeWork,
+ database: "present",
+ change: "not-started",
+ membership: "solo",
+ canConnectInstance: true,
+ canCreateChange: true,
+ canViewRecentActivity: true,
+ })
+ ).toEqual([
+ "project-next",
+ "project-collaborate",
+ "project-propose-change",
+ "project-access",
+ "project-review",
+ ]);
+ }
+ );
+
+ test("offers project discovery after database access is confirmed", () => {
+ expect(
+ getLandingStarterIds({
+ scope: "project",
+ activeWork: "empty",
+ database: "present",
+ change: "not-started",
+ membership: "has-collaborators",
+ canConnectInstance: true,
+ canCreateChange: true,
+ canViewRecentActivity: true,
+ })
+ ).toEqual(["project-next", "project-propose-change"]);
+ });
+
+ test("does not offer a database-change prompt to a member who cannot create one", () => {
+ expect(
+ getLandingStarterIds({
+ scope: "project",
+ activeWork: "empty",
+ database: "present",
+ change: "not-started",
+ membership: "has-collaborators",
+ canConnectInstance: true,
+ canCreateChange: false,
+ canViewRecentActivity: true,
+ })
+ ).toEqual(["project-next"]);
+ });
+
+ test("does not offer first-change prompts after a database change is proposed", () => {
+ expect(
+ getLandingStarterIds({
+ scope: "project",
+ activeWork: "present",
+ database: "present",
+ change: "proposed",
+ membership: "has-collaborators",
+ canConnectInstance: true,
+ canCreateChange: true,
+ canViewRecentActivity: true,
+ })
+ ).toEqual(["project-open-blockers", "project-open-recent"]);
+ });
+
+ test("offers connection guidance only when the member can connect an instance", () => {
+ expect(
+ getLandingStarterIds({
+ scope: "project",
+ activeWork: "empty",
+ database: "empty",
+ change: "not-started",
+ membership: "has-collaborators",
+ canConnectInstance: false,
+ canCreateChange: false,
+ canViewRecentActivity: true,
+ })
+ ).toEqual(["project-organize"]);
+ });
+
+ test("offers collaboration prompts to a solo project member", () => {
+ expect(
+ getLandingStarterIds({
+ scope: "project",
+ activeWork: "empty",
+ database: "present",
+ change: "rolled-out",
+ membership: "solo",
+ canConnectInstance: true,
+ canCreateChange: true,
+ canViewRecentActivity: true,
+ })
+ ).toEqual(["project-collaborate", "project-access", "project-review"]);
+ });
+
+ test.each(["loading", "unknown"] as const)(
+ "falls back to answerable project guidance when database discovery is %s",
+ (database) => {
+ expect(
+ getLandingStarterIds({
+ scope: "project",
+ activeWork: "unknown",
+ database,
+ change: "unknown",
+ membership: "unknown",
+ canConnectInstance: true,
+ canCreateChange: false,
+ canViewRecentActivity: true,
+ })
+ ).toEqual(["project-next"]);
+ }
+ );
+
+ test("does not offer recent activity without audit-log access", () => {
+ expect(
+ getLandingStarterIds({
+ scope: "project",
+ activeWork: "present",
+ database: "present",
+ change: "rolled-out",
+ membership: "has-collaborators",
+ canConnectInstance: true,
+ canCreateChange: false,
+ canViewRecentActivity: false,
+ })
+ ).toEqual(["project-open-blockers"]);
+ });
+});
diff --git a/frontend/src/modules/agent/logic/landingStarters.ts b/frontend/src/modules/agent/logic/landingStarters.ts
new file mode 100644
index 0000000000..54f6402fcb
--- /dev/null
+++ b/frontend/src/modules/agent/logic/landingStarters.ts
@@ -0,0 +1,103 @@
+export type LandingStarterId =
+ | "workspace-setup-first"
+ | "workspace-concepts"
+ | "workspace-governance"
+ | "workspace-attention"
+ | "workspace-recent"
+ | "project-connect"
+ | "project-organize"
+ | "project-next"
+ | "project-propose-change"
+ | "project-open-blockers"
+ | "project-open-recent"
+ | "project-collaborate"
+ | "project-access"
+ | "project-review";
+
+type Availability = "loading" | "present" | "empty" | "unknown";
+
+export type LandingStarterInput =
+ | {
+ scope: "workspace";
+ setupResources: Availability;
+ canViewRecentActivity: boolean;
+ }
+ | {
+ scope: "project";
+ activeWork: Availability;
+ database: Availability;
+ change: "loading" | "not-started" | "proposed" | "rolled-out" | "unknown";
+ membership: "unknown" | "solo" | "has-collaborators";
+ canConnectInstance: boolean;
+ canCreateChange: boolean;
+ canViewRecentActivity: boolean;
+ };
+
+const workspaceSetupStarters: LandingStarterId[] = [
+ "workspace-setup-first",
+ "workspace-concepts",
+ "workspace-governance",
+];
+
+const workspaceAttentionStarters: LandingStarterId[] = [
+ "workspace-attention",
+ "workspace-recent",
+];
+
+const projectGeneralStarters: LandingStarterId[] = ["project-next"];
+
+function rankProjectStarterGroups(
+ groups: LandingStarterId[][]
+): LandingStarterId[] {
+ return [
+ ...groups.flatMap((group) => group.slice(0, 1)),
+ ...groups.flatMap((group) => group.slice(1)),
+ ];
+}
+
+export function getLandingStarterIds(
+ input: LandingStarterInput
+): LandingStarterId[] {
+ if (input.scope === "workspace") {
+ if (input.setupResources === "empty") {
+ return workspaceSetupStarters;
+ }
+ return [
+ workspaceAttentionStarters[0],
+ ...(input.canViewRecentActivity ? [workspaceAttentionStarters[1]] : []),
+ ];
+ }
+
+ const groups: LandingStarterId[][] = [];
+
+ if (input.activeWork === "present") {
+ groups.push([
+ "project-open-blockers",
+ ...(input.canViewRecentActivity
+ ? (["project-open-recent"] as const)
+ : []),
+ ]);
+ }
+
+ if (input.database === "present" && input.change === "not-started") {
+ groups.push([
+ "project-next",
+ ...(input.canCreateChange ? (["project-propose-change"] as const) : []),
+ ]);
+ }
+
+ if (input.database === "empty") {
+ groups.push([
+ ...(input.canConnectInstance ? (["project-connect"] as const) : []),
+ "project-organize",
+ ]);
+ }
+
+ if (input.membership === "solo") {
+ groups.push(["project-collaborate", "project-access", "project-review"]);
+ }
+
+ return groups.length > 0
+ ? rankProjectStarterGroups(groups)
+ : projectGeneralStarters;
+}
diff --git a/frontend/src/modules/agent/logic/prompt.test.ts b/frontend/src/modules/agent/logic/prompt.test.ts
index d7620dddf0..80efb05862 100644
--- a/frontend/src/modules/agent/logic/prompt.test.ts
+++ b/frontend/src/modules/agent/logic/prompt.test.ts
@@ -38,4 +38,18 @@ describe("buildSystemPrompt", () => {
expect(prompt).not.toContain("read element indices");
expect(prompt).not.toContain("dom_action(type, index, value)");
});
+
+ test("keeps a read-only landing starter on its current page", () => {
+ const prompt = buildSystemPrompt({
+ path: "/projects/orders",
+ title: "Order service",
+ runMode: "read-only",
+ });
+
+ expect(prompt).toContain("Stay on the current page");
+ expect(prompt).toContain("Do not navigate");
+ expect(prompt).toContain("get_project_open_issues");
+ expect(prompt).toContain("get_project_recent_activity");
+ expect(prompt).toContain("get_workspace_recent_activity");
+ });
});
diff --git a/frontend/src/modules/agent/logic/prompt.ts b/frontend/src/modules/agent/logic/prompt.ts
index cc8bb464eb..6c21460dec 100644
--- a/frontend/src/modules/agent/logic/prompt.ts
+++ b/frontend/src/modules/agent/logic/prompt.ts
@@ -1,3 +1,5 @@
+import type { AgentRunMode } from "./types";
+
const serviceDirectory = `API Directory — use search_api(service="...") to browse endpoints, search_api(operationId="...") for schemas.
Database Management:
@@ -57,6 +59,7 @@ export function buildSystemPrompt(pageContext: {
title: string;
role?: string;
context?: string;
+ runMode?: AgentRunMode;
}): 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,
@@ -65,7 +68,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.
+${pageContext.runMode === "read-only" ? "- This is a read-only landing starter. 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 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.
- 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.
diff --git a/frontend/src/modules/agent/logic/tools/index.test.ts b/frontend/src/modules/agent/logic/tools/index.test.ts
index 3a92830eb0..b291ba2a70 100644
--- a/frontend/src/modules/agent/logic/tools/index.test.ts
+++ b/frontend/src/modules/agent/logic/tools/index.test.ts
@@ -17,12 +17,36 @@ vi.mock("./navigate", () => ({
vi.mock("./pageState", () => ({
createPageStateTool: vi.fn(() => vi.fn(async () => "page_state")),
}));
+vi.mock("./projectOpenIssues", () => ({
+ createProjectOpenIssuesTool: vi.fn(() => vi.fn(async () => "project_issues")),
+}));
+vi.mock("./projectRecentActivity", () => ({
+ createProjectRecentActivityTool: vi.fn(() =>
+ vi.fn(async () => "project_recent_activity")
+ ),
+}));
+vi.mock("./workspaceRecentActivity", () => ({
+ createWorkspaceRecentActivityTool: vi.fn(() =>
+ vi.fn(async () => "workspace_recent_activity")
+ ),
+}));
+vi.mock("./workspaceAttention", () => ({
+ createWorkspaceAttentionTool: vi.fn(() =>
+ vi.fn(async () => "workspace_attention")
+ ),
+}));
vi.mock("./searchApi", () => ({
searchApi: vi.fn(async () => "search_api"),
}));
import { createToolExecutor, getToolDefinitions } from ".";
+import { callApi } from "./callApi";
+import { createDomActionTool } from "./domAction";
import { createNavigateTool } from "./navigate";
+import { createProjectOpenIssuesTool } from "./projectOpenIssues";
+import { createProjectRecentActivityTool } from "./projectRecentActivity";
+import { createWorkspaceAttentionTool } from "./workspaceAttention";
+import { createWorkspaceRecentActivityTool } from "./workspaceRecentActivity";
describe("agent tools navigate", () => {
test("calls onNavigate after a successful navigation result", async () => {
@@ -112,6 +136,171 @@ describe("agent tools dom_action", () => {
});
});
+describe("agent tools read-only mode", () => {
+ test("only exposes page inspection, guidance, and completion", () => {
+ expect(
+ getToolDefinitions({ runMode: "read-only" }).map((tool) => tool.name)
+ ).toEqual([
+ "get_page_state",
+ "get_project_open_issues",
+ "get_project_recent_activity",
+ "get_workspace_attention",
+ "get_workspace_recent_activity",
+ "get_skill",
+ "ask_user",
+ "done",
+ ]);
+ expect(getToolDefinitions().map((tool) => tool.name)).not.toContain(
+ "get_project_open_issues"
+ );
+ expect(getToolDefinitions().map((tool) => tool.name)).not.toContain(
+ "get_project_recent_activity"
+ );
+ expect(getToolDefinitions().map((tool) => tool.name)).not.toContain(
+ "get_workspace_recent_activity"
+ );
+ expect(getToolDefinitions().map((tool) => tool.name)).not.toContain(
+ "get_workspace_attention"
+ );
+ });
+
+ test("uses the chat-bound Project for a starter issue lookup", async () => {
+ const issueTool = vi.fn(async () =>
+ JSON.stringify({
+ project: "projects/sample",
+ issues: [
+ {
+ name: "projects/sample/issues/1",
+ title: "Add customer table",
+ relation: "review",
+ approvalStatus: "PENDING",
+ },
+ ],
+ partial: false,
+ })
+ );
+ vi.mocked(createProjectOpenIssuesTool).mockReturnValue(issueTool);
+ const executeTool = createToolExecutor({} as AppRouterInstance, {
+ context: "projects/sample",
+ runMode: "read-only",
+ });
+
+ await expect(
+ executeTool("get_project_open_issues", {}, "tool-issues")
+ ).resolves.toEqual({
+ kind: "tool_result",
+ result: expect.stringContaining("Add customer table"),
+ });
+ expect(createProjectOpenIssuesTool).toHaveBeenCalledWith({
+ projectName: "projects/sample",
+ });
+ expect(issueTool).toHaveBeenCalledWith();
+ });
+
+ test("uses the chat-bound Project for a starter recent-activity lookup", async () => {
+ const recentActivityTool = vi.fn(async () => "project_recent_activity");
+ vi.mocked(createProjectRecentActivityTool).mockReturnValue(
+ recentActivityTool
+ );
+ const executeTool = createToolExecutor({} as AppRouterInstance, {
+ context: "projects/sample",
+ runMode: "read-only",
+ });
+
+ await expect(
+ executeTool("get_project_recent_activity", {}, "tool-recent-activity")
+ ).resolves.toEqual({
+ kind: "tool_result",
+ result: "project_recent_activity",
+ });
+ expect(createProjectRecentActivityTool).toHaveBeenCalledWith({
+ projectName: "projects/sample",
+ });
+ expect(recentActivityTool).toHaveBeenCalledWith();
+ });
+
+ test("uses the chat-bound workspace for a starter recent-activity lookup", async () => {
+ const recentActivityTool = vi.fn(async () => "workspace_recent_activity");
+ vi.mocked(createWorkspaceRecentActivityTool).mockReturnValue(
+ recentActivityTool
+ );
+ const executeTool = createToolExecutor({} as AppRouterInstance, {
+ context: "workspaces/acme",
+ runMode: "read-only",
+ });
+
+ await expect(
+ executeTool("get_workspace_recent_activity", {}, "tool-recent-activity")
+ ).resolves.toEqual({
+ kind: "tool_result",
+ result: "workspace_recent_activity",
+ });
+ expect(createWorkspaceRecentActivityTool).toHaveBeenCalledWith({
+ workspaceName: "workspaces/acme",
+ });
+ expect(recentActivityTool).toHaveBeenCalledWith();
+ });
+
+ test("uses the chat-bound workspace for a starter attention lookup", async () => {
+ const attentionTool = vi.fn(async () => "workspace_attention");
+ vi.mocked(createWorkspaceAttentionTool).mockReturnValue(attentionTool);
+ const executeTool = createToolExecutor({} as AppRouterInstance, {
+ context: "workspaces/acme",
+ runMode: "read-only",
+ });
+
+ await expect(
+ executeTool("get_workspace_attention", {}, "tool-attention")
+ ).resolves.toEqual({
+ kind: "tool_result",
+ result: "workspace_attention",
+ });
+ expect(createWorkspaceAttentionTool).toHaveBeenCalledWith({
+ workspaceName: "workspaces/acme",
+ });
+ expect(attentionTool).toHaveBeenCalledWith();
+ });
+
+ test("rejects unavailable tools before they can change the page or make a call", async () => {
+ const navigateTool = vi.fn(async () => "navigate");
+ vi.mocked(createNavigateTool).mockReturnValue(navigateTool);
+ const executeTool = createToolExecutor({} as AppRouterInstance, {
+ runMode: "read-only",
+ });
+ const callApiMock = vi.mocked(callApi);
+ const createDomActionToolMock = vi.mocked(createDomActionTool);
+ callApiMock.mockClear();
+ createDomActionToolMock.mockClear();
+
+ await expect(
+ executeTool("call_api", { operationId: "SQLService/Query" }, "tool-api")
+ ).resolves.toEqual({
+ kind: "tool_result",
+ result: expect.stringContaining("not available during this starter"),
+ });
+ await expect(
+ executeTool("dom_action", { type: "click", ref: "e1" }, "tool-dom")
+ ).resolves.toEqual({
+ kind: "tool_result",
+ result: expect.stringContaining("not available during this starter"),
+ });
+ await expect(
+ executeTool(
+ "navigate",
+ { path: "/projects/demo/issues" },
+ "tool-navigate"
+ )
+ ).resolves.toEqual({
+ kind: "tool_result",
+ result: expect.stringContaining("not available during this starter"),
+ });
+
+ expect(callApiMock).not.toHaveBeenCalled();
+ expect(createDomActionToolMock).not.toHaveBeenCalled();
+ expect(navigateTool).not.toHaveBeenCalled();
+ });
+});
+
describe("agent tools ask_user", () => {
test("exposes choose in the ask_user schema", () => {
const askUser = getToolDefinitions().find(
diff --git a/frontend/src/modules/agent/logic/tools/index.ts b/frontend/src/modules/agent/logic/tools/index.ts
index 39b916ed09..3fec5044f9 100644
--- a/frontend/src/modules/agent/logic/tools/index.ts
+++ b/frontend/src/modules/agent/logic/tools/index.ts
@@ -4,6 +4,7 @@ import type {
AgentAskUserKind,
AgentAskUserOption,
AgentPendingAsk,
+ AgentRunMode,
ToolDefinition,
ToolExecutionResult,
ToolExecutor,
@@ -12,7 +13,11 @@ import { callApi, type CallApiArgs } from "./callApi";
import { createDomActionTool, type DomActionArgs } from "./domAction";
import { createNavigateTool } from "./navigate";
import { createPageStateTool, type PageStateArgs } from "./pageState";
+import { createProjectOpenIssuesTool } from "./projectOpenIssues";
+import { createProjectRecentActivityTool } from "./projectRecentActivity";
import { searchApi, type SearchApiArgs } from "./searchApi";
+import { createWorkspaceRecentActivityTool } from "./workspaceRecentActivity";
+import { createWorkspaceAttentionTool } from "./workspaceAttention";
const toToolResult = (result: string): ToolExecutionResult => ({
kind: "tool_result",
@@ -116,8 +121,24 @@ const parseAskUserArgs = (
};
};
-export function getToolDefinitions(): ToolDefinition[] {
- return [
+const READ_ONLY_TOOL_NAMES = new Set([
+ "get_page_state",
+ "get_project_open_issues",
+ "get_project_recent_activity",
+ "get_workspace_attention",
+ "get_workspace_recent_activity",
+ "get_skill",
+ "ask_user",
+ "done",
+]);
+
+const READ_ONLY_TOOL_ERROR =
+ "This tool is not available during this starter. Inspect the current page or ask the user to send a follow-up message to take action.";
+
+export function getToolDefinitions(
+ options: { runMode?: AgentRunMode } = {}
+): ToolDefinition[] {
+ const tools: ToolDefinition[] = [
{
name: "search_api",
description: `Browse API endpoints and get request/response schemas. Use the API Directory in the system prompt to identify the right service first.
@@ -229,6 +250,42 @@ Use mode="dom" before dom_action to get element refs like [e1]. Use semantic mod
},
},
},
+ {
+ name: "get_project_open_issues",
+ description:
+ "List the current user's open Bytebase Issues in the Project bound to this chat. The result includes Issues awaiting the user's approval and Issues the user created. This tool has no parameters and cannot read another Project.",
+ parametersSchema: {
+ type: "object",
+ properties: {},
+ },
+ },
+ {
+ name: "get_project_recent_activity",
+ description:
+ "List the newest recorded activity for the project bound to this chat. The result contains at most five safe summaries with the time, actor, action, resource, and outcome. It excludes audit-log request and response data. This tool has no parameters and cannot read another project.",
+ parametersSchema: {
+ type: "object",
+ properties: {},
+ },
+ },
+ {
+ name: "get_workspace_attention",
+ description:
+ "List the current user's open Issues across the workspace bound to this chat. The result includes Issues awaiting the user's approval and Issues the user created, with at most five of each, and does not navigate. This tool has no parameters and cannot read another workspace.",
+ parametersSchema: {
+ type: "object",
+ properties: {},
+ },
+ },
+ {
+ name: "get_workspace_recent_activity",
+ description:
+ "List the newest recorded activity in the workspace bound to this chat, including project and workspace administration changes. The result contains at most five safe summaries with the time, actor, action, resource, and outcome. It excludes audit-log request and response data. This tool has no parameters and cannot read another workspace.",
+ parametersSchema: {
+ type: "object",
+ properties: {},
+ },
+ },
{
name: "dom_action",
description: `Last-resort DOM interaction — use only when no API endpoint covers the action.
@@ -363,11 +420,24 @@ Use mode="dom" before dom_action to get element refs like [e1]. Use semantic mod
},
},
];
+
+ if (options.runMode === "read-only") {
+ return tools.filter((tool) => READ_ONLY_TOOL_NAMES.has(tool.name));
+ }
+ return tools.filter(
+ (tool) =>
+ tool.name !== "get_project_open_issues" &&
+ tool.name !== "get_project_recent_activity" &&
+ tool.name !== "get_workspace_attention" &&
+ tool.name !== "get_workspace_recent_activity"
+ );
}
interface CreateToolExecutorOptions {
chatId?: string;
+ context?: string;
onNavigate?: () => void;
+ runMode?: AgentRunMode;
}
const PAGE_MUTATION_TOOL_NAMES = new Set(["navigate", "dom_action"]);
@@ -404,12 +474,28 @@ export function createToolExecutor(
const navigateTool = createNavigateTool(router);
const pageStateTool = createPageStateTool(router);
const domActionTool = createDomActionTool(router);
+ const projectOpenIssuesTool = createProjectOpenIssuesTool({
+ projectName: options.context,
+ });
+ const projectRecentActivityTool = createProjectRecentActivityTool({
+ projectName: options.context,
+ });
+ const workspaceRecentActivityTool = createWorkspaceRecentActivityTool({
+ workspaceName: options.context,
+ });
+ const workspaceAttentionTool = createWorkspaceAttentionTool({
+ workspaceName: options.context,
+ });
return async (
name: string,
args: Record<string, unknown>,
toolCallId: string
): Promise<ToolExecutionResult> => {
+ if (options.runMode === "read-only" && !READ_ONLY_TOOL_NAMES.has(name)) {
+ return toToolResult(JSON.stringify({ error: READ_ONLY_TOOL_ERROR }));
+ }
+
switch (name) {
case "search_api":
return toToolResult(await searchApi(args as SearchApiArgs));
@@ -436,6 +522,14 @@ export function createToolExecutor(
}
case "get_page_state":
return toToolResult(await pageStateTool(args as PageStateArgs));
+ case "get_project_open_issues":
+ return toToolResult(await projectOpenIssuesTool());
+ case "get_project_recent_activity":
+ return toToolResult(await projectRecentActivityTool());
+ case "get_workspace_attention":
+ return toToolResult(await workspaceAttentionTool());
+ case "get_workspace_recent_activity":
+ return toToolResult(await workspaceRecentActivityTool());
case "dom_action":
return toToolResult(
await withPageMutationLock(options.chatId, name, async () => {
diff --git a/frontend/src/modules/agent/logic/tools/projectOpenIssues.test.ts b/frontend/src/modules/agent/logic/tools/projectOpenIssues.test.ts
new file mode 100644
index 0000000000..787012bcca
--- /dev/null
+++ b/frontend/src/modules/agent/logic/tools/projectOpenIssues.test.ts
@@ -0,0 +1,121 @@
+// @vitest-environment node
+import { describe, expect, test, vi } from "vitest";
+import { ApprovalStatus, IssueStatus } from "@/types/proto-es/v1/common_pb";
+import type { Issue } from "@/types/proto-es/v1/issue_service_pb";
+
+const state = {
+ currentUser: { name: "users/[email protected]" },
+ listIssues: vi.fn(),
+};
+
+vi.mock("@/stores/app", () => ({
+ useAppStore: {
+ getState: () => state,
+ },
+}));
+
+import { createProjectOpenIssuesTool } from "./projectOpenIssues";
+
+const issue = (values: Partial<Issue>): Issue =>
+ ({
+ name: "projects/sample/issues/issue-1",
+ title: "Add customer table",
+ status: IssueStatus.OPEN,
+ approvalStatus: ApprovalStatus.PENDING,
+ creator: "users/[email protected]",
+ ...values,
+ }) as Issue;
+
+describe("projectOpenIssues", () => {
+ test("lists the current member's open Project issues without navigating", async () => {
+ state.listIssues.mockReset();
+ state.listIssues
+ .mockResolvedValueOnce({
+ nextPageToken: "",
+ issues: [issue({ name: "projects/sample/issues/review" })],
+ })
+ .mockResolvedValueOnce({
+ nextPageToken: "",
+ issues: [
+ issue({ name: "projects/sample/issues/created" }),
+ issue({ name: "projects/sample/issues/review" }),
+ ],
+ });
+
+ const result = JSON.parse(
+ await createProjectOpenIssuesTool({ projectName: "projects/sample" })()
+ );
+
+ expect(state.listIssues).toHaveBeenNthCalledWith(1, {
+ find: {
+ project: "projects/sample",
+ query: "",
+ currentApprover: "users/[email protected]",
+ statusList: [IssueStatus.OPEN],
+ approvalStatus: ApprovalStatus.PENDING,
+ orderBy: "update_time desc",
+ },
+ pageSize: 10,
+ });
+ expect(state.listIssues).toHaveBeenNthCalledWith(2, {
+ find: {
+ project: "projects/sample",
+ query: "",
+ creator: "users/[email protected]",
+ statusList: [IssueStatus.OPEN],
+ orderBy: "update_time desc",
+ },
+ pageSize: 10,
+ });
+ expect(result).toEqual({
+ project: "projects/sample",
+ issues: [
+ {
+ name: "projects/sample/issues/review",
+ title: "Add customer table",
+ relation: "review",
+ approvalStatus: "PENDING",
+ },
+ {
+ name: "projects/sample/issues/created",
+ title: "Add customer table",
+ relation: "created",
+ approvalStatus: "PENDING",
+ },
+ ],
+ partial: false,
+ });
+ });
+
+ test("refuses to query a chat that is not bound to a Project", async () => {
+ state.listIssues.mockReset();
+
+ const result = JSON.parse(
+ await createProjectOpenIssuesTool({ projectName: "workspaces/default" })()
+ );
+
+ expect(result).toEqual({
+ error: "This starter is not bound to a Project.",
+ });
+ expect(state.listIssues).not.toHaveBeenCalled();
+ });
+
+ test("marks the result partial when either Issue query has another page", async () => {
+ state.listIssues.mockReset();
+ state.listIssues
+ .mockResolvedValueOnce({
+ nextPageToken: "next-review-page",
+ issues: [issue({ name: "projects/sample/issues/review" })],
+ })
+ .mockResolvedValueOnce({
+ nextPageToken: "",
+ issues: [issue({ name: "projects/sample/issues/created" })],
+ });
+
+ const result = JSON.parse(
+ await createProjectOpenIssuesTool({ projectName: "projects/sample" })()
+ );
+
+ expect(result.partial).toBe(true);
+ });
+});
diff --git a/frontend/src/modules/agent/logic/tools/projectOpenIssues.ts b/frontend/src/modules/agent/logic/tools/projectOpenIssues.ts
new file mode 100644
index 0000000000..dbd43105d5
--- /dev/null
+++ b/frontend/src/modules/agent/logic/tools/projectOpenIssues.ts
@@ -0,0 +1,105 @@
+import { useAppStore } from "@/stores/app";
+import { ApprovalStatus, IssueStatus } from "@/types/proto-es/v1/common_pb";
+import type { Issue } from "@/types/proto-es/v1/issue_service_pb";
+
+const PAGE_SIZE = 10;
+
+type ProjectOpenIssue = {
+ name: string;
+ title: string;
+ relation: "review" | "created";
+ approvalStatus: string;
+};
+
+function isProjectName(value: string | undefined): value is string {
+ return !!value && /^projects\/[^/]+$/.test(value);
+}
+
+function summarizeIssue(
+ issue: Issue,
+ relation: ProjectOpenIssue["relation"]
+): ProjectOpenIssue {
+ return {
+ name: issue.name,
+ title: issue.title,
+ relation,
+ approvalStatus: ApprovalStatus[issue.approvalStatus],
+ };
+}
+
+export function createProjectOpenIssuesTool({
+ projectName,
+}: {
+ projectName?: string;
+}) {
+ return async (): Promise<string> => {
+ if (!isProjectName(projectName)) {
+ return JSON.stringify({
+ error: "This starter is not bound to a Project.",
+ });
+ }
+
+ const { currentUser, listIssues } = useAppStore.getState();
+ if (!currentUser?.name) {
+ return JSON.stringify({ error: "The current user is unavailable." });
+ }
+
+ const results = await Promise.allSettled([
+ listIssues({
+ find: {
+ project: projectName,
+ query: "",
+ currentApprover: currentUser.name,
+ statusList: [IssueStatus.OPEN],
+ approvalStatus: ApprovalStatus.PENDING,
+ orderBy: "update_time desc",
+ },
+ pageSize: PAGE_SIZE,
+ }),
+ listIssues({
+ find: {
+ project: projectName,
+ query: "",
+ creator: currentUser.name,
+ statusList: [IssueStatus.OPEN],
+ orderBy: "update_time desc",
+ },
+ pageSize: PAGE_SIZE,
+ }),
+ ]);
+
+ const fulfilledCount = results.filter(
+ (result) => result.status === "fulfilled"
+ ).length;
+ if (!fulfilledCount) {
+ return JSON.stringify({
+ error: "Unable to load open issues for this Project.",
+ });
+ }
+
+ const issues = new Map<string, ProjectOpenIssue>();
+ const pendingReviews =
+ results[0].status === "fulfilled" ? results[0].value.issues : [];
+ const createdIssues =
+ results[1].status === "fulfilled" ? results[1].value.issues : [];
+ for (const issue of pendingReviews) {
+ issues.set(issue.name, summarizeIssue(issue, "review"));
+ }
+ for (const issue of createdIssues) {
+ if (!issues.has(issue.name)) {
+ issues.set(issue.name, summarizeIssue(issue, "created"));
+ }
+ }
+
+ return JSON.stringify({
+ project: projectName,
+ issues: [...issues.values()],
+ partial:
+ fulfilledCount !== results.length ||
+ results.some(
+ (result) =>
+ result.status === "fulfilled" && Boolean(result.value.nextPageToken)
+ ),
+ });
+ };
+}
diff --git a/frontend/src/modules/agent/logic/tools/projectRecentActivity.test.ts b/frontend/src/modules/agent/logic/tools/projectRecentActivity.test.ts
new file mode 100644
index 0000000000..8369a84c87
--- /dev/null
+++ b/frontend/src/modules/agent/logic/tools/projectRecentActivity.test.ts
@@ -0,0 +1,193 @@
+// @vitest-environment node
+import { create } from "@bufbuild/protobuf";
+import { timestampFromMs } from "@bufbuild/protobuf/wkt";
+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
+import { AuditLogSchema } from "@/types/proto-es/v1/audit_log_service_pb";
+
+const mocks = vi.hoisted(() => ({ searchAuditLogs: vi.fn() }));
+
+vi.mock("@/api", () => ({
+ auditLogServiceClientConnect: { searchAuditLogs: mocks.searchAuditLogs },
+}));
+
+import { createProjectRecentActivityTool } from "./projectRecentActivity";
+
+describe("createProjectRecentActivityTool", () => {
+ beforeEach(() => {
+ mocks.searchAuditLogs.mockReset();
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ test("loads a bounded, sanitized summary from the chat-bound Project", async () => {
+ mocks.searchAuditLogs.mockResolvedValue({
+ auditLogs: [
+ create(AuditLogSchema, {
+ createTime: timestampFromMs(Date.UTC(2026, 9, 20, 8)),
+ actor: "users/[email protected]",
+ method: "/bytebase.v1.IssueService/CreateIssue",
+ resource: "projects/orders/issues/42",
+ request: '{"title":"Sensitive request payload"}',
+ response: '{"private":"response payload"}',
+ }),
+ create(AuditLogSchema, {
+ createTime: timestampFromMs(Date.UTC(2026, 9, 20, 7)),
+ actor: "users/[email protected]",
+ method: "/bytebase.v1.UnknownService/UnknownMethod",
+ resource: "projects/orders/resources/1",
+ }),
+ ],
+ nextPageToken: "next-page",
+ });
+
+ const result = JSON.parse(
+ await createProjectRecentActivityTool({
+ projectName: "projects/orders",
+ })()
+ );
+
+ expect(mocks.searchAuditLogs).toHaveBeenCalledWith(
+ expect.objectContaining({
+ parent: "projects/orders",
+ orderBy: "create_time desc",
+ pageSize: 500,
+ })
+ );
+ expect(result).toEqual({
+ project: "projects/orders",
+ events: [
+ {
+ occurredAt: "2026-10-20T08:00:00.000Z",
+ actor: "users/[email protected]",
+ action: "created an Issue",
+ resource: "projects/orders/issues/42",
+ outcome: "succeeded",
+ },
+ ],
+ partial: true,
+ });
+ expect(JSON.stringify(result)).not.toContain("Sensitive request payload");
+ expect(JSON.stringify(result)).not.toContain("response payload");
+ });
+
+ test("rejects an unbound Project without calling the audit API", async () => {
+ const result = JSON.parse(await createProjectRecentActivityTool({})());
+
+ expect(result).toEqual({
+ error: "This starter is not bound to a project.",
+ });
+ expect(mocks.searchAuditLogs).not.toHaveBeenCalled();
+ });
+
+ test("returns at most five events from one bounded audit-log page", async () => {
+ mocks.searchAuditLogs.mockResolvedValue({
+ auditLogs: Array.from({ length: 6 }, (_, index) =>
+ create(AuditLogSchema, {
+ actor: "users/[email protected]",
+ method: "/bytebase.v1.PlanService/CreatePlan",
+ resource: `projects/orders/plans/${index}`,
+ })
+ ),
+ });
+
+ const result = JSON.parse(
+ await createProjectRecentActivityTool({
+ projectName: "projects/orders",
+ })()
+ );
+
+ expect(result.events).toHaveLength(5);
+ expect(result.partial).toBe(true);
+ });
+
+ test("includes project settings, policies, and access changes", async () => {
+ mocks.searchAuditLogs.mockResolvedValue({
+ auditLogs: [
+ create(AuditLogSchema, {
+ actor: "users/[email protected]",
+ method: "/bytebase.v1.ProjectService/UpdateProject",
+ resource: "projects/orders",
+ }),
+ create(AuditLogSchema, {
+ actor: "users/[email protected]",
+ method: "/bytebase.v1.OrgPolicyService/UpdatePolicy",
+ resource: "projects/orders/policies/review",
+ }),
+ create(AuditLogSchema, {
+ actor: "users/[email protected]",
+ method: "/bytebase.v1.ProjectService/SetIamPolicy",
+ resource: "projects/orders",
+ }),
+ ],
+ });
+
+ const result = JSON.parse(
+ await createProjectRecentActivityTool({
+ projectName: "projects/orders",
+ })()
+ );
+
+ expect(result.events).toEqual([
+ expect.objectContaining({ action: "updated project settings" }),
+ expect.objectContaining({ action: "updated a policy" }),
+ expect.objectContaining({ action: "updated project access" }),
+ ]);
+ });
+
+ test("searches the last three days and omits routine audit entries", async () => {
+ vi.useFakeTimers();
+ vi.setSystemTime(new Date("2026-10-20T12:00:00.000Z"));
+ mocks.searchAuditLogs.mockResolvedValue({
+ auditLogs: [
+ create(AuditLogSchema, {
+ actor: "users/[email protected]",
+ method: "/bytebase.v1.SQLService/Query",
+ resource: "instances/prod",
+ }),
+ create(AuditLogSchema, {
+ actor: "users/[email protected]",
+ method: "/bytebase.v1.IssueService/ApproveIssue",
+ resource: "projects/orders/issues/42",
+ }),
+ create(AuditLogSchema, {
+ actor: "users/[email protected]",
+ method: "/bytebase.v1.SettingService/UpdateSetting",
+ resource: "settings/workspace-profile",
+ }),
+ ],
+ });
+
+ const result = JSON.parse(
+ await createProjectRecentActivityTool({
+ projectName: "projects/orders",
+ })()
+ );
+
+ expect(mocks.searchAuditLogs).toHaveBeenCalledWith(
+ expect.objectContaining({
+ filter: "create_time >= '2026-10-17T12:00:00.000Z'",
+ pageSize: 500,
+ })
+ );
+ expect(result.events).toEqual([
+ expect.objectContaining({ action: "approved an Issue" }),
+ expect.objectContaining({ action: "updated a workspace setting" }),
+ ]);
+ });
+
+ test("returns a safe failure when the audit API is unavailable", async () => {
+ mocks.searchAuditLogs.mockRejectedValue(new Error("permission denied"));
+
+ const result = JSON.parse(
+ await createProjectRecentActivityTool({
+ projectName: "projects/orders",
+ })()
+ );
+
+ expect(result).toEqual({
+ error: "Unable to load recent activity.",
+ });
+ });
+});
diff --git a/frontend/src/modules/agent/logic/tools/projectRecentActivity.ts b/frontend/src/modules/agent/logic/tools/projectRecentActivity.ts
new file mode 100644
index 0000000000..3d60faa931
--- /dev/null
+++ b/frontend/src/modules/agent/logic/tools/projectRecentActivity.ts
@@ -0,0 +1,26 @@
+import { getRecentActivity } from "./recentActivity";
+
+function isProjectName(value: string | undefined): value is string {
+ return !!value && /^projects\/[^/]+$/.test(value);
+}
+
+export function createProjectRecentActivityTool({
+ projectName,
+}: {
+ projectName?: string;
+}) {
+ return async (): Promise<string> => {
+ if (!isProjectName(projectName)) {
+ return JSON.stringify({
+ error: "This starter is not bound to a project.",
+ });
+ }
+
+ const result = await getRecentActivity(projectName);
+ const payload = JSON.parse(result) as Record<string, unknown>;
+ if (typeof payload.error === "string") {
+ return result;
+ }
+ return JSON.stringify({ project: projectName, ...payload });
+ };
+}
diff --git a/frontend/src/modules/agent/logic/tools/recentActivity.ts b/frontend/src/modules/agent/logic/tools/recentActivity.ts
new file mode 100644
index 0000000000..78b29f2066
--- /dev/null
+++ b/frontend/src/modules/agent/logic/tools/recentActivity.ts
@@ -0,0 +1,97 @@
+import { create } from "@bufbuild/protobuf";
+import { auditLogServiceClientConnect } from "@/api";
+import { getTimeForPbTimestampProtoEs } from "@/types";
+import {
+ type AuditLog,
+ SearchAuditLogsRequestSchema,
+} from "@/types/proto-es/v1/audit_log_service_pb";
+
+const PAGE_SIZE = 500;
+const MAX_EVENTS = 5;
+const RECENT_ACTIVITY_WINDOW_MS = 3 * 24 * 60 * 60 * 1000;
+
+const actionByMethod: Record<string, string> = {
+ "/bytebase.v1.DatabaseService/CreateDatabase": "created a database",
+ "/bytebase.v1.DatabaseService/UpdateDatabase": "updated a database",
+ "/bytebase.v1.IssueService/CreateIssue": "created an Issue",
+ "/bytebase.v1.IssueService/UpdateIssue": "updated an Issue",
+ "/bytebase.v1.IssueService/CreateIssueComment": "commented on an Issue",
+ "/bytebase.v1.IssueService/UpdateIssueComment": "updated an Issue comment",
+ "/bytebase.v1.IssueService/BatchUpdateIssuesStatus": "updated Issue status",
+ "/bytebase.v1.IssueService/ApproveIssue": "approved an Issue",
+ "/bytebase.v1.IssueService/RejectIssue": "rejected an Issue",
+ "/bytebase.v1.IssueService/RequestIssue": "requested changes to an Issue",
+ "/bytebase.v1.IssueService/RunReview": "ran an Issue review",
+ "/bytebase.v1.PlanService/CreatePlan": "created a plan",
+ "/bytebase.v1.PlanService/UpdatePlan": "updated a plan",
+ "/bytebase.v1.PlanService/RunPlanChecks": "ran plan checks",
+ "/bytebase.v1.PlanService/CancelPlanCheckRun": "canceled plan checks",
+ "/bytebase.v1.ProjectService/UpdateProject": "updated project settings",
+ "/bytebase.v1.ProjectService/SetIamPolicy": "updated project access",
+ "/bytebase.v1.ProjectService/CreateProject": "created a project",
+ "/bytebase.v1.ProjectService/DeleteProject": "deleted a project",
+ "/bytebase.v1.ProjectService/UndeleteProject": "restored a project",
+ "/bytebase.v1.WorkspaceService/UpdateWorkspace": "updated workspace settings",
+ "/bytebase.v1.WorkspaceService/SetIamPolicy": "updated workspace access",
+ "/bytebase.v1.SettingService/UpdateSetting": "updated a workspace setting",
+ "/bytebase.v1.OrgPolicyService/CreatePolicy": "created a policy",
+ "/bytebase.v1.OrgPolicyService/UpdatePolicy": "updated a policy",
+ "/bytebase.v1.OrgPolicyService/DeletePolicy": "deleted a policy",
+ "/bytebase.v1.UserService/CreateUser": "created a user",
+ "/bytebase.v1.UserService/UpdateUser": "updated a user",
+ "/bytebase.v1.UserService/DeleteUser": "deleted a user",
+ "/bytebase.v1.UserService/UndeleteUser": "restored a user",
+ "/bytebase.v1.UserService/UpdateEmail": "updated a user's email",
+ "/bytebase.v1.RoleService/CreateRole": "created a role",
+ "/bytebase.v1.RoleService/UpdateRole": "updated a role",
+ "/bytebase.v1.RoleService/DeleteRole": "deleted a role",
+ "/bytebase.v1.GroupService/CreateGroup": "created a group",
+ "/bytebase.v1.GroupService/UpdateGroup": "updated a group",
+ "/bytebase.v1.GroupService/DeleteGroup": "deleted a group",
+ "/bytebase.v1.RolloutService/CreateRollout": "created a rollout",
+ "/bytebase.v1.RolloutService/BatchRunTasks": "started rollout tasks",
+ "/bytebase.v1.RolloutService/BatchSkipTasks": "skipped rollout tasks",
+ "/bytebase.v1.RolloutService/BatchCancelTaskRuns": "canceled task runs",
+};
+
+function summarizeAuditLog(log: AuditLog) {
+ const timestamp = getTimeForPbTimestampProtoEs(log.createTime);
+ return {
+ ...(timestamp !== undefined
+ ? { occurredAt: new Date(timestamp).toISOString() }
+ : {}),
+ actor: log.actor,
+ action: actionByMethod[log.method] ?? "recorded activity",
+ resource: log.resource,
+ outcome: log.status?.code ? "failed" : "succeeded",
+ };
+}
+
+function isMeaningfulAuditLog(log: AuditLog): boolean {
+ return actionByMethod[log.method] !== undefined;
+}
+
+export async function getRecentActivity(parent: string): Promise<string> {
+ try {
+ const response = await auditLogServiceClientConnect.searchAuditLogs(
+ create(SearchAuditLogsRequestSchema, {
+ parent,
+ filter: `create_time >= '${new Date(
+ Date.now() - RECENT_ACTIVITY_WINDOW_MS
+ ).toISOString()}'`,
+ orderBy: "create_time desc",
+ pageSize: PAGE_SIZE,
+ })
+ );
+ const auditLogs = response.auditLogs ?? [];
+ const meaningfulAuditLogs = auditLogs.filter(isMeaningfulAuditLog);
+ return JSON.stringify({
+ events: meaningfulAuditLogs.slice(0, MAX_EVENTS).map(summarizeAuditLog),
+ partial:
+ Boolean(response.nextPageToken) ||
+ meaningfulAuditLogs.length > MAX_EVENTS,
+ });
+ } catch {
+ return JSON.stringify({ error: "Unable to load recent activity." });
+ }
+}
diff --git a/frontend/src/modules/agent/logic/tools/workspaceAttention.test.ts b/frontend/src/modules/agent/logic/tools/workspaceAttention.test.ts
new file mode 100644
index 0000000000..842b28989b
--- /dev/null
+++ b/frontend/src/modules/agent/logic/tools/workspaceAttention.test.ts
@@ -0,0 +1,100 @@
+// @vitest-environment node
+import { create } from "@bufbuild/protobuf";
+import { beforeEach, describe, expect, test, vi } from "vitest";
+import {
+ IssueSchema,
+ SearchIssuesRequestSchema,
+} from "@/types/proto-es/v1/issue_service_pb";
+
+const mocks = vi.hoisted(() => ({ searchIssues: vi.fn() }));
+
+vi.mock("@/api", () => ({
+ issueServiceClientConnect: { searchIssues: mocks.searchIssues },
+}));
+
+vi.mock("@/stores/app", () => ({
+ useAppStore: {
+ getState: () => ({ currentUser: { name: "users/[email protected]" } }),
+ },
+}));
+
+import { createWorkspaceAttentionTool } from "./workspaceAttention";
+
+describe("createWorkspaceAttentionTool", () => {
+ beforeEach(() => {
+ mocks.searchIssues.mockReset();
+ });
+
+ test("lists the current user's pending approvals and open Issues", async () => {
+ mocks.searchIssues
+ .mockResolvedValueOnce({
+ issues: [
+ create(IssueSchema, {
+ name: "projects/orders/issues/42",
+ title: "Add customer table",
+ }),
+ ],
+ nextPageToken: "next-page",
+ })
+ .mockResolvedValueOnce({
+ issues: [
+ create(IssueSchema, {
+ name: "projects/orders/issues/43",
+ title: "Backfill customer data",
+ }),
+ create(IssueSchema, {
+ name: "projects/orders/issues/42",
+ title: "Add customer table",
+ }),
+ ],
+ nextPageToken: "",
+ });
+
+ await expect(
+ createWorkspaceAttentionTool({ workspaceName: "workspaces/acme" })()
+ ).resolves.toBe(
+ JSON.stringify({
+ issues: [
+ {
+ name: "projects/orders/issues/42",
+ title: "Add customer table",
+ relation: "review",
+ },
+ {
+ name: "projects/orders/issues/43",
+ title: "Backfill customer data",
+ relation: "created",
+ },
+ ],
+ partial: true,
+ })
+ );
+
+ expect(mocks.searchIssues).toHaveBeenNthCalledWith(
+ 1,
+ create(SearchIssuesRequestSchema, {
+ parent: "projects/-",
+ filter:
+ 'current_approver == "users/[email protected]" && approval_status == "PENDING" && status in ["OPEN"]',
+ orderBy: "update_time desc",
+ pageSize: 5,
+ })
+ );
+ expect(mocks.searchIssues).toHaveBeenNthCalledWith(
+ 2,
+ create(SearchIssuesRequestSchema, {
+ parent: "projects/-",
+ filter: 'creator == "users/[email protected]" && status in ["OPEN"]',
+ orderBy: "update_time desc",
+ pageSize: 5,
+ })
+ );
+ });
+
+ test("refuses an unbound workspace without searching Issues", async () => {
+ await expect(createWorkspaceAttentionTool({})()).resolves.toBe(
+ JSON.stringify({ error: "This starter is not bound to a workspace." })
+ );
+ expect(mocks.searchIssues).not.toHaveBeenCalled();
+ });
+});
diff --git a/frontend/src/modules/agent/logic/tools/workspaceAttention.ts b/frontend/src/modules/agent/logic/tools/workspaceAttention.ts
new file mode 100644
index 0000000000..596c978a9d
--- /dev/null
+++ b/frontend/src/modules/agent/logic/tools/workspaceAttention.ts
@@ -0,0 +1,105 @@
+import { create } from "@bufbuild/protobuf";
+import { issueServiceClientConnect } from "@/api";
+import { useAppStore } from "@/stores/app";
+import { buildIssueFilter } from "@/stores/app/issue";
+import { ApprovalStatus, IssueStatus } from "@/types/proto-es/v1/common_pb";
+import { SearchIssuesRequestSchema } from "@/types/proto-es/v1/issue_service_pb";
+
+const PAGE_SIZE = 5;
+
+type WorkspaceAttentionIssue = {
+ name: string;
+ title: string;
+ relation: "review" | "created";
+};
+
+function isWorkspaceName(value: string | undefined): value is string {
+ return !!value && /^workspaces\/[^/]+$/.test(value);
+}
+
+export function createWorkspaceAttentionTool({
+ workspaceName,
+}: {
+ workspaceName?: string;
+}) {
+ return async (): Promise<string> => {
+ if (!isWorkspaceName(workspaceName)) {
+ return JSON.stringify({
+ error: "This starter is not bound to a workspace.",
+ });
+ }
+
+ const currentUser = useAppStore.getState().currentUser;
+ if (!currentUser?.name) {
+ return JSON.stringify({ error: "The current user is unavailable." });
+ }
+
+ const results = await Promise.allSettled([
+ issueServiceClientConnect.searchIssues(
+ create(SearchIssuesRequestSchema, {
+ parent: "projects/-",
+ filter: buildIssueFilter({
+ project: "projects/-",
+ query: "",
+ currentApprover: currentUser.name,
+ statusList: [IssueStatus.OPEN],
+ approvalStatus: ApprovalStatus.PENDING,
+ }),
+ orderBy: "update_time desc",
+ pageSize: PAGE_SIZE,
+ })
+ ),
+ issueServiceClientConnect.searchIssues(
+ create(SearchIssuesRequestSchema, {
+ parent: "projects/-",
+ filter: buildIssueFilter({
+ project: "projects/-",
+ query: "",
+ creator: currentUser.name,
+ statusList: [IssueStatus.OPEN],
+ }),
+ orderBy: "update_time desc",
+ pageSize: PAGE_SIZE,
+ })
+ ),
+ ]);
+ const fulfilled = results.filter((result) => result.status === "fulfilled");
+ if (!fulfilled.length) {
+ return JSON.stringify({
+ error: "Unable to load items needing attention.",
+ });
+ }
+
+ const issues = new Map<string, WorkspaceAttentionIssue>();
+ const pendingReviews =
+ results[0].status === "fulfilled" ? results[0].value.issues : [];
+ const createdIssues =
+ results[1].status === "fulfilled" ? results[1].value.issues : [];
+ for (const issue of pendingReviews) {
+ issues.set(issue.name, {
+ name: issue.name,
+ title: issue.title,
+ relation: "review",
+ });
+ }
+ for (const issue of createdIssues) {
+ if (!issues.has(issue.name)) {
+ issues.set(issue.name, {
+ name: issue.name,
+ title: issue.title,
+ relation: "created",
+ });
+ }
+ }
+
+ return JSON.stringify({
+ issues: [...issues.values()],
+ partial:
+ fulfilled.length !== results.length ||
+ results.some(
+ (result) =>
+ result.status === "fulfilled" && Boolean(result.value.nextPageToken)
+ ),
+ });
+ };
+}
diff --git a/frontend/src/modules/agent/logic/tools/workspaceRecentActivity.test.ts b/frontend/src/modules/agent/logic/tools/workspaceRecentActivity.test.ts
new file mode 100644
index 0000000000..475a3d4f7f
--- /dev/null
+++ b/frontend/src/modules/agent/logic/tools/workspaceRecentActivity.test.ts
@@ -0,0 +1,40 @@
+// @vitest-environment node
+import { beforeEach, describe, expect, test, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({ getRecentActivity: vi.fn() }));
+
+vi.mock("./recentActivity", () => ({
+ getRecentActivity: mocks.getRecentActivity,
+}));
+
+import { createWorkspaceRecentActivityTool } from "./workspaceRecentActivity";
+
+describe("createWorkspaceRecentActivityTool", () => {
+ beforeEach(() => {
+ mocks.getRecentActivity.mockReset();
+ });
+
+ test("uses the workspace-wide project audit scope", async () => {
+ mocks.getRecentActivity.mockResolvedValue(
+ JSON.stringify({ events: [], partial: false })
+ );
+
+ await expect(
+ createWorkspaceRecentActivityTool({ workspaceName: "workspaces/acme" })()
+ ).resolves.toBe(
+ JSON.stringify({
+ workspace: "workspaces/acme",
+ events: [],
+ partial: false,
+ })
+ );
+ expect(mocks.getRecentActivity).toHaveBeenCalledWith("projects/-");
+ });
+
+ test("rejects an unbound workspace without searching audit logs", async () => {
+ await expect(createWorkspaceRecentActivityTool({})()).resolves.toBe(
+ JSON.stringify({ error: "This starter is not bound to a workspace." })
+ );
+ expect(mocks.getRecentActivity).not.toHaveBeenCalled();
+ });
+});
diff --git a/frontend/src/modules/agent/logic/tools/workspaceRecentActivity.ts b/frontend/src/modules/agent/logic/tools/workspaceRecentActivity.ts
new file mode 100644
index 0000000000..401357dc61
--- /dev/null
+++ b/frontend/src/modules/agent/logic/tools/workspaceRecentActivity.ts
@@ -0,0 +1,26 @@
+import { getRecentActivity } from "./recentActivity";
+
+function isWorkspaceName(value: string | undefined): value is string {
+ return !!value && /^workspaces\/[^/]+$/.test(value);
+}
+
+export function createWorkspaceRecentActivityTool({
+ workspaceName,
+}: {
+ workspaceName?: string;
+}) {
+ return async (): Promise<string> => {
+ if (!isWorkspaceName(workspaceName)) {
+ return JSON.stringify({
+ error: "This starter is not bound to a workspace.",
+ });
+ }
+
+ const result = await getRecentActivity("projects/-");
+ const payload = JSON.parse(result) as Record<string, unknown>;
+ if (typeof payload.error === "string") {
+ return result;
+ }
+ return JSON.stringify({ workspace: workspaceName, ...payload });
+ };
+}
diff --git a/frontend/src/modules/agent/logic/types.ts b/frontend/src/modules/agent/logic/types.ts
index 4777f26548..711b19cc81 100644
--- a/frontend/src/modules/agent/logic/types.ts
+++ b/frontend/src/modules/agent/logic/types.ts
@@ -20,6 +20,8 @@ export interface Message {
export type AgentChatStatus = "idle" | "running" | "awaiting_user" | "error";
+export type AgentRunMode = "default" | "read-only";
+
export interface AgentChatSnapshot {
path: string;
title: string;
@@ -44,6 +46,7 @@ export interface AgentChat {
id: string;
title: string;
context?: string;
+ workspaceName?: string;
createdTs: number;
updatedTs: number;
status: AgentChatStatus;
@@ -54,6 +57,7 @@ export interface AgentChat {
requiresAIConfiguration?: boolean;
interrupted?: boolean;
runId?: string | null;
+ runMode?: AgentRunMode;
}
export type AgentAskUserKind = "input" | "confirm" | "choose";
diff --git a/frontend/src/modules/agent/store/agent.test.ts b/frontend/src/modules/agent/store/agent.test.ts
index 6d33bcb900..532636cfdf 100644
--- a/frontend/src/modules/agent/store/agent.test.ts
+++ b/frontend/src/modules/agent/store/agent.test.ts
@@ -6,6 +6,8 @@ import {
AGENT_WINDOW_KEY,
AGENT_WINDOW_LAYOUT_VERSION,
createAgentStore,
+ getAgentStateKey,
+ getAgentWindowKey,
selectLoading,
selectOrderedChats,
} from "./agent";
@@ -91,6 +93,134 @@ describe("useAgentStore (Zustand)", () => {
expect(s(store).chats[0].totalTokensUsed).toBe(0);
});
+ test("keeps chat history in the current workspace cache", () => {
+ const store = createAgentStore();
+ s(store).setWorkspaceName("workspaces/alpha");
+ const alphaChatId = s(store).currentChatId!;
+ s(store).addMessage({
+ chatId: alphaChatId,
+ role: "user",
+ content: "Alpha workspace work",
+ });
+
+ expect(
+ localStorage.getItem(getAgentStateKey("workspaces/alpha"))
+ ).toContain("Alpha workspace work");
+
+ s(store).setWorkspaceName("workspaces/beta");
+ expect(s(store).getMessages(s(store).currentChatId)).toEqual([]);
+
+ s(store).setWorkspaceName("workspaces/alpha");
+ expect(s(store).getMessages(s(store).currentChatId)).toHaveLength(1);
+ expect(s(store).getMessages(s(store).currentChatId)[0]?.content).toBe(
+ "Alpha workspace work"
+ );
+ });
+
+ test("keeps agent window layout in the current workspace cache", () => {
+ const store = createAgentStore();
+ s(store).setWorkspaceName("workspaces/alpha");
+ s(store).setPosition(320, 240);
+ s(store).saveWindowState();
+
+ expect(
+ localStorage.getItem(getAgentWindowKey("workspaces/alpha"))
+ ).toContain('"x":320');
+
+ s(store).setWorkspaceName("workspaces/beta");
+ expect(s(store).position).not.toEqual({ x: 320, y: 240 });
+
+ s(store).setWorkspaceName("workspaces/alpha");
+ expect(s(store).position).toEqual({ x: 320, y: 240 });
+ });
+
+ test("migrates unscoped legacy chats to the first workspace context", () => {
+ localStorage.setItem(
+ AGENT_STATE_KEY,
+ JSON.stringify({
+ currentChatId: "alpha-chat",
+ chats: [
+ {
+ id: "alpha-chat",
+ title: "Alpha",
+ workspaceName: "workspaces/alpha",
+ createdTs: 10,
+ updatedTs: 20,
+ status: "idle",
+ },
+ {
+ id: "beta-chat",
+ title: "Beta",
+ workspaceName: "workspaces/beta",
+ createdTs: 10,
+ updatedTs: 20,
+ status: "idle",
+ },
+ {
+ id: "legacy-chat",
+ title: "Legacy",
+ context: "projects/orders",
+ createdTs: 10,
+ updatedTs: 20,
+ status: "idle",
+ },
+ ],
+ messagesByChatId: {
+ "alpha-chat": [],
+ "beta-chat": [],
+ "legacy-chat": [],
+ },
+ pendingAskByChatId: {},
+ })
+ );
+
+ const store = createAgentStore();
+ s(store).setWorkspaceName("workspaces/alpha");
+
+ expect(s(store).getChat("alpha-chat")).not.toBeNull();
+ expect(s(store).getChat("beta-chat")).toBeNull();
+ expect(s(store).getChat("legacy-chat")).toMatchObject({
+ workspaceName: "workspaces/alpha",
+ context: "workspaces/alpha",
+ });
+
+ s(store).setWorkspaceName("workspaces/beta");
+ expect(s(store).getChat("beta-chat")).not.toBeNull();
+ expect(s(store).getChat("alpha-chat")).toBeNull();
+
+ expect(localStorage.getItem(AGENT_STATE_KEY)).toBeNull();
+ expect(localStorage.getItem(`${AGENT_STATE_KEY}.legacy`)).toBeNull();
+ });
+
+ test("recovers chats stored by the interim unassigned legacy migration", () => {
+ localStorage.setItem(
+ `${AGENT_STATE_KEY}.legacy`,
+ JSON.stringify({
+ currentChatId: "legacy-chat",
+ chats: [
+ {
+ id: "legacy-chat",
+ title: "Legacy",
+ createdTs: 10,
+ updatedTs: 20,
+ status: "idle",
+ },
+ ],
+ messagesByChatId: { "legacy-chat": [] },
+ pendingAskByChatId: {},
+ })
+ );
+
+ const store = createAgentStore();
+ s(store).setWorkspaceName("workspaces/alpha");
+
+ expect(s(store).getChat("legacy-chat")).toMatchObject({
+ workspaceName: "workspaces/alpha",
+ context: "workspaces/alpha",
+ });
+ expect(localStorage.getItem(`${AGENT_STATE_KEY}.legacy`)).toBeNull();
+ });
+
test("takes a queued user message only for its chat and only once", () => {
const store = createAgentStore();
const chat = s(store).createChat({ context: "projects/orders" });
@@ -109,8 +239,122 @@ describe("useAgentStore (Zustand)", () => {
expect(s(store).queuedUserMessage).toBeNull();
});
+ test("reuses an idle chat with the exact landing context", () => {
+ const store = createAgentStore();
+ const chat = s(store).createChat({ context: "projects/orders" });
+ s(store).addMessage({
+ chatId: chat.id,
+ role: "user",
+ content: "Earlier project work",
+ });
+
+ const selected = s(store).selectOrCreateChatForContext("projects/orders", {
+ path: "/projects/orders",
+ title: "Orders",
+ });
+
+ expect(selected?.id).toBe(chat.id);
+ expect(s(store).currentChatId).toBe(chat.id);
+ expect(s(store).chats).toHaveLength(2);
+ expect(s(store).getChat(chat.id)?.page).toEqual({
+ path: "/projects/orders",
+ title: "Orders",
+ });
+ });
+
+ test("does not reuse a project chat from another workspace", () => {
+ const store = createAgentStore();
+ const first = s(store).selectOrCreateChatForContext(
+ "projects/orders",
+ undefined,
+ "workspaces/alpha"
+ );
+
+ const second = s(store).selectOrCreateChatForContext(
+ "projects/orders",
+ undefined,
+ "workspaces/beta"
+ );
+
+ expect(first?.id).not.toBe(second?.id);
+ expect(s(store).getChat(second?.id)?.workspaceName).toBe("workspaces/beta");
+ s(store).setWorkspaceName("workspaces/alpha");
+ expect(s(store).getChat(first?.id)?.workspaceName).toBe("workspaces/alpha");
+ });
+
+ test("prefers the current chat when it has the exact landing context", () => {
+ const store = createAgentStore();
+ const current = s(store).createChat({ context: "projects/orders" });
+ s(store).addMessage({
+ chatId: current.id,
+ role: "user",
+ content: "Continue this work",
+ });
+ const other = s(store).createChat({ context: "projects/orders" });
+ s(store).addMessage({
+ chatId: other.id,
+ role: "user",
+ content: "A separate conversation",
+ });
+ s(store).setCurrentChat(current.id);
+
+ const selected = s(store).selectOrCreateChatForContext("projects/orders");
+
+ expect(selected?.id).toBe(current.id);
+ expect(s(store).currentChatId).toBe(current.id);
+ });
+
+ test("does not reuse a chat that needs attention", () => {
+ const store = createAgentStore();
+ const unavailable = s(store).createChat({
+ context: "projects/orders",
+ });
+ s(store).setChatStatus(unavailable.id, "error");
+
+ const selected = s(store).selectOrCreateChatForContext("projects/orders");
+
+ expect(selected?.id).not.toBe(unavailable.id);
+ expect(selected?.context).toBe("projects/orders");
+ expect(s(store).chats).toHaveLength(3);
+ });
+
+ test("selects an existing matching context without changing another chat", () => {
+ const store = createAgentStore();
+ const orders = s(store).createChat({ context: "projects/orders" });
+ s(store).addMessage({
+ chatId: orders.id,
+ role: "user",
+ content: "Orders work",
+ });
+ const billing = s(store).createChat({ context: "projects/billing" });
+ s(store).addMessage({
+ chatId: billing.id,
+ role: "user",
+ content: "Billing work",
+ });
+
+ const selected = s(store).selectOrCreateChatForContext("projects/orders");
+
+ expect(selected?.id).toBe(orders.id);
+ expect(s(store).currentChatId).toBe(orders.id);
+ expect(s(store).getChat(billing.id)?.context).toBe("projects/billing");
+ expect(s(store).chats).toHaveLength(3);
+ });
+
+ test("binds an empty unscoped chat before creating a landing chat", () => {
+ const store = createAgentStore();
+ const emptyChatId = s(store).currentChatId!;
+
+ const selected = s(store).selectOrCreateChatForContext("workspaces/demo");
+
+ expect(selected?.id).toBe(emptyChatId);
+ expect(s(store).getChat(emptyChatId)?.context).toBe("workspaces/demo");
+ expect(s(store).chats).toHaveLength(1);
+ });
+
test("keeps a chat's resource context when its page changes and after reload", () => {
const store = createAgentStore();
+ s(store).setWorkspaceName("workspaces/acme");
const chat = s(store).createChat({ context: "projects/orders" });
s(store).updateChatPage(chat.id, {
@@ -119,13 +363,16 @@ describe("useAgentStore (Zustand)", () => {
});
expect(s(store).getChat(chat.id)?.context).toBe("projects/orders");
- expect(s(createAgentStore()).getChat(chat.id)?.context).toBe(
+ const rehydratedStore = createAgentStore();
+ s(rehydratedStore).setWorkspaceName("workspaces/acme");
+ expect(s(rehydratedStore).getChat(chat.id)?.context).toBe(
"projects/orders"
);
});
- test("binds only an empty legacy chat when a context is supplied", () => {
+ test("binds a context only to an empty chat created before the context was available", () => {
const store = createAgentStore();
+ s(store).setWorkspaceName("workspaces/acme");
const emptyChatId = s(store).currentChatId!;
s(store).ensureCurrentChat(undefined, "workspaces/demo");
@@ -139,10 +386,14 @@ describe("useAgentStore (Zustand)", () => {
});
s(store).ensureCurrentChat(undefined, "projects/orders");
expect(s(store).getChat(legacy.id)?.context).toBeUndefined();
+ const rehydratedStore = createAgentStore();
+ s(rehydratedStore).setWorkspaceName("workspaces/acme");
+ expect(s(rehydratedStore).getChat(legacy.id)?.context).toBeUndefined();
});
test("changes the context of an empty chat without creating another chat", () => {
const store = createAgentStore();
+ s(store).setWorkspaceName("workspaces/acme");
const chat = s(store).ensureCurrentChat(undefined, "projects/orders");
const selected = s(store).selectChatContext("workspaces/demo");
@@ -150,12 +401,14 @@ describe("useAgentStore (Zustand)", () => {
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(
+ const rehydratedStore = createAgentStore();
+ s(rehydratedStore).setWorkspaceName("workspaces/acme");
+ expect(s(rehydratedStore).getChat(chat.id)?.context).toBe(
"workspaces/demo"
);
});
- test("changes the context of a populated chat without losing its history", () => {
+ test("changes the context of a populated bound chat", () => {
const store = createAgentStore();
const original = s(store).ensureCurrentChat(undefined, "projects/orders");
s(store).addMessage({
@@ -173,6 +426,7 @@ describe("useAgentStore (Zustand)", () => {
expect(selected?.context).toBe("projects/billing");
expect(s(store).chats).toHaveLength(1);
expect(s(store).currentChatId).toBe(original.id);
+ expect(s(store).getChat(original.id)?.context).toBe("projects/billing");
expect(s(store).getMessages(original.id)).toHaveLength(1);
});
@@ -213,8 +467,8 @@ describe("useAgentStore (Zustand)", () => {
const store = createAgentStore();
- expect(s(store).size).toEqual({ width: 605, height: 451 });
- expect(s(store).position).toEqual({ x: 819, y: 433 });
+ expect(s(store).size).toEqual({ width: 750, height: 521 });
+ expect(s(store).position).toEqual({ x: 674, y: 363 });
expect(s(store).sidebarWidth).toBe(200);
});
@@ -240,13 +494,14 @@ describe("useAgentStore (Zustand)", () => {
);
const store = createAgentStore();
+ s(store).setWorkspaceName("workspaces/acme");
- expect(s(store).position).toEqual({ x: 819, y: 433 });
- expect(s(store).size).toEqual({ width: 605, height: 451 });
+ expect(s(store).position).toEqual({ x: 674, y: 363 });
+ expect(s(store).size).toEqual({ width: 750, height: 521 });
expect(s(store).sidebarWidth).toBe(280);
- expect(localStorage.getItem(AGENT_WINDOW_KEY)).toContain(
- `"layoutVersion":${AGENT_WINDOW_LAYOUT_VERSION}`
- );
+ expect(
+ localStorage.getItem(getAgentWindowKey("workspaces/acme"))
+ ).toContain(`"layoutVersion":${AGENT_WINDOW_LAYOUT_VERSION}`);
});
test("loads persisted window state from the current layout version", () => {
@@ -261,16 +516,21 @@ describe("useAgentStore (Zustand)", () => {
);
const store = createAgentStore();
+ s(store).setWorkspaceName("workspaces/acme");
s(store).loadWindowState();
expect(s(store).sidebarWidth).toBe(280);
expect(s(store).position).toEqual({ x: 120, y: 240 });
expect(s(store).size).toEqual({ width: 480, height: 640 });
- expect(localStorage.getItem(AGENT_WINDOW_KEY)).toContain('"width":480');
- expect(localStorage.getItem(AGENT_WINDOW_KEY)).toContain(
- '"sidebarWidth":280'
- );
- expect(localStorage.getItem(AGENT_STATE_KEY)).not.toBeNull();
+ expect(
+ localStorage.getItem(getAgentWindowKey("workspaces/acme"))
+ ).toContain('"width":480');
+ expect(
+ localStorage.getItem(getAgentWindowKey("workspaces/acme"))
+ ).toContain('"sidebarWidth":280');
+ expect(
+ localStorage.getItem(getAgentStateKey("workspaces/acme"))
+ ).not.toBeNull();
});
test("keeps persisted position when opening the agent", () => {
@@ -286,6 +546,7 @@ describe("useAgentStore (Zustand)", () => {
);
const store = createAgentStore();
+ s(store).setWorkspaceName("workspaces/acme");
s(store).toggle();
@@ -322,7 +583,7 @@ describe("useAgentStore (Zustand)", () => {
test("normalizes stale running chats on load", () => {
localStorage.setItem(
- AGENT_STATE_KEY,
+ getAgentStateKey("workspaces/acme"),
JSON.stringify({
currentChatId: "thread-1",
chats: [
@@ -351,6 +612,7 @@ describe("useAgentStore (Zustand)", () => {
);
const store = createAgentStore();
+ s(store).setWorkspaceName("workspaces/acme");
const chat = s(store).getChat(s(store).currentChatId);
expect(chat).not.toBeNull();
@@ -383,6 +645,7 @@ describe("useAgentStore (Zustand)", () => {
test("persists the selected chat across store reloads", () => {
const store = createAgentStore();
+ s(store).setWorkspaceName("workspaces/acme");
const firstChatId = s(store).currentChatId!;
s(store).addMessage({
@@ -400,6 +663,7 @@ describe("useAgentStore (Zustand)", () => {
s(store).setCurrentChat(secondChat.id);
const rehydratedStore = createAgentStore();
+ s(rehydratedStore).setWorkspaceName("workspaces/acme");
expect(s(rehydratedStore).currentChatId).toBe(secondChat.id);
expect(s(rehydratedStore).getMessages(firstChatId)).toHaveLength(1);
expect(s(rehydratedStore).getChat(secondChat.id)?.page).toEqual({
@@ -410,7 +674,7 @@ describe("useAgentStore (Zustand)", () => {
test("preserves a cleared current chat across store reloads", () => {
localStorage.setItem(
- AGENT_STATE_KEY,
+ getAgentStateKey("workspaces/acme"),
JSON.stringify({
currentChatId: null,
chats: [
@@ -431,6 +695,7 @@ describe("useAgentStore (Zustand)", () => {
);
const store = createAgentStore();
+ s(store).setWorkspaceName("workspaces/acme");
expect(s(store).chats).toHaveLength(1);
expect(s(store).getChat("thread-1")).not.toBeNull();
@@ -439,6 +704,7 @@ describe("useAgentStore (Zustand)", () => {
test("increments and persists chat token totals", () => {
const store = createAgentStore();
+ s(store).setWorkspaceName("workspaces/acme");
const chatId = s(store).currentChatId!;
s(store).incrementChatTotalTokens(chatId, 120);
@@ -447,6 +713,7 @@ describe("useAgentStore (Zustand)", () => {
expect(s(store).getChat(chatId)?.totalTokensUsed).toBe(150);
const rehydratedStore = createAgentStore();
+ s(rehydratedStore).setWorkspaceName("workspaces/acme");
expect(s(rehydratedStore).getChat(chatId)?.totalTokensUsed).toBe(150);
});
@@ -554,6 +821,7 @@ describe("useAgentStore (Zustand)", () => {
test("persists pending choose asks for awaiting-user chats", () => {
const store = createAgentStore();
+ s(store).setWorkspaceName("workspaces/acme");
const chatId = s(store).currentChatId!;
s(store).awaitUser(chatId, {
@@ -575,6 +843,7 @@ describe("useAgentStore (Zustand)", () => {
});
const rehydratedStore = createAgentStore();
+ s(rehydratedStore).setWorkspaceName("workspaces/acme");
expect(s(rehydratedStore).getChat(chatId)?.status).toBe("awaiting_user");
expect(s(rehydratedStore).getPendingAsk(chatId)).toEqual({
toolCallId: "tool-1",
@@ -599,7 +868,7 @@ describe("useAgentStore (Zustand)", () => {
test("normalizes invalid persisted choose asks to input", () => {
localStorage.setItem(
- AGENT_STATE_KEY,
+ getAgentStateKey("workspaces/acme"),
JSON.stringify({
currentChatId: "thread-1",
chats: [
@@ -626,6 +895,7 @@ describe("useAgentStore (Zustand)", () => {
);
const store = createAgentStore();
+ s(store).setWorkspaceName("workspaces/acme");
expect(s(store).getPendingAsk("thread-1")).toEqual({
toolCallId: "tool-1",
@@ -702,7 +972,7 @@ describe("useAgentStore (Zustand)", () => {
test("migrates persisted chats without archived state", () => {
localStorage.setItem(
- AGENT_STATE_KEY,
+ getAgentStateKey("workspaces/acme"),
JSON.stringify({
currentChatId: "thread-1",
chats: [
@@ -722,6 +992,7 @@ describe("useAgentStore (Zustand)", () => {
);
const store = createAgentStore();
+ s(store).setWorkspaceName("workspaces/acme");
expect(s(store).getChat("thread-1")?.archived).toBe(false);
});
diff --git a/frontend/src/modules/agent/store/agent.ts b/frontend/src/modules/agent/store/agent.ts
index 7d4bba3f09..a62cd0a808 100644
--- a/frontend/src/modules/agent/store/agent.ts
+++ b/frontend/src/modules/agent/store/agent.ts
@@ -1,6 +1,8 @@
import { v4 as uuidv4 } from "uuid";
import { create } from "zustand";
import { immer } from "zustand/middleware/immer";
+import { getResourceId, workspaceNamePrefix } from "@/lib/resourceName";
+import type { LandingStarterId } from "../logic/landingStarters";
import type {
AgentAskUserResponse,
AgentChat,
@@ -8,6 +10,7 @@ import type {
AgentChatStatus,
AgentMessage,
AgentPendingAsk,
+ AgentRunMode,
Message,
ToolCall,
} from "../logic/types";
@@ -18,7 +21,22 @@ import {
export const AGENT_STATE_KEY = "bb-agent-state-v2";
export const AGENT_WINDOW_KEY = "bb-agent-window";
-export const AGENT_WINDOW_LAYOUT_VERSION = 3;
+export const AGENT_WINDOW_LAYOUT_VERSION = 4;
+
+const getWorkspaceStorageKey = (key: string, workspaceName: string) => {
+ const workspaceId = getResourceId(workspaceName, workspaceNamePrefix);
+ return workspaceId ? `${key}.${workspaceId}` : null;
+};
+
+export const getAgentStateKey = (workspaceName: string) =>
+ getWorkspaceStorageKey(AGENT_STATE_KEY, workspaceName) ?? AGENT_STATE_KEY;
+
+export const getAgentWindowKey = (workspaceName: string) =>
+ getWorkspaceStorageKey(AGENT_WINDOW_KEY, workspaceName) ?? AGENT_WINDOW_KEY;
+
+// This key was used briefly while workspace-scoped persistence was introduced.
+// Read it as a migration source so those chats remain recoverable.
+const UNASSIGNED_LEGACY_AGENT_STATE_KEY = `${AGENT_STATE_KEY}.legacy`;
interface PersistedAgentState {
currentChatId: string | null;
@@ -30,6 +48,7 @@ interface PersistedAgentState {
interface CreateChatOptions {
page?: AgentChatSnapshot;
context?: string;
+ workspaceName?: string;
select?: boolean;
title?: string;
archived?: boolean;
@@ -44,6 +63,8 @@ interface QueuedUserMessage {
chatId: string;
text: string;
page: AgentChatSnapshot;
+ runMode?: AgentRunMode;
+ starterId?: LandingStarterId;
}
const DEFAULT_CHAT_STATUS: AgentChatStatus = "idle";
@@ -56,6 +77,7 @@ const createChatRecord = (options: CreateChatOptions = {}): AgentChat => {
id: uuidv4(),
title: options.title ?? "",
context: options.context,
+ workspaceName: options.workspaceName,
createdTs: now,
updatedTs: now,
status: DEFAULT_CHAT_STATUS,
@@ -201,6 +223,10 @@ const normalizeChat = (raw: unknown): AgentChat => {
typeof chat.context === "string" && chat.context.trim()
? chat.context
: undefined,
+ workspaceName:
+ typeof chat.workspaceName === "string" && chat.workspaceName.trim()
+ ? chat.workspaceName
+ : undefined,
createdTs: typeof chat.createdTs === "number" ? chat.createdTs : now,
updatedTs: typeof chat.updatedTs === "number" ? chat.updatedTs : now,
status,
@@ -229,6 +255,10 @@ const normalizeChat = (raw: unknown): AgentChat => {
requiresAIConfiguration: Boolean(chat.requiresAIConfiguration),
interrupted: Boolean(chat.interrupted),
runId: typeof chat.runId === "string" ? chat.runId : null,
+ runMode:
+ chat.runMode === "read-only" || chat.runMode === "default"
+ ? chat.runMode
+ : undefined,
};
};
@@ -349,6 +379,7 @@ export interface AgentState {
minimized: boolean;
// Chat state
+ workspaceName: string | null;
chats: AgentChat[];
messagesByChatId: Record<string, AgentMessage[]>;
pendingAskByChatId: Record<string, AgentPendingAsk>;
@@ -371,10 +402,20 @@ export interface AgentState {
queueUserMessage: (message: QueuedUserMessage) => void;
takeQueuedUserMessage: (chatId: string) => QueuedUserMessage | null;
finishQueuedUserMessage: (chatId: string) => void;
- ensureCurrentChat: (page?: AgentChatSnapshot, context?: string) => AgentChat;
+ ensureCurrentChat: (
+ page?: AgentChatSnapshot,
+ context?: string,
+ workspaceName?: string
+ ) => AgentChat;
selectChatContext: (
context: string,
- page?: AgentChatSnapshot
+ page?: AgentChatSnapshot,
+ workspaceName?: string
+ ) => AgentChat | null;
+ selectOrCreateChatForContext: (
+ context: string,
+ page?: AgentChatSnapshot,
+ workspaceName?: string
) => AgentChat | null;
setCurrentChat: (chatId: string) => void;
clearCurrentChat: () => void;
@@ -413,7 +454,7 @@ export interface AgentState {
startChatRun: (
chatId: string,
page?: AgentChatSnapshot,
- options?: { runId?: string }
+ options?: { runId?: string; runMode?: AgentRunMode }
) => void;
finishChatRun: (
chatId: string,
@@ -456,6 +497,7 @@ export interface AgentState {
clearError: (chatId?: string | null) => void;
// Persistence
+ setWorkspaceName: (workspaceName?: string) => boolean;
saveWindowState: () => void;
loadWindowState: () => void;
saveState: () => void;
@@ -549,49 +591,164 @@ const getInitialWindowState = () => {
return getDefaultAgentWindowState(window.innerWidth, window.innerHeight);
};
-const loadInitialState = (): {
- chats: AgentChat[];
- messagesByChatId: Record<string, AgentMessage[]>;
- pendingAskByChatId: Record<string, AgentPendingAsk>;
- currentChatId: string | null;
-} => {
- const storage = getSafeStorage();
- const saved = storage?.getItem(AGENT_STATE_KEY);
- let state: PersistedAgentState | null = null;
-
- if (saved) {
- try {
- state = normalizePersistedState(JSON.parse(saved));
- } catch {
- storage?.removeItem(AGENT_STATE_KEY);
- }
- }
-
+const ensureCurrentChat = (state: PersistedAgentState): PersistedAgentState => {
if (
- state &&
- (state.currentChatId === null
+ state.currentChatId === null
? state.chats.length > 0
- : state.chats.some((c) => c.id === state.currentChatId))
+ : state.chats.some((chat) => chat.id === state.currentChatId)
) {
return state;
}
- // Need a default chat
- const chats = state?.chats ?? [];
- const messagesByChatId = state?.messagesByChatId ?? {};
- const pendingAskByChatId = state?.pendingAskByChatId ?? {};
const defaultChat = createChatRecord();
- chats.push(defaultChat);
- messagesByChatId[defaultChat.id] = [];
+ return {
+ ...state,
+ chats: [...state.chats, defaultChat],
+ messagesByChatId: {
+ ...state.messagesByChatId,
+ [defaultChat.id]: [],
+ },
+ currentChatId: defaultChat.id,
+ };
+};
+
+const readPersistedState = (
+ storage: Storage | null,
+ key: string
+): PersistedAgentState | null => {
+ const saved = storage?.getItem(key);
+ if (!saved) return null;
+ try {
+ return normalizePersistedState(JSON.parse(saved));
+ } catch {
+ storage?.removeItem(key);
+ return null;
+ }
+};
+const getPersistedState = (storage: Storage | null, key: string) =>
+ ensureCurrentChat(
+ readPersistedState(storage, key) ?? createEmptyPersistedState()
+ );
+
+const getPersistedStateForChats = (
+ state: PersistedAgentState,
+ chats: AgentChat[]
+): PersistedAgentState => {
+ const chatIds = new Set(chats.map((chat) => chat.id));
return {
+ currentChatId: chatIds.has(state.currentChatId ?? "")
+ ? state.currentChatId
+ : (chats[0]?.id ?? null),
+ chats,
+ messagesByChatId: Object.fromEntries(
+ chats.map((chat) => [chat.id, state.messagesByChatId[chat.id] ?? []])
+ ),
+ pendingAskByChatId: Object.fromEntries(
+ chats.flatMap((chat) => {
+ const pendingAsk = state.pendingAskByChatId[chat.id];
+ return pendingAsk ? [[chat.id, pendingAsk]] : [];
+ })
+ ),
+ };
+};
+
+const mergePersistedStates = (
+ existing: PersistedAgentState | null,
+ incoming: PersistedAgentState
+) => {
+ if (!existing) return incoming;
+ const chatsById = new Map(existing.chats.map((chat) => [chat.id, chat]));
+ for (const chat of incoming.chats) {
+ const current = chatsById.get(chat.id);
+ if (!current || current.updatedTs < chat.updatedTs) {
+ chatsById.set(chat.id, chat);
+ }
+ }
+ const chats = [...chatsById.values()];
+ const messagesByChatId = {
+ ...existing.messagesByChatId,
+ ...incoming.messagesByChatId,
+ };
+ const pendingAskByChatId = {
+ ...existing.pendingAskByChatId,
+ ...incoming.pendingAskByChatId,
+ };
+ return {
+ currentChatId:
+ existing.currentChatId && chatsById.has(existing.currentChatId)
+ ? existing.currentChatId
+ : incoming.currentChatId,
chats,
messagesByChatId,
pendingAskByChatId,
- currentChatId: defaultChat.id,
};
};
+const migrateLegacyState = (
+ storage: Storage | null,
+ fallbackWorkspaceName: string
+) => {
+ if (!storage) return;
+ const sourceKeys = [AGENT_STATE_KEY, UNASSIGNED_LEGACY_AGENT_STATE_KEY];
+ const legacyState = sourceKeys
+ .map((key) => readPersistedState(storage, key))
+ .reduce<PersistedAgentState | null>(
+ (state, next) => (next ? mergePersistedStates(state, next) : state),
+ null
+ );
+ if (!legacyState) return;
+
+ const chatsByWorkspace = new Map<string, AgentChat[]>();
+ for (const chat of legacyState.chats) {
+ const key = chat.workspaceName
+ ? getWorkspaceStorageKey(AGENT_STATE_KEY, chat.workspaceName)
+ : null;
+ if (!key) {
+ const fallbackKey = getWorkspaceStorageKey(
+ AGENT_STATE_KEY,
+ fallbackWorkspaceName
+ );
+ if (!fallbackKey) return;
+ const chats = chatsByWorkspace.get(fallbackKey) ?? [];
+ // Legacy state has no trustworthy project-to-workspace association.
+ chats.push({
+ ...chat,
+ workspaceName: fallbackWorkspaceName,
+ context: fallbackWorkspaceName,
+ });
+ chatsByWorkspace.set(fallbackKey, chats);
+ } else {
+ const chats = chatsByWorkspace.get(key) ?? [];
+ chats.push(chat);
+ chatsByWorkspace.set(key, chats);
+ }
+ }
+
+ try {
+ for (const [key, chats] of chatsByWorkspace) {
+ const incoming = getPersistedStateForChats(legacyState, chats);
+ const existing = readPersistedState(storage, key);
+ storage.setItem(
+ key,
+ JSON.stringify(mergePersistedStates(existing, incoming))
+ );
+ }
+ for (const key of sourceKeys) storage.removeItem(key);
+ } catch {
+ // Keep the source cache until every target cache has been written.
+ }
+};
+
+const loadInitialState = (): {
+ chats: AgentChat[];
+ messagesByChatId: Record<string, AgentMessage[]>;
+ pendingAskByChatId: Record<string, AgentPendingAsk>;
+ currentChatId: string | null;
+} => {
+ return ensureCurrentChat(createEmptyPersistedState());
+};
+
export const createAgentStore = () => {
const initial = loadInitialState();
const initialWindowState = getInitialWindowState();
@@ -626,6 +783,7 @@ export const createAgentStore = () => {
minimized: false,
// Chat state (from persisted/initial)
+ workspaceName: null,
chats: initial.chats,
messagesByChatId: initial.messagesByChatId,
pendingAskByChatId: initial.pendingAskByChatId,
@@ -781,25 +939,21 @@ export const createAgentStore = () => {
state.queuedUserMessageInFlight = false;
}),
- ensureCurrentChat: (page, context) => {
+ ensureCurrentChat: (page, context, workspaceName) => {
const existing = _getChat(get().currentChatId);
if (existing) {
- if (
- (page && !existing.page) ||
- (context &&
- !existing.context &&
- get().getMessages(existing.id).length === 0)
- ) {
+ const canBindContext =
+ Boolean(context) &&
+ !existing.context &&
+ get().getMessages(existing.id).length === 0;
+ if ((page && !existing.page) || canBindContext) {
set((state) => {
const chat = state.chats.find((c) => c.id === existing.id);
if (chat) {
if (page && !chat.page) chat.page = page;
- if (
- context &&
- !chat.context &&
- !state.messagesByChatId[chat.id]?.length
- ) {
+ if (canBindContext && context) {
chat.context = context;
+ chat.workspaceName = workspaceName;
}
_touchChatInDraft(state.chats, chat.id);
}
@@ -807,25 +961,105 @@ export const createAgentStore = () => {
}
return _getChat(existing.id)!;
}
- return get().createChat({ page, context });
+ return get().createChat({ page, context, workspaceName });
},
- selectChatContext: (context, page) => {
- if (!context || _hasRunningChat()) return null;
+ selectChatContext: (context, page, workspaceName) => {
+ if (!context) return null;
+ if (
+ workspaceName &&
+ get().workspaceName !== workspaceName &&
+ !get().setWorkspaceName(workspaceName)
+ ) {
+ return null;
+ }
+ if (_hasRunningChat()) return null;
const current = _getChat(get().currentChatId);
- if (!current) return get().createChat({ page, context });
- if (current.context === context) return current;
+ if (!current)
+ return get().createChat({ page, context, workspaceName });
+ if (
+ current.context === context &&
+ current.workspaceName === workspaceName
+ ) {
+ return current;
+ }
if (get().getPendingAsk(current.id)) return null;
set((state) => {
const chat = state.chats.find((c) => c.id === current.id);
if (chat) {
chat.context = context;
+ chat.workspaceName = workspaceName;
_touchChatInDraft(state.chats, chat.id);
}
});
return _getChat(current.id);
},
+ selectOrCreateChatForContext: (context, page, workspaceName) => {
+ if (!context || _hasRunningChat() || get().queuedUserMessage) {
+ return null;
+ }
+ if (
+ workspaceName &&
+ get().workspaceName !== workspaceName &&
+ !get().setWorkspaceName(workspaceName)
+ ) {
+ return null;
+ }
+
+ const isReusable = (chat: AgentChat) =>
+ !chat.archived &&
+ chat.status === "idle" &&
+ !get().getPendingAsk(chat.id);
+ const current = _getChat(get().currentChatId);
+ const matchingChat =
+ current?.context === context &&
+ current.workspaceName === workspaceName &&
+ isReusable(current)
+ ? current
+ : [...get().chats]
+ .filter(
+ (chat) =>
+ chat.context === context &&
+ chat.workspaceName === workspaceName &&
+ isReusable(chat)
+ )
+ .sort(
+ (a, b) =>
+ b.updatedTs - a.updatedTs || b.createdTs - a.createdTs
+ )[0];
+
+ if (matchingChat) {
+ set((state) => {
+ const chat = state.chats.find((c) => c.id === matchingChat.id);
+ if (!chat) return;
+ if (page) chat.page = page;
+ state.currentChatId = chat.id;
+ _touchChatInDraft(state.chats, chat.id);
+ });
+ return _getChat(matchingChat.id);
+ }
+
+ if (
+ current &&
+ !current.context &&
+ isReusable(current) &&
+ get().getMessages(current.id).length === 0
+ ) {
+ set((state) => {
+ const chat = state.chats.find((c) => c.id === current.id);
+ if (!chat) return;
+ chat.context = context;
+ chat.workspaceName = workspaceName;
+ if (page) chat.page = page;
+ _touchChatInDraft(state.chats, chat.id);
+ });
+ return _getChat(current.id);
+ }
+
+ return get().createChat({ context, page, workspaceName });
+ },
+
setCurrentChat: (chatId) => {
if (get().canSelectChat(chatId)) {
set((state) => {
@@ -1097,6 +1331,7 @@ export const createAgentStore = () => {
const chat = state.chats.find((c) => c.id === chatId);
if (chat) {
chat.runId = options.runId ?? chat.runId ?? null;
+ chat.runMode = options.runMode;
}
});
},
@@ -1111,6 +1346,7 @@ export const createAgentStore = () => {
const chat = state.chats.find((c) => c.id === chatId);
if (chat) {
chat.runId = null;
+ chat.runMode = undefined;
}
});
},
@@ -1204,12 +1440,47 @@ export const createAgentStore = () => {
},
// Persistence
+ setWorkspaceName: (workspaceName) => {
+ if (!workspaceName || get().workspaceName === workspaceName) {
+ return Boolean(workspaceName);
+ }
+ if (_hasRunningChat() || get().queuedUserMessage) {
+ return false;
+ }
+ const stateKey = getWorkspaceStorageKey(
+ AGENT_STATE_KEY,
+ workspaceName
+ );
+ if (!stateKey) return false;
+
+ get().saveState();
+ const storage = getSafeStorage();
+ migrateLegacyState(storage, workspaceName);
+ const persistedState = getPersistedState(storage, stateKey);
+ set((draft) => {
+ draft.workspaceName = workspaceName;
+ draft.chats = persistedState.chats;
+ draft.messagesByChatId = persistedState.messagesByChatId;
+ draft.pendingAskByChatId = persistedState.pendingAskByChatId;
+ draft.currentChatId = persistedState.currentChatId;
+ draft.abortControllersByChatId = {};
+ draft.queuedUserMessage = null;
+ draft.queuedUserMessageInFlight = false;
+ });
+ get().loadWindowState();
+ return true;
+ },
+
saveWindowState: () => {
const storage = getSafeStorage();
- if (!storage) return;
+ const workspaceName = get().workspaceName;
+ const key = workspaceName
+ ? getWorkspaceStorageKey(AGENT_WINDOW_KEY, workspaceName)
+ : null;
+ if (!storage || !key) return;
const state = get();
storage.setItem(
- AGENT_WINDOW_KEY,
+ key,
JSON.stringify({
layoutVersion: AGENT_WINDOW_LAYOUT_VERSION,
position: state.position,
@@ -1221,8 +1492,22 @@ export const createAgentStore = () => {
loadWindowState: () => {
const storage = getSafeStorage();
- const saved = storage?.getItem(AGENT_WINDOW_KEY);
- if (!saved) return;
+ const workspaceName = get().workspaceName;
+ const key = workspaceName
+ ? getWorkspaceStorageKey(AGENT_WINDOW_KEY, workspaceName)
+ : null;
+ if (!key) return;
+ const saved =
+ storage?.getItem(key) ?? storage?.getItem(AGENT_WINDOW_KEY);
+ if (!saved) {
+ const defaultWindowState = getInitialWindowState();
+ set((draft) => {
+ draft.position = defaultWindowState.position;
+ draft.size = defaultWindowState.size;
+ draft.sidebarWidth = defaultWindowState.sidebarWidth;
+ });
+ return;
+ }
try {
const state = JSON.parse(saved) as {
layoutVersion?: number;
@@ -1261,15 +1546,21 @@ export const createAgentStore = () => {
draft.sidebarWidth = state.sidebarWidth;
}
});
- if (!isCurrentLayout) get().saveWindowState();
+ if (!isCurrentLayout || !storage?.getItem(key)) {
+ get().saveWindowState();
+ }
} catch {
- storage?.removeItem(AGENT_WINDOW_KEY);
+ storage?.removeItem(key);
}
},
saveState: () => {
const storage = getSafeStorage();
- if (!storage) return;
+ const workspaceName = get().workspaceName;
+ const key = workspaceName
+ ? getWorkspaceStorageKey(AGENT_STATE_KEY, workspaceName)
+ : null;
+ if (!storage || !key) return;
const state = get();
const persistedState: PersistedAgentState = {
currentChatId: state.currentChatId,
@@ -1277,39 +1568,23 @@ export const createAgentStore = () => {
messagesByChatId: state.messagesByChatId,
pendingAskByChatId: state.pendingAskByChatId,
};
- storage.setItem(AGENT_STATE_KEY, JSON.stringify(persistedState));
+ storage.setItem(key, JSON.stringify(persistedState));
},
loadState: () => {
const storage = getSafeStorage();
- const saved = storage?.getItem(AGENT_STATE_KEY);
- if (saved) {
- try {
- const state = normalizePersistedState(JSON.parse(saved));
- set((draft) => {
- draft.chats = state.chats;
- draft.messagesByChatId = state.messagesByChatId;
- draft.pendingAskByChatId = state.pendingAskByChatId;
- draft.currentChatId = state.currentChatId;
- });
- } catch {
- storage?.removeItem(AGENT_STATE_KEY);
- }
- }
-
- const s = get();
- if (
- s.chats.length === 0 ||
- (s.currentChatId !== null &&
- !s.chats.some((c) => c.id === s.currentChatId))
- ) {
- const chat = createChatRecord();
- set((draft) => {
- draft.chats.push(chat);
- draft.messagesByChatId[chat.id] = [];
- draft.currentChatId = chat.id;
- });
- }
+ const workspaceName = get().workspaceName;
+ const key = workspaceName
+ ? getWorkspaceStorageKey(AGENT_STATE_KEY, workspaceName)
+ : null;
+ if (!key) return;
+ const state = getPersistedState(storage, key);
+ set((draft) => {
+ draft.chats = state.chats;
+ draft.messagesByChatId = state.messagesByChatId;
+ draft.pendingAskByChatId = state.pendingAskByChatId;
+ draft.currentChatId = state.currentChatId;
+ });
},
};
})
@@ -1319,10 +1594,14 @@ export const createAgentStore = () => {
// Auto-persist only the chat state slice (not UI/window state).
// Uses a serialization check to avoid redundant writes during
// drag/resize operations that only change position/size.
- let lastSerialized = "";
+ const lastSerializedByWorkspace = new Map<string, string>();
store.subscribe((state) => {
const storage = getSafeStorage();
- if (!storage) {
+ const workspaceName = state.workspaceName;
+ const key = workspaceName
+ ? getWorkspaceStorageKey(AGENT_STATE_KEY, workspaceName)
+ : null;
+ if (!storage || !key) {
return;
}
const persistedState: PersistedAgentState = {
@@ -1332,15 +1611,12 @@ export const createAgentStore = () => {
pendingAskByChatId: state.pendingAskByChatId,
};
const serialized = JSON.stringify(persistedState);
- if (serialized !== lastSerialized) {
- lastSerialized = serialized;
- storage.setItem(AGENT_STATE_KEY, serialized);
+ if (serialized !== lastSerializedByWorkspace.get(key)) {
+ lastSerializedByWorkspace.set(key, serialized);
+ storage.setItem(key, serialized);
}
});
- // Load persisted window state (position, size, sidebar width) on creation.
- store.getState().loadWindowState();
-
return store;
};
diff --git a/frontend/src/modules/agent/window.ts b/frontend/src/modules/agent/window.ts
index d08283e62c..9f4cb98e72 100644
--- a/frontend/src/modules/agent/window.ts
+++ b/frontend/src/modules/agent/window.ts
@@ -7,8 +7,8 @@ export const MIN_HEIGHT = 400;
export const WINDOW_MARGIN = 16;
export const DEFAULT_SIDEBAR_WIDTH = 200;
-const DEFAULT_WIDTH_RATIO = 0.43;
-const DEFAULT_HEIGHT_RATIO = 0.52;
+const DEFAULT_WIDTH_RATIO = 0.6;
+const DEFAULT_HEIGHT_RATIO = 0.6;
const MAX_DEFAULT_WIDTH = 750;
const MAX_DEFAULT_HEIGHT = 590;
diff --git a/frontend/src/routes/project/ProjectHomePage.test.tsx b/frontend/src/routes/project/ProjectHomePage.test.tsx
index 8412c00423..64c929bcec 100644
--- a/frontend/src/routes/project/ProjectHomePage.test.tsx
+++ b/frontend/src/routes/project/ProjectHomePage.test.tsx
@@ -55,7 +55,7 @@ const mocks = vi.hoisted(() => ({
missedPermissions: [] as Permission[],
probedPermissions: [] as Permission[],
open: vi.fn(),
- createChat: vi.fn(() => ({ id: "new-chat" })),
+ selectOrCreateChatForContext: vi.fn(() => ({ id: "new-chat" })),
queueUserMessage: vi.fn(),
listRollouts: vi.fn(),
}));
@@ -79,6 +79,10 @@ vi.mock("@/components/ComponentPermissionGuard", () => ({
return { missedPermissions: mocks.missedPermissions };
},
}));
+vi.mock("@/hooks/useAppState", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@/hooks/useAppState")>()),
+ usePlanFeature: () => mocks.state.hasFeature(),
+}));
vi.mock("@/components/ProjectPageLayout", () => ({
ProjectPageLayout: ({ children }: { children: ReactNode }) => (
<div>{children}</div>
@@ -105,7 +109,7 @@ vi.mock("@/modules/agent/store/agent", () => ({
{
getState: () => ({
open: mocks.open,
- createChat: mocks.createChat,
+ selectOrCreateChatForContext: mocks.selectOrCreateChatForContext,
queueUserMessage: mocks.queueUserMessage,
chats: [],
queuedUserMessage: null,
@@ -115,6 +119,28 @@ vi.mock("@/modules/agent/store/agent", () => ({
selectHasRunningChat: () => false,
}));
+vi.mock("@/modules/agent/components/LandingStarterSelector", () => ({
+ LandingStarterSelector: ({
+ starterIds,
+ disabled,
+ onSelect,
+ }: {
+ starterIds: string[];
+ disabled: boolean;
+ onSelect: (starterId: string) => void;
+ }) => (
+ <button
+ type="button"
+ disabled={disabled}
+ data-testid="landing-starter-primary"
+ data-starter-ids={starterIds.join(",")}
+ onClick={() => onSelect(starterIds[0])}
+ >
+ {starterIds[0]}
+ </button>
+ ),
+}));
+
import { ProjectHomePage } from "./ProjectHomePage";
beforeEach(() => {
@@ -128,6 +154,7 @@ beforeEach(() => {
mocks.state.projectsByName["projects/orders"].state = State.ACTIVE;
mocks.state.projectsByName["projects/second"].state = State.ACTIVE;
mocks.state.hasInstanceFeature.mockReturnValue(true);
+ mocks.state.hasFeature.mockReturnValue(true);
mocks.state.hasWorkspacePermission.mockReturnValue(true);
mocks.state.fetchDatabases.mockResolvedValue({
databases: [
@@ -144,7 +171,108 @@ beforeEach(() => {
});
describe("ProjectHomePage", () => {
- test("checks migration rollouts with one project-scoped request", async () => {
+ test("sends a Project starter in a reusable read-only Agent chat", async () => {
+ render(<ProjectHomePage projectId="orders" />);
+
+ const starter = await screen.findByTestId("landing-starter-primary");
+ const prompt = screen.getByRole("textbox", {
+ name: "project.home.ai-placeholder",
+ });
+ await waitFor(() => expect(starter).toHaveTextContent("project-next"));
+ expect(
+ starter.compareDocumentPosition(prompt) & Node.DOCUMENT_POSITION_FOLLOWING
+ ).toBeTruthy();
+ fireEvent.click(starter);
+
+ expect(mocks.selectOrCreateChatForContext).toHaveBeenCalledWith(
+ "projects/orders",
+ expect.objectContaining({ path: expect.any(String) }),
+ "workspaces/demo"
+ );
+ expect(mocks.queueUserMessage).toHaveBeenCalledWith(
+ expect.objectContaining({
+ chatId: "new-chat",
+ text: "agent.landing-starters.project-next",
+ runMode: "read-only",
+ starterId: "project-next",
+ })
+ );
+ expect(mocks.open).toHaveBeenCalledOnce();
+ });
+
+ test("combines active Project work with database and collaboration starters", async () => {
+ mocks.state.listIssues.mockImplementation(({ find }) =>
+ Promise.resolve({
+ issues: find.typeList
+ ? []
+ : [
+ create(IssueSchema, {
+ name: "projects/orders/issues/1",
+ status: IssueStatus.OPEN,
+ }),
+ ],
+ })
+ );
+ render(<ProjectHomePage projectId="orders" />);
+
+ await waitFor(() =>
+ expect(screen.getByTestId("landing-starter-primary")).toHaveAttribute(
+ "data-starter-ids",
+ "project-open-blockers,project-next,project-collaborate,project-open-recent,project-propose-change,project-access,project-review"
+ )
+ );
+ });
+
+ test("does not offer recent activity without audit-log permission", async () => {
+ mocks.state.listIssues.mockImplementation(({ find }) =>
+ Promise.resolve({
+ issues: find.typeList
+ ? []
+ : [
+ create(IssueSchema, {
+ name: "projects/orders/issues/1",
+ status: IssueStatus.OPEN,
+ }),
+ ],
+ })
+ );
+ mocks.missedPermissions = ["bb.auditLogs.search"];
+ render(<ProjectHomePage projectId="orders" />);
+
+ await waitFor(() =>
+ expect(screen.getByTestId("landing-starter-primary")).toHaveAttribute(
+ "data-starter-ids",
+ "project-open-blockers,project-next,project-collaborate,project-propose-change,project-access,project-review"
+ )
+ );
+
+ });
+
+ test("does not offer recent activity without the audit-log feature", async () => {
+ mocks.state.listIssues.mockImplementation(({ find }) =>
+ Promise.resolve({
+ issues: find.typeList
+ ? []
+ : [
+ create(IssueSchema, {
+ name: "projects/orders/issues/1",
+ status: IssueStatus.OPEN,
+ }),
+ ],
+ })
+ );
+ mocks.state.hasFeature.mockReturnValue(false);
+ render(<ProjectHomePage projectId="orders" />);
+
+ await waitFor(() =>
+ expect(screen.getByTestId("landing-starter-primary")).toHaveAttribute(
+ "data-starter-ids",
+ "project-open-blockers,project-next,project-collaborate,project-propose-change,project-access,project-review"
+ )
+ );
+ });
+
+ test("checks project-scoped rollout and open database-change Issue state", async () => {
render(<ProjectHomePage projectId="orders" />);
await waitFor(() => expect(mocks.listRollouts).toHaveBeenCalledWith({
parent: "projects/orders",
@@ -153,6 +281,16 @@ describe("ProjectHomePage", () => {
}, expect.objectContaining({ contextValues: expect.anything() })));
expect(mocks.listRollouts.mock.calls[0][1].contextValues.get(silentContextKey)).toBe(true);
expect(mocks.listRollouts).toHaveBeenCalledOnce();
+ expect(mocks.state.listIssues).toHaveBeenCalledWith(
+ expect.objectContaining({
+ find: expect.objectContaining({
+ project: "projects/orders",
+ typeList: [Issue_Type.DATABASE_CHANGE],
+ statusList: [IssueStatus.OPEN],
+ }),
+ pageSize: 1,
+ })
+ );
});
test("shows archived status without loading active project data", () => {
@@ -202,11 +340,15 @@ describe("ProjectHomePage", () => {
expect(screen.getByRole("region", { name: "project.home.next-step" })).toBeTruthy();
});
const prompt = screen.getByRole("textbox", { name: "project.home.ai-placeholder" });
+ expect(screen.getByTestId("landing-starter-primary")).toBeTruthy();
expect(screen.getByRole("button", { name: "agent.send" }).hasAttribute("disabled")).toBe(true);
fireEvent.change(prompt, { target: { value: "List databases" } });
+ expect(screen.queryByTestId("landing-starter-primary")).toBeNull();
fireEvent.click(screen.getByRole("button", { name: "agent.send" }));
- expect(mocks.createChat).toHaveBeenCalledWith(
- expect.objectContaining({ context: "projects/orders" })
+ expect(mocks.selectOrCreateChatForContext).toHaveBeenCalledWith(
+ "projects/orders",
+ expect.objectContaining({ path: expect.any(String) }),
+ "workspaces/demo"
);
expect(mocks.queueUserMessage).toHaveBeenCalledWith(
expect.objectContaining({ chatId: "new-chat", text: "List databases" })
@@ -230,12 +372,12 @@ describe("ProjectHomePage", () => {
).toContain("items-end");
const shiftEnterWasNotCanceled = fireEvent.keyDown(prompt, { key: "Enter", shiftKey: true });
expect(shiftEnterWasNotCanceled).toBe(true);
- expect(mocks.createChat).not.toHaveBeenCalled();
+ expect(mocks.selectOrCreateChatForContext).not.toHaveBeenCalled();
fireEvent.change(prompt, { target: { value: "Explain this\nproject" } });
const enterWasCanceled = fireEvent.keyDown(prompt, { key: "Enter" });
expect(enterWasCanceled).toBe(false);
- expect(mocks.createChat).toHaveBeenCalledOnce();
+ expect(mocks.selectOrCreateChatForContext).toHaveBeenCalledOnce();
expect(mocks.queueUserMessage).toHaveBeenCalledWith(
expect.objectContaining({ text: "Explain this\nproject" })
);
@@ -770,7 +912,9 @@ describe("ProjectHomePage", () => {
title: "Access request",
status: IssueStatus.OPEN,
});
- mocks.state.listIssues.mockResolvedValue({ issues: [accessIssue] });
+ mocks.state.listIssues.mockImplementation(({ find }) =>
+ Promise.resolve({ issues: find.typeList ? [] : [accessIssue] })
+ );
const view = render(<ProjectHomePage projectId="orders" />);
const next = await screen.findByRole("region", { name: "project.home.next-step" });
expect((await within(next).findByRole("link", { name: "project.home.change-database" })).getAttribute("href"))
@@ -786,18 +930,29 @@ describe("ProjectHomePage", () => {
await waitFor(() => expect(screen.queryByRole("region", { name: "project.home.next-step" })).toBeNull());
});
- test("keeps setup visible for an issue without a migration rollout", async () => {
- mocks.state.listIssues.mockResolvedValue({
- issues: [
- create(IssueSchema, {
- name: "projects/orders/issues/change",
- status: IssueStatus.OPEN,
- }),
- ],
- });
+ test("hides first-change guidance when a database change Issue is open", async () => {
+ mocks.state.listIssues.mockImplementation(({ find }) =>
+ Promise.resolve({
+ issues: find.typeList?.includes(Issue_Type.DATABASE_CHANGE)
+ ? [
+ create(IssueSchema, {
+ name: "projects/orders/issues/change",
+ type: Issue_Type.DATABASE_CHANGE,
+ status: IssueStatus.OPEN,
+ }),
+ ]
+ : [],
+ })
+ );
render(<ProjectHomePage projectId="orders" />);
const next = await screen.findByRole("region", { name: "project.home.next-step" });
- expect(await within(next).findByRole("link", { name: "project.home.change-database" })).toBeTruthy();
+ await waitFor(() => expect(mocks.listRollouts).toHaveBeenCalledOnce());
+ expect(
+ within(next).queryByRole("link", { name: "project.home.change-database" })
+ ).toBeNull();
+ expect(
+ within(next).queryByRole("link", { name: "project.home.query-database" })
+ ).toBeNull();
expect(mocks.listRollouts).toHaveBeenCalledOnce();
});
diff --git a/frontend/src/routes/project/ProjectHomePage.tsx b/frontend/src/routes/project/ProjectHomePage.tsx
index c5999a1f45..2da3d92b7c 100644
--- a/frontend/src/routes/project/ProjectHomePage.tsx
+++ b/frontend/src/routes/project/ProjectHomePage.tsx
@@ -30,12 +30,15 @@ import { ProjectPageLayout } from "@/components/ProjectPageLayout";
import { RouterLink } from "@/components/RouterLink";
import { Button, buttonVariants } from "@/components/ui/button";
import { Textarea } from "@/components/ui/textarea";
+import { usePlanFeature } from "@/hooks/useAppState";
import {
PREPARE_DATABASE_PRODUCT_INTRO,
PREPARE_DATABASE_TRANSFER_TIP,
PRODUCT_INTRO_QUERY_KEY,
PRODUCT_INTRO_TIP_QUERY_KEY,
} from "@/lib/productIntro";
+import { LandingStarterSelector } from "@/modules/agent/components/LandingStarterSelector";
+import { getLandingStarterIds } from "@/modules/agent/logic/landingStarters";
import {
selectHasRunningChat,
useAgentStore,
@@ -49,6 +52,8 @@ import {
State,
} from "@/types/proto-es/v1/common_pb";
import type { Database as DatabaseResource } from "@/types/proto-es/v1/database_service_pb";
+import { Issue_Type } from "@/types/proto-es/v1/issue_service_pb";
+import { PlanFeature } from "@/types/proto-es/v1/subscription_service_pb";
import { getUserEmailInBinding } from "@/types/v1/user";
import { autoDatabaseRoute } from "@/utils/auto-route";
import { isBindingPolicyExpired } from "@/utils/v1/iam";
@@ -80,6 +85,7 @@ const HOME_PERMISSIONS: Permission[] = [
"bb.sheets.create",
"bb.projects.getIamPolicy",
"bb.projects.setIamPolicy",
+ "bb.auditLogs.search",
];
const PLAN_DETAIL_PERMISSIONS: Permission[] = [
"bb.plans.get",
@@ -130,6 +136,7 @@ export function ProjectHomePage({ projectId }: { projectId: string }) {
const aiEnabled = useAppStore(
(state) => state.serverInfo?.aiEnabled === true
);
+ const hasAuditLogFeature = usePlanFeature(PlanFeature.FEATURE_AUDIT_LOG);
const hasRunningChat = useAgentStore(selectHasRunningChat);
const hasQueuedMessage = useAgentStore(
(state) => state.queuedUserMessage !== null
@@ -193,6 +200,8 @@ export function ProjectHomePage({ projectId }: { projectId: string }) {
!missedPermissions.includes("bb.issues.create") &&
!missedPermissions.includes("bb.sheets.create") &&
canGetPlanDetail;
+ const canViewRecentActivity =
+ hasAuditLogFeature && !missedPermissions.includes("bb.auditLogs.search");
const canQueryDatabase =
canListDatabases && !missedPermissions.includes("bb.projects.getIamPolicy");
const membership =
@@ -252,7 +261,7 @@ export function ProjectHomePage({ projectId }: { projectId: string }) {
: "loading";
const [changeState, setChangeState] = useState<{
projectName: string;
- status: "loading" | "not-started" | "rolled-out" | "unknown";
+ status: "loading" | "not-started" | "proposed" | "rolled-out" | "unknown";
}>({ projectName, status: "loading" });
const changeStatus =
changeState.projectName === projectName ? changeState.status : "loading";
@@ -380,25 +389,47 @@ export function ProjectHomePage({ projectId }: { projectId: string }) {
useEffect(() => {
if (isArchived || availability !== "present") return;
let active = true;
- if (!canListRollouts) {
+ const canInspectDatabaseChanges = canListIssues && canReadIssues;
+ if (!canListRollouts && !canInspectDatabaseChanges) {
setChangeState({ projectName, status: "unknown" });
return;
}
setChangeState({ projectName, status: "loading" });
- void rolloutServiceClientConnect
- .listRollouts(
- {
- parent: projectName,
- pageSize: 1,
- filter: 'task_type in ["DATABASE_MIGRATE"]',
- },
- { contextValues: createContextValues().set(silentContextKey, true) }
- )
- .then(({ rollouts }) => {
+ void Promise.all([
+ canListRollouts
+ ? rolloutServiceClientConnect.listRollouts(
+ {
+ parent: projectName,
+ pageSize: 1,
+ filter: 'task_type in ["DATABASE_MIGRATE"]',
+ },
+ { contextValues: createContextValues().set(silentContextKey, true) }
+ )
+ : Promise.resolve(undefined),
+ canInspectDatabaseChanges
+ ? listIssues({
+ find: {
+ project: projectName,
+ query: "",
+ typeList: [Issue_Type.DATABASE_CHANGE],
+ statusList: [IssueStatus.OPEN],
+ orderBy: "update_time desc",
+ },
+ pageSize: 1,
+ })
+ : Promise.resolve(undefined),
+ ])
+ .then(([rolloutResponse, issueResponse]) => {
if (active) {
setChangeState({
projectName,
- status: rollouts.length ? "rolled-out" : "not-started",
+ status: issueResponse?.issues.length
+ ? "proposed"
+ : rolloutResponse?.rollouts.length
+ ? "rolled-out"
+ : canListRollouts && canInspectDatabaseChanges
+ ? "not-started"
+ : "unknown",
});
}
})
@@ -408,7 +439,15 @@ export function ProjectHomePage({ projectId }: { projectId: string }) {
return () => {
active = false;
};
- }, [availability, canListRollouts, isArchived, projectName]);
+ }, [
+ availability,
+ canListIssues,
+ canListRollouts,
+ canReadIssues,
+ isArchived,
+ listIssues,
+ projectName,
+ ]);
useEffect(() => {
if (isArchived) return;
@@ -504,6 +543,23 @@ export function ProjectHomePage({ projectId }: { projectId: string }) {
canManageMembers,
goal: readSelectedGuideScenarioId(),
});
+ const landingStarterIds = getLandingStarterIds({
+ scope: "project",
+ activeWork:
+ activeIssueStatus === "ready"
+ ? activeIssues.length
+ ? "present"
+ : "empty"
+ : activeIssueStatus === "loading"
+ ? "loading"
+ : "unknown",
+ database: availability,
+ change: changeStatus,
+ membership,
+ canConnectInstance,
+ canCreateChange,
+ canViewRecentActivity,
+ });
const nextStepCopy = (step: ProjectHomeNextStep) => {
switch (step) {
@@ -586,12 +642,43 @@ export function ProjectHomePage({ projectId }: { projectId: string }) {
path: `${window.location.pathname}${window.location.search}${window.location.hash}`,
title: document.title,
};
- const chat = store.createChat({ context: project.name, page });
+ const chat = store.selectOrCreateChatForContext(
+ project.name,
+ page,
+ workspaceName
+ );
+ if (!chat) return;
store.queueUserMessage({ chatId: chat.id, text, page });
store.open();
setAiPrompt("");
};
+ const sendLandingStarter = (
+ starterId: (typeof landingStarterIds)[number]
+ ) => {
+ if (!aiEnabled) return;
+ const store = useAgentStore.getState();
+ if (selectHasRunningChat(store) || store.queuedUserMessage) return;
+ const page = {
+ path: `${window.location.pathname}${window.location.search}${window.location.hash}`,
+ title: document.title,
+ };
+ const chat = store.selectOrCreateChatForContext(
+ project.name,
+ page,
+ workspaceName
+ );
+ if (!chat) return;
+ store.queueUserMessage({
+ chatId: chat.id,
+ text: t(`agent.landing-starters.${starterId}`),
+ page,
+ runMode: "read-only",
+ starterId,
+ });
+ store.open();
+ };
+
return (
<ProjectPageLayout>
<header className="min-w-0">
@@ -611,6 +698,15 @@ export function ProjectHomePage({ projectId }: { projectId: string }) {
sendAIMessage();
}}
>
+ {!aiPrompt.trim() && (
+ <div className="px-3 pt-2">
+ <LandingStarterSelector
+ starterIds={landingStarterIds}
+ disabled={hasRunningChat || hasQueuedMessage}
+ onSelect={sendLandingStarter}
+ />
+ </div>
+ )}
<Textarea
size="md"
rows={2}
diff --git a/frontend/src/routes/project/projectHomeNextSteps.test.ts b/frontend/src/routes/project/projectHomeNextSteps.test.ts
index 215304e101..a49fce8bb5 100644
--- a/frontend/src/routes/project/projectHomeNextSteps.test.ts
+++ b/frontend/src/routes/project/projectHomeNextSteps.test.ts
@@ -96,6 +96,16 @@ describe("getProjectHomeNextSteps", () => {
).toEqual(["changeDatabase", "queryDatabase", "members"]);
});
+ test("does not offer a first database change after one is proposed", () => {
+ expect(
+ getProjectHomeNextSteps({
+ ...input,
+ database: "present",
+ change: "proposed",
+ })
+ ).toEqual(["members"]);
+ });
+
test("waits for initial discovery before showing membership setup", () => {
expect(getProjectHomeNextSteps({ ...input, database: "loading" })).toEqual(
[]
diff --git a/frontend/src/routes/project/projectHomeNextSteps.ts b/frontend/src/routes/project/projectHomeNextSteps.ts
index dd83d2cc28..195ba6dc88 100644
--- a/frontend/src/routes/project/projectHomeNextSteps.ts
+++ b/frontend/src/routes/project/projectHomeNextSteps.ts
@@ -15,7 +15,7 @@ export type ProjectHomeNextStepInput = {
database: ResourceAvailability;
instance: ResourceAvailability;
transferableDatabase: ResourceAvailability;
- change: "loading" | "not-started" | "rolled-out" | "unknown";
+ change: "loading" | "not-started" | "proposed" | "rolled-out" | "unknown";
membership: "unknown" | "solo" | "has-collaborators";
isDefault: boolean;
canConnectInstance: boolean;
diff --git a/frontend/src/routes/workspace/LandingPage.test.tsx b/frontend/src/routes/workspace/LandingPage.test.tsx
index 05eb96d09e..f4035c89a8 100644
--- a/frontend/src/routes/workspace/LandingPage.test.tsx
+++ b/frontend/src/routes/workspace/LandingPage.test.tsx
@@ -18,13 +18,18 @@ import { LandingPage } from "./LandingPage";
const mocks = vi.hoisted(() => ({
aiEnabled: true as boolean | undefined,
canConfigureAI: true,
+ canSearchAuditLogs: true,
+ hasAuditLogFeature: true,
chatRunning: false,
queuedUserMessage: null as { chatId: string } | null,
- createChat: vi.fn(() => ({ id: "workspace-chat" })),
+ selectOrCreateChatForContext: vi.fn(() => ({ id: "workspace-chat" })),
lastVisitProjectPath: "",
openAgent: vi.fn(),
push: vi.fn(),
queueUserMessage: vi.fn(),
+ searchProjects: vi.fn(),
+ listInstances: vi.fn(),
+ listDatabases: vi.fn(),
isSaaSMode: false,
}));
@@ -35,6 +40,12 @@ vi.mock("react-i18next", () => ({
vi.mock("@/app/router", () => ({ router: { push: mocks.push } }));
+vi.mock("@/api", () => ({
+ projectServiceClientConnect: { searchProjects: mocks.searchProjects },
+ instanceServiceClientConnect: { listInstances: mocks.listInstances },
+ databaseServiceClientConnect: { listDatabases: mocks.listDatabases },
+}));
+
vi.mock("@/components/RouterLink", () => ({
RouterLink: ({ children, to }: { children: ReactNode; to: unknown }) => (
<a href="#" data-route={JSON.stringify(to)}>{children}</a>
@@ -59,9 +70,16 @@ vi.mock("@/components/ui/sheet", () => ({
}));
vi.mock("@/hooks/useAppState", () => ({
- useOptionalCurrentUser: () => ({ email: "[email protected]" }),
+ useOptionalCurrentUser: () => ({
+ name: "users/creator",
+ email: "[email protected]",
+ }),
useServerState: () => ({ isSaaSMode: mocks.isSaaSMode, version: "", changelogURL: "" }),
- useWorkspacePermission: () => mocks.canConfigureAI,
+ usePlanFeature: () => mocks.hasAuditLogFeature,
+ useWorkspacePermission: (permission: string) =>
+ permission === "bb.auditLogs.search"
+ ? mocks.canSearchAuditLogs
+ : mocks.canConfigureAI,
useWorkspace: () => ({ name: "workspaces/acme", title: "Acme workspace" }),
}));
@@ -76,7 +94,7 @@ vi.mock("@/modules/agent/store/agent", () => ({
selector({ queuedUserMessage: mocks.queuedUserMessage }),
{
getState: () => ({
- createChat: mocks.createChat,
+ selectOrCreateChatForContext: mocks.selectOrCreateChatForContext,
open: mocks.openAgent,
queueUserMessage: mocks.queueUserMessage,
queuedUserMessage: mocks.queuedUserMessage,
@@ -85,6 +103,28 @@ vi.mock("@/modules/agent/store/agent", () => ({
),
}));
+vi.mock("@/modules/agent/components/LandingStarterSelector", () => ({
+ LandingStarterSelector: ({
+ starterIds,
+ disabled,
+ onSelect,
+ }: {
+ starterIds: string[];
+ disabled: boolean;
+ onSelect: (starterId: string) => void;
+ }) => (
+ <button
+ type="button"
+ disabled={disabled}
+ data-testid="landing-starter-primary"
+ data-starter-ids={starterIds.join(",")}
+ onClick={() => onSelect(starterIds[0])}
+ >
+ {starterIds[0]}
+ </button>
+ ),
+}));
+
vi.mock("./WorkspaceLandingGettingStarted", () => ({
WorkspaceLandingGettingStarted: () => null,
}));
@@ -92,7 +132,9 @@ vi.mock("./WorkspaceLandingGettingStarted", () => ({
vi.mock("@/stores/app", () => ({
useAppStore: Object.assign(
(selector: (state: object) => unknown) =>
- selector({ serverInfo: { aiEnabled: mocks.aiEnabled } }),
+ selector({
+ serverInfo: { aiEnabled: mocks.aiEnabled },
+ }),
{
getState: () => ({
getOrFetchProjectByName: async () => ({
@@ -107,20 +149,123 @@ vi.mock("@/stores/app", () => ({
beforeEach(() => {
mocks.aiEnabled = true;
mocks.canConfigureAI = true;
+ mocks.canSearchAuditLogs = true;
+ mocks.hasAuditLogFeature = true;
mocks.chatRunning = false;
mocks.isSaaSMode = false;
mocks.queuedUserMessage = null;
mocks.lastVisitProjectPath = "";
- mocks.createChat.mockClear();
+ mocks.selectOrCreateChatForContext.mockClear();
mocks.openAgent.mockClear();
mocks.queueUserMessage.mockClear();
+ mocks.searchProjects.mockReset();
+ mocks.listInstances.mockReset();
+ mocks.listDatabases.mockReset();
+ mocks.searchProjects.mockResolvedValue({ projects: [] });
+ mocks.listInstances.mockResolvedValue({ instances: [] });
+ mocks.listDatabases.mockResolvedValue({ databases: [] });
localStorage.clear();
});
afterEach(cleanup);
describe("LandingPage", () => {
- test("sends a prompt in a new workspace-bound Agent chat", async () => {
+ test("offers a starter above the empty composer and sends it in a read-only chat", async () => {
+ render(<LandingPage />);
+
+ const prompt = screen.getByRole("textbox", {
+ name: "landing.ai-placeholder",
+ });
+ const starter = screen.getByTestId("landing-starter-primary");
+ await waitFor(() =>
+ expect(starter).toHaveTextContent("workspace-setup-first")
+ );
+ expect(
+ starter.compareDocumentPosition(prompt) & Node.DOCUMENT_POSITION_FOLLOWING
+ ).toBeTruthy();
+
+ fireEvent.click(starter);
+
+ expect(mocks.selectOrCreateChatForContext).toHaveBeenCalledWith(
+ "workspaces/acme",
+ expect.objectContaining({ path: expect.any(String) }),
+ "workspaces/acme"
+ );
+ expect(mocks.queueUserMessage).toHaveBeenCalledWith({
+ chatId: "workspace-chat",
+ text: "agent.landing-starters.workspace-setup-first",
+ page: expect.objectContaining({ path: expect.any(String) }),
+ runMode: "read-only",
+ starterId: "workspace-setup-first",
+ });
+ expect(mocks.openAgent).toHaveBeenCalledOnce();
+ });
+
+ test("updates workspace starters when setup resources are found", async () => {
+ mocks.searchProjects.mockResolvedValue({
+ projects: [{ name: "projects/orders" }],
+ });
+ render(<LandingPage />);
+
+ await waitFor(() =>
+ expect(screen.getByTestId("landing-starter-primary")).toHaveAttribute(
+ "data-starter-ids",
+ "workspace-attention,workspace-recent"
+ )
+ );
+ });
+
+ test("uses minimal resource reads to discover workspace setup", async () => {
+ render(<LandingPage />);
+
+ await waitFor(() =>
+ expect(mocks.searchProjects).toHaveBeenCalledWith(
+ expect.objectContaining({
+ filter: 'exclude_default == true && state == "ACTIVE"',
+ pageSize: 1,
+ })
+ )
+ );
+ expect(mocks.listInstances).toHaveBeenCalledWith(
+ expect.objectContaining({ pageSize: 1, showDeleted: false })
+ );
+ expect(mocks.listDatabases).toHaveBeenCalledWith(
+ expect.objectContaining({
+ parent: "workspaces/acme",
+ pageSize: 1,
+ showDeleted: false,
+ })
+ );
+ });
+
+ test("does not assume a workspace needs setup when resource discovery is incomplete", async () => {
+ mocks.searchProjects.mockRejectedValue(new Error("permission denied"));
+ render(<LandingPage />);
+
+ await waitFor(() =>
+ expect(screen.getByTestId("landing-starter-primary")).toHaveAttribute(
+ "data-starter-ids",
+ "workspace-attention,workspace-recent"
+ )
+ );
+ });
+
+ test("does not offer workspace recent activity without audit-log access", async () => {
+ mocks.listInstances.mockResolvedValue({
+ instances: [{ name: "instances/primary" }],
+ });
+ mocks.canSearchAuditLogs = false;
+ render(<LandingPage />);
+
+ await waitFor(() =>
+ expect(screen.getByTestId("landing-starter-primary")).toHaveAttribute(
+ "data-starter-ids",
+ "workspace-attention"
+ )
+ );
+ });
+
+ test("sends a prompt in a reusable workspace-bound Agent chat", async () => {
render(<LandingPage />);
expect(
@@ -136,12 +281,14 @@ describe("LandingPage", () => {
fireEvent.change(screen.getByRole("textbox", { name: "landing.ai-placeholder" }), {
target: { value: " Show the projects in this workspace " },
});
+ expect(screen.queryByTestId("landing-starter-primary")).not.toBeInTheDocument();
fireEvent.click(screen.getByRole("button", { name: "agent.send" }));
- expect(mocks.createChat).toHaveBeenCalledWith({
- context: "workspaces/acme",
- page: expect.objectContaining({ path: expect.any(String) }),
- });
+ expect(mocks.selectOrCreateChatForContext).toHaveBeenCalledWith(
+ "workspaces/acme",
+ expect.objectContaining({ path: expect.any(String) }),
+ "workspaces/acme"
+ );
expect(mocks.queueUserMessage).toHaveBeenCalledWith({
chatId: "workspace-chat",
text: "Show the projects in this workspace",
@@ -165,7 +312,7 @@ describe("LandingPage", () => {
fireEvent.change(prompt, { target: { value: "Workspace\nprojects" } });
expect(fireEvent.keyDown(prompt, { key: "Enter", shiftKey: true })).toBe(true);
- expect(mocks.createChat).not.toHaveBeenCalled();
+ expect(mocks.selectOrCreateChatForContext).not.toHaveBeenCalled();
expect(fireEvent.keyDown(prompt, { key: "Enter" })).toBe(false);
expect(mocks.queueUserMessage).toHaveBeenCalledWith(
expect.objectContaining({ text: "Workspace\nprojects" })
@@ -222,7 +369,7 @@ describe("LandingPage", () => {
rerender(<LandingPage />);
expect(send).toBeDisabled();
fireEvent.submit(send.closest("form")!);
- expect(mocks.createChat).not.toHaveBeenCalled();
+ expect(mocks.selectOrCreateChatForContext).not.toHaveBeenCalled();
});
test("keeps Last visit beside the shortcuts title", async () => {
diff --git a/frontend/src/routes/workspace/LandingPage.tsx b/frontend/src/routes/workspace/LandingPage.tsx
index 51b7eccf7f..6d235be4d6 100644
--- a/frontend/src/routes/workspace/LandingPage.tsx
+++ b/frontend/src/routes/workspace/LandingPage.tsx
@@ -1,3 +1,4 @@
+import { create } from "@bufbuild/protobuf";
import {
Bot,
CircleDot,
@@ -23,6 +24,11 @@ import {
useState,
} from "react";
import { useTranslation } from "react-i18next";
+import {
+ databaseServiceClientConnect,
+ instanceServiceClientConnect,
+ projectServiceClientConnect,
+} from "@/api";
import { router } from "@/app/router";
import {
DATABASE_ROUTE_DASHBOARD,
@@ -64,6 +70,7 @@ import { Textarea } from "@/components/ui/textarea";
import { WorkspacePageLayout } from "@/components/WorkspacePageLayout";
import {
useOptionalCurrentUser,
+ usePlanFeature,
useServerState,
useWorkspace,
useWorkspacePermission,
@@ -73,6 +80,8 @@ import {
AI_ASSISTANT_PRODUCT_INTRO,
PRODUCT_INTRO_QUERY_KEY,
} from "@/lib/productIntro";
+import { LandingStarterSelector } from "@/modules/agent/components/LandingStarterSelector";
+import { getLandingStarterIds } from "@/modules/agent/logic/landingStarters";
import {
selectHasRunningChat,
useAgentStore,
@@ -80,7 +89,13 @@ import {
import { useAppStore } from "@/stores/app";
import { projectNamePrefix } from "@/stores/modules/v1/common";
import { UNKNOWN_PROJECT_NAME } from "@/types";
-import type { Project } from "@/types/proto-es/v1/project_service_pb";
+import { ListDatabasesRequestSchema } from "@/types/proto-es/v1/database_service_pb";
+import { ListInstancesRequestSchema } from "@/types/proto-es/v1/instance_service_pb";
+import {
+ type Project,
+ SearchProjectsRequestSchema,
+} from "@/types/proto-es/v1/project_service_pb";
+import { PlanFeature } from "@/types/proto-es/v1/subscription_service_pb";
import { extractProjectResourceName, storageKeyQuickAccess } from "@/utils";
import { WorkspaceLandingGettingStarted } from "./WorkspaceLandingGettingStarted";
@@ -450,6 +465,7 @@ function ConfigSheet({
export function LandingPage(_: Record<string, never> = {}) {
const { t } = useTranslation();
+ const hasAuditLogFeature = usePlanFeature(PlanFeature.FEATURE_AUDIT_LOG);
const [showConfigDrawer, setShowConfigDrawer] = useState(false);
const [aiPrompt, setAiPrompt] = useState("");
const workspace = useWorkspace();
@@ -460,8 +476,13 @@ export function LandingPage(_: Record<string, never> = {}) {
(state) => state.queuedUserMessage !== null
);
- const email = useOptionalCurrentUser()?.email ?? "";
+ const currentUser = useOptionalCurrentUser();
+ const email = currentUser?.email ?? "";
const { isSaaSMode, version, changelogURL } = useServerState();
+ const canSearchAuditLogs = useWorkspacePermission("bb.auditLogs.search");
+ const [setupResources, setSetupResources] = useState<
+ "loading" | "present" | "empty" | "unknown"
+ >("loading");
const fullList = useFullQuickLinkList();
const { config, setConfig } = useQuickAccessConfig(email);
@@ -486,6 +507,67 @@ export function LandingPage(_: Record<string, never> = {}) {
}
}, []);
+ useEffect(() => {
+ if (!aiEnabled || !workspace?.name) {
+ setSetupResources("unknown");
+ return;
+ }
+ let active = true;
+ setSetupResources("loading");
+ const hasProject = projectServiceClientConnect
+ .searchProjects(
+ create(SearchProjectsRequestSchema, {
+ filter: 'exclude_default == true && state == "ACTIVE"',
+ pageSize: 1,
+ orderBy: "title",
+ showDeleted: false,
+ })
+ )
+ .then(({ projects }) => projects.length > 0);
+ const hasInstance = instanceServiceClientConnect
+ .listInstances(
+ create(ListInstancesRequestSchema, {
+ pageSize: 1,
+ showDeleted: false,
+ })
+ )
+ .then(({ instances }) => instances.length > 0);
+ const hasDatabase = databaseServiceClientConnect
+ .listDatabases(
+ create(ListDatabasesRequestSchema, {
+ parent: workspace.name,
+ pageSize: 1,
+ showDeleted: false,
+ })
+ )
+ .then(({ databases }) => databases.length > 0);
+ void Promise.allSettled([hasProject, hasInstance, hasDatabase]).then(
+ (results) => {
+ if (!active) return;
+ if (
+ results.some(
+ (result) => result.status === "fulfilled" && result.value
+ )
+ ) {
+ setSetupResources("present");
+ } else if (results.every((result) => result.status === "fulfilled")) {
+ setSetupResources("empty");
+ } else {
+ setSetupResources("unknown");
+ }
+ }
+ );
+ return () => {
+ active = false;
+ };
+ }, [aiEnabled, workspace?.name]);
+
+ const landingStarterIds = getLandingStarterIds({
+ scope: "workspace",
+ setupResources,
+ canViewRecentActivity: hasAuditLogFeature && canSearchAuditLogs,
+ });
+
const sendAIMessage = () => {
const text = aiPrompt.trim();
if (!text || !aiEnabled || !workspace?.name) return;
@@ -495,12 +577,43 @@ export function LandingPage(_: Record<string, never> = {}) {
path: `${window.location.pathname}${window.location.search}${window.location.hash}`,
title: document.title,
};
- const chat = store.createChat({ context: workspace.name, page });
+ const chat = store.selectOrCreateChatForContext(
+ workspace.name,
+ page,
+ workspace.name
+ );
+ if (!chat) return;
store.queueUserMessage({ chatId: chat.id, text, page });
store.open();
setAiPrompt("");
};
+ const sendLandingStarter = (
+ starterId: (typeof landingStarterIds)[number]
+ ) => {
+ if (!aiEnabled || !workspace?.name) return;
+ const store = useAgentStore.getState();
+ if (selectHasRunningChat(store) || store.queuedUserMessage) return;
+ const page = {
+ path: `${window.location.pathname}${window.location.search}${window.location.hash}`,
+ title: document.title,
+ };
+ const chat = store.selectOrCreateChatForContext(
+ workspace.name,
+ page,
+ workspace.name
+ );
+ if (!chat) return;
+ store.queueUserMessage({
+ chatId: chat.id,
+ text: t(`agent.landing-starters.${starterId}`),
+ page,
+ runMode: "read-only",
+ starterId,
+ });
+ store.open();
+ };
+
return (
<>
<WorkspacePageLayout>
@@ -519,6 +632,15 @@ export function LandingPage(_: Record<string, never> = {}) {
sendAIMessage();
}}
>
+ {!aiPrompt.trim() && (
+ <div className="px-3 pt-2">
+ <LandingStarterSelector
+ starterIds={landingStarterIds}
+ disabled={hasRunningChat || hasQueuedMessage}
+ onSelect={sendLandingStarter}
+ />
+ </div>
+ )}
<Textarea
size="md"
rows={2}
diff --git a/frontend/src/routes/workspace/general/BrandingSection.test.tsx b/frontend/src/routes/workspace/general/BrandingSection.test.tsx
new file mode 100644
index 0000000000..4f16f69c36
--- /dev/null
+++ b/frontend/src/routes/workspace/general/BrandingSection.test.tsx
@@ -0,0 +1,60 @@
+import type { ReactNode } from "react";
+import { render, screen } from "@testing-library/react";
+import { describe, expect, test, vi } from "vitest";
+
+const workspaceID = "eJ3L1eOJf3EXzEgr";
+
+vi.mock("react-i18next", () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+vi.mock("@/components/FeatureBadge", () => ({
+ FeatureBadge: () => null,
+}));
+vi.mock("@/components/PermissionGuard", () => ({
+ PermissionGuard: ({ children }: { children: ReactNode }) => children,
+ usePermissionCheck: () => [true],
+}));
+vi.mock("@/components/ui/button", () => ({
+ Button: ({ children }: { children: ReactNode }) => <button>{children}</button>,
+}));
+vi.mock("@/components/ui/copy-button", () => ({
+ CopyButton: ({ content }: { content: string }) => (
+ <button aria-label="Copy workspace ID" data-content={content} />
+ ),
+}));
+vi.mock("@/components/ui/form", () => ({
+ FormField: ({ children, title }: { children: ReactNode; title: ReactNode }) => (
+ <div>{title}{children}</div>
+ ),
+ FormFieldGroup: ({ children }: { children: ReactNode }) => <div>{children}</div>,
+ FormSection: ({ children }: { children: ReactNode }) => <section>{children}</section>,
+}));
+vi.mock("@/components/ui/input", () => ({
+ Input: (props: React.InputHTMLAttributes<HTMLInputElement>) => <input {...props} />,
+}));
+vi.mock("@/hooks/useAppState", () => ({
+ usePlanFeature: () => true,
+ useWorkspace: () => ({
+ name: `workspaces/${workspaceID}`,
+ title: "Workspace title",
+ }),
+}));
+vi.mock("@/stores", () => ({ pushNotification: vi.fn() }));
+vi.mock("@/stores/app", () => ({
+ useAppStore: (selector: (state: { updateWorkspace: () => void }) => unknown) =>
+ selector({ updateWorkspace: vi.fn() }),
+}));
+
+import { BrandingSection } from "./BrandingSection";
+
+describe("BrandingSection", () => {
+ test("places a copy button beside the workspace ID", () => {
+ render(<BrandingSection title="Branding" onDirtyChange={vi.fn()} />);
+
+ expect(screen.getByDisplayValue(workspaceID)).toBeDisabled();
+ expect(screen.getByRole("button", { name: "Copy workspace ID" })).toHaveAttribute(
+ "data-content",
+ workspaceID
+ );
+ });
+});
diff --git a/frontend/src/routes/workspace/general/BrandingSection.tsx b/frontend/src/routes/workspace/general/BrandingSection.tsx
index 11b04027b6..26e001774e 100644
--- a/frontend/src/routes/workspace/general/BrandingSection.tsx
+++ b/frontend/src/routes/workspace/general/BrandingSection.tsx
@@ -16,6 +16,7 @@ import {
usePermissionCheck,
} from "@/components/PermissionGuard";
import { Button } from "@/components/ui/button";
+import { CopyButton } from "@/components/ui/copy-button";
import { FormField, FormFieldGroup, FormSection } from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import { usePlanFeature, useWorkspace } from "@/hooks/useAppState";
@@ -177,7 +178,14 @@ export const BrandingSection = forwardRef<SectionHandle, BrandingSectionProps>(
<FormFieldGroup>
{/* Workspace ID */}
<FormField title={t("settings.general.workspace.id")}>
- <Input value={workspaceID} disabled />
+ <div className="flex items-center gap-2">
+ <Input
+ className="min-w-0 flex-1"
+ value={workspaceID}
+ disabled
+ />
+ <CopyButton content={workspaceID} />
+ </div>
</FormField>
{/* Workspace Title */}