Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions .changeset/35081-ai-history-follows-app.md
Original file line number Diff line number Diff line change
@@ -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.
65 changes: 61 additions & 4 deletions ui/packages/app-shell/src/console/ai/ConversationsSidebar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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}. */
Expand All @@ -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(
Expand Down Expand Up @@ -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<string | undefined>(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,
});
Expand Down Expand Up @@ -291,6 +311,35 @@ export function ConversationsSidebar({
{t('console.ai.newChat')}
</Button>
</div>
{appPackageId !== undefined ? (
<div
role="group"
aria-label={t('console.ai.historyScope.label')}
className="grid grid-cols-2 gap-0.5 rounded-md bg-muted p-0.5"
data-testid="ai-conversations-scope"
>
{([
{ all: false, label: t('console.ai.historyScope.app') },
{ all: true, label: t('console.ai.historyScope.all') },
] as const).map((option) => (
<button
key={option.all ? 'all' : 'app'}
type="button"
aria-pressed={showAll === option.all}
onClick={() => setAllFor(option.all ? appPackageId : undefined)}
className={cn(
'rounded px-2 py-0.5 text-xs transition-colors',
showAll === option.all
? 'bg-background font-medium text-foreground shadow-sm'
: 'text-muted-foreground hover:text-foreground',
)}
data-testid={option.all ? 'ai-conversations-scope-all' : 'ai-conversations-scope-app'}
>
{option.label}
</button>
))}
</div>
) : null}
<div className="relative">
<Search className="pointer-events-none absolute left-2 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground" />
<Input
Expand All @@ -312,8 +361,10 @@ export function ConversationsSidebar({
) : scoped.length === 0 ? (
<Empty className="px-3 py-8">
<MessageSquare className="h-8 w-8 text-muted-foreground" />
<EmptyTitle>{t('console.ai.noChatsYet')}</EmptyTitle>
<EmptyDescription>{t('console.ai.noChatsDescription')}</EmptyDescription>
<EmptyTitle>{t(listApp ? 'console.ai.noChatsInApp' : 'console.ai.noChatsYet')}</EmptyTitle>
<EmptyDescription>
{t(listApp ? 'console.ai.noChatsInAppDescription' : 'console.ai.noChatsDescription')}
</EmptyDescription>
</Empty>
) : visible.length === 0 ? (
<div className="px-3 py-4 text-xs text-muted-foreground">{t('console.ai.noMatchingChats')}</div>
Expand All @@ -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?.();
}}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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'));
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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<typeof vi.fn>;

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');
});
});
23 changes: 18 additions & 5 deletions ui/packages/app-shell/src/hooks/useChatConversation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,14 @@ export interface UseChatConversationOptions {
* create, so its identity does not matter.
*/
createMetadata?: Readonly<Record<string, unknown>>;
/**
* 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 {
Expand Down Expand Up @@ -762,12 +770,16 @@ export async function fetchConversation(apiBase: string, id: string): Promise<Se
async function createConversation(
apiBase: string,
metadata?: Readonly<Record<string, unknown>>,
packageId?: string,
): Promise<ServerConversation> {
const body: Record<string, unknown> = {};
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;
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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<string | undefined>(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.
Expand All @@ -867,7 +880,7 @@ export function useChatConversation(
if (mountedRef.current) setCreateError(undefined);
entry.promise = (async (): Promise<string | undefined> => {
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
Expand Down
26 changes: 20 additions & 6 deletions ui/packages/app-shell/src/hooks/useConversationList.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, unknown>;
/**
* 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 {
Expand All @@ -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
Expand Down Expand Up @@ -83,6 +96,7 @@ interface ServerConversation {
preview?: unknown;
messages?: Array<{ role: string; content: unknown }>;
metadata?: unknown;
packageId?: unknown;
}

function readMetadata(value: unknown): Record<string, unknown> | undefined {
Expand Down Expand Up @@ -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 } : {}),
};
}

Expand Down Expand Up @@ -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<ConversationListItem[]>([]);
Expand Down Expand Up @@ -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[]
Expand Down Expand Up @@ -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 };
}
Expand Down
10 changes: 10 additions & 0 deletions ui/packages/app-shell/src/layout/ChatDock.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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`.
Expand Down Expand Up @@ -320,6 +326,7 @@ export function ChatDockPanel({
title,
target,
onTargetChange,
onOpenInApp,
onShownConversationChange,
children,
}: ChatDockPanelProps) {
Expand Down Expand Up @@ -407,6 +414,7 @@ export function ChatDockPanel({
surfaceArtifactLabel={surfaceArtifactLabel}
target={target}
onTargetChange={onTargetChange}
onOpenInApp={onOpenInApp}
presentation={full ? 'full' : 'rail'}
historyOpen={historyOpen}
onHistoryOpenChange={setHistoryOpen}
Expand Down Expand Up @@ -466,6 +474,7 @@ export function ChatDockMobileSheet({
title,
target,
onTargetChange,
onOpenInApp,
onShownConversationChange,
children,
}: ChatDockMobileSheetProps) {
Expand Down Expand Up @@ -525,6 +534,7 @@ export function ChatDockMobileSheet({
surfaceArtifactLabel={surfaceArtifactLabel}
target={target}
onTargetChange={onTargetChange}
onOpenInApp={onOpenInApp}
presentation="sheet"
historyOpen={historyOpen}
onHistoryOpenChange={setHistoryOpen}
Expand Down
Loading
Loading