Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
chore: optimize workspace landing (#21594)
ecmadao4e40e5557bdf
diff --git a/frontend/src/app/layouts/BodyLayout.tsx b/frontend/src/app/layouts/BodyLayout.tsxindex 744f747bd8..28d6af42dc 100644--- a/frontend/src/app/layouts/BodyLayout.tsx+++ b/frontend/src/app/layouts/BodyLayout.tsx@@ -11,6 +11,7 @@ import { DashboardBodyShell } from "@/components/DashboardBodyShell";import { DashboardSidebar } from "@/components/DashboardSidebar";import { ProjectSidebar } from "@/components/ProjectSidebar";import { RoutePermissionGuardShell } from "@/components/RoutePermissionGuardShell";+import { GuideContextProvider } from "@/modules/workspace-setup-guide/GuideContextProvider";import { WorkspaceSetupGuide } from "@/modules/workspace-setup-guide/WorkspaceSetupGuide";// Mounts the workspace `DashboardBodyShell` (header + sidebar slot + body slot)@@ -72,7 +73,7 @@ export function BodyLayout() {const sidebarTargets = [targets.desktopSidebar, targets.mobileSidebar];return (- <>+ <GuideContextProvider><DashboardBodyShellvariant={variant}isRootPath={isRootPath}@@ -109,6 +110,6 @@ export function BodyLayout() {{targets.quickstart? createPortal(<WorkspaceSetupGuide />, targets.quickstart): null}- </>+ </GuideContextProvider>);}diff --git a/frontend/src/components/BannersWrapper.test.tsx b/frontend/src/components/BannersWrapper.test.tsxindex 6fb54cb3d9..fe4be58426 100644--- a/frontend/src/components/BannersWrapper.test.tsx+++ b/frontend/src/components/BannersWrapper.test.tsx@@ -216,6 +216,7 @@ describe("BannersWrapper", () => {expect(mocks.routerPush).toHaveBeenCalledWith({name: "setting.workspace.general",+ hash: "#external-url",query: { intro: "external-url" },});unmount();diff --git a/frontend/src/components/BannersWrapper.tsx b/frontend/src/components/BannersWrapper.tsxindex 32df15c669..82be977a7c 100644--- a/frontend/src/components/BannersWrapper.tsx+++ b/frontend/src/components/BannersWrapper.tsx@@ -91,6 +91,7 @@ function BannerExternalUrl() {<RouterLinkto={{name: SETTING_ROUTE_WORKSPACE_GENERAL,+ hash: "#external-url",query: {[PRODUCT_INTRO_QUERY_KEY]: EXTERNAL_URL_PRODUCT_INTRO,},diff --git a/frontend/src/components/ExternalUrlAlert.test.tsx b/frontend/src/components/ExternalUrlAlert.test.tsxindex c13a818db1..d0d9724227 100644--- a/frontend/src/components/ExternalUrlAlert.test.tsx+++ b/frontend/src/components/ExternalUrlAlert.test.tsx@@ -68,6 +68,7 @@ describe("ExternalUrlAlert", () => {expect(mocks.routerPush).toHaveBeenCalledWith({name: "setting.workspace.general",+ hash: "#external-url",query: { intro: "external-url" },});diff --git a/frontend/src/components/ExternalUrlAlert.tsx b/frontend/src/components/ExternalUrlAlert.tsxindex aa6b26dae3..eeab29dfef 100644--- a/frontend/src/components/ExternalUrlAlert.tsx+++ b/frontend/src/components/ExternalUrlAlert.tsx@@ -45,6 +45,7 @@ export function ExternalUrlAlert({<RouterLinkto={{name: SETTING_ROUTE_WORKSPACE_GENERAL,+ hash: "#external-url",query: {[PRODUCT_INTRO_QUERY_KEY]: EXTERNAL_URL_PRODUCT_INTRO,},diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.jsonindex 642c4f78cf..f598134234 100644--- a/frontend/src/locales/en-US.json+++ b/frontend/src/locales/en-US.json@@ -44,12 +44,12 @@"context": "Context","context-no-projects": "No accessible projects","context-select": "Select context",- "context-start-new-chat": "Start new chat in {{name}}","context-workspace": "Workspace","delete-all-chats": "Delete all chats","delete-all-chats-confirmation": "Are you sure you want to delete all archived chats? This action cannot be undone.","delete-chat": "Delete chat","delete-chat-confirmation": "Are you sure you want to delete this chat? This action cannot be undone.",+ "input-keyboard-hint": "Enter to send · Shift+Enter for a new line","input-placeholder": "Ask AI anything...","interrupted": "Interrupted","interrupted-retry-hint": "The conversation was interrupted. You can retry or send a new message.",@@ -1604,14 +1604,26 @@}},"landing": {+ "ai-placeholder": "Ask AI about workspace setup, projects, or access",+ "ai-setup": {+ "action": "Configure AI",+ "description": "Configure a provider and model to use AI in this workspace.",+ "title": "Set up AI Assistant"+ },"changelog-for-version": "Changelog for {{version}}","last-visit": "Last visit",+ "onboarding": {+ "completed-progress": "{{completed}} of {{total}} complete",+ "connect-action": "Connect an instance",+ "connect-description": "Connect a database server to {{project}}."+ },"quick-link": {"manage": "Manage quick link",- "self": "Quick Link","visit-issues": "Visit Issues",- "visit-prjects": "Visit Projects"- }+ "visit-prjects": "Visit Projects",+ "yours": "Your quick links"+ },+ "workspace": "Workspace"},"masking": {"reason": {@@ -2018,6 +2030,7 @@"create-database": "Create a database","create-database-description": "Create the first database on a connected instance.","created-by-you": "You created",+ "customize": "Customize","databases": "Databases","databases-load-error": "Databases could not be loaded.","databases-unavailable": "Databases are not available to you in this project.",@@ -2508,9 +2521,9 @@"placeholder": "An API Key usually starts with sk-*****","self": "API Key"},+ "available-in-saas": "AI Assistant is available in this workspace and managed by Bytebase.","description": "Use AI to assist the database development tasks.","enable-ai-assistant": "Enable AI Assistant",- "enabled-in-saas": "Gemini AI is enabled automatically in the SaaS mode.","endpoint": {"description": "Enter the API endpoint for the custom model.","openai-description": "Use a /responses endpoint for the Responses API or /chat/completions for the Chat Completions API.",@@ -2531,7 +2544,8 @@"open_ai": "OpenAI","self": "AI Provider"},- "self": "AI Assistant"+ "self": "AI Assistant",+ "unavailable-in-saas": "AI Assistant isn't available in this workspace. Contact your Bytebase administrator."},"allow-admin-data-source": {"description": "When enabled, users can choose between admin and read-only data sources. When disabled, users are forced to use read-only data sources if configured, otherwise fall back to admin data sources.",diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.jsonindex fe6a169a85..153dc87fed 100644--- a/frontend/src/locales/es-ES.json+++ b/frontend/src/locales/es-ES.json@@ -44,12 +44,12 @@"context": "Contexto","context-no-projects": "No hay proyectos accesibles","context-select": "Seleccionar contexto",- "context-start-new-chat": "Iniciar un chat nuevo en {{name}}","context-workspace": "Espacio de trabajo","delete-all-chats": "Eliminar todos los chats","delete-all-chats-confirmation": "¿Está seguro de que desea eliminar todos los chats archivados? Esta acción no se puede deshacer.","delete-chat": "Eliminar chat","delete-chat-confirmation": "¿Está seguro de que desea eliminar este chat? Esta acción no se puede deshacer.",+ "input-keyboard-hint": "Enter para enviar · Shift+Enter para un salto de línea","input-placeholder": "Pregunta algo a la IA...","interrupted": "Interrumpido","interrupted-retry-hint": "La conversación fue interrumpida. Puede reintentar o enviar un nuevo mensaje.",@@ -1604,14 +1604,26 @@}},"landing": {+ "ai-placeholder": "Pregunta a la IA sobre la configuración del espacio de trabajo, los proyectos o el acceso",+ "ai-setup": {+ "action": "Configurar IA",+ "description": "Configura un proveedor y un modelo para usar la IA en este espacio de trabajo.",+ "title": "Configurar el asistente de IA"+ },"changelog-for-version": "Registro de cambios para {{version}}","last-visit": "Última visita",+ "onboarding": {+ "completed-progress": "{{completed}} de {{total}} completados",+ "connect-action": "Conectar una instancia",+ "connect-description": "Conecta un servidor de bases de datos a {{project}}."+ },"quick-link": {"manage": "Administrar enlace rápido",- "self": "Enlace rápido","visit-issues": "Problemas de visita",- "visit-prjects": "Visitar Proyectos"- }+ "visit-prjects": "Visitar Proyectos",+ "yours": "Tus enlaces rápidos"+ },+ "workspace": "Espacio de trabajo"},"masking": {"reason": {@@ -2018,6 +2030,7 @@"create-database": "Crear una base de datos","create-database-description": "Crea la primera base de datos en una instancia conectada.","created-by-you": "Creado por ti",+ "customize": "Personalizar","databases": "Bases de datos","databases-load-error": "No se pudieron cargar las bases de datos.","databases-unavailable": "Las bases de datos de este proyecto no están disponibles para ti.",@@ -2508,9 +2521,9 @@"placeholder": "Una clave de API generalmente comienza con sk-*****","self": "Clave de API"},+ "available-in-saas": "El Asistente de IA está disponible en este espacio de trabajo y lo administra Bytebase.","description": "Utilice AI para ayudar en las tareas de desarrollo de bases de datos.","enable-ai-assistant": "Habilitar el Asistente de IA",- "enabled-in-saas": "Gemini AI se habilita automáticamente en el modo SaaS.","endpoint": {"description": "Introduzca el endpoint de API para el modelo personalizado.","openai-description": "Use un endpoint /responses para la API Responses o /chat/completions para la API Chat Completions.",@@ -2531,7 +2544,8 @@"open_ai": "OpenAI","self": "Proveedor de IA"},- "self": "Asistente de AI"+ "self": "Asistente de AI",+ "unavailable-in-saas": "El Asistente de IA no está disponible en este espacio de trabajo. Contacte con su administrador de Bytebase."},"allow-admin-data-source": {"description": "Cuando está habilitado, los usuarios pueden elegir entre fuentes de datos de administración y de solo lectura. Cuando está deshabilitado, los usuarios se ven obligados a usar fuentes de datos de solo lectura si están configuradas; de lo contrario, vuelven a usar fuentes de datos de administración.",diff --git a/frontend/src/locales/ja-JP.json b/frontend/src/locales/ja-JP.jsonindex baeb6545ca..2ea965967e 100644--- a/frontend/src/locales/ja-JP.json+++ b/frontend/src/locales/ja-JP.json@@ -44,12 +44,12 @@"context": "コンテキスト","context-no-projects": "アクセス可能なプロジェクトがありません","context-select": "コンテキストを選択",- "context-start-new-chat": "{{name}} で新しいチャットを開始","context-workspace": "ワークスペース","delete-all-chats": "すべてのチャットを削除","delete-all-chats-confirmation": "アーカイブ済みのチャットをすべて削除しますか?この操作は元に戻せません。","delete-chat": "チャットを削除","delete-chat-confirmation": "このチャットを削除しますか?この操作は元に戻せません。",+ "input-keyboard-hint": "Enter で送信・Shift+Enter で改行","input-placeholder": "AI に何でも聞いてください...","interrupted": "中断","interrupted-retry-hint": "会話が中断されました。再試行するか、新しいメッセージを送信できます。",@@ -1604,14 +1604,26 @@}},"landing": {+ "ai-placeholder": "ワークスペースの設定、プロジェクト、アクセスについて AI に質問",+ "ai-setup": {+ "action": "AI を設定",+ "description": "このワークスペースで AI を使用するため、プロバイダーとモデルを設定してください。",+ "title": "AI アシスタントを設定"+ },"changelog-for-version": "{{version}} の変更履歴","last-visit": "最終訪問",+ "onboarding": {+ "completed-progress": "{{total}} 件中 {{completed}} 件完了",+ "connect-action": "インスタンスを接続",+ "connect-description": "データベースサーバーを {{project}} に接続します。"+ },"quick-link": {"manage": "クイックリンクを管理する",- "self": "クイックリンク","visit-issues": "イシューを開く",- "visit-prjects": "プロジェクトを開く"- }+ "visit-prjects": "プロジェクトを開く",+ "yours": "クイックリンク"+ },+ "workspace": "ワークスペース"},"masking": {"reason": {@@ -2018,6 +2030,7 @@"create-database": "データベースを作成","create-database-description": "接続済みインスタンスに最初のデータベースを作成します。","created-by-you": "あなたが作成",+ "customize": "カスタマイズ","databases": "データベース","databases-load-error": "データベースを読み込めませんでした。","databases-unavailable": "このプロジェクトのデータベースは利用できません。",@@ -2508,9 +2521,9 @@"placeholder": "API キーは通常 sk-***** で始まります","self": "APIキー"},+ "available-in-saas": "AI アシスタントはこのワークスペースで利用でき、Bytebase によって管理されています。","description": "AI を使用してデータベース開発タスクを支援します。","enable-ai-assistant": "AIアシスタントを有効にする",- "enabled-in-saas": "Gemini AI は SaaS モードで自動的に有効になります。","endpoint": {"description": "カスタムモデルの API エンドポイントを入力します。","openai-description": "Responses API には /responses、Chat Completions API には /chat/completions のエンドポイントを使用します。",@@ -2531,7 +2544,8 @@"open_ai": "OpenAI","self": "AIプロバイダー"},- "self": "AI アシスタント"+ "self": "AI アシスタント",+ "unavailable-in-saas": "このワークスペースでは AI アシスタントを利用できません。Bytebase 管理者にお問い合わせください。"},"allow-admin-data-source": {"description": "有効にすると、ユーザーは管理データソースと読み取り専用データソースのどちらかを選択できます。無効にすると、読み取り専用データソースが設定されている場合は強制的に読み取り専用データソースを使用し、設定されていない場合は管理データソースにフォールバックします。",diff --git a/frontend/src/locales/vi-VN.json b/frontend/src/locales/vi-VN.jsonindex 9ad504db27..e62df251a3 100644--- a/frontend/src/locales/vi-VN.json+++ b/frontend/src/locales/vi-VN.json@@ -44,12 +44,12 @@"context": "Ngữ cảnh","context-no-projects": "Không có dự án nào có thể truy cập","context-select": "Chọn ngữ cảnh",- "context-start-new-chat": "Bắt đầu cuộc trò chuyện mới trong {{name}}","context-workspace": "Không gian làm việc","delete-all-chats": "Xóa tất cả cuộc trò chuyện","delete-all-chats-confirmation": "Bạn có chắc chắn muốn xóa tất cả cuộc trò chuyện đã lưu trữ không? Hành động này không thể hoàn tác.","delete-chat": "Xóa cuộc trò chuyện","delete-chat-confirmation": "Bạn có chắc chắn muốn xóa cuộc trò chuyện này? Hành động này không thể hoàn tác.",+ "input-keyboard-hint": "Enter để gửi · Shift+Enter để xuống dòng","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.",@@ -1604,14 +1604,26 @@}},"landing": {+ "ai-placeholder": "Hỏi AI về thiết lập không gian làm việc, dự án hoặc quyền truy cập",+ "ai-setup": {+ "action": "Cấu hình AI",+ "description": "Cấu hình nhà cung cấp và mô hình để sử dụng AI trong không gian làm việc này.",+ "title": "Thiết lập Trợ lý AI"+ },"changelog-for-version": "Nhật ký thay đổi cho phiên bản {{version}}","last-visit": "Lần truy cập cuối",+ "onboarding": {+ "completed-progress": "Đã hoàn thành {{completed}}/{{total}}",+ "connect-action": "Kết nối một instance",+ "connect-description": "Kết nối máy chủ cơ sở dữ liệu với {{project}}."+ },"quick-link": {"manage": "Quản lý liên kết nhanh",- "self": "Liên kết nhanh","visit-issues": "Truy cập Vấn đề",- "visit-prjects": "Truy cập Dự án"- }+ "visit-prjects": "Truy cập Dự án",+ "yours": "Liên kết nhanh của bạn"+ },+ "workspace": "Không gian làm việc"},"masking": {"reason": {@@ -2018,6 +2030,7 @@"create-database": "Tạo cơ sở dữ liệu","create-database-description": "Tạo cơ sở dữ liệu đầu tiên trên một phiên bản đã kết nối.","created-by-you": "Bạn đã tạo",+ "customize": "Tùy chỉnh","databases": "Cơ sở dữ liệu","databases-load-error": "Không thể tải cơ sở dữ liệu.","databases-unavailable": "Bạn không thể xem cơ sở dữ liệu trong dự án này.",@@ -2508,9 +2521,9 @@"placeholder": "Khóa API thường bắt đầu bằng sk-*****","self": "Khóa API"},+ "available-in-saas": "Trợ lý AI có sẵn trong workspace này và do Bytebase quản lý.","description": "Sử dụng AI để hỗ trợ các tác vụ phát triển cơ sở dữ liệu.","enable-ai-assistant": "Bật Trợ lý AI",- "enabled-in-saas": "Gemini AI được bật tự động trong chế độ SaaS.","endpoint": {"description": "Nhập endpoint API cho model tùy chỉnh.","openai-description": "Dùng endpoint /responses cho Responses API hoặc /chat/completions cho Chat Completions API.",@@ -2531,7 +2544,8 @@"open_ai": "OpenAI","self": "Nhà cung cấp AI"},- "self": "Trợ lý AI"+ "self": "Trợ lý AI",+ "unavailable-in-saas": "Trợ lý AI không khả dụng trong workspace này. Hãy liên hệ với quản trị viên Bytebase."},"allow-admin-data-source": {"description": "Khi được bật, người dùng có thể chọn giữa nguồn dữ liệu quản trị và nguồn dữ liệu chỉ đọc. Khi bị tắt, người dùng buộc phải sử dụng nguồn dữ liệu chỉ đọc nếu được cấu hình, nếu không sẽ quay lại sử dụng nguồn dữ liệu quản trị.",diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.jsonindex d10a8f5e67..ffbd2626f3 100644--- a/frontend/src/locales/zh-CN.json+++ b/frontend/src/locales/zh-CN.json@@ -44,12 +44,12 @@"context": "上下文","context-no-projects": "没有可访问的项目","context-select": "选择上下文",- "context-start-new-chat": "在 {{name}} 中开始新对话","context-workspace": "工作区","delete-all-chats": "删除所有对话","delete-all-chats-confirmation": "确定要删除所有已归档对话吗?此操作无法撤销。","delete-chat": "删除对话","delete-chat-confirmation": "确定要删除此对话吗?此操作无法撤销。",+ "input-keyboard-hint": "按 Enter 发送 · 按 Shift+Enter 换行","input-placeholder": "向 AI 提问...","interrupted": "已中断","interrupted-retry-hint": "对话已中断。您可以重试或发送新消息。",@@ -1604,14 +1604,26 @@}},"landing": {+ "ai-placeholder": "向 AI 询问工作区设置、项目或访问权限",+ "ai-setup": {+ "action": "配置 AI",+ "description": "配置服务提供方和模型,以在此工作区使用 AI。",+ "title": "设置 AI 助手"+ },"changelog-for-version": "{{version}} 的更新日志","last-visit": "上次访问",+ "onboarding": {+ "completed-progress": "已完成 {{completed}} / {{total}} 项",+ "connect-action": "连接实例",+ "connect-description": "将数据库服务器连接到 {{project}}。"+ },"quick-link": {"manage": "管理快捷访问",- "self": "快捷访问","visit-issues": "访问工单",- "visit-prjects": "访问项目"- }+ "visit-prjects": "访问项目",+ "yours": "你的快捷链接"+ },+ "workspace": "工作空间"},"masking": {"reason": {@@ -2018,6 +2030,7 @@"create-database": "创建数据库","create-database-description": "在已连接的实例中创建首个数据库。","created-by-you": "由你创建",+ "customize": "自定义","databases": "数据库","databases-load-error": "无法加载数据库。","databases-unavailable": "你无法查看此项目的数据库。",@@ -2508,9 +2521,9 @@"placeholder": "API Key 通常以 sk-***** 开头","self": "API Key"},+ "available-in-saas": "AI 助手已在此工作空间中启用,并由 Bytebase 管理。","description": "使用 AI 来辅助数据库开发任务。","enable-ai-assistant": "启用 AI 助手",- "enabled-in-saas": "Gemini AI 在 SaaS 模式下自动启用。","endpoint": {"description": "请输入自定义模型的 API 端点。","openai-description": "Responses API 使用 /responses 端点,Chat Completions API 使用 /chat/completions 端点。",@@ -2531,7 +2544,8 @@"open_ai": "OpenAI","self": "AI 提供方"},- "self": "AI 助手"+ "self": "AI 助手",+ "unavailable-in-saas": "此工作空间尚未启用 AI 助手。请联系 Bytebase 管理员。"},"allow-admin-data-source": {"description": "启用时,用户可以在主数据源和只读数据源之间进行选择。禁用时,如果配置了只读数据源,则强制用户使用只读数据源,否则回退到使用主数据源。",diff --git a/frontend/src/modules/agent/components/AgentContextPicker.tsx b/frontend/src/modules/agent/components/AgentContextPicker.tsxindex 14500427ed..243a50bbdc 100644--- a/frontend/src/modules/agent/components/AgentContextPicker.tsx+++ b/frontend/src/modules/agent/components/AgentContextPicker.tsx@@ -12,7 +12,6 @@ interface AgentContextPickerProps {context?: string;contextTitle?: string;workspace?: { name: string; title: string };- hasMessages: boolean;disabled: boolean;onSelect: (context: string) => boolean;}@@ -24,7 +23,6 @@ interface ContextOptionsProps extends AgentContextPickerProps {function ContextOptions({context,workspace,- hasMessages,onSelect,close,}: ContextOptionsProps) {@@ -37,11 +35,6 @@ function ContextOptions({if (onSelect(resource)) close();};- const optionLabel = (name: string, title: string) =>- hasMessages && name !== context- ? t("agent.context-start-new-chat", { name: title })- : title;-return (<div className="flex max-h-80 flex-col" data-agent-context-options><Input@@ -68,7 +61,7 @@ function ContextOptions({><Building2 className="size-4 shrink-0" /><span className="min-w-0 flex-1 truncate">- {optionLabel(workspace.name, workspace.title || workspace.name)}+ {workspace.title || workspace.name}</span>{context === workspace.name ? <Check className="size-4" /> : null}</Button>@@ -89,7 +82,7 @@ function ContextOptions({<FolderKanban className="size-4 shrink-0" /><span className="min-w-0 flex-1 text-left"><span className="block truncate">- {optionLabel(project.name, project.title || project.name)}+ {project.title || project.name}</span><span className="block truncate text-xs text-control-light">{getProjectName(project.name)}diff --git a/frontend/src/modules/agent/components/AgentInput.test.tsx b/frontend/src/modules/agent/components/AgentInput.test.tsxindex e326ae9472..2f697308a8 100644--- a/frontend/src/modules/agent/components/AgentInput.test.tsx+++ b/frontend/src/modules/agent/components/AgentInput.test.tsx@@ -212,10 +212,7 @@ beforeEach(async () => {mocks.useTranslation.mockReset();mocks.useTranslation.mockReturnValue({- t: (key: string, options?: { name?: string }) =>- key === "agent.context-start-new-chat"- ? `Start new chat in ${options?.name}`- : key,+ t: (key: string) => key,});mocks.routerPush.mockReset();mocks.lazyExtractDomRefSuggestions.mockReset();@@ -252,6 +249,22 @@ afterEach(() => {});describe("AgentInput", () => {+ test("shows the send and newline keyboard hint only in the empty input placeholder", () => {+ const view = renderIntoContainer(<AgentInput />);+ view.render();+ expect(view.container.querySelector("[data-agent-input-placeholder]")?.textContent).toContain(+ "agent.input-keyboard-hint"+ );+ const textarea = view.container.querySelector("textarea") as HTMLTextAreaElement;+ act(() => {+ setTextareaValue(textarea, "List databases");+ textarea.dispatchEvent(new Event("input", { bubbles: true }));+ });+ expect(view.container.querySelector("[data-agent-input-placeholder]")).toBeNull();+ expect(view.container.textContent).not.toContain("agent.input-keyboard-hint");+ view.unmount();+ });+test("sends a queued Project Home message in its bound chat once", async () => {mocks.runAgentLoop.mockResolvedValue({ kind: "completed", totalTokensUsed: 0 });const page = { path: "/projects/billing", title: "Billing" };@@ -420,7 +433,7 @@ describe("AgentInput", () => {unmount();});- test("starts a new chat when choosing a different context after a message", async () => {+ test("changes the current chat context after a message", async () => {const original = useAgentStore.getState().ensureCurrentChat(undefined, "projects/orders");@@ -439,7 +452,8 @@ describe("AgentInput", () => {.querySelector<HTMLButtonElement>("[data-agent-context-trigger]")?.click();});- expect(document.body.textContent).toContain("Start new chat in Billing");+ expect(document.body.textContent).not.toContain("Start new chat in Billing");+ expect(document.body.textContent).toContain("Billing");await act(async () => {document.querySelector<HTMLButtonElement>(@@ -448,16 +462,29 @@ describe("AgentInput", () => {?.click();});- expect(useAgentStore.getState().chats).toHaveLength(2);+ expect(useAgentStore.getState().chats).toHaveLength(1);expect(useAgentStore.getState().getChat(original.id)?.context).toBe(- "projects/orders"+ "projects/billing");expect(useAgentStore.getState().getMessages(original.id)).toHaveLength(1);- expect(- useAgentStore- .getState()- .getChat(useAgentStore.getState().currentChatId)?.context- ).toBe("projects/billing");+ expect(useAgentStore.getState().currentChatId).toBe(original.id);++ mocks.runAgentLoop.mockResolvedValue({+ kind: "completed",+ totalTokensUsed: 0,+ });+ const textarea = container.querySelector("textarea") as HTMLTextAreaElement;+ await act(async () => {+ setTextareaValue(textarea, "What about this project?");+ textarea.dispatchEvent(new Event("input", { bubbles: true }));+ });+ await act(async () => {+ (container.querySelector("[data-agent-send]") as HTMLButtonElement).click();+ await Promise.resolve();+ });+ expect(mocks.buildSystemPrompt).toHaveBeenLastCalledWith(+ expect.objectContaining({ context: "projects/billing" })+ );unmount();});@@ -741,7 +768,9 @@ describe("AgentInput", () => {const placeholder = container.querySelector("[data-agent-input-placeholder]");- expect(placeholder?.textContent).toBe("agent.input-placeholder");+ expect(placeholder?.textContent).toBe(+ "agent.input-placeholder · agent.input-keyboard-hint"+ );expect(placeholder?.className).toContain("truncate");expect(placeholder?.className).toContain("pointer-events-none");expect(placeholder?.className).toContain("inset-y-0");diff --git a/frontend/src/modules/agent/components/AgentInput.tsx b/frontend/src/modules/agent/components/AgentInput.tsxindex 2f94440cd3..889336514a 100644--- a/frontend/src/modules/agent/components/AgentInput.tsx+++ b/frontend/src/modules/agent/components/AgentInput.tsx@@ -119,9 +119,6 @@ export function AgentInput() {const currentPendingAsk = useAgentStore(selectCurrentPendingAsk);const loading = useAgentStore(selectLoading);const hasRunningChat = useAgentStore(selectHasRunningChat);- const hasMessages = useAgentStore((s) =>- Boolean(s.messagesByChatId[s.currentChatId ?? ""]?.length)- );const isAIConfigurationBlocked = useAgentStore(selectCurrentChatRequiresAIConfiguration);@@ -852,7 +849,6 @@ export function AgentInput() {context={context}contextTitle={contextTitle}workspace={workspace}- hasMessages={hasMessages}disabled={hasRunningChat || Boolean(currentPendingAsk)}onSelect={selectContext}/>@@ -905,7 +901,6 @@ export function AgentInput() {))}</div>) : (- /* Input row with @-mention autocomplete */<div className="relative flex items-end gap-x-2" data-agent-input-row><div className="relative w-full">{!input && (@@ -913,7 +908,7 @@ export function AgentInput() {className="pointer-events-none absolute inset-x-3 inset-y-0 z-10 flex items-center truncate text-sm leading-5 text-control-light"data-agent-input-placeholder>- {inputPlaceholder}+ {inputPlaceholder} · {t("agent.input-keyboard-hint")}</div>)}<Textareadiff --git a/frontend/src/modules/agent/store/agent.test.ts b/frontend/src/modules/agent/store/agent.test.tsindex 8d4e193b60..6d33bcb900 100644--- a/frontend/src/modules/agent/store/agent.test.ts+++ b/frontend/src/modules/agent/store/agent.test.ts@@ -155,7 +155,7 @@ describe("useAgentStore (Zustand)", () => {);});- test("starts a new chat when changing the context of a populated chat", () => {+ test("changes the context of a populated chat without losing its history", () => {const store = createAgentStore();const original = s(store).ensureCurrentChat(undefined, "projects/orders");s(store).addMessage({@@ -169,14 +169,26 @@ describe("useAgentStore (Zustand)", () => {title: "Orders",});- expect(selected?.id).not.toBe(original.id);+ expect(selected?.id).toBe(original.id);expect(selected?.context).toBe("projects/billing");- expect(s(store).currentChatId).toBe(selected?.id);- expect(s(store).getMessages(selected?.id)).toEqual([]);- expect(s(store).getChat(original.id)?.context).toBe("projects/orders");+ expect(s(store).chats).toHaveLength(1);+ expect(s(store).currentChatId).toBe(original.id);expect(s(store).getMessages(original.id)).toHaveLength(1);});+ test("adds context to a populated chat that has none", () => {+ const store = createAgentStore();+ const chat = s(store).ensureCurrentChat();+ s(store).addMessage({ chatId: chat.id, role: "user", content: "Hello" });++ const selected = s(store).selectChatContext("projects/billing");++ expect(selected?.id).toBe(chat.id);+ expect(selected?.context).toBe("projects/billing");+ expect(s(store).chats).toHaveLength(1);+ expect(s(store).getMessages(chat.id)).toHaveLength(1);+ });+test("does not change context while any chat is running", () => {const store = createAgentStore();const chat = s(store).ensureCurrentChat(undefined, "projects/orders");diff --git a/frontend/src/modules/agent/store/agent.ts b/frontend/src/modules/agent/store/agent.tsindex be1795e870..7d4bba3f09 100644--- a/frontend/src/modules/agent/store/agent.ts+++ b/frontend/src/modules/agent/store/agent.ts@@ -816,9 +816,6 @@ export const createAgentStore = () => {if (!current) return get().createChat({ page, context });if (current.context === context) return current;if (get().getPendingAsk(current.id)) return null;- if (get().getMessages(current.id).length > 0) {- return get().createChat({ page, context });- }set((state) => {const chat = state.chats.find((c) => c.id === current.id);if (chat) {diff --git a/frontend/src/modules/sql-editor/components/SQLEditorHomePage.test.tsx b/frontend/src/modules/sql-editor/components/SQLEditorHomePage.test.tsxindex f56faf3671..8a3163a8cf 100644--- a/frontend/src/modules/sql-editor/components/SQLEditorHomePage.test.tsx+++ b/frontend/src/modules/sql-editor/components/SQLEditorHomePage.test.tsx@@ -2,6 +2,7 @@ import type { ReactElement } from "react";import { act } from "react";import { createRoot } from "react-dom/client";import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";+import { useSharedGuideContext } from "@/modules/workspace-setup-guide/GuideContextProvider";(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT =true;@@ -42,6 +43,7 @@ vi.mock("react-resizable-panels", () => ({}));vi.mock("@/app/router", () => ({+ useCurrentRoute: () => ({ name: "workspace.sql-editor", params: {} }),useNavigate: () => ({resolve: vi.fn(() => ({ fullPath: "/plans/create" })),}),@@ -52,7 +54,23 @@ vi.mock("@/components/IAMRemindDialog", () => ({}));vi.mock("@/modules/workspace-setup-guide/WorkspaceSetupGuide", () => ({- WorkspaceSetupGuide: () => <div>unified-guide</div>,+ WorkspaceSetupGuide: () => {+ const { contextReady } = useSharedGuideContext();+ return <div>{contextReady ? "unified-guide" : "loading-guide"}</div>;+ },+}));++vi.mock("@/hooks/useAppState", () => ({+ useIntroStateByKey: () => false,+}));++vi.mock("@/modules/workspace-setup-guide/selection", () => ({+ readGuideWorkspaceUsage: () => undefined,+ readSelectedGuideScenarioId: () => undefined,+}));++vi.mock("@/modules/workspace-setup-guide/useGuideContext", () => ({+ useGuideContext: () => ({ context: {}, contextReady: true }),}));vi.mock("@/components/ui/layer", () => ({@@ -128,7 +146,8 @@ vi.mock("@/modules/sql-editor/store/tab", () => ({vi.mock("@/stores/app", () => ({useAppStore: Object.assign(- (selector: (state: unknown) => unknown) => selector({}),+ (selector: (state: unknown) => unknown) =>+ selector({ workspaceSetupGuideEnabled: () => true }),{ getState: vi.fn() }),}));diff --git a/frontend/src/modules/sql-editor/components/SQLEditorHomePage.tsx b/frontend/src/modules/sql-editor/components/SQLEditorHomePage.tsxindex fa857793fe..29446599b3 100644--- a/frontend/src/modules/sql-editor/components/SQLEditorHomePage.tsx+++ b/frontend/src/modules/sql-editor/components/SQLEditorHomePage.tsx@@ -38,6 +38,7 @@ import {useCurrentSQLEditorTab,useIsDisconnected,} from "@/modules/sql-editor/store/tab";+import { GuideContextProvider } from "@/modules/workspace-setup-guide/GuideContextProvider";import { WorkspaceSetupGuide } from "@/modules/workspace-setup-guide/WorkspaceSetupGuide";import { useAppStore } from "@/stores/app";import { unknownProject } from "@/types";@@ -271,7 +272,9 @@ export function SQLEditorHomePage() {</Panel></PanelGroup>- <WorkspaceSetupGuide />+ <GuideContextProvider>+ <WorkspaceSetupGuide />+ </GuideContextProvider>{projectContextReady && project && <IAMRemindDialog project={project} />}<ConnectionPanel />diff --git a/frontend/src/modules/workspace-setup-guide/GuideContextProvider.test.tsx b/frontend/src/modules/workspace-setup-guide/GuideContextProvider.test.tsxnew file mode 100644index 0000000000..8a64a781c8--- /dev/null+++ b/frontend/src/modules/workspace-setup-guide/GuideContextProvider.test.tsx@@ -0,0 +1,77 @@+import { render, screen } from "@testing-library/react";+import { describe, expect, test, vi } from "vitest";+import {+ GuideContextProvider,+ useSharedGuideContext,+} from "./GuideContextProvider";++const mocks = vi.hoisted(() => ({+ dismissed: false,+ route: { name: "workspace.landing", params: {} },+ useGuideContext: vi.fn(+ ({ dismissed }: { dismissed: boolean }) => ({+ context: { projectName: "projects/orders" },+ contextReady: !dismissed,+ })+ ),+}));++vi.mock("@/app/router", () => ({+ useCurrentRoute: () => mocks.route,+}));+vi.mock("@/hooks/useAppState", () => ({+ useIntroStateByKey: (key: string) =>+ key === "workspace-setup-guide.dismissed" && mocks.dismissed,+}));+vi.mock("@/stores/app", () => ({+ useAppStore: (selector: (state: object) => unknown) =>+ selector({ workspaceSetupGuideEnabled: () => true }),+}));+vi.mock("./selection", () => ({+ readGuideWorkspaceUsage: () => undefined,+ readSelectedGuideScenarioId: () => undefined,+}));+vi.mock("./useGuideContext", () => ({+ useGuideContext: mocks.useGuideContext,+}));++function GuideConsumer({ label }: { label: string }) {+ const { context, contextReady } = useSharedGuideContext();+ return (+ <div>+ {label}: {contextReady ? context.projectName : "loading"}+ </div>+ );+}++describe("GuideContextProvider", () => {+ test("shares one guide context with the landing and bottom surfaces", () => {+ mocks.dismissed = false;+ mocks.useGuideContext.mockClear();+ const view = render(+ <GuideContextProvider>+ <GuideConsumer label="landing" />+ <GuideConsumer label="bottom" />+ </GuideContextProvider>+ );++ expect(screen.getByText("landing: projects/orders")).toBeVisible();+ expect(screen.getByText("bottom: projects/orders")).toBeVisible();+ expect(mocks.useGuideContext).toHaveBeenCalledTimes(1);++ mocks.dismissed = true;+ view.rerender(+ <GuideContextProvider>+ <GuideConsumer label="landing" />+ <GuideConsumer label="bottom" />+ </GuideContextProvider>+ );++ expect(screen.getByText("landing: loading")).toBeVisible();+ expect(screen.getByText("bottom: loading")).toBeVisible();+ expect(mocks.useGuideContext).toHaveBeenCalledTimes(2);+ expect(mocks.useGuideContext).toHaveBeenLastCalledWith(+ expect.objectContaining({ dismissed: true, route: mocks.route })+ );+ });+});diff --git a/frontend/src/modules/workspace-setup-guide/GuideContextProvider.tsx b/frontend/src/modules/workspace-setup-guide/GuideContextProvider.tsxnew file mode 100644index 0000000000..3ca62974c7--- /dev/null+++ b/frontend/src/modules/workspace-setup-guide/GuideContextProvider.tsx@@ -0,0 +1,56 @@+import { createContext, type ReactNode, useContext, useMemo } from "react";+import { useCurrentRoute } from "@/app/router";+import { useIntroStateByKey } from "@/hooks/useAppState";+import { useAppStore } from "@/stores/app";+import {+ GUIDE_PROGRESS_KEYS,+ guideCompletionAcknowledgedKey,+} from "./progress";+import { getGuideJourney } from "./scenarios";+import {+ readGuideWorkspaceUsage,+ readSelectedGuideScenarioId,+} from "./selection";+import { useGuideContext } from "./useGuideContext";++type SharedGuideContext = ReturnType<typeof useGuideContext>;++const GuideContext = createContext<SharedGuideContext | null>(null);++export function GuideContextProvider({ children }: { children: ReactNode }) {+ const route = useCurrentRoute();+ const scenarioId = readSelectedGuideScenarioId();+ const workspaceUsage = readGuideWorkspaceUsage();+ const journey = useMemo(+ () => getGuideJourney(scenarioId, workspaceUsage),+ [scenarioId, workspaceUsage]+ );+ const dismissed = useIntroStateByKey(GUIDE_PROGRESS_KEYS.dismissed);+ const completionAcknowledged = useIntroStateByKey(+ guideCompletionAcknowledgedKey(journey.id)+ );+ const allowMultipleMembers =+ workspaceUsage === "team" && !completionAcknowledged;+ const enabled = useAppStore((state) =>+ state.workspaceSetupGuideEnabled(allowMultipleMembers)+ );+ const value = useGuideContext({+ enabled,+ dismissed,+ route,+ scenarioId,+ workspaceUsage,+ });++ return (+ <GuideContext.Provider value={value}>{children}</GuideContext.Provider>+ );+}++export function useSharedGuideContext(): SharedGuideContext {+ const value = useContext(GuideContext);+ if (!value) {+ throw new Error("GuideContextProvider is required");+ }+ return value;+}diff --git a/frontend/src/modules/workspace-setup-guide/WorkspaceHomeGettingStarted.tsx b/frontend/src/modules/workspace-setup-guide/WorkspaceHomeGettingStarted.tsxnew file mode 100644index 0000000000..8f7265197d--- /dev/null+++ b/frontend/src/modules/workspace-setup-guide/WorkspaceHomeGettingStarted.tsx@@ -0,0 +1,138 @@+import { CheckCircle, ListChecks, X } from "lucide-react";+import { useTranslation } from "react-i18next";+import { SQLEditorButton } from "@/components/SQLEditorButton";+import { Button } from "@/components/ui/button";+import { Tooltip } from "@/components/ui/tooltip";+import { cn } from "@/lib/utils";+import { useAppStore } from "@/stores/app";+import type { GuideAction, ResolvedGuide, ResolvedGuideStep } from "./types";++export function WorkspaceHomeGettingStarted({+ guide,+ projectName,+ onSelectStep,+ onCaptureStepAction,+ onDismiss,+}: {+ guide: ResolvedGuide;+ projectName: string;+ onSelectStep: (step: ResolvedGuideStep) => void;+ onCaptureStepAction: (step: ResolvedGuideStep, action: GuideAction) => void;+ onDismiss: () => void;+}) {+ const { t } = useTranslation();+ const actionStep = guide.activeStep;+ const action = actionStep?.actions.primary;+ const actionLabel = actionStep+ ? actionStep.definition.id === "connect-instance"+ ? t("landing.onboarding.connect-action")+ : t(actionStep.definition.labelKey)+ : undefined;+ const projectTitle = useAppStore(+ (state) => state.projectsByName?.[projectName]?.title+ );+ const completedStepCount = guide.steps.filter((step) => step.done).length;++ return (+ <section data-testid="workspace-home-getting-started" className="min-w-0">+ <div className="flex flex-wrap items-center justify-between gap-2 pb-4">+ <h2 className="text-base font-semibold text-main">+ {t("workspace-setup-guide.getting-started")}+ </h2>+ <span className="text-xs text-control-light">+ {t("landing.onboarding.completed-progress", {+ completed: completedStepCount,+ total: guide.steps.length,+ })}+ </span>+ </div>++ <div className="flex min-w-0 flex-wrap items-center gap-4 border-y border-block-border py-5">+ <span className="flex size-8 shrink-0 items-center justify-center rounded-full border border-accent text-accent">+ {guide.complete ? (+ <CheckCircle className="size-4" />+ ) : (+ <ListChecks className="size-4" />+ )}+ </span>+ <div className="min-w-0 flex-1">+ <div className="text-sm font-semibold text-main">+ {actionLabel ?? t("workspace-setup-guide.all-steps-completed")}+ </div>+ {actionStep && (+ <p className="mt-1 text-xs text-control-light">+ {actionStep.definition.id === "connect-instance" && projectTitle+ ? t("landing.onboarding.connect-description", {+ project: projectTitle,+ })+ : t(actionStep.definition.descriptionKey)}+ </p>+ )}+ </div>+ {actionStep &&+ actionStep.actions.select &&+ (action?.type === "open-sql-editor" ? (+ <span+ onClickCapture={() => onCaptureStepAction(actionStep, action)}+ >+ <SQLEditorButton+ data-testid="workspace-home-next-action"+ database={action.database}+ query={action.query}+ openInNewTab+ size="sm"+ label={actionLabel}+ />+ </span>+ ) : (+ <Button+ type="button"+ size="sm"+ className="shrink-0"+ data-testid="workspace-home-next-action"+ onClick={() => onSelectStep(actionStep)}+ >+ {actionLabel}+ </Button>+ ))}+ {guide.complete && (+ <Tooltip content={t("workspace-setup-guide.dismiss")}>+ <Button+ type="button"+ size="sm"+ appearance="secondary"+ aria-label={t("workspace-setup-guide.dismiss")}+ onClick={onDismiss}+ >+ <X className="size-4" />+ </Button>+ </Tooltip>+ )}+ </div>++ <div className="flex flex-wrap items-center gap-x-2 gap-y-1 pt-3">+ {guide.steps.map((step, index) => (+ <div+ key={step.definition.id}+ className="inline-flex items-center gap-x-2"+ >+ {index > 0 && <span className="text-xs text-control-light">/</span>}+ <span+ className={cn(+ "inline-flex items-center gap-x-1 text-xs",+ step.done+ ? "text-success"+ : step.definition.id === actionStep?.definition.id+ ? "font-semibold text-main"+ : "text-control-light"+ )}+ >+ {step.done && <CheckCircle className="size-3" />}+ {t(step.definition.labelKey)}+ </span>+ </div>+ ))}+ </div>+ </section>+ );+}diff --git a/frontend/src/modules/workspace-setup-guide/WorkspaceSetupGuide.test.tsx b/frontend/src/modules/workspace-setup-guide/WorkspaceSetupGuide.test.tsxindex 4d57eb7050..732b4e455f 100644--- a/frontend/src/modules/workspace-setup-guide/WorkspaceSetupGuide.test.tsx+++ b/frontend/src/modules/workspace-setup-guide/WorkspaceSetupGuide.test.tsx@@ -149,8 +149,8 @@ vi.mock("./selection", () => ({readSelectedGuideScenarioId: () => mocks.scenarioId,}));-vi.mock("./useGuideContext", () => ({- useGuideContext: () => ({+vi.mock("./GuideContextProvider", () => ({+ useSharedGuideContext: () => ({context: mocks.guideContext,contextReady: mocks.contextReady,}),diff --git a/frontend/src/modules/workspace-setup-guide/WorkspaceSetupGuide.tsx b/frontend/src/modules/workspace-setup-guide/WorkspaceSetupGuide.tsxindex a09ec3bb6a..e34723cd0c 100644--- a/frontend/src/modules/workspace-setup-guide/WorkspaceSetupGuide.tsx+++ b/frontend/src/modules/workspace-setup-guide/WorkspaceSetupGuide.tsx@@ -26,6 +26,7 @@ import { PRODUCT_INTRO_QUERY_KEY } from "@/lib/productIntro";import { cn } from "@/lib/utils";import { useAppStore } from "@/stores/app";import { getGuideAnalyticsProperties } from "./analytics";+import { useSharedGuideContext } from "./GuideContextProvider";import {GUIDE_PROGRESS_KEYS,guideCompletionAcknowledgedKey,@@ -39,7 +40,6 @@ import {} from "./selection";import { GUIDE_STEP_DEFINITIONS } from "./steps";import type { GuideAction, GuideStepId, ResolvedGuideStep } from "./types";-import { useGuideContext } from "./useGuideContext";export function WorkspaceSetupGuide() {const { i18n, t } = useTranslation();@@ -64,13 +64,7 @@ export function WorkspaceSetupGuide() {const productModelAvailable = !!getHowBytebaseWorksGuideContent(i18n.resolvedLanguage ?? "en-US");- const { context, contextReady } = useGuideContext({- enabled: guideEnabled,- dismissed,- route: currentRoute,- scenarioId,- workspaceUsage,- });+ const { context, contextReady } = useSharedGuideContext();const hasContextualProductIntro =typeof currentRoute.query?.[PRODUCT_INTRO_QUERY_KEY] === "string";const [productModelOpen, setProductModelOpen] = useState(false);diff --git a/frontend/src/routes/auth/WorkspaceSetupPage.test.tsx b/frontend/src/routes/auth/WorkspaceSetupPage.test.tsxindex 967e2354e6..874292a535 100644--- a/frontend/src/routes/auth/WorkspaceSetupPage.test.tsx+++ b/frontend/src/routes/auth/WorkspaceSetupPage.test.tsx@@ -13,13 +13,15 @@ import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";import { skipErrorNotificationContextKey } from "@/api/context-key";import { SplashPanelContext } from "@/app/layouts/SplashLayout";import {- PROJECT_V1_ROUTE_DASHBOARD,- PROJECT_V1_ROUTE_DETAIL,+ PROJECT_V1_ROUTE_DATABASES,+ PROJECT_V1_ROUTE_INSTANCES,+ WORKSPACE_ROUTE_LANDING,} from "@/app/router/handles";import "@/lib/i18n";import {- CREATE_PROJECT_PRODUCT_INTRO,+ CREATE_INSTANCE_PRODUCT_INTRO,PRODUCT_INTRO_QUERY_KEY,+ PROJECT_INSTANCE_SYNCED_PRODUCT_INTRO,} from "@/lib/productIntro";import {readGuideTeamSize,@@ -382,7 +384,11 @@ beforeEach(() => {if (!project) throw new ConnectError("not found", Code.NotFound);return project;});- mocks.prepareSampleProjectInstance.mockResolvedValue({});+ mocks.prepareSampleProjectInstance.mockImplementation(async (project: string) => {+ const name = `${project}/instances/sample`;+ mocks.sample.instances = [{ instance: name }];+ return { name };+ });mocks.getProjectIamPolicy.mockImplementation(async () => server.projectPolicy);@@ -750,8 +756,7 @@ describe("WorkspaceSetupPage", () => {await landed();expect(mocks.routerReplace).toHaveBeenCalledWith({- name: PROJECT_V1_ROUTE_DASHBOARD,- query: { [PRODUCT_INTRO_QUERY_KEY]: CREATE_PROJECT_PRODUCT_INTRO },+ name: WORKSPACE_ROUTE_LANDING,});expect(writes()).toEqual(["updateUser", "updateWorkspace"]);expect(readSelectedGuideScenarioId()).toBe("create-database-change");@@ -970,8 +975,7 @@ describe("WorkspaceSetupPage", () => {await landed();expect(mocks.routerReplace).toHaveBeenCalledWith({- name: PROJECT_V1_ROUTE_DASHBOARD,- query: { [PRODUCT_INTRO_QUERY_KEY]: CREATE_PROJECT_PRODUCT_INTRO },+ name: WORKSPACE_ROUTE_LANDING,});expect(writes()).toEqual(["updateUser", "updateWorkspace"]);expect(readSelectedGuideScenarioId()).toBe("create-database-change");@@ -2003,14 +2007,18 @@ describe("WorkspaceSetupPage", () => {await landed();expect(mocks.routerReplace).toHaveBeenCalledWith({- name: PROJECT_V1_ROUTE_DETAIL,+ name: PROJECT_V1_ROUTE_DATABASES,params: { projectId: "payments-ab12" },+ query: {+ syncingInstance: "sample",+ [PRODUCT_INTRO_QUERY_KEY]: PROJECT_INSTANCE_SYNCED_PRODUCT_INTRO,+ },});});});describe("Finish", () => {- test("creates nothing before Finish, then everything in order, and lands on the project home", async () => {+ test("creates nothing before Finish, then everything in order, and opens project databases", async () => {await startAtTeam({ goal: CHANGE_GOAL });fireEvent.click(screen.getByText("2–10"));enterAddress("[email protected]");@@ -2076,8 +2084,32 @@ describe("WorkspaceSetupPage", () => {REPORT);expect(mocks.routerReplace).toHaveBeenCalledWith({- name: PROJECT_V1_ROUTE_DETAIL,+ name: PROJECT_V1_ROUTE_DATABASES,+ params: { projectId: "payments-ab12" },+ query: {+ syncingInstance: "sample",+ [PRODUCT_INTRO_QUERY_KEY]: PROJECT_INSTANCE_SYNCED_PRODUCT_INTRO,+ },+ });+ });++ test("keeps the sample instance sync hint when server info is not refreshed", async () => {+ mocks.prepareSampleProjectInstance.mockResolvedValueOnce({+ name: "projects/payments-ab12/instances/sample",+ });+ await startAtTeam();++ finishAlone();++ await landed();+ expect(mocks.sample.instances).toEqual([]);+ expect(mocks.routerReplace).toHaveBeenCalledWith({+ name: PROJECT_V1_ROUTE_DATABASES,params: { projectId: "payments-ab12" },+ query: {+ syncingInstance: "sample",+ [PRODUCT_INTRO_QUERY_KEY]: PROJECT_INSTANCE_SYNCED_PRODUCT_INTRO,+ },});});@@ -2173,15 +2205,16 @@ describe("WorkspaceSetupPage", () => {]);});- test("finishes the own-instance path with an empty project, on the project home", async () => {+ test("finishes the own-instance path on project instances", async () => {await startAtTeam({ database: OWN_INSTANCE });finishAlone();await landed();expect(writes()).toEqual(["updateUser", "updateWorkspace", "createProject"]);expect(mocks.routerReplace).toHaveBeenCalledWith({- name: PROJECT_V1_ROUTE_DETAIL,+ name: PROJECT_V1_ROUTE_INSTANCES,params: { projectId: "payments-ab12" },+ query: { [PRODUCT_INTRO_QUERY_KEY]: CREATE_INSTANCE_PRODUCT_INTRO },});});@@ -2392,6 +2425,9 @@ describe("WorkspaceSetupPage", () => {});test("tries again without creating the project or requesting the sample twice", async () => {+ mocks.prepareSampleProjectInstance.mockResolvedValueOnce({+ name: "projects/payments-ab12/instances/sample",+ });mocks.patchWorkspaceIamPolicy.mockRejectedValueOnce(unavailable());await startAtTeam();finishInviting("[email protected]");@@ -2413,6 +2449,15 @@ describe("WorkspaceSetupPage", () => {"workspaceMembers",]);expect(screen.queryByRole("alert")).not.toBeInTheDocument();+ expect(mocks.sample.instances).toEqual([]);+ expect(mocks.routerReplace).toHaveBeenCalledWith({+ name: PROJECT_V1_ROUTE_DATABASES,+ params: { projectId: "payments-ab12" },+ query: {+ syncingInstance: "sample",+ [PRODUCT_INTRO_QUERY_KEY]: PROJECT_INSTANCE_SYNCED_PRODUCT_INTRO,+ },+ });});test("drops an invitee removed after a failed attempt from the project too", async () => {@@ -2804,8 +2849,9 @@ describe("WorkspaceSetupPage", () => {await landed();expect(mocks.createProject).not.toHaveBeenCalled();expect(mocks.routerReplace).toHaveBeenCalledWith({- name: PROJECT_V1_ROUTE_DETAIL,+ name: PROJECT_V1_ROUTE_INSTANCES,params: { projectId: "payments-ab12" },+ query: { [PRODUCT_INTRO_QUERY_KEY]: CREATE_INSTANCE_PRODUCT_INTRO },});});@@ -3207,7 +3253,7 @@ describe("WorkspaceSetupPage", () => {expect(screen.getByText("This setup ended in another tab")).toBeInTheDocument();expect(mocks.routerReplace).toHaveBeenCalledWith({- name: PROJECT_V1_ROUTE_DASHBOARD,+ name: WORKSPACE_ROUTE_LANDING,});});});@@ -3421,8 +3467,12 @@ describe("WorkspaceSetupPage", () => {fireEvent.click(finishButton());await landed();expect(mocks.routerReplace).toHaveBeenCalledWith({- name: PROJECT_V1_ROUTE_DETAIL,+ name: PROJECT_V1_ROUTE_DATABASES,params: { projectId: "orders-ab12" },+ query: {+ syncingInstance: "sample",+ [PRODUCT_INTRO_QUERY_KEY]: PROJECT_INSTANCE_SYNCED_PRODUCT_INTRO,+ },});});@@ -3482,8 +3532,12 @@ describe("WorkspaceSetupPage", () => {expect(mocks.createProject).toHaveBeenCalledTimes(2);expect(server.projects.size).toBe(1);expect(mocks.routerReplace).toHaveBeenCalledWith({- name: PROJECT_V1_ROUTE_DETAIL,+ name: PROJECT_V1_ROUTE_DATABASES,params: { projectId: "payments-ab12" },+ query: {+ syncingInstance: "sample",+ [PRODUCT_INTRO_QUERY_KEY]: PROJECT_INSTANCE_SYNCED_PRODUCT_INTRO,+ },});});diff --git a/frontend/src/routes/auth/WorkspaceSetupPage.tsx b/frontend/src/routes/auth/WorkspaceSetupPage.tsxindex 60104b80b2..d4ec95b47a 100644--- a/frontend/src/routes/auth/WorkspaceSetupPage.tsx+++ b/frontend/src/routes/auth/WorkspaceSetupPage.tsx@@ -6,8 +6,9 @@ import { behaviorAnalytics } from "@/app/analytics/provider";import { SplashPanel } from "@/app/layouts/SplashLayout";import { router } from "@/app/router";import {- PROJECT_V1_ROUTE_DASHBOARD,- PROJECT_V1_ROUTE_DETAIL,+ PROJECT_V1_ROUTE_DATABASES,+ PROJECT_V1_ROUTE_INSTANCES,+ WORKSPACE_ROUTE_LANDING,} from "@/app/router/handles";import { Button } from "@/components/ui/button";import {@@ -17,8 +18,9 @@ import {useWorkspacePermission,} from "@/hooks/useAppState";import {- CREATE_PROJECT_PRODUCT_INTRO,+ CREATE_INSTANCE_PRODUCT_INTRO,PRODUCT_INTRO_QUERY_KEY,+ PROJECT_INSTANCE_SYNCED_PRODUCT_INTRO,} from "@/lib/productIntro";import {saveGuideTeamSize,@@ -28,6 +30,7 @@ import { saveWorkspaceSetupFinished } from "@/modules/workspace-setup-guide/setuimport { useAppStore } from "@/stores/app";import { projectNamePrefix } from "@/stores/modules/v1/common";import type { ValidatedMessage } from "@/types";+import { extractInstanceResourceName } from "@/utils";import { extractProjectResourceName } from "@/utils/v1/project";import {clearSetupDraft,@@ -309,11 +312,10 @@ function WorkspaceSetupWizard() {workspaceTitle: workspaceTitle.trim(),};- // The projects page, which offers to create the first one.+ // Self-hosted setup may finish without a project.const leaveWithoutProject = () =>router.replace({- name: PROJECT_V1_ROUTE_DASHBOARD,- query: { [PRODUCT_INTRO_QUERY_KEY]: CREATE_PROJECT_PRODUCT_INTRO },+ name: WORKSPACE_ROUTE_LANDING,});// Self-hosted only: setup is offered once there and may be left for later.@@ -390,7 +392,8 @@ function WorkspaceSetupWizard() {{projectCreateSent: () => save({ attemptedProjectId: draft.projectId }),projectCreated: (createdProject) => save({ createdProject }),- samplePrepared: () => save({ samplePrepared: true }),+ samplePrepared: (sampleInstanceName) =>+ save({ samplePrepared: true, sampleInstanceName }),projectGrants: (projectGrants) => save({ projectGrants }),});@@ -441,9 +444,32 @@ function WorkspaceSetupWizard() {// Everything exists on the server; a browser that cannot store the// recent project must still leave the wizard.}+ const projectId = extractProjectResourceName(result.project);+ const sampleInstanceName =+ finishSource === "sample"+ ? (draftRef.current.sampleInstanceName ??+ useAppStore+ .getState()+ .serverInfo?.sample?.instances.find(({ instance }) =>+ instance.startsWith(`${result.project}/`)+ )?.instance)+ : undefined;router.replace({- name: PROJECT_V1_ROUTE_DETAIL,- params: { projectId: extractProjectResourceName(result.project) },+ name:+ finishSource === "sample"+ ? PROJECT_V1_ROUTE_DATABASES+ : PROJECT_V1_ROUTE_INSTANCES,+ params: { projectId },+ query:+ finishSource === "sample"+ ? {+ ...(sampleInstanceName && {+ syncingInstance:+ extractInstanceResourceName(sampleInstanceName),+ }),+ [PRODUCT_INTRO_QUERY_KEY]: PROJECT_INSTANCE_SYNCED_PRODUCT_INTRO,+ }+ : { [PRODUCT_INTRO_QUERY_KEY]: CREATE_INSTANCE_PRODUCT_INTRO },});};@@ -561,9 +587,7 @@ function WorkspaceSetupWizard() {</h1>{elsewhere === "ended" ? (<Button- onClick={() =>- router.replace({ name: PROJECT_V1_ROUTE_DASHBOARD })- }+ onClick={() => router.replace({ name: WORKSPACE_ROUTE_LANDING })}>{t("workspace-setup.elsewhere.workspace")}</Button>diff --git a/frontend/src/routes/auth/workspace-setup/draft.ts b/frontend/src/routes/auth/workspace-setup/draft.tsindex 3f33e7bfcb..fc0a1951bc 100644--- a/frontend/src/routes/auth/workspace-setup/draft.ts+++ b/frontend/src/routes/auth/workspace-setup/draft.ts@@ -41,6 +41,7 @@ export type SetupDraft = {// project's name, ID and prepared sample are fixed.createdProject?: string;samplePrepared?: boolean;+ sampleInstanceName?: string;projectGrants?: ProjectGrants;};@@ -107,6 +108,7 @@ export const readSetupDraft = (isSaaS: boolean): SetupDraft => {refusedProjectId: refusedId(stored.refusedProjectId),createdProject: optionalString(stored.createdProject),samplePrepared: stored.samplePrepared === true,+ sampleInstanceName: optionalString(stored.sampleInstanceName),projectGrants: grants(stored.projectGrants),};const projectAnswered = draft.projectTitle.trim()diff --git a/frontend/src/routes/auth/workspace-setup/finish.ts b/frontend/src/routes/auth/workspace-setup/finish.tsindex 35767ff4c4..91d84e3ffa 100644--- a/frontend/src/routes/auth/workspace-setup/finish.ts+++ b/frontend/src/routes/auth/workspace-setup/finish.ts@@ -316,7 +316,7 @@ type SetupFinishEvents = {// Called before the create is sent: its answer may never arrive.projectCreateSent: () => void;projectCreated: (project: string) => void;- samplePrepared: () => void;+ samplePrepared: (instanceName: string) => void;// The project's roles the wizard has given, as they stand.projectGrants: (grants: Record<string, string[]>) => void;};@@ -354,11 +354,11 @@ const commitSetup = async (}));try {- await store.prepareSampleProjectInstance(project);+ const instance = await store.prepareSampleProjectInstance(project);+ on.samplePrepared(instance.name);} catch (error) {return { ok: false, stage: "sample", error };}- on.samplePrepared();}try {diff --git a/frontend/src/routes/project/ProjectHomePage.test.tsx b/frontend/src/routes/project/ProjectHomePage.test.tsxindex f7e3c033fb..8412c00423 100644--- a/frontend/src/routes/project/ProjectHomePage.test.tsx+++ b/frontend/src/routes/project/ProjectHomePage.test.tsx@@ -3,6 +3,7 @@ import { create } from "@bufbuild/protobuf";import { TimestampSchema } from "@bufbuild/protobuf/wkt";import { fireEvent, render, screen, waitFor, within } from "@testing-library/react";import { beforeEach, describe, expect, test, vi } from "vitest";+import { silentContextKey } from "@/api/context-key";import type { Permission } from "@/types/iam";import { ApprovalStatus, Engine, IssueStatus, State } from "@/types/proto-es/v1/common_pb";import { DatabaseSchema$ } from "@/types/proto-es/v1/database_service_pb";@@ -32,10 +33,8 @@ const mocks = vi.hoisted(() => ({},currentUser: { name: "users/alice", email: "[email protected]", workspace: "workspaces/demo" },fetchDatabases: vi.fn(),- fetchIssueByName: vi.fn(),fetchInstanceList: vi.fn(),listIssues: vi.fn(),- listPlans: vi.fn(),hasWorkspacePermission: vi.fn((_permission: Permission) => true),workspaceResourceName: vi.fn(() => "workspaces/demo"),projectPoliciesByName: {@@ -58,8 +57,12 @@ const mocks = vi.hoisted(() => ({open: vi.fn(),createChat: vi.fn(() => ({ id: "new-chat" })),queueUserMessage: vi.fn(),+ listRollouts: vi.fn(),}));+vi.mock("@/api", () => ({+ rolloutServiceClientConnect: { listRollouts: mocks.listRollouts },+}));vi.mock("react-i18next", async (importOriginal) => ({...(await importOriginal<typeof import("react-i18next")>()),useTranslation: () => ({ t: (key: string) => key }),@@ -135,16 +138,23 @@ beforeEach(() => {],});mocks.state.fetchInstanceList.mockResolvedValue({ instances: [] });- mocks.state.fetchIssueByName.mockReset();- mocks.state.fetchIssueByName.mockResolvedValue(- create(IssueSchema, { draft: false })- );mocks.state.listIssues.mockResolvedValue({ issues: [] });- mocks.state.listPlans.mockReset();- mocks.state.listPlans.mockResolvedValue({ plans: [], nextPageToken: "" });+ mocks.listRollouts.mockReset();+ mocks.listRollouts.mockResolvedValue({ rollouts: [] });});describe("ProjectHomePage", () => {+ test("checks migration rollouts with one project-scoped request", async () => {+ render(<ProjectHomePage projectId="orders" />);+ await waitFor(() => expect(mocks.listRollouts).toHaveBeenCalledWith({+ parent: "projects/orders",+ pageSize: 1,+ filter: 'task_type in ["DATABASE_MIGRATE"]',+ }, expect.objectContaining({ contextValues: expect.anything() })));+ expect(mocks.listRollouts.mock.calls[0][1].contextValues.get(silentContextKey)).toBe(true);+ expect(mocks.listRollouts).toHaveBeenCalledOnce();+ });+test("shows archived status without loading active project data", () => {mocks.state.projectsByName["projects/orders"].state = State.DELETED;render(<ProjectHomePage projectId="orders" />);@@ -155,7 +165,7 @@ describe("ProjectHomePage", () => {expect(mocks.state.fetchDatabases).not.toHaveBeenCalled();expect(mocks.state.fetchInstanceList).not.toHaveBeenCalled();expect(mocks.state.listIssues).not.toHaveBeenCalled();- expect(mocks.state.listPlans).not.toHaveBeenCalled();+ expect(mocks.listRollouts).not.toHaveBeenCalled();});test("offers database change creation without plan-list permission", async () => {@@ -170,7 +180,7 @@ describe("ProjectHomePage", () => {params: { project: "orders" },});expect(query.className).not.toContain("bg-accent");- expect(mocks.state.listPlans).not.toHaveBeenCalled();+ expect(mocks.probedPermissions).not.toContain("bb.plans.list");});test("offers database change creation without database-list permission", async () => {@@ -205,18 +215,26 @@ describe("ProjectHomePage", () => {expect((prompt as HTMLTextAreaElement).value).toBe("");});- test("keeps Enter for a new line and submits a multiline prompt with Send", async () => {+ test("sends on Enter and keeps Shift+Enter for a new line", async () => {render(<ProjectHomePage projectId="orders" />);await waitFor(() => expect(screen.getByRole("region", { name: "project.home.next-step" })).toBeTruthy());const prompt = screen.getByRole("textbox", { name: "project.home.ai-placeholder" });fireEvent.change(prompt, { target: { value: "Explain this project" } });- const enterWasNotCanceled = fireEvent.keyDown(prompt, { key: "Enter" });- expect(enterWasNotCanceled).toBe(true);+ expect(prompt.getAttribute("placeholder")).toBe(+ "project.home.ai-placeholder · agent.input-keyboard-hint"+ );+ expect(screen.queryByText("agent.input-keyboard-hint")).toBeNull();+ expect(+ screen.getByText("agent.context: Order service").parentElement?.parentElement?.className+ ).toContain("items-end");+ const shiftEnterWasNotCanceled = fireEvent.keyDown(prompt, { key: "Enter", shiftKey: true });+ expect(shiftEnterWasNotCanceled).toBe(true);expect(mocks.createChat).not.toHaveBeenCalled();fireEvent.change(prompt, { target: { value: "Explain this\nproject" } });- fireEvent.click(screen.getByRole("button", { name: "agent.send" }));+ const enterWasCanceled = fireEvent.keyDown(prompt, { key: "Enter" });+ expect(enterWasCanceled).toBe(false);expect(mocks.createChat).toHaveBeenCalledOnce();expect(mocks.queueUserMessage).toHaveBeenCalledWith(expect.objectContaining({ text: "Explain this\nproject" })@@ -426,27 +444,22 @@ describe("ProjectHomePage", () => {);});- test("finds a synced instance on a later page", async () => {+ test("checks only the first instance in each permitted scope", async () => {mocks.state.fetchDatabases.mockResolvedValue({ databases: [] });- mocks.state.fetchInstanceList.mockImplementation(async ({ parent, pageToken }) => {- if (!parent) return { instances: [], nextPageToken: "" };- if (!pageToken) {- return {- instances: [],- nextPageToken: "next",- };- }- return {- instances: [{ name: "instances/second" }],- nextPageToken: "",- };+ mocks.state.fetchInstanceList.mockImplementation(async ({ parent }) => {+ if (parent) return { instances: [], nextPageToken: "" };+ return { instances: [{ name: "instances/shared" }], nextPageToken: "next" };});render(<ProjectHomePage projectId="orders" />);const next = await screen.findByRole("region", { name: "project.home.next-step" });expect(await within(next).findByRole("link", { name: "project.home.create-database" })).toBeTruthy();expect(mocks.state.fetchInstanceList).toHaveBeenCalledWith(- expect.objectContaining({ parent: "projects/orders", pageToken: "next" })+ expect.objectContaining({ parent: "projects/orders", pageSize: 1 }));+ expect(mocks.state.fetchInstanceList).toHaveBeenCalledWith(+ expect.objectContaining({ parent: undefined, pageSize: 1 })+ );+ expect(mocks.state.fetchInstanceList).toHaveBeenCalledTimes(2);});test("does not claim a connection is needed when instance discovery fails", async () => {@@ -603,11 +616,7 @@ describe("ProjectHomePage", () => {}),}));- expect(mocks.state.listPlans).toHaveBeenCalledWith(- expect.objectContaining({- find: expect.objectContaining({ specType: "change_database_config" }),- })- );+ expect(mocks.listRollouts).toHaveBeenCalledOnce();});test("shows distinct borderless destination links beside both preview headings", async () => {@@ -766,84 +775,44 @@ describe("ProjectHomePage", () => {const next = await screen.findByRole("region", { name: "project.home.next-step" });expect((await within(next).findByRole("link", { name: "project.home.change-database" })).getAttribute("href")).toBe("workspace.project.plan.detail");- expect(mocks.state.listPlans).toHaveBeenCalledWith(- expect.objectContaining({- find: expect.objectContaining({ specType: "change_database_config" }),- })- );+ expect(mocks.listRollouts).toHaveBeenCalledOnce();expect(screen.getByRole("region", { name: "project.home.next-step" })).toBeTruthy();view.unmount();- mocks.state.listPlans.mockResolvedValue({- plans: [create(PlanSchema, { issue: "projects/orders/issues/change" })],- nextPageToken: "",+ mocks.listRollouts.mockResolvedValue({+ rollouts: [{ name: "projects/orders/rollouts/change" }],});render(<ProjectHomePage projectId="orders" />);- await waitFor(() =>- expect(mocks.state.fetchIssueByName).toHaveBeenCalledWith(- "projects/orders/issues/change",- true- )- );- await waitFor(() => expect(screen.queryByRole("region", { name: "project.home.next-step" })).toBeNull());- });-- test("finds a submitted database change after unlinked plans on an earlier page", async () => {- mocks.state.listPlans.mockImplementation(async ({ pageToken }) =>- pageToken- ? {- plans: [create(PlanSchema, { issue: "projects/orders/issues/change" })],- nextPageToken: "",- }- : {- plans: [create(PlanSchema, { name: "projects/orders/plans/draft" })],- nextPageToken: "next",- }- );- render(<ProjectHomePage projectId="orders" />);- await waitFor(() =>- expect(mocks.state.listPlans).toHaveBeenCalledWith(- expect.objectContaining({ pageToken: "next" })- )- );await waitFor(() => expect(screen.queryByRole("region", { name: "project.home.next-step" })).toBeNull());});- test("keeps setup visible when only create-database issues exist", async () => {+ test("keeps setup visible for an issue without a migration rollout", async () => {mocks.state.listIssues.mockResolvedValue({issues: [create(IssueSchema, {- type: Issue_Type.DATABASE_CHANGE,- plan: "projects/orders/plans/create-database",+ name: "projects/orders/issues/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();- expect(mocks.state.listPlans).toHaveBeenCalledWith(- expect.objectContaining({- find: expect.objectContaining({ specType: "change_database_config" }),- })- );+ expect(mocks.listRollouts).toHaveBeenCalledOnce();});- test("keeps setup visible when the linked database-change issue is a draft", async () => {- mocks.state.listPlans.mockResolvedValue({- plans: [create(PlanSchema, { issue: "projects/orders/issues/draft" })],- nextPageToken: "",- });- mocks.state.fetchIssueByName.mockResolvedValue(create(IssueSchema, { draft: true }));+ test("keeps setup available when rollout discovery is unavailable", async () => {+ mocks.listRollouts.mockRejectedValue(new Error("Unavailable"));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();});- test("discovers changes with issue-read permission without issue-list permission", async () => {- mocks.missedPermissions = ["bb.issues.list"];+ test("keeps creation available without rollout-list permission", async () => {+ mocks.missedPermissions = ["bb.rollouts.list"];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();- expect(mocks.state.listPlans).toHaveBeenCalled();+ expect(mocks.listRollouts).not.toHaveBeenCalled();});});diff --git a/frontend/src/routes/project/ProjectHomePage.tsx b/frontend/src/routes/project/ProjectHomePage.tsxindex 373e493c05..c5999a1f45 100644--- a/frontend/src/routes/project/ProjectHomePage.tsx+++ b/frontend/src/routes/project/ProjectHomePage.tsx@@ -1,3 +1,4 @@+import { createContextValues } from "@connectrpc/connect";import {ArrowRightLeft,ChevronRight,@@ -10,6 +11,8 @@ import {} from "lucide-react";import { useEffect, useState } from "react";import { useTranslation } from "react-i18next";+import { rolloutServiceClientConnect } from "@/api";+import { silentContextKey } from "@/api/context-key";import {DATABASE_ROUTE_DASHBOARD,PROJECT_V1_ROUTE_DATABASES,@@ -64,7 +67,7 @@ const HOME_PERMISSIONS: Permission[] = ["bb.databases.list","bb.databases.get","bb.databases.update",- "bb.plans.list",+ "bb.rollouts.list","bb.plans.get","bb.planCheckRuns.get","bb.taskRuns.list",@@ -134,10 +137,8 @@ export function ProjectHomePage({ projectId }: { projectId: string }) {const [aiPrompt, setAiPrompt] = useState("");const [discoveryRefreshToken, setDiscoveryRefreshToken] = useState(0);const fetchDatabases = useAppStore((state) => state.fetchDatabases);- const fetchIssueByName = useAppStore((state) => state.fetchIssueByName);const fetchInstanceList = useAppStore((state) => state.fetchInstanceList);const listIssues = useAppStore((state) => state.listIssues);- const listPlans = useAppStore((state) => state.listPlans);const canListWorkspaceInstances = useAppStore((state) =>state.hasWorkspacePermission("bb.instances.list"));@@ -164,7 +165,7 @@ export function ProjectHomePage({ projectId }: { projectId: string }) {const canGetPlanDetail = PLAN_DETAIL_PERMISSIONS.every((permission) => !missedPermissions.includes(permission));- const canListPlans = !missedPermissions.includes("bb.plans.list");+ const canListRollouts = !missedPermissions.includes("bb.rollouts.list");const canReadIssues = !missedPermissions.includes("bb.issues.get");const canListIssues = !missedPermissions.includes("bb.issues.list");const canListProjectInstances =@@ -251,7 +252,7 @@ export function ProjectHomePage({ projectId }: { projectId: string }) {: "loading";const [changeState, setChangeState] = useState<{projectName: string;- status: "loading" | "not-started" | "submitted" | "unknown";+ status: "loading" | "not-started" | "rolled-out" | "unknown";}>({ projectName, status: "loading" });const changeStatus =changeState.projectName === projectName ? changeState.status : "loading";@@ -298,21 +299,13 @@ export function ProjectHomePage({ projectId }: { projectId: string }) {return;}const inspectInstances = async (parent?: string) => {- let pageToken = "";- do {- const result = await fetchInstanceList({- parent,- pageSize: 100,- pageToken,- filter: { state: State.ACTIVE },- silent: true,- });- if (result.instances.length > 0) {- return "present" as const;- }- pageToken = result.nextPageToken;- } while (pageToken);- return "empty" as const;+ const { instances } = await fetchInstanceList({+ parent,+ pageSize: 1,+ filter: { state: State.ACTIVE },+ silent: true,+ });+ return instances.length > 0 ? ("present" as const) : ("empty" as const);};const requests = [...(canListProjectInstances ? [inspectInstances(projectName)] : []),@@ -387,54 +380,35 @@ export function ProjectHomePage({ projectId }: { projectId: string }) {useEffect(() => {if (isArchived || availability !== "present") return;let active = true;- if (!canReadIssues || !canListPlans) {+ if (!canListRollouts) {setChangeState({ projectName, status: "unknown" });return;}setChangeState({ projectName, status: "loading" });- const load = async () => {- let pageToken = "";- try {- do {- const result = await listPlans({- find: {- project: projectName,- specType: "change_database_config",- state: "ACTIVE",- },- pageSize: 20,- pageToken,+ void rolloutServiceClientConnect+ .listRollouts(+ {+ parent: projectName,+ pageSize: 1,+ filter: 'task_type in ["DATABASE_MIGRATE"]',+ },+ { contextValues: createContextValues().set(silentContextKey, true) }+ )+ .then(({ rollouts }) => {+ if (active) {+ setChangeState({+ projectName,+ status: rollouts.length ? "rolled-out" : "not-started",});- if (!active) return;- for (const plan of result.plans) {- if (!plan.issue) continue;- const issue = await fetchIssueByName(plan.issue, true);- if (!active) return;- if (!issue.draft) {- setChangeState({ projectName, status: "submitted" });- return;- }- }- pageToken = result.nextPageToken;- } while (pageToken);- setChangeState({ projectName, status: "not-started" });- } catch {+ }+ })+ .catch(() => {if (active) setChangeState({ projectName, status: "unknown" });- }- };- void load();+ });return () => {active = false;};- }, [- availability,- canListPlans,- canReadIssues,- fetchIssueByName,- isArchived,- listPlans,- projectName,- ]);+ }, [availability, canListRollouts, isArchived, projectName]);useEffect(() => {if (isArchived) return;@@ -642,14 +616,29 @@ export function ProjectHomePage({ projectId }: { projectId: string }) {rows={2}value={aiPrompt}aria-label={t("project.home.ai-placeholder")}- placeholder={t("project.home.ai-placeholder")}+ placeholder={`${t("project.home.ai-placeholder")} · ${t("agent.input-keyboard-hint")}`}className="min-h-20 resize-none border-0 focus:border-0 focus:ring-0"onChange={(event) => setAiPrompt(event.target.value)}+ onKeyDown={(event) => {+ if (+ event.key === "Enter" &&+ !event.shiftKey &&+ !event.altKey &&+ !event.ctrlKey &&+ !event.metaKey &&+ !event.nativeEvent.isComposing+ ) {+ event.preventDefault();+ sendAIMessage();+ }+ }}/>- <div className="flex flex-wrap items-center justify-between gap-2 px-3 pb-3">- <span className="min-w-0 flex-1 truncate text-xs text-control-light">- {t("agent.context")}: {project.title}- </span>+ <div className="flex flex-wrap items-end justify-between gap-2 px-3 pb-3">+ <div className="flex min-w-0 flex-1 items-center text-xs text-control-light">+ <span className="min-w-0 max-w-full truncate">+ {t("agent.context")}: {project.title}+ </span>+ </div><Buttontype="submit"size="sm"diff --git a/frontend/src/routes/project/projectHomeNextSteps.test.ts b/frontend/src/routes/project/projectHomeNextSteps.test.tsindex c7f255c41c..215304e101 100644--- a/frontend/src/routes/project/projectHomeNextSteps.test.ts+++ b/frontend/src/routes/project/projectHomeNextSteps.test.ts@@ -162,12 +162,12 @@ describe("getProjectHomeNextSteps", () => {).toEqual(["members"]);});- test("hides setup after the first submitted database change", () => {+ test("hides setup after the first database-change rollout", () => {expect(getProjectHomeNextSteps({...input,database: "present",- change: "submitted",+ change: "rolled-out",})).toEqual([]);});diff --git a/frontend/src/routes/project/projectHomeNextSteps.ts b/frontend/src/routes/project/projectHomeNextSteps.tsindex e9a4593ee7..dd83d2cc28 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" | "submitted" | "unknown";+ change: "loading" | "not-started" | "rolled-out" | "unknown";membership: "unknown" | "solo" | "has-collaborators";isDefault: boolean;canConnectInstance: boolean;@@ -37,7 +37,7 @@ export function getProjectHomeNextSteps(input.transferableDatabase === "present";if (input.isDefault ||- input.change === "submitted" ||+ input.change === "rolled-out" ||input.database === "loading" ||(input.database === "present" && input.change === "loading")) {diff --git a/frontend/src/routes/workspace/LandingPage.test.tsx b/frontend/src/routes/workspace/LandingPage.test.tsxnew file mode 100644index 0000000000..05eb96d09e--- /dev/null+++ b/frontend/src/routes/workspace/LandingPage.test.tsx@@ -0,0 +1,243 @@+import {+ cleanup,+ fireEvent,+ render,+ screen,+ waitFor,+ within,+} from "@testing-library/react";+import type { ReactNode } from "react";+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";+import { SETTING_ROUTE_WORKSPACE_GENERAL } from "@/app/router/handles";+import {+ AI_ASSISTANT_PRODUCT_INTRO,+ PRODUCT_INTRO_QUERY_KEY,+} from "@/lib/productIntro";+import { LandingPage } from "./LandingPage";++const mocks = vi.hoisted(() => ({+ aiEnabled: true as boolean | undefined,+ canConfigureAI: true,+ chatRunning: false,+ queuedUserMessage: null as { chatId: string } | null,+ createChat: vi.fn(() => ({ id: "workspace-chat" })),+ lastVisitProjectPath: "",+ openAgent: vi.fn(),+ push: vi.fn(),+ queueUserMessage: vi.fn(),+ isSaaSMode: false,+}));++vi.mock("react-i18next", () => ({+ initReactI18next: { type: "3rdParty", init: () => undefined },+ useTranslation: () => ({ t: (key: string) => key }),+}));++vi.mock("@/app/router", () => ({ router: { push: mocks.push } }));++vi.mock("@/components/RouterLink", () => ({+ RouterLink: ({ children, to }: { children: ReactNode; to: unknown }) => (+ <a href="#" data-route={JSON.stringify(to)}>{children}</a>+ ),+}));++vi.mock("@/components/ui/quick-link", () => ({+ QuickLinkButton: ({ children }: { children: ReactNode }) => (+ <button type="button">{children}</button>+ ),+ QuickLinkLink: ({ children }: { children: ReactNode }) => (+ <a>{children}</a>+ ),+}));++vi.mock("@/components/ui/sheet", () => ({+ Sheet: () => null,+ SheetBody: () => null,+ SheetContent: () => null,+ SheetHeader: () => null,+ SheetTitle: () => null,+}));++vi.mock("@/hooks/useAppState", () => ({+ useOptionalCurrentUser: () => ({ email: "[email protected]" }),+ useServerState: () => ({ isSaaSMode: mocks.isSaaSMode, version: "", changelogURL: "" }),+ useWorkspacePermission: () => mocks.canConfigureAI,+ useWorkspace: () => ({ name: "workspaces/acme", title: "Acme workspace" }),+}));++vi.mock("@/hooks/useRecentVisit", () => ({+ useRecentVisit: () => ({ lastVisitProjectPath: mocks.lastVisitProjectPath }),+}));++vi.mock("@/modules/agent/store/agent", () => ({+ selectHasRunningChat: () => mocks.chatRunning,+ useAgentStore: Object.assign(+ (selector: (state: object) => unknown) =>+ selector({ queuedUserMessage: mocks.queuedUserMessage }),+ {+ getState: () => ({+ createChat: mocks.createChat,+ open: mocks.openAgent,+ queueUserMessage: mocks.queueUserMessage,+ queuedUserMessage: mocks.queuedUserMessage,+ }),+ }+ ),+}));++vi.mock("./WorkspaceLandingGettingStarted", () => ({+ WorkspaceLandingGettingStarted: () => null,+}));++vi.mock("@/stores/app", () => ({+ useAppStore: Object.assign(+ (selector: (state: object) => unknown) =>+ selector({ serverInfo: { aiEnabled: mocks.aiEnabled } }),+ {+ getState: () => ({+ getOrFetchProjectByName: async () => ({+ name: "projects/project-sample",+ title: "Sample project",+ }),+ }),+ }+ ),+}));++beforeEach(() => {+ mocks.aiEnabled = true;+ mocks.canConfigureAI = true;+ mocks.chatRunning = false;+ mocks.isSaaSMode = false;+ mocks.queuedUserMessage = null;+ mocks.lastVisitProjectPath = "";+ mocks.createChat.mockClear();+ mocks.openAgent.mockClear();+ mocks.queueUserMessage.mockClear();+ localStorage.clear();+});++afterEach(cleanup);++describe("LandingPage", () => {+ test("sends a prompt in a new workspace-bound Agent chat", async () => {+ render(<LandingPage />);++ expect(+ screen.getByRole("heading", { name: "Acme workspace" })+ ).toBeVisible();+ expect(screen.getByText("landing.quick-link.yours")).toBeVisible();+ expect(screen.getByText("settings.sidebar.general")).toBeVisible();+ expect(screen.getByText("agent.context: Acme workspace")).toBeVisible();+ expect(+ screen.queryByRole("button", { name: "project.home.ask-ai" })+ ).not.toBeInTheDocument();++ fireEvent.change(screen.getByRole("textbox", { name: "landing.ai-placeholder" }), {+ target: { value: " Show the projects in this workspace " },+ });+ fireEvent.click(screen.getByRole("button", { name: "agent.send" }));++ expect(mocks.createChat).toHaveBeenCalledWith({+ context: "workspaces/acme",+ page: expect.objectContaining({ path: expect.any(String) }),+ });+ expect(mocks.queueUserMessage).toHaveBeenCalledWith({+ chatId: "workspace-chat",+ text: "Show the projects in this workspace",+ page: expect.objectContaining({ path: expect.any(String) }),+ });+ expect(mocks.openAgent).toHaveBeenCalledOnce();+ expect(screen.getByRole("textbox", { name: "landing.ai-placeholder" })).toHaveValue("");+ });++ test("shows the keyboard hint and sends only on unmodified Enter", () => {+ render(<LandingPage />);+ const prompt = screen.getByRole("textbox", { name: "landing.ai-placeholder" });+ expect(prompt).toHaveAttribute(+ "placeholder",+ "landing.ai-placeholder · agent.input-keyboard-hint"+ );+ expect(screen.queryByText("agent.input-keyboard-hint")).not.toBeInTheDocument();+ expect(+ screen.getByText("agent.context: Acme workspace").parentElement?.parentElement+ ).toHaveClass("items-end");+ fireEvent.change(prompt, { target: { value: "Workspace\nprojects" } });++ expect(fireEvent.keyDown(prompt, { key: "Enter", shiftKey: true })).toBe(true);+ expect(mocks.createChat).not.toHaveBeenCalled();+ expect(fireEvent.keyDown(prompt, { key: "Enter" })).toBe(false);+ expect(mocks.queueUserMessage).toHaveBeenCalledWith(+ expect.objectContaining({ text: "Workspace\nprojects" })+ );+ });++ test("guides an eligible workspace admin to AI configuration", () => {+ mocks.aiEnabled = false;+ const { rerender } = render(<LandingPage />);++ expect(+ screen.queryByRole("textbox", { name: "landing.ai-placeholder" })+ ).not.toBeInTheDocument();+ expect(screen.queryByRole("button", { name: "agent.send" })).not.toBeInTheDocument();+ expect(screen.getByText("landing.ai-setup.description")).toBeVisible();+ const configure = screen.getByRole("link", { name: "landing.ai-setup.action" });+ expect(JSON.parse(configure.getAttribute("data-route")!)).toEqual({+ name: SETTING_ROUTE_WORKSPACE_GENERAL,+ hash: "#ai-assistant",+ query: { [PRODUCT_INTRO_QUERY_KEY]: AI_ASSISTANT_PRODUCT_INTRO },+ });++ mocks.aiEnabled = true;+ rerender(<LandingPage />);+ expect(screen.queryByRole("link", { name: "landing.ai-setup.action" })).not.toBeInTheDocument();+ expect(screen.getByRole("textbox", { name: "landing.ai-placeholder" })).toBeVisible();+ });++ test.each([+ { aiEnabled: false, canConfigureAI: false, isSaaSMode: false },+ { aiEnabled: false, canConfigureAI: true, isSaaSMode: true },+ { aiEnabled: undefined, canConfigureAI: true, isSaaSMode: false },+ ])("does not offer AI setup when configuration is unavailable: %j", ({ aiEnabled, canConfigureAI, isSaaSMode }) => {+ mocks.aiEnabled = aiEnabled;+ mocks.canConfigureAI = canConfigureAI;+ mocks.isSaaSMode = isSaaSMode;+ render(<LandingPage />);++ expect(screen.queryByRole("link", { name: "landing.ai-setup.action" })).not.toBeInTheDocument();+ expect(screen.queryByRole("textbox", { name: "landing.ai-placeholder" })).not.toBeInTheDocument();+ });++ test("does not send an empty prompt or queue behind another Agent run", () => {+ const { rerender } = render(<LandingPage />);+ const send = screen.getByRole("button", { name: "agent.send" });+ expect(send).toBeDisabled();++ fireEvent.change(screen.getByRole("textbox", { name: "landing.ai-placeholder" }), {+ target: { value: "What is configured?" },+ });+ expect(send).toBeEnabled();++ mocks.chatRunning = true;+ rerender(<LandingPage />);+ expect(send).toBeDisabled();+ fireEvent.submit(send.closest("form")!);+ expect(mocks.createChat).not.toHaveBeenCalled();+ });++ test("keeps Last visit beside the shortcuts title", async () => {+ mocks.lastVisitProjectPath = "/projects/project-sample";+ render(<LandingPage />);++ const title = screen.getByRole("heading", {+ name: "landing.quick-link.yours",+ });+ await waitFor(() =>+ expect(+ within(title.parentElement!).getByRole("link", {+ name: "landing.last-visit: Sample project",+ })+ ).toBeVisible()+ );+ });+});diff --git a/frontend/src/routes/workspace/LandingPage.tsx b/frontend/src/routes/workspace/LandingPage.tsxindex fa6ae32203..51b7eccf7f 100644--- a/frontend/src/routes/workspace/LandingPage.tsx+++ b/frontend/src/routes/workspace/LandingPage.tsx@@ -1,10 +1,12 @@import {+ Bot,CircleDot,Database,GalleryHorizontalEnd,GripVertical,Layers,Link,+ Send,Settings,ShieldCheck,SquareStack,@@ -47,7 +49,8 @@ import {WORKSPACE_ROUTE_WORKLOAD_IDENTITIES,} from "@/app/router/handles";import { RouterLink } from "@/components/RouterLink";-import { Button } from "@/components/ui/button";+import { Alert } from "@/components/ui/alert";+import { Button, buttonVariants } from "@/components/ui/button";import { Checkbox } from "@/components/ui/checkbox";import { QuickLinkButton, QuickLinkLink } from "@/components/ui/quick-link";import {@@ -57,14 +60,29 @@ import {SheetHeader,SheetTitle,} from "@/components/ui/sheet";-import { Tooltip } from "@/components/ui/tooltip";-import { useOptionalCurrentUser, useServerState } from "@/hooks/useAppState";+import { Textarea } from "@/components/ui/textarea";+import { WorkspacePageLayout } from "@/components/WorkspacePageLayout";+import {+ useOptionalCurrentUser,+ useServerState,+ useWorkspace,+ useWorkspacePermission,+} from "@/hooks/useAppState";import { useRecentVisit } from "@/hooks/useRecentVisit";+import {+ AI_ASSISTANT_PRODUCT_INTRO,+ PRODUCT_INTRO_QUERY_KEY,+} from "@/lib/productIntro";+import {+ selectHasRunningChat,+ useAgentStore,+} from "@/modules/agent/store/agent";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 { extractProjectResourceName, storageKeyQuickAccess } from "@/utils";+import { WorkspaceLandingGettingStarted } from "./WorkspaceLandingGettingStarted";// ---------------------------------------------------------------------------// Types@@ -244,10 +262,10 @@ function useFullQuickLinkList(): QuickLinkDef[] {// ---------------------------------------------------------------------------const DEFAULT_CONFIG = [- "visit-issues",- "visit-projects",+ PROJECT_V1_ROUTE_DASHBOARD,WORKSPACE_ROUTE_USERS,WORKSPACE_ROUTE_SQL_REVIEW,+ SETTING_ROUTE_WORKSPACE_GENERAL,];function useQuickAccessConfig(email: string) {@@ -433,9 +451,17 @@ function ConfigSheet({export function LandingPage(_: Record<string, never> = {}) {const { t } = useTranslation();const [showConfigDrawer, setShowConfigDrawer] = useState(false);+ const [aiPrompt, setAiPrompt] = useState("");+ const workspace = useWorkspace();+ const aiEnabled = useAppStore((state) => state.serverInfo?.aiEnabled);+ const canConfigureAI = useWorkspacePermission("bb.settings.set");+ const hasRunningChat = useAgentStore(selectHasRunningChat);+ const hasQueuedMessage = useAgentStore(+ (state) => state.queuedUserMessage !== null+ );const email = useOptionalCurrentUser()?.email ?? "";- const { version, changelogURL } = useServerState();+ const { isSaaSMode, version, changelogURL } = useServerState();const fullList = useFullQuickLinkList();const { config, setConfig } = useQuickAccessConfig(email);@@ -460,80 +486,183 @@ export function LandingPage(_: Record<string, never> = {}) {}}, []);+ const sendAIMessage = () => {+ const text = aiPrompt.trim();+ if (!text || !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.createChat({ context: workspace.name, page });+ store.queueUserMessage({ chatId: chat.id, text, page });+ store.open();+ setAiPrompt("");+ };+return (<>- <div className="py-4 px-4 flex flex-col h-full items-center relative">- <div className="flex-1" />- <div className="flex-[60%] flex flex-col gap-y-6">- <div className="flex items-baseline gap-x-4">- <div className="flex items-start gap-x-1">- <div className="font-semibold text-2xl">- {t("landing.quick-link.self")}- </div>- <Tooltip content={t("landing.quick-link.manage")}>+ <WorkspacePageLayout>+ <div className="flex min-w-0 flex-col gap-y-8">+ <header className="min-w-0">+ <h1 className="min-w-0 break-words text-2xl font-bold text-main">+ {workspace?.title ?? t("landing.workspace")}+ </h1>+ </header>++ {aiEnabled && workspace?.name && (+ <form+ className="min-w-0 rounded-sm border border-accent/60 bg-background focus-within:border-accent focus-within:ring-1 focus-within:ring-accent"+ onSubmit={(event) => {+ event.preventDefault();+ sendAIMessage();+ }}+ >+ <Textarea+ size="md"+ rows={2}+ value={aiPrompt}+ aria-label={t("landing.ai-placeholder")}+ placeholder={`${t("landing.ai-placeholder")} · ${t("agent.input-keyboard-hint")}`}+ className="min-h-20 resize-none border-0 focus:border-0 focus:ring-0"+ onChange={(event) => setAiPrompt(event.target.value)}+ onKeyDown={(event) => {+ if (+ event.key === "Enter" &&+ !event.shiftKey &&+ !event.altKey &&+ !event.ctrlKey &&+ !event.metaKey &&+ !event.nativeEvent.isComposing+ ) {+ event.preventDefault();+ sendAIMessage();+ }+ }}+ />+ <div className="flex flex-wrap items-end justify-between gap-2 px-3 pb-3">+ <div className="flex min-w-0 flex-1 items-center text-xs text-control-light">+ <span className="min-w-0 max-w-full truncate">+ {t("agent.context")}: {workspace.title}+ </span>+ </div><Button- appearance="secondary"- size="xs"- className="aspect-square px-0"- onClick={() => setShowConfigDrawer(true)}+ type="submit"+ size="sm"+ disabled={+ !aiPrompt.trim() || hasRunningChat || hasQueuedMessage+ }>- <Settings className="w-4 h-4 text-control-light" />- <span className="sr-only">- {t("landing.quick-link.manage")}- </span>+ <Send className="size-4" />+ {t("agent.send")}</Button>- </Tooltip>- </div>- {lastProject && lastVisitProjectPath && (- <RouterLink- to={{ path: lastVisitProjectPath }}- className="underline normal-link cursor-pointer"+ </div>+ </form>+ )}++ {aiEnabled === false && canConfigureAI && !isSaaSMode && (+ <Alert+ role="region"+ aria-label={t("landing.ai-setup.title")}+ showIcon={false}+ className="border-block-border bg-background text-main shadow-none"+ >+ <div className="flex flex-wrap items-center gap-3">+ <span className="flex size-8 shrink-0 items-center justify-center rounded-xs bg-accent/10 text-accent">+ <Bot className="size-4" aria-hidden="true" />+ </span>+ <div className="min-w-0 flex-1">+ <h2 className="text-sm font-semibold">+ {t("landing.ai-setup.title")}+ </h2>+ <p className="text-sm text-control-light">+ {t("landing.ai-setup.description")}+ </p>+ </div>+ <RouterLink+ to={{+ name: SETTING_ROUTE_WORKSPACE_GENERAL,+ hash: "#ai-assistant",+ query: {+ [PRODUCT_INTRO_QUERY_KEY]: AI_ASSISTANT_PRODUCT_INTRO,+ },+ }}+ className={buttonVariants({ size: "sm" })}+ >+ {t("landing.ai-setup.action")}+ </RouterLink>+ </div>+ </Alert>+ )}++ <WorkspaceLandingGettingStarted />++ <section className="min-w-0">+ <div className="flex flex-wrap items-center justify-between gap-2 border-b border-block-border pb-4">+ <div className="flex min-w-0 flex-wrap items-baseline gap-x-4 gap-y-2">+ <h2 className="text-base font-semibold text-main">+ {t("landing.quick-link.yours")}+ </h2>+ {lastProject && lastVisitProjectPath && (+ <RouterLink+ to={{ path: lastVisitProjectPath }}+ className="normal-link text-sm underline"+ >+ {t("landing.last-visit")}: {lastProject.title}+ </RouterLink>+ )}+ </div>+ <Button+ type="button"+ appearance="outline"+ size="sm"+ onClick={() => setShowConfigDrawer(true)}>- {t("landing.last-visit")}: {lastProject.title}- </RouterLink>- )}- </div>-- <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-4">- {quickLinkList.map((link) => {- if (link.route) {+ {t("project.home.customize")}+ </Button>+ </div>+ <div className="mt-4 grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-4">+ {quickLinkList.map((link) => {+ if (link.route) {+ return (+ <QuickLinkLink+ key={link.id}+ to={{ name: link.route }}+ className="min-w-0 justify-start py-3"+ icon={<link.icon className="size-4 text-control-light" />}+ >+ {link.title}+ </QuickLinkLink>+ );+ }return (- <QuickLinkLink+ <QuickLinkButtonkey={link.id}- to={{ name: link.route }}- icon={<link.icon className="w-5 h-5 text-control-light" />}+ type="button"+ onClick={() => handleClick(link)}+ className="min-w-0 justify-start py-3"+ icon={<link.icon className="size-4 text-control-light" />}>{link.title}- </QuickLinkLink>+ </QuickLinkButton>);- }- return (- <QuickLinkButton- key={link.id}- type="button"- onClick={() => handleClick(link)}- icon={<link.icon className="w-5 h-5 text-control-light" />}- >- {link.title}- </QuickLinkButton>- );- })}- </div>-- <div className="flex flex-col gap-y-2">- {changelogURL && (- <a- className="underline normal-link"- target="_blank"- rel="noopener noreferrer"- href={changelogURL}- >- {t("landing.changelog-for-version", { version })}- </a>- )}- </div>+ })}+ </div>+ </section>++ {changelogURL && (+ <a+ className="normal-link w-fit text-sm underline"+ target="_blank"+ rel="noopener noreferrer"+ href={changelogURL}+ >+ {t("landing.changelog-for-version", { version })}+ </a>+ )}</div>- </div>+ </WorkspacePageLayout><ConfigSheetopen={showConfigDrawer}diff --git a/frontend/src/routes/workspace/WorkspaceLandingGettingStarted.test.tsx b/frontend/src/routes/workspace/WorkspaceLandingGettingStarted.test.tsxnew file mode 100644index 0000000000..f244c22b86--- /dev/null+++ b/frontend/src/routes/workspace/WorkspaceLandingGettingStarted.test.tsx@@ -0,0 +1,168 @@+import { cleanup, fireEvent, render, screen } from "@testing-library/react";+import type { ReactNode } from "react";+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";+import type {+ GuideContext,+ ResolvedGuide,+ ResolvedGuideStep,+} from "@/modules/workspace-setup-guide/types";+import { WorkspaceLandingGettingStarted } from "./WorkspaceLandingGettingStarted";++const mocks = vi.hoisted(() => ({+ captureMetric: vi.fn(),+ completionAcknowledged: false,+ contextReady: true,+ dismissed: false,+ enabled: true,+ hasExploredDatabase: false,+ hasInstance: false,+ hasProject: true,+ projectName: "projects/orders",+ push: vi.fn(),+ saveIntroStateByKey: vi.fn(),+}));++vi.mock("@/app/analytics/behavior", () => ({+ createBehaviorMetric: (event: string, options: unknown) => ({+ event,+ options,+ }),+}));+vi.mock("@/app/analytics/provider", () => ({+ behaviorAnalytics: { captureMetric: mocks.captureMetric },+}));+vi.mock("@/app/router", () => ({+ router: { push: mocks.push },+ useCurrentRoute: () => ({ name: "workspace.landing", params: {}, query: {} }),+}));+vi.mock("@/hooks/useAppState", () => ({+ useIntroStateByKey: (key: string) =>+ key === "workspace-setup-guide.dismissed"+ ? mocks.dismissed+ : key.startsWith("workspace-setup-guide.completed.")+ ? mocks.completionAcknowledged+ : false,+}));+vi.mock("@/stores/app", () => {+ const storeState = {+ workspaceSetupGuideEnabled: () => mocks.enabled,+ saveIntroStateByKey: mocks.saveIntroStateByKey,+ };+ return {+ useAppStore: Object.assign(+ (selector: (state: typeof storeState) => unknown) => selector(storeState),+ { getState: () => storeState }+ ),+ };+});+vi.mock("@/modules/workspace-setup-guide/selection", () => ({+ readGuideWorkspaceUsage: () => undefined,+ readSelectedGuideScenarioId: () => undefined,+}));+vi.mock("@/modules/workspace-setup-guide/GuideContextProvider", () => ({+ useSharedGuideContext: () => ({+ context: {+ hasProject: mocks.hasProject,+ hasInstance: mocks.hasInstance,+ hasExploredDatabase: mocks.hasExploredDatabase,+ hasRunStatement: false,+ hasCreatedChangeIssue: false,+ hasMarkedSensitiveData: false,+ isSaaS: false,+ hasOtherHumanUser: false,+ hasOtherWorkspaceMember: false,+ projectName: mocks.projectName,+ instanceName: "",+ databaseProjectName: "projects/orders",+ databaseName: "instances/test/databases/app",+ route: { name: "workspace.landing", params: {} },+ } satisfies GuideContext,+ contextReady: mocks.contextReady,+ }),+}));+vi.mock("@/modules/workspace-setup-guide/WorkspaceHomeGettingStarted", () => ({+ WorkspaceHomeGettingStarted: ({+ guide,+ onSelectStep,+ onDismiss,+ }: {+ guide: ResolvedGuide;+ onSelectStep: (step: ResolvedGuideStep) => void;+ onDismiss: () => void;+ }): ReactNode => (+ <div data-testid="workspace-home-getting-started">+ <button+ type="button"+ onClick={() => guide.activeStep && onSelectStep(guide.activeStep)}+ >+ {guide.activeStep?.definition.id}+ </button>+ {guide.complete && (+ <button type="button" onClick={onDismiss}>+ Dismiss+ </button>+ )}+ </div>+ ),+}));++beforeEach(() => {+ vi.clearAllMocks();+ mocks.contextReady = true;+ mocks.completionAcknowledged = false;+ mocks.dismissed = false;+ mocks.enabled = true;+ mocks.hasExploredDatabase = false;+ mocks.hasInstance = false;+ mocks.hasProject = true;+ mocks.projectName = "projects/orders";+});+afterEach(cleanup);++describe("WorkspaceLandingGettingStarted", () => {+ test("renders the current setup step and opens its destination", () => {+ render(<WorkspaceLandingGettingStarted />);++ fireEvent.click(screen.getByRole("button", { name: "connect-instance" }));+ expect(mocks.push).toHaveBeenCalledWith(+ expect.objectContaining({ params: { projectId: "orders" } })+ );+ expect(mocks.captureMetric).toHaveBeenCalledWith(+ expect.objectContaining({+ event: "workspace setup guide step action selected",+ })+ );+ });++ test.each([+ { dismissed: true, enabled: true, contextReady: true },+ { dismissed: false, enabled: false, contextReady: true },+ { dismissed: false, enabled: true, contextReady: false },+ ])("hides the setup section when the guide is unavailable: %j", (state) => {+ Object.assign(mocks, state);+ render(<WorkspaceLandingGettingStarted />);++ expect(screen.queryByTestId("workspace-home-getting-started")).toBeNull();+ });++ test("acknowledges the completed guide through the shared progress key", () => {+ mocks.hasInstance = true;+ mocks.hasExploredDatabase = true;+ render(<WorkspaceLandingGettingStarted />);++ fireEvent.click(screen.getByRole("button", { name: "Dismiss" }));+ expect(mocks.saveIntroStateByKey).toHaveBeenCalledWith({+ key: "workspace-setup-guide.completed.workspace-setup",+ newState: true,+ });+ });++ test("hides a completed guide after acknowledgment", () => {+ mocks.hasInstance = true;+ mocks.hasExploredDatabase = true;+ mocks.completionAcknowledged = true;+ render(<WorkspaceLandingGettingStarted />);++ expect(screen.queryByTestId("workspace-home-getting-started")).toBeNull();+ });+});diff --git a/frontend/src/routes/workspace/WorkspaceLandingGettingStarted.tsx b/frontend/src/routes/workspace/WorkspaceLandingGettingStarted.tsxnew file mode 100644index 0000000000..34c7e7fdd6--- /dev/null+++ b/frontend/src/routes/workspace/WorkspaceLandingGettingStarted.tsx@@ -0,0 +1,117 @@+import { useMemo } from "react";+import {+ type BehaviorMetricName,+ createBehaviorMetric,+} from "@/app/analytics/behavior";+import { behaviorAnalytics } from "@/app/analytics/provider";+import { router } from "@/app/router";+import { useIntroStateByKey } from "@/hooks/useAppState";+import { preCreateIssue } from "@/lib/plan/issue";+import { getGuideAnalyticsProperties } from "@/modules/workspace-setup-guide/analytics";+import { useSharedGuideContext } from "@/modules/workspace-setup-guide/GuideContextProvider";+import {+ GUIDE_PROGRESS_KEYS,+ guideCompletionAcknowledgedKey,+} from "@/modules/workspace-setup-guide/progress";+import { resolveGuide } from "@/modules/workspace-setup-guide/resolve";+import { getGuideJourney } from "@/modules/workspace-setup-guide/scenarios";+import {+ readGuideWorkspaceUsage,+ readSelectedGuideScenarioId,+} from "@/modules/workspace-setup-guide/selection";+import { GUIDE_STEP_DEFINITIONS } from "@/modules/workspace-setup-guide/steps";+import type {+ GuideAction,+ ResolvedGuideStep,+} from "@/modules/workspace-setup-guide/types";+import { WorkspaceHomeGettingStarted } from "@/modules/workspace-setup-guide/WorkspaceHomeGettingStarted";+import { useAppStore } from "@/stores/app";++export function WorkspaceLandingGettingStarted() {+ const scenarioId = readSelectedGuideScenarioId();+ const workspaceUsage = readGuideWorkspaceUsage();+ const journey = useMemo(+ () => getGuideJourney(scenarioId, workspaceUsage),+ [scenarioId, workspaceUsage]+ );+ const dismissed = useIntroStateByKey(GUIDE_PROGRESS_KEYS.dismissed);+ const completionAcknowledged = useIntroStateByKey(+ guideCompletionAcknowledgedKey(journey.id)+ );+ const allowMultipleMembers =+ workspaceUsage === "team" && !completionAcknowledged;+ const enabled = useAppStore((state) =>+ state.workspaceSetupGuideEnabled(allowMultipleMembers)+ );+ const { context, contextReady } = useSharedGuideContext();+ const guide = useMemo(+ () =>+ resolveGuide({+ journey,+ definitions: GUIDE_STEP_DEFINITIONS,+ context,+ }),+ [context, journey]+ );++ if (+ dismissed ||+ !enabled ||+ !contextReady ||+ (guide.complete && completionAcknowledged)+ ) {+ return null;+ }++ const captureMetric = (+ event: BehaviorMetricName,+ properties: Record<string, unknown> = {}+ ) => {+ behaviorAnalytics.captureMetric(+ createBehaviorMetric(event, {+ properties: {+ ...getGuideAnalyticsProperties({+ guide,+ journey,+ scenarioId,+ workspaceUsage,+ }),+ ...properties,+ },+ })+ );+ };+ const captureStepAction = (step: ResolvedGuideStep, action: GuideAction) => {+ captureMetric("workspace setup guide step action selected", {+ step: step.definition.id,+ action_type: action.type,+ });+ };+ const onSelectStep = (step: ResolvedGuideStep) => {+ const action = step.actions.select;+ if (action) captureStepAction(step, action);+ if (action?.type === "navigate") void router.push(action.target);+ if (action?.type === "create-change") {+ void preCreateIssue(action.project, [action.database]);+ }+ };+ const onDismiss = () => {+ captureMetric("workspace setup guide dismissed");+ useAppStore.getState().saveIntroStateByKey({+ key: guide.complete+ ? guideCompletionAcknowledgedKey(journey.id)+ : GUIDE_PROGRESS_KEYS.dismissed,+ newState: true,+ });+ };++ return (+ <WorkspaceHomeGettingStarted+ guide={guide}+ projectName={context.projectName}+ onSelectStep={onSelectStep}+ onCaptureStepAction={captureStepAction}+ onDismiss={onDismiss}+ />+ );+}diff --git a/frontend/src/routes/workspace/general/AIAugmentationSection.test.tsx b/frontend/src/routes/workspace/general/AIAugmentationSection.test.tsxindex 06aed80d4b..f05e757eb6 100644--- a/frontend/src/routes/workspace/general/AIAugmentationSection.test.tsx+++ b/frontend/src/routes/workspace/general/AIAugmentationSection.test.tsx@@ -7,13 +7,15 @@ const mocks = vi.hoisted(() => ({getOrFetchSettingByName: vi.fn(),upsertSetting: vi.fn(),refreshServerInfo: vi.fn(),+ isSaaSMode: false,+ aiEnabled: false as boolean | undefined,}));vi.mock("react-i18next", () => ({useTranslation: () => ({ t: (key: string) => key }),}));vi.mock("@/hooks/useAppState", () => ({- useServerState: () => ({ isSaaSMode: false }),+ useServerState: () => ({ isSaaSMode: mocks.isSaaSMode }),}));vi.mock("@/lib/productIntro", () => ({AI_ASSISTANT_PRODUCT_INTRO: "ai-assistant",@@ -29,6 +31,9 @@ vi.mock("@/stores/app", () => {getOrFetchSettingByName: mocks.getOrFetchSettingByName,upsertSetting: mocks.upsertSetting,refreshServerInfo: mocks.refreshServerInfo,+ get serverInfo() {+ return { aiEnabled: mocks.aiEnabled };+ },};return {useAppStore: Object.assign(@@ -54,7 +59,9 @@ vi.mock("@/components/ui/form", () => ({<div>{title}{children}</div>),FormFieldGroup: ({ children }: { children: ReactNode }) => <div>{children}</div>,- FormSection: ({ children }: { children: ReactNode }) => <section>{children}</section>,+ FormSection: ({ children, id }: { children: ReactNode; id?: string }) => (+ <section id={id}>{children}</section>+ ),}));vi.mock("@/components/ui/input", () => ({Input: (props: React.InputHTMLAttributes<HTMLInputElement>) => <input {...props} />,@@ -82,10 +89,65 @@ import { AIAugmentationSection } from "./AIAugmentationSection";describe("AIAugmentationSection", () => {beforeEach(() => {vi.clearAllMocks();+ mocks.isSaaSMode = false;+ mocks.aiEnabled = false;mocks.upsertSetting.mockResolvedValue(undefined);mocks.refreshServerInfo.mockResolvedValue(undefined);});+ test.each([+ [true, "available-in-saas"],+ [false, "unavailable-in-saas"],+ ])(+ "shows actual SaaS AI availability when aiEnabled is %s",+ (aiEnabled, message) => {+ mocks.isSaaSMode = true;+ mocks.aiEnabled = aiEnabled;+ render(<AIAugmentationSection title="AI" onDirtyChange={vi.fn()} />);++ expect(+ screen.getByText(`settings.general.workspace.ai-assistant.${message}`)+ ).toBeTruthy();+ expect(+ screen.queryByText(+ "settings.general.workspace.ai-assistant.enabled-in-saas"+ )+ ).toBeNull();+ expect(screen.queryByRole("checkbox", { name: "enable-ai" })).toBeNull();+ }+ );++ test("does not report AI unavailable before server info loads", () => {+ mocks.isSaaSMode = true;+ mocks.aiEnabled = undefined;+ render(<AIAugmentationSection title="AI" onDirtyChange={vi.fn()} />);++ expect(+ screen.queryByText(+ "settings.general.workspace.ai-assistant.unavailable-in-saas"+ )+ ).toBeNull();+ });++ test("exposes the AI settings section as a hash target without scrolling itself", () => {+ const originalUrl = window.location.href;+ const originalScrollIntoView = HTMLElement.prototype.scrollIntoView;+ const scrollIntoView = vi.fn();+ HTMLElement.prototype.scrollIntoView = scrollIntoView;+ window.history.replaceState(null, "", "#ai-assistant");++ try {+ const { container } = render(+ <AIAugmentationSection title="AI" onDirtyChange={vi.fn()} />+ );+ expect(container.querySelector("#ai-assistant")).toBeTruthy();+ expect(scrollIntoView).not.toHaveBeenCalled();+ } finally {+ window.history.replaceState(null, "", originalUrl);+ HTMLElement.prototype.scrollIntoView = originalScrollIntoView;+ }+ });+test("saves AI without depending on a second actuator request", async () => {mocks.refreshServerInfo.mockRejectedValue(new Error("refresh failed"));const ref = createRef<SectionHandle>();diff --git a/frontend/src/routes/workspace/general/AIAugmentationSection.tsx b/frontend/src/routes/workspace/general/AIAugmentationSection.tsxindex 8d36da4d10..8b6430ba67 100644--- a/frontend/src/routes/workspace/general/AIAugmentationSection.tsx+++ b/frontend/src/routes/workspace/general/AIAugmentationSection.tsx@@ -80,9 +80,9 @@ export const AIAugmentationSection = forwardRef<AIAugmentationSectionProps>(function AIAugmentationSection({ title, onDirtyChange }, ref) {const { t } = useTranslation();- const containerRef = useRef<HTMLElement>(null);const { isSaaSMode } = useServerState();+ const aiEnabled = useAppStore((s) => s.serverInfo?.aiEnabled);const canEdit = hasWorkspacePermissionV2("bb.settings.set") && !isSaaSMode;const settingsByName = useAppStore((s) => s.settingsByName);@@ -128,13 +128,6 @@ export const AIAugmentationSection = forwardRef<.getOrFetchSettingByName(Setting_SettingName.AI, true);}, []);- // Scroll into view on mount.- useEffect(() => {- if (location.hash === "#ai-assistant" && containerRef.current) {- containerRef.current.scrollIntoView({ block: "nearest" });- }- }, []);-useProductIntro({id: AI_ASSISTANT_PRODUCT_INTRO,title: t("settings.general.workspace.ai-assistant.self"),@@ -275,8 +268,7 @@ export const AIAugmentationSection = forwardRef<return (<FormSection- id="ai"- ref={containerRef}+ id={AI_ASSISTANT_PRODUCT_INTRO}title={title}data-product-intro-target={AI_ASSISTANT_PRODUCT_INTRO}>@@ -284,12 +276,20 @@ export const AIAugmentationSection = forwardRef<<PermissionGuard permissions={["bb.settings.set"]} display="block"><FormFieldGroup>{isSaaSMode ? (- <Alert- variant="info"- description={t(- "settings.general.workspace.ai-assistant.enabled-in-saas"- )}- />+ aiEnabled !== undefined && (+ <Alert+ variant="info"+ description={+ aiEnabled+ ? t(+ "settings.general.workspace.ai-assistant.available-in-saas"+ )+ : t(+ "settings.general.workspace.ai-assistant.unavailable-in-saas"+ )+ }+ />+ )) : (<>{/* Enable toggle */}diff --git a/frontend/src/routes/workspace/general/GeneralSection.tsx b/frontend/src/routes/workspace/general/GeneralSection.tsxindex d7d0c0e88a..94e6ea3df2 100644--- a/frontend/src/routes/workspace/general/GeneralSection.tsx+++ b/frontend/src/routes/workspace/general/GeneralSection.tsx@@ -197,6 +197,7 @@ export const GeneralSection = forwardRef<SectionHandle, GeneralSectionProps>({/* External URL — hidden in SaaS/cloud mode */}{!isSaaSMode && (<FormField+ id={EXTERNAL_URL_PRODUCT_INTRO}title={t("settings.general.workspace.external-url.self")}description={<>