From f095b9bded54e0472715a57b11c03c90f443ecc2 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 14:59:03 +0000 Subject: [PATCH 1/4] feat(app-shell): favourite conversations open the assistant drawer in place from the sidebar A favourite of type `conversation` stores the conversation id and agent; its sidebar row opens the drawer on it, follows its server label, and is drawn unavailable when the server answers it is gone or not this user's. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01L9qibxdwshRvTk3qXc7A6A --- .changeset/37863-favourite-conversations.md | 14 + .../src/context/FavoritesProvider.tsx | 12 +- .../src/hooks/useConversationList.ts | 16 + .../app-shell/src/layout/UnifiedSidebar.tsx | 43 ++- ...debar.conversationFavorites-37863.test.tsx | 364 ++++++++++++++++++ .../app-shell/src/layout/contentItemTile.tsx | 2 + .../src/layout/conversationFavorites.ts | 112 ++++++ ui/packages/i18n/src/locales/ar.ts | 1 + ui/packages/i18n/src/locales/de.ts | 1 + ui/packages/i18n/src/locales/en.ts | 1 + ui/packages/i18n/src/locales/es.ts | 1 + ui/packages/i18n/src/locales/fr.ts | 1 + ui/packages/i18n/src/locales/ja.ts | 1 + ui/packages/i18n/src/locales/ko.ts | 1 + ui/packages/i18n/src/locales/pt-BR.ts | 1 + ui/packages/i18n/src/locales/ru.ts | 1 + ui/packages/i18n/src/locales/zh-Hans.ts | 1 + ui/packages/i18n/src/locales/zh-Hant.ts | 1 + 18 files changed, 569 insertions(+), 5 deletions(-) create mode 100644 .changeset/37863-favourite-conversations.md create mode 100644 ui/packages/app-shell/src/layout/__tests__/UnifiedSidebar.conversationFavorites-37863.test.tsx create mode 100644 ui/packages/app-shell/src/layout/conversationFavorites.ts diff --git a/.changeset/37863-favourite-conversations.md b/.changeset/37863-favourite-conversations.md new file mode 100644 index 00000000000..8acd4a1aef1 --- /dev/null +++ b/.changeset/37863-favourite-conversations.md @@ -0,0 +1,14 @@ +--- +'@object-ui/app-shell': patch +'@object-ui/i18n': patch +--- + +feat(app-shell): favourite conversations open in the assistant drawer in place, from the sidebar's Favorites + +Clause-②: no +Metadata-protocol: none + +- **A conversation can be a favourite.** `FavoriteItem` gains the `conversation` type, id `conversation:ID`, with the conversation's id and agent (`conversationId`, `agent`); its `href` is the conversation's `/ai…` address. `conversationFavoriteItem` builds the entry. Conversation favourites count against the same cap of 20 as the other content favourites. +- **The sidebar row opens the drawer in place.** A favourite conversation is a row of the sidebar's Favorites section, with the chat-bubble icon. Clicking it opens the assistant drawer on that conversation, the way its history row does, and the page stays where it is. The address is followed only where no drawer can take it: a page without the drawer, the app's AI inquiry page, or a click that opens a new tab. +- **The label follows the conversation.** The sidebar reads each favourite conversation once and keeps the label its history row shows (the server's title, else the latest message the user wrote). +- **A deleted conversation is marked.** A conversation the server answers is gone, or is not this user's, is drawn struck through as unavailable (`sidebar.conversationUnavailable`, new in every pack), opens nothing, and is still removed from its ⋯ menu. A failed read of any other kind marks nothing. diff --git a/ui/packages/app-shell/src/context/FavoritesProvider.tsx b/ui/packages/app-shell/src/context/FavoritesProvider.tsx index fac49ba94fe..a6f241c0c75 100644 --- a/ui/packages/app-shell/src/context/FavoritesProvider.tsx +++ b/ui/packages/app-shell/src/context/FavoritesProvider.tsx @@ -55,11 +55,15 @@ export interface FavoriteItem { * favorites surfaced on Home (Starred Apps) and the sidebar Favorites * section. A `view` is one list view of an object (objectstack#27594), id * `view:OBJECT:VIEW`; the sidebar draws it only in the app its `href` names. + * - `conversation` — an AI conversation the user starred in the assistant + * drawer's header (objectstack#37863), id `conversation:ID`. The sidebar + * row opens it in the drawer in place; `href` is its `/ai…` address, the + * fallback where no drawer can take it. It counts against the content cap. * - `nav` — a sidebar navigation entry promoted to the "Pinned" position via * the in-tree pin toggle (see `useNavPins`). Excluded from Home/Starred and * from the generic sidebar Favorites list so it doesn't render twice. */ - type: 'object' | 'dashboard' | 'page' | 'report' | 'record' | 'view' | 'nav'; + type: 'object' | 'dashboard' | 'page' | 'report' | 'record' | 'view' | 'conversation' | 'nav'; /** ISO timestamp of when the item was favorited */ favoritedAt: string; /** @@ -80,6 +84,10 @@ export interface FavoriteItem { * tree node without leaking the synthesized favorite into other UIs. */ navId?: string; + /** For `type === 'conversation'` items: the conversation the drawer opens. */ + conversationId?: string; + /** For `type === 'conversation'` items: the agent the conversation is with, by route name. */ + agent?: string; } interface FavoritesContextValue { @@ -140,7 +148,7 @@ const STORAGE_BASE_KEY = 'objectui-favorites'; /** Legacy key used by the standalone `useNavPins` hook before it was merged * into Favorites. Migrated once at provider mount, then deleted. */ const LEGACY_NAV_PINS_KEY = 'objectui-nav-pins'; -/** Cap for user-visible content favorites (object/dashboard/page/report/record). */ +/** Cap for user-visible content favorites (every type but `nav`). */ const MAX_FAVORITES = 20; /** Independent cap for nav-pin favorites — they live in a separate bucket. */ const MAX_NAV_PINS = 20; diff --git a/ui/packages/app-shell/src/hooks/useConversationList.ts b/ui/packages/app-shell/src/hooks/useConversationList.ts index b0f9ee10fbf..6876ca838e5 100644 --- a/ui/packages/app-shell/src/hooks/useConversationList.ts +++ b/ui/packages/app-shell/src/hooks/useConversationList.ts @@ -169,6 +169,22 @@ async function fetchConversationDetail( return normalize(row as ServerConversation); } +/** + * One conversation's history row, read by id; `null` when the server answers + * that it is gone or not this user's (404, 403). Any other failure throws, so + * a network blip never reads as a deleted conversation. + */ +export async function readConversationRow(apiBase: string, id: string): Promise { + const res = await authFetch(`${apiBase}/conversations/${encodeURIComponent(id)}`, { + credentials: 'include', + }); + if (res.status === 404 || res.status === 403) return null; + if (!res.ok) throw Object.assign(new Error(`GET conversation failed: ${res.status}`), { status: res.status }); + const body = (await res.json()) as ServerConversation | { conversation?: ServerConversation }; + const row = 'conversation' in body && body.conversation ? body.conversation : body; + return normalize(row as ServerConversation); +} + export function useConversationList( options: UseConversationListOptions, ): UseConversationListReturn { diff --git a/ui/packages/app-shell/src/layout/UnifiedSidebar.tsx b/ui/packages/app-shell/src/layout/UnifiedSidebar.tsx index 96334f1fae8..c0e4421d19b 100644 --- a/ui/packages/app-shell/src/layout/UnifiedSidebar.tsx +++ b/ui/packages/app-shell/src/layout/UnifiedSidebar.tsx @@ -98,6 +98,9 @@ import { useWorkspacePreference } from '../utils/workspacePreference.js'; import { SidebarItemMenu, sidebarItemDesignPath, favoriteDesignPath } from './SidebarItemMenu.js'; import { SortableFavoriteRows, type FavoriteRowDragProps } from './SortableFavoriteRows.js'; import { favoriteAppSegment } from './listViewFavorites.js'; +import { useChatDockControl } from './chatDockControl.js'; +import { conversationFavoriteTarget, useUnavailableConversationFavorites } from './conversationFavorites.js'; +import { resolveAiApiBase } from '../hooks/aiApiBase.js'; import { useDesignModeActive } from './designMode.js'; import { electSidebarArea, type SidebarAreaRoute } from './sidebarAreaElection.js'; import type { FavoriteItem } from '../hooks/useFavorites.js'; @@ -336,7 +339,8 @@ export function UnifiedSidebar({ // A recent entry's text is the item's own, resolved on this render // (objectui#11678); the entry stores identity only. const recentLabel = useRecentItemLabel(); - const { favorites, removeFavorite, reorderFavorites } = useFavorites(); + const { favorites, removeFavorite, reorderFavorites, refreshLabel: refreshFavoriteLabel } = useFavorites(); + const chatDock = useChatDockControl(); const metadata = useMetadata(); const { apps: metadataApps } = metadata; @@ -690,15 +694,48 @@ export function UnifiedSidebar({ .filter(f => f.type !== 'nav') .filter(f => f.type !== 'view' || matchAppBySegment(apps.filter((a: any) => a.active !== false), favoriteAppSegment(f.href)) === activeApp) .slice(0, 8); + // objectstack#37863 — a favourite conversation's row opens the drawer in + // place on it (the target its history row opens), and its address only where + // no drawer takes it: no host, the app's AI inquiry page (A4), or a click + // that asks for a new tab. A conversation the server answers is gone or not + // this user's is drawn unavailable and opens nothing; its ⋯ still removes it. + const unavailableConversations = useUnavailableConversationFavorites( + contentFavorites, + resolveAiApiBase(), + refreshFavoriteLabel, + ); + const openConversationFavorite = (item: FavoriteItem, event: React.MouseEvent) => { + const target = conversationFavoriteTarget(item); + if (!target) return; + if (unavailableConversations.has(item.id)) { + event.preventDefault(); + return; + } + if (!chatDock || chatDock.askPageActive) return; + if (event.defaultPrevented || event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return; + event.preventDefault(); + chatDock.open(target); + if (isMobile) setOpenMobile(false); + }; const contentFavoriteRow = (item: FavoriteItem, drag?: FavoriteRowDragProps) => { + const unavailable = unavailableConversations.has(item.id); + const unavailableText = t('sidebar.conversationUnavailable', { defaultValue: 'This conversation is no longer available' }); return ( <> - - + + openConversationFavorite(item, event) : undefined} + aria-disabled={unavailable || undefined} + data-unavailable={unavailable || undefined} + className={unavailable ? 'text-muted-foreground line-through decoration-muted-foreground/60' : undefined} + > {/* objectstack#36141 — the menu's tiles: an object, one of its views or records is that object's tile, the rest neutral. */} {contentTile(item.type, favoriteItemObject(item), item.type === 'view' ? item.icon : undefined)} {item.label} + {unavailable ? {`(${unavailableText})`} : null} ({ + ...(await importOriginal>()), + useObjectTranslation: () => ({ + t: (key: string, options?: Record) => + String(options?.defaultValue ?? key).replace(/\{\{(\w+)\}\}/g, (_hole, name: string) => + String(options?.[name] ?? ''), + ), + language: 'en', + }), + useObjectLabel: () => ({ + objectLabel: ({ label }: { label?: string }) => label, + viewLabel: (_o: string, _v: string, fallback?: string) => fallback, + dashboardLabel: ({ label }: { label?: string }) => label, + appLabel: ({ label }: { label?: string }) => label, + }), +})); + +vi.mock('@object-ui/auth', async (importOriginal) => ({ + ...(await importOriginal>()), + useAuth: () => ({ user: null, activeOrganization: null }), + useWorkspaceAdminStatus: () => ({ isAdmin: false, isResolved: true }), +})); + +vi.mock('@object-ui/permissions', async (importOriginal) => ({ + ...(await importOriginal()), + usePermissions: () => ({ can: () => true, hasCapabilities: () => false }), +})); + +let metadataState: { apps: unknown[]; objects: unknown[] }; +vi.mock('../../providers/MetadataProvider', () => ({ + useMetadata: () => metadataState, +})); + +vi.mock('../../providers/ExpressionProvider', () => ({ + useExpressionContext: () => ({ evaluator: null }), + evaluateVisibility: (expr: unknown) => expr !== false && expr !== 'false', + evaluateNavigationVisibility: (expr: unknown) => expr !== false && expr !== 'false', + useHasExpressionScope: () => true, +})); + +vi.mock('../../utils', () => ({ + resolveKeyedI18nLabel: (label: unknown) => (typeof label === 'string' ? label : ''), + matchAppBySegment: (apps: Array<{ name?: string }>, segment?: string) => + apps.find((a) => a?.name === segment), + appRouteSegment: (app: { name?: string }) => app?.name, +})); + +// An icon is drawn as its name, so a row's icon can be read. +vi.mock('../../utils/getIcon', () => ({ + getIcon: (name?: string) => (props: { className?: string }) => , +})); +vi.mock('../../hooks/useRecentItems', () => ({ useRecentItems: () => ({ recentItems: [] }) })); +vi.mock('../../hooks/useNavActionDispatch', () => ({ + useNavActionDispatch: () => vi.fn(), +})); +vi.mock('../../context/NavigationContext', () => ({ + useNavigationContext: () => ({ context: 'app', currentAppName: 'crm' }), +})); +vi.mock('../ContextSelectors', () => ({ + useAppContextSelectors: () => ({ contextValues: {}, element: null }), + contextSelectorQueryKey: (id: string) => (id === 'active_package' ? 'package' : id), + STUDIO_PACKAGE_SELECTOR_ID: 'active_package', +})); +vi.mock('../LocalizedSidebarTrigger', () => ({ + LocalizedSidebarTrigger: () => null, +})); + +import { SidebarProvider } from '@object-ui/components'; +import { UnifiedSidebar } from '../UnifiedSidebar'; +import { ChatDockControlProvider, type ChatDockControl } from '../chatDockControl'; +import { conversationFavoriteItem } from '../conversationFavorites'; +import { FavoritesProvider, useFavorites, type FavoriteItem } from '../../context/FavoritesProvider'; + +const NAVIGATION: NavigationItem[] = [ + { id: 'nav_leads', type: 'object', objectName: 'crm_lead', label: 'Leads' } as NavigationItem, +]; + +const conversationFavorite = (conversationId: string, label: string, agent = 'ask'): FavoriteItem => ({ + ...conversationFavoriteItem({ conversationId, agent, label }), + favoritedAt: '2026-11-27T00:00:00.000Z', +}); +const ACME = conversationFavorite('c-acme', 'Analyse Acme'); + +/** The provider's local key for a signed-out session. */ +const STORE_KEY = 'objectui-favorites'; +const seed = (favorites: FavoriteItem[]) => localStorage.setItem(STORE_KEY, JSON.stringify(favorites)); +const stored = (): FavoriteItem[] => JSON.parse(localStorage.getItem(STORE_KEY) ?? '[]'); + +/** What the server answers for a conversation read, by id: a status and, for 200, the row. */ +let conversations: Record }>; +const conversationReads: string[] = []; + +function Where() { + const location = useLocation(); + return {`${location.pathname}${location.search}`}; +} + +function renderSidebar(dock: ChatDockControl | null) { + metadataState = { + apps: [{ name: 'crm', label: 'CRM', active: true, navigation: NAVIGATION }], + objects: [], + }; + const sidebar = ( + + + + + + ); + return render( + + {dock ? {sidebar} : sidebar} + + , + ); +} + +const makeDock = (overrides: Partial = {}): ChatDockControl & { open: ReturnType } => ({ + expanded: false, + fullWindow: false, + toggle: vi.fn(), + open: vi.fn(), + ...overrides, +}) as ChatDockControl & { open: ReturnType }; + +const tick = () => act(async () => { await new Promise((r) => setTimeout(r, 0)); }); +const favoritesSection = () => + screen.getAllByText('Favorites')[0].closest('[data-sidebar="group"]') as HTMLElement; +const row = (name: RegExp | string) => within(favoritesSection()).getByRole('link', { name }); +const where = () => screen.getByTestId('where').textContent; + +beforeEach(() => { + localStorage.clear(); + conversationReads.length = 0; + conversations = { 'c-acme': { status: 200, row: { id: 'c-acme', title: 'Analyse Acme', agentId: 'ask' } } }; + vi.stubGlobal( + 'fetch', + vi.fn(async (url: unknown) => { + const match = /\/api\/v1\/ai\/conversations\/([^/?#]+)$/.exec(String(url)); + if (match) { + const id = decodeURIComponent(match[1]); + conversationReads.push(id); + const answer = conversations[id] ?? { status: 404 }; + if (answer.status === 0) throw new TypeError('Failed to fetch'); + return { + headers: new Headers(), + ok: answer.status >= 200 && answer.status < 300, + status: answer.status, + json: async () => ({ conversation: answer.row }), + }; + } + return { headers: new Headers(), ok: true, status: 200, json: async () => ({ data: [] }) }; + }), + ); +}); + +afterEach(() => { + cleanup(); + vi.unstubAllGlobals(); +}); + +describe('a favourite conversation opens the drawer in place (objectstack#37863)', () => { + it('is a row of the Favorites section, with its stored label and the conversation glyph', async () => { + seed([ACME]); + renderSidebar(makeDock()); + await tick(); + const link = row('Analyse Acme'); + expect(link).toHaveAttribute('href', '/ai/ask/c-acme'); + expect(link.querySelector('[data-icon]')).toHaveAttribute('data-icon', 'message-circle'); + }); + + it('a click opens the drawer on that conversation, and the page stays where it is', async () => { + seed([ACME]); + const dock = makeDock(); + renderSidebar(dock); + await tick(); + fireEvent.click(row('Analyse Acme')); + expect(dock.open).toHaveBeenCalledTimes(1); + expect(dock.open).toHaveBeenCalledWith({ agent: 'ask', conversationId: 'c-acme' }); + expect(where()).toBe('/apps/crm'); + }); + + it('the agent stored is a route name, so a backend name opens the same target', async () => { + seed([conversationFavorite('c-ask', 'Backend-named', 'data_chat')]); + conversations['c-ask'] = { status: 200, row: { id: 'c-ask', title: 'Backend-named' } }; + const dock = makeDock(); + renderSidebar(dock); + await tick(); + fireEvent.click(row('Backend-named')); + expect(dock.open).toHaveBeenCalledWith({ agent: 'ask', conversationId: 'c-ask' }); + }); + + it('a click with a modifier is left to the link: the drawer does not open', async () => { + seed([ACME]); + const dock = makeDock(); + renderSidebar(dock); + await tick(); + fireEvent.click(row('Analyse Acme'), { ctrlKey: true }); + fireEvent.click(row('Analyse Acme'), { metaKey: true }); + expect(dock.open).not.toHaveBeenCalled(); + }); + + it('with no drawer host, the row follows the conversation address', async () => { + seed([ACME]); + renderSidebar(null); + await tick(); + fireEvent.click(row('Analyse Acme')); + expect(where()).toBe('/ai/ask/c-acme'); + }); + + it("on the app's AI inquiry page (A4), the row follows the address instead of opening the drawer", async () => { + seed([ACME]); + const dock = makeDock({ askPageActive: true }); + renderSidebar(dock); + await tick(); + fireEvent.click(row('Analyse Acme')); + expect(dock.open).not.toHaveBeenCalled(); + expect(where()).toBe('/ai/ask/c-acme'); + }); + + it('other favourites keep their plain link', async () => { + seed([ + ACME, + { id: 'record:account:1', label: 'Acme Corp', href: '/apps/crm/account/record/1', type: 'record', favoritedAt: '2026-11-26T00:00:00.000Z' }, + ]); + const dock = makeDock(); + renderSidebar(dock); + await tick(); + fireEvent.click(row('Acme Corp')); + expect(dock.open).not.toHaveBeenCalled(); + expect(where()).toBe('/apps/crm/account/record/1'); + }); +}); + +describe('a favourite conversation follows the conversation (objectstack#37863)', () => { + it('a title the server gave the conversation since replaces the stored label, once', async () => { + seed([conversationFavorite('c-acme', 'analyse this company')]); + renderSidebar(makeDock()); + await waitFor(() => expect(row('Analyse Acme')).toBeInTheDocument()); + expect(stored().find((f) => f.id === 'conversation:c-acme')?.label).toBe('Analyse Acme'); + await tick(); + expect(conversationReads).toEqual(['c-acme']); + }); + + it('with no title, the label is the latest message the user wrote, as its history row reads', async () => { + seed([conversationFavorite('c-acme', 'old')]); + conversations['c-acme'] = { + status: 200, + row: { id: 'c-acme', title: 'New conversation', messages: [{ role: 'user', content: 'who owns Acme?' }] }, + }; + renderSidebar(makeDock()); + await waitFor(() => expect(row('who owns Acme?')).toBeInTheDocument()); + }); + + it.each([ + [404, 'gone'], + [403, 'not this user\'s'], + ])('a conversation the server answers %s (%s) is drawn unavailable and opens nothing', async (status) => { + seed([ACME]); + conversations['c-acme'] = { status }; + const dock = makeDock(); + renderSidebar(dock); + await waitFor(() => expect(row(/Analyse Acme/)).toHaveAttribute('data-unavailable', 'true')); + const link = row(/Analyse Acme/); + expect(link).toHaveAttribute('aria-disabled', 'true'); + expect(link).toHaveAccessibleName('Analyse Acme (This conversation is no longer available)'); + fireEvent.click(link); + expect(dock.open).not.toHaveBeenCalled(); + expect(where()).toBe('/apps/crm'); + // The stored entry is untouched: the mark is this mount's reading. + expect(stored().map((f) => f.id)).toEqual(['conversation:c-acme']); + }); + + it('an unavailable conversation is removed from its ⋯ menu', async () => { + seed([ACME]); + conversations['c-acme'] = { status: 404 }; + renderSidebar(makeDock()); + await waitFor(() => expect(row(/Analyse Acme/)).toHaveAttribute('data-unavailable', 'true')); + fireEvent.keyDown(within(favoritesSection()).getByRole('button', { name: 'More actions for Analyse Acme' }), { key: 'Enter' }); + fireEvent.click(await screen.findByRole('menuitem', { name: 'Remove from favorites' })); + await waitFor(() => expect(stored()).toEqual([])); + }); + + it.each([ + [500, 'a server error'], + [0, 'a network failure'], + ])('a read that fails with %s (%s) marks nothing and keeps the label', async (status) => { + seed([ACME]); + conversations['c-acme'] = { status }; + const dock = makeDock(); + renderSidebar(dock); + await waitFor(() => expect(conversationReads).toEqual(['c-acme'])); + await tick(); + const link = row('Analyse Acme'); + expect(link).not.toHaveAttribute('data-unavailable'); + fireEvent.click(link); + expect(dock.open).toHaveBeenCalledWith({ agent: 'ask', conversationId: 'c-acme' }); + }); +}); + +describe('conversation favourites count against the content cap (objectstack#37863)', () => { + function Probe({ onReady }: { onReady: (api: ReturnType) => void }) { + const api = useFavorites(); + onReady(api); + return null; + } + + it('the 21st content favourite rolls the oldest off, a conversation among them', async () => { + const records: FavoriteItem[] = Array.from({ length: 19 }, (_, i) => ({ + id: `record:account:${i}`, + label: `Account ${i}`, + href: `/apps/crm/account/record/${i}`, + type: 'record', + favoritedAt: `2026-11-${String(26 - Math.floor(i / 10)).padStart(2, '0')}T00:00:${String(i).padStart(2, '0')}.000Z`, + })); + seed([...records, ACME]); + let api: ReturnType | undefined; + render( + + { api = next; }} /> + , + ); + expect(api!.favorites).toHaveLength(20); + act(() => { + api!.addFavorite({ ...conversationFavoriteItem({ conversationId: 'c-new', agent: 'ask', label: 'New one' }) }); + }); + expect(api!.favorites).toHaveLength(20); + expect(api!.favorites[0].id).toBe('conversation:c-new'); + expect(api!.favorites.some((f) => f.id === 'conversation:c-acme')).toBe(false); + }); +}); diff --git a/ui/packages/app-shell/src/layout/contentItemTile.tsx b/ui/packages/app-shell/src/layout/contentItemTile.tsx index c25b5533283..ef58f5ca488 100644 --- a/ui/packages/app-shell/src/layout/contentItemTile.tsx +++ b/ui/packages/app-shell/src/layout/contentItemTile.tsx @@ -30,6 +30,8 @@ export const CONTENT_KIND_ICON: Readonly> = { ...NAV_KIND_ICON, package: 'package', metadata: 'file-code', + // objectstack#37863 — a favourite conversation, the glyph of the "Ask AI" entry. + conversation: 'message-circle', }; /** diff --git a/ui/packages/app-shell/src/layout/conversationFavorites.ts b/ui/packages/app-shell/src/layout/conversationFavorites.ts new file mode 100644 index 00000000000..7bbf64a4049 --- /dev/null +++ b/ui/packages/app-shell/src/layout/conversationFavorites.ts @@ -0,0 +1,112 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#37863 — favourite conversations. The assistant drawer's ☆ stores + * a conversation in the user's favourites; the sidebar's Favorites section + * lists it, and its row opens the drawer in place on that conversation, the + * target a history row opens (ui ADR-0057 Amendment A5, row 5). Its `href` is + * the conversation's `/ai…` address, which a page without a drawer follows. + * + * A favourite's label follows the conversation: the sidebar reads each shown + * conversation favourite once per mount and keeps the label its history row + * carries. A conversation the server answers is gone or not this user's is + * marked unavailable for that mount (never stored), and stays removable. + */ + +import * as React from 'react'; +import { agentRouteName } from '@object-ui/plugin-chatbot/core'; +import type { FavoriteItem } from '../context/FavoritesProvider.js'; +import { readConversationRow } from '../hooks/useConversationList.js'; +import { aiAddressOf, type ChatDockTarget } from './chatDockTarget.js'; + +/** The favourite id of conversation `conversationId`. */ +export function conversationFavoriteId(conversationId: string): string { + return `conversation:${conversationId}`; +} + +/** + * The favourite entry of a conversation with `agent` (a route or backend + * name), labelled `label`: what the drawer's ☆ toggles. + */ +export function conversationFavoriteItem(input: { + conversationId: string; + agent: string; + label: string; +}): Omit { + const agent = agentRouteName(input.agent); + return { + id: conversationFavoriteId(input.conversationId), + label: input.label, + href: aiAddressOf({ agent, conversationId: input.conversationId }, agentRouteName), + type: 'conversation', + conversationId: input.conversationId, + agent, + }; +} + +/** The drawer target a conversation favourite opens; `undefined` for any other favourite. */ +export function conversationFavoriteTarget(item: FavoriteItem): ChatDockTarget | undefined { + if (item.type !== 'conversation' || !item.conversationId) return undefined; + return item.agent + ? { agent: item.agent, conversationId: item.conversationId } + : { conversationId: item.conversationId }; +} + +/** + * Reads each conversation favourite in `items` once per mount: a label that + * moved on the server is written back through `refreshLabel`, and the ids the + * server answers are gone (404) or not this user's (403) are returned. A read + * that fails any other way marks nothing. + */ +export function useUnavailableConversationFavorites( + items: readonly FavoriteItem[], + apiBase: string, + refreshLabel: (id: string, label: string) => void, +): ReadonlySet { + const [unavailable, setUnavailable] = React.useState>(() => new Set()); + const refreshLabelRef = React.useRef(refreshLabel); + React.useLayoutEffect(() => { + refreshLabelRef.current = refreshLabel; + }, [refreshLabel]); + const requested = React.useRef(new Set()); + + const pending = items + .filter((item) => item.type === 'conversation' && !!item.conversationId) + .map((item) => `${item.id}\n${item.conversationId}`) + .sort() + .join('\n\n'); + + const mounted = React.useRef(true); + React.useEffect(() => { + mounted.current = true; + return () => { + mounted.current = false; + }; + }, []); + + React.useEffect(() => { + if (!pending) return; + for (const pair of pending.split('\n\n')) { + const [id, conversationId] = pair.split('\n'); + const key = `${apiBase}\n${id}`; + if (requested.current.has(key)) continue; + requested.current.add(key); + readConversationRow(apiBase, conversationId).then( + (row) => { + if (!mounted.current) return; + if (row === null) { + setUnavailable((prev) => (prev.has(id) ? prev : new Set(prev).add(id))); + return; + } + const label = row.title || row.preview; + if (label) refreshLabelRef.current(id, label); + }, + () => { + requested.current.delete(key); + }, + ); + } + }, [pending, apiBase]); + + return unavailable; +} diff --git a/ui/packages/i18n/src/locales/ar.ts b/ui/packages/i18n/src/locales/ar.ts index 7aad391e849..84fe7bae40f 100644 --- a/ui/packages/i18n/src/locales/ar.ts +++ b/ui/packages/i18n/src/locales/ar.ts @@ -3815,6 +3815,7 @@ const ar = { recent: "الأخيرة", starred: "المميزة", removeFromFavorites: "إزالة {{name}} من المفضلة", + conversationUnavailable: "لم تعد هذه المحادثة متاحة", allReports: "كل التقارير", collapse: 'طي الشريط الجانبي', expand: 'توسيع الشريط الجانبي', diff --git a/ui/packages/i18n/src/locales/de.ts b/ui/packages/i18n/src/locales/de.ts index bf443a5a9fc..237fa2ef379 100644 --- a/ui/packages/i18n/src/locales/de.ts +++ b/ui/packages/i18n/src/locales/de.ts @@ -3500,6 +3500,7 @@ const de = { recent: "Zuletzt", starred: "Markiert", removeFromFavorites: "{{name}} aus Favoriten entfernen", + conversationUnavailable: "Diese Unterhaltung ist nicht mehr verfügbar", allReports: "Alle Berichte", collapse: 'Seitenleiste einklappen', expand: 'Seitenleiste ausklappen', diff --git a/ui/packages/i18n/src/locales/en.ts b/ui/packages/i18n/src/locales/en.ts index 7242665c70a..75ba0d52cdc 100644 --- a/ui/packages/i18n/src/locales/en.ts +++ b/ui/packages/i18n/src/locales/en.ts @@ -4216,6 +4216,7 @@ const en = { recent: 'Recent', starred: 'Starred', removeFromFavorites: 'Remove {{name}} from favorites', + conversationUnavailable: 'This conversation is no longer available', allReports: 'All reports', collapse: 'Collapse sidebar', expand: 'Expand sidebar', diff --git a/ui/packages/i18n/src/locales/es.ts b/ui/packages/i18n/src/locales/es.ts index 106310c7133..8a2f40568bc 100644 --- a/ui/packages/i18n/src/locales/es.ts +++ b/ui/packages/i18n/src/locales/es.ts @@ -3580,6 +3580,7 @@ const es = { recent: "Reciente", starred: "Destacados", removeFromFavorites: "Quitar {{name}} de favoritos", + conversationUnavailable: "Esta conversación ya no está disponible", allReports: "Todos los informes", collapse: 'Contraer la barra lateral', expand: 'Expandir la barra lateral', diff --git a/ui/packages/i18n/src/locales/fr.ts b/ui/packages/i18n/src/locales/fr.ts index 9dd3e6a56f0..4cdecdd8379 100644 --- a/ui/packages/i18n/src/locales/fr.ts +++ b/ui/packages/i18n/src/locales/fr.ts @@ -3576,6 +3576,7 @@ const fr = { recent: "Récent", starred: "Étoilés", removeFromFavorites: "Retirer {{name}} des favoris", + conversationUnavailable: "Cette conversation n’est plus disponible", allReports: "Tous les rapports", collapse: 'Réduire la barre latérale', expand: 'Développer la barre latérale', diff --git a/ui/packages/i18n/src/locales/ja.ts b/ui/packages/i18n/src/locales/ja.ts index 8fecce1e1e7..360617333b2 100644 --- a/ui/packages/i18n/src/locales/ja.ts +++ b/ui/packages/i18n/src/locales/ja.ts @@ -3502,6 +3502,7 @@ const ja = { recent: "最近", starred: "スター付き", removeFromFavorites: "お気に入りから {{name}} を削除", + conversationUnavailable: "この会話はもう利用できません", allReports: "すべてのレポート", collapse: 'サイドバーを折りたたむ', expand: 'サイドバーを展開', diff --git a/ui/packages/i18n/src/locales/ko.ts b/ui/packages/i18n/src/locales/ko.ts index 2cbfdc1e883..24a8180718f 100644 --- a/ui/packages/i18n/src/locales/ko.ts +++ b/ui/packages/i18n/src/locales/ko.ts @@ -3500,6 +3500,7 @@ const ko = { recent: "최근", starred: "즐겨찾기", removeFromFavorites: "즐겨찾기에서 {{name}} 제거", + conversationUnavailable: "이 대화는 더 이상 사용할 수 없습니다", allReports: "모든 보고서", collapse: '사이드바 접기', expand: '사이드바 펼치기', diff --git a/ui/packages/i18n/src/locales/pt-BR.ts b/ui/packages/i18n/src/locales/pt-BR.ts index 1176e882d23..365071a3928 100644 --- a/ui/packages/i18n/src/locales/pt-BR.ts +++ b/ui/packages/i18n/src/locales/pt-BR.ts @@ -3575,6 +3575,7 @@ const pt = { recent: "Recente", starred: "Favoritos", removeFromFavorites: "Remover {{name}} dos favoritos", + conversationUnavailable: "Esta conversa não está mais disponível", allReports: "Todos os relatórios", collapse: 'Recolher a barra lateral', expand: 'Expandir a barra lateral', diff --git a/ui/packages/i18n/src/locales/ru.ts b/ui/packages/i18n/src/locales/ru.ts index 9e7ba809ee9..35d8ab1958a 100644 --- a/ui/packages/i18n/src/locales/ru.ts +++ b/ui/packages/i18n/src/locales/ru.ts @@ -3665,6 +3665,7 @@ const ru = { recent: "Недавние", starred: "Отмеченные", removeFromFavorites: "Убрать {{name}} из избранного", + conversationUnavailable: "Этот диалог больше недоступен", allReports: "Все отчёты", collapse: 'Свернуть боковую панель', expand: 'Развернуть боковую панель', diff --git a/ui/packages/i18n/src/locales/zh-Hans.ts b/ui/packages/i18n/src/locales/zh-Hans.ts index 4ab8b0cd431..1482a85556d 100644 --- a/ui/packages/i18n/src/locales/zh-Hans.ts +++ b/ui/packages/i18n/src/locales/zh-Hans.ts @@ -3633,6 +3633,7 @@ const zh = { recent: '最近使用', starred: '已收藏', removeFromFavorites: '从收藏中移除 {{name}}', + conversationUnavailable: '该对话已不可用', allReports: '全部报表', collapse: '收起侧边栏', expand: '展开侧边栏', diff --git a/ui/packages/i18n/src/locales/zh-Hant.ts b/ui/packages/i18n/src/locales/zh-Hant.ts index 28fff9b6892..2a889fa9304 100644 --- a/ui/packages/i18n/src/locales/zh-Hant.ts +++ b/ui/packages/i18n/src/locales/zh-Hant.ts @@ -3633,6 +3633,7 @@ const zhHant = { recent: '最近使用', starred: '已收藏', removeFromFavorites: '從收藏中移除 {{name}}', + conversationUnavailable: '該對話已不可用', allReports: '全部報表', collapse: '收起側邊欄', expand: '展開側邊欄', From 41071e92e96541d02817f12a2b9b55c2756390ae Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 15:14:41 +0000 Subject: [PATCH 2/4] docs(app-shell): README names the conversation favourite and its sidebar row Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01L9qibxdwshRvTk3qXc7A6A --- .changeset/37863-favourite-conversations.md | 2 +- ui/packages/app-shell/README.md | 9 +++++++++ 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/.changeset/37863-favourite-conversations.md b/.changeset/37863-favourite-conversations.md index 8acd4a1aef1..1ba95a5de27 100644 --- a/.changeset/37863-favourite-conversations.md +++ b/.changeset/37863-favourite-conversations.md @@ -8,7 +8,7 @@ feat(app-shell): favourite conversations open in the assistant drawer in place, Clause-②: no Metadata-protocol: none -- **A conversation can be a favourite.** `FavoriteItem` gains the `conversation` type, id `conversation:ID`, with the conversation's id and agent (`conversationId`, `agent`); its `href` is the conversation's `/ai…` address. `conversationFavoriteItem` builds the entry. Conversation favourites count against the same cap of 20 as the other content favourites. +- **A conversation can be a favourite.** `FavoriteItem` gains the `conversation` type, id `conversation:ID`, with the conversation's id and agent (`conversationId`, `agent`); its `href` is the conversation's `/ai…` address. Conversation favourites count against the same cap of 20 as the other content favourites. - **The sidebar row opens the drawer in place.** A favourite conversation is a row of the sidebar's Favorites section, with the chat-bubble icon. Clicking it opens the assistant drawer on that conversation, the way its history row does, and the page stays where it is. The address is followed only where no drawer can take it: a page without the drawer, the app's AI inquiry page, or a click that opens a new tab. - **The label follows the conversation.** The sidebar reads each favourite conversation once and keeps the label its history row shows (the server's title, else the latest message the user wrote). - **A deleted conversation is marked.** A conversation the server answers is gone, or is not this user's, is drawn struck through as unavailable (`sidebar.conversationUnavailable`, new in every pack), opens nothing, and is still removed from its ⋯ menu. A failed read of any other kind marks nothing. diff --git a/ui/packages/app-shell/README.md b/ui/packages/app-shell/README.md index 653ae39c155..471946c963f 100644 --- a/ui/packages/app-shell/README.md +++ b/ui/packages/app-shell/README.md @@ -1412,6 +1412,15 @@ adapter syncs both flows. The legacy `objectui-nav-pins` localStorage key is migrated on first mount and then removed. Content favorites (20) and nav pins (20) each have an independent cap. See the guide below for details. +An AI conversation can be a content favorite too (`type: 'conversation'`, id +`conversation:ID`, with `conversationId` and `agent`), starred from the +assistant drawer. Its sidebar row opens the drawer in place +on that conversation, and follows its `href` (the conversation's `/ai…` +address) only where no drawer can take it. The sidebar reads each favorite +conversation once: the label follows the conversation's title, and a +conversation the server answers is gone or not this user's is drawn +unavailable, stays removable, and opens nothing. + The sidebar's Pinned section keeps the user's order, stored with the pins: `pinnedIds` lists them in it, a new pin joins the end, and `reorderPins(orderedIds)` saves a new order. The sidebar passes both to From 334639300b3f2e2ed6c4c31de3764803847f8d53 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 16:01:11 +0000 Subject: [PATCH 3/4] feat(app-shell): the drawer header's star favourites the conversation in view Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01L9qibxdwshRvTk3qXc7A6A --- .changeset/37863-favourite-conversations.md | 3 +- ui/packages/app-shell/src/layout/ChatDock.tsx | 71 +++++- .../src/layout/ChatDockConversation.tsx | 3 +- .../ChatDock.favoriteStar-37863.test.tsx | 225 ++++++++++++++++++ .../app-shell/src/layout/chatDockTarget.ts | 2 + 5 files changed, 300 insertions(+), 4 deletions(-) create mode 100644 ui/packages/app-shell/src/layout/__tests__/ChatDock.favoriteStar-37863.test.tsx diff --git a/.changeset/37863-favourite-conversations.md b/.changeset/37863-favourite-conversations.md index 1ba95a5de27..05b5de5fd81 100644 --- a/.changeset/37863-favourite-conversations.md +++ b/.changeset/37863-favourite-conversations.md @@ -3,11 +3,12 @@ '@object-ui/i18n': patch --- -feat(app-shell): favourite conversations open in the assistant drawer in place, from the sidebar's Favorites +feat(app-shell): the assistant drawer's ☆ favourites a conversation, and the sidebar's Favorites open it in the drawer in place Clause-②: no Metadata-protocol: none +- **The drawer header's ☆.** Once the first message has created the conversation, the header's ☆ (before +) adds it to the user's favourites, and is pressed while it is one; pressed again, it removes it. It is drawn in the side panel, the full window and the phone sheet. While the conversation is a favourite, its stored label follows the header's title. - **A conversation can be a favourite.** `FavoriteItem` gains the `conversation` type, id `conversation:ID`, with the conversation's id and agent (`conversationId`, `agent`); its `href` is the conversation's `/ai…` address. Conversation favourites count against the same cap of 20 as the other content favourites. - **The sidebar row opens the drawer in place.** A favourite conversation is a row of the sidebar's Favorites section, with the chat-bubble icon. Clicking it opens the assistant drawer on that conversation, the way its history row does, and the page stays where it is. The address is followed only where no drawer can take it: a page without the drawer, the app's AI inquiry page, or a click that opens a new tab. - **The label follows the conversation.** The sidebar reads each favourite conversation once and keeps the label its history row shows (the server's title, else the latest message the user wrote). diff --git a/ui/packages/app-shell/src/layout/ChatDock.tsx b/ui/packages/app-shell/src/layout/ChatDock.tsx index b7493ad291e..3880893d9ce 100644 --- a/ui/packages/app-shell/src/layout/ChatDock.tsx +++ b/ui/packages/app-shell/src/layout/ChatDock.tsx @@ -39,7 +39,7 @@ import { SheetHeader, SheetTitle, } from '@object-ui/components'; -import { History, Maximize2, MessagesSquare, Minimize2, MoreHorizontal, Plus, Share2, X } from 'lucide-react'; +import { History, Maximize2, MessagesSquare, Minimize2, MoreHorizontal, Plus, Share2, Star, X } from 'lucide-react'; import { formatNumber, useObjectTranslation } from '@object-ui/i18n'; import { useAgents } from '@object-ui/plugin-chatbot/core'; import { resolveApiBase } from '../console/ai/resolveApiBase.js'; @@ -48,6 +48,8 @@ import { useAiUsage } from '../hooks/useAiUsage.js'; import { cloudConsoleUrl } from '../console/marketplace/marketplaceApi.js'; import { getUpgradeUrl } from '../runtime-config.js'; import { usePlanApprovalPending } from '../assistant/assistantBus.js'; +import { useFavorites } from '../context/FavoritesProvider.js'; +import { conversationFavoriteId, conversationFavoriteItem } from './conversationFavorites.js'; import type { ChatSurfaceContext } from './chatSurfaceContext.js'; import { readStoredDockFullWindow, @@ -394,7 +396,64 @@ interface DockHeaderButtonsProps { } /** - * ui ADR-0057 Amendment A5 — the header's + and history buttons, as icons: + * objectstack#37863 — the header's ☆: adds the thread in view to the user's + * favourites, or removes it (pressed while it is one). Drawn once the first + * send has created the thread. While it is a favourite, the stored label + * follows the label the header reads. + */ +function DockFavoriteButton({ + actions, + box, + icon, + testId, +}: { + actions: ChatDockConversationActions; + box: string; + icon: string; + testId: string; +}) { + const { t } = useObjectTranslation(); + const { isFavorite, toggleFavorite, refreshLabel } = useFavorites(); + const conversationId = actions.conversationId as string; + const id = conversationFavoriteId(conversationId); + const starred = isFavorite(id); + const label = actions.labelPending ? undefined : actions.label; + const refreshLabelRef = React.useRef(refreshLabel); + React.useLayoutEffect(() => { + refreshLabelRef.current = refreshLabel; + }); + React.useEffect(() => { + if (starred && label) refreshLabelRef.current(id, label); + }, [starred, id, label]); + const name = starred + ? t('common.removeFromFavorites', { defaultValue: 'Remove from favorites' }) + : t('common.addToFavorites', { defaultValue: 'Add to favorites' }); + return ( + + ); +} + +/** + * ui ADR-0057 Amendment A5 — the header's ☆ (objectstack#37863), + and history buttons, as icons: * + starts a new conversation on the agent in use, the clock shows the * history over the chat (pressed while it does) and goes back to the chat. */ @@ -409,6 +468,14 @@ function DockHeaderButtons({ actions, history, size, onStartNew }: DockHeaderBut : t('console.ai.dock.history', { defaultValue: 'History' }); return ( <> + {actions?.conversationId && actions.agent ? ( + + ) : null} {startNew ? (