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(new-layout): new agents view (#6377)

dev-rb7aba85e459e4
diff --git a/apps/web/src/components/app/PreviewPanel.tsx b/apps/web/src/components/app/PreviewPanel.tsx
index 608ebde1a5..b4be1996f7 100644
--- a/apps/web/src/components/app/PreviewPanel.tsx
+++ b/apps/web/src/components/app/PreviewPanel.tsx
@@ -1,8 +1,11 @@
import {
+ type CalendarPreviewSelection,
+ type ChannelPreviewSelection,
calendarBlockParamsForEntity,
getChannelEntityTarget,
navigateCalendarEntityToTarget,
navigateChannelEntityToTarget,
+ type ReminderPreviewSelection,
reminderSplitTarget,
} from '@app/features/next-soup/utils';
import { CALENDAR_BLOCK_ID } from '@block-calendar/types';
@@ -16,12 +19,7 @@ import { fileTypeToResolvedBlockName } from '@core/constant/allBlocks';
import { USE_MACRO_PR_SUMMARY_BLOCK } from '@core/constant/featureFlags';
import { useHotkeyDOMScope } from '@core/hotkey/hotkeys';
import type { BlockOrchestrator } from '@core/orchestrator';
-import {
- type EntityData,
- isGithubPrEntity,
- isSnippetEntity,
- isTaskEntity,
-} from '@entity';
+import type { DocumentEntity, ForeignEntity } from '@entity';
import { createContextProvider } from '@solid-primitives/context';
import {
createMemo,
@@ -44,16 +42,50 @@ import {
type SplitPanelContextType,
} from './split-layout/context';
+type IdOnlyPreviewSelection = {
+ id: string;
+ type:
+ | 'agent_session'
+ | 'automation'
+ | 'call'
+ | 'chat'
+ | 'crm_company'
+ | 'crm_contact'
+ | 'email'
+ | 'project';
+};
+
+type DocumentPreviewSelection = Pick<
+ DocumentEntity,
+ 'id' | 'type' | 'fileType' | 'subType'
+>;
+
+type ForeignPreviewSelection = Pick<
+ ForeignEntity,
+ 'id' | 'type' | 'foreignSource'
+>;
+
+export type PreviewPanelSelection =
+ | IdOnlyPreviewSelection
+ | DocumentPreviewSelection
+ | ForeignPreviewSelection
+ | ChannelPreviewSelection
+ | CalendarPreviewSelection
+ | ReminderPreviewSelection;
+
export const [PreviewPanelContext, useMaybePreviewPanel] =
createContextProvider(
- (props: { previewEntity: EntityData; onFocusOut?: VoidFunction }) => ({
+ (props: {
+ previewEntity: PreviewPanelSelection;
+ onFocusOut?: VoidFunction;
+ }) => ({
previewEntity: () => props.previewEntity,
onFocusOut: () => props.onFocusOut?.(),
})
);
export type PreviewPanelProps = {
- selectedEntity: EntityData | undefined;
+ selectedEntity: PreviewPanelSelection | undefined;
orchestrator: BlockOrchestrator;
splitPanelContext: SplitPanelContextType;
onFocusOut?: VoidFunction;
@@ -69,7 +101,7 @@ type PreviewBlockTarget = {
};
function PreviewPanelContent(
- props: PreviewPanelProps & { selectedEntity: EntityData }
+ props: PreviewPanelProps & { selectedEntity: PreviewPanelSelection }
) {
const scopedLayoutRefs: SplitPanelContextType['layoutRefs'] = {};
const headerCollapseController = createPriorityCollapseController();
@@ -83,22 +115,28 @@ function PreviewPanelContent(
const target = match(entity)
.returnType<PreviewBlockTarget>()
- .when(isTaskEntity, (task) => ({
- blockType: fileTypeToResolvedBlockName(task.fileType),
- blockId: task.id,
- aliasContext: {
- alias: 'task',
- baseType: 'md',
- } satisfies BlockAliasContext,
- }))
- .when(isSnippetEntity, (snippet) => ({
- blockType: fileTypeToResolvedBlockName(snippet.fileType),
- blockId: snippet.id,
- aliasContext: {
- alias: 'snippet',
- baseType: 'md',
- } satisfies BlockAliasContext,
- }))
+ .with(
+ { type: 'document', fileType: 'md', subType: { type: 'task' } },
+ (task) => ({
+ blockType: fileTypeToResolvedBlockName(task.fileType),
+ blockId: task.id,
+ aliasContext: {
+ alias: 'task',
+ baseType: 'md',
+ } satisfies BlockAliasContext,
+ })
+ )
+ .with(
+ { type: 'document', fileType: 'md', subType: { type: 'snippet' } },
+ (snippet) => ({
+ blockType: fileTypeToResolvedBlockName(snippet.fileType),
+ blockId: snippet.id,
+ aliasContext: {
+ alias: 'snippet',
+ baseType: 'md',
+ } satisfies BlockAliasContext,
+ })
+ )
.with({ type: 'document' }, (document) => ({
blockType: fileTypeToResolvedBlockName(document.fileType),
blockId: document.id,
@@ -124,7 +162,8 @@ function PreviewPanelContent(
)
.with({ type: 'foreign' }, (foreignEntity) => ({
blockType:
- USE_MACRO_PR_SUMMARY_BLOCK && isGithubPrEntity(foreignEntity)
+ USE_MACRO_PR_SUMMARY_BLOCK &&
+ foreignEntity.foreignSource === 'github_pull_request'
? 'pr'
: 'unknown',
blockId: foreignEntity.id,
@@ -175,8 +214,15 @@ function PreviewPanelContent(
() => props.selectedEntity,
(entity) => {
setInteractedWith(false);
- void navigateChannelEntityToTarget(entity, props.orchestrator);
- void navigateCalendarEntityToTarget(entity, props.orchestrator);
+ if (
+ entity.type === 'channel' ||
+ entity.type === 'channel_message' ||
+ entity.type === 'channel_thread'
+ ) {
+ void navigateChannelEntityToTarget(entity, props.orchestrator);
+ } else if (entity.type === 'calendar_event') {
+ void navigateCalendarEntityToTarget(entity, props.orchestrator);
+ }
}
)
);
diff --git a/apps/web/src/components/app/split-layout/componentRegistry.tsx b/apps/web/src/components/app/split-layout/componentRegistry.tsx
index 3bf2c9e989..1572923734 100644
--- a/apps/web/src/components/app/split-layout/componentRegistry.tsx
+++ b/apps/web/src/components/app/split-layout/componentRegistry.tsx
@@ -1,5 +1,6 @@
import { openEntityInSplit } from '@app/features/activity/open-entity-in-split';
import { useActivityFeedFlag } from '@app/features/activity/use-activity-feed-flag';
+import { AgentsView } from '@app/features/agents-view/views/AgentsView';
import { ComposeAgentSession } from '@app/features/block-agent/component/ComposeAgentSession';
import type { EventEditorInitialValues } from '@app/features/calendar/components/composer/event-form-model';
import type { CalendarEvent } from '@app/features/calendar/types';
@@ -372,27 +373,44 @@ registerComponent('my-activity', () => (
<RedirectSplit to={{ type: 'component', id: 'activity' }} />
));
-registerComponent(
- 'agents',
- withAuth(() => {
- usePageViewTracking('agents');
- const user = useUserContext();
- const preset = getViewPreset('agents', undefined, {
- userId: user.userId(),
- isTeamAdmin: false,
- });
- const automationEntities = useAutomationEntities();
- return (
- <SoupView
- viewName="Agents"
- initialFilters={preset?.filters}
- initialClientFilters={preset?.clientFilters}
- initialGroupBy={preset?.groupBy}
- additionalEntities={automationEntities}
- />
- );
- })
-);
+function LegacyAgentsView() {
+ const user = useUserContext();
+ const preset = getViewPreset('agents', undefined, {
+ userId: user.userId(),
+ isTeamAdmin: false,
+ });
+ const automationEntities = useAutomationEntities();
+
+ return (
+ <SoupView
+ viewName="Agents"
+ initialFilters={preset?.filters}
+ initialClientFilters={preset?.clientFilters}
+ initialGroupBy={preset?.groupBy}
+ additionalEntities={automationEntities}
+ />
+ );
+}
+
+function RegisteredAgentsView() {
+ usePageViewTracking('agents');
+ const newAppViews = useNewAppViews({
+ enabledLayout: () => (isTouchDevice() ? 'legacy' : 'composable'),
+ });
+
+ return (
+ <Show when={newAppViews.ready()} fallback={<LoadingBlock />}>
+ <Show
+ when={newAppViews.enabled() && !isTouchDevice()}
+ fallback={<LegacyAgentsView />}
+ >
+ <AgentsView />
+ </Show>
+ </Show>
+ );
+}
+
+registerComponent('agents', withAuth(RegisteredAgentsView));
function LegacyMailView() {
const preset = getViewPreset('mail');
diff --git a/apps/web/src/components/ui/components/EmptyStatePanel.tsx b/apps/web/src/components/ui/components/EmptyStatePanel.tsx
index f4afc41b30..78bb684e11 100644
--- a/apps/web/src/components/ui/components/EmptyStatePanel.tsx
+++ b/apps/web/src/components/ui/components/EmptyStatePanel.tsx
@@ -15,8 +15,10 @@ export interface EmptyStatePanelProps {
graphic?: Component<{ class?: string }>;
graphicClass?: string;
title?: string;
+ titleClass?: string;
description?: JSXElement;
descriptionClass?: string;
+ topSpacerClass?: string;
primaryAction?: EmptyStateAction;
actionsClass?: string;
/**
@@ -60,7 +62,13 @@ export function EmptyStatePanel(props: EmptyStatePanelProps) {
position is constant; the bottom grows to fill. On mobile the viewport
is short and the panel already adds a top inset, so the spacer is
reduced to keep content from overflowing the visible area. */}
- <div aria-hidden="true" class="shrink-0 basis-[28%] mobile:basis-[8%]" />
+ <div
+ aria-hidden="true"
+ class={cn(
+ 'shrink-0 basis-[28%] mobile:basis-[8%]',
+ props.topSpacerClass
+ )}
+ />
<div
class={cn(
// Explicit vertical rhythm: a generous gap below the graphic, then a
@@ -84,7 +92,9 @@ export function EmptyStatePanel(props: EmptyStatePanelProps) {
)}
</Show>
<Show when={props.title}>
- <h2 class="text-base font-semibold text-ink">{props.title}</h2>
+ <h2 class={cn('text-base font-semibold text-ink', props.titleClass)}>
+ {props.title}
+ </h2>
</Show>
<Show when={props.description}>
<p
diff --git a/apps/web/src/features/agents-view/components/AgentResourceList.tsx b/apps/web/src/features/agents-view/components/AgentResourceList.tsx
new file mode 100644
index 0000000000..f9bc8690bd
--- /dev/null
+++ b/apps/web/src/features/agents-view/components/AgentResourceList.tsx
@@ -0,0 +1,96 @@
+import { runCreateAction } from '@app/features/command/Launcher';
+import {
+ compileToAst,
+ defineQueryFilters,
+ queryStateFrom,
+} from '@app/features/next-soup/filters/filter-store';
+import { useSplitLayout } from '@components/app/split-layout/layout';
+import ClockIcon from '@phosphor/clock-clockwise.svg';
+import PlusIcon from '@phosphor/plus.svg';
+import SkillIcon from '@phosphor/sparkle.svg';
+import { useAutomationEntities } from '@queries/agent-schedule/entities';
+import { useSoupAstItemsQuery } from '@queries/soup/items';
+import { Button } from '@ui';
+import { For, Show } from 'solid-js';
+import { Dynamic } from 'solid-js/web';
+
+export function AgentResourceList(props: { page: 'routines' | 'skills' }) {
+ const layout = useSplitLayout();
+ const automations = useAutomationEntities();
+ const skillsQuery = useSoupAstItemsQuery(
+ () => ({
+ params: { limit: 100, sort_method: 'updated_at' },
+ body: compileToAst(
+ queryStateFrom(defineQueryFilters({ include: { subType: ['skill'] } }))
+ ),
+ }),
+ () => ({ enabled: props.page === 'skills' })
+ );
+ const items = () =>
+ props.page === 'routines'
+ ? automations()
+ : skillsQuery.isLoading
+ ? []
+ : (skillsQuery.data?.entities ?? []);
+ const loading = () => props.page === 'skills' && skillsQuery.isLoading;
+ const error = () => props.page === 'skills' && Boolean(skillsQuery.error);
+
+ return (
+ <div class="flex h-full min-h-0 flex-col">
+ <div class="flex h-12 shrink-0 items-center px-4">
+ <Button
+ variant="ghost"
+ size="sm"
+ class="h-8 gap-2 rounded-lg bg-ink/4 px-3"
+ onClick={() =>
+ runCreateAction(props.page === 'routines' ? 'automation' : 'skill')
+ }
+ >
+ <PlusIcon class="size-3.5" />
+ {props.page === 'routines' ? 'New routine' : 'New skill'}
+ </Button>
+ </div>
+ <div class="min-h-0 flex-1 overflow-y-auto p-3">
+ <For each={items()}>
+ {(item) => (
+ <Button
+ variant="ghost"
+ class="h-12 w-full justify-start gap-3 rounded-xl px-3 font-normal"
+ onClick={() =>
+ layout.openWithSplit({
+ type: props.page === 'routines' ? 'automation' : 'skill',
+ id: item.id,
+ })
+ }
+ >
+ <Dynamic
+ component={props.page === 'routines' ? ClockIcon : SkillIcon}
+ class="size-4 text-ink-muted"
+ />
+ <span class="truncate">{item.name}</span>
+ </Button>
+ )}
+ </For>
+ <Show when={items().length === 0 && !error()}>
+ <p class="px-3 py-6 text-sm text-ink-muted">
+ {loading() ? 'Loading skills…' : `No ${props.page} yet`}
+ </p>
+ </Show>
+ <Show when={error()}>
+ <Button variant="ghost" onClick={() => void skillsQuery.refetch()}>
+ Retry loading skills
+ </Button>
+ </Show>
+ <Show when={props.page === 'skills' && skillsQuery.hasNextPage}>
+ <Button
+ variant="ghost"
+ disabled={skillsQuery.isFetchingNextPage}
+ onClick={() => void skillsQuery.fetchNextPage()}
+ >
+ {skillsQuery.isFetchingNextPage ? 'Loading…' : 'More skills'}
+ </Button>
+ </Show>
+ </div>
+ </div>
+ );
+}
diff --git a/apps/web/src/features/agents-view/components/AgentSessionPane.tsx b/apps/web/src/features/agents-view/components/AgentSessionPane.tsx
new file mode 100644
index 0000000000..ed1c34c2d4
--- /dev/null
+++ b/apps/web/src/features/agents-view/components/AgentSessionPane.tsx
@@ -0,0 +1,61 @@
+import { AgentComposer } from '@app/features/block-agent/component/AgentComposer';
+import { Transcript } from '@app/features/block-agent/component/Transcript';
+import {
+ AgentSessionProvider,
+ useAgentSession,
+} from '@app/features/block-agent/context/AgentSessionContext';
+import {
+ forgetPendingSession,
+ pendingSession,
+} from '@app/features/block-agent/context/pending-session';
+import { LoadErrorPanel } from '@core/component/EntityLoadGate';
+import { onCleanup, Show } from 'solid-js';
+
+function AgentSessionContent() {
+ const { loadFailed, loadRetryable, metadata, retryLoad, session } =
+ useAgentSession();
+
+ return (
+ <>
+ <header class="flex h-12 shrink-0 items-center border-b border-edge px-4">
+ <h2 class="truncate text-sm font-semibold text-ink">
+ {metadata()?.title ?? session()?.name ?? 'New Chat'}
+ </h2>
+ </header>
+ <Show
+ when={!loadFailed()}
+ fallback={
+ <LoadErrorPanel
+ title="Unable to load this session"
+ onRetry={loadRetryable() ? retryLoad : undefined}
+ />
+ }
+ >
+ <div class="flex min-h-0 flex-1 overflow-hidden">
+ <Transcript />
+ </div>
+ <div class="mx-auto w-full max-w-4xl shrink-0 px-4 pb-4">
+ <AgentComposer autofocus />
+ </div>
+ </Show>
+ </>
+ );
+}
+
+export function AgentSessionPane(props: {
+ id: string;
+ onSessionId: (sessionId: string) => void;
+}) {
+ const pending = pendingSession(props.id);
+ onCleanup(() => {
+ if (pending?.sessionId() || pending?.failed()) {
+ forgetPendingSession(props.id);
+ }
+ });
+
+ return (
+ <AgentSessionProvider blockId={props.id} onSessionId={props.onSessionId}>
+ <AgentSessionContent />
+ </AgentSessionProvider>
+ );
+}
diff --git a/apps/web/src/features/agents-view/components/AgentsSidebar.tsx b/apps/web/src/features/agents-view/components/AgentsSidebar.tsx
new file mode 100644
index 0000000000..bb9f771753
--- /dev/null
+++ b/apps/web/src/features/agents-view/components/AgentsSidebar.tsx
@@ -0,0 +1,450 @@
+import { createListController } from '@app/components/list';
+import {
+ CollapsibleSection,
+ SearchBar,
+ useViewControlHotkeys,
+ ViewSidebar,
+} from '@app/components/view-shell';
+import { DOCS_BASE } from '@app/constants/docs-links';
+import { FavoriteContextMenu } from '@app/features/favorites/FavoriteContextMenu';
+import { FavoriteIcon } from '@app/features/favorites/FavoriteIcon';
+import {
+ type EntityActionViewContext,
+ toEntityActionListState,
+} from '@app/features/next-soup/actions';
+import { SoupEntityContextMenu } from '@app/features/soup';
+import { DEBUG_SETTING_KEYS, useDebugSetting } from '@app/lib/debugSettings';
+import { useFavoriteDisplayName } from '@app/util/favorites';
+import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';
+import { SplitPanel } from '@components/app/split-panel';
+import { ScrollIndicators } from '@core/component/VerticalScrollIndicators';
+import EmptyStateAiGraphic from '@design/empty-state-ai.svg';
+import EmptyStateNoSearchMatchGraphic from '@design/empty-state-no-search-match.svg';
+import { EntityRowIcon } from '@entity';
+import BookOpenIcon from '@phosphor/book-open.svg';
+import ClockIcon from '@phosphor/clock-clockwise.svg';
+import MagnifyingGlassIcon from '@phosphor/magnifying-glass.svg';
+import PlugsIcon from '@phosphor/plugs.svg';
+import PlusIcon from '@phosphor/plus.svg';
+import RobotIcon from '@phosphor/robot.svg';
+import SkillIcon from '@phosphor/sparkle.svg';
+import SpinnerIcon from '@phosphor/spinner.svg';
+import {
+ type FavoritesFilter,
+ useFavoritesData,
+} from '@queries/favorites/favorites';
+import type { Favorite } from '@service-storage/generated/schemas/favorite';
+import { Key } from '@solid-primitives/keyed';
+import { Button, cn, EmptyStatePanel, Scroll } from '@ui';
+import {
+ createEffect,
+ createMemo,
+ createSignal,
+ For,
+ onCleanup,
+ Show,
+} from 'solid-js';
+import { Dynamic } from 'solid-js/web';
+import type { AgentsPage } from '../core/pages';
+import type {
+ AgentConversationEntity,
+ AgentConversationTarget,
+} from '../core/recent-conversations';
+
+const PAGES = [
+ { id: 'new', label: 'New Chat', icon: PlusIcon },
+ { id: 'routines', label: 'Routines', icon: ClockIcon },
+ { id: 'agents', label: 'Agents', icon: RobotIcon },
+ { id: 'connections', label: 'Connections', icon: PlugsIcon },
+ { id: 'skills', label: 'Skills', icon: SkillIcon },
+] satisfies {
+ id: AgentsPage;
+ label: string;
+ icon: typeof PlusIcon;
+}[];
+
+const AGENT_ACTION_VIEW_CONTEXT: EntityActionViewContext = {
+ supportsMarkDone: false,
+ senderBucket: undefined,
+};
+
+const AGENT_FAVORITES_FILTER = {
+ entityType: ['agent_session', 'chat'],
+} satisfies FavoritesFilter;
+
+function FavoriteRow(props: {
+ favorite: Favorite;
+ onOpen: (favorite: Favorite) => void;
+}) {
+ const name = useFavoriteDisplayName(props.favorite);
+
+ return (
+ <FavoriteContextMenu favorite={props.favorite} triggerClass="block">
+ <ViewSidebar.Item
+ class="font-normal"
+ title={name()}
+ onClick={() => props.onOpen(props.favorite)}
+ >
+ <span class="flex size-4 shrink-0 items-center justify-center">
+ <FavoriteIcon favorite={props.favorite} class="size-4" />
+ </span>
+ <span class="truncate">{name()}</span>
+ </ViewSidebar.Item>
+ </FavoriteContextMenu>
+ );
+}
+
+function AgentFavorites(props: {
+ onOpenConversation: (conversation: AgentConversationTarget) => void;
+}) {
+ const favoritesData = useFavoritesData(AGENT_FAVORITES_FILTER);
+ const [open, setOpen] = createSignal(true);
+ const favorites = createMemo(() =>
+ (favoritesData()?.favorites ?? []).toSorted(
+ (left, right) => left.sortOrder - right.sortOrder
+ )
+ );
+
+ const openFavorite = (favorite: Favorite) => {
+ if (
+ favorite.entityType !== 'agent_session' &&
+ favorite.entityType !== 'chat'
+ ) {
+ return;
+ }
+
+ props.onOpenConversation({
+ id: favorite.entityId,
+ type: favorite.entityType,
+ });
+ };
+
+ return (
+ <Show when={favorites().length > 0}>
+ <CollapsibleSection.Root open={open()} onOpenChange={setOpen}>
+ <CollapsibleSection.Trigger class="text-xs">
+ <CollapsibleSection.Indicator class="order-first ml-0" />
+ <span class="truncate">Favorites</span>
+ </CollapsibleSection.Trigger>
+ <CollapsibleSection.Content>
+ <ViewSidebar.Nav aria-label="Favorite agent chats">
+ <For each={favorites()}>
+ {(favorite) => (
+ <FavoriteRow favorite={favorite} onOpen={openFavorite} />
+ )}
+ </For>
+ </ViewSidebar.Nav>
+ </CollapsibleSection.Content>
+ </CollapsibleSection.Root>
+ </Show>
+ );
+}
+
+function ConversationRow(props: {
+ conversation: AgentConversationEntity;
+ active: boolean;
+ onOpen: () => void;
+}) {
+ return (
+ <ViewSidebar.Item
+ active={props.active}
+ class="font-normal"
+ title={props.conversation.name || 'Untitled chat'}
+ onClick={props.onOpen}
+ >
+ <span class="flex size-4 shrink-0 items-center justify-center">
+ <EntityRowIcon entity={props.conversation} class="size-4" />
+ </span>
+ <span class="truncate">{props.conversation.name || 'Untitled chat'}</span>
+ </ViewSidebar.Item>
+ );
+}
+
+function RecentChatsEmptyState(props: {
+ search: string;
+ onStartChat: () => void;
+}) {
+ const search = () => props.search.trim();
+
+ return (
+ <EmptyStatePanel
+ centered
+ graphic={search() ? EmptyStateNoSearchMatchGraphic : EmptyStateAiGraphic}
+ graphicClass="aspect-square h-auto w-[clamp(12rem,70%,18rem)] self-center"
+ title={search() ? `No results for "${search()}"` : 'No recent chats'}
+ description={
+ search()
+ ? 'Try a different search.'
+ : 'Your latest agent conversations will appear here.'
+ }
+ descriptionClass="mt-1 text-balance"
+ actionsClass="mt-5 flex-row @max-sm:flex-row"
+ topSpacerClass="basis-0"
+ titleClass={search() ? 'w-full break-words' : undefined}
+ primaryAction={
+ search()
+ ? undefined
+ : {
+ label: 'Start a chat',
+ icon: PlusIcon,
+ onClick: props.onStartChat,
+ }
+ }
+ documentationUrl={`${DOCS_BASE}/product/${search() ? 'search' : 'agents'}`}
+ documentationIcon={BookOpenIcon}
+ class="h-auto overflow-visible px-2 pt-4 @4xl:px-2"
+ />
+ );
+}
+
+export type AgentsSidebarProps = {
+ page: AgentsPage;
+ activeConversationId: string | undefined;
+ search: string;
+ conversations: AgentConversationEntity[];
+ loading: boolean;
+ error: boolean;
+ hasNextPage: boolean;
+ loadingNextPage: boolean;
+ loadMoreError: boolean;
+ onNavigate: (page: AgentsPage) => void;
+ onSearchChange: (search: string) => void;
+ onOpenConversation: (conversation: AgentConversationTarget) => void;
+ onRetry: () => void;
+ onLoadMore: () => void;
+};
+
+export function AgentsSidebar(props: AgentsSidebarProps) {
+ const panel = useSplitPanelOrThrow();
+ const forceEmptyState = useDebugSetting(
+ DEBUG_SETTING_KEYS.FORCE_EMPTY_STATES
+ );
+ const [searchOpen, setSearchOpen] = createSignal(false);
+ const [scrollRoot, setScrollRoot] = createSignal<HTMLElement>();
+ const [loadMoreSentinel, setLoadMoreSentinel] =
+ createSignal<HTMLDivElement>();
+ let searchInput: HTMLInputElement | undefined;
+ const visibleConversations = () =>
+ forceEmptyState() ? [] : props.conversations;
+ const actionController = createListController({
+ items: visibleConversations,
+ getKey: (conversation) => conversation.id,
+ isSelectable: () => false,
+ });
+ const actionList = toEntityActionListState({
+ controller: actionController,
+ getEntity: (conversation) => conversation,
+ });
+
+ const openSearch = () => {
+ setSearchOpen(true);
+ queueMicrotask(() => searchInput?.focus());
+ };
+
+ useViewControlHotkeys({
+ scopeId: panel.splitHotkeyScope,
+ enabled: panel.isPanelActive,
+ search: {
+ description: 'Search agent chats',
+ run: () => {
+ openSearch();
+ return true;
+ },
+ },
+ });
+
+ createEffect(() => {
+ const root = scrollRoot();
+ const sentinel = loadMoreSentinel();
+ if (
+ !root ||
+ !sentinel ||
+ forceEmptyState() ||
+ !props.hasNextPage ||
+ props.loadingNextPage ||
+ props.loadMoreError
+ ) {
+ return;
+ }
+
+ const observer = new IntersectionObserver(
+ (entries) => {
+ if (!entries[0]?.isIntersecting) return;
+ if (
+ forceEmptyState() ||
+ !props.hasNextPage ||
+ props.loadingNextPage ||
+ props.loadMoreError
+ ) {
+ return;
+ }
+ props.onLoadMore();
+ },
+ { root, rootMargin: '0px 0px 200px' }
+ );
+ observer.observe(sentinel);
+ onCleanup(() => observer.disconnect());
+ });
+
+ return (
+ <ViewSidebar.Root aria-label="Agents navigation">
+ <ViewSidebar.Header>
+ <div class="flex min-w-0 items-center gap-1">
+ <SplitPanel.CloseButton />
+ <ViewSidebar.Title>Agents</ViewSidebar.Title>
+ </div>
+ <SplitPanel.ControlGroup>
+ <SplitPanel.BackButton />
+ <SplitPanel.ForwardButton />
+ </SplitPanel.ControlGroup>
+ </ViewSidebar.Header>
+
+ <ViewSidebar.Content class="flex flex-col gap-6 overflow-hidden pt-4">
+ <ViewSidebar.Nav aria-label="Agent views">
+ <For each={PAGES}>
+ {(item) => (
+ <ViewSidebar.Item
+ active={props.page === item.id && !props.activeConversationId}
+ class="font-normal"
+ onClick={() => props.onNavigate(item.id)}
+ >
+ <Dynamic
+ component={item.icon}
+ aria-hidden="true"
+ class="size-4 shrink-0"
+ />
+ <span class="truncate">{item.label}</span>
+ </ViewSidebar.Item>
+ )}
+ </For>
+ </ViewSidebar.Nav>
+
+ <Show when={!forceEmptyState()}>
+ <AgentFavorites onOpenConversation={props.onOpenConversation} />
+ </Show>
+
+ <section class="flex min-h-0 flex-1 flex-col gap-1">
+ <div class="flex h-7 shrink-0 items-center justify-between pr-1 pl-3 text-xs font-medium text-ink-subtle">
+ <h2>Recent chats</h2>
+ <Button
+ variant="ghost"
+ size="icon-sm"
+ label={
+ searchOpen() ? 'Close agent chat search' : 'Search agent chats'
+ }
+ aria-pressed={searchOpen()}
+ class={cn(
+ 'size-7 rounded-lg',
+ searchOpen() && 'bg-active text-ink'
+ )}
+ onClick={() => {
+ if (searchOpen()) {
+ props.onSearchChange('');
+ setSearchOpen(false);
+ } else {
+ openSearch();
+ }
+ }}
+ >
+ <MagnifyingGlassIcon class="size-3.5" />
+ </Button>
+ </div>
+ <Show when={searchOpen()}>
+ <SearchBar
+ label="Search agent chats"
+ placeholder="Search chats"
+ ref={(element) => {
+ searchInput = element;
+ }}
+ value={props.search}
+ onValueChange={props.onSearchChange}
+ onEscape={() => {
+ if (!props.search) setSearchOpen(false);
+ }}
+ class="h-9 shrink-0 rounded-xl"
+ />
+ </Show>
+ <div class="relative min-h-0 flex-1">
+ <Scroll scrollRef={setScrollRoot}>
+ <ViewSidebar.Nav aria-label="Recent agent chats">
+ {/* Soup cache updates replace entity objects. Key rows by id so
+ those updates preserve the list DOM and scroll position. */}
+ <Key each={visibleConversations()} by="id">
+ {(conversation) => (
+ <SoupEntityContextMenu
+ entity={conversation()}
+ list={actionList}
+ selectedEntities={() => []}
+ viewContext={AGENT_ACTION_VIEW_CONTEXT}
+ class="block w-full"
+ onOpenChange={(open) => {
+ if (!open) return;
+ actionController.focus.set(conversation().id, {
+ reason: 'pointer',
+ force: true,
+ });
+ }}
+ >
+ <ConversationRow
+ conversation={conversation()}
+ active={
+ props.activeConversationId === conversation().id
+ }
+ onOpen={() => props.onOpenConversation(conversation())}
+ />
+ </SoupEntityContextMenu>
+ )}
+ </Key>
+ <Show when={!forceEmptyState() && props.loading}>
+ <p class="px-3 py-2 text-xs text-ink-muted">Loading chats…</p>
+ </Show>
+ <Show when={!forceEmptyState() && props.error}>
+ <Button variant="ghost" onClick={props.onRetry}>
+ Retry loading chats
+ </Button>
+ </Show>
+ <Show
+ when={
+ forceEmptyState() ||
+ (!props.loading &&
+ !props.error &&
+ props.conversations.length === 0)
+ }
+ >
+ <RecentChatsEmptyState
+ search={forceEmptyState() ? '' : props.search}
+ onStartChat={() => props.onNavigate('new')}
+ />
+ </Show>
+ <Show when={!forceEmptyState() && props.hasNextPage}>
+ <div
+ ref={setLoadMoreSentinel}
+ role={props.loadingNextPage ? 'status' : undefined}
+ aria-label={
+ props.loadingNextPage ? 'Loading more chats' : undefined
+ }
+ class="grid h-9 shrink-0 place-items-center text-ink-muted"
+ >
+ <Show when={props.loadMoreError}>
+ <Button variant="ghost" onClick={props.onLoadMore}>
+ Retry loading more chats
+ </Button>
+ </Show>
+ <Show when={!props.loadMoreError && props.loadingNextPage}>
+ <SpinnerIcon class="size-4 animate-spin" />
+ </Show>
+ </div>
+ </Show>
+ </ViewSidebar.Nav>
+ </Scroll>
+ <ScrollIndicators
+ scrollRef={scrollRoot}
+ appearance="gradient"
+ gradientColor="panel"
+ />
+ </div>
+ </section>
+ </ViewSidebar.Content>
+ </ViewSidebar.Root>
+ );
+}
diff --git a/apps/web/src/features/agents-view/core/pages.ts b/apps/web/src/features/agents-view/core/pages.ts
new file mode 100644
index 0000000000..4b705dfa30
--- /dev/null
+++ b/apps/web/src/features/agents-view/core/pages.ts
@@ -0,0 +1,6 @@
+export type AgentsPage =
+ | 'new'
+ | 'routines'
+ | 'agents'
+ | 'connections'
+ | 'skills';
diff --git a/apps/web/src/features/agents-view/core/recent-conversations.ts b/apps/web/src/features/agents-view/core/recent-conversations.ts
new file mode 100644
index 0000000000..8daa3f27b0
--- /dev/null
+++ b/apps/web/src/features/agents-view/core/recent-conversations.ts
@@ -0,0 +1,42 @@
+import type { AgentSessionEntity, ChatEntity, EntityData } from '@entity';
+
+export type AgentConversationEntity = AgentSessionEntity | ChatEntity;
+export type AgentConversationTarget = Pick<
+ AgentConversationEntity,
+ 'id' | 'type'
+>;
+
+function isAgentConversation(
+ entity: EntityData
+): entity is AgentConversationEntity {
+ return entity.type === 'agent_session' || entity.type === 'chat';
+}
+
+function timestamp(entity: AgentConversationEntity): number {
+ const value = entity.updatedAt ?? entity.createdAt;
+ if (!value) return 0;
+
+ const parsed = new Date(value).getTime();
+ return Number.isNaN(parsed) ? 0 : parsed;
+}
+
+/** Select the current user's agent conversations, newest first. */
+export function selectRecentAgentConversations(
+ entities: EntityData[],
+ ownerId: string | undefined,
+ search: string
+): AgentConversationEntity[] {
+ if (!ownerId) return [];
+
+ const query = search.trim().toLocaleLowerCase();
+
+ return entities
+ .filter(isAgentConversation)
+ .filter((entity) => entity.ownerId === ownerId)
+ .filter(
+ (entity) =>
+ !query ||
+ (entity.name || 'Untitled chat').toLocaleLowerCase().includes(query)
+ )
+ .toSorted((left, right) => timestamp(right) - timestamp(left));
+}
diff --git a/apps/web/src/features/agents-view/views/AgentsView.tsx b/apps/web/src/features/agents-view/views/AgentsView.tsx
new file mode 100644
index 0000000000..ce32957789
--- /dev/null
+++ b/apps/web/src/features/agents-view/views/AgentsView.tsx
@@ -0,0 +1,246 @@
+import { ViewShell } from '@app/components/view-shell';
+import { startPendingSession } from '@app/features/block-agent/context/pending-session';
+import { AgentInput } from '@app/features/block-agent/ui';
+import { HomeChatInput } from '@app/features/home/home';
+import { QUERY_FILTERS_BASE } from '@app/features/next-soup/filters/query-filters';
+import { Agents } from '@app/features/settings/Agents';
+import { ConnectedAccounts } from '@app/features/settings/ConnectedAccounts';
+import { useFeatureFlag } from '@app/lib/analytics/posthog';
+import { useGlobalBlockOrchestrator } from '@components/app/GlobalAppState';
+import { PreviewPanel } from '@components/app/PreviewPanel';
+import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';
+import { SplitPanel } from '@components/app/split-panel';
+import { ChatInputProvider } from '@core/component/AI/context';
+import { StaticMarkdownContext } from '@core/component/LexicalMarkdown/component/core/StaticMarkdown';
+import { enableChatV3Agents } from '@core/constant/featureFlags';
+import { useUserId } from '@core/context/user';
+import { ListEntityMetadataQueryProvider } from '@entity';
+import SpinnerIcon from '@phosphor/spinner.svg';
+import { useSoupItemsQuery } from '@queries/soup/items';
+import { createSignal, Match, onMount, Show, Suspense, Switch } from 'solid-js';
+import { AgentResourceList } from '../components/AgentResourceList';
+import { AgentSessionPane } from '../components/AgentSessionPane';
+import { AgentsSidebar } from '../components/AgentsSidebar';
+import type { AgentsPage } from '../core/pages';
+import {
+ type AgentConversationTarget,
+ selectRecentAgentConversations,
+} from '../core/recent-conversations';
+
+const PAGE_TITLES: Record<AgentsPage, string> = {
+ new: 'New Chat',
+ routines: 'Routines',
+ agents: 'Agents',
+ connections: 'Connections',
+ skills: 'Skills',
+};
+
+type SelectedConversation = {
+ conversation: AgentConversationTarget;
+ activeConversationId: string;
+};
+
+function LoadingComposer() {
+ return (
+ <div class="grid size-full place-items-center text-ink-muted">
+ <SpinnerIcon
+ aria-label="Loading agent composer"
+ class="size-5 animate-spin"
+ />
+ </div>
+ );
+}
+
+function AgentsWorkspace() {
+ const panel = useSplitPanelOrThrow();
+ const orchestrator = useGlobalBlockOrchestrator();
+ const userId = useUserId();
+ const agentsFlag = useFeatureFlag(enableChatV3Agents);
+ const [page, setPage] = createSignal<AgentsPage>('new');
+ const [selected, setSelected] = createSignal<SelectedConversation>();
+ const [search, setSearch] = createSignal('');
+ const query = useSoupItemsQuery(
+ () => {
+ const ownerId = userId();
+ return {
+ params: { sort_method: 'updated_at', limit: 100 },
+ body: {
+ ...QUERY_FILTERS_BASE,
+ chat_filters: { owners: ownerId ? [ownerId] : [] },
+ agent_session_filters: {
+ include: true,
+ owners: ownerId ? [ownerId] : [],
+ },
+ },
+ };
+ },
+ () => ({ enabled: Boolean(userId()) })
+ );
+ const conversations = () =>
+ selectRecentAgentConversations(
+ query.isSuccess ? query.data : [],
+ userId(),
+ search()
+ );
+
+ onMount(() => panel.handle.setDisplayName('Agents'));
+
+ const navigate = (next: AgentsPage) => {
+ setSelected(undefined);
+ setPage(next);
+ };
+
+ const openConversation = (conversation: AgentConversationTarget) => {
+ setPage('new');
+ setSelected({
+ conversation: { id: conversation.id, type: conversation.type },
+ activeConversationId: conversation.id,
+ });
+ };
+
+ const startSession = (prompt: string) => {
+ const id = startPendingSession({ prompt });
+ openConversation({ id, type: 'agent_session' });
+ };
+
+ const adoptSessionId = (placeholderId: string, sessionId: string) => {
+ setSelected((current) => {
+ if (
+ current?.conversation.type !== 'agent_session' ||
+ current.conversation.id !== placeholderId
+ ) {
+ return current;
+ }
+ return { ...current, activeConversationId: sessionId };
+ });
+ };
+
+ return (
+ <SplitPanel.Root>
+ <SplitPanel.Body>
+ <ViewShell.Root
+ class="bg-panel"
+ resizable
+ aside={{
+ width: 320,
+ min: 224,
+ max: 380,
+ preserveDuringResize: false,
+ }}
+ breakpoints={{ collapsed: 0 }}
+ layoutBreakpoint="collapsed"
+ main={{ min: 280, preferredWidth: 640 }}
+ >
+ <ViewShell.Aside>
+ <AgentsSidebar
+ page={page()}
+ activeConversationId={selected()?.activeConversationId}
+ search={search()}
+ conversations={conversations()}
+ loading={query.isPending}
+ error={query.isLoadingError}
+ hasNextPage={Boolean(query.hasNextPage)}
+ loadingNextPage={query.isFetchingNextPage}
+ loadMoreError={query.isFetchNextPageError}
+ onNavigate={navigate}
+ onSearchChange={setSearch}
+ onOpenConversation={openConversation}
+ onRetry={() => void query.refetch()}
+ onLoadMore={() => void query.fetchNextPage()}
+ />
+ </ViewShell.Aside>
+
+ <ViewShell.Main class="overflow-hidden">
+ <Show
+ when={selected()?.conversation}
+ keyed
+ fallback={
+ <>
+ <ViewShell.TopBar>{PAGE_TITLES[page()]}</ViewShell.TopBar>
+ <div class="min-h-0 flex-1">
+ <Suspense fallback={<LoadingComposer />}>
+ <Switch>
+ <Match when={page() === 'new'}>
+ <div class="flex size-full items-center justify-center px-6 pb-16">
+ <div class="w-full max-w-2xl">
+ <Switch>
+ <Match when={agentsFlag().loading}>
+ <LoadingComposer />
+ </Match>
+ <Match when={agentsFlag().enabled}>
+ <AgentInput
+ autofocus
+ placeholder="Message the agent, @mention anything"
+ onSend={startSession}
+ />
+ </Match>
+ <Match when={true}>
+ <ChatInputProvider>
+ <HomeChatInput />
+ </ChatInputProvider>
+ </Match>
+ </Switch>
+ </div>
+ </div>
+ </Match>
+ <Match when={page() === 'routines'}>
+ <AgentResourceList page="routines" />
+ </Match>
+ <Match when={page() === 'agents'}>
+ <Agents />
+ </Match>
+ <Match when={page() === 'connections'}>
+ <ConnectedAccounts />
+ </Match>
+ <Match when={page() === 'skills'}>
+ <AgentResourceList page="skills" />
+ </Match>
+ </Switch>
+ </Suspense>
+ </div>
+ </>
+ }
+ >
+ {(conversation) => (
+ <Switch>
+ <Match when={conversation.type === 'agent_session'}>
+ <Suspense>
+ <AgentSessionPane
+ id={conversation.id}
+ onSessionId={(sessionId) =>
+ adoptSessionId(conversation.id, sessionId)
+ }
+ />
+ </Suspense>
+ </Match>
+ <Match when={true}>
+ <Suspense>
+ <PreviewPanel
+ selectedEntity={conversation}
+ orchestrator={orchestrator}
+ splitPanelContext={panel}
+ />
+ </Suspense>
+ </Match>
+ </Switch>
+ )}
+ </Show>
+ </ViewShell.Main>
+ </ViewShell.Root>
+ </SplitPanel.Body>
+ </SplitPanel.Root>
+ );
+}
+
+/** Dedicated Agents workspace used by the new app views layout. */
+export function AgentsView() {
+ return (
+ <ListEntityMetadataQueryProvider>
+ <StaticMarkdownContext>
+ <Suspense fallback={<LoadingComposer />}>
+ <AgentsWorkspace />
+ </Suspense>
+ </StaticMarkdownContext>
+ </ListEntityMetadataQueryProvider>
+ );
+}
diff --git a/apps/web/src/features/home/home.tsx b/apps/web/src/features/home/home.tsx
index dddbfa54a2..e3cf6a3953 100644
--- a/apps/web/src/features/home/home.tsx
+++ b/apps/web/src/features/home/home.tsx
@@ -159,7 +159,7 @@ function HomeContent() {
);
}
-const HomeChatInput = () => {
+export const HomeChatInput = () => {
const splitPanelContext = useSplitPanelOrThrow();
const input = useChatInputContext();
diff --git a/apps/web/src/features/next-soup/utils.ts b/apps/web/src/features/next-soup/utils.ts
index 35883fc10d..e3b8494ef8 100644
--- a/apps/web/src/features/next-soup/utils.ts
+++ b/apps/web/src/features/next-soup/utils.ts
@@ -39,7 +39,11 @@ import { throwOnErr } from '@core/util/result';
import { waitForFrames } from '@core/util/sleep';
import { openExternalUrl } from '@core/util/url';
import {
+ type CalendarEventEntity,
type ChannelClickTarget,
+ type ChannelEntity,
+ type ChannelMessageEntity,
+ type ChannelThreadEntity,
type EntityData,
emailQueryKeyExcludesDone,
getSnippetHit,
@@ -54,6 +58,7 @@ import {
type ReminderEntity,
type SearchLocation,
toNotificationEntity,
+ type WithNotification,
type WithSearch,
} from '@entity';
import {
@@ -452,8 +457,20 @@ export function preventDuplicatePreviewEntityOpen(
* row's preview shows (which may be your own send) rather than an older
* notification or nothing.
*/
+export type ChannelPreviewSelection = WithNotification<
+ | Pick<ChannelEntity, 'id' | 'type' | 'target'>
+ | Pick<
+ ChannelMessageEntity,
+ 'id' | 'type' | 'channelId' | 'messageId' | 'threadId' | 'target'
+ >
+ | Pick<
+ ChannelThreadEntity,
+ 'id' | 'type' | 'channelId' | 'messageId' | 'threadId' | 'target'
+ >
+>;
+
export function getChannelEntityTarget(
- entity: EntityData
+ entity: EntityData | ChannelPreviewSelection
): ChannelClickTarget | undefined {
if (
entity.type !== 'channel' &&
@@ -513,22 +530,16 @@ export function getChannelEntityTarget(
* entity unchanged, so a reactive derivation would never re-run — but a click
* should always re-activate the target (e.g. after the user cleared the
* highlight by clicking a message), matching the old inbox's per-click
- * behaviour. No-ops for non-channel entities or when there is no target.
+ * behaviour.
*/
export async function navigateChannelEntityToTarget(
- entity: EntityData,
+ entity: ChannelPreviewSelection,
blockOrchestrator: BlockOrchestrator
): Promise<void> {
const target = getChannelEntityTarget(entity);
if (!target) return;
- const channelId =
- entity.type === 'channel'
- ? entity.id
- : entity.type === 'channel_message' || entity.type === 'channel_thread'
- ? entity.channelId
- : undefined;
- if (!channelId) return;
+ const channelId = entity.type === 'channel' ? entity.id : entity.channelId;
if (target.kind === 'latest') {
await goToChannelLatest(blockOrchestrator, channelId);
@@ -543,13 +554,15 @@ export async function navigateChannelEntityToTarget(
);
}
+export type CalendarPreviewSelection = WithNotification<
+ Pick<CalendarEventEntity, 'id' | 'type' | 'time' | 'occurrenceKey'>
+>;
+
/** Retargets the singleton Calendar block to a calendar event row. */
export async function navigateCalendarEntityToTarget(
- entity: EntityData,
+ entity: CalendarPreviewSelection,
blockOrchestrator: BlockOrchestrator
): Promise<void> {
- if (entity.type !== 'calendar_event') return;
-
const calendarHandle = await blockOrchestrator.getBlockHandle(
CALENDAR_BLOCK_ID,
'calendar'
@@ -838,16 +851,17 @@ export function markReminderSeenOnOpen(
* The event and instance a calendar row points at, resolved exactly as the
* open path resolves it so a copied link lands where a click would.
*/
-export function calendarEventLinkTarget(
- entity: Extract<EntityData, { type: 'calendar_event' }>
-): { eventId: string; occurrenceKey?: string } {
+export function calendarEventLinkTarget(entity: CalendarPreviewSelection): {
+ eventId: string;
+ occurrenceKey?: string;
+} {
const { eventId, occurrenceKey } = calendarBlockParamsForEntity(entity);
return { eventId: eventId ?? entity.id, occurrenceKey };
}
/** Build singleton calendar block parameters for an event row's occurrence. */
export function calendarBlockParamsForEntity(
- entity: Extract<EntityData, { type: 'calendar_event' }>
+ entity: CalendarPreviewSelection
): CalendarBlockProps {
const notifications = isWithNotification(entity)
? (entity.notifications?.() ?? [])
@@ -885,7 +899,12 @@ export function calendarBlockParamsForEntity(
* `fileType`/`subType` come resolved from the server, so a referenced document
* lands on its real block rather than 'unknown'.
*/
-export function reminderSplitTarget(entity: ReminderEntity) {
+export type ReminderPreviewSelection = Pick<
+ ReminderEntity,
+ 'id' | 'type' | 'referencedEntity'
+>;
+
+export function reminderSplitTarget(entity: ReminderPreviewSelection) {
const referenced = entity.referencedEntity;
if (!referenced) return undefined;
return {
@@ -1193,7 +1212,14 @@ function notificationsForMarkDone(
notifications: UnifiedNotification[],
scopeChannelNotificationsToEntity: boolean
): UnifiedNotification[] {
- if (!scopeChannelNotificationsToEntity) return notifications;
+ if (
+ !scopeChannelNotificationsToEntity ||
+ (entity.type !== 'channel' &&
+ entity.type !== 'channel_message' &&
+ entity.type !== 'channel_thread')
+ ) {
+ return notifications;
+ }
return scopeChannelNotificationsForEntity(entity, notifications);
}
diff --git a/apps/web/src/features/soup/entity-notifications.ts b/apps/web/src/features/soup/entity-notifications.ts
index 93bfdfb8d2..35b9865426 100644
--- a/apps/web/src/features/soup/entity-notifications.ts
+++ b/apps/web/src/features/soup/entity-notifications.ts
@@ -1,4 +1,9 @@
-import type { EntityData } from '@entity/types/entity';
+import type {
+ ChannelEntity,
+ ChannelMessageEntity,
+ ChannelThreadEntity,
+ EntityData,
+} from '@entity/types/entity';
import type { WithNotification } from '@entity/types/notification';
import { toNotificationEntity } from '@entity/utils/notification';
import { channelThreadRootId } from '@notifications/channel-thread-root';
@@ -47,12 +52,17 @@ function channelThreadNotificationIds(
return ids;
}
+export type ChannelNotificationScopeEntity =
+ | Pick<ChannelEntity, 'type'>
+ | Pick<ChannelMessageEntity, 'type'>
+ | Pick<ChannelThreadEntity, 'type' | 'messageId'>;
+
/**
* Splits notifications shared by channel and channel-thread entities into the
* stack rendered by each Inbox row.
*/
export function scopeChannelNotificationsForEntity(
- entity: EntityData,
+ entity: ChannelNotificationScopeEntity,
notifications: UnifiedNotification[]
): UnifiedNotification[] {
if (entity.type === 'channel') {
@@ -100,7 +110,10 @@ export function withEntityNotifications<T extends EntityData>(
...entity,
notifications: () => {
const notifications = read();
- return options.scopeChannelThreads
+ return options.scopeChannelThreads &&
+ (entity.type === 'channel' ||
+ entity.type === 'channel_message' ||
+ entity.type === 'channel_thread')
? scopeChannelNotificationsForEntity(entity, notifications)
: notifications;
},
diff --git a/apps/web/src/lib/queries/favorites/favorites.test.tsx b/apps/web/src/lib/queries/favorites/favorites.test.tsx
index 33179d71e7..b6012950c4 100644
--- a/apps/web/src/lib/queries/favorites/favorites.test.tsx
+++ b/apps/web/src/lib/queries/favorites/favorites.test.tsx
@@ -70,9 +70,13 @@ import {
let testQueryClient: QueryClient;
let dispose: (() => void) | undefined;
-function favorite(entityId: string, sortOrder: number): Favorite {
+function favorite(
+ entityId: string,
+ sortOrder: number,
+ entityType: Favorite['entityType'] = 'document'
+): Favorite {
return {
- entityType: 'document',
+ entityType,
entityId,
sortOrder,
createdAt: '2026-01-01T00:00:00Z',
@@ -194,6 +198,64 @@ describe('favorites transport', () => {
);
});
+ it('updates matching filtered REST caches optimistically', async () => {
+ mocks.graphqlSoupEnabled.mockReturnValue(false);
+ const agentFilter: FavoritesFilter = {
+ entityType: ['agent_session', 'chat'],
+ };
+ const channelFilter: FavoritesFilter = { entityType: ['channel'] };
+ const agent1 = favorite('agent-1', 0, 'agent_session');
+ const agent2 = favorite('agent-2', 1, 'agent_session');
+ const channel = favorite('channel-1', 2, 'channel');
+ testQueryClient.setQueryData<FavoritesList>(favoriteKeys.list().queryKey, {
+ favorites: [agent1, agent2, channel],
+ });
+ testQueryClient.setQueryData<FavoritesList>(
+ favoriteKeys.list(agentFilter).queryKey,
+ { favorites: [agent1, agent2] }
+ );
+ testQueryClient.setQueryData<FavoritesList>(
+ favoriteKeys.list(channelFilter).queryKey,
+ { favorites: [channel] }
+ );
+ mocks.addFavoriteRest.mockResolvedValue(
+ ok(favorite('agent-3', 2, 'agent_session'))
+ );
+ mocks.removeFavoriteRest.mockResolvedValue(ok(undefined));
+ mocks.reorderFavoritesRest.mockResolvedValue(ok(undefined));
+ const mutations = renderHook(() => ({
+ add: useAddFavoriteMutation(),
+ remove: useRemoveFavoriteMutation(),
+ reorder: useReorderFavoritesMutation(),
+ }));
+
+ await mutations.add.mutateAsync({
+ entityType: 'agent_session',
+ entityId: 'agent-3',
+ });
+ await mutations.remove.mutateAsync({
+ entityType: 'agent_session',
+ entityId: 'agent-1',
+ });
+ await mutations.reorder.mutateAsync({
+ favorites: [
+ { entityType: 'agent_session', entityId: 'agent-3' },
+ { entityType: 'agent_session', entityId: 'agent-2' },
+ ],
+ });
+
+ expect(
+ testQueryClient
+ .getQueryData<FavoritesList>(favoriteKeys.list(agentFilter).queryKey)
+ ?.favorites.map((item) => item.entityId)
+ ).toEqual(['agent-3', 'agent-2']);
+ expect(
+ testQueryClient
+ .getQueryData<FavoritesList>(favoriteKeys.list(channelFilter).queryKey)
+ ?.favorites.map((item) => item.entityId)
+ ).toEqual(['channel-1']);
+ });
+
it('keeps queued reorder entirely on the captured GraphQL path', async () => {
const mutation = renderHook(() => useReorderFavoritesMutation());
expect(mocks.graphqlSoupEnabled).toHaveBeenCalledOnce();
diff --git a/apps/web/src/lib/queries/favorites/favorites.ts b/apps/web/src/lib/queries/favorites/favorites.ts
index 555543809f..c1107f7a5f 100644
--- a/apps/web/src/lib/queries/favorites/favorites.ts
+++ b/apps/web/src/lib/queries/favorites/favorites.ts
@@ -113,17 +113,44 @@ export function useFavoritesData(
return () => (query.isSuccess ? query.data : undefined);
}
-function readList(): FavoritesList | undefined {
- return queryClient.getQueryData<FavoritesList>(favoriteKeys.list().queryKey);
+function readLists() {
+ return queryClient.getQueriesData<FavoritesList>({
+ queryKey: favoriteKeys.list._def,
+ });
}
-function writeList(update: (prev: FavoritesList) => FavoritesList) {
- queryClient.setQueryData<FavoritesList>(
- favoriteKeys.list().queryKey,
- (prev) => (prev ? update(prev) : prev)
+type FavoriteListsSnapshot = ReturnType<typeof readLists>;
+type FavoriteListQueryKey = ReturnType<typeof favoriteKeys.list>['queryKey'];
+
+function favoriteMatchesFilter(
+ favorite: Favorite,
+ filter: FavoritesFilter | undefined
+): boolean {
+ return (
+ (!filter?.entityType || filter.entityType.includes(favorite.entityType)) &&
+ (!filter?.entityId || filter.entityId.includes(favorite.entityId))
);
}
+function writeLists(
+ update: (
+ prev: FavoritesList,
+ filter: FavoritesFilter | undefined
+ ) => FavoritesList
+) {
+ for (const [queryKey, prev] of readLists()) {
+ if (!prev) continue;
+ const [, , filter] = queryKey as FavoriteListQueryKey;
+ queryClient.setQueryData<FavoritesList>(queryKey, update(prev, filter));
+ }
+}
+
+function restoreLists(snapshot: FavoriteListsSnapshot) {
+ for (const [queryKey, previous] of snapshot) {
+ queryClient.setQueryData(queryKey, previous);
+ }
+}
+
export function invalidateFavorites() {
if (isFeatureEnabled(enableGraphqlSoup)) {
return refreshActiveGraphqlFavoritesQueries();
@@ -164,23 +191,20 @@ export function useAddFavoriteMutation(callbacks?: AddFavoriteCallbacks) {
{
onMutate: async (args: AddFavoriteArgs) => {
await queryClient.cancelQueries({
- queryKey: favoriteKeys.list().queryKey,
+ queryKey: favoriteKeys.list._def,
});
- const previous = readList();
+ const previous = readLists();
const optimistic = pendingFavorite(args);
- writeList((prev) => ({
- ...prev,
- favorites: [...prev.favorites, optimistic],
- }));
+ writeLists((prev, filter) =>
+ favoriteMatchesFilter(optimistic, filter)
+ ? {
+ ...prev,
+ favorites: [...prev.favorites, optimistic],
+ }
+ : prev
+ );
return {
- rollback: () => {
- if (previous) {
- queryClient.setQueryData(
- favoriteKeys.list().queryKey,
- previous
- );
- }
- },
+ rollback: () => restoreLists(previous),
};
},
onError: (_error, _args, context) => {
@@ -218,27 +242,20 @@ export function useRemoveFavoriteMutation(callbacks?: RemoveFavoriteCallbacks) {
{
onMutate: async (args: RemoveFavoriteArgs) => {
await queryClient.cancelQueries({
- queryKey: favoriteKeys.list().queryKey,
+ queryKey: favoriteKeys.list._def,
});
- const previous = readList();
+ const previous = readLists();
const keep = (favorite: Favorite) =>
!(
favorite.entityType === args.entityType &&
favorite.entityId === args.entityId
);
- writeList((prev) => ({
+ writeLists((prev) => ({
...prev,
favorites: prev.favorites.filter(keep),
}));
return {
- rollback: () => {
- if (previous) {
- queryClient.setQueryData(
- favoriteKeys.list().queryKey,
- previous
- );
- }
- },
+ rollback: () => restoreLists(previous),
};
},
onError: (_error, _args, context) => {
@@ -291,9 +308,9 @@ export function useReorderFavoritesMutation(
{
onMutate: async (args: ReorderFavoritesArgs) => {
await queryClient.cancelQueries({
- queryKey: favoriteKeys.list().queryKey,
+ queryKey: favoriteKeys.list._def,
});
- const previous = readList();
+ const previous = readLists();
const reorder = (favorites: Favorite[]) => {
const byKey = new Map(
favorites.map((f) => [
@@ -314,19 +331,12 @@ export function useReorderFavoritesMutation(
);
return [...ordered, ...leftover];
};
- writeList((prev) => ({
+ writeLists((prev) => ({
...prev,
favorites: reorder(prev.favorites),
}));
return {
- rollback: () => {
- if (previous) {
- queryClient.setQueryData(
- favoriteKeys.list().queryKey,
- previous
- );
- }
- },
+ rollback: () => restoreLists(previous),
};
},
onError: (_error, _args, context) => {
diff --git a/apps/web/src/lib/queries/favorites/graphql.test.tsx b/apps/web/src/lib/queries/favorites/graphql.test.tsx
index 330cd840f9..3867f79b16 100644
--- a/apps/web/src/lib/queries/favorites/graphql.test.tsx
+++ b/apps/web/src/lib/queries/favorites/graphql.test.tsx
@@ -302,6 +302,38 @@ describe('GraphQL favorites queries', () => {
);
});
+ it('optimistically updates matching filtered GraphQL lists', async () => {
+ const hooks = renderHook(() => ({
+ query: createGraphqlFavoritesQuery({
+ entityType: ['document'],
+ }),
+ mutation: createGraphqlAddFavoriteMutation(),
+ }));
+ await vi.waitFor(() => expect(hooks.query.isSuccess).toBe(true));
+
+ await hooks.mutation.mutateAsync({
+ entityType: 'document',
+ entityId: 'document-3',
+ });
+
+ const optimistic =
+ executeMutation.mock.calls[0]?.[2]?.normalizedCacheOptimistic;
+ expect(optimistic.linkPatches).toEqual([
+ expect.objectContaining({
+ variablesJson: '{"filter":{"entityTypes":["DOCUMENT"]}}',
+ operation: expect.objectContaining({ kind: 'prependUnique' }),
+ }),
+ ]);
+ expect(optimistic.revalidations).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({ variablesJson: '{}' }),
+ expect.objectContaining({
+ variablesJson: '{"filter":{"entityTypes":["DOCUMENT"]}}',
+ }),
+ ])
+ );
+ });
+
it('refetches the urql-solid list after setting a favorite', async () => {
const onSuccess = vi.fn();
const hooks = renderHook(() => ({
diff --git a/apps/web/src/lib/queries/favorites/graphql.ts b/apps/web/src/lib/queries/favorites/graphql.ts
index bdce399e7e..5e2ab13dd5 100644
--- a/apps/web/src/lib/queries/favorites/graphql.ts
+++ b/apps/web/src/lib/queries/favorites/graphql.ts
@@ -18,6 +18,7 @@ import {
import {
executeGraphqlReorderFavoritesMutation,
executeGraphqlSetFavoriteMutation,
+ type FavoritesCacheTarget,
graphqlReorderFavoritesResult,
graphqlSetFavoriteResult,
mapGraphqlFavorite,
@@ -37,7 +38,13 @@ type GraphqlFavoritesQuery = UrqlQueryResult<
FavoritesQuery
>;
-const activeFavoritesQueries = new Set<GraphqlFavoritesQuery>();
+type ActiveFavoritesQuery = {
+ query: GraphqlFavoritesQuery;
+ filter: ListFavoritesParams | undefined;
+ variables: FavoritesQueryVariables;
+};
+
+const activeFavoritesQueries = new Set<ActiveFavoritesQuery>();
function selectFavorites(data: FavoritesQuery): FavoritesList {
return {
@@ -47,10 +54,53 @@ function selectFavorites(data: FavoritesQuery): FavoritesList {
};
}
+function favoritesQueryVariables(
+ filter: ListFavoritesParams | undefined
+): FavoritesQueryVariables {
+ return filter
+ ? {
+ filter: {
+ entityTypes: filter.entityType?.map(toGraphqlFavoriteEntityType),
+ entityIds: filter.entityId,
+ },
+ }
+ : {};
+}
+
+function favoriteMatchesFilter(
+ favorite: SetFavoriteArgs,
+ filter: ListFavoritesParams | undefined
+): boolean {
+ return (
+ (!filter?.entityType || filter.entityType.includes(favorite.entityType)) &&
+ (!filter?.entityId || filter.entityId.includes(favorite.entityId))
+ );
+}
+
+function activeFavoritesCacheTargets(
+ favorite?: SetFavoriteArgs
+): FavoritesCacheTarget[] {
+ const targets = new Map<string, FavoritesCacheTarget>([
+ [JSON.stringify({}), { variables: {}, updateCachedList: false }],
+ ]);
+ for (const active of activeFavoritesQueries) {
+ if (favorite && !favoriteMatchesFilter(favorite, active.filter)) continue;
+ const key = JSON.stringify(active.variables);
+ targets.set(key, {
+ variables: active.variables,
+ updateCachedList:
+ Boolean(active.query.data) ||
+ Boolean(targets.get(key)?.updateCachedList),
+ });
+ }
+ return [...targets.values()];
+}
+
/** Creates the live urql-solid favorites query. */
export function createGraphqlFavoritesQuery(
filter?: ListFavoritesParams
): GraphqlFavoritesQuery {
+ const variables = favoritesQueryVariables(filter);
const query = createUrqlQuery<
FavoritesQuery,
FavoritesQueryVariables,
@@ -58,28 +108,22 @@ export function createGraphqlFavoritesQuery(
>(() => ({
query: FavoritesDocument,
client: getGraphqlSoupClient(),
- variables: filter
- ? {
- filter: {
- entityTypes: filter.entityType?.map(toGraphqlFavoriteEntityType),
- entityIds: filter.entityId,
- },
- }
- : {},
+ variables,
requestPolicy: 'cache-and-network',
keepPreviousData: false,
select: selectFavorites,
}));
- activeFavoritesQueries.add(query);
- onCleanup(() => activeFavoritesQueries.delete(query));
+ const active = { query, filter, variables };
+ activeFavoritesQueries.add(active);
+ onCleanup(() => activeFavoritesQueries.delete(active));
return query;
}
/** Refetches mounted lists, including clients running without the cache exchange. */
export async function refreshActiveGraphqlFavoritesQueries(): Promise<void> {
await Promise.all(
- [...activeFavoritesQueries].map((query) =>
+ [...activeFavoritesQueries].map(({ query }) =>
// Refetch replaces the observer's subscription. Read through the cache
// to register its dependencies even if the network request fails, so
// later offline optimistic writes still update this mounted list.
@@ -88,13 +132,9 @@ export async function refreshActiveGraphqlFavoritesQueries(): Promise<void> {
);
}
-function hasCachedFavoritesList(): boolean {
- return [...activeFavoritesQueries].some((query) => query.data !== undefined);
-}
-
function nextFavoriteSortOrder(): number {
let maximum = -1;
- for (const query of activeFavoritesQueries) {
+ for (const { query } of activeFavoritesQueries) {
for (const favorite of query.data?.favorites ?? []) {
maximum = Math.max(maximum, favorite.sortOrder);
}
@@ -184,7 +224,7 @@ export function createGraphqlAddFavoriteMutation<Context = void>(
input,
true,
nextFavoriteSortOrder(),
- hasCachedFavoritesList()
+ activeFavoritesCacheTargets(input)
),
select: graphqlSetFavoriteResult,
callbacks,
@@ -203,7 +243,7 @@ export function createGraphqlRemoveFavoriteMutation<Context = void>(
input,
false,
0,
- hasCachedFavoritesList()
+ activeFavoritesCacheTargets(input)
),
select: (result) => {
graphqlSetFavoriteResult(result);
@@ -222,7 +262,12 @@ export function createGraphqlReorderFavoritesMutation<Context = void>(
) {
return createFavoriteMutation({
mutation: ReorderFavoritesDocument,
- execute: executeGraphqlReorderFavoritesMutation,
+ execute: (client, input) =>
+ executeGraphqlReorderFavoritesMutation(
+ client,
+ input,
+ activeFavoritesCacheTargets().map((target) => target.variables)
+ ),
select: graphqlReorderFavoritesResult,
callbacks,
});
diff --git a/apps/web/src/lib/service-clients/service-storage/graphql-favorites.ts b/apps/web/src/lib/service-clients/service-storage/graphql-favorites.ts
index 505846c52c..981759748d 100644
--- a/apps/web/src/lib/service-clients/service-storage/graphql-favorites.ts
+++ b/apps/web/src/lib/service-clients/service-storage/graphql-favorites.ts
@@ -14,6 +14,7 @@ import type { ReorderFavoritesRequest } from './generated/schemas/reorderFavorit
import {
type FavoriteFieldsFragment,
FavoritesDocument,
+ type FavoritesQueryVariables,
type GraphqlEntityType,
ReorderFavoritesDocument,
type ReorderFavoritesMutation,
@@ -92,13 +93,20 @@ export type SetFavoriteArgs = {
entityId: string;
};
+export type FavoritesCacheTarget = {
+ variables: FavoritesQueryVariables;
+ updateCachedList: boolean;
+};
+
/** Submit a durable optimistic GraphQL add/remove favorite mutation. */
export function executeGraphqlSetFavoriteMutation(
client: Client,
args: SetFavoriteArgs,
favorite: boolean,
optimisticSortOrder: number,
- updateCachedList = true
+ cacheTargets: readonly FavoritesCacheTarget[] = [
+ { variables: {}, updateCachedList: true },
+ ]
): Promise<OperationResult<SetFavoriteMutation, SetFavoriteMutationVariables>> {
const entityType = toGraphqlFavoriteEntityType(args.entityType);
const optimisticFavorite: FavoriteFieldsFragment = {
@@ -117,9 +125,6 @@ export function executeGraphqlSetFavoriteMutation(
__typename: optimisticFavorite.__typename,
id: optimisticFavorite.id,
};
- const favorites = select(FavoritesDocument, {})
- .field('user')
- .field('favorites');
const optimisticData: SetFavoriteMutation = {
setFavorite: {
__typename: 'SetFavoritePayload',
@@ -144,15 +149,20 @@ export function executeGraphqlSetFavoriteMutation(
// A cold offline cache has no user.favorites field to patch. The
// optimistic mutation itself can still be durably queued; replay
// revalidation populates the list once the network is available.
- updates: updateCachedList
- ? [
- update(
- favorites,
- favorite ? prependUnique(identity) : remove(identity)
- ),
- ]
- : [],
- revalidations: [{ document: FavoritesDocument, variables: {} }],
+ updates: cacheTargets
+ .filter((target) => target.updateCachedList)
+ .map((target) =>
+ update(
+ select(FavoritesDocument, target.variables)
+ .field('user')
+ .field('favorites'),
+ favorite ? prependUnique(identity) : remove(identity)
+ )
+ ),
+ revalidations: cacheTargets.map((target) => ({
+ document: FavoritesDocument,
+ variables: target.variables,
+ })),
}
).toPromise();
}
@@ -193,7 +203,8 @@ export type ReorderFavoritesResult =
/** Submit a durable optimistic GraphQL favorites reorder. */
export function executeGraphqlReorderFavoritesMutation(
client: Client,
- args: ReorderFavoritesRequest
+ args: ReorderFavoritesRequest,
+ revalidationVariables: readonly FavoritesQueryVariables[] = [{}]
): Promise<
OperationResult<ReorderFavoritesMutation, ReorderFavoritesMutationVariables>
> {
@@ -234,7 +245,10 @@ export function executeGraphqlReorderFavoritesMutation(
optimisticData,
{
uuid: REORDER_FAVORITES_OPTIMISTIC_UUID,
- revalidations: [{ document: FavoritesDocument, variables: {} }],
+ revalidations: revalidationVariables.map((variables) => ({
+ document: FavoritesDocument,
+ variables,
+ })),
}
).toPromise();
}
diff --git a/docs/AGENT_GUIDE/ai-chat.md b/docs/AGENT_GUIDE/ai-chat.md
index 2db7803922..ca719bbb71 100644
--- a/docs/AGENT_GUIDE/ai-chat.md
+++ b/docs/AGENT_GUIDE/ai-chat.md
@@ -2,8 +2,12 @@
## Where chats live
-- List: `Go to Agents` → `/app/component/agents`, tabs Owned / Running / Shared /
- Automations / Skills. Existing chats are listed by auto-generated title.
+- List: `Go to Agents` → `/app/component/agents`. With new app views enabled
+ on desktop, an Agents sidebar opens New Chat, Routines, configured Agents,
+ Connections, and Skills, followed by favorite and recent conversations.
+ Selecting a recent chat or agent session opens it inside the workspace.
+ Touch devices and users outside the flag retain the Owned / Running / Shared /
+ Automations / Skills list.
- A chat is `/app/chat/<uuid>`. A doc-scoped chat is `/app/md/<doc>/chat/<chat>` (split view).
## Start a standalone chat