Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
import { randomUUID } from 'node:crypto';
import { CoreApiClient } from 'twenty-client-sdk/core';
import { describe, expect, it } from 'vitest';

import { upsertCallRecordingOrThrow } from 'src/logic-functions/utils/upsert-call-recording-or-throw.util';

describe('Granola personal recordings', () => {
it('applies newer personal edits until workspace sync owns the recording', async () => {
const coreApiClient = new CoreApiClient();
const callRecordingId = randomUUID();

try {
await expect(
upsertCallRecordingOrThrow({
coreApiClient,
callRecordingId,
fields: {
title: 'Personal import',
granolaPersonalNoteUpdatedAt: '2026-11-18T12:00:00Z',
},
}),
).resolves.toMatchObject({ created: true });

await expect(
upsertCallRecordingOrThrow({
coreApiClient,
callRecordingId,
fields: {
title: 'Newer personal edit',
granolaPersonalNoteUpdatedAt: '2026-11-18T12:05:00Z',
},
}),
).resolves.toEqual({ callRecordingId, created: false });

await expect(
upsertCallRecordingOrThrow({
coreApiClient,
callRecordingId,
fields: {
title: 'Older personal edit',
granolaPersonalNoteUpdatedAt: '2026-11-18T12:02:00Z',
},
}),
).resolves.toMatchObject({ skipped: true });

await Promise.all([
upsertCallRecordingOrThrow({
coreApiClient,
callRecordingId,
fields: {
title: 'Concurrent personal edit',
granolaPersonalNoteUpdatedAt: '2026-11-18T12:10:00Z',
},
}),
upsertCallRecordingOrThrow({
coreApiClient,
callRecordingId,
fields: {
title: 'Workspace import',
granolaPersonalNoteUpdatedAt: null,
},
}),
]);

await expect(
upsertCallRecordingOrThrow({
coreApiClient,
callRecordingId,
fields: {
title: 'Later personal edit',
granolaPersonalNoteUpdatedAt: '2026-11-18T12:15:00Z',
},
}),
).resolves.toMatchObject({ skipped: true });

const { callRecording } = await coreApiClient.query({
callRecording: {
__args: { filter: { id: { eq: callRecordingId } } },
title: true,
},
});

expect(callRecording?.title).toBe('Workspace import');
} finally {
await coreApiClient.mutation({
destroyCallRecording: {
__args: { id: callRecordingId },
id: true,
},
});
}
});
});
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
import { defineConnectionProvider } from 'twenty-sdk/define';

import { GRANOLA_PERSONAL_CONNECTION_PROVIDER_NAME } from 'src/constants/granola-personal-connection.constant';
import { GRANOLA_PERSONAL_CONNECTION_UNIVERSAL_IDENTIFIER } from 'src/constants/universal-identifiers';
import {
GRANOLA_PERSONAL_CONNECTION_UNIVERSAL_IDENTIFIER,
GRANOLA_PERSONAL_DISCONNECT_UNIVERSAL_IDENTIFIER,
GRANOLA_PERSONAL_RECONCILE_UNIVERSAL_IDENTIFIER,
} from 'src/constants/universal-identifiers';

