From d82cadcb1e1e75ef99ebece13230574778d62783 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 04:42:21 +0000 Subject: [PATCH 1/3] feat(console-ai): the AI assistant is one right-side drawer, opened from the top-bar robot and maximized in place The console's chat drawer becomes the assistant's only container (ui ADR-0057, amended by its Amendment A3): - The top-bar robot toggles the drawer on the current page without navigating, and carries the plan-awaiting-approval marker. The floating bottom-right button is removed. - The drawer's expand button makes the same element fill the window in place, with the conversation history as a column; the same button restores the rail, and leaving the page restores it too. At rail width the history is behind a History button; the phone sheet has one as well. - What the drawer shows is a per-tab target (agent, conversation, package, fresh), held by the layout host (useConsoleChatDock) that ConsoleLayout and HomeLayout both mount. Pages open the drawer through useOpenAssistant; outside a host it falls back to the old address. - The /ai, /ai/:agent and /ai/:agent/:conversationId routes render AiAddressRedirect, which arms the drawer on the address (open, filling the window) and lands on the declared home; a Builder handoff rides navigation state only. - Home's "Build with AI" / "Ask AI" and app management's "Edit with AI" open the drawer. A new build still starts unbound. - Inside an app, a builder's empty state names data questions as well as changes, and its first suggestions are data questions. - The drawer's share button opens the share dialog (it was a no-op there). Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01WGufzidTEhaEGRzboS7xTa --- .changeset/34608-ai-assistant-one-drawer.md | 21 + ui/apps/console/src/App.tsx | 44 +- .../App.agentChatLink-10640.test.tsx | 9 +- .../src/__tests__/App.docsPortalLazy.test.tsx | 2 +- .../App.nativeShellMode-29039.test.tsx | 2 +- .../App.nativeShellOpenSet-29330.test.tsx | 2 +- .../App.uploadAltitude-10131.test.tsx | 2 +- .../__tests__/i18nAfterSignIn-12034.test.tsx | 2 +- .../src/__tests__/internalFormShell.test.tsx | 2 +- ui/apps/console/src/components/aiChatPage.ts | 18 - .../src/pages/system/AppManagementPage.tsx | 6 +- ...rdShortcutsDialog.wiredOnly-11674.test.tsx | 2 + .../src/console/ai/AiAddressRedirect.tsx | 48 +++ .../app-shell/src/console/ai/AiChatPage.tsx | 71 ++-- .../src/console/ai/ConversationsSidebar.tsx | 39 +- .../AiAddressRedirect-34608.test.tsx | 97 +++++ ...ChatPage.appContextComposer-11658.test.tsx | 23 ++ .../AiChatPage.draftsBarInFlow-12978.test.tsx | 2 + ...lanApprovalReachesLaunchers-11666.test.tsx | 28 +- .../__tests__/ConversationsSidebar.test.tsx | 58 ++- .../ai/__tests__/editModeEmptyState.test.ts | 20 +- .../app-shell/src/console/home/HomeLayout.tsx | 60 ++- .../app-shell/src/console/home/HomePage.tsx | 24 +- ui/packages/app-shell/src/index.ts | 10 + .../app-shell/src/layout/AppHeader.tsx | 18 +- .../src/layout/AssistantTopBarButton.tsx | 66 +++ ui/packages/app-shell/src/layout/ChatDock.tsx | 270 ++++++++----- .../src/layout/ChatDockConversation.tsx | 381 +++++++++++++++--- .../src/layout/ConsoleChatbotFab.tsx | 170 -------- .../app-shell/src/layout/ConsoleLayout.tsx | 148 ++----- .../ChatDock.appBinding-10926.test.tsx | 57 +-- .../ChatDock.partialRuntimeConfig.test.tsx | 3 + .../ChatDock.requestContext-30043.test.tsx | 1 - .../src/layout/__tests__/ChatDock.test.tsx | 173 +++++--- .../__tests__/ConsoleChatbotFab.test.tsx | 36 -- ...soleChatbotFab.yieldsCorner-12248.test.tsx | 172 -------- ...leLayout.aiEntryAsksUnsaved-13253.test.tsx | 150 ------- ...nsoleLayout.appBrandingLogo-10827.test.tsx | 3 +- .../ConsoleLayout.dockBinding-10926.test.tsx | 53 +-- ...eLayout.fabYieldsToOpenDock-10899.test.tsx | 106 ----- ...soleLayout.previewFrameDock-26470.test.tsx | 13 +- ...leLayout.robotTogglesDrawer-34608.test.tsx | 111 +++++ .../layout/__tests__/chatDockTarget.test.ts | 126 ++++++ .../launcherPlanApprovalMarker-11666.test.tsx | 22 +- .../app-shell/src/layout/chatDockControl.tsx | 68 ++++ .../app-shell/src/layout/chatDockTarget.ts | 203 ++++++++++ .../src/layout/useConsoleChatDock.tsx | 184 +++++++++ ui/packages/i18n/src/locales/ar.ts | 8 + ui/packages/i18n/src/locales/de.ts | 8 + ui/packages/i18n/src/locales/en.ts | 8 + ui/packages/i18n/src/locales/es.ts | 8 + ui/packages/i18n/src/locales/fr.ts | 8 + ui/packages/i18n/src/locales/ja.ts | 8 + ui/packages/i18n/src/locales/ko.ts | 8 + ui/packages/i18n/src/locales/pt-BR.ts | 8 + ui/packages/i18n/src/locales/ru.ts | 8 + ui/packages/i18n/src/locales/zh-Hans.ts | 8 + ui/packages/i18n/src/locales/zh-Hant.ts | 8 + 58 files changed, 2022 insertions(+), 1192 deletions(-) create mode 100644 .changeset/34608-ai-assistant-one-drawer.md delete mode 100644 ui/apps/console/src/components/aiChatPage.ts create mode 100644 ui/packages/app-shell/src/console/ai/AiAddressRedirect.tsx create mode 100644 ui/packages/app-shell/src/console/ai/__tests__/AiAddressRedirect-34608.test.tsx create mode 100644 ui/packages/app-shell/src/layout/AssistantTopBarButton.tsx delete mode 100644 ui/packages/app-shell/src/layout/ConsoleChatbotFab.tsx delete mode 100644 ui/packages/app-shell/src/layout/__tests__/ConsoleChatbotFab.test.tsx delete mode 100644 ui/packages/app-shell/src/layout/__tests__/ConsoleChatbotFab.yieldsCorner-12248.test.tsx delete mode 100644 ui/packages/app-shell/src/layout/__tests__/ConsoleLayout.aiEntryAsksUnsaved-13253.test.tsx delete mode 100644 ui/packages/app-shell/src/layout/__tests__/ConsoleLayout.fabYieldsToOpenDock-10899.test.tsx create mode 100644 ui/packages/app-shell/src/layout/__tests__/ConsoleLayout.robotTogglesDrawer-34608.test.tsx create mode 100644 ui/packages/app-shell/src/layout/__tests__/chatDockTarget.test.ts create mode 100644 ui/packages/app-shell/src/layout/chatDockControl.tsx create mode 100644 ui/packages/app-shell/src/layout/chatDockTarget.ts create mode 100644 ui/packages/app-shell/src/layout/useConsoleChatDock.tsx diff --git a/.changeset/34608-ai-assistant-one-drawer.md b/.changeset/34608-ai-assistant-one-drawer.md new file mode 100644 index 00000000000..10ae18ed670 --- /dev/null +++ b/.changeset/34608-ai-assistant-one-drawer.md @@ -0,0 +1,21 @@ +--- +'@object-ui/app-shell': patch +'@object-ui/console': patch +'@object-ui/i18n': patch +--- + +feat(console-ai): the AI assistant is one right-side drawer, opened from the top-bar robot, with no full page + +Clause-②: yes (widening — new @object-ui/i18n locale keys only) +Metadata-protocol: none + +The console's AI assistant now has one container, the right-side drawer (ui ADR-0057, amended). + +- The robot in the top bar opens and closes the drawer on the page you are on. The URL does not change. The floating button in the bottom-right corner is gone. While a proposed plan waits for approval, the robot carries the marker that button used to carry. +- The drawer's expand button makes it fill the window in place, with the conversation history as a column beside the chat. The same button puts it back as a side panel. Moving to another page puts it back too. At side-panel width the history is behind a "History" button. On a phone the drawer is a bottom sheet with the same "History" button. +- Home hosts the same drawer. "Build with AI" and "Ask AI" on Home, and "Edit with AI" in app management, open the drawer instead of a page. A new build still starts unbound to any app (ADR-0057 A1). +- The old `/ai`, `/ai/AGENT` and `/ai/AGENT/CONVERSATION` addresses still work. That includes bookmarks, shared links, `?package=` and `?new=`. They open the drawer on the conversation they name, filling the window, over the home page. A Builder handoff still travels only as navigation state. +- Inside an app, a builder's empty state offers data questions as well as changes, as the composer hint already did. Its description and its first suggestions name both. +- The drawer's share button now opens the share dialog. Before, it did nothing in the drawer. + +`@object-ui/i18n`: new keys `console.ai.dock.history`, `console.ai.dock.backToChat`, `console.ai.dock.expand`, `console.ai.dock.restore` and `console.ai.empty.editApp.askOrChangeDescription`, in every locale pack. No key was removed or changed. The console no longer reads `console.ai.dock.maximize` or `console.ai.empty.editApp.description`. Retiring them is a separate change. diff --git a/ui/apps/console/src/App.tsx b/ui/apps/console/src/App.tsx index 133bc9c175f..a2e2f16f628 100644 --- a/ui/apps/console/src/App.tsx +++ b/ui/apps/console/src/App.tsx @@ -24,6 +24,7 @@ import { DevModal } from './dev/DevModal'; import { DevLookup } from './dev/DevLookup'; import { DevRowActions } from './dev/DevRowActions'; import { + AiAddressRedirect, ConsoleShell, RequireAiSurface, RequireOrganization, @@ -94,20 +95,12 @@ const DocsSlug = lazy(() => import('./pages/DocsSlug')); const DocPage = lazy(() => import('./pages/DocPage')); /* - * The AI chat surfaces, lazy for the same reason (objectui#13410). - * - * `/ai…` and the public share page `/s/:token` are the two console routes that - * render the chat UI (`ChatbotEnhanced` and everything it reaches in - * `@object-ui/plugin-chatbot`: `streamdown`, `shiki`, the AI Elements). Imported - * statically here, that UI was in every first page load, the third-largest - * eager chunk, including for users who never open a chat. The AI page arrives - * through `./components/aiChatPage`, a console-local module nothing imports - * statically, because an `import()` of the `@object-ui/app-shell` barrel this - * file already imports would move nothing (see `./components/studioBuilder`). + * The public share page `/s/:token` renders the chat UI (`ChatbotEnhanced` and + * everything it reaches in `@object-ui/plugin-chatbot`), so it is lazy for the + * same reason (objectui#13410). The `/ai…` addresses no longer draw a page: they + * open the console's chat drawer (objectstack#34608, `AiAddressRedirect`), whose + * body loads the chat UI when it first renders. */ -const DefaultAiChatPage = lazy(() => - import('./components/aiChatPage').then((m) => ({ default: m.DefaultAiChatPage })), -); const SharedRecordPage = lazy(() => import('./pages/SharedRecordPage')); const SERVER_URL = import.meta.env.VITE_SERVER_URL || ''; @@ -498,34 +491,33 @@ export function App() { } /> {/* - AI surfaces are agent-scoped: the active assistant is baked into - the route (`/ai/:agent`) rather than a `?agent=` query snapshot, - so each assistant ("build" authoring vs "ask" data Q&A, plus any - custom `*.agent.ts`) is its own page. AiChatPage handles the - back-compat redirects: bare `/ai` → the default agent surface, and - a single-segment `/ai/:agent` that is actually a legacy bare - conversation id → `/ai/:agent/:conversationId`. + objectstack#34608 (ui ADR-0057 as amended) — the AI assistant has + one container, the right-side drawer, and no page. The old + full-page addresses (`/ai`, `/ai/:agent`, + `/ai/:agent/:conversationId`, with `?package=` / `?new=`) stay + routed so bookmarks and shared links keep working: + `AiAddressRedirect` opens the drawer on the conversation the + address names, filling the window, over the declared landing. `RequireAiSurface` keeps these from dead-ending on a runtime that serves no AI (Community Edition): with AI unavailable a stale bookmark / external link gets a screen saying so, with the way - home, instead of a chat with no agent to talk to. Cloud installs - pass straight through. Purely additive runtime gating — same - server signal the floating-chat FAB has always used. + home. Purely additive runtime gating — the same server signal the + top-bar robot uses. */} - }> + } /> - }> + } /> - }> + } /> {/* `RedirectWithSplash`, not a bare `` (objectui#6378). diff --git a/ui/apps/console/src/__tests__/App.agentChatLink-10640.test.tsx b/ui/apps/console/src/__tests__/App.agentChatLink-10640.test.tsx index d1bccfc91f5..0e5400a1421 100644 --- a/ui/apps/console/src/__tests__/App.agentChatLink-10640.test.tsx +++ b/ui/apps/console/src/__tests__/App.agentChatLink-10640.test.tsx @@ -21,8 +21,9 @@ * `internalFormShell.test.tsx` does. A hand-copied route list would be free to * agree with whatever the source does. Everything `App.tsx` imports but this * card does not touch is stubbed, with the same list that file uses. The - * catch-all's element (`RedirectWithSplash`) and the chat page - * (`DefaultAiChatPage`) are stubbed to markers; the chat stub reports the + * catch-all's element (`RedirectWithSplash`) and the chat address's element + * (`AiAddressRedirect`, which opens the chat drawer since objectstack#34608) + * are stubbed to markers; the chat stub reports the * `:agent` and `:conversationId` params and the `new` flag it was routed with. * * The href is not written here: it is the one the REAL registered agent @@ -91,7 +92,9 @@ vi.mock('@object-ui/app-shell', async (importOriginal) => { DefaultInvitationsPage: stub('invitations-page'), DefaultSettingsPage: stub('settings-page'), DefaultAcceptInvitationPage: stub('accept-invitation-page'), - DefaultAiChatPage: AiChatPageProbe, + // objectstack#34608 — the `/ai…` routes render `AiAddressRedirect` (it opens + // the chat drawer on the address); the probe reports what it was routed with. + AiAddressRedirect: AiChatPageProbe, StudioDesignSurface: stub('studio-design-surface'), BuilderLanding: stub('builder-landing'), getProductName: () => 'ObjectOS', diff --git a/ui/apps/console/src/__tests__/App.docsPortalLazy.test.tsx b/ui/apps/console/src/__tests__/App.docsPortalLazy.test.tsx index 145cec1c305..655566d76c1 100644 --- a/ui/apps/console/src/__tests__/App.docsPortalLazy.test.tsx +++ b/ui/apps/console/src/__tests__/App.docsPortalLazy.test.tsx @@ -104,7 +104,7 @@ vi.mock('@object-ui/app-shell', async (importOriginal) => ({ DefaultInvitationsPage: stub('invitations-page'), DefaultSettingsPage: stub('settings-page'), DefaultAcceptInvitationPage: stub('accept-invitation-page'), - DefaultAiChatPage: stub('ai-chat-page'), + AiAddressRedirect: stub('ai-chat-page'), StudioDesignSurface: stub('studio-design-surface'), BuilderLanding: stub('builder-landing'), getProductName: () => 'ObjectOS', diff --git a/ui/apps/console/src/__tests__/App.nativeShellMode-29039.test.tsx b/ui/apps/console/src/__tests__/App.nativeShellMode-29039.test.tsx index 0dce5abe299..d9d375c7e43 100644 --- a/ui/apps/console/src/__tests__/App.nativeShellMode-29039.test.tsx +++ b/ui/apps/console/src/__tests__/App.nativeShellMode-29039.test.tsx @@ -93,7 +93,7 @@ vi.mock('@object-ui/app-shell', async (importOriginal) => ({ DefaultInvitationsPage: stub('invitations-page'), DefaultSettingsPage: stub('settings-page'), DefaultAcceptInvitationPage: stub('accept-invitation-page'), - DefaultAiChatPage: stub('ai-chat-page'), + AiAddressRedirect: stub('ai-chat-page'), StudioDesignSurface: stub('studio-design-surface'), BuilderLanding: stub('builder-landing'), getProductName: () => 'ObjectOS', diff --git a/ui/apps/console/src/__tests__/App.nativeShellOpenSet-29330.test.tsx b/ui/apps/console/src/__tests__/App.nativeShellOpenSet-29330.test.tsx index 32a0681d629..ddf3fe12a83 100644 --- a/ui/apps/console/src/__tests__/App.nativeShellOpenSet-29330.test.tsx +++ b/ui/apps/console/src/__tests__/App.nativeShellOpenSet-29330.test.tsx @@ -72,7 +72,7 @@ vi.mock('@object-ui/app-shell', async (importOriginal) => ({ DefaultInvitationsPage: stub('invitations-page'), DefaultSettingsPage: stub('settings-page'), DefaultAcceptInvitationPage: stub('accept-invitation-page'), - DefaultAiChatPage: stub('ai-chat-page'), + AiAddressRedirect: stub('ai-chat-page'), StudioDesignSurface: stub('studio-design-surface'), BuilderLanding: stub('builder-landing'), getProductName: () => 'ObjectOS', diff --git a/ui/apps/console/src/__tests__/App.uploadAltitude-10131.test.tsx b/ui/apps/console/src/__tests__/App.uploadAltitude-10131.test.tsx index 035af81341d..95c043f6c8e 100644 --- a/ui/apps/console/src/__tests__/App.uploadAltitude-10131.test.tsx +++ b/ui/apps/console/src/__tests__/App.uploadAltitude-10131.test.tsx @@ -156,7 +156,7 @@ vi.mock('@object-ui/app-shell', async (importOriginal) => ({ DefaultInvitationsPage: stub('invitations-page'), DefaultSettingsPage: stub('settings-page'), DefaultAcceptInvitationPage: stub('accept-invitation-page'), - DefaultAiChatPage: stub('ai-chat-page'), + AiAddressRedirect: stub('ai-chat-page'), StudioDesignSurface: stub('studio-design-surface'), BuilderLanding: stub('builder-landing'), getProductName: () => 'ObjectOS', diff --git a/ui/apps/console/src/__tests__/i18nAfterSignIn-12034.test.tsx b/ui/apps/console/src/__tests__/i18nAfterSignIn-12034.test.tsx index 591a822829a..110a70f1225 100644 --- a/ui/apps/console/src/__tests__/i18nAfterSignIn-12034.test.tsx +++ b/ui/apps/console/src/__tests__/i18nAfterSignIn-12034.test.tsx @@ -82,7 +82,7 @@ vi.mock('@object-ui/app-shell', async (importOriginal) => ({ DefaultInvitationsPage: stub('invitations-page'), DefaultSettingsPage: stub('settings-page'), DefaultAcceptInvitationPage: stub('accept-invitation-page'), - DefaultAiChatPage: stub('ai-chat-page'), + AiAddressRedirect: stub('ai-chat-page'), StudioDesignSurface: stub('studio-design-surface'), BuilderLanding: stub('builder-landing'), getProductName: () => 'ObjectOS', diff --git a/ui/apps/console/src/__tests__/internalFormShell.test.tsx b/ui/apps/console/src/__tests__/internalFormShell.test.tsx index 7dd8cca2223..267d0c9ad95 100644 --- a/ui/apps/console/src/__tests__/internalFormShell.test.tsx +++ b/ui/apps/console/src/__tests__/internalFormShell.test.tsx @@ -81,7 +81,7 @@ vi.mock('@object-ui/app-shell', async (importOriginal) => ({ DefaultInvitationsPage: stub('invitations-page'), DefaultSettingsPage: stub('settings-page'), DefaultAcceptInvitationPage: stub('accept-invitation-page'), - DefaultAiChatPage: stub('ai-chat-page'), + AiAddressRedirect: stub('ai-chat-page'), StudioDesignSurface: stub('studio-design-surface'), BuilderLanding: stub('builder-landing'), getProductName: () => 'ObjectOS', diff --git a/ui/apps/console/src/components/aiChatPage.ts b/ui/apps/console/src/components/aiChatPage.ts deleted file mode 100644 index fc9e4bed5ea..00000000000 --- a/ui/apps/console/src/components/aiChatPage.ts +++ /dev/null @@ -1,18 +0,0 @@ -// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. - -/** - * The full-page AI chat, as the ONE module the console loads it through - * (objectui#13410). - * - * `App.tsx` reaches `DefaultAiChatPage` through `import('./aiChatPage')` - * behind a `lazy()` boundary, so the page and the `@object-ui/plugin-chatbot` - * chat UI only it reaches leave the eager closure every console page load - * pays for. The mechanism, and why this is a console-local module rather than - * an `import()` of `@object-ui/app-shell`, is written once on - * `./studioBuilder`; ⛔ not restated here. - * - * ⛔ A static `import ... from './aiChatPage'` anywhere in the console makes - * that `import()` ineffective again, and the chat UI rejoins every first load. - */ - -export { DefaultAiChatPage } from '@object-ui/app-shell'; diff --git a/ui/apps/console/src/pages/system/AppManagementPage.tsx b/ui/apps/console/src/pages/system/AppManagementPage.tsx index 1d889086a82..e40f39deb9b 100644 --- a/ui/apps/console/src/pages/system/AppManagementPage.tsx +++ b/ui/apps/console/src/pages/system/AppManagementPage.tsx @@ -109,7 +109,7 @@ import { } from 'lucide-react'; import { toast } from 'sonner'; import type { ObjectStackClient } from '@objectstack/client'; -import { ConsolePageHeader, useMetadata, useAdapter } from '@object-ui/app-shell'; +import { ConsolePageHeader, useMetadata, useAdapter, useOpenAssistant } from '@object-ui/app-shell'; import { useObjectTranslation } from '@object-ui/i18n'; import { resolveKeyedI18nLabel } from '../../utils'; @@ -237,6 +237,7 @@ function SetDefaultStar({ export function AppManagementPage() { const { t } = useObjectTranslation(); const navigate = useNavigate(); + const openAssistant = useOpenAssistant(); const { appName } = useParams(); const basePath = appName ? `/apps/${appName}` : ''; const { apps, refresh } = useMetadata(); @@ -657,8 +658,9 @@ export function AppManagementPage() { // pre-scoped to this app's package (passed as the chat // context.packageId the cloud seeds as the active package), // so the AI iterates within THIS app, not the whole env. + // objectstack#34608 — in the console's chat drawer, in place. onClick={() => - navigate(`/ai/build?package=${encodeURIComponent(app._packageId!)}&new=1`) + openAssistant({ agent: 'build', packageId: app._packageId, fresh: true }) } > diff --git a/ui/packages/app-shell/src/chrome/KeyboardShortcutsDialog.wiredOnly-11674.test.tsx b/ui/packages/app-shell/src/chrome/KeyboardShortcutsDialog.wiredOnly-11674.test.tsx index 5fa38127224..69af248faa3 100644 --- a/ui/packages/app-shell/src/chrome/KeyboardShortcutsDialog.wiredOnly-11674.test.tsx +++ b/ui/packages/app-shell/src/chrome/KeyboardShortcutsDialog.wiredOnly-11674.test.tsx @@ -52,6 +52,8 @@ vi.mock('../layout/ChatDock', () => ({ width: 420, dragging: false, maximized: false, + fullWindow: false, + setFullWindow: vi.fn(), toggle: () => {}, expand: () => {}, collapse: () => {}, diff --git a/ui/packages/app-shell/src/console/ai/AiAddressRedirect.tsx b/ui/packages/app-shell/src/console/ai/AiAddressRedirect.tsx new file mode 100644 index 00000000000..fae3bdee3f3 --- /dev/null +++ b/ui/packages/app-shell/src/console/ai/AiAddressRedirect.tsx @@ -0,0 +1,48 @@ +// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#34608 (ui ADR-0057 as amended) — the old full-page chat + * addresses, `/ai`, `/ai/AGENT` and `/ai/AGENT/CONVERSATION` (with `?package=` + * and `?new=`), open the console's chat drawer instead: a bookmark, a shared + * link or an in-app link from a surface without a drawer (Studio) still lands + * on the conversation it named. + * + * The address is parsed into the drawer's target and armed per tab, with the + * drawer open and filling the window — the closest thing to the page the link + * used to open — then the visit is replaced by the declared landing + * (`useHomePath`), which hosts the drawer. While the app list is still loading + * that answers the launcher (`/home`), which hosts the same drawer, so a cold + * boot on an old link still opens the conversation. A Builder handoff carried as + * navigation state (objectui#12493: never in the URL) is handed on the same + * way, as navigation state of the landing. + * + * Deliberately light: it imports no chat code, so following an old link loads + * the chat graph only when the drawer body renders. + */ + +import { useEffect } from 'react'; +import { useLocation, useNavigate } from 'react-router-dom'; +import { useHomePath } from '../../hooks/useHomePath.js'; +import { writeStoredDockExpanded, DOCK_EXPANDED_STORAGE_KEY } from '../../layout/chatDockState.js'; +import { + parseAiAddress, + readBuilderHandoffState, + writeStoredDockFullWindow, + writeStoredDockTarget, + DOCK_HANDOFF_STATE_KEY, +} from '../../layout/chatDockTarget.js'; + +export function AiAddressRedirect() { + const location = useLocation(); + const navigate = useNavigate(); + const homePath = useHomePath(); + useEffect(() => { + writeStoredDockTarget(parseAiAddress(location.pathname, location.search)); + writeStoredDockExpanded(DOCK_EXPANDED_STORAGE_KEY, true); + writeStoredDockFullWindow(true); + const handoff = readBuilderHandoffState(location.state); + const carries = Boolean(handoff.handoffPrompt || handoff.parentConversationId); + navigate(homePath, { replace: true, state: carries ? { [DOCK_HANDOFF_STATE_KEY]: handoff } : null }); + }, [location.key, location.pathname, location.search, location.state, homePath, navigate]); + return null; +} diff --git a/ui/packages/app-shell/src/console/ai/AiChatPage.tsx b/ui/packages/app-shell/src/console/ai/AiChatPage.tsx index 10500cc89d6..3240d4c55c7 100644 --- a/ui/packages/app-shell/src/console/ai/AiChatPage.tsx +++ b/ui/packages/app-shell/src/console/ai/AiChatPage.tsx @@ -118,6 +118,8 @@ import { } from '@object-ui/plugin-chatbot/core'; import { AppHeader } from '../../layout/AppHeader.js'; +import { readBuilderHandoffState, type BuilderHandoffState } from '../../layout/chatDockTarget.js'; +import { useOpenAssistant } from '../../layout/chatDockControl.js'; import { CONSOLE_TOP_BAR } from '../../layout/consoleTopBar.js'; import { armChatDockExpanded, readDockReturnLocation } from '../../layout/chatDockState.js'; import type { ChatSurfaceContext } from '../../layout/chatSurfaceContext.js'; @@ -508,9 +510,12 @@ export function agentEmptyState( app: editContext.appLabel, }) : t('console.ai.empty.editApp.titleGeneric', { defaultValue: 'Edit this app' }), - description: t('console.ai.empty.editApp.description', { + // objectstack#34608 item 4 — the maker's one composer answers data + // questions too (build is a data superset, cloud#1673), so the empty + // state offers both: asking about the app's data, and changing it. + description: t('console.ai.empty.editApp.askOrChangeDescription', { defaultValue: - 'What would you like to change? I’ll modify this app in place — add a field, object, view or dashboard, or adjust what’s already there.', + 'Ask about this app’s data — counts, lists and summaries — or tell me what to change, and I’ll modify the app in place: a field, an object, a view or a dashboard.', }), }; } @@ -860,32 +865,9 @@ export function resolveCollapseToDockTarget( * render would churn the pane's `initialMessages` identity for no reason. */ const EMPTY_INITIAL_MESSAGES: HydratedUIMessage[] = []; -/** - * objectui#12493 — the ADR-0057 P4 Builder handoff ("Open in Builder →" on the - * `ask` surface) travels as react-router NAVIGATION STATE, never as a URL - * parameter. A URL can be written by anyone and opened by a signed-in user in - * one click; the build surface sends its seeded first message with no further - * user action, so a URL-borne prompt would let a link author (and, with - * `autoPublishAiBuilds`, publish) metadata as that user. Navigation state can - * only be set by this app's own in-app `navigate()` call. - */ -interface BuilderHandoffState { - /** The build prompt the `ask` agent handed off; sent once as the build surface's first message. */ - handoffPrompt?: string; - /** The source `ask` conversation id, forwarded as the build agent's first-turn context (cloud#817). */ - parentConversationId?: string; -} - -/** Reads the handoff from `location.state`; anything that is not a non-empty string is absent. */ -function readBuilderHandoffState(state: unknown): BuilderHandoffState { - if (!state || typeof state !== 'object') return {}; - const record = state as Record; - const text = (v: unknown) => (typeof v === 'string' && v.trim() ? v.trim() : undefined); - return { - handoffPrompt: text(record.handoffPrompt), - parentConversationId: text(record.parentConversationId), - }; -} +// objectui#12493 — the ADR-0057 P4 Builder handoff travels as navigation state +// (or an in-memory drawer call), never in a URL: `BuilderHandoffState` and its +// reader live with the drawer's target grammar (objectstack#34608). export interface PendingFirstMessage { content: string; @@ -2016,15 +1998,19 @@ export function ChatPane({ // own packageId, else this surface's edit package (`?package=` only scopes the // surface; it sends nothing). cloud#817: also carry THIS (ask) thread's id so // the Builder's first turn starts with the ask conversation as context. + // + // objectstack#34608 — inside the console's drawer this retargets the drawer + // in place; under no drawer host it navigates to `/ai/build` as before. + const openAssistant = useOpenAssistant(); const openBuilder = useCallback( (handoff: { prompt: string; packageId?: string }) => { const pkg = handoff.packageId || editPackageId; const state: BuilderHandoffState = {}; if (handoff.prompt) state.handoffPrompt = handoff.prompt; if (conversationId) state.parentConversationId = conversationId; - navigate(`/ai/build${pkg ? `?package=${encodeURIComponent(pkg)}` : ''}`, { state }); + openAssistant({ agent: 'build', packageId: pkg }, state); }, - [navigate, editPackageId, conversationId], + [openAssistant, editPackageId, conversationId], ); // cloud#1658 — land the user on the record an `open_record` hand-off names. @@ -2675,9 +2661,12 @@ export function ChatPane({ // change in " + change-oriented starters, instead of the from-scratch // magic-flow guidance. Computed here (not earlier) so it can read the app name. const editing = isBuildSurface && Boolean(editPackageId); + // objectstack#34608 item 4 — bound to an app, the maker's starters lead with + // two data questions before the change-oriented ones. const suggestions = useMemo(() => { if (hydrated.length > 0) return undefined; - return buildAgentSuggestions(activeAgent, activeAgentLabel, t, editing); + const starters = buildAgentSuggestions(activeAgent, activeAgentLabel, t, editing); + return editing ? [...editAppDataSuggestions(t), ...starters] : starters; }, [hydrated.length, activeAgent, activeAgentLabel, t, editing]); const emptyState = useMemo( () => agentEmptyState(t, activeAgent, editing ? { appLabel: editAppLabel } : undefined), @@ -2845,7 +2834,7 @@ export function ChatPane({ // to the Select when many custom agents would overflow the header. navigate(`/ai/${agentRouteName(name)}`)} + onValueChange={(name) => openAssistant({ agent: name })} > navigate(`/ai/${agentRouteName(name)}`)} + onValueChange={(name) => openAssistant({ agent: name })} disabled={agentsLoading} > { if (pkg.id !== boundPackageId) { - navigate(`/ai/build?package=${encodeURIComponent(pkg.id)}`); + openAssistant({ agent: 'build', packageId: pkg.id }); } }} > @@ -2953,7 +2942,7 @@ export function ChatPane({ navigate('/ai/build?new=1')} + onSelect={() => openAssistant({ agent: 'build', fresh: true })} > {t('console.ai.newApp', { defaultValue: 'New app' })} @@ -3614,6 +3603,18 @@ function editAppSuggestions(t: TranslationFn): string[] { ]; } +/** + * objectstack#34608 item 4 — the data-question starters the build agent offers + * beside its edit chips when bound to an app: the maker's composer answers data + * questions too. Reuses the data agent's own strings. + */ +export function editAppDataSuggestions(t: TranslationFn): string[] { + return [ + t('console.ai.suggestions.dataChat.recentRecords', { defaultValue: 'List the 5 most recently created records.' }), + t('console.ai.suggestions.dataChat.recordCounts', { defaultValue: 'Count records for each object.' }), + ]; +} + export function buildAgentSuggestions( agentName: string | undefined, agentLabel: string, diff --git a/ui/packages/app-shell/src/console/ai/ConversationsSidebar.tsx b/ui/packages/app-shell/src/console/ai/ConversationsSidebar.tsx index 102decfeb80..d669af77232 100644 --- a/ui/packages/app-shell/src/console/ai/ConversationsSidebar.tsx +++ b/ui/packages/app-shell/src/console/ai/ConversationsSidebar.tsx @@ -1,9 +1,12 @@ // Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license. /** - * Left sidebar listing the signed-in user's AI conversations. Active row is - * derived from `useParams<{ conversationId }>()`; clicking a row navigates to - * `/ai/:id`, the "New chat" button navigates to `/ai`. + * Sidebar listing the signed-in user's AI conversations. Two hosts: + * - a routed page: the active row is `useParams<{ conversationId }>()`, a row + * navigates to `/ai/:agent/:id` and "New chat" to `/ai/:agent?new=1`; + * - the console's chat drawer (objectstack#34608), which has no route: it + * passes {@link ConversationsSidebarProps.onSelectConversation} and its + * siblings, and the list calls them instead of navigating. */ import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from 'react'; @@ -44,6 +47,16 @@ export interface ConversationsSidebarProps { refreshKey?: number | string; titleHints?: Record; onNavigate?: () => void; + /** + * objectstack#34608 — the drawer host. When set, a row calls this instead of + * navigating, the active row is {@link activeConversationId}, and "New chat" + * and deleting the open conversation call {@link onNewConversation}. + */ + onSelectConversation?: (conversation: { id: string; agentId?: string }) => void; + /** The drawer host's "New chat" (also after deleting the open conversation). */ + onNewConversation?: () => void; + /** The drawer host's open conversation; read only with {@link onSelectConversation}. */ + activeConversationId?: string; } function formatTimestamp( @@ -145,10 +158,15 @@ export function ConversationsSidebar({ refreshKey, titleHints, onNavigate, + onSelectConversation, + onNewConversation, + activeConversationId, }: ConversationsSidebarProps) { const { t } = useObjectTranslation(); const navigate = useNavigate(); - const { conversationId: activeId } = useParams<{ conversationId?: string }>(); + const { conversationId: routeActiveId } = useParams<{ conversationId?: string }>(); + const hosted = onSelectConversation !== undefined; + const activeId = hosted ? activeConversationId : routeActiveId; const { conversations, isLoading, error, remove, rename } = useConversationList({ userId, apiBase, @@ -220,20 +238,22 @@ export function ConversationsSidebar({ // resumes the last cached conversation (by design), so without the flag // this button silently landed back on the current chat. Stays on the // active agent's surface. - navigate(agentRoute ? `/ai/${agentRoute}?new=1` : '/ai?new=1'); + if (hosted) onNewConversation?.(); + else navigate(agentRoute ? `/ai/${agentRoute}?new=1` : '/ai?new=1'); onNavigate?.(); - }, [navigate, agentRoute, onNavigate]); + }, [hosted, onNewConversation, navigate, agentRoute, onNavigate]); const handleDelete = useCallback( async (e: React.MouseEvent, id: string) => { e.stopPropagation(); await remove(id); if (id === activeId) { - navigate(agentRoute ? `/ai/${agentRoute}` : '/ai', { replace: true }); + if (hosted) onNewConversation?.(); + else navigate(agentRoute ? `/ai/${agentRoute}` : '/ai', { replace: true }); onNavigate?.(); } }, - [remove, activeId, navigate, agentRoute, onNavigate], + [remove, activeId, hosted, onNewConversation, navigate, agentRoute, onNavigate], ); const handleRenameSubmit = useCallback( @@ -308,7 +328,8 @@ export function ConversationsSidebar({ active={c.id === activeId} renaming={c.id === renamingId} onSelect={() => { - navigate(conversationHref(c)); + if (onSelectConversation) onSelectConversation({ id: c.id, agentId: c.agentId }); + else navigate(conversationHref(c)); onNavigate?.(); }} onDelete={(e) => handleDelete(e, c.id)} diff --git a/ui/packages/app-shell/src/console/ai/__tests__/AiAddressRedirect-34608.test.tsx b/ui/packages/app-shell/src/console/ai/__tests__/AiAddressRedirect-34608.test.tsx new file mode 100644 index 00000000000..fd8181f82a1 --- /dev/null +++ b/ui/packages/app-shell/src/console/ai/__tests__/AiAddressRedirect-34608.test.tsx @@ -0,0 +1,97 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#34608 (ui ADR-0057 as amended) — an old full-page chat address + * (a bookmark, a share link, Studio's maximize) opens the chat drawer on the + * conversation it named instead of a page (acceptance 4 of the card). + * + * The real `AiAddressRedirect` under a real router; the landing it replaces the + * visit with reports its address, its navigation state and the per-tab keys + * the drawer host reads when it mounts. Only the app list is a stand-in. + */ +import '@testing-library/jest-dom/vitest'; +import { afterEach, describe, expect, it, vi } from 'vitest'; +import React from 'react'; +import { cleanup, render, screen } from '@testing-library/react'; +import { MemoryRouter, Route, Routes, useLocation } from 'react-router-dom'; + +const meta = vi.hoisted(() => ({ apps: [] as Array> })); +vi.mock('../../../providers/MetadataProvider', async (importOriginal) => ({ + ...(await importOriginal>()), + useMetadata: () => ({ apps: meta.apps }), +})); + +import { AiAddressRedirect } from '../AiAddressRedirect'; +import { DOCK_EXPANDED_STORAGE_KEY } from '../../../layout/chatDockState'; +import { readStoredDockFullWindow, readStoredDockTarget, DOCK_HANDOFF_STATE_KEY } from '../../../layout/chatDockTarget'; + +function Landing() { + const location = useLocation(); + return ( + + {`${location.pathname}${location.search}`} + + ); +} + +function visit(entry: string | { pathname: string; search?: string; state?: unknown }) { + return render( + + + } /> + } /> + } /> + } /> + + , + ); +} + +afterEach(() => { + cleanup(); + meta.apps = []; + window.sessionStorage.clear(); +}); + +describe('an old /ai address opens the drawer on what it named (objectstack#34608)', () => { + it('/ai/build/ID lands home with the drawer armed open, filling the window, on that conversation', async () => { + visit('/ai/build/c-42'); + expect(await screen.findByTestId('landing')).toHaveTextContent(/^\/home$/); + expect(readStoredDockTarget()).toEqual({ agent: 'build', conversationId: 'c-42' }); + expect(window.sessionStorage.getItem(DOCK_EXPANDED_STORAGE_KEY)).toBe('1'); + expect(readStoredDockFullWindow()).toBe(true); + expect(screen.getByTestId('landing')).toHaveAttribute('data-state', 'null'); + }); + + it('the "Edit with AI" address keeps its package and fresh start', async () => { + visit('/ai/build?package=app.crm&new=1'); + await screen.findByTestId('landing'); + expect(readStoredDockTarget()).toEqual({ agent: 'build', packageId: 'app.crm', fresh: true }); + }); + + it('bare /ai opens the ambient thread, replacing a target left from before', async () => { + window.sessionStorage.setItem('ai-chat-dock-target', JSON.stringify({ agent: 'ask', conversationId: 'old' })); + visit('/ai'); + await screen.findByTestId('landing'); + expect(readStoredDockTarget()).toBeUndefined(); + }); + + it('lands on the declared home when the deployment declares one', async () => { + meta.apps = [{ name: 'crm', isDefault: true, active: true }]; + visit('/ai/ask'); + const landing = await screen.findByTestId('landing'); + expect(landing).toHaveTextContent(/^\/apps\/crm$/); + }); + + it('a Builder handoff rides navigation state to the landing, never storage (objectui#12493)', async () => { + visit({ pathname: '/ai/build', state: { handoffPrompt: 'Build a CRM', parentConversationId: 'ask-1' } }); + const landing = await screen.findByTestId('landing'); + expect(JSON.parse(landing.getAttribute('data-state') ?? 'null')).toEqual({ + [DOCK_HANDOFF_STATE_KEY]: { handoffPrompt: 'Build a CRM', parentConversationId: 'ask-1' }, + }); + for (let i = 0; i < window.sessionStorage.length; i += 1) { + const key = window.sessionStorage.key(i)!; + expect(window.sessionStorage.getItem(key)).not.toContain('Build a CRM'); + } + }); +}); diff --git a/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.appContextComposer-11658.test.tsx b/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.appContextComposer-11658.test.tsx index 8423a08e4ac..9b020a15eb9 100644 --- a/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.appContextComposer-11658.test.tsx +++ b/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.appContextComposer-11658.test.tsx @@ -179,3 +179,26 @@ describe('objectui#11658 item 5 — the host resolves the scope chip\'s app labe expect(resolve('no_such_app')).toBeUndefined(); }); }); + +// objectstack#34608 — acceptance 3: a builder's empty state inside an app +// shows data suggestions (the ruling:「问数据,或者让我改这个应用」), ahead of +// the change starters; the empty-state description names both halves. +describe('the build agent inside an app offers data questions too (objectstack#34608)', () => { + it('en: the starters lead with data questions, then the change starters', () => { + const props = renderPane('en', { agent: 'build', editPackageId: 'app.crm' }); + const suggestions = props.suggestions as string[]; + expect(suggestions.slice(0, 2)).toEqual([ + 'List the 5 most recently created records.', + 'Count records for each object.', + ]); + expect(suggestions.join(' ')).toMatch(/Add a field/); + const labels = props.labels as { emptyDescription: string }; + expect(labels.emptyDescription).toMatch(/Ask about this app’s data/); + }); + + it('control: the from-scratch build surface (no app) offers no data questions', () => { + const props = renderPane('en', { agent: 'build' }); + const suggestions = (props.suggestions as string[] | undefined) ?? []; + expect(suggestions).not.toContain('Count records for each object.'); + }); +}); diff --git a/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.draftsBarInFlow-12978.test.tsx b/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.draftsBarInFlow-12978.test.tsx index c810838d900..0c31fbf3394 100644 --- a/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.draftsBarInFlow-12978.test.tsx +++ b/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.draftsBarInFlow-12978.test.tsx @@ -151,6 +151,8 @@ function dockState(): ChatDockState { width: 420, dragging: false, maximized: false, + fullWindow: false, + setFullWindow: vi.fn(), toggle: vi.fn(), expand: vi.fn(), collapse: vi.fn(), diff --git a/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.planApprovalReachesLaunchers-11666.test.tsx b/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.planApprovalReachesLaunchers-11666.test.tsx index b9b3461c6df..d6f74bc5a3f 100644 --- a/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.planApprovalReachesLaunchers-11666.test.tsx +++ b/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.planApprovalReachesLaunchers-11666.test.tsx @@ -7,8 +7,8 @@ * The launchers are on screen only while the chat is closed, so the reading * must leave the chat: `ChatbotEnhanced` reports it (pinned in plugin-chatbot's * `ChatbotEnhanced.planApprovalPending-11666.test.tsx`), `ChatPane` publishes it - * on the assistant bus, and the FAB reads the bus. This file pins the middle - * hop end to end — the REAL `ChatPane` and the REAL FAB, with `ChatbotEnhanced` + * on the assistant bus, and the console launcher reads the bus. This file pins the middle + * hop end to end — the REAL `ChatPane` and the REAL top-bar robot (the FAB until objectstack#34608), with `ChatbotEnhanced` * replaced by a prop recorder so the case can play the chat's reading. */ @@ -55,7 +55,7 @@ vi.mock('../../../providers/AdapterProvider', async (importOriginal) => { import { I18nProvider } from '@object-ui/i18n'; import type { AgentDescriptor } from '@object-ui/plugin-chatbot'; import { ChatPane } from '../AiChatPage'; -import { ConsoleChatbotFab } from '../../../layout/ConsoleChatbotFab'; +import { AssistantTopBarButton } from '../../../layout/AssistantTopBarButton'; import { useConversationList } from '../../../hooks/useConversationList'; import { publishPlanApprovalPending, usePlanApprovalPendingCount } from '../../../assistant/assistantBus'; @@ -70,7 +70,9 @@ window.matchMedia = ((query: string) => ({ dispatchEvent: () => false, })) as unknown as typeof window.matchMedia; -const MARKER = 'console-chatbot-fab-plan-pending'; +// objectstack#34608 — the top-bar robot replaced the floating button as the +// console's launcher and carries its marker. +const MARKER = 'topbar-ai-assistant-plan-pending'; function renderPane(conversationId: string) { captured = {}; @@ -95,10 +97,12 @@ function renderPane(conversationId: string) { ); } -function renderFab() { +function renderLauncher() { return render( - {}} /> + + + , ); } @@ -124,9 +128,9 @@ afterEach(() => { vi.unstubAllGlobals(); }); -describe('ChatPane → assistant bus → FAB (objectui#11666)', () => { - it('the chat reading a waiting plan lights the FAB, and the marker outlives the chat closing', () => { - renderFab(); +describe('ChatPane → assistant bus → top-bar robot (objectui#11666)', () => { + it('the chat reading a waiting plan lights the robot, and the marker outlives the chat closing', () => { + renderLauncher(); const pane = renderPane('conv-1'); expect(screen.queryByTestId(MARKER)).not.toBeInTheDocument(); @@ -139,7 +143,7 @@ describe('ChatPane → assistant bus → FAB (objectui#11666)', () => { }); it('reopening the chat clears nothing by itself; the plan leaving "awaiting" does', () => { - renderFab(); + renderLauncher(); const first = renderPane('conv-1'); chatReports(true); first.unmount(); @@ -156,7 +160,7 @@ describe('ChatPane → assistant bus → FAB (objectui#11666)', () => { }); it('a chat on another thread reporting no plan does not clear the waiting one', () => { - renderFab(); + renderLauncher(); const first = renderPane('conv-1'); chatReports(true); first.unmount(); @@ -168,7 +172,7 @@ describe('ChatPane → assistant bus → FAB (objectui#11666)', () => { it('deleting the thread drops its reading (the /ai sidebar delete)', async () => { vi.stubGlobal('fetch', vi.fn(async () => new Response(null, { status: 204 }))); - renderFab(); + renderLauncher(); const pane = renderPane('conv-1'); chatReports(true); pane.unmount(); diff --git a/ui/packages/app-shell/src/console/ai/__tests__/ConversationsSidebar.test.tsx b/ui/packages/app-shell/src/console/ai/__tests__/ConversationsSidebar.test.tsx index b9316c9e093..95ba3d385fb 100644 --- a/ui/packages/app-shell/src/console/ai/__tests__/ConversationsSidebar.test.tsx +++ b/ui/packages/app-shell/src/console/ai/__tests__/ConversationsSidebar.test.tsx @@ -1,7 +1,7 @@ import '@testing-library/jest-dom/vitest'; import { describe, expect, it, vi } from 'vitest'; import { fireEvent, render, screen } from '@testing-library/react'; -import { MemoryRouter, Route, Routes } from 'react-router-dom'; +import { MemoryRouter, Route, Routes, useLocation } from 'react-router-dom'; const remove = vi.fn(async () => undefined); const rename = vi.fn(async () => undefined); @@ -114,3 +114,59 @@ describe('ConversationsSidebar', () => { expect(mark).toHaveTextContent(/pipe/i); }); }); + +// objectstack#34608 (ui ADR-0057 as amended) — hosted by the chat drawer, the +// history moves the drawer instead of the address: a row, "New" and deleting +// the open conversation call the host back and never navigate, and the row +// the drawer shows is the highlighted one, whatever the URL says. +describe('ConversationsSidebar — hosted by the chat drawer (objectstack#34608)', () => { + function Where() { + const location = useLocation(); + return {`${location.pathname}${location.search}`}; + } + + function renderHosted() { + const onSelectConversation = vi.fn(); + const onNewConversation = vi.fn(); + const onNavigate = vi.fn(); + render( + + + + , + ); + return { onSelectConversation, onNewConversation, onNavigate }; + } + + it('a row opens that conversation in the drawer, leaving the URL alone', () => { + const { onSelectConversation, onNavigate } = renderHosted(); + fireEvent.click(screen.getByTestId('ai-conversation-select-conv-a')); + expect(onSelectConversation).toHaveBeenCalledWith(expect.objectContaining({ id: 'conv-a' })); + expect(onNavigate).toHaveBeenCalledTimes(1); + expect(screen.getByTestId('where')).toHaveTextContent('/apps/crm/opportunity'); + }); + + it('highlights the conversation the drawer shows', () => { + renderHosted(); + expect(screen.getByTestId('ai-conversation-row-conv-b').className).toContain('border-primary'); + expect(screen.getByTestId('ai-conversation-row-conv-a').className).not.toContain('border-primary'); + }); + + it('"New" and deleting the open conversation start a new one in the drawer', async () => { + const { onNewConversation } = renderHosted(); + fireEvent.click(screen.getByTestId('ai-new-chat')); + expect(onNewConversation).toHaveBeenCalledTimes(1); + + fireEvent.click(screen.getByTestId('ai-conversation-delete-conv-b')); + await vi.waitFor(() => expect(onNewConversation).toHaveBeenCalledTimes(2)); + expect(remove).toHaveBeenCalledWith('conv-b'); + expect(screen.getByTestId('where')).toHaveTextContent('/apps/crm/opportunity'); + }); +}); diff --git a/ui/packages/app-shell/src/console/ai/__tests__/editModeEmptyState.test.ts b/ui/packages/app-shell/src/console/ai/__tests__/editModeEmptyState.test.ts index 0c688bef56b..3c65543280c 100644 --- a/ui/packages/app-shell/src/console/ai/__tests__/editModeEmptyState.test.ts +++ b/ui/packages/app-shell/src/console/ai/__tests__/editModeEmptyState.test.ts @@ -8,7 +8,7 @@ import { describe, it, expect } from 'vitest'; -import { agentEmptyState, buildAgentSuggestions } from '../AiChatPage'; +import { agentEmptyState, buildAgentSuggestions, editAppDataSuggestions } from '../AiChatPage'; // Identity translator: returns the defaultValue, interpolating `{{app}}` so the // edit-mode named title can be asserted. Lets us test the branching without the @@ -73,3 +73,21 @@ describe('buildAgentSuggestions — magic vs edit starters', () => { expect(s.join(' ')).not.toMatch(/Add a field/); }); }); + +// objectstack#34608 — a builder editing an app is offered both halves, as the +// ruling put it:「问数据,或者让我改这个应用」. The empty state names data +// questions as well as changes, and the starters lead with data questions. +describe('edit mode offers data questions as well as changes (objectstack#34608)', () => { + it('the edit-mode description names asking about the data and changing the app', () => { + const s = agentEmptyState(t, 'build', { appLabel: 'Tiny Todo' }); + expect(s.description).toMatch(/ask about this app’s data/i); + expect(s.description).toMatch(/counts, lists and summaries/i); + expect(s.description).toMatch(/change/i); + }); + + it('editAppDataSuggestions are data questions, drawn from the ask agent’s starters', () => { + const s = editAppDataSuggestions(t); + expect(s.length).toBeGreaterThanOrEqual(2); + for (const line of s) expect(line).not.toMatch(/^Add /); + }); +}); diff --git a/ui/packages/app-shell/src/console/home/HomeLayout.tsx b/ui/packages/app-shell/src/console/home/HomeLayout.tsx index 59f635a0ad8..2bc8532e2fb 100644 --- a/ui/packages/app-shell/src/console/home/HomeLayout.tsx +++ b/ui/packages/app-shell/src/console/home/HomeLayout.tsx @@ -40,11 +40,16 @@ * handed inside an app as well. Once mounted it stays, so it closes as it * always has. * + * It hosts the AI assistant's drawer too (objectstack#34608): the same drawer, + * the same thread and the same per-tab state as inside an app, opened by the + * bar's robot. Home has no app, so a build thread here starts unbound. + * * @module */ -import React, { useCallback, useEffect, useMemo, useState } from 'react'; -import { useLocation, useNavigate } from 'react-router-dom'; +import React, { useEffect, useMemo, useState } from 'react'; +import { useNavigate } from 'react-router-dom'; +import { cn } from '@object-ui/components'; import { useNavigationContext } from '../../context/NavigationContext.js'; import { CommandPaletteProvider, useCommandPalette } from '../../context/CommandPaletteProvider.js'; import { CommandPalette } from '../../chrome/CommandPalette.js'; @@ -59,11 +64,8 @@ import { navigationNames } from '../appObjectScope.js'; import type { ReadNamesWithoutViews } from '../../hooks/useObjectPresence.js'; import { buildExpressionUser } from '../../providers/expressionUser.js'; import { useAuth } from '@object-ui/auth'; -import { useObjectTranslation } from '@object-ui/i18n'; - -// The ChatDock's launcher (dependency-free button). -import { ConsoleChatbotFab } from '../../layout/ConsoleChatbotFab.js'; -import { rememberDockReturnLocation } from '../../layout/chatDockState.js'; +import { useConsoleChatDock } from '../../layout/useConsoleChatDock.js'; +import { ChatDockControlProvider } from '../../layout/chatDockControl.js'; /** * Home's `app`, `data` and `features`: none. Module constants, not the @@ -127,8 +129,8 @@ function HomeCommandPalette(props: HomeCommandPaletteProps) { interface HomeLayoutProps { children: React.ReactNode; /** - * Signed-in user id. Kept for API stability (callers pass it); the full-page - * chat surface resolves the user itself via useAuth. + * Signed-in user id. Kept for API stability (callers pass it); the drawer + * reads the session user itself. */ userId?: string; } @@ -140,20 +142,12 @@ export function HomeLayout({ children }: HomeLayoutProps) { const expressionUser = useMemo(() => buildExpressionUser(user), [user]); const { apps } = useMetadata(); const dataSource = useAdapter(); - const { t } = useObjectTranslation(); const navigate = useNavigate(); - const location = useLocation(); - // ADR-0057: Home has no AppShell to host the docked rail, so its FAB opens - // the full-page surface — which IS the dock maximized, same thread. The - // origin is remembered so `/ai`'s collapse-to-dock lands back here. - const openAssistant = useCallback(() => { - rememberDockReturnLocation(`${location.pathname}${location.search}`); - navigate('/ai'); - }, [location.pathname, location.search, navigate]); - // Render the chatbot only when the server serves AI (or an explicit + // The drawer exists only when the server serves AI (or an explicit // `VITE_AI_BASE_URL` opt-in is set) — same runtime signal as the rest of the // console's AI surface. See useAiSurfaceEnabled. const { enabled: showChatbot } = useAiSurfaceEnabled(); + const chatDock = useConsoleChatDock({ enabled: showChatbot, userId: user?.id }); useEffect(() => { setContext('home'); @@ -174,7 +168,13 @@ export function HomeLayout({ children }: HomeLayoutProps) { return ( -
+ + {/* With the drawer's rail open the page is bounded to the window, so the + rail spans it and the page scrolls in its own box beside it. */} +
{/* The provider wraps the bar and the palette only: the page below reads neither, so mounting it once the app list arrives re-mounts the bar and leaves the page as it is. */} @@ -191,19 +191,15 @@ export function HomeLayout({ children }: HomeLayoutProps) { ) : ( header )} -
- {children} -
- - {/* Assistant entry on the home/workspace screen — opens the full-page - chat (the dock maximized; Home has no shell to dock a rail into). */} - {showChatbot && ( - - )} +
+
+ {children} +
+ {chatDock.rail} +
+ {chatDock.sheet}
+
); } diff --git a/ui/packages/app-shell/src/console/home/HomePage.tsx b/ui/packages/app-shell/src/console/home/HomePage.tsx index a6d7a220d97..51382b130a5 100644 --- a/ui/packages/app-shell/src/console/home/HomePage.tsx +++ b/ui/packages/app-shell/src/console/home/HomePage.tsx @@ -69,6 +69,7 @@ import { fetchPackages } from '../../views/studio-design/packages-io.js'; import { resolveAiApiBase } from '../../hooks/useAiSurface.js'; import { isAiStudioEnabled, isMarketplaceEnabled } from '../../runtime-config.js'; import { STUDIO_NEW_PACKAGE_PATH } from '../../views/studio-design/studioNewPackage.js'; +import { useOpenAssistant } from '../../layout/chatDockControl.js'; /** * Which AI home CTAs to surface, driven by the live agent catalog (the single @@ -206,14 +207,15 @@ function HomeAiActions({ askAvailable, buildAvailable, canAuthorMetadata, - navigate, + openAssistant, t, layout = 'row', }: { askAvailable: boolean; buildAvailable: boolean; canAuthorMetadata: boolean; - navigate: (to: string) => void; + /** objectstack#34608 — opens the console's chat drawer on this agent, in place. */ + openAssistant: (agent: 'build' | 'ask') => void; t: (key: string, opts?: any) => string; layout?: 'row' | 'stack'; }) { @@ -229,18 +231,18 @@ function HomeAiActions({ return (
{showBuild && ( - )} {/* cloud#1674 maker convergence: with the build CTA shown, "Ask AI" is not a second door — the build composer answers data questions too - (data superset since cloud#1673), and `/ai/ask` would bounce a maker - straight back to `/ai/build`. Non-authoring sessions keep it. */} + (data superset since cloud#1673), and the ask agent would converge a + maker straight back onto build. Non-authoring sessions keep it. */} {askAvailable && !showBuild && ( - )} + Community Edition so it can't dead-end on an agent-less chat). + objectstack#34608: it opens and closes the drawer in place. */} + {aiEnabled && } {/* Help & Documentation — an aggregated menu rather than a bare external link: contextual "This app's docs" (only when the diff --git a/ui/packages/app-shell/src/layout/AssistantTopBarButton.tsx b/ui/packages/app-shell/src/layout/AssistantTopBarButton.tsx new file mode 100644 index 00000000000..a5b3b0df514 --- /dev/null +++ b/ui/packages/app-shell/src/layout/AssistantTopBarButton.tsx @@ -0,0 +1,66 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * objectstack#34608 (ui ADR-0057 as amended) — the top-bar robot, the AI + * assistant's ONE standing entry: it opens and closes the right-side drawer + * without leaving the page. The floating bottom-right button it replaces is + * gone; what that button carried moved here: + * - objectui#11666 — while a proposed plan awaits the user's approval the + * robot carries a marker, so a user who closed the chat still sees the + * assistant is waiting on them. Read off the assistant bus; only a change + * of the plan's state clears it, never opening the chat. + * + * Under a layout with no drawer it is a link to the pre-drawer address, which + * the console routes back into the drawer. + */ +import * as React from 'react'; +import { Link } from 'react-router-dom'; +import { Bot } from 'lucide-react'; +import { Button, cn } from '@object-ui/components'; +import { useObjectTranslation } from '@object-ui/i18n'; +import { usePlanApprovalPending } from '../assistant/assistantBus.js'; +import { useChatDockControl } from './chatDockControl.js'; + +export function AssistantTopBarButton({ className }: { className?: string }) { + const { t } = useObjectTranslation(); + const control = useChatDockControl(); + const planPending = usePlanApprovalPending(); + const markerId = React.useId(); + const label = t('topbar.aiAssistant', { defaultValue: 'AI Assistant' }); + const marker = planPending ? ( + + + ) : null; + const classes = cn('relative h-8 w-8 max-md:size-11 shrink-0', className); + if (!control) { + return ( + + ); + } + return ( + + ); +} diff --git a/ui/packages/app-shell/src/layout/ChatDock.tsx b/ui/packages/app-shell/src/layout/ChatDock.tsx index 90d8d5b4f95..c4e74ca8ca8 100644 --- a/ui/packages/app-shell/src/layout/ChatDock.tsx +++ b/ui/packages/app-shell/src/layout/ChatDock.tsx @@ -9,13 +9,17 @@ * operator opts in, none of this renders and the FAB stays the canonical entry. * * It reuses the shared {@link ChatPane} engine over the P1 `(user, app, product)` - * conversation — the same thread the full-page `/ai` surface shows — so the dock - * is a VIEW, not a new conversation. P3b retired the FAB into this dock's - * launcher. P3c makes `/ai` the dock maximized (the header's maximize button ⇄ - * the page's collapse-to-dock button, same thread both ways) and auto-maximizes + * conversation, so the dock is a VIEW, not a new conversation. P3c auto-maximizes * the rail while the ADR-0037 Live Canvas is open. (P3c also reused the panel * under Studio; objectui#12725 moved the Studio copilot into that surface's own * right slot, `StudioRightSlot`, so the console is this panel's one host.) + * + * objectstack#34608 (ADR-0057 as amended) — the drawer is the console's ONLY + * chat container. The top-bar robot opens and closes it; there is no floating + * button and no full-page chat route. Expanding fills the window IN PLACE (the + * page stays mounted under it and the address does not change) and the same + * button restores the rail; the conversation history sits beside the chat in + * the full window and behind a History button in the rail. */ import * as React from 'react'; import { @@ -27,12 +31,18 @@ import { SheetHeader, SheetTitle, } from '@object-ui/components'; -import { Maximize2, MessagesSquare, PanelRightClose } from 'lucide-react'; +import { History, Maximize2, MessagesSquare, Minimize2, PanelRightClose, X } from 'lucide-react'; import { useObjectTranslation } from '@object-ui/i18n'; import { resolveApiBase } from '../console/ai/resolveApiBase.js'; import { AiUsageIndicator } from './AiUsageIndicator.js'; import { usePlanApprovalPending } from '../assistant/assistantBus.js'; import type { ChatSurfaceContext } from './chatSurfaceContext.js'; +import { + readStoredDockFullWindow, + writeStoredDockFullWindow, + type ChatDockHandoff, + type ChatDockTarget, +} from './chatDockTarget.js'; import { clampDockWidth, maximizedDockWidth, @@ -72,6 +82,13 @@ export interface ChatDockOptions { * objectui#12725 gave Studio a fixed-width right slot.) */ persistWidthKey?: string; + /** + * objectstack#34608 — round-trip the full-window flag through sessionStorage + * (`DOCK_FULL_WINDOW_STORAGE_KEY`), so an old full-page link the console + * routes into the drawer opens it filling the window. The console drawer + * sets it; off, the flag lives in memory. + */ + persistFullWindow?: boolean; } export interface ChatDockState { @@ -91,6 +108,14 @@ export interface ChatDockState { maximize: () => void; /** Undo `maximize` — a no-op unless currently maximized (see doc below). */ restore: () => void; + /** + * objectstack#34608 — true while the drawer fills the window in place. Not + * the canvas latch above: that one widens the rail beside the page, this one + * covers the page, which stays mounted under it. + */ + fullWindow: boolean; + /** Fill the window, or go back to the rail. Opening is implied when filling. */ + setFullWindow: (fullWindow: boolean) => void; /** Pointer-down on the rail's left-edge resize handle. */ onResizePointerDown: (e: React.PointerEvent) => void; } @@ -120,6 +145,7 @@ export function useChatDockState(options?: ChatDockOptions): ChatDockState { defaultExpanded = false, persistExpandedKey, persistWidthKey = DOCK_WIDTH_STORAGE_KEY, + persistFullWindow = false, } = options ?? {}; const [expanded, setExpandedState] = React.useState(() => persistExpandedKey ? readStoredDockExpanded(persistExpandedKey, defaultExpanded) : defaultExpanded, @@ -127,6 +153,9 @@ export function useChatDockState(options?: ChatDockOptions): ChatDockState { const [width, setWidth] = React.useState(() => readStoredWidth(persistWidthKey)); const [dragging, setDragging] = React.useState(false); const [maximized, setMaximized] = React.useState(false); + const [fullWindow, setFullWindowState] = React.useState(() => + persistFullWindow ? readStoredDockFullWindow() : false, + ); // The latch and the width to return to when the canvas closes. Refs, not // state: they are only read inside handlers (never rendered), and the latch // must be checkable synchronously so a double-fired maximize/restore (React @@ -206,9 +235,26 @@ export function useChatDockState(options?: ChatDockOptions): ChatDockState { setMaximized(false); }, [persistWidthKey]); - const toggle = React.useCallback(() => setExpanded((v) => !v), [setExpanded]); + const setFullWindow = React.useCallback( + (next: boolean) => { + setFullWindowState(next); + if (persistFullWindow) writeStoredDockFullWindow(next); + if (next) setExpanded(() => true); + }, + [persistFullWindow, setExpanded], + ); + // Closing the drawer also leaves the full window: the next open is the rail. + const toggle = React.useCallback(() => { + setExpanded((v) => !v); + setFullWindowState(false); + if (persistFullWindow) writeStoredDockFullWindow(false); + }, [setExpanded, persistFullWindow]); const expand = React.useCallback(() => setExpanded(() => true), [setExpanded]); - const collapse = React.useCallback(() => setExpanded(() => false), [setExpanded]); + const collapse = React.useCallback(() => { + setExpanded(() => false); + setFullWindowState(false); + if (persistFullWindow) writeStoredDockFullWindow(false); + }, [setExpanded, persistFullWindow]); return { expanded, @@ -220,6 +266,8 @@ export function useChatDockState(options?: ChatDockOptions): ChatDockState { collapse, maximize, restore, + fullWindow, + setFullWindow, onResizePointerDown, }; } @@ -236,7 +284,17 @@ const ChatDockConversation = React.lazy(() => import('./ChatDockConversation.js').then((m) => ({ default: m.ChatDockConversation })), ); -export interface ChatDockPanelProps { +/** objectstack#34608 — what the drawer shows, and the handoff it seeds (see `chatDockTarget.ts`). */ +export interface ChatDockThreadProps { + /** Absent → the ambient thread (see {@link ChatDockConversation}). */ + target?: ChatDockTarget; + /** Replaces the target in place: a history row, a minted fresh thread, a binding. */ + onTargetChange?: (target: ChatDockTarget | undefined) => void; + /** A Builder handoff to seed once as the build thread's first message. */ + handoff?: ChatDockHandoff; +} + +export interface ChatDockPanelProps extends ChatDockThreadProps { dock: ChatDockState; /** Signed-in user id for the default (console ask) body. Unused with `children`. */ userId?: string; @@ -259,30 +317,24 @@ export interface ChatDockPanelProps { surfaceArtifactLabel?: string; /** Header title override; default "Assistant". */ title?: string; - /** - * ADR-0057 P3c — render a maximize header button that opens the full-page - * focus surface (`/ai…`) on the SAME thread. The caller supplies the - * navigation because the right target is per-surface (console → `/ai`, - * Studio → `/ai/build?package=…`). The default body's bound package - * (objectui#10926) is passed along — `undefined` when the thread is - * app-less, and always with a `children` body. - */ - onMaximize?: (boundPackageId?: string) => void; /** * Body override. Default mounts {@link ChatDockConversation} (the console's - * own thread — app-bound for `build` inside an authorable app, product-only - * otherwise). A caller may pass its own conversation instead (the Studio - * dock passed its package-scoped build thread until objectui#12725) — note - * the empty-catalog gate then lives in the caller, because the default - * body's self-gate is bypassed. + * drawer thread, with its history). A caller may pass its own conversation + * instead — the empty-catalog gate then lives in the caller, because the + * default body's self-gate is bypassed, and there is no History button. */ children?: React.ReactNode; } /** - * The expanded rail — pass into {@link AppShell} `rightRail` so it reflows the - * main content. Only render this when `dock.expanded` (the caller decides), so a - * collapsed dock contributes no flex child. + * The expanded drawer — pass into {@link AppShell} `rightRail` so the rail + * reflows the main content. Only render this when `dock.expanded` (the caller + * decides), so a collapsed dock contributes no flex child. + * + * objectstack#34608 — `dock.fullWindow` turns the SAME element into a fixed + * layer over the whole window: the chat is not remounted (a streaming answer + * keeps streaming), the page underneath stays mounted, and the address does not + * change. The header's expand button becomes the restore button. */ export function ChatDockPanel({ dock, @@ -293,12 +345,15 @@ export function ChatDockPanel({ surfaceContext, surfaceArtifactLabel, title, - onMaximize, + target, + onTargetChange, + handoff, children, }: ChatDockPanelProps) { const { t } = useObjectTranslation(); const apiBase = React.useMemo(() => resolveApiBase(apiBaseProp), [apiBaseProp]); - const [boundPackageId, setBoundPackageId] = React.useState(undefined); + const [historyOpen, setHistoryOpen] = React.useState(false); + const full = dock.fullWindow; // ADR-0037/P3c — the default body auto-maximizes the rail while the Live // Canvas is open and tucks back when it closes (restore self-guards against // the mount-time false, StrictMode, and user-drag takeover). @@ -306,30 +361,38 @@ export function ChatDockPanel({ (open: boolean) => (open ? dock.maximize() : dock.restore()), [dock.maximize, dock.restore], ); + const expandLabel = full + ? t('console.ai.dock.restore', { defaultValue: 'Restore side panel' }) + : t('console.ai.dock.expand', { defaultValue: 'Expand' }); return (