Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(favorites): favorites (#4498)

teo6801156f7cba
diff --git a/.github/workspace-dep-closures.json b/.github/workspace-dep-closures.json
index 7d83bb3101..ed117df5b8 100644
--- a/.github/workspace-dep-closures.json
+++ b/.github/workspace-dep-closures.json
@@ -1358,6 +1358,7 @@
"entity_access",
"entity_access_db_utils",
"entity_access_management",
+ "favorites",
"filter_ast",
"foreign_entity",
"frecency",
@@ -2127,6 +2128,30 @@
"models_permissions",
"workspace-hack"
],
+ "favorites": [
+ "agent",
+ "ai_toolset",
+ "ai_usage",
+ "attachment",
+ "cowlike",
+ "document_sub_type",
+ "entity_access",
+ "favorites",
+ "macro_env_var",
+ "macro_user_id",
+ "macro_uuid",
+ "model",
+ "model-entity",
+ "model-error-response",
+ "model_file_type",
+ "model_user",
+ "models_bulk_upload",
+ "models_pagination",
+ "models_permissions",
+ "non_empty",
+ "prompt",
+ "workspace-hack"
+ ],
"filter_ast": [
"filter_ast",
"workspace-hack"
diff --git a/js/app/packages/app/component/ItemDragAndDrop.tsx b/js/app/packages/app/component/ItemDragAndDrop.tsx
index 6087b80f60..48e121a766 100644
--- a/js/app/packages/app/component/ItemDragAndDrop.tsx
+++ b/js/app/packages/app/component/ItemDragAndDrop.tsx
@@ -8,7 +8,11 @@ import {
useDragDropContext,
} from '@thisbeyond/solid-dnd';
import { Layer } from '@ui';
-import { EntityIcon, getEntityIconType } from 'core/component/EntityIcon';
+import {
+ EntityIcon,
+ type EntityIconSelector,
+ getEntityIconType,
+} from 'core/component/EntityIcon';
import {
type Accessor,
createContext,
@@ -73,10 +77,15 @@ function ItemDragOverlay() {
return state?.active.draggable;
});
- const iconType = createMemo(() => {
- const data = activeDraggable()?.data as EntityDragData | undefined;
+ const iconType = createMemo((): EntityIconSelector => {
+ const data = activeDraggable()?.data;
if (!data) return 'default';
- return getEntityIconType(data);
+ // Favorite sortables carry a precomputed icon type (see FavoriteDragData
+ // in app-sidebar/favorites-section) instead of an entity shape.
+ if (data.dragType === 'favorite') {
+ return data.iconType as EntityIconSelector;
+ }
+ return getEntityIconType(data as EntityDragData);
});
const centeredOnPointerStyle = createMemo(() => {
diff --git a/js/app/packages/app/component/Layout.tsx b/js/app/packages/app/component/Layout.tsx
index c268fb7434..2b3d2c4075 100644
--- a/js/app/packages/app/component/Layout.tsx
+++ b/js/app/packages/app/component/Layout.tsx
@@ -31,6 +31,7 @@ import { BundleUpdateProgressBar } from './BundleUpdateProgressBar';
import Banner from './banner/Banner';
import { GlobalBulkEditEntityModal } from './bulk-edit-entity/BulkEditEntityModal';
import { CommandMenu } from './command';
+import { FavoritesCommands } from './command/FavoritesCommands';
import { DevStatusBar } from './DevStatusBar';
import { GithubReauthenticationPrompt } from './GithubReauthenticationPrompt';
import GlobalShortcuts from './GlobalHotkeys';
@@ -139,6 +140,7 @@ function LayoutInner(props: RouteSectionProps) {
<GlobalShortcuts />
<Show when={!isMobile()}>
<Suspense>
+ <FavoritesCommands />
<CommandMenu />
</Suspense>
</Show>
@@ -168,21 +170,23 @@ function LayoutInner(props: RouteSectionProps) {
<Paywall />
</Show>
<div class="max-h-full grow flex">
- <Show when={isSidebarVisible()}>
- <AppSidebar
- sidebarState={sidebarState()}
- onOpenChange={(open) => {
- if (!open) {
- setSidebarState(isMobile() ? 'hidden' : 'slim');
- return;
- }
+ {/* The provider spans the sidebar too so its favorites can register
+ sortables with the same drag-drop context as the entity drags. */}
+ <ItemDndProvider>
+ <Show when={isSidebarVisible()}>
+ <AppSidebar
+ sidebarState={sidebarState()}
+ onOpenChange={(open) => {
+ if (!open) {
+ setSidebarState(isMobile() ? 'hidden' : 'slim');
+ return;
+ }
- setSidebarState('expanded');
- }}
- />
- </Show>
+ setSidebarState('expanded');
+ }}
+ />
+ </Show>
- <ItemDndProvider>
<div class="flex-1 w-full min-h-0 font-sans text-ink caret-accent">
{props.children}
</div>
diff --git a/js/app/packages/app/component/app-sidebar/favorites-section.tsx b/js/app/packages/app/component/app-sidebar/favorites-section.tsx
new file mode 100644
index 0000000000..1d34f95192
--- /dev/null
+++ b/js/app/packages/app/component/app-sidebar/favorites-section.tsx
@@ -0,0 +1,260 @@
+import type { SidebarState } from '@app/component/app-sidebar/sidebar';
+import { useSplitLayout } from '@app/component/split-layout/layout';
+import { globalSplitManager } from '@app/signal/splitLayout';
+import {
+ favoriteDisplayName,
+ favoriteIconType,
+ favoriteSplitContent,
+} from '@app/util/favorites';
+import { ContextMenuContent, MenuItem } from '@core/component/ContextMenu';
+import {
+ EntityIcon,
+ type EntityIconSelector,
+} from '@core/component/EntityIcon';
+import { ContextMenu } from '@kobalte/core/context-menu';
+import CaretDownIcon from '@phosphor/caret-down.svg';
+import {
+ favoriteEntityKey,
+ useFavoritesData,
+ useRemoveFavoriteMutation,
+ useReorderFavoritesMutation,
+} from '@queries/favorites/favorites';
+import type { Favorite } from '@service-storage/generated/schemas/favorite';
+import { makePersisted } from '@solid-primitives/storage';
+import {
+ createSortable,
+ SortableProvider,
+ useDragDropContext,
+} from '@thisbeyond/solid-dnd';
+import { cn, NavRow } from '@ui';
+import { createMemo, createSignal, For, Show } from 'solid-js';
+
+/**
+ * Drag data carried by favorite row sortables. Distinct from `EntityDragData`
+ * (`dragType: 'entity'`) so entity drop consumers ignore favorite drags; the
+ * global `ItemDragOverlay` branches on it to render its chip.
+ */
+export type FavoriteDragData = {
+ dragType: 'favorite';
+ iconType: EntityIconSelector;
+ name: string;
+ /** Read by the `pointerWithin` collision detector to skip collapsed rows. */
+ isDropTargetDisabled: () => boolean;
+};
+
+/**
+ * Linear-style favorites for the expanded sidebar: a collapsible "Favorites"
+ * list of the user's favorited entities. Rows navigate like other sidebar rows
+ * and are drag-reorderable. Hidden entirely in slim mode and when the user has
+ * no favorites.
+ */
+export const FavoritesSection = (props: { sidebarState: SidebarState }) => {
+ // Non-suspending accessor: a pending or failed favorites query must not
+ // suspend or crash the sidebar; the section just stays hidden until loaded.
+ const favoritesData = useFavoritesData();
+
+ const favorites = () => favoritesData()?.favorites ?? [];
+
+ return (
+ <Show when={props.sidebarState === 'expanded' && favorites().length > 0}>
+ <div class="w-full shrink-0 max-h-[40%] overflow-y-auto overscroll-contain">
+ <FavoritesGroup
+ label="Favorites"
+ favorites={favorites()}
+ persistKey="sidebar-favorites-expanded"
+ />
+ </div>
+ </Show>
+ );
+};
+
+const FavoritesGroup = (props: {
+ label: string;
+ favorites: Favorite[];
+ persistKey: string;
+}) => {
+ const [expanded, setExpanded] = makePersisted(createSignal(true), {
+ name: props.persistKey,
+ });
+ const reorderMutation = useReorderFavoritesMutation();
+
+ // Rows are keyed by what they point at; favorites have no surrogate id.
+ const keys = createMemo(() =>
+ props.favorites.map((favorite) =>
+ favoriteEntityKey(favorite.entityType, favorite.entityId)
+ )
+ );
+
+ // The sidebar lives inside the app-wide DragDropProvider (ItemDndProvider);
+ // register on its events rather than mounting a nested provider.
+ const [, dndActions] = useDragDropContext() ?? [];
+
+ dndActions?.onDragEnd(({ draggable, droppable }) => {
+ const dragData = draggable.data;
+ if (dragData?.dragType !== 'favorite') return;
+ // Dropping outside the list leaves the order unchanged.
+ if (!droppable) return;
+ const dropData = droppable.data;
+ if (dropData?.dragType !== 'favorite') return;
+ const current = keys();
+ const fromIndex = current.indexOf(String(draggable.id));
+ const toIndex = current.indexOf(String(droppable.id));
+ if (fromIndex < 0 || toIndex < 0 || fromIndex === toIndex) return;
+ const ordered = props.favorites.slice();
+ ordered.splice(toIndex, 0, ...ordered.splice(fromIndex, 1));
+ reorderMutation.mutate({
+ favorites: ordered.map((favorite) => ({
+ entityType: favorite.entityType,
+ entityId: favorite.entityId,
+ })),
+ });
+ });
+
+ return (
+ <section class="w-full py-1.5">
+ <header class="shrink-0 my-1 px-1">
+ <button
+ type="button"
+ class="w-full flex items-center gap-1 text-xs font-medium text-ink-extra-muted/50 hover:text-ink-muted transition-colors"
+ aria-expanded={expanded()}
+ onClick={() => setExpanded(!expanded())}
+ >
+ <h1>{props.label}</h1>
+ <CaretDownIcon
+ class={cn(
+ 'size-3 transition-transform duration-200',
+ expanded() && 'rotate-180'
+ )}
+ />
+ </button>
+ </header>
+
+ <div
+ class="grid w-full transition-[grid-template-rows] duration-200 ease-out"
+ style={{ 'grid-template-rows': expanded() ? '1fr' : '0fr' }}
+ >
+ <ul class="min-h-0 overflow-hidden flex flex-col gap-0.5">
+ <SortableProvider ids={keys()}>
+ <For each={props.favorites}>
+ {(favorite, index) => (
+ <li
+ class={cn(
+ 'w-full transition-[opacity,transform] duration-200 ease-out',
+ expanded()
+ ? 'opacity-100 translate-y-0'
+ : 'opacity-0 -translate-y-2'
+ )}
+ style={{
+ 'transition-delay': expanded()
+ ? `${index() * 30}ms`
+ : '0ms',
+ }}
+ >
+ <FavoriteRow favorite={favorite} disabled={!expanded()} />
+ </li>
+ )}
+ </For>
+ </SortableProvider>
+ </ul>
+ </div>
+ </section>
+ );
+};
+
+const FavoriteRow = (props: { favorite: Favorite; disabled: boolean }) => {
+ const layout = useSplitLayout();
+ const removeMutation = useRemoveFavoriteMutation();
+ const [dndState] = useDragDropContext() ?? [];
+
+ const iconType = () => favoriteIconType(props.favorite);
+ const displayName = () => favoriteDisplayName(props.favorite);
+
+ // `For` keys rows by favorite identity, so the favorite (and drag data
+ // derived from it) is stable for the row's lifetime.
+ //
+ // `isDropTargetDisabled` is read by the app's `pointerWithin` collision
+ // detector (see ItemDragAndDrop). A collapsed group still renders its rows
+ // (clipped to 0 height for the expand/collapse animation), so without this
+ // their stale layout rects would capture drops. Gating on `disabled` keeps
+ // collapsed rows out of collision detection entirely.
+ const sortable = createSortable(
+ favoriteEntityKey(props.favorite.entityType, props.favorite.entityId),
+ {
+ dragType: 'favorite',
+ iconType: favoriteIconType(props.favorite),
+ name: favoriteDisplayName(props.favorite),
+ isDropTargetDisabled: () => props.disabled,
+ } satisfies FavoriteDragData
+ );
+
+ const content = () => favoriteSplitContent(props.favorite);
+
+ const isActive = () => {
+ const active = globalSplitManager()?.activeSplit()?.content();
+ return (
+ !!active &&
+ active.type !== 'component' &&
+ active.id === props.favorite.entityId
+ );
+ };
+
+ const open = (e: MouseEvent) => {
+ layout.openWithSplit(content(), {
+ referredFrom: 'sidebar',
+ activate: true,
+ preferNewSplit: e.shiftKey,
+ });
+ globalSplitManager()?.returnFocus();
+ };
+
+ const removeFromFavorites = () => {
+ removeMutation.mutate({
+ entityType: props.favorite.entityType,
+ entityId: props.favorite.entityId,
+ });
+ };
+
+ return (
+ <div
+ ref={sortable}
+ class={cn(
+ 'w-full',
+ // Smoothly shift rows out of the way while a drag is live; snap
+ // (no transition) when it ends so the settled order doesn't animate
+ // twice.
+ !!dndState?.active.draggable && 'transition-transform',
+ sortable.isActiveDraggable && 'opacity-40'
+ )}
+ >
+ <ContextMenu>
+ <ContextMenu.Trigger class="w-full h-8">
+ <NavRow
+ draggable={false}
+ disabled={props.disabled}
+ data-sidebar-favorite={favoriteEntityKey(
+ props.favorite.entityType,
+ props.favorite.entityId
+ )}
+ data-active={isActive() ? '' : undefined}
+ active={isActive()}
+ class="h-8"
+ fullWidth
+ onClick={open}
+ >
+ <EntityIcon size="xs" targetType={iconType()} />
+ <span class="truncate">{displayName()}</span>
+ </NavRow>
+ </ContextMenu.Trigger>
+
+ <ContextMenu.Portal>
+ <ContextMenuContent class="text-xs text-ink-muted">
+ <MenuItem
+ text="Remove from favorites"
+ onClick={removeFromFavorites}
+ />
+ </ContextMenuContent>
+ </ContextMenu.Portal>
+ </ContextMenu>
+ </div>
+ );
+};
diff --git a/js/app/packages/app/component/app-sidebar/sidebar.tsx b/js/app/packages/app/component/app-sidebar/sidebar.tsx
index ab0b8abd58..922a450aaf 100644
--- a/js/app/packages/app/component/app-sidebar/sidebar.tsx
+++ b/js/app/packages/app/component/app-sidebar/sidebar.tsx
@@ -1,6 +1,7 @@
import { useAnalytics } from '@app/component/analytics-context';
import { SidebarActiveCallWidget } from '@app/component/app-sidebar/active-call-widget';
import { ChannelsUnreadWidget } from '@app/component/app-sidebar/channels-unread-widget';
+import { FavoritesSection } from '@app/component/app-sidebar/favorites-section';
import {
InviteModal,
setInviteModalOpen,
@@ -855,6 +856,8 @@ export const AppSidebar = (props: AppSidebarProps) => {
<hr class="border-transparent my-2" />
</div>
+ <FavoritesSection sidebarState={props.sidebarState ?? 'expanded'} />
+
<div class="min-h-0 flex-1 overflow-hidden">
<ChannelsUnreadWidget sidebarState={props.sidebarState ?? 'expanded'} />
</div>
diff --git a/js/app/packages/app/component/command/CommandMenu.tsx b/js/app/packages/app/component/command/CommandMenu.tsx
index db7e84f266..1bb60ee4f6 100644
--- a/js/app/packages/app/component/command/CommandMenu.tsx
+++ b/js/app/packages/app/component/command/CommandMenu.tsx
@@ -226,6 +226,9 @@ export function CommandMenuInner(props: {
);
CommandState.setQuery('');
CommandState.setCommandScopeCommands(nestedCommands);
+ CommandState.activateCommandScopePlaceholder(
+ command.activateCommandScopeId
+ );
CommandState.setSelectedIndex(0);
return;
}
@@ -520,6 +523,11 @@ export function CommandMenuInner(props: {
if (!isInCommandScope()) return;
CommandState.clearCommandScopeCommands();
CommandState.setSelectedIndex(0);
+ // Match the Escape/Backspace handlers: restore the menu's hotkey scope.
+ // Clicking the back button doesn't focus it in some browsers, so without
+ // this the sub-view's command scope stays active and stray keypresses
+ // (e.g. digits) would be routed to it.
+ setActiveScope(hotkeyScope);
};
const resultsHeight = () => {
@@ -562,7 +570,10 @@ export function CommandMenuInner(props: {
<input
type="text"
class="flex-1 bg-transparent border-0 outline-none focus:outline-none ring-0 focus:ring-0 text-ink-muted placeholder:text-ink-placeholder"
- placeholder={isEntityActionMode() ? 'Search actions...' : 'Search...'}
+ placeholder={
+ CommandState.commandScopePlaceholder() ??
+ (isEntityActionMode() ? 'Search actions...' : 'Search...')
+ }
value={CommandState.query()}
onInput={(e) => CommandState.setQuery(e.currentTarget.value)}
autofocus
diff --git a/js/app/packages/app/component/command/FavoritesCommands.tsx b/js/app/packages/app/component/command/FavoritesCommands.tsx
new file mode 100644
index 0000000000..dadb300ace
--- /dev/null
+++ b/js/app/packages/app/component/command/FavoritesCommands.tsx
@@ -0,0 +1,115 @@
+import {
+ favoriteDisplayName,
+ favoriteIconType,
+ favoriteSplitContent,
+} from '@app/util/favorites';
+import { EntityIcon } from '@core/component/EntityIcon';
+import { registerScope } from '@core/hotkey/utils';
+import Star from '@phosphor/star.svg';
+import { useFavoritesData } from '@queries/favorites/favorites';
+import type { Favorite } from '@service-storage/generated/schemas/favorite';
+import { createHotkeyGroup, registerHotkey } from 'core/hotkey/hotkeys';
+import { createEffect, onCleanup } from 'solid-js';
+import { useSplitLayout } from '../split-layout/layout';
+import { CommandState } from './state';
+
+/** Command scope for the favorites sub-view of the command menu. */
+export const FAVORITES_COMMAND_SCOPE = 'command-scope-favorites';
+
+registerScope({
+ parentScopeId: 'global',
+ scopeId: FAVORITES_COMMAND_SCOPE,
+ type: 'command',
+});
+
+const FAVORITES_KEYWORDS = ['favorites', 'favorite', 'starred', 'pinned'];
+
+/**
+ * Registers the "Favorites" command-menu command and keeps the per-favorite
+ * commands in its sub-view scope in sync with the favorites data. Renders
+ * nothing.
+ */
+export function FavoritesCommands() {
+ // Non-suspending accessor: command `condition()`s are evaluated during the
+ // command menu's setup under a Suspense boundary, where a pending or failed
+ // favorites query must not suspend or throw.
+ const favoritesData = useFavoritesData();
+ const { openWithSplit } = useSplitLayout();
+
+ const openFavorite = (favorite: Favorite) => {
+ openWithSplit(favoriteSplitContent(favorite), {
+ referredFrom: 'kommand-menu',
+ });
+ // Close the menu and clear the query once a favorite is opened.
+ CommandState.close();
+ CommandState.setQuery('');
+ };
+
+ const staticGroup = createHotkeyGroup();
+ const dynamicGroup = createHotkeyGroup();
+
+ staticGroup.addDisposer(
+ CommandState.registerCommandScopePlaceholder(
+ FAVORITES_COMMAND_SCOPE,
+ 'Open favorite...'
+ )
+ );
+
+ staticGroup.add(
+ registerHotkey({
+ scopeId: 'global',
+ description: 'Favorites',
+ // An empty sub-view is a dead end, so hide the command until the user
+ // has favorites.
+ condition: () => (favoritesData()?.favorites.length ?? 0) > 0,
+ keyDownHandler: () => true,
+ activateCommandScopeId: FAVORITES_COMMAND_SCOPE,
+ keywords: FAVORITES_KEYWORDS,
+ icon: Star,
+ })
+ );
+
+ const registerFavorites = (list: Favorite[]) => {
+ // Registered without a hotkey: bare digits would fight type-to-filter in
+ // the sub-view's search input. The entries are still listed and openable
+ // via arrow/enter or click (the handler runs with `e` undefined).
+ // `runWithInputFocused` is required even without a hotkey: entering the
+ // sub-view captures its commands while the menu's search input has focus,
+ // and the capture filter drops commands without this flag.
+ list.forEach((favorite) => {
+ dynamicGroup.add(
+ registerHotkey({
+ scopeId: FAVORITES_COMMAND_SCOPE,
+ description: favoriteDisplayName(favorite),
+ keyDownHandler: () => {
+ openFavorite(favorite);
+ return true;
+ },
+ commandPaletteIcon: (props) => (
+ <EntityIcon
+ targetType={favoriteIconType(favorite)}
+ class={props.class}
+ />
+ ),
+ runWithInputFocused: true,
+ })
+ );
+ });
+ };
+
+ // Hotkey registrations are non-reactive, so sync them with the favorites
+ // data: dispose and re-register the per-favorite commands on every change.
+ createEffect(() => {
+ const data = favoritesData();
+ dynamicGroup.dispose();
+ if (!data) return;
+ registerFavorites(data.favorites);
+ });
+
+ onCleanup(() => {
+ dynamicGroup.dispose();
+ staticGroup.dispose();
+ });
+
+ return null;
+}
diff --git a/js/app/packages/app/component/command/state.ts b/js/app/packages/app/component/command/state.ts
index 017e9eae13..69198cf65e 100644
--- a/js/app/packages/app/component/command/state.ts
+++ b/js/app/packages/app/component/command/state.ts
@@ -36,6 +36,14 @@ interface ICommandState {
clearCommandScopeCommands: () => void;
isInCommandScope: Accessor<boolean>;
+ /** input placeholder while a command scope is active */
+ commandScopePlaceholder: Accessor<string | undefined>;
+ registerCommandScopePlaceholder: (
+ scopeId: string,
+ placeholder: string
+ ) => () => void;
+ activateCommandScopePlaceholder: (scopeId: string) => void;
+
/** entity action mode (for selection modification commands) */
entityActionEntities: Accessor<EntityData[]>;
setEntityActionEntities: Setter<EntityData[]>;
@@ -66,6 +74,25 @@ function createCommandState(): ICommandState {
EntityData[]
>([]);
+ /** Optional input placeholders for command scopes, keyed by scope id. */
+ const commandScopePlaceholders = new Map<string, string>();
+ const [commandScopePlaceholder, setCommandScopePlaceholder] =
+ createSignal<string>();
+
+ function registerCommandScopePlaceholder(
+ scopeId: string,
+ placeholder: string
+ ) {
+ commandScopePlaceholders.set(scopeId, placeholder);
+ return () => {
+ commandScopePlaceholders.delete(scopeId);
+ };
+ }
+
+ function activateCommandScopePlaceholder(scopeId: string) {
+ setCommandScopePlaceholder(commandScopePlaceholders.get(scopeId));
+ }
+
function toggle() {
setIsOpen((prev) => !prev);
}
@@ -92,6 +119,7 @@ function createCommandState(): ICommandState {
function clearCommandScopeCommands() {
setCommandScopeCommands([]);
+ setCommandScopePlaceholder(undefined);
}
function isInCommandScope() {
@@ -161,6 +189,10 @@ function createCommandState(): ICommandState {
clearCommandScopeCommands,
isInCommandScope,
+ commandScopePlaceholder,
+ registerCommandScopePlaceholder,
+ activateCommandScopePlaceholder,
+
entityActionEntities,
setEntityActionEntities,
clearEntityActionEntities,
diff --git a/js/app/packages/app/component/next-soup/actions/index.ts b/js/app/packages/app/component/next-soup/actions/index.ts
index 44728348ce..280a4d4a85 100644
--- a/js/app/packages/app/component/next-soup/actions/index.ts
+++ b/js/app/packages/app/component/next-soup/actions/index.ts
@@ -4,6 +4,7 @@ export { makeCopyBranchNameAction } from './make-copy-branch-name-action';
export { makeCopyEntityIdAction } from './make-copy-entity-id-action';
export { makeCopyLinkAction } from './make-copy-link-action';
export { makeDeleteAction } from './make-delete-action';
+export { makeFavoriteAction } from './make-favorite-action';
export { makeHideCompanyAction } from './make-hide-company-action';
export { makeMarkDoneAction } from './make-mark-done-action';
export { makeMarkSenderSignalAction } from './make-mark-sender-important-action';
diff --git a/js/app/packages/app/component/next-soup/actions/make-favorite-action.ts b/js/app/packages/app/component/next-soup/actions/make-favorite-action.ts
new file mode 100644
index 0000000000..d41618f8a4
--- /dev/null
+++ b/js/app/packages/app/component/next-soup/actions/make-favorite-action.ts
@@ -0,0 +1,91 @@
+import { toast } from '@core/component/Toast/Toast';
+import type { EntityData } from '@entity';
+import {
+ favoriteEntityType,
+ useAddFavoriteMutation,
+ useFavoritesData,
+ useRemoveFavoriteMutation,
+} from '@queries/favorites/favorites';
+import type { SoupState } from '../create-soup-state';
+
+/**
+ * Toggle an entity in the user's favorites.
+ *
+ * `execute` favorites every entity that is not yet favorited; when all of them
+ * already are, it unfavorites them instead.
+ */
+export const makeFavoriteAction = () => {
+ // Non-suspending accessor: isFavorited runs inside command-menu
+ // description()/condition() callbacks, where a pending or failed favorites
+ // query must not suspend or throw.
+ const favoritesData = useFavoritesData();
+ const addMutation = useAddFavoriteMutation();
+ const removeMutation = useRemoveFavoriteMutation();
+
+ const canExecute = (entity: EntityData): boolean =>
+ favoriteEntityType(entity.type) !== undefined;
+
+ const isFavorited = (entity: EntityData): boolean => {
+ const type = favoriteEntityType(entity.type);
+ if (!type) return false;
+ const favorites = favoritesData()?.favorites;
+ if (!favorites) return false;
+ return favorites.some(
+ (favorite) =>
+ favorite.entityType === type && favorite.entityId === entity.id
+ );
+ };
+
+ const execute = async (entities: EntityData[]) => {
+ const favoritable = entities.filter(canExecute);
+ if (favoritable.length === 0) return;
+ // Ignore re-triggers while a toggle is still settling so a rapid
+ // double-press can't fire an add and its own remove against each other.
+ if (addMutation.isPending || removeMutation.isPending) return;
+
+ const shouldRemove = favoritable.every((entity) => isFavorited(entity));
+ const verb = shouldRemove ? 'Removed' : 'Added';
+ const preposition = shouldRemove ? 'from' : 'to';
+
+ // On add, skip entities already favorited so counts reflect real work.
+ const targets = shouldRemove
+ ? favoritable
+ : favoritable.filter((entity) => !isFavorited(entity));
+ if (targets.length === 0) return;
+
+ const results = await Promise.allSettled(
+ targets.map((entity) => {
+ const entityType = favoriteEntityType(entity.type)!;
+ const args = { entityType, entityId: entity.id };
+ return shouldRemove
+ ? removeMutation.mutateAsync(args)
+ : addMutation.mutateAsync(args);
+ })
+ );
+
+ // Each mutation rolls its own optimistic change back on failure, so report
+ // what actually happened rather than an all-or-nothing result.
+ const failed = results.filter((r) => r.status === 'rejected').length;
+ const succeeded = results.length - failed;
+ if (failed === 0) {
+ toast.success(
+ succeeded > 1
+ ? `${verb} ${succeeded} items ${preposition} favorites`
+ : `${verb} ${preposition} favorites`
+ );
+ } else if (succeeded === 0) {
+ toast.failure('Failed to update favorites');
+ } else {
+ toast.failure(
+ `${verb} ${succeeded} of ${results.length} items ${preposition} favorites; ${failed} failed`
+ );
+ }
+ };
+
+ const executeWithSoup = async (entities: EntityData[], _soup: SoupState) => {
+ // Favoriting doesn't change the list contents; keep selection/focus.
+ await execute(entities);
+ };
+
+ return { canExecute, isFavorited, execute, executeWithSoup };
+};
diff --git a/js/app/packages/app/component/next-soup/actions/use-block-entity-commands.ts b/js/app/packages/app/component/next-soup/actions/use-block-entity-commands.ts
index 961fa4e8e2..9302720930 100644
--- a/js/app/packages/app/component/next-soup/actions/use-block-entity-commands.ts
+++ b/js/app/packages/app/component/next-soup/actions/use-block-entity-commands.ts
@@ -22,6 +22,7 @@ import {
makeCopyEntityIdAction,
makeCopyLinkAction,
makeDeleteAction,
+ makeFavoriteAction,
makeMarkDoneAction,
makeMoveToProjectAction,
makeRenameAction,
@@ -54,6 +55,7 @@ export const useBlockEntityCommands = () => {
const copyLinkAction = makeCopyLinkAction();
const copyBranchNameAction = makeCopyBranchNameAction();
const copyEntityIdAction = makeCopyEntityIdAction();
+ const favoriteAction = makeFavoriteAction();
const allProperties = useAllProperties();
@@ -192,6 +194,32 @@ export const useBlockEntityCommands = () => {
tags: [HotkeyTags.SelectionModification],
}).withGroup(group);
+ // Favorite - 'opt+f' (macOS emits 'ƒ'; normalizeEventKeyPress maps it back to 'f')
+ registerHotkey({
+ hotkey: ['opt+f'],
+ hotkeyToken: TOKENS.entity.action.favorite,
+ scopeId,
+ description: () => {
+ const entity = getEntity();
+ return entity && favoriteAction.isFavorited(entity)
+ ? 'Unfavorite'
+ : 'Favorite';
+ },
+ keyDownHandler: () => {
+ const entity = getEntity();
+ if (!entity) return false;
+ if (!favoriteAction.canExecute(entity)) return false;
+ favoriteAction.execute([entity]);
+ return true;
+ },
+ condition: () => {
+ const entity = getEntity();
+ return entity !== undefined && favoriteAction.canExecute(entity);
+ },
+ displayPriority: 10,
+ tags: [HotkeyTags.SelectionModification],
+ }).withGroup(group);
+
registerHotkey({
scopeId,
description: 'Duplicate item',
diff --git a/js/app/packages/app/component/next-soup/actions/use-entity-action-hotkeys.ts b/js/app/packages/app/component/next-soup/actions/use-entity-action-hotkeys.ts
index 6ff03dd038..5a4e4e693a 100644
--- a/js/app/packages/app/component/next-soup/actions/use-entity-action-hotkeys.ts
+++ b/js/app/packages/app/component/next-soup/actions/use-entity-action-hotkeys.ts
@@ -21,6 +21,7 @@ import {
makeCopyEntityIdAction,
makeCopyLinkAction,
makeDeleteAction,
+ makeFavoriteAction,
makeMarkDoneAction,
makeMoveToProjectAction,
makeRenameAction,
@@ -73,6 +74,8 @@ export const useEntityActionHotkeys = (
const shareAction = makeShareAction();
+ const favoriteAction = makeFavoriteAction();
+
const getEntitiesForAction = (): EntityData[] => {
if (
splitHandle?.content().type === 'component' &&
@@ -209,6 +212,35 @@ export const useEntityActionHotkeys = (
tags: [HotkeyTags.SelectionModification],
}).withGroup(group);
+ // Favorite - 'opt+f' (macOS emits 'ƒ'; normalizeEventKeyPress maps it back to 'f')
+ registerHotkey({
+ hotkey: ['opt+f'],
+ hotkeyToken: TOKENS.entity.action.favorite,
+ scopeId,
+ description: () => {
+ const entities = getEntitiesForAction();
+ const allFavorited =
+ entities.length > 0 &&
+ entities.every((entity) => favoriteAction.isFavorited(entity));
+ return allFavorited ? 'Unfavorite' : 'Favorite';
+ },
+ keyDownHandler: () => {
+ const entities = getEntitiesForAction();
+ if (entities.length === 0) return false;
+ if (!entities.every(favoriteAction.canExecute)) return false;
+
+ favoriteAction.executeWithSoup(entities, soup);
+ return true;
+ },
+ condition: () => {
+ if (condition && !condition()) return false;
+ const entities = getEntitiesForAction();
+ return entities.length > 0 && entities.every(favoriteAction.canExecute);
+ },
+ displayPriority: 10,
+ tags: [HotkeyTags.SelectionModification],
+ }).withGroup(group);
+
// Copy - 'cmd+d'
registerHotkey({
hotkey: ['cmd+d'],
diff --git a/js/app/packages/app/component/next-soup/soup-view/create-soup-entity-actions.ts b/js/app/packages/app/component/next-soup/soup-view/create-soup-entity-actions.ts
index 979d82e125..275875d753 100644
--- a/js/app/packages/app/component/next-soup/soup-view/create-soup-entity-actions.ts
+++ b/js/app/packages/app/component/next-soup/soup-view/create-soup-entity-actions.ts
@@ -6,10 +6,12 @@ import { globalSplitManager } from '@app/signal/splitLayout';
import { getChannelParams } from '@block-channel/utils/link';
import { fileTypeToBlockName, itemToBlockName } from '@core/constant/allBlocks';
import { useUserId } from '@core/context/user';
+import { type HotkeyToken, TOKENS } from '@core/hotkey/tokens';
import { isMobile } from '@core/mobile/isMobile';
import type { EntityData } from '@entity';
import { useSetCompanyHiddenMutation } from '@queries/crm/companies';
import { useIsTeamAdmin } from '@queries/team/teams';
+import type { Component, JSX } from 'solid-js';
import {
makeBlockSenderAction,
makeCopyAction,
@@ -17,6 +19,7 @@ import {
makeCopyEntityIdAction,
makeCopyLinkAction,
makeDeleteAction,
+ makeFavoriteAction,
makeHideCompanyAction,
makeMarkDoneAction,
makeMarkSenderNoiseAction,
@@ -37,6 +40,8 @@ const NOISE_TABS = new Set(['noise']);
type SoupEntityActionItem = {
id: string;
label: string;
+ icon?: Component<JSX.SvgSVGAttributes<SVGSVGElement>>;
+ hotkeyToken?: HotkeyToken;
onClick: () => void | Promise<void>;
destructive?: boolean;
};
@@ -77,6 +82,7 @@ export function createSoupEntityActions(): {
});
const copyAction = makeCopyAction();
+ const favoriteAction = makeFavoriteAction();
const moveToProjectAction = makeMoveToProjectAction();
const copyLinkAction = makeCopyLinkAction();
const copyBranchNameAction = makeCopyBranchNameAction();
@@ -224,6 +230,19 @@ export function createSoupEntityActions(): {
});
}
+ if (canExecuteAll(favoriteAction.canExecute)) {
+ const allFavorited = entities.every((entity) =>
+ favoriteAction.isFavorited(entity)
+ );
+ // No icon: the other items in this menu don't have one.
+ middleItems.push({
+ id: 'favorite',
+ label: allFavorited ? 'Unfavorite' : 'Favorite',
+ hotkeyToken: TOKENS.entity.action.favorite,
+ onClick: handle(favoriteAction.executeWithSoup),
+ });
+ }
+
if (canExecuteAll(moveToProjectAction.canExecute)) {
middleItems.push({
id: 'move-to-folder',
diff --git a/js/app/packages/app/component/next-soup/soup-view/soup-entity-actions-menu.tsx b/js/app/packages/app/component/next-soup/soup-view/soup-entity-actions-menu.tsx
index 32b2b775ed..e91b2dfac5 100644
--- a/js/app/packages/app/component/next-soup/soup-view/soup-entity-actions-menu.tsx
+++ b/js/app/packages/app/component/next-soup/soup-view/soup-entity-actions-menu.tsx
@@ -39,6 +39,8 @@ export const SoupEntityActionsMenu = (props: SoupEntityActionsMenuProps) => {
{(action) => (
<MenuItem
text={action.label}
+ icon={action.icon}
+ hotkeyToken={action.hotkeyToken}
onClick={() => handleAction(action.onClick)}
class={action.destructive ? 'text-failure-ink' : undefined}
/>
diff --git a/js/app/packages/app/component/split-layout/components/SplitFileMenu.tsx b/js/app/packages/app/component/split-layout/components/SplitFileMenu.tsx
index f5a4c7aad6..d1d8d2b235 100644
--- a/js/app/packages/app/component/split-layout/components/SplitFileMenu.tsx
+++ b/js/app/packages/app/component/split-layout/components/SplitFileMenu.tsx
@@ -1,19 +1,22 @@
import { openBulkEditModal } from '@app/component/bulk-edit-entity/BulkEditEntityModal';
import { MobileDrawer } from '@app/component/mobile/MobileDrawer';
+import { makeFavoriteAction } from '@app/component/next-soup/actions';
import type { BlockTool } from '@app/component/ResponsiveBlockToolbar';
import { useBlockAliasedName, useBlockName } from '@core/block';
import { useItemOperations } from '@core/component/FileList/useItemOperations';
import { toast } from '@core/component/Toast/Toast';
+import { useQuickAccess } from '@core/context/quickAccess';
import { triggerFocusInput } from '@core/directive/focusInput';
import { isTouchDevice } from '@core/mobile/isTouchDevice';
import { useIsDocumentOwner } from '@core/signal/permissions';
-import { buildEntityData } from '@entity';
+import { buildEntityData, type EntityData } from '@entity';
import DotsThree from '@icon/dots-three-large.svg';
import ArrowRight from '@phosphor/arrow-right.svg';
import CaretDown from '@phosphor/caret-down.svg';
import CaretRight from '@phosphor/caret-right.svg';
import Copy from '@phosphor/copy.svg';
import Rename from '@phosphor/pencil-line.svg';
+import Star from '@phosphor/star.svg';
import Trash from '@phosphor/trash-simple.svg';
import { blockNameToItemType, type ItemType } from '@service-storage/client';
import { cn, Dropdown } from '@ui';
@@ -247,9 +250,36 @@ export function SplitFileMenu(props: {
const [open, setOpen] = createSignal(false);
const itemOperations = useItemOperations();
+ const quickAccess = useQuickAccess();
+ const favoriteAction = makeFavoriteAction();
const { replaceOrInsertSplit, resetSplit } = useSplitLayout();
+ // The entity this menu operates on: prefer the quick-access cache (richer
+ // data, covers channels/calls), fall back to building it from the block's
+ // id/name/blockName like the rename/move ops do.
+ const menuEntity = createMemo<EntityData | undefined>(() => {
+ const item = quickAccess.getById(props.id);
+ if (item?.kind === 'entity') return item.data;
+ return buildEntityData({
+ id: props.id,
+ name: props.name,
+ blockName: aliasedBlockName,
+ });
+ });
+
+ const favoriteOp = (): SplitFileMenuAction | undefined => {
+ const entity = menuEntity();
+ if (!entity || !favoriteAction.canExecute(entity)) return undefined;
+ return {
+ label: favoriteAction.isFavorited(entity) ? 'Unfavorite' : 'Favorite',
+ icon: Star,
+ action: () => {
+ void favoriteAction.execute([entity]);
+ },
+ };
+ };
+
createEffect(() => {
const openMenu = () => setOpen(true);
ctx.setTitleFileMenuTrigger(() => openMenu);
@@ -257,7 +287,8 @@ export function SplitFileMenu(props: {
});
const ops = createMemo<SplitFileMenuAction[]>(() => {
- return props.ops
+ const favorite = favoriteOp();
+ const mapped = props.ops
.map((op) => {
if (isDefaultFileOperation(op)) {
switch (op.op) {
@@ -356,6 +387,7 @@ export function SplitFileMenu(props: {
}
})
.filter((op) => !!op);
+ return favorite ? [favorite, ...mapped] : mapped;
});
const filteredTools = createMemo(() =>
diff --git a/js/app/packages/app/util/favorites.ts b/js/app/packages/app/util/favorites.ts
new file mode 100644
index 0000000000..d93f5b575e
--- /dev/null
+++ b/js/app/packages/app/util/favorites.ts
@@ -0,0 +1,57 @@
+import type { SplitContent } from '@app/component/split-layout/layoutManager';
+import { getChannelParams } from '@block-channel/utils/link';
+import type { EntityIconSelector } from '@core/component/EntityIcon';
+import { getIconConfig } from '@core/component/EntityIcon';
+import { fileTypeToBlockName } from '@core/constant/allBlocks';
+import type { Favorite } from '@service-storage/generated/schemas/favorite';
+
+/** The block to open for a favorite (also its URL type segment). */
+export function favoriteBlockName(favorite: Favorite) {
+ if (favorite.entityType === 'document') {
+ return fileTypeToBlockName(favorite.documentSubType ?? favorite.fileType);
+ }
+ if (favorite.entityType === 'email_thread') return 'email' as const;
+ // Passes chat/channel/project/call through and remaps channel_message and
+ // CRM entity types to their block names.
+ return fileTypeToBlockName(favorite.entityType);
+}
+
+/**
+ * The split content that opens a favorite. Channel-message favorites open
+ * their owning channel (hydrated as `channelId`) focused on the message.
+ */
+export function favoriteSplitContent(favorite: Favorite): SplitContent {
+ if (favorite.entityType === 'channel_message' && favorite.channelId) {
+ return {
+ type: 'channel',
+ id: favorite.channelId,
+ params: getChannelParams(favorite.entityId),
+ };
+ }
+ return { type: favoriteBlockName(favorite), id: favorite.entityId };
+}
+
+export function favoriteIconType(favorite: Favorite): EntityIconSelector {
+ if (
+ favorite.entityType === 'channel' ||
+ favorite.entityType === 'channel_message'
+ ) {
+ return (favorite.channelType ?? 'channel') as EntityIconSelector;
+ }
+ if (favorite.entityType === 'document') {
+ // icon: true keeps e.g. docx showing the write icon instead of pdf
+ return fileTypeToBlockName(
+ favorite.documentSubType ?? favorite.fileType,
+ true
+ );
+ }
+ return favoriteBlockName(favorite);
+}
+
+export function favoriteDisplayName(favorite: Favorite): string {
+ return (
+ favorite.name?.trim() ||
+ getIconConfig(favoriteIconType(favorite) ?? 'default').prettyName ||
+ 'Untitled'
+ );
+}
diff --git a/js/app/packages/block-canvas/component/CanvasController.tsx b/js/app/packages/block-canvas/component/CanvasController.tsx
index 37cbb538ce..647a76e3c6 100644
--- a/js/app/packages/block-canvas/component/CanvasController.tsx
+++ b/js/app/packages/block-canvas/component/CanvasController.tsx
@@ -930,11 +930,14 @@ export function CanvasController(props: ParentProps) {
};
onDragEnd((event) => {
+ // Only soup entity drags create nodes (not e.g. sidebar favorite drags).
+ if (event.draggable?.data.dragType !== 'entity') return;
if (event.droppable?.id !== 'canvas-input-' + _id) return;
dndDragEnd(event as EntityDragEvent);
});
onDragMove((event) => {
+ if (event.draggable?.data.dragType !== 'entity') return;
dndDragMove(event as EntityDragEvent);
});
diff --git a/js/app/packages/block-md/component/MarkdownEditor.tsx b/js/app/packages/block-md/component/MarkdownEditor.tsx
index 2bce868117..334ef3e90d 100644
--- a/js/app/packages/block-md/component/MarkdownEditor.tsx
+++ b/js/app/packages/block-md/component/MarkdownEditor.tsx
@@ -414,10 +414,13 @@ export function MarkdownEditor(props: {
}, 60);
onDragEnd((event: EntityDragEvent) => {
+ // Only soup entity drags insert mentions (not e.g. sidebar favorite drags).
+ if (event.draggable?.data.dragType !== 'entity') return;
dndDragEnd(event);
});
onDragMove((event: EntityDragEvent) => {
+ if (event.draggable?.data.dragType !== 'entity') return;
dndDragMove(event);
});
diff --git a/js/app/packages/core/hotkey/hotkeys.ts b/js/app/packages/core/hotkey/hotkeys.ts
index 3f4f5e2551..ea1ecc4eed 100644
--- a/js/app/packages/core/hotkey/hotkeys.ts
+++ b/js/app/packages/core/hotkey/hotkeys.ts
@@ -301,18 +301,30 @@ export function registerHotkey(
// Remove this specific command from scope's hotkey handlers
const scope = hotkeyScopeTree.get(scopeId);
- if (scope && hotkeys) {
- hotkeys.forEach((h) => {
- const existingHandlers = scope.hotkeyCommands.get(h);
- if (existingHandlers) {
- const newHandlers = existingHandlers.filter((c) => c !== command);
- if (newHandlers.length > 0) {
- scope.hotkeyCommands.set(h, newHandlers);
- } else {
- scope.hotkeyCommands.delete(h);
+ if (scope) {
+ if (hotkeys) {
+ hotkeys.forEach((h) => {
+ const existingHandlers = scope.hotkeyCommands.get(h);
+ if (existingHandlers) {
+ const newHandlers = existingHandlers.filter((c) => c !== command);
+ if (newHandlers.length > 0) {
+ scope.hotkeyCommands.set(h, newHandlers);
+ } else {
+ scope.hotkeyCommands.delete(h);
+ }
}
+ });
+ } else {
+ // Unkeyed commands are pushed onto `unkeyedCommands` at registration
+ // (see above). Without this branch they leaked until the whole scope
+ // was removed — re-registering unkeyed commands (e.g. per-favorite
+ // command-menu entries) grew the list unboundedly and left ghost
+ // rows for removed/renamed entries.
+ const idx = scope.unkeyedCommands.indexOf(command);
+ if (idx !== -1) {
+ scope.unkeyedCommands.splice(idx, 1);
}
- });
+ }
}
// Remove command scope only if we created it (not if we're using a shared one)
diff --git a/js/app/packages/core/hotkey/tokens.ts b/js/app/packages/core/hotkey/tokens.ts
index 776d05d49c..83cece5934 100644
--- a/js/app/packages/core/hotkey/tokens.ts
+++ b/js/app/packages/core/hotkey/tokens.ts
@@ -54,6 +54,7 @@ export const TOKENS = {
share: 'entity.action.share',
copyBranchName: 'entity.action.copyBranchName',
copyEntityId: 'entity.action.copyEntityId',
+ favorite: 'entity.action.favorite',
properties: 'entity.action.properties',
priority: 'entity.action.priority',
status: 'entity.action.status',
diff --git a/js/app/packages/queries/favorites/favorites.ts b/js/app/packages/queries/favorites/favorites.ts
new file mode 100644
index 0000000000..189dd5780a
--- /dev/null
+++ b/js/app/packages/queries/favorites/favorites.ts
@@ -0,0 +1,278 @@
+import { throwOnErr } from '@core/util/result';
+import type { EntityData } from '@entity';
+import { storageServiceClient } from '@service-storage/client';
+import type { AddFavoriteRequest } from '@service-storage/generated/schemas/addFavoriteRequest';
+import type { Favorite } from '@service-storage/generated/schemas/favorite';
+import type { FavoritesList } from '@service-storage/generated/schemas/favoritesList';
+import { useMutation, useQuery } from '@tanstack/solid-query';
+import type { Accessor } from 'solid-js';
+
+import { queryClient } from '../client';
+import { type MutationCallbacks, withCallbacks } from '../utils';
+
+import { favoriteKeys } from './keys';
+
+export type FavoriteEntityType = AddFavoriteRequest['entityType'];
+
+/**
+ * Maps a frontend entity to the backend favorites entity type, or undefined
+ * for entity kinds that cannot be favorited.
+ */
+export function favoriteEntityType(
+ type: EntityData['type']
+): FavoriteEntityType | undefined {
+ switch (type) {
+ case 'document':
+ return 'document';
+ case 'chat':
+ return 'chat';
+ case 'project':
+ return 'project';
+ case 'email':
+ return 'email_thread';
+ case 'channel':
+ return 'channel';
+ // Individual channel messages/threads are intentionally not favoritable:
+ // their frontend id is a composite `channelId:messageId` that never
+ // hydrates or navigates, and the entity-access layer has no access level
+ // for a message, so a message favorite can't be authorized like every
+ // other type. Favorite the channel instead.
+ case 'call':
+ return 'call';
+ case 'crm_company':
+ return 'crm_company';
+ case 'crm_contact':
+ return 'crm_contact';
+ default:
+ return undefined;
+ }
+}
+
+export function favoriteEntityKey(
+ entityType: FavoriteEntityType,
+ entityId: string
+): string {
+ return `${entityType}:${entityId}`;
+}
+
+/** The user's favorites. */
+export function useFavoritesQuery() {
+ return useQuery(() => ({
+ queryKey: favoriteKeys.list.queryKey,
+ queryFn: async () =>
+ await throwOnErr(() => storageServiceClient.favorites.getFavorites()),
+ staleTime: 60_000,
+ }));
+}
+
+/**
+ * Non-suspending, non-throwing view of the favorites list.
+ *
+ * Reading `query.data` off the solid-query proxy suspends the nearest
+ * Suspense boundary while the query is pending and throws once it errors.
+ * Favorites are read from broad surfaces (command menu conditions and
+ * descriptions, the sidebar, context menus) where a slow or failing
+ * favorites request must never take the surface down. Gating on `isSuccess`
+ * keeps the read reactive without either behavior; callers see `undefined`
+ * until the list has loaded.
+ */
+export function useFavoritesData(): Accessor<FavoritesList | undefined> {
+ const query = useFavoritesQuery();
+ return () => (query.isSuccess ? query.data : undefined);
+}
+
+function readList(): FavoritesList | undefined {
+ return queryClient.getQueryData<FavoritesList>(favoriteKeys.list.queryKey);
+}
+
+function writeList(update: (prev: FavoritesList) => FavoritesList) {
+ queryClient.setQueryData<FavoritesList>(favoriteKeys.list.queryKey, (prev) =>
+ prev ? update(prev) : prev
+ );
+}
+
+export function invalidateFavorites() {
+ return queryClient.invalidateQueries({
+ queryKey: favoriteKeys.list.queryKey,
+ });
+}
+
+type FavoriteMutationContext = { rollback: () => void };
+
+type AddFavoriteArgs = AddFavoriteRequest;
+type AddFavoriteCallbacks = MutationCallbacks<
+ Favorite,
+ Error,
+ AddFavoriteArgs,
+ FavoriteMutationContext
+>;
+
+export function useAddFavoriteMutation(callbacks?: AddFavoriteCallbacks) {
+ return useMutation(() => ({
+ mutationFn: async (args: AddFavoriteArgs) =>
+ await throwOnErr(() => storageServiceClient.favorites.addFavorite(args)),
+ ...withCallbacks<Favorite, Error, AddFavoriteArgs, FavoriteMutationContext>(
+ {
+ onMutate: async (args: AddFavoriteArgs) => {
+ await queryClient.cancelQueries({
+ queryKey: favoriteKeys.list.queryKey,
+ });
+ const previous = readList();
+ const optimistic: Favorite = {
+ entityType: args.entityType,
+ entityId: args.entityId,
+ sortOrder: Number.MAX_SAFE_INTEGER,
+ createdAt: new Date().toISOString(),
+ };
+ writeList((prev) => ({
+ ...prev,
+ favorites: [...prev.favorites, optimistic],
+ }));
+ return {
+ rollback: () => {
+ if (previous) {
+ queryClient.setQueryData(favoriteKeys.list.queryKey, previous);
+ }
+ },
+ };
+ },
+ onError: (_error, _args, context) => {
+ context?.rollback();
+ },
+ onSettled: () => invalidateFavorites(),
+ },
+ callbacks
+ ),
+ }));
+}
+
+type RemoveFavoriteArgs = {
+ entityType: FavoriteEntityType;
+ entityId: string;
+};
+type RemoveFavoriteCallbacks = MutationCallbacks<
+ void,
+ Error,
+ RemoveFavoriteArgs,
+ FavoriteMutationContext
+>;
+
+export function useRemoveFavoriteMutation(callbacks?: RemoveFavoriteCallbacks) {
+ return useMutation(() => ({
+ mutationFn: async (args: RemoveFavoriteArgs) => {
+ await throwOnErr(() =>
+ storageServiceClient.favorites.removeFavoriteByEntity(args)
+ );
+ },
+ ...withCallbacks<void, Error, RemoveFavoriteArgs, FavoriteMutationContext>(
+ {
+ onMutate: async (args: RemoveFavoriteArgs) => {
+ await queryClient.cancelQueries({
+ queryKey: favoriteKeys.list.queryKey,
+ });
+ const previous = readList();
+ const keep = (favorite: Favorite) =>
+ !(
+ favorite.entityType === args.entityType &&
+ favorite.entityId === args.entityId
+ );
+ writeList((prev) => ({
+ ...prev,
+ favorites: prev.favorites.filter(keep),
+ }));
+ return {
+ rollback: () => {
+ if (previous) {
+ queryClient.setQueryData(favoriteKeys.list.queryKey, previous);
+ }
+ },
+ };
+ },
+ onError: (_error, _args, context) => {
+ context?.rollback();
+ },
+ onSettled: () => invalidateFavorites(),
+ },
+ callbacks
+ ),
+ }));
+}
+
+type ReorderFavoritesArgs = {
+ /** The user's favorited entities in the desired order. */
+ favorites: { entityType: FavoriteEntityType; entityId: string }[];
+};
+type ReorderFavoritesCallbacks = MutationCallbacks<
+ void,
+ Error,
+ ReorderFavoritesArgs,
+ FavoriteMutationContext
+>;
+
+export function useReorderFavoritesMutation(
+ callbacks?: ReorderFavoritesCallbacks
+) {
+ return useMutation(() => ({
+ mutationFn: async (args: ReorderFavoritesArgs) => {
+ // Entities the user has not favorited (e.g. an optimistic row whose add
+ // is still in flight) are ignored by the backend.
+ if (args.favorites.length === 0) return;
+ await throwOnErr(() =>
+ storageServiceClient.favorites.reorderFavorites({
+ favorites: args.favorites,
+ })
+ );
+ },
+ ...withCallbacks<
+ void,
+ Error,
+ ReorderFavoritesArgs,
+ FavoriteMutationContext
+ >(
+ {
+ onMutate: async (args: ReorderFavoritesArgs) => {
+ await queryClient.cancelQueries({
+ queryKey: favoriteKeys.list.queryKey,
+ });
+ const previous = readList();
+ const reorder = (favorites: Favorite[]) => {
+ const byKey = new Map(
+ favorites.map((f) => [
+ favoriteEntityKey(f.entityType, f.entityId),
+ f,
+ ])
+ );
+ const orderedKeys = args.favorites.map((f) =>
+ favoriteEntityKey(f.entityType, f.entityId)
+ );
+ const ordered = orderedKeys
+ .map((key) => byKey.get(key))
+ .filter((f): f is Favorite => !!f);
+ const orderedSet = new Set(orderedKeys);
+ const leftover = favorites.filter(
+ (f) =>
+ !orderedSet.has(favoriteEntityKey(f.entityType, f.entityId))
+ );
+ return [...ordered, ...leftover];
+ };
+ writeList((prev) => ({
+ ...prev,
+ favorites: reorder(prev.favorites),
+ }));
+ return {
+ rollback: () => {
+ if (previous) {
+ queryClient.setQueryData(favoriteKeys.list.queryKey, previous);
+ }
+ },
+ };
+ },
+ onError: (_error, _args, context) => {
+ context?.rollback();
+ },
+ onSettled: () => invalidateFavorites(),
+ },
+ callbacks
+ ),
+ }));
+}
diff --git a/js/app/packages/queries/favorites/keys.ts b/js/app/packages/queries/favorites/keys.ts
new file mode 100644
index 0000000000..34cbc30725
--- /dev/null
+++ b/js/app/packages/queries/favorites/keys.ts
@@ -0,0 +1,5 @@
+import { createQueryKeys } from '@lukemorales/query-key-factory';
+
+export const favoriteKeys = createQueryKeys('favorites', {
+ list: null,
+});
diff --git a/js/app/packages/service-clients/service-storage/client.ts b/js/app/packages/service-clients/service-storage/client.ts
index bafd31de47..a4835b63b6 100644
--- a/js/app/packages/service-clients/service-storage/client.ts
+++ b/js/app/packages/service-clients/service-storage/client.ts
@@ -32,7 +32,10 @@ import { err, ok, type Result } from 'neverthrow';
import type { ApiChannelWithLatest } from './channel-list-types';
import type {
AccessLevel,
+ AddFavoriteRequest,
CallRecordPreview,
+ Favorite,
+ FavoritesList,
ForeignEntity,
GithubPullRequestsResponse,
GroupedSoupGroupPage,
@@ -43,6 +46,7 @@ import type {
PostGroupedSoupAstRequest,
PostSoupAstRequest,
PostSoupRequest,
+ ReorderFavoritesRequest,
SoupPage,
View,
ViewsResponse,
@@ -2095,6 +2099,33 @@ export const storageServiceClient = {
});
},
},
+
+ favorites: {
+ async getFavorites() {
+ return await dssFetch<FavoritesList>('/favorites');
+ },
+ async addFavorite(params: AddFavoriteRequest) {
+ return await dssFetch<Favorite>('/favorites', {
+ method: 'POST',
+ body: JSON.stringify(params),
+ });
+ },
+ async removeFavoriteByEntity(params: {
+ entityType: AddFavoriteRequest['entityType'];
+ entityId: string;
+ }) {
+ return await dssFetch(
+ `/favorites/${params.entityType}/${encodeURIComponent(params.entityId)}`,
+ { method: 'DELETE' }
+ );
+ },
+ async reorderFavorites(params: ReorderFavoritesRequest) {
+ return await dssFetch('/favorites/reorder', {
+ method: 'PATCH',
+ body: JSON.stringify(params),
+ });
+ },
+ },
async editThread(params) {
const { threadId, ...body } = params;
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/addFavoriteRequest.ts b/js/app/packages/service-clients/service-storage/generated/schemas/addFavoriteRequest.ts
new file mode 100644
index 0000000000..cb4acb62d9
--- /dev/null
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/addFavoriteRequest.ts
@@ -0,0 +1,17 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { AddFavoriteRequestEntityType } from './addFavoriteRequestEntityType';
+
+/**
+ * Request body for favoriting an entity.
+ */
+export interface AddFavoriteRequest {
+ /** The id of the entity to favorite. */
+ entityId: string;
+ /** The type of the entity to favorite. */
+ entityType: AddFavoriteRequestEntityType;
+}
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/addFavoriteRequestEntityType.ts b/js/app/packages/service-clients/service-storage/generated/schemas/addFavoriteRequestEntityType.ts
new file mode 100644
index 0000000000..8b1331a32d
--- /dev/null
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/addFavoriteRequestEntityType.ts
@@ -0,0 +1,24 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * The type of the entity to favorite.
+ */
+export type AddFavoriteRequestEntityType =
+ | 'user'
+ | 'chat'
+ | 'channel'
+ | 'channel_message'
+ | 'document'
+ | 'project'
+ | 'email_thread'
+ | 'team'
+ | 'call'
+ | 'foreign_entity'
+ | 'static_file'
+ | 'crm_company'
+ | 'crm_contact';
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/favorite.ts b/js/app/packages/service-clients/service-storage/generated/schemas/favorite.ts
new file mode 100644
index 0000000000..76994c720a
--- /dev/null
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/favorite.ts
@@ -0,0 +1,40 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { FavoriteChannelId } from './favoriteChannelId';
+import type { FavoriteChannelType } from './favoriteChannelType';
+import type { FavoriteDocumentSubType } from './favoriteDocumentSubType';
+import type { FavoriteEntityType } from './favoriteEntityType';
+import type { FavoriteFileType } from './favoriteFileType';
+import type { FavoriteName } from './favoriteName';
+
+/**
+ * A single favorited entity, including display metadata hydrated from the
+favorited entity where available.
+
+A favorite is identified by `(entity_type, entity_id)` within the user's
+collection; there is no surrogate id.
+ */
+export interface Favorite {
+ /** Owning channel id of the favorited channel message, when applicable. */
+ channelId?: FavoriteChannelId;
+ /** Channel type (e.g. `public`, `direct_message`) of the favorited channel, when applicable. */
+ channelType?: FavoriteChannelType;
+ /** When the favorite was created. */
+ createdAt: string;
+ /** Document sub type (e.g. `task`) of the favorited document, when applicable. */
+ documentSubType?: FavoriteDocumentSubType;
+ /** The id of the favorited entity. */
+ entityId: string;
+ /** The type of the favorited entity. */
+ entityType: FavoriteEntityType;
+ /** File type of the favorited document, when applicable. */
+ fileType?: FavoriteFileType;
+ /** Display name of the favorited entity, when it could be resolved. */
+ name?: FavoriteName;
+ /** Manual ordering value; lower sorts first. */
+ sortOrder: number;
+}
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/favoriteChannelId.ts b/js/app/packages/service-clients/service-storage/generated/schemas/favoriteChannelId.ts
new file mode 100644
index 0000000000..01b559eaaa
--- /dev/null
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/favoriteChannelId.ts
@@ -0,0 +1,11 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Owning channel id of the favorited channel message, when applicable.
+ */
+export type FavoriteChannelId = string | null;
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/favoriteChannelType.ts b/js/app/packages/service-clients/service-storage/generated/schemas/favoriteChannelType.ts
new file mode 100644
index 0000000000..43eba9e1ad
--- /dev/null
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/favoriteChannelType.ts
@@ -0,0 +1,11 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Channel type (e.g. `public`, `direct_message`) of the favorited channel, when applicable.
+ */
+export type FavoriteChannelType = string | null;
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/favoriteDocumentSubType.ts b/js/app/packages/service-clients/service-storage/generated/schemas/favoriteDocumentSubType.ts
new file mode 100644
index 0000000000..f326010edc
--- /dev/null
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/favoriteDocumentSubType.ts
@@ -0,0 +1,11 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Document sub type (e.g. `task`) of the favorited document, when applicable.
+ */
+export type FavoriteDocumentSubType = string | null;
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/favoriteEntityRef.ts b/js/app/packages/service-clients/service-storage/generated/schemas/favoriteEntityRef.ts
new file mode 100644
index 0000000000..e3126d6bf2
--- /dev/null
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/favoriteEntityRef.ts
@@ -0,0 +1,17 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { FavoriteEntityRefEntityType } from './favoriteEntityRefEntityType';
+
+/**
+ * A reference to a favorited entity.
+ */
+export interface FavoriteEntityRef {
+ /** The id of the favorited entity. */
+ entityId: string;
+ /** The type of the favorited entity. */
+ entityType: FavoriteEntityRefEntityType;
+}
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/favoriteEntityRefEntityType.ts b/js/app/packages/service-clients/service-storage/generated/schemas/favoriteEntityRefEntityType.ts
new file mode 100644
index 0000000000..168e934f19
--- /dev/null
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/favoriteEntityRefEntityType.ts
@@ -0,0 +1,24 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * The type of the favorited entity.
+ */
+export type FavoriteEntityRefEntityType =
+ | 'user'
+ | 'chat'
+ | 'channel'
+ | 'channel_message'
+ | 'document'
+ | 'project'
+ | 'email_thread'
+ | 'team'
+ | 'call'
+ | 'foreign_entity'
+ | 'static_file'
+ | 'crm_company'
+ | 'crm_contact';
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/favoriteEntityType.ts b/js/app/packages/service-clients/service-storage/generated/schemas/favoriteEntityType.ts
new file mode 100644
index 0000000000..c02044c12f
--- /dev/null
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/favoriteEntityType.ts
@@ -0,0 +1,24 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * The type of the favorited entity.
+ */
+export type FavoriteEntityType =
+ | 'user'
+ | 'chat'
+ | 'channel'
+ | 'channel_message'
+ | 'document'
+ | 'project'
+ | 'email_thread'
+ | 'team'
+ | 'call'
+ | 'foreign_entity'
+ | 'static_file'
+ | 'crm_company'
+ | 'crm_contact';
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/favoriteFileType.ts b/js/app/packages/service-clients/service-storage/generated/schemas/favoriteFileType.ts
new file mode 100644
index 0000000000..cec80c2b05
--- /dev/null
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/favoriteFileType.ts
@@ -0,0 +1,11 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * File type of the favorited document, when applicable.
+ */
+export type FavoriteFileType = string | null;
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/favoriteName.ts b/js/app/packages/service-clients/service-storage/generated/schemas/favoriteName.ts
new file mode 100644
index 0000000000..f49e328d57
--- /dev/null
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/favoriteName.ts
@@ -0,0 +1,11 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Display name of the favorited entity, when it could be resolved.
+ */
+export type FavoriteName = string | null;
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/favoritesList.ts b/js/app/packages/service-clients/service-storage/generated/schemas/favoritesList.ts
new file mode 100644
index 0000000000..46598c987d
--- /dev/null
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/favoritesList.ts
@@ -0,0 +1,15 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { Favorite } from './favorite';
+
+/**
+ * The user's favorites, in manual order.
+ */
+export interface FavoritesList {
+ /** The requesting user's favorites, in manual order. */
+ favorites: Favorite[];
+}
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/index.ts b/js/app/packages/service-clients/service-storage/generated/schemas/index.ts
index 1bb6a959c9..a1d209517e 100644
--- a/js/app/packages/service-clients/service-storage/generated/schemas/index.ts
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/index.ts
@@ -10,6 +10,8 @@ export * from './activity';
export * from './activityOneOf';
export * from './activityOneOfTwo';
export * from './activityType';
+export * from './addFavoriteRequest';
+export * from './addFavoriteRequestEntityType';
export * from './addParticipantsRequest';
export * from './addPinRequest';
export * from './anchor';
@@ -500,6 +502,16 @@ export * from './errorResponse';
export * from './excludeDefaultViewRequest';
export * from './excludedDefaultView';
export * from './exportDocumentResponse';
+export * from './favorite';
+export * from './favoriteChannelId';
+export * from './favoriteChannelType';
+export * from './favoriteDocumentSubType';
+export * from './favoriteEntityRef';
+export * from './favoriteEntityRefEntityType';
+export * from './favoriteEntityType';
+export * from './favoriteFileType';
+export * from './favoriteName';
+export * from './favoritesList';
export * from './fileSystemNodeWithIds';
export * from './fileSystemNodeWithIdsOneOf';
export * from './fileSystemNodeWithIdsOneOfThree';
@@ -790,6 +802,7 @@ export * from './propertyValueOneOfType';
export * from './reactionAction';
export * from './recentlyDeletedResponseData';
export * from './removeParticipantsRequest';
+export * from './reorderFavoritesRequest';
export * from './reorderPinRequest';
export * from './ringStatus';
export * from './ringStatusResponse';
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/reorderFavoritesRequest.ts b/js/app/packages/service-clients/service-storage/generated/schemas/reorderFavoritesRequest.ts
new file mode 100644
index 0000000000..2a2e9f58f3
--- /dev/null
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/reorderFavoritesRequest.ts
@@ -0,0 +1,15 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { FavoriteEntityRef } from './favoriteEntityRef';
+
+/**
+ * Request body for reordering favorites.
+ */
+export interface ReorderFavoritesRequest {
+ /** The user's favorited entities in the desired order. */
+ favorites: FavoriteEntityRef[];
+}
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/soupApiItemAllOf.ts b/js/app/packages/service-clients/service-storage/generated/schemas/soupApiItemAllOf.ts
index 68c3556451..575581f395 100644
--- a/js/app/packages/service-clients/service-storage/generated/schemas/soupApiItemAllOf.ts
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/soupApiItemAllOf.ts
@@ -7,4 +7,6 @@
export type SoupApiItemAllOf = {
frecency_score: number;
+ /** Whether the requesting user has favorited this entity. */
+ is_favorited: boolean;
};
diff --git a/js/app/packages/service-clients/service-storage/generated/zod.ts b/js/app/packages/service-clients/service-storage/generated/zod.ts
index c08e2f19e8..5096a09534 100644
--- a/js/app/packages/service-clients/service-storage/generated/zod.ts
+++ b/js/app/packages/service-clients/service-storage/generated/zod.ts
@@ -6218,6 +6218,231 @@ export const getEntityPermissionResponse = zod
])
.describe('API response envelope for entity permissions.');
+/**
+ * @summary List the caller's favorites.
+ */
+export const listFavoritesResponse = zod
+ .object({
+ favorites: zod
+ .array(
+ zod
+ .object({
+ channelId: zod
+ .string()
+ .nullish()
+ .describe(
+ 'Owning channel id of the favorited channel message, when applicable.'
+ ),
+ channelType: zod
+ .string()
+ .nullish()
+ .describe(
+ 'Channel type (e.g. `public`, `direct_message`) of the favorited channel, when applicable.'
+ ),
+ createdAt: zod.iso
+ .datetime({})
+ .describe('When the favorite was created.'),
+ documentSubType: zod
+ .string()
+ .nullish()
+ .describe(
+ 'Document sub type (e.g. `task`) of the favorited document, when applicable.'
+ ),
+ entityId: zod.string().describe('The id of the favorited entity.'),
+ entityType: zod
+ .enum([
+ 'user',
+ 'chat',
+ 'channel',
+ 'channel_message',
+ 'document',
+ 'project',
+ 'email_thread',
+ 'team',
+ 'call',
+ 'foreign_entity',
+ 'static_file',
+ 'crm_company',
+ 'crm_contact',
+ ])
+ .describe('The type of an entity in Macro')
+ .describe('The type of the favorited entity.'),
+ fileType: zod
+ .string()
+ .nullish()
+ .describe(
+ 'File type of the favorited document, when applicable.'
+ ),
+ name: zod
+ .string()
+ .nullish()
+ .describe(
+ 'Display name of the favorited entity, when it could be resolved.'
+ ),
+ sortOrder: zod
+ .number()
+ .describe('Manual ordering value; lower sorts first.'),
+ })
+ .describe(
+ "A single favorited entity, including display metadata hydrated from the\nfavorited entity where available.\n\nA favorite is identified by `(entity_type, entity_id)` within the user's\ncollection; there is no surrogate id."
+ )
+ )
+ .describe("The requesting user's favorites, in manual order."),
+ })
+ .describe("The user's favorites, in manual order.");
+
+/**
+ * @summary Favorite an entity in the caller's collection.
+ */
+export const addFavoriteBody = zod
+ .object({
+ entityId: zod.string().describe('The id of the entity to favorite.'),
+ entityType: zod
+ .enum([
+ 'user',
+ 'chat',
+ 'channel',
+ 'channel_message',
+ 'document',
+ 'project',
+ 'email_thread',
+ 'team',
+ 'call',
+ 'foreign_entity',
+ 'static_file',
+ 'crm_company',
+ 'crm_contact',
+ ])
+ .describe('The type of an entity in Macro')
+ .describe('The type of the entity to favorite.'),
+ })
+ .describe('Request body for favoriting an entity.');
+
+export const addFavoriteResponse = zod
+ .object({
+ channelId: zod
+ .string()
+ .nullish()
+ .describe(
+ 'Owning channel id of the favorited channel message, when applicable.'
+ ),
+ channelType: zod
+ .string()
+ .nullish()
+ .describe(
+ 'Channel type (e.g. `public`, `direct_message`) of the favorited channel, when applicable.'
+ ),
+ createdAt: zod.iso.datetime({}).describe('When the favorite was created.'),
+ documentSubType: zod
+ .string()
+ .nullish()
+ .describe(
+ 'Document sub type (e.g. `task`) of the favorited document, when applicable.'
+ ),
+ entityId: zod.string().describe('The id of the favorited entity.'),
+ entityType: zod
+ .enum([
+ 'user',
+ 'chat',
+ 'channel',
+ 'channel_message',
+ 'document',
+ 'project',
+ 'email_thread',
+ 'team',
+ 'call',
+ 'foreign_entity',
+ 'static_file',
+ 'crm_company',
+ 'crm_contact',
+ ])
+ .describe('The type of an entity in Macro')
+ .describe('The type of the favorited entity.'),
+ fileType: zod
+ .string()
+ .nullish()
+ .describe('File type of the favorited document, when applicable.'),
+ name: zod
+ .string()
+ .nullish()
+ .describe(
+ 'Display name of the favorited entity, when it could be resolved.'
+ ),
+ sortOrder: zod
+ .number()
+ .describe('Manual ordering value; lower sorts first.'),
+ })
+ .describe(
+ "A single favorited entity, including display metadata hydrated from the\nfavorited entity where available.\n\nA favorite is identified by `(entity_type, entity_id)` within the user's\ncollection; there is no surrogate id."
+ );
+
+/**
+ * @summary Persist a manual order for the caller's favorites.
+ */
+export const reorderFavoritesBody = zod
+ .object({
+ favorites: zod
+ .array(
+ zod
+ .object({
+ entityId: zod.string().describe('The id of the favorited entity.'),
+ entityType: zod
+ .enum([
+ 'user',
+ 'chat',
+ 'channel',
+ 'channel_message',
+ 'document',
+ 'project',
+ 'email_thread',
+ 'team',
+ 'call',
+ 'foreign_entity',
+ 'static_file',
+ 'crm_company',
+ 'crm_contact',
+ ])
+ .describe('The type of an entity in Macro')
+ .describe('The type of the favorited entity.'),
+ })
+ .describe('A reference to a favorited entity.')
+ )
+ .describe("The user's favorited entities in the desired order."),
+ })
+ .describe('Request body for reordering favorites.');
+
+export const reorderFavoritesResponseDefault = null;
+
+export const reorderFavoritesResponse = zod.unknown();
+
+/**
+ * @summary Remove a favorite by entity.
+ */
+export const removeFavoriteByEntityParams = zod.object({
+ entity_type: zod
+ .enum([
+ 'user',
+ 'chat',
+ 'channel',
+ 'channel_message',
+ 'document',
+ 'project',
+ 'email_thread',
+ 'team',
+ 'call',
+ 'foreign_entity',
+ 'static_file',
+ 'crm_company',
+ 'crm_contact',
+ ])
+ .describe('The type of the favorited entity.'),
+ entity_id: zod.string().describe('The id of the favorited entity.'),
+});
+
+export const removeFavoriteByEntityResponseDefault = null;
+
+export const removeFavoriteByEntityResponse = zod.unknown();
+
/**
* @summary Get a visible foreign entity by its internal ID.
*/
@@ -8217,6 +8442,11 @@ export const getItemsSoupResponse = zod
.and(
zod.object({
frecency_score: zod.number(),
+ is_favorited: zod
+ .boolean()
+ .describe(
+ 'Whether the requesting user has favorited this entity.'
+ ),
})
)
.describe('API representation of a soup item with its frecency score.')
@@ -10558,6 +10788,11 @@ export const postItemsSoupResponse = zod
.and(
zod.object({
frecency_score: zod.number(),
+ is_favorited: zod
+ .boolean()
+ .describe(
+ 'Whether the requesting user has favorited this entity.'
+ ),
})
)
.describe('API representation of a soup item with its frecency score.')
@@ -12431,6 +12666,11 @@ export const postItemsSoupAstResponse = zod
.and(
zod.object({
frecency_score: zod.number(),
+ is_favorited: zod
+ .boolean()
+ .describe(
+ 'Whether the requesting user has favorited this entity.'
+ ),
})
)
.describe('API representation of a soup item with its frecency score.')
@@ -14634,6 +14874,11 @@ export const postItemsSoupAstGroupedResponse = zod
.and(
zod.object({
frecency_score: zod.number(),
+ is_favorited: zod
+ .boolean()
+ .describe(
+ 'Whether the requesting user has favorited this entity.'
+ ),
})
)
.describe(
@@ -16509,6 +16754,11 @@ export const postItemsSoupAstGroupedResponse = zod
.and(
zod.object({
frecency_score: zod.number(),
+ is_favorited: zod
+ .boolean()
+ .describe(
+ 'Whether the requesting user has favorited this entity.'
+ ),
})
)
.describe(
diff --git a/js/app/packages/service-clients/service-storage/graphql-soup.ts b/js/app/packages/service-clients/service-storage/graphql-soup.ts
index d0140cea9a..bf77c1c484 100644
--- a/js/app/packages/service-clients/service-storage/graphql-soup.ts
+++ b/js/app/packages/service-clients/service-storage/graphql-soup.ts
@@ -189,6 +189,9 @@ function normalizeChannelType(channelType: string) {
function mapGraphqlSoupItem(item: GraphqlSoupItem): SoupApiItem {
const frecency = item.frecencyScore;
+ // `is_favorited: false` below: the GraphQL soup surface has no favorites
+ // data; the REST `SoupApiItem` shape requires the flag, and nothing
+ // consumes it on this path yet.
return match(item.entity)
.with(
@@ -197,6 +200,7 @@ function mapGraphqlSoupItem(item: GraphqlSoupItem): SoupApiItem {
({
tag: 'document',
frecency_score: frecency,
+ is_favorited: false,
data: {
id: entity.id,
name: entity.documentName,
@@ -219,6 +223,7 @@ function mapGraphqlSoupItem(item: GraphqlSoupItem): SoupApiItem {
({
tag: 'chat',
frecency_score: frecency,
+ is_favorited: false,
data: {
id: entity.id,
name: entity.chatName,
@@ -239,6 +244,7 @@ function mapGraphqlSoupItem(item: GraphqlSoupItem): SoupApiItem {
({
tag: 'project',
frecency_score: frecency,
+ is_favorited: false,
data: {
id: entity.id,
name: entity.projectName,
@@ -258,6 +264,7 @@ function mapGraphqlSoupItem(item: GraphqlSoupItem): SoupApiItem {
({
tag: 'emailThread',
frecency_score: frecency,
+ is_favorited: false,
data: {
id: entity.id,
providerId: entity.providerId ?? undefined,
@@ -314,6 +321,7 @@ function mapGraphqlSoupItem(item: GraphqlSoupItem): SoupApiItem {
({
tag: 'channel',
frecency_score: frecency,
+ is_favorited: false,
data: {
channel: {
id: entity.id,
@@ -347,6 +355,7 @@ function mapGraphqlSoupItem(item: GraphqlSoupItem): SoupApiItem {
({
tag: 'channelThread',
frecency_score: frecency,
+ is_favorited: false,
data: {
id: entity.id,
attachments: [],
@@ -374,6 +383,7 @@ function mapGraphqlSoupItem(item: GraphqlSoupItem): SoupApiItem {
({
tag: 'call',
frecency_score: frecency,
+ is_favorited: false,
data: {
callId: entity.id,
channelId: entity.channelId,
@@ -401,6 +411,7 @@ function mapGraphqlSoupItem(item: GraphqlSoupItem): SoupApiItem {
({
tag: 'crmCompany',
frecency_score: frecency,
+ is_favorited: false,
data: {
id: entity.id,
teamId: entity.crmTeamId,
@@ -426,6 +437,7 @@ function mapGraphqlSoupItem(item: GraphqlSoupItem): SoupApiItem {
({
tag: 'foreignEntity',
frecency_score: frecency,
+ is_favorited: false,
data: {
id: entity.id,
foreignEntityId: entity.foreignEntityId,
diff --git a/js/app/packages/service-clients/service-storage/openapi.json b/js/app/packages/service-clients/service-storage/openapi.json
index 940b5608c6..0b6b71c690 100644
--- a/js/app/packages/service-clients/service-storage/openapi.json
+++ b/js/app/packages/service-clients/service-storage/openapi.json
@@ -6690,6 +6690,256 @@
}
}
},
+ "/favorites": {
+ "get": {
+ "tags": ["favorites"],
+ "summary": "List the caller's favorites.",
+ "operationId": "list_favorites",
+ "responses": {
+ "200": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/FavoritesList"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ }
+ }
+ },
+ "post": {
+ "tags": ["favorites"],
+ "summary": "Favorite an entity in the caller's collection.",
+ "operationId": "add_favorite",
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/AddFavoriteRequest"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/Favorite"
+ }
+ }
+ }
+ },
+ "400": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "403": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
+ "/favorites/reorder": {
+ "patch": {
+ "tags": ["favorites"],
+ "summary": "Persist a manual order for the caller's favorites.",
+ "operationId": "reorder_favorites",
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ReorderFavoritesRequest"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "default": null
+ }
+ }
+ }
+ },
+ "400": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
+ "/favorites/{entity_type}/{entity_id}": {
+ "delete": {
+ "tags": ["favorites"],
+ "summary": "Remove a favorite by entity.",
+ "operationId": "remove_favorite_by_entity",
+ "parameters": [
+ {
+ "name": "entity_type",
+ "in": "path",
+ "description": "The type of the favorited entity.",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "description": "The type of an entity in Macro",
+ "enum": [
+ "user",
+ "chat",
+ "channel",
+ "channel_message",
+ "document",
+ "project",
+ "email_thread",
+ "team",
+ "call",
+ "foreign_entity",
+ "static_file",
+ "crm_company",
+ "crm_contact"
+ ]
+ }
+ },
+ {
+ "name": "entity_id",
+ "in": "path",
+ "description": "The id of the favorited entity.",
+ "required": true,
+ "schema": {
+ "type": "string"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "default": null
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "404": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
"/foreign_entity/{id}": {
"get": {
"tags": ["foreign_entity"],
@@ -9288,6 +9538,41 @@
"description": "The kind of activity a user performs in a channel.",
"enum": ["view", "interact"]
},
+ "AddFavoriteRequest": {
+ "type": "object",
+ "description": "Request body for favoriting an entity.",
+ "required": ["entityType", "entityId"],
+ "properties": {
+ "entityId": {
+ "type": "string",
+ "description": "The id of the entity to favorite."
+ },
+ "entityType": {
+ "oneOf": [
+ {
+ "type": "string",
+ "description": "The type of an entity in Macro",
+ "enum": [
+ "user",
+ "chat",
+ "channel",
+ "channel_message",
+ "document",
+ "project",
+ "email_thread",
+ "team",
+ "call",
+ "foreign_entity",
+ "static_file",
+ "crm_company",
+ "crm_contact"
+ ]
+ }
+ ],
+ "description": "The type of the entity to favorite."
+ }
+ }
+ },
"AddParticipantsRequest": {
"type": "object",
"description": "Request to add participants.",
@@ -14046,6 +14331,120 @@
}
}
},
+ "Favorite": {
+ "type": "object",
+ "description": "A single favorited entity, including display metadata hydrated from the\nfavorited entity where available.\n\nA favorite is identified by `(entity_type, entity_id)` within the user's\ncollection; there is no surrogate id.",
+ "required": ["entityType", "entityId", "sortOrder", "createdAt"],
+ "properties": {
+ "channelId": {
+ "type": ["string", "null"],
+ "description": "Owning channel id of the favorited channel message, when applicable."
+ },
+ "channelType": {
+ "type": ["string", "null"],
+ "description": "Channel type (e.g. `public`, `direct_message`) of the favorited channel, when applicable."
+ },
+ "createdAt": {
+ "type": "string",
+ "format": "date-time",
+ "description": "When the favorite was created."
+ },
+ "documentSubType": {
+ "type": ["string", "null"],
+ "description": "Document sub type (e.g. `task`) of the favorited document, when applicable."
+ },
+ "entityId": {
+ "type": "string",
+ "description": "The id of the favorited entity."
+ },
+ "entityType": {
+ "oneOf": [
+ {
+ "type": "string",
+ "description": "The type of an entity in Macro",
+ "enum": [
+ "user",
+ "chat",
+ "channel",
+ "channel_message",
+ "document",
+ "project",
+ "email_thread",
+ "team",
+ "call",
+ "foreign_entity",
+ "static_file",
+ "crm_company",
+ "crm_contact"
+ ]
+ }
+ ],
+ "description": "The type of the favorited entity."
+ },
+ "fileType": {
+ "type": ["string", "null"],
+ "description": "File type of the favorited document, when applicable."
+ },
+ "name": {
+ "type": ["string", "null"],
+ "description": "Display name of the favorited entity, when it could be resolved."
+ },
+ "sortOrder": {
+ "type": "number",
+ "format": "double",
+ "description": "Manual ordering value; lower sorts first."
+ }
+ }
+ },
+ "FavoriteEntityRef": {
+ "type": "object",
+ "description": "A reference to a favorited entity.",
+ "required": ["entityType", "entityId"],
+ "properties": {
+ "entityId": {
+ "type": "string",
+ "description": "The id of the favorited entity."
+ },
+ "entityType": {
+ "oneOf": [
+ {
+ "type": "string",
+ "description": "The type of an entity in Macro",
+ "enum": [
+ "user",
+ "chat",
+ "channel",
+ "channel_message",
+ "document",
+ "project",
+ "email_thread",
+ "team",
+ "call",
+ "foreign_entity",
+ "static_file",
+ "crm_company",
+ "crm_contact"
+ ]
+ }
+ ],
+ "description": "The type of the favorited entity."
+ }
+ }
+ },
+ "FavoritesList": {
+ "type": "object",
+ "description": "The user's favorites, in manual order.",
+ "required": ["favorites"],
+ "properties": {
+ "favorites": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/Favorite"
+ },
+ "description": "The requesting user's favorites, in manual order."
+ }
+ }
+ },
"FileSystemNodeWithIds": {
"oneOf": [
{
@@ -17223,6 +17622,20 @@
}
}
},
+ "ReorderFavoritesRequest": {
+ "type": "object",
+ "description": "Request body for reordering favorites.",
+ "required": ["favorites"],
+ "properties": {
+ "favorites": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/FavoriteEntityRef"
+ },
+ "description": "The user's favorited entities in the desired order."
+ }
+ }
+ },
"ReorderPinRequest": {
"type": "object",
"required": ["pinnedItemId", "pinnedItemType", "pinIndex"],
@@ -17607,11 +18020,15 @@
},
{
"type": "object",
- "required": ["frecency_score"],
+ "required": ["frecency_score", "is_favorited"],
"properties": {
"frecency_score": {
"type": "number",
"format": "double"
+ },
+ "is_favorited": {
+ "type": "boolean",
+ "description": "Whether the requesting user has favorited this entity."
}
}
}
diff --git a/js/app/packages/service-clients/service-storage/service.ts b/js/app/packages/service-clients/service-storage/service.ts
index bac403a36d..261976d370 100644
--- a/js/app/packages/service-clients/service-storage/service.ts
+++ b/js/app/packages/service-clients/service-storage/service.ts
@@ -235,6 +235,36 @@ const ViewsSvc = new Svc('Views Service')
throws: withFetchErrors(),
});
+const FavoritesSvc = new Svc('Favorites Service')
+ .use('fetchErrors', fetchErrorsSvc)
+ .fn('getFavorites', {
+ description: "Get the user's favorites",
+ result: schemas.listFavoritesResponse.shape,
+ throws: withFetchErrors(),
+ })
+ .fn('addFavorite', {
+ description: "Favorite an entity in the user's collection",
+ args: schemas.addFavoriteBody.shape,
+ modifies: true,
+ result: schemas.addFavoriteResponse.shape,
+ throws: withFetchErrors(),
+ })
+ .fn('removeFavoriteByEntity', {
+ description: 'Remove a favorite by entity',
+ args: {
+ entityType: schemas.removeFavoriteByEntityParams.shape.entity_type,
+ entityId: schemas.removeFavoriteByEntityParams.shape.entity_id,
+ },
+ modifies: true,
+ throws: withFetchErrors(),
+ })
+ .fn('reorderFavorites', {
+ description: "Persist a manual order for the user's favorites",
+ args: schemas.reorderFavoritesBody.shape,
+ modifies: true,
+ throws: withFetchErrors(),
+ });
+
const PermissionsTokensSvc = new Svc('Permissions Tokens Service')
.use('fetchErrors', fetchErrorsSvc)
.fn('createPermissionToken', {
@@ -682,7 +712,8 @@ export const StorageService = new Svc('Document++ Storage Service API')
.use('projects', ProjectsSvc)
.use('permissionsTokens', PermissionsTokensSvc)
.use('instructions', InstructionsSvc)
- .use('views', ViewsSvc);
+ .use('views', ViewsSvc)
+ .use('favorites', FavoritesSvc);
export type StorageService = typeof StorageService;
export type StorageServiceClient = ServiceClient<StorageService>;
diff --git a/rust/cloud-storage/.sqlx/query-36a185a68b67c421880ace1b043b023106f3890102b5a71a5172d8fd401fba9c.json b/rust/cloud-storage/.sqlx/query-36a185a68b67c421880ace1b043b023106f3890102b5a71a5172d8fd401fba9c.json
new file mode 100644
index 0000000000..131bd65561
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-36a185a68b67c421880ace1b043b023106f3890102b5a71a5172d8fd401fba9c.json
@@ -0,0 +1,70 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT\n f.entity_type as \"entity_type!\",\n f.entity_id as \"entity_id!\",\n f.sort_order as \"sort_order!\",\n f.created_at as \"created_at!\",\n CASE f.entity_type\n WHEN 'document' THEN d.name\n WHEN 'chat' THEN c.name\n WHEN 'project' THEN p.name\n WHEN 'channel' THEN ch.name::text\n WHEN 'email_thread' THEN em.subject\n END as \"name?\",\n d.\"fileType\" as \"file_type?\",\n dt.sub_type::text as \"document_sub_type?\",\n ch.channel_type::text as \"channel_type?\",\n cm.channel_id::text as \"channel_id?\"\n FROM favorite f\n LEFT JOIN \"Document\" d ON f.entity_type = 'document' AND d.id = f.entity_id\n LEFT JOIN document_sub_type dt ON f.entity_type = 'document' AND dt.document_id = f.entity_id\n LEFT JOIN \"Chat\" c ON f.entity_type = 'chat' AND c.id = f.entity_id\n LEFT JOIN \"Project\" p ON f.entity_type = 'project' AND p.id = f.entity_id\n LEFT JOIN comms_channels ch ON f.entity_type = 'channel' AND ch.id::text = f.entity_id\n LEFT JOIN comms_messages cm ON f.entity_type = 'channel_message' AND cm.id::text = f.entity_id\n LEFT JOIN email_threads et ON f.entity_type = 'email_thread' AND et.id::text = f.entity_id\n LEFT JOIN LATERAL (\n SELECT m.subject\n FROM email_messages m\n WHERE m.thread_id = et.id AND m.is_draft = false\n ORDER BY m.internal_date_ts DESC NULLS LAST\n LIMIT 1\n ) em ON f.entity_type = 'email_thread'\n WHERE f.user_id = $1\n AND (f.entity_type <> 'document' OR (d.id IS NOT NULL AND d.\"deletedAt\" IS NULL))\n AND (f.entity_type <> 'chat' OR (c.id IS NOT NULL AND c.\"deletedAt\" IS NULL))\n AND (f.entity_type <> 'project' OR (p.id IS NOT NULL AND p.\"deletedAt\" IS NULL))\n ORDER BY f.sort_order ASC, f.created_at ASC\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "entity_type!",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 1,
+ "name": "entity_id!",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 2,
+ "name": "sort_order!",
+ "type_info": "Float8"
+ },
+ {
+ "ordinal": 3,
+ "name": "created_at!",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 4,
+ "name": "name?",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 5,
+ "name": "file_type?",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 6,
+ "name": "document_sub_type?",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 7,
+ "name": "channel_type?",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 8,
+ "name": "channel_id?",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ false,
+ false,
+ null,
+ true,
+ null,
+ null,
+ null
+ ]
+ },
+ "hash": "36a185a68b67c421880ace1b043b023106f3890102b5a71a5172d8fd401fba9c"
+}
diff --git a/rust/cloud-storage/.sqlx/query-79c99ea2b9c2b71f4b730276a90d782436dfd70526616d68c698ba064b30559a.json b/rust/cloud-storage/.sqlx/query-79c99ea2b9c2b71f4b730276a90d782436dfd70526616d68c698ba064b30559a.json
new file mode 100644
index 0000000000..8b56170253
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-79c99ea2b9c2b71f4b730276a90d782436dfd70526616d68c698ba064b30559a.json
@@ -0,0 +1,30 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT DISTINCT f.entity_type as \"entity_type!\", f.entity_id as \"entity_id!\"\n FROM favorite f\n JOIN UNNEST($2::text[], $3::text[]) AS w(entity_type, entity_id)\n ON w.entity_type = f.entity_type AND w.entity_id = f.entity_id\n WHERE f.user_id = $1\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "entity_type!",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 1,
+ "name": "entity_id!",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text",
+ "TextArray",
+ "TextArray"
+ ]
+ },
+ "nullable": [
+ false,
+ false
+ ]
+ },
+ "hash": "79c99ea2b9c2b71f4b730276a90d782436dfd70526616d68c698ba064b30559a"
+}
diff --git a/rust/cloud-storage/.sqlx/query-8059e21e0b3d99eff4104039e3a09675906a08d3a5ef25ce2bd8a9d39c7bd065.json b/rust/cloud-storage/.sqlx/query-8059e21e0b3d99eff4104039e3a09675906a08d3a5ef25ce2bd8a9d39c7bd065.json
new file mode 100644
index 0000000000..01627e95e9
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-8059e21e0b3d99eff4104039e3a09675906a08d3a5ef25ce2bd8a9d39c7bd065.json
@@ -0,0 +1,16 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n UPDATE favorite f\n SET sort_order = x.ord::float8 - 1, updated_at = now()\n FROM UNNEST($2::text[], $3::text[]) WITH ORDINALITY AS x(entity_type, entity_id, ord)\n WHERE f.user_id = $1\n AND f.entity_type = x.entity_type\n AND f.entity_id = x.entity_id\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Text",
+ "TextArray",
+ "TextArray"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "8059e21e0b3d99eff4104039e3a09675906a08d3a5ef25ce2bd8a9d39c7bd065"
+}
diff --git a/rust/cloud-storage/.sqlx/query-80d861cc026e5dd2cb4885e3bc09d33ec8b543246fc5509ad5196d5882f71ad4.json b/rust/cloud-storage/.sqlx/query-80d861cc026e5dd2cb4885e3bc09d33ec8b543246fc5509ad5196d5882f71ad4.json
new file mode 100644
index 0000000000..e25cb88946
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-80d861cc026e5dd2cb4885e3bc09d33ec8b543246fc5509ad5196d5882f71ad4.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT COUNT(*) as \"count!\" FROM favorite WHERE user_id = $1",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "count!",
+ "type_info": "Int8"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "80d861cc026e5dd2cb4885e3bc09d33ec8b543246fc5509ad5196d5882f71ad4"
+}
diff --git a/rust/cloud-storage/.sqlx/query-c79cd38f694914ff51703f156a3e8194bb04de710d32829470e3d729902234c3.json b/rust/cloud-storage/.sqlx/query-c79cd38f694914ff51703f156a3e8194bb04de710d32829470e3d729902234c3.json
new file mode 100644
index 0000000000..6b2af1de64
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-c79cd38f694914ff51703f156a3e8194bb04de710d32829470e3d729902234c3.json
@@ -0,0 +1,16 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n DELETE FROM favorite\n WHERE user_id = $1 AND entity_type = $2 AND entity_id = $3\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Text",
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "c79cd38f694914ff51703f156a3e8194bb04de710d32829470e3d729902234c3"
+}
diff --git a/rust/cloud-storage/.sqlx/query-cdeb95aa35e2207dc99cd6d6935eef5787ce1ef740b56c75c998746732743416.json b/rust/cloud-storage/.sqlx/query-cdeb95aa35e2207dc99cd6d6935eef5787ce1ef740b56c75c998746732743416.json
new file mode 100644
index 0000000000..3a14193d11
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-cdeb95aa35e2207dc99cd6d6935eef5787ce1ef740b56c75c998746732743416.json
@@ -0,0 +1,72 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO favorite (user_id, entity_type, entity_id, sort_order)\n VALUES (\n $1, $2, $3,\n COALESCE((SELECT MAX(sort_order) + 1 FROM favorite WHERE user_id = $1), 0)\n )\n ON CONFLICT (user_id, entity_type, entity_id)\n DO UPDATE SET updated_at = now()\n RETURNING\n entity_type as \"entity_type!\",\n entity_id as \"entity_id!\",\n sort_order as \"sort_order!\",\n created_at as \"created_at!\",\n NULL::text as \"name?\",\n NULL::text as \"file_type?\",\n NULL::text as \"document_sub_type?\",\n NULL::text as \"channel_type?\",\n NULL::text as \"channel_id?\"\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "entity_type!",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 1,
+ "name": "entity_id!",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 2,
+ "name": "sort_order!",
+ "type_info": "Float8"
+ },
+ {
+ "ordinal": 3,
+ "name": "created_at!",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 4,
+ "name": "name?",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 5,
+ "name": "file_type?",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 6,
+ "name": "document_sub_type?",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 7,
+ "name": "channel_type?",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 8,
+ "name": "channel_id?",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Text",
+ "Text"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ false,
+ false,
+ null,
+ null,
+ null,
+ null,
+ null
+ ]
+ },
+ "hash": "cdeb95aa35e2207dc99cd6d6935eef5787ce1ef740b56c75c998746732743416"
+}
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lock
index f3e3687791..8f9d4560b9 100644
--- a/rust/cloud-storage/Cargo.lock
+++ b/rust/cloud-storage/Cargo.lock
@@ -3982,6 +3982,7 @@ dependencies = [
"embedding",
"entity_access",
"entity_access_management",
+ "favorites",
"foreign_entity",
"frecency",
"futures",
@@ -5009,6 +5010,32 @@ version = "2.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9f1f227452a390804cdb637b74a86990f2a7d7ba4b7d5693aac9b4dd6defd8d6"
+[[package]]
+name = "favorites"
+version = "0.1.0"
+dependencies = [
+ "anyhow",
+ "axum",
+ "chrono",
+ "cowlike",
+ "entity_access",
+ "macro_db_migrator",
+ "macro_user_id",
+ "mockall",
+ "model-entity",
+ "model-error-response",
+ "model_user",
+ "serde",
+ "serde_json",
+ "sqlx",
+ "thiserror 2.0.18",
+ "tokio",
+ "tracing",
+ "utoipa",
+ "uuid",
+ "workspace-hack",
+]
+
[[package]]
name = "fax"
version = "0.2.7"
diff --git a/rust/cloud-storage/Cargo.toml b/rust/cloud-storage/Cargo.toml
index 7c6420a258..ebbeb0ba4b 100644
--- a/rust/cloud-storage/Cargo.toml
+++ b/rust/cloud-storage/Cargo.toml
@@ -32,6 +32,7 @@ members = [
"email_sfs_delete_handler",
"email_suppression_handler",
"embedding",
+ "favorites",
"foreign_entity",
"graphql_soup",
"image_optimizer",
diff --git a/rust/cloud-storage/document_storage_service/Cargo.toml b/rust/cloud-storage/document_storage_service/Cargo.toml
index b3de089a17..7efcfd1482 100644
--- a/rust/cloud-storage/document_storage_service/Cargo.toml
+++ b/rust/cloud-storage/document_storage_service/Cargo.toml
@@ -70,6 +70,7 @@ dynamodb_client = { path = "../dynamodb_client" }
email = { path = "../email", features = ["outbound", "ports"] }
entity_access = { path = "../entity_access", features = ["inbound", "schema"] }
entity_access_management = { path = "../entity_access_management" }
+favorites = { path = "../favorites", features = ["inbound", "postgres"] }
foreign_entity = { path = "../foreign_entity", features = ["inbound"] }
frecency = { path = "../frecency", features = ["postgres"] }
futures = { workspace = true }
diff --git a/rust/cloud-storage/document_storage_service/src/api/context.rs b/rust/cloud-storage/document_storage_service/src/api/context.rs
index 33505bb95e..084bc14597 100644
--- a/rust/cloud-storage/document_storage_service/src/api/context.rs
+++ b/rust/cloud-storage/document_storage_service/src/api/context.rs
@@ -49,6 +49,10 @@ use email::{
outbound::EmailPgRepo,
};
use entity_access::{domain::service::EntityAccessServiceImpl, outbound::PgAccessRepository};
+use favorites::{
+ domain::service::FavoritesServiceImpl, inbound::axum_router::FavoritesRouterState,
+ outbound::pg_favorites_repo::PgFavoritesRepo,
+};
use foreign_entity::{
domain::service::ForeignEntityServiceImpl, inbound::axum_router::ForeignEntityRouterState,
outbound::pg_foreign_entity_repo::PgForeignEntityRepo,
@@ -280,6 +284,12 @@ pub(crate) type DssCallWebhookState = WebhookRouterState<DssCallService>;
/// Type alias for the internal call router state.
pub(crate) type DssCallInternalState = InternalCallRouterState<DssCallService>;
+/// Type alias for the favorites service.
+pub(crate) type FavoritesServiceType = FavoritesServiceImpl<PgFavoritesRepo>;
+
+/// Type alias for the favorites router state.
+pub(crate) type DssFavoritesState = FavoritesRouterState<FavoritesServiceType, EntityAccessService>;
+
/// Type alias for the foreign entity service.
pub(crate) type ForeignEntityServiceType = ForeignEntityServiceImpl<PgForeignEntityRepo>;
@@ -327,6 +337,7 @@ pub(crate) struct ApiContext {
pub graphql_soup_schema: graphql_soup::SharedSoupSchema<DssSoupService>,
#[cfg(feature = "graphql")]
pub graphql_notification_reader: Arc<dyn graphql_soup::SoupNotificationEdgeReader>,
+ pub favorites_state: DssFavoritesState,
pub foreign_entity_state: DssForeignEntityState,
pub sqs_client: Arc<sqs_client::SQS>,
pub contacts_ingress: Arc<SqsContactsIngress<SqsContactsQueue>>,
diff --git a/rust/cloud-storage/document_storage_service/src/api/mod.rs b/rust/cloud-storage/document_storage_service/src/api/mod.rs
index e3e6fcb370..f5f1a4d4a8 100644
--- a/rust/cloud-storage/document_storage_service/src/api/mod.rs
+++ b/rust/cloud-storage/document_storage_service/src/api/mod.rs
@@ -224,6 +224,10 @@ fn api_router(state: ApiContext) -> Router {
state.channel_bot_webhook_state.clone(),
),
)
+ .nest(
+ "/favorites",
+ favorites::inbound::axum_router::favorites_router(state.favorites_state.clone()),
+ )
.nest(
"/foreign_entity",
foreign_entity::inbound::axum_router::foreign_entity_router(
diff --git a/rust/cloud-storage/document_storage_service/src/api/swagger.rs b/rust/cloud-storage/document_storage_service/src/api/swagger.rs
index 5cc0fed1fc..3bb255e2ec 100644
--- a/rust/cloud-storage/document_storage_service/src/api/swagger.rs
+++ b/rust/cloud-storage/document_storage_service/src/api/swagger.rs
@@ -77,6 +77,10 @@ use documents_hex::inbound::axum_router::{
edit_document::EditDocumentResponse, get_branch_name::BranchNameResponse,
get_short_id::ShortIdResponse,
};
+use favorites::domain::models::{Favorite, FavoritesList};
+use favorites::inbound::axum_router::{
+ AddFavoriteRequest, FavoriteEntityRef, ReorderFavoritesRequest,
+};
use foreign_entity::domain::models::ForeignEntity;
use model::document::response::{
CreateDocumentRequest, CreateDocumentResponse, CreateDocumentResponseData,
@@ -285,6 +289,12 @@ use utoipa::OpenApi;
entity::get_entity_permission::handler,
+ // favorites
+ favorites::inbound::axum_router::list_favorites_handler,
+ favorites::inbound::axum_router::add_favorite_handler,
+ favorites::inbound::axum_router::remove_favorite_by_entity_handler,
+ favorites::inbound::axum_router::reorder_favorites_handler,
+
// foreign_entity
foreign_entity::inbound::axum_router::get_foreign_entity_handler,
@@ -400,6 +410,11 @@ use utoipa::OpenApi;
SoupProject,
SoupForeignEntity,
ForeignEntity,
+ Favorite,
+ FavoritesList,
+ AddFavoriteRequest,
+ FavoriteEntityRef,
+ ReorderFavoritesRequest,
SoupApiSort,
SoupPage,
SoupEnrichedEmailThreadPreview,
diff --git a/rust/cloud-storage/document_storage_service/src/main.rs b/rust/cloud-storage/document_storage_service/src/main.rs
index 58f3591b0d..7837429970 100644
--- a/rust/cloud-storage/document_storage_service/src/main.rs
+++ b/rust/cloud-storage/document_storage_service/src/main.rs
@@ -55,6 +55,10 @@ use email::{
outbound::EmailPgRepo,
};
use embedding::embedding_provider::openai::TextEmbedding3Small;
+use favorites::{
+ domain::service::FavoritesServiceImpl, inbound::axum_router::FavoritesRouterState,
+ outbound::pg_favorites_repo::PgFavoritesRepo,
+};
use foreign_entity::{
domain::service::ForeignEntityServiceImpl, inbound::axum_router::ForeignEntityRouterState,
outbound::pg_foreign_entity_repo::PgForeignEntityRepo,
@@ -671,12 +675,21 @@ async fn main() -> anyhow::Result<()> {
foreign_entity_service_for_soup,
));
+ let favorites_service = Arc::new(FavoritesServiceImpl::new(PgFavoritesRepo::new(db.clone())));
+
let api_context = ApiContext {
contacts_ingress: contacts_ingress.clone(),
soup_router_state: SoupRouterState::from_arc(
soup_service.clone(),
email_service,
entity_access_service.clone(),
+ )
+ .with_favorites_reader(Arc::new(
+ service::soup_favorites_reader::DssSoupFavoritesReader(favorites_service.clone()),
+ )),
+ favorites_state: FavoritesRouterState::new(
+ favorites_service,
+ entity_access_service.clone(),
),
#[cfg(feature = "graphql")]
graphql_soup_schema: graphql_soup::build_schema_from_arc(soup_service),
diff --git a/rust/cloud-storage/document_storage_service/src/service/mod.rs b/rust/cloud-storage/document_storage_service/src/service/mod.rs
index 432bf9171e..0251a7a714 100644
--- a/rust/cloud-storage/document_storage_service/src/service/mod.rs
+++ b/rust/cloud-storage/document_storage_service/src/service/mod.rs
@@ -4,3 +4,4 @@ pub mod conn_gateway;
pub mod delete_document_worker;
pub mod property_search_indexer;
pub mod s3;
+pub mod soup_favorites_reader;
diff --git a/rust/cloud-storage/document_storage_service/src/service/soup_favorites_reader.rs b/rust/cloud-storage/document_storage_service/src/service/soup_favorites_reader.rs
new file mode 100644
index 0000000000..a730d7b5b2
--- /dev/null
+++ b/rust/cloud-storage/document_storage_service/src/service/soup_favorites_reader.rs
@@ -0,0 +1,29 @@
+//! Glue adapter exposing the favorites service to soup's `is_favorited`
+//! enrichment.
+
+use std::collections::HashSet;
+use std::pin::Pin;
+use std::sync::Arc;
+
+use favorites::domain::ports::FavoritesService as _;
+use macro_user_id::user_id::MacroUserIdStr;
+use model_entity::Entity;
+use soup::inbound::axum_router::SoupFavoritesReader;
+
+use crate::api::context::FavoritesServiceType;
+
+/// [SoupFavoritesReader] backed by the DSS favorites service.
+pub struct DssSoupFavoritesReader(pub Arc<FavoritesServiceType>);
+
+impl SoupFavoritesReader for DssSoupFavoritesReader {
+ fn favorited_entities<'a>(
+ &'a self,
+ user_id: &'a str,
+ entities: Vec<Entity<'static>>,
+ ) -> Pin<Box<dyn Future<Output = anyhow::Result<HashSet<Entity<'static>>>> + Send + 'a>> {
+ Box::pin(async move {
+ let user = MacroUserIdStr::parse_from_str(user_id)?;
+ Ok(self.0.favorited_entities(&user, &entities).await?)
+ })
+ }
+}
diff --git a/rust/cloud-storage/favorites/Cargo.toml b/rust/cloud-storage/favorites/Cargo.toml
new file mode 100644
index 0000000000..0a60ede7de
--- /dev/null
+++ b/rust/cloud-storage/favorites/Cargo.toml
@@ -0,0 +1,45 @@
+[package]
+edition = "2024"
+name = "favorites"
+publish = false
+version = "0.1.0"
+
+[features]
+default = []
+inbound = [
+ "dep:axum",
+ "dep:model-error-response",
+ "dep:model_user",
+ "dep:utoipa",
+ "entity_access/inbound",
+ "ports",
+]
+mock = ["dep:mockall"]
+outbound = ["ports"]
+ports = ["dep:entity_access", "dep:tokio", "dep:tracing"]
+postgres = ["dep:sqlx", "outbound"]
+
+[dependencies]
+anyhow = { workspace = true }
+axum = { workspace = true, optional = true }
+chrono = { workspace = true, features = ["serde"] }
+cowlike = { path = "../cowlike" }
+entity_access = { path = "../entity_access", optional = true, default-features = false, features = ["ports"] }
+macro_user_id = { path = "../macro_user_id" }
+mockall = { workspace = true, optional = true }
+model-entity = { path = "../model-entity" }
+model-error-response = { path = "../model-error-response", optional = true }
+model_user = { path = "../model_user", optional = true, features = ["axum"] }
+serde = { workspace = true }
+sqlx = { workspace = true, optional = true }
+thiserror = { workspace = true }
+tokio = { workspace = true, optional = true }
+tracing = { workspace = true, optional = true }
+utoipa = { workspace = true, optional = true }
+workspace-hack = { version = "0.1", path = "../workspace-hack" }
+
+[dev-dependencies]
+macro_db_migrator = { path = "../macro_db_migrator" }
+serde_json = { workspace = true }
+tokio = { workspace = true, features = ["macros", "rt-multi-thread"] }
+uuid = { workspace = true, features = ["v7"] }
diff --git a/rust/cloud-storage/favorites/src/domain.rs b/rust/cloud-storage/favorites/src/domain.rs
new file mode 100644
index 0000000000..8623e6a1d9
--- /dev/null
+++ b/rust/cloud-storage/favorites/src/domain.rs
@@ -0,0 +1,7 @@
+//! Domain layer for favorites.
+
+pub mod models;
+#[cfg(feature = "ports")]
+pub mod ports;
+#[cfg(feature = "ports")]
+pub mod service;
diff --git a/rust/cloud-storage/favorites/src/domain/models.rs b/rust/cloud-storage/favorites/src/domain/models.rs
new file mode 100644
index 0000000000..ad6fa03309
--- /dev/null
+++ b/rust/cloud-storage/favorites/src/domain/models.rs
@@ -0,0 +1,72 @@
+//! Domain models for favorites.
+
+use chrono::{DateTime, Utc};
+use model_entity::{Entity, EntityType};
+use serde::{Deserialize, Serialize};
+
+/// A single favorited entity, including display metadata hydrated from the
+/// favorited entity where available.
+///
+/// A favorite is identified by `(entity_type, entity_id)` within the user's
+/// collection; there is no surrogate id.
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]
+#[serde(rename_all = "camelCase")]
+pub struct Favorite {
+ /// The type of the favorited entity.
+ // Inlined so the shared `EntityType` component name is not claimed in
+ // specs that also expose the properties `EntityType` enum.
+ #[cfg_attr(feature = "inbound", schema(inline))]
+ pub entity_type: EntityType,
+ /// The id of the favorited entity.
+ pub entity_id: String,
+ /// Manual ordering value; lower sorts first.
+ pub sort_order: f64,
+ /// When the favorite was created.
+ pub created_at: DateTime<Utc>,
+ /// Display name of the favorited entity, when it could be resolved.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub name: Option<String>,
+ /// File type of the favorited document, when applicable.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub file_type: Option<String>,
+ /// Document sub type (e.g. `task`) of the favorited document, when applicable.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub document_sub_type: Option<String>,
+ /// Channel type (e.g. `public`, `direct_message`) of the favorited channel, when applicable.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub channel_type: Option<String>,
+ /// Owning channel id of the favorited channel message, when applicable.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub channel_id: Option<String>,
+}
+
+impl Favorite {
+ /// The favorited entity as a [model_entity::Entity].
+ pub fn entity(&self) -> Entity<'_> {
+ self.entity_type.with_entity_str(&self.entity_id)
+ }
+}
+
+/// The user's favorites, in manual order.
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]
+#[serde(rename_all = "camelCase")]
+pub struct FavoritesList {
+ /// The requesting user's favorites, in manual order.
+ pub favorites: Vec<Favorite>,
+}
+
+/// Errors returned by the favorites service.
+#[derive(Debug, thiserror::Error)]
+pub enum FavoritesError {
+ /// The favorite (or entity) could not be found in the user's collection.
+ #[error("favorite not found")]
+ NotFound,
+ /// The request was invalid.
+ #[error("{0}")]
+ BadRequest(String),
+ /// Any other internal error.
+ #[error(transparent)]
+ Internal(#[from] anyhow::Error),
+}
diff --git a/rust/cloud-storage/favorites/src/domain/ports.rs b/rust/cloud-storage/favorites/src/domain/ports.rs
new file mode 100644
index 0000000000..6eb92cacc3
--- /dev/null
+++ b/rust/cloud-storage/favorites/src/domain/ports.rs
@@ -0,0 +1,99 @@
+//! Ports (trait contracts) for the favorites domain.
+
+use std::collections::HashSet;
+
+use macro_user_id::user_id::MacroUserIdStr;
+use model_entity::Entity;
+
+use crate::domain::models::{Favorite, FavoritesError};
+
+/// Outbound persistence port for favorites.
+pub trait FavoritesRepo: Send + Sync + 'static {
+ /// The error type returned by repository operations.
+ type Err: Send + std::fmt::Debug;
+
+ /// Insert a favorite at the end of the user's collection.
+ ///
+ /// Adding an entity that is already favorited by the user is a no-op
+ /// that returns the existing record.
+ fn add_favorite(
+ &self,
+ user_id: &MacroUserIdStr<'_>,
+ entity: &Entity<'_>,
+ ) -> impl Future<Output = Result<Favorite, Self::Err>> + Send;
+
+ /// Count the favorites currently in the user's collection.
+ fn count_favorites(
+ &self,
+ user_id: &MacroUserIdStr<'_>,
+ ) -> impl Future<Output = Result<i64, Self::Err>> + Send;
+
+ /// List the user's favorites in manual order, hydrated with display
+ /// metadata. Favorites pointing at deleted entities are omitted.
+ fn list_favorites(
+ &self,
+ user_id: &MacroUserIdStr<'_>,
+ ) -> impl Future<Output = Result<Vec<Favorite>, Self::Err>> + Send;
+
+ /// Remove the favorite for the given entity from the user's collection.
+ ///
+ /// Returns `true` when a row was removed.
+ fn remove_favorite_by_entity(
+ &self,
+ user_id: &MacroUserIdStr<'_>,
+ entity: &Entity<'_>,
+ ) -> impl Future<Output = Result<bool, Self::Err>> + Send;
+
+ /// Persist a manual ordering for the user's favorites. `ordered` is the
+ /// full list of the user's favorited entities in the desired order;
+ /// entities the user has not favorited are ignored.
+ fn reorder_favorites(
+ &self,
+ user_id: &MacroUserIdStr<'_>,
+ ordered: &[Entity<'_>],
+ ) -> impl Future<Output = Result<(), Self::Err>> + Send;
+
+ /// Of the given entities, return the subset favorited by the user.
+ fn favorited_entities(
+ &self,
+ user_id: &MacroUserIdStr<'_>,
+ entities: &[Entity<'_>],
+ ) -> impl Future<Output = Result<HashSet<Entity<'static>>, Self::Err>> + Send;
+}
+
+/// Inbound service port: the favorites API used by drivers (HTTP, soup enrichment).
+pub trait FavoritesService: Send + Sync + 'static {
+ /// Add an entity to the user's favorites (idempotent).
+ fn add_favorite(
+ &self,
+ user_id: &MacroUserIdStr<'_>,
+ entity: &Entity<'_>,
+ ) -> impl Future<Output = Result<Favorite, FavoritesError>> + Send;
+
+ /// List the user's favorites in manual order.
+ fn list_favorites(
+ &self,
+ user_id: &MacroUserIdStr<'_>,
+ ) -> impl Future<Output = Result<Vec<Favorite>, FavoritesError>> + Send;
+
+ /// Remove the favorite for the given entity from the user's collection.
+ fn remove_favorite_by_entity(
+ &self,
+ user_id: &MacroUserIdStr<'_>,
+ entity: &Entity<'_>,
+ ) -> impl Future<Output = Result<(), FavoritesError>> + Send;
+
+ /// Persist a manual ordering for the user's favorites.
+ fn reorder_favorites(
+ &self,
+ user_id: &MacroUserIdStr<'_>,
+ ordered: &[Entity<'_>],
+ ) -> impl Future<Output = Result<(), FavoritesError>> + Send;
+
+ /// Of the given entities, return the subset favorited by the user.
+ fn favorited_entities(
+ &self,
+ user_id: &MacroUserIdStr<'_>,
+ entities: &[Entity<'_>],
+ ) -> impl Future<Output = Result<HashSet<Entity<'static>>, FavoritesError>> + Send;
+}
diff --git a/rust/cloud-storage/favorites/src/domain/service.rs b/rust/cloud-storage/favorites/src/domain/service.rs
new file mode 100644
index 0000000000..eb4e62c2aa
--- /dev/null
+++ b/rust/cloud-storage/favorites/src/domain/service.rs
@@ -0,0 +1,148 @@
+//! Favorites service implementation.
+
+use std::collections::HashSet;
+
+use macro_user_id::user_id::MacroUserIdStr;
+use model_entity::Entity;
+
+use crate::domain::models::{Favorite, FavoritesError};
+use crate::domain::ports::{FavoritesRepo, FavoritesService};
+
+/// Upper bound on favorites per user; keeps reorder payloads and sidebar
+/// lists sane.
+pub const MAX_FAVORITES_PER_COLLECTION: usize = 500;
+
+/// Concrete favorites service backed by a [FavoritesRepo].
+#[derive(Debug, Clone)]
+pub struct FavoritesServiceImpl<R> {
+ repo: R,
+}
+
+impl<R> FavoritesServiceImpl<R>
+where
+ R: FavoritesRepo,
+ anyhow::Error: From<R::Err>,
+{
+ /// Create a favorites service backed by the provided repository.
+ pub fn new(repo: R) -> Self {
+ Self { repo }
+ }
+}
+
+fn validate_entity(entity: &Entity<'_>) -> Result<(), FavoritesError> {
+ if entity.entity_id.trim().is_empty() {
+ return Err(FavoritesError::BadRequest(
+ "entity_id must not be empty".to_string(),
+ ));
+ }
+ Ok(())
+}
+
+impl<R> FavoritesService for FavoritesServiceImpl<R>
+where
+ R: FavoritesRepo,
+ anyhow::Error: From<R::Err>,
+{
+ #[tracing::instrument(err, skip(self))]
+ async fn add_favorite(
+ &self,
+ user_id: &MacroUserIdStr<'_>,
+ entity: &Entity<'_>,
+ ) -> Result<Favorite, FavoritesError> {
+ validate_entity(entity)?;
+ // Cap the collection at add time. Enforcing it here (rather than only
+ // in `reorder_favorites`) keeps table growth bounded and guarantees a
+ // reorder payload can never exceed the limit and be rejected. Re-adding
+ // an already-favorited entity while exactly at the cap is rejected too;
+ // that is a harmless, fail-closed edge.
+ let count = self
+ .repo
+ .count_favorites(user_id)
+ .await
+ .map_err(anyhow::Error::from)?;
+ if count as usize >= MAX_FAVORITES_PER_COLLECTION {
+ return Err(FavoritesError::BadRequest(format!(
+ "cannot have more than {MAX_FAVORITES_PER_COLLECTION} favorites"
+ )));
+ }
+ Ok(self
+ .repo
+ .add_favorite(user_id, entity)
+ .await
+ .map_err(anyhow::Error::from)?)
+ }
+
+ #[tracing::instrument(err, skip(self))]
+ async fn list_favorites(
+ &self,
+ user_id: &MacroUserIdStr<'_>,
+ ) -> Result<Vec<Favorite>, FavoritesError> {
+ Ok(self
+ .repo
+ .list_favorites(user_id)
+ .await
+ .map_err(anyhow::Error::from)?)
+ }
+
+ #[tracing::instrument(err, skip(self))]
+ async fn remove_favorite_by_entity(
+ &self,
+ user_id: &MacroUserIdStr<'_>,
+ entity: &Entity<'_>,
+ ) -> Result<(), FavoritesError> {
+ validate_entity(entity)?;
+ let removed = self
+ .repo
+ .remove_favorite_by_entity(user_id, entity)
+ .await
+ .map_err(anyhow::Error::from)?;
+ if removed {
+ Ok(())
+ } else {
+ Err(FavoritesError::NotFound)
+ }
+ }
+
+ #[tracing::instrument(err, skip(self, ordered))]
+ async fn reorder_favorites(
+ &self,
+ user_id: &MacroUserIdStr<'_>,
+ ordered: &[Entity<'_>],
+ ) -> Result<(), FavoritesError> {
+ if ordered.is_empty() {
+ return Ok(());
+ }
+ if ordered.len() > MAX_FAVORITES_PER_COLLECTION {
+ return Err(FavoritesError::BadRequest(format!(
+ "cannot reorder more than {MAX_FAVORITES_PER_COLLECTION} favorites"
+ )));
+ }
+ let unique: HashSet<&Entity<'_>> = ordered.iter().collect();
+ if unique.len() != ordered.len() {
+ return Err(FavoritesError::BadRequest(
+ "ordered entities must not contain duplicates".to_string(),
+ ));
+ }
+ Ok(self
+ .repo
+ .reorder_favorites(user_id, ordered)
+ .await
+ .map_err(anyhow::Error::from)?)
+ }
+
+ #[tracing::instrument(err, skip(self, entities))]
+ async fn favorited_entities(
+ &self,
+ user_id: &MacroUserIdStr<'_>,
+ entities: &[Entity<'_>],
+ ) -> Result<HashSet<Entity<'static>>, FavoritesError> {
+ if entities.is_empty() {
+ return Ok(HashSet::new());
+ }
+ Ok(self
+ .repo
+ .favorited_entities(user_id, entities)
+ .await
+ .map_err(anyhow::Error::from)?)
+ }
+}
diff --git a/rust/cloud-storage/favorites/src/inbound.rs b/rust/cloud-storage/favorites/src/inbound.rs
new file mode 100644
index 0000000000..6ce8fb9476
--- /dev/null
+++ b/rust/cloud-storage/favorites/src/inbound.rs
@@ -0,0 +1,3 @@
+//! Inbound (driving) adapters for favorites.
+
+pub mod axum_router;
diff --git a/rust/cloud-storage/favorites/src/inbound/axum_router.rs b/rust/cloud-storage/favorites/src/inbound/axum_router.rs
new file mode 100644
index 0000000000..87f784afd7
--- /dev/null
+++ b/rust/cloud-storage/favorites/src/inbound/axum_router.rs
@@ -0,0 +1,331 @@
+//! Axum router for favorites endpoints.
+
+use std::sync::Arc;
+
+use axum::{
+ Json, Router,
+ extract::{Path, State},
+ http::StatusCode,
+ response::IntoResponse,
+ routing::{delete, get, patch, post},
+};
+use entity_access::domain::ports::EntityAccessService;
+use model_entity::EntityType;
+use model_error_response::ErrorResponse;
+use model_user::axum_extractor::MacroUserExtractor;
+use serde::Deserialize;
+
+use crate::domain::{
+ models::{Favorite, FavoritesError, FavoritesList},
+ ports::FavoritesService,
+};
+
+/// Router state for favorites endpoints.
+pub struct FavoritesRouterState<S, AccessSvc> {
+ service: Arc<S>,
+ access_service: Arc<AccessSvc>,
+}
+
+impl<S, AccessSvc> Clone for FavoritesRouterState<S, AccessSvc> {
+ fn clone(&self) -> Self {
+ Self {
+ service: self.service.clone(),
+ access_service: self.access_service.clone(),
+ }
+ }
+}
+
+impl<S, AccessSvc> FavoritesRouterState<S, AccessSvc>
+where
+ S: FavoritesService,
+ AccessSvc: EntityAccessService,
+{
+ /// Create router state from shared service references.
+ pub fn new(service: Arc<S>, access_service: Arc<AccessSvc>) -> Self {
+ Self {
+ service,
+ access_service,
+ }
+ }
+}
+
+/// Ensure the caller has at least view access to the entity they are trying
+/// to favorite.
+///
+/// Favorites hydrate display metadata (names, email subjects, channel types)
+/// on read, so without this check a caller could favorite an arbitrary id and
+/// use `GET /favorites` as an oracle for entities they cannot see. Entity
+/// types the access layer does not recognize (e.g. channel messages) resolve
+/// to "no access" and are rejected.
+async fn ensure_entity_access<AccessSvc>(
+ access_service: &AccessSvc,
+ user: &MacroUserExtractor,
+ entity_type: EntityType,
+ entity_id: &str,
+) -> Result<(), FavoritesApiError>
+where
+ AccessSvc: EntityAccessService,
+{
+ let access = access_service
+ .get_access_level(Some(&user.macro_user_id), entity_id, entity_type)
+ .await
+ .map_err(|e| {
+ tracing::error!(error=?e, "favorites: failed to check entity access");
+ FavoritesApiError::Favorites(FavoritesError::Internal(anyhow::anyhow!(
+ "failed to check entity access"
+ )))
+ })?;
+ if access.is_some() {
+ Ok(())
+ } else {
+ Err(FavoritesApiError::Forbidden)
+ }
+}
+
+/// Build the favorites router.
+///
+/// Routes:
+/// - `GET /` — list the caller's favorites.
+/// - `POST /` — favorite an entity.
+/// - `DELETE /{entity_type}/{entity_id}` — remove a favorite.
+/// - `PATCH /reorder` — persist a manual order.
+pub fn favorites_router<S, AccessSvc, T>(state: FavoritesRouterState<S, AccessSvc>) -> Router<T>
+where
+ S: FavoritesService,
+ AccessSvc: EntityAccessService,
+ T: Send + Sync + 'static,
+{
+ Router::new()
+ .route("/", get(list_favorites_handler::<S, AccessSvc>))
+ .route("/", post(add_favorite_handler::<S, AccessSvc>))
+ .route(
+ "/{entity_type}/{entity_id}",
+ delete(remove_favorite_by_entity_handler::<S, AccessSvc>),
+ )
+ .route("/reorder", patch(reorder_favorites_handler::<S, AccessSvc>))
+ .with_state(state)
+}
+
+/// Request body for favoriting an entity.
+#[derive(Debug, Deserialize, utoipa::ToSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct AddFavoriteRequest {
+ /// The type of the entity to favorite.
+ // Inlined to avoid claiming the shared `EntityType` component name (see
+ // `Favorite::entity_type`).
+ #[schema(inline)]
+ pub entity_type: EntityType,
+ /// The id of the entity to favorite.
+ pub entity_id: String,
+}
+
+/// Path params for removing a favorite by entity.
+#[derive(Debug, Deserialize, utoipa::IntoParams)]
+#[into_params(parameter_in = Path)]
+pub struct RemoveFavoriteByEntityParams {
+ /// The type of the favorited entity.
+ #[param(inline)]
+ pub entity_type: EntityType,
+ /// The id of the favorited entity.
+ pub entity_id: String,
+}
+
+/// A reference to a favorited entity.
+#[derive(Debug, Deserialize, utoipa::ToSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct FavoriteEntityRef {
+ /// The type of the favorited entity.
+ // Inlined to avoid claiming the shared `EntityType` component name (see
+ // `Favorite::entity_type`).
+ #[schema(inline)]
+ pub entity_type: EntityType,
+ /// The id of the favorited entity.
+ pub entity_id: String,
+}
+
+/// Request body for reordering favorites.
+#[derive(Debug, Deserialize, utoipa::ToSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct ReorderFavoritesRequest {
+ /// The user's favorited entities in the desired order.
+ pub favorites: Vec<FavoriteEntityRef>,
+}
+
+/// List the caller's favorites.
+#[utoipa::path(
+ get,
+ tag = "favorites",
+ operation_id = "list_favorites",
+ path = "/favorites",
+ responses(
+ (status = 200, body = FavoritesList),
+ (status = 401, body = ErrorResponse),
+ (status = 500, body = ErrorResponse),
+ )
+)]
+#[tracing::instrument(err, skip_all)]
+pub async fn list_favorites_handler<S, AccessSvc>(
+ State(state): State<FavoritesRouterState<S, AccessSvc>>,
+ user: MacroUserExtractor,
+) -> Result<Json<FavoritesList>, FavoritesApiError>
+where
+ S: FavoritesService,
+ AccessSvc: EntityAccessService,
+{
+ let favorites = state.service.list_favorites(&user.macro_user_id).await?;
+ Ok(Json(FavoritesList { favorites }))
+}
+
+/// Favorite an entity in the caller's collection.
+#[utoipa::path(
+ post,
+ tag = "favorites",
+ operation_id = "add_favorite",
+ path = "/favorites",
+ request_body = AddFavoriteRequest,
+ responses(
+ (status = 200, body = Favorite),
+ (status = 400, body = ErrorResponse),
+ (status = 401, body = ErrorResponse),
+ (status = 403, body = ErrorResponse),
+ (status = 500, body = ErrorResponse),
+ )
+)]
+#[tracing::instrument(err, skip_all)]
+pub async fn add_favorite_handler<S, AccessSvc>(
+ State(state): State<FavoritesRouterState<S, AccessSvc>>,
+ user: MacroUserExtractor,
+ Json(req): Json<AddFavoriteRequest>,
+) -> Result<Json<Favorite>, FavoritesApiError>
+where
+ S: FavoritesService,
+ AccessSvc: EntityAccessService,
+{
+ // Only let the caller favorite entities they can actually access, so a
+ // favorite can't be used as an oracle for entity metadata (name, subject,
+ // private-channel type) they were never allowed to see.
+ ensure_entity_access(
+ state.access_service.as_ref(),
+ &user,
+ req.entity_type,
+ &req.entity_id,
+ )
+ .await?;
+ let entity = req.entity_type.with_entity_str(&req.entity_id);
+ let favorite = state
+ .service
+ .add_favorite(&user.macro_user_id, &entity)
+ .await?;
+ Ok(Json(favorite))
+}
+
+/// Remove a favorite by entity.
+#[utoipa::path(
+ delete,
+ tag = "favorites",
+ operation_id = "remove_favorite_by_entity",
+ path = "/favorites/{entity_type}/{entity_id}",
+ params(RemoveFavoriteByEntityParams),
+ responses(
+ (status = 200, body = ()),
+ (status = 401, body = ErrorResponse),
+ (status = 404, body = ErrorResponse),
+ (status = 500, body = ErrorResponse),
+ )
+)]
+#[tracing::instrument(err, skip_all)]
+pub async fn remove_favorite_by_entity_handler<S, AccessSvc>(
+ State(state): State<FavoritesRouterState<S, AccessSvc>>,
+ user: MacroUserExtractor,
+ Path(params): Path<RemoveFavoriteByEntityParams>,
+) -> Result<Json<()>, FavoritesApiError>
+where
+ S: FavoritesService,
+ AccessSvc: EntityAccessService,
+{
+ let entity = params.entity_type.with_entity_str(&params.entity_id);
+ state
+ .service
+ .remove_favorite_by_entity(&user.macro_user_id, &entity)
+ .await?;
+ Ok(Json(()))
+}
+
+/// Persist a manual order for the caller's favorites.
+#[utoipa::path(
+ patch,
+ tag = "favorites",
+ operation_id = "reorder_favorites",
+ path = "/favorites/reorder",
+ request_body = ReorderFavoritesRequest,
+ responses(
+ (status = 200, body = ()),
+ (status = 400, body = ErrorResponse),
+ (status = 401, body = ErrorResponse),
+ (status = 500, body = ErrorResponse),
+ )
+)]
+#[tracing::instrument(err, skip_all)]
+pub async fn reorder_favorites_handler<S, AccessSvc>(
+ State(state): State<FavoritesRouterState<S, AccessSvc>>,
+ user: MacroUserExtractor,
+ Json(req): Json<ReorderFavoritesRequest>,
+) -> Result<Json<()>, FavoritesApiError>
+where
+ S: FavoritesService,
+ AccessSvc: EntityAccessService,
+{
+ let ordered: Vec<_> = req
+ .favorites
+ .iter()
+ .map(|r| r.entity_type.with_entity_str(&r.entity_id))
+ .collect();
+ state
+ .service
+ .reorder_favorites(&user.macro_user_id, &ordered)
+ .await?;
+ Ok(Json(()))
+}
+
+/// API-level error for favorites handlers.
+#[derive(Debug, thiserror::Error)]
+pub enum FavoritesApiError {
+ /// The caller does not have access to the entity they tried to favorite.
+ #[error("you do not have access to this entity")]
+ Forbidden,
+ /// Domain error.
+ #[error(transparent)]
+ Favorites(#[from] FavoritesError),
+}
+
+impl IntoResponse for FavoritesApiError {
+ fn into_response(self) -> axum::response::Response {
+ let status_code = match &self {
+ FavoritesApiError::Forbidden => StatusCode::FORBIDDEN,
+ FavoritesApiError::Favorites(FavoritesError::NotFound) => StatusCode::NOT_FOUND,
+ FavoritesApiError::Favorites(FavoritesError::BadRequest(_)) => StatusCode::BAD_REQUEST,
+ FavoritesApiError::Favorites(FavoritesError::Internal(_)) => {
+ StatusCode::INTERNAL_SERVER_ERROR
+ }
+ };
+
+ if status_code.is_server_error() {
+ tracing::error!(error=?self, "favorites internal server error");
+ }
+
+ let message = match &self {
+ FavoritesApiError::Favorites(FavoritesError::Internal(_)) => {
+ "internal server error".to_string()
+ }
+ error => error.to_string(),
+ };
+
+ (
+ status_code,
+ Json(ErrorResponse {
+ message: message.into(),
+ }),
+ )
+ .into_response()
+ }
+}
diff --git a/rust/cloud-storage/favorites/src/lib.rs b/rust/cloud-storage/favorites/src/lib.rs
new file mode 100644
index 0000000000..b4f3241eb4
--- /dev/null
+++ b/rust/cloud-storage/favorites/src/lib.rs
@@ -0,0 +1,17 @@
+#![deny(missing_docs)]
+//! Favorites: user- and team-scoped ordered collections of entities,
+//! following the hexagonal architecture pattern.
+//!
+//! # Architecture
+//!
+//! - **domain**: domain models, ports, and the service implementation.
+//! - **inbound**: driving adapters (Axum HTTP router).
+//! - **outbound**: driven adapters (Postgres repository).
+
+pub mod domain;
+
+#[cfg(feature = "inbound")]
+pub mod inbound;
+
+#[cfg(feature = "outbound")]
+pub mod outbound;
diff --git a/rust/cloud-storage/favorites/src/outbound.rs b/rust/cloud-storage/favorites/src/outbound.rs
new file mode 100644
index 0000000000..b0a0434412
--- /dev/null
+++ b/rust/cloud-storage/favorites/src/outbound.rs
@@ -0,0 +1,4 @@
+//! Outbound (driven) adapters for favorites.
+
+#[cfg(feature = "postgres")]
+pub mod pg_favorites_repo;
diff --git a/rust/cloud-storage/favorites/src/outbound/pg_favorites_repo.rs b/rust/cloud-storage/favorites/src/outbound/pg_favorites_repo.rs
new file mode 100644
index 0000000000..6aeeab3c78
--- /dev/null
+++ b/rust/cloud-storage/favorites/src/outbound/pg_favorites_repo.rs
@@ -0,0 +1,272 @@
+//! PostgreSQL implementation of the [`FavoritesRepo`] port.
+
+#[cfg(test)]
+mod tests;
+
+use std::collections::HashSet;
+
+use chrono::{DateTime, Utc};
+use macro_user_id::user_id::MacroUserIdStr;
+use model_entity::{Entity, EntityType};
+use sqlx::PgPool;
+
+use crate::domain::models::Favorite;
+use crate::domain::ports::FavoritesRepo;
+
+/// Postgres-backed favorites repository.
+#[derive(Debug, Clone)]
+pub struct PgFavoritesRepo {
+ pool: PgPool,
+}
+
+impl PgFavoritesRepo {
+ /// Create a repository backed by the provided pool.
+ pub fn new(pool: PgPool) -> Self {
+ Self { pool }
+ }
+}
+
+/// Errors produced by the Postgres favorites repository.
+#[derive(Debug, thiserror::Error)]
+pub enum FavoritesRepoErr {
+ /// Underlying database error.
+ #[error(transparent)]
+ Db(#[from] sqlx::Error),
+ /// A stored entity type could not be parsed into [EntityType].
+ #[error("invalid entity type stored for favorite: {0}")]
+ InvalidEntityType(String),
+}
+
+struct FavoriteRow {
+ entity_type: String,
+ entity_id: String,
+ sort_order: f64,
+ created_at: DateTime<Utc>,
+ name: Option<String>,
+ file_type: Option<String>,
+ document_sub_type: Option<String>,
+ channel_type: Option<String>,
+ channel_id: Option<String>,
+}
+
+impl FavoriteRow {
+ fn into_favorite(self) -> Result<Favorite, FavoritesRepoErr> {
+ let entity_type: EntityType = self
+ .entity_type
+ .parse()
+ .map_err(|_| FavoritesRepoErr::InvalidEntityType(self.entity_type.clone()))?;
+ Ok(Favorite {
+ entity_type,
+ entity_id: self.entity_id,
+ sort_order: self.sort_order,
+ created_at: self.created_at,
+ name: self.name,
+ file_type: self.file_type,
+ document_sub_type: self.document_sub_type,
+ channel_type: self.channel_type,
+ channel_id: self.channel_id,
+ })
+ }
+}
+
+impl FavoritesRepo for PgFavoritesRepo {
+ type Err = FavoritesRepoErr;
+
+ #[tracing::instrument(err, skip(self))]
+ async fn add_favorite(
+ &self,
+ user_id: &MacroUserIdStr<'_>,
+ entity: &Entity<'_>,
+ ) -> Result<Favorite, Self::Err> {
+ let entity_type: &str = entity.entity_type.into();
+ let row = sqlx::query_as!(
+ FavoriteRow,
+ r#"
+ INSERT INTO favorite (user_id, entity_type, entity_id, sort_order)
+ VALUES (
+ $1, $2, $3,
+ COALESCE((SELECT MAX(sort_order) + 1 FROM favorite WHERE user_id = $1), 0)
+ )
+ ON CONFLICT (user_id, entity_type, entity_id)
+ DO UPDATE SET updated_at = now()
+ RETURNING
+ entity_type as "entity_type!",
+ entity_id as "entity_id!",
+ sort_order as "sort_order!",
+ created_at as "created_at!",
+ NULL::text as "name?",
+ NULL::text as "file_type?",
+ NULL::text as "document_sub_type?",
+ NULL::text as "channel_type?",
+ NULL::text as "channel_id?"
+ "#,
+ user_id.as_ref(),
+ entity_type,
+ entity.entity_id.as_ref(),
+ )
+ .fetch_one(&self.pool)
+ .await?;
+ row.into_favorite()
+ }
+
+ #[tracing::instrument(err, skip(self))]
+ async fn count_favorites(&self, user_id: &MacroUserIdStr<'_>) -> Result<i64, Self::Err> {
+ let count = sqlx::query_scalar!(
+ r#"SELECT COUNT(*) as "count!" FROM favorite WHERE user_id = $1"#,
+ user_id.as_ref(),
+ )
+ .fetch_one(&self.pool)
+ .await?;
+ Ok(count)
+ }
+
+ #[tracing::instrument(err, skip(self))]
+ async fn list_favorites(
+ &self,
+ user_id: &MacroUserIdStr<'_>,
+ ) -> Result<Vec<Favorite>, Self::Err> {
+ // Resolves display metadata for the favorited entity where possible and
+ // omits favorites whose target is deleted.
+ let rows = sqlx::query_as!(
+ FavoriteRow,
+ r#"
+ SELECT
+ f.entity_type as "entity_type!",
+ f.entity_id as "entity_id!",
+ f.sort_order as "sort_order!",
+ f.created_at as "created_at!",
+ CASE f.entity_type
+ WHEN 'document' THEN d.name
+ WHEN 'chat' THEN c.name
+ WHEN 'project' THEN p.name
+ WHEN 'channel' THEN ch.name::text
+ WHEN 'email_thread' THEN em.subject
+ END as "name?",
+ d."fileType" as "file_type?",
+ dt.sub_type::text as "document_sub_type?",
+ ch.channel_type::text as "channel_type?",
+ cm.channel_id::text as "channel_id?"
+ FROM favorite f
+ LEFT JOIN "Document" d ON f.entity_type = 'document' AND d.id = f.entity_id
+ LEFT JOIN document_sub_type dt ON f.entity_type = 'document' AND dt.document_id = f.entity_id
+ LEFT JOIN "Chat" c ON f.entity_type = 'chat' AND c.id = f.entity_id
+ LEFT JOIN "Project" p ON f.entity_type = 'project' AND p.id = f.entity_id
+ LEFT JOIN comms_channels ch ON f.entity_type = 'channel' AND ch.id::text = f.entity_id
+ LEFT JOIN comms_messages cm ON f.entity_type = 'channel_message' AND cm.id::text = f.entity_id
+ LEFT JOIN email_threads et ON f.entity_type = 'email_thread' AND et.id::text = f.entity_id
+ LEFT JOIN LATERAL (
+ SELECT m.subject
+ FROM email_messages m
+ WHERE m.thread_id = et.id AND m.is_draft = false
+ ORDER BY m.internal_date_ts DESC NULLS LAST
+ LIMIT 1
+ ) em ON f.entity_type = 'email_thread'
+ WHERE f.user_id = $1
+ AND (f.entity_type <> 'document' OR (d.id IS NOT NULL AND d."deletedAt" IS NULL))
+ AND (f.entity_type <> 'chat' OR (c.id IS NOT NULL AND c."deletedAt" IS NULL))
+ AND (f.entity_type <> 'project' OR (p.id IS NOT NULL AND p."deletedAt" IS NULL))
+ ORDER BY f.sort_order ASC, f.created_at ASC
+ "#,
+ user_id.as_ref(),
+ )
+ .fetch_all(&self.pool)
+ .await?;
+ rows.into_iter().map(FavoriteRow::into_favorite).collect()
+ }
+
+ #[tracing::instrument(err, skip(self))]
+ async fn remove_favorite_by_entity(
+ &self,
+ user_id: &MacroUserIdStr<'_>,
+ entity: &Entity<'_>,
+ ) -> Result<bool, Self::Err> {
+ let entity_type: &str = entity.entity_type.into();
+ let res = sqlx::query!(
+ r#"
+ DELETE FROM favorite
+ WHERE user_id = $1 AND entity_type = $2 AND entity_id = $3
+ "#,
+ user_id.as_ref(),
+ entity_type,
+ entity.entity_id.as_ref(),
+ )
+ .execute(&self.pool)
+ .await?;
+ Ok(res.rows_affected() > 0)
+ }
+
+ #[tracing::instrument(err, skip(self, ordered))]
+ async fn reorder_favorites(
+ &self,
+ user_id: &MacroUserIdStr<'_>,
+ ordered: &[Entity<'_>],
+ ) -> Result<(), Self::Err> {
+ let (entity_types, entity_ids): (Vec<String>, Vec<String>) = ordered
+ .iter()
+ .map(|e| {
+ (
+ <&str>::from(e.entity_type).to_string(),
+ e.entity_id.to_string(),
+ )
+ })
+ .unzip();
+ sqlx::query!(
+ r#"
+ UPDATE favorite f
+ SET sort_order = x.ord::float8 - 1, updated_at = now()
+ FROM UNNEST($2::text[], $3::text[]) WITH ORDINALITY AS x(entity_type, entity_id, ord)
+ WHERE f.user_id = $1
+ AND f.entity_type = x.entity_type
+ AND f.entity_id = x.entity_id
+ "#,
+ user_id.as_ref(),
+ &entity_types,
+ &entity_ids,
+ )
+ .execute(&self.pool)
+ .await?;
+ Ok(())
+ }
+
+ #[tracing::instrument(err, skip(self, entities))]
+ async fn favorited_entities(
+ &self,
+ user_id: &MacroUserIdStr<'_>,
+ entities: &[Entity<'_>],
+ ) -> Result<HashSet<Entity<'static>>, Self::Err> {
+ let (entity_types, entity_ids): (Vec<String>, Vec<String>) = entities
+ .iter()
+ .map(|e| {
+ (
+ <&str>::from(e.entity_type).to_string(),
+ e.entity_id.to_string(),
+ )
+ })
+ .unzip();
+
+ let rows = sqlx::query!(
+ r#"
+ SELECT DISTINCT f.entity_type as "entity_type!", f.entity_id as "entity_id!"
+ FROM favorite f
+ JOIN UNNEST($2::text[], $3::text[]) AS w(entity_type, entity_id)
+ ON w.entity_type = f.entity_type AND w.entity_id = f.entity_id
+ WHERE f.user_id = $1
+ "#,
+ user_id.as_ref(),
+ &entity_types,
+ &entity_ids,
+ )
+ .fetch_all(&self.pool)
+ .await?;
+
+ rows.into_iter()
+ .map(|r| {
+ let entity_type: EntityType = r
+ .entity_type
+ .parse()
+ .map_err(|_| FavoritesRepoErr::InvalidEntityType(r.entity_type.clone()))?;
+ Ok(entity_type.with_entity_string(r.entity_id))
+ })
+ .collect()
+ }
+}
diff --git a/rust/cloud-storage/favorites/src/outbound/pg_favorites_repo/tests.rs b/rust/cloud-storage/favorites/src/outbound/pg_favorites_repo/tests.rs
new file mode 100644
index 0000000000..fa67a4637c
--- /dev/null
+++ b/rust/cloud-storage/favorites/src/outbound/pg_favorites_repo/tests.rs
@@ -0,0 +1,249 @@
+use cowlike::CowLike;
+use macro_db_migrator::MACRO_DB_MIGRATIONS;
+use macro_user_id::user_id::MacroUserIdStr;
+use model_entity::EntityType;
+use sqlx::PgPool;
+use uuid::Uuid;
+
+use super::PgFavoritesRepo;
+use crate::domain::ports::FavoritesRepo;
+
+const USER_A: &str = "macro|[email protected]";
+const USER_B: &str = "macro|[email protected]";
+
+fn user(id: &str) -> MacroUserIdStr<'_> {
+ MacroUserIdStr::parse_from_str(id).expect("valid user id")
+}
+
+async fn insert_user(pool: &PgPool, id: &str) {
+ let macro_user_id = Uuid::now_v7();
+ sqlx::query(
+ r#"INSERT INTO macro_user (id, username, email, stripe_customer_id) VALUES ($1, $2, $2, $2)"#,
+ )
+ .bind(macro_user_id)
+ .bind(id)
+ .execute(pool)
+ .await
+ .expect("macro_user should insert");
+ sqlx::query(r#"INSERT INTO "User" (id, email, macro_user_id) VALUES ($1, $1, $2)"#)
+ .bind(id)
+ .bind(macro_user_id)
+ .execute(pool)
+ .await
+ .expect("user should insert");
+}
+
+async fn insert_document(pool: &PgPool, id: &str, name: &str, owner: &str) {
+ sqlx::query(r#"INSERT INTO "Document" (id, name, owner) VALUES ($1, $2, $3)"#)
+ .bind(id)
+ .bind(name)
+ .bind(owner)
+ .execute(pool)
+ .await
+ .expect("document should insert");
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn add_favorite_appends_and_is_idempotent(pool: PgPool) {
+ insert_user(&pool, USER_A).await;
+ let repo = PgFavoritesRepo::new(pool);
+
+ let first = repo
+ .add_favorite(
+ &user(USER_A),
+ &EntityType::Document.with_entity_str("doc-1"),
+ )
+ .await
+ .expect("first favorite should insert");
+ let second = repo
+ .add_favorite(
+ &user(USER_A),
+ &EntityType::Channel.with_entity_str("chan-1"),
+ )
+ .await
+ .expect("second favorite should insert");
+ assert!(second.sort_order > first.sort_order);
+
+ let duplicate = repo
+ .add_favorite(
+ &user(USER_A),
+ &EntityType::Document.with_entity_str("doc-1"),
+ )
+ .await
+ .expect("duplicate favorite should be a no-op");
+ // The existing record is returned unchanged (same position).
+ assert_eq!(duplicate.sort_order, first.sort_order);
+ assert_eq!(
+ repo.count_favorites(&user(USER_A))
+ .await
+ .expect("count should run"),
+ 2
+ );
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn count_favorites_counts_user_collection(pool: PgPool) {
+ insert_user(&pool, USER_A).await;
+ let repo = PgFavoritesRepo::new(pool);
+
+ assert_eq!(
+ repo.count_favorites(&user(USER_A))
+ .await
+ .expect("count should run"),
+ 0
+ );
+
+ for entity_id in ["doc-1", "doc-2", "doc-3"] {
+ repo.add_favorite(
+ &user(USER_A),
+ &EntityType::Document.with_entity_str(entity_id),
+ )
+ .await
+ .expect("favorite should insert");
+ }
+ // Re-adding an existing entity is a no-op and must not inflate the count.
+ repo.add_favorite(
+ &user(USER_A),
+ &EntityType::Document.with_entity_str("doc-1"),
+ )
+ .await
+ .expect("duplicate favorite should be a no-op");
+
+ assert_eq!(
+ repo.count_favorites(&user(USER_A))
+ .await
+ .expect("count should run"),
+ 3
+ );
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn list_favorites_hydrates_names_and_skips_deleted(pool: PgPool) {
+ insert_user(&pool, USER_A).await;
+ insert_document(&pool, "doc-live", "Launch plan", USER_A).await;
+ insert_document(&pool, "doc-gone", "Old doc", USER_A).await;
+ sqlx::query(r#"UPDATE "Document" SET "deletedAt" = now() WHERE id = 'doc-gone'"#)
+ .execute(&pool)
+ .await
+ .expect("document should soft delete");
+
+ let repo = PgFavoritesRepo::new(pool);
+ for entity_id in ["doc-live", "doc-gone"] {
+ repo.add_favorite(
+ &user(USER_A),
+ &EntityType::Document.with_entity_str(entity_id),
+ )
+ .await
+ .expect("favorite should insert");
+ }
+ // An entity with no local table (e.g. a foreign id) still lists, unhydrated.
+ repo.add_favorite(
+ &user(USER_A),
+ &EntityType::EmailThread.with_entity_str(&Uuid::now_v7().to_string()),
+ )
+ .await
+ .expect("email favorite should insert");
+
+ let favorites = repo
+ .list_favorites(&user(USER_A))
+ .await
+ .expect("favorites should list");
+ assert_eq!(favorites.len(), 2);
+ assert_eq!(favorites[0].entity_id, "doc-live");
+ assert_eq!(favorites[0].name.as_deref(), Some("Launch plan"));
+ assert_eq!(favorites[1].entity_type, EntityType::EmailThread);
+ assert_eq!(favorites[1].name, None);
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn remove_favorite_by_entity_scopes_to_user(pool: PgPool) {
+ insert_user(&pool, USER_A).await;
+ insert_user(&pool, USER_B).await;
+ insert_document(&pool, "doc-1", "Doc 1", USER_A).await;
+ let repo = PgFavoritesRepo::new(pool);
+ let entity = EntityType::Document.with_entity_str("doc-1");
+
+ repo.add_favorite(&user(USER_A), &entity)
+ .await
+ .expect("user A favorite should insert");
+ repo.add_favorite(&user(USER_B), &entity)
+ .await
+ .expect("user B favorite should insert");
+
+ let removed = repo
+ .remove_favorite_by_entity(&user(USER_A), &entity)
+ .await
+ .expect("user A unfavorite should run");
+ assert!(removed);
+
+ // User B's favorite for the same entity is untouched.
+ let b_favorites = repo
+ .list_favorites(&user(USER_B))
+ .await
+ .expect("user B favorites should list");
+ assert_eq!(b_favorites.len(), 1);
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn reorder_favorites_sets_manual_order(pool: PgPool) {
+ insert_user(&pool, USER_A).await;
+ for entity_id in ["a", "b", "c"] {
+ insert_document(&pool, entity_id, entity_id, USER_A).await;
+ }
+ let repo = PgFavoritesRepo::new(pool);
+
+ for entity_id in ["a", "b", "c"] {
+ repo.add_favorite(
+ &user(USER_A),
+ &EntityType::Document.with_entity_str(entity_id),
+ )
+ .await
+ .expect("favorite should insert");
+ }
+
+ let reordered =
+ ["c", "b", "a"].map(|entity_id| EntityType::Document.with_entity_str(entity_id));
+ repo.reorder_favorites(&user(USER_A), &reordered)
+ .await
+ .expect("reorder should run");
+
+ let favorites = repo
+ .list_favorites(&user(USER_A))
+ .await
+ .expect("favorites should list");
+ let listed: Vec<&str> = favorites.iter().map(|f| f.entity_id.as_str()).collect();
+ assert_eq!(listed, ["c", "b", "a"]);
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn favorited_entities_returns_user_favorites(pool: PgPool) {
+ insert_user(&pool, USER_A).await;
+ insert_user(&pool, USER_B).await;
+ let repo = PgFavoritesRepo::new(pool);
+
+ let user_entity = EntityType::Document.with_entity_str("doc-user");
+ let other_entity = EntityType::Chat.with_entity_str("chat-other");
+
+ repo.add_favorite(&user(USER_A), &user_entity)
+ .await
+ .expect("user favorite should insert");
+
+ let favorited = repo
+ .favorited_entities(
+ &user(USER_A),
+ &[user_entity.copied(), other_entity.copied()],
+ )
+ .await
+ .expect("favorited lookup should run");
+
+ assert_eq!(favorited.len(), 1);
+ assert!(favorited.contains(&user_entity));
+ assert!(!favorited.contains(&other_entity));
+
+ // USER_B has not favorited the entity, so it is not returned for them.
+ let favorited_b = repo
+ .favorited_entities(&user(USER_B), &[user_entity.copied()])
+ .await
+ .expect("favorited lookup should run");
+ assert!(favorited_b.is_empty());
+}
diff --git a/rust/cloud-storage/justfile b/rust/cloud-storage/justfile
index c55c95dc87..bf6eadb50e 100644
--- a/rust/cloud-storage/justfile
+++ b/rust/cloud-storage/justfile
@@ -84,6 +84,7 @@ setup_test_envs:
echo "DATABASE_URL={{ DATABASE_URL }}" >> ./roles_and_permissions/.env
echo "DATABASE_URL={{ DATABASE_URL }}" >> ./teams/.env
echo "DATABASE_URL={{ DATABASE_URL }}" >> ./frecency/.env
+ echo "DATABASE_URL={{ DATABASE_URL }}" >> ./favorites/.env
echo "DATABASE_URL={{ DATABASE_URL }}" >> ./soup/.env
echo "DATABASE_URL={{ DATABASE_URL }}" >> ./email/.env
echo "DATABASE_URL={{ DATABASE_URL }}" >> ./system_properties/.env
diff --git a/rust/cloud-storage/macro_db_client/migrations/20260702014623_create_favorites_table.sql b/rust/cloud-storage/macro_db_client/migrations/20260702014623_create_favorites_table.sql
new file mode 100644
index 0000000000..3262f9e2cc
--- /dev/null
+++ b/rust/cloud-storage/macro_db_client/migrations/20260702014623_create_favorites_table.sql
@@ -0,0 +1,19 @@
+-- Favorites: a user's personal ordered collection of entities.
+CREATE TABLE favorite
+(
+ user_id TEXT NOT NULL REFERENCES "User" (id) ON DELETE CASCADE,
+ entity_type TEXT NOT NULL,
+ entity_id TEXT NOT NULL,
+ sort_order DOUBLE PRECISION NOT NULL DEFAULT 0,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ -- A favorite is identified by what it points at; one favorite per entity
+ -- per user.
+ PRIMARY KEY (user_id, entity_type, entity_id)
+);
+
+-- Ordered listing per user.
+CREATE INDEX favorite_user_sort_idx ON favorite (user_id, sort_order);
+
+-- Reverse lookup: "is this entity favorited?" checks by (entity_type, entity_id).
+CREATE INDEX favorite_entity_idx ON favorite (entity_type, entity_id);
diff --git a/rust/cloud-storage/soup/src/inbound/axum_router.rs b/rust/cloud-storage/soup/src/inbound/axum_router.rs
index 2c606c3f88..60b0f924c3 100644
--- a/rust/cloud-storage/soup/src/inbound/axum_router.rs
+++ b/rust/cloud-storage/soup/src/inbound/axum_router.rs
@@ -13,6 +13,7 @@ use axum::{
routing::{get, post},
};
use axum_extra::{either::Either, extract::Cached};
+use cowlike::CowLike;
use email::{
domain::{
models::{EmailErr, PreviewView},
@@ -44,6 +45,7 @@ use item_filters::{
},
};
use macro_user_id::user_id::MacroUserIdStr;
+use model_entity::Entity;
use model_error_response::ErrorResponse;
use model_user::axum_extractor::MacroUserExtractor;
use models_grouping::{GroupByField, GroupingConfig};
@@ -56,7 +58,8 @@ use non_empty::IsEmpty;
use recursion::CollapsibleExt;
use rootcause::{Report, report};
use serde::{Deserialize, Serialize};
-use std::collections::HashMap;
+use std::collections::{HashMap, HashSet};
+use std::pin::Pin;
use std::sync::Arc;
use thiserror::Error;
use utoipa::{IntoParams, ToSchema};
@@ -353,11 +356,38 @@ struct ApiGroupedSoupParts {
groups: Vec<ApiGroupMeta>,
}
+/// Reader used to flag soup items that the requesting user (or their team)
+/// has favorited. Object-safe so the router state can hold it without an
+/// extra generic; the concrete impl is provided by the mounting service.
+pub trait SoupFavoritesReader: Send + Sync + 'static {
+ /// Of the given entities, return the subset favorited by the user or
+ /// the user's team.
+ fn favorited_entities<'a>(
+ &'a self,
+ user_id: &'a str,
+ entities: Vec<Entity<'static>>,
+ ) -> Pin<Box<dyn Future<Output = anyhow::Result<HashSet<Entity<'static>>>> + Send + 'a>>;
+}
+
+/// Default [SoupFavoritesReader] that marks nothing as favorited.
+pub struct NoFavoritesReader;
+
+impl SoupFavoritesReader for NoFavoritesReader {
+ fn favorited_entities<'a>(
+ &'a self,
+ _user_id: &'a str,
+ _entities: Vec<Entity<'static>>,
+ ) -> Pin<Box<dyn Future<Output = anyhow::Result<HashSet<Entity<'static>>>> + Send + 'a>> {
+ Box::pin(async { Ok(HashSet::new()) })
+ }
+}
+
/// Shared state for soup API routes.
pub struct SoupRouterState<T, U, EAS> {
service: Arc<T>,
email: EmailRouterState<U>,
entity_access_service: Arc<EAS>,
+ favorites: Arc<dyn SoupFavoritesReader>,
}
impl<T, U, EAS> Clone for SoupRouterState<T, U, EAS> {
@@ -366,6 +396,7 @@ impl<T, U, EAS> Clone for SoupRouterState<T, U, EAS> {
service: self.service.clone(),
email: self.email.clone(),
entity_access_service: self.entity_access_service.clone(),
+ favorites: self.favorites.clone(),
}
}
}
@@ -399,9 +430,17 @@ where
service,
email: EmailRouterState::new(email),
entity_access_service,
+ favorites: Arc::new(NoFavoritesReader),
}
}
+ /// Attach a [SoupFavoritesReader] used to populate `is_favorited` on
+ /// returned soup items.
+ pub fn with_favorites_reader(mut self, favorites: Arc<dyn SoupFavoritesReader>) -> Self {
+ self.favorites = favorites;
+ self
+ }
+
/// Returns an `Arc` to the inner soup service.
pub fn service(&self) -> Arc<T> {
Arc::clone(&self.service)
@@ -428,6 +467,7 @@ where
SoupRequest<R>: IntoSoupReqAst,
R: Clone + Serialize + Send + RequestsCrmScope + RequestsCrmAdmin,
{
+ let user_for_favorites = macro_user_id.copied().into_owned();
let create_fallback = move || -> SoupQuery<R> {
let params_sort = params
.sort_method
@@ -477,9 +517,10 @@ where
)
.await?;
- Ok(Json(
- res.type_erase().map(SoupApiItem::from_frecency_soup_item),
- ))
+ let mut page = res.type_erase().map(SoupApiItem::from_frecency_soup_item);
+ mark_favorited(&*self.favorites, &user_for_favorites, page.items.iter_mut()).await;
+
+ Ok(Json(page))
}
async fn handle_grouped(
@@ -489,6 +530,7 @@ where
params: GroupedParams,
cursor: Option<CursorWithValAndFilter<Uuid, SimpleSortMethod, EntityFilterAst>>,
) -> Result<ApiGroupedSoupParts, SoupHandlerErr> {
+ let user_for_favorites = macro_user_id.copied().into_owned();
let limit = params.limit.unwrap_or(20).clamp(20, 500);
let sort_method = params
.sort_method
@@ -525,12 +567,15 @@ where
filters,
);
+ let mut items: HashMap<Uuid, SoupApiItem> = response
+ .items
+ .into_iter()
+ .map(|(id, item)| (id, SoupApiItem::from_frecency_soup_item(item)))
+ .collect();
+ mark_favorited(&*self.favorites, &user_for_favorites, items.values_mut()).await;
+
Ok(ApiGroupedSoupParts {
- items: response
- .items
- .into_iter()
- .map(|(id, item)| (id, SoupApiItem::from_frecency_soup_item(item)))
- .collect(),
+ items,
groups: response
.groups
.into_iter()
@@ -625,6 +670,8 @@ pub struct SoupApiItem {
#[serde(flatten)]
item: SoupItem,
frecency_score: f64,
+ /// Whether the requesting user has favorited this entity.
+ is_favorited: bool,
}
impl SoupApiItem {
@@ -638,6 +685,35 @@ impl SoupApiItem {
frecency_score: frecency_score
.map(|f| f.data.frecency_score)
.unwrap_or_default(),
+ is_favorited: false,
+ }
+ }
+}
+
+/// Populate `is_favorited` on the given items from one batched favorites
+/// lookup. A lookup failure leaves every flag `false` rather than failing
+/// the soup query.
+async fn mark_favorited<'a>(
+ favorites: &dyn SoupFavoritesReader,
+ user_id: &MacroUserIdStr<'_>,
+ items: impl Iterator<Item = &'a mut SoupApiItem>,
+) {
+ let items: Vec<&mut SoupApiItem> = items.collect();
+ if items.is_empty() {
+ return;
+ }
+ let entities = items.iter().map(|i| i.item.entity()).collect();
+ match favorites
+ .favorited_entities(user_id.as_ref(), entities)
+ .await
+ {
+ Ok(favorited) => {
+ for item in items {
+ item.is_favorited = favorited.contains(&item.item.entity());
+ }
+ }
+ Err(error) => {
+ tracing::error!(error=?error, "failed to resolve favorited soup items");
}
}
}