export default defineConnectionProvider({
universalIdentifier: GRANOLA_PERSONAL_CONNECTION_UNIVERSAL_IDENTIFIER,
Expand All @@ -10,4 +14,10 @@ export default defineConnectionProvider({
logo: 'public/logo.png',
type: 'api-key',
scope: 'USER',
onConnectLogicFunction: {
universalIdentifier: GRANOLA_PERSONAL_RECONCILE_UNIVERSAL_IDENTIFIER,
},
onDisconnectLogicFunction: {
universalIdentifier: GRANOLA_PERSONAL_DISCONNECT_UNIVERSAL_IDENTIFIER,
},
});
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,5 @@ export const GRANOLA_PERSONAL_CONNECTIONS_ROUTE_PATH =
export const GRANOLA_PERSONAL_FOLDERS_ROUTE_PATH = '/granola/personal-folders';
export const GRANOLA_PERSONAL_FOLDER_SELECTION_ROUTE_PATH =
'/granola/personal-folder-selection';

export const GRANOLA_PERSONAL_REGISTRATION_PREFIX = 'personal-';
Original file line number Diff line number Diff line change
Expand Up @@ -53,3 +53,9 @@ export const GRANOLA_PERSONAL_FOLDERS_ROUTE_UNIVERSAL_IDENTIFIER =
'dfcc4aae-76de-42f2-8d5f-4cb45bc09d4f';
export const GRANOLA_PERSONAL_FOLDER_SELECTION_ROUTE_UNIVERSAL_IDENTIFIER =
'c35065d3-b087-4a5d-be07-f6b95a8bf6c4';
export const GRANOLA_PERSONAL_WEBHOOK_UNIVERSAL_IDENTIFIER =
'6d90e977-d8e9-46c3-9006-6161aedca8c3';
export const GRANOLA_PERSONAL_RECONCILE_UNIVERSAL_IDENTIFIER =
'add7433a-f163-406d-9ead-8ca9072bbf91';
export const GRANOLA_PERSONAL_DISCONNECT_UNIVERSAL_IDENTIFIER =
'74644994-a5d7-4153-88cb-fc09d21482cb';
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import {
defineField,
FieldType,
STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS,
} from 'twenty-sdk/define';

export default defineField({
universalIdentifier: 'ca7e661a-508f-4365-84f9-5aee493613df',
name: 'granolaPersonalNoteUpdatedAt',
label: 'Granola personal note updated at',
description:
'Source revision for recordings synced by a personal Granola connection.',
type: FieldType.DATE_TIME,
objectUniversalIdentifier:
STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS.callRecording.universalIdentifier,
icon: 'IconClock',
isNullable: true,
isUIEditable: false,
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import { getConnection, kv } from 'twenty-sdk/logic-function';
import { afterEach, describe, expect, it, vi } from 'vitest';

import { GRANOLA_PERSONAL_REGISTRATION_PREFIX } from 'src/constants/granola-personal-connection.constant';
import { OWN_CONNECTION } from 'src/__tests__/utils/granola-personal-connection-fixtures';
import { granolaPersonalDisconnectHandler } from 'src/logic-functions/granola-personal-disconnect';
import { getGranolaPersonalFolderSelectionKey } from 'src/logic-functions/utils/get-granola-personal-folder-selection-key.util';
import { getGranolaPersonalWebhookKey } from 'src/logic-functions/utils/get-granola-personal-webhook-key.util';
import { getGranolaRegistrationClaimKey } from 'src/logic-functions/utils/get-granola-registration-claim-key.util';

vi.mock('twenty-sdk/logic-function', async (importOriginal) => ({
...(await importOriginal<typeof import('twenty-sdk/logic-function')>()),
getConnection: vi.fn(),
kv: { get: vi.fn(), delete: vi.fn() },
}));

afterEach(() => {
vi.resetAllMocks();
vi.restoreAllMocks();
vi.unstubAllGlobals();
});

describe('granolaPersonalDisconnectHandler', () => {
it('revokes the selection and claim even if Granola refuses to delete the webhook', async () => {
const connectionId = OWN_CONNECTION.id;
vi.mocked(getConnection).mockResolvedValue(OWN_CONNECTION);
vi.mocked(kv.get).mockResolvedValue({ webhookEndpointId: 'whe_stale' });
vi.spyOn(console, 'error').mockImplementation(() => undefined);
vi.stubGlobal(
'fetch',
vi
.fn<typeof fetch>()
.mockResolvedValue(new Response(null, { status: 403 })),
);

await expect(
granolaPersonalDisconnectHandler({ connectedAccountId: connectionId }),
).resolves.toEqual({ success: true });

expect(kv.delete).toHaveBeenCalledWith(
getGranolaPersonalFolderSelectionKey(connectionId),
);
expect(kv.delete).toHaveBeenCalledWith(
getGranolaRegistrationClaimKey(
GRANOLA_PERSONAL_REGISTRATION_PREFIX + connectionId,
),
{ scope: 'SERVER' },
);
expect(kv.delete).toHaveBeenCalledWith(
getGranolaPersonalWebhookKey(connectionId),
);
});
});
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import {
enqueueJobs,
kv,
listConnections,
reportConnectionAuthFailure,
Expand All @@ -14,6 +15,7 @@ import { getGranolaPersonalFolderSelectionKey } from 'src/logic-functions/utils/

vi.mock('twenty-sdk/logic-function', async (importOriginal) => ({
...(await importOriginal<typeof import('twenty-sdk/logic-function')>()),
enqueueJobs: vi.fn(),
listConnections: vi.fn(),
reportConnectionAuthFailure: vi.fn(),
kv: { get: vi.fn(), set: vi.fn() },
Expand Down Expand Up @@ -51,6 +53,23 @@ describe('granolaPersonalFolderSelectionHandler', () => {
expect(kv.set).not.toHaveBeenCalled();
});

it('rejects an account without an active Twenty workspace membership', async () => {
vi.mocked(listConnections).mockResolvedValue([
{ ...OWN_CONNECTION, workspaceMemberId: null },
]);
const fetchProvider = vi.fn<typeof fetch>();
vi.stubGlobal('fetch', fetchProvider);

await expect(
granolaPersonalFolderSelectionHandler(
{ body: { connectionId: OWN_CONNECTION.id, folderIds: [] } },
context,
),
).resolves.toMatchObject({ status: 404 });
expect(fetchProvider).not.toHaveBeenCalled();
expect(kv.set).not.toHaveBeenCalled();
});

it('marks a rejected personal key for reconnect before saving', async () => {
vi.mocked(listConnections).mockResolvedValue([OWN_CONNECTION]);
vi.stubGlobal(
Expand All @@ -72,7 +91,45 @@ describe('granolaPersonalFolderSelectionHandler', () => {
expect(kv.set).not.toHaveBeenCalled();
});

it('reports a setup failure when saved choices could not schedule reconciliation', async () => {
vi.mocked(listConnections).mockResolvedValue([OWN_CONNECTION]);
vi.mocked(enqueueJobs).mockRejectedValue(new Error('Queue unavailable'));
const log = vi.spyOn(console, 'error').mockImplementation(() => undefined);
vi.stubGlobal(
'fetch',
vi.fn<typeof fetch>().mockResolvedValue(
Response.json({
folders: [],
hasMore: false,
cursor: null,
}),
),
);

try {
await expect(
granolaPersonalFolderSelectionHandler(
{ body: { connectionId: OWN_CONNECTION.id, folderIds: [] } },
context,
),
).resolves.toMatchObject({ status: 503 });
expect(kv.set).toHaveBeenCalledWith(
getGranolaPersonalFolderSelectionKey(OWN_CONNECTION.id),
[],
);
} finally {
log.mockRestore();
}
});

it('validates folders with the member key and timestamps new selections', async () => {
vi.mocked(enqueueJobs).mockResolvedValue({
enqueued: true,
logicFunctionUniversalIdentifier: 'reconcile',
enqueuedJobsCount: 1,
jobIds: ['reconcile-job'],
jobs: [],
});
vi.useFakeTimers();
vi.setSystemTime(new Date(OPTED_IN_AT));
vi.mocked(listConnections).mockResolvedValue([OWN_CONNECTION]);
Expand Down Expand Up @@ -121,6 +178,18 @@ describe('granolaPersonalFolderSelectionHandler', () => {
headers: { Authorization: `Bearer ${OWN_CONNECTION.accessToken}` },
}),
);
expect(enqueueJobs).toHaveBeenCalledWith(
expect.objectContaining({
jobs: [
expect.objectContaining({
payload: {
connectedAccountId: OWN_CONNECTION.id,
userWorkspaceId: OWN_CONNECTION.userWorkspaceId,
},
}),
],
}),
);
expect(kv.set).toHaveBeenCalledWith(
getGranolaPersonalFolderSelectionKey(OWN_CONNECTION.id),
[
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ const { kvStore } = vi.hoisted(() => ({ kvStore: new Map<string, unknown>() }));

vi.mock('twenty-sdk/logic-function', async (importOriginal) => ({
...(await importOriginal<typeof import('twenty-sdk/logic-function')>()),
listConnections: vi.fn().mockResolvedValue([]),
kv: {
get: vi.fn(async (key: string) => kvStore.get(key)),
delete: vi.fn(async (key: string) => {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { defineLogicFunction } from 'twenty-sdk/define';
import { getConnection } from 'twenty-sdk/logic-function';

import { GRANOLA_PERSONAL_DISCONNECT_UNIVERSAL_IDENTIFIER } from 'src/constants/universal-identifiers';
import { disconnectGranolaPersonalConnection } from 'src/logic-functions/utils/disconnect-granola-personal-connection.util';
import { toErrorMessage } from 'src/logic-functions/utils/to-error-message.util';

export const granolaPersonalDisconnectHandler = async ({
connectedAccountId: connectionId,
}: {
connectedAccountId: string;
}) => {
const connection = await getConnection(connectionId).catch(
(error: unknown) => {
console.error(
`[granola] Could not read the disconnecting connection ${connectionId}. ${toErrorMessage(error)}`,
);

return undefined;
},
);

await disconnectGranolaPersonalConnection({
connectionId,
apiKey: connection?.accessToken,
});

return { success: true };
};

export default defineLogicFunction({
universalIdentifier: GRANOLA_PERSONAL_DISCONNECT_UNIVERSAL_IDENTIFIER,
name: 'granola-personal-disconnect',
description: 'Stops personal Granola sync when a member disconnects.',
timeoutSeconds: 30,
handler: granolaPersonalDisconnectHandler,
});
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,10 @@ import {
} from 'src/constants/granola-api.constant';
import { GRANOLA_PERSONAL_FOLDER_SELECTION_ROUTE_PATH } from 'src/constants/granola-personal-connection.constant';
import { GRANOLA_PERSONAL_FOLDER_SELECTION_ROUTE_UNIVERSAL_IDENTIFIER } from 'src/constants/universal-identifiers';
import { enqueueGranolaPersonalReconcileOrThrow } from 'src/logic-functions/utils/enqueue-granola-personal-reconcile-or-throw.util';
import { getGranolaSelectedParentFolders } from 'src/logic-functions/utils/get-granola-selected-parent-folders.util';
import { loadGranolaPersonalFolderSettings } from 'src/logic-functions/utils/load-granola-personal-folder-settings.util';
import { toErrorMessage } from 'src/logic-functions/utils/to-error-message.util';

const FOLDER_SELECTION_SCHEMA = z.object({
connectionId: z.uuid(),
Expand Down Expand Up @@ -72,6 +74,22 @@ export const granolaPersonalFolderSelectionHandler = async (
})),
);

try {
await enqueueGranolaPersonalReconcileOrThrow({
connectionId: request.data.connectionId,
userWorkspaceId,
});
} catch (error) {
console.error(
`[granola] Could not start personal sync reconciliation. ${toErrorMessage(error)}`,
);

return new Response(
{ error: 'SYNC_RECONCILIATION_UNAVAILABLE' },
{ status: 503 },
);
}

return { success: true, folderIds };
};

Expand Down
Loading
Loading