diff --git a/.changeset/37788-app-ai-inquiry-page.md b/.changeset/37788-app-ai-inquiry-page.md new file mode 100644 index 00000000000..c4b3e8a83fc --- /dev/null +++ b/.changeset/37788-app-ai-inquiry-page.md @@ -0,0 +1,20 @@ +--- +'@object-ui/app-shell': patch +'@object-ui/i18n': patch +--- + +feat(app-shell): an app's AI inquiry page — the `ai:chat` menu entry opens a home for asking, and the drawer stays closed there + +Clause-②: no +Metadata-protocol: none + +An app can now put the platform's AI inquiry page on its menu, as ui ADR-0057 Amendment A4 records: a `type: 'component'` navigation entry with `componentRef: 'ai:chat'`. It is the app's home by the app's existing landing rule: a declared `landing` comes first; with none, from 768 px up the first entry shown lands, so an entry placed first is the home; below 768 px the app root is the app's menu, and the page is one row of it. Before, that entry drew "Component not registered". + +- **Home state.** The entry's `params` (`AiChatNavParamsSchema`, `@objectstack/spec/ui`) give the welcome title and subtitle, the question box's placeholder and up to four suggested questions; a key the entry omits falls back to neutral platform copy, and nothing is read from the URL. A static badge says answers prefer this app's data. Clicking a suggestion asks it. +- **Conversation.** The first question turns the same page into the conversation, with the platform `ask` agent (a maker gets `ask` here too), bound to the app's package (`context.activeApp`) under the conversation key `app:PKG:ask`. The conversation create sends `metadata: { activePackageId: PKG }`, and the page's address carries `?c=ID` from then on, so a reload restores it. A `?c=` that names a conversation that is not the caller's, or that this app's page did not create, opens the home state: no error, and nothing of it is shown. "New conversation" returns to the home state. +- **No second conversation on the page.** While the page is the active route the assistant drawer is closed, the top-bar robot is not drawn, and Ctrl/Cmd+Shift+I opens nothing; a build hand-off from the page still opens the drawer. On every other page the desktop drawer is as the user left it; a phone's sheet, which already closes when the user moves to another page, stays closed after the page. +- **No AI for this person** (no AI on the deployment, or no seat): the page shows the existing "AI assistant unavailable" state. +- `useChatConversation` takes an optional `createMetadata`, the `metadata` its first-send create carries; every other caller still sends an empty body. +- `@object-ui/i18n`: one new string, `console.ai.askPage.scopeBadge`, in every locale. + +Nothing to migrate. diff --git a/ui/packages/app-shell/src/console/ai/AppAskPage.tsx b/ui/packages/app-shell/src/console/ai/AppAskPage.tsx new file mode 100644 index 00000000000..89fb5b817c1 --- /dev/null +++ b/ui/packages/app-shell/src/console/ai/AppAskPage.tsx @@ -0,0 +1,370 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * AppAskPage — an app's AI inquiry page, the built-in component an app places + * on its menu as a `type: 'component'` entry with `componentRef: 'ai:chat'` + * (ui ADR-0057 Amendment A4). + * + * Home state first: the entry's welcome title and subtitle, a large question + * box with its placeholder, and up to four suggested questions, all from the + * entry's `params` (`AiChatNavParamsSchema`), never from the URL; a key the + * entry omits falls back to the platform's neutral copy. The first question + * turns the same page into the conversation: the shared `ChatPane`, pinned to + * the platform `ask` agent (a maker gets `ask` here too), bound to this app's + * package (`context.activeApp`) under the key `app:PKG:ask`. The create + * records `metadata.activePackageId`, and the page's address carries + * `?c=ID` from then on, so a reload restores it. A `?c=` naming a + * conversation that is not the caller's, or not this app's, opens the home + * state: no error, and nothing of it is shown. + * + * The page is the one ask conversation on its screen: while it is the active + * route the console's drawer stays closed and its triggers are hidden or inert + * (`useConsoleChatDock`'s `askPageActive`). A build hand-off from here still + * opens the drawer. + * + * Registered lazily (`services/builtinComponents.tsx`): this module statically + * reaches the chat UI, so ⛔ nothing in the eager console graph may import it. + */ + +import * as React from 'react'; +import { useNavigate, useParams, useSearchParams } from 'react-router-dom'; +import { ArrowUp, Plus, Sparkles } from 'lucide-react'; +import { useAuth } from '@object-ui/auth'; +import { Badge, Button, Textarea, cn } from '@object-ui/components'; +import { useObjectTranslation } from '@object-ui/i18n'; +import { resolveNavItemLabel } from '@object-ui/layout'; +import type { NavigationItem } from '@object-ui/types'; +import { resolveAgentParam, useAgents } from '@object-ui/plugin-chatbot/core'; +import { ChatPane, type PendingFirstMessage } from './AiChatPage.js'; +import { AiUnavailable } from './AiUnavailable.js'; +import { resolveApiBase } from './resolveApiBase.js'; +import { + ASK_CONVERSATION_PARAM, + askPageConversationScope, + askPageCreateMetadata, + conversationBelongsToAskPage, + findAiChatNavEntry, + readAiChatPageCopy, +} from './appAskPageModel.js'; +import { useChatConversation, type HydratedUIMessage } from '../../hooks/useChatConversation.js'; +import { fetchConversation } from '../../hooks/useChatConversation.js'; +import { useAiSurfaceEnabled } from '../../hooks/useAiSurface.js'; +import { useHomePath } from '../../hooks/useHomePath.js'; +import { useMetadata } from '../../providers/MetadataProvider.js'; +import { useNavigationContext } from '../../context/NavigationContext.js'; +import { matchAppBySegment } from '../../utils/appRoute.js'; +import { PageHeader } from '../../layout/PageHeader.js'; + +const EMPTY_INITIAL_MESSAGES: HydratedUIMessage[] = []; + +/** What the page knows about the conversation its address names. */ +type RequestedVerdict = { id: string; verdict: 'checking' | 'ours' | 'foreign' }; + +export function AppAskPage() { + const { t, language } = useObjectTranslation(); + const navigate = useNavigate(); + const homePath = useHomePath(); + const [searchParams, setSearchParams] = useSearchParams(); + const { user } = useAuth(); + const userId = user?.id; + + // ── The app, its `ai:chat` entry and the entry's copy ─────────────────── + const metadata = useMetadata(); + const { currentAppName } = useNavigationContext(); + const routeParams = useParams(); + const app = matchAppBySegment( + (metadata.apps ?? []) as Array>, + currentAppName || routeParams.appName, + ); + const packageId = typeof app?._packageId === 'string' ? app._packageId : undefined; + const entry = React.useMemo(() => findAiChatNavEntry(app), [app]); + const copy = React.useMemo(() => readAiChatPageCopy(entry), [entry]); + const pageLabel = entry ? resolveNavItemLabel(entry as unknown as NavigationItem, t, undefined, language) : ''; + const title = copy.title ?? t('console.ai.empty.ask.title', { defaultValue: 'Ask your data' }); + const subtitle = copy.subtitle ?? t('console.ai.empty.ask.description', { + defaultValue: + 'Ask questions about your records — counts, lists, and summaries across the data you can access.', + }); + const placeholder = copy.placeholder ?? t('console.ai.askAnything', { defaultValue: 'Ask anything…' }); + + // ── The agent: always the platform `ask` ──────────────────────────────── + const apiBase = React.useMemo(() => resolveApiBase(), []); + const surface = useAiSurfaceEnabled(); + const { agents, isLoading: agentsLoading, error: agentsError, refetch: refetchAgents } = useAgents({ apiBase }); + const catalogNames = React.useMemo(() => agents.map((a) => a.name), [agents]); + const askAgent = agents.length > 0 ? resolveAgentParam('ask', catalogNames) : undefined; + const chatApi = askAgent ? `${apiBase}/agents/${encodeURIComponent(askAgent)}/chat` : undefined; + const unavailable = !surface.isLoading && !surface.enabled && !agentsLoading; + + // ── The conversation the address names (`?c=`) ────────────────────────── + const requestedId = searchParams.get(ASK_CONVERSATION_PARAM)?.trim() || undefined; + // Ids this page created: they are this app's by construction, so the + // address the page writes for them is never re-checked. + const ownIdsRef = React.useRef>(new Set()); + const [requested, setRequested] = React.useState(undefined); + if (requestedId && requested?.id !== requestedId) { + setRequested({ id: requestedId, verdict: ownIdsRef.current.has(requestedId) ? 'ours' : 'checking' }); + } else if (!requestedId && requested) { + setRequested(undefined); + } + const checking = requested?.verdict === 'checking' ? requested.id : undefined; + React.useEffect(() => { + if (!checking) return; + let cancelled = false; + void (async () => { + let ours = false; + if (packageId) { + try { + ours = conversationBelongsToAskPage(await fetchConversation(apiBase, checking), packageId); + } catch { + ours = false; + } + } + if (cancelled) return; + setRequested((prev) => (prev?.id === checking ? { id: checking, verdict: ours ? 'ours' : 'foreign' } : prev)); + })(); + return () => { + cancelled = true; + }; + }, [checking, apiBase, packageId]); + // A foreign `?c=` leaves the address: the page opens its home state. + const foreign = requested?.verdict === 'foreign' ? requested.id : undefined; + React.useEffect(() => { + if (!foreign) return; + setSearchParams( + (prev) => { + const next = new URLSearchParams(prev); + if (next.get(ASK_CONVERSATION_PARAM) === foreign) next.delete(ASK_CONVERSATION_PARAM); + return next; + }, + { replace: true }, + ); + }, [foreign, setSearchParams]); + const activeId = requested?.verdict === 'ours' ? requested.id : undefined; + + // ── The page's thread ─────────────────────────────────────────────────── + // `started`: the first question was asked on the home state, so the pane is + // up while its conversation is created. + const [started, setStarted] = React.useState(false); + const scope = packageId ? askPageConversationScope(packageId) : undefined; + const createMetadata = React.useMemo( + () => (packageId ? askPageCreateMetadata(packageId) : undefined), + [packageId], + ); + const { + conversationId, + conversationScope, + initialMessages, + isLoading: conversationLoading, + ensureConversation, + createError, + } = useChatConversation({ + userId: askAgent && scope ? userId : undefined, + scope, + apiBase, + activeId, + // The home state is a new question: never the last cached thread. + forceNew: !activeId, + createMetadata, + }); + const scopeMatched = conversationScope === scope; + const paneConversationId = scopeMatched ? conversationId : undefined; + const paneInitialMessages = scopeMatched ? initialMessages : EMPTY_INITIAL_MESSAGES; + + // The first send created the conversation: the address names it from now on. + React.useEffect(() => { + if (!started || !paneConversationId || requestedId === paneConversationId) return; + ownIdsRef.current.add(paneConversationId); + setSearchParams( + (prev) => { + const next = new URLSearchParams(prev); + next.set(ASK_CONVERSATION_PARAM, paneConversationId); + return next; + }, + { replace: true }, + ); + }, [started, paneConversationId, requestedId, setSearchParams]); + + const pendingFirstMessageRef = React.useRef(null); + const [selectedModelId, setSelectedModelId] = React.useState(undefined); + const ask = React.useCallback((text: string) => { + const content = text.trim(); + if (!content) return; + pendingFirstMessageRef.current = { content }; + setStarted(true); + }, []); + const startOver = React.useCallback(() => { + pendingFirstMessageRef.current = null; + setStarted(false); + setSelectedModelId(undefined); + setSearchParams( + (prev) => { + const next = new URLSearchParams(prev); + next.delete(ASK_CONVERSATION_PARAM); + return next; + }, + ); + }, [setSearchParams]); + + // ── What the page draws ───────────────────────────────────────────────── + const restoring = Boolean(checking) || (Boolean(activeId) && !started && conversationLoading); + const inConversation = started || Boolean(activeId); + let body: React.ReactNode; + if (unavailable || (!surface.isLoading && surface.enabled && !agentsLoading && !askAgent)) { + body = ( + navigate(homePath)} + t={t} + /> + ); + } else if (surface.isLoading || restoring) { + body =
; + } else if (inConversation) { + body = ( +
+ +
+ ); + } else { + body = ( + + ); + } + + return ( +
+ } + actions={ + inConversation && !unavailable ? ( + + ) : undefined + } + /> + {body} +
+ ); +} + +function noop() {} + +interface AskHomeProps { + title: string; + subtitle: string; + placeholder: string; + suggestions: string[]; + scopeLabel: string; + sendLabel: string; + onAsk: (text: string) => void; +} + +/** The home state: the welcome, the large question box and the suggested questions. */ +function AskHome({ title, subtitle, placeholder, suggestions, scopeLabel, sendLabel, onAsk }: AskHomeProps) { + const [text, setText] = React.useState(''); + const submit = () => { + if (text.trim()) onAsk(text); + }; + return ( +
+
+
+

+ {title} +

+

+ {subtitle} +

+
+
{ + event.preventDefault(); + submit(); + }} + > +