Skip to content

Commit e50ab8f

Browse files
feat(app-shell): an app's AI inquiry page (ai:chat) — home state, conversation, drawer closed there (#37889)
<!-- claude-projects-attribution: {"github_login":"os-elon-musk"} --> _Requested by **Elon** · [project thread](https://claude.ai/code/project/chan_01WedDzV26nniwxv7jC88B9D?thread=cmsg_01WedDzV26nniwxv7jC88B9D71daFMSfEFsgPq1ECrMYCy)_ Fixes #37788 Clause-②: no Metadata-protocol: none ## 维护者速读 - 是什么:平台通用的「AI 问询」页面上线。应用在菜单里放一个 `ai:chat` 入口(按应用现有的首页规则:没声明 landing 时,电脑上放第一位就是首页;手机上应用首页是菜单),进来先看到应用配置的欢迎语、大输入框和推荐问题;提问后同一页变成对话,刷新能恢复。 - 为什么:落地 ADR-0057 修订 A4(#37825 已合)。以前这个入口会显示「组件未注册」;现在有页面,而且这一页上右上角机器人隐藏、快捷键无效,不会出现两个对话。 - 出错会怎样:只影响菜单里放了 `ai:chat` 的应用;其他页面抽屉照旧。没开 AI 或没席位的人看到现有的「AI 助手不可用」页。 - 要你做的:无,区内复审后交座位。 ## What changes The `ai:chat` component ref (`AI_CHAT_COMPONENT_REF`, `@objectstack/spec/ui`) gets its page, per ui ADR-0057 Amendment A4 as merged in #37825. - **`console/ai/AppAskPage.tsx`** (new, +370) — the page, registered lazily in `services/builtinComponents.tsx` (`registerAppComponent` + `lazyPage`, so it stays out of the eager closure; the console build's declared-lazy check passes). Home state: title, subtitle, placeholder and up to four suggestions from the entry's `params`, read through `AiChatNavParamsSchema`; a key the entry omits falls back to neutral platform copy, and nothing is read from the URL. A static badge, 「Answers prefer this app」. Enter sends, Shift+Enter and IME composition do not. The first question turns the same page into the conversation: the existing `ChatPane` (header hidden) on the `ask` agent, a maker included, bound to the app's package (`activeAppPackageId`), under the conversation key `app:PKG:ask`. The first message is held and replayed by the pane's existing deferred-first-send path, so the conversation row is created on first send. - **`?c=ID`** — once the conversation exists the address carries it (`replace`), so a reload restores it. A `?c=` the page did not create is checked with the existing `GET /conversations/:id`: one whose `metadata.activePackageId` is not this app's package, or one that is not the caller's (403/404), opens the home state and is removed from the address; nothing of it is drawn. 「New conversation」 in the page header returns to the home state. - **`console/ai/appAskPageModel.ts`** (new, +128) — the rules without React: finding the app's `ai:chat` entry (navigation, then `areas[].navigation`, through `children`), reading its copy (a record the schema refuses is read as declaring nothing, with one console warning), the conversation key, the create metadata, and the belongs-to-this-app test. - **`hooks/useChatConversation.ts`** — an optional `createMetadata`; the first-send create sends `{ metadata }` when it is set. Only the page sets it (`{ activePackageId: PKG }`); every other caller still sends `{}`. `ServerConversation` gains the `metadata` the GET contract already returns. - **Drawer rule, `layout/**`** — `isAppAskPagePath` (`consoleRoutePaths.ts`) names the page's route; `ConsoleLayout` passes `askPageActive` to `useConsoleChatDock`. While it holds: the drawer renders closed (the stored preference is untouched and comes back off the page), `open()` and the assistant bus are inert, the Ctrl/Cmd+Shift+I effect is not bound, and `AssistantTopBarButton` returns `null` (`ChatDockControl.askPageActive`). A build hand-off still opens the drawer: `open()` with a handoff or a build-agent target passes (`opensBesideAskPage`), and the drawer stays open until it is collapsed or the user leaves the page. On a phone, arriving on the page with the sheet stored open collapses it, so the next page does not bring it back (the sheet already closes on any move away, #37556); the desktop rail keeps its stored state. - **`@object-ui/i18n`** — one key, `console.ai.askPage.scopeBadge`, in all 11 packs. The other strings reuse existing keys (`console.ai.empty.ask.*`, `console.ai.askAnything`, `console.ai.submit`, `console.ai.newConversation`). - One changeset (`@object-ui/app-shell` and `@object-ui/i18n`, patch). Not touched: `AiChatPage.tsx`, `ChatbotEnhanced.tsx`, `ui/docs/adr/**`, `packages/spec/src`. ## Tests - `console/ai/__tests__/AppAskPage-37788.test.tsx` (11) — the real page, the real `useChatConversation` over a stubbed `fetch`, the real router and registry; stand-ins for the agent catalog, the AI gate, app metadata, `ChatPane` and `AiUnavailable`. It covers: the registry entry; declared copy; fallback copy; no copy from the URL; a suggestion asks it (pane on `ask`, bound to the package, the create body `{ metadata: { activePackageId } }`, the address gains `?c=`); a maker gets `ask`; a reload restores from `?c=`; another app's conversation opens the home state and leaves the address; a 403 opens the home state; New conversation; and the unavailable state. - `console/ai/__tests__/appAskPageModel.test.ts` — finding the entry, copy and fallback, the warning on a refused record, the key, belongs-to-this-app, and `isAppAskPagePath` agreeing with `componentRefToUrlSegments(AI_CHAT_COMPONENT_REF)`. - `layout/__tests__/useConsoleChatDock.phoneCollapseOnNavigate-37556.test.tsx` (+7, real dock + control provider + top-bar button): the drawer is closed on the page and back off it; the robot is hidden on the page only; the toggle chord and `ask` opens are inert on the page; control: the chord works off it; a build open still opens the drawer; on a phone, a sheet open on arrival is closed by the page and stays closed on the next page; on a phone, a build hand-off still opens the sheet. - `layout/__tests__/ConsoleLayout.askPageHidesEntry-37788.test.tsx` (new, 2): through the real `ConsoleLayout` wiring, the entry is not drawn on the `ai:chat` route and is back on another; a drawer open elsewhere is closed on the route and comes back after it. - `hooks/__tests__/useChatConversation.test.tsx` (+2): `createMetadata` reaches the create body; the drawer's create is still `{}`. - Ablations: with `AssistantTopBarButton`'s `askPageActive` return removed, "the robot is hidden on the page only" fails; with the phone-collapse branch disabled, the phone case fails (1 failed / 15 passed); with `ConsoleLayout`'s `askPageActive` set to `false`, both wiring cases fail. Restored, all pass. ## Acceptance notes - **Item 10, `context.surface`: not tagged, and why.** A cheap hook does exist: `ChatPane` takes `surfaceContext` and sends it as `context.surface`, and the spec's `pillar` is a free advisory string (`packages/spec/src/contracts/ai-service.ts`, `surfaceContext`). It is left out because the shape is cloud#1610's, and cloud's agent route sanitizes it field by field (`ui/packages/app-shell/src/layout/chatSurfaceContext.ts`, module doc). Which `pillar` value that sanitizer keeps cannot be read from here: the cloud repository is out of this seat's reach. So the page sends no value that cloud might drop, and the console invents no new vocabulary. Evals can still split these turns: every conversation the page creates carries `metadata.activePackageId`, which only this page sets. Once cloud names a value, tagging is a one-prop change on `ChatPane`. - **Location-state hand-offs.** A `/ai…` address with handoff state that lands on the page does not open the drawer. Only `open()` with a build target or a handoff does. - **Phone root** is out of scope, as the ADR names it. - **The entry stays hidden after a hand-off opens the drawer on the page.** That is A4's rule: on the page the triggers are hidden or inert. The drawer closes with its own control, and reopening it there would put a second conversation on the page. - **L1 nits not taken in this delta**, to keep it to the dock hook, the tests, the changeset and this body. They are: a transient error on the `?c=` check is read as foreign; the check fetches the full conversation to read `metadata`; an app with no `_packageId` gets no message; duplicate suggestions share a React key. Each one touches `AppAskPage.tsx`. - **Beyond the order's file list:** the 11 locale packs (one key), the model module `appAskPageModel.ts`, and four files under `layout/**` (`consoleRoutePaths.ts`, `chatDockControl.tsx`, `AssistantTopBarButton.tsx`, `ConsoleLayout.tsx`). ui AGENTS asks for docs updates (README, `content/docs/frontend`); those are outside this PR's surface and are left for a follow-up. - **Overlap:** #37885 (Ask AI entry button) rewrites `AssistantTopBarButton.tsx`, so the two PRs conflict textually there. The conflict is one early return plus a doc line: `if (control?.askPageActive) return null;` goes at the top of the rewritten component. With #37885, the entry also appears in page headers, and this return hides it on the page too. Whichever PR lands second rebases. With `origin/main` and #37676 this branch merges cleanly. ## Verification - At `df8d6f75`: `pnpm exec vitest run` of the AppAskPage, dock, the two ConsoleLayout and the model/conversation test files: all green (AppAskPage 11/11, dock 16/16, ConsoleLayout wiring 2/2, robot 2/2). `app-shell` type-check, both programs: exit 0. eslint on the changed files: 0 errors. - The derived gates (`dispatch-gates --ran`: 41 of 41 run), plus the i18n keys, drift, dead-keys, all-locales parity, product-neutral ratchet, eslint on the changed files and `check:new-line-citations`: all exit 0 (re-read after the L1 delta: the changeset gates, `check:test-source-alias`, cross-package test inputs, the timer probe, ceremony text, the role word and new-line citations, all exit 0). `check:test-source-alias` first flagged that the two edited test files reach `AiChatPage`'s lazy `import('@object-ui/plugin-grid')`; fixed by loading it at module top, as the gate prescribes. - Full `pnpm build`: exit 0. - **Browser** (showcase app, `pnpm dev --fresh`, console on Vite): an `ai:chat` entry was injected first in `showcase_app`'s navigation through a Playwright route on `/api/v1/meta/app`, with no source edit. `/api/v1/ai/**` was stubbed, since OSS has no AI. Results: - The home state draws the declared copy, the badge and four suggestions. - `?c=conv-1` restores the conversation (user question plus a markdown answer) with 「New conversation」 in the header. - The top-bar Ask AI entry counts 0 on the page and 1 on the Capability Map page. - Screenshots, at 1440×900 @2x, of the home state and the restored conversation, are kept with the project. The relay cannot upload images. Both were viewed at L1 (comment 7215194705). --- _Generated by [Claude Code](https://claude.ai/code/session_016WV4czF5gqc48r9LUsmRpw)_ <!-- signed: repo:objectstack#1 · os-elon-musk · session_016WV4czF5gqc48r9LUsmRpw --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 0a3ea67 commit e50ab8f

26 files changed

Lines changed: 1311 additions & 15 deletions
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
---
2+
'@object-ui/app-shell': patch
3+
'@object-ui/i18n': patch
4+
---
5+
6+
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
7+
8+
Clause-②: no
9+
Metadata-protocol: none
10+
11+
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".
12+
13+
- **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.
14+
- **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.
15+
- **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.
16+
- **No AI for this person** (no AI on the deployment, or no seat): the page shows the existing "AI assistant unavailable" state.
17+
- `useChatConversation` takes an optional `createMetadata`, the `metadata` its first-send create carries; every other caller still sends an empty body.
18+
- `@object-ui/i18n`: one new string, `console.ai.askPage.scopeBadge`, in every locale.
19+
20+
Nothing to migrate.
Lines changed: 370 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,370 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* AppAskPage — an app's AI inquiry page, the built-in component an app places
5+
* on its menu as a `type: 'component'` entry with `componentRef: 'ai:chat'`
6+
* (ui ADR-0057 Amendment A4).
7+
*
8+
* Home state first: the entry's welcome title and subtitle, a large question
9+
* box with its placeholder, and up to four suggested questions, all from the
10+
* entry's `params` (`AiChatNavParamsSchema`), never from the URL; a key the
11+
* entry omits falls back to the platform's neutral copy. The first question
12+
* turns the same page into the conversation: the shared `ChatPane`, pinned to
13+
* the platform `ask` agent (a maker gets `ask` here too), bound to this app's
14+
* package (`context.activeApp`) under the key `app:PKG:ask`. The create
15+
* records `metadata.activePackageId`, and the page's address carries
16+
* `?c=ID` from then on, so a reload restores it. A `?c=` naming a
17+
* conversation that is not the caller's, or not this app's, opens the home
18+
* state: no error, and nothing of it is shown.
19+
*
20+
* The page is the one ask conversation on its screen: while it is the active
21+
* route the console's drawer stays closed and its triggers are hidden or inert
22+
* (`useConsoleChatDock`'s `askPageActive`). A build hand-off from here still
23+
* opens the drawer.
24+
*
25+
* Registered lazily (`services/builtinComponents.tsx`): this module statically
26+
* reaches the chat UI, so ⛔ nothing in the eager console graph may import it.
27+
*/
28+
29+
import * as React from 'react';
30+
import { useNavigate, useParams, useSearchParams } from 'react-router-dom';
31+
import { ArrowUp, Plus, Sparkles } from 'lucide-react';
32+
import { useAuth } from '@object-ui/auth';
33+
import { Badge, Button, Textarea, cn } from '@object-ui/components';
34+
import { useObjectTranslation } from '@object-ui/i18n';
35+
import { resolveNavItemLabel } from '@object-ui/layout';
36+
import type { NavigationItem } from '@object-ui/types';
37+
import { resolveAgentParam, useAgents } from '@object-ui/plugin-chatbot/core';
38+
import { ChatPane, type PendingFirstMessage } from './AiChatPage.js';
39+
import { AiUnavailable } from './AiUnavailable.js';
40+
import { resolveApiBase } from './resolveApiBase.js';
41+
import {
42+
ASK_CONVERSATION_PARAM,
43+
askPageConversationScope,
44+
askPageCreateMetadata,
45+
conversationBelongsToAskPage,
46+
findAiChatNavEntry,
47+
readAiChatPageCopy,
48+
} from './appAskPageModel.js';
49+
import { useChatConversation, type HydratedUIMessage } from '../../hooks/useChatConversation.js';
50+
import { fetchConversation } from '../../hooks/useChatConversation.js';
51+
import { useAiSurfaceEnabled } from '../../hooks/useAiSurface.js';
52+
import { useHomePath } from '../../hooks/useHomePath.js';
53+
import { useMetadata } from '../../providers/MetadataProvider.js';
54+
import { useNavigationContext } from '../../context/NavigationContext.js';
55+
import { matchAppBySegment } from '../../utils/appRoute.js';
56+
import { PageHeader } from '../../layout/PageHeader.js';
57+
58+
const EMPTY_INITIAL_MESSAGES: HydratedUIMessage[] = [];
59+
60+
/** What the page knows about the conversation its address names. */
61+
type RequestedVerdict = { id: string; verdict: 'checking' | 'ours' | 'foreign' };
62+
63+
export function AppAskPage() {
64+
const { t, language } = useObjectTranslation();
65+
const navigate = useNavigate();
66+
const homePath = useHomePath();
67+
const [searchParams, setSearchParams] = useSearchParams();
68+
const { user } = useAuth();
69+
const userId = user?.id;
70+
71+
// ── The app, its `ai:chat` entry and the entry's copy ───────────────────
72+
const metadata = useMetadata();
73+
const { currentAppName } = useNavigationContext();
74+
const routeParams = useParams();
75+
const app = matchAppBySegment(
76+
(metadata.apps ?? []) as Array<Record<string, unknown>>,
77+
currentAppName || routeParams.appName,
78+
);
79+
const packageId = typeof app?._packageId === 'string' ? app._packageId : undefined;
80+
const entry = React.useMemo(() => findAiChatNavEntry(app), [app]);
81+
const copy = React.useMemo(() => readAiChatPageCopy(entry), [entry]);
82+
const pageLabel = entry ? resolveNavItemLabel(entry as unknown as NavigationItem, t, undefined, language) : '';
83+
const title = copy.title ?? t('console.ai.empty.ask.title', { defaultValue: 'Ask your data' });
84+
const subtitle = copy.subtitle ?? t('console.ai.empty.ask.description', {
85+
defaultValue:
86+
'Ask questions about your records — counts, lists, and summaries across the data you can access.',
87+
});
88+
const placeholder = copy.placeholder ?? t('console.ai.askAnything', { defaultValue: 'Ask anything…' });
89+
90+
// ── The agent: always the platform `ask` ────────────────────────────────
91+
const apiBase = React.useMemo(() => resolveApiBase(), []);
92+
const surface = useAiSurfaceEnabled();
93+
const { agents, isLoading: agentsLoading, error: agentsError, refetch: refetchAgents } = useAgents({ apiBase });
94+
const catalogNames = React.useMemo(() => agents.map((a) => a.name), [agents]);
95+
const askAgent = agents.length > 0 ? resolveAgentParam('ask', catalogNames) : undefined;
96+
const chatApi = askAgent ? `${apiBase}/agents/${encodeURIComponent(askAgent)}/chat` : undefined;
97+
const unavailable = !surface.isLoading && !surface.enabled && !agentsLoading;
98+
99+
// ── The conversation the address names (`?c=`) ──────────────────────────
100+
const requestedId = searchParams.get(ASK_CONVERSATION_PARAM)?.trim() || undefined;
101+
// Ids this page created: they are this app's by construction, so the
102+
// address the page writes for them is never re-checked.
103+
const ownIdsRef = React.useRef<Set<string>>(new Set());
104+
const [requested, setRequested] = React.useState<RequestedVerdict | undefined>(undefined);
105+
if (requestedId && requested?.id !== requestedId) {
106+
setRequested({ id: requestedId, verdict: ownIdsRef.current.has(requestedId) ? 'ours' : 'checking' });
107+
} else if (!requestedId && requested) {
108+
setRequested(undefined);
109+
}
110+
const checking = requested?.verdict === 'checking' ? requested.id : undefined;
111+
React.useEffect(() => {
112+
if (!checking) return;
113+
let cancelled = false;
114+
void (async () => {
115+
let ours = false;
116+
if (packageId) {
117+
try {
118+
ours = conversationBelongsToAskPage(await fetchConversation(apiBase, checking), packageId);
119+
} catch {
120+
ours = false;
121+
}
122+
}
123+
if (cancelled) return;
124+
setRequested((prev) => (prev?.id === checking ? { id: checking, verdict: ours ? 'ours' : 'foreign' } : prev));
125+
})();
126+
return () => {
127+
cancelled = true;
128+
};
129+
}, [checking, apiBase, packageId]);
130+
// A foreign `?c=` leaves the address: the page opens its home state.
131+
const foreign = requested?.verdict === 'foreign' ? requested.id : undefined;
132+
React.useEffect(() => {
133+
if (!foreign) return;
134+
setSearchParams(
135+
(prev) => {
136+
const next = new URLSearchParams(prev);
137+
if (next.get(ASK_CONVERSATION_PARAM) === foreign) next.delete(ASK_CONVERSATION_PARAM);
138+
return next;
139+
},
140+
{ replace: true },
141+
);
142+
}, [foreign, setSearchParams]);
143+
const activeId = requested?.verdict === 'ours' ? requested.id : undefined;
144+
145+
// ── The page's thread ───────────────────────────────────────────────────
146+
// `started`: the first question was asked on the home state, so the pane is
147+
// up while its conversation is created.
148+
const [started, setStarted] = React.useState(false);
149+
const scope = packageId ? askPageConversationScope(packageId) : undefined;
150+
const createMetadata = React.useMemo(
151+
() => (packageId ? askPageCreateMetadata(packageId) : undefined),
152+
[packageId],
153+
);
154+
const {
155+
conversationId,
156+
conversationScope,
157+
initialMessages,
158+
isLoading: conversationLoading,
159+
ensureConversation,
160+
createError,
161+
} = useChatConversation({
162+
userId: askAgent && scope ? userId : undefined,
163+
scope,
164+
apiBase,
165+
activeId,
166+
// The home state is a new question: never the last cached thread.
167+
forceNew: !activeId,
168+
createMetadata,
169+
});
170+
const scopeMatched = conversationScope === scope;
171+
const paneConversationId = scopeMatched ? conversationId : undefined;
172+
const paneInitialMessages = scopeMatched ? initialMessages : EMPTY_INITIAL_MESSAGES;
173+
174+
// The first send created the conversation: the address names it from now on.
175+
React.useEffect(() => {
176+
if (!started || !paneConversationId || requestedId === paneConversationId) return;
177+
ownIdsRef.current.add(paneConversationId);
178+
setSearchParams(
179+
(prev) => {
180+
const next = new URLSearchParams(prev);
181+
next.set(ASK_CONVERSATION_PARAM, paneConversationId);
182+
return next;
183+
},
184+
{ replace: true },
185+
);
186+
}, [started, paneConversationId, requestedId, setSearchParams]);
187+
188+
const pendingFirstMessageRef = React.useRef<PendingFirstMessage | null>(null);
189+
const [selectedModelId, setSelectedModelId] = React.useState<string | undefined>(undefined);
190+
const ask = React.useCallback((text: string) => {
191+
const content = text.trim();
192+
if (!content) return;
193+
pendingFirstMessageRef.current = { content };
194+
setStarted(true);
195+
}, []);
196+
const startOver = React.useCallback(() => {
197+
pendingFirstMessageRef.current = null;
198+
setStarted(false);
199+
setSelectedModelId(undefined);
200+
setSearchParams(
201+
(prev) => {
202+
const next = new URLSearchParams(prev);
203+
next.delete(ASK_CONVERSATION_PARAM);
204+
return next;
205+
},
206+
);
207+
}, [setSearchParams]);
208+
209+
// ── What the page draws ─────────────────────────────────────────────────
210+
const restoring = Boolean(checking) || (Boolean(activeId) && !started && conversationLoading);
211+
const inConversation = started || Boolean(activeId);
212+
let body: React.ReactNode;
213+
if (unavailable || (!surface.isLoading && surface.enabled && !agentsLoading && !askAgent)) {
214+
body = (
215+
<AiUnavailable
216+
hasError={Boolean(agentsError)}
217+
onRetry={refetchAgents}
218+
onHome={() => navigate(homePath)}
219+
t={t}
220+
/>
221+
);
222+
} else if (surface.isLoading || restoring) {
223+
body = <div className="flex-1" data-testid="app-ask-page-loading" aria-busy="true" />;
224+
} else if (inConversation) {
225+
body = (
226+
<div className="flex min-h-0 min-w-0 flex-1 flex-col" data-testid="app-ask-page-conversation">
227+
<ChatPane
228+
key={`${chatApi ?? 'local'}:${paneConversationId ?? 'pending'}`}
229+
agents={agents}
230+
agentsLoading={agentsLoading}
231+
agentsError={agentsError}
232+
activeAgent={askAgent}
233+
chatApi={chatApi}
234+
apiBase={apiBase}
235+
conversationId={paneConversationId}
236+
requestedConversationId={activeId}
237+
activeAppPackageId={packageId}
238+
initialMessages={paneInitialMessages}
239+
pendingFirstMessageRef={pendingFirstMessageRef}
240+
ensureConversation={ensureConversation}
241+
conversationCreateError={createError}
242+
selectedModelId={selectedModelId}
243+
onSelectedModelChange={setSelectedModelId}
244+
onSent={noop}
245+
onShare={noop}
246+
hideHeader
247+
/>
248+
</div>
249+
);
250+
} else {
251+
body = (
252+
<AskHome
253+
title={title}
254+
subtitle={subtitle}
255+
placeholder={placeholder}
256+
suggestions={copy.suggestions}
257+
scopeLabel={t('console.ai.askPage.scopeBadge', { defaultValue: 'Answers prefer this app' })}
258+
sendLabel={t('console.ai.submit', { defaultValue: 'Submit' })}
259+
onAsk={ask}
260+
/>
261+
);
262+
}
263+
264+
return (
265+
<div className="flex h-full min-h-0 flex-col" data-testid="app-ask-page">
266+
<PageHeader
267+
posture="list"
268+
title={pageLabel || title}
269+
icon={<Sparkles className="h-4 w-4" />}
270+
actions={
271+
inConversation && !unavailable ? (
272+
<Button variant="outline" size="sm" onClick={startOver} data-testid="app-ask-page-new">
273+
<Plus className="mr-1 h-4 w-4" />
274+
{t('console.ai.newConversation', { defaultValue: 'New conversation' })}
275+
</Button>
276+
) : undefined
277+
}
278+
/>
279+
{body}
280+
</div>
281+
);
282+
}
283+
284+
function noop() {}
285+
286+
interface AskHomeProps {
287+
title: string;
288+
subtitle: string;
289+
placeholder: string;
290+
suggestions: string[];
291+
scopeLabel: string;
292+
sendLabel: string;
293+
onAsk: (text: string) => void;
294+
}
295+
296+
/** The home state: the welcome, the large question box and the suggested questions. */
297+
function AskHome({ title, subtitle, placeholder, suggestions, scopeLabel, sendLabel, onAsk }: AskHomeProps) {
298+
const [text, setText] = React.useState('');
299+
const submit = () => {
300+
if (text.trim()) onAsk(text);
301+
};
302+
return (
303+
<div className="flex flex-1 flex-col items-center overflow-y-auto px-4 py-10 sm:py-16" data-testid="app-ask-home">
304+
<div className="flex w-full max-w-2xl flex-col items-center gap-6">
305+
<div className="flex flex-col items-center gap-2 text-center">
306+
<h1 className="text-2xl font-semibold tracking-tight sm:text-3xl" data-testid="app-ask-title">
307+
{title}
308+
</h1>
309+
<p className="max-w-xl text-sm text-muted-foreground sm:text-base" data-testid="app-ask-subtitle">
310+
{subtitle}
311+
</p>
312+
</div>
313+
<form
314+
className="w-full rounded-2xl border bg-background p-3 shadow-sm focus-within:ring-2 focus-within:ring-ring"
315+
onSubmit={(event) => {
316+
event.preventDefault();
317+
submit();
318+
}}
319+
>
320+
<Textarea
321+
value={text}
322+
onChange={(event) => setText(event.target.value)}
323+
onKeyDown={(event) => {
324+
if (event.key !== 'Enter' || event.shiftKey || event.nativeEvent.isComposing) return;
325+
event.preventDefault();
326+
submit();
327+
}}
328+
placeholder={placeholder}
329+
aria-label={placeholder}
330+
rows={3}
331+
className="min-h-24 resize-none border-0 bg-transparent p-1 text-base shadow-none focus-visible:ring-0"
332+
data-testid="app-ask-input"
333+
/>
334+
<div className="mt-2 flex items-center justify-between gap-2">
335+
<Badge variant="secondary" className="font-normal" data-testid="app-ask-scope">
336+
{scopeLabel}
337+
</Badge>
338+
<Button
339+
type="submit"
340+
size="icon"
341+
className="h-9 w-9 rounded-full"
342+
disabled={!text.trim()}
343+
aria-label={sendLabel}
344+
data-testid="app-ask-send"
345+
>
346+
<ArrowUp className="h-4 w-4" />
347+
</Button>
348+
</div>
349+
</form>
350+
{suggestions.length > 0 ? (
351+
<div className={cn('grid w-full gap-2', suggestions.length > 1 && 'sm:grid-cols-2')} data-testid="app-ask-suggestions">
352+
{suggestions.map((suggestion) => (
353+
<Button
354+
key={suggestion}
355+
type="button"
356+
variant="outline"
357+
className="h-auto justify-start whitespace-normal px-3 py-2 text-left text-sm font-normal"
358+
onClick={() => onAsk(suggestion)}
359+
>
360+
{suggestion}
361+
</Button>
362+
))}
363+
</div>
364+
) : null}
365+
</div>
366+
</div>
367+
);
368+
}
369+
370+
export default AppAskPage;

0 commit comments

Comments
 (0)