diff --git a/.changeset/35081-ai-history-follows-app.md b/.changeset/35081-ai-history-follows-app.md new file mode 100644 index 00000000000..ace44931fe6 --- /dev/null +++ b/.changeset/35081-ai-history-follows-app.md @@ -0,0 +1,17 @@ +--- +'@object-ui/app-shell': patch +'@object-ui/i18n': patch +--- + +feat(app-shell): the AI drawer's conversation history lists the app's own conversations, with an All switch + +Clause-②: no +Metadata-protocol: none + +Inside an app, the history in the console's AI drawer now lists the conversations started in that app, read from the list route's `packageId` filter. A two-way switch above the search box ("This app" / "All") shows every conversation instead, and moving to another app starts on that app's own list again. At Home and in the built-in apps (Setup) there is no current app: the list shows every conversation and draws no switch. + +A row started in another app moves the console to that app first, and the conversation opens there; a row with no app, or started in the app in view, opens in place as before. A new conversation sends the app it starts in as `packageId` on `POST /api/v1/ai/conversations`, so the server can record it; at Home and in a built-in app it sends none. + +The app's AI inquiry page (`ai:chat`) keeps its own history filter and draws no switch. The full-page `/ai` history and the empty conversation's recent list are unchanged. + +`@object-ui/i18n` adds `console.ai.historyScope.label`, `console.ai.historyScope.app`, `console.ai.historyScope.all`, `console.ai.noChatsInApp` and `console.ai.noChatsInAppDescription` in every locale pack. diff --git a/ui/packages/app-shell/src/console/ai/ConversationsSidebar.tsx b/ui/packages/app-shell/src/console/ai/ConversationsSidebar.tsx index ee69cacc90c..a24d301b17d 100644 --- a/ui/packages/app-shell/src/console/ai/ConversationsSidebar.tsx +++ b/ui/packages/app-shell/src/console/ai/ConversationsSidebar.tsx @@ -11,6 +11,10 @@ * objectstack#38454 — a host may also narrow the list to the rows it owns * ({@link ConversationsSidebarProps.rowFilter}): the app's `ai:chat` page lists * only the conversations it started for its app. + * + * objectstack#35081 — the drawer lists the conversations started in the app in + * view by default ({@link ConversationsSidebarProps.appPackageId}), with an + * 「All」 switch beside it; with no app in view the list holds them all. */ import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from 'react'; @@ -48,7 +52,7 @@ export interface ConversationsSidebarProps { * 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; + onSelectConversation?: (conversation: { id: string; agentId?: string; packageId?: 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}. */ @@ -64,6 +68,14 @@ export interface ConversationsSidebarProps { * row, scoped by agent alone. */ rowFilter?: (conversation: ConversationListItem) => boolean; + /** + * objectstack#35081 — the package of the app in view. Set, the list shows the + * conversations started in that app (the list route's `packageId` filter) and + * offers an 「All」 switch to every conversation; it returns to the app's own + * list whenever the app changes. Absent (no app in view), the list shows + * every conversation and draws no switch. + */ + appPackageId?: string; } function formatTimestamp( @@ -168,16 +180,24 @@ export function ConversationsSidebar({ onNewConversation, activeConversationId, rowFilter, + appPackageId, }: ConversationsSidebarProps) { const { t } = useObjectTranslation(); const navigate = useNavigate(); const { conversationId: routeActiveId } = useParams<{ conversationId?: string }>(); const hosted = onSelectConversation !== undefined; const activeId = hosted ? activeConversationId : routeActiveId; + // objectstack#35081 — 「All」 is chosen per app: another app starts on its + // own list. Derived state set during render, keyed by the app. + const [allFor, setAllFor] = useState(undefined); + if (allFor !== undefined && allFor !== appPackageId) setAllFor(undefined); + const showAll = appPackageId === undefined || allFor === appPackageId; + const listApp = showAll ? undefined : appPackageId; const { conversations, isLoading, error, remove, rename } = useConversationList({ userId, apiBase, refreshKey, + packageId: listApp, // Only the rows this host lists read their missing previews. selectBackfillRows: rowFilter ? (rows) => rows.filter(rowFilter) : undefined, }); @@ -291,6 +311,35 @@ export function ConversationsSidebar({ {t('console.ai.newChat')} + {appPackageId !== undefined ? ( +
+ {([ + { all: false, label: t('console.ai.historyScope.app') }, + { all: true, label: t('console.ai.historyScope.all') }, + ] as const).map((option) => ( + + ))} +
+ ) : null}
- {t('console.ai.noChatsYet')} - {t('console.ai.noChatsDescription')} + {t(listApp ? 'console.ai.noChatsInApp' : 'console.ai.noChatsYet')} + + {t(listApp ? 'console.ai.noChatsInAppDescription' : 'console.ai.noChatsDescription')} + ) : visible.length === 0 ? (
{t('console.ai.noMatchingChats')}
@@ -333,7 +384,13 @@ export function ConversationsSidebar({ active={c.id === activeId} renaming={c.id === renamingId} onSelect={() => { - if (onSelectConversation) onSelectConversation({ id: c.id, agentId: c.agentId }); + if (onSelectConversation) { + onSelectConversation({ + id: c.id, + agentId: c.agentId, + ...(c.packageId ? { packageId: c.packageId } : {}), + }); + } else navigate(conversationHref(c)); onNavigate?.(); }} diff --git a/ui/packages/app-shell/src/console/ai/__tests__/AppAskPage-37788.test.tsx b/ui/packages/app-shell/src/console/ai/__tests__/AppAskPage-37788.test.tsx index b10bed31a55..56c7a17111d 100644 --- a/ui/packages/app-shell/src/console/ai/__tests__/AppAskPage-37788.test.tsx +++ b/ui/packages/app-shell/src/console/ai/__tests__/AppAskPage-37788.test.tsx @@ -174,7 +174,11 @@ describe('AppAskPage (objectstack#37788)', () => { expect(pane).toHaveAttribute('data-hide-header', 'true'); expect(pane).toHaveAttribute('data-held', 'How do I apply?'); await waitFor(() => expect(creates()).toHaveLength(1)); - expect(JSON.parse(String((creates()[0][1] as RequestInit).body))).toEqual({ metadata: { activePackageId: PKG } }); + // objectstack#35081 — and the app it was started in, the drawer history's per-app filter. + expect(JSON.parse(String((creates()[0][1] as RequestInit).body))).toEqual({ + metadata: { activePackageId: PKG }, + packageId: PKG, + }); // The address names the conversation once it exists. await waitFor(() => expect(screen.getByTestId('location')).toHaveTextContent('?c=conv-1')); }); diff --git a/ui/packages/app-shell/src/hooks/__tests__/useConversationList.test.tsx b/ui/packages/app-shell/src/hooks/__tests__/useConversationList.test.tsx index 7c21364175d..76792b4b56c 100644 --- a/ui/packages/app-shell/src/hooks/__tests__/useConversationList.test.tsx +++ b/ui/packages/app-shell/src/hooks/__tests__/useConversationList.test.tsx @@ -106,3 +106,54 @@ describe('useConversationList selectBackfillRows (objectstack#37959)', () => { expect(result.current.conversations.find((r) => r.id === 'c')?.preview).toBeUndefined(); }); }); + +// objectstack#35081 — the list route records the app a conversation was +// started in (`packageId` on the row) and lists one app's conversations when +// asked (`?packageId=`); the hook carries both. +describe('useConversationList — the app a conversation was started in (objectstack#35081)', () => { + let fetchMock: ReturnType; + + beforeEach(() => { + fetchMock = vi.fn(async () => + jsonResponse({ + conversations: [ + { id: 'in-crm', title: 'Open deals', packageId: 'app.crm', updatedAt: '2025-01-02T00:00:00.000Z' }, + { id: 'no-app', title: 'At home', updatedAt: '2025-01-01T00:00:00.000Z' }, + { id: 'blank-app', title: 'Blank', packageId: '', updatedAt: '2024-12-31T00:00:00.000Z' }, + ], + }), + ); + vi.stubGlobal('fetch', fetchMock); + }); + + afterEach(() => { + vi.unstubAllGlobals(); + }); + + it("each row carries the app the list route recorded, and a row with none carries no app", async () => { + const { result } = renderHook(() => useConversationList({ userId: 'u1', apiBase: API_BASE })); + await waitFor(() => expect(result.current.conversations).toHaveLength(3)); + const byId = Object.fromEntries(result.current.conversations.map((row) => [row.id, row])); + expect(byId['in-crm'].packageId).toBe('app.crm'); + expect(byId['no-app']).not.toHaveProperty('packageId'); + expect(byId['blank-app']).not.toHaveProperty('packageId'); + }); + + it('asks the list route for one app with `packageId`, and for every conversation without it', async () => { + const { rerender } = renderHook( + ({ packageId }: { packageId?: string }) => useConversationList({ userId: 'u1', apiBase: API_BASE, packageId }), + { initialProps: { packageId: 'app.crm' } as { packageId?: string } }, + ); + await waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(1)); + const first = new URL(String(fetchMock.mock.calls[0][0])); + expect(first.pathname).toBe('/api/v1/ai/conversations'); + expect(first.searchParams.get('packageId')).toBe('app.crm'); + expect(first.searchParams.get('limit')).toBe('50'); + + rerender({ packageId: undefined }); + await waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(2)); + const second = new URL(String(fetchMock.mock.calls[1][0])); + expect(second.searchParams.has('packageId')).toBe(false); + expect(second.searchParams.get('limit')).toBe('50'); + }); +}); diff --git a/ui/packages/app-shell/src/hooks/useChatConversation.ts b/ui/packages/app-shell/src/hooks/useChatConversation.ts index 52ae48681f0..dde104b29e8 100644 --- a/ui/packages/app-shell/src/hooks/useChatConversation.ts +++ b/ui/packages/app-shell/src/hooks/useChatConversation.ts @@ -136,6 +136,14 @@ export interface UseChatConversationOptions { * create, so its identity does not matter. */ createMetadata?: Readonly>; + /** + * objectstack#35081 — the package id of the app the conversation is started + * in, sent as the create's `packageId` (service-ai records it when the + * caller can see an app that package ships, and the history list filters + * by it). Absent = the create names no app. Read at the moment of the + * create, as {@link createMetadata} is. + */ + createPackageId?: string; } export interface UseChatConversationReturn { @@ -762,12 +770,16 @@ export async function fetchConversation(apiBase: string, id: string): Promise>, + packageId?: string, ): Promise { + const body: Record = {}; + if (metadata) body.metadata = metadata; + if (packageId) body.packageId = packageId; const res = await authFetch(`${apiBase}/conversations`, { method: 'POST', credentials: 'include', headers: { 'Content-Type': 'application/json' }, - body: metadata ? JSON.stringify({ metadata }) : '{}', + body: JSON.stringify(body), }); if (!res.ok) throw notSentCreateError(`POST conversation failed: ${res.status}`, res.status); return (await res.json()) as ServerConversation; @@ -801,6 +813,7 @@ export function useChatConversation( legacyScope, adoptLegacy, createMetadata, + createPackageId, } = options; // The host's read of `activeId`, spent by the first resolve that uses it. const activeRecordRef = useRef(activeRecord); @@ -836,14 +849,14 @@ export function useChatConversation( // event handler, after commit) acts for the surface the user is looking at. // Synced in a LAYOUT effect: those run before every passive effect of the // commit, the host's replay effect included. - const latestRef = useRef({ userId, scope, apiBase, createMetadata }); + const latestRef = useRef({ userId, scope, apiBase, createMetadata, createPackageId }); // Mirror of `conversationId`, written eagerly beside every create/settle so // a call landing before the re-render still sees the held id. const conversationIdRef = useRef(conversationId); useLayoutEffect(() => { - latestRef.current = { userId, scope, apiBase, createMetadata }; + latestRef.current = { userId, scope, apiBase, createMetadata, createPackageId }; conversationIdRef.current = conversationId; - }, [userId, scope, apiBase, createMetadata, conversationId]); + }, [userId, scope, apiBase, createMetadata, createPackageId, conversationId]); // The cache key the hook has SETTLED on with no conversation: nothing to // resume, so the first send mints the row. `undefined` while a resolve runs // or once a conversation is held. @@ -867,7 +880,7 @@ export function useChatConversation( if (mountedRef.current) setCreateError(undefined); entry.promise = (async (): Promise => { try { - const fresh = await createConversation(base, latestRef.current.createMetadata); + const fresh = await createConversation(base, latestRef.current.createMetadata, latestRef.current.createPackageId); // The row exists and is the (user, scope)'s, whatever happens next. writeCache(key, fresh.id); // Adopt only while the hook is still waiting on THIS key. A resolve diff --git a/ui/packages/app-shell/src/hooks/useConversationList.ts b/ui/packages/app-shell/src/hooks/useConversationList.ts index 98fd2f4a76c..d88b9078d09 100644 --- a/ui/packages/app-shell/src/hooks/useConversationList.ts +++ b/ui/packages/app-shell/src/hooks/useConversationList.ts @@ -43,6 +43,13 @@ export interface ConversationListItem { * carries it; absent when the row carries none or a value that is not a record. */ metadata?: Record; + /** + * objectstack#35081 — the package id of the app the conversation was started + * in, as the list route records it (service-ai's `packageId`, written at the + * create from the app the console was in). Absent = no app: a conversation + * started outside any app, or created before the server recorded one. + */ + packageId?: string; } export interface UseConversationListOptions { @@ -51,6 +58,12 @@ export interface UseConversationListOptions { limit?: number; /** Bump to force a refetch (e.g. after creating/deleting a conversation). */ refreshKey?: number | string; + /** + * objectstack#35081 — list only the conversations started in this app (the + * list route's `packageId` filter). Absent = every conversation, rows with + * no app included. + */ + packageId?: string; /** * The rows the caller actually shows, picked from the sorted list page. Only * those rows have their missing title and preview read from each one's @@ -83,6 +96,7 @@ interface ServerConversation { preview?: unknown; messages?: Array<{ role: string; content: unknown }>; metadata?: unknown; + packageId?: unknown; } function readMetadata(value: unknown): Record | undefined { @@ -165,6 +179,7 @@ function normalize(row: ServerConversation): ConversationListItem { updatedAt: row.updatedAt, preview, metadata: readMetadata(row.metadata), + ...(typeof row.packageId === 'string' && row.packageId ? { packageId: row.packageId } : {}), }; } @@ -200,7 +215,7 @@ export async function readConversationRow(apiBase: string, id: string): Promise< export function useConversationList( options: UseConversationListOptions, ): UseConversationListReturn { - const { userId, apiBase, limit = 50, refreshKey, selectBackfillRows } = options; + const { userId, apiBase, limit = 50, refreshKey, packageId, selectBackfillRows } = options; const selectBackfillRowsRef = useRef(selectBackfillRows); selectBackfillRowsRef.current = selectBackfillRows; const [conversations, setConversations] = useState([]); @@ -263,10 +278,9 @@ export function useConversationList( setError(undefined); (async () => { try { - const res = await authFetch( - `${apiBase}/conversations?limit=${encodeURIComponent(String(limit))}`, - { credentials: 'include' }, - ); + const query = new URLSearchParams({ limit: String(limit) }); + if (packageId) query.set('packageId', packageId); + const res = await authFetch(`${apiBase}/conversations?${query.toString()}`, { credentials: 'include' }); if (!res.ok) throw new Error(`GET conversations failed: ${res.status}`); const body = (await res.json()) as | ServerConversation[] @@ -318,7 +332,7 @@ export function useConversationList( return () => { cancelled = true; }; - }, [userId, apiBase, limit, internalKey, refreshKey]); + }, [userId, apiBase, limit, packageId, internalKey, refreshKey]); return { conversations, isLoading, error, refetch, remove, rename }; } diff --git a/ui/packages/app-shell/src/layout/ChatDock.tsx b/ui/packages/app-shell/src/layout/ChatDock.tsx index 8a962cefb45..24df901631f 100644 --- a/ui/packages/app-shell/src/layout/ChatDock.tsx +++ b/ui/packages/app-shell/src/layout/ChatDock.tsx @@ -260,6 +260,12 @@ export interface ChatDockThreadProps { target?: ChatDockTarget; /** Replaces the target in place: a history row or a minted fresh thread. */ onTargetChange?: (target: ChatDockTarget | undefined) => void; + /** + * objectstack#35081 — a history row started in another app: move the console + * to that app, then show the target there (see {@link ChatDockConversation}). + * Unused with `children`. + */ + onOpenInApp?: (packageId: string, target: ChatDockTarget) => void; /** * ui ADR-0057 Amendment A5 — told the conversation the default body shows, * so the host can record it at a close. Unused with `children`. @@ -320,6 +326,7 @@ export function ChatDockPanel({ title, target, onTargetChange, + onOpenInApp, onShownConversationChange, children, }: ChatDockPanelProps) { @@ -407,6 +414,7 @@ export function ChatDockPanel({ surfaceArtifactLabel={surfaceArtifactLabel} target={target} onTargetChange={onTargetChange} + onOpenInApp={onOpenInApp} presentation={full ? 'full' : 'rail'} historyOpen={historyOpen} onHistoryOpenChange={setHistoryOpen} @@ -466,6 +474,7 @@ export function ChatDockMobileSheet({ title, target, onTargetChange, + onOpenInApp, onShownConversationChange, children, }: ChatDockMobileSheetProps) { @@ -525,6 +534,7 @@ export function ChatDockMobileSheet({ surfaceArtifactLabel={surfaceArtifactLabel} target={target} onTargetChange={onTargetChange} + onOpenInApp={onOpenInApp} presentation="sheet" historyOpen={historyOpen} onHistoryOpenChange={setHistoryOpen} diff --git a/ui/packages/app-shell/src/layout/ChatDockConversation.tsx b/ui/packages/app-shell/src/layout/ChatDockConversation.tsx index dbcb56fd70f..2bde8666b2d 100644 --- a/ui/packages/app-shell/src/layout/ChatDockConversation.tsx +++ b/ui/packages/app-shell/src/layout/ChatDockConversation.tsx @@ -29,6 +29,7 @@ import { isAiStudioEnabled } from '../runtime-config.js'; import type { ChatSurfaceContext } from './chatSurfaceContext.js'; import { surfaceRecord, useConversationFocus } from './chatFocus.js'; import { + ambientAppPackage, sameDockTarget, type ChatDockConversationActions, type ChatDockPresentation, @@ -68,6 +69,12 @@ export interface ChatDockConversationProps { target?: ChatDockTarget; /** Replaces the target in place: a picked history row or a minted fresh thread. */ onTargetChange?: (target: ChatDockTarget | undefined) => void; + /** + * objectstack#35081 — opens a history row started in another app: the host + * moves the console to the app `packageId` names, then shows `target` there. + * Absent → every row opens in place through {@link onTargetChange}. + */ + onOpenInApp?: (packageId: string, target: ChatDockTarget) => void; /** Rail (history behind a button), full window (history beside the chat), or phone sheet. */ presentation?: ChatDockPresentation; /** Rail and sheet only: the history list shown over the chat. */ @@ -159,6 +166,7 @@ export function ChatDockConversation({ surfaceArtifactLabel, target, onTargetChange, + onOpenInApp, presentation = 'rail', historyOpen = false, onHistoryOpenChange, @@ -224,6 +232,10 @@ export function ChatDockConversation({ ? `${apiBase}/agents/${encodeURIComponent(activeAgent)}/chat` : undefined; const product = chatProductOfAgent(activeAgent); + // objectstack#35081 — the app in view (an authorable one; none at Home or in + // a built-in app): a new conversation is recorded as started in it, and the + // history lists its conversations by default. + const ambientApp = ambientAppPackage(appPackageId); const scope = activeAgent ? (hostScope?.key ?? chatConversationScope({ product })) : undefined; const requestedConversationId = legacyConversationId ? undefined : target?.conversationId; const forceNew = Boolean(target?.fresh) && !requestedConversationId; @@ -245,6 +257,7 @@ export function ChatDockConversation({ activeRecord, forceNew, createMetadata: hostScope?.createMetadata, + createPackageId: ambientApp, }); // #2450 — hand the pane only a scope-matched conversation. Switching agents // changes the scope while the dock stays mounted; until the hook @@ -350,16 +363,23 @@ export function ChatDockConversation({ onTargetChange?.({ agent: activeAgentRoute, fresh: true }); onHistoryOpenChange?.(false); }, [onTargetChange, activeAgentRoute, onHistoryOpenChange]); + // objectstack#35081 — a row started in another app moves the console to + // that app first (the host's `onOpenInApp`), and the thread opens there; a + // row with no app, or started in the app in view, opens in place. const openConversation = React.useCallback( - (conversation: { id: string; agentId?: string }) => { + (conversation: { id: string; agentId?: string; packageId?: string }) => { const next: ChatDockTarget = { agent: conversation.agentId ? agentRouteName(conversation.agentId) : activeAgentRoute, conversationId: conversation.id, }; - if (!sameDockTarget(next, target)) onTargetChange?.(next); + if (conversation.packageId && conversation.packageId !== appPackageId && onOpenInApp) { + onOpenInApp(conversation.packageId, next); + } else if (!sameDockTarget(next, target)) { + onTargetChange?.(next); + } onHistoryOpenChange?.(false); }, - [activeAgentRoute, target, onTargetChange, onHistoryOpenChange], + [activeAgentRoute, appPackageId, target, onTargetChange, onOpenInApp, onHistoryOpenChange], ); // History freshness: a sent turn moves its row up, and the server titles a @@ -441,6 +461,10 @@ export function ChatDockConversation({ onSelectConversation={openConversation} onNewConversation={startNewConversation} rowFilter={historyRowFilter} + // objectstack#35081 — the app in view's own conversations first, with an + // 「All」 switch. A host that lists its own rows (the ai:chat page's + // filter) keeps exactly those, with no switch. + appPackageId={historyRowFilter ? undefined : ambientApp} className={presentation === 'full' ? 'w-72 shrink-0 border-r' : 'border-r-0'} /> ); diff --git a/ui/packages/app-shell/src/layout/__tests__/ChatDock.historyByApp-35081.test.tsx b/ui/packages/app-shell/src/layout/__tests__/ChatDock.historyByApp-35081.test.tsx new file mode 100644 index 00000000000..e89da2dd13c --- /dev/null +++ b/ui/packages/app-shell/src/layout/__tests__/ChatDock.historyByApp-35081.test.tsx @@ -0,0 +1,308 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#35081 — the drawer's conversation history follows the app + * (objectstack#35014 item 4, with service-ai recording each conversation's app): + * + * - in an app, the history lists the conversations started in that app (the + * list route's `packageId` filter), with an 「All」 switch to every one; + * - with no app in view (Home, a built-in app) it lists every conversation and + * draws no switch; + * - a row started in another app moves the console to that app first, and the + * conversation opens there; a row of the app in view opens in place; + * - a new conversation sends the app it starts in at create. + * + * ## Real subjects + * + * The console host (`useConsoleChatDock`) with its REAL default body, the REAL + * `ConversationsSidebar` and `useConversationList`, the REAL `ChatPane` and + * `useChatConversation`, under a router whose address decides the app in view. + * The stand-ins are those of `ChatDock.appBinding-10926.test.tsx` (the agent + * catalog, the metadata apps list, the chat transport, `ChatbotEnhanced`), and + * the conversation API is a `fetch` stub that filters its list by `packageId` + * as service-ai does. Its own file because that harness replaces the history + * list with a stub for every one of its pins. + */ + +// AiChatPage reads a dropped spreadsheet through `import('@object-ui/plugin-grid')`; load it +// here so collection pays that transform, not a clocked case (check-test-source-alias). +import '@object-ui/plugin-grid'; +import '@testing-library/jest-dom/vitest'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'; +import { MemoryRouter, useLocation } from 'react-router-dom'; +import React from 'react'; + +interface ChatOptions { + conversationId?: string; +} + +const state = { + agents: [] as Array<{ name: string; label: string }>, + chat: undefined as ChatOptions | undefined, +}; + +vi.mock('@object-ui/plugin-chatbot', async (importOriginal) => { + const actual = await importOriginal>(); + return { + ...actual, + useAiModels: () => ({ models: [], defaultModelId: undefined }), + useHitlInChat: () => ({ decide: vi.fn(), decisions: {} }), + useObjectChat: (options: ChatOptions) => { + state.chat = options; + return { + messages: [], + isLoading: false, + error: undefined, + sendMessage: vi.fn(), + stop: vi.fn(), + reload: vi.fn(), + clear: vi.fn(), + setMessages: vi.fn(), + }; + }, + ChatbotEnhanced: (props: { headerSlot?: React.ReactNode; onSendMessage?: (text: string) => void }) => ( +
+ {props.headerSlot} + +
+ ), + }; +}); +vi.mock('@object-ui/plugin-chatbot/core', async (importOriginal) => ({ + ...(await importOriginal()), + useAgents: () => ({ agents: state.agents, isLoading: false, error: undefined, refetch: vi.fn() }), +})); +vi.mock('@object-ui/auth', async (importOriginal) => ({ + ...(await importOriginal>()), + useAuth: () => ({ user: { id: 'u1' } }), +})); + +const APPS = [ + { name: 'crm_app', label: 'Customer Desk', _packageId: 'app.crm' }, + { name: 'notes_app', label: 'Meeting Notes', _packageId: 'app.notes' }, + { name: 'setup', label: 'Setup', _packageId: 'com.objectstack.setup' }, +]; +vi.mock('../../providers/MetadataProvider', async (importOriginal) => ({ + ...(await importOriginal>()), + useMetadata: () => ({ apps: APPS }), +})); +vi.mock('../../providers/AdapterProvider', async (importOriginal) => ({ + ...(await importOriginal>()), + useAdapter: () => null, +})); +vi.mock('../AiUsageIndicator', () => ({ AiUsageIndicator: () => null })); + +import { I18nProvider } from '@object-ui/i18n'; +// The dock body is a `lazy()` chunk carrying the whole chat UI. Loaded at module +// scope, so no test's wait spends its budget on the first cold import. +import '../ChatDockConversation'; +import { DOCK_EXPANDED_STORAGE_KEY } from '../chatDockState'; +import { DOCK_TARGET_STORAGE_KEY } from '../chatDockTarget'; +import { useConsoleChatDock } from '../useConsoleChatDock'; + +window.matchMedia = ((query: string) => ({ + matches: false, + media: query, + onchange: null, + addEventListener: () => {}, + removeEventListener: () => {}, + addListener: () => {}, + removeListener: () => {}, + dispatchEvent: () => false, +})) as unknown as typeof window.matchMedia; + +const API = '/api/v1/ai'; + +/** The caller's conversations, each with the app service-ai recorded for it (or none). */ +const ROWS = [ + { id: 'crm-1', title: 'Open deals', agentId: 'ask', packageId: 'app.crm', updatedAt: new Date().toISOString() }, + { id: 'notes-1', title: 'Action items', agentId: 'ask', packageId: 'app.notes', updatedAt: new Date(Date.now() - 1000).toISOString() }, + { id: 'home-1', title: 'General question', agentId: 'ask', updatedAt: new Date(Date.now() - 2000).toISOString() }, +]; + +let lists: URL[]; +let creates: Array>; + +function installFetch(): void { + vi.stubGlobal( + 'fetch', + vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => { + const url = new URL(String(input), 'http://console.test'); + const method = init?.method ?? 'GET'; + const json = (body: unknown, status = 200) => + new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json' } }); + if (url.pathname === `${API}/conversations` && method === 'POST') { + creates.push(JSON.parse(String(init?.body ?? '{}')) as Record); + return json({ id: `conv-minted-${creates.length}`, messages: [] }, 201); + } + if (url.pathname === `${API}/conversations` && method === 'GET') { + lists.push(url); + // service-ai's list: `packageId` names one app's conversations; absent, every one. + const app = url.searchParams.get('packageId'); + return json({ conversations: ROWS.filter((row) => !app || row.packageId === app), hasMore: false }); + } + const one = url.pathname.match(/\/conversations\/([^/]+)$/); + if (one && method === 'GET') { + const row = ROWS.find((r) => r.id === decodeURIComponent(one[1])); + return row ? json({ ...row, messages: [] }) : json({}, 404); + } + return json({ success: true, data: [] }); + }), + ); +} + +/** The console's host, in the app the address names (`/apps/SEGMENT`); none at `/home`. */ +function DockHost() { + const location = useLocation(); + const segment = location.pathname.match(/^\/apps\/([^/]+)/)?.[1]; + const app = segment + ? APPS.find((a) => a._packageId === decodeURIComponent(segment) || a.name === segment) + : undefined; + const dock = useConsoleChatDock({ enabled: true, userId: 'u1', appPackageId: app?._packageId }); + return ( + <> + {location.pathname} + {dock.rail} + + ); +} + +function renderConsole(path: string): void { + render( + + + + + , + ); +} + +async function openHistory(): Promise { + fireEvent.click(await screen.findByTestId('chat-dock-history-toggle')); + await screen.findByTestId('ai-conversations-sidebar'); +} + +function listedIds(): string[] { + return screen + .queryAllByTestId(/^ai-conversation-row-/) + .map((row) => row.getAttribute('data-testid')!.replace('ai-conversation-row-', '')); +} + +const lastList = () => lists[lists.length - 1]; + +beforeEach(() => { + state.agents = [{ name: 'ask', label: 'Ask' }]; + state.chat = undefined; + lists = []; + creates = []; + window.localStorage.clear(); + window.sessionStorage.clear(); + window.sessionStorage.setItem(DOCK_EXPANDED_STORAGE_KEY, '1'); + installFetch(); +}); + +afterEach(() => { + cleanup(); + vi.unstubAllGlobals(); +}); + +describe("the drawer history lists the app's conversations, with an All switch (objectstack#35081)", () => { + it("in an app, the history lists that app's conversations by default", async () => { + renderConsole('/apps/app.crm'); + await openHistory(); + await waitFor(() => expect(listedIds()).toEqual(['crm-1'])); + expect(lastList().searchParams.get('packageId')).toBe('app.crm'); + expect(screen.getByTestId('ai-conversations-scope-app')).toHaveAttribute('aria-pressed', 'true'); + expect(screen.getByTestId('ai-conversations-scope-all')).toHaveAttribute('aria-pressed', 'false'); + }); + + it('All lists every conversation, and This app goes back to the app\'s own', async () => { + renderConsole('/apps/app.crm'); + await openHistory(); + await waitFor(() => expect(listedIds()).toEqual(['crm-1'])); + + fireEvent.click(screen.getByTestId('ai-conversations-scope-all')); + await waitFor(() => expect(listedIds()).toEqual(['crm-1', 'notes-1', 'home-1'])); + expect(lastList().searchParams.has('packageId')).toBe(false); + expect(screen.getByTestId('ai-conversations-scope-all')).toHaveAttribute('aria-pressed', 'true'); + + fireEvent.click(screen.getByTestId('ai-conversations-scope-app')); + await waitFor(() => expect(listedIds()).toEqual(['crm-1'])); + expect(lastList().searchParams.get('packageId')).toBe('app.crm'); + }); + + it('with no app in view (Home, the built-in Setup app) the list holds every conversation and draws no switch', async () => { + renderConsole('/home'); + await openHistory(); + await waitFor(() => expect(listedIds()).toEqual(['crm-1', 'notes-1', 'home-1'])); + expect(lastList().searchParams.has('packageId')).toBe(false); + expect(screen.queryByTestId('ai-conversations-scope')).toBeNull(); + cleanup(); + + renderConsole('/apps/setup'); + await openHistory(); + await waitFor(() => expect(listedIds()).toEqual(['crm-1', 'notes-1', 'home-1'])); + expect(lastList().searchParams.has('packageId')).toBe(false); + expect(screen.queryByTestId('ai-conversations-scope')).toBeNull(); + }); + + it('a row started in another app moves the console to that app first, and the conversation opens there', async () => { + renderConsole('/apps/app.crm'); + await openHistory(); + await waitFor(() => expect(listedIds()).toEqual(['crm-1'])); + fireEvent.click(screen.getByTestId('ai-conversations-scope-all')); + await waitFor(() => expect(listedIds()).toContain('notes-1')); + + fireEvent.click(screen.getByTestId('ai-conversation-select-notes-1')); + await waitFor(() => expect(screen.getByTestId('location')).toHaveTextContent('/apps/app.notes')); + await waitFor(() => expect(state.chat?.conversationId).toBe('notes-1'), { timeout: 4000 }); + // Placed in the app it moved to, so that app shows it. + expect(JSON.parse(window.sessionStorage.getItem(DOCK_TARGET_STORAGE_KEY) ?? 'null')).toMatchObject({ + conversationId: 'notes-1', + app: 'app.notes', + }); + expect(screen.queryByTestId('chat-dock-history')).toBeNull(); + }); + + it('from Home, a row started in an app moves the console into that app first', async () => { + renderConsole('/home'); + await openHistory(); + await waitFor(() => expect(listedIds()).toContain('crm-1')); + fireEvent.click(screen.getByTestId('ai-conversation-select-crm-1')); + await waitFor(() => expect(screen.getByTestId('location')).toHaveTextContent('/apps/app.crm')); + await waitFor(() => expect(state.chat?.conversationId).toBe('crm-1'), { timeout: 4000 }); + }); + + it("a row of the app in view, or with no app, opens in place", async () => { + renderConsole('/apps/app.crm'); + await openHistory(); + await waitFor(() => expect(listedIds()).toEqual(['crm-1'])); + fireEvent.click(screen.getByTestId('ai-conversation-select-crm-1')); + await waitFor(() => expect(state.chat?.conversationId).toBe('crm-1'), { timeout: 4000 }); + expect(screen.getByTestId('location')).toHaveTextContent('/apps/app.crm'); + + await openHistory(); + fireEvent.click(screen.getByTestId('ai-conversations-scope-all')); + await waitFor(() => expect(listedIds()).toContain('home-1')); + fireEvent.click(screen.getByTestId('ai-conversation-select-home-1')); + await waitFor(() => expect(state.chat?.conversationId).toBe('home-1'), { timeout: 4000 }); + expect(screen.getByTestId('location')).toHaveTextContent('/apps/app.crm'); + }); + + it('a new conversation sends the app it starts in at create, and none outside an authorable app', async () => { + renderConsole('/apps/app.crm'); + fireEvent.click(await screen.findByTestId('pane-send')); + await waitFor(() => expect(creates).toHaveLength(1)); + expect(creates[0]).toEqual({ packageId: 'app.crm' }); + cleanup(); + window.localStorage.clear(); + + renderConsole('/apps/setup'); + fireEvent.click(await screen.findByTestId('pane-send')); + await waitFor(() => expect(creates).toHaveLength(2)); + expect(creates[1]).toEqual({}); + }); +}); diff --git a/ui/packages/app-shell/src/layout/useConsoleChatDock.tsx b/ui/packages/app-shell/src/layout/useConsoleChatDock.tsx index 236dc6a3894..12528ada072 100644 --- a/ui/packages/app-shell/src/layout/useConsoleChatDock.tsx +++ b/ui/packages/app-shell/src/layout/useConsoleChatDock.tsx @@ -416,6 +416,22 @@ export function useConsoleChatDock({ writeSheetShownAt(location.key); }, [enabled, isMobile, expanded, storedExpanded, askPageActive, location.key, navigationType, closeBy]); + // objectstack#35081 — a history row started in another app: the console + // moves to that app first, and the thread opens there. The target is placed + // in the app it moves to, so that app shows it (`dockTargetFollowsApp`). The + // move is the drawer's own, asked for by picking the row, so the phone sheet + // stays open over the new page: the entry it was shown on is forgotten + // rather than read as a move away (objectstack#37556). + const openInApp = React.useCallback( + (packageId: string, next: ChatDockTarget) => { + setTarget({ ...next, app: ambientAppPackage(packageId) ?? null }); + movedAwayRef.current = false; + writeSheetShownAt(null); + navigate(`/apps/${encodeURIComponent(packageId)}`); + }, + [setTarget, navigate], + ); + // A designer surface can ask the assistant to open through the assistant bus // (e.g. an "Ask AI" button). const { openSeq } = useAssistant(); @@ -445,7 +461,7 @@ export function useConsoleChatDock({ [enabled, expanded, fullWindow, entryToggle, open, openEntry, askPageActive], ); - const thread = { target: shownTarget, onTargetChange: setTarget, handoff, onShownConversationChange }; + const thread = { target: shownTarget, onTargetChange: setTarget, onOpenInApp: openInApp, handoff, onShownConversationChange }; const rail = enabled && expanded && !isMobile ? (