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
refactor(entities): route flagged mutations through graphql (#8348)
Sean Ayeab27bd931f40
diff --git a/apps/web/AGENTS.md b/apps/web/AGENTS.mdindex 666aacff3e..c355c5122f 100644--- a/apps/web/AGENTS.md+++ b/apps/web/AGENTS.md@@ -111,6 +111,11 @@ ownership. Cancel, logout, and the ten-minute timeout retire pending callbacks.feature-specific query orchestration with its owning feature.- Refresh the channel list's bounded unread edge when opening a conversation,including an empty unread result after a read on another device.+- Route supported move, trash, restore, permanent-delete, duplicate, and share-policy+ writes through `queries/storage/entity-mutations` when GraphQL Soup is enabled;+ never retry failed GraphQL writes through REST. Preserve non-owner history removal+ and version-specific markdown forks on their existing paths. Confirmed restores+ clear earlier deletion markers without clearing a newer delete's intent.- Preserve loaded block content on initial access confirmation when its loadersupplies no permissions; reload only on a later confirmed permission change.Apply shared access in place only after a successful permissionless load.diff --git a/apps/web/src/features/entity/queries/dss.test.tsx b/apps/web/src/features/entity/queries/dss.test.tsxindex f1080515e9..88b91ce31e 100644--- a/apps/web/src/features/entity/queries/dss.test.tsx+++ b/apps/web/src/features/entity/queries/dss.test.tsx@@ -13,6 +13,7 @@ const mocks = vi.hoisted(() => ({graphqlEnabled: vi.fn(() => true),deleteItem: vi.fn(),deleteCall: vi.fn(),+ deleteCallGraphql: vi.fn(),deleteReminder: vi.fn(),deleteSchedule: vi.fn(),moveToFolder: vi.fn(),@@ -58,6 +59,9 @@ vi.mock('@queries/soup/cache', () => ({vi.mock('@queries/soup/graphql/active-queries', () => ({refreshActiveGraphqlSoupQueries: mocks.refresh,}));+vi.mock('@queries/storage/entity-mutations', () => ({+ permanentlyDeleteEntity: mocks.deleteCallGraphql,+}));vi.mock('@service-call/client', () => ({callServiceClient: { deleteCallRecord: mocks.deleteCall },}));@@ -336,7 +340,7 @@ describe('bulk delete GraphQL optimism', () => {];client.setQueryData(scheduledActionKeys.list.queryKey, schedules);mocks.deleteItem.mockRejectedValue(new Error('document delete failed'));- mocks.deleteCall.mockResolvedValue(ok(undefined));+ mocks.deleteCallGraphql.mockResolvedValue(undefined);mocks.deleteSchedule.mockImplementation(async ({ scheduleId }: { scheduleId: string }) =>scheduleId === 'deleted-auto'@@ -352,6 +356,11 @@ describe('bulk delete GraphQL optimism', () => {entity('failed-auto', 'routine'),])).rejects.toBeInstanceOf(BulkDeleteFailure);+ expect(mocks.deleteCallGraphql).toHaveBeenCalledWith({+ type: 'CALL',+ id: 'deleted-call',+ });+ expect(mocks.deleteCall).not.toHaveBeenCalled();expect(invalidate).toHaveBeenCalledWith({ queryKey: callKeys._def });expect(invalidate).toHaveBeenCalledWith({queryKey: scheduledActionKeys.list.queryKey,@@ -372,7 +381,7 @@ describe('bulk delete GraphQL optimism', () => {.mockResolvedValue(undefined);const schedules = [{ id: 'failed-auto' }];client.setQueryData(scheduledActionKeys.list.queryKey, schedules);- mocks.deleteCall.mockRejectedValue(new Error('failed call'));+ mocks.deleteCallGraphql.mockRejectedValue(new Error('failed call'));mocks.deleteSchedule.mockRejectedValue(new Error('failed schedule'));const { mutation } = mount();await expect(diff --git a/apps/web/src/features/entity/queries/dss.ts b/apps/web/src/features/entity/queries/dss.tsindex 3504595666..d1b8b048e0 100644--- a/apps/web/src/features/entity/queries/dss.ts+++ b/apps/web/src/features/entity/queries/dss.ts@@ -32,6 +32,7 @@ import {} from '@queries/soup/graphql/optimistic-deletions';import { soupKeys } from '@queries/soup/keys';import { ownTouchStamp } from '@queries/soup/normalized-cache/own-touch';+import { permanentlyDeleteEntity } from '@queries/storage/entity-mutations';import { callServiceClient } from '@service-call/client';import { scheduledActionClient } from '@service-scheduled-action/client';import { useMutation } from '@tanstack/solid-query';@@ -126,6 +127,10 @@ export function createBulkDeleteDssItemsMutation() {return true;}if (e.type === 'call') {+ if (isFeatureEnabled(enableGraphqlSoup)) {+ await permanentlyDeleteEntity({ type: 'CALL', id: e.id });+ return true;+ }return throwOnErr(() =>callServiceClient.deleteCallRecord(e.id)).then(() => true);diff --git a/apps/web/src/lib/core/component/FileList/itemOperations.test.ts b/apps/web/src/lib/core/component/FileList/itemOperations.test.tsnew file mode 100644index 0000000000..85e8ed487c--- /dev/null+++ b/apps/web/src/lib/core/component/FileList/itemOperations.test.ts@@ -0,0 +1,314 @@+import { err, ok } from 'neverthrow';+import { beforeEach, describe, expect, it, vi } from 'vitest';++const mocks = vi.hoisted(() => ({+ graphql: true,+ showPaywall: vi.fn(),+ metadata: vi.fn(),+ edit: vi.fn(),+ trash: vi.fn(),+ restore: vi.fn(),+ permanent: vi.fn(),+ copy: vi.fn(),+ removeHistory: vi.fn(),+ mutation: vi.fn(),+ refresh: vi.fn(),+ resources: vi.fn(),+ removeDeleted: vi.fn(),+}));+vi.mock('@app/lib/analytics', () => ({ analytics: { track: vi.fn() } }));+vi.mock('@core/constant/featureFlags', () => ({+ enableGraphqlSoup: {},+ isFeatureEnabled: () => mocks.graphql,+}));+vi.mock('@core/constant/PaywallState', () => ({+ usePaywallState: () => ({ showPaywall: mocks.showPaywall }),+}));+vi.mock('@queries/history/history', () => ({+ removeHistoryItem: mocks.removeHistory,+}));+vi.mock('@queries/storage/deleted', () => ({+ getDeletedTree: () => ({ itemMap: {} }),+ optimisticallyRemoveDeletedItem: mocks.removeDeleted,+}));+vi.mock('@queries/soup/graphql/active-queries', () => ({+ refreshActiveGraphqlSoupQueries: mocks.refresh,+}));+vi.mock('@service-storage/util/refetchResources', () => ({+ refetchResources: mocks.resources,+}));+vi.mock('@service-storage/graphql-soup', () => ({+ getEntityGraphqlClient: () => ({ mutation: mocks.mutation }),+}));+vi.mock('@service-storage/client', () => ({+ storageServiceClient: {+ getDocumentMetadata: mocks.metadata,+ editDocument: mocks.edit,+ deleteDocument: mocks.trash,+ revertDocumentDelete: mocks.restore,+ permanentlyDeleteDocument: mocks.permanent,+ copyDocument: mocks.copy,+ projects: {+ getProject: mocks.metadata,+ edit: mocks.edit,+ delete: mocks.trash,+ revertDelete: mocks.restore,+ permanentlyDelete: mocks.permanent,+ },+ },+}));+vi.mock('@service-cognition/client', () => ({+ cognitionApiServiceClient: {+ getChat: mocks.metadata,+ editChatProject: mocks.edit,+ deleteChat: mocks.trash,+ revertDeleteChat: mocks.restore,+ permanentlyDeleteChat: mocks.permanent,+ copyChat: mocks.copy,+ },+}));+vi.mock('@service-email/client', () => ({+ emailClient: { updateThreadProject: mocks.edit },+}));+vi.mock('@service-call/client', () => ({ callServiceClient: {} }));++import { getOperationAST } from 'graphql';+import {+ copyItem,+ deleteItem,+ moveToFolder,+ permanentlyDelete,+ revertDelete,+} from './itemOperations';++beforeEach(() => {+ vi.resetAllMocks();+ mocks.graphql = true;+ mocks.metadata.mockResolvedValue(ok({ userAccessLevel: 'owner' }));+ for (const fn of [mocks.edit, mocks.trash, mocks.restore, mocks.permanent])+ fn.mockResolvedValue(ok(undefined));+ mocks.copy.mockResolvedValue(ok({ documentId: 'copy', id: 'copy' }));+ mocks.removeHistory.mockResolvedValue(true);+ mocks.refresh.mockResolvedValue(undefined);+ mocks.mutation.mockImplementation((document) => ({+ toPromise: async () => {+ const operation = getOperationAST(document)?.name?.value ?? '';+ const field = operation[0].toLowerCase() + operation.slice(1);+ return {+ data: {+ [field]: {+ results: [{ __typename: 'GraphqlMutationSuccess', effects: [] }],+ },+ },+ };+ },+ }));+});++function variables() {+ return mocks.mutation.mock.calls[0][1];+}++describe('flagged entity callers', () => {+ it.each([+ ['document', 'DOCUMENT'],+ ['chat', 'CHAT'],+ ['project', 'PROJECT'],+ ['email', 'EMAIL_THREAD'],+ ] as const)(+ 'moves %s to a folder and root without REST preflights',+ async (itemType, type) => {+ for (const folderId of ['folder', null]) {+ mocks.mutation.mockClear();+ expect(await moveToFolder({ itemType, id: 'source', folderId })).toBe(+ true+ );+ expect(variables()).toEqual({+ inputs: [{ entity: { type, id: 'source' }, projectId: folderId }],+ });+ }+ expect(mocks.edit).not.toHaveBeenCalled();+ expect(mocks.metadata).not.toHaveBeenCalled();+ }+ );++ it.each(['document', 'chat', 'project'] as const)(+ 'trashes/restores/permanently deletes %s through GraphQL',+ async (itemType) => {+ expect(await deleteItem({ itemType, id: 'source' })).toBe(true);+ expect(await revertDelete({ itemType, id: 'source' })).toBe(true);+ expect(await permanentlyDelete({ itemType, id: 'source' })).toBe(true);+ expect(+ mocks.mutation.mock.calls.map(+ ([doc]) => getOperationAST(doc)?.name?.value+ )+ ).toEqual([+ 'TrashEntities',+ 'RestoreEntities',+ 'DeleteEntitiesPermanently',+ ]);+ expect(mocks.trash).not.toHaveBeenCalled();+ expect(mocks.restore).not.toHaveBeenCalled();+ expect(mocks.permanent).not.toHaveBeenCalled();+ }+ );++ it('keeps non-owner deletion as a history removal', async () => {+ mocks.metadata.mockResolvedValue(ok({ userAccessLevel: 'edit' }));+ expect(await deleteItem({ itemType: 'document', id: 'shared' })).toBe(true);+ expect(mocks.removeHistory).toHaveBeenCalledWith('document', 'shared');+ expect(mocks.mutation).not.toHaveBeenCalled();+ expect(mocks.trash).not.toHaveBeenCalled();+ });++ it.each(['document', 'chat'] as const)(+ 'opens the new %s identity returned by duplicate effects',+ async (itemType) => {+ mocks.mutation.mockReturnValue({+ toPromise: async () => ({+ data: {+ duplicateEntities: {+ results: [+ {+ __typename: 'GraphqlMutationSuccess',+ effects: [+ {+ __typename: 'SoupUpdated',+ item: {+ __typename:+ itemType === 'document'+ ? 'GraphqlSoupDocument'+ : 'GraphqlSoupChat',+ id: 'new-copy',+ },+ },+ ],+ },+ ],+ },+ },+ }),+ });+ expect(await copyItem({ itemType, id: 'source', name: 'Original' })).toBe(+ 'new-copy'+ );+ expect(variables()).toEqual({+ inputs: [+ {+ entity: {+ type: itemType === 'document' ? 'DOCUMENT' : 'CHAT',+ id: 'source',+ },+ displayName: itemType === 'document' ? 'Original copy' : undefined,+ },+ ],+ });+ expect(mocks.copy).not.toHaveBeenCalled();+ expect(mocks.showPaywall).not.toHaveBeenCalled();+ }+ );++ it.each([+ [true, 'chat', 'FORBIDDEN', 1],+ [false, 'chat', 'FORBIDDEN', 1],+ [true, 'document', 'FORBIDDEN', 0],+ [false, 'document', 'FORBIDDEN', 0],+ [true, 'chat', 'NOT_FOUND', 0],+ [true, 'chat', 'INTERNAL', 0],+ ] as const)(+ 'preserves copy paywall behavior (graphql=%s, item=%s, error=%s)',+ async (graphql, itemType, errorCode, paywallCalls) => {+ mocks.graphql = graphql;+ mocks.mutation.mockReturnValue({+ toPromise: async () => ({+ data: {+ duplicateEntities: {+ results: [+ {+ __typename: 'GraphqlMutationError',+ errorCode,+ message: 'Copy refused',+ },+ ],+ },+ },+ }),+ });+ mocks.copy.mockResolvedValue(+ err([{ code: errorCode, message: 'Copy refused' }])+ );++ expect(+ await copyItem({ itemType, id: 'source', name: 'Original' })+ ).toBeNull();+ expect(mocks.showPaywall).toHaveBeenCalledTimes(paywallCalls);+ expect(mocks.mutation).toHaveBeenCalledTimes(graphql ? 1 : 0);+ expect(mocks.copy).toHaveBeenCalledTimes(graphql ? 0 : 1);+ expect(mocks.resources).not.toHaveBeenCalled();+ expect(mocks.refresh).not.toHaveBeenCalled();+ }+ );++ it('preserves every REST path when the flag is disabled', async () => {+ mocks.graphql = false;+ expect(+ await moveToFolder({ itemType: 'document', id: 'source', folderId: null })+ ).toBe(true);+ expect(await deleteItem({ itemType: 'document', id: 'source' })).toBe(true);+ expect(await revertDelete({ itemType: 'document', id: 'source' })).toBe(+ true+ );+ expect(+ await permanentlyDelete({ itemType: 'document', id: 'source' })+ ).toBe(true);+ expect(+ await copyItem({ itemType: 'document', id: 'source', name: 'Original' })+ ).toBe('copy');+ expect(mocks.edit).toHaveBeenCalledWith({+ documentId: 'source',+ projectId: '',+ });+ for (const fn of [mocks.trash, mocks.restore, mocks.permanent, mocks.copy])+ expect(fn).toHaveBeenCalledOnce();+ expect(mocks.mutation).not.toHaveBeenCalled();+ });++ it('does not convert a forbidden GraphQL write into a REST retry or success', async () => {+ mocks.mutation.mockReturnValue({+ toPromise: async () => ({+ data: {+ moveEntities: {+ results: [+ {+ __typename: 'GraphqlMutationError',+ errorCode: 'FORBIDDEN',+ message: 'Denied',+ },+ ],+ },+ },+ }),+ });+ expect(+ await moveToFolder({+ itemType: 'document',+ id: 'source',+ folderId: 'folder',+ })+ ).toBe(false);+ expect(mocks.edit).not.toHaveBeenCalled();+ expect(mocks.refresh).not.toHaveBeenCalled();+ expect(mocks.resources).not.toHaveBeenCalled();+ });++ it('keeps REST permission failures unchanged', async () => {+ mocks.graphql = false;+ mocks.metadata.mockResolvedValue(+ err([{ code: 'FORBIDDEN', message: 'Denied' }])+ );+ expect(+ await moveToFolder({ itemType: 'document', id: 'source', folderId: null })+ ).toBe(false);+ expect(mocks.edit).not.toHaveBeenCalled();+ });+});diff --git a/apps/web/src/lib/core/component/FileList/itemOperations.ts b/apps/web/src/lib/core/component/FileList/itemOperations.tsindex 97e912c919..681bd4e077 100644--- a/apps/web/src/lib/core/component/FileList/itemOperations.ts+++ b/apps/web/src/lib/core/component/FileList/itemOperations.ts@@ -1,12 +1,23 @@import { analytics } from '@app/lib/analytics';+import {+ enableGraphqlSoup,+ isFeatureEnabled,+} from '@core/constant/featureFlags';import { usePaywallState } from '@core/constant/PaywallState';import { isPaymentError } from '@core/util/handlePaymentError';-+import { catchToResult } from '@core/util/result';import { removeHistoryItem } from '@queries/history/history';import {getDeletedTree,optimisticallyRemoveDeletedItem,} from '@queries/storage/deleted';+import {+ duplicateEntity,+ moveEntity,+ permanentlyDeleteEntity,+ restoreEntity,+ trashEntity,+} from '@queries/storage/entity-mutations';import { callServiceClient } from '@service-call/client';import { cognitionApiServiceClient } from '@service-cognition/client';import { emailClient } from '@service-email/client';@@ -21,6 +32,12 @@ import {} from '../SharePermissions';const DEFAULT_CHUNK_SIZE = 10;+const ENTITY_TYPES = {+ document: 'DOCUMENT',+ project: 'PROJECT',+ chat: 'CHAT',+ email: 'EMAIL_THREAD',+} as const;export async function getItemAccessLevel({itemType,@@ -165,29 +182,37 @@ export async function deleteItem(args: {if (accessLevel === 'owner') {let result;- switch (itemType) {- case 'document': {- result = await storageServiceClient.deleteDocument({- documentId: id,- });- break;- }- case 'project': {- result = await storageServiceClient.projects.delete({- id,- });- break;- }- case 'chat': {- result = await cognitionApiServiceClient.deleteChat({- chat_id: id,- });- break;- }- default: {- return false;+ if (+ isFeatureEnabled(enableGraphqlSoup) &&+ (itemType === 'document' || itemType === 'project' || itemType === 'chat')+ ) {+ result = await catchToResult(() =>+ trashEntity({ type: ENTITY_TYPES[itemType], id })+ );+ } else+ switch (itemType) {+ case 'document': {+ result = await storageServiceClient.deleteDocument({+ documentId: id,+ });+ break;+ }+ case 'project': {+ result = await storageServiceClient.projects.delete({+ id,+ });+ break;+ }+ case 'chat': {+ result = await cognitionApiServiceClient.deleteChat({+ chat_id: id,+ });+ break;+ }+ default: {+ return false;+ }}- }if (result.isErr()) {return false;}@@ -257,46 +282,60 @@ export async function moveToFolder(args: {folderId: string | null;}): Promise<boolean> {const { itemType, id, folderId } = args;- const accessLevel = await getItemAccessLevel({ itemType, id });- if (!accessLevel) return false;- if (!hasPermissions(getPermissions(accessLevel), Permissions.CAN_EDIT))- return false;+ const graphql = isFeatureEnabled(enableGraphqlSoup);+ if (!graphql) {+ const accessLevel = await getItemAccessLevel({ itemType, id });+ if (!accessLevel) return false;+ if (!hasPermissions(getPermissions(accessLevel), Permissions.CAN_EDIT))+ return false;+ }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 ?? '',- });- break;- }- case 'project': {- result = await storageServiceClient.projects.edit({- id,- projectParentId: folderId ?? '',- });- break;- }- case 'chat': {- result = await cognitionApiServiceClient.editChatProject({- chat_id: id,- project_id: folderId ?? '',- });- break;- }- case 'email': {- result = await emailClient.updateThreadProject({- thread_id: id,- projectId: folderId,- });- break;- }- default: {- return false;+ if (+ graphql &&+ (itemType === 'document' ||+ itemType === 'project' ||+ itemType === 'chat' ||+ itemType === 'email')+ ) {+ result = await catchToResult(() =>+ moveEntity({ type: ENTITY_TYPES[itemType], id }, folderId)+ );+ } else+ switch (itemType) {+ // Storage/chat backends clear the folder on empty string; email on null.+ case 'document': {+ result = await storageServiceClient.editDocument({+ documentId: id,+ projectId: folderId ?? '',+ });+ break;+ }+ case 'project': {+ result = await storageServiceClient.projects.edit({+ id,+ projectParentId: folderId ?? '',+ });+ break;+ }+ case 'chat': {+ result = await cognitionApiServiceClient.editChatProject({+ chat_id: id,+ project_id: folderId ?? '',+ });+ break;+ }+ case 'email': {+ result = await emailClient.updateThreadProject({+ thread_id: id,+ projectId: folderId,+ });+ break;+ }+ default: {+ return false;+ }}- }if (result.isErr()) {return false;@@ -364,33 +403,48 @@ export async function copyItem(args: {};let newId = '';- switch (itemType) {- case 'document': {- const result = await storageServiceClient.copyDocument({- documentId: id,- documentName: createCopyName(name),- });- if (result.isErr()) return null;- newId = result.value.documentId;- break;- }- case 'chat': {- const result = await cognitionApiServiceClient.copyChat({- chat_id: id,- name: createCopyName(name),- });- if (isPaymentError(result)) {- showPaywall();+ if (+ isFeatureEnabled(enableGraphqlSoup) &&+ (itemType === 'document' || itemType === 'chat')+ ) {+ const result = await catchToResult(() =>+ duplicateEntity(+ { type: ENTITY_TYPES[itemType], id },+ // The REST chat endpoint also ignores the supplied name and names the copy itself.+ itemType === 'document' ? createCopyName(name) : undefined+ )+ );+ if (itemType === 'chat' && isPaymentError(result)) showPaywall();+ if (result.isErr()) return null;+ newId = result.value;+ } else+ switch (itemType) {+ case 'document': {+ const result = await storageServiceClient.copyDocument({+ documentId: id,+ documentName: createCopyName(name),+ });+ if (result.isErr()) return null;+ newId = result.value.documentId;+ break;}- if (result.isErr()) {- return null;+ case 'chat': {+ const result = await cognitionApiServiceClient.copyChat({+ chat_id: id,+ name: createCopyName(name),+ });+ if (isPaymentError(result)) {+ showPaywall();+ }+ if (result.isErr()) {+ return null;+ }+ newId = result.value.id;+ break;}- newId = result.value.id;- break;+ default:+ return null;}- default:- return null;- }analytics.track('create_entity', {entityType: itemType,@@ -447,30 +501,37 @@ export async function revertDelete(args: {const { itemType, id } = args;let result;-- switch (itemType) {- case 'document': {- result = await storageServiceClient.revertDocumentDelete({- documentId: id,- });- break;- }- case 'project': {- result = await storageServiceClient.projects.revertDelete({- id,- });- break;- }- case 'chat': {- result = await cognitionApiServiceClient.revertDeleteChat({- chat_id: id,- });- break;- }- default: {- return false;+ if (+ isFeatureEnabled(enableGraphqlSoup) &&+ (itemType === 'document' || itemType === 'project' || itemType === 'chat')+ ) {+ result = await catchToResult(() =>+ restoreEntity({ type: ENTITY_TYPES[itemType], id })+ );+ } else+ switch (itemType) {+ case 'document': {+ result = await storageServiceClient.revertDocumentDelete({+ documentId: id,+ });+ break;+ }+ case 'project': {+ result = await storageServiceClient.projects.revertDelete({+ id,+ });+ break;+ }+ case 'chat': {+ result = await cognitionApiServiceClient.revertDeleteChat({+ chat_id: id,+ });+ break;+ }+ default: {+ return false;+ }}- }if (result.isErr()) {return false;@@ -490,9 +551,13 @@ export async function permanentlyDelete(args: {switch (itemType) {case 'document': {optimisticallyRemoveDeletedItem(id);- result = await storageServiceClient.permanentlyDeleteDocument({- documentId: id,- });+ result = isFeatureEnabled(enableGraphqlSoup)+ ? await catchToResult(() =>+ permanentlyDeleteEntity({ type: 'DOCUMENT', id })+ )+ : await storageServiceClient.permanentlyDeleteDocument({+ documentId: id,+ });break;}case 'project': {@@ -515,16 +580,22 @@ export async function permanentlyDelete(args: {});optimisticallyRemoveDeletedItem(id);- result = await storageServiceClient.projects.permanentlyDelete({- id,- });+ result = isFeatureEnabled(enableGraphqlSoup)+ ? await catchToResult(() =>+ permanentlyDeleteEntity({ type: 'PROJECT', id })+ )+ : await storageServiceClient.projects.permanentlyDelete({ id });break;}case 'chat': {optimisticallyRemoveDeletedItem(id);- result = await cognitionApiServiceClient.permanentlyDeleteChat({- chat_id: id,- });+ result = isFeatureEnabled(enableGraphqlSoup)+ ? await catchToResult(() =>+ permanentlyDeleteEntity({ type: 'CHAT', id })+ )+ : await cognitionApiServiceClient.permanentlyDeleteChat({+ chat_id: id,+ });break;}default: {diff --git a/apps/web/src/lib/core/component/TopBar/ShareButton.test.tsx b/apps/web/src/lib/core/component/TopBar/ShareButton.test.tsxindex f860531d23..56b36fb8b5 100644--- a/apps/web/src/lib/core/component/TopBar/ShareButton.test.tsx+++ b/apps/web/src/lib/core/component/TopBar/ShareButton.test.tsx@@ -45,6 +45,8 @@ const SOMEONE_ELSE = 'macro|[email protected]';const mocks = vi.hoisted(() => ({sendToChannel: vi.fn(),sendToUsers: vi.fn(),+ graphql: false,+ graphqlShare: vi.fn(),mobile: false,hasTeam: false,getAgentPermissions: vi.fn(),@@ -78,6 +80,12 @@ vi.mock('@app/features/crm/sharing-adapter', () => ({updatePipelineSharePermissions: mocks.updatePipelinePermissions,updatePipelineTeamShare: mocks.updatePipelineTeamShare,}));+vi.mock('@queries/storage/entity-mutations', () => ({+ usesGraphqlSharePolicy: (type: string) =>+ mocks.graphql &&+ ['document', 'chat', 'project', 'email', 'call'].includes(type),+ updateEntitySharePolicy: mocks.graphqlShare,+}));vi.mock('@queries/storage/databases', () => ({getDatabaseSharePermissions: mocks.getDatabasePermissions,updateDatabaseSharePermissions: mocks.updateDatabasePermissions,@@ -381,6 +389,8 @@ beforeEach(() => {mocks.blockEditPermissionEnabled = true;mocks.mobile = false;mocks.hasTeam = false;+ mocks.graphql = false;+ mocks.graphqlShare.mockResolvedValue(ok(undefined));mocks.callRecordShared = true;mocks.callRecordChannelId = 'channel-1';mocks.callRecordQuerySuccess = true;@@ -965,6 +975,33 @@ describe('call team sharing', () => {});describe('chat team sharing', () => {+ it.each([false, true])(+ 'uses GraphQL for team and link changes on mobile=%s',+ async (mobile) => {+ mocks.graphql = true;+ mocks.mobile = mobile;+ mocks.hasTeam = true;+ mountChatShare();+ if (mobile) fireEvent.click(screen.getByRole('tab', { name: 'Link' }));+ fireEvent.click(+ screen.getByRole('button', { name: 'Set Team access level edit' })+ );+ await vi.waitFor(() =>+ expect(mocks.graphqlShare).toHaveBeenCalledWith('chat', 'chat-1', {+ teamShareAccessLevel: 'edit',+ })+ );+ fireEvent.click(screen.getByRole('button', { name: 'Set link PUBLIC' }));+ await vi.waitFor(() =>+ expect(mocks.graphqlShare).toHaveBeenCalledWith('chat', 'chat-1', {+ linkShare: 'PUBLIC',+ linkShareAccessLevel: 'view',+ })+ );+ expect(mocks.updateChatPermissions).not.toHaveBeenCalled();+ }+ );+it('lets the owner share the chat with their team through the chat permissions endpoint', async () => {mocks.hasTeam = true;mountChatShare();diff --git a/apps/web/src/lib/core/component/TopBar/ShareButton.tsx b/apps/web/src/lib/core/component/TopBar/ShareButton.tsxindex 430a653c3f..6c1f021a72 100644--- a/apps/web/src/lib/core/component/TopBar/ShareButton.tsx+++ b/apps/web/src/lib/core/component/TopBar/ShareButton.tsx@@ -85,6 +85,10 @@ import {getDatabaseSharePermissions,updateDatabaseSharePermissions,} from '@queries/storage/databases';+import {+ updateEntitySharePolicy,+ usesGraphqlSharePolicy,+} from '@queries/storage/entity-mutations';import {getFormSharePermissions,updateFormSharePermissions,@@ -1001,7 +1005,23 @@ export function ShareModal(props: ShareModalProps) {const removeChannelAccess = createCallback(async (channelId: string) => {if (recipientPermissions() !== Permissions.OWNER) return;- if (props.itemType === 'crm_pipeline') {+ if (usesGraphqlSharePolicy(props.itemType)) {+ const result = await updateEntitySharePolicy(props.itemType, props.id, {+ channelSharePermissions: [{ operation: 'remove', channelId }],+ });+ if (result.isOk()) {+ fireAndForget(refetch(), 'share-modal');+ toast.success(+ props.itemType === 'project'+ ? 'Removed folder access'+ : 'Removed channel access'+ );+ } else {+ toast.alert('Failed to remove channel access', {+ subtext: 'Please try again',+ });+ }+ } else if (props.itemType === 'crm_pipeline') {const result = await updatePipelineSharePermissions(props.id, {channelSharePermissions: [{ operation: 'remove', channelId }],});@@ -1150,7 +1170,13 @@ export function ShareModal(props: ShareModalProps) {| Result<any, ResultError<any>[]>| Result<void, ResultError<any>[]>| null = null;- if (props.itemType === 'crm_pipeline') {+ if (usesGraphqlSharePolicy(props.itemType)) {+ result = await updateEntitySharePolicy(props.itemType, props.id, {+ channelSharePermissions: [+ { operation: 'replace', accessLevel, channelId },+ ],+ });+ } else if (props.itemType === 'crm_pipeline') {result = await updatePipelineSharePermissions(props.id, {channelSharePermissions: [{ operation: 'replace', accessLevel, channelId },@@ -1302,7 +1328,13 @@ export function ShareModal(props: ShareModalProps) {getTeamShareScope(sharePermission.teamShareAccessLevel) !== 'NONE';let result: Result<unknown, ResultError<any>[]>;- if (props.itemType === 'crm_pipeline') {+ if (props.itemType !== 'call' && usesGraphqlSharePolicy(props.itemType)) {+ result = await updateEntitySharePolicy(+ props.itemType,+ props.id,+ sharePermission+ );+ } else if (props.itemType === 'crm_pipeline') {result = await updatePipelineTeamShare(props.id, shared);} else if (props.itemType === 'agent_session') {result = await updateAgentSessionSharePermissions(@@ -1393,7 +1425,13 @@ export function ShareModal(props: ShareModalProps) {const scope = getLinkShareScope(sharePermission.linkShare);let result: Result<any, ResultError<any>[]> | undefined;- if (props.itemType === 'agent_session') {+ if (usesGraphqlSharePolicy(props.itemType)) {+ result = await updateEntitySharePolicy(+ props.itemType,+ props.id,+ sharePermission+ );+ } else if (props.itemType === 'agent_session') {result = await updateAgentSessionSharePermissions(props.id,sharePermissiondiff --git a/apps/web/src/lib/queries/call/call.test.ts b/apps/web/src/lib/queries/call/call.test.tsindex b71cee4f0d..dfd9738557 100644--- a/apps/web/src/lib/queries/call/call.test.ts+++ b/apps/web/src/lib/queries/call/call.test.ts@@ -8,6 +8,8 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';const callClient = vi.hoisted(() => ({getCallRecord: vi.fn(),editCallRecord: vi.fn(),+ graphql: false,+ graphqlShare: vi.fn(),}));vi.mock('@queries/client', async () => {const { QueryClient } = await import('@tanstack/solid-query');@@ -23,6 +25,10 @@ vi.mock('@core/component/Toast/Toast', () => ({toast: { alert: vi.fn(), failure: vi.fn(), success: vi.fn() },}));vi.mock('@core/constant/featureFlags', () => ({ ENABLE_CALLS: true }));+vi.mock('../storage/entity-mutations', () => ({+ usesGraphqlSharePolicy: () => callClient.graphql,+ updateEntitySharePolicy: callClient.graphqlShare,+}));import { queryClient } from '@queries/client';import type { CallRecord } from '@service-storage/generated/schemas/callRecord';@@ -121,10 +127,20 @@ const record = (over: Partial<CallRecord>): CallRecord => ({});describe('call team sharing helpers', () => {+ it('uses the GraphQL share policy for flagged archived-call updates', async () => {+ callClient.graphql = true;+ await updateCallTeamShare('call-1', true);+ expect(callClient.graphqlShare).toHaveBeenCalledWith('call', 'call-1', {+ teamShareAccessLevel: 'view',+ });+ expect(callClient.editCallRecord).not.toHaveBeenCalled();+ });beforeEach(() => {queryClient.clear();callClient.getCallRecord.mockReset();callClient.editCallRecord.mockReset();+ callClient.graphql = false;+ callClient.graphqlShare.mockReset();});it('never represents standalone calls as team shared, including stale record and cache values', () => {diff --git a/apps/web/src/lib/queries/call/call.ts b/apps/web/src/lib/queries/call/call.tsindex b1d5ca1ac5..84b3941352 100644--- a/apps/web/src/lib/queries/call/call.ts+++ b/apps/web/src/lib/queries/call/call.ts@@ -10,6 +10,10 @@ import type { SharePermissionV2 } from '@service-storage/generated/schemas/shareimport type { UpdateSharePermissionRequestV2 } from '@service-storage/generated/schemas/updateSharePermissionRequestV2';import { queryOptions, useMutation, useQuery } from '@tanstack/solid-query';import type { Accessor } from 'solid-js';+import {+ updateEntitySharePolicy,+ usesGraphqlSharePolicy,+} from '../storage/entity-mutations';import { callKeys } from './keys';function activeCallQueryOptions(channelId: string) {@@ -230,6 +234,12 @@ export function buildCallTeamSharePayload(}export function updateCallTeamShare(callId: string, shared: boolean) {+ if (usesGraphqlSharePolicy('call'))+ return updateEntitySharePolicy(+ 'call',+ callId,+ buildCallTeamSharePayload(shared)+ );return callServiceClient.editCallRecord({callId,sharePermission: buildCallTeamSharePayload(shared),diff --git a/apps/web/src/lib/queries/email/integration.ts b/apps/web/src/lib/queries/email/integration.tsindex b4e174043c..f220fdc421 100644--- a/apps/web/src/lib/queries/email/integration.ts+++ b/apps/web/src/lib/queries/email/integration.ts@@ -13,6 +13,7 @@ import {getActiveGraphqlSoupRevalidations,refreshActiveGraphqlSoupQueries,} from '../soup/graphql/active-queries';+import { updateEntitySharePolicy } from '../storage/entity-mutations';/** Provider operations used by email's production adapters alongside shared mutations. */export const scheduleEmailMessage = (@@ -67,6 +68,12 @@ export async function ensureEmailAttachmentPublic(attachmentId: string) {permissions.value.linkShareAccessLevel === 'view')return undefined;+ if (isFeatureEnabled(enableGraphqlSoup)) {+ return updateEntitySharePolicy('document', attachmentId, {+ linkShare: 'PUBLIC',+ linkShareAccessLevel: 'view',+ });+ }return storageServiceClient.editDocument({documentId: attachmentId,sharePermission: { linkShare: 'PUBLIC', linkShareAccessLevel: 'view' },diff --git a/apps/web/src/lib/queries/mutation-coverage.test.ts b/apps/web/src/lib/queries/mutation-coverage.test.tsindex 2f16331a85..7974e09f34 100644--- a/apps/web/src/lib/queries/mutation-coverage.test.ts+++ b/apps/web/src/lib/queries/mutation-coverage.test.ts@@ -52,12 +52,17 @@ const policies = {'authoritative: exact affected notification IDs required for undo',UndoWorkFeedItemsDone:'authoritative: the server returns the restored feed entries',- MoveEntities: 'inactive: UI uses other transports',- UpdateEntitySharePolicies: 'inactive: UI uses other transports',- TrashEntities: 'inactive: UI uses other transports',- RestoreEntities: 'inactive: UI uses other transports',- DeleteEntitiesPermanently: 'inactive: UI uses other transports',- DuplicateEntities: 'inactive: UI uses other transports',+ MoveEntities:+ 'authoritative: destination authorization and membership refresh',+ UpdateEntitySharePolicies:+ 'authoritative: permission changes require server confirmation',+ TrashEntities:+ 'authoritative: existing UI deletion overlay settles per server result',+ RestoreEntities:+ 'authoritative: server resolves restored ancestry and membership',+ DeleteEntitiesPermanently:+ 'authoritative: irreversible deletion requires server confirmation',+ DuplicateEntities: 'authoritative: server assigns the copy identity',SetEntityFavorite: 'inactive: UI uses SetFavorite',} satisfies Record<string,diff --git a/apps/web/src/lib/queries/soup/graphql/optimistic-deletions.test.ts b/apps/web/src/lib/queries/soup/graphql/optimistic-deletions.test.tsindex b782cf0627..5e3c8f4fe1 100644--- a/apps/web/src/lib/queries/soup/graphql/optimistic-deletions.test.ts+++ b/apps/web/src/lib/queries/soup/graphql/optimistic-deletions.test.ts@@ -18,6 +18,7 @@ import {createGraphqlSoupDeletion,GRAPHQL_SOUP_DELETE_MUTATION_KEY,GRAPHQL_SOUP_DELETE_RETENTION_MS,+ prepareGraphqlSoupRestore,usePendingGraphqlSoupDeleteIds,withoutPendingGraphqlSoupDeletes,withoutPendingSoupEntities,@@ -66,6 +67,39 @@ function data(): SoupAstItemsData {}describe('GraphQL Soup deletion lifecycle', () => {+ it('does not resurrect restored ids when an earlier deletion settles late', async () => {+ refresh.mockReturnValue(new Promise<void>(() => {}));+ const deletion = createGraphqlSoupDeletion(['restored', 'sibling']);+ let started!: () => void;+ const ready = new Promise<void>((resolve) => {+ started = resolve;+ });+ let finish!: () => void;+ const network = new Promise<void>((resolve) => {+ finish = resolve;+ });+ const mutation = client.getMutationCache().build(client, {+ mutationKey: GRAPHQL_SOUP_DELETE_MUTATION_KEY,+ onMutate: () => ({ graphqlDeletion: deletion }),+ mutationFn: async () => {+ started();+ await network;+ },+ onSettled: () => deletion.settle(['restored', 'sibling']),+ });+ const request = mutation.execute(undefined);+ await ready;+ try {+ const confirmRestore = prepareGraphqlSoupRestore();+ confirmRestore(['restored']);+ finish();+ await request;+ expect(deletion.ids()).toEqual(['sibling']);+ } finally {+ deletion.release();+ }+ });+it('retains confirmed ids after their completed mutation is garbage collected', async () => {let finishRefresh!: () => void;refresh.mockReturnValue(diff --git a/apps/web/src/lib/queries/soup/graphql/optimistic-deletions.ts b/apps/web/src/lib/queries/soup/graphql/optimistic-deletions.tsindex cb2c1d80f5..83b369e8ca 100644--- a/apps/web/src/lib/queries/soup/graphql/optimistic-deletions.ts+++ b/apps/web/src/lib/queries/soup/graphql/optimistic-deletions.ts@@ -1,6 +1,6 @@import { fireAndForget } from '@core/util/fireAndForget';import { skipToken, useMutationState, useQuery } from '@tanstack/solid-query';-import { type Accessor, createMemo, createSignal } from 'solid-js';+import { type Accessor, batch, createMemo, createSignal } from 'solid-js';import { queryClient } from '../../client';import type { SoupAstItemsData } from '../items';import { refreshActiveGraphqlSoupQueries } from './active-queries';@@ -15,13 +15,15 @@ export const GRAPHQL_SOUP_DELETE_RETENTION_MS = 60_000;const REVALIDATION_ATTEMPTS = 3;const RETRY_DELAY_MS = 1_000;const RETAINED_DELETIONS_KEY = graphqlSoupKeys.retainedDeletions.queryKey;-type RetainedDeletionIds = Array<Accessor<readonly string[]>>;+type RetainedDeletions = GraphqlSoupDeletion[];export type GraphqlSoupDeletion = {ids: Accessor<readonly string[]>;/** Restore failed ids immediately and revalidate the confirmed deletions. */settle: (deletedIds: readonly string[]) => void;release: () => void;+ /** Retire only ids confirmed restored after this deletion began. */+ restore: (ids: readonly string[]) => void;};/** Per-operation state outlives the mutation and its observers until revalidation. */@@ -33,15 +35,16 @@ export function createGraphqlSoupDeletion(let released = false;let expiryTimer: ReturnType<typeof setTimeout> | undefined;let retryTimer: ReturnType<typeof setTimeout> | undefined;+ const restoredIds = new Set<string>();const release = () => {if (released) return;released = true;clearTimeout(expiryTimer);clearTimeout(retryTimer);setDeletedIds([]);- queryClient.setQueryData<RetainedDeletionIds>(+ queryClient.setQueryData<RetainedDeletions>(RETAINED_DELETIONS_KEY,- (retained) => retained?.filter((ids) => ids !== deletedIds)+ (retained) => retained?.filter((entry) => entry.ids !== deletedIds));};const revalidate = async (attempt: number): Promise<void> => {@@ -59,14 +62,24 @@ export function createGraphqlSoupDeletion();}};- return {+ const deletion: GraphqlSoupDeletion = {ids: deletedIds,release,+ restore: (ids) => {+ if (released) return;+ for (const id of ids) restoredIds.add(id);+ setDeletedIds((previous) =>+ previous.filter((id) => !restoredIds.has(id))+ );+ if (deletedIds().length === 0) release();+ },settle: (successfulIds) => {if (settled || released) return;settled = true;- setDeletedIds([...new Set(successfulIds)]);- if (successfulIds.length === 0) {+ setDeletedIds(+ [...new Set(successfulIds)].filter((id) => !restoredIds.has(id))+ );+ if (deletedIds().length === 0) {release();// Reconcile uncertain failures without retaining a failed deletion.if (ids.length > 0)@@ -75,15 +88,42 @@ export function createGraphqlSoupDeletion(}// A mutation observer can detach before the API finishes, starting its// GC clock early. Keep confirmed ids outside that mutation's lifetime.- queryClient.setQueryData<RetainedDeletionIds>(+ queryClient.setQueryData<RetainedDeletions>(RETAINED_DELETIONS_KEY,- (retained) => [...(retained ?? []), deletedIds]+ (retained) => [...(retained ?? []), deletion]);// Cleanup is independent of hung refresh promises and query lifetime.expiryTimer = setTimeout(release, GRAPHQL_SOUP_DELETE_RETENTION_MS);fireAndForget(revalidate(0), 'soup-optimistic-deletions');},};+ return deletion;+}++/** Snapshot before the restore request: a later delete must keep its own intent.+ * Call the returned function only after server confirmation. Retained entries+ * survive mutation GC, so consult both sources. */+export function prepareGraphqlSoupRestore() {+ const deletions = new Set([+ ...(queryClient.getQueryData<RetainedDeletions>(RETAINED_DELETIONS_KEY) ??+ []),+ ...queryClient+ .getMutationCache()+ .findAll({+ mutationKey: GRAPHQL_SOUP_DELETE_MUTATION_KEY,+ exact: true,+ })+ .flatMap((mutation) => {+ const deletion = (+ mutation.state.context as GraphqlSoupDeleteContext | undefined+ )?.graphqlDeletion;+ return deletion ? [deletion] : [];+ }),+ ]);+ return (restoredIds: readonly string[]) =>+ batch(() => {+ for (const deletion of deletions) deletion.restore(restoredIds);+ });}/** Only GraphQL-enabled bulk deletes opt into the display overlay. */@@ -91,7 +131,7 @@ export type GraphqlSoupDeleteContext = {graphqlDeletion?: GraphqlSoupDeletion;};-/** Reflect pending and confirmed REST deletions in GraphQL views. Completed+/** Reflect pending and confirmed deletions in GraphQL views. Completed* mutations retain their own tombstones until strict revalidation or expiry.*/export function usePendingGraphqlSoupDeleteIds() {@@ -99,7 +139,7 @@ export function usePendingGraphqlSoupDeleteIds() {() => ({queryKey: RETAINED_DELETIONS_KEY,queryFn: skipToken,- initialData: [] as RetainedDeletionIds,+ initialData: [] as RetainedDeletions,// One empty index may live for the client session; its entries always have// bounded lifetimes, even when no view is mounted to observe this query.gcTime: Infinity,@@ -122,7 +162,9 @@ export function usePendingGraphqlSoupDeleteIds() {() =>new Set([...deletions().flatMap((ids) => ids?.() ?? []),- ...(retained.isSuccess ? retained.data.flatMap((ids) => ids()) : []),+ ...(retained.isSuccess+ ? retained.data.flatMap((entry) => entry.ids())+ : []),]));}diff --git a/apps/web/src/lib/queries/storage/entity-mutations.test.ts b/apps/web/src/lib/queries/storage/entity-mutations.test.tsnew file mode 100644index 0000000000..a13ede9a4e--- /dev/null+++ b/apps/web/src/lib/queries/storage/entity-mutations.test.ts@@ -0,0 +1,285 @@+import { CombinedError } from '@urql/core';+import { afterEach, beforeEach, expect, it, vi } from 'vitest';++const mocks = vi.hoisted(() => ({+ graphql: true,+ mutation: vi.fn(),+ refresh: vi.fn(),+}));+vi.mock('@core/constant/featureFlags', () => ({+ enableGraphqlSoup: {},+ isFeatureEnabled: () => mocks.graphql,+}));+vi.mock('@service-storage/graphql-soup', () => ({+ getEntityGraphqlClient: () => ({ mutation: mocks.mutation }),+}));+vi.mock('../soup/graphql/active-queries', () => ({+ refreshActiveGraphqlSoupQueries: mocks.refresh,+}));+vi.mock('@queries/client', async () => {+ const { QueryClient } = await import('@tanstack/solid-query');+ return { queryClient: new QueryClient() };+});++import { UpdateEntitySharePoliciesDocument } from '@service-storage/graphql/generated/graphql';+import { queryClient } from '../client';+import { createGraphqlSoupDeletion } from '../soup/graphql/optimistic-deletions';+import {+ duplicateEntity,+ moveEntity,+ restoreEntity,+ updateEntitySharePolicy,+ usesGraphqlSharePolicy,+} from './entity-mutations';++beforeEach(() => {+ vi.resetAllMocks();+ mocks.graphql = true;+ mocks.refresh.mockResolvedValue(undefined);+ mocks.mutation.mockReturnValue({+ toPromise: async () => ({+ data: {+ updateEntitySharePolicies: {+ results: [+ {+ __typename: 'GraphqlMutationSuccess',+ effects: [],+ },+ ],+ },+ },+ }),+ });+});++afterEach(() => queryClient.clear());++it('shows a confirmed restore immediately while retaining unrelated and newer deletes', async () => {+ mocks.refresh.mockReturnValue(new Promise<void>(() => {}));+ const earlier = createGraphqlSoupDeletion(['restored', 'sibling']);+ earlier.settle(['restored', 'sibling']);+ let finish!: () => void;+ const network = new Promise<void>((resolve) => {+ finish = resolve;+ });+ mocks.mutation.mockReturnValue({+ toPromise: async () => {+ await network;+ return {+ data: {+ restoreEntities: {+ results: [+ {+ __typename: 'GraphqlMutationSuccess',+ effects: [+ {+ __typename: 'SoupUpdated',+ item: { __typename: 'GraphqlSoupDocument', id: 'restored' },+ },+ ],+ },+ ],+ },+ },+ };+ },+ });+ const restore = restoreEntity({ type: 'DOCUMENT', id: 'restored' });+ const newer = createGraphqlSoupDeletion(['restored']);+ newer.settle(['restored']);+ try {+ finish();+ await restore;+ expect(earlier.ids()).toEqual(['sibling']);+ expect(newer.ids()).toEqual(['restored']);+ } finally {+ earlier.release();+ newer.release();+ }+});++it('keeps prior deletion markers when the server refuses restoration', async () => {+ mocks.refresh.mockReturnValue(new Promise<void>(() => {}));+ const deletion = createGraphqlSoupDeletion(['deleted']);+ deletion.settle(['deleted']);+ mocks.mutation.mockReturnValue({+ toPromise: async () => ({+ data: {+ restoreEntities: {+ results: [+ {+ __typename: 'GraphqlMutationError',+ errorCode: 'FORBIDDEN',+ message: 'Denied',+ },+ ],+ },+ },+ }),+ });+ try {+ await expect(+ restoreEntity({ type: 'DOCUMENT', id: 'deleted' })+ ).rejects.toBeDefined();+ expect(deletion.ids()).toEqual(['deleted']);+ } finally {+ deletion.release();+ }+});++it.each([+ ['document', 'DOCUMENT'],+ ['chat', 'CHAT'],+ ['project', 'PROJECT'],+ ['email', 'EMAIL_THREAD'],+ ['call', 'CALL'],+] as const)(+ 'updates %s permissions with enum translation and explicit revocation',+ async (type, gqlType) => {+ const result = await updateEntitySharePolicy(type, 'entity', {+ linkShare: null,+ linkShareAccessLevel: null,+ teamShareAccessLevel: 'view',+ channelSharePermissions: [+ { operation: 'add', channelId: 'a', accessLevel: 'view' },+ { operation: 'replace', channelId: 'b', accessLevel: 'edit' },+ { operation: 'remove', channelId: 'c' },+ ],+ });+ expect(result.isOk()).toBe(true);+ expect(mocks.mutation).toHaveBeenCalledWith(+ UpdateEntitySharePoliciesDocument,+ {+ inputs: [+ {+ entity: { type: gqlType, id: 'entity' },+ policy: {+ linkShare: null,+ linkShareAccessLevel: null,+ teamShareAccessLevel: 'VIEW',+ channelSharePermissions: [+ { operation: 'ADD', channelId: 'a', accessLevel: 'VIEW' },+ { operation: 'REPLACE', channelId: 'b', accessLevel: 'EDIT' },+ { operation: 'REMOVE', channelId: 'c', accessLevel: undefined },+ ],+ },+ },+ ],+ }+ );+ expect(mocks.refresh).toHaveBeenCalledOnce();+ }+);++it('leaves omitted sharing fields absent on the wire', async () => {+ await updateEntitySharePolicy('document', 'entity', {+ teamShareAccessLevel: null,+ });+ expect(JSON.parse(JSON.stringify(mocks.mutation.mock.calls[0][1]))).toEqual({+ inputs: [+ {+ entity: { type: 'DOCUMENT', id: 'entity' },+ policy: { teamShareAccessLevel: null },+ },+ ],+ });+});++it('reads the rollout flag at invocation and excludes unsupported kinds', () => {+ expect(usesGraphqlSharePolicy('document')).toBe(true);+ for (const kind of [+ 'agent_session',+ 'initiative',+ 'database',+ 'form',+ 'crm_pipeline',+ 'channel',+ ])+ expect(usesGraphqlSharePolicy(kind)).toBe(false);+ mocks.graphql = false;+ expect(usesGraphqlSharePolicy('document')).toBe(false);+});++it.each([+ {},+ { data: { moveEntities: { results: [] } } },+ {+ data: {+ moveEntities: {+ results: [+ {+ __typename: 'GraphqlMutationError',+ errorCode: 'NOT_FOUND',+ message: 'Missing',+ },+ ],+ },+ },+ },+ { error: new CombinedError({ networkError: new Error('Connection lost') }) },+])(+ 'rejects missing or failed results without refreshing: %j',+ async (response) => {+ mocks.mutation.mockReturnValue({ toPromise: async () => response });+ await expect(+ moveEntity({ type: 'DOCUMENT', id: 'entity' }, null)+ ).rejects.toBeDefined();+ expect(mocks.mutation).toHaveBeenCalledOnce();+ expect(mocks.refresh).not.toHaveBeenCalled();+ }+);++it('preserves a sharing domain refusal as a failed result', async () => {+ mocks.mutation.mockReturnValue({+ toPromise: async () => ({+ data: {+ updateEntitySharePolicies: {+ results: [+ {+ __typename: 'GraphqlMutationError',+ errorCode: 'FORBIDDEN',+ message: 'Denied',+ },+ ],+ },+ },+ }),+ });+ const result = await updateEntitySharePolicy('document', 'entity', {+ teamShareAccessLevel: 'edit',+ });+ expect(result.isErr() && result.error).toEqual([+ { code: 'FORBIDDEN', message: 'Denied' },+ ]);+ expect(mocks.refresh).not.toHaveBeenCalled();+});++it('never mistakes a source or parent patch for the duplicated entity', async () => {+ mocks.mutation.mockReturnValue({+ toPromise: async () => ({+ data: {+ duplicateEntities: {+ results: [+ {+ __typename: 'GraphqlMutationSuccess',+ effects: [+ {+ __typename: 'SoupUpdated',+ item: { __typename: 'GraphqlSoupProject', id: 'parent' },+ },+ {+ __typename: 'SoupUpdated',+ item: { __typename: 'GraphqlSoupDocument', id: 'source' },+ },+ ],+ },+ ],+ },+ },+ }),+ });+ await expect(+ duplicateEntity({ type: 'DOCUMENT', id: 'source' })+ ).rejects.toThrow('no copy identity');+ expect(mocks.mutation).toHaveBeenCalledOnce();+});diff --git a/apps/web/src/lib/queries/storage/entity-mutations.ts b/apps/web/src/lib/queries/storage/entity-mutations.tsnew file mode 100644index 0000000000..237fd92a75--- /dev/null+++ b/apps/web/src/lib/queries/storage/entity-mutations.ts@@ -0,0 +1,148 @@+import {+ enableGraphqlSoup,+ isFeatureEnabled,+} from '@core/constant/featureFlags';+import { fireAndForget } from '@core/util/fireAndForget';+import { catchToResult } from '@core/util/result';+import type { AccessLevel } from '@service-storage/generated/schemas/accessLevel';+import type { UpdateSharePermissionRequestV2 } from '@service-storage/generated/schemas/updateSharePermissionRequestV2';+import type {+ EntityRefInput,+ EntitySharePolicyInput,+ GraphqlEntityAccessLevel,+ GraphqlSharePolicyOperation,+} from '@service-storage/graphql/generated/graphql';+import {+ duplicateGraphqlEntity,+ moveGraphqlEntity,+ permanentlyDeleteGraphqlEntity,+ restoreGraphqlEntity,+ trashGraphqlEntity,+ updateGraphqlEntitySharePolicy,+} from '@service-storage/graphql-entity-mutations';+import { match } from 'ts-pattern';+import { refreshActiveGraphqlSoupQueries } from '../soup/graphql/active-queries';+import { prepareGraphqlSoupRestore } from '../soup/graphql/optimistic-deletions';++// Membership changes need a refresh even when the normalized cache is disabled.+// A failed refresh must not turn a committed write into a retryable UI failure.+function refreshSoup() {+ fireAndForget(refreshActiveGraphqlSoupQueries(), 'entity-mutation');+}++export async function moveEntity(+ entity: EntityRefInput,+ projectId: string | null+) {+ await moveGraphqlEntity({ entity, projectId });+ refreshSoup();+}++export async function trashEntity(entity: EntityRefInput) {+ await trashGraphqlEntity(entity);+ refreshSoup();+}++export async function restoreEntity(entity: EntityRefInput) {+ const confirmRestore = prepareGraphqlSoupRestore();+ const result = await restoreGraphqlEntity(entity);+ confirmRestore([+ String(entity.id),+ ...result.effects.flatMap((effect) =>+ effect.__typename === 'SoupUpdated' ? [effect.item.id] : []+ ),+ ]);+ refreshSoup();+}++export async function permanentlyDeleteEntity(entity: EntityRefInput) {+ await permanentlyDeleteGraphqlEntity(entity);+ refreshSoup();+}++export async function duplicateEntity(+ entity: EntityRefInput,+ displayName?: string+): Promise<string> {+ const result = await duplicateGraphqlEntity({ entity, displayName });+ refreshSoup();+ for (const effect of result.effects) {+ if (effect.__typename !== 'SoupUpdated' || effect.item.id === entity.id)+ continue;+ if (+ (entity.type === 'DOCUMENT' &&+ effect.item.__typename === 'GraphqlSoupDocument') ||+ (entity.type === 'CHAT' && effect.item.__typename === 'GraphqlSoupChat')+ )+ return effect.item.id;+ }+ throw new Error(+ 'Duplication succeeded but returned no copy identity; do not retry automatically'+ );+}++function shareEntityType(itemType: string) {+ return match(itemType)+ .with('document', () => 'DOCUMENT' as const)+ .with('project', () => 'PROJECT' as const)+ .with('chat', () => 'CHAT' as const)+ .with('email', () => 'EMAIL_THREAD' as const)+ .with('call', () => 'CALL' as const)+ .otherwise(() => undefined);+}++export function usesGraphqlSharePolicy(itemType: string): boolean {+ return (+ isFeatureEnabled(enableGraphqlSoup) &&+ shareEntityType(itemType) !== undefined+ );+}++const ACCESS_LEVELS: Record<AccessLevel, GraphqlEntityAccessLevel> = {+ view: 'VIEW',+ comment: 'COMMENT',+ edit: 'EDIT',+ owner: 'OWNER',+};+const SHARE_OPERATIONS: Record<+ 'add' | 'remove' | 'replace',+ GraphqlSharePolicyOperation+> = {+ add: 'ADD',+ remove: 'REMOVE',+ replace: 'REPLACE',+};++/** Preserve omission versus explicit null: null revokes, omission leaves unchanged. */+function sharePolicy(+ request: UpdateSharePermissionRequestV2+): EntitySharePolicyInput {+ const level = (value: AccessLevel | null | undefined) =>+ value == null ? value : ACCESS_LEVELS[value];+ return {+ linkShare: request.linkShare,+ linkShareAccessLevel: level(request.linkShareAccessLevel),+ teamShareAccessLevel: level(request.teamShareAccessLevel),+ channelSharePermissions: request.channelSharePermissions?.map((entry) => ({+ channelId: entry.channelId,+ operation: SHARE_OPERATIONS[entry.operation],+ accessLevel: level(entry.accessLevel),+ })),+ };+}++export function updateEntitySharePolicy(+ itemType: string,+ id: string,+ request: UpdateSharePermissionRequestV2+) {+ return catchToResult(async () => {+ const type = shareEntityType(itemType);+ if (!type) throw new Error(`Unsupported GraphQL share policy: ${itemType}`);+ await updateGraphqlEntitySharePolicy({+ entity: { type, id },+ policy: sharePolicy(request),+ });+ refreshSoup();+ });+}diff --git a/apps/web/src/lib/service-clients/service-storage/graphql-entity-mutations.ts b/apps/web/src/lib/service-clients/service-storage/graphql-entity-mutations.tsnew file mode 100644index 0000000000..be3e298371--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/graphql-entity-mutations.ts@@ -0,0 +1,103 @@+import { ThrownResultError } from '@core/util/result';+import type { TypedDocumentNode } from '@graphql-typed-document-node/core';+import { Telemetry } from '@macro-inc/observability';+import type { AnyVariables } from '@urql/core';+import {+ DeleteEntitiesPermanentlyDocument,+ DuplicateEntitiesDocument,+ type DuplicateEntityInput,+ type EntityMutationPayloadFieldsFragment,+ type EntityRefInput,+ MoveEntitiesDocument,+ type MoveEntityInput,+ RestoreEntitiesDocument,+ TrashEntitiesDocument,+ UpdateEntitySharePoliciesDocument,+ type UpdateEntitySharePolicyInput,+} from './graphql/generated/graphql';+import { getEntityGraphqlClient } from './graphql-soup';++/** These operations require an authoritative result, not a queued prediction.+ * Never retry a failed/ambiguous GraphQL write through the REST transport. */+async function mutateEntity<Data, Variables extends AnyVariables>(+ operation: string,+ entity: EntityRefInput,+ document: TypedDocumentNode<Data, Variables>,+ variables: Variables,+ payload: (data: Data) => EntityMutationPayloadFieldsFragment+) {+ return Telemetry.span(`entity.${operation}`, async (span) => {+ span.setAttr('entity.id', entity.id);+ span.setAttr('entity.type', entity.type);+ const result = await getEntityGraphqlClient()+ .mutation(document, variables)+ .toPromise();+ if (result.error) throw result.error;+ const results = result.data ? payload(result.data).results : [];+ const outcome = results[0];+ if (results.length !== 1 || !outcome)+ throw new Error(`${operation} returned no unambiguous entity result`);+ if (outcome.__typename === 'GraphqlMutationError') {+ throw new ThrownResultError([+ { code: outcome.errorCode, message: outcome.message },+ ]);+ }+ return outcome;+ });+}++export const moveGraphqlEntity = (input: MoveEntityInput) =>+ mutateEntity(+ 'move',+ input.entity,+ MoveEntitiesDocument,+ { inputs: [input] },+ (data) => data.moveEntities+ );++export const trashGraphqlEntity = (entity: EntityRefInput) =>+ mutateEntity(+ 'trash',+ entity,+ TrashEntitiesDocument,+ { entities: [entity] },+ (data) => data.trashEntities+ );++export const restoreGraphqlEntity = (entity: EntityRefInput) =>+ mutateEntity(+ 'restore',+ entity,+ RestoreEntitiesDocument,+ { entities: [entity] },+ (data) => data.restoreEntities+ );++export const permanentlyDeleteGraphqlEntity = (entity: EntityRefInput) =>+ mutateEntity(+ 'delete_permanently',+ entity,+ DeleteEntitiesPermanentlyDocument,+ { entities: [entity] },+ (data) => data.deleteEntitiesPermanently+ );++export const duplicateGraphqlEntity = (input: DuplicateEntityInput) =>+ mutateEntity(+ 'duplicate',+ input.entity,+ DuplicateEntitiesDocument,+ { inputs: [input] },+ (data) => data.duplicateEntities+ );++export const updateGraphqlEntitySharePolicy = (+ input: UpdateEntitySharePolicyInput+) =>+ mutateEntity(+ 'update_share_policy',+ input.entity,+ UpdateEntitySharePoliciesDocument,+ { inputs: [input] },+ (data) => data.updateEntitySharePolicies+ );diff --git a/docs/agent-guide/files.md b/docs/agent-guide/files.mdindex 8ed5e18f27..42c6bf5cfb 100644--- a/docs/agent-guide/files.md+++ b/docs/agent-guide/files.md@@ -16,6 +16,20 @@ viewer identity is available, document inserts into Shared are rejected.Files opens **Drive** using the same shell as Tasks, on desktop and touchdevices alike.+With `enable-graphql-soup` enabled, supported file/folder/chat moves, trash,+restore, permanent deletion, duplication, and share-policy changes use GraphQL+mutations. Verify moving into a folder and back to root, opening the returned+copy, and updating team/link/channel access on desktop and touch. Call-record+permanent deletion and team sharing also use these mutations. A denied or failed+GraphQL write must not retry through REST or report success; mixed bulk actions+retain successful siblings. A plan-refused chat duplicate still opens the paywall+with either transport; it must not create a copy or retry through REST. Restore immediately after trash and confirm the row+returns without waiting for retained deletion markers to expire, even if the+trash's background refresh failed. A delete started after the restore request+must still hide its row. With the flag off, the existing REST paths remain.+Deleting a non-owned item still only removes it from history. Forking a markdown+history version still uses REST because GraphQL duplication copies current content.+With `enable-databases` enabled, **My Files** includes owned databases and**Shared with me** includes databases shared by other owners. **All files**also includes accessible databases owned by others. **Search Drive** matches