Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(soup): add Remove from folder context menu action in folder views (#4608)
Evan Hutnika7b34fd56b83
diff --git a/js/app/packages/app/component/next-soup/actions/index.ts b/js/app/packages/app/component/next-soup/actions/index.tsindex 280a4d4a85..3248a47d4b 100644--- a/js/app/packages/app/component/next-soup/actions/index.ts+++ b/js/app/packages/app/component/next-soup/actions/index.ts@@ -10,6 +10,7 @@ export { makeMarkDoneAction } from './make-mark-done-action';export { makeMarkSenderSignalAction } from './make-mark-sender-important-action';export { makeMarkSenderNoiseAction } from './make-mark-sender-noise-action';export { makeMoveToProjectAction } from './make-move-to-project-action';+export { makeRemoveFromProjectAction } from './make-remove-from-project-action';export { makeRenameAction } from './make-rename-action';export { makeShareAction } from './make-share-action';export { useBlockEntityCommands } from './use-block-entity-commands';diff --git a/js/app/packages/app/component/next-soup/actions/make-remove-from-project-action.ts b/js/app/packages/app/component/next-soup/actions/make-remove-from-project-action.tsnew file mode 100644index 0000000000..07ecc2cd48--- /dev/null+++ b/js/app/packages/app/component/next-soup/actions/make-remove-from-project-action.ts@@ -0,0 +1,53 @@+import { useMaybePreviewPanel } from '@app/component/PreviewPanel';+import { toast } from '@core/component/Toast/Toast';+import type { EntityData } from '@entity';+import { createBulkRemoveFromProjectDssEntityMutation } from '@macro-entity';+import type { SoupState } from '../create-soup-state';+import { restoreSoupFocus } from '../utils';++/** Clear the entities' folder (set their project to none). */+export const makeRemoveFromProjectAction = () => {+ const removeMutation = createBulkRemoveFromProjectDssEntityMutation();++ const canExecute = (entity: EntityData): boolean =>+ entity.type === 'document' ||+ entity.type === 'chat' ||+ entity.type === 'project' ||+ entity.type === 'email';++ const execute = async (entities: EntityData[]): Promise<boolean> => {+ // Failure toast is shown by the mutation+ const result = await removeMutation+ .mutateAsync({ entities })+ .catch(() => null);+ if (!result) return false;+ toast.success(+ entities.length > 1+ ? `Removed ${entities.length} items from folder`+ : 'Removed from folder'+ );+ return true;+ };++ const previewPanel = useMaybePreviewPanel();++ const executeWithSoup = async (entities: EntityData[], soup: SoupState) => {+ // Entities leave the viewed folder's list; move focus to a neighbor+ const currentIndex = soup.focus.index();+ const nextRow =+ soup.items.at(currentIndex + 1) ?? soup.items.at(currentIndex - 1);+ const inPreview = previewPanel !== undefined;++ const success = await execute(entities);+ // Rolled back on failure; keep selection and focus for a retry+ if (!success) return;++ soup.selection.clear();+ if (nextRow) {+ soup.focus.set(nextRow.id);+ }+ restoreSoupFocus(nextRow?.id, inPreview);+ };++ return { canExecute, execute, executeWithSoup };+};diff --git a/js/app/packages/app/component/next-soup/soup-view/SoupEntityActionDrawer.tsx b/js/app/packages/app/component/next-soup/soup-view/SoupEntityActionDrawer.tsxindex 9f371188f1..d1863ce769 100644--- a/js/app/packages/app/component/next-soup/soup-view/SoupEntityActionDrawer.tsx+++ b/js/app/packages/app/component/next-soup/soup-view/SoupEntityActionDrawer.tsx@@ -5,7 +5,10 @@ import { triggerFocusInput } from '@core/directive/focusInput';import { InlineEntity } from '@entity';import { cn } from '@ui';import { For, Show } from 'solid-js';-import { createSoupEntityActions } from './create-soup-entity-actions';+import {+ createSoupEntityActions,+ viewedProjectIdFromContent,+} from './create-soup-entity-actions';import { useSoupEntityActionDrawer } from './soup-entity-action-drawer-context';import { useSoupView } from './soup-view-context';@@ -24,9 +27,11 @@ export function SoupEntityActionDrawer() {const e = drawerState.entity();const s = drawerState.soup();if (!e || !s) return [];+ const content = panel.handle.content();return buildActionGroups(s, [e], {activeTab: activeTab(),- activeListView: panel.handle.content().id,+ activeListView: content.id,+ viewedProjectId: viewedProjectIdFromContent(content),});};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.tsindex 275875d753..e3e0fdb1b5 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@@ -25,6 +25,7 @@ import {makeMarkSenderNoiseAction,makeMarkSenderSignalAction,makeMoveToProjectAction,+ makeRemoveFromProjectAction,makeRenameAction,makeShareAction,} from '../actions';@@ -56,9 +57,20 @@ type BuildActionGroups = (context: {activeListView: string;activeTab: string | undefined;+ /** Set when the list is a folder's contents (project block view) */+ viewedProjectId?: string;}) => SoupEntityActionGroup[];+/** The folder whose contents the split is showing, if any. */+export const viewedProjectIdFromContent = (content: {+ type: string;+ id: string;+}): string | undefined =>+ content.type === 'project' && content.id !== 'root' && content.id !== 'trash'+ ? content.id+ : undefined;+export function createSoupEntityActions(): {buildActionGroups: BuildActionGroups;} {@@ -84,6 +96,7 @@ export function createSoupEntityActions(): {const copyAction = makeCopyAction();const favoriteAction = makeFavoriteAction();const moveToProjectAction = makeMoveToProjectAction();+ const removeFromProjectAction = makeRemoveFromProjectAction();const copyLinkAction = makeCopyLinkAction();const copyBranchNameAction = makeCopyBranchNameAction();const copyEntityIdAction = makeCopyEntityIdAction();@@ -100,7 +113,7 @@ export function createSoupEntityActions(): {const buildActionGroups: BuildActionGroups = (soup,entities,- { activeTab, activeListView }+ { activeTab, activeListView, viewedProjectId }) => {const canExecuteAll = (canExecute: (e: EntityData) => boolean) =>entities.length > 0 && entities.every(canExecute);@@ -251,6 +264,14 @@ export function createSoupEntityActions(): {});}+ if (viewedProjectId && canExecuteAll(removeFromProjectAction.canExecute)) {+ middleItems.push({+ id: 'remove-from-folder',+ label: 'Remove from folder',+ onClick: handle(removeFromProjectAction.executeWithSoup),+ });+ }+if (canExecuteAll(copyAction.canExecute)) {middleItems.push({id: 'duplicate',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.tsxindex e91b2dfac5..c05704114e 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@@ -3,7 +3,10 @@ import { MenuItem, MenuSeparator } from '@core/component/ContextMenu';import type { EntityData } from '@entity';import { For, Show } from 'solid-js';import type { SoupState } from '../create-soup-state';-import { createSoupEntityActions } from './create-soup-entity-actions';+import {+ createSoupEntityActions,+ viewedProjectIdFromContent,+} from './create-soup-entity-actions';import { useSoupView } from './soup-view-context';interface SoupEntityActionsMenuProps {@@ -17,11 +20,14 @@ export const SoupEntityActionsMenu = (props: SoupEntityActionsMenuProps) => {const { activeTab } = useSoupView();const { buildActionGroups } = createSoupEntityActions();- const groups = () =>- buildActionGroups(props.soup, props.entities, {+ const groups = () => {+ const content = panel.handle.content();+ return buildActionGroups(props.soup, props.entities, {activeTab: activeTab(),- activeListView: panel.handle.content().id,+ activeListView: content.id,+ viewedProjectId: viewedProjectIdFromContent(content),});+ };const handleAction = async (onClick: () => void | Promise<void>) => {await onClick();diff --git a/js/app/packages/core/component/FileList/itemOperations.ts b/js/app/packages/core/component/FileList/itemOperations.tsindex 607239f852..56c9ce1bc3 100644--- a/js/app/packages/core/component/FileList/itemOperations.ts+++ b/js/app/packages/core/component/FileList/itemOperations.ts@@ -253,7 +253,8 @@ export async function bulkDelete(export async function moveToFolder(args: {itemType: ItemType;id: string;- folderId: string;+ /** null removes the item from its folder */+ folderId: string | null;}): Promise<boolean> {const { itemType, id, folderId } = args;const accessLevel = await getItemAccessLevel({ itemType, id });@@ -263,24 +264,25 @@ export async function moveToFolder(args: {let result;switch (itemType) {+ // Storage/chat backends clear the folder on empty string; email on null.case 'document': {result = await storageServiceClient.editDocument({documentId: id,- projectId: folderId,+ projectId: folderId ?? '',});break;}case 'project': {result = await storageServiceClient.projects.edit({id,- projectParentId: folderId,+ projectParentId: folderId ?? '',});break;}case 'chat': {result = await cognitionApiServiceClient.editChatProject({chat_id: id,- project_id: folderId,+ project_id: folderId ?? '',});break;}diff --git a/js/app/packages/macro-entity/src/index.tsx b/js/app/packages/macro-entity/src/index.tsxindex 02eec8ae7a..4d5ebb5044 100644--- a/js/app/packages/macro-entity/src/index.tsx+++ b/js/app/packages/macro-entity/src/index.tsx@@ -3,6 +3,7 @@ export {createBulkCopyDssEntityMutation,createBulkDeleteDssItemsMutation,createBulkMoveToProjectDssEntityMutation,+ createBulkRemoveFromProjectDssEntityMutation,createMoveToProjectDssEntityMutation,} from './queries/dss';export { createEmailsInfiniteQuery } from './queries/email';diff --git a/js/app/packages/macro-entity/src/queries/dss.ts b/js/app/packages/macro-entity/src/queries/dss.tsindex 60ab2e2916..9f904aa875 100644--- a/js/app/packages/macro-entity/src/queries/dss.ts+++ b/js/app/packages/macro-entity/src/queries/dss.ts@@ -5,7 +5,7 @@ import {} from '@core/component/FileList/itemOperations';import { toast } from '@core/component/Toast/Toast';import { throwOnErr } from '@core/util/result';-import type { EntityData } from '@entity';+import { type EntityData, getEntityProjectId } from '@entity';import { scheduledActionKeys } from '@queries/agent-schedule/keys';import { callKeys } from '@queries/call/keys';import { queryClient } from '@queries/client';@@ -16,6 +16,7 @@ import {optimisticUpdateSoupEntity,removeSearchEntities,removeSoupEntities,+ removeSoupEntitiesFromQueriesReferencing,} from '@queries/soup/cache';import { soupKeys } from '@queries/soup/keys';import { callServiceClient } from '@service-call/client';@@ -160,6 +161,114 @@ export function createMoveToProjectDssEntityMutation() {}));}+export function createBulkRemoveFromProjectDssEntityMutation() {+ const isUnsupportedEntity = (entity: EntityData) => {+ const type = entity.type;+ return (+ type !== 'chat' &&+ type !== 'document' &&+ type !== 'project' &&+ type !== 'email'+ );+ };++ return useMutation(() => ({+ mutationFn: async ({ entities }: { entities: EntityData[] }) => {+ if (entities.some(isUnsupportedEntity)) {+ throw new Error(`Unsupported entity type provided`);+ }++ const results = await Promise.all(+ entities.map((entity) =>+ moveToFolder({+ itemType: entity.type as 'document' | 'chat' | 'project' | 'email',+ id: entity.id,+ folderId: null,+ })+ )+ );++ if (results.some((r) => !r)) {+ throw new Error(`One or more DSS items failed to move`);+ }++ return { success: true };+ },++ onMutate: async ({ entities }: { entities: EntityData[] }) => {+ const moveableEntities = entities.filter(+ (e): e is typeof e & { type: 'document' | 'chat' | 'email' } =>+ e.type === 'document' || e.type === 'chat' || e.type === 'email'+ );+ const txns = moveableEntities.map((e) => {+ const current = getSoupEntityById(e.id);+ const tag = e.type === 'email' ? 'emailThread' : e.type;+ return optimisticUpdateSoupEntity({+ tag,+ data: { id: e.id, projectId: null },+ frecency_score: current?.frecency_score ?? 0,+ });+ });++ // Drop the rows from the source folders' views right away; other views+ // keep the entities+ const sourceProjectIds = [+ ...new Set(+ entities.flatMap((e) => {+ const projectId =+ getEntityProjectId(e) || getSoupEntityProjectId(e.id);+ return projectId ? [projectId] : [];+ })+ ),+ ];+ txns.push(+ removeSoupEntitiesFromQueriesReferencing(+ new Set(entities.map((e) => e.id)),+ sourceProjectIds+ )+ );++ return { txns, sourceProjectIds };+ },++ onSettled: (data, error, { entities }, context) => {+ const failed = data?.success === false || !!error;+ if (failed) {+ // Reverse order: each txn's snapshot captures the previous txns' writes+ context?.txns.toReversed().forEach((txn) => txn.rollback());+ console.error(+ `Failed to remove dss items from folder`,+ entities,+ error+ );+ toast.failure('Failed to remove items from folder');+ }++ // Queries still containing the entities+ for (const entity of entities) {+ invalidateSoupEntity(entity.id);+ }+ // The source folders' views no longer contain the entities after the+ // optimistic removal, so match them by project id in the key+ invalidateSoupQueriesReferencing(context?.sourceProjectIds ?? []);+ queryClient.invalidateQueries({ queryKey: ['entity'] });+ // Removed projects' breadcrumbs (and nested projects') change too+ if (entities.some((e) => e.type === 'project')) {+ queryClient.invalidateQueries({ queryKey: ['project'] });+ }+ },+ }));+}++/** Source project of a soup-cached entity ('project' items nest it as parentId). */+function getSoupEntityProjectId(entityId: string): string | undefined {+ const cached = getSoupEntityById(entityId);+ if (!cached) return undefined;+ if (cached.tag === 'project') return cached.data.parentId ?? undefined;+ if ('projectId' in cached.data) return cached.data.projectId ?? undefined;+ return undefined;+}+export function createBulkCopyDssEntityMutation() {// Only support chat + document, same as single-copy versionconst isUnsupportedEntity = (entity: EntityData) => {diff --git a/js/app/packages/queries/soup/normalized-cache/grouped-operations.ts b/js/app/packages/queries/soup/normalized-cache/grouped-operations.tsindex 8649d595e4..96ff745049 100644--- a/js/app/packages/queries/soup/normalized-cache/grouped-operations.ts+++ b/js/app/packages/queries/soup/normalized-cache/grouped-operations.ts@@ -1,5 +1,5 @@import type { SoupApiItem } from '@service-storage/generated/schemas';-import type { InfiniteData } from '@tanstack/solid-query';+import type { InfiniteData, QueryKey } from '@tanstack/solid-query';import { createSignal } from 'solid-js';import { queryClient } from '../../client';@@ -360,12 +360,16 @@ export function removeGroupedPage(}/** Removes items from all expanded group queries while preserving unaffected pages. */-export function removeGroupQueries(entityIds: Set<string>) {+export function removeGroupQueries(+ entityIds: Set<string>,+ keyFilter?: (key: QueryKey) => boolean+) {const queries = queryClient.getQueryCache().findAll({queryKey: soupKeys.groupedGroup._def,});for (const query of queries) {+ if (keyFilter && !keyFilter(query.queryKey)) continue;const prev = query.state.data as GroupedGroupInfiniteData | undefined;if (!prev?.pages?.length) continue;diff --git a/js/app/packages/queries/soup/normalized-cache/index.ts b/js/app/packages/queries/soup/normalized-cache/index.tsindex edfd85b8af..498e3a2fcc 100644--- a/js/app/packages/queries/soup/normalized-cache/index.ts+++ b/js/app/packages/queries/soup/normalized-cache/index.ts@@ -12,6 +12,7 @@ export {refetchSoupEntity,removeSearchEntities,removeSoupEntities,+ removeSoupEntitiesFromQueriesReferencing,} from './operations';export type {SoupEntityTag,diff --git a/js/app/packages/queries/soup/normalized-cache/operations.ts b/js/app/packages/queries/soup/normalized-cache/operations.tsindex 8f7299f8ee..7df0f0a7cc 100644--- a/js/app/packages/queries/soup/normalized-cache/operations.ts+++ b/js/app/packages/queries/soup/normalized-cache/operations.ts@@ -325,6 +325,98 @@ export function removeSoupEntities(entityIds: Set<string>): SoupTransaction {return { rollback: () => restoreSnapshot(previous) };}+/**+ * Remove entities only from soup queries whose key references any of the+ * given ids (e.g. a source folder's project-scoped views — the project UUID is+ * embedded in their compiled filter AST). Other queries keep the entities.+ */+export function removeSoupEntitiesFromQueriesReferencing(+ entityIds: Set<string>,+ referenceIds: string[]+): SoupTransaction {+ if (referenceIds.length === 0) return { rollback: () => {} };++ const referencesIds = (key: QueryKey) => {+ const serialized = JSON.stringify(key);+ return referenceIds.some((id) => serialized.includes(id));+ };++ // Scoped equivalent of cancelSoupQueries (same data !== undefined guard)+ const cancelPredicate = (query: Query) =>+ query.state.data !== undefined && referencesIds(query.queryKey);+ queryClient.cancelQueries({+ queryKey: soupKeys.items._def,+ predicate: cancelPredicate,+ });+ queryClient.cancelQueries({+ queryKey: soupKeys.astItems._def,+ predicate: cancelPredicate,+ });++ const previous = snapshotSoup();++ queryClient.setQueriesData<SoupItemsInfiniteData>(+ {+ predicate: (q) =>+ partialMatchKey(q.queryKey, soupKeys.items._def) &&+ referencesIds(q.queryKey),+ },+ (prev) => {+ if (!prev?.pages) return prev;+ return {+ ...prev,+ pages: prev.pages.map((page) => {+ const items = page.items.filter(+ (item) => !entityIds.has(getSoupItemId(item))+ );+ if (items.length === page.items.length) return page;+ return { ...page, items };+ }),+ };+ }+ );++ queryClient.setQueriesData<SoupAstItemsInfiniteData>(+ {+ queryKey: soupKeys.astItems._def,+ predicate: (q) => referencesIds(q.queryKey),+ },+ (prev) => {+ if (!prev?.pages?.length) return prev;++ const firstPage = prev.pages[0];++ if (firstPage.kind === 'flat') {+ let changed = false;+ const pages = prev.pages.map((page) => {+ if (page.kind !== 'flat') return page;++ const items = page.items.filter(+ (item) => !entityIds.has(getSoupItemId(item))+ );++ if (items.length === page.items.length) return page;++ changed = true;+ return { ...page, items };+ });++ return changed ? { ...prev, pages } : prev;+ }++ const nextPage = removeGroupedPage(firstPage, entityIds);++ return nextPage === firstPage+ ? prev+ : { ...prev, pages: [nextPage, ...prev.pages.slice(1)] };+ }+ );++ removeGroupQueries(entityIds, referencesIds);++ return { rollback: () => restoreSnapshot(previous) };+}+export function removeSearchEntities(entityIds: Set<string>): SoupTransaction {queryClient.cancelQueries({ queryKey: soupKeys.search._def });diff --git a/rust/cloud-storage/document_storage_service/src/api/projects/edit_project.rs b/rust/cloud-storage/document_storage_service/src/api/projects/edit_project.rsindex 64b9a3f596..f101c219bb 100644--- a/rust/cloud-storage/document_storage_service/src/api/projects/edit_project.rs+++ b/rust/cloud-storage/document_storage_service/src/api/projects/edit_project.rs@@ -132,30 +132,33 @@ async fn edit_project_v2("project parent id matches project id".to_string(),));}- match macro_db_client::projects::nested_projects::is_project_recursively_nested(- ctx.db.clone(),- id.as_str(),- project_parent_id.as_str(),- )- .await- {- Ok(e) => {- if e.is_some() {- tracing::warn!(error=?e, "project is recursively nested");+ // An empty parent id clears the parent, so there is no nesting to check+ if !project_parent_id.is_empty() {+ match macro_db_client::projects::nested_projects::is_project_recursively_nested(+ ctx.db.clone(),+ id.as_str(),+ project_parent_id.as_str(),+ )+ .await+ {+ Ok(e) => {+ if e.is_some() {+ tracing::warn!(error=?e, "project is recursively nested");+ return Err((+ StatusCode::BAD_REQUEST,+ "project is recursively nested".to_string(),+ ));+ }+ }+ Err(e) => {+ tracing::error!(error=?e, "unable to check if project is recursively nested");return Err((- StatusCode::BAD_REQUEST,- "project is recursively nested".to_string(),+ StatusCode::INTERNAL_SERVER_ERROR,+ "error checking if project is recursively nested".to_string(),));}- }- Err(e) => {- tracing::error!(error=?e, "unable to check if project is recursively nested");- return Err((- StatusCode::INTERNAL_SERVER_ERROR,- "error checking if project is recursively nested".to_string(),- ));- }- };+ };+ }}if req.share_permission.is_some() && users_access_level != AccessLevel::Owner {@@ -206,6 +209,8 @@ async fn edit_project_v2(.as_ref(),req.project_parent_id.as_ref()+ // An empty parent id clears the parent+ .filter(|p| !p.is_empty()).map(|p| macro_uuid::string_to_uuid(p).unwrap()).as_ref(),)diff --git a/rust/cloud-storage/entity_access/src/inbound/axum_extractors/project.rs b/rust/cloud-storage/entity_access/src/inbound/axum_extractors/project.rsindex fc980d5d3e..2bd8d53303 100644--- a/rust/cloud-storage/entity_access/src/inbound/axum_extractors/project.rs+++ b/rust/cloud-storage/entity_access/src/inbound/axum_extractors/project.rs@@ -271,6 +271,14 @@ where});};+ // An empty id clears the entity's project: no target project to authorize+ if project.id().is_empty() {+ return Ok(Self::ProjectNotInBody {+ body: cb()?,+ _marker: PhantomData,+ });+ }+if internal_user.is_some() {return Ok(Self::FoundProject {entity_access_receipt: EntityAccessReceipt